var defaultLoginSignUpOverlay;
var cellarLoginSignUpOverlay;


if (jQuery.browser.msie && jQuery.browser.version == '6.0') {

//	$.fn.livequery = function () {
//
//	};

}
(function($){

	/*--------------------------------------------------------------------------------------------
		Cufon font replacement
	--------------------------------------------------------------------------------------------*/
	
	Cufon.replace('#Header h1, h1.howItWorks, h2, h3, h4');

	Cufon.replace('#Nav a', {
		hover : true
	});
	
	$(function () {

		/*--------------------------------------------------------------------------------------------
			Autohide on Search Field
		--------------------------------------------------------------------------------------------*/
		
		$('#Query').autohide({
			defaultValue: 'Search for wine'
		});

		/*--------------------------------------------------------------------------------------------
			Overlays
		--------------------------------------------------------------------------------------------*/

		if ($('.editprofile').length) {

			$('.editprofile').overlay({
				windowWidth : 278,
				windowPosX : $('#Container').offset().left,
				windowPosY : 50,
				orientation : 'right',
				getContentFrom : $('#EditProfile')
			});

		}		
		
		if ($('.signup').length) {

			$('.signup').overlay({
				windowWidth : 269,
				windowPosX : (($(document).width() - $('#Container').width()) / 2) + 54,
				windowPosY : 31,
				orientation : 'right',
				getContentFrom : $('#SignUp')
			});

		}
		
		if ($('.login').length) {
			
			loginOverlay = $('.login').overlay({
				windowWidth : 266,
				windowPosX : (($(document).width() - $('#Container').width()) / 2) + 54,
				windowPosY : 31,
				orientation : 'right',
				getContentFrom : $('#LoginForm'),
				onLoadCallback : function(overlaywindow){
					resetPasswordHandler(overlaywindow);
				}
			});

		}
		
		defaultLoginSignUpOverlay = $('').overlay({
			windowWidth : 510,
			windowPosX : (($(document).width() - $('#Container').width()) / 2) + 54,
			windowPosY : 31,
			orientation : 'right',
			addExtraMarkup : {
				placement : 'before',
				html : '<h2 class="sectionHeader">Want to review a wine? Great!</h2>'
			},
			getContentFrom : $('#LoginForm, #SignUp'),
			onLoadCallback : function(overlaywindow){
				resetPasswordHandler(overlaywindow);
				$.scrollTo(0, 500);
			}
		});

		cellarLoginSignUpOverlay = $('').overlay({
			windowWidth : 510,
			windowPosX : (($(document).width() - $('#Container').width()) / 2) + 54,
			windowPosY : 31,
			orientation : 'right',
			addExtraMarkup : {
				placement : 'before',
				html : '<h2 class="sectionHeader">Want to add to cellar? Great!</h2>'
			},
			getContentFrom : $('#LoginForm, #SignUp'),
			onLoadCallback : function(overlaywindow){
				resetPasswordHandler(overlaywindow);
				$.scrollTo(0, 500);
			}
		});


		function resetPasswordHandler($window) {

			$('.forgotten', $window).click(function (event) {
				event.preventDefault();

				$(this).fadeOut(500);

				$('#Login_Form', $window).slideUp(500, function () {

					$('#Login_Form', $window).parent().prev().html('<strong>Reset Password</strong>');

					Cufon.refresh();

					$('#ForgottenPasswordForm', $window).slideDown();

				});

			});

			$('#CancelResetPassword', $window).click(function (event) {
				event.preventDefault();

				$('#ForgottenPasswordForm', $window).slideUp(500, function () {

					$('#Login_Form', $window).parent().prev().html('<strong>Login</strong>');

					Cufon.refresh();

					$('#Login_Form', $window).slideDown();

					$('.forgotten', $window).fadeIn(500);
				});

			});

		}


		
		/*--------------------------------------------------------------------------------------------
			Form Styling/Behaviour
		--------------------------------------------------------------------------------------------*/
		
		$('form').livequery(function () {

			var $form = $(this);
			
			var doValidation = true;

			if ($form.attr('id') == "Login_Form" || $form.attr('id') == "Search_Form" || $form.attr('id') == 'EditProfileForm' || $form.attr('id') == "VerifyAgeForm") {

				doValidation = false;

			}

			$form.forms({
				validation : doValidation,
				errorCallback : function () {
					
					if ($form.attr('id') == 'CreateWineForm') {
						
						$form.parent().find('h5').hide();
						$form.parent().find('h2').css({
							'border-bottom' : 0,
							'margin-bottom' : 0
						});
						
					}

				},
				onBlurCallback : function (field) {
					var varietyMap = {
						'sauvignon-blanc': -168,
						'gewurztraminer': -336,
						'chardonnay': -504,
						'pinot-noir': -672,
						'merlot': -840,
						'pinot-gris': -1008,
						'riesling': -1176,
						'rose': -1344,
						'default': 0
					};
					
					if (field.attr('id') == "CreateWine_Variety") {
						$.ajax({
							url: '/ajax/varietydefaultimage/variety/' + field.val(),
							dataType: 'json',
							success: function (data) {
								$('#Bottle').css({
									backgroundPosition : '0px ' + varietyMap[data.variety] + 'px'
								});
							}
						});

					}
				}
			});

			if ($('#CreateWine_Variety').length) {
				$('#CreateWine_Variety').blur();
			}
		});

		/*--------------------------------------------------------------------------------------------
			Styled checkboxes
		--------------------------------------------------------------------------------------------*/
		
		$('input[type="checkbox"]').livequery(function () {
			$(this).styledCheckbox();
		});


		/*--------------------------------------------------------------------------------------------
			Filter dropdowns
		--------------------------------------------------------------------------------------------*/

		if ($('p.filter').length || $('#Filter p').length) {

			$('p.filter, #Filter p').filtermenu({
				classForMenu : $("#Filter").attr('class') + '_Menu'
			});

		}
		
		/*--------------------------------------------------------------------------------------------
			Notifications
		--------------------------------------------------------------------------------------------*/

		if ($('.notification .close').length) {

			$('.notification .close').click(function (event) {

				event.preventDefault();

				$('.notification').css('overflow','hidden').slideUp(700);

			});

		}
		
		/*--------------------------------------------------------------------------------------------
			Edit Profile reveal/collapse forms
		--------------------------------------------------------------------------------------------*/

		$('.editDetails').livequery(function () {

			$(this).click(function (event) {
				event.preventDefault();

				$(this).closest('.section').slideUp(500, function () {

					$(this).closest('.section').find('.sectionDetails').hide();
					$(this).closest('.section').find('form').show();

					$(this).closest('.section').slideDown(500);

				});

			});
			
		});

		$('.section input[type="reset"]').livequery(function () {

			$(this).click( function () {

				$(this).closest('.section').slideUp(500, function () {

					$(this).closest('.section').find('form').hide();
					$(this).closest('.section').find('.sectionDetails').show();

					$(this).closest('.section').slideDown(500);

					$(this).closest('.section').find('.error').removeClass('error');
					$(this).closest('.section').find('.valid').removeClass('valid');

				});

			});

		});

		/*--------------------------------------------------------------------------------------------
			Star Ratings
		--------------------------------------------------------------------------------------------*/

		if ($('#Form_Rating .formRadio').length) {

			$('#Form_Rating .formRadio').starRating();

		}

		/*--------------------------------------------------------------------------------------------
			Review form behaviour
		--------------------------------------------------------------------------------------------*/

		if ($("#Review").length) {

			$("#Review").reviews();
			
		}		

		/*--------------------------------------------------------------------------------------------
			Wine Review character counter
		--------------------------------------------------------------------------------------------*/

		if ($('#Note').length) {

			var review_charLimit = 180;
			$('#Note').charactercounter({
				characterLimit : review_charLimit,
				exceededCallbackFn : function () {

					$("#Counter").addClass('hint');

				},
				remainingCallbackFn : function () {

					$("#Counter").removeClass('hint');

				},
				messageCharsRemaining : review_charLimit + ' character limit : CHAR_COUNT left',
				messageCharsExceeded : review_charLimit + ' character limit : CHAR_COUNT over!'
			});
			
		}

		var noteField, initialNoteValue, saveInProgress;

		noteField = $('#Note');
		saveInProgress = false;

		if (noteField.length) {
			initialNoteValue = noteField.val();

			$('form').submit(function () {
				saveInProgress = true;
			});

			$(window).bind('beforeunload', function (event) {
				if (!saveInProgress && initialNoteValue !== noteField.val()) {
					return 'You have an unsaved review.';
				}
			});
		}

		/*--------------------------------------------------------------------------------------------
			Cellar
		--------------------------------------------------------------------------------------------*/
		//$("#Cellar form").cellar();


		if (jQuery.browser.msie && jQuery.browser.version == '6.0') {

			if ($('#CreateWine_Variety').length) {

				var $firstOption = $('#CreateWine_Variety option:first');

				var $options = $('#CreateWine_Variety').find('option:not(:first)');

				var $otherOption = $('<option></option>').attr('value','Other').text('Other');
				
				var $otherOptgroup = $('<optgroup></optgroup>').attr('label','Other').append($otherOption);
				
				var $varietyOptgroup = $('<optgroup></optgroup>').attr('label','Varieties').append($options);

				$('#CreateWine_Variety').empty().append($firstOption);

				$('#CreateWine_Variety').append($otherOptgroup);

				$('#CreateWine_Variety').append($varietyOptgroup);

				$('#CreateWine_Variety').change(function (event) {

					if ($(this).val() == 'Other') {

						$('#Form_CreateWine_OtherVariety').css('display','inline'); // display:inline, to fix double floated margin bug
						
					} else {

						$('#Form_CreateWine_OtherVariety').hide();

					}
					
				});

			}

		}

	});
	
})(jQuery);
