var agt = navigator.userAgent.toLowerCase()
var appVer = navigator.appVersion.toLowerCase()
var is_minor = parseFloat(appVer)
var is_major = parseInt(is_minor)
var is_opera = (agt.indexOf("opera") != -1)
var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1)
var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1)
var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1)
var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1)
var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1)
var is_opera7 = (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1)
var is_opera7up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6)
var is_opera8up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6 && !is_opera7)
var iePos = appVer.indexOf('msie')
if (iePos != -1) {
    is_minor = parseFloat(appVer.substring(iePos + 5, appVer.indexOf(';', iePos)))
    is_major = parseInt(is_minor)
}
var is_konq = false
var kqPos = agt.indexOf('konqueror')
if (kqPos != -1) {
    is_konq = true
    is_minor = parseFloat(agt.substring(kqPos + 10, agt.indexOf(';', kqPos)))
    is_major = parseInt(is_minor)
}
var is_getElementById = (document.getElementById) ? "true" : "false"
var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false"
var is_documentElement = (document.documentElement) ? "true" : "false"
var is_safari = ((agt.indexOf('safari') != -1) && (agt.indexOf('mac') != -1)) ? true : false
var is_khtml = (is_safari || is_konq)
var is_gecko = ((!is_khtml) && (navigator.product) && (navigator.product.toLowerCase() == "gecko")) ? true : false
var is_gver = 0
if (is_gecko)is_gver = navigator.productSub
var is_moz = false
var is_moz_ver = 0
if (is_gecko && (agt.indexOf('netscape') == -1) && (!is_khtml)) {
    is_moz = true
    is_moz_ver = agt.indexOf('rv:')
    is_moz_ver = agt.substring(is_moz_ver + 3)
    is_paren = is_moz_ver.indexOf(')')
    is_moz_ver = is_moz_ver.substring(0, is_paren)
    is_minor = is_moz_ver
    is_major = parseInt(is_moz_ver)
}
var is_nav = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1)
        && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1)
        && (agt.indexOf('webtv') == -1) && (agt.indexOf('hotjava') == -1)
        && (!is_khtml) && (!(is_moz)))
if ((navigator.vendor) && ((navigator.vendor == "Netscape6") || (navigator.vendor == "Netscape")) && (is_nav)) {
    is_major = parseInt(navigator.vendorSub)
    is_minor = parseFloat(navigator.vendorSub)
}
var is_nav2 = (is_nav && (is_major == 2))
var is_nav3 = (is_nav && (is_major == 3))
var is_nav4 = (is_nav && (is_major == 4))
var is_nav4up = (is_nav && is_minor >= 4)
var is_navonly = (is_nav && ((agt.indexOf(";nav") != -1) ||
                             (agt.indexOf("; nav") != -1)))
var is_nav6 = (is_nav && is_major == 6)
var is_nav6up = (is_nav && is_minor >= 6)
var is_nav5 = (is_nav && is_major == 5 && !is_nav6)
var is_nav5up = (is_nav && is_minor >= 5)
var is_nav7 = (is_nav && is_major == 7)
var is_nav7up = (is_nav && is_minor >= 7)
var is_ie = ((iePos != -1) && (!is_opera) && (!is_khtml))
var is_ie3 = (is_ie && (is_major < 4))
var is_ie4 = (is_ie && is_major == 4)
var is_ie4up = (is_ie && is_minor >= 4)
var is_ie5 = (is_ie && is_major == 5)
var is_ie5up = (is_ie && is_minor >= 5)
var is_ie5_5 = (is_ie && (agt.indexOf("msie 5.5") != -1))
var is_ie5_5up = (is_ie && is_minor >= 5.5)
var is_ie6 = (is_ie && is_major == 6)
var is_ie6up = (is_ie && is_minor >= 6)
var is_ie7 = (is_ie && is_major == 7)
var is_ie7up = (is_ie && is_minor >= 7)
function hideElement() {
    var el = document.getElementById(arguments[0])
    if(!el) {
       return;
    }
    var state
    var IEfix = false
    if (arguments.length == 1)state = 2
    else if (arguments.length > 1)state = arguments[1]
    if (arguments.length > 2)IEfix = arguments[2]
    if (state == 1)el.style.display = "block"
    else if (state == 6)el.style.display = "inline"
    else if (state == 0)el.style.display = "none"
    else if (state == 3)el.style.visibility = "hidden"
    else if (state == 4)el.style.visibility = "visible"
    else if (state == 2) {
        if (el.style.display == "none" || el.style.display == "")el.style.display = "block"
        else el.style.display = "none"
    } else if (state == 5) {
        if (el.style.visibility == "hidden" || el.style.visibility == "")el.style.visibility = "visible"
        else el.style.visibility = "hidden"
    }
    if (IEfix)hideShowCovered(el)
}
function changeClass(id, newClass) {
    if (is_ie4) {
        id.className = newClass
    } else if (is_nav4) {
        whichEl = eval("document." + id)
        whichEl.className = newClass
    } else if (document.getElementById(id)) {
        document.getElementById(id).className = newClass
    } else {
        return false
    }
}
function swapImage(id, newImage) {
    if (is_ie4) {
        id.src = newImage
    } else if (is_nav4) {
        whichEl = eval("document." + id)
        whichEl.src = newImage
    } else {
        document.getElementById(id).src = newImage
    }
}
function swapTab(id, newImage) {
	document.getElementById(id).style.backgroundImage = "url("+newImage+")";
}

