/*
 * All java script logic for the Demanware reference application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */


/*
 * Register more initializations here
 * commented out to prevent collisions with init.js code

window.onload = function()
{
}
*/

/*
	Opens a new window with the provided url and dimension. Used
	for Scene7 and other situations.

	@param url the url to open
	@param width the window width
	@param height the window height
*/
function openPopup( url, width, height )
{
	if (url != null)
	{
		if (width != null && height != null)
		{
			window.open(url, "", "width=" + width +", height=" + height +", scrollbars=no, resizable=yes");
		}
		else
		{
			window.open(url, "", "scrollbars=no, resizable=yes");
		}
	}
}

// to accommodate threading on the server side
var LcgSelect1 = { url: '' }
var LcgSelect2 = { url: '' }

function xWalkTree(node, selectEle, selectedValue) {
	// we're interested in only the <option> tags
	if (node.nodeName == "option") {
		// create a new option element
		var optionEle = new Option(	node.attributes.getNamedItem("label").value, node.attributes.getNamedItem("value").value);			
		// before we add it to the list, is this a selected value?
		if (node.attributes.getNamedItem("value").value == selectedValue) {
			// yup
			optionEle.selected = true;			
		}
		// add it to the list
		selectEle.options.add(optionEle);
	}
	// just a simple way to walk the entire, returned XML structure
	for (var c = node.firstChild; c; c = c.nextSibling) {
	 	if (c.nodeType == 1) xWalkTree(c, selectEle, selectedValue);
	}
}

function handlerFunc(req) {
	// first, retrieve the execution context from the returned XMLDocument
	var contextNodes = req.responseXML.getElementsByTagName("context");
	var contextNode = contextNodes[0]; // better be one and only one "context" node
	// get the context string
	var context = contextNode.attributes.getNamedItem("value").value;
	
	// context string is "<id-of-targeted-select-tag>:<currently-selected-value>"
	var i = context.indexOf(":");
	// get the id
	var elementId = context.substring(0,i);
	// get the current value
	var currentValue = context.substring(i+1);
	// get the targeted select element		
	var selectEle = document.getElementById(elementId);	
	// finally, walk the returned XML looking for <option> elements with which to populate the select list
	xWalkTree(req.responseXML, selectEle, currentValue);	
}
function superChange(CAID, superSelectEleParm, subSelectEleParm) {
	// save these for the callback to reference
	this.subSelectEle = subSelectEleParm;
	this.subSelectEleCurrentValue = subSelectEleParm.value;			
	// reset the targeted select list
	subSelectEleParm.options.length = 0;	
	// "CAID" == "Content Asset ID" of dependent select list; "Filter" is the filtering value being applied
	var postdata = "CAID=" + CAID + "&Filter=" + superSelectEleParm.value + "&Context=" + subSelectEleParm.id + ":" + this.subSelectEleCurrentValue;
	// let's send it off and hope for the best!
	new Ajax.Request( this.url, {method:'post', postBody:postdata, onSuccess:this.handlerFunc});		
}
function LcgSelect(url) {
	this.url 						= url;
	this.subSelectEle 				= '';	
	this.subSelectEleCurrentValue 	= '';
	this.superChange			 	= superChange;
	this.handlerFunc			 	= handlerFunc;
	this.xWalkTree				 	= xWalkTree;
}

function addSelectOption(sele, otext, ovalue, oselected)
{
	var opt = document.createElement('option');
 	opt.text = otext;
 	opt.value = ovalue;
 	opt.selected = oselected;
 	try
 	{
 		sele.add(opt, null);
  	}
  	catch(ex)
  	{
  		sele.add(opt);
	}			  			
}

