function BeforePrint() {
    sDocument = document.body.innerHTML;
    var sText = $("divPrint").innerHTML;
    document.body.innerHTML = sText;
}

function AfterPrint() {
    document.body.innerHTML = sDocument;
}


$JQuery = jQuery;
var timeout = 1000;
var closetimer = 0;
var ddmenuitem = 0;
var menuitem = 0;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    $JQuery(this).toggleClass("selected");
    ddmenuitem = $JQuery(this).find('ul').eq(0).css('visibility', 'visible');
}

function jsddm_close() {
    if (ddmenuitem) {
        ddmenuitem.css('visibility', 'hidden');
        ddmenuitem.parents('li[type="mainnav"]').attr("class", "navbaritem");
        ddmenuitem.parents('li[type="mainnav_special"]').attr("class", "navbarspecial");
    }
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}
$JQuery(document).ready(function() {
    $JQuery('#jsddm > li').hover(jsddm_open, jsddm_timer); 
    document.onclick = jsddm_close;
    new Ajax.Autocompleter('headerquote', 'stock_suggestions', '/ajax/companylookup.aspx', {
        minChars: 1,
        updateElement: getSelectedItem
    });
});


function getSelectionId(text, li) {
    alert($(text).value);
    alert(li.id);
}

function getSelectedItem(li) {
    $('indicator1').show();
    $('headerquote').value = li.id;
    GetQuote();
}

function GetQuote() {
    var strNewUrl;
    var strSearchTerm;
    strSymbol = $('headerquote').value;
    strSymbol = strSymbol.replace(/[\.][^A-Za-z]+/g, '');
    strSymbol = strSymbol.toUpperCase();
    strNewUrl = "/streetools/stock_quotes.aspx?Ticker=" + escape(strSymbol);
    window.location = strNewUrl;
}

function MOGetQuote() {
    var strNewUrl;
    var strSearchTerm;
    strSymbol = $('MOquote').value;
    strSymbol = strSymbol.replace(/[\.][^A-Za-z]+/g, '');
    strSymbol = strSymbol.toUpperCase();
    strNewUrl = "/streetools/stock_quotes.aspx?Ticker=" + escape(strSymbol);
    window.location = strNewUrl;
}

function chart(a) {
    var dow = $("chart_dow");
    var nas = $("chart_nas");
    var rut = $("chart_rut");
    var spx = $("chart_spx");
    var dowr = $("row_dow");
    var nasr = $("row_nas");
    var rutr = $("row_rut");
    var spxr = $("row_spx");
    dow.style.display = "none";
    dowr.className = "";
    nas.style.display = "none";
    nasr.className = "";
    rut.style.display = "none";
    rutr.className = "";
    spx.style.display = "none";
    spxr.className = "";
    if (a == 1) {
        dow.style.display = "block";
        dowr.className = "dark";
    }
    if (a == 2) {
        nas.style.display = "block";
        nasr.className = "dark";
    }
    if (a == 3) {
        spx.style.display = "block";
        spxr.className = "dark";
    }
    if (a == 4) {
        rut.style.display = "block";
        rutr.className = "dark";
    }
}

function addOnLoad(newFunction) {
    var currentOnLoad = window.onload;
    if (typeof window.onload != "function") {
        window.onload = newFunction;
    } else {
        window.onload = function() {
            currentOnLoad();
            newFunction();
        }
    }
}

function createCookie(name, value, days, domain) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    wholecookie = name + "=" + value + expires + "; path=/;";
    if (domain) {
        wholecookie = wholecookie + "domain=" + domain + ";";
    }
    document.cookie = wholecookie;
}

function createHourExpireCookie(name, value, domain) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    wholecookie = name + "=" + value + expires + "; path=/;";
    if (domain) {
        wholecookie = wholecookie + "domain=" + domain + ";";
    }
    document.cookie = wholecookie;
}

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;
}

function eraseCookie(name, domain) {
    createCookie(name, "", -1, domain);
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    } else if (obj.x) curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y) curtop += obj.y;
    return curtop;
}
var scrolldelay;

function scrollPageTo(end) {
    clearTimeout(scrolldelay);
    var currentPos = (document.all) ? document.body.scrollTop : window.pageYOffset;
    if (currentPos > end) {
        window.scrollBy(0, -10);
        scrolldelay = setTimeout('scrollPageTo(\'' + end + '\')', 10);
    }
}

function upperFirst(u) {
    u = u.toLowerCase();
    u = u.split(' ');
    for (i = 0; i < u.length; i++)
        u[i] = u[i].replace(/^(.)/, u[i].charAt(0).toUpperCase());
    return u.join(' ');
}

function makewindow(url, name, wi, hi, scroll) {
    if (!scroll) {
        scroll = 0;
    }
    mywin = window.open(url, name, 'width=' + wi + ',height=' + hi + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll);
}
var phone_field_length = 0;

function TabNext(obj, event, len, next_field) {
    if (event == "down") {
        phone_field_length = obj.value.length;
    } else if (event == "up") {
        if (obj.value.length != phone_field_length) {
            phone_field_length = obj.value.length;
            if (phone_field_length == len) {
                next_field.focus();
            }
        }
    }
}

