/**************************************************************************************************************************
     Author              :      PA
     Version             :      1.0
     Date Created        :         
	   
     Change history      :
	
     Task/Bug                  Date(mm-dd-yyyy)       Author            Change Description	
	 
     Trac 1179                 10-08-2008             SNaina            Code modified as per Anthro Redesign 2008, product detail family view page.
	 
     Trac 1179                 10-13-2008             Hgolla            Code modified for Anthro Redesign 2008, Product detail page.
	 
     Remove javascript
     links on category
     pages(Task 79).           12-16-2008             HAlagesan         Code Modified to add two new function "changeColorForSwatches" & "InitializeValues".
	 
     Trac 1380                 03-11-2009             PSahu             Removed navId parameter after new navigation redesign. 	
	 
     Anthro Bazzar Voice 2009  03-16-2009             PVeedu            Modified page for Anthro Bazzar Voice 2009. 
     
     Trac 1586                 04-21-2009             PVeedu            Code added for downloading images on the product detail pages.
     
     Trac 1499                 07-15-2009             BTellajeera       openDebitcardNotificationPopUp() function has been added to generate Debit-Card double-hold notification pop-up.
     
     Removed unused code,      07-27-2009             HGolla            Modified code for changing product color in category pages.
     which is repeating 
     unnecessarily
     in category pages.
     
     Wrong left nav and breadcrumb 
     are displayed for the 
     following scenario       08-13-2009              HAlagesan         isProduct=true parameter added and parentid is changed to catId.
     
     Trac 1680                09-08-2009              HGolla            Parameter isBigImage added to the product url.
     
     Trac 1215                09-21-2009              SGopidinne        subCategoryId parameter passed to the product url.
     
     Anthro - Baynote  2009   11-09-2009              SGopidinne        GetXmlHttpObject() & ajaxCallToBaynoteStatus() added.
     
     Trac 2025                01-27-2009              HGolla            Added method getViewCode(), this method extracts alternate view code from product's URL.
                                                                        Passing this alternate view code parameter to the popup_zoomviewer.jsp.

     Trac 2025                02-01-2010              HGolla            Passing product image URL to download form.

     Trac 1974                06-08-2010              Rpark	            for familymod template, updated functions changeColor(), setViewerWithColor(), changeColorForSwatches()
 
     Trac 2363                07-10-2010              mTorbin           Added functions for the start of a global library
 	 
     Trac 2391                08-20-2010              HGolla            Removed unused colorName parameter.
     
     Color name is not displayed 
     for Main product in 
     Family product page      09-14-2010             HAlagesan          changeColor() function modified to display Color name.
 	 
     Trac 2391                12-13-2010             HAlagesan          changeColorForSwatches() function modified to add null checks.
***************************************************************************************************************************/
function importScript(url){
	var tag = document.createElement("script");
	tag.type="text/javascript";
	tag.src = url;
	document.body.appendChild(tag);
}

if ((window.location.href.indexOf("search1.anthropologie.com") != -1) || (window.location.href.indexOf("search.anthropologie.com") != -1)) {
	importScript("http://www.anthropologie.com/anthro/ui/scripts/jquery.cookie.js");
}

var AdlucentCookie =  new Class.create();
AdlucentCookie.prototype = {
	initialize: function(cookieValue){
	  this.cookieDomain = ";domain=anthropologie.com";
	  this.cookieName = "kwid";
	  this.cookieValue = cookieValue;
	  if (cookieValue != null && cookieValue != "") {
		  if (this.getCookie() != null && this.getCookie() != "") { //destroy old cookie
		  	this.deleteCookie(this.cookieName);
		  }
		  this.createCookie(this.cookieName, this.cookieValue, 14, this.cookieDomain); // for test purposes, set at 1 day
	  }
	},
	createCookie: function(name,value,days,cookieDomain) {
	 if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	 }
	 else var expires = "";
	 document.cookie = name+"="+value+expires+cookieDomain+"; path=/";
    },
    getCookie: function(){
	  var results = document.cookie.match ( '(^|;) ?' + this.cookieName + '=([^;]*)(;|$)' );
	  if (results)
	    return ( unescape ( results[2] ) );
	  else
		return null;
    },
	deleteCookie: function(name){
	  var cookie_date = new Date ( );  // current date & time
  	  cookie_date.setTime ( cookie_date.getTime() - 1 );
      document.cookie = name += "=; expires=" + cookie_date.toGMTString();
    }
};