function stateFilter(countryCode, state, selectedState)
{
	var save = state.value;
	if (selectedState != null) {
		save = selectedState;
	}
	
	while(state.length > 0)
	{
		state.remove(0);
	}
	if(countryCode == 'US')
	{
		addSelectOption(state, 'select state/province', '', save == '');
		addSelectOption(state, 'Alabama', 'AL', save == 'AL');
		addSelectOption(state, 'Alaska', 'AK', save == 'AK');
		addSelectOption(state, 'American Samoa', 'AS', save == 'AS');
		addSelectOption(state, 'Armed Forces (AA)', 'AA', save == 'AA');
		addSelectOption(state, 'Armed Forces (AE)', 'AE', save == 'AE');
		addSelectOption(state, 'Armed Forces (AP)', 'AP', save == 'AP');
		addSelectOption(state, 'Arizona', 'AZ', save == 'AZ');
		addSelectOption(state, 'Arkansas', 'AR', save == 'AR');
		addSelectOption(state, 'California', 'CA', save == 'CA');
		addSelectOption(state, 'Colorado', 'CO', save == 'CO');
		addSelectOption(state, 'Connecticut', 'CT', save == 'CT');
		addSelectOption(state, 'Delaware', 'DE', save == 'DE');
		addSelectOption(state, 'District of Columbia', 'DC', save == 'DC');
		addSelectOption(state, 'Florida', 'FL', save == 'FL');
		addSelectOption(state, 'Georgia', 'GA', save == 'GA');
		addSelectOption(state, 'Guam', 'GU', save == 'GU');
		addSelectOption(state, 'Hawaii', 'HI', save == 'HI');
		addSelectOption(state, 'Idaho', 'ID', save == 'ID');
		addSelectOption(state, 'Illinois', 'IL', save == 'IL');
		addSelectOption(state, 'Indiana', 'IN', save == 'IN');
		addSelectOption(state, 'Iowa', 'IA', save == 'IA');
		addSelectOption(state, 'Kansas', 'KS', save == 'KS');
		addSelectOption(state, 'Kentucky', 'KY', save == 'KY');
		addSelectOption(state, 'Louisiana', 'LA', save == 'LA');
		addSelectOption(state, 'Maine', 'ME', save == 'ME');
		addSelectOption(state, 'Maryland', 'MD', save == 'MD');
		addSelectOption(state, 'Massachusetts', 'MA', save == 'MA');
		addSelectOption(state, 'Michigan', 'MI', save == 'MI');
		addSelectOption(state, 'Minnesota', 'MN', save == 'MN');
		addSelectOption(state, 'Mississippi', 'MS', save == 'MS');
		addSelectOption(state, 'Missouri', 'MO', save == 'MO');
		addSelectOption(state, 'Montana', 'MT', save == 'MT');
		addSelectOption(state, 'Nebraska', 'NE', save == 'NE');
		addSelectOption(state, 'Nevada', 'NV', save == 'NV');
		addSelectOption(state, 'New Hampshire', 'NH', save == 'NH');
		addSelectOption(state, 'New Jersey', 'NJ', save == 'NJ');
		addSelectOption(state, 'New Mexico', 'NM', save == 'NM');
		addSelectOption(state, 'New York', 'NY', save == 'NY');
		addSelectOption(state, 'North Carolina', 'NC', save == 'NC');
		addSelectOption(state, 'North Dakota', 'ND', save == 'ND');
		addSelectOption(state, 'Northern Mariana Islands', 'MP', save == 'MP');
		addSelectOption(state, 'Ohio', 'OH', save == 'OH');
		addSelectOption(state, 'Oklahoma', 'OK', save == 'OK');
		addSelectOption(state, 'Oregon', 'OR', save == 'OR');
		addSelectOption(state, 'Pennsylvania', 'PA', save == 'PA');
		addSelectOption(state, 'Puerto Rico', 'PR', save == 'PR');
		addSelectOption(state, 'Rhode Island', 'RI', save == 'RI');
		addSelectOption(state, 'South Carolina', 'SC', save == 'SC');
		addSelectOption(state, 'South Dakota', 'SD', save == 'SD');
		addSelectOption(state, 'Tennessee', 'TN', save == 'TN');
		addSelectOption(state, 'Texas', 'TX', save == 'TX');
		addSelectOption(state, 'Utah', 'UT', save == 'UT');
		addSelectOption(state, 'Vermont', 'VT', save == 'VT');
		addSelectOption(state, 'Virginia', 'VA', save == 'VA');
		addSelectOption(state, 'Virgin Islands', 'VI', save == 'VI');
		addSelectOption(state, 'Washington', 'WA', save == 'WA');
		addSelectOption(state, 'West Virginia', 'WV', save == 'WV');
		addSelectOption(state, 'Wisconsin', 'WI', save == 'WI');
		addSelectOption(state, 'Wyoming', 'WY', save == 'WY');
	}
	else if(countryCode == 'CA')
	{	
		addSelectOption(state, 'select state/province', '', save == '');
		addSelectOption(state, 'Alberta', 'AB', save == 'AB');
		addSelectOption(state, 'British Columbia', 'BC', save == 'BC');
		addSelectOption(state, 'Manitoba', 'MB', save == 'MB');
		addSelectOption(state, 'New Brunswick', 'NB', save == 'NB');
		addSelectOption(state, 'Newfoundland', 'NF', save == 'NF');
		addSelectOption(state, 'Northwest Territories', 'NT', save == 'NT');
		addSelectOption(state, 'Nova Scotia', 'NS', save == 'NS');
		addSelectOption(state, 'Ontario', 'ON', save == 'ON');
		addSelectOption(state, 'Prince Edward Island', 'PE', save == 'PE');
		addSelectOption(state, 'Quebec', 'QC', save == 'QC');
		addSelectOption(state, 'Saskatchewan', 'SK', save == 'SK');
		addSelectOption(state, 'Yukon Territory', 'YT', save == 'YT');
	}
}

