/*
 * All java script logic for the Demandware reference application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */

//Determine IE browser. 999 returned if not IE
var Browser = {
  Version: function() {
		var version = 999; 
		if (navigator.appVersion.indexOf("MSIE") != -1)
			version = parseFloat(navigator.appVersion.split("MSIE")[1]);
		return version;
  }
};

//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) + "...";
}

function xContains (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    if(containee)
	    containee = containee.parentNode;

  }
  while (containee != null);
  return isParent;
}

function mouseReallyOut(t, e) {
var rel = (window.event) ? e.toElement : e.relatedTarget;
	return !(xContains(t,rel));
}

function buttonLink(form, buttonName)
{
       var el = document.createElement("INPUT");
       el.type="hidden";
       el.name=buttonName;
       el.value="x"; // whatever
       form.appendChild(el);
       form.submit();
       return false;
}


function setCookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}



function showDiv(obj, textDiv, showText, hideText)
{
	var qtyDiv 		= document.getElementById('boxQdrop');
	var hideShowText = document.getElementById(textDiv);
	
	if(document.getElementById(obj).style.display == 'block')
	{
		document.getElementById(obj).style.display = 'none';
		if (qtyDiv!=null)
			qtyDiv.style.display = 'block';
			
		if (hideShowText!=null)
			hideShowText.innerHTML = showText;
	}
	else
	{
		document.getElementById(obj).style.display = 'block';
		if (qtyDiv!=null)
			qtyDiv.style.display = 'none';
		
		if (hideShowText!=null)
			hideShowText.innerHTML = hideText;
		
	}
}