function imgClicked(imgId, imgElem){ 
 var end=imgId.lastIndexOf("_");
  imgId=imgId.substring(0,end);
 if (end!=-1)
    {
       unselectAll_iterator(imgId);     
    }
 else{ 
       unselectAll(imgId);
 }

 imgElem.name="selected";
 imgElem.className = "selected";
}

/* Code modified for Trac 1974 */
/* prodTempl added which is used from familymod product detail page */
function changeColor(id, pColorCode, prodImg,skuId, pColorName, isLeaderProduct, pSizeName, prodTempl){
    //Code modified for Trac 2025
	var viewCode = getViewCode(prodImg);
	var uniqueId = id;    
    if(pSizeName!=null && pSizeName!=""){
        uniqueId = pSizeName;
    }
    
    if(isLeaderProduct!=null & isLeaderProduct=="true"){
        uniqueId = "l"+uniqueId;
    }
    if(skuId!=null && skuId!="")
    {
        getElement(uniqueId+"catalogRefIds").value = skuId;
        getElement(uniqueId+"qty").name = skuId;
    }

	if(getElement("color"+uniqueId)!=null){
	   getElement("color"+uniqueId).value=pColorCode;
	}
	if (getElement("colorName"+uniqueId) != null){
		getElement("colorName"+uniqueId).value=pColorName;
	}
	if(getElement(uniqueId+"selectedColor")!=null && pColorName!=null)
	{    
		getElement(uniqueId+"selectedColor").innerHTML=pColorName.toUpperCase();
	}
	
	// code is added for trac 1179 
	if(getElement(uniqueId+"selectedColorMoreInfo")!=null && pColorName!=null)	{	
		getElement(uniqueId+"selectedColorMoreInfo").innerHTML=pColorName.toUpperCase();		
	}
	// End of code is added for trac 1179 
    
    if(getElement(id+"sizeguide")!=null && pColorCode!=null && id!=null)
    {
        getElement(id+"sizeguide").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_sizeguide.jsp?productid="+id+"&color="+pColorCode+"');";
    }
    
    if(getElement(id+"careguide")!=null && pColorCode!=null && id!=null)
    {
        getElement(id+"careguide").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_careguide.jsp?productid="+id+"&color="+pColorCode+"');";
    }    
    
    if(getElement(id+"requestswatches")!=null && pColorCode!=null && id!=null)
    {
        getElement(id+"requestswatches").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_requestswatches.jsp?productid="+id+"&color="+pColorCode+"');";
    }    
    
    if(getElement(id+"image")!=null && pColorCode!=null && id!=null)
    {
        //Code modified for Trac 2025: Passing parameter viewCode to the popup_zoomviewer.jsp
        getElement(id+"image").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+id+"&color="+pColorCode+"&viewCode="+viewCode+"');";
    }    
    
    if(getElement(uniqueId+"zoomviewer")!=null && pColorCode!=null && id!=null)
    {
        //Code modified for Trac 2025: Passing parameter viewCode to the popup_zoomviewer.jsp
        getElement(uniqueId+"zoomviewer").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+id+"&color="+pColorCode+"&viewCode="+viewCode+"');";
    }
   
    //Code modified for Trac 1586.
    if(getElement("imgdownload"+id)!=null && pColorCode!=null && id!=null){
        getElement("imgdownload"+id).innerHTML="<a href=\"javascript:downloadImage('"+prodImg+"');\">download image</a>";
    //Code modified for Trac 2025.    
	}else if(document.imageDownload!=null && typeof(scene7ImgSize) != "undefined"){
		var urlSize = prodImg.split("?");
		if(urlSize.length > 1){
           document.imageDownload.url.value = urlSize[0]+scene7ImgSize;
		}else{
		   document.imageDownload.url.value = prodImg+scene7ImgSize;
		}
	}
	//End of code modified for Trac 2025.
	//End of Code modified for Trac 1586. 

     if(isLeaderProduct!=null & isLeaderProduct=="true"){
        if(getElement("scene7viewer")!=null && pColorCode!=null && uniqueId!=null)
        {    
            //Code modified for Trac 2025: Passing parameter viewCode to the popup_zoomviewer.jsp
            getElement("scene7viewer").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+id+"&color="+pColorCode+"&viewCode="+viewCode+"');";
        }
        if(getElement("openlargerimage")!=null && pColorCode!=null && uniqueId!=null)
        {
            //Code modified for Trac 2025: Passing parameter viewCode to the popup_zoomviewer.jsp
            getElement("openlargerimage").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+id+"&color="+pColorCode+"&viewCode="+viewCode+"');";
        }
        if(getElement("tellafriend")!=null && pColorCode!=null && uniqueId!=null)
        {
            getElement("tellafriend").href=encodeURI(contextPath+'/user/login_check.jsp?productId='+id+'&cCode='+pColorCode);
        }
		if (prodTempl == "familymod"){
			setViewerWithColor(pColorCode, id, prodImg, prodTempl);
		}
		else{
			setViewerWithColor(pColorCode, id, prodImg);
		}
	} 
	//Code modified for Trac 1179:Product detail page.
	changeImage("img"+uniqueId,prodImg);    
	//End of code modified for Trac 1179: Product Detail.
		
}

