﻿/*
        Name            :           baudville-main.js
        Purpose         :           Functions used through out the site
        Author          :           JohnD (Baudville) - 7/1/2008
        
        Note(s)         :           
*/

var _strCPId = "ctl00_ContentPlaceHolder1_";
var _strMPId = "ctl00_";
var _strQPId = "ctl00_ContentPlaceHolder1_ucQuickPeek_";
var _intMinWidth = 1024;
var _intMinHeight = 768;
var _intSlideGoTo = 0;            
var _blnSlideJumpTo = false;   
var _blnOn = false;
var  _strXmlReturn = "";


/*
    Name        :       validateThankYouForm
    Purpose     :       Validates the email address field on the thank you page.
    Author      :       JohnD (Baudville) - 2/3/2010
*/
function validateThankYouForm(tbxEmail) {
 var blnReturn = true;
 var strErrMsg = '';
 if (!validateEmailAddress(tbxEmail)) {
    strErrMsg = "Invalid Email Address";
    radalert(strErrMsg,300,100,'Blog Subscribition Failed');
    blnReturn = false
 } else {
 
 
    GetRadWindow().close(); 
    subscribeMe(tbxEmail.value);
 }
 
 return blnReturn

    
}

/*
    
    Name        :       subscribeMe
    Purpose     :       Passes the person's email address to the feedburner
    Author      :       Kevin M (Baudville) 2009
                        Pulled in the code from what Kevin did on the baudville blog.
    Date        :       2/3/2010                        
*/	
function subscribeMe(strEmailAddr)
{
window.open('http://feedburner.google.com/fb/a/mailverify?uri=Baudville&email=' + strEmailAddr, 'popupwindow', 'scrollbars=yes,width=550,height=520');
}


/*
        Name            :           openFolderPersonaization
        Purpose         :           Opens up the personalization window
        Author          :           JohnD (Baudville) - 12/30/2009
        Params          :           blnContentPage - Will be set to true if it is
                                                     coming from a content page.
                                    
                                    blnQuickPeek - Will be set to true if it is
                                                   coming from the quickpeek page.
*/
function openFoldersPersonalization(blnContentPage, blnQuickPeek) {
    var strQuickPeek = "N";
    var strContentPageId = _strCPId;
    if (!blnContentPage) {
        strContentPageId = "";
    }
    
    var strUrl = getElementId(strContentPageId + 'hidSiteUrl').value;
    var lngQty = 0;
    

    if (getElementId(strContentPageId + 'chbFoldersPersOnly').checked) {
        strUrl += 'folder-details-p/' + getElementId(strContentPageId + 'hidInvtId').value;
    if (blnQuickPeek) {
        strQuickPeek = "PFP";
    } else {
        strQuickPeek = "FP"
    }
      
      
        lnQty = 100;
    } else if (getElementId(strContentPageId + 'chbFoldersCustOnly').checked) {
        strUrl += 'folder-details-c/' + getElementId(strContentPageId + 'hidInvtId').value;
        lnQty = 500;
        
        if (blnQuickPeek) {
        strQuickPeek = "PFC";
    } else {
        strQuickPeek = "FC"
    }
    }
    //Append whether it is called from quick peek or not
    strUrl += '/' + strQuickPeek;
    //Open up the rad window   
    ChangePage(strUrl, lngQty,1000,850,64,1 );
    //return value
    return false;
}

/*
        Name            :           changeAddToSection
        Purpose         :           Toggles the cart section from personalize to stock
        Author          :           JohnD (Baudville) - 12/30/2009
*/
function changeAddToCartSection(intMode, blnContentPage) {

    var strContentPageId = _strCPId;
    if (!blnContentPage) {
        strContentPageId = "";
    }
    
    
    var imgAddToCart = strContentPageId;
    var strCartStock = 'imbAddToCart';
    var strCartStockFolder = 'imgAddToCartFolders';
    var strCartStockFolderCust = 'imgAddToCartFoldersCustom';
    var spnQty  = strContentPageId + 'spnQty';

    var blnCustOnly =  false
    var blnStockOnly = false;
    var blnPersOnly =  false;
    
    
    
    if (getElementId(strContentPageId + 'chbFoldersCustOnly') != null) {
        blnCustOnly = getElementId(strContentPageId + 'chbFoldersCustOnly').checked;
    }
    blnStockOnly = getElementId(strContentPageId + 'chbFoldersStockOnly').checked;
    blnPersOnly = getElementId(strContentPageId + 'chbFoldersPersOnly').checked
    
    if (!blnStockOnly && !blnPersOnly && !blnCustOnly) {
        getElementId(strContentPageId + 'chbFoldersStockOnly').checked = true;
        intMode = 1;
    } 
    switch (intMode) {
        case 1:
        
        getElementId('divAvailable').className = 'show-block'
        
            getElementId(imgAddToCart + strCartStock).className = 'show-block';            
            getElementId(spnQty).className = 'show-inline';
            getElementId(imgAddToCart + strCartStockFolder).className = 'no-show';
            getElementId(imgAddToCart + strCartStockFolderCust).className = 'no-show';
            getElementId(strContentPageId + 'tbxQty').style.display="inline";
            getElementId(strContentPageId + 'hidPersType').value="";
            break;
        case 2:
        getElementId('divAvailable').className = 'no-show'
            getElementId(imgAddToCart + strCartStock).className = 'no-show';            
            getElementId(spnQty).className = 'no-show';
            getElementId(imgAddToCart + strCartStockFolder).className = 'show-block';
            getElementId(imgAddToCart + strCartStockFolderCust).className = 'no-show';
            getElementId(strContentPageId + 'tbxQty').style.display="none";
            getElementId(strContentPageId + 'hidPersType').value=getElementId(strContentPageId + 'hidOrigPersType').value;
            break;
        case 3:
        getElementId('divAvailable').className = 'no-show'
            getElementId(imgAddToCart + strCartStock).className = 'no-show';            
            getElementId(spnQty).className = 'no-show';
            getElementId(imgAddToCart + strCartStockFolderCust).className = 'show-block';
            getElementId(imgAddToCart + strCartStockFolder).className = 'no-show';
            getElementId(strContentPageId + 'tbxQty').style.display="none";
                        getElementId(strContentPageId + 'hidPersType').value=getElementId(strContentPageId + 'hidOrigPersType').value;

            break;
    }
    
}

/*
    Name        :   getParentElementId
    Purpose     :   Wrapper for the call to parent.document.getElementById, passed in the element
                    name as a string. REturns a reference to the passed in object.
    Author      :   JohnD (Baudville) - 12/30/2009                    
*/
function getParentElementId(elementName) {
    return parent.document.getElementById(elementName);
}


/*

    Name         :       saveDataPost
    Author       :       JohnD (Baudville) - 12/15/2009
    Params       :       strUrl - Url that is being called by the post
                         strDataSent - values separated by ampersand
                         blnCallType - true/false
*/

function saveDataPost(strUrl, strDataSent, blnCallType) {
    //Local variables
    var xmlHTTP = GetXmlHttpObject();
     _strXmlReturn = "";
    //Set the default value of blnCallType
    if (blnCallType == null) {
        blnCallType = false;
    }

    //Create the xmlHttp object
    xmlHTTP.open("POST", strUrl, blnCallType);
    xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHTTP.setRequestHeader("Content-length", strDataSent.length);
    xmlHTTP.setRequestHeader("Connection", "close");

    //check to see what version of FF is being used
    if (_intFireFoxVers >= 2) {
        //Firefox call for xmlHTTP
        xmlHTTP.onload = function() {
             if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete") {
             _strXmlReturn= xmlHTTP.responseText;
             }
        }
        xmlHTTP.send(strDataSent);
    } else {
        //Non firefox call for xmlHTTP
        xmlHTTP.onreadystatechange = function() {
             if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete") {
            _strXmlReturn = xmlHTTP.responseText;
            }
        }
        xmlHTTP.send(strDataSent);
    }
    return _strXmlReturn;
}

