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 urlRule = '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()
    xmlhttp = undefined
    tabIndex = tabindex
    if (selectName && selectName != 'undefined') {
        townSelectName = selectName
    }
    if ((county_id) && (county_id > 0) && (county_id != 'undefined')) {
        url = '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);
    }
);
/* ****************************************************************************** */



