wtEnabledGCF = 'false';

$(document).ready(function() {
	wtEnabledGCF = $('#wtEnabledGCFId').text().toLowerCase();		
	
	// added for p2a 
	if($('#IsP2AAvailable').length)
	{
	    var isp2aAvailable=$('#IsP2AAvailable').text();
	    if(isp2aAvailable.length>0)
	    {
	        isp2aAvailable=isp2aAvailable.toLowerCase()
	        if(isp2aAvailable=="false")
	        {
	            $('#headerContainerGlobal').css('font-size',"14px");
	        }
	    }
	}
	
	$('.P2AHeaderModule').bind('mouseenter', function() {
         $(this).addClass('megaMenuLinkHover');           
    });
    
    $('.P2AHeaderModule').bind('mouseleave', function() {
        $(this).removeClass('megaMenuLinkHover');
    });
    
   

	
	// end of changes for p2a	
});

function handleError() {
    return true;
} //end function

window.onerror = handleError;

function openPop(pURL,pName,pWidth,pHeight){
   var winWidth = 420;
   var winHeight = 325;
   var winName = "newWin";
   if (pWidth > 0){
      winWidth = pWidth;
   }//end if
   if (pHeight > 0){
      winHeight = pHeight;
   }//end if
   if (pName.length > 0){
      winName = pName;
   }//end if
   var newWin = window.open(pURL,winName,'width=' + winWidth + ',height=' + winHeight + ',status=no,toolbar=no,scrollbars=yes,resizable=yes,left=1,top=1')
   if (window.focus){ 
      newWin.focus()
   }//end if
}//end function

function submit_form(vals)
{
   //Submit the form to the next page passing along the hidden fields
   if(document.getElementById){
      document.getElementById(vals).submit();
   }else{
      document.forms[vals].submit();
   }//end if
}

function stopExit(){
   if (top.fraNavigation){
      if (top.fraNavigation.doExit){
         top.fraNavigation.doExit = false;
      }
   }
   return true;
}

function SetCookieDictionary(dictName,dictKey,dictValue,expires,path,domain,secure){
   var Dictionary = String(GetCookieBase(dictName));
   var newValue = new String();
   if (Dictionary != null){
      //Then this key exists...but is it a dictionary?
      if (Dictionary.indexOf("=") > 0){
         //This value has an equal sign in it, so most likely a dictionary
         //Now see if this value has the key in that we want
         if (Dictionary.indexOf(dictKey + "=") >= 0){
            //Yes this key is already in here, now change its value
            var arParts = Dictionary.split("&");
            var arVals = new Array();
            var indexOfEqual;
            for (var i = 0; i < arParts.length; i++){
               indexOfEqual = String(arParts[i]).indexOf("=")
               //arVals = String(arParts[i]).split("=",1);
               arVals[0] = String(arParts[i]).substring(0,indexOfEqual);
               arVals[1] = String(arParts[i]).substring(indexOfEqual+1);
               //alert('Length: ' + arVals.length + '\n\nName: ' + arVals[0] + '\n\nValue: ' + arVals[1]);

               if (newValue.length != 0){
                  newValue += "&"
               }
               if (arVals[0] == dictKey){
                  newValue += arVals[0] + "=" + escape(dictValue);
               }else{
                  newValue += arVals[0] + "=" + escape(arVals[1]);
               }   
            }
            SetCookie(dictName,newValue,expires,path,domain,secure);
         }else{
            //No, this key does not exist so add it
            newValue = Dictionary + "&" + dictKey + "=" + dictValue;
            SetCookie(dictName,newValue,expires,path,domain,secure);
         }
      }else{
         //This value is not a dictionary...how to handle?
      }
      
   }else{
      //This Dictionary has never been created, so create it
      newValue = dictKey + "=" + dictValue
      SetCookie(dictName,newValue,expires,path,domain,secure)
   }
}

function GetCookieDictionary(dictName,dictKey){
   var retval = "";
   var tempString = String(GetCookieBase(dictName));
   var arPairs;
   var arKeyValue;
   if (tempString != null){
      arPairs = tempString.split("&");
      for (var i=0; i < arPairs.length; i++){
         arKeyValue = arPairs[i].split("=");
         if (arKeyValue[0] == dictKey){
            retval = arKeyValue[1];
            return retval;
         }
      }
   
   }
   
   return retval;
}
function GetCookie (name) {
   var retval = "";
   
   if (GetCookieBase(name) != null){
      retval = String(GetCookieBase(name));
   }
   
   return retval;
}

function GetCookieBase (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen) {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg){
         return GetCookieVal (j);
      }
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) {
         break;
      }
   }
   return null;
}
function SetCookie (name,value,expires,path,domain,secure) {
   
   var cookieValue = name + "=" + (value) +
   ((expires) ? "; expires=" + expires.toGMTString() : "") +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "");
   document.cookie = cookieValue;
}

function GetCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function launchStudio(pCID,pAPNum,pFID,pIID){
   
   var winPop;
   var newWindow = false;
   var mTop = 10;
   var mLeft = 10;
   //if (screen.width >= 1024) {
      var WindowName="FrameStudio" + new Date().getTime();
	var langPrefix = '';
	if (GetCookieDictionary('ap','islangdefault') == 'false') {		
		langPrefix = '/'+GetCookieDictionary('ap','langIso');
	}
	
       if (pAPNum.indexOf("apnum") > 0)
       {
            if (pAPNum.substring(pAPNum.length-1) == "&")
                pAPNum = pAPNum.substring(0,pAPNum.length-1);
            winPop = window.open(langPrefix+"/FrameStudio/default.asp?CID=" + pCID + pAPNum + "&FID=" + pFID + "&IID=" + pIID,WindowName,'toolbar=no,location=no,status=no,statusbar=no,menubar=no,height=678,width=900,scrollbars=no,resizable=no,top=' + mTop + ',left=' + mLeft);
       }
      else
      {
            winPop = window.open(langPrefix+"/FrameStudio/default.asp?CID=" + pCID + "&apnum=" + pAPNum + "&FID=" + pFID + "&IID=" + pIID,WindowName,'toolbar=no,location=no,status=no,statusbar=no,menubar=no,height=678,width=900,scrollbars=no,resizable=no,top=' + mTop + ',left=' + mLeft);
      }
      if (winPop){
         if (winPop.focus){
            winPop.focus()
         }//end if
      }else{
         window.location.href = langPrefix+"/FrameStudio/error.asp?error=popup&" + pParameters + "&ui=" + qs_sessionid;
      }
   //}else{
      //top.document.location.href = "/Frame.asp?CID=" + pCID + "&APNum=" + pAPNum + "&FID=" + pFID + "&IID=" + pIID;
   //}
}


