/*
 * 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()
{
}

function dwSubmitForm(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 cartAdd( form, addButton)
{
	var servicePlan = $('selectServicePlan');
	if(servicePlan != null && servicePlan.value != '')
	{
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "spid";
		el.value = servicePlan.value;
		form.appendChild(el);
	}
	
	var upSells = $('selectUpSell');
	if(upSells != null && upSells.value != '')
	{
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "upid";
		el.value = upSells.value;
		form.appendChild(el);
	}
	
	var cItems = '';
	var itemsEmpty = true;
	$$(".accCB").each(function(cb){if(cb.checked) {if(!itemsEmpty) cItems += ','; else itemsEmpty = false; cItems += cb.value;}} )
	if(!itemsEmpty)
	{
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "accessories";
		el.value = cItems;
		form.appendChild(el);
	}
	
	var sItems = '';
	itemsEmpty = true;
	$$(".setRB").each(function(cb){if(cb.checked) {if(!itemsEmpty) sItems += ','; else itemsEmpty = false; sItems += cb.value;}} )
	if(!itemsEmpty)
	{
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "set_options";
		el.value = sItems;
		form.appendChild(el);
	}

 	form.submit();
	return false;
}
function checkout(form, buttonName)
{
	var cItems = '';
	var itemsEmpty = true;
	$$(".accCB").each(function(cb){if(cb.checked) {if(!itemsEmpty) cItems += ','; else itemsEmpty = false; cItems += cb.value;}} )
	if(!itemsEmpty)
	{
		var el = document.createElement("INPUT");
		el.type = "hidden";
		el.name = "accessories";
		el.value = cItems;
		form.appendChild(el);
	}

     var el = document.createElement("INPUT");
     el.type="hidden";
     el.name=buttonName;
     el.value="x"; // whatever
     form.appendChild(el);
     form.submit();
     return false;
}

function wishlistAdd(pid, qty, addButton)
{
	var form = $('wlac');

	var el = document.createElement("INPUT");
	el.type = "hidden";
	el.name = "pid";
	el.value = pid;
	form.appendChild(el);

	el = document.createElement("INPUT");
	el.type = "hidden";
	el.name = "Quantity";
	el.value = qty;
	form.appendChild(el);

	form.submit();
	return false;
}

function ajaxPopup(popupURL, h, w)
{
	Dialog.alert({url: popupURL}, {windowParameters: {className: 'alphacube', height: h, width: w}, okLabel: 'Close'}); 
	return false;
}

function textPopup(popupText)
{
	Dialog.alert(popupText, {windowParameters: {className: 'alphacube'}, okLabel: 'Close'}); 
	return false;
}

var vlFlash = '';
function imgPopup(popupURL)
{
	setVLActive(vlFlash != '');
	Dialog.alert2({url: popupURL}, {windowParameters: {className: 'alphacube', height: 575, width: 625}, okLabel: 'Close'}); 

	return false;
}
function vlActivate()
{
	if(vlFlash != '')
	{
		var so = new SWFObject(vlFlash, "vlFlash", "500", "500", "7", "#FFFFFF");
		so.addParam("wmode", "opaque");
		so.write("largeImage");
	}
}

function videoPopup(videoURL)
{
	Dialog.alert('<div id="productVideo">Product Video</div>', {windowParameters: {className: 'alphacube', height: 540, width: 680}, okLabel: 'Close'}); 
	var so = new SWFObject(videoURL, "catFlash", "640", "480", "7", "#FFFFFF");
	so.addParam("wmode", "opaque");
	so.write("productVideo");
	return false;
}

var activeImage = 0;
var flashActive = false;
function productFlash(flashURL, ai)
{
	activeImage = ai;
	flashActive = true;
	
	var so = new SWFObject(flashURL, "productFlash", "190", "190", "7", "#FFFFFF");
	so.addParam("wmode", "opaque");
	so.write("productImage");
	
	return false;
}

var vlActive = false;
function isVLActive()
{
	return vlActive;
}
function setVLActive(state)
{
	vlActive = state;
}
function svlFlash(flashURL)
{
	
	var so = new SWFObject(flashURL, "vlFlash", "500", "500", "7", "#FFFFFF");
	so.addParam("wmode", "opaque");
	so.write("largeImage");

	return false;
}

/*
	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");
		}
	}
}


/*
 * Support for the compare window
 */
ProductCompare = {
	openPopup: function( url ) {
		var cItems = '';
		var itemsEmpty = true;
		$$(".cbCompare").each(function(cb){if(cb.checked) {if(!itemsEmpty) cItems += ','; else itemsEmpty = false; cItems += cb.value;}} )
		document.location = url + '&items=' + cItems;
		/*window.open(
			url + '&items=' + cItems,
			'product_compare',
			'width=800,height=600,scrollbars=yes,resizable=yes',
			true 
		).focus(); */
	}
}