function MM_findObj(n, d) {
    var p,i,x;
    if (!d)d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p)
    }
    if (!(x = d[n]) && d.all)x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++)x = d.forms[i][n]
    for (i = 0; !x && d.layers && i < d.layers.length; i++)x = MM_findObj(n, d.layers[i].document)
    if (!x && d.getElementById)x = d.getElementById(n);
    return x
}
function MM_swapImage() {
    var i,j = 0,x,a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc)x.oSrc = x.src;
            x.src = a[i + 2]
        }
}
function MM_swapImgRestore() {
    var i,x,a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)x.src = x.oSrc
}
function MM_preloadImages() {
    var d = document;
    if (d.images) {
        if (!d.MM_p)d.MM_p = new Array()
        var i,j = d.MM_p.length,a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i]
            }
    }
}
function MM_goToURL() {
    var i,args = MM_goToURL.arguments;
    document.MM_returnValue = false
    for (i = 0; i < (args.length - 1); i += 2)eval(args[i] + ".location='" + args[i + 1] + "'")
}
function MM_closeBrWindow(theURL, winName, features) {
    window.close(theURL, winName, features)
}
function MM_openBrWindow(theURL, winName, features) {
    window.open(theURL, winName, features)
}
function getexpirydate(nodays) {
    var UTCstring
    Today = new Date()
    nomilli = Date.parse(Today)
    Today.setTime(nomilli + nodays * 24 * 60 * 60 * 1000)
    UTCstring = Today.toUTCString()
    return UTCstring
}
function getcookie(cookiename) {
    var cookiestring = "" + document.cookie
    var index1 = cookiestring.indexOf(cookiename)
    if (index1 == -1 || cookiename == "")return ""
    var index2 = cookiestring.indexOf(';', index1)
    if (index2 == -1)index2 = cookiestring.length
    return unescape(cookiestring.substring(index1 + cookiename.length + 1, index2))
}
function setexpiringcookie(name, value, domain, expires) {
    var expire = new Date()
    expire.setTime(expire.getTime() + 60000 * expires)
    cookiestring = name + "=" + escape(value) + ";domain=" + escape(domain) + ";expires=" + expire.toGMTString() + ";path=/"
    document.cookie = cookiestring
    if (!getcookie(name)) {
        return false
    } else {
        return true
    }
}
function setcookie(name, value, domain) {
    cookiestring = name + "=" + escape(value) + ";path=/"
    if (domain && domain != '') {
        cookiestring = cookiestring + ";domain=" + escape(domain)
    }
    document.cookie = cookiestring
    if (!getcookie(name)) {
        return false
    } else {
        return true
    }
}
function getHost() {
    hostname = new String(document.location)
    return cleanName(hostname)
}
function cleanName(hostname) {
    var index = hostname.indexOf('http://')
    if (index != -1) {
        hostname = hostname.substring(7, hostname.length)
    } else {
        index = hostname.indexOf('https://')
        if (index != -1) {
            hostname = hostname.substring(8, hostname.length)
        }
    }
    index = hostname.indexOf('/')
    if (index != -1) {
        hostname = hostname.substring(0, index)
    }
    index = hostname.indexOf(':')
    if (index != -1) {
        hostname = hostname.substring(0, index)
    }
	var bcsite = hostname.substring(3,4);
	if (hostname.substring(0,3) == 'www')
	{
	   if(!isNaN(bcsite))
	   {
		  hostname = hostname.substring(4,hostname.length);
	   }
	   else
	   {
		  hostname = hostname.substring(3,hostname.length);
	   }
	}
    return hostname
}
function getReferrer() {
    return cleanName(document.referrer)
}
function getArgs() {
    var args = new Object()
    var query = location.search.substring(1)
    var pairs = query.split("&")
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=')
        if (pos == -1)continue
        var argname = pairs[i].substring(0, pos)
        var value = pairs[i].substring(pos + 1)
        args[argname] = unescape(value)
    }
    return args
}
function maxlength_js(obj, maxlength) {
    if (navigator.userAgent.indexOf('Netscape6') != -1) {
        return
    }
    if (obj.value.length >= maxlength) {
        obj.value = obj.value.slice(0, maxlength)
    }
}
function waitForObject(element, func) {
    if (func == false) {
        return false
    }
    if (document.getElementById(element)) {
        eval(func)
    } else {
        setTimeout("waitForObject(\"" + element + "\", \"" + func + "\")", 5)
    }
}
function domOpenXMLDocAAAPI(url, processReqChange) {
    var theDate = new Date().getTime();
    var argv = domOpenXMLDocAAAPI.arguments;
    var argc = domOpenXMLDocAAAPI.arguments.length;
    var httpMethod = (argc > 2) ? argv[2] : 'GET'; // i think this was supposed to be if there are too many arguments use the POST method instead
    var data = ((argc > 3) ? argv[3] : null);
/*	if (url.indexOf('?') == -1) {
		url += "?"
	} else {
		url += "&"
	}
*/    var req
	if (window.ActiveXObject)
	{
		req = null
        req = new ActiveXObject("Microsoft.XMLHTTP")
        if (req) {
            req.onreadystatechange = processReqChange
            req.open(httpMethod, url, true)
            if (httpMethod = "GET") {
                req.send(data)
            } else {
                alert("utils.js @ line 299 wants you to know that\nhttpMethod(" + httpMethod + ") != \"GET\"");
            }
        }
    } 
    else if (window.XMLHttpRequest)
	{
        req = new XMLHttpRequest()
        if (req.overrideMimeType) {
            req.overrideMimeType('text/xml')
        }
        req.onreadystatechange = processReqChange
        req.open(httpMethod, url, true)
        if (httpMethod = "GET") {
            req.send(data);
        } else {
            alert("utils.js @ line 310 wants you to know that\nhttpMethod(" + httpMethod + ") != \"GET\"");
        }
    } 
	else
	{
        req = null
    }
    return req
}
function domOpenXMLDoc(url, processReqChange) {
    var theDate = new Date().getTime()
    var argv = domOpenXMLDoc.arguments
    var argc = domOpenXMLDoc.arguments.length
    var httpMethod = (argc > 2) ? argv[2] : 'GET'
    var data = (argc > 3) ? argv[3] : null
    if (url.indexOf('?') == -1) {
        url += "?"
    } else {
        url += "&"
    }
    var req
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest()
        if (req.overrideMimeType) {
            req.overrideMimeType('text/xml')
        }
        req.onreadystatechange = processReqChange
        req.open(httpMethod, url, true)
        if (httpMethod = "POST") {
            req.send(data)
        }
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP")
        if (req) {
            req.onreadystatechange = processReqChange
            req.open(httpMethod, url, true)
            if (httpMethod = "POST") {
                req.send(data)
            }
        }
    } else {
        req = null
    }
    return req
}
function domSetInnerHTML(obj, html_string) {
    if (obj.innerHTML != null) {
        obj.innerHTML = html_string
    } else if (document.createRange) {
        var rng = document.createRange()
        if (rng.setStartBefore && rng.createContextualFragment &&
            obj.removeChild && obj.appendChild) {
            rng.setStartBefore(obj)
            htmlFrag = rng.createContextualFragment(content)
            while (obj.hasChildNodes())
                obj.removeChild(obj.lastChild)
            obj.appendChild(htmlFrag)
        }
    } else if (obj.document != null && obj.document.open != null) {
        obj.document.open()
        obj.document.write(html_string)
        obj.document.close()
    }
}
function domGetInnerHTML(obj) {
    if (obj.innerHTML) {
        return obj.innerHTML
    }
}
function domGetWindowWidth() {
    if (window.innerWidth != null)
        return window.innerWidth
    else if (document.documentElement &&
             document.documentElement.clientWidth)
        return document.documentElement.clientWidth
    else if (document.body != null)
        return document.body.clientWidth
    else
        return document.body.offsetWidth
}
function domGetWindowHeight() {
    if (window.innerHeight != null)
        return window.innerHeight
    else if (document.documentElement &&
             document.documentElement.clientHeight)
        return document.documentElement.clientHeight
    else if (document.body != null)
        return document.body.clientHeight
    else
        return document.body.offsetHeight
}
function altSwap(altImage, state) {
    var myProduct
    if (currentProduct == '')myProduct = currentProductBase
    else myProduct = currentProduct
    if (state == 1) {
        currentProductSrc = document.getElementById(myProduct + '_image').src
        swapImage(myProduct + '_image', '/kernel/imageload?table=cat_images;key1=' + altImage)
    } else {
        swapImage(myProduct + '_image', currentProductSrc)
    }
}
function toggleField(selectName, fieldValue, fieldIdOne, fieldIdTwo) {
    var index = document.getElementById(selectName).selectedIndex
    var person = document.getElementById(selectName).options[index]
    if (person.value == fieldValue) {
        hideElement(fieldIdOne, 1)
        if (fieldIdTwo) {
            document.getElementById(fieldIdTwo).value = ' '
            hideElement(fieldIdTwo, 1)
        }
    } else {
        hideElement(fieldIdOne, 0)
        if (fieldIdTwo) {
            hideElement(fieldIdTwo, 0)
        }
    }
}
var list_of_addresses
var address_keyvalpair
var addressList = getcookie('vr_address_list').replace(/\%20/g, ' ')
var address_url
var address_xmlhttp
function getAddressIndex(address_wanted) {
    var address_index
    if (addressList != "" && list_of_addresses != null) {
        for (var i = 0; i < list_of_addresses.length; i++) {
            address_keyvalpair = list_of_addresses[i].split(":")
            if (address_keyvalpair[0] == address_wanted) {
                address_index = i
            }
        }
    }
    return address_index
}
function prepopulateZip(recipientField_id, zip_id, name_id, skip_id) {
    var index = document.getElementById(recipientField_id).selectedIndex
    var address = document.getElementById(recipientField_id).options[index]
    if (document.getElementById(zip_id)) {
        if ((address.value != -1) && (address.value)) {
            var address_index = getAddressIndex(address.value)
            if (address_index != 'undefined') {
                var found_address = list_of_addresses[address_index].split(":")
                if (found_address[4]) {
                    document.getElementById(zip_id).value = unescape(found_address[4])
                } else {
                    document.getElementById(zip_id).value = ''
                }
                if (document.getElementById(name_id)) {
                    document.getElementById(name_id).value = unescape(found_address[0])
                }
                if (document.getElementById(skip_id)) {
                    if (unescape(found_address[6]) == 1) {
                        document.getElementById(skip_id).checked = true
                    } else {
                        document.getElementById(skip_id).checked = false
                    }
                }
            } else {
                document.getElementById(zip_id).value = ''
            }
        } else {
            document.getElementById(zip_id).value = ''
            if (document.getElementById(name_id)) {
                document.getElementById(name_id).value = ''
            }
            if (document.getElementById(skip_id)) {
                document.getElementById(skip_id).checked = false
            }
        }
    }
}
function setHiddenValue(fieldName, address_id, hiddenFieldName) {
    var dynamicField = fieldName + "_" + address_id
    if (document.getElementById(dynamicField)) {
        var field = document.getElementById(dynamicField)
        if (document.getElementById(hiddenFieldName)) {
            document.getElementById(hiddenFieldName).value = field.options[field.selectedIndex].value
        }
    }
}
function populateTown(town_id, fieldName) {
    var field
    var selected = 0
    if (document.getElementById(fieldName)) {
        field = document.getElementById(fieldName)
        for (var i = 0; i < field.options.length; i++) {
            if (field.options[i].value == town_id) {
                selected = i
            }
        }
        if (selected == 0) {
            return false
        } else {
            field.selectedIndex = selected
			aaapi_array["cal"]["aa_town"] = field[field.selectedIndex].text;
        }
    } else {
        return false
    }
}
function fillText(recipient_id, field_id, arrayNumber) {
    if (document.getElementById(field_id)) {
        var value
        var address_index = getAddressIndex(recipient_id)
        if (address_index && address_index != 'undefined') {
            var found_address = list_of_addresses[address_index].split(":")
            value = unescape(found_address[arrayNumber])
        }
        if (value && value != 'undefined') {
            document.getElementById(field_id).value = value
        } else {
            document.getElementById(field_id).value = ""
        }
    }
}
var getIdSuffix = function(theID) {
	//set a hidden input value to the cart id
	document.getElementById('tempCartId').value = theID;
}