function compareDates(pOne,pTwo){
   var retval = false;
   pOne = new Date(pOne); pTwo = new Date(pTwo);
   var oneMonth,oneDay,oneYear; var twoMonth,twoDay,twoYear;
   oneMonth = pOne.getMonth(); oneDay = pOne.getDate(); oneYear = pOne.getFullYear();
   twoMonth = pTwo.getMonth(); twoDay = pTwo.getDate(); twoYear = pTwo.getFullYear();
   if (oneYear == twoYear){
      if (oneMonth == twoMonth){
         if (oneDay == twoDay){
            retval = true;
         }
      }
   }
   return retval;
}
function compareTimes(pOne,pTwo){
   var retval = false;
   pOne = new Date(pOne); pTwo = new Date(pTwo);
   var oneMonth,oneDay,oneMinute,oneYear;
   var twoMonth,twoDay,twoMinute,twoYear;
   oneMonth = pOne.getMonth(); oneDay = pOne.getDate(); oneYear = pOne.getFullYear(); oneMinute = pOne.getMinutes();
   twoMonth = pTwo.getMonth(); twoDay = pTwo.getDate(); twoYear = pTwo.getFullYear(); twoMinute = pTwo.getMinutes();
   if (oneYear == twoYear){
      if (oneMonth == twoMonth){
         if (oneDay == twoDay){
           if(oneMinute == twoMinute)
             retval = true;
         }
      }
   }
   return retval;
}


function setScreenResolutionCookie()
{
	//this function writes the screen resolution to cookie apc, key BrAttr for tealeaf
	//and replaces the ajax call made to brattr_callback.asp
	if (document.cookie){
		var apc = GetCookie('apc');
		if (apc){
			var browserHeight = window.screen.height;
			var browserWidth = window.screen.width;
			var newBrAttrString = browserWidth + 'x' + browserHeight;
			var currentBrAttrString = GetCookieDictionary('apc','BrAttr');
			if (currentBrAttrString == '' || currentBrAttrString == 'yes'){
				//apc = apc.replace(/BrAttr=yes/, newBrAttrString);
				//writeCookie('apc', apc);
				var sHostname = location.hostname;
				var startAt = sHostname.indexOf('.allposters.');
				sHostname = sHostname.substring(startAt);
				SetCookieDictionary('apc','BrAttr',newBrAttrString,'','/',sHostname,'');
			}
		}
	}
}
//setScreenResolutionCookie();


//SECTION - OBJECTS - Functions that act on HTML OBJECTS ------------------------------------------------------------------------
function getWidthHeight(pObj){
	var width = height = 0;
   width = getWidth(pObj, true, true);
   height = getHeight(pObj, true, true);
	return [width,height];
}

function objResize(pObj,pDimension){
   if (pObj.style){
      var BorderWidth = parseInt(pObj.style.borderWidth);
      if (navigator.appName.indexOf("Microsoft")==-1) {
         pObj.style.width = pDimension[0] - (2*BorderWidth);
      }else{
         pObj.style.width = pDimension[0];
      }
      pObj.style.height = pDimension[1] - (2*BorderWidth);
   }
}

function objMove(pObj,pX,pY){
   if (pObj.style){
      pObj.style.top = pY;
      pObj.style.left = pX;
   }
}

function findPos(pObj) {
	var curleft = curtop = 0;
   curleft = findPosX(pObj);
   curtop = findPosY(pObj);
	return [curleft,curtop];
}

function findPosX(obj)
{
   var curleft = 0;
   if(obj.offsetParent)
      while(1) 
      {
         curleft += obj.offsetLeft;
         if(!obj.offsetParent)
         break;
         obj = obj.offsetParent;
      }
   else if(obj.x)
      curleft += obj.x;
   return curleft;
}

function findPosY(obj)
{
   var curtop = 0;
   if(obj.offsetParent)
      while(1)
      {
         curtop += obj.offsetTop;
         if(!obj.offsetParent)
            break;
         obj = obj.offsetParent;
      }
   else if(obj.y)
      curtop += obj.y;
   return curtop;
}

function getWidth(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
   var width;
   el = (typeof(el) == "string") ? document.getElementById(el) : el;	
   
   if(window.getComputedStyle) { // FF, Safari, Opera
      var style = document.defaultView.getComputedStyle(el, null);
      if(style.getPropertyValue("display") == "none")
         return 0;
      width = parseInt(style.getPropertyValue("width"));
      
      if(/opera/i.test(navigator.userAgent)) {
         // opera includes the padding and border when reporting the width/height - subtract that out
         width -= parseInt(style.getPropertyValue("padding-left"));
         width -= parseInt(style.getPropertyValue("padding-right"));
         width -= parseInt(style.getPropertyValue("border-left-width"));
         width -= parseInt(style.getPropertyValue("border-right-width"));
      }
      
      if(includePadding) {
         width += parseInt(style.getPropertyValue("padding-left"));
         width += parseInt(style.getPropertyValue("padding-right"));
      }
      
      if(includeBorder) {
         width += parseInt(style.getPropertyValue("border-left-width"));
         width += parseInt(style.getPropertyValue("border-right-width"));
      }
   } else { // IE
      if(el.currentStyle["display"] == "none")
         return 0;
      var bRegex = /thin|medium|thick/; // regex for css border width keywords
      width = el.offsetWidth; // currently the width including padding + border
      
      if(!includeBorder) {
         var borderLeftCSS = el.currentStyle["borderLeftWidth"];
         var borderRightCSS = el.currentStyle["borderRightWidth"];
         var temp = document.createElement("DIV");
         if(el.offsetWidth > el.clientWidth && el.currentStyle["borderLeftStyle"] != "none") {
            if(!bRegex.test(borderLeftCSS)) {
               temp.style.width = borderLeftCSS;
               el.parentNode.appendChild(temp);
               width -= Math.round(temp.offsetWidth);
               el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderLeftCSS)) {
               temp.style.width = "10px";
               temp.style.border = borderLeftCSS + " " + el.currentStyle["borderLeftStyle"] + " #000000";
               el.parentNode.appendChild(temp);
               width -= Math.round((temp.offsetWidth-10)/2);
               el.parentNode.removeChild(temp);
            }
         }
         if(el.offsetWidth > el.clientWidth && el.currentStyle["borderRightStyle"] != "none") {
            if(!bRegex.test(borderRightCSS)) {
               temp.style.width = borderRightCSS;
               el.parentNode.appendChild(temp);
               width -= Math.round(temp.offsetWidth);
               el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderRightCSS)) {
               temp.style.width = "10px";
               temp.style.border = borderRightCSS + " " + el.currentStyle["borderRightStyle"] + " #000000";
               el.parentNode.appendChild(temp);
               width -= Math.round((temp.offsetWidth-10)/2);
               el.parentNode.removeChild(temp);
            }
         }
      }
      
      if(!includePadding) {
         var paddingLeftCSS = el.currentStyle["paddingLeft"];
         var paddingRightCSS = el.currentStyle["paddingRight"];
         var temp = document.createElement("DIV");
         temp.style.width = paddingLeftCSS;
         el.parentNode.appendChild(temp);
         width -= Math.round(temp.offsetWidth);
         temp.style.width = paddingRightCSS;
         width -= Math.round(temp.offsetWidth);
         el.parentNode.removeChild(temp);
      }
   }
   
   return width;
}

