/**
 * This file contains Javascript utility functions used throughout the blueprint application.
 */

dojo.provide("atg.b2cblueprint.util");

atg.b2cblueprint.util={
  /** 
   * Used on the cart page to autoselect the giftnote when 
   * a user selects the gift wrap option
   */
  autoSelectGiftNote: function() {    
    if (document.cartform.atg_b2cblueprint_addWrap.checked &&
        !document.cartform.atg_b2cblueprint_addNote.checked) {       
      document.cartform.atg_b2cblueprint_addNote.click();
    }  
  },
  
  /**
   * The email campaign popup.  First check the form fields to 
   * make sure we can submit.
   */ 
  emailSignup: function(URL, theForm) {  
    // need to make sure the required fields are not null
    var openWindow = true;
    
    // check to see if we have an email address at all
    var addressEntered = theForm.emailAddress.value;
    if (dojo.string.trim(addressEntered) === "") {
      openWindow = false;
    }
    
    //if email id is not valid don't open the window
    if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(addressEntered))){
      openWindow = false;
    }
  
    // don't open window if we had a form error
    if (openWindow) {
      document.open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=480,height=500");
    }
  },
  
  /**
   * The product details popup 
   */
  detailsPopup: function(URL) {
    document.open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=640,height=680");
  },
  
  /**
   * The notify me when in-stock popup 
   */
  notifyMePopup: function(URL) {
    document.open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=480,height=500");
  },

  /**
   * Return false if the key pressed in the event object is the return key, true otherwise
   */
  killEnter: function(evt) {
    if(evt.keyCode == 13 || evt.which == 13) {
      return false;
    }
    return true;
  },

  /**
   * Update facet trail value
   */
  updateFacetTrail: function(xkeyword){
    var trltxt = dojo.string.trim(document.facetSearch.trailtext.value);
    if(trltxt === "" || trltxt === dojo.string.trim(xkeyword)){
      document.facetSearch.addFacet.value="";
      document.facetSearch.trailtext.value="";
    }
    else{
      document.facetSearch.addFacet.value="SRCH:"+trltxt;
    }
    return true;
  }, 
  /**
   * Display block if none 
   */
  toggleDiv: function(divName){
    var displayStyle = document.getElementById(divName).style.display;
    displayStyle=(displayStyle!="block")? "block" : "none";
    document.getElementById(divName).style.display=displayStyle; 
  },
  /**
   * Display blocks as per number of facetIndex
   */
  compressDiv: function(i){
    var displayStyleBlock = "block";
    var displayStyleNone = "none";
    if (document.getElementById("moreDiv"+i) != null) {
      document.getElementById("moreDiv"+i).style.display=displayStyleBlock;
      document.getElementById("lessDiv"+i).style.display=displayStyleNone;
    }
  },
  /**
   * Caller function for toggleDIv and compressDiv
   */
  toggleBothDiv: function(idx, totalFacet){
    atg.b2cblueprint.util.toggleDiv("moreDiv"+idx);
    atg.b2cblueprint.util.toggleDiv("lessDiv"+idx);
    for (i=0;i<totalFacet;i++) {
      if (i != idx) {
        atg.b2cblueprint.util.compressDiv(i);
      }
      else {
        continue;
      }
    }
  },
  /**
   * Display the catalog flyout menus in IE6. All other browsers handle flyouts via CSS.
   */
  catalogNavIE: function(){
    if (!dojo.render.html.ie60){
      // Only apply to IE6
      return;
    }
    
    var catNav = dojo.byId('atg_b2cblueprint_catalogNav');
    if (!catNav){
      return;
    }
    
    var navItems = catNav.getElementsByTagName('ul');
  
    for(i=1; i<navItems.length; i++){    
      // Add the "over" class if the current list item doesn't have the class "active"
      dojo.event.connect(navItems[i].parentNode, "onmouseover", function(evt){
          dojo.html.addClass(evt.currentTarget, "over");
      });
    
      // Remove the "over" class   
      dojo.event.connect(navItems[i].parentNode, "onmouseout", function(evt){
        dojo.html.removeClass(evt.currentTarget, "over");
        evt.stopPropagation();
      });
    }
  },

  /**
   * Text Area character counter
   */
  textAreaCounter: function(htmlTextArea , currentCounter, maxCounter) {
    var maxLimit = document.getElementById(maxCounter).firstChild.nodeValue;
    var currentCount = document.getElementById(currentCounter);

    if (htmlTextArea.value.length > maxLimit){
      htmlTextArea.value = htmlTextArea.value.substring(0, maxLimit);
    }else{
      currentCount.innerHTML = htmlTextArea.value.length;
    }
  },
  
  /**
   * Disable nodes that have atg_behavior_disableOnClick CSS class applied to them when they are clicked.
   * 
   * Expects the following attributes passed in on the params object
   *   cssClass: CSS class denoting the behavior
   *   defaultDisabledValue: Text value that will be set on the node when clicked and disabled
   *   freezeWidth: boolean signifying whether the width of the nodes should be retained
   * 
   * Any node that the behavior is attached to will be disabled whenever a click event is intercepted. This
   * should help prevent any double submit errors on the server.
   * 
   * A 'disabledValue' attribute may be set on the node itself. This value will override any default 
   * value that is set on this function.
   */
  applyDisableOnClickBehavior: function(params){
    var elements=dojo.html.getElementsByClass(params.cssClass);
    dojo.debug("Applying DisableOnClick behavior to "+elements.length+" nodes with class ["+params.cssClass+"]");
    
    for (var i=0; i<elements.length; i++){
      var node=elements[i];
      dojo.debug(node);
      
      dojo.event.connect(node,"onclick",function(evt){  
        var node=evt.target;
        if (node.justClicked){
          dojo.debug("Ignoring click");
          // Node has already been clicked and is being handled, so ignore this click
          evt.preventDefault();
          evt.stopPropagation();
          return false;
        }
        
        dojo.debug("Disabling node before form submission");
        dojo.debug(node);
        
        // retain original node width - prevents node from resizing when disabled value text is set on it
        if (params.freezeWidth){
          node.style.width=dojo.html.getBorderBox(node).width+"px";
        }
        
        // Get disabled text from node if set, otherwise use default passed to this function. If default not
        // set, just use the existing value on the button.
        var disabledValue=node.getAttribute("disabledValue");
        var originalValue=(node.nodeName=="INPUT" ? node.value : node.innerHTML);
        if (!disabledValue) { 
          disabledValue=(params.defaultDisabledValue ? params.defaultDisabledValue : originalValue);
        }
        
        if (node.nodeName=="INPUT"){
          // Create hidden form element to copy submit button's value into. Need to do this as disabled elements
          // are not submitted from a form by the browser.
          var replacementNode=document.createElement("INPUT");
          replacementNode.type="hidden";
          replacementNode.name=node.name;
          replacementNode.value=node.value;
          
          // Append this to the parent form
          var formNode=dojo.html.getParentByType(node,"FORM");
          formNode.appendChild(replacementNode);
          
          // Disable the node
          node.value=disabledValue;
          node.name="";
          node.disabled=true;
          
          // Disabling the submit button prevents the form from being submitted in IE, so submit it here
          evt.preventDefault();
          formNode.submit();        
        } 
        else if (node.nodeName=="A"){
          node.innerHTML=disabledValue;
          node.justClicked=true; // Prevent further clicks from causing default behavior
        }
        
        // Continue with normal browser processing of click event
        return true;
      });
    }
  },
  noenter: function() {
    return !(window.event && window.event.keyCode == 13); 
  }
};