function preloadImg(imgSrc)
{
	var img = new Image;
	img.src = imgSrc;
}

/*
 * 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: '',
	
	progressImageSrc: '',

	// timer for automatic close of cart item view
	timer: null,

	updateMiniCart: function(req)
	{
		// 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
		var minicart = $('minicart');
		minicart.innerHTML = req.responseText;

		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 = pos[0] + 0 + 'px';
			minicartcontent.style.top = pos[1] + dim.height + 1 + 'px';
			minicartcontent.style.width = dim.width - 2 + 'px';

			new Effect.ScrollTo('headerTop');
			new Effect.SlideDown('minicartcontent');

			// after a time out automatically close it
			MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
		}
	},
	
	wishlistAdd: function(pid, qty, addButton)
	{
		// get the data of the form as serialized string
		var postdata = 'pid=' + pid + '&Quantity=' + qty + '&add=';
	
	
		var previousImageSrc = null;
	
		// show progress indicator
		if (addButton != null)
		{
			previousImageSrc = addButton.src;
			addButton.src = MiniCart.progressImageSrc;
		}
	
		var handlerFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			
			MiniCart.updateMiniCart(req);		
		}

		var errFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
		}

		// close a product QuickView
		// if ( QuickView ) QuickView.closeQuickView();

		// cloes a previous mini cart
		MiniCart.cartClose();

		// add the product
		new Ajax.Request( MiniCart.url, {method:'post', postBody:postdata, onSuccess:handlerFunc, onFailure:errFunc});
	},

	cartAdd: function( form, addButton)
	{
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		
		var servicePlan = $('selectServicePlan');
		if(servicePlan != null && servicePlan.value != '')
			postdata += '&spid=' + servicePlan.value;
	
		// disable form
		Form.disable(form);
	
		var previousImageSrc = null;
	
		// show progress indicator
		if (addButton != null)
		{
			previousImageSrc = addButton.src;
			addButton.src = MiniCart.progressImageSrc;
		}
	
		var handlerFunc = function(req)
		{
			// hide progress indicator
			if (addButton != null)
			{
				addButton.src = previousImageSrc;
			}
			Form.enable(form);	
			
			MiniCart.updateMiniCart(req);	
		}

		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();

		// add the product
		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;
	}}
/*
 * Functionality from rounded CSS divs.
 */
var makeRound = function(){var els = document.getElementsByTagName('div'); for(var i=0; el=els[i]; i++) if(el.className.indexOf('round')>-1 && el.firstChild && el.firstChild.className!='t') el.innerHTML = '<b class="t"><b class="r"></b></b><div class="c"><b class="br"></b>'+el.innerHTML+'<b class="br"></b></div><b class="b"><b class="r"><!----></b></b>';}

	window.onload = makeRound;
	
	
	
	
var IframeShim = {
 	 
 	  /*
 	    Method: initialize
 	    Constructor
 	      
 	      Creates iframe shim and appends it to the body.
 	      Note that this method does not perform proper positioning and resizing of an iframe.
 	      To do that use positionUnder method
 	      
 	    Returns:
 	      this
 	  */
 	  element: null,
 	  initialize: function() {
 	  },
 	 
 	  /*
 	    Method: hide
 	      Hides iframe shim leaving its position and dimensions intact
 	      
 	    Returns:
 	      this
 	  */
 	  hide: function() {
 	    this.element.hide();
 	  },
 	 
 	  /*
 	    Method: show
 	      Show iframe shim leaving its position and dimensions intact
 	      
 	    Returns:
 	      this
 	  */
 	  show: function() {
 	    this.element.show();
 	  },
 	 
 	  /*
 	    Method: positionUnder
 	      Positions iframe shim under the specified element
 	      Sets proper dimensions, offset, zIndex and shows it
 	      Note that the element should have explicitly specified zIndex
 	      
 	    Returns:
 	      this
 	  */
 	  positionUnder: function(elementx, shim) {
	 	this.element = $(shim);
 	    var ele = $(elementx),
 	        offset = ele.cumulativeOffset(),
 	        dimensions = ele.getDimensions(),
 	        style = {
	          height: dimensions.height + 'px'
	        };
	    this.element.setStyle(style).show();	   
	  },
 	 
 	  /*
 	    Method: setBounds
 	      Sets element's width, height, top and left css properties using 'px' as units
 	    
 	    Returns:
 	      this
 	  */
 	  setBounds: function(bounds) {
 	    for (prop in bounds) {
 	      bounds[prop] += 'px';
 	    }
 	    this.element.setStyle(bounds);
 	  },
 	 
 	  /*
 	    Method: destroy
 	      Completely removes the iframe shim from the document
 	      
 	    Returns:
 	      this
 	  */
 	  destroy: function() {
 	    if (this.element)
 	      this.element.remove();
 	  }
 	}
