//Product Selection Tool
function prodSelector(){
	var categoryInput = $('category');
	var categoryDisplay = $('categoryDisplay');
	var selectorContainer = $('productSelector');
	var statusContainer = $('selectorStatus');
	var categoryContainer = $('productCategories');
	var submitButtons = $$('p.submit');
	var resetButtons = $$('label.reset');
	var selectBoxes = $$('#hasIE6 #main select');
	
	if(!selectorContainer) return false;
	
	//Manage all click related events on the categories and subcategories.
	var categoryMasterList = categoryContainer.down('ul');
	
	normalizeListHeight(categoryMasterList);
	var categoryMasterHTML = categoryMasterList.innerHTML;
	
				
	var chosenCategories = new Element('ul');
	chosenCategories.addClassName('chosenCategories');
	
	statusContainer.down('p.submit').insert({before: chosenCategories});
	
	categoryInput.value = 'Select Category >'; //Reset the value on start.
	//Observe the click on the input and bring up the selection window. Create a darkened lightbox
	//back-drop to focus the user's attention.  Hide panel and destroy background on click out.
	
	//Function - Normalize List Height
	//Parameter: listContainer - Containing Unordered List Element
	//Go into the Categories panel and fix the heights of the LIs by
	//grabbing the height of the third item and matching the previous LI heights to it
	function normalizeListHeight(listContainer){
		var listElements = listContainer.childElements('li');
		//console.log(listElements);
		
		listElements.eachSlice(3, function(listSlice){
			var maxHeight = listSlice.max(function(listElement){
				return listElement.getHeight();
			});
			
			listSlice.each(function(listElement){
				listElement.setStyle({
					height: maxHeight + 'px'
				});
			});
		});
	}
	
	categoryDisplay.observe('click', function(event){
		selectorContainer.addClassName('shown');
		selectorContainer.hide();
		
		categoryMasterList.innerHTML = categoryMasterHTML;
		//console.log(categoryMasterHTML);
		var categoryLinks = categoryMasterList.select('li');
		
		categoryLinks.each(function(categoryLink, index) {
			categoryLink.observe('click', function(event){

		      	statusContainer.appear();		
				var subCategory = categoryLink.down('ul');
				var previousList = categoryLink.up('ul');
				
				if(subCategory){
					var categoryName = subCategory.up('li').down('a').innerHTML.unescapeHTML();
					categoryDisplay.update(categoryDisplay.innerHTML + '<span>' + categoryName + '</span>');
					document.getElementById("subproduct").value=categoryName;
					
					categoryInput.value = categoryName;
					
					previousList.remove();
					
					categoryContainer.down('h2').insert({after: subCategory});
					
					categoryItem = new Element('li');				
					categoryItem.update(categoryName);
					
					chosenCategories.insert({bottom: categoryItem});
					
					normalizeListHeight(categoryContainer.down('ul'));
					
				} 
				else{
					var categoryName = this.down('a').innerHTML.unescapeHTML();
					document.RequestForm["sourceid"].value=this.down('a').name;
					document.getElementById("subproduct").value=document.getElementById("subproduct").value+","+categoryName;
					categoryInput.value = categoryName;
					categoryDisplay.update(categoryDisplay.innerHTML + '<span>' + categoryName + '</span>');
					blackout.fire('parker:closeSelector');
				}
			});
			
		});
		
		new Effect.Appear(selectorContainer, {duration: .5});
		var selectcat ="Select Category";
		if(document.getElementById("selectcategorys")!=null)
		{
			selectcat = document.getElementById("selectcategorys").innerHTML;
		}
		categoryDisplay.update('<em>'+selectcat+'</em> ');		
		
		var viewport = document.viewport.getDimensions();
		var viewportWidth = viewport.width; // Usable window width
		var viewportHeight = viewport.height; // Usable window height
		var pageBody = $('main');
		var pageBodyOffset = pageBody.cumulativeOffset();
		
		//Reset list contents to the Master Category List
		categoryContainer.down('ul').remove();
		categoryContainer.insert({
			bottom: categoryMasterList
		});
		
		if(chosenCategories.down('li')){
			chosenCategories.innerHTML = "";
		}
		
		//To stop IE6 select box zindex issue, we hide them while the tools in use.
		selectBoxes.each(function(selectBox){
			selectBox.hide();
		});
		
		//Create page blackout 
		blackout = new Element('div');
		blackout.addClassName('blackout');
		blackout.setOpacity(.5);
		blackout.setStyle({
			width: viewportWidth + 'px',
			height: viewportHeight + 1000 + 'px'
		});
		
		//reposition the tool to the top center of the page.
		selectorContainer.setStyle({
			left: pageBodyOffset.left + 'px',
			top: pageBodyOffset.top + 'px'
			
		});
		
		pageBody.insert({
			bottom: blackout
		});
		
		//Create Close Button
		closeButton = new Element('p');
		closeButton.addClassName('close');
		closeButton.update('Close Selector');
		
		categoryContainer.insert({
			top: closeButton
		});
		
		//Handle the submission events.
		blackout.observe('click', function(event){
			blackout.fire('parker:closeSelector');
		});
	
		closeButton.observe('click', function(event){
			blackout.fire('parker:closeSelector');
			
		});
	});	
		
	//Handle the final submission event.
	submitButtons.each(function(submitButton){
		submitButton.observe('click', function(event){
			blackout.fire('parker:closeSelector');		
		});
	});
	
	resetButtons.each(function(resetButton){
		resetButton.observe('click', function(event){
			window.location.reload();
		});
	});
	
	statusContainer.setStyle({
		opacity: 0
	});
	
	document.observe('parker:closeSelector', function(event){		
		blackout.remove();
		stateHide("states");
		closeButton.remove();
		
		new Effect.Fade(selectorContainer, {duration: .2});
		
		selectBoxes.each(function(selectBox){
			selectBox.show();
		});
	});
	
}