/*
 * 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 )
{
	if (url != null)
	{
		if (width != null && height != null)
		{
			window.open(url, "", " width=" + width +", height=" + height +", scrollbars=yes, resizable=yes").focus();
		}
		else
		{
			window.open(url, "", "location=no, scrollbars=yes, resizable=yes").focus();
		}
	}
}


/*
 * 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: '',
	popupURL: '',
	// timer for automatic close of cart item view
	timer: null,
	globalForm: null,

	cartAddMultiple: function( form, progressImageSrc )
	{
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		
		var tmpForms = $$(".addToCartFormClass");
		var cbs = $$(".interOfferCB");
		
		var productsAdded = false;
		
		for (var i = 0; i < cbs.length; i++) {
			var cb = cbs[i];
			var pid = cb.value; 
			var Quantity = 1;
				
			
			if (cb != null && cb.checked) {
				//alert('adding to cart: ' + Quantity + ' of ' + pid);
				productsAdded = true;
				var el = document.createElement("INPUT");
				el.type = "hidden";
				el.name = "pid" + i;
				el.value = pid;
				form.appendChild(el);
				
				var el = document.createElement("INPUT");
				el.type = "hidden";
				el.name = "Quantity" + i;
				el.value = Quantity;
				form.appendChild(el);

			}
		}
		if (productsAdded) {
			form.submit();
		}
		else {
			
			Dialog.alertNoButtons({url: MiniCart.popupURL}, {windowParameters: {className: '', width: 350}});
			return false;
			
		}
	},
	cartAddSeason: function( form, progressImageSrc )
	{
		
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		
		var tmpForms = $$(".addToCartFormClass");
		var cbs = $$(".tvSeason");
		
		var productsAdded = false;
		
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "pid";
		el.value = cbs[0].value;
		form.appendChild(el);
		
		for (var i = 0; i < cbs.length; i++) {
			var cb = cbs[i];
			var pid = cb.value; 
			var Quantity = 1;
			
			
			if (cb != null) {
				//alert('adding to cart: ' + Quantity + ' of ' + pid);
				productsAdded = true;
				var el = document.createElement("INPUT");
				el.type = "hidden";
				el.name = "pid" + i;
				el.value = pid;
				form.appendChild(el);
				
				var el = document.createElement("INPUT");
				el.type = "hidden";
				el.name = "Quantity" + i;
				el.value = Quantity;
				form.appendChild(el);

			}
		}
		
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "tvSeasonProd";
		el.value = "true";
		form.appendChild(el);
		
		MiniCart.globalForm = form;
		// 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)
		{
			
			//debugger;
			// 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');
			
			
			if(req.responseText.indexOf('DUPEST_DUPEST') > 0)
			{
				Dialog.alertNoButtons(req.responseText.replace('DUPEST_DUPEST', ''), {windowParameters: {className: '',height: 400, width: 500}, okLabel: 'Close'});
				return false;
			}
			
			var pos = Position.cumulativeOffset(minicarttotal);
			var dim = Element.getDimensions(minicarttotal);

			// replace the content
			var minicart = $('minicart');
			
			//debugger;
			minicart.innerHTML = req.responseText;
			MiniCart.suppressSlideDown = false;

			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 = $('minicartcontent');
	
				minicartcontent.style.left =  130 + 'px'; //pos[0]
				minicartcontent.style.height = 55+'px';
				if (navigator.appVersion.indexOf("MSIE")!=-1)
				{
					if(Browser.Version() < 8)
						minicartcontent.style.top = pos[1] + dim.height - 23 + 'px';
					else
						minicartcontent.style.top = pos[1] + dim.height - 4 + 'px';
				}
				else
				{
					minicartcontent.style.top = pos[1] + dim.height -4 + 'px';
				}
				
				
				
				minicartcontent.style.width ='58px'; //dim.width - 2 + 'px';
	
				new Effect.ScrollTo('header');
				new Effect.Appear('minicartcontent');
				
				if(Browser.Version() < 7 && form.qSelectDrop && minicartcontent.innerHTML.split('minicart_item').length >= 3)
					form.qSelectDrop.style.visibility = "hidden";
				
				// after a time out automatically close it
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 996000 );
			}
		}

		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
			
		}
		if (productsAdded) {
			var cartURL = "/on/demandware.store/Sites-WB-Site/default/Cart-MiniAddProduct";
		
			// add the product
			new Ajax.Request( cartURL, {method:'post', postBody:postdata,onSuccess:handlerFunc, onFailure:errFunc});
		}
		else {
			
			Dialog.alertNoButtons({url: MiniCart.popupURL}, {windowParameters: {className: '', width: 350}});
			return false;
			
		}
	},
	cartAdd: function( form, progressImageSrc, est, callbackFn, scope )
	{
		if(est && !ESTOK)
		{
			Dialog.alert({url: MiniCart.popupURL}, {windowParameters: {className: 'alphacube', width: 650}, okLabel: 'Close'});
			return false;
		}
		
		//set up callback
		var callback = function(){};
		if(callbackFn && scope) {
			try {
				callback = callbackFn.bind(scope);
			} catch(e) {
				if(console && console.error) console.error(e);
			}
		}
		
		MiniCart.globalForm = form;
		// 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)
		{
			//alert('ok');
			// 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');
			
			if(req.responseText.indexOf('DUPEST_DUPEST') > 0)
			{
				Dialog.alertNoButtons(req.responseText.replace('DUPEST_DUPEST', ''), {windowParameters: {className: '',height: 400, width: 500}, okLabel: 'Close'});
				return false;
			}
			
			var pos = Position.cumulativeOffset(minicarttotal);
			var dim = Element.getDimensions(minicarttotal);

			// replace the content
			var minicart = $('minicart');
			
			//debugger;
			minicart.innerHTML = req.responseText;
			
			 
			if(form.id == 'dwfrm_wishlist_items')
				var suppressMC = true;
			else
				var suppressMC = false;

			if( MiniCart.suppressSlideDown && MiniCart.suppressSlideDown() || suppressMC)
			{
				//alert("do nothing");
				// do nothing
				// the hook 'MiniCart.suppressSlideDown()' should have done the refresh
				
			}
			else
			{
				//alert("do something");
				// show the item
				// this display is optimized for Firefox. IE6/7 display the 
				// sliding down cart with an offset of -1
				var minicartcontent = $('minicartcontent');
	
				minicartcontent.style.left =  130 + 'px'; //pos[0]
				minicartcontent.style.height = 55+'px';
				if (navigator.appVersion.indexOf("MSIE")!=-1)
				{
					if(Browser.Version() < 8)
						minicartcontent.style.top = pos[1] + dim.height - 23 + 'px';
					else
						minicartcontent.style.top = pos[1] + dim.height - 4 + 'px';
				}
				else
				{
					minicartcontent.style.top = pos[1] + dim.height -4 + 'px';
				}
				
				
				
				minicartcontent.style.width ='58px'; //dim.width - 2 + 'px';
	
				new Effect.ScrollTo('header');
				new Effect.Appear('minicartcontent');
				
				if(Browser.Version() < 7 && form.qSelectDrop && minicartcontent.innerHTML.split('minicart_item').length >= 3)
					form.qSelectDrop.style.visibility = "hidden";
				
				// after a time out automatically close it
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 996000 );
				
				

				
				
				
				
			}
			
			callback({
				 success: 	true
				,postdata:	postdata
			});

		}

		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);
			//alert('err');
			callback({
				 success: 	true
				,postdata:	postdata
			});
			
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();
		if (postdata.indexOf('pid=')>-1)
		{
			var prodId = postdata.substr(postdata.indexOf('pid=')+4);
			if (prodId.indexOf('&')>-1)
			{
				prodId = prodId.substr(0,prodId.indexOf('&'));
				
			}
			
			
			var s=s_gi('wbroswhvb2c');
			s.linkTrackVars='events,products,trackingServer';
			s.linkTrackEvents='scAdd,scOpen';
			s.events='scAdd,scOpen';
			s.products=';'+prodId;
			s.trackingServer='warnerbros.112.2o7.net';
			s.tl(true,'o','Add to Cart');
			//alert(s);
		}
		
		// cloes a previous mini cart
		MiniCart.cartClose();
		
		var cartURL = "/on/demandware.store/Sites-WB-Site/default/Cart-MiniAddProduct";
		if(MiniCart.url != null && MiniCart.url != "")
			cartURL = MiniCart.url;
		
		// add the product
		new Ajax.Request( cartURL, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});
	},

	cartClose: function()
	{
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			
			$('minicartcontent').hide(); 
			
			if(MiniCart.globalForm && MiniCart.globalForm.qSelectDrop)
				MiniCart.globalForm.qSelectDrop.style.visibility = "visible";
		}
	},

	showCartNoClose: function()
	{
		if(!Element.visible('minicartcontent'))
		{
				var minicartcontent = $('minicartcontent');
				var minicarttotal = $('minicarttotal');
				var pos = Position.cumulativeOffset(minicarttotal);
				var dim = Element.getDimensions(minicarttotal);
	
				minicartcontent.style.left =  130 + 'px'; //pos[0]
				minicartcontent.style.height = 55+'px';
				if (navigator.appVersion.indexOf("MSIE")!=-1)
				{
					if(Browser.Version() < 8)
						minicartcontent.style.top = pos[1] + dim.height - 23 + 'px';
					else
						minicartcontent.style.top = pos[1] + dim.height - 4 + 'px';
				}
				else
				{
					minicartcontent.style.top = pos[1] + dim.height -4 + 'px';
				}
				
				
				
				minicartcontent.style.width ='58px'; //dim.width - 2 + 'px';
				
				new Effect.Appear('minicartcontent');
	
				// after a time out automatically close it
				//MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 4000 );
				MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 996000 );
		}
	},
	
	showCartWithDelay: function()
	{
	    if(MiniCart.timer)
	    {
		  window.clearTimeout(MiniCart.timer);
		  MiniCart.timer=null;
	    }

	  	if(!Element.visible('minicartcontent'))
	  	{
	    	MiniCart.timer=window.setTimeout('MiniCart.showCartNoClose()',100); //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;
	}
}

var version=0;
var ESTOK = true;

/*if (navigator.appVersion.indexOf("MSIE")!=-1)
{
	var temp=navigator.appVersion.split("MSIE");
	version=parseFloat(temp[1]);
}

if (version >= 7) 
	ESTOK = true;
else if (version >= 6 && navigator.userAgent.indexOf("SV1") != -1)
	ESTOK = true;
	
if(!ESTOK)
{
   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();
    var is_konq = false;
    var kqPos   = agt.indexOf('konqueror');
    if (kqPos !=-1)                 
       is_konq  = true;
    var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
    var is_khtml  = (is_safari || is_konq);
	var is_gecko = ((!is_khtml)&&(navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false;
   var is_fx = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                 (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                 (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                 (is_gecko) && ((navigator.vendor=="Firefox")||(agt.indexOf('firefox')!=-1)));
	if(is_fx)
	{
       var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0;
       if(is_fx&&!is_moz_ver) {
           is_moz_ver = agt.indexOf('firefox/');
           is_moz_ver = agt.substring(is_moz_ver+8);
           is_moz_ver = parseFloat(is_moz_ver);
       }
       if(!(is_moz_ver)) {
           is_moz_ver = agt.indexOf('rv:');
           is_moz_ver = agt.substring(is_moz_ver+3);
           is_paren   = is_moz_ver.indexOf(')');
           is_moz_ver = is_moz_ver.substring(0,is_paren);
       }
       
       if(is_moz_ver >= 2 && (agt.indexOf("windows nt")!=-1))
		ESTOK = true;
	}
}
*/

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('search').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);
	}
}

