$(function(){
	
	/*================================= Form binding =================================*/
	
	// Define vars //
	var $triggerSubmit			= $('._jsTriggerFormSubmit');
	var $triggerSubmitSpan		= $triggerSubmit.find('span');
	var $loading				= $(' <img src="img/icons/loadingGreenGreyBg.gif" class="loadingNextToBtn"/>');
	var loadingHtml				= 'Proccessing...';
	var $defaultDiv				= $('._jsDefaultWrapper');
	var $successDiv				= $('<div class="_jsSuccessWrapper"></div>');
	var $errorDiv				= $('<div class="_jsErrorWrapper"></div>');
	
	// Set html for differnt form sections. //
	if( $('#subscribeForm').size() ){
		if( $('#subscribeForm').hasClass('_jsUnsubscribe') ){
			$successDiv.html('<h2>We&#146;re sorry to see you go.</h2><p>You have been successfully unsubscribed from our newsletter.</p>');
		}else{
			
			var section = location.search.split('/')[1];
			$successDiv.html('<h2>Thank You.</h2><p>You have been successfully <span class="keyword">subscribed</span> to our newsletter!</p>');
			
			if( !section || section != 'eNewsletter' ) $successDiv.append('<p><a href="?/eNewsletter" title="Read the most current newsletter">Click here</a> to view our latest newsletter.</p>')
		}
		$errorDiv.html('<h2>An Error Occured.</h2><p>Please try again, or head over to our <a href="?/info/contact" title="Go to our subscribe page">contact page</a> to report an error.</p>');
	}else if( $('#contactForm').size() ){
		$successDiv.html('<h2>Thank You.</h2><p>Your message has been sent.</p><p><a href="?/" title="Go to the home page">Click here</a> to continue browsing.</p>');
		$errorDiv.html('<h2>We&#146;re sorry, but there seemed to be an error, please try again, or <a href="mailto:reservations@nambitihills.com" title="email us">email us.</a>');
	}else if( $('#testimonialForm').size() ){
		$successDiv.html('<h2>Thank You.</h2><p>We have received your testimonial &amp; we&#146;ll be reviewing it &amp; hopefully posting it later on.<br/>Please check back later.</p>');
		$errorDiv.html('<h2>We&#146;re sorry, but there seemed to be an error.<br/>Please try again, or <a href="mailto:reservations@nambitihills.com" title="email us">email us.</a>');
	}
	
	
	// Initial css and values. //
	$triggerSubmitSpan.data('origHtml', $triggerSubmitSpan.html());
	$triggerSubmit.data('origHtml', $triggerSubmit.html());
	$successDiv.hide();
	$errorDiv.hide();
	//$loading.css({'margin':'0px 0px -12px 5px'});
	
	
	$('#subscribeForm, #contactForm, #testimonialForm')
		.find('input[type=submit]').remove().end()
		.find('._jsTriggerFormSubmit').show().css({'display':'inline-block'}).end()
		.formConfig({
			listeners: [
				{
					'click' : ['._jsTriggerFormSubmit'],
					'onKeyEnter' : ['input']
				}
			],
			ajaxSubmit : true,
			onBeforeSubmit: function( $form ){
				$triggerSubmitSpan.html(loadingHtml);
				$triggerSubmit
					.addClass('disabled')
					.after($loading);
				$form.find('input, textarea, select').attr('disabled','disabled');
			},
			fnSuccess: function( $form, data, textStatus, xhr ){
				$form.find('input, textarea, select').removeAttr('disabled');
				if( data.resubscribed ) $successDiv.find('.keyword').html('resubscribed');
				$defaultDiv.after($successDiv);
				if( $.support.opacity ){
					$errorDiv.fadeOut();
					$defaultDiv.fadeOut(function(){
						$successDiv.delay(500).fadeIn();
					});
				}else{
					$errorDiv.hide();
					$defaultDiv.hide();
					$successDiv.show();
				}
			},
			fnFailure: function( $form, errorThrown ){
				$form.find('input, textarea, select').removeAttr('disabled');
				$defaultDiv.after($errorDiv);
				if( $.support.opacity ) $errorDiv.fadeIn();
				else $errorDiv.show();
				$triggerSubmitSpan.html($triggerSubmitSpan.data('origHtml'));
				$triggerSubmit.removeClass('disabled')
				$loading.remove();
			},
			ajaxKeyword:'ajax_on',
			validator: {
				allowBlank : false,
				inputTips : false,
				failureCls : 'valFailed',
				successCls : 'valPassed'
			},
			disableListener:true
		});
	
	$('#reservationForm').formConfig({
		ajaxSubmit : false,
		validator: {
			allowBlank : false,
			inputTips : false,
			failureCls : 'valFailed',
			successCls : 'valPassed'
		}
	});
	
	_initReferralForm = function(){
		$( '#referralInputSubmit' ).remove();
		$( '#referralForm span.submitLoading' ).hide();
		$( '#referralSubmit' ).css({ 'display':'inline-block'});
		$( '#referralForm').formConfig({
			listeners: [
				{
					'click' : ['._jsTriggerFormSubmit']
				}
			],
			onBeforeSubmit: function( $form ){
				if ( _ie ) {
					$( '#referralForm span.submitLoading' ).show();
					$('._jsValidationError').hide();
				} else {
					$( '#referralForm span.submitLoading' ).fadeIn();
					$('._jsValidationError').fadeOut();
				}
			},
			ajaxSubmit : false,
			validator: {
				allowBlank : false,
				inputTips : false,
				failureCls : 'valFailed',
				successCls : 'valPassed',
				onSubmitFailed : function () {
					if ( _ie ) {
						$('._jsValidationError').show();
					} else {
						$('._jsValidationError').fadeIn();
					}
				}
			}
		});
	}
	_initReferralForm();
	
	
	// ===================================== INTERNAL COMMENT FORM ================================== //
	
	
	/*var $commentForm = $('form._jsCommentForm');
	
	$commentForm.find('textarea').removeAttr('disabled');
	$commentForm.formConfig({
		listeners: [
			{
				'click' : ['a._jsTriggerFormSubmit']
			}
		],
		ajaxSubmit : true,
		onBeforeSubmit: function( $form ){
			$loading = $('<img class="loadingIcon" src="img/icons/loadingGreenGreyBg.gif"/>'); // Change this to red when the net comes back
			$loading.css({'border':'none'});
			$form.find('textarea').attr('disabled', 'disabled');
			$form.find('._jsTriggerFormSubmit')
				.html(loadingHtml)
				.addClass('disabled')
				.after($loading);
		},
		ajaxKeyword:'ajax_on',
		validator :{
			inputTips:false,
			allowBlank:false
		},
		fnSuccess: function( $form, data ){
			_commentSuccess ($form, data );
		},
		fnFailure: function( $form){
			_commentFailed ($form);
		}
	});
	
	_commentSuccess = function( $form, data ){
		
		var obj = data;
		
		if(!obj){
			obj = {};	
		}
		
		// Get the comment template to return to html //
		var $original = $form.find('div._jsCommentTemplate');
		$template = $original.clone();
		$template.removeClass('_jsCommentTemplate hide');
		
		// Put together profile link for facebook //
		var profileLink = $template.find('a.userName').attr('href');
		
		var template = $('<div>').append( $template ).html();
		template = template.replace('_user_facebook_id_', data.user_facebook_id);
		
		for(var x in obj){
			template = template.replace('[' + x + ']', obj[x]);
		}
		
		$form.find('div._jsCommentWrapper').find('p').first().after( template );
		$form.find('.commentInputContainer textarea').val('');
		
		$form.find('.commentInputContainer').fadeTo(300, 1);
		
		var $loadingMsg = $form.find('p.successOrFailMsg');
		$loadingMsg.html('Your comment was posted!');
		
		var origHtml = $form.find('._jsTriggerFormSubmit').data('origHtml');
		
		$form.find('textarea').removeAttr('disabled');
		
		$form.find('._jsTriggerFormSubmit').html(origHtml).removeClass('disabled');
		
		$loading.hide();
		
		// Update comment count //
		var $commentCounter = $form.find('input._jsCommentCountInt');
		var commentCount = parseInt( $commentCounter.val() );
		var updateCountVal = commentCount + 1;
		$commentCounter.val( updateCountVal );
		
		$form.find('span.commentsLink').text( updateCountVal );
		$('._jsCommentCount').html((updateCountVal)+' Comments');
	}
	
	_commentFailed = function( $form ){
		var $loadingMsg = $form.find('p.successOrFailMsg');
		$loadingMsg.html('An error occurred. Your comment may have failed to post. Please refresh this page and try again.');
		$form.find('.commentInputContainer').fadeTo(300, 1);
	}
	
	$commentForm.delegate('a._jsDeleteComment', 'click', function(){
		
		if( confirm('Are you sure that you want to delete this comment?') ){	
		
			var $this = $(this);
			var id = $this.siblings('input').val();
			
			// Update comment count //
			var $commentCounter = $('input._jsCommentCountInt');
			var commentCount = parseInt( $commentCounter.val() );
			var updateCountVal = commentCount - 1;
			$commentCounter.val( updateCountVal );
			
			$commentForm.find('span.commentsLink').text( updateCountVal );
			$commentForm.find('._jsCommentCount').html((updateCountVal)+' Comments');
			
			if( updateCountVal == 0 ){
				$commentForm.find('div._jsCommentWrapper').find('p').html('There are currently no comments');
				$('div.showMore').hide();
			}
			
			// Remove the comment. //
			$this.parents('div._jsComment').first().slideUp(function(){
				$(this).remove();
			});
			
			// Remove comment in the db. //
			$.ajax({
				url:'?/comments',
				type:'post',
				data:{
					comment_action:'delete',
					id:id,
					ajax_on:true
				}
			});
			
			// Remove any loading msg //
			$('p._jsLoadingMsg').remove();
		}
	});*/
	
	/*================================= End of form binding =================================*/
	
	/*================================= Menu =================================*/
	
		
		$('#header .menuBar')
			.removeClass('noJs')
			.menu({
				hoverClass : 'active',
				menuChildrenTagNames : '.menuLinks'
			});
		
	
	/*================================= End of Menu =================================*/

});
