/*
 * All java script logic for the Demanware reference application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */


/*
 * Register more initializations here
 */
window.onload = function()
{
  initPopupLinks();
  externalLinks();
}


/*
	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, scrollbars )
{
	var scroll = null;
	if(scrollbars != null && scrollbars == 'true')
	{
		scroll = "scrollbars=yes";
	}
	else
	{
		scroll = "scrollbars=no";
	}
	
	if (url != null)
	{
		if (width != null && height != null)
		{
			window.open(url, "", "width=" + width +", height=" + height +", "+ scroll +", resizable=yes");
		}
		else
		{
			window.open(url, "", scroll + ", resizable=yes");
		}
	}
}


/*
 * 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,
	
	routeToUrl: 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)
		{
			// 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
			var minicart = $('minicart');
			//minicart.innerHTML = req.responseText;
			Element.update(minicart,req.responseText);

			// 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.SlideDown('minicartcontent');
			
			// after a time out automatically close it
			MiniCart.timer = setTimeout( 'MiniCart.cartClose()', 6000 );
		}

		var errFunc = function(req)
		{
			// reset routeToUrl
			routeToUrl = null;
			
			// 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});
	},
	
	cartAddAndRoute: function( form, progressImageSrc, url )
	{
		MiniCart.cartAdd(form, progressImageSrc);

		routeToUrl = url;
	},

	cartClose: function()
	{
		if ( MiniCart.timer != null )
		{
			clearTimeout( MiniCart.timer );
			MiniCart.timer = null;
			Effect.SlideUp('minicartcontent');
			if (routeToUrl != null)
				window.location.href = routeToUrl;
		}
		routeToUrl = null;
	}
}

var popupLinkConfig = new Array;

// popupLinkConfig["classname"] = new Array ( "targetname", "width=550,height=350,scrollbars=yes,resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes");
popupLinkConfig["popup"]    = new Array ( "", "width=450,height=450,scrollbar=yes,resizable=yes");
popupLinkConfig["fullpage"] = new Array ( "", "width=780,height=350,scrollbars=yes,resizable=yes,status=yes");
popupLinkConfig["warrantypop"] = new Array ( "", "width=595,height=720,scrollbars=yes,resizable=yes,status=yes");



// ==========================================================================
 
// Note: Make sure that no other javscripts assign a fuction to window.onload
// There can be only one function tied to window.onload at a time.



function initPopupLinks()
{
  if (!document.getElementsByTagName) return true;
  var pageLinks = document.getElementsByTagName("a");
  for (var i = 0; i < pageLinks.length; i++) 
  {
    if (((pageLinks[i].className != null) && 
         (pageLinks[i].className != "")) ||
        ((pageLinks[i].parentNode.className != null) && 
         (pageLinks[i].parentNode.className != "")))
    {
      var linkClass = " " + pageLinks[i].className + " ";
      if ((linkClass == "  ") && (pageLinks[i].parentNode.className != ""))
      {
        linkClass = " " + pageLinks[i].parentNode.className + " ";
      }
      for (var theKey in popupLinkConfig) 
      {
        if (linkClass.indexOf(" " + theKey + " ") > -1)
        {
          if ((pageLinks[i].target == "") || (pageLinks[i].target == null))
          {
            pageLinks[i].target = (popupLinkConfig[theKey][0] != "") ? popupLinkConfig[theKey][0] : theKey;
          }
          pageLinks[i].settings = popupLinkConfig[theKey][1];
          pageLinks[i].onclick = popUp;
        }
      }
    }
  }
  return true;
}

function popUp()
{
  newWin = window.open(this.href, this.target, this.settings);
  newWin.focus();
  return false;
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
    anchor.target = "_blank";
    }
}
}