/**
 * 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].hits + '</span><span class="term">' + elipsis(jsonPayload.suggestions[i].suggestion, 40) +'</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('search').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('search').value = divNode.getAttribute('suggestion');
	var ss = document.getElementById('search_suggest');
	ss.innerHTML = '';
	ss.style.visibility = "hidden";
}

/**
 * The QuickView object handles the showing and hiding 
 * of QuickView bubbles.
 */
QVBonRight = false;
QuickView =
{

	mouseOverDelay: 25,
	mouseOutDelay: 100,
	overBubble: false,
	overSelect: false,
	overTimeoutId: null,
	outTimeoutId: null,
	divId: "quickView",
	mDiv: null,
	merchId: "psw",
	isShowing: null,
	
	/**
	 * 2009-04-23 changed bu Juergen Naeckel:
	 * added two optional parameters:  Product Line Item ID and Product List ID.
	 * this is required when showing the quick view for items in wish lists.
	 * if PLI is provided prodList must be procided too!
	 */
	handleItemOver: function(itemX, itemY, productId, divid, prodListID, pliID )
	{
		if(divid != null)
			this.mDiv = divid;
		else
			this.mDiv = null;
			
		if(this.overTimeoutId != null)
			clearTimeout(this.overTimeoutId);

		if(this.isShowing != productId)
			this.overTimeoutId = setTimeout("QuickView.handleOverTimeout(" + itemX + ", " + itemY + ", '" + productId + (pliID ? "', '" + prodListID + "', '" + pliID : "") + "')", this.mouseOverDelay);
	}, 
	
	handleMouseOut: function()
	{
		if(this.overTimeoutId != null)
		{
			clearTimeout(this.overTimeoutId);
			this.overTimeoutId = null;
			return;
		}
		
		if(!this.overBubble)
			this.outTimeoutId = setTimeout("QuickView.handleOutTimeout()", this.mouseOutDelay);
	},
	
	quickViewOver: function()
	{
		if(this.outTimeoutId != null) 
			clearTimeout(this.outTimeoutId);
		this.outTimeoutId = null;
	}, 

	/**
	 * 2009-04-23 changed bu Juergen Naeckel:
	 * added two optional parameters:  Product Line Item ID and Product List ID.
	 * this is required when showing the quick view for items in wish lists.
	 * if PLI is provided prodList must be procided too!
	 */
	handleOverTimeout: function(itemX, itemY, productId, prodListID, pliID )
	{
		var quickViewDiv = $(this.divId);
		var merchDiv = $(this.mDiv); 
		
		if(merchDiv == null)
			merchDiv = $$(".productScrollWrapper").find(function (s){return s.up().up().visible()});
		
		var merchDivPosition = this.getPosition(merchDiv);
	
		var x = merchDivPosition.x + itemX + 75;
		var y = merchDivPosition.y + itemY - 25;
		
		$('ieqvb').hide();
		$('ieqvbrt').hide();
		quickViewDiv.innerHTML = '';
		quickViewDiv.style.left = x + "px";
		quickViewDiv.style.top = y + "px";
			
		this.isShowing = productId;
	
		var rtStr = '';
		if(document.viewport.getWidth() < quickViewDiv.viewportOffset().left + 520)
		{
			rtStr = '&rt=true';
			quickViewDiv.style.left = (x - 500) + "px";
			QVBonRight = true;
		}
		else
			QVBonRight = false;
			
		if ( pliID != null )
		{
			rtStr += "&selectedItemID=" + pliID + "&productListID=" + prodListID;
		}

		new Ajax.Request( QuickView.url + '?pid=' + productId + rtStr, {onSuccess:QuickView.handlerFunc});
		
		this.overTimeoutId = null;
	
	},

	handlerFunc: function(req)
	{
		var quickViewDiv = $('quickView');
		
		if(QVBonRight)
			quickViewDiv.innerHTML = req.responseText+'<div id="qv_bot" class="qb_bottom_2">&nbsp;</div>';
		else
			quickViewDiv.innerHTML = req.responseText+'<div id="qv_bot" class="qb_bottom">&nbsp;</div>';
			
		if(qvbie6)
		{
			if(QVBonRight)
			{
				//$('ieqvbrt').clonePosition(quickViewDiv);
		        offset = quickViewDiv.cumulativeOffset();
		        dimensions = quickViewDiv.getDimensions();
		        style = {
		          left: offset[0] + 'px',
		          top: (offset[1]) + 'px',
		          width: dimensions.width + 'px',
		          height: (dimensions.height - 50) + 'px'
		        };
    			$('ieqvbrt').setStyle(style).show();
			}
			else
			{
				//$('ieqvb').clonePosition(quickViewDiv);
		        offset = quickViewDiv.cumulativeOffset();
		        dimensions = quickViewDiv.getDimensions();
		        style = {
		          left: offset[0] + 'px',
		          top: (offset[1]) + 'px',
		          width: dimensions.width + 'px',
		          height: (dimensions.height - 50) + 'px'
		        };
    			$('ieqvb').setStyle(style).show();
			}
		}

		quickViewDiv.onmouseover = function(){QuickView.handleQuickViewOver();};
		quickViewDiv.onmouseout = function(){QuickView.handleQVOut();};
		$$('#quickView select').invoke('observe', 'mouseover', QuickView.handleInputOver);
		

		sifrQuickBubbles();
		
		quickViewDiv.style.visibility = "visible";
		if(document.viewport.getHeight() < quickViewDiv.viewportOffset().top + 400)
			new Effect.ScrollTo('quickView', {offset: -1 * (quickViewDiv.viewportOffset().top + (document.viewport.getHeight() - (quickViewDiv.viewportOffset().top + 400)))});
	},
	
	url: '',
	

	handleOutTimeout: function()
	{
		if(this.isShowing != null)
		{
			var quickViewDiv = document.getElementById(this.divId);
			quickViewDiv.style.visibility = "hidden";
			this.isShowing = null;
			quickViewDiv.innerHTML = '';
			$('ieqvb').hide();
			$('ieqvbrt').hide();
		}
		else
		{
			if(this.overTimeoutId != null) clearTimeout(this.overTimeoutId);
		}
	},
	
	handleQVOut: function()
	{
		if(QuickView.overSelect)
		{
			QuickView.overSelect = false;
			return;
		}
		this.overBubble = false;
		if(this.overTimeoutId == null)
			this.outTimeoutId = setTimeout("QuickView.handleOutTimeout()", this.mouseOutDelay);
	},

	handleInputOver: function()
	{
		QuickView.overSelect = true;
	},
	
	handleQuickViewOver: function()
	{

		this.overBubble = true;
		if(this.outTimeoutId != null) 
			clearTimeout(this.outTimeoutId);
		this.outTimeoutId = null;
	}, 
	
	// Util
	
	getPosition: function(element)
	{
		var x = 0;
		var y = 0;
		if(element.offsetParent)
		{
			do
			{
				x += element.offsetLeft;
				y += element.offsetTop;
			}
			while(element = element.offsetParent);
		}
		return {x: x, y: y};
	}

};

