var theCookieName = cookieName_secondary; //"wxbug_cookie2";
//document.cookie = 'wxbug_cookie2=;expires=Mon, 01 Jan 2001 01:00:00 UTC; domain=' + cookieDomain + '; path=/';

function setCookie(cookieName, value) {
    try {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 20 * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
        document.cookie = cookieName + "=" + value + expires + "; domain=" + cookieDomain + "; path=/";
    }
    catch (e) { }
}

function readCookie(cookieName) {
    try {
        var nameEQ = cookieName + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
    }
    catch (e) { }
    return null;
}

function eraseCookie(cookieName) {
    setCookie(cookieName, "");
}


function SetRecentLocation(country, state, city, zip, stationId) {


    
    var uniqueLocs = new Array();
    var savedLocs = new Array();

    if (stationId == undefined || stationId == "undefined") {
        stationId = "";
    }

    try {
        var numLocations = 0;
        var thisIdx = -1;
        var hasDuplicates = false;

        // build array of locations from cookie
        var curLocIdx = 0;
        for (var i = 0; i < 5; i++) {
            var cn = readCookieValue(theCookieName, "country_name" + i);
            var st = readCookieValue(theCookieName, "state_code" + i);
            var ct = readCookieValue(theCookieName, "city_name" + i);
            var zc = readCookieValue(theCookieName, "zip" + i);
            if (zc == undefined || zc == "undefined")
                zc = "";
            var sid = readCookieValue(theCookieName, "stat" + i);
            if (sid == undefined || sid == "undefined")
                sid = "";

            // skip over duplicates and stationless zipcodes
            var uniqueKey = cn + st + ct + zc + sid;
            if ((uniqueKey in uniqueLocs) || (zc != "" && sid == "")) {
                hasDuplicates = true;
                continue;
            }

            uniqueLocs[uniqueKey] = 1;
            savedLocs[curLocIdx] = { "country_name": cn,
                "state_code": st,
                "city_name": ct,
                "zip": zc,
                "stat": sid
            };

            // find current location
            if ((cn == country) && (st == state) && (ct == city) && (zc == zip) && (sid == stationId)) thisIdx = curLocIdx;

            curLocIdx++;
            numLocations++;

        }

        // if current location is different from the first recent location OR if duplicates are found in the cookie, we need to rebuild the cookie
        if (hasDuplicates || (state != savedLocs[0]["state_code"]) || (zip != savedLocs[0]["zip"]) || (stationId != savedLocs[0]["stat"]) || (city != savedLocs[0]["city_name"]) || (country != savedLocs[0]["country_name"])) {
            setCookieValue(theCookieName, "country_name0", country);
            setCookieValue(theCookieName, "state_code0", state);
            setCookieValue(theCookieName, "city_name0", city);
            setCookieValue(theCookieName, "zip0", zip);
            setCookieValue(theCookieName, "stat0", stationId);

            if (numLocations > 0) {
                var cookieIdx = 1;
                for (var i = 0; i < numLocations; i++) {
                    if (i != thisIdx) {
                        setCookieValue(theCookieName, "country_name" + cookieIdx, savedLocs[i]["country_name"]);
                        setCookieValue(theCookieName, "state_code" + cookieIdx, savedLocs[i]["state_code"]);
                        setCookieValue(theCookieName, "city_name" + cookieIdx, savedLocs[i]["city_name"]);
                        setCookieValue(theCookieName, "zip" + cookieIdx, savedLocs[i]["zip"]);
                        setCookieValue(theCookieName, "stat" + cookieIdx, savedLocs[i]["stat"]);
                        cookieIdx++;
                    }
                }

                // clear out remaining locations that were not set (as a result of being duplicates)
                for (var j = numLocations; j < 5; j++) {
                    setCookieValue(theCookieName, "country_name" + j, "");
                    setCookieValue(theCookieName, "state_code" + j, "");
                    setCookieValue(theCookieName, "city_name" + j, "");
                    setCookieValue(theCookieName, "zip" + j, "");
                    setCookieValue(theCookieName, "stat" + j, "");
                }
            }

        }

    }
    catch (e) { }
}

