// Read a cookie.  Return null if the cookie has no value.
function readCookie(name) {
    var nameEQ = name + "=";
    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);
    }
    return null;
}

// If the user appears to be logged in, redirect to insession,
// otherwise, update the login form action to match the directory of this page.
function redir() {
    var href = window.location.href;
    var i = 0;
    if (/trendtrack\.com/.test(href)) {
        href = href.replace(/trendtrack\.com/, "cqstatetrack.com").replace(/\/[^\/]+\.html/,"").split("/");
        i = (href[href.length-1] == "") ? href.length-1 : href.length;
        href[i] = "newurl.html";
        window.location = href.join("/");
        return true;
    }
    var parts = href.split("?")[0].split(/\/(index)|(about)|(contact)/)[0].split("/");
    i = (parts[parts.length-1] == "") ? parts.length-1 : parts.length;
    parts[i] = "insession";
    if (parts[3] == "texis") return true;
    parts[2] += "/texis";
    //if (!/Auth\.version/.test(document.cookie)) {
    if (!readCookie("Auth.version")) {
        // force a logout the first time this version is used.
        parts[parts.length] = "+/home/logout"
        window.location = parts.join("/");
        return true;
    }
    var url = parts.join("/");
    //if (/Auth\.usrtkn/.test(document.cookie)) {
    if (readCookie("Auth.usrtkn")) {
        window.location = url;
        return true;
    }
    document.forms[0].action = url;
    document.getElementById("frm.host").value = getQuerystring("frm.host");
    return true;
}

// get URL query string parameters
function getQuerystring(key, default_) {
    if (default_==null) default_="";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
        return default_;
    else
        return qs[1];
}
