/*
 * All java script logic for the Demandware reference application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */


/*
 * Register more initializations here
 */
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, scroll )
{
	if (url != null)
	{
		if (width != null && height != null)
		{
			window.open(url, "", "width=" + width +", height=" + height +", scrollbars=" + scroll +", resizable=yes");
		}
		else
		{
			window.open(url, "", "scrollbars=no, resizable=yes");
		}
	}
}


/*
 * Support for the compare window
 */
ProductCompare = {
	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();
	}
}


/*
 * 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: '',

	// during page loading, the Demandware URL is stored here
	editurl: '',

	totalURL: '',
	
	itemsURL: '',
	
	// 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)
		{			
			// execute all scripts which are transmitted in the response
			// for example warning that the product is not in stock 
			req.responseText.evalScripts();
			req.responseText.stripScripts();
			// 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 minicarttotal = $('minicarttotal');
			//var pos = Position.cumulativeOffset(minicarttotal);
			//var dim = Element.getDimensions(minicarttotal);

			// replace the content
			//alert(req.responseText;)
			var minicart = $('minicart');			
			minicart.innerHTML = req.responseText;
			//alert(minicart);
			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 minicartcontent2 = $('minicartcontent2');	
				new Effect.SlideDown('minicartcontent2');			
	
				// after a time out automatically close it
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
				cmDisplayShop5s();
			}
		}
		


		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();

		// cloes a previous mini cart
		MiniCart.cartClose();		
		
		// show a loading message under the add to bag button
		var underbag = $('divunderaddtobag');
		var quickview = window.frames.quickview;
		if(quickview != undefined) {				
			underbag = quickview.document.getElementById('divunderaddtobag');
			// fix for internet explorer because the elements
			// does not have yet the update function
			if(navigator.appVersion.match(/\bMSIE\b/)) {
				underbag = Element.extend(underbag);
			}
		}
		// this already disappeared during quick view
		if(underbag != undefined) {
			underbag.update("<img src='"+progressImageSrc+"' alt='' />");
		}
		// add the product	
		new Ajax.Request( MiniCart.url, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});	
	},

	cartEdit: 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', 'edit');
	
		// 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)
		{			
			// execute all scripts which are transmitted in the response
			// for example warning that the product is not in stock 
			req.responseText.evalScripts();
			req.responseText.stripScripts();
			// 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 minicarttotal = $('minicarttotal');
			//var pos = Position.cumulativeOffset(minicarttotal);
			//var dim = Element.getDimensions(minicarttotal);

			// replace the content
			//alert(req.responseText;)
			//var minicart = $('minicart');			
			//minicart.innerHTML = req.responseText;
			//alert(minicart);
			//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 minicartcontent2 = $('minicartcontent2');	
				//new Effect.SlideDown('minicartcontent2');			
	
				// after a time out automatically close it
				//MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
				//cmDisplayShop5s();
			//}
		}
		


		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();

		// cloes a previous mini cart
		//MiniCart.cartClose();		
		
		// show a loading message under the add to bag button
		var underbag = $('divunderaddtobag');
		var quickview = window.frames.quickview;
		if(quickview != undefined) {				
			underbag = quickview.document.getElementById('divunderaddtobag');
			// fix for internet explorer because the elements
			// does not have yet the update function
			if(navigator.appVersion.match(/\bMSIE\b/)) {
				underbag = Element.extend(underbag);
			}
		}
		// this already disappeared during quick view
		if(underbag != undefined) {
			underbag.update("<img src='"+progressImageSrc+"' alt='' />");
		}
		// add the product	
		new Ajax.Request( MiniCart.editurl, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});	
	},
	
	cartRemove: 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', 'remove');
	
		// 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)
		{			
			// execute all scripts which are transmitted in the response
			// for example warning that the product is not in stock 
			req.responseText.evalScripts();
			req.responseText.stripScripts();
			// 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 minicarttotal = $('minicarttotal');
			//var pos = Position.cumulativeOffset(minicarttotal);
			//var dim = Element.getDimensions(minicarttotal);

			// replace the content
			//alert(req.responseText;)
			//var minicart = $('minicart');			
			//minicart.innerHTML = req.responseText;
			//alert(minicart);
			//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 minicartcontent2 = $('minicartcontent2');	
				//new Effect.SlideDown('minicartcontent2');			
	
				// after a time out automatically close it
				//MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
				//cmDisplayShop5s();
			//}
		}
		


		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();

		// cloes a previous mini cart
		//MiniCart.cartClose();		
		
		// show a loading message under the add to bag button
		var underbag = $('divunderaddtobag');
		var quickview = window.frames.quickview;
		if(quickview != undefined) {				
			underbag = quickview.document.getElementById('divunderaddtobag');
			// fix for internet explorer because the elements
			// does not have yet the update function
			if(navigator.appVersion.match(/\bMSIE\b/)) {
				underbag = Element.extend(underbag);
			}
		}
		// this already disappeared during quick view
		if(underbag != undefined) {
			underbag.update("<img src='"+progressImageSrc+"' alt='' />");
		}
			// remove the product
		new Ajax.Request( MiniCart.removeurl, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});	
	},
	
	cartClose: function()
	{
			
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			Effect.SlideUp('minicartcontent2');			
			new Ajax.Updater('minicarttotal', MiniCart.totalURL,{asynchronous:false, evalScripts:true });
			new Ajax.Updater('qvFly', MiniCart.itemsURL,{asynchronous:false, evalScripts:true });
			var quickview = window.frames.quickview;
			//if(quickview == undefined) 
			//{
			//checkCart();
			//}				
			
			
		}
	},
	
	cartRefresh: function(checkoutstep)
	{
		//location.href = location.href;
		// new Ajax.Updater('cart', MiniCart.showurl,{asynchronous:false, evalScripts:true });	
		//new Ajax.Updater('cartfooter', MiniCart.showurltotal,{asynchronous:false, evalScripts:true });	
		new Ajax.Updater('minicarttotal', MiniCart.totalURL,{asynchronous:false, evalScripts:true });
		new Ajax.Updater('qvFly', MiniCart.itemsURL,{asynchronous:false, evalScripts:true });
		//new Ajax.Updater('errormessage', MiniCart.showurlErrorMessage,{asynchronous:false, evalScripts:true });
		
		// Address Page
		if (checkoutstep == "2") {
			new Ajax.Updater('ContainerAddress', MiniCart.showurlAddress,{asynchronous:false, evalScripts:true });
		}
		
		// Shipping Page
		if (checkoutstep == "3") {
			new Ajax.Updater('ContainerShipping', MiniCart.showurlShipping,{asynchronous:false, evalScripts:true });
			new Ajax.Updater('cShipping', MiniCart.showurlShippingInfo,{asynchronous:false, evalScripts:true });
			new Ajax.Updater('ajaxshippingaddressform', MiniCart.showurlShippingPromo,{asynchronous:false, evalScripts:true });
		}
		
		//Payment Page
		if (checkoutstep == "4") {
			new Ajax.Updater('ContainerPayments', MiniCart.showurlPayments,{asynchronous:false, evalScripts:true });
			new Ajax.Updater('cPayments', MiniCart.showurlPaymentsInfo,{asynchronous:false, evalScripts:true });
			new Ajax.Updater('editedorder', MiniCart.showurlOrderDetails,{asynchronous:false, evalScripts:true });
		}
		
	},

	// hook which can be replaced by individual pages/page types (e.g. cart)
	suppressSlideDown: function()
	{
		return false;
	}
}

Effect.Appear2 = function(ele) {
  element = $(ele);
  var options = Object.extend(
  {
  	from: 0.0,
  	to:   element.getOpacity(),
  	// force Safari to render floated elements properly
  	afterFinishInternal: function(effect) 
  	{
    	effect.element.forceRerendering();
  	},
  	beforeSetup: function(effect) 
  	{
    	effect.element.setOpacity(effect.options.from);
    	effect.element.show(); 
  	}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

var PopupDiv = {
	rti: null,

	show: function(arg)
	{
		$('popupbody').style.top=getTop()+'px';
		$('popupbody').style.left=getLeft()+'px';		
		$('popupbody').style.height=(getHeight()-1)+'px';	
		$('popupbody').style.width=(getWidth()-scrollerWidth)+'px';
		//Effect.Appear2('popupbody');
		document.getElementById('popupbody').style.display = 'block';
		window.onresize=resizeHandler;
		window.onscroll=resizeHandler;
		PopupDiv.rti = arg;
		var popup = $(PopupDiv.rti);
		centerComponent(popup);
		popup.scrollTop=0;
		//Effect.Appear(PopupDiv.rti);
		document.getElementById(PopupDiv.rti).style.display = 'block';
	},

	close: function()
	{
		
		document.getElementById(PopupDiv.rti).src = "";
		document.getElementById(PopupDiv.rti).style.display = 'none';
		document.getElementById('popupbody').style.display = 'none'
				
		//Effect.Fade(PopupDiv.rti);
		//Effect.Fade('popupbody');
	},
		
	
	showByUrl: function( url, arg, closeTimer, returnUrl )
	{
		var index=0;
		PopupDiv.rti = arg;
		$('popupbody').style.top=getTop()+'px';
		$('popupbody').style.left=getLeft()+'px';
		$('popupbody').style.height=(getHeight())+'px';		
		$('popupbody').style.width=(getWidth()-1)+'px';
		//$('popupbody').style.width=(getWidth()-scrollerWidth)+'px';
		//alert($('popupbody').style.width);
		$('popupbody').style.top=getTop()+'px';
		window.onresize=resizeHandler;
		window.onscroll=resizeHandler;
		document.getElementById(PopupDiv.rti).style.display = 'none';
		//Effect.Appear2('popupbody');
		document.getElementById('popupbody').style.display = 'block';
		var popup = $(PopupDiv.rti);
		popup.src = url;
		centerComponent(popup);
		//Element.hide(PopupDiv.rti);
		document.getElementById(PopupDiv.rti).style.display = 'block';
		//Effect.Appear(PopupDiv.rti);
	}
}

function resizeHandler()
{
	centerVisibleComponent($(PopupDiv.rti));
	$('popupbody').style.top=getTop()+'px';
	$('popupbody').style.left=getLeft()+'px';
	$('popupbody').style.height=getHeight()+'px';
	$('popupbody').style.width=getWidth()+'px';
	$('popupbody').style.top=getTop()+'px';
}

function centerVisibleComponent(compo)
{
	var ch=getTop() + getHeight()/2 - compo.clientHeight/2;
	var cw=getLeft() + getWidth()/2 - compo.clientWidth/2;
	compo.style.marginTop =ch + 'px';
	compo.style.marginLeft =cw + 'px';
}

function centerComponent(compo)
{
	compo.style.visibility='hidden';
	compo.style.display='block';
	var ch=getTop() + getHeight()/2 - compo.clientHeight/2;
	var cw=getLeft() + getWidth()/2 - compo.clientWidth/2;
	compo.style.display='none';
	compo.style.visibility='';
	compo.style.marginTop =ch + 'px';
	compo.style.marginLeft =cw + 'px';
}

function getLeft()
{
	var scrollPos;
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(typeof window.pageXOffset != 'undefined')
		{
			scrollPos=window.pageXOffset;
		}
		else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
		{
			scrollPos=document.documentElement.scrollLeft;
		}
		else if(typeof document.body != 'undefined')
		{
			scrollPos=document.body.scrollLeft;
		}
	} 
	else
	{
		scrollPos=window.pageXOffset;	
	}
	return scrollPos;
}

function getHeight()
{
	var scrollPos;
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(typeof window.innerHeight != 'undefined')
		{
			scrollPos=window.innerHeight;
		}
		else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
		{
			scrollPos=document.documentElement.clientHeight;
		}
		else if(typeof document.body != 'undefined')
		{
			scrollPos=document.body.clientHeight;
		}
	} 
	else
	{
		scrollPos=window.innerHeight;	
	}
	return scrollPos;
}

function getWidth()
{
	var scrollPos;
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(typeof window.innerWidth != 'undefined')
		{
			scrollPos=window.innerWidth;
		}
		else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
		{
			scrollPos=document.documentElement.clientWidth;
		}
		else if(typeof document.body != 'undefined')
		{
			scrollPos=document.body.clientWidth;
		}
	} 
	else if (navigator.userAgent.match(/Safari/i)) {
		scrollPos=((window.innerWidth)-14);	
	}
	else 
	{
		scrollPos=((window.innerWidth)-17);			
	}
	return scrollPos;
}

function getTop()
{
	var scrollPos;
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(typeof window.pageYOffset != 'undefined')
		{
			scrollPos=window.pageYOffset;
		}
		else if(typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat')
		{
			scrollPos=document.documentElement.scrollTop;
		}
		else if(typeof document.body != 'undefined')
		{
			scrollPos=document.body.scrollTop;
		}
	} 
	else
	{
		scrollPos=window.pageYOffset;	
	}
	return scrollPos;
}

/************************************************
 * Returns the width of the windows scrollers 
 ************************************************/
