//-----------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (C) Copyright IBM Corp. 2009 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with
// IBM Corp.
//-----------------------------------------------------------------


/** 
 * @fileOverview This file provides the common functions which are specific to the Madisons store.
 * This JavaScript file is used by StoreCommonUtilities.jspf.
 */

//Import the required Dojo libraries
dojo.registerModulePath("wc", "../wc");
	
dojo.require("wc.service.common");
dojo.require("dojo.io.iframe");
dojo.require("dojo.io.script");


dojo.require("dijit.Tooltip");

dojo.provide("heroic.PersistTooltip");
dojo.declare("heroic.PersistTooltip", [dijit.Tooltip], {

    postCreate: function()
        {
            if(!dijit._masterTT){
                dijit._masterTT = new dijit._MasterTooltip();
            }
            // should get the connection list & see if another heroic.widget.PersistTooltip
            // has already made these connections.
            
           
            dijit._masterTT.connect(dijit._masterTT.domNode,'onmouseover',this.ttPersist);
            dijit._masterTT.connect(dijit._masterTT.domNode,'onmouseout',this.ttFade);
            this.inherited("postCreate", arguments);
        },

                     ttPersist: function (evt)
                     {
                         
                         // console.log("persist");
                         this.fadeOut.stop();
                         this.fadeIn.play();
                     },

                     ttFade: function (evt)
                     {
                         // console.log("fade");
                         this.fadeOut.play();
                     }

    }
    )
//Reloads widgets when parts of the page has been re-loaded from server
dojo.require("dojo.parser");

//Category menu support
dojo.require("dijit.form.Button");
dojo.require("wc.widget.WCMenu");
dojo.require("wc.widget.WCDialog");
dojo.require("wc.widget.ScrollablePane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");	
dojo.require("dijit.Tooltip");
dojo.require("wc.widget.WCDropDownButton");
dojo.require("dijit.Dialog");
dojo.require("dojo.dnd.Source");
dojo.require("dojo.currency");
dojo.require("dijit.Tree");
dojo.require("dojo.back");
dojo.require("dijit.form.DateTextBox");
dojo.require("wc.widget.RefreshArea");
dojo.require("wc.render.RefreshController");
dojo.require("wc.render.Context");
dojo.require("dojo.cookie");
dojo.require("dojoc.PersistTooltip"); //* this is for the product item info inline hover pop ups  */
dojo.require("dojo.parser");
dojo.require("heroic.PersistTooltip");


    
/** This variable indicates whether the dropdown is shown or not. */
var showDropdown = false;

/** This variable stores the current dropdown dialog element. */
var dropDownDlg = null;

/** This variable indicates whether the browser used is Internet Explorer or not. */
var isIE = (document.all) ? true : false;

/** 
 * This variable indicates whether a request has been submitted or not.
 * The value is initialized to true and resets to false on full page load.
 */
var requestSubmitted = true;

/** 
 * This variable stores the id of the element (ex: button/link) which the user clicked.
 * This id is set when the user clicks an element which triggers an Ajax request.
 */
var currentId = "";

/** 
 * Sends back focus to the first focusable element on tabbing from the last focusable element.
 */
function focusSetter(){  
	if(dojo.byId("MiniCartFocusReceiver1"))
		dojo.byId("MiniCartFocusReceiver1").focus();
	else
		dojo.byId("MiniCartFocusReceiver2").focus();
}

/** 
 * Sends back focus to the last focusable element on reverse tabbing from the first focusable element.
 * 
 * @param {object} event The event triggered from user actions
 */
function determineFocus(event) {
		if(event.shiftKey && event.keyCode == dojo.keys.TAB)
		{
			if(dojo.isIE!=0)
			{
				if(event.srcElement.id=="MiniCartFocusReceiver1")
				{
					if(dojo.byId("checkoutButton"))
					{
						dojo.byId("checkoutButton").focus();
					}
					dojo.stopEvent(event);
				}
				else if(event.srcElement.id=="MiniCartFocusReceiver2")
				{
					dojo.byId("MiniCartFocusReceiver2").focus();
					dojo.stopEvent(event);
				}
			}
			else
			{
				if(event.target.id=="MiniCartFocusReceiver1")
				{
					if(dojo.byId("checkoutButton"))
					{
						dojo.byId("checkoutButton").focus();
					}
					dojo.stopEvent(event);
				}
				else if(event.target.id=="MiniCartFocusReceiver2")
				{
					dojo.byId("MiniCartFocusReceiver2").focus();
					dojo.stopEvent(event);
				}
			}
		}
}