function getHeight(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
    var height;
    el = (typeof(el) == "string") ? document.getElementById(el) : el;
    
    if(window.getComputedStyle) { // FF, Safari, Opera
        var style = document.defaultView.getComputedStyle(el, null);
        if(style.getPropertyValue("display") == "none")
            return 0;
        height = parseInt(style.getPropertyValue("height"));
        
        if(/opera/i.test(navigator.userAgent)) {
            // opera includes the padding and border when reporting the width/height - subtract that out
            height -= parseInt(style.getPropertyValue("padding-top"));
            height -= parseInt(style.getPropertyValue("padding-bottom"));
            height -= parseInt(style.getPropertyValue("border-top-width"));
            height -= parseInt(style.getPropertyValue("border-bottom-width"));
        }
        
        if(includePadding) {
            height += parseInt(style.getPropertyValue("padding-top"));
            height += parseInt(style.getPropertyValue("padding-bottom"));
        }
        
        if(includeBorder) {
            height += parseInt(style.getPropertyValue("border-top-width"));
            height += parseInt(style.getPropertyValue("border-bottom-width"));
        }
    } else { // IE
        if(el.currentStyle["display"] == "none")
            return 0;
        var bRegex = /thin|medium|thick/; // regex for css border width keywords
        height = el.offsetHeight; // currently the height including padding + border
    
        if(!includeBorder) {
            var borderTopCSS = el.currentStyle["borderTopWidth"];
            var borderBottomCSS = el.currentStyle["borderBottomWidth"];
            var temp = document.createElement("DIV");
            if(el.offsetHeight > el.clientHeight && el.currentStyle["borderTopStyle"] != "none") {
                if(!bRegex.test(borderTopCSS)) {
                    temp.style.width = borderTopCSS;
                    el.parentNode.appendChild(temp);
                    height -= Math.round(temp.offsetWidth);
                    el.parentNode.removeChild(temp);
                } else if(bRegex.test(borderTopCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderTopCSS + " " + el.currentStyle["borderTopStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
            if(el.offsetHeight > el.clientHeight && el.currentStyle["borderBottomStyle"] != "none") {
                if(!bRegex.test(borderBottomCSS)) {
                    temp.style.width = borderBottomCSS;
                    el.parentNode.appendChild(temp);
                    height -= Math.round(temp.offsetWidth);
                    el.parentNode.removeChild(temp);
                } else if(bRegex.test(borderBottomCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderBottomCSS + " " + el.currentStyle["borderBottomStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
        }
    
        if(!includePadding) {
            var paddingTopCSS = el.currentStyle["paddingTop"];
            var paddingBottomCSS = el.currentStyle["paddingBottom"];
            var temp = document.createElement("DIV");
            temp.style.width = paddingTopCSS;
            el.parentNode.appendChild(temp);
            height -= Math.round(temp.offsetWidth);
            temp.style.width = paddingBottomCSS;
            height -= Math.round(temp.offsetWidth);
            el.parentNode.removeChild(temp);
        }
    }
    
    return height;
}
//SECTION - OBJECTS : END --- Functions that act on HTML OBJECTS ------------------------------------------------------------------------

//SECTION - UTILITY : BEGIN - Functions that offer utility to the program but are absctracted from specific objects ---------------------
function Wait(millis) 
{
   var date = new Date();
   var curDate = null;
   do { curDate = new Date(); } 
   while(curDate-date < millis);
} 
//SECTION - UTILITY : END --- Functions that offer utility to the program but are absctracted from specific objects ---------------------

//SECTION - EVENTS : BEGIN - Functions that provide event handling to objects or add events ---------------------------------------------
function addEvent(pEvent,pFunction){
    if( window.addEventListener) 
   {
     window.addEventListener(pEvent,pFunction,false);
   } 
   else if( document.addEventListener ) 
   {
     document.addEventListener(pEvent,pFunction,false);  
   } 
   else if( window.attachEvent ) 
   { //For IE
     window.attachEvent('on' + pEvent,pFunction); 
   } 
}
function addEventToObject(pObject,pEvent,pFunction){
    if( eval(pObject).addEventListener) 
   {
     eval(pObject).addEventListener(pEvent,pFunction,false);
   } 
   else if( eval(pObject).attachEvent ) 
   { //For IE
     eval(pObject).attachEvent('on' + pEvent,pFunction); 
   } 
}
//SECTION - EVENTS : END --- Functions that provide event handling to objects or add events ---------------------------------------------

//Added for buying funnel.
function launchInlineFrameStudio(pCID,pAPNum,pFID,pIID,Referrer)
{
   if (pAPNum.indexOf("apnum") > 0)
    {
        if (pAPNum.substring(pAPNum.length-1) == "&")
        {
             pAPNum = pAPNum.substring(0,pAPNum.length-1);
        }
            top.document.location.href = "/framestep?CID=" + pCID + pAPNum + "&FID=" + pFID + "&IID=" + pIID + "&Referrer=" + Referrer;    
    }
    else
    {
			top.document.location.href = "/framestep?CID=" + pCID + "&apnum=" + pAPNum + "&FID=" + pFID + "&IID=" + pIID + "&Referrer=" + Referrer;
	}
}

function makeAjaxCallToAddToCart(action){
	 var baseURL = "/addToCart.asp?";
	 var baseURLParams = buildAddToCartParams(action);
	 var urlToSend = baseURL + baseURLParams;
	 var destinationURL = '/frameStep/?'+baseURLParams;
	 var cartItemId = "";
	 $.ajax({
        url: urlToSend,
        processData: false,
        cache: false,
        type: "GET",
		dataType: "text",
        success: function(callback) {
        	if ((callback.indexOf('added#') > -1)){
				theStatusSplit = callback.split('#');
				theCartCount = theStatusSplit[1];
				cartItemId   = theStatusSplit[2];
				cartImageFileName = theStatusSplit[3];
				destinationURL += '&cartCount='+theCartCount;
				
				//if the iid is already present in the url , then replace with this value, else append the IID.
				if(destinationURL.toLowerCase().indexOf('iid=') > -1)
				{
					destinationURL = ReplaceKeyValue(destinationURL,'iid',cartItemId);
				}
				else
				{
					destinationURL += '&IID='+cartItemId;
				}
				destinationURL = destinationURL + '&action=AddItem&imagePath=' + cartImageFileName;
				location.href = destinationURL;
			}
			else{
				//alert('error: ajax response OK, but no added text found.');
				//linkForm(action);*/
			}
		},
        error: function(textStatus, errorThrown) {
           //linkForm(action);
		   //alert('error in ajax response');
		}
    });
}

function buildAddToCartParams(action){
	var params = '';
	var apnum = extractValueFromKey(action, 'apnum');
	params = 'CID='+extractValueFromKey(action, 'cid')+'&apnum=' + apnum;
	var iid = extractValueFromKey(action,'iid');
	params = params + '&IID=' + iid;
	var PODConfigID = extractValueFromKey(action,'podconfigid');
	if (PODConfigID != '')
		params = params + '&PODConfigID='+PODConfigID;
	return params;
}

function extractValueFromKey(theURL, theKey)
{
	var loc1;
	var loc2;
	var theValue = "";
	var theURLCopy = theURL.toLowerCase();
	theKeyString = theKey + '=';
	loc1 = theURLCopy.indexOf(theKeyString);
	if(loc1 > -1)
	{
		loc2 = theURL.indexOf('&',loc1);
		//if loc2 is -1, then indicates it is the last parameter in the url and there is no & after that.
		if(loc2 < 0)
		{
			loc2 = theURL.length;
		}
		theValue = theURL.substring(loc1,loc2);
		theValue = theValue.substring(theKey.length+1,theValue.length);
	}	
	return theValue;		
}

function ReplaceKeyValue(url,theKey,value)
{
	var loc1;
	var loc2;
	var str = "";
	loc1 = url.toLowerCase().indexOf(theKey);
	
	if(loc1 > -1)
	{
		loc2 = url.indexOf('&',loc1);
		if(loc2 > -1) 
		{
			str = replaceValueInString(url,theKey + "=" + url.substring(loc1 + theKey.length + 1,loc2),theKey + "=" + value);
		}
		else
		{
			str = replaceValueInString(url,theKey + "=" + url.substring(loc1,url.length),theKey + "=" + value);
		}
	}
	return str;
}

function replaceValueInString(str, strToBeReplaced, newStr) {
        var reg, result

        if (str != null) {
            reg = new RegExp(strToBeReplaced, "gi");
            result = str.replace(reg, newStr);
        }
        return result;
}


function trackGAEvent(eventName, pageName) {
    try {
        console.info('Google tracking : Event = ' + eventName + ' : Page = ' + pageName);
    }
    catch (e) {
    }
    if (typeof (_gaq) != "undefined") {
        var tmpEventName = "\'" + eventName + "\'";
        var tmpPageName = "\'" + pageName + "\'";
        _gaq.push(['t1._trackEvent', tmpPageName, tmpEventName, tmpEventName]);
    }
}   
function LogGAMessage(msg) {
    try {
        console.info(msg);
    }
    catch (e) {
    }
}
function trackGAWithCategory(category, eventLabel, eventPage) {
    var msg = 'GA: Category: [' + category + '] Page Name: [' + eventPage + '] Event Action: [' + eventLabel + ']';
    if (typeof (_gaq) != "undefined") {
        LogGAMessage(msg);        
        _gaq.push(['t1._trackEvent', category, eventPage, eventLabel]);
    }
}

var CurrentSessionData;
function LogIt(msg) {
    try {
        console.log(msg);
    }
    catch (e) {
    }
}

function isATGObjectEmpty(obj) {
    for (var i in obj) { if (obj.hasOwnProperty(i)) { return false; } }
    return true;
}

function isATGRecoExist() {
    //alert("In - isATGRecoExist");
    var initArray = ['pdp', 'cart', 'upsell']; // add more id's if need be
    var bret = false; // ensure this is false
    // break as soon as any one of the initArray elements are present
    //--CONDENAST-- To Avoid the script object error in condenast added try catch.
    try {
        for (var i = 0; i < initArray.length; i++) {
            if (!isATGObjectEmpty(ATGSvcs.REC_DATA[initArray[i]])) {
                bret = true;
                break;
            }
        }
    }
    catch (e) {
    }
    //--CONDENAST--
    LogIt("isATGRecoExist=" + bret);
    return bret;
}
//Function is called to display Recommendations only when there is data in Recommendation Engine/also it aligns the images vertically by calculating height and width dynamically.
function atgRecInitial() {
    //alert("In - atgRecInitial");
    handleRecoRenderer();
    if (isATGRecoExist()) {
        setCurrentSessionData();
        setATGTracking();
        getDynData();
    }
}
function setATGTrackCookie(pageId, eventId, apNum) {
    setTrackCookie(pageId, eventId, apNum, "ATGTrack");
}
function getATGGAPageId() {
    var gaPage = $("#recoRend").find(".ga_page").text();
    if (gaPage == "Up-sell Page") {
        return "U";
    }
    else if (gaPage == "Cart Page") {
        return "C";
    }
    return "";
}
function getAPNum($this) {
    var regexOnlyDigits = /\d+/g;
    thisAPNum = $this.parents('.cs-rec').attr('id');
    return thisAPNum.match(regexOnlyDigits);
}
function setATGTracking() {
    var gaPage = $("#recoRend").find(".ga_page").text();
    var pageId = getATGGAPageId();
    
    if (gaPage != undefined && gaPage != '') {
        trackGAWithCategory("Recommendations", "ATG module - loaded", gaPage);           
       
    $('#recoRend .scroll-button-left').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG left arrow - clicked", gaPage);         
    });    

    $('#recoRend .scroll-button-right').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG right arrow - clicked", gaPage); 
    });

    $('.cs-rec a img[class=cs-image]').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG product image - clicked", gaPage);
    setATGTrackCookie(pageId, "I", getAPNum($(this)));
    });

    $('.cs-rec a .cs-title').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG product link - clicked", gaPage);
    setATGTrackCookie(pageId, "L", getAPNum($(this)));
    });
    
    $('.cs-rec a .cs-dynPrice').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG price link - clicked", gaPage);
    });

    $('.cs-rec span[class=dynCartButton]').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG add to cart single - clicked", gaPage);
    setATGTrackCookie(pageId, "A", getAPNum($(this)));
    });

    $('.cs-rec a[class=dynCartButton]').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG add to cart single - clicked", gaPage);
    setATGTrackCookie(pageId, "A", getAPNum($(this)));
    });

    $('.cs-rec span[class=dynCartPopButton]').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG add to cart multi - clicked", gaPage);
    });

    $('#addToCartDetailsTable input[name=radItem]').live('click', function() {
    trackGAWithCategory("Recommendations", "ATG options in modal - clicked", gaPage);
    });

    $('.addToCartUIDialog .addToCartButton').live('click', function() {
        trackGAWithCategory("Recommendations", "ATG add to cart modal - clicked", gaPage);
    });

    $('#REqVImage').live('click', function() {
        setATGTrackCookie(pageId, "I", $('#REApNum').text());
    });

    $('#REqVText a').live('click', function() {
        setATGTrackCookie(pageId, "L", $('#REApNum').text());
    });  
}
}
function setCurrentSessionData() {
    CurrentSessionData = new Object();
    CurrentSessionData.CurrentCurrencyCode = GetCookieDictionary('apc', 'CurrentCurrencyCode');
    CurrentSessionData.CustomerZoneID = GetCookieDictionary('apc', 'CustomerZoneID');
    CurrentSessionData.LanguageId = $('#gTxt_LanguageId').text()
    CurrentSessionData.SearchServiceUrl = $('#gTxt_SearchServiceURL').text();
    //alert("Lang:" + CurrentSessionData.LanguageId + "zone:" + CurrentSessionData.CustomerZoneID + "Cur:" + CurrentSessionData.CurrentCurrencyCode + "Url:" + CurrentSessionData.SearchServiceUrl);
}
function getDynData() {
    //get productID from all items, store in an array
    //pass array to a service
    //get back array of apnums,  prices, add to cart params, etc
    //inject data into module    
    //alert("In - getDynData");
    var productIDs = "";
    $('.cs-rec').each(function(i) {
        var regexOnlyDigits = /\d+/g;
        thisProductID = $(this).attr('id');
        thisProductID = thisProductID.match(regexOnlyDigits);
        if (productIDs != "") {
            productIDs = productIDs + ","
        }
        productIDs = productIDs + thisProductID;
    });
    //alert(productIDs);
    //send productIDs to a service
    serviceCallUrl = CurrentSessionData.SearchServiceUrl;
    serviceCallUrl = serviceCallUrl + "/ajax/GetSearchResultInSimpleFormat?method=?&Refinements=&Search=&RecordsPerPage=10&PageNumber=1&CustomerZoneId=" + CurrentSessionData.CustomerZoneID + "&SortBy=&ArtistCategoryId=0&APNumList=" + productIDs + "&ImageIdList=&CurrencyCode=" + CurrentSessionData.CurrentCurrencyCode + "&LanguageId=" + CurrentSessionData.LanguageId +"&FilterSpecialItems=false";
    //alert(serviceCallUrl);
    $.ajax({
        url: serviceCallUrl,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function() {
        },
        success: function(callbackResults) {
            //get data from service (price, intl title, add to cart params, etc)
            //inject data back into module, we cannot do one-one mapping for products returned since same product with multi size ging one ImageDetail, and order is different.
            $('.cs-rec').each(function(i) {
                var regexOnlyDigits = /\d+/g;
                thisAPNum = $(this).attr('id');
                thisAPNum = thisAPNum.match(regexOnlyDigits);
                thisProduct = getProductForApNum(callbackResults.ImageDetails, thisAPNum);
                if (thisProduct != null) {
                    var hasMutipleSizes = false;
                    if (thisProduct.NumberOfSizes > 1) {
                        hasMutipleSizes = true;
                    }
                    thisPrice = thisProduct.ItemPrice.DisplayPrice;
                    thisButtonbuttonUrl = getCartUrl(thisProduct.UrlInfo.AddToCartURL);
                    thisImageId = thisProduct.ImageId;
                    title = (thisProduct.Title.length > 28) ? thisProduct.Title.substring(0, 25) + '...' : thisProduct.Title;
                    $(this).find('.cs-title').text(title);
                    $(this).find('.cs-title').attr('title', thisProduct.Title);
                    $(this).find('.cs-dynPrice').text(thisPrice);
                    $(this).find('.cs-dynPrice').css("display", "block");
                    $(this).find('a').after(getCartButton(hasMutipleSizes, thisButtonbuttonUrl, thisImageId, thisAPNum));
                    $(this).find('a:first').attr("href", thisProduct.UrlInfo.ProductPageUrl);                     
                    //$(this).find('a:first').attr("href", $(this).find('a:first').attr("href").replace("www", "qa3-www")); //TODO:Need to be removed once we are live.
                    //$(this).find('img.cs-image').attr("src", $(this).find('img.cs-image').attr("src").replace("lrg", "med"));
                }
            });

        },
        error: function(textStatus, errorThrown) {
            //alert(errorThrown);
        }
    });


}
function getProductForApNum(products, apNum) {
    retval = null;
    jQuery.each(products, function() {
        foundInApnumVariation = false;
        if (this.APNum == apNum) {
            retval = this;
        }
        else {
            if (this.ApnumVariations != null) {
                jQuery.each(this.ApnumVariations, function() {
                    if (this.toString() == apNum.toString()) {
                        foundInApnumVariation = true;
                    }
                });
            }
        }
        if (foundInApnumVariation == true) {
            retval = this;
        }
    });
    return retval;
}
function getCartButton(showPopup, url, imageId, productID) {
    var strCartImage = "";
    strCartImage = $('#gTxt_ImgUrlAddToCart').text();
    strCartImage = "<img src=\"" + strCartImage + " class='dynCartImage'>";
    addCartFunc = "";
    addCartClass = "dynCartButton";
    if (showPopup == '1') {
        addCartFunc = 'showCartModalDailog(' + imageId + ', this , ' + productID + ');';
        addCartClass = "dynCartPopButton";
    }
    else {

        if (wtEnabledGCF == 'true') {
            addCartFunc = 'makeAjaxCallToAddATGItemToCart(\'' + url + '\');dcsMultiTrack(\'WT.ti\',\'Add-To-Cart\',\'DCS.dcsuri\', \'/root/pages/cart/add.aspx\',\'WT.pn_sku\',\'' + productID + '\',\'WT.tx_u\',\'1\', \'WT.tx_e\', \'a\',\'WT.cg_n\', \'Add-To-Cart\',\'WT.tx_e\', \'a\',\'WT.si_n\', \'Shopping\',\'WT.si_x\', \'3\',\'WT.z_cur\', \'' + CurrentSessionData.CurrentCurrencyCode + '\',\'WT.dl\', \'10\');';
        }
        else {
            addCartFunc = 'makeAjaxCallToAddATGItemToCart(\'' + url + '\');';
        }
        var isUpsellRedirect = $('#recoRend').find(".IsUpsellRedirect").text();
        if (isUpsellRedirect != undefined && isUpsellRedirect != '') {
            if (isUpsellRedirect == '1') {
                return '<a onclick="' + addCartFunc + '" href ="' + url + '" class="dynCartButton">' + strCartImage + '</a>';
            }
        }
    }
    return '<span class="' + addCartClass + '" onclick="' + addCartFunc + '">' + strCartImage + '</span>';
}