var xmlhttpRule
var urlRule
var sendToAAAPI = function(queryString, theID) {
	var ruleIdArray = new Array()
	xmlhttpRule = undefined;
	var theDate = new Date().getTime();
	var urlPrefix;
	if(location.pathname.match(/(\/product\/|\/category\/)/)){
		urlPrefix = '/catalog/';
	}
	else if(location.pathname.match(/(\/product2\/|\/category2\/)/)){
		urlPrefix = '/catalog2/';
	}
	else{
		urlPrefix = '';
	}	
	var urlRule = urlPrefix + 'aa_check.xml'+'?price=' + queryString + '&' + theDate;
	xmlhttpRule = domOpenXMLDocAAAPI(urlRule, xmlhttpChangeAAAPI);
	getIdSuffix(theID);
	return false;
}
var url
var xmlhttp
var townSelectName
var tabIndex
function loadTownXML(county_id, selectName, country_id, tabindex) {
    var townArray = new Array()
    var theDate = new Date().getTime()
    var urlPrefix;
    xmlhttp = undefined
    tabIndex = tabindex
    if(location.pathname.match(/(\/product\/|\/category\/)/)){
    	urlPrefix = '/catalog/';
    }
    else if(location.pathname.match(/(\/product2\/|\/category2\/)/)){
    	urlPrefix = '/catalog2/';
    }
    else{
    	urlPrefix = '';
    }
    if (selectName && selectName != 'undefined') {
        townSelectName = selectName
    }
    if ((county_id) && (county_id > 0) && (county_id != 'undefined')) {
        url = urlPrefix +'location.xml?county_id=' + county_id + '&' + 'country_id=' + country_id + '&' + theDate
        xmlhttp = domOpenXMLDoc(url, xmlhttpChange)
    } else {
        if (townSelectName && townSelectName != 'undefined') {
            setDynamicSelect(townSelectName, townArray, "townCell", 0)
        } else {
            setDynamicSelect('town_id', townArray, "townCell", 0)
        }
    }
    return false
}
function xmlhttpChange() {
    var townArray = new Array()
    var districtArray = new Array()
    if (xmlhttp && xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            var result
            if (window.ActiveXObject) {
                result = new ActiveXObject("Microsoft.XMLDOM")
                result.loadXML(xmlhttp.responseText)
            } else {
                result = xmlhttp.responseXML
            }
            if (document.getElementById("townCell")) {
                populateArray(result, townArray, "town", "name", "town_id")
                if (townSelectName && townSelectName != 'undefined') {
                    setDynamicSelect(townSelectName, townArray, "townCell", 0)
                } else {
                    setDynamicSelect('town_id', townArray, "townCell", 0)
                }
            }
        } else {
        }
    }
}
function xmlhttpChangeAAAPI() {
	var ruleIdArray = new Array()
    if (xmlhttpRule && xmlhttpRule.readyState == 4) {
        if (xmlhttpRule.status == 200) {
            var result
            if (window.ActiveXObject) {
                result = new ActiveXObject("Microsoft.XMLDOM")
                result.loadXML(xmlhttpRule.responseText)
            } else {
                result = xmlhttpRule.responseXML
            }
			populateArray(result, ruleIdArray, "option", "name", "value")
			setDynamicRules('avail_rules', ruleIdArray, "ruleCell", 0)
        } 
    } 
}
function grabCurrentDateTime(country, cf_ind, weight, from_date, to_date, nodel_from, nodel_to, same_day) {
    xmlhttp = undefined
    var theDate = new Date().getTime()
    url = 'datetime.xml?country=' + country + ';cf_ind=' + cf_ind + ';weight=' + weight + ';from_date=' + from_date + ';to_date=' + to_date + ';nodel_from=' + nodel_from + ';nodel_to=' + nodel_to + ';same_day=' + same_day + ';' + theDate
    xmlhttp = domOpenXMLDoc(url, xmlhttpDateTime)
    return false
}
function xmlhttpDateTime() {
    if (xmlhttp && xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            var result
            if (window.ActiveXObject) {
                result = new ActiveXObject("Microsoft.XMLDOM")
                result.loadXML(xmlhttp.responseText)
            } else {
                result = xmlhttp.responseXML
            }
            var start_year = result.getElementsByTagName("start_year")[0].firstChild.nodeValue
            var end_year = result.getElementsByTagName("end_year")[0].firstChild.nodeValue
            var earliest_date = result.getElementsByTagName("earliest_date")[0].firstChild.nodeValue
            var same_day = result.getElementsByTagName("same_day")[0].firstChild.nodeValue
            var today = result.getElementsByTagName("today")[0].firstChild.nodeValue
            window.calendar.setRange(start_year, end_year)
            window.calendar.earliest_date = new Date(earliest_date)
            window.calendar.same_day = same_day
            window.calendar.today = today
            earliest_date = new Date(earliest_date)
            if (earliest_date.getTime() > window.calendar.date.getTime()) {
                window.calendar.date = earliest_date
            }
            window.calendar.refresh()
        }
    }
}
function populateArray(result, arrayName, tagone, tagtwo, tagthree) {
    var options = result.getElementsByTagName(tagone)
    for (i = 0; i < options.length; i++) {
        var name = options[i].getElementsByTagName(tagtwo)[0].firstChild.nodeValue
        var value = options[i].getElementsByTagName(tagthree)[0].firstChild.nodeValue
        arrayName[name] = value
    }
}
var referring_url_required = getcookie("referring_url_required")
var current_page_name = document.URL.match(/access_deny\.html/)
if ((referring_url_required != "") && (current_page_name != "access_deny.html")) {
    var referring_url_ok = getcookie("referring_url_ok")
    if ((referring_url_ok == "") || (referring_url_ok == 0)) {
        referring_url_ok = getReferrer().indexOf(referring_url_required)
        if (referring_url_ok == -1) {
            referring_url_ok = 0
        } else {
            referring_url_ok = 1
        }
        setcookie("referring_url_ok", referring_url_ok, "")
    }
    if (referring_url_ok == 0) {
        document.location.href = "/access_deny.html"
    }
}
var entry_page = getcookie("entry_page")
if (entry_page == '') {
    ref = String(document.location)
    host = getHost()
    setcookie('entry_page', ref, host)
}
var user = getcookie('vr_user_fname').replace(/\+/g, ' ')
user = user.replace(/\</g, '&lt;');
user = user.replace(/\>/g, '&gt;');
user = user.replace(/\"/g, '&quot;');
user = user.replace(/\'/g, '&#39;');
user = user.replace(/\(/g, '&#40;');
user = user.replace(/\)/g, '&#41;');
user = user.replace(/\%/g, '&#37;');
user = user.replace(/\+/g, '&#43;');
user = user.replace(/\-/g, '&#45;');
var delay_hide = 250
var openMenu = null
function resetDelay() {
    if (openMenu != null)delayhide = setTimeout("switchMenu(openMenu)", delay_hide)
}
function clear_delayhide() {
    if (window.delayhide)clearTimeout(delayhide)
}
function switchMenu() {
    var whichEl = "globalTabMenu" + arguments[0]
    var myTab = arguments[1] ? document.getElementById('tab_' + arguments[1]) : false
    clear_delayhide()
    if (openMenu != null) {
        hideElement("globalTabMenu" + openMenu, 0, true)
    }
    if (openMenu == arguments[0]) {
        openMenu = null
    } else if (document.getElementById(whichEl)) {
        if (myTab) {
            var elStyle = document.getElementById(whichEl).style
            elStyle.top = (getAbsolutePos(myTab).y + (is_ie ? 31 : 31)) + "px"
            elStyle.left = (getAbsolutePos(myTab).x) + "px"
        }
        hideElement(whichEl, 2, true)
        openMenu = arguments[0]
    } else {
        alert('no menu found ' + arguments[0])
    }
}
function swapTab(id, newImage) {
	document.getElementById(id).style.backgroundImage = "url("+newImage+")";
}
//new code for the new top nav menu
// Copyright 2006-2007 javascript-array.com 
//(altered)
var timeout    = 1;
var closetimer    = 0;
var ddmenuitem    = 0;
// open hidden layer
function mopen(id,key,img,width,height)
{
    var myTab = arguments[1] ? document.getElementById('tab_' + arguments[1]) : false
    // cancel close timer
    mcancelclosetime();
    // close old layer
    if(ddmenuitem) ddmenuitem.style.display = 'none';
    // get new layer and show it
    ddmenuitem = document.getElementById(id);
    ddmenuitem.style.display = 'block';
    myTab.style.backgroundImage = "url("+arguments[2]+")";
    var elStyle = document.getElementById(id).style
	var theHeight = parseFloat(height)
	elStyle.top = (getAbsolutePos(myTab).y + (is_ie ? theHeight : theHeight)) + "px"
    elStyle.left = (getAbsolutePos(myTab).x) + "px"
	//test for IE versions - IE6 must have a width plus nowrap whitespace, IE7 and FF act the same with a min-width and a nowrap whitespace
	var isIE = (navigator.appName=="Microsoft Internet Explorer");
	var IEversion = navigator.appVersion;
	if(isIE) {IEversion = parseInt(IEversion.substr(IEversion.indexOf("MSIE")+4));}
	else {IEversion = 0;}
	if(IEversion==6){elStyle.width = width + "px"}
	else if(IEversion==7){elStyle.minWidth = width + "px"}
    else {elStyle.minWidth = width + "px"}
}
// close showed layer (internal function)
function mclose()
{
    if(ddmenuitem) ddmenuitem.style.display = 'none';
}
// go close timer
function mclosetime()
{
    closetimer = window.setTimeout(mclose, timeout);
}
// cancel close timer
function mcancelclosetimewithparams(tab, img)
{
    document.getElementById(tab).style.backgroundImage = "url("+img+")";
    if(closetimer)
    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}
function mcancelclosetime()
{
    if(closetimer)
    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}
//end new code for new top nav menu

function getAbsolutePos(el) {
    var SL = 0,ST = 0
    var is_div = /^div$/i.test(el.tagName)
    if (is_div && el.scrollLeft)
        SL = el.scrollLeft
    if (is_div && el.scrollTop)
        ST = el.scrollTop
    var r = {x:el.offsetLeft - SL,y:el.offsetTop - ST}
    if (el.offsetParent) {
        var tmp = this.getAbsolutePos(el.offsetParent)
        r.x += tmp.x
        r.y += tmp.y
    }
    return r
}
function fixPosition(box) {
    if (box.x < 0)box.x = 0
    if (box.y < 0)box.y = 0
    var cp = document.createElement("div")
    var s = cp.style
    s.position = "absolute"
    s.right = s.bottom = s.width = s.height = "0px"
    document.body.appendChild(cp)
    var br = getAbsolutePos(cp)
    document.body.removeChild(cp)
    var Y = is_ie ? document.body.scrollTop : window.scrollY
    var X = is_ie ? document.body.scrollLeft : window.scrollX
    br.y += Y
    br.x += X
    var tmp = box.x + box.width - br.x
    if (tmp > 0)box.x -= tmp
    else if (box.x < X)box.x = X + 10
    else if (is_ie)box.x += 30
    tmp = box.y + box.height - br.y
    if (tmp > 0)box.y -= tmp
    else if (box.y < Y)box.y = Y + 10
    else if (is_ie)box.y += 30
    return box
}
function posElement() {
    var trig = document.getElementById(arguments[0])
    var p = getAbsolutePos(trig)
    var el = document.getElementById(arguments[1])
    var s = el.style
    p.x += (trig.offsetWidth - el.offsetWidth) / 2
    p.y += (trig.offsetHeight - el.offsetHeight) / 2
    p = fixPosition(p)
    s.top = p.y + 'px'
    s.left = p.x + 'px'
    hideShowCovered(el)
}
function hideShowCovered(el) {
    if (!is_ie && !is_opera)
        return
    function getVisib(obj) {
        var value = obj.style.visibility
        if (!value) {
            if (document.defaultView && typeof(document.defaultView.getComputedStyle) == "function") {
                if (!is_khtml)
                    value = document.defaultView.
                            getComputedStyle(obj, "").getPropertyValue("visibility")
                else
                    value = ''
            } else if (obj.currentStyle) {
                value = obj.currentStyle.visibility
            } else
                value = ''
        }
        return value
    }
    var tags = new Array("applet", "iframe", "select")
    var p = getAbsolutePos(el)
    var EX1 = p.x
    var EX2 = el.offsetWidth + EX1
    var EY1 = p.y
    var EY2 = el.offsetHeight + EY1
    for (var k = tags.length; k > 0;) {
        var ar = document.getElementsByTagName(tags[ --k])
        var cc = null
        for (var i = ar.length; i > 0;) {
            cc = ar[ --i]
            p = getAbsolutePos(cc)
            var CX1 = p.x
            var CX2 = cc.offsetWidth + CX1
            var CY1 = p.y
            var CY2 = cc.offsetHeight + CY1
            if (el.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
                if (!cc.__msh_save_visibility) {
                    cc.__msh_save_visibility = getVisib(cc)
                }
                cc.style.visibility = cc.__msh_save_visibility
            } else {
                if (!cc.__msh_save_visibility) {
                    cc.__msh_save_visibility = getVisib(cc)
                }
                cc.style.visibility = "hidden"
            }
        }
    }
}
function positionElementAtEvent(evt, elemId, xOffset, yOffset) {
    var elem = document.getElementById(elemId)
    if (!evt)var evt = window.event
    var x =
            (xOffset ? new Number(xOffset) : 0)
                    + (evt.pageX ? evt.pageX : (
                    evt.clientX ? evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : 0
                    )
                    )
    var y =
            (yOffset ? new Number(yOffset) : 0)
                    + (evt.pageY ? evt.pageY : (
                    evt.clientY ? evt.clientY + document.body.scrollTop + document.documentElement.scrollTop : 0
                    )
                    )
    elem.style.left = new String(x + 'px')
    elem.style.top = new String(y + 'px')
}

/* ****************************************************************************** *\
    IE hack to add an Array.push() method
\* ****************************************************************************** */
if (document.all && !window.opera) Array.prototype.push = function () {
    if (arguments.length < 1) return false;
    var len = this.length;
    for (var i = 0; i < arguments.length; i++) this[len++] = arguments[i];
};
/* ****************************************************************************** */

/* ****************************************************************************** */
var Utils = new Function ();
/* ****************************************************************************** */
    Utils.replaceText = function (id, new_text) { // more XHTML compatible than .innerHTML=
        var elem = document.getElementById(id);
        if (!elem) return;
        while ( elem.firstChild ) elem.removeChild( elem.firstChild );
        elem.appendChild( document.createTextNode( new_text ) );
    };
    Utils.getElementsById = function (elemIdsList) {
        var elemList = [];
        for (var i = 0; i < elemIdsList.length; i++) {
            elemList[i] = document.getElementById( elemIdsList[i] );
        }
        return elemList;
    };
    Utils.disableFormElements = function (elemList, bool) {
        for (var i = 0; i < elemList.length; i++) {
            if (bool) elemList[i].disabled = false;
            else elemList[i].disabled = true;
        }
    };
    Utils.httpReq = function (uri, srcDispatchTable, argsHash, method, sync) {
        /*
            --- REQUIRED ---
            uri                 : an http universal resource indicator
            srcDispatchTable    : a hashref of function references keyed by http server response code
                                  - default key 'success' fires on server response codes 200 & 304

            --- OPTIONAL ---
            argsHash            : a hashref of GET/POST parameters to be sent with the request
            method              : a string indicating http request type ('GET', 'POST', 'HEAD', etc).
            sync                : boolean: true == synchronous http req; false == asynchronous http req
        */
        if (!uri || !srcDispatchTable) return false;
        if (!method) method = 'GET';
        var queryString = new Array ();
        if (argsHash) {
            for (var key in argsHash) queryString.push( escape(key) +'='+ escape( argsHash[key] ) );
        }
        if (method == 'GET') {
            uri += ( /\?/.test(uri) ) ?  '&' : '?';
            uri += queryString.join('&');
        }
        var req;
        if (window.XMLHttpRequest) req = new XMLHttpRequest();
        else if (window.ActiveXObject) req = new ActiveXObject('Microsoft.XMLHTTP');
        req.open( method, uri, sync ? false : true );
        var execCallBack = function (req) {
            if ( // 304 == "Not Modified" (ie. use cached version)
                (req.status == 200 || req.status == 304)
                && srcDispatchTable['success']
            ) {
                srcDispatchTable['success']( req );
            } else if ( srcDispatchTable[ req.status ] ) {
                srcDispatchTable[ req.status ]( req );
            }
        };
        req.onreadystatechange = function () {
            if (req.readyState == 4) execCallBack(req);
        };
        if ( method == 'POST' ) {
            queryString = queryString.join('&');
            req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            req.setRequestHeader('Content-length', queryString.length);
            req.setRequestHeader('Connection', 'close');
            req.send( queryString );
        } else {
            req.send( null );
        }
        if (sync) execCallBack(req);
    };
    Utils.require = function (uri) { // similar to Perl's require() function
        this.httpReq(
            uri,
            {
                success: function (req) {
                    if (req && req.responseText) eval( req.responseText );
                }
            }
        );
    };
    Utils.money = function (number) { // returns a String()
        number = new Number (number);
        number = Math.round( number * 100 ) / 100;
        number = new String (number);
        if ( /\.\d\d$/.test(number) ) return number;
        else if ( /\.\d$/.test(number) ) return number +'0';
        else if ( !/\./.test(number) ) return number +'.00';
        else return false;
    };
/* ****************************************************************************** */

/* ****************************************************************************** */
var Diag = new Function ();
/* ****************************************************************************** */
    Diag.objToString = function(obj) {
        var string = new String ();
        for (var key in obj) {
            string += key +': '+ obj[key] +"\n";
        }
        return string;
    };
    Diag.objToHtml = function(obj) {
        var html = new String ();
        for (var key in obj) {
            html += '<font color=red>'+ key +'</font>: <font color=green>'+ obj[key] +'</font><br />';
        }
        return html;
    };
    Diag.objToLayer = function(obj) {
        if (!this.debugLayer) {
            var _debug = document.createElement('DIV');
            _debug.setAttribute('id','debug_layer');
            _debug.setAttribute('name','debug_layer');
            document.getElementsByTagName('BODY')[0].appendChild(_debug);
            this.debugLayer = document.getElementById('debug_layer');
            this.debugLayer.style.border = '1px solid blue';
            this.debugLayer.style.backgroundColor = '#d0d0d0';
            this.debugLayer.style.padding = '4px 4px 4px 4px';
            this.debugLayer.style.overflow = 'scroll';
            this.debugLayer.style.top = '4px';
            this.debugLayer.style.left = '4px';
            this.debugLayer.innerHTML = '<pre id=debug_pre></pre>';
            this.debugPre = document.getElementById('debug_layer');
        }
        if (this.debugPre.innerHTML) {
            this.debugPre.innerHTML = this.objToHtml(obj);
        } else {
            this.debugPre.innerHTML += '--------------------------------------------------------------------------------'
                +"\n"+ this.objToHtml(obj);
        }
        return this.debugPre;
    };
/* ****************************************************************************** */

/* ****************************************************************************** */
var CSS = function () {}; // package namespace for CSS specific functions
/* ****************************************************************************** */
    CSS.cssToJsStyle = function (style) {
        var _style = style.split(/-/);
        for (var i = 1; i < _style.length; i++) {
            var strings = _style[i].match(/^(.)(.*)$/);
            _style[i] = strings[1].toUpperCase() + strings[2].toLowerCase();
        }
        style = _style.join('');
        return style;
    };
    CSS.jsToCssStyle = function (style) {
        style = style.replace(/[A-Z]/g, "-$&");
        style = style.toLowerCase();
        return style;
    };
    CSS.getNumericStyle = function (elem, style) { // Opera & IE do not add border size to offsetWidth or offsetHeight
        var value = new Number (0);
        if (document.all) { // IE & Opera
            var _value;
            if (elem.currentStyle) { // IE
                style = ( /-/.test(style) ) ? this.cssToJsStyle(style) : style;
                if ( elem.currentStyle[style] )
                    _value = elem.currentStyle[style];
            } else if (elem.getComputedStyle) { // Opera .. (does not work unless the style is explicitely preset)
                style = ( /-/.test(style) ) ? style : this.jsToCssStyle(style);
                if ( document.defaultView.getComputedStyle(elem, null).getPropertyValue(style) )
                    _value = document.defaultView.getComputedStyle(elem, null).getPropertyValue(style);
            }
            if (_value) _value = _value.replace(/\D/g, ''); // strip off any increment type suffix
            if (_value && _value != '') value += _value;
        }
        // numeric type cast
        return new Number (value);
    };
    CSS.getElemWidthHeight = function (id) {
        var elem = document.getElementById(id);
        var wh = new Array ( elem.offsetWidth, elem.offsetHeight );
        if (document.all) { // IE & Opera
            wh[0] += this.getNumericStyle(elem, 'border-right-width');
            wh[0] += this.getNumericStyle(elem, 'border-left-width');
            wh[1] += this.getNumericStyle(elem, 'border-top-width');
            wh[1] += this.getNumericStyle(elem, 'border-bottom-width');
        }
        return wh;
    };
/* ****************************************************************************** */

/* ****************************************************************************** *\
    The following Exec package is Free Software released by sourcery.ca
    to the Toronto Perl Mongers on Feb 3, 2006
\* ****************************************************************************** */
var Exec = new Function ();
var theBrowser = navigator.userAgent.toLowerCase();
/* ****************************************************************************** */
    Exec.onLoad = function (strCallback, agressive) {
        if (!strCallback) return;
        var funcRef;
        if (window.onload) {
            var onLoad = window.onload;
            if(theBrowser.indexOf("safari") != -1)
            {
                if (agressive) funcRef = function () { strCallback; onLoad() };
                else funcRef = function () { onLoad(); strCallback };
            }
            else
            {
                if (agressive) funcRef = function () { eval(strCallback); onLoad() };
                else funcRef = function () { onLoad(); eval(strCallback) };
            }
        } else {
            if(theBrowser.indexOf("safari") != -1)
            {
                funcRef = function () { strCallback };
            }
            else
            {
                funcRef = function () { eval(strCallback) };
            }
        }
        window.onload = funcRef;
    };
        Exec.onTimer = function (strCallback, n, t, d) {
        /*
            n = number of times to execute per iteration
            t = iteration time in seconds
            d = total duration to execute
            ie. alert('hello world') 5 times per 1 second for 2 seconds
                Exec.onTimer('alert("hello world")', 5, 1, 2);
        */
        if (!strCallback) return;
        if (!n) n = 1;
        if (!t) t = 1000;
        else t *= 1000;
        if (!d) d = 1000;
        else d *= 1000;
        if(theBrowser.indexOf("safari") != -1)
        {
        }
        else
        {
                Exec.interval = setInterval(strCallback, t/n);
        }
        setTimeout('clearInterval(Exec.interval)', d);
    };
	Exec.onError = function (funcRef) {
        if (window.onerror) var onError = window.onerror;
        window.onerror = function (error, file, line) {
            funcRef(error, file, line);
            if (onError) onError();
        };
    };
/* ****************************************************************************** */

/* ****************************************************************************** *\
    !!! THE FOLLOWING SECTION EXECUTES !!!
\* ****************************************************************************** */
Exec.onError(
    function (error, file, line) {
        alert('error: '+error+"\nfile: "+file+"\nline: "+line);
    }
);
/* ****************************************************************************** */

/* ****************************************************************************** *\
	!!! COMMON FUNCTIONS !!!
\* ****************************************************************************** */
function ajaxLoader(url, stateChangeHandler, arg1, arg2, arg3, arg4, arg5) {
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  }
  if (x) {
    x.onreadystatechange = function() {
        stateChangeHandler(x, arg1, arg2, arg3, arg4, arg5);
    };
    x.open("GET", url, true);
    x.send(null);
  }
}

/* ****************************************************************************** *\
    !!! INFO POPUP SECTION !!!
\* ****************************************************************************** */
var infoPop=new Object();
infoPop.container_id='infoPopup';
infoPop.product_container='';
infoPop.saved_requests=new Object();

infoPop.show = function(containerId, productId, categoryId) {
  infoPop.product_container=containerId;
  infoPop.productId=productId;
  infoPop.categoryId=categoryId;
  infoPop.ajax(productId, categoryId);
}

infoPop.ajax = function(productId, categoryId) {
  var saved_request=this.saved_requests[infoPop.productId];
  if(saved_request) {
    this.changeHandler(saved_request);
  }
  var url='/catalog/product_info.xml?product_id=';
  url+=infoPop.productId + ';category_id=' + infoPop.categoryId;
  ajaxLoader(url, infoPop.changeHandler);
}

infoPop.changeHandler = function(req) {
   if (req.readyState == 4
        && req.status == 200
        && req.responseText.length > 0) {
        try {
       //     alert(eval('(' + req.responseText + ')'));
          var json = eval('(' + req.responseText + ')');
    	  //  if(json.product_id != infoPop.product_id) {
		   	 //   return;
		   	//  }
          infoPop.saved_requests[infoPop.productId]=req;
          infoPop.json = json;
          infoPop.buildPop();            
        }
        catch(e) {
        // what do we want to do on errors??
		//errAlert(e, 'Trying to display the Info popover');
        }
    }
}

infoPop.buildPop =function() {
  var product_image_cords = CSS.getElementPos(infoPop.product_container);
  var product_top=product_image_cords.top + 'px';
  var product_left=product_image_cords.left + 'px';
  var actual_position=getObject(infoPop.container_id);
  getObject('product_pop_title').innerHTML='';
  getObject('product_pop_price').innerHTML='';
  getObject('product_promo_info').innerHTML='';
  getObject('product_promo_info').style.color = '';
  getObject('product_desc').innerHTML='';
  getObject('product_short_desc').innerHTML='';
  getObject('product_pop_image').src='';
  getObject('product_pop_image').height='';
  getObject('product_pop_image').width='';
  getObject('product_pop_image_overlay').src='';
  getObject('product_pop_image_overlay').display='none';
  getObject('product_pop_image_overlay').height='';
  getObject('product_pop_image_overlay').width='';
  getObject('product_link').href='';
  getObject('product_extra_info').innerHTML='';
  if(infoPop.json.title != undefined) {
    getObject('product_pop_title').innerHTML=infoPop.json.title;
  }
  if(infoPop.json.price != undefined) {
    getObject('product_pop_price').innerHTML=infoPop.json.price;
  }
  if(infoPop.json.content.promo_info != undefined) {
    getObject('product_promo_info').innerHTML=infoPop.json.content.promo_info;
    if(infoPop.json.content.promo_color === '' || infoPop.json.content.promo_color === null || infoPop.json.content.promo_color === undefined) {
    	getObject('product_promo_info').style.color = "#990000";
    }else{
    	getObject('product_promo_info').style.color = infoPop.json.content.promo_color;
    }
  }
  if(infoPop.json.content.description != undefined) {
    getObject('product_desc').innerHTML=infoPop.json.content.description;
  }
  if(infoPop.json.content.short_description != undefined) {
    getObject('product_short_desc').innerHTML=infoPop.json.content.short_description;
  }
  if(infoPop.json.image != undefined) {
    getObject('product_pop_image').src=infoPop.json.image;
    getObject('product_pop_image').height=infoPop.json.image_height;
    getObject('product_pop_image').width=infoPop.json.image_width;
  }
  if(infoPop.json.link != undefined) {
    getObject('product_link').href=infoPop.json.link;
  }
  if(infoPop.json.image_height != undefined) {
    getObject('product_img_box').style.height=infoPop.json.image_height + 'px';
  }
  if(infoPop.json.image_width != undefined) {
    getObject('product_img_box').style.width=infoPop.json.image_width + 'px';
    var left_space=(250-infoPop.json.image_width)/2;
    getObject('product_img_box').style.marginLeft=left_space + 'px';
  }
  if(infoPop.json.image_overlay === '' || infoPop.json.image_overlay === null || infoPop.json.image_overlay === undefined) {
     // do nothing.
  } else {
    getObject('product_pop_image_overlay').src=infoPop.json.image_overlay;
    getObject('product_pop_image_overlay').height=infoPop.json.image_height;
    getObject('product_pop_image_overlay').width=infoPop.json.image_width;
    getObject('product_pop_image_overlay').style.display='block';
  }
   if(infoPop.json.content.extra_info_content === '' || infoPop.json.content.extra_info_content === null || infoPop.json.content.extra_info_content === undefined) {
           // do nothing
   } else {
	   getObject('product_extra_info').innerHTML=infoPop.json.content.extra_info_content;
   }
  actual_position.style.top=product_top;
  actual_position.style.left='300px';
  hideElement(infoPop.container_id, 1);
}

infoPop.hide = function() {
  try{
      hideElement(infoPop.container_id, 0);
  }catch (e) {
     alert(e.message);
  }  
}

//Same day next day section
var sdndObj = new Object();

sdndObj.ajax = function(prodArray,category_id) {
  var url='/catalog/same_day_next_day.xml?';
  var prod_url = 'product_ids=';
  for(var prod in prodArray){
  		prod_url+=prodArray[prod]+':';
  }
  url+=prod_url+';category_id='+category_id;
  ajaxLoader(url, sdndObj.changeHandler);
}
sdndObj.changeHandler = function(req) {
   if (req.readyState == 4
        && req.status == 200
        && req.responseText.length > 0) {
        try {
            //alert(eval('(' + req.responseText + ')'));
          var json = eval('(' + req.responseText + ')');
    	  //  if(json.product_id != infoPop.product_id) {
		   	 //   return;
		   	//  }
          sdndObj.json = json;
	  sdndObj.setValues();
        }
        catch(e) {
        // what do we want to do on errors??
		//errAlert(e, 'Trying to display the Info popover');
        }
    }
}

sdndObj.setValues = function(){
		for (var product in sdndObj.json){
			if(sdndObj.json[product].text != undefined){
				try{
					if(document.getElementById(product) === null || document.getElementById(product) === undefined){
						//do nothing
					}
					else{
						document.getElementById(product).innerHTML = sdndObj.json[product].text;
						document.getElementById(product).style.color = sdndObj.json[product].color;
					}
				}
				catch(e){
					alert(e.message);
				}
				
			}
        }
}

/* ****************************************************************************** *\
	!!! GBB SECTION !!!
\* ****************************************************************************** */
//get the width of the browser window or document.body
CSS.windowWidth = function () {

    if(window.innerWidth) {
     return window.innerWidth;
    }
	else if ((document.compatMode && document.compatMode.indexOf("CSS1") >=0)) {
	 return document.body.parentElement.clientWidth;
	}
    else if (document.body && document.body.clientWidth) {
     return document.body.clientWidth;
    }
return 0;
}

//get the height of the browser window or document body
CSS.windowHeight = function (){

	if(window.innerHeight){
        return window.innerHeight;
        }
	else if((document.compatMode && document.compatMode.indexOf("CSS1") >=0)){
        return document.body.parentElement.clientHeight;
        }
	else if (document.body && document.body.clientHeight){
        return document.body.clientHeight;
        }
return 0;
}

/* this should get our scrolling offsets in ALL browsers
Returns it in an object that you can access as properties, so use it like so:
var scrollOffsets = CSS.getScrollXY();
alert("You have scrolled " + scrollOffsets.y + "pixels down the page");
*/
CSS.getScrollXY = function () {
var scrOfX = 0, scrOfY = 0;

	if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
	}
	else if( document.body 
		   && ( document.body.scrollLeft 
			  || document.body.scrollTop)
			) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  	}
	else if( document.documentElement 
			&& (document.documentElement.scrollLeft 
				|| document.documentElement.scrollTop)
			  ) {
     //IE6 standards compliant mode
     scrOfY = document.documentElement.scrollTop;
     scrOfX = document.documentElement.scrollLeft;
	}

 return {x:scrOfX, y:scrOfY};
}

