﻿// Function retrieved from: http://cass-hacks.com/articles/code/js_url_encode_decode/  
function URLEncode(clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        }
        else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

// Retrieved from: http://www.htmlcodetutorial.com/forms/index_famsupp_157.html  
function SubmitOnEnter(myfield, e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    else
        return true;

    if (keycode == 13 && myfield.value != "") {
        SubscribeToNewsletter();
        return false;
    }
    else if (keycode == 13 && myfield.value == "") {
        return false;
    }
    else
        return true;
}

// Set default login button on enter key press 
function SubmitOnEnterLogin(myfield, e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    else
        return true;

    if (keycode == 13 && myfield.value != "") {
        var btn = document.getElementById('ctl00_MainContent_LoginView1_Login1_LoginButton');
        if (btn != null) {
            btn.click();
            return false;
        }
    }
    else if (keycode == 13 && myfield.value == "") {
        return false;
    }
    else
        return true;
}

//Left Trim
function ltrim(s) {
    return s.replace(/^\s*/, "");
}

function SetEnd(TB) {
    if (TB.createTextRange) {
        var FieldRange = TB.createTextRange();
        FieldRange.moveStart('character', TB.value.length);
        FieldRange.collapse();
        FieldRange.select();
    }
}

var allHTMLTags = new Array();

function simClickByClass(theClass) {

    // *** NOT USED ***
    // SAMPLE CALL simClickByClass('gsc-search-button');

    var allHTMLTags = document.getElementsByTagName('input');

    //Loop through all tags using a for loop
    for (i = 0; i < allHTMLTags.length; i++) {

        //Get all tags with the specified class name.
        if (allHTMLTags[i].className == theClass) {
            // start google search
            allHTMLTags[i].click();
            // hide google search button
            allHTMLTags[i].style.display = 'none';
            return;

        }
    }
}

function hideClass(theClass) {

    //Create Array of All HTML Tags
    var cse = document.getElementById('cse');
    if (cse != null) {
        //Loop through all tags using a for loop
        var allHTMLTags = cse.getElementsByTagName('div');
        for (i = 0; i < allHTMLTags.length; i++) {
            //Get all tags with the specified class name.
            if (allHTMLTags[i].className == theClass) {
                // hide div
                allHTMLTags[i].style.display = 'none';
                //assume only one div with theClass
                //break;
            }
        }
    }
}

function showClass(theClass) {

    //Create Array of All HTML Tags
    var cse = document.getElementById('cse');
    if (cse != null) {
        //Loop through all tags using a for loop
        var allHTMLTags = cse.getElementsByTagName('div');
        for (i = 0; i < allHTMLTags.length; i++) {
            //Get all tags with the specified class name.
            if (allHTMLTags[i].className == theClass) {
                // hide div
                allHTMLTags[i].style.display = 'block';
                //assume only one div with theClass
                //break;
            }
        }
    }
}

function switchDivs(which) {
    testHome();
    var ms = document.getElementById('ctl00_MainSection');
    var cs = document.getElementById('ctl00_searchresults');
    if (which == 'search') {
        if (ms != null) {
            //ms.style.visibility='hidden'
            ms.style.display = 'none';
            //ms.className = 'hide';
        }
        if (cs != null) {
            cs.style.display = 'block';
        }
    }
    else {
        if (ms != null) {
            ms.style.display = 'block';
        }
        if (cs != null) {
            cs.style.display = 'none';
        }
    }
}

function testHome() {
    /* fix padding for browsearticles and home pages */

    var home = document.getElementById('homestores');
    var browse = document.getElementById('browse');
    if (home != null || browse != null) {
        var sr = document.getElementById('ctl00_searchresults');
        if (sr != null) {
            sr.style.paddingLeft = '9px';
            sr.style.paddingTop = '6px';
            sr.style.paddingRight = '3px';
            sr.style.paddingBottom = '6px';
        }
    }
}


