﻿function pageSetup() {
    if (typeof landerExtras == 'function')
        landerExtras();

    var theHead = document.getElementsByTagName("head")[0];
    var maxScript = document.createElement('script');
    maxScript.type = 'text/javascript';
    maxScript.src = 'http://j.maxmind.com/app/geoip.js';
    theHead.appendChild(maxScript);

    if (typeof load == 'function')
        load();

    if (step == "One") {

        var keys = getQueryKeys();
        var inputs = document.getElementsByTagName("INPUT");
        var theForm = document.getElementsByTagName("FORM")[0];
        var addInput = true;
        for (i = 0; i < keys.length; i++) {

            if (keys[i]) {
                addInput = true;
                for (t = 0; t < inputs.length; t++) {
                    if (inputs[t].name == keys[i]) {
                        addInput = false;
                    }

                }

                if (addInput) {
                    var newInp = document.createElement("input");
                    newInp.name = keys[i];
                    newInp.value = getQueryValue(keys[i]);
                    newInp.type = "hidden";
                  //  alert(keys[i]);


                    theForm.appendChild(newInp);
                } else {
                    inputs[t].value = getQueryValue(keys[i]);
                }
            }
        } 
    }

    if (step == "Two") {

        if (getQueryValue("aff_sub4")) {
            var MAIN_OFFER_ID = getQueryValue("aff_sub4");

            if (MAIN_OFFER_ID.indexOf("A") == 0) {
                document.getElementById("inpRedirectURL").value =
             "http://quotes.usinsuranceonline.com/autocontact.php?refID=13326&refCampaign=" + MAIN_OFFER_ID + "&startZip=&brand=7&kw=dsp";

            }
        }
        window.moveTo(0, 0);
        window.resizeTo(screen.width, screen.height);
        loadStep2();
    }

    focusZip();


    var stateSpans = getElementsByClassName("spanState", "SPAN");

  

    var stateName=geoip_region_name();
    if (window.location.href.indexOf("california") > -1)
        stateName = "California";
    if (window.location.href.indexOf("illinois") > -1)
        stateName = "Illinois";
    if (window.location.href.indexOf("texas") > -1)
        stateName = "Texas";

    if (getQueryValue("aff_sub5")) {
        switch (getQueryValue("aff_sub5").toUpperCase()) {

            case "AK": stateName = "Alaska"; break;
            case "AL": stateName = "Alabama"; break;
            case "AR": stateName = "Arkansas"; break;
            case "AZ": stateName = "Arizona"; break;
            case "CA": stateName = "California"; break;
            case "CO": stateName = "Colorado"; break;
            case "CT": stateName = "Connecticut"; break;
            case "DC": stateName = "District Of Columbia"; break;
            case "DE": stateName = "Delaware"; break;
            case "FL": stateName = "Florida"; break;
            case "GA": stateName = "Georgia"; break;
            case "HI": stateName = "Hawaii"; break;
            case "IA": stateName = "Iowa"; break;
            case "ID": stateName = "Idaho"; break;
            case "IL": stateName = "Illinois"; break;
            case "IN": stateName = "Indiana"; break;
            case "KS": stateName = "Kansas"; break;
            case "KY": stateName = "Kentucky"; break;
            case "LA": stateName = "Louisiana"; break;
            case "MA": stateName = "Massachusetts"; break;
            case "MD": stateName = "Maryland"; break;
            case "ME": stateName = "Maine"; break;
            case "MI": stateName = "Michigan"; break;
            case "MN": stateName = "Minnesota"; break;
            case "MO": stateName = "Missouri"; break;
            case "MS": stateName = "Mississippi"; break;
            case "MT": stateName = "Montana"; break;
            case "NC": stateName = "North Carolina"; break;
            case "ND": stateName = "North Dakota"; break;
            case "NE": stateName = "Nebraska"; break;
            case "NH": stateName = "New Hampshire"; break;
            case "NJ": stateName = "New Jersey"; break;
            case "NM": stateName = "New Mexico"; break;
            case "NV": stateName = "Nevada"; break;
            case "NY": stateName = "New York"; break;
            case "OH": stateName = "Ohio"; break;
            case "OK": stateName = "Oklahoma"; break;
            case "OR": stateName = "Oregon"; break;
            case "PA": stateName = "Pennsylvania"; break;
            case "PR": stateName = "Puerto Rico"; break;
            case "PW": stateName = "Palau"; break;
            case "RI": stateName = "Rhode Island"; break;
            case "SC": stateName = "South Carolina"; break;
            case "SD": stateName = "South Dakota"; break;
            case "TN": stateName = "Tennessee"; break;
            case "TX": stateName = "Texas"; break;
            case "UT": stateName = "Utah"; break;
            case "VA": stateName = "Virginia"; break;
            case "VI": stateName = "Virgin Islands"; break;
            case "VT": stateName = "Vermont"; break;
            case "WA": stateName = "Washington"; break;
            case "WI": stateName = "Wisconsin"; break;
            case "WV": stateName = "West Virginia"; break;
            case "WY": stateName = "Wyoming"; break;
        } 
    }

    for (i = 0; i < stateSpans.length; i++) {
        stateSpans[i].innerHTML = stateName;
    }

//    if (underpop) {

//        // add target to google map form
//        var formGM = document.getElementById("formGM");
//        if (formGM)
//            formGM.setAttribute("target", "_blank");

//        // add target to main form
//        var formMain = document.getElementById("formMain");
//        if (formMain)
//            formMain.setAttribute("target", "_blank");
//    }
}



