/*
 * 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, windowName )
{
	if (url != null)
	{
		if ( windowName == null )
			windowName = "";
			
		if (width != null && height != null)
		{
			return window.open(url, windowName, "width=" + width +", height=" + height +", scrollbars=no, resizable=yes");
		}
		else
		{
			return window.open(url, windowName, "scrollbars=no, resizable=yes");
		}
	}
}

/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
*/ 

var w=1
var h=1

function gettrailobj()
{
	if (document.getElementById) return document.getElementById("trailimageid").style
	else if (document.all) return document.all.trailimagid.style
}

function truebody()
{
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function hidetrail()
{
	document.onmousemove=""
	gettrailobj().visibility="hidden"
	gettrailobj().left=-1000
	gettrailobj().top=0
}


function showtrail(width,height,file)
{
	if(navigator.userAgent.toLowerCase().indexOf('opera') == -1)
	{
		w=width
		h=height
		
		// followmouse()
	
		document.getElementById('ttimg').src=file
		document.onmousemove=followmouse
		gettrailobj().visibility="visible"
		gettrailobj().width=w+"px"
		gettrailobj().height=h+"px"


	}
}


function followmouse(e)
{

	if(navigator.userAgent.toLowerCase().indexOf('opera') == -1)
	{

		var xcoord=20
		var ycoord=20

		if (typeof e != "undefined")
		{
			xcoord+=e.pageX
			ycoord+=e.pageY
		}
		else if (typeof window.event !="undefined")
		{
			xcoord+=truebody().scrollLeft+event.clientX
			ycoord+=truebody().scrollTop+event.clientY
		}

		var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
		var docheight=document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)

		if (xcoord+w+3>docwidth)
		xcoord=xcoord-w-(20*2)

		if (ycoord-truebody().scrollTop+h>truebody().clientHeight)
		ycoord=ycoord-h-20;

		gettrailobj().left=xcoord+"px"
		gettrailobj().top=ycoord+"px"

	}

}

/*
 * 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: '',
	
	mainCartUrl: '',
	// 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');
	
		var pid = Form.getInputs(form, 'hidden', 'pid')[0].value;
		
		// 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
		// Pfaltzgraff does only text buttons!
		if (addButtons.length == 0)
		{
			addButtons = Form.getInputs(form, 'submit', 'add');
		}
		if (addButtons.length == 1)
		{
			addButton = addButtons[0];	
		}
	
		var previousImageSrc = null;
		var previousBackground = null;
	
		// show progress indicator
		if (addButton != null)
		{
			previousImageSrc = addButton.src;
			addButton.src = progressImageSrc;
			// since text buttons color them greyish
			previousBackground = addButton.style.backgroundColor;
			addButton.style.backgroundColor = "gray";
		}
		
		// This function is being called when the item was successfully added
		// to the shopping cart.  The return of the request is published to 
		// header top right corner: "Shopping Cart: 1 item $123"
		var handlerFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
				addButton.style.backgroundColor = previousBackground;
			}
			Form.enable(form);
		
			// Thisis actually the line in the top right corner:
			// "Shopping Cart: 1 item $123"
			// 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');
			// replace the content
			var minicart = $('minicart');
			minicart.innerHTML = req.responseText;

			var elem = $( "cartquick" );
			if ( elem != null )
			{
				// this seems to be working for both: IE && FF
				if ( elem.contentWindow.document.body.innerHTML.length > 0 )
				{
					elem.contentWindow.document.body.innerHTML = "<DIV class='clear'></DIV><H1><DIV style='margin: 50px 30px; padding: 10px 15px; background-color:#F1CD00;'> Please stand by while updating the cart!</DIV></H1>";
				}
			}
			
			// and this does an acutal load of the current basket
			// The pipeline is "Cart-Cartpopup".
			// the pid need to be specified otherwise the cart is displayed ugly
			PopupDiv.showByUrl(MiniCart.mainCartUrl + '?pid=' + pid,'cartquick');
		}

		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
				addButton.style.backgroundColor = previousBackground;
			}
			Form.enable(form);
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();

		// cloes a previous mini cart
		MiniCart.cartClose();
		// add the product
		// this request calls the ProductList-MiniAddProduct pipline.
		// the return value in responseText is the minicart line "Shopping Cart: 1 item $123"
		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('minicartcontent');
		}
	},

	// hook which can be replaced by individual pages/page types (e.g. cart)
	suppressSlideDown: function()
	{
		return false;
	}
}

/*
   Submits the given form with additional name and value pairs attached. 
   The parameters are passed as arbitrary length of name - value pairs.
   @param formElementId the form id
   @param name1 the name of the first attribute.
   @param value1 the value of the first attribute
   @param name2 the name of the 2nd attribute.
   @param value2 the value of the 2nd attribute
   @param name3 the name of the 3rd attribute.
   @param value3 the value of the 3rd attribute
*/
function submitWithAdditionalData(formElementId) {
	var el = $(formElementId);
	// iterate over all other arguments
	for (var i=1; i<arguments.length; i+=2) {
		addHiddenInputField(el, arguments[i], arguments[i+1]);
	}
	el.submit();
}