function getScrollerWidth() {
    var scr = null;
    var inn = null;
    var wNoScroll = 0;
    var wScroll = 0;

    // Outer scrolling div
    scr = document.createElement('div');
    scr.style.position = 'absolute';
    scr.style.top = '-1000px';
    scr.style.left = '-1000px';
    scr.style.width = '100px';
    scr.style.height = '50px';
    // Start with no scrollbar
    scr.style.overflow = 'hidden';

    // Inner content div
    inn = document.createElement('div');
    inn.style.width = '100%';
    inn.style.height = '200px';

    // Put the inner div in the scrolling div
    scr.appendChild(inn);
    // Append the scrolling div to the doc
    document.body.appendChild(scr);

    // Width of the inner div sans scrollbar
    wNoScroll = inn.offsetWidth;
    // Add the scrollbar
    scr.style.overflow = 'auto';
    // Width of the inner div width scrollbar
    wScroll = inn.offsetWidth;

    // Remove the scrolling div from the doc
    document.body.removeChild(
        document.body.lastChild);

    // Pixel width of the scroller
//    return (wNoScroll - wScroll);
return 100;
}

function refreshTaxAddress(form){
var shipToState = document.getElementById('ShipToState').value;
var ShipToCountry = document.getElementById('ShipToCountry').value;
var ShipToCity = document.getElementById('ShipToCity').value;
var ShipToZip = document.getElementById('ShipToZip').value;


if(ShipToCountry =="US" ||ShipToCountry =="CA"){

	  if(shipToState!="" && ShipToCountry!=="" && ShipToCity!=="" && ShipToZip!=="") {				
     
            //document.getElementById('tfoot').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'></div>";
            // get the data of the form as serialized string
            var postdata = Form.serialize(form);
           // alert(postdata);
            // get the methods and update list
			new Ajax.Updater('ContainerAddress', taxUrl,{ method: 'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc });
                        
            var handlerFunc = function(req) {
                  Form.enable(form);
            }

            var errFunc = function(req) {
                  Form.enable(form);
            }
 	   }
 } else {
         
            // $('tfoot').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'></div>";
            // get the data of the form as serialized string
           
            var postdata = Form.serialize(form);
            document.getElementById('ShipToZip').value = ""; 
            // get the methods and update list
			new Ajax.Updater('ContainerAddress', taxUrl,{ method: 'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc });
                        
            var handlerFunc = function(req)
            {
                 
                  Form.enable(form);
                 
            }

            var errFunc = function(req)
            {
                  Form.enable(form);
            }
                 
   }
 }
 

function refreshCart(form){
//var shipToState = document.getElementById('ShipToState').value;
var ShipToCountry = document.getElementById('ShipToCountry').value;
//var ShipToCity = document.getElementById('ShipToCity').value;
var ShipToZip = document.getElementById('ShipToZip').value;


if(ShipToCountry =="US"){

	     
            //document.getElementById('tfoot').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'></div>";
            // get the data of the form as serialized string
            var postdata = Form.serialize(form);
          //  alert(postdata);
            // get the methods and update list
          	new Ajax.Updater('updatecartshipping', shipUrl,{ method: 'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc });
           // new Ajax.Updater('shippingCalc',shipTaxTotalUrl,{asynchronous:false, evalScripts:true });          
            var handlerFunc = function(req) {
                  Form.enable(aform);
            }

            var errFunc = function(req) {
                  Form.enable(aform);
            }
 	  
 } else {
      
         
            // $('tfoot').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'></div>";
            // get the data of the form as serialized string
           
            var postdata = Form.serialize(form);
            document.getElementById('ShipToZip').value = ""; 
            // get the methods and update list
         	new Ajax.Updater('updatecartshipping',shipUrl,{ method: 'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc });
           // new Ajax.Updater('shippingCalc', shipTaxTotalUrl,{asynchronous:false, evalScripts:true });          
           
            var handlerFunc = function(req)
            {
                 
                  Form.enable(form);
                 
            }

            var errFunc = function(req)
            {
                  Form.enable(form);
            }
                 
   }
 }
 

function CartTotalShippingTax()
 {
// document.getElementById('shippingCalc').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'></div>";
 // new Ajax.Updater('shippingCalc', shipTaxTotalUrl,{asynchronous:false, evalScripts:true });  
 
	$("shippingCalc").innerHTML = '';
	$("shippingCalc").hide();
 }
  
function OrderHistoryAjax(Url) {
	Ajax.Responders.register({   
		onCreate: function(){
			$('orderhistorylist').innerHTML = "<div style='padding-bottom: 8px;padding-left:10px'><img src='"+svrPath+"images/loadingAnimation.gif'> Loading...Please Wait</div>";        
			}
		});
	new Ajax.Updater('orderhistorylist', Url, { method: 'post', asynchronous: true,
		onFailure: function() {
			$('orderhistorylist').innerHTML = "An error occurred. Please try again.";
		}
		});
}  