/**
*
* these scripts are used for accessibility: switching between alternate style sheets
* author: rsharp, AShrivastava
* client: esfrs
* date created: 3/11/09
* version: 1.0.1
* since: 1.0.0
* 1.0.0 - 3/11/09 - version 1 created
* 1.0.0 - 5/11/09 - Added function matchBlocksHeight() to match the height of blocks on text resize. -AShrivastava
**/

/**
 * Following is a script level call to setPageStyle() function which reassures that style is set before
 * other components are rendered, this avoids any flickering at page load.
 */
var readyState = false;
setPageStyle();
/**
 * On page load following function allows us to chain events to window.onload event.
 * @param functionToAdd: (Function-Object) The function that needs to be added in the chain of onload event.
 */
function addEventToPageLoad(functionToAdd) {
    var defaultOnLoad = window.onload;
    if(typeof defaultOnLoad == 'function') {
        window.onload = function() {
            if (defaultOnLoad) {
                defaultOnLoad();
            }
            functionToAdd();
        }
    } else {
        window.onload = functionToAdd;
    }
}

/**
 * Following list of method-calls is used to chain events to window.onload event.
 */
//addEventToPageLoad(setPageStyle);
addEventToPageLoad(matchBlocksHeight);
addEventToPageLoad(toggleJumpToTopDisplay);


/**
 * Following list of method-calls is used to chain the functions to event-handler.
 */
Event.observe(window, 'scroll', toggleJumpToTopDisplay);

/**
 * creates a cookie with active style sheet stored
 */
Event.observe(window, 'unload', function(){
    var title = getActiveStyleSheet();
    setCookie("style", title, 365);
});

/**
 * Resizes/matches the block's borders when windos is resized.
 */
Event.observe(window, 'resize', matchBlocksHeight);

/**
 * Following function handles: cookies, stylesheets, font-size etc.
 */
function setPageStyle() {
    var cookie = getCookie("style");
    //var title = cookie ? cookie : getPreferredStyleSheet(); // Removed since function only/always returns String "default"
    var title = cookie ? cookie : 'default';
    setActiveStyleSheet(title);
}

/**
 * sets a style sheet
 * @param title - the name of a style sheet
 */
function setActiveStyleSheet(title) {
    var i=0, elem=$$("link[title]");ifras = null;
    for(i=0; i < elem.length; i++) {
        elem[i].disabled = true;
        if(elem[i].getAttribute("title") == title){
            elem[i].disabled = false;
        }
    }
    if(!window.frameElement){ //making sure that only container/shtml will execute the following code NOT the iframe/object.
        ifras=window.frames; //ifras=$$("iframe");
        if(ifras.length>0){
            for(i=0; i < ifras.length; i++) {
                if(ifras[i].document.getElementsByTagName('h1')[0] == undefined){ // if "iframe.document.element" is available (instead of iframe.contentWindow) i.e. a plain server-generated output (e.g. 404 error) is sent rather than the actual generated content.
                    ifras[i].setActiveStyleSheet(title);
                }
                //resizeSystemFrames(ifras[i]); //not needed since iframe's size does NOT change when page-style is switched - Ed.
            }
        }
        if(this.readyState) highlightElement(($$('#leftNavBar a[style]')[0]));//Executes via switchers (Does not execute on page-load/reload) Applies style to highlighted menu-item on leftNavBar.
    }
}


/**
 * resizes the frame to fit content
 * @param ifra - the frame/iframe that needs to be resized.
 */
function resizeSystemFrames(ifra){
    var h=0;
    if(ifra.contentWindow != undefined){
        if(/MSIE/i.test(navigator.userAgent)) h=ifra.contentWindow.document.body.scrollHeight;
        else h=ifra.contentWindow.document.body.offsetHeight;
        ifra.style.height = h + "px";
        //ifra.style.position = "relative";  // this is needed for <=IE7.
        ifra.style.overflow = "hidden";
    }
}

/**
 * returns the currently active style sheet
 */
function getActiveStyleSheet() {
    var i=0, elem=$$("link");
    for(i=0; i < elem.length; i++)
        if(elem[i].getAttribute("rel").indexOf("style") != -1 && elem[i].getAttribute("title") && !elem[i].disabled)
            return elem[i].getAttribute("title");
    return null;
}

/**
 * returns the preferred style sheet i.e. the default style sheet
 */
/*
function getPreferredStyleSheet() {
    var i=0, elem=null;
    for(i=0; (elem = $$("link")[i]); i++) {
        if(elem.getAttribute("rel").indexOf("style") != -1
            && elem.getAttribute("rel").indexOf("alt") == -1
            && elem.getAttribute("title")
                ){
                    return elem.getAttribute("title");
                }
    }
    return 'default';
}
*/

/**
 * Matches the height of the blocks in the centralPanel, when user a) resizes the text b) resizes the window :
 */