/*
   Adds an html hidden input field (dynamically created) to the given HTML form element.
   @param formElement the given HTML form element
   @param fieldName the name of the hidden input field
   @param fieldValue the (string) value of the hidden input field
*/
function addHiddenInputField(formElement, fieldName, fieldValue) {
   var inputElement = document.createElement("input");
   inputElement.setAttributeNode(createHtmlAttribute("type", "hidden"));
   inputElement.setAttributeNode(createHtmlAttribute("name", fieldName));
   inputElement.setAttributeNode(createHtmlAttribute("value", fieldValue));
   formElement.appendChild(inputElement);
}

/*
   Creates an html attribute.
   @param name the name of the attribute.
   @param value the (string) value of the attribute.
   @return the newly created html attribute
*/
function createHtmlAttribute(name, value) {
   var attribute = document.createAttribute(name)
   attribute.nodeValue = value
   return attribute
}

function resizeHandler()
{
	centerVisibleComponent($(PopupDiv.rti));
	$(PopupDiv.bg).style.top=getTop()+'px';
	$(PopupDiv.bg).style.left=getLeft()+'px';
	$(PopupDiv.bg).style.height=getHeight()+'px';
	$(PopupDiv.bg).style.width=getWidth()+'px';
	$(PopupDiv.bg).style.top=getTop()+'px';
}

function centerVisibleComponent(compo)
{
	var dimensions = compo.getDimensions();
	var ch=getTop()-(dimensions.height/4);
	var cw=getLeft()-dimensions.width/2;
	compo.style.marginTop =ch + 'px';
	compo.style.marginLeft =cw + 'px';
}

function centerComponent(compo)
{
	compo.style.visibility='hidden';
	compo.style.display='block';
	centerVisibleComponent(compo);
	compo.style.display='none';
	compo.style.visibility='';
}

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 0;
	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 10000;
	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
	{
		scrollPos=window.innerWidth;	
	}
//	return 2000;
	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 0;
	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);
}

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);
}



/* popup framework */

var PopupDiv = {
	rti: null,
    bg: null,
    
	show: function(arg)
	{
		PopupDiv.showWithBackground(arg,"popupbody");
	},

	showModal: function(arg)
	{
		PopupDiv.showWithBackground(arg,"modalpopupbody");
	},
	
	showWithBackground: function(arg,bg)
	{
		PopupDiv.bg = document.getElementById(bg);
		PopupDiv.bg.style.top=getTop()+'px';
		PopupDiv.bg.style.left=getLeft()+'px';
		PopupDiv.bg.style.height=(getHeight()-1)+'px';
		PopupDiv.bg.style.width=(getWidth()-getScrollerWidth())+'px';
		Effect.Appear2(bg);
		window.onresize=resizeHandler;
		window.onscroll=resizeHandler;
		PopupDiv.rti = arg;
		var popup = $(PopupDiv.rti);
		centerComponent(popup);
		popup.scrollTop=0;
		Effect.Appear(PopupDiv.rti);
	},
	
	close: function()
	{
		var elem = $( PopupDiv.rti );
		/*	
		if ( elem != null && typeof elem.contentDocument == 'undefined' )
		{
			// this is IE specific
			// it is actually not really working in the IE...
			if ( typeof elem.document.innerHTML != 'undefined' && elem.document.innerHTML.length > 0 )
			{
				elem.document.innerHTML = "";
			}
			// else
			// {
			// }
		}
		*/
		Effect.Fade(PopupDiv.rti);
		Effect.Fade('popupbody');
	},
	
	closeModal: function()
	{
		Effect.Fade(PopupDiv.rti);
		Effect.Fade('modalpopupbody');
	},
	
	showModalByUrl: function( url, arg, closeTimer, returnUrl )
	{
		PopupDiv.showByUrlWithBackground( url, arg, closeTimer, returnUrl ,"modalpopupbody");
	},
	
	showByUrl: function( url, arg, closeTimer, returnUrl )
	{
		PopupDiv.showByUrlWithBackground( url, arg, closeTimer, returnUrl ,"popupbody");
	},

	showByUrlWithBackground: function( url, arg, closeTimer, returnUrl ,bg)
	{
		PopupDiv.bg = document.getElementById(bg);
		var index=0;
		PopupDiv.rti = arg;
		PopupDiv.bg.style.top=getTop()+'px';
		PopupDiv.bg.style.left=getLeft()+'px';
		PopupDiv.bg.style.height=(getHeight()-1)+'px';
		PopupDiv.bg.style.width=(getWidth()-getScrollerWidth())+'px';
		PopupDiv.bg.style.top=getTop()+'px';
		window.onresize=resizeHandler;
		window.onscroll=resizeHandler;

		Effect.Appear2(bg);
		var popup = $(PopupDiv.rti);
		popup.src = url;
		centerComponent(popup);

		Element.hide(PopupDiv.rti);
		Effect.Appear(PopupDiv.rti);
	},
	
	showByContent: function( content, arg, closeTimer, returnUrl )
	{
		PopupDiv.showByContentWithBackground( content, arg, closeTimer, returnUrl ,"popupbody");
	},
	
	
	showByContentWithBackground: function( content, arg, closeTimer, returnUrl ,bg)
	{
		PopupDiv.bg = document.getElementById(bg);
		var index=0;
		PopupDiv.rti = arg;
		PopupDiv.bg.style.top=getTop()+'px';
		PopupDiv.bg.style.left=getLeft()+'px';
		PopupDiv.bg.style.height=(getHeight()-1)+'px';
		PopupDiv.bg.style.width=(getWidth()-getScrollerWidth())+'px';
		PopupDiv.bg.style.top=getTop()+'px';
		window.onresize=resizeHandler;
		window.onscroll=resizeHandler;
		Effect.Appear2(bg);
		var popup = $(PopupDiv.rti);
		popup.innerHTML = content;
		centerComponent(popup);
		Element.hide(PopupDiv.rti);
		Effect.Appear(PopupDiv.rti);
	}
	
}