/**
 * Destroys the existing dialogs with outdated data.
 */
function destroyDialog(){
	//If data has changed, then we should destroy the quick_cart_container dialog and recreate it with latest data
	dojo.query('.dijitDialog', document).forEach(function(tag) {
		if (dijit.byNode(tag).id == 'quick_cart_container') 
			dijit.byNode(tag).destroyRecursive();// or dijit.getEnclosingWidget(tag).destroyRecursive();
	 });
	 dropDownDlg = null;
}

/**
 * Displays the dropdown content of the mini shopping cart when keyboard keys are used to expand/collapse the dropdown.
 *
 * @param {object} event The event to retrieve the input keyboard key
 * @param {string} relativeId The id of a placeholder element to position the dropdown relatively
 * @param {string} contentId The id of the content pane containing the mini shopping cart dropdown contents
 * @param {string} contentType The content that will be shown in the expanded mini shopping cart dropdown.
 */
function showMiniShopCartDropDown1(event,relativeId,contentId,contentType){
	console.debug(event.keyCode);
	if(event.keyCode == dojo.keys.DOWN_ARROW){
		showMiniShopCartDropDown(event,relativeId,contentId,contentType);
	}
	else if(event.shiftKey && event.keyCode == dojo.keys.ENTER){
		showMiniShopCartDropDown(event,relativeId,contentId,contentType);
		dojo.stopEvent(event);
	}
}

/**
 * Displays the dropdown content of the mini shopping cart when the user hovers over the 
 * mini shopping cart or uses keyboard keys to expand the dropdown.
 *
 * @param {object} event The event triggered from user actions
 * @param {string} relativeId The id of a placeholder element to position the dropdown relatively
 * @param {string} contentId The id of the content pane containing the mini shopping cart dropdown contents
 * @param {string} contentType The content that will be shown in the expanded mini shopping cart dropdown.
 */
function showMiniShopCartDropDown(event,relativeId,contentId,contentType){

	//Calculate the X and Y co-ordinates for the dialog. We dont want it to be at the center of the screen.
	var t = dojo.byId(relativeId);
	var c = dojo.coords(t,true); 
	var x1 = c.x; 
	var y1 = c.y;

	/* If the Dialog is already created, then just set the X and Y co-ordinates for this dialog. Sometimes,
	if the browser is resized, the (x,y) co-ordinates will change from the initial values. So everytime before calling Dialog.show() method reset the (x,y) co-ordinates. The Dialog.show() method will internally call _rePosition() method which repositions the dialog.
	*/

	if(dropDownDlg){
			dropDownDlg.y = y1;
			dropDownDlg.x = x1 +dojo.contentBox(dojo.byId(relativeId)).w-230;
	}

	/* Dialog is not yet created..Create one */
	if(!dropDownDlg){
		var pane = document.getElementById(contentId);
		dropDownDlg = new wc.widget.WCDialog({relatedSource: relativeId, x:x1,y:y1},pane);
		dropDownDlg.x=x1 +dojo.contentBox(dojo.byId(relativeId)).w-230;
	}

	if(dojo.isOpera!=0)
	{
		dropDownDlg.x = dropDownDlg.x + window.pageXOffset;
		dropDownDlg.y = dropDownDlg.y + window.pageYOffset;
	}

	if(contentType == 'orderItemsList'){
		//dojo.byId("MiniShopCartProductsList").style.display = "block";
		//dojo.byId("MiniShopCartProductAdded").style.display = "none";
		dojo.byId("MiniShopCartProductsList").style.display = "block";
	}
	else if(contentType == 'orderItemAdded'){
		//dojo.byId("MiniShopCartProductsList").style.display = "none";
		//dojo.byId("MiniShopCartProductAdded").style.display = "block";
		dojo.byId("MiniShopCartProductsList").style.display = "block";
	}
	if(dojo.isIE!=0)
	{
		setTimeout(dojo.hitch(dropDownDlg,"show",null),5);
		setTimeout(dojo.hitch(this,"hideUnderlayWrapper",""),5);
	}
	else
	{
		setTimeout(dojo.hitch(dropDownDlg,"show",event),5);
		setTimeout(dojo.hitch(this,"hideUnderlayWrapper",""),5);
	}
}

/**
 * Hides the DialogUnderlayWrapper component, the component that grays out the screen behind,
 * as we do not want the background to be greyed out.
 */