function getItemSize(dimension) {
    return Math.round(dimension.Width) + '" X ' + Math.round(dimension.Height) + '"';
}
function getCartUrl(url) {
    //we can add any other parms of url here
    return url + "&CID=" + GetCookie("CID");
}
function addToCartItemSelected(obj) {
    var url = $(obj).next("div").html();
    var canFrame = $(obj).next("div").next("span").text();    
    if (canFrame != "true") {
        $("#addToCartFrameText").show();
    }
    else {
        $("#addToCartFrameText").hide();
    }
    if (url != "") {
        $("#addToCartDetailsTable").find("tr").removeClass("addToCartDetailsSelected");
        $(obj).parents("tr").addClass("addToCartDetailsSelected");
        $("#hdnCartURL").html(url);
    }
}
function navigateToAddToCart() {
    var isUpsellRedirect = $('#recoRend').find(".IsUpsellRedirect").text();
    var pageId = getATGGAPageId();
    setATGTrackCookie(pageId, "A", $('#addToCartDetailsTable input:radio[name=radItem]:checked').val());
    if (isUpsellRedirect != undefined && isUpsellRedirect == '1') {
        location.href = $("#hdnCartURL").text();
    }
    else {
        makeAjaxCallToAddATGItemToCart("'" + $("#hdnCartURL").text() + "'");
    }
}