function shrmSignUpValidation() {
    var strBr = "\n"
    var strDataSent = "";
    var strErrMsg = "Following fields are required:" + strBr;
    var blnValid=true;
    if (getElementId(_strCPId + "tbxEmail").value.length == 0) {
        strErrMsg += "Email" + strBr;
        blnValid=false;
    } else {
        if (!validateEmailAddress(getElementId(_strCPId + "tbxEmail"))) {
            strErrMsg += "Invalid Email Address" + strBr;
            blnValid=false;
        }
    }
    if (blnValid) {
        strDataSent = "typ=shrm&fn=&ln=cn=&ad=&ci=&st=&zip=&em=" + getElementId(_strCPId +'tbxEmail').value + "&ph=";
    
        saveContactInfoToDb(strDataSent,'shrm-thankyou');
        
    } else {
        alert(strErrMsg)
    }
    
    return blnValid;
}


/*
    Name        :       ShowQuickPeekButton
    Purpose     :       Uncovers the Quick Peek button onmouseover
    Author      :       NikZ (Baudville) - 9/30/2009
*/
function ShowQuickPeekButton(divQPButton)
{
	getElementId(divQPButton).style.display = "block";
}

/*
    Name        :       HideQuickPeekButton
    Purpose     :       Hides the Quick Peek button on mouseout
    Author      :       NikZ (Baudville) - 10/20/2009
*/
function HideQuickPeekButton(divQPButton)
{
	getElementId(divQPButton).style.display = "none";
}

/*
    Name        :       CloseToolTip
    Purpose     :       Closes any currently active tooltip
    Author      :       NikZ (Baudville) - 9/30/2009
*/
function CloseToolTip()
{
	try {
		var tooltip = Telerik.Web.UI.RadToolTip.getCurrent(); 
		if(tooltip) tooltip.hide();
	}
	catch(err) {
	}
}

/*
    Name        :       onSelectedQuickPeekTab
    Purpose     :       Handles the tab selected event
    Author      :       NikZ (Baudville) - 9/28/2009
*/
function onSelectedQuickPeekTab(sender, args) {
	var tabs = args.get_tab();
	var strTabText = tabs.get_text();
        
	if (strTabText.indexOf("Price") > -1) {
		tabs.set_selectedIndex(0);
	} else if (strTabText.indexOf("Details") > -1) {
		tabs.set_selectedIndex(1);
	}
}

/*
    Name            :       wordWrap
    Purpose         :       Fixes the FF word wrap issue.
    Author          :       See comment section down below, but this was added in by Greg Jensen (Baudville) - 6/19/2009
*/
function wordWrap(){
/******
* wordWrap to firefox for big words
* Creative Commons license * Version: 1.0 - 26/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - http://elmicoxcodes.blogspot.com
* Uso: call the function on onload of body element.
* put the class "word-wrap" on elements to wordwrap
*******/
    var larg_total,larg_carac,quant_quebra,pos_quebra;
    var elementos,quem, caracs, texto, display_orig;
    
    elementos = document.getElementsByTagName("p")
    
    for(var i=0; i<elementos.length;i++){
        if(elementos[i].className=="word-wrap"){
            quem = elementos[i];
            
            quem.innerHTML = String(quem.innerHTML).replace(/ /g,"Ø")
            texto = String(quem.innerHTML)
            
            quem.innerHTML = " "
            
            display_orig = quem.style.display;
            quem.style.display="block";
            larg_oficial = quem.offsetWidth;
            //alert("oficial: " + larg_oficial)
            //alert("display " + quem.style.display)
            if(!document.all) quem.style.display="table";
            //alert("display " + quem.style.display)
            quem.innerHTML = texto;
            larg_total = quem.offsetWidth;
            //alert("total: " + larg_total)
            
            pos_quebra = 0;
            caracs = texto.length;
            texto = texto.replace(/Ø/g," ")
            larg_carac = larg_total / caracs
            if(larg_total>larg_oficial){
                quant_quebra = parseInt(larg_oficial/larg_carac)
                quant_quebra = quant_quebra - (parseInt(quant_quebra/6)) //quanto menor o num, maior a garantia;
                quem.innerHTML = ""
                while(pos_quebra<=caracs){
                    quem.innerHTML = quem.innerHTML + texto.substring(pos_quebra,pos_quebra + quant_quebra) + " "
                    pos_quebra = pos_quebra + quant_quebra;
                }
            }else{
                quem.innerHTML = texto;
            }//end if do larg_total>larg_oficial
            quem.style.display = display_orig;
        }//end if do word wrap
    }//end for loop dos elementos
}


/*
    Name        :       cartCaboodle
    Purpose     :       Something to do with the cart
    Author      :       JohnD (Baudville) - 6/2009
*/
function cartCaboodle(strDomain,intOl) {
    window.location = strDomain + 'cartcaboodle/71500/' + intOl;
}


/*
    Name        :       boxImageRollover
    Purpose     :       Handles the image rollovers, if it blnOn is set to true, then the rollover will take place.
    Author      :       JohnD (Baudville) - 5/2009
*/
function boxImageRollover(imgSrc, intBox, blnOn) {

    if (blnOn) {
        if (getElementId('imgBox' + intBox) != null) {
            getElementId('imgBox' + intBox).src = imgSrc;
        }
    }
}



/*
 Name            :       validateEmailAddress
 Purpose         :
 Author          :       JohnD (Baudville)
 Date            :       5/13/2009
 */
function validateEmailAddress(tbEm) {

    
    var blnReturn = false;
    tbEm.value = tbEm.value.trim();
    if (tbEm.value.match(/^[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9]@[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9][\.][a-z0-9]{2,4}$/i))    {
        blnReturn = true;
    }
    
    return blnReturn
}


/*
 Name            :       validateMultipleEmailAddress
 Purpose         :       This function accepts 1 or more delimited email addresses.  The delimiter can be passed in, or will default to comma
 Author          :       Kevin M (Baudville)
 Date            :       11/06/2009
 */
function validateMultipleEmailAddresses(tbEm, strDelimiter) {    
    var blnReturn = false;
    var blnAllEmailTrue = true;
    var emailArray = new Array();
    tbEm.value = tbEm.value.trim();
    
    //check for delimiter passed into function
    if(strDelimiter === undefined)
        strDelimiter = ",";
    
    //Check directly for a valid email address (in case they only inserted a single address)   
    if (tbEm.value.match(/^[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9]@[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9][\.][a-z0-9]{2,4}$/i)) {
        blnReturn = true;
    }
    //Else if the input isn't a single valid email, then check if it's multiple email addresses
    else  {
        //Check for a comma, if not then they the input isn't multiple email addresses
        if(tbEm.value.indexOf(strDelimiter) > -1) {
            emailArray = tbEm.value.split(strDelimiter);
            var i;
            for(i=0; i < emailArray.length; i++) {
                if (!emailArray[i].trim().match(/^[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9]@[a-z0-9][a-z0-9_\.-]{0,}[a-z0-9][\.][a-z0-9]{2,4}$/i))  {
                    blnAllEmailTrue = false;
                }    
            }
         
            if(blnAllEmailTrue)
               blnReturn = true;        
             
        }
    }

    return blnReturn
}
 