function hideUnderlayWrapper(){
	dojo.query('.dijitDialogUnderlayWrapper', document).forEach(function(tag) {		
		tag.style.display='none';
	});	
}

/**
 * Loads the specified URL.
 *
 * @param {string} url The URL of the page to be loaded.
 */
function loadLink(url){
	document.location.href=url;
}

/**
 * Clears the Search term string displayed in Simple Search field.
 */
function clearSearchField() {
	searchText = document.getElementById("SimpleSearchForm_SearchTerm").value;
	document.getElementById("SimpleSearchForm_SearchTerm").value = "";
}

/**
 * Displays the Search term string in Simple Search field.
 */
function fillSearchField() {
	if (document.getElementById("SimpleSearchForm_SearchTerm").value == "") {
		document.getElementById("SimpleSearchForm_SearchTerm").value = searchText;
	}
}

/**
 * Displays the top dropdown menu, including the category dropdowns and the mini shopping cart.
 */
function showDropDownMenu(){
	var showMenu = document.getElementById("header_menu_dropdown");
	if(document.getElementById("header_menu_dropdown")!=null && document.getElementById("header_menu_dropdown")!='undefined'){
		showMenu.style.display = "block";
	}
	if(document.getElementById("outerCartContainer")!=null && document.getElementById("outerCartContainer")!='undefined'){
		var outershopcart = document.getElementById("outerCartContainer");
		outershopcart.style.display = "block";
	}
}

/**
 * Initializes the mini shopping cart object and subscribes dojo actions on this object.
 */
function initShopcartTarget(){
			
	dojo.subscribe("/dnd/drop", function(source, nodes, copy, target){
		
		target.deleteSelectedNodes();
		
		var actionListScroll = new popupActionProperties(); 
		actionListScroll.showProductCompare = showProductCompare;

		if(target.parent.id=='miniShopCart_dndTarget'){
			var indexOfIdentifier = source.parent.id.indexOf("_",0);
			if ( indexOfIdentifier >= 0) {
				//remove the prefix including the "underscore"
				source.parent.id = source.parent.id.substring(indexOfIdentifier+1);					
			}
			if(source.node.getAttribute('dndType')=='item' || source.node.getAttribute('dndType')=='package') {
				categoryDisplayJS.AddItem2ShopCartAjax(source.parent.id ,1);
			} else if(source.node.getAttribute('dndType')=='product' || source.node.getAttribute('dndType')=='bundle') {
				showPopup(source.parent.id,storeId,langId,catalogId,function(e){return e;},'miniShopCart_dndTarget',null,actionListScroll);
			}
		}
	});
}

/**
 * Displays the progress bar dialog to indicate a request is currently running.
 * There are certain cases where displaying the progress bar causes problems in Opera,
 * the optional parameter "checkForOpera" is passed to specifically check if the browser used is Opera,
 * if so, do not display the progress bar in these cases.
 *
 * @param {boolean} checkForOpera Indicates whether to check if the browser is Opera or not.
 */
function cursor_wait(checkForOpera) {
	var showPopup = true;	

	//Since dijit does not support Opera
	//Some progress bar dialog will be blocked in Opera to avoid error
	if(checkForOpera == true){
		if(dojo.isOpera > 0){
			showPopup = false;
		}
	}
	
	//For all other browsers and pages that work with Opera
	//Display the progress bar dialog
	if(showPopup){
		//Delay the progress bar from showing up
		setTimeout('showProgressBar()',500);
	}
}

/**
 * Helper method for cursor_wait() to display the progress bar pop-up.
 * Displays progress bar, next to the element if the element id was specified in currentId,
 * or defaults to the center of the page if currentId is empty.
 * Progress bar will only be displayed if the submitted request has not been completed.
 * This method is only called implicitly by the cursor_wait() method, which is triggered before a request is submitted.
 */
function showProgressBar(){
	//After the delay, if the request is still not finished
	//Then continue and show the progress bar
	//Otherwise, do not execute the following code
	if(!requestSubmitted){
		return;
	}
	
	var dialog = dijit.byId('progress_bar_dialog');
	
	//Make sure the dialog is created
	if(dialog != null){
			
		//Hide the header for the close button
		dialog.closeButtonNode.style.display='none';		
		
		var progressBar = document.getElementById('progress_bar');
		progressBar.style.display = 'block';	
				
		//Check whether or not an element ID is provided
		//If yes, point the progress bar to this element
		//Otherwise, show the progress bar in a dialog
		if(this.currentId != ""){
			var element = document.getElementById(this.currentId);	
			var pos = dijit.placeOnScreenAroundElement(progressBar,element,{'TR':'TL'});	
		} else {
			dialog.containerNode.innerHTML == "";
			progressBar.style.left = '';
			progressBar.style.top = '';
			dialog.containerNode.appendChild(progressBar);
			dialog.show();		
		}
		
		//Make sure the progress bar dialog goes away after 40 seconds 
		//and does not hang if server calls does not return
		//Assuming the longest server calls return before 40 seconds (considering large search results etc)
		setTimeout("cursor_clear()",40000);
	}
}