function populateCartDailogData(imageId, productID) {
    var wtAPNUM;
    $("#addToCartDetails").html("Loading...");
    serviceCallUrl = CurrentSessionData.SearchServiceUrl;  
    serviceCallUrl = serviceCallUrl + "/ajax/GetProductsForMultipleSizes?method=?&ImageId=" + imageId + "&CustomerZoneId=" + CurrentSessionData.CustomerZoneID + "&LanguageId=" + CurrentSessionData.LanguageId + "&CurrencyCode=" + CurrentSessionData.CurrentCurrencyCode
    //alert(serviceCallUrl);
    $.ajax({
        url: serviceCallUrl,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function() {
        },
        success: function(callbackResults) {
            defaultCartUrl = "";
            strPrice = $('#gTxt_Price').text();
            strSize = $('#gTxt_Size').text();
            strUsusallyShipsIn = $('#gTxt_UsusallyShipsIn').text();
            strType = $('#gTxt_Type').text();
            strAddToCart = $('#gTxt_AddToCart').text();

            htmlData = "<table width='575px' id='addToCartDetailsTable'>";
            htmlData = htmlData + "<tr class='addToCartDetailsBold'><td width='25px;'></td> <td width='75px;'>" + strSize + "</td> <td width='205px;'>" + strType + "</td> <td width='120px'>" + strUsusallyShipsIn + "</td> <td width='75px;'>" + strPrice + "</td></tr>";
            var isItemSelected = false;
            jQuery.each(callbackResults.ImageDetails, function() {
                var selectedRadio = "";
                var selectedClass = "";
                if (productID == this.APNum && isItemSelected != true) {
                    isItemSelected = true;
                    selectedRadio = "checked"; selectedClass = " class='addToCartDetailsSelected'"
                    defaultCartUrl = getCartUrl(this.UrlInfo.AddToCartURL);
                    if (this.ServiceFlags.CanFrame != true) {
                        $("#addToCartFrameText").show();
                    }
                }
                var itemSize = "";
                if (this.tShirtSize != null) {
                    itemSize = this.tShirtSize;
                }
                else {
                    itemSize = getItemSize(this.PhysicalDimensions);
                }
                wtAPNUM = this.APNum;
                htmlData = htmlData + "<tr" + selectedClass + "><td><input type='radio' id='radItem" + this.APNum + "' name='radItem' value='" + this.APNum + "' onclick='addToCartItemSelected(this);'" + selectedRadio + " /><div class='hidden'>" + getCartUrl(this.UrlInfo.AddToCartURL) + "</div><span class='hidden'>" + this.ServiceFlags.CanFrame + "</span></td> <td>" + itemSize + "</td> <td>" + this.ItemDisplayedType + "</td> <td>" + this.FulfillmentInformation.TimeToShip.DisplayText + "</td> <td>" + this.ItemPrice.DisplayPrice + "</td></tr>";
            });
            htmlData = htmlData + "<tr><td colspan='5'></td></tr>"
            //htmlData = htmlData + "<tr><td colspan='5' align='center'><div class='addToCartButton' onclick='navigateToAddToCart();'>" + strAddToCart + "<div id='hdnCartURL' class='hidden'>" + defaultCartUrl + "</div></div></td></tr>"
            htmlData = htmlData + "</table>"
            $("#addToCartDetails").html(htmlData);
            $(".ui-dialog .addToCartUIDialog").remove();

            if (wtEnabledGCF == 'true') {
                $(".ui-dialog").append("<div class='addToCartUIDialog' style='padding:10px 0px 10px 0px; background-color:white;'><div class='addToCartButton' onclick='navigateToAddToCart();dcsMultiTrack(\"WT.ti\",\"Add-To-Cart\",\"DCS.dcsuri\", \"/root/pages/cart/add.aspx\",\"WT.pn_sku\",\"" + wtAPNUM + "\",\"WT.tx_u\",\"1\", \"WT.tx_e\", \"a\",\"WT.cg_n\", \"Add-To-Cart\",\"WT.tx_e\", \"a\",\"WT.si_n\", \"Shopping\",\"WT.si_x\", \"3\",\"WT.z_cur\", \"" + CurrentSessionData.CurrentCurrencyCode + "\",\"WT.dl\", \"10\");'>" + strAddToCart + "<div id='hdnCartURL' class='hidden'>" + defaultCartUrl + "</div></div></div>");
            }
            else {
                $(".ui-dialog").append("<div class='addToCartUIDialog' style='padding:10px 0px 10px 0px; background-color:white;'><div class='addToCartButton' onclick='navigateToAddToCart();'>" + strAddToCart + "<div id='hdnCartURL' class='hidden'>" + defaultCartUrl + "</div></div></div>");
            }
            adjustPopupLocation();
        },
        error: function(textStatus, errorThrown) {
            //alert(errorThrown);
        }
    });
}
function adjustPopupLocation() {
    //adjust modal position if the entire container is not completely in the window
    screenHeight = document.body.clientHeight;
    screenWidth = document.body.clientWidth;
    theItemTop = parseInt($('.ui-dialog').css('top'));
    theScrollTop = parseInt(document.body.scrollTop);

    if ((theItemTop - theScrollTop + $('.ui-dialog').height()) > (screenHeight)) {
        //bump up
        theItemTop = theScrollTop - (($('.ui-dialog').height()) - screenHeight) - 5;
    }
    else if (theItemTop < theScrollTop) {
        //push down
        theItemTop = theScrollTop + 5;
    }
    if (theItemTop < 0) {
        //push down
        theItemTop = 40;
    }
    if ($.browser.msie)
        $('#addToCartModalDailog').height(($('#addToCartModalDailog').innerHeight() > 400) ? "400px" : "auto");
    $('.ui-dialog').css('top', theItemTop);

}
function showCartModalDailog(imageId, element, productID) {
    populateCartDailogData(imageId, productID);
    var x = $(element).offset().left;
    var y = $(element).offset().top;
    y = y - 220;
    x = x - 205;
    if ($(window).scrollTop() && $(window).scrollTop() > 0) {
        y -= $(window).scrollTop();
    }
    if ($(window).scrollLeft() && $(window).scrollLeft() > 0) {
        x -= $(window).scrollLeft();
    }
    $('#addToCartModalDailog').dialog({ modal: true, autoOpen: false, width: 605, closeOnEscape: false, closeText: "" });
    $('#addToCartModalDailog').dialog("option", "position", "center");
    $("#addToCartModalDailog").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").removeClass('ui-dialog-titlebar').addClass("dialog-titlebar");
    $("#addToCartModalDailog").dialog().parents(".ui-dialog").find(".ui-icon").removeClass('ui-icon').addClass("close-icon");
    $('#addToCartModalDailog').dialog('open');
    $('.ui-widget-overlay').removeClass("ui-widget-overlay").addClass("dailog_ui-widget-overlay");
    //$('#addToCartModalDailog').css('width', '576px');

}