function saveContactInfoToDb(strDataSent, thankyou_url) {

    

	var xmlHTTP = GetXmlHttpObject();
	var strHttpServer = document.getElementById(_strCPId + 'hidSiteDomain').value;
    
	var szURL = "/dialogs/xmlcallback.aspx?dlg=svecontactinfo"
	strSCSiteUrl = strHttpServer;
	
	
	strSCWinLoc = "countdown-thankyou";
	if (thankyou_url != null) {
	strSCWinLoc = thankyou_url;
	}
	
	
	
	
    
	
	
	xmlHTTP.open("POST", szURL, false);
	xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHTTP.setRequestHeader("Content-length", strDataSent.length);
    xmlHTTP.setRequestHeader("Connection", "close");
	
	if (_intFireFoxVers >=2) {

	xmlHTTP.onload = function(){
	 if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete") {
                    var strXmlReturn = xmlHTTP.responseText;
                    strXmlReturn = strXmlReturn.replace("<Response><item>", "");
                    strXmlReturn = strXmlReturn.replace("</item></Response>", "");
                    strXmlReturn = strXmlReturn.replace('<?xml version="1.0" ?>', '');
                    if (strXmlReturn != null) {
                        if (strXmlReturn.length > 0) {
                            //alert(strXmlReturn + "1");
                        }
                    }

                    if (strXmlReturn.indexOf('Error') > - 1) {
                        //alert("Coupon code was not be applied.");

                        window.location = strSCSiteUrl + strSCWinLoc; 
                    } else {

                        window.location = strSCSiteUrl + strSCWinLoc; 
                    }
                  }
	}
	xmlHTTP.send(strDataSent);
	} else {
	xmlHTTP.onreadystatechange = function(){
	 if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete") {
                    var strXmlReturn = xmlHTTP.responseText;
                    strXmlReturn = strXmlReturn.replace("<Response><item>", "");
                    strXmlReturn = strXmlReturn.replace("</item></Response>", "");
                    strXmlReturn = strXmlReturn.replace('<?xml version="1.0" ?>', '');
                    if (strXmlReturn != null) {
                        if (strXmlReturn.length > 0) {
                            //alert(strXmlReturn + "1");
                        }
                    }
                    if (strXmlReturn.indexOf('Error') > - 1) {
                        //alert("Coupon code was not be applied.");
                        window.location = strSCSiteUrl + strSCWinLoc; 
                    } else {
                        window.location = strSCSiteUrl + strSCWinLoc; 
                    }
                  }
	}
	xmlHTTP.send(strDataSent);
	}
}

function d2dSignUpValidation() {
    var strBr = "\n"
    var strDataSent = "";
    var strErrMsg = "Following fields are required:" + strBr;
    var blnValid=true;
    if (getElementId(_strCPId + "tbxFName").value.length == 0) {
        strErrMsg += "First Name" + strBr;
        blnValid=false;
    }
    if (getElementId(_strCPId + "tbxLName").value.length == 0) {
        strErrMsg += "Last Name" + strBr;
        blnValid=false;
    }
        if (getElementId(_strCPId + "tbxAddr").value.length == 0) {
        strErrMsg += "Address" + strBr;
        blnValid=false;
    }
    if (getElementId(_strCPId + "tbxCity").value.length == 0) {
        strErrMsg += "City" + strBr;
        blnValid=false;
    }
    if (getElementId(_strCPId + "tbxState").value.length == 0) {
        strErrMsg += "State" + strBr;
        blnValid=false;
    }
    if (getElementId(_strCPId + "tbxZip").value.length == 0) {
        strErrMsg += "Zip" + strBr;
        blnValid=false;
    }
    if (getElementId(_strCPId + "tbxEmail").value.length == 0) {
        strErrMsg += "Email" + strBr;
        blnValid=false;
    } else {
        if (!validateEmailAddress(getElementId(_strCPId + "tbxEmail"))) {
            strErrMsg += "Invalid Email Address" + strBr;
            blnValid=false;
        }
    }
    if (blnValid) {
        strDataSent = "fn=" + getElementId(_strCPId + 'tbxFName').value + "&ln=" + getElementId(_strCPId + 'tbxLName').value + "&cn=" + getElementId(_strCPId + 'tbxCName').value + "&ad=" + getElementId(_strCPId + 'tbxAddr').value + "&ci=" + getElementId(_strCPId +'tbxCity').value + "&st=" + getElementId(_strCPId +'tbxState').value + "&zip=" + getElementId(_strCPId +'tbxZip').value + "&em=" + getElementId(_strCPId +'tbxEmail').value + "&ph=" + getElementId(_strCPId + 'tbxPhone').value;
    
        saveContactInfoToDb(strDataSent);
        
    } else {
        alert(strErrMsg)
    }
    

    return blnValid;
}


function changeLoc(intSlide) {

frs = getElementId('frsList');

frs.src = "/dialogs/prodlist.aspx?slideid=" + intSlide;

}

/*
 Name             :       displayProductSortResultClearanceCategories
 Purpose          :       Display the product sort results
 Author           :       JohnD (Baudville) - 5/4/2009
 Note(s)          :
 */
function displayProductSortResultClearanceCategories(ddl) {

    var ddlSort  = getElementId(_strCPId + 'ucProductSortRefineList_ddlSortResultsTop');
    var ddlRefine  = getElementId(_strCPId + 'ucProductSortRefineList_ddlRefineResults');
    if (ddl.selectedIndex >= 0) {
    
        if (ddl.options[ddl.selectedIndex].value.indexOf("/ALL/") > -1) {
            var lngSiteCatId = 0;
            if (ddlRefine.selectedIndex > 0) {
                lngSiteCatId = ddlRefine.value
            }
            window.location = ddl.options[ddl.selectedIndex].value.replace("/ALL/","/" + lngSiteCatId + "/"); // + '/';
        } else {
            var strLocation = ddlSort.value;
            var strValue = ddl.options[ddl.selectedIndex].value;
            if (strValue.indexOf("Show All") > -1) {
                strValue = "0";
            }
            window.location = strLocation.replace("/ALL/",'/' + strValue + '/') ; // + '/';
        }
            
    }
}

/*
    Name        :       checkUserScreenResolution
    Purpose     :       Checks to see what the screen resolution is for the user, if it is less
                        than the minimum, then a message is displayed.
    Author      :       JohnD (Baudville) - 3/31/2009
*/
function checkUserScreenResolution(intMsgType) {
 var intUserWidth = screen.width;
 var intUserHeight = screen.height;
 
 if (intMsgType == null) {
    intMsgType = 1;
 }
 
 if (parseInt(intUserWidth) < parseInt(_intMinWidth) && parseInt(intUserHeight) < parseInt(_intMinHeight)) {
    if (intMsgType == 1) {
        var strMsg = _arrUserMsg[11];
        strMsg = strMsg.replace('MINWIDTH',_intMinWidth);
        strMsg = strMsg.replace('MINHEIGHT',_intMinHeight);
        strMsg = strMsg.replace('USERWIDTH',intUserWidth);
        strMsg = strMsg.replace('USERHT',intUserHeight);
        getElementId('spnScrRes').innerHTML = strMsg + "<br>";
        getElementId('spnScrRes').style.display="inline";
    } else {        
        if (getElementId(_strCPId + 'hidPersType').value.length > 0) {
           var strMsg = _arrUserMsg[12];
           strMsg = strMsg.replace('MINWIDTH',_intMinWidth);
           strMsg = strMsg.replace('MINHEIGHT',_intMinHeight);
           getElementId(_strCPId + 'imbAddToCart').style.display = "none";
           getElementId('spnScrResDetails').innerHTML = strMsg + "<br>";
           getElementId('spnScrResDetails').style.display="inline";
        }
        
    }
    
 }

}