function changeImage(imageHandle,prodImg){  
    if(window.useModelViews == true){
	  prodImg = swapForModelViews(prodImg);	
	}
	if(prodImg != null && document[imageHandle]!=null){
        document[imageHandle].src = prodImg;
    } 
}

function changeSelectedColorText(prodId, pColorName) {  
  if(getElement(prodId+"selectedColor")!=null && pColorName!=null) {    
    getElement(prodId+"selectedColor").innerHTML=pColorName.toUpperCase();
    }
}

function changeImageMixMatch(imgProdSelectorName, imgProdSelectorUrl, imgMixMatchName, imgMixMatchUrl ) {  
  changeImage(imgProdSelectorName, imgProdSelectorUrl); 
  changeImage(imgMixMatchName, imgMixMatchUrl);
}

function imgMouseOver(imgElem, color){
  
 imgElem.className = "mouseOver";
}

function imgMouseOut(imgElem, color){
 if(imgElem.name == "selected"){
  imgElem.className="selected";
 } else {
  imgElem.className="unselected";
 }
}
 function unselectAll_iterator(elementId){
 var i=0;
 while(!isNull(document.getElementById(elementId+"_"+i))) {
    var elem=document.getElementById(elementId+"_"+i)
    if(elem.name == "selected") {
        elem.name = "";
        elem.className="unselected";
   }
   i++;
 }
}

function isNull(elem) {
    if(elem==null) return true;
    return false;
}
function unselectAll(elementId){
 if(document.all){
  var length = document.all(elementId).length;
  for(var i=0;i<length;i++){
   var elem = document.all(elementId, i);
   if(elem.name == "selected"){
    elem.name = "";
    elem.className="unselected";
   }
  }
 } else {
  var length = document.getElementById(elementId).length;
  for(var i=0;i<length;i++){
   var elem = document.getElementById(elementId, i);
   if(elem.name = "selected"){
       elem.name = "";
        elem.className="unselected";
   }
  }
 }
}

var scriptfunctionsarray = new Array();

function addScriptFunction(pProductId, pSizeName, pProductColor, pProdImg,pSkuId, pColorName){
    scriptfunctionsarray.push(new scriptfunction(pProductId, pSizeName, pProductColor, pProdImg,pSkuId, pColorName));
}

function callscriptfunctions(){
    for(var i=0;i<scriptfunctionsarray.length;i++){        
        changeColor(scriptfunctionsarray[i].productId,scriptfunctionsarray[i].productColor,scriptfunctionsarray[i].prodImg,scriptfunctionsarray[i].skuId, scriptfunctionsarray[i].colorName, '', scriptfunctionsarray[i].sizeName);
    }
}

function scriptfunction(productId, pSizeName, pProductColor, pProdImg, pSkuId, pColorName){
    this.productId = productId;
    this.sizeName = pSizeName;
    this.productColor = pProductColor;
    this.prodImg = pProdImg;
    this.skuId = pSkuId;
    this.colorName = pColorName;    
}

function addItemToBag(){
    document.frmAddToCart.action.value = "addToBag";
    document.frmAddToCart.submit();
}    
function addItemToWishlist(){
    document.frmAddToCart.action.value = "addToWishlist";
    document.frmAddToCart.submit();
}    
function getElement(elementId){
    return document.all ? document.all[elementId] : document.getElementById(elementId);
}    

function View(pViewName, pViewURL){
    this.viewName = pViewName;
    this.viewURL = pViewURL;
}

function Color(pColorCode, pColorName, pProductImageURL){
    this.colorCode = pColorCode;
    this.colorName = pColorName;
    this.productImageURL = pProductImageURL;
    this.viewList = new Array();
    
    
    this.addView = function(pViewName, pViewURL){
        this.viewList.push(new View(pViewName, pViewURL));
    }
}