function testLoginOrRegister() {
    /* reinstate focus if login, register, query or  passsword recovery pages */

    var login = document.getElementById('ctl00_MainContent_LoginView1_Login1_UserName');
    if (login != null) {
        login.focus();
        return;
    }
    var register = document.getElementById('ctl00_MainContent_CreateUserWizard1_CreateUserStepContainer_UserName');
    if (register != null) {
        register.focus();
        return;
    }
    var query = document.getElementById('ctl00_MainContent_txtName');
    if (query != null) {
        query.focus();
        return;
    }
    var pr1 = document.getElementById('ctl00_MainContent_PasswordRecovery1_UserNameContainerID_UserName');
    if (pr1 != null) {
        pr1.focus();
        return;
    }
    var pr2 = document.getElementById('ctl00_MainContent_PasswordRecovery1_QuestionContainerID_Answer');
    if (pr2 != null) {
        pr2.focus();
        return;
    }
}

// Limit max length for characters entered into multiline textbox (textarea - html)
function limitCharsLength(Object, MaxLen) {
    if (Object.value.length > MaxLen - 1)
    { Object.value = Object.value.substring(0, MaxLen); }
}

function cancelEvent() {
    // ie hack
    if (window.event) window.event.cancelBubble = true;
    return false;
}

function SubscribeToNewsletter() {
    var email = document.getElementById('txtNewsletterEmail');
    if (email.value == 'Your email here')
    { return false; }

    //    if (email.value == '') {
    //        email.focus();
    //        return false;
    //    }

    window.document.location.href = 'Register.aspx?Email=' + email.value;
}

function NewsletterFocus(email) {
    //    var email = window.document.getElementById('ctl00_LoginView2_txtNewsletterEmail');
    email.className = 'highlight';
    if (email.value == 'Your email here') {
        email.value = '';
        return false;
    }
}

function NewsletterNoFocus(email) {
    //    var email = window.document.getElementById('ctl00_LoginView2_txtNewsletterEmail');
    if (email.value == '') {
        email.value = 'Your email here';
        email.className = 'cancelhighlight';
    }
}

function disableSearchBox() {
    var IE = /*@cc_on!@*/false;
    var sb = document.getElementById("q");
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if (sb != null) {
        sb.disabled = true;
        sb.value = ' please wait ...';
        // checks the browser type to see if it is firefox / not IE
        if (!IE) {
            // changes the style accordingly
            sb.style.color = '#ffffff';
            sb.style.background = '#ff9900';
        }
        if (is_chrome) {
            // changes the style accordingly
            sb.style.color = '#333333';
            sb.style.background = '#ffffff';
        }

        //        else {
        //            // won't work online - strange ??
        //            sb.style.backgroundImage = "url('images/please_wait.gif')";
        //            sb.backgroundPosition = "0 0";
        //            sb.backgroundRepeat = "none";
        //            sb.disabled = true;
        //        }
    }
}

function SearchFocus(s) {
    s.className = 'highlight';
    s.disabled = false;  // reinstate enabled property

    // RetrieveSearchText(); // in load event so shouldn't need here

    if (s.value == 'Your search text here') {
        s.value = '';
    }

    //  switchDivs('search');
    // switch divs via server code behind
    var b = document.getElementById("ctl00_switchSearch");
    if (b != null) {
        var cs = document.getElementById('ctl00_searchresults');
        if (cs != null) {
            if (cs.style.display != 'block') {
                // run serverside event
                b.click();
            }
        }
    }
}


function SearchNoFocus(s) {
    s.className = 'cancelhighlight';
    if (s.value == '') {
        s.value = 'Your search text here';
        CancelSearch();
    }
    // save search text in case postback via theme selector
    SaveSearchText();
}