/*
    Name        :       getFireFoxVers
    Purpose     :       Pulls back the version of firefox
    Author      :       JohnD (Baudville) - 3/20/2009
*/
function getFireFoxVers() {

    var intReturn = 0;

    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ffversion>=3) {
            intReturn = 3;
        } else if (ffversion>=2) {
            intReturn = 2;
        } else if (ffversion>=1) {
            intReturn = 1;
        } else {
            intReturn = 0;
        }     
    }        

    return intReturn;
}
//Set the firefox version if known
var _intFireFoxVers = getFireFoxVers();


//Generic Functions
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}



/*
    Name        :   formatAsMoney
    Purpose     :   Takes a numeric value and formats it as money
    Author      :   JohnD (Baudville) - 2/11/2009
*/
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}


/*
    Name        :   escapeSpecialCharacters
    Purpose     :   Escapes any special characters that are in this list
                    &#%\
    Author      :   JohnD (Baudville) - 2/5/2009
*/
function escapeSpecialCharacters(strTextIn) {
    var arrSpecialChars = new Array('&','#','%','#');
    var strTemp = "";
    var strReturn = "";
    for (s=0;s<=strTextIn.length;s++) {
        strTemp = strTextIn.substr(s,1);
        for (i=0;i<=arrSpecialChars.length -1;i++) {
            if (strTemp.indexOf(arrSpecialChars[i]) > -1) {
                    strTemp = strTemp.replace(arrSpecialChars[i],escape(arrSpecialChars[i]));
                    break;
            }
        }
        strReturn += strTemp;
    }
    return strReturn;
}

/*
    Name        :   gotoIdvilleProdDetails
    Purpose     :   Will send the user to the idville details landing page for the
                    passed in invtid.
    Author      :   JohnD (Baudville) - January 2009                    
*/
function gotoIdvilleProdDetails(inv) {
    window.open('http://www.idville.com/details.aspx?PNO=' + inv,'IDVilleOrder','width=800,height=640,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
    return false;
}


/*
    Name        :   getElementId
    Purpose     :   Wrapper for the call to document.getElementById, passed in the element
                    name as a string. REturns a reference to the passed in object.
    Author      :   JohnD (Baudville) - January 2009                    
*/
function getElementId(elementName) {
    return document.getElementById(elementName);
}

/*
    Name        :       closeDialogWindow
    Purpose     :       Confirms the closing of the personalization dialog
                        
    Author      :       JohnD (Baudville) - 1/14/2009
                            
*/    
function closeDialogWindow(intWnd) {
    var strMsg = _arrUserMsg[2];
    var lngHt = 150;
    var lngWd = 400;
    var strTitle = "";
    var blnConfirm = true;
    
    switch (intWnd) {
        case 1:
            strTitle = "Trophy Personalization Changes";
            break;
            
        case 2:
            strTitle = "Plaque Personalization Changes";
            break;
            
        case 3:
            strTitle = "Greeting Card Personalization Changes";
            break;
            
        case 4:
            strMsg = _arrUserMsg[17]
            lngHt = 150;
            lngWd = 400;
            strTitle = "Quickview Product Changes";
            blnConfirm = false;
            break;
        
		  case 5:
				strTitle = "Continue Shopping";
				blnConfirm = false;
				break;
				
		  case 6:
				strTitle = "Proceed to Checkout";
				blnConfirm = false;
				break;
        case 7:
            strTitle = "Folder Personalization Changes";
            break;				
    }
    
	 if (intWnd == 5 || intWnd == 6) {
      GetRadWindow().close();
      if (intWnd == 5) {
			top.location.reload();
		}
		if (intWnd == 6) { 
			var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
         var strHttpserver = "";
         if (hidSite == null) {
             strHttpServer = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain').value;
         } else {
             strHttpServer = hidSite.value;
         }
			top.location.href = strHttpServer + 'shopping-cart';
		}	    
	 } else {
		radconfirm(strMsg, confirmCloseFn,lngWd,lngHt,"",strTitle);
	 }
}

/*
    Name        :       confirmCloseFn
    Purpose     :       Closes the passed in window, this can be called from any dialog window.
    Author      :       JohnD (Baudville) - 1/14/2009
    
*/
function confirmCloseFn(arg) {
   if (arg) {
        var radWnd = GetRadWindow();
        radWnd.close();
    }
}  

/*
    Name        :       imageLoad
    Purpose     :       This handles the broken image links on the page, if there is a broken image then it defaults
                        to the not available image.
    Author      :       JohnD & GregJ - Baudville - 1/13/2009 
    Changed     :       GregJ - 2/12/09  Added code to use secure link                       
*/
function imageLoad(img, blnPageType, ht, wd, IsSecure) {
    var strImgNA = "";
    if (blnPageType) {
        img.style.display='none';
        if (IsSecure != null) {
            strImgNA = "https://a248.e.akamai.net/f/248/9086/1.ccd/origin-d2.scene7.com/is/image/Baudville/NOTAVAIL?hei=" + ht + "&wid=" + wd + "&op_sharpen=0";
        }
        else {
            strImgNA = "http://s7d2.scene7.com/is/image/Baudville/NOTAVAIL?hei=" + ht + "&wid=" + wd + "&op_sharpen=0";
        }
        img.src = strImgNA;
        img.style.display='inline';
    } else {
        img.style.display='none';
    }
}



/*
    Name        :       IsNumeric
    Purpose     :       Validates if the value is numeric or not
                        this in baudville.
    Author      :       JohnD (Baudville) - 11/2008
                            
*/

function IsNumeric(sText)
{
var ValidChars = "0123456789";
for (i = 0; i < sText.length; i++) { 
if (ValidChars.indexOf(sText.charAt(i)) == -1) {
return false;
}
}
return true;
}

/*
    Name        :       showErrMsg
    Purpose     :       Displays the error messaged based on whether or not
                        this in baudville.
    Author      :       JohnD (Baudville) - 11/20/2008
                            
*/
function showErrMsg(strMsg) {
    var hidIsBaudville = document.getElementById('hidIsBaudville');
    
    if (hidIsBaudville != null) {
    var intIsBaudville = hidIsBaudville.value

    if (intIsBaudville == 1) {
        alert(strMsg);
    }
    }
}

function redirectSubCat(ddl) {

    var sbp = document.getElementById(_strCPId + 'hidSiteDomain').value;
    var rg1 = document.getElementById(_strCPId + 'hidRg1');
    var rg2 = document.getElementById(_strCPId + 'hidRg2');
    var cat = document.getElementById(_strCPId + 'hidCatId');
    var sm = document.getElementById(_strCPId + 'hidSortMode');
    var strUrl = sbp;

    if (ddl.selectedIndex > 0) {
        var strLoc = "";
        var arrSbp = new Array();

        arrSbp = ddl.options[ddl.selectedIndex].value.split('|');
        if (arrSbp.length == 2) {
            strLoc = sbp + arrSbp[0] + 'productpricesubcat/' + rg1.value + '/' + rg2.value + '/' + cat.value + '/' + arrSbp[1];
            window.location = strLoc
        }
    }
}

function redirectSubCatWTS(ddl, type) {

    var sbp = document.getElementById(_strCPId + 'hidSiteDomain').value;
    var cat = document.getElementById(_strCPId + 'hidCatID');
    //var subcat = document.getElementById(_strCPId + 'hidSubCatID');
    var sm = document.getElementById(_strCPId + 'hidSortMode');
    var strUrl = sbp;
    
    if (sm.value.length == 0) {
        sm.value = 'best'
    }

    if (ddl.selectedIndex > 0) {
        var strLoc = "";
        var arrSbp = new Array();

        arrSbp = ddl.options[ddl.selectedIndex].value.split('|');
        if (arrSbp.length == 2) {
            strLoc = sbp + arrSbp[0] + type + '/' + cat.value + '/' + sm.value + '/' + arrSbp[1];
            window.location = strLoc
        }
    }
}

function redirectSubSubCat(ddl) {
    var sbp = document.getElementById(_strCPId + 'hidSiteDomain').value;
    if (ddl.selectedIndex > 0 && ddl.selectedIndex < ddl.length) {
        window.location = sbp + ddl.options[ddl.selectedIndex].value;
    } else if (ddl.selectedIndex == ddl.length) {

}
}

function redirectForRCProducts(ddl) {
    var sbp = document.getElementById(_strCPId + 'hidSiteDomain').value;
    if (ddl.selectedIndex > 0 && ddl.selectedIndex < ddl.length) {
        window.location = sbp + ddl.options[ddl.selectedIndex].value;
    } else if (ddl.selectedIndex == ddl.length) {

}
}

/*
 Name             :       displayProductSortResult
 Purpose          :       Display the product sort results
 Author           :       JohnD (Baudville) - 11/2008
 Note(s)          :
 */
function displayProductSortResult(ddl) {
    if (ddl.selectedIndex >= 0) {
        window.location = ddl.options[ddl.selectedIndex].value; // + '/';
    }
}

/*
 Name             :       displayRefineResultForSearch
 Purpose          :       Display the product sort results
 Author           :       JohnD (Baudville) - 11/2008
 Note(s)          :
 */
function displayRefineResultForSearch(ddl) {
    window.location = ddl.options[ddl.selectedIndex].value;
}

/*
 Name             :       displayRefineResultForArticleListing
 Purpose          :       Display the product sort results
 Author           :       GregJ (Baudville) - 12/2008
 Note(s)          :
 */
function displayRefineResultForArticleListing(ddl) {
    window.location = ddl.options[ddl.selectedIndex].value;
}

/*
 Name             :       redirectToRefinedSearch
 Purpose          :       Redirect to the refined results
 Author           :       JohnD (Baudville) - 11/2008
 Note(s)          :
 */
function redirectToRefinedSearch(ddl) {
    if (ddl.selectedIndex >= 0) {
        var tid = document.getElementById(_strCPId + 'hidTid').value;
        var tgid = document.getElementById(_strCPId + 'hidTgid').value;
        var sbp = document.getElementById(_strCPId + 'hidSiteDomain').value;
        var pp = document.getElementById(_strCPId + 'hidPagePath').value;
        var loc = "";
        if (ddl.options[ddl.selectedIndex].value == "Show All") {
            loc = pp + 'ts/' + tgid + '/' + tid
        } else {
            loc = pp + 'rs/' + tgid + '/' + tid + '/' + ddl.options[ddl.selectedIndex].value
        }
        
        window.location = loc;
    }
}

/*
 Name             :       displaySortResult
 Purpose          :       Display sort results
 Author           :       JohnD (Baudville) - 11/2008
 Note(s)          :
 */
function displaySortResult(ddl) {
    
   if (ddl.selectedIndex >= 0) {
        window.location = ddl.options[ddl.selectedIndex].value;    
    }
    
    
}

/*
 Name             :       redirectToTheme
 Purpose          :       Redirects the selection from the dropdown to the correct theme
 Author           :       JohnD (Baudville) - 11/2008
 Note(s)          :
 */
function redirectToTheme(ddl) {
    var strLocation = "";
    var hidSiteDomain = document.getElementById(_strCPId + 'hidSiteDomain');
    if (ddl.selectedIndex > 0) {
        if (ddl.selectedIndex == ddl.length - 1) {
            strLocation = hidSiteDomain.value + 'recognition-themes/showthm/all';
        } else {
            strLocation = ddl.options[ddl.selectedIndex].value;
        }
        window.location = strLocation;
    }
}

/*
 Name             :       CurrencyFormat
 Purpose          :       Formats the value as a currency number
 Author           :       JohnD (Baudville) - 7/14/2008
 Note(s)          :       http://www.web-source.net/web_development/currency_formatting.htm
 */
function CurrencyFormat(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) {
        i = 0.00;
    }
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) {
        s += '.00';
    }
    if (s.indexOf('.') == (s.length - 2)) {
        s += '0';
    }
    s = minus + s;
    return s;
}