/**
 * Stores the id of the element (ex: button/link) that triggered the current submitted request.
 * Store the new element id only when no request is currently running.
 *
 * @param {string} id The id of element triggering the submitted request.
 */
function setCurrentId(id){
	//If there is no request already submitted, update the id
	if(!requestSubmitted && this.currentId == ""){
		this.currentId = id;
	}
}

/**
 * This function trims the spaces from the pased in word.
 * Delete all pre and trailing spaces around the word.
 * 
 * @param {string} inword The word to trim.
 */
function trim(inword)
{
	word = inword.toString();
	var i=0;
	var j=word.length-1;
	while(word.charAt(i) == " ") i++;
	while(word.charAt(j) == " ") j=j-1;
	if (i > j) {
		return word.substring(i,i);
	} else {
		return word.substring(i,j+1);
	}
}

/**
 * Hides the progress bar dialog when the submitted request has completed.
 * Set the visibility of the progress bar dialog to hide from the page.
 */
function cursor_clear() {
		//Reset the flag 
		requestSubmitted = false;

		//Hide the progress bar dialog
		var dialog = dijit.byId('progress_bar_dialog');
		var progressBar = document.getElementById('progress_bar');
		if(dialog != null){
			if(progressBar != null){
				progressBar.style.display = 'none';
			}
			dialog.hide();
			this.currentId="";
		}
}	

/**
 * Checks whether a request can be submitted or not.
 * A new request may only be submitted when no request is currently running.
 * If a request is already running, then the new request will be rejected.
 *
 * @return {boolean} Indicates whether the new request was submitted (true) or rejected (false).
 */
function submitRequest() {
	if(!requestSubmitted) {
		requestSubmitted  = true;
		return true;
	}
	return false;
}
 
/**
 * Set the current page to a new URL.
 * Takes a new URL as input and set the current page to it, executing the command in the URL.
 * Used for Non-ajax calls that requires multiple clicks handling.
 * 
 * @param {string} newPageLink The URL of the new page to redirect to.
 */
function setPageLocation(newPageLink) {
	//For Handling multiple clicks
	if(!submitRequest()){
		return;
	}
			
	document.location.href = newPageLink;
}

/**
 * Submits the form parameter.
 * Requires a form element to be passed in and submits form with its inputs.
 * Used for Non-ajax calls that requires multiple clicks handling.
 *
 * @param {element} form The form to be submitted.
 */
function submitSpecifiedForm(form) {
	if(!submitRequest()){
		return;
	}
	form.submit();
}


/**
 * Parses a Dojo widget.
 * Pass in the id of a dojo widget or a HTML container element containing a dojo widget, such as a div,
 * and this method will parse that widget, or all the widgets within that HTML container element.
 * 
 * @param {string} id The id of a dojo widget or a HTML container of a dojo widget to be parsed.
 */
function parseWidget(id)
{
	var node;
	var widget = dijit.byId(id);
	
	if (widget == null || widget == undefined)
	{ 
		if (id == null || id == undefined)
		{	
			node = dojo.body();
		}
		else
		{
			node = dojo.byId(id);
		}
		
		if (node != null && node != undefined)
		{	
			if (node.getAttribute("dojoType") != null && node.getAttribute("dojoType") != undefined)
			{
				dojo.parser.instantiate([node]);
			}
			else
			{
				dojo.parser.parse(node);
			}
		}
	}
}

/**
 * Parses the header menu.
 * The header menu is only parsed when the user hovers over it to improve the performance of the store loading.
 *
 * @param {string} id The id of the menu item which the user hovers over to initialize the progress bar next to that item.
 */