function makeDivLink(classname) {
    var myArray = $$('div.' + classname);
    var htmlvalue = "";
    for (var index = 0; index < myArray.length; ++index) {
        var elm = myArray[index];
        htmlvalue = htmlvalue + '<p>' + elm.type + '</p>'
    }
    $('linkmaker').innerHTML = htmlvalue;
}

function setupHeadlineEvents() {
    var sp = $$('.newsitem').each(function(e) {
        var inc = e.getElementsByTagName("a");
        e.setAttribute('link', inc[0].getAttribute('href'));
        e.onclick = function() {
            location.href = this.getAttribute('link');
        }
        e.onmouseover = function() {
            this.className = "newsitemon";
        }
        e.onmouseout = function() {
            this.className = "newsitem";
        }
    });
}

function getBiggest() {
    var biggest = 0;
    $$('div.overviewContainer').each(function(e) {
        e.onmouseover = function() {
            e.className = 'overviewContainerActive';
        }
        e.onmouseout = function() {
            e.className = 'overviewContainer';
        }
        e.onclick = function() {
            location.href = e.getElementsByTagName("a")[0].getAttribute("href");
        }
        if (e.offsetHeight > biggest) {
            biggest = e.offsetHeight;
        }
    });
    $$('div.overviewContainer').each(function(e) {
        e.style.height = biggest;
    });
}
var msg = "";

function validateForm() {
    $('divprogress').show();
    $('formitems').hide();
    msg = "";
    $('divResponse').update('');
    $('divResponse').hide();
    if ($('firstname').value.length == 0) {
        msg += 'First Name<br/>';
    }
    if ($('lastname').value.length == 0) {
        msg += 'Last Name<br/>';
    }
    if ($('password').value.length < 4) {
        msg += 'Valid password<br/>';
    }
    if (!validateEmail()) {
        msg += "Valid email address";
    }
    if (msg != '') {
        $('divResponse').show();
        $('divResponse').update('<p class=\"deprecated\"><strong>Please verify the following:</strong> <br>' + msg + '</p>');
        $('divprogress').hide();
        $('formitems').show();
        return false;
    } else {
        checkAccount();
    }
}

function validateGoogleSignupForm() {
    $('divprogress').show();
    $('formitems').hide();
    msg = "";
    $('divResponse').update('');
    $('divResponse').hide();
    if ($('firstname').value.length == 0) {
        msg += 'First Name<br/>';
    }
    if ($('lastname').value.length == 0) {
        msg += 'Last Name<br/>';
    }
    if ($('password').value.length < 4) {
        msg += 'Valid password<br/>';
    }
    if (!validateEmail()) {
        msg += "Valid email address<br/>";
    }
    var checkboxcount = 0;
    if ($('chbMMO').checked == true) {
        checkboxcount++;
    }
    if ($('chbRecap').checked == true) {
        checkboxcount++;
    }
    if ($('chbOV').checked == true) {
        checkboxcount++;
    }
    if (checkboxcount == 0) {
        msg += "Select an e-newsletter <br/>"
    }
    if (msg != '') {
        $('divResponse').show();
        $('divResponse').update('<p class=\"deprecated\"><strong>Please verify the following:</strong> <br>' + msg + '</p>');
        $('divprogress').hide();
        $('formitems').show();
        return false;
    } else {
        checkAccount();
    }
}

function validateShadowboxSignupForm() {
    $('divprogress').show();
    $('formitems').hide();
    msg = "";
    $('divResponse').update('');
    $('divResponse').hide();
    if ($('firstname').value.length == 0) {
        msg += 'First Name<br/>';
    }
    if ($('lastname').value.length == 0) {
        msg += 'Last Name<br/>';
    }
    if ($('password').value.length < 4) {
        msg += 'Valid password<br/>';
    }
    if (!validateEmail()) {
        msg += "Valid email address<br/>";
    }
    if (msg != '') {
        $('divResponse').show();
        $('divResponse').update('<p class=\"deprecated\"><strong>Please verify the following:</strong> <br>' + msg + '</p>');
        $('divprogress').hide();
        $('formitems').show();
        return false;
    } else {
        checkAccount();
    }
}

function validateEmail() {
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    str = $('emailaddress').value;
    if (!str.match(emailRegEx)) {
        return false;
    }
    return true;
}

function checkAccount() {
    var url = '/ajax/verifysub.aspx';
    var email = $('emailaddress').value;
    var pars = 'emailaddress=' + email + '&dt=' + Date();
    var ajaxCheckAccountRequest = new Ajax.Request(url, {
        method: 'put',
        parameters: pars,
        asynchronous: true,
        onComplete: function(request) {
            var results = request.responseText.toString();
            return showEmailCheckResponse(results);
        }
    });
}

function showEmailCheckResponse(emailresponse) {
    var emailaddress = '';
    var textMessage = emailresponse;
    emailaddress = $('emailaddress').value;
    textMessage = (textMessage.toUpperCase()).strip();
    emailaddress = (emailaddress.toUpperCase()).strip();
    if (textMessage == emailaddress) {
        $('divResponse').update('');
        $('divResponse').hide();
        createSubscriber(true);
    } else {
        $('divResponse').update('');
        $('divResponse').hide();
        createSubscriber(false);
    }
}