function CancelSearch() {
    var s = document.getElementById("q");
    if (s != null) {
        s.value = 'Your search text here';
        s.className = 'cancelhighlight';
        s.blur();
        SaveSearchText(); // reset hidden value
    }
    // switchDivs('cancelsearch');
    // switch divs via server code behind
    var b = document.getElementById("ctl00_switchMainSection");
    if (b != null) {
        var ms = document.getElementById('ctl00_MainSection');
        if (ms != null) {
            if (ms.style.display != 'block') {
                // run serverside event
                b.click();
            }
            else {
                testLoginOrRegister(); // reset focus on textboxes
            }
        }
    }
}

//function CkKeyPress(e) {
//    var evt = (e) ? e : window.event;
//    var key = (evt.keyCode) ? evt.keyCode : evt.which;
//    if (key == 13) {
//        return false;
//    }
//    return true;
//}

function testEmpty(sbox, e) {
    // on search box key down event
    var key = window.event ? e.keyCode : e.which;

    //    if (sbox.value.length.toString() < 1) {
    //        switchDivs('search');

    //    }

    if (key == 8 && sbox.value.length.toString() <= 1) {
        hideClass('gsc-wrapper');
    }
    else {
        showClass('gsc-wrapper');
    }
    // save search text in case postback delay?
    // SaveSearchText();
    return true;
}


function loadCSE() {
    // Change the customSearchId string to the ID of your own Custom Search engine.
    var customSearchControl = new google.search.CustomSearchControl('003331299041567252283:xykigjr6bjw');
    //customSearchControl.enableAds(/* put your publisher ID here */);
    customSearchControl.setNoResultsString('Sorry no results for this query, please check spelling or try a different search.');
    // Set drawing options to use my text box as input instead of having the library create one.
    var drawOptions = new google.search.DrawOptions();
    drawOptions.setInput(document.getElementById('q'));

    // Draw the control in content div
    customSearchControl.draw('cse', drawOptions);
    //customSearchControl.setSearchCompleteCallback(null, hideresultstext);
    customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
    
    //restore search box
    RetrieveSearchText();
    testHome();
    var s = document.getElementById("q");
    if (s != null) {
        //alert(s.value.toString());
        s.disabled = false;  // reinstate enabled property
        if (s.value != 'Your search text here' && s.value != '') {
            s.className = 'highlight';
            s.focus();
            // re-execute search
            customSearchControl.execute(s.value);
        }
        else {
            // set focus on search box if searchresults div is currently displayed
            var cs = document.getElementById('ctl00_searchresults');
            if (cs != null) {
                if (cs.style.display == 'block') {
                    // set focus after server postback
                    s.focus();
                }
                else {
                    // just display default search text
                    s.value = 'Your search text here';
                    testLoginOrRegister(); // set focus on login, query, register etc.
                }
            }
        }
    }
}


function filterPdfs() {
    var sr = document.getElementById('ctl00_searchresults');
    if (sr != null) {
        if (sr.style.display == 'block') {
            var titleLinks = sr.getElementsByTagName('A');
            for (i = 0; i < titleLinks.length; i++) {
                var link = titleLinks[i].href;
                link = link.toLowerCase();
                //amend all title links referencing pdfs
                if (link.indexOf('.pdf') != -1) {
                    titleLinks[i].target = '_blank'
                }
            }
        }
    }
}

function SaveSearchText() {
    var sb = document.getElementById("q");
    var hiddenControl = document.getElementById('ctl00_inpHide');
    if (sb != null && hiddenControl != null) {
        hiddenControl.value = sb.value;
        //alert('saved search text = ' + sb.value.toString());
        //createCookie('search', sb.value, 1);
    }
}

function RetrieveSearchText() {
    //var x = readCookie('search');
    var sb = document.getElementById("q");
    var hiddenControl = document.getElementById('ctl00_inpHide');
    if (sb != null && hiddenControl != null) {
        sb.value = hiddenControl.value;
    }
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

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) {
    createCookie(name, "", -1);
}