function parseHeader(id)
{
	var node = dojo.byId("progress_bar_dialog");
	var showMenu = document.getElementById("header_menu_loaded");
	var hideMenu = document.getElementById("header_menu_overlay");
	
	if(currentId.length == 0 && document.getElementById("header_menu_loaded")!=null && document.getElementById("header_menu_loaded")!='undefined' && document.getElementById("header_menu_overlay")!=null && document.getElementById("header_menu_overlay")!='undefined' && document.getElementById("header_menu_loaded").style.display == 'none')
	{
		setCurrentId((id != null && id != undefined)?id:hideMenu.id);
		submitRequest();
		cursor_wait();
		hideMenu.style.display = "none";
		parseWidget("header_menu_loaded");
		showMenu.style.display = "block";
		cursor_clear();
	}
}


 /**
  * This function is used to hide an element with the specified id.
  * @param {string} elementId The id of the element to be hidden.
  */

  function hideElementById(elementId){
		var div = dojo.byId(elementId);
		div.style.display = "none";
 }

/**
  * This function is used to display an element with the specified id.
  * @param {string} elementId The id of the element to be displayed.
  */

   function showElementById(elementId){
		var div = dojo.byId(elementId);
		div.style.display = "block";
}



var objectsParsed=new Array();
var objectCounter = 0;

function changeImage(id,wid)
{
	if (wid == null || wid =='undefined')
	wid="";
	linkParsed = false;
	//check if object is parsed already to avoid infinite loop
	for(i=0;i<objectsParsed.length;i++)
	{
		obj = objectsParsed[i]
		linkParsed = obj===id
		if(linkParsed) 
			break;		
	}
	if(linkParsed)
		return;
	try{	
		var scene7Url=location.protocol+'//brands.scene7.com/is/image/brands/';
		if(location.protocol=="https:")
		scene7Url=location.protocol+'//a248.e.akamai.net/f/248/9086/10h/origin-g2.scene7.com/is/image/brands/';
	//assign new image
		id.src= scene7Url+'bh_imageNotAvailable_'+wid+'?fmt=png-alpha&wid='+wid;	
		objectsParsed[objectsParsed.length]= id;
		}
	catch(er)
		{
		}
}


// add a delay to the topcategories menu
if (!bh) var bh = {};
bh.topcategories = {
      delay : null,
      DELAY_TIME: 3000,
      init : function() {
            // create jQuery like hover event for Dojo
            dojo.NodeList.prototype.hover = function(over, out){
                return this.onmouseenter(over).onmouseleave(out || over);
            }
            dojo.addOnLoad(function() {
                  bh.topcategories.addEvents();
            });
      }(),
      hideMenuAfterDelay : function() {
            bh.topcategories.delay = setTimeout("bh.topcategories.hideTopLevelMenu()", bh.topcategories.DELAY_TIME);
      },
      hideTopLevelMenu : function() {
      		dojo.query("#header_logo a")[0].focus();
            clearTimeout(bh.topcategories.delay);
      },
      addEvents : function() {
            dojo.query("#header_menu_loaded a, .dijitPopup h1, .dropdown h1,"+
                        ".dijitPopup h2, .dropdown h2, .dijitPopup li a, .dropdown li a,"+
                        ".dijitPopup table, .dropdown table").hover(
            function(e){
                  // mouseenter
                  clearTimeout(bh.topcategories.delay);
            },
            function() {
                  // mouseleave
                  bh.topcategories.hideMenuAfterDelay();
            });
      }
}; //end bh.topcategories

var addUrlClass =  {
	imagePath : "",
	PRE_CLASS : "url-", // appended class name in format url-http, url-https
	url: "", 
	prefix : "", 
	bodyTag : null, 
	bodyClass : "",
	newClass : "",
	HTTP_URL : "http://brands.scene7.com/is/image/brands/",
	HTTPS_URL : "https://a248.e.akamai.net/f/248/9086/10h/origin-g2.scene7.com/is/image/brands/",
	init : function() {
		dojo.addOnLoad(function() {
			// reduce namespace
			var uc = addUrlClass;
			uc.url = window.location.href; 
			uc.prefix = uc.url.substring(0,uc.url.indexOf(":"));
			uc.bodyTag = document.getElementsByTagName("body")[0];
			uc.bodyClass = uc.bodyTag.className;
			// append class
			uc.newClass = uc.bodyClass + " " + uc.PRE_CLASS + uc.prefix.toLowerCase();
			uc.bodyTag.className = uc.newClass;
			switch(uc.prefix) {
				case "http" : uc.imagePath = uc.HTTP_URL;
				break;
				case "https" : uc.imagePath = uc.HTTPS_URL;
				break;
				case "file" : uc.imagePath = uc.HTTP_URL;
				break;
			}
		});
	}()
}; // end addUrlClass