/*  
    Name        :       selectParentChild
    Purpose     :       Handles the image changing and everything in relation parent/child
    Author      :       JohnD (Baudville) October/2008
    Note(s)     :       JohnD (Baudville) - 11/18/2008
                        Added in the case for when the parent is not selected, that the add to cart should show up.
         
*/
function selectParentChild() {

var strLocation = "";
    var hidUrl = document.getElementById(_strCPId + 'hidUrl');
    var ddl = document.getElementById(_strCPId + 'radDdlParentChild');
    var ddl1 = $find(_strCPId + 'radDdlParentChild');
    var hidParentInvtId = getElementId (_strCPId + 'hidParentInvtId');
    
    if (ddl1._value != 0) {
        strLocation = hidUrl.value + ddl1._value;
        window.location = strLocation;        
    } else{
        strLocation = hidUrl.value + hidParentInvtId.value;
        window.location = strLocation;        
    }
}

/*  
    Name        :       selectQuickPeekParentChild
    Purpose     :       Handles the image changing and everything in relation parent/child for quickpeek
    Author      :       NikZ (Baudville) October/2009
    Note(s)     :                
*/
function selectQuickPeekParentChild(obj)
{
    var qs = new Querystring();
	var inv = obj.value;
	var cat = qs.get('prodcategory');
	var url = '/dialogs/quickpeek.aspx?inv=' + inv + '&prodcategory=' + cat;
	ChangePage(url,1);
}

/*
    Name        :       openImageViewerWindow(invtID, view)
    Purpose     :       Opens a radwindow that displays the imageviewer dialog page.
    Author      :       Kevin M (Baudville) December/2009
    Note(s)     :       
*/
function openImageViewerWindow(invtID, view)
{
    var strUrl = "/dialogs/imageviewer.aspx?invtID=" + invtID + "&view=" + view;
   
    var radWnd = radopen(strUrl, "radFlashViewer");      
    //Set the size of the window  
    radWnd.setSize(560, 760);
    radWnd.center();
}

/********************** Telerik Rad Specific Functions **********************************/


function confirmCallBackFn(arg) {
    if (arg) {
        var oManager = GetRadWindow();
        var oWnd = oManager.GetWindowByName(CurrentWinName);
        oWnd.Close();
    }
}
// Called when a window is being closed.
function OnClientCloseWin(sender) {
    //Another option for passing a callback value
    //Set the radWindow.argument property in the dialog
    //And read it here --> var oValue = radWindow.argument;										
    //Do cleanup if necessary
    //					var arg = new Object();				

    var returnValue = sender.Argument;

    var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
    var strHttpserver = "";
    if (hidSite == null) {
        hidSite = document.getElementById('hidSiteUrl');
        if (hidSite == null) {
            hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain');
        }
        strHttpServer = hidSite.value;
    } else {
        strHttpServer = hidSite.value
    }
    
    //Commented out because the functionality changed.
   if (returnValue.recsaved == 1 || returnValue.recsaved==2) {
        window.location = strHttpServer + "shopping-cart";
   } else if (returnValue.recsaved==3) {
        window.location = strHttpServer + returnValue.redirectUrl;
   }
  
    
  /*var childDoc = sender.GetContentFrame().contentWindow.document;
  var unsavedChanges = childDoc.getElementById('hidNewRecord').value;
    if (unsavedChanges == 1)
    {
    radconfirm('You have unsaved changes. Continue?',confirmCallBackFn);
    }  */
        
    
}

