/*
 * All java script logic for the Demandware reference application.
 *
 * The code relies on the prototype.js, scriptaculous.js and jquery libraries to
 * be also loaded.
 */


/*
	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");
		}
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/*
 * 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: '',

	// timer for automatic close of cart item view
	timer: null,
	
	mcform: null,
	addButton : null,
	previousImageSrc: null,
	cartOpen: false,
	products: null,
	
	cartAdd: function( form, progressImageSrc )
	{
		this.mcform = form;
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			$('minicartcontent').hide();
		}

		// 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
		this.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)
		{
			this.addButton = addButtons[0];	
		}
	
		this.previousImageSrc = null;
	
		// show progress indicator
		if (this.addButton != null)
		{
			this.previousImageSrc = this.addButton.src;
			this.addButton.src = progressImageSrc;
		}

		// cloes a previous mini cart
		MiniCart.cartClose();

		MiniCart.products = ';' + $('opid').value;
		
		// add the product
		new Ajax.Request( MiniCart.url, {method:'post', postBody:postdata, onSuccess:this.handlerFunc, onFailure:this.errFunc});
	},

	outfitAdd: function( form, str, prods, progressImageSrc )
	{
		this.mcform = form;
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			$('minicartcontent').hide();
		}

		// get the data of the form as serialized string
		var postdata = str;
		
		// the button to update
		this.addButton = $('addtobag');
		
		// disable form
		Form.disable(form);
	
		this.previousImageSrc = null;
	
		// show progress indicator
		if (this.addButton != null)
		{
			this.previousImageSrc = this.addButton.src;
			this.addButton.src = progressImageSrc;
		}

		// cloes a previous mini cart
		MiniCart.cartClose();
		MiniCart.products = prods;

		// add the product
		new Ajax.Request( MiniCart.url, {method:'post', postBody:postdata, onSuccess:this.handlerFunc, onFailure:this.errFunc});
	},

	handlerFunc: function(req)
	{
		MiniCart.errFunc(req);
	
		// replace the content
		var minicart = $('minicart');
		minicart.innerHTML = req.responseText;

		if( MiniCart.suppressSlideDown && MiniCart.suppressSlideDown() )
		{
			// do nothing
			// the hook 'MiniCart.suppressSlideDown()' should have done the refresh
		}
		else
		{
			new Effect.ScrollTo('header');
			new Effect.SlideDown('minicartcontent');

			// after a time out automatically close it
			MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 4000 );
		}

		var s=s_gi(s_account);
		s.linkTrackVars="products,events";
		if(MiniCart.cartOpen)
		{
			s.events="scAdd";
			s.linkTrackEvents="scAdd";
		}
		else
		{
			s.events="scAdd,scOpen";
			s.linkTrackEvents="scAdd,scOpen";
			MiniCart.cartOpen = true;
		}

		s.products= MiniCart.products;
		MiniCart.products = null;

		s.tl(this,'o','Add to Cart');

	},

	errFunc: function(req)
	{
		// hide progress indicator
		if (MiniCart.addButton != null)
		{
			MiniCart.addButton.src = MiniCart.previousImageSrc;
		}
		Form.enable(MiniCart.mcform);
	},

	cartClose: function()
	{
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			Effect.SlideUp('minicartcontent');
		}
	},

	showCartNoClose: function()
	{
		if(!Element.visible('minicartcontent'))
		{
			Effect.SlideDown('minicartcontent');	
		}
	},
	
	showCartWithDelay: function()
	{
	    if(MiniCart.timer)
	    {
		  window.clearTimeout(MiniCart.timer);
		  MiniCart.timer=null;
	    }
	  	if(!Element.visible('minicartcontent'))
	  	{
	    	MiniCart.timer=window.setTimeout('MiniCart.showCartNoClose()',300); //0.3 seconds
	    }
	},

	closeCartWithDelay: function()	
	{
	    if(MiniCart.timer)
		{
		  window.clearTimeout(MiniCart.timer);
		  MiniCart.timer=null;
		}
	  	if(Element.visible('minicartcontent'))
		{
			MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 4000 );
		}
  	},

	// hook which can be replaced by individual pages/page types (e.g. cart)
	suppressSlideDown: function()
	{
		return false;
	}
}

function activateDropDownMenus()
{
	$$('.dropdown').invoke('observe', 'mouseover', ddMouseOver);
	$$('.dropdown .divider').invoke('observe', 'mouseover', ddMouseOverDivider);
	$$('.dropdown').invoke('observe', 'mouseout', ddMouseOut);
}

function ddMouseOver(e)
{
	$(this).down('a').addClassName('active');
	
	if ($(this).down('dl') != null && !$(this).down('dl').empty())
	{
		$(this).down('dl').show();
		if (jQuery.browser.msie && jQuery.browser.version == 6.0)
			iframeshim.positionUnder($(this).down('dl'), 17);
	}

	if ($(this).down('div') != null)
	{
		$(this).down('div').show();
		if (jQuery.browser.msie && jQuery.browser.version == 6.0)
			iframeshim.positionUnder($(this).down('div'), 17);
	}
}

function ddMouseOverDivider(e)
{
	e.stop();
}

function ddMouseOut()
{
	$(this).down('a').removeClassName('active');
	
	if (jQuery.browser.msie && jQuery.browser.version == 6.0)
		iframeshim.hide(); 

	if ($(this).down('dl') != null)
	{
		$(this).down('dl').hide();
	}
	if ($(this).down('div') != null)
	{
		$(this).down('div').hide();
	}
}

document.observe("dom:loaded", activateDropDownMenus);

/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/
jQuery.fn.equalHeights = function(px) {
	jQuery(this).each(function(){
		var currentTallest = 0;
		jQuery(this).children().each(function(i){
			if (jQuery(this).height() > currentTallest) { currentTallest = jQuery(this).height(); }
		});
		/*if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified */
		// for ie6, set height since min-height isn't supported
		if (jQuery.browser.msie && jQuery.browser.version == 6.0) { jQuery(this).children().css({'height': currentTallest}); }
		jQuery(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};

jQuery(document).ready(function() {
	// Handle click of the search button.
	jQuery('#searchButton').click(function (event) {
		event.preventDefault();
		jQuery('#SimpleSearchForm').submit();
	});
	
	// Clean up the Shop By Sport nav.
	jQuery('.shopBySportNav .sportNav:last').addClass('last');
	
	// Add the "Back to" link to the bread crumbs.  This is always the 
	// same as the last link in the bread crumbs.
	var lastLink = jQuery('#breadcrumbs a:last');
	jQuery('#breadcrumbs ul').prepend('<li class="first-crumb"><a href="' + $(lastLink).attr('href') + '">&laquo; Back to ' + $(lastLink).html() + '</a></li>');

	//hide search suggest when user clicks off
	jQuery('body').click(function(e){
		try {
			var ss = document.getElementById('search_suggest');
			ss.style.visibility = "hidden";
		} catch(e) {}
	})
});

JSONDecoder = new (function(){
	this.decode = function(json){
		return eval("(" + json + ')');
	};
})();

var searchReq;

function doServerQuery(searchTerm) {

	if(searchReq==undefined){
		searchReq = new Ajax.Request(searchSuggestURL, {
			method : "get",
			parameters : "q=" + encodeURI(searchTerm),
			onComplete: function(response){
				handleSearchSuggest(response.responseText);
			}
		});
	}
	else{
		searchReq = new Ajax.Request(searchSuggestURL, {
			method : "get",
			parameters : "q=" + encodeURI(searchTerm),
			onComplete: function(response){
				handleSearchSuggest(response.responseText);
			}
		});
	}
}

/**
 * Starts a delayed search suggest. 
 */
function suggest()
{
	window.setTimeout('searchSuggest()', 500);
}

/**
 * Does the actual suggest.
 */
function searchSuggest() {
	var ss = document.getElementById('search_suggest');
	ss.innerHTML = '';
	ss.style.visibility = "hidden";

	var str = document.getElementById('searchinput').value;
	
	//do not ask server for suggestions if user typed in 0 characters,
	//because of the huge amount of suggestions this would make no sense
	if(str.length == 0) return;
	//do a server call only if there is no request still on the run
	//because it keeps us from making requests quicker than we recieve them
	if (searchReq==undefined || searchReq.transport.readyState == 4 || searchReq.transport.readyState == 0) {
		doServerQuery(str);
	}
}

//Trims strings longer than charMax to charMax's length and appends '...' 
function elipsis(stringToTruncate, charMax){
	if(!stringToTruncate) 								return null;			
	if(!charMax || stringToTruncate.length <= charMax)	return stringToTruncate;
	for(var i=charMax; i>=0; i--)
		if(stringToTruncate.charAt(i) == " ") 			return stringToTruncate.substr(0, i) + "...";
	return stringToTruncate.substr(0, charMax) + "...";
}

/**
 * Handles the returned JSON response.
 */
function handleSearchSuggest(responseText) {
	var ss = document.getElementById('search_suggest');
	ss.innerHTML = '';
	ss.style.visibility = "hidden";

	var jsonPayload	= JSONDecoder.decode(responseText);

	if(jsonPayload.suggestions.length==0) return;

	for(i=0; i < jsonPayload.suggestions.length; i++) {
		//Build our element string.  This is cleaner using the DOM, but
		//IE doesn't support dynamically added attributes.
		var suggest = '<div ';
		//if(i%2 == 0) suggest += 'style="background-color:#0D1F32" ';
		suggest += 'onmouseover="javascript:suggestOver(this);" ';
		suggest += 'onmouseout="javascript:suggestOut(this);" ';
		suggest += 'onclick="javascript:setSearch(this);" ';
		suggest += 'suggestion="'+ jsonPayload.suggestions[i].suggestion + '" ';
		suggest += '><span class="hitcount">'+jsonPayload.suggestions[i].count + '</span><span class="term">' + elipsis(jsonPayload.suggestions[i].suggestion, 45) +'</span></div>';
		ss.innerHTML += suggest;    
	}

	ss.style.visibility = "visible";
}

/**
 * Handles mouse over
 */
function suggestOver(div_value) {
	div_value.className = 'over';
}

/**
 * Handles mouse out
 */
function suggestOut(div_value) {
	div_value.className = '';
}

/**
 * Handles suggest click (alternative 1)
 */
function setSearch(divNode) {
	document.getElementById('searchinput').value = divNode.getAttribute('suggestion');
	//document.getElementById('search').value = value;
	var ss = document.getElementById('search_suggest');
	ss.innerHTML = '';
	ss.style.visibility = "hidden";
	document.forms.SimpleSearchForm.submit();
}

/**
 * Handles suggest click (alternative 2)
 */
function setSearchTerm(divNode) {
	document.getElementById('searchinput').value = divNode.getAttribute('suggestion');
	var ss = document.getElementById('search_suggest');
	ss.innerHTML = '';
	ss.style.visibility = "hidden";
}