function matchBlocksHeight() {
    if($("centrePanelRowWrapper1")){  //if condition makes sure that the rest of the code will only run if the page is home page.
        var rows=1, maxHeight=0, i=0;  //int type variables declarations.
        var blocksInRow = null, totRows = $$("div.centrePanelRow"), divandid = "div#centrePanelRowWrapper";  //String type variables declarations.
        if((vcBlock=$$("div.vCentre")) && (!((navigator.appVersion.toString().charAt(navigator.appVersion.toString().indexOf("MSIE")+5))<8))){
            maxHeight = 0;
            for (i=0; i<vcBlock.length; i++){
                vcBlock[i].firstChild.firstChild.style.height = "auto";
                vcBlock[i].style.height = "auto";
                if (maxHeight < vcBlock[i].offsetHeight) maxHeight = vcBlock[i].offsetHeight;//window.getComputedStyle(vcBlock[i],null).height
            }
            for (i=0; i<vcBlock.length; i++){
                vcBlock[i].firstChild.firstChild.style.height = maxHeight+"px";
                vcBlock[i].style.height = maxHeight+"px";
                vcBlock[i].style.display = "none"; /* re-drawing the div to solve IE's issue of display-refresh. */
                vcBlock[i].style.display = "block";
            }
        }
        for(; rows<=totRows.length; rows++){
            blocksInRow = $$(divandid + rows + ">div");
            maxHeight = 0;
            for (i=0; i<blocksInRow.length; i++){
                //if(blocksInRow[i].getAttribute("className") == "midBlockContainer")blocksInRow[i] = blocksInRow[i].firstDescendant(); // IE fix: runs only in IE. // Removed & used faster approach to achieve same effect - Ed.
                blocksInRow[i].style.height = "auto";
                if (maxHeight < blocksInRow[i].offsetHeight) maxHeight = blocksInRow[i].offsetHeight;
            }
            for (i=0; i<blocksInRow.length; i++) blocksInRow[i].style.height = maxHeight+"px";
        }
    }
    this.readyState = true;
    
    // Following code decreases gaps between external-icons & links-images (only when external-links are images:
    if( $$("a.external>img").length > 0 ){
        var iteration=0, xAnchors=$$("a.external");
        for(; iteration < xAnchors.length; iteration++) {
            if(xAnchors[iteration].firstChild.tagName == "IMG"){
                //xAnchors[iteration].paddingRight = "0px"; // Doesn't work since the pseudo classes :visited etc. override it.
                xAnchors[iteration].setAttribute("style","padding-right:17px;");
            }
        }
    }
}

/**
 * Opens a link in a new tab.
 * @param anchor: (Element) anchor element whose target needs to be opened in a new tab.
 */
function openInNewTab(anchor){
    anchor.target='_blank';
}

/**
 * Toggles the display of string "Enter search terms" within the search box.
 * @param box: (Element) Textbox element where string needs to be displayed.
 * @param hasFocus: (Boolean) To determine whether focus has been received or lost.
 */
function searchBoxMsg(box,hasFocus) {
    var strSearchMsg = 'Enter search terms';
    if(hasFocus==true && box.value==strSearchMsg){
        box.value=''
    }
    else if(hasFocus==false && box.value.strip()==''){
        box.value=strSearchMsg;
    }
}

/**
 * Following code toggles the display of the jump to top button.
 */
function toggleJumpToTopDisplay(){
    var jtt=null;
    if(jtt = $('jumpToTop')){
        if(document.viewport.getScrollOffsets()[1] > 9) jtt.style.visibility = 'visible';
        else jtt.style.visibility = 'hidden';
    }
}

/**
 * At page load, following function highlights current category's menu or sub-menu item on the LeftNavBar.
 */