/* set the position of a DOM node to within the current scrolled region 
   works only on absolute positioned nodes (it sets absolute and shows) */
CSS.bring_abs_node_to_view = function(node){
    var $ = jQuery;

    var ww = $(window).width();
    var wn = $(node).width();
    var w  = (ww-wn)/2;
    if (w < 5){ w = 5; }

    var hw = $(window).height();
    var hn = $(node).height();
    var h  = (hw-hn)/2;
    if (h < 5){ h = 5; }

    var s = CSS.getScrollXY();

    $(node).css('position', 'absolute');
    $(node).css('top',  (s.y + h) + 'px');
    $(node).css('left', w + 'px');
    $(node).show();

}

/* Getting our elements left and top cords */
CSS.getElementPos = function (elemID) {
var offsetTrail = getObject(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}


CSS.scroll_delta = 100;  //how far to scroll each time, you can set this if you want
CSS.scroll_id;   //scroll timeoutid
CSS.scrollY = 0;  //keep track of how far we scrolled
CSS.scrollX = 0;
CSS.scroll_time = 200; //how many milliseconds before next scroll occurs
// This was created for Good, Better, Best popover but put it here
// so other people could use it as well Ticket #117952
// this will continously scroll to page to your y cordinates
// whereY is where you want to evenutally end up on the page
// haven't tested this with x coordinates but we really want to avoid
// horizontal scrolling.  
CSS.setScroll = function (whereY) {

    if(CSS.scrollY < whereY) {
     CSS.scrollY += (CSS.scroll_delta * 1);

	 // we never want to scroll past our whereY
	 // so let's make sure before we go the full delta
	 	if(CSS.scrollY > whereY) {
		// we are going to end up past where they wanted to 
		// scroll so let's compensate, just go directly to where we want
		CSS.scrollY = whereY;
		}
     window.scrollTo(0, CSS.scrollY);
     CSS.scroll_timeoutid = window.setTimeout('CSS.setScroll('+whereY+')', CSS.scroll_time);
    }
CSS.scroll_timeoutid;
}
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
CSS.fixPNG = function (myImage) {

	if((version >= 5.5) && (version < 7) && (document.body.filters)) {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }

}

function getObject(obj) {
    var theObj;
    if(typeof obj=="string") {
        return document.getElementById(obj);
    } else {
        return obj.style;
    }
    return null;
}

function hideElement() {
  var el = arguments[0];
    
	var state;
    if (arguments.length == 1) state = 2;
    else if (arguments.length > 1) state = arguments[1];

    if (document.getElementById(el)) {
        if (state == 1) document.getElementById(el).style.display = "block";
        else if (state == 0) document.getElementById(el).style.display = "none";
        else if (state == 2) {
            if (
                document.getElementById(el).style.display == "none"
                || document.getElementById(el).style.display == ""
            ) document.getElementById(el).style.display = "block";
            else document.getElementById(el).style.display = "none";
        }
    }
}

var GBB = new Object();
GBB.frame_id        = 'gbb_frame';
GBB.link_name       = 'Good Better Best';  //// for omniture custom click
GBB.link_type       = 'o';   // for omniture custom click
GBB.container_id    = 'gbb_popover';  //this is the surounding div of the content
GBB.content_id      = 'popover_content';  //this is the div for all our content
GBB.opened          = 0; 		//this lets us know that a popover is currently open
GBB.close_timeout   = 300; 	// this is just to give some time before we close the popover
GBB.saved_requests  = new Object();//a 'hash' with product id as the key and the AJAX req returned from the server.
GBB.scroll_delta    = 70;  //this is how many pixels we scroll at a time
GBB.scroll_time     = 50;
GBB.scroll_offset   = 2; //we will subtract this from where we scroll 
					// this is an attempt to not let the user's mouse move off the popover
GBB.visual_margin   = 3; // this the result of an IE workaround where I have to set the top
					// margin of the visual queue to -3px, this must be taken into account
					// when displaying the popover
GBB.product_id = '';  //this will store our popover product id
// this is for debugging, we will print a form on the page with a
// textarea in it for logging information.
GBB.debug = 0;  //set this to 1 if you want to have debugging printed to the screen.
GBB.log_created;
GBB.fix_png = 0;
GBB.image_cache = new Array();  // this will hold an array of image objects for the popover
						// this will result in the images being cached
						// the actual images that we will try to cache are set in _start.html

// fuction to set a close for the popover
GBB.setClose = function () {
GBB.close_timeout_id = window.setTimeout('GBB.close()', GBB.close_timeout);

}

/* if a close timeout is set the quickly clear it */
GBB.unSetClose = function () {
clearTimeout(GBB.close_timeout_id);
}

//simple function to do the actual close call
GBB.close = function () {
GBB.clear_values();
GBB.opened = 0;
clearTimeout(CSS.scroll_timeoutid);
if (document.getElementById('gbb_row_parent'))
{
  if (getObject('gbb_row_parent').scrollTop!=0)
  {
    getObject('gbb_row_parent').scrollTop=0;
  }
}
if(is_ie6) {
hideElement(GBB.frame_id, 0);
}
hideElement(GBB.container_id, 0);
}

// just clearing any values that we need to clear often
GBB.clear_values = function () {
GBB.product_id = '';
GBB.img_id     = '';
}

/* this will be called when we are just about to open the popover,
it will perform any necessary checks to see if we really should open
for instance, if we are already open or if something changed
We will also set our product id and image id for the popover
This will return 1 if we should continue to open or nothing if we 
should not open
*/
GBB.onopen = function (img_id, product_id) {

	// test to see if the product id sent in is equal to the current
	// product id, if so, we must already be open so stop the close
	//and remain open
	if(GBB.product_id != '' && GBB.product_id == product_id) {
	GBB.unSetClose(); // just in case
    return;
    }
	else {
	}

    clearTimeout(GBB.show_timeout_id);  // clear out another product popover
	  clearTimeout(CSS.scroll_timeoutid);  // stop scrolling
    GBB.unSetClose(); // clear any close calls that were set

	//if something is open then lets quickly close it
    if(GBB.opened) {
    GBB.close();
    }

    GBB.product_id = product_id;
    GBB.image_id   = img_id;
	return 1;
}

/* this is called on our mouseover events, it will set a timeout to
display our popover */
GBB.setShow = function (timeout, img_id, product_id, category_id, image_type, perrow) {
  GBB.per_row = perrow;
  if(image_type=='herolongthumb') {
    GBB.image_height=242;
  }
  if(image_type=='heroproduct') {
    GBB.image_height=222;
  }
  if(image_type=='heromegathumb') {
    GBB.image_height=240;	
  }
  if(image_type=='herosmallthumb') {
    GBB.image_height=145;
  }
  if(image_type=='herolargethumb') {
    GBB.image_height=242;
  }
  if(image_type=='herothumb') {
    GBB.image_height=162;
  }
  if(GBB.onopen(img_id, product_id)) {
    GBB.show_timeout_id = window.setTimeout("GBB.ajax('"+product_id+"', '"+category_id+"')", timeout);
  }
};

/* this is similar to set show, except that we don't
do any timeouts, we just display right away */
GBB.show = function (img_id, product_id, category_id) {
	//onopen can return false if it is already open
	// so no point doing it again
	if(GBB.onopen(img_id, product_id)) {
	GBB.ajax(product_id, category_id);
	}
}


// this will do our ajax call
// we pass in product id because we want to 
// make sure that the id is the same id as when any
//timeouts were set
GBB.ajax = function (prod_id,cat_id) {
	//it is possible that while we where busy getting
    //our ajax the user moved their mouse over another product
   // so we should not do what we are about to do
   if(prod_id != GBB.product_id) {
   return;
  }
  // we save any ajax results in a hash so we don't have to make the same
  // call twice
  var saved_request = this.saved_requests[GBB.product_id];
      
    if(saved_request) {  // look to see if we did this call already
    this.changeHandler(saved_request);
    }
    else {//not called yet, so go to the server
	//build our url, we need to send product id, markcode
	//index id, parent index id and a flag to let us know if we need
	// to perform any png hacks for stupid IE6
	var url = '/catalog/gbb_popup.xml?product_id=';
	url +=GBB.product_id+';category_id='+cat_id;

     ajaxLoader(
		url,
       // request state change handler see function below
      GBB.changeHandler
     );
    }

};

/* this is the callback for our ajax request
  once we have a successful response we get our 
  json object and then build our popover based on our
  return data
*/
GBB.changeHandler = function (req) {
    if (req.readyState == 4
        && req.status == 200
        && req.responseText.length > 0) {
        try {
       //     alert(eval('(' + req.responseText + ')'));
           var json = eval('(' + req.responseText + ')');
   //    alert("----"+json.product_id+"----"+GBB.product_id+"----"); 
			//it is possible that while we where busy getting
			//our ajax the user moved their mouse over another product
			// so we should not do what we are about to do
   //     alert(json.product_id+"----------"+GBB.product_id);
    	if(json.product_id != GBB.product_id) {
		   	return;
		   	}

            //save our req
            GBB.saved_requests[GBB.product_id] = req;
            //set up anything we need to with our json
            GBB.json = json
            //build the dam thing
              GBB.build()              
        }
        catch(e) {
        // what do we want to do on errors??
		//errAlert(e, 'Trying to display the GBB popover');
        }
    }
}

/* GBB is where it all goes down
 we have to do some resizing of divs and determine where
 the popover is going to display and if this will end up 
 below the user's screen, if so we scroll
*/
GBB.build = function () {
  //get a reference to the image where we want to display it
// our popover and the content container for the HTML
var viewer = getObject(GBB.container_id);  //the main outer popover div
var where  = getObject(GBB.image_id);  //product image on category page where we want to display
var gbb_div = getObject(GBB.content_id); //the div surrounding our content
//getting where the image is located on the page
var product_img_cords = CSS.getElementPos(GBB.image_id);
//this is how far over the content that contains the products is
var container_coords  = CSS.getElementPos('sd-hero_slot');
//now determine how high the image is, since we want to display below this
//var img_height = document.images[GBB.image_id].height;
//var img_width  = document.images[GBB.image_id].width;
var img_height = GBB.image_height;
//var img_width  = 150;

var img_parentid = getObject(GBB.image_id).parentNode.id;
var productstring = img_parentid.split('_');
var productno = productstring[productstring.length-1];
if(GBB.per_row == 3) {
  if(productno%3 == 1) {
    var left  = container_coords.left + 5;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
  if(productno%3 == 2) {
    var left = 295;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
  if(productno%3 == 0) {
    var left = 372;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left= left + 'px';
    }
  }
} else if(GBB.per_row == 4) {
  if(productno%4 == 1) {
    var left  = container_coords.left;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
  if(productno%4 == 2) {
    var left = 295;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
if(productno%4 == 0) {
    var left = 372;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
  if(productno%4 == 3) {
    var left = 295;
    viewer.style.left = left + 'px';
    if(is_ie6) {
      var frameviewer=getObject(GBB.frame_id);
      frameviewer.style.left = left + 'px';
    }
  }
} else {
  var left = container_coords.left;
  viewer.style.left = left + 'px';
  if(is_ie6) {
    var frameviewer=getObject(GBB.frame_id);
    frameviewer.style.left = left + 'px';
   }
}
//so the top of our popover will be where the product image is how far the product
//image is down the page + the height of our product image (because we display below)
// minus the stupid margin for the visual queue...which we had to add for it to look nice in IE
var top   = ((product_img_cords.top * 1) + (img_height * 1)) - GBB.visual_margin;
// our product images are all contained inside an outer div, so this is how far over 
//we want to display
//var left  = container_coords.left;
// fill in the inner html of the popover from our json object
// just a big chunck of HTML
gbb_div.innerHTML = GBB.json.html;
if(is_ie6) {
var frameviewer=getObject(GBB.frame_id);
frameviewer.style.top = top + 'px';
//frameviewer.style.left = left + 'px';
frameviewer.style.zIndex = '10';
}
// now we set all the necessary coordinates of where we want the
// viewer to display, and how wide we want it, which we get from AJAX
viewer.style.position = 'absolute';
viewer.style.top      = top + 'px';
//viewer.style.left     = left + 30 + 'px';
//viewer.style.width    = GBB.json.popover_width + 'px';
viewer.style.zIndex   = '1001';
//set the display to block
hideElement(GBB.container_id, 1);
if(is_ie6) {
hideElement(GBB.frame_id, 1);
}

//set our open flag
GBB.opened = 1;
//perform any necessary resizing of the popover html
GBB.resizeDivs('gbb_product_price_', 1, GBB.json.cols, 0);
GBB.resizeDivs('gbb_product_title_', 1, GBB.json.cols, 0);  
//set our actual height
//var viewer_height = GBB.setHeights();  
//alert(viewer_height);
//now determine if we need to scroll
// if the popover is going to display below the height of the
//window then we will need to scroll...sounds easy, but how do we do that??
//first, lets get the height of the window
var window_height = CSS.windowHeight();
// now, how far are we scrolled down the screen??
var scrolled = CSS.getScrollXY();
//alert(window_height +" ---- "+ scrolled);
//so, now we need to determine how far down the screen the bottom of the popover
// will display, this is the height of the popover + how far down we are displaying
// it on the screen.
var width_height = CSS.getElemWidthHeight(viewer.id);
var bottom = (top * 1) + width_height[1]; 
//now we determine if the bottom is below the bottom of the window
// which is: (bottom - how far we are scrolled) > window height

	if((bottom - scrolled.y) > window_height) {
	//ok so now we know that our bottom is below the bottom of the window
	// so where do we want to scroll.  
	// the problem is if we scroll too far, then the user's mouse will be scrolled
	// off the popover...which causes the popover to close of course
	// so, to stop this we will scroll to the point where the bottom of the popover
	// is at the very bottom of the screen, we get this by subtracting
	// the window height from the bottom of the viewer...but we will subtract
	// our scroll_offset just for a little tweaking to garentee we don't scroll too
	//far
	var where = (bottom - window_height) - GBB.scroll_offset;
	// now we use our CSS scroll functions to scroll the page
	if (screen.width=='1024' && screen.height=='768') {
	     where+=18;
	}

	CSS.scrollY = scrolled.y;
	CSS.scroll_delta = GBB.scroll_delta;
	CSS.scroll_time = GBB.scroll_time;
	CSS.setScroll(where);
	}
	else {
	//do nothing, we are all done
	}

//ok right now, the popover is displayed underneath the product image and we 
//might be scrolling down the page so the user can see the whole thing
}

/* this is for making a group of divs the same size, they have to have
the same id but for a trailing number, they will all be set to be the same height
as max_height, which can be passed in, but if any divs are bigger than this
we will use that value
*/
GBB.resizeDivs = function (id, start, end, max_height) {
	//first get our max height
  for(var i = start; i <= end; i++) {
	var wh = CSS.getElemWidthHeight(id+i);
		if(wh[1] > max_height) {
		max_height = wh[1];
		}
	}
	//now set each height
	for(var i = start; i <= end; i++) {
	var obj = getObject(id+i);
	obj.style.height = max_height + 'px';
	}
}

/* this function is for setting the heights of 
the entire popover div and the product_row div which is where all the main content is stored
we will then set the top of a bunch of our absolutly positioned
elements like the rounded coners and drop shadows
*/
GBB.setHeights = function () {
var viewer = getObject(GBB.container_id); // popover div
//first we determine the height of the first position
// we are assuming that each position is the same height
// which they should be, but sometimes they don't seem to be
var wh = CSS.getElemWidthHeight('gbb_position_1');
var h  = wh[1];
var h2 = h;  // save this for the product row div because it is already below the title bar
// now we want to know what the height of our title bar is
wh = CSS.getElemWidthHeight('gbb_popup_title_bar');
//add this height to our height variable
h += wh[1];
// now set our height
viewer.style.height = h + 'px';
//alert(viewer.style.height);
//let's also set the product_row height:

for (var i=1;i<=GBB.json.rows;i++) {
  getObject('gbb_product_row_'+i).style.height=h2+'px';
}
getObject('gbb_row_parent').style.height=h2+'px';

/* have to set all our shadow and rounded corners based
off the height of the product row */

// now we do our drop shadows with the repeating backgrounds
//left side shadow
var lside_shadow = getObject('gbb_lside_shadow');
lside_shadow.style.height = h2 + 'px';
//right side shadow
var rside_shadow = getObject('gbb_rside_shadow');
rside_shadow.style.height = h2+ 'px';  
// for some we add the bottom corner height because we want them to be completely
// outside the div so we can utilize our transparentness and hide the square corners
//shadow across the bottom 
var bottom_shadow = getObject('gbb_bottom_shadow');
bottom_shadow.style.top = h + 'px';
//bottom_shadow.style.top = ((h2 * 1) + GBB.json.bottom_corner_height)+ 'px';

// our bottom rounded corners
//bottom left corner
var bottom_lcorner = getObject('gbb_bottom_lcorner');
//bottom_lcorner.style.top = ((h2 * 1) + GBB.json.bottom_corner_height)+ 'px';
bottom_lcorner.style.top = h + 'px';
//bottom right corner
var bottom_rcorner = getObject('gbb_bottom_rcorner');
//bottom_rcorner.style.top = ((h2 * 1) + GBB.json.bottom_corner_height)+ 'px';
bottom_rcorner.style.top = h + 'px';
if(GBB.fix_png){
  DD_belatedPNG.fix('.png');
}
return h;
}

/*this should be called when the page loads
it will determine if we need to do our png hack, this need to be done for 
IE < 7
*/
GBB.setFixPNG = function() {
var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
    if((version >= 5.5) && (version < 7) && (document.body.filters)) {
	GBB.fix_png = 1;
	}
}

/* this is for pre loading the images when the page 
first loads so when the popover first displays it will
display faster
*/
GBB.pre_fetch_images = function() {

//making sure we have the image object...although if we don't
// this is the least of our problems :)
if(document.images) {
	var len = GBB.images.length;

	for(var i = 0; i < len; i++) {
	GBB.image_cache[i] = new Image();
    GBB.image_cache[i].src = GBB.images[i];
	}
}

}

