/* wine-selector.js requires wine-selecor.css and some specific markup in your templates. */
$('document').ready(function(){
	$('body').removeClass('no-js').addClass('js');
	var ws = $('#wine-selector');
	var wsForm = $('#wine-selector form');
	var wsOptionList = $('#wine-selector-option-list');
	var wsLinks = $('#wine-selector-option-list>li>a');
	var wsInsidelinks = $('.ws-menu li a').not('li.close a');
	var wsSelections = getUrlVars();

	// Initialize some styles for wsInsidelinks
	wsInsidelinks.each(function(){
		$(this).addClass($(this).attr('href').replace('#',''));
	});
	
	// Initialize search form action URL to have fragments appended
	wsForm.attr('action', wsForm.attr('action') + '#');
	
	// Initialize wsLinks for persisted states from last POST
	wsLinks.each(function(){
		$(this).attr('id', $(this).attr('href').replace('#',''));
		if(wsSelections[$(this).attr('id')]) {
			setSelectedOption($(this).parent().find('.' + wsSelections[$(this).attr('id')]));
		}
	});
	
	// Wine selector links - top level
	wsLinks.click(function(event){
		event.preventDefault();
		
		// Close any open selector sections
		closeSelectorSection();
		
		// Are we selecting or un-selecting?
		if($(this).is('.selected')) {
			// We are un-selecting
			clearSelectedOption($(this));
			
			// run the search again since the options have changed
			wsForm.submit();
		} else {
			// Open up the sub menu to make a selection
			$(this).addClass('open').append('<span class="arrow"/>');
			$(this).parent().find('.ws-menu').fadeIn('slow');
			$('.arrow').delay(200).fadeIn();
		}
	});

	// Wine selector inside links
	wsInsidelinks.click(function(event){
		event.preventDefault();
		
		// Update Wine Selector and page with selection
		setSelectedOption($(this));

		// Do the search
		wsForm.submit();
		
		// close the open menu
		closeSelectorSection();
	});

	// Wine selector form submit
	$('#wine-selector form').submit(function(){
		$('#wine-selector #search_string').val(function(index, value){
			return value.replace('Search all products', '');
		});
		
		// Deal with $50+ maximum price
		if($("#ws-price-max").val() == 50) {
			$("#ws-price-max").val( 999 );
		}
		
		return true;
	});

	// Wine selector close link
	$('.close').click(function(event){
		event.preventDefault();
		closeSelectorSection();
	});
	
	// Reset All
	$('a.reset-all').click(function(event){
		event.preventDefault();
		$('.choice').remove();
		$('.selected').removeClass('selected');
		$('#search_string').val('Search all products');
		$('#type-choice').val('');
		$('#region-choice').val('');
		$('#variety-choice').val('');
		$('#body-choice').val('');
		$('#pairing-choice').val('');
		$('#ws-price-min').val(10);
		$('#ws-price-max').val(50);
		wsForm.submit();
	});
	
	// Initialize Search String
	$('#search_string').val() == '' && $('#search_string').val('Search all products');
	$('#search_string').focus(function(){
		$(this).val($(this).val().replace('Search all products', ''));
	}).blur(function(){
		if($(this).val() == '') {
			$(this).val('Search all products');
		}
	});

	// Price input slider
	$('#ws-price-slider').slider({
		orientation: 'horizontal',
		range: true,
		min: 10,
		max: 50,
		values: [ $("#ws-price-min").val(), $("#ws-price-max").val() ],
		step: 5,
		slidecreate: function( event, ui ) {
			$( "#ws-price-range" ).after();
		},
		slide: function( event, ui ) {
			var minPrice = ui.values[ 0 ];
			var maxPrice = ui.values[ 1 ];

			if(minPrice == 10) {
				$( "#ws-price-min" ).val( 0 );
			} else {
				$( "#ws-price-min" ).val( minPrice );
			}

			if(maxPrice == 50) {
				$( "#ws-price-max" ).val( 999 );
			} else {
				$( "#ws-price-max" ).val( maxPrice );
			}
		},
		stop: function() { wsForm.submit(); }
	});

	$('#ws-price-min').val( $('#ws-price-slider').slider('values', 0 ));
	$('#ws-price-max').val( $('#ws-price-slider').slider('values', 1 ));

});

// Helper functions
function setSelectedOption(insideLink) {
	var categoryLink = insideLink.parent().parent().parent().find('>a');
	var category = categoryLink.attr('href').replace('#','');
	var choiceText = insideLink.text();
	var choice = insideLink.attr('href').replace('#','')
	var choiceSpan = '<span class="choice"> : ' + choiceText + '</span>';
	var wsForm = $('#wine-selector form');
	
	// set a selector on the insideLink
	insideLink.addClass('selected-option');

	// append a URL fragment to the search form action
	wsForm.attr('action', wsForm.attr('action') + category + '=' + choice + '+');

	// set the custom search field
	$('#' + category + '-choice').attr('value', choiceText);

	// store the selected choice in query criteria
	$('#search_string').val(function(index, value){
		return value.replace('Search all products', '') + ' ' + choiceText;
	});

	// set a style change on the parent link indicating a choice has been made
	// NOTE only wrap on WP pages, XCart pages are generating this
	categoryLink.addClass('selected').wrapInner('<span class="choice-category"/>').append(choiceSpan);
}

function clearSelectedOption(topLink) {
	var wsForm = $('#wine-selector form');
	var category = topLink.attr('href').replace('#','');
	wsForm.attr('action', wsForm.attr('action').replace(category + '=', 'unselect='));

	var choiceText = topLink.find('span.choice').text().replace(': ','');

	// remove previous choice and selected style
	topLink.find('.choice').remove();
	topLink.removeClass('selected');
	topLink.parent().find('.selected-option').removeClass('selected-option');

	// remove selection from query criteria
	$('#search_string').val(function(index, value){
		return value.replace(choiceText, '').replace('  ', ' ');
	});
	
	// remove selection search field
	var searchField = $('#' + topLink.attr('href').replace('#','') + '-choice');
	searchField.attr('value','');
}


function closeSelectorSection() {
	$('.arrow').remove();
	$('.open').removeClass('open');
	$('.ws-menu').fadeOut();
}


function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('+');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