function qs2form() {
    var qs = window.location.search;
    var markup = "";
    if (qs.indexOf("?") == 0) {
        qs = qs.substring(1);
        var pairs = qs.split("&");
        for (i = 0; i < pairs.length; i++) {
            if (pairs[i].split("=").length = 2) {
                var key = pairs[i].split("=")[0];

                if (key == "prepopzip" || key == "page") {
                } else {
                    if (key == "zipcode")
                        key = "prepopzip";
                    var val = pairs[i].split("=")[1];
                    markup += '<input type="hidden" name="' + key + '" value="' + val + '"/>';

                }
            }
        }
    }
    return markup;
}

function getQueryValue(key) {
    var qs = window.location.search;
    if (qs.indexOf("?") == 0) {
        var pairs = qs.replace("?","").split("&");
        for (i = 0; i < pairs.length; i++) {
            if (pairs[i].split("=").length = 2) {
                if (pairs[i].split("=")[0] == key) {
                    return pairs[i].split("=")[1];
                }
            }
        }


    }
    return "";

}

function getQueryKeys() {
    var keys = new Array();
    var qs = window.location.search;
    if (qs.indexOf("?") == 0) {
        var pairs = qs.split("&");
        for (i = 0; i < pairs.length; i++) {
            if (pairs[i].split("=").length = 2) {
                var key = pairs[i].split("=")[0];

                if(key.indexOf("?")>-1)
                    key=key.replace("?", "");
                keys.push(key);
            }
        }


    }
    return keys;
}

function loadStep2(zip) {

    startTimer();

}


function checkKey(evt) {
    if (evt.keyCode == 13) {
        return true;
    }
    var charCode = (evt.which) ? evt.which : event.keyCode


    if (charCode == 8 || charCode == 9) {
        return true;
    }
    if ((charCode >= 96 && charCode <= 105) || (charCode >= 48 && charCode <= 57))
        return true;

    return false;
}

function checkSubmit(clickFrom) {
    if (GetZipCode().length == 5) {
        loadUnderPop();
        return true;
    }
    if (clickFrom == "map") {
        inlineMsg("inpMapZip", "Please enter a valid Zipcode!",3);
    }
    else {
        inlineMsg("inpMainZip", "Please enter a valid Zipcode!");
    }
    return false;
}

function loadUnderPop() {
    if (underpop) {
        //  alert('window.location.href = ' + underPopHref + GetZipCode());
        setTimeout(navigateUnderPop, 3000);
    }
}

function navigateUnderPop() {
    window.location.href = underPopHref + GetZipCode();
}


function focusZip() {
    var inpMainZip = document.getElementById("inpMainZip");
    if (inpMainZip)
        inpMainZip.focus();
}