function openFlashWindow(strFile) {

    var strUrl = "/dialogs/flashviewer.aspx?swf=" + strFile;
    var radWnd = radopen(strUrl, "radWndFlash")
    radWnd.setSize(1000, 850);
    radWnd.reload();
    radWnd.SetModal(true);
    radWnd.center();

}
/*
        Name            :           openPersFromShopCart
        Purpose         :           Opens the personalization window from the shopping cart page
                                    
        Author          :           JohnD (Baudville) - 7/22/2008
        
        Note(s)         :           JohnD (Baudville) - 11/25/2008
                                    Added in some new parameters 
                                    ,pip,sip,qf,layer1,colour,extcode,timg
                                    
                                    JohnD (Baudville) - 12/8/2008
                                    Added in the parameters graphic and line1
                                    
                                    JohnD (Baudville) - 2/2/2009
                                    Added in the parameters initials and instructions
                                    
                                    JohnD (Baudville) - 1/4/2010
                                    Added in the param strFpc
*/
function openPersFromShopCart(strSb, strPT, intQty, strInvtId, lngOrdLine, tbxQty, dblPurchPrice,pip,sip,qf,layer1,colour,extcode,timg, graphic, line1,quickorder, initials,instructions,strFpc) {
    var strUrl = strSb;

    switch (strPT) {
    case "F":
        switch (strFpc) {
            case "Y":
                strUrl += "folder-cart-c/" + strInvtId + "/" + lngOrdLine;
                break;
            case "N":
                strUrl += "folder-cart-p/" + strInvtId + "/" + lngOrdLine;
                break;
        }
        break;
    case "R":
        strUrl += "dialogs/greetingcards.aspx?m=edit&qty=" + intQty + "&inv=" + strInvtId + "&ol=" + lngOrdLine + "&prc=" + dblPurchPrice + "&pip=" + pip + "&sip=" + sip + "&colour=" + colour + "&layer1=" + layer1 + "&timg=" + timg + "&qf=" + qf;
        break;
    case "P":
        strUrl += "dialogs/plaques.aspx?m=edit&qty=" + intQty + "&inv=" + strInvtId + "&ol=" + lngOrdLine + "&prc=" + dblPurchPrice + "&pip=" + pip + "&sip=" + sip + "&colour=" + colour + "&layer1=" + layer1 + "&timg=" + timg + "&qf=" + qf + "&qo=" + quickorder + "&initials=" + initials + "&instructions=" + instructions;

        break;
    case "T":
        strUrl += "dialogs/trophies.aspx?m=edit&qty=" + intQty  + "&inv=" + strInvtId + "&ol=" + lngOrdLine + "&prc=" + dblPurchPrice + "&pip=" + pip + "&sip=" + sip + "&colour=" + colour + "&layer1=" + layer1 + "&timg=" + timg + "&qf=" + qf + "&extcode=" + escape(extcode) + "&graphic=" + graphic + "&perstype=" + strPT + "&line1=" + line1 + "&qo=" + quickorder + "&initials=" + initials + "&instructions=" + instructions;
        break;

    case "1":
        strUrl += "dialogs/trophies.aspx?m=edit&qty=" + intQty  + "&inv=" + strInvtId + "&ol=" + lngOrdLine + "&prc=" + dblPurchPrice + "&pip=" + pip + "&sip=" + sip + "&colour=" + colour + "&layer1=" + layer1 + "&timg=" + timg + "&qf=" + qf + "&extcode=" + escape(extcode) + "&graphic=" + graphic + "&perstype=" + strPT + "&line1=" + line1 + "&qo=" + quickorder + "&qo=" + quickorder + "&initials=" + initials + "&instructions=" + instructions;
        break;
        
     case "G":
             strUrl += "dialogs/trophies.aspx?m=edit&qty=" + intQty  + "&inv=" + strInvtId + "&ol=" + lngOrdLine + "&prc=" + dblPurchPrice + "&pip=" + pip + "&sip=" + sip + "&colour=" + colour + "&layer1=" + layer1 + "&timg=" + timg + "&qf=" + qf + "&extcode=" + escape(extcode) + "&graphic=" + graphic + "&perstype=" + strPT + "&line1=" + line1 + "&qo=" + quickorder + "&qo=" + quickorder + "&initials=" + initials + "&instructions=" + instructions;
        break;
    }

    if (strPT == "F") {
        ChangePage(strUrl, tbxQty,1000,850,64,1 );
    } else {
        ChangePage(strUrl, tbxQty);
    }
    return false;

}

/*
        Name            :           openRadWindow
        Purpose         :           Opens up a rad window based on the values passed into it.
                                    
        Author          :           JohnD (Baudville) - 7/16/2008
        
*/
function openRadWindow(strUrl, intHt, intWid, isModal, isReload, isCentered, isStatusBar, tbxQty, ddlPersonalize) {

    var blnContinue = true;
    var tbx = document.getElementById(tbxQty);
    var ddl = document.getElementById(ddlPersonalize);
    var radDdl = $find(_strCPId + "radDdlParentChild");
    var strErrMsg = "";
    var blnError = false;

    if (tbx != null) {
        if (tbx.value.length == 0 || tbx.value == 0) {
            strErrMsg += "<br />Quantity";
            blnError = true;
            blnContinue = false;
        } else {

            var intMultiples = document.getElementById(_strCPId + 'hidQtyMult').value;

            if (intMultiples > 1) {
                if (parseInt(tbx.value) % parseInt(intMultiples) > 0) {
                    strErrMsg += "<br />Item must be ordered in quantities of " + intMultiples + ". Please adjust your quantity.";
                    blnError = true;
                    blnContinue = false;

                }
            } else {
                if (parseInt(tbx.value) < intMultiples) {
                    strErrMsg += "<br />Item quantity must be at least " + intMultiples + ". Please adjust your quantity.";
                    blnError = true;
                    blnContinue = false;
                }
            }

        }
    }
    
    // Close any active tooltips before opening rad window. (ie: QuickPeek)
    CloseToolTip();

    if (blnError) {
        radalert(strErrMsg, 300, 100, 'Item Error');
    } else {
        var arg = new Object();
        arg.recsaved = 0;
        arg.redirectUrl = "";
        if (tbx != null) {
            strUrl += "&qty=" + tbx.value;
        }
        
        var strValue = "";
        
        if (radDdl != null) {
            strValue = radDdl.get_value();
        }
        
        //Set the rad window
        var radWnd = radopen(strUrl, "RadWindow");
        radWnd.Argument = arg;

        //Check to see if the window is modal or not
        if (isModal == 1) {
            radWnd.SetModal(true);
        } else {
            radWnd.SetModal(false);
        }

        //Set the size of the window  
        radWnd.setSize(intWid, intHt);

        //Check to see if the window is centered or not
        if (isCentered == 1) {
            radWnd.center();

        }

        //Execute function on window close
        radWnd.add_close(OnClientCloseWin);
        
        //Check to see if the reload or close buttons should be hidden or not
        var hidShowCloseButton = getElementId(_strCPId + 'hidShowCloseButton');
        var hidHideReloadBtn = getElementId(_strCPId + 'hidHideReloadBtn');
        var hidWindowBehaviorMove = getElementId(_strCPId + 'hidWindowBehaviorMove');
        var strBehaviors = "";
        var strTelerik = "Telerik.Web.UI.WindowBehaviors.";
        
        strBehaviors = strTelerik + "None";
        if (hidShowCloseButton != null) {
				if (hidShowCloseButton.value == "true") {
					strBehaviors += " + " + strTelerik + "Close";
				}
        }
        if (hidWindowBehaviorMove != null) {
				if (hidWindowBehaviorMove.value == "true") {
					strBehaviors += " + " + strTelerik + "Move";
				}
		  }
        if (hidHideReloadBtn != null) {
			  if (hidHideReloadBtn.value != "true") {
					strBehaviors += " + " + strTelerik + "Reload";
			  }
		  }
		  radWnd.set_behaviors(eval(strBehaviors));
        
        //Reload
        if (isReload == 1) {
            radWnd.reload();
        }

        //Status bar
        if (isStatusBar == 0) {
        
        } else {
            radWnd.set_status("");
        }
    }

}