function createSubscriber(exists) {
    var sub = '';
    var url = '/ajax/subsetup.aspx';
    var email = $('emailaddress').value;
    var firstname = $('firstname').value;
    var lastname = $('lastname').value;
    var password = $('password').value;
    var contact = 0;
    if ($('allowcontact').checked) {
        contact = 1;
    }
    sub = '<subscriber firstname=\"' + firstname + '\" lastname=\"' + lastname + '\" password=\"' + password + '\" emailaddress=\"' + email + '\" allowcontact=\"' + contact + '\" exist=\"' + exists + '\">';
    $$('input[name="ezine"]').each(function(s) {
        if (s.checked) {
            sub += '<product name=\"' + s.value + '\" sourcecode=\"' + s.readAttribute('sourcecode') + '\" />';
        }
        if (s.value == "OA") {
            sub += '<product name=\"' + s.value + '\" sourcecode=\"' + s.readAttribute('sourcecode') + '\" />';
        }
    });
    sub += '</subscriber>'
    var pars = 'sub=' + sub + '&dt=' + Date();
    var ajaxCreateSubRequest = new Ajax.Request(url, {
        method: 'put',
        encoding: 'UTF-8',
        parameters: pars,
        asynchronous: true,
        onComplete: function(request) {
            var results = request.responseText;
            if (results.length > 0) {
                var processresults = results.indexOf('created');
                if (processresults > 0) {
                    showEzineThankyou();
                } else {
                    showError();
                }
            }
        }
    });
}

function showError() {
    $('divResponse').show();
    $('divResponse').update('<p class=\"deprecated\">You have already signed up for this promotion. If you have received this message in error, please contact customer service 1-800-327-8833. Thank You.</p>');
    $('divprogress').hide();
    $('closer').show();
    $('formitems').show();
}

function showThankyou() {
    $('divResponse').show();
    $('divResponse').update('<p><br>Thank you for signing up for the members-only report.<br> Please check your email for instruction on viewing the members-only report.</p>');
    $('divprogress').hide();
    $('closer').show();
    createCookie('GoogleBlogPopup', 'signup', 365);
}

function showEzineThankyou() {
    $('divMessage').show();
    $('divMessage').update('<p><br><strong>"Thank You for your subscription to our email newsletters<br><br>You should receive an email shortly verifying your subscription."</p></strong>');
    $('divprogress').hide();
    $('closer').show();
    createCookie('GoogleBlogPopup', 'signup', 365);
}

function closeSignupForm() {
    $('light').hide();
    $('fade').hide();
}

function posFade() {
    $('fade').style.width = document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth + 'px';
    $('fade').style.height = document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px';
}


idleTime = 0;
var idleTimeLimit = 5;
var idleTimeOn = false;
$JQuery(document).ready(function() {

    if (idleTimeOn) {

        //Increment the idle time counter every minute.
        var idleInterval = setInterval("timerIncrement()", 60000); // 60000 = 1 minute

        //Zero the idle timer on mouse movement.
        $JQuery(this).mousemove(function(e) {
            idleTime = 0;
            console.log("idleTime = " + idleTime);
            $JQuery('#counter').html("idleTime = " + idleTime)
        });
        $JQuery(this).keypress(function(e) {
            idleTime = 0;
            console.log("idleTime = " + idleTime);
            $JQuery('#counter').html("idleTime = " + idleTime)
        });
    }
})

function timerIncrement() {
    idleTime = idleTime + 1;
    console.log("idleTime = " + idleTime);
    $JQuery('#counter').html("idleTime = " + idleTime)
    if (idleTime >= idleTimeLimit) { // 5 minutes
        console.log("Past idleTime " + idleTime + " refresh");
        window.location.hash = "#refresh";
        //window.location.url = window.location.search + '&refresh=1';
        //clearInterval(idelInterval);
        window.location.reload();
    }
}


//(function($) {
$JQuery(document).ready(function() {
    var refreshtimeout = 60000 * 3;
    if (idleTimeOn) {
        $JQuery(document).bind("idle.idleTimer", function() {
            var elapsedTime = $JQuery.idleTimer('getElapsedTime');
            var href = $JQuery(location).attr('href');
            var search = $JQuery(location).attr('search');
            //$JQuery("#status").html("User is idle :( for " + elapsedTime).css("backgroundColor", "silver");
            //console.log("User is idle :(");        
            window.location.replace(href);
            //alert($JQuery.data(document, 'idleTimer'));
        });

        $JQuery(document).bind("active.idleTimer", function() {
            $JQuery("#status").html("User is active :D").css("backgroundColor", "yellow");
            console.log("User is active :D");
            //alert($JQuery.data(document, 'idleTimer'));
        });

        $JQuery.idleTimer(refreshtimeout);
        // correct the page
        //$('#timeout').text(timeout / 1000);
        //})(jQuery);
    }

});


function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}