//Resize blackout on window resize.
function resizeBlackout(){
	var blackouts = $$('div.blackout');			
	
	var selectorContainer = $('productSelector');
	var viewport = document.viewport.getDimensions();
	var viewportWidth = viewport.width; // Usable window width
	var viewportHeight = viewport.height; // Usable window height
	var pageBody = $('main');
	var pageBodyOffset = pageBody.cumulativeOffset();
	
	if(selectorContainer.hasClassName('shown')){
		
		blackouts.each(function(blackout){
			blackout.setStyle({
				width: viewportWidth + 'px',
				height: viewportHeight + 1000 + 'px'
			});
		});	
			
		selectorContainer.setStyle({
			left: pageBodyOffset.left + 'px',
			top: pageBodyOffset.top + 'px'
			
		});
	
	}
}


//Country Selection reveal City/State
function countryTool(){
	var cityStateFields = $$('label.optional');
	var countryOptions = $$('select.countrySelect option');
	var countrySelects = $$('select.countrySelect');
		
		countrySelects.each(function(countrySelect) {
			countrySelect.observe('change', function(event){
				
				var selectOptions = countrySelect.select('option');
				
				selectOptions.each(function(selectOption){
					if(selectOption.selected == true){
						if(selectOption.hasClassName('hasCityState')){
							cityStateFields.each(function(cityStateField){
								cityStateField.setStyle({
									display: 'block'
								});
							});
						} else {
							cityStateFields.each(function(cityStateField){
								cityStateField.setStyle({
									display: 'none'
								});
							});
						}
					}	
				});
			});
		});	
}

function selectWidthFix(){
	var resizedSelects = $$('#contact select.countrySelect');
		
		resizedSelects.each(function(resizedSelect){
			resizedSelect.setStyle({
				width: '300px'
			});
			resizedSelect.up('label').setStyle({
				height: resizedSelect.up('label').getHeight() + 'px'
			});
			resizedSelect.observe('mousedown', function(event){
				this.setStyle({
					width: 'auto'
				});
			});
			resizedSelect.observe('blur', function(event){
				this.setStyle({
					width: '300px'
				});
			});
			resizedSelect.observe('change', function(event){
				this.setStyle({
					width: '300px'
				});
			});
		});
}

//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
	var firstLIs =	$$('ul > li:first-child');
	var lastLIs = $$('ul > li:last-child');
	
	firstLIs.each(function(liFirst) {
		liFirst.addClassName('first');
		});
		
	lastLIs.each(function(liLast) {
		liLast.addClassName('last');
	});
}

//External Link Helper
//Updates Links with External Relation to
//use target="_blank"
function externalLinks(){
	var externalLinks = $$('a[rel=external]');
	
	externalLinks.each(function(externaLink){
		externalLinks.writeAttribute('target', '_blank');
	});
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
	var textInputs = $$('input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
			if(textInput.value == textInput.initialValue){
				textInput.clear();
			}
		});
		textInput.observe('blur', function(event){
			if(textInput.value.blank() == true) {
				textInput.value = textInput.initialValue;
			}
		});
	});
}

// Cookie Functions
// Set the cookie 
function setCookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// Read the cookie 
function readCookie(name) { 
	var needle = name + "="; 
	var cookieArray = document.cookie.split(';'); 
	for(var i=0;i < cookieArray.length;i++) { 
		var pair = cookieArray[i]; 
		while (pair.charAt(0)==' ') { 
			pair = pair.substring(1, pair.length); 
		} 
		if (pair.indexOf(needle) == 0) { 
			return pair.substring(needle.length, pair.length); 
		} 
	} 
	return null; 
}

//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {
	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	countryTool();
	prodSelector();
	Event.observe(document.onresize ? document : window, "resize", function() {
		resizeBlackout();
	});

	//selectWidthFix();
});