// The following functions capture events from the Fluid 
// Retail Merchandiser control and hand them off to the 
// quick view functionality.
/**
* 2009-04-27 Change by Pavani:
* Disabled the QVBs for fluid controls.
*/
function handleItemOver(itemX, itemY, productId, divid)
{
	//alert("x:" + itemX+ " y:" + itemY + " prodID:" + productId);
	//QuickView.handleItemOver(itemX, itemY, productId, divid);
}

function handleItemOut()
{
	QuickView.handleMouseOut();
}

function switchTab( el, newID ) {
	$(el).addClassName('active');
	$(el).siblings().invoke('removeClassName','active');
	
	$(newID).siblings().invoke('hide');
	$(newID).show();
}

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		/*Update : FF copytoclipboard FAILS, edit to just highlight text 10/1/2010   :jasper*/
		document.getElementById('copyLinkURL').select();
		$('copyURLLINK_txt').update("*Please Copy The Highlighted Text Above");
		$('copyURLLINK_txt').setStyle({color:'#f8fb1e',fontSize:'10px'});
		/*// You have to sign the code to enable this or allow the action in about:config by changing
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);
		*/	   
	}
}


//Arrays of states for addresses
var USStates = [];
USStates.push(new Option('Armed Forces (AA)','AA'));
USStates.push(new Option('Armed Forces (AE)','AE'));
USStates.push(new Option('Armed Forces (AP)','AP'));
USStates.push(new Option('Alabama','AL'));
USStates.push(new Option('Alaska','AK'));
USStates.push(new Option('American Samoa','AS'));
USStates.push(new Option('Arizona','AZ'));
USStates.push(new Option('Arkansas','AR'));
USStates.push(new Option('California','CA'));
USStates.push(new Option('Colorado','CO'));
USStates.push(new Option('Connecticut','CT'));
USStates.push(new Option('Delaware','DE'));
USStates.push(new Option('District of Columbia','DC'));
USStates.push(new Option('Florida','FL'));
USStates.push(new Option('Georgia','GA'));
USStates.push(new Option('Guam','GU'));
USStates.push(new Option('Hawaii','HI'));
USStates.push(new Option('Idaho','ID'));
USStates.push(new Option('Illinois','IL'));
USStates.push(new Option('Indiana','IN'));
USStates.push(new Option('Iowa','IA'));
USStates.push(new Option('Kansas','KS'));
USStates.push(new Option('Kentucky','KY'));
USStates.push(new Option('Louisiana','LA'));
USStates.push(new Option('Maine','ME'));
USStates.push(new Option('Maryland','MD'));
USStates.push(new Option('Massachusetts','MA'));
USStates.push(new Option('Michigan','MI'));
USStates.push(new Option('Minnesota','MN'));
USStates.push(new Option('Mississippi','MS'));
USStates.push(new Option('Missouri','MO'));
USStates.push(new Option('Montana','MT'));
USStates.push(new Option('Nebraska','NE'));
USStates.push(new Option('Nevada','NV'));
USStates.push(new Option('New Hampshire','NH'));
USStates.push(new Option('New Jersey','NJ'));
USStates.push(new Option('New Mexico','NM'));
USStates.push(new Option('New York','NY'));
USStates.push(new Option('North Carolina','NC'));
USStates.push(new Option('North Dakota','ND'));
USStates.push(new Option('N. Mariana Islands','MP'));
USStates.push(new Option('Ohio','OH'));
USStates.push(new Option('Oklahoma','OK'));
USStates.push(new Option('Oregon','OR'));
USStates.push(new Option('Palau Island','PW'));
USStates.push(new Option('Pennsylvania','PA'));
USStates.push(new Option('Puerto Rico','PR'));
USStates.push(new Option('Rhode Island','RI'));
USStates.push(new Option('South Carolina','SC'));
USStates.push(new Option('South Dakota','SD'));
USStates.push(new Option('Tennessee','TN'));
USStates.push(new Option('Texas','TX'));
USStates.push(new Option('Utah','UT'));
USStates.push(new Option('Vermont','VT'));
USStates.push(new Option('Virgin Islands','VI'));
USStates.push(new Option('Virginia','VA'));
USStates.push(new Option('Washington','WA'));
USStates.push(new Option('West Virginia','WV'));
USStates.push(new Option('Wisconsin','WI'));
USStates.push(new Option('Wyoming','WY'));