function makeAjaxCallToGetResults(url) {
    $.ajax({
        url: url,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function() {
        },
        success: function(callbackResults) {
            return callbackResults;
        },
        error: function(textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}
function makeAjaxCallToAddATGItemToCart(action) {
	 var baseURL = "/addToCart.asp?";
	 var baseURLParams = buildAddToCartParams(action);
	 var urlToSend = baseURL + baseURLParams;
	 //alert("urlToSend:" + urlToSend);
	 //Redirect to Cart page once the item is added to cart.
	 var destinationURL = '/gallery.asp?CID=' + GetCookie("CID") + '&startat=/viewcart.asp';
	 var cartItemId = "";
	 $.ajax({
        url: urlToSend,
        processData: false,
        cache: false,
        type: "GET",
		dataType: "text",
        success: function(callback) {
        	if ((callback.indexOf('added#') > -1)){				
				location.href = destinationURL;
			}
			else{
				//alert('error: ajax response OK, but no added text found.');
			}
		},
        error: function(textStatus, errorThrown) {
		   //alert('error in ajax response');
		}
    });
}
function handleRecoRenderer() {
    //this function shows the module and module title only if items are present
    //and also center-aligns each product image
    $('#recoRend').hide();
    if (isATGRecoExist()) {
        $('#recoRend').show();
        $('.cs-rec').each(function(i) {
        var $thisImg = $(this).find('.cs-image');
            //on image load calling function to set the margin.
            $thisImg.one("load", function() {
                setMargin($(this));
            }).each(function() {
            if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
                $(this).trigger("load");
            }); 
        });
    }
}

function setMargin($thisImg) {
    var imageMaxHeight = 160;
    var defaultMargin = 12;
    var defaultBottomMargin = 20;
    
    var imageWidth = $thisImg.width();
    var imageHeight = $thisImg.height();
    var ar = imageWidth / imageHeight;
    var mt = defaultMargin;
    if (ar > 1.0) {
        mt = (imageWidth - imageHeight) / 2;
    }
    $thisImg.css('margin-top', mt);
    var bottomMargin = ((imageMaxHeight - imageHeight) / 2);
    if (bottomMargin > 0) {
        topMargin = bottomMargin + defaultMargin;
        bottomMargin = bottomMargin + defaultBottomMargin;
        $thisImg.css('margin-top', topMargin);
        $thisImg.css('margin-bottom', bottomMargin);
    }
    $thisImg.hoverIntent({
        over: hoverCarouselImage,
        timeout: 500,
        interval: 300
    });
}

function qVAtgCarousel($theItem) {
    //calculate size of new image
    $theImage = $theItem.find('img.cs-image');
    medImageWidth = $theImage.width();
    medImageHeight = $theImage.height();
    var maxImgWidth = 350;
    var maxImgHeight = 390;
    var theImageRatio;
    var regexOnlyDigits = /\d+/g;

    if (medImageWidth >= medImageHeight) {
        theImageRatio = medImageHeight / medImageWidth;
        lrgImageWidth = maxImgWidth;
        lrgImageHeight = Math.round(lrgImageWidth * theImageRatio);
    }
    else {
        theImageRatio = medImageWidth / medImageHeight;
        lrgImageHeight = maxImgHeight;
        lrgImageWidth = Math.round(lrgImageHeight * theImageRatio);
    }

    //instantly load gallery medium-sized image, resized to the large image dimensions
    theItemImageSrc = $theImage.attr('src');
    $('#REqVImage').attr('src', theItemImageSrc);
    $('#REqVImage').attr('width', lrgImageWidth);
    $('#REqVImage').attr('height', lrgImageHeight);
    thisAPNum = $theItem.attr('id');
    thisAPNum = thisAPNum.match(regexOnlyDigits);
    $('#REApNum').text(thisAPNum.toString());
    //swap medium image with high-quality large image
    newItemImageSrc = theItemImageSrc.replace('med', 'lrg');
    $('#REqVImage').attr('src', newItemImageSrc);

    //get data elements

    //var bCanFrame = true;
    var theProductTitle = $theItem.find('.cs-name').attr('title');
    //var theProductType = $theItem.find('.jcarousel-itemCount').text() + ($theItem.find('.jcarousel-itemCount').text() == "1" ? " item" : " items");
    qVTextString = '<a href="">' + theProductTitle + '</a>';
    $('#REqVText').html(qVTextString);
    $('#REqvImageContainer a, #REqVText a').attr('href', $theItem.find('a').attr('href'));

    //position container module
    var offset = $theItem.offset();
    theItemTop = offset.top;
    theItemLeft = offset.left;

    qvWidth = lrgImageWidth + 42;
    if (qvWidth < 289)
        qvWidth = 289;
    $('#REquickViewContainer').width(qvWidth);

    //vertically center popup to gallery image
    largeImageTop = $theImage.offset().top - (lrgImageHeight - medImageHeight) / 2;

    theItemLeft = theItemLeft - ($('#REquickViewContainer').width() - $theItem.width()) / 2;
    theItemTop = largeImageTop - 21; //account for top padding and border of image

    //adjust quick view position if the entire container is not completely in the window
    qscreenHeight = document.body.clientHeight;
    qscreenWidth = document.body.clientWidth;
    theScrollTop = parseInt(document.body.scrollTop);

    if ((theItemTop - theScrollTop + $('#REquickViewContainer').height()) > (qscreenHeight)) {
        //bump up
        theItemTop = theScrollTop - (($('#REquickViewContainer').height()) - qscreenHeight);
    }
    else if (theItemTop < theScrollTop) {
        //push down
        theItemTop = theScrollTop;
    }

    if ((theItemLeft + $('#REquickViewContainer').width()) > (qscreenWidth)) {
        //bump left
        theItemLeft = qscreenWidth - $('#REquickViewContainer').width();
    }

    $('#REquickViewContainer').css('top', theItemTop);
    $('#REquickViewContainer').css('left', theItemLeft);

    //display container module
    t = setTimeout('showREQuickView()', 20);
    //showREQuickView();
}
function hoverCarouselImage() {
    $qvCatItem = $(this).parents('.cs-rec');
    qVAtgCarousel($qvCatItem);
    var gaPage = $('#recoRend').find(".ga_page").text();
    if (gaPage != undefined && gaPage != '') {
        trackGAWithCategory("Recommendations", "ATG product image - hover", gaPage);
    }
}
function showREQuickView() {
    $('#REquickViewContainer').fadeIn('fast');
    clearTimeout(t);
}
function hideREQuickView() {
    $('#REquickViewContainer').hide();
}
var blnScrollGAfired = false;
function captureScrollForGA(testBlock) {
    var gaPage = $('#recoRend').find(".ga_page").text();
    if (!blnScrollGAfired) {
        if (gaPage != undefined && gaPage != '') {
            trackGAWithCategory("Recommendations", "Testimonials -Scrolled", gaPage);
            blnScrollGAfired = true;
        }
    }
}

//Added for HDT - 72107 - GA tracking on APC DFE module
function SetDFEGATracking() {
    var dfePage = $(this).find("#ga_dfeload_page").text();
    var pageId = "P";

    $('.centerItem').live("click", function() {
        trackGAWithCategory("DFE", "DFE product image – clicked", dfePage);
    });
    
    $('#captionAddToCart').live("click", function() {
    trackGAWithCategory("DFE", "DFE add to cart – clicked", dfePage);
    if ($('#myImageFlow_images img').length == 15) {
        var imageClicked = $('.captionTop').text().replace("/", " of ");
        trackGAWithCategory("DFE", "DFE add to cart " + imageClicked + "-clicked", dfePage);
    }
    });
    
    $('.centerItem').live("mouseover", function() {
        trackGAWithCategory("DFE", "DFE product image – hover", dfePage);
    });
    
    $('#colorpickericon').live("click", function() {
    trackGAWithCategory("DFE", "DFE wall color - select", dfePage);
    });
    
    $('#wallcolor').live("click", function() {
    trackGAWithCategory("DFE", "DFE wall color - choose", dfePage);
    });
    
    $('#myImageFlow_images img').live("click", function() {
        var imageClicked = $('.captionTop').text().split("/");

        if (imageClicked[0] == 1) {
            trackGAWithCategory("DFE", "DFE carousel – click far left", dfePage);
        }
        else if (imageClicked[0] == $('#myImageFlow_images img').length) {
            trackGAWithCategory("DFE", "DFE carousel – click far right", dfePage);
        }
       //Events Middle left & Middle Right
        if (imageClicked[0] == (parseInt($('.captionTop').attr('pselected')) - 1)) {
            trackGAWithCategory("DFE", "DFE carousel – click middle left", dfePage);
        }
        else if (imageClicked[0] == (parseInt($('.captionTop').attr('pselected')) + 1)) {
            trackGAWithCategory("DFE", "DFE carousel – click middle right", dfePage);
        }
        if ($('#myImageFlow_images img').length == 15) {
            var imageClicked = $('.captionTop').text().replace("/", " of ");
            trackGAWithCategory("DFE", "DFE product image " + imageClicked + "-clicked", dfePage);
            window.setTimeout(function() { trackGAWithCategory("DFE", "DFE product image " + imageClicked + "-viewed", dfePage); }, 1000);
        }
    });
      
    $('#myImageFlow_next').live("click", function() {
    trackGAWithCategory("DFE", "DFE slider - right arrow clicked", dfePage);
    });
    
    $('#myImageFlow_previous').live("click", function() {
    trackGAWithCategory("DFE", "DFE slider - left arrow clicked", dfePage);
    });
}
function setTrackCookie(pageId, eventId, apNum, trackName) {
    var theDomain = "";
    var cValue = "";
    theDomain = document.domain;
    var theDomainStart = theDomain.indexOf("allposters");
    theDomain = theDomain.substr(theDomainStart);
    theDomain = '.' + theDomain;
    var dfeCookieValue = GetCookieDictionary("apc", trackName);
    cValue = pageId + "_" + eventId + "|" + apNum;
    if (dfeCookieValue.indexOf(cValue) < 0) {
        if (dfeCookieValue.length > 0) {
            dfeCookieValue = dfeCookieValue + ","
        }
        SetCookieDictionary("apc", trackName, dfeCookieValue + cValue, '', "/", "" + theDomain + "", false);
    }
}

function setDFETrackCookie(pageId, eventId, apNum) {
    setTrackCookie(pageId, eventId, apNum, "DFETrack");
}


$(document).ready(function() {

//alert("GlobalContent:" + wtEnabledGCF);
    /* Holiday 2010 */
    $('.holiday2010LongMsgContainer').hide();
    $('.holiday2010ShortMsgContainer').hide();
    $('.holiday2010NotArriveMsgContainer').hide();

    if ($('.sizeOptionBlockSelected').length > 0 || $('.singleItemPriceContainer').length > 0) {
        $('.sizeOptionBlockSelected .holiday2010LongMsgContainer, .singleItemPriceContainer .holiday2010LongMsgContainer ').show();
        $('.sizeOptionBlockSelected .holiday2010NotArriveMsgContainer, .singleItemPriceContainer .holiday2010NotArriveMsgContainer ').show();
        $('.sizeOptionBlockSelected .holiday2010ShortMsgContainer, .singleItemPriceContainer .holiday2010ShortMsgContainer').hide();
    }
    else {
        $('.holiday2010LongMsgContainer').show();
        $('.holiday2010NotArriveMsgContainer').show();
        $('.holiday2010ShortMsgContainer').hide();
    }

    gaPageFrame = $(this).find("#ga_frameload_Page").text();
    gaEventFrame = $(this).find("#ga_event_upframeload").text();
    if (gaEventFrame != undefined && gaEventFrame != '' && gaPageFrame != undefined && gaPageFrame != '') {
        trackGAWithCategory("Recommendations", gaEventFrame, gaPageFrame);
    }
    gaPageBS = $(this).find("#ga_BSload_Page").text();
    gaEventBS = $(this).find("#ga_event_BSload").text();
    if (gaEventBS != undefined && gaEventBS != '' && gaPageBS != undefined && gaPageBS != '') {
        trackGAWithCategory("Recommendations", gaEventBS, gaPageBS);
    }
    gaPageRel = $(this).find("#ga_Relload_Page").text();
    gaEventRel = $(this).find("#ga_event_Relload").text();
    if (gaEventRel != undefined && gaEventRel != '' && gaPageRel != undefined && gaPageRel != '') {
        trackGAWithCategory("Recommendations", gaEventRel, gaPageRel);
    }
    //Calling handleRecoRederer after 1000 milli seconds.
    setTimeout("atgRecInitial()", 1000);

    $(document).bind('click', function() {
        $('#REquickViewContainer').hide();
    });

    $('#REquickViewContainer').bind('mouseleave', function() {
        hideREQuickView();
    });
});


function InternalAdFunction(divid, linktype, link, width, height) {
    // LinkType     OpenIn
    // 0            newtab
    // 1            samewindow
    // 2            popup
    if (link != null && link != "") {
        if (linktype == 0) {
            window.open(link);
        }
        if (linktype == 1) {
            window.location.href = link;
        }
        if (linktype == 2) {
            window.open(link, '', 'width=' + width + ',height=' + height + ',scrollbars=1,resizable=1,top=0,left=0');
        }
    }
    else {
        return false;
    }
}

function FrameStudioInline(pURL, pParameters, qs_sessionid, glbCustomerZoneID, sAltLink){      

      var url;         
      if(pURL.indexOf('photostoart/default.asp')>-1){
         url = pURL + "&" + pParameters + "&ui=" + qs_sessionid + "&customerzoneid=" + glbCustomerZoneID + "&pagetype=overview";
      }
      else {            
      url = pURL + "?" + pParameters + "&ui=" + qs_sessionid + "&customerzoneid=" + glbCustomerZoneID;
      }
      window.location.href = url;
}