function openWindow(pURL, pName, pWidth, pHeight){
    var features = "width="+pWidth+",height="+pHeight+",status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,titlebar=no,resizable=no";
    window.open(encodeURI(pURL), pName, features);
}

/* Code modified for new Shoe Size Guide that includes Euro sizes */
function openProductPopupWindow(pURL){ // all size guides call this popup
	if (pURL.match("/html/sizeguide-shoes.html")){ // shoe size guide is especially long
	    openWindow(pURL, 'productpopup', 800, 200);
	} else if(pURL.match("/html/sizeguide-bra.html")){ // bra size guide is big.
    openWindow(pURL, 'productpopup', 760, 855);
	} else if(pURL.match("/html/sizeguide-rings.html")){ // ring is long too
    openWindow(pURL, 'productpopup', 600, 200);
	} else {
    openWindow(pURL, 'productpopup', 500, 690);
	}
}

function openInformationalPopupWindow(pURL){
    openWindow(pURL, 'informationalpopup', 477, 600);
}

function loginSubmit(){
    document.loginForm.action.value = "login";
    document.loginForm.submit();
}   

function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   myfield.form.submit();
   return false;
   }
else
   return true;
}

function formatPhoneNumber(phone){
	var sAreaCode = phone.substring(0,3);
	var s3dig = phone.substring(3,6);
	var s4dig = phone.substring(6,10);
	var newPhone = "("+sAreaCode+") "+s3dig+"-"+s4dig;
	return newPhone;
}

// code modified for Trac 1974: accepting pSubId and prodTempl
// code is added for "Remove javascript links on category pages"(Task 79).
function changeColorForSwatches(pProductId, prodImg,pColorCode,pColorName, pIsBigImage, pTemplateType, pSubCategoryId, pSubId, prodTempl){
		var uniqueId = pProductId;
		var viewAllinkHandle = "viewAllink"+uniqueId;
		var viewAldeslinkHandle = "viewAldeslink"+uniqueId;
		var viewAldislinkHandle = "viewAldislink"+uniqueId;
		var deslinkHandle = "deslink"+uniqueId;
		var imglinkHandle = "imglink" + uniqueId;
		if(window.useModelViews == true){
	  	  prodImg = swapForModelViews(prodImg);	
		}
		if(prodImg != null && pProductId!=null){
			getElement("color"+uniqueId).value=pColorCode;
			document["img"+uniqueId].src = prodImg;
		}
		
		/* if this is product is in a familymod template, we want to append the child product ID in the link so that we get the correct faceout product ID initialized when we hit the product detail page, since, at the category level, we are showing swatches for all the child products; otherwise, just leave the param out */
		var subIdParams = '';
		if (prodTempl == "familymod"){
			subIdParams = '&subId='+pSubId;
		}
		var detailLink = contextPath+'/catalog/productdetail.jsp?id='+pProductId+'&catId='+catId+'&navCount='+navCount+'&navAction='+navAction+'&isProduct=true';
		
		if (pushId != null && pushId != "" && pushId.length != 0){
			detailLink = detailLink+'&pushId='+pushId;
		}
		if (popId != null && popId != "" && popId.length != 0){
			detailLink = detailLink+'&popId='+popId;
		}
		if (fromCategoryPage != null && fromCategoryPage != "" && fromCategoryPage.length != 0){
			detailLink = detailLink+'&fromCategoryPage='+fromCategoryPage;
		}
		if (pColorCode != null && pColorCode != "" && pColorCode.length != 0){
			detailLink = detailLink+'&color='+pColorCode;
		}
		if (pTemplateType != null && pTemplateType != "" && pTemplateType.length != 0){
			detailLink = detailLink+'&templateType='+pTemplateType;
		}
		if (pSubCategoryId != null && pSubCategoryId != "" && pSubCategoryId.length != 0){
			detailLink = detailLink+'&subCategoryId='+pSubCategoryId;
		}
		if (pIsBigImage != null && pIsBigImage != "" && pIsBigImage.length != 0){
			detailLink = detailLink+'&isBigImage='+pIsBigImage;
		}
		//Code modified for Wrong left nav and breadcrumb are displayed for the following scenario.
		if(getElement(imglinkHandle) != null){
			getElement(imglinkHandle).href=encodeURI(detailLink+subIdParams);
		}
		
		if(getElement(deslinkHandle) != null){
			getElement(deslinkHandle).href=encodeURI(detailLink+subIdParams);
		}
		
		if(getElement(viewAllinkHandle) != null){
			getElement(viewAllinkHandle).href=encodeURI(detailLink+subIdParams);
		}
		
		if(getElement(viewAldeslinkHandle) != null){
			getElement(viewAldeslinkHandle).href=encodeURI(detailLink+subIdParams);
		}
		
		if(getElement(viewAldislinkHandle) != null){
			getElement(viewAldislinkHandle).href=encodeURI(detailLink+subIdParams);
		}
		//End of code modified for Wrong left nav and breadcrumb are displayed for the following scenario.
		
	}