var CAStates = [];
CAStates.push(new Option('Alberta','AB'));
CAStates.push(new Option('British Columbia','BC'));
CAStates.push(new Option('Manitoba','MB'));
CAStates.push(new Option('New Brunswick','NB'));
CAStates.push(new Option('Newfoundland and Labrador','NL'));
CAStates.push(new Option('Northwest Territories','NT'));
CAStates.push(new Option('Nova Scotia','NS'));
CAStates.push(new Option('Nunavut','NU'));
CAStates.push(new Option('Ontario','ON'));
CAStates.push(new Option('Prince Edward Island','PE'));
CAStates.push(new Option('Quebec','QC'));
CAStates.push(new Option('Saskatchewan','SK'));
CAStates.push(new Option('Yukon','YT'));

var AUStates = [];
AUStates.push(new Option('Australian Capital Territory','ACT'));
AUStates.push(new Option('New South Wales','NSW'));
AUStates.push(new Option('Northern Territory','NT'));
AUStates.push(new Option('Queensland','Qld'));
AUStates.push(new Option('South Australia','SA'));
AUStates.push(new Option('Tasmania','Tas'));
AUStates.push(new Option('Victoria','Vic'));
AUStates.push(new Option('Western Australia','WA'));

varInternationalStates = [];
varInternationalStates.push(new Option('Non-US/Other','##'));