function highlightCurrentMenu(){
    var qStr="", url="", menus=null, i=0;
    url = document.location.href ? document.location.href : document.location; // For cross-browser compatibility.
    qStr = url.substring(7);
    qStr = qStr.substring(qStr.indexOf("/"),(qStr.lastIndexOf("#")!=-1?qStr.lastIndexOf("#"):qStr.length));
    if(/\/stations\/stations\//i.test(qStr) || /\/stations\/boroughs\//i.test(qStr)){
        menus = $$('a[href="/stations/index.shtml"]');
        highlightElement(menus[1]);
        return;
    }else if(/\/communitySafety\/safetyAdvice\//i.test(qStr)){
        menus = $$('a[href="/communitySafety/fsAtHome.shtml"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/news\//i.test(qStr)){
        menus = $$('a[href="/news/"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/stations\/blaze*/i.test(qStr)) {
        menus = $$('a[href="/stations/blaze.shtml"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/planning\//i.test(qStr)){
        menus = $$('a[href="/planning/index.shtml"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/hsv.shtml/i.test(qStr)){
        menus = $$('a[href="/communitySafety/"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/equality\/protectedCharacteristics/i.test(qStr)) {
        menus = $$('a[href="/equality/protectedCharacteristics.shtml"]');
        highlightElement(menus[0]);
        return;
    }else if(/\/equality\/entryPages/i.test(qStr)) {
        menus = $$('a[href="/equality/index.shtml"]');
        highlightElement(menus[0]);
        return;
/*
    }else if(/\/equality\//i.test(qStr) && !(/\/equality\/equalityStrands\//i.test(qStr))){   //excluding subfolder.
        menus = $$('a[href="/equality/index.shtml"]');
        highlightElement(menus[0]);
        return;
*/
    }else{
        menus = $$("#leftNavBar a");
        //if(qStr.charAt(qStr.length-1) == '/') qStr += "index.shtml";
        for(i=0;i<menus.length;i++){
            if(qStr == menus[i].getAttribute('href') || qStr+"index.shtml" == menus[i].getAttribute('href')  || qStr == menus[i].getAttribute('href')+"index.shtml" || qStr == menus[i].getAttribute('href')+"/" ||
                url == menus[i].getAttribute('href') || url+"index.shtml" == menus[i].getAttribute('href')  || url == menus[i].getAttribute('href')+"index.shtml" || url == menus[i].getAttribute('href')+"/"){  /* url is added since in IE <= IE7 getAttribute() returns the full-URL instead of just what's written in href attribute - Ed. */
                highlightElement(menus[i]);
                return;
            }
        }
    }
}
addEventToPageLoad(highlightCurrentMenu);  //to chain passed event to window.onload.


/**
 * Following highlights/styles the passed element (which typically should be menu or sub-menu item on the LeftNavBar).
 * @param elem - HTMLELement : that needs to be styled/highlighted.
 */
function highlightElement(elem){
    if(elem){//If an iframe is using this js file, this function gets called (from within iframe) parameter elem gets assigned with null.
        var displayStyle = getActiveStyleSheet()?getActiveStyleSheet():'default'; // sets 'default' style if cookies are disabled.
        elem.style.fontWeight = 'bold';
        if(displayStyle == 'default'){
            elem.style.border = "2px solid #f0f0f0";
            elem.style.borderLeftWidth = "0";
            elem.style.color = "#900000";
            elem.style.backgroundColor = "#fff";
        }
        else{
            elem.style.border = "2px solid #232323";
            elem.style.borderLeftWidth = "0";
            elem.style.color = "#fff";
            elem.style.backgroundColor = "#000";
        }
    }
}


/**
 * Following function indents all the subsequent lines (not the first-line) of List-Items:
 */
function indentListItems(){
    var i=0;
    var strUA = navigator.userAgent;
    var newItem=null, hashElems = {
        ulWithDisc:$$("#contentBlock ul.ulWithDisc li"),
        ulWithCircle:$$("#contentBlock ul.ulWithCircle li"),
        ulWithSquare:$$("#contentBlock ul.ulWithSquare li"),
        olWithAlphabets:$$("#contentBlock ol.olWithAlphabets li"),
        olWithRoman:$$("#contentBlock ol.olWithRoman li")
    };
    for (lst in hashElems){
        if(hashElems[lst].length>0)
            for(i=0; i<hashElems[lst].length; i++){
                newItem = document.createElement("div");
                newItem.style.marginTop = "-3ex";
                if(parseInt(navigator.appVersion.toString().charAt(navigator.appVersion.toString().indexOf("MSIE")+5))<8 || /Safari/i.test(strUA)){ // || /Chrome/i.test(strUA) && (hashElems[lst][i].childNodes[0].tagName == undefined || hashElems[lst][i].childNodes[0].NodeType>1)
                    newItem.style.marginTop = "0";
                    newItem.style.textIndent = "-0.8em";
                }
                newItem.style.marginLeft = "3ex";
                newItem.innerHTML = hashElems[lst][i].innerHTML;
                hashElems[lst][i].innerHTML ="";
                /* Had to use innerHtml instead of childNodes[] due to browser compatibility issues.
                for(j=0; j<hashElems[lst][i].childNodes.length;j++){
                    newItem.removeChild(hashElems[lst][i].childNodes[j]);
                }
                */
                hashElems[lst][i].appendChild(newItem);
            }
    }
}
//if(!window.frameElement){addEventToPageLoad(indentListItems);//to chain passed event to window.onload, but only from top-level window (NOT from within an Iframe/object that causes function to run twice.)


/**
 * Following function looks for duplicate IDs or all elements in a page, if found, it prints an error message on the firebug's console:
 */
function findDuplicateIDs() {
    $$('[id]').each(function(elemWithID){
        var elemsWithSameID = $$('[id='+elemWithID.id+']');
        if(elemsWithSameID.length > 1){
            elemsWithSameID.each(function(elemWithDupID){
                if(elemWithID == elemWithDupID)
                    console.error("Duplicate Tag-ID: \"%s\" has been detected under <%s> element.", elemWithID.id, elemWithID.tagName);
            });
        }
    });
}
addEventToPageLoad(findDuplicateIDs);  //to chain passed event to window.onload.

