/**
 * All java script logic for the Sally Beauty storefront application.
 *
 */

/**
 * Methods for country <--> state/province selectbox synchronisation in address forms.
 */
var shipToStates = "";

var savedCountries = null;
var savedStates = new Object();;

var countriesFiltered = false;
var containsEquip;
var containsOrmd;

function filterCountries(idextension)
{
	if (countriesFiltered)
		return;

	var countrySelection = document.getElementById('CountrySelection'+((idextension!=undefined)?idextension:''));
	
	if(savedCountries == null){
		savedCountries = new Array();
		for (var i = 1; i < countrySelection.options.length; i++)
		{
			var opt = new Option(countrySelection.options[i].text, countrySelection.options[i].value, countrySelection.options[i].selected, countrySelection.options[i].defaultSelected);
			opt.id = countrySelection.options[i].id;
			savedCountries[i] = opt;
		}
	}
	 
	// remove countries
	for (var i = countrySelection.options.length - 1 ; i > 0 ; i--)
	{
		//countrySelection.options[i] = null;
		countrySelection.remove(i);
	}
	
	// add filtered
	for (var i = 1; i < savedCountries.length; i++)
	{
		if((shipToStates.indexOf(savedCountries[i].id+'-') > -1)){
			var opt = new Option(savedCountries[i].text, savedCountries[i].value, savedCountries[i].selected, savedCountries[i].defaultSelected);
			opt.id = savedCountries[i].id;
			countrySelection.options[countrySelection.options.length] = opt;
		  	
		}
	}
	countriesFiltered = true;
}
 
function onCountrySelection(idextension, filter)
{
	var countrySelection = document.getElementById('CountrySelection'+((idextension!=undefined)?idextension:''));
	var stateSelection = document.getElementById('StateSelection'+((idextension!=undefined)?idextension:''));
	
	var selectedCountryId = countrySelection.options[countrySelection.selectedIndex].id;
	
	stateSelection.selectedIndex = 0;

	var index = idextension+'';
	if(savedStates[index] == undefined){
		savedStates[index] = new Array();
		for (var i = 0; i < stateSelection.options.length; i++)
		{
  		    var opt = new Option(stateSelection.options[i].text, stateSelection.options[i].value, stateSelection.options[i].selected, stateSelection.options[i].defaultSelected);
  		    opt.id = stateSelection.options[i].id;
			savedStates[index][i] = opt;
		}
	}
	 
	// remove countries
	for (var i = stateSelection.options.length - 1 ; i > 0; i--)
	{
	    //stateSelection.options[i] = null;
		stateSelection.remove(i);
	}
	//stateSelection.options.innerHtml = "";
	
	var opt = new Option(savedStates[index][0].text, savedStates[index][0].value, savedStates[index][0].selected, savedStates[index][0].defaultSelected);
	opt.id=savedStates[index][0].id;
	stateSelection.options[0] = savedStates[index][0];
	var start = 0;
	if(((selectedCountryId == "US") || (selectedCountryId == "CA"))){
	      opt = new Option(savedStates[index][0].text, savedStates[index][0].value, savedStates[index][0].selected, savedStates[index][0].defaultSelected);
		  opt.id=savedStates[index][0].id;
		  stateSelection.options[0] = opt;
		  start = 1;
	}
	

	// add filtered
	var j = start;
	if(containsEquip == undefined)
	{
		containsEquip = false;
	}
	if(containsOrmd == undefined)
	{
		containsOrmd = false;
	}
	for (var i = start; i < savedStates[index].length; i++)
	{
		if((containsEquip || containsOrmd)&& index == 2 && (savedStates[index][i].id == "US-AK" || savedStates[index][i].id == "US-HI"))
		{
			continue;
		}
		
		if((savedStates[index][i].id.indexOf(selectedCountryId) == 0) && (!filter || shipToStates.indexOf(savedStates[index][i].id) > -1)){
		  opt = new Option(savedStates[index][i].text, savedStates[index][i].value, savedStates[index][i].selected, savedStates[index][i].defaultSelected);
		  opt.id=savedStates[index][i].id;
		  stateSelection.options[j++] = opt;
		  //stateSelection.options[stateSelection.options.length-1].id = savedStates[i].id;
		}
	}

}

var firstStateSelectionFocus = new Array();

function onStateSelectionFocus(idextension,filter)
{
	if (((idextension+'') in firstStateSelectionFocus) && !firstStateSelectionFocus[idextension])
		return;
		
	firstStateSelectionFocus[idextension] = false;
	onCountrySelection(idextension,filter);
}

/*
 * Functionality around generic popups.
 */