function updateStateSelect(country, stateSelect) {
	
	if (stateSelect == null) {
		return;
	}
	// Lookup the existing state value and reset it if necessary
	var stateVal = stateSelect.options[stateSelect.selectedIndex].value;
	var stateIndex = 0;
	
	stateSelect.options.length=0;
	if (country == null || country == '') {
		stateSelect.options.add(new Option('Please select a country',''));
	}
	else if (country == 'US') {
		stateSelect.options.add(new Option('Please select a state',''));
		
		for (var i = 0; i < USStates.length; i++) {
			//IE7 doesn't like adding objects directly
			//stateSelect.options.add(USStates[i]);
			stateSelect.options.add(new Option(USStates[i].text,USStates[i].value));

			if (USStates[i].value == stateVal) {
				stateIndex = i+1; // +1 because we've added in a 'Please select...' option
			}
		}
	}
	else if (country == 'CA') {
		stateSelect.options.add(new Option('Please select a province',''));
		for (var i = 0; i < CAStates.length; i++ ) {
			//IE7 doesn't like adding objects directly
			//stateSelect.options.add(USStates[i]);
			stateSelect.options.add(new Option(CAStates[i].text,CAStates[i].value));


			if (CAStates[i].value == stateVal) {
				stateIndex = i+1; // +1 because we've added in a 'Please select...' option
			}
		}
	}
	else if( country == 'AU') {
		stateSelect.options.add(new Option('Please select a province',''));
		for (var i = 0; i < AUStates.length; i++ ) {
			//IE7 doesn't like adding objects directly
			//stateSelect.options.add(USStates[i]);
			stateSelect.options.add(new Option(AUStates[i].text,AUStates[i].value));


			if (AUStates[i].value == stateVal) {
				stateIndex = i+1; // +1 because we've added in a 'Please select...' option
			}
		}
	}
	else if (country != 'US' && country != 'CA' && country != 'AU') {
		stateSelect.options.add(new Option('Non-US/Other','##'));
	}
	stateSelect.selectedIndex = stateIndex;
	
	return;

}
function doStateChange(countrySelect, stateSelectName) {
	var countryName = countrySelect.options[countrySelect.selectedIndex].value;
	var stateSelect = $(stateSelectName);
	
	updateStateSelect(countryName, stateSelect);
}

