$(document).ready(function() {




	// Javascript configuration starts here
	// use #for ids for eg.. 
	//<div id='main'> than var main = '#main'
	// if <div class='main'> than var main = '.main'
	var other = '#other';
	// please note that values of the the selection ingredients are displayed in element with id mainval for main , cusineval for cuisine and so on...
	////////////////// Do not alter beyond this line ///////////////////////////
	// slider values ... since there are 2 sliders configure their values as an array
	var sliderweight = new Array();
	$("select[name='weightval']").children('option').each(function(i, e) {
		sliderweight[i] = '<a rel="' + i + '">' + $(this).html() + '</a>';
	});

	/*//similarly for slider value 2
	var sliderflavor = new Array();
	$("select[name='flavorval']").children('option').each(function(i, e) {
		sliderflavor[i] = '<a rel="' + i + '">' + $(this).html() + '</a>';
	});*/

	//count the values in array to make appropriate slider
	var sl1c = sliderweight.length;
	$('#sliderweight').slider({
		min: 0,
		value: 10,
		max: sl1c - 1,
		change: function(e, ui) {
			//alert('changeinit');//pyp 
			var val = sliderweight[ui.value];
			$('#weightval').html(val);
		},
		stop: function(e, ui) {
			var val = sliderweight[ui.value];
			$('#weightval').html(val);
		}
	});
	$('#sliderweight').bind('slidechange',
	function(event, ui) {
		//alert('changebind'); 
		var val = sliderweight[ui.value];
		$('#weightval').html(val);
	}); //pyp


	/*var sl2c = sliderflavor.length;
	$('#sliderflavor').slider({
		min: 0,
		value: 10,
		max: sl2c - 1,
		slide: function(e, ui) {
			var val = sliderflavor[ui.value];
			$('#flavorval').html(val);
		},
		stop: function(e, ui) {
			var val = sliderflavor[ui.value];
			$('#flavorval').html(val);
		}
	});
	$('#sliderflavor').bind('slidechange',
	function(event, ui) {
		//			alert('changebind'); 
		val = sliderweight[ui.value];
		$('#flavorval').html(val);
	}); //pyp */

	
	$('#weightval').html('<a rel="10"></a>');
	
	/*$('#flavorval').html('<a rel="10"></a>');*/

	//var val =	;
	//$('#flavorval').html(sliderflavor[ui.value]);

	/////////////// sliders are done ////////////////
	//get value for all the boxes from selects
	var mainval = new Array();
	$("select[name='mainval']").children('option').each(function(i, e) {
		//put them and wrap them
		mainval[i] = '<a href="#" title="'+e.title+'" class="opt '+ e.className /* <---------- added by andrew */ +'" rel="' + e.value + '">' + e.text + '</a>';
/*		mainval[i] = '<a href="#" class="opt" rel="' + e.value + '">' + e.text + '</a>';*/
		$('#main').append(mainval[i]);
	});
	$('#main').append('<div class="clearfloat"></div>');

	var cuisineval = new Array();
	$("select[name='cuisineval']").children('option').each(function(i, e) {
		//put them and wrap them
		cuisineval[i] = '<a href="#" title="'+e.title+'" class="opt" rel="' + e.value + '">' + e.text + '</a>';
		$('#cuisine').append(cuisineval[i]);
	});
	$('#cuisine').append('<div class="clearfloat"></div>');

	var cookingval = new Array();
	$("select[name='cookingval']").children('option').each(function(i, e) {
		//put them and wrap them
		cookingval[i] = '<a href="#" title="'+e.title+'" class="opt" rel="' + e.value + '">' + e.text + '</a>';
		$('#cooking').append(cookingval[i]);
	});
	$('#cooking').append('<div class="clearfloat"></div>');

	var otherval = new Array();
	$("select[name='otherval']").children('option').each(function(i, e) {
		//put them and wrap them
		otherval[i] = '<a href="#" title="'+e.title+'" class="opt" rel="' + e.value + '">' + e.text + '</a>';
		$('#misc').before(otherval[i]); //append to the select element rather than the parent, because there's a second <select> within that same parent 
	});
//	$('#other').append('<div class="clearfloat"></div>');

	var miscval = new Array();
	$("select[name='miscval']").children('option').each(function(i, e) {
		//put them and wrap them
		miscval[i] = '<a href="#" title="'+e.title+'" class="opt" rel="' + e.value + '">' + e.text + '</a>';
		$('#misc').append(miscval[i]);
	});
	$('#misc').append('<div class="clearfloat"></div>');

	// now do the four boxes thing
	//hide all the children first
	$('.children').css('display', 'none');
	$('.children').height('260px');
	//wait we want to display first children though
	$('#main').css('display', 'block');

//---------begin pyp version which was working well prior to importing andrew logic
//add Next on load
//	$('#cuisineprnt').addClass('next');
//	$('#cuisineprnt').removeClass('disabled');
//	$('#mainprnt').removeClass('disabled');

	//show them when their parent is clicked
	$('.parent').click(function(event) {
		if (($(this).children('.children').css('display') == 'none') && (!$('.children:animated').size()) && (!($(this).hasClass('disabled')))) //allows clicking at hidden tabs with 'next' or 'change'
		{
			//set next tab status to 'next'
//			if ($(this).next('.parent').hasClass('disabled')) {
//				$(this).next('.parent').removeClass('disabled');
//				$(this).next('.parent').addClass('next');
//			};

			//set recently active tab to 'change' status
			//$('.parent .current').removeClass('disabled');
			$('.parent .current').addClass('change');
			//$('.parenttab.current').find('.status').html('[Change]');
			//remove current state from recently active tab
			$('.parent').removeClass('current');
			//animate
			$('.children').slideUp("slow");
			$(this).children('.children').slideDown("slow");
			//set new active tab status
			$(this).removeClass('next');
			$(this).removeClass('change');
			//$(this).addClass('disabled');
			$(this).addClass('current');
		}
	});//-----------------------end pyp version 


// -------------- modified by andrew below this line
/*
	//add Next on load
	$('#cuisineprnt').addClass('next');
	$('#cuisineprnt').removeClass('disabled');
	//$('#mainprnt').removeClass('current');

	//show them when their parent is clicked
	$('.parent').click(function(event) {
		if (($(this).children('.children').css('display') == 'none') && (!$('.children:animated').size()) && (!($(this).hasClass('disabled')))) //allows clicking at hidden tabs with 'next' or default status
		{
			//set next tab status to 'next'
//			if ($(this).next('.parent').hasClass('disabled')) {
//				$(this).next('.parent').removeClass('disabled');
//				$(this).next('.parent').addClass('next');
//			};
			
			//set recently active tab to default status by removing 'current' state from 'parents'
			$('.parent').removeClass('current');
			//animate
			$('.children').slideUp("slow");
			$(this).children('.children').slideDown("slow");
			//set new active tab status
			$(this).removeClass('next');
			$(this).removeClass('change');
			$(this).addClass('current');
		}
	});

// -------------- modified by andrew above this line
*/


	//if a a tag in children is clicked update the selection
	$('.children').click(function(event) {
		if ($(event.target).is('a')) {
			//get the id to be updated
			var id = $(this).attr('id');
			//get data to be added from this a tag
			var val = '<a href="javascript:void(0);" rel="' + $(event.target).attr('rel') + '" class="' + $(event.target).html() + '">' + $(event.target).html() + '</a>';
			//also update the rel tag to mark the chosen a tag
			if (id != 'other') {$(this).children('.opt').removeClass('current');}
			if (id == 'other' || id=='misc') { //right now always runs as other, because misc is not .children because making it .children screws up the tabs
				var x = 0;
				//$('#'+id+'val').html($('#'+id+'val').html().replace(/  /,' '));
				$('#'+id+'val').children().each(function(i) {
					if ($(this).html() == $(event.target).html()) { //if one of the children of the idval is the target of the click
						$(this).remove();
						//if ($('#'+id+'val').html().substr(0,2)==', ') {$('#'+id+'val').html($('#'+id+'val').html().substr(1));}
						//$('#'+id+'val').html().replace(', ','');
						$('#'+id+'val').children()
						$(event.target).removeClass('current');
						x = 1;
					}
				});
				//$('#'+id+'val').html($('#'+id+'val').html().substr(1));
				if (x != 1) {
					if ($('#'+id+'val').children().size() >= 4) {
						alert("Sorry, you may only make four selections total on this tab.\n\nPlease select only the four strongest matches from this menu. You may unselect an item by clicking it a second time.");
					}

					//find if there is such a children
					//var x =0;
					else {
						// now update the given id with a tag's value'
						/*if ($('#'+id+'val').children().size() == 0) {*/$('#'+id+'val').append(val);/*} else {$('#'+id+'val').append(', '+val);}*/
						$(event.target).addClass('current');
					}
				}
				$('#'+id+'val').html($('#'+id+'val').html().replace(/, /g,''));
				$('#'+id+'val').children('*:gt(0)').before(', ');

			}
			else {
				$('#' + id + 'val').html(val);
				$(event.target).addClass('current');
				//$('#'+id+'prnt').next('.parent').addClass('next');
				$('.parent').removeClass('next');
				$('#'+id+'prnt').next('.parent').addClass('next');
				//$('#'+id+'prnt').next('.parent').removeClass('disabled');
				$('#'+id+'prnt').next('.parent').removeClass('disabled');
//				$('#'+id+'prnt').next('.parent').animate({margin:'30px 0px'}, 250, function(){$(this).animate({margin:'0px 0px'},350);});
				$('#'+id+'prnt').next('.parent').animate({opacity:0}, 250, function(){$(this).animate({opacity: 1},350);});
//				nextTip($('#'+id+'prnt').next('.parent'));
//setTimeout(function(){$('#'+id+'prnt').next('.parent').trigger('mouseout')},800); ///////////////////////////////////////////////////////////////
				//$('#'+id+'prnt').removeClass('disabled');
				$('#'+id+'prnt').removeClass('disabled');

			}
		}
		if (!(($('#mainval').children().length==0) || ($('#cuisineval').children().length==0) || ($('#cookingval').children().length==0))) {$('#results').attr('src','http://d3pfzl1h3g4695.cloudfront.net/images/viewthewines.png');}
		return false;
	})

	
	//logic for reset button. **someday go back and eliminate hard-coding of id's
	$('#reset').click(function(event) {
		$('.children').slideUp("slow");
		$('.children').children('.opt').removeClass('current');
		$('#misc').children('.opt').removeClass('current'); //handled separately because it's a submenu within #other
		$('#mainval').children().remove();
		$('#cuisineval').children().remove();
		$('#cookingval').children().remove();
		$('#otherval').children().remove();
		$('#otherval').html('');
		$('#miscval').children().remove();
		$('#weightval').html('<a rel="10"></a>');
		$('#sliderweight').slider('value', 10);
		$('.parent').removeClass('current');
		$('.parent').removeClass('change');
		$('.parent').addClass('disabled');
//		$('#cuisineprnt').removeClass('disabled');
//		$('#cuisineprnt').addClass('next');
		$('#mainprnt').removeClass('disabled');
//		$('#mainprnt').children().addClass('current');
		$('#mainprnt').addClass('current');
		$('#mainprnt').children('.children').slideDown("slow");
		$('#results').attr('src','http://d3pfzl1h3g4695.cloudfront.net/images/viewthewines_disabled.png');		
		return false;
	})



	// now when show results is clicked then shift everything sideways
	//build the tag cloud data 
	//create list for tag links   
	//create tags

	var jsonstring = '';
	$('#results').click(function() {
		if (($('#mainval').children().length==0) || ($('#cuisineval').children().length==0) || ($('#cookingval').children().length==0)) { alert('Sorry, you are missing a mandatory selection.\n\nThe Main Flavor, Cuisine, and Cooking Method tabs are mandatory.');  return false;}




		// post the results to wine.php file
		var mainval = '' + $('#mainval').children('a').attr('rel');
		var weightval = '' + $('#weightval').children('a').attr('rel');
		var flavorval = '' + $('#flavorval').children('a').attr('rel');
		var cuisineval = '' + $('#cuisineval').children('a').attr('rel');
		var cookingval = '' + $('#cookingval').children('a').attr('rel');
		var otherval = '';
		$('#otherval').children('a').each(function() {
			otherval = '' + otherval + $(this).attr('rel') + '|';
		});
		otherval = otherval.substr(0, otherval.length - 1);
		$.post('/libs/wine.php', {
			mainval: mainval,
			weightval: weightval - 10,
			flavorval: flavorval - 10,
			cookingval: cookingval,
			cuisineval: cuisineval,
			otherval: otherval
		},
		function(data) {
			var json = data;

			$('#sidebar2').empty();
			$("#sidebar2").append("<ul id=\"ul-results\"></ul>");

			//$('#sidebar2').append('<h3>Results area</h3>');
			$.each(json.items,
			function(i, val) {
				var li = $("<li>");
				li.append("<a href='" + val.url + "' rel='" + val.urlname + "'>" + val.html + "</a>");
				li.children().css("fontSize", val.freq + "px"); // pyp
				li.appendTo("#sidebar2 ul");
				var li2 = $("<li style='width:2px;'>");
				li2.appendTo("#sidebar2 ul");
				//jsonstring = jsonstring + "\n" + val.html + ": " + val.freq;
			});
$("#sidebar2").append("<div class=\"clearfloat\" />");
$("#sidebar2").append("<div id=\"results-note\">*** wines in larger type are stronger pairs, though all results should pair agreeably</div>");
//$("#sidebar2").append("<div id=\"below-results\">"+"<a href=\"http://www.jdoqocy.com/click-3528611-8262199\" target=\"_blank\" onmouseover=\"window.status='http://www.wineenthusiast.com';return true;\" onmouseout=\"window.status=' ';return true;\"><img src=\"http://www.awltovhc.com/image-3528611-8262199\" width=\"125\" height=\"125\" alt=\"Cellar Outlet - Save Big on near perfect cellars!\" border=\"0\"/></a>"+"</div>");
		},
		'json');
//		alert(jsonstring);

		jsonstring = '';

		return false;
	});

	$('#sidebar2').click(function(event) {
		//var sidebar = $(this).html();
		//var bgrnd = $(this).css('background-image');
		if ($(event.target).is('li a')) {
			//get sidebar data to populate later
			var wid = $(event.target).attr('rel');
			//change later = 
			var href = 'http://www.winetomatch.com/scripts/wine-detail/'+wid;
			$.get(href,
			function(data) {
				$('#rollPanel .inner').html(data);
				$('#mainContent').fadeOut("fast",
				function() {
					$('#rollPanel').css('display', 'block');
					$('#rollPanel').animate({
						width: '608px'
					},
					'normal',
					function() {
						$('#article').css('display', 'block');
						//$(this).css('background-image','none'); /* remove vertical line */
					})
				});

				//initialize Back button
				$('#back').click(function() {
					//$('#sidebar2').html(sidebar);
					//$('#sidebar2').css('background-image',bgrnd);
					$('#article').css('display', 'none');
					$('#rollPanel').animate({
						width: '0px'
					},
					'normal',
					function() {
						$('#rollPanel').css('display', 'none');
						$('#mainContent').fadeIn("fast");
					});
					$(this).html('');

				});

			});
			return false;
		}
	});

	$('select').remove();
	

if ( window.preLoad ) {
preLoad();
}

});