/***********************/
/* topdrawer functions */
/***********************/

function PopUp(URL, windowName, width, height) {
  window.open(URL, windowName, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width='+width+',height='+height+',left = 10,top = 10');
}

function PopUpWithScroll(URL, windowName, width, height) {
  window.open(URL, windowName, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width='+width+',height='+height+',left = 10,top = 10');
}

function printPage() {
  if (window.print)
    window.print()
  else
    alert("Sorry, your browser doesn't support this feature. Please use the menubar to print page.");
}

	/* top drawer photofader */
	
	// originally from http://www.houserdesign.com/photofader/
	
	// modified by Joel Desamero
	// 	* improved OOP implementation for handling multiple instances
	// 	* independent control of speed/delay per instance
	//  * no need to initialize external image array, use 'addImage' method instead
	//  * custom links/alttags/target per image
	
	
	function photofader(sName)
	{
		// global reference for current instance
		var goThisPF = this;
		
		////// properties
		
		this.sName = sName;
		this.aImages = new Array();
		this.iCurImgIdx = 0;
		this.iCurDivIdx = 1;
		this.iSpeed = 20;		// in seconds
		this.iDelay = 2;		// in seconds
		
		
		////// accessor methods
		
		
		// set speed and delay values
		this.setSpeedDelay = function(iSpeed, iDelay)
		{
			this.iSpeed = iSpeed;		// in seconds
			this.iDelay = iDelay;		// in seconds
		}
			
		// add an image to the slideshow
		this.addImage = function(sImageSrc, sLink, sTarget, sAltTag)
		{
			this.aImages.push(new Array(sImageSrc, sLink, sTarget, sAltTag));
		}
		
		
		////// other methods
		
		this.preLoad = function()
		{		
			// styles
			document.write('<style type="text/css">\n');
			document.write('#' + this.sName + '_photo1 img { visibility:hidden; }\n');
			document.write('#' + this.sName + '_photo1 { position:absolute; z-index: 1; left: 0px; }\n');
			document.write('#' + this.sName + '_photo2 { position:absolute; z-index: 0; left: 0px; }\n');
			document.write('</style>');
			
			
			// preload
			for(i = 0; i < this.aImages.length; i++)
			{
				eval('var ' + this.sName + 'img' + i + ' = new Image();');
				eval(this.sName + 'img' + i + '.src = "' + this.aImages[i][0] + '";');
			}
		
		}
		
		// call to initialize
		this.initImages = function()
		{
			// initialize
			sDiv1ID = this.sName + '_photo1';
			sDiv2ID = this.sName + '_photo2';
					
			eDiv1 = document.createElement('div');
			eDiv1.id = sDiv1ID;
			eDiv1.innerHTML = '<img src="' + this.aImages[0][0] + '" alt="' + this.aImages[0][3] + '"/>';
			
			eDiv2 = document.createElement('div');
			eDiv2.id = sDiv2ID;
					
			eMainDiv = document.getElementById(this.sName);
			eMainDiv.appendChild(eDiv1);
			eMainDiv.appendChild(eDiv2);
			
			eCurrentImg = document.getElementById(sDiv1ID).childNodes[0];
			
			this.setLink(this.aImages[0][1], this.aImages[0][2]);
			
			this.setOpacity(eCurrentImg, 0);
			eCurrentImg.style.visibility = 'visible';
			this.fadeIn(sDiv1ID, 0);
	
	
		}
		
		// set opacity
		this.setOpacity = function(eSubject, iOpacity)
		{
			iOpacity = (iOpacity == 100) ? 99.999 : iOpacity;
			
			// IE/Win
			eSubject.style.filter = "alpha(opacity:" + iOpacity + ")";
			
			// Safari<1.2, Konqueror
			eSubject.style.KHTMLOpacity = iOpacity / 100;
			
			// Older Mozilla and Firefox
			eSubject.style.MozOpacity = iOpacity / 100;
			
			// Safari 1.2, newer Firefox and Mozilla, CSS3
			eSubject.style.opacity = iOpacity / 100;
		}
		
		// fade in
		this.fadeIn = function(sElemID, iOpacity)
		{
			if (document.getElementById)
			{
				eSubject = document.getElementById(sElemID).childNodes[0];
				if (iOpacity < 100)
				{
					this.iSpeed = (this.iSpeed < 2) ? 2 : this.iSpeed;
					this.setOpacity(eSubject, iOpacity);
					iOpcDiff = Math.ceil((100 - iOpacity) / this.iSpeed);
					iOpacity += iOpcDiff;
					//iOpacity += 2;
					
					setTimeout(function(){goThisPF.fadeIn(sElemID, iOpacity);}, 100);
				}
				else
				{
					setTimeout(function(){goThisPF.swapImages();}, this.iDelay * 1000);
				}
			}
		}
		
		// swap images
		this.swapImages = function()
		{
			// find out which 
			if (this.iCurImgIdx == this.aImages.length - 1)
			{
				this.iCurImgIdx = 0;
			}
			else 
			{
				++this.iCurImgIdx;
			}
			
			// now get the div to hld the new image
			if (this.iCurDivIdx == 1)
			{
				sTargetDivID = this.sName + "_photo2";
				sReplaceDivID = this.sName + "_photo1";
				this.iCurDivIdx = 2;
			}
			else
			{
				sTargetDivID = this.sName + "_photo1";
				sReplaceDivID = this.sName + "_photo2";
				this.iCurDivIdx = 1;
			}
			
			eTargetDiv = document.getElementById(sTargetDivID);
			eReplaceDiv = document.getElementById(sReplaceDivID);
			
			// now fill the target div
			eTargetDiv.innerHTML = "<img src='" + this.aImages[this.iCurImgIdx][0] + "' alt='" + this.aImages[this.iCurImgIdx][3] + "' style='visibility:hidden;' />";
			
			//move the divs around in z-index
			eReplaceDiv.style.zIndex = 0;
			eTargetDiv.style.zIndex = 1;
			
			// And finally fade in the image
			
			eImage = eTargetDiv.childNodes[0];
			
			this.setLink(this.aImages[this.iCurImgIdx][1], this.aImages[this.iCurImgIdx][2]);
			
			this.setOpacity(eImage, 0);
			eImage.style.visibility = 'visible';
			this.fadeIn(eTargetDiv.id, 0);
		}
		
		this.setLink = function(sLink, sTarget)
		{
			eMainDiv = document.getElementById(this.sName);
				
			if ('' == sLink)
			{
				// no link
				eMainDiv.style.cursor = 'auto';
				eMainDiv.onclick = null;
			}
			else
			{
				eMainDiv.style.cursor = 'pointer';
				// attach onclick action to the main div
				if ('_blank' == sTarget)
				{
					eMainDiv.onclick = function(){window.open(sLink);}
				}
				else
				{
					eMainDiv.onclick = function(){window.location=sLink;}		
				}
			}
		}
	}
	



	/* end top drawer photofader */

/***************************/
/* end topdrawer functions */
/***************************/