var nojaxPopup = {
		// timer for automatic close of the popup
		timer: null,
		
		replacementTagId: null,

		show: function( replacementTagId, closeTimer )
		{
			// get the data of the form as serialized string
			var postdata = null;
			
			nojaxPopup.replacementTagId = replacementTagId;
		

				// replace the content
				var popup = $(nojaxPopup.replacementTagId);
				popup.style.display='';
				
				
				Element.extend(popup);
				makeElementCentered(popup);
				Element.hide(popup);
				popup.style.zIndex = 100; // overlay has 90
				
				fadeOut();
				new Effect.Appear(popup);

				// after a time out automatically close it
				/*
				if(!empty(closeTimer)){
					nojaxPopup.timer = setTimeout( 'Popup.close()', closeTimer );
				}
				*/

		},

		close: function()
		{
			if ( nojaxPopup.timer != null )
			{
				clearTimeout( Popup.timer );
				nojaxPopup.timer = null;
			}
			fadeIn();
			var popup = $(nojaxPopup.replacementTagId);
			popup.style.display='none';
			Effect.Fade(popup);
		}
	}


var Popup = {

	// timer for automatic close of the popup
	timer: null,
	
	replacementTagId: null,

	show: function( url, replacementTagId, closeTimer, returnUrl )
	{
		// get the data of the form as serialized string
		var postdata = null;
		
		Popup.replacementTagId = replacementTagId;
	
		var handlerFunc = function(req)
		{
			// replace the content
			var popup = $(Popup.replacementTagId);
			popup.innerHTML = req.responseText;
			
			Element.extend(popup);
			makeElementCentered(popup);
			Element.hide(popup);
			popup.style.zIndex = 100; // overlay has 90
			
			fadeOut();
			new Effect.Appear(popup);

			// after a time out automatically close it
			if(!empty(closeTimer)){
				Popup.timer = setTimeout( 'Popup.close()', closeTimer );
			}
		}

		var errFunc = function(req)
		{
		}

		// add the product
		new Ajax.Request( url, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});
	},

	close: function()
	{
		if ( Popup.timer != null )
		{
			clearTimeout( Popup.timer );
			Popup.timer = null;
		}
		fadeIn();
		var popup = $(Popup.replacementTagId);
		Effect.Fade(popup);
	}
}

/**
 * ProductCompare helper
 */

var ProductCompare = {

	products : new Object(),
	
	// called by the checkboxes
	update : function(checkbox){
		if(checkbox.checked){
			ProductCompare.products[checkbox.value]="compare";
		}else{
			delete ProductCompare.products[checkbox.value];
		}
	},
	
	// used at search result pages
	submit : function(url){
		var pstring = "";
		var product;
		for(product in ProductCompare.products){
			if(ProductCompare.products[product] == "compare"){
				pstring += product+",";
			}
		}
		pstring = pstring.substr(0,pstring.length-1);
		ProductCompare.openPopup(url+"?ProductIds="+escape(pstring));
	},

	// keep this method, that is how the default compare functionality works
	openPopup: function( url ) {
		window.open(
			url,
			'product_compare',
			'width=800,height=600,scrollbars=yes,resizable=yes',
			true /* replace history in the popped up window */
		).focus();
	}
}


function addToCartAction(formId, imgUrl)
{
	var aForm = document.forms[formId];
	if ((aForm.Warranty == null) || aForm.Warranty.checked)
	{
		MiniCart.cartAdd( aForm, imgUrl );
	}
	else
	{
		aForm.submit();
	}
}

function makeElementCentered(x)
{

	//get viewport's width and height
	var vpdims = getWindowDims();
	
	//get dialog's width and height
	var dims = x.getDimensions();
	
	//get dialog's scrolling offsets
	var offsets = getScrollXY();
	
	//calculate position
	dialogTop = (vpdims.height/2) - (dims.height/2) + offsets.yOffset;
	dialogLeft = (vpdims.width/2) - (dims.width/2) + offsets.xOffset;

	//Position the Dialog
	x.style.top =dialogTop+"px";
	x.style.left =dialogLeft+"px";
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { xOffset : scrOfX, yOffset : scrOfY };
}

function getWindowDims() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return { width : myWidth, height : myHeight };
}

function fadeOut(){
	var objBody = document.getElementsByTagName("body").item(0);
	
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objOverlay.onclick = function() { Popup.close(); return false; }
	objBody.appendChild(objOverlay);

	hideSelectBoxes();

	// stretch overlay to fill page and fade in
	var arrayPageSize = getPageSize();
	Element.setHeight('overlay', arrayPageSize[1]);
	new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.3 }); // DW: change
	
}

function fadeIn() {
	new Effect.Fade('overlay', { duration: 0.2});
	showSelectBoxes();
	
	// cleanup
	var objBody = document.getElementsByTagName("body").item(0);
	var objOverlay = $('overlay');
	objBody.removeChild(objOverlay);
}

// flash stuff (IE security workaround)
function insertFlash(url, width, height){
	document.write('<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="ProductFlash" type="application/x-shockwave-flash" width="'+width+'" height="'+height+'" data="'+url+'">');
	document.write('	<param name=movie value="'+url+'">');
	document.write('	<param name="wmode" value="transparent">');
    document.write('    <EMBED src="'+url+'" WIDTH="'+width+'" HEIGHT="'+height+'" SWLIVECONNECT="true" NAME="ProductFlash"');
	document.write('        TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">');
    document.write('    </EMBED>');
	document.write('</object>');
}

