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();
       if (pAPNum.indexOf("apnum") > 0)
       {
            if (pAPNum.substring(pAPNum.length-1) == "&")
                pAPNum = pAPNum.substring(0,pAPNum.length-1);
            winPop = window.open("/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("/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 = "/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;
}