/*
 * Functionality around the mini cart.
 */
var MiniCart = {
	// flag, whether cart is open or not
	state: 0,

	// during page loading, the Demandware URL is stored here
	url: '',
	popupURL: '',
	// timer for automatic close of cart item view
	timer: null,

	cartAdd: function( form, progressImageSrc )
	{
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);

		// get button reference
		var addButtons = Form.getInputs(form, 'image', 'add');
		
		// the button to update
		var addButton = null;
		
		// disable form
		Form.disable(form);

		// it is an array of buttons, but we need only one all
		// other combinations are strange so far
		if (addButtons.length == 1)
		{
			addButton = addButtons[0];	
		}
		
		var previousImageSrc = null;
	
		// show progress indicator
		if (addButton != null)
		{
			previousImageSrc = addButton.src;
			addButton.src = progressImageSrc;
		}
	
		var handlerFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
		
			// Get the position before the innerHTML is set. After
			// the set the elements have no coordinates. A display
			// refresh from the browser is necessary.
			var minicartcaption = $('minicartcaption');
			
			var pos = Position.cumulativeOffset(minicartcaption);
			var dim = Element.getDimensions(minicartcaption);
			
			// replace the content
			var shoppingbagcontainer = $('shoppingbagcontainer');
			
			shoppingbagcontainer.innerHTML = req.responseText;

			if( MiniCart.suppressSlideDown && MiniCart.suppressSlideDown() )
			{
				// do nothing
				// the hook 'MiniCart.suppressSlideDown()' should have done the refresh
				
			}
			else
			{
				// show the item
				// this display is optimized for Firefox. IE6/7 display the 
				// sliding down cart with an offset of -1
				var minicartcontent = $('minicart');
	
				new Effect.ScrollTo('header');
				new Effect.SlideDown('minicart');
	
				// after a time out automatically close it
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
			}
		}

		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
		}

		// cloes a previous mini cart
		MiniCart.cartClose();
		
		// add the product
		new Ajax.Request( MiniCart.url, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});
	},

	cartClose: function()
	{
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			Effect.SlideUp('minicart');
			//$('minicart').hide(); 
		}
	},

	// hook which can be replaced by individual pages/page types (e.g. cart)
	suppressSlideDown: function()
	{
		return false;
	}
}

function clearField(field){
   if (field.value == field.defaultValue) {
      field.value = "";
   }
}