function InitializeValues(pCatId,pPushId,pPopId,pSortProperties,pNavCount,pNavAction,pFromCategoryPage,pSelectedProductSize,pSelectedProductSize1){
	
	this.catId = pCatId;
	this.pushId = pPushId;
	this.popId = pPopId;
	this.sortProperties = pSortProperties;
	this.navCount = pNavCount;
	this.navAction = pNavAction;	 
	this.fromCategoryPage = pFromCategoryPage;
	this.selectedProductSize = pSelectedProductSize;
	this.selectedProductSize1 = pSelectedProductSize1;
}
// End of code is added for "Remove javascript links on category pages"(Task 79).

//Code added for Trac 1499.
function openDebitcardNotificationPopUp(Url) {
     var myRef = window.open(Url,'debitCardNotification',"height=200,width=340,status=no,toolbar=no,menubar=no,location=no,resizable=no");
}
//End of code added for Trac 1499.

//GetXmlHttpObject() added for Anthro Baynote.
function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
      } catch (e) {
      // Internet Explorer
	         try {
	                 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	         } catch (e) {
	                 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
      }
    return xmlHttp;
 }

//ajaxCallToBaynoteStatus() added for Anthro Baynote.
function ajaxCallToBaynoteStatus() {           
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp==null) {
        return;
    } 
    if(typeof(bnPolicy) != "undefined"){
    	var isBaynoteEnabled = bnPolicy.get("guide","ok");
		if(isBaynoteEnabled != null){
	    	var url="/anthro/catalog/baynote_status.jsp?baynoteEnabled="+isBaynoteEnabled;
    		xmlHttp.open("GET",url,true);
    		xmlHttp.send(null);
		}
	
    }

}

//Added method for Trac 2025.
//The below method is used to extract alternate view code from product image url.
function getViewCode(pProductImageUrl){
	var productImageCode = pProductImageUrl.split("?");
	var imageUrl = productImageCode[0].split("/");
	var imageParams = imageUrl[imageUrl.length-1];
	var imageAttributes = imageParams.split("_");
	return imageAttributes[2];
}

// MATT TORBIN GLOBAL LIB FUCTIONS
function getCookie(myCookieName){
	var myCookies = new Array();
	if (document.cookie.length > 0){
		cookieTray = document.cookie.split(";");
		for(x = 0; x < cookieTray.length; x++) {myCookies[x] = new Array(cookieTray[x].split("="));}
		for(y = 0; y < myCookies.length; y++) {if(myCookies[y][0][0] == myCookieName) {return myCookies[y][0][1];}}
	}
	else{return "";}
}

function parseNavOBJ(index,value,response){
	var myNavARR = new Array();
	for(attribs in navigator){myNavARR[attribs] = navigator[attribs];}
	if(myNavARR[index].indexOf(value) != -1){
		if(response != 1){return myNavARR[index];}
		else{return true;}
	}
	else{return false;}
}

function globalReplace(myString,myFind,myReplace){
	var tempSTR = "";
	for(var x = 0; x < myString.length; x++){tempSTR += (myString.charAt(x) == myFind) ? myReplace : myString.charAt(x);}
	return tempSTR;
}

function showRqSwch(mySwatchType){
	var productStyleRegEx = new RegExp("[0-9]{5,11}");
	var styleNumber = String(productStyleRegEx.exec($("style").innerHTML));
	var myURL = "rqSwch.jsp?type=" + mySwatchType + "&style=" + styleNumber;
	if(opener && !opener.closed){opener.focus();}
	else{var rqSwchWin = window.open(myURL,'Swatch_Request','width=876,height=600,location=no,resizable=no');opener = rqSwchWin;}
}

function submitform(s)
{
    document.loginForm.formAction.value=s;
    document.loginForm.submit();
}

//Memory Leak Fix - added to release event memory once we're done with it in all browsers
//Effects IE6/IE7 & FF the most
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
   