/*
        Name            :           GetRadWindow
        Purpose         :           Function exist on the page, it is needed to get a 
                                    reference to the radwindow wrapper
        Author          :           JohnD (Baudville) - 7/1/2008
        
*/
function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow;
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
    return oWindow;
}

/********************** Telerik Rad Specific Functions **********************************/

function cartItemToBeRemoved(hid, val, pt) {
    var hidCartItemRemove = document.getElementById(hid);
    hidCartItemRemove.value = val;
    getElementId('ctl00_ContentPlaceHolder1_hidPersTypeRemove').value = pt
}

function removeItemFromCart(arg) {
    if (arg) {
        var hidCartItemRemove = document.getElementById('ctl00_ContentPlaceHolder1_hidCartItemRemove');

        var strDataSent = ""
        var objHTTP = GetXmlHttpObject();
        var szURL = "/dialogs/xmlcallback.aspx?dlg=rifc";
        var szHttpMethod = "POST";
        var strAddType = "Remove";

        //Set the data to be sent over
        strDataSent = "&ol=" + hidCartItemRemove.value;
        var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
        strDataSent += "&pt=" + getElementId('ctl00_ContentPlaceHolder1_hidPersTypeRemove').value;
        var strHttpserver = "";
        if (hidSite == null) {
            strHttpServer = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain').value;
        } else {
            strHttpServer = hidSite.value
        }
        var blnReturn = AddItemToCartPost(strDataSent, szURL, szHttpMethod, strHttpServer, strAddType);
    }
}
/*
 Name             :      AddStockItem
 Purpose          :      Add stock items to the cart
 Author           :      JohnD (BV) - Sometime in 2008
 Note(s)          :      JohnD (BAudville) - 1/22/2010
                         Added in the change to handle folder personalization items
                         
                         JohnD (BAudville) - 2/4/2010
                         
 
*/
function AddStockItem(qty, inv, ohi, refinv) {

    var strDataSent = ""
    var objHTTP = GetXmlHttpObject();
    var szURL = "/dialogs/xmlcallback.aspx?dlg=cssi";
    var szHttpMethod = "POST";
    var strAddType = "Add";
    var strPersType = "";
    var hidPersType = getElementId(_strCPId + 'hidPersType')
    
    //Handle the check for folder personalization items, since this is a stock and a personalized item
    if (hidPersType == null) {
        hidPersType = getElementId('hidPersType')
    }
    if (hidPersType == null) {
        strPersType = "";
    } else {
        strPersType = hidPersType.value;
    }
    //Set the data to be sent over
    if (refinv == null) {
		refinv= "n/a";
    }
    //Send the data to the cart
    strDataSent = "&qty=" + qty + "&inv=" + inv + "&ohi=" + ohi + "&refinv=" + refinv + "&perstype=" + strPersType;
    var blnReturn = AddItemToCartPost(strDataSent, szURL, szHttpMethod, strAddType, inv, qty);
}

/*
 Name             :       AddItemToCartPost
*/
function AddItemToCartPost(strDataSent, szURL, szHttpMethod, strAddType, inv, qty) {
    var blnReturn = false;
    var objHTTP = GetXmlHttpObject();
    objHTTP.open(szHttpMethod, szURL, false);
    objHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objHTTP.setRequestHeader("Content-length", strDataSent.length);
    objHTTP.setRequestHeader("Connection", "close");

	if (_intFireFoxVers >= 2) {
		// New browsers
    objHTTP.onload = function() {
        if (objHTTP.readyState == 4 || objHTTP.readyState == "complete") {

            var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
            var hidSiteDomain = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain')
            var strHttpserver = "";
            if (hidSite == null) {
					if (hidSiteDomain != null) {
						strHttpServer = hidSiteDomain.value;
					} else {
						// Dialog pages and other non-master pages don't have the placeholder added to clientid
						hidSite = document.getElementById('hidSiteUrl');
						hidSiteDomain = document.getElementById('hidSiteDomain');
						if (hidSite == null) {
							strHttpServer = hidSiteDomain.value;
						} else {
							strHttpServer = hidSite.value;
						}
					}
            } else {
                strHttpServer = hidSite.value
            }

            var strXmlReturn = objHTTP.responseText;
            strXmlReturn = strXmlReturn.replace("<Response><item>", "");
            strXmlReturn = strXmlReturn.replace("</item></Response>", "");
            strXmlReturn = strXmlReturn.replace('<?xml version="1.0" ?>', '');
            if (strXmlReturn != null && strXmlReturn.length > 0) {

             //  showErrMsg(strXmlReturn);
            }


            if (strXmlReturn.indexOf('Error') > -1) {
                alert("Order failed to save, please confirm everything is correct and try again.");
            } else {
               if (strAddType == "Add") {
						ChangePage(strHttpServer + 'dialogs/aov.aspx?inv=' + inv, qty)
               } else {
						window.location = strHttpServer + 'shopping-cart';
               }
            }
        }
    }

    objHTTP.send(strDataSent);
    } else {
    // Old browsers & IE
    objHTTP.onreadystatechange = function() {
        if (objHTTP.readyState == 4 || objHTTP.readyState == "complete") {

            var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
            var hidSiteDomain = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain')
            var strHttpserver = "";
            if (hidSite == null) {
					if (hidSiteDomain != null) {
						strHttpServer = hidSiteDomain.value;
					} else {
						// Dialogs pages and other non-master pages don't have the placeholder added to clientid
						hidSite = document.getElementById('hidSiteUrl');
						hidSiteDomain = document.getElementById('hidSiteDomain');
						if (hidSite == null) {
							strHttpServer = hidSiteDomain.value;
						} else {
							strHttpServer = hidSite.value;
						}
					}
            } else {
                strHttpServer = hidSite.value
            }

            var strXmlReturn = objHTTP.responseText;
            strXmlReturn = strXmlReturn.replace("<Response><item>", "");
            strXmlReturn = strXmlReturn.replace("</item></Response>", "");
            strXmlReturn = strXmlReturn.replace('<?xml version="1.0" ?>', '');
            if (strXmlReturn != null && strXmlReturn.length > 0) {

            //   showErrMsg(strXmlReturn);
            }

            if (strXmlReturn.indexOf('Error') > -1) {
                alert("Order failed to save, please confirm everything is correct and try again.");
            } else {
               if (strAddType == "Add") {
						ChangePage(strHttpServer + 'dialogs/aov.aspx?inv=' + inv, qty)
               } else {
						window.location = strHttpServer + 'shopping-cart';
               }
            }
        }
    }

    objHTTP.send(strDataSent);
	}

    return blnReturn;
}

/*
 Name             :       ChangePage
 Purpose          :		  Opens or changes a radwindow to specified page
 Author           :       NikZ (Baudville) - 9/9/2009
 */