function GetZipCode() {

    var inpMainZip = document.getElementById("inpMainZip");
    if (!inpMainZip) {
        try { return geoip_postal_code(); }
        catch (err) { }
    }
    if (inpMainZip && inpMainZip.value.length == 5) {

        return inpMainZip.value;
    }

    var inpMapZip = document.getElementById("inpMapZip");
    if (inpMapZip && inpMapZip.value.length == 5) {
        return inpMapZip.value;
    }

    return "";

}


    function startTimer() {
        setTimeout(compileUrl, 3500);
    }

    function compileUrl() {

        var key = '';
        //        if (Main_Offer_KW == '') {

        //            try {
        //                key = frames[0].location.href.split('?')[1];
        //            } catch (errr) {
        //                key = 'test';
        //            } 
        //        }
        var rUrl = document.getElementById('inpRedirectURL').value + key

        if (rUrl.indexOf('startZip=&') > -1) {
            rUrl = rUrl.replace('startZip=&', 'startZip=' + getQueryValue('zipcode') + '&');
        }
        if (rUrl.indexOf('zip=&') > -1) {
            rUrl = rUrl.replace('zip=&', 'zip=' + getQueryValue('zipcode') + '&');
        }

        window.location.href = rUrl;
    }

    var fadeEffect = function () {
        return {
            init: function (id, flag, target, next) {
                this.next = next;
                this.elem = document.getElementById(id);
                clearInterval(this.elem.si);
                this.target = target ? target : flag ? 100 : 0;
                this.flag = flag || -1;
                this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
                this.si = setInterval(function () { fadeEffect.tween() }, 15);
            },
            tween: function () {
                if (this.alpha == this.target) {
                    clearInterval(this.si);
                    if (typeof this.next == 'function')
                        this.next();
                } else {
                    var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
                    this.elem.style.opacity = value / 100;
                    this.elem.style.filter = 'alpha(opacity=' + value + ')';
                    this.alpha = value
                }
            }
        }
    } ();



    // START OF MESSAGE SCRIPT //

    var MSGTIMER = 20;
    var MSGSPEED = 5;
    var MSGOFFSET = 3;
    var MSGHIDE = 0;

    // build out the divs, set attributes and call the fade function //
    function inlineMsg(target, string, autohide) {
        var msg;
        var msgcontent;
        if (!document.getElementById('msg')) {
            msg = document.createElement('div');
          //  msg.onmouseover = clearMsg;
            msg.id = 'msg';
            msgcontent = document.createElement('div');
            msgcontent.id = 'msgcontent';
            document.body.appendChild(msg);
            msg.appendChild(msgcontent);
            msg.style.filter = 'alpha(opacity=0)';
            msg.style.opacity = 0;
            msg.alpha = 0;
        } else {
            msg = document.getElementById('msg');
            msgcontent = document.getElementById('msgcontent');
        }
        msgcontent.innerHTML = string;
        msg.style.display = 'block';
        var msgheight = msg.offsetHeight;
        var targetdiv = document.getElementById(target);
//        if (!targetdiv)
//            return;
        targetdiv.focus();
        var targetheight = targetdiv.offsetHeight;
        var targetwidth = targetdiv.offsetWidth;
        var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);

        var moreOffset = 0;
        if (target == "inpMapZip")
            moreOffset = 110;
        var leftposition = leftPosition(targetdiv) +moreOffset+ targetwidth + MSGOFFSET;
        msg.style.top = topposition + 'px';
        msg.style.left = leftposition + 'px';
        clearInterval(msg.timer);
        msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
        if (!autohide) {
            autohide = MSGHIDE;
        }
        if (autohide)
            window.setTimeout("hideMsg()", (autohide * 1000));
    }

    function clearMsg() {
        var msg = document.getElementById('msg');
        parent = msg.parentNode;
        parent.removeChild(msg)

    }

    // hide the form alert //
    function hideMsg(msg) {
        var msg = document.getElementById('msg');
        if (!msg.timer) {
            msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
        }
    }

    // face the message box //
    function fadeMsg(flag) {
        if (flag == null) {
            flag = 1;
        }
        var msg = document.getElementById('msg');
        var value;
        if (flag == 1) {
            value = msg.alpha + MSGSPEED;
        } else {
            value = msg.alpha - MSGSPEED;
        }
        msg.alpha = value;
        msg.style.opacity = (value / 100);
        msg.style.filter = 'alpha(opacity=' + value + ')';
        if (value >= 99) {
            clearInterval(msg.timer);
            msg.timer = null;
        } else if (value <= 1) {
            msg.style.display = "none";
            clearInterval(msg.timer);
        }
    }

    // calculate the position of the element in relation to the left of the browser //
    function leftPosition(target) {
        var left = 0;
        if (target.offsetParent) {
            while (1) {
                left += target.offsetLeft;
                if (!target.offsetParent) {
                    break;
                }
                target = target.offsetParent;
            }
        } else if (target.x) {
            left += target.x;
        }
        
        return left;
    }

    // calculate the position of the element in relation to the top of the browser window //
    function topPosition(target) {
        var top = 0;
        if (target.offsetParent) {
            while (1) {
                top += target.offsetTop;
                if (!target.offsetParent) {
                    break;
                }
                target = target.offsetParent;
            }
        } else if (target.y) {
            top += target.y;
        }
        return top;
    }

    // preload the arrow //
    if (document.images) {
        arrow = new Image(7, 80);
        arrow.src = "images/msg_arrow.gif";
    }

    function getElementsByClassName(className, tag) {
        ///<summary>Get all the elements of the given classname of the given tag.</summary>
        ///<param name="classname" type="String">css className of DOM Elements to get</param>
        ///<param name="tag" type="String">tag name of DOM Elements to get</param>
        ///<returns>DOM object Array</returns>
        if (!tag) tag = "*";
        var anchs = document.getElementsByTagName(tag);
        var total_anchs = anchs.length;
        var regexp = new RegExp('\\b' + className + '\\b');
        var class_items = new Array();

        for (var i = 0; i < total_anchs; i++) //Go thru all the links seaching for the class name
        {
            var this_item = anchs[i];
            if (regexp.test(this_item.className))
                class_items.push(this_item);
        };
        return class_items;
    }