function WriteRecentLocationsHTML(host, page, title) {

    try {
        var uniqueLocs = new Array();
        var countries = new Array(5);
        var states = new Array(5);
        var cities = new Array(5);
        var zips = new Array(5);
        var stations = new Array(5);
        var numLocations = 0;

        var curLocIdx = 0;

        for (var i = 0; i < 5; i++) {

            var cn = readCookieValue(theCookieName, "country_name" + i);
            var st = readCookieValue(theCookieName, "state_code" + i);
            var ct = readCookieValue(theCookieName, "city_name" + i);
            var zc = readCookieValue(theCookieName, "zip" + i);

            if (cn == "" && st == "" && ct == "" && zc == "")
            { break; }

            if (zc == undefined || zc == "undefined") {
                zc = "";
            }

            var sid = readCookieValue(theCookieName, "stat" + i);
            if (sid == undefined || sid == "undefined") {
                sid = "";
            }

            if (ct == "") {
                break;
            }

            // skip over duplicates
            var uniqueKey = cn + st + ct + zc + sid;
            if (uniqueKey in uniqueLocs) {
                continue;
            }

            uniqueLocs[uniqueKey] = 1;

            countries[curLocIdx] = cn;
            states[curLocIdx] = st;
            cities[curLocIdx] = ct;
            zips[curLocIdx] = zc;
            stations[curLocIdx] = sid;

            curLocIdx++;
            numLocations++;

        }

        // write out the HTML for the recent locations if there are more than one of them
        if (numLocations > 1) {
            var html = "<div id=\"loc-recent\">";
            html += "<a href=\"#\" id=\"loc-recent-hdr\">";
            html += "<span>" + title + "</span>";
            html += "</a>";
            html += "<ul>";

            for (var i = 0; i < numLocations; i++) {
                var loc = states[i] + "/" + cities[i];
                var locName = cities[i] + ", " + states[i];
                if ((zips[i] == "") && (countries[i] != "Canada")){
                    loc = countries[i] + "/" + cities[i];
                    locName = cities[i] + ", " + countries[i];
                }
                else if ((zips[i] == "") && (countries[i] == "Canada")) {
                    loc = states[i] + "/" + cities[i];
                    locName = cities[i] + ", " + states[i];
                }
                if (zips[i] != "") {
                    for (var j = 0; j < numLocations; j++) {
                        if (j != i) {
                            if ((cities[i] == cities[j]) && (states[i] == states[j])) {
                                locName = cities[i] + ", " + states[i] + " (" + zips[i] + ")";
                            }
                        }
                    }
                }

                var url = host + "/" + loc + page;

                if (page.indexOf("?") <= 0) {
                    url += "?stat=" + stations[i];
                }
                else {
                    url += "&stat=" + stations[i];
                }
                if (zips[i] != "") url += "&zip=" + zips[i];

                html += "<li><a href=\"" + url + "\">" + locName + "</a></li>";
            }

            html += "</ul>";
            html += "</div>";

            document.getElementById("loc-recent-div").innerHTML = html;
        }
    }
    catch (e) {

    }
}

function readCookieValue(cookieName, name) {
    try {
        var cookie = readCookie(cookieName);
        if (cookie == null) cookie = '';
        var nameEQ = name + "=";
        var ca = cookie.split('&');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
    }
    catch (e) { }
    return "";
}

function setCookieValue(cookieName, name, value) {
    try {
        var cookie = readCookie(cookieName);
        if (cookie == null) cookie = "";
        var nameEQ = name + "=";
        var ca = cookie.split('&');
        var found = 0;
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            if (c.indexOf(nameEQ) == 0) {
                ca[i] = nameEQ + value;
                found = 1;
            }
        }
        cookie = "";
        for (var i = 0; i < ca.length; i++) {
            if (i > 0) cookie += "&";
            cookie += ca[i];
        }
        if (found == 0) {
            if (ca.length > 0) cookie += "&";
            cookie += nameEQ + value;
        }
        setCookie(cookieName, cookie);
    }
    catch (e) { }
}


function wXshowHide(clickID, objectID) {
    try {
        var clickElem = document.getElementById(clickID);
        var objectElem = document.getElementById(objectID);
        if (clickElem) {
            if ((clickElem.className.search('close') == -1) && (clickElem.className.search('Close') == -1) && ((clickElem.className.search('open') != -1) || (clickElem.className.search('Open') != -1))) { // ( if OPEN ) index of -1 == not present in string
                objectElem.style.display = 'none';
                clickElem.className = clickElem.className.replace('open', 'close').replace('Open', 'Close'); // (close arrow) replace('Replace This', 'Replace With')
            }
            else {  // ( if CLOSED )
                objectElem.style.display = 'block';
                clickElem.className = clickElem.className.replace('close', 'open').replace('Close', 'Open');  // (open arrow)
            }
        }
    }
    catch (e) {
    }
}

function buildHorizMenu() {
	jQuery("#wXhorizmenu > li:last-child").addClass("last");
	jQuery("#wXhorizmenu ul").css("top", parseInt(jQuery("#wXhorizmenu").height()) - 1 + "px");
	jQuery("#wXhorizmenu > li").each(function() {
		var navtimer;
		var menuItem = jQuery(this);
		menuItem.bind("mouseover", function() {
			if (navtimer) clearTimeout(navtimer);
			menuItem.addClass("open");
			jQuery("#ie-lte6root .wXhoriznav ul li.last ul").css("height", "1%");
			// the code below is because IE9 seems to have an issue where mouseover/mouseout of certain
			// nav entries lose their background color. For whatever reason, setting nav UL background color to 
			// match the entry color on mouseover fixes it. harumph.
			jQuery("#.wXhoriznav ul").css("background", "#198015");
		});
		menuItem.bind("mouseout", function() {
			if (navtimer) clearTimeout(navtimer);
			navtimer = setTimeout(function() {
				jQuery("#ie-lte6root .wXhoriznav ul li.last ul").css("height", "auto");
				menuItem.removeClass("open");
			}, 10);
		})
	});
    // the code below removes top level padding,
    // calculates and applies padding per list item,
    // measures the width of all padded list items, and
    // applies this width to the menu, achieving centering.
    jQuery("#wXhorizmenu > li a").css("padding", "0");
    var menuFullWidth = parseInt(jQuery(".wXhoriznav").width());
    var menuWidth = 0;
    jQuery("#wXhorizmenu > li").each(function() { menuWidth = menuWidth + jQuery(this).width(); });
    var menuItems = jQuery("#wXhorizmenu > li").size();
    var padding = Math.floor(((menuFullWidth - menuWidth) / menuItems) / 2);
    jQuery("#wXhorizmenu > li a").css("padding", "0 " + padding + "px");
    var newMenuWidth = 0; //now get new UL width so we can be centered
    jQuery("#wXhorizmenu > li").each(function() { newMenuWidth = newMenuWidth + jQuery(this).width(); });
    jQuery("#wXhorizmenu").css("width", newMenuWidth + "px");
}