//******************************************************************************************************
// START script for rollover popups
//******************************************************************************************************

/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
*/

var offsetfrommouse=[15,25]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0; //duration in seconds image should remain visible. 0 for always.

var defaultimageheight = 40;	// maximum image size.
var defaultimagewidth = 40;	// maximum image size.

var timer;

function gettrailobj(){
if (document.getElementById)
return document.getElementById("preview_div").style
}

function gettrailobjnostyle(){
if (document.getElementById)
return document.getElementById("preview_div")
}


function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : 

document.body
}


function hidetrail(){	
	gettrailobj().display= "none";
	document.onmousemove=""
	gettrailobj().left="-500px"
	clearTimeout(timer);
}

function showtrail(imagename,title,width,height){
	i = imagename
	t = title
	w = width
	h = height
	timer = setTimeout("show('"+i+"',t,w,h);",200);
}
function show(imagename,title,width,height){
 
    var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth - 

offsetfrommouse[0]
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : 

Math.min(window.innerHeight)

	if( (navigator.userAgent.indexOf("Konqueror")==-1  || navigator.userAgent.indexOf("Firefox")!=-1 || 

(navigator.userAgent.indexOf("Opera")==-1 && navigator.appVersion.indexOf("MSIE")!=-1)) && (docwidth>650 && docheight>500)) 

{
		( width == 0 ) ? width = defaultimagewidth: '';
		( height == 0 ) ? height = defaultimageheight: '';
			
		width+=30
		height+=55
		defaultimageheight = height
		defaultimagewidth = width
	
		document.onmousemove=followmouse; 

		
		newHTML = '<div class="border_preview" style="width:'+  width +'px;height:'+ height +'px"><div id="loader_container"><div id="loader"><div align="center">Loading template preview...</div><div id="loader_bg"><div id="progress"> </div></div></div></div>';
		newHTML = newHTML + '<h3 class="title_h3">' + ' '+title + '</h3>'
    	newHTML = newHTML + '<div class="preview_temp_load"><img onload="javascript:remove_loading();" src="' + imagename + '" border="0"></div>';
		newHTML = newHTML + '</div>'; 
		
		if(navigator.userAgent.indexOf("MSIE")!=-1 && navigator.userAgent.indexOf("Opera")==-1 ){
			newHTML = newHTML+'<iframe src="about:blank" scrolling="no" frameborder="0" width="'+width+'" height="'+height+'"></iframe>';
		}		

		gettrailobjnostyle().innerHTML = newHTML;
		gettrailobj().display="block";
	}
}

function followmouse(e){

	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : 

Math.min(window.innerHeight)

	if (typeof e != "undefined"){
		if (docwidth - e.pageX < defaultimagewidth + 2*offsetfrommouse[0]){
			xcoord = e.pageX - xcoord - defaultimagewidth; // Move to the left side of the cursor
		} else {
			xcoord += e.pageX;
		}
		if (docheight - e.pageY < defaultimageheight + 2*offsetfrommouse[1]){
			ycoord += e.pageY - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + e.pageY - docheight - truebody().scrollTop));
		} else {
			ycoord += e.pageY;
		}

	} else if (typeof window.event != "undefined"){
		if (docwidth - event.clientX < defaultimagewidth + 2*offsetfrommouse[0]){
			xcoord = event.clientX + truebody().scrollLeft - xcoord - defaultimagewidth; // Move to the left side of the cursor
		} else {
			xcoord += truebody().scrollLeft+event.clientX
		}
		if (docheight - event.clientY < (defaultimageheight + 2*offsetfrommouse[1])){
			ycoord += event.clientY + truebody().scrollTop - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + event.clientY - docheight));
		} else {
			ycoord += truebody().scrollTop + event.clientY;
		}
	}
	gettrailobj().left=xcoord+"px"
	gettrailobj().top=ycoord+"px"

}

var t_id = setInterval(animate,20);
var pos=0;
var dir=2;
var len=0;

function animate()
{
var elem = document.getElementById('progress');
if(elem != null) {
if (pos==0) len += dir;
if (len>32 || pos>79) pos += dir;
if (pos>79) len -= dir;
if (pos>79 && len==0) pos=0;
elem.style.left = pos;
elem.style.width = len;
}
}

function remove_loading() {
this.clearInterval(t_id);
var targelem = document.getElementById('loader_container');
targelem.style.display='none';
targelem.style.visibility='hidden';
var t_id = setInterval(animate,60);
}

//******************************************************************************************************
// END script for rollover popups
//******************************************************************************************************

/**
 * get paramater from query string
 */

function getQueryStringParam(){

	// get querystring as an array split on "&"
	var querystring = location.search.replace( '?', '' ).split( '&' );
	// declare object
	var queryObj = {};
	// loop through each name-value pair and populate object
	for ( var i=0; i<querystring.length; i++ ) {
	      // get name and value
	      var name = querystring[i].split('=')[0];
	      var value = querystring[i].split('=')[1];
	      // populate object
	      queryObj[name] = value;
	}
	
	return queryObj;
}