/**
 * TODO: remove? never used anywhere in the code
 */
function toggleVisOn(id) {
	var e = document.getElementById(id);
	e.style.display = 'block';
}

/**
 * TODO: remove? never used anywhere in the code
 */
function toggleVisOff(id) {
	var e = document.getElementById(id);
	e.style.display = 'none';
}


/* 
Functionality for the submenu dropdown in the Header area */

function showsubmenu(id)
{
    var content = document.getElementById(id);
    content.style.display = 'block';
}

function hidesubmenu(id)
{
    var content = document.getElementById(id);
    content.style.display = 'none';
}
function toggle(id){
var content = document.getElementById(id);
if (content.className == 'collapsed') {
    content.className = 'expand'    } 
else {
    content.className = 'collapsed'}
}

/* not allow input other than numbers */
function numbercheck(el) {
	var val = el.value.replace(/[^\d]/g, '');
	el.value = val;
}

/**
 * This function executes the given function when the loading of the page has finished.
 * @param func The function to execute.
 */
function onContentReady(func) {
	if (window.attachEvent) {
		window.attachEvent("onload", func);
	}
	else
	{
		document.addEventListener('DOMContentLoaded',func,'false');
	}
}

/**
 * String helper functions
 */
/*
 * removes leading and tailing white spaces 
 */ 
function trim( str )
{
	var WHITE_CHAR = "\r\n\t ";
	var end = str.length - 1;
	while ( end >= 0 )
	{
		if ( WHITE_CHAR.indexOf( str.charAt( end ) ) == -1 )
			break;
		end--;
	}
	var start = 0;
	while ( start < end )
	{
		if ( WHITE_CHAR.indexOf( str.charAt( start ) ) == -1 )
			break;
		start++;
	}
	if ( end - start == str.length )
		return str;
	return str.substring( start, end + 1 );
}

/**
 * A none tolerant Int parser.  The regular parseInt() accepts "2qwe" 
 * without any complaints...  Also "ZXC" doesn't give any errors.
 */
function myParseInt( str )
{
	var ret = 0;
	if ( str == null )
		throw "NullPointer Exception in MyParseInt...";
	var c;
	for ( i = 0; i < str.length; i++ )
	{
		if ( ((c=str.charAt( i )) >= '0') && (c <= '9' ) )
		{
			ret = (10 * ret) + (1*c);
		}
		else
		{
			throw "'" + c + "' is not a digit!"; 
		}
	}
	return ret;
}

/**
 * close to the Java class MessageFormat
 * looks for {0}, {1}, ..., {n} and replaces them with the 
 * the corresponding elements from the args array.
 * since this is a light version, there are no spaces allowed within
 * the curly barckets, e.g. "{ 0 }" will be ignored.  Also 
 * any formater for the curley bracked will be ignored!
 */
function formatMessage( msg, args )
{
	var index;
	var lookFor;
	for ( var i = 0; i < args.length; i++ )
	{
		lookFor = "{" + i + "}";
		while ( (index = msg.indexOf( lookFor )) != -1 )
		{
			msg = msg.substring( 0, index ) + args[i] + msg.substring( index + lookFor.length ); 
		}
	}
	return msg;
} 