function ChangePage(FileName, qty, customwidth, customheight, custombehaviours, customtype) 
{
	var destination = "";
	var width = 0;
	var height = 0;
	var modal = 1;
	
	if (customtype == null) {
	    customtype=0;
	}
	
	if (FileName.indexOf("aov") > -1) {
		destination = "aov";
		width = 645;
		height = 600;
	} else if (FileName.indexOf("quickpeek") > -1) {
		destination = "quickpeek";
		width = 440;
		height = 425;
		modal = 0;
    } else if (customtype==1) {
        width = customwidth;
        height = customheight;
        
	} else {
		destination = "pers";
		width = 1000;
		height = 850;
	}

   if (window.frameElement) {
		// A window is already open - Redirect
		var radWnd = GetRadWindow();
		radWnd.SetUrl(FileName);
		
		// Resize & reconfigure the window
		var curWindowSize = radWnd.getWindowBounds();
		radWnd.center();
		radWnd.setSize(width,height);
		radWnd.SetModal(modal);
		
		//Telerik Window Behavior Codes
		//None : 0
		//Resize : 1
		//Minimize : 2
		//Close : 4
		//Pin : 8
		//Maximize : 16
		//Move: 32
		//Reload: 64
		switch (destination) {
			case "aov":
				radWnd.set_behaviors(0 + 4 + 64);
				break;
			case "quickpeek":
				radWnd.set_behaviors(0 + 4 + 32);
				break;
			case "pers":
				radWnd.set_behaviors(0 + 64);
				break;
			default:
			    
			    if (customtype == 1) {
			        radWnd.set_behaviors(custombehaviours);
			    }
				break;
		}		
		radWnd.show();
	} else {
		// No window - open a new one
		openRadWindow(FileName,height,width,modal,0,1,1,qty);
	}
}

 
/*
 Name             :       CloseWindowRedirect
 Purpose          :		  Closes the RadWindow and redirects the parent browser
 Author           :       NikZ (Baudville) - 9/15/2009
 */
function CloseWindowRedirect(strRedirURL)
{
	// If a radwindow is open, close it
	if (window.frameElement) {
		GetRadWindow().close();
	}
	//Redirect parent browser window
	GotoPage(strRedirURL);
}  

/*
 Name             :       GotoPage
 Purpose          :
 Author           :       NikZ (Baudville) - 9/2/2009
 */
function GotoPage(strPage) {
	var hidSite = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteUrl');
   var hidSiteDomain = document.getElementById('ctl00_ContentPlaceHolder1_hidSiteDomain')
   var strHttpserver = "";
   if (hidSite == null) {
		if (hidSiteDomain != null) {
			strHttpServer = hidSiteDomain.value;
		} else {
			// Dialogs pages and other non-master pages don't have the placeholder added to clientid
			hidSite = document.getElementById('hidSiteUrl');
			hidSiteDomain = document.getElementById('hidSiteDomain');
			if (hidSite == null) {
				strHttpServer = hidSiteDomain.value;
			} else {
				strHttpServer = hidSite.value;
			}
		}
   } else {
       strHttpServer = hidSite.value
   }

	top.location.href = strHttpServer + strPage;
}

/*
 Name             :       GetXmlHttpObject
 Purpose          :
 Author           :       JohnD (Baudville) - 7/28/2008
 */
function GetXmlHttpObject() {
    var objXMLHttp = null;
    if (window.XMLHttpRequest) {
        objXMLHttp = new XMLHttpRequest();

    }
    else if (window.ActiveXObject) {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}

/*
 * 		Name			:			validateProductDetails
 * 		Purpose			:			Validates the contents of the product details page
 * 		Author			:			JohnD (Baudviile) - 7/1/2008
 * 		Parameter(s)	:			tbxQ
 */
function validateProductDetails(tbx, ddl, inv, ordhdrid,hidQtyMult) {
    var blnReturn = true;
    var blnError = false;
    var tbxQty = getElementId(tbx);
    var ddlPersonalize = getElementId(ddl);
    var strErrMsg = "";
    if (tbxQty.value.length == 0 || tbxQty.value == 0) {
        strErrMsg += "<br />Quantity";
        blnReturn = false;
        blnError = true;
    } else {
            var intMultiples = getElementId(hidQtyMult).value;

            if (intMultiples > 1) {
                if (parseInt(tbxQty.value) % parseInt(intMultiples) > 0) {
                    strErrMsg += "<br />Item must be ordered in quantities of " + intMultiples + ". Please adjust your quantity.";
                    blnError = true;
                    blnContinue = false;

                }
            } else {
                if (parseInt(tbxQty.value) < intMultiples) {
                    strErrMsg += "<br />Item quantity must be at least " + intMultiples + ". Please adjust your quantity.";
                    blnError = true;
                    blnContinue = false;
                }
            }

        }

    if (ddlPersonalize != null && !blnError) {
        if (ddlPersonalize.selectedValue != "Yes") {
            blnReturn = true;
        }
    }

    if (blnError) {
        radalert(strErrMsg, 300, 100, 'Item Error');
    } else {
        AddStockItem(tbxQty.value, inv, ordhdrid);
    }

    return blnReturn;
}

/*
 * 		Name			:			AddEmailToETList
 * 		Purpose			:			Add the email address to the given exact target list
 * 		Author			:			GregJ (Baudviile) - 1/12/2009
 * 		Parameter(s)	:			txtEmail, ListID
 */
function AddEmailToETList(txtEmail, ListID, divEmail) {
    //var blnReturn = true;
    //var blnError = false;
    
    var strErrMsg = ""; //"The following field(s) are required:<br />";
    
    if(txtEmail)
    {
        var txtEmail = document.getElementById(txtEmail);
        // If the box is empty, we'll add back in our default value
        if (txtEmail.value != '')
        {
            if (validateEmail(txtEmail))
            {
                var xmlHTTP = GetXmlHttpObject();
    	        var szURL = "/dialogs/xmlcallback.aspx?dlg=addemail"
	            var strDataSent = "email=" + txtEmail.value + "&list=" + ListID;
	    
	            xmlHTTP.open("POST", szURL, true);
	            xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xmlHTTP.setRequestHeader("Content-length", strDataSent.length);
                xmlHTTP.setRequestHeader("Connection", "close");
            	
	            xmlHTTP.onreadystatechange = function(){
	                if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete") {
                        var strXmlReturn = xmlHTTP.responseText;
                        strXmlReturn = strXmlReturn.replace("<Response><item>", "");
                        strXmlReturn = strXmlReturn.replace("</item></Response>", "");
                        strXmlReturn = strXmlReturn.replace('<?xml version="1.0" ?>', '');
                        if (strXmlReturn != null) {
                            if (strXmlReturn.length > 0) {
                                //alert(strXmlReturn + "1");
                            }
                        }
                        if (strXmlReturn.indexOf('Error') > - 1) {
                            //set message on page 
                            alert("Your email address was not added to the list.  Please try again later")
                        } else {
                        alert("Your email address was added to the list.")
                            //set message on page
                            if (divEmail) {
                                var divEmailText = document.getElementById(divEmail);
                                if (divEmailText.value != '') {
                                    divEmailText.value = "Your email address has been added."
                                } 
                            } 
                        }
                    }
                }
	            xmlHTTP.send(strDataSent);
            }
            else
            {
                alert("Incorrect email format!")
            }
        }
        else
        {
            alert("Incorrect email format!")
        }
    }
    else
    {
        alert("Incorrect email format!")
    }

    //return blnReturn;
}


/*
 * 		Name			:			showShopingCartTT(trigger)
 * 		Purpose			:			Shows the shopping cart tool tip on the element that the function was called from
 * 		Author			:			Kevin Adam Mitchell (Baudviile) - 10/06/2009
 * 		Parameter(s)	:			trigger - the element that triggered the function
 */
function showShoppingCartTT(trigger)
{
    var tooltip = $find("ctl00_radShoppingCartMainTT");
    if(tooltip != null)
    {   
        tooltip.set_targetControl(trigger);  
        tooltip.show();   
    }
}
