﻿// St John Ambulance JavaScript
// (c) 2009 St John Ambulance
// Author: Andrew Settle
// Created: 19 May 2009

/* ##############################################
# Functions in this JS file
# - addLoadEvent(func)
# - getObj(name)
# - getElementsByClassName(nodeType,className)
# - createNode(elem,text,className)
# - detectBrowser()
# - createShareLinks()
# - initializeDashboard()
# - processDashboard(Dashboard, DashNum)
# - getCookie(cookieName)
# - processButtonLinks()
# - processButtonLink(ButtonDiv)
# - IndividualTabControl(objTab)
# - getClearDiv()
# - createDashboardTabListItem(Title,TabControl,TabNum)
# - setActiveTab(TabControl,TabNum)
# - changeTabState(TabControl,TabNum)
# - setDashboardItemState(DashNum,State)
# - changeDashboard(objDash,DashNum,State)
# - ieDropDownFix(Select, SelectType)
# - AddBookmark()
# - fontDisplay()
# - getAllSheets()
# - changeStyle()
# - rememberStyle()
# - useStyleAgain()
# - EmailThisPage()
# - selectPassword(Password,rbHasPassword)
# - ValidatePasswordRequired(sender, args)
# - addControlToValidate(FunctionName)
# - validateControls()
################################################*/

/* load/unload events to handle style switcher */
window.onload = function(e) {
    useStyleAgain('styleTestStore');
}
window.onunload = function(e) {
    rememberStyle('styleTestStore',10);
}
addLoadEvent(fontDisplay);

//Provide a means for adding multiple load events
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// Get an object
// Returns the entire object if it is accessible by ID,
// document.all or document.layers
function getObj(name){
  if (document.getElementById) {
  	this.obj = document.getElementById(name);
	if (this.obj != void(0)) {
		this.style = document.getElementById(name).style;
	}
  } else if (document.all) {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  } else if (document.layers) {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}

// returns an array of elements with 
//TagName of nodeType with a class of className
function getElementsByClassName(nodeType,className,rootNode) {
    if (rootNode == void(0)) {
        rootNode = document;
    }
    var pageNodes = rootNode.getElementsByTagName(nodeType);
    var selNodes = new Array();
    for (i=0; i<pageNodes.length; i++){
        if (pageNodes[i].className == className) {
            selNodes.length++;
            selNodes[selNodes.length-1] = pageNodes[i];
        }
    }
    return selNodes;
  }
//legacy implementation of above function
function GetNodeWithClass(nodeType,className) {
    return getElementsByClassName(nodeType,className);
}

// Create a new document node
// TagName = elem
// Class = className
// Text inside tag = text
function createNode(elem,text,className) {
    Node = document.createElement(elem);
    if (text != '') Node.appendChild(document.createTextNode(text));
    if (className != '') Node.className = className;
    return Node;
  }

// Detect the users browser and store the browser ID and major version
// in global variables.  
var Browser = '';
var Version = 0;
function detectBrowser() {
  if (window.navigator.userAgent.indexOf("MSIE") != -1) {
    Browser = 'IE';
    Version = parseFloat(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("MSIE")+4));
  } else if (window.navigator.userAgent.indexOf("Firefox") != -1) {
    Browser = "FF";
    Version = parseFloat(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("Firefox")+8));
  } else if (window.navigator.appName == 'Opera') {
    Browser = "OP";
    Version = parseFloat(window.navigator.appVersion);
  } else if (window.navigator.userAgent.indexOf("Chrome") != -1) {
    Browser = "GC";
    Version = parseFloat(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("Chrome")+7));
  } else if (window.navigator.userAgent.indexOf("Safari") != -1) {
    Browser = "SA";
    Version = parseFloat(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("Version")+7));
  } else {
    Browser = "ZZ";
  }
}

function createShareLinks() {
    var ShareNodes = getElementsByClassName("div","SharePage");
    if (ShareNodes.length > 0) {
        for (sn=0; sn < ShareNodes.length; sn++){
            var ShareUL = ShareNodes[sn].getElementsByTagName("UL");
            //bookmarks only work properly in IE
            if (Browser == 'IE') {
                var bookText = "Add to favourites"
                var li = createNode("li","","");
                var a = createNode("a",bookText,"Bookmark");
                a.setAttribute("href","javascript:AddBookmark()");
                li.appendChild(a);
                ShareUL[0].appendChild(li);
            }
            var li = createNode("li","","");
            var a = createNode("a","Print this page","Print");
            a.setAttribute("href","javascript:window.print()");
            li.appendChild(a);
            ShareUL[0].appendChild(li);
        }
    }
    var EmailNodes = getElementsByClassName("a","Email");
    for (en=0; en < EmailNodes.length; en++) {
        EmailNodes[en].onclick = function(){ EmailThisPage(this.href); return false; }
    }
}

var intNumTabControls = 0;
// Initalise the Dashboard
function initializeDashboard(){
    var objDash = getElementsByClassName("div","DashboardItem");
    var intDashboards = 0;
    for (dN=0; dN < objDash.length; dN++) {
        processDashboard(objDash[dN], intDashboards);
        intDashboards++;
    }
    var cookie = getCookie("TrainingDash");
    for (ck = 0; ck < cookie.length; ck++) {
        // if the item should be closed, close it!
        if (cookie.charAt(ck) == '0') setDashboardItemState(ck,'close'); 
    }
    var cookie = getCookie("TrainingDashTab");
    for (ckt = 0; ckt < cookie.length; ckt++) {
        if (parseInt(cookie.charAt(ckt)) > 0) setActiveTab(ckt,parseInt(cookie.charAt(ckt)));
    }
    
}

// Processes an individual dashboard
// enables the Dashboard Item to be opened/closed
// sets-up TabbedItems to appear as Tabs
// fixes ButtonLinks to display as a button
function processDashboard(Dashboard, DashNum){
    var objDashDivs = Dashboard.getElementsByTagName("div");
    var DashName = '';
    for (DashItems=0; DashItems < objDashDivs.length; DashItems++) {
        switch (objDashDivs[DashItems].className){
        case 'DashboardItemTitle':
            //process the title bar - add in the open/close control
            var objH2 = objDashDivs[DashItems].getElementsByTagName("h2");
            if (objH2.length >= -1) {
                objH2[0].style.cssFloat='left';
                if (objH2[0].id != '') {
                    DashName = objH2[0].id;
                } else {
                    objH2[0].id = 'D'+ DashNum;
                    DashName = 'D' + DashNum;
                }
            }
            var Span = createNode("span","close","");
            var Anchor = document.createElement("a");
            Anchor.setAttribute("href", location.href + "#" + DashName);
            Anchor.onclick = function() { eval("setDashboardItemState(" + DashNum + ",'close');"); return false; }
            Anchor.setAttribute("title","Close");
            Anchor.appendChild(Span);
            var Div = document.createElement("div");
            Div.className = "OpenItem";
            Div.appendChild(Anchor);
            objDashDivs[DashItems].appendChild(Div);
            objDashDivs[DashItems].appendChild(getClearDiv());
            break;
        case "DashboardTabItems":
                //process that tabbed control
                IndividualTabControl(objDashDivs[DashItems]);
                intNumTabControls++;
                break;
        /*case "ButtonLink":
                ProcessButtonLink(objDashDivs[DashItems]);
                break;*/
        }
    }
}

// retrieves a cookie with the given name
function getCookie(cookieName) {
    if (document.cookie.length > 1) {
        StartCookie = document.cookie.indexOf(cookieName + "=");
        if (StartCookie != -1) {
            StartCookie = StartCookie + cookieName.length + 1;
            var EndCookie = document.cookie.indexOf(";",StartCookie);
            if (EndCookie == -1) EndCookie = document.cookie.length;
            return unescape(document.cookie.substring(StartCookie,EndCookie));
        }
    }
    return "";
}

function setCookie(cookieName,cookieValue,isPersistent) {
    var cookieText = cookieName + "=" + escape(cookieValue)
    if (isPersistent) {
        var ExpDate = new Date();
        ExpDate.setDate(ExpDate.getDate()+730);
        cookieText += ";expires=" + ExpDate.toGMTString() + ";"
    }
    cookieText += "path=/";
    document.cookie = cookieText;
}

var buttonLinksHasProcessed = false;
// Process a DIV with class of 'ButtonLink' of 'SmallButtonLink' and insert
// additional SPAN tags to display as a button
function processButtonLinks() {
    if (!(buttonLinksHasProcessed)) {
        var buttonLinks = getElementsByClassName("div","ButtonLink");
        for (bL = 0; bL < buttonLinks.length; bL++) {
            processButtonLink(buttonLinks[bL]);
        }    
        var buttonLinks = getElementsByClassName("p","ButtonLink");
        for (bL = 0; bL < buttonLinks.length; bL++) {
            processButtonLink(buttonLinks[bL]);
        }
        var smBtnLinks = getElementsByClassName("div","SmallButtonLink");
        for (sL = 0; sL < smBtnLinks.length; sL++) {
            processButtonLink(smBtnLinks[sL]);
        }
        var smpBtnLinks = getElementsByClassName("p","SmallButtonLink");
        for (sL = 0; sL < smpBtnLinks.length; sL++) {
            processButtonLink(smpBtnLinks[sL]);
        }
        buttonLinksHasProcessed=true;
   }
}
// function to insert the additional tags
function processButtonLink(ButtonDiv) {
    var a = ButtonDiv.getElementsByTagName("a");
    if (a.length >= 0) {
        a[0].className = "ShowButton";
        var linkText = a[0].innerHTML
        a[0].innerHTML = "";
        var InnerSpan = document.createElement("span");
        InnerSpan.appendChild(document.createTextNode(linkText));
        var OuterSpan = document.createElement("span");
        OuterSpan.appendChild(InnerSpan);
        a[0].appendChild(OuterSpan);
    }
}

// Create a TABBED control. The tab control should have
// an empty DIV tag with a class of 'DashboardTabs' into
// which the TABS are placed.
// The title for each TAB is given via a H3 heading
// The contents for each TAB (including the heading) are
// wrapped in a DIV tag with a class of 'DashboardTabContent'
function IndividualTabControl(objTab){
    // get all the divs in that tab control
    var objTabItems = objTab.getElementsByTagName("div"); 
    var objH2 = objTab.getElementsByTagName("h2");
    var objUl = document.createElement("ul");
    var objTabs;
    
    var intNumTabs = 0;
    for (ti=0; ti < objTabItems.length; ti++) {
        switch (objTabItems[ti].className) {
            case "DashboardTabs":
                objTabs = objTabItems[ti];
                break;
            case "DashboardTabContent":
                //find the heading, add it to objUl, hide it
                var objH3 = objTabItems[ti].getElementsByTagName("h3");
                if (objH3.length >= 0) {
                    objUl.appendChild(createDashboardTabListItem(objH3[0].innerHTML, intNumTabControls,intNumTabs));
                    objH3[0].style.display = 'none';
                }
                //if intNumTabs = 0 then show the tab content, otherwise hide it
                if (intNumTabs == 0){
                } else {
                    objTabItems[ti].style.display = 'none';
                }
                intNumTabs++;
                break;
             default:
                //not sure
                break;                
        }
    }
    if (objTabs == (void(0))) {
        alert("Tab control is missing required DIV with class of 'DashboardTabs' inside of a DIV with class 'DashboardTabItems'");
    } else {
        objTabs.appendChild(objUl);
        objTabs.appendChild(getClearDiv());
    }
    
}

// Returns a DIV with a class of 'clear'
function getClearDiv(){
    return createNode("div"," ","clear");
}

// Returns a HTML list item to create the TABS
// It initializes with the first tab set as active
// all other tabs are therefore set as inactive
function createDashboardTabListItem(Title,TabControl, TabNum){
    var ListItem = document.createElement("li");
    var Anchor = document.createElement("a");
    Anchor.setAttribute("href", location.href + "#"+ TabControl+TabNum);
    if (TabNum == 0){
        ListItem.className = 'ActiveTab';
    } else {
        ListItem.className = 'InactiveTab';
    }
    Anchor.appendChild(document.createTextNode(Title));
    Anchor.onclick = function() { setActiveTab(TabControl,TabNum); return false; }
    ListItem.appendChild(Anchor);
    return ListItem;
}

// Finds the referenced TabControl and then calls
// ChangeTabState to actually change the active tab
function setActiveTab(TabControl,TabNumber) {
    var intTabControlsFound = 0;
    if (document.getElementsByTagName) {
        // get all the divs
        var objDiv = document.getElementsByTagName("div");
        //find a div with the class name "DashboardTabItems"
        for (dC=0; dC < objDiv.length; dC++) {
            if (objDiv[dC].className == "DashboardTabItems") {
                //process that tabbed control
                if (intTabControlsFound == TabControl) {
                    changeTabState(objDiv[dC],TabNumber);
                    setTabCookie(TabControl,TabNumber);
                }
                intTabControlsFound++;
            }
        }
    }
}

// Changes the TabState for the referenced TabControl
// to show the selected TabNumber as active. It also
// hides the content for other tabs whilst unhiding the
// content for the active tab
function changeTabState(TabControl,TabNumber){
    var objDiv = TabControl.getElementsByTagName("div");
    var intNumTabs = 0;
    for (dC=0; dC < objDiv.length; dC++) {
        switch (objDiv[dC].className) {
            case "DashboardTabs":
                var objUl = objDiv[dC].getElementsByTagName("li");
                for (liC = 0; liC < objUl.length; liC++){
                    if (liC == TabNumber) {
                        objUl[liC].className = 'ActiveTab';
                    } else {
                        objUl[liC].className = 'InactiveTab';
                    }
                }
                break;
            case "DashboardTabContent":
                //if intNumTabs = 0 then show the tab content, otherwise hide it
                if (intNumTabs == TabNumber){
                    objDiv[dC].style.display = 'block';
                } else {
                    objDiv[dC].style.display = 'none';
                }
                intNumTabs++;
                break;
             default:
                //not sure
        }
    }
}

// sets the given dashboard number to the state
function setDashboardItemState(DashNum, State) {
    var objDiv = getElementsByClassName("div","DashboardItem");
    var intDashboards = 0
    for (dC=0; dC < objDiv.length; dC++) {
        if (intDashboards == DashNum) {
            changeDashboard(objDiv[dC], DashNum, State);
            setDashboardCookie(DashNum, State);
            intDashboards++;
        } else {
            intDashboards++;
        }
    }
}

function setDashboardCookie(DashNum,State) {
    var cookie = getCookie("TrainingDash");
    if (cookie.length < DashNum) {
        for (pad = cookie.length; pad < DashNum + 1; pad++) {
            cookie += '1'; //'cos it is open by default!
        }
    }
    var cookieVal
    if (State == 'close') {
        cookieVal = '0';
    } else {
        cookieVal = '1';
    }
    cookie = cookie.substring(0,DashNum) + cookieVal + cookie.substr(DashNum + 1);
    setCookie("TrainingDash",cookie,true);
}

function setTabCookie(TabControlNum,TabNum){
    var cookie = getCookie("TrainingDashTab");
    if (cookie.length < TabControlNum) {
        for (pad = cookie.length; pad < DashNum + 1; pad++) {
            cookie += '0'; //'cos we default to the first tab
        }
    }
    cookie = cookie.substring(0,TabControlNum) + TabNum + cookie.substr(TabControlNum + 1);
    setCookie("TrainingDashTab", cookie,true);
}

function changeDashboard(objDash, DashNum, State){
    var objDashDiv = objDash.getElementsByTagName("div");
    for (DivNum = 0; DivNum < objDashDiv.length; DivNum++) {
        switch (objDashDiv[DivNum].className) {
            case "OpenItem":
                objDashDiv[DivNum].className = "CloseItem";
                objDashDiv[DivNum].innerHTML = objDashDiv[DivNum].innerHTML.replace("close","open");
                objDashDiv[DivNum].innerHTML = objDashDiv[DivNum].innerHTML.replace("Close","Open");
                var Anchor = objDashDiv[DivNum].getElementsByTagName('a');
                if (Anchor.length >= 0) {
                    Anchor[0].onclick = function() { eval("setDashboardItemState(" + DashNum + ",'open');"); return false; }
                }
                break;
            case "CloseItem":
                objDashDiv[DivNum].className = "OpenItem";
                objDashDiv[DivNum].innerHTML = objDashDiv[DivNum].innerHTML.replace("open","close");
                objDashDiv[DivNum].innerHTML = objDashDiv[DivNum].innerHTML.replace("Open","Close");
                var Anchor = objDashDiv[DivNum].getElementsByTagName('a');
                if (Anchor.length >= 0) {
                    Anchor[0].onclick = function() { eval("setDashboardItemState(" + DashNum + ",'close');"); return false; }
                }
                break;
            case "DashboardContent":
            case "DashboardTabItems":
                if (State == 'close') {
                    objDashDiv[DivNum].style.display = 'none';
                } else {
                    objDashDiv[DivNum].style.display = 'block';
                }
        }
    }
}

function ieDropDownFix(Select,SelectType){
    if (Browser != 'IE') {
        return false;
    } else if (SelectType == 'focus') {
        Select.style.position = 'absolute';
        Select.style.width = 'auto';
    } else {
        Select.style.position = '';
        Select.style.width = '';
    }
}

 function AddBookmark(){
  //different browsers handle it differently
    if (document.all) {
        window.external.addFavorite(document.location.href,document.title);
    } else {
        alert("Your browser doesn't support adding bookmarks directly. Please add from the bookmarks menu.");
    }
  }
  
  function fontDisplay() {

  if (navigator.appName == 'Microsoft Internet Explorer' && navigator.platform == 'MacPPC' || !document.getElementById || !document.getElementById("SubNav")) return false;

  var div = document.createElement("div");
  var h2 = document.createElement("h3");
  h2.appendChild(document.createTextNode("Font size:"));  
  h2.setAttribute("class", "NoShow");
  h2.setAttribute("className", "NoShow");
  
  var ulist = document.createElement("ul");
  ulist.setAttribute("id","fonts");

  var listitem1 = document.createElement("li");
  var ahref1 = document.createElement("a");
  var off1 = document.createElement("span");

  listitem1.setAttribute("class", "sma");
  listitem1.setAttribute("className", "sma");
  ahref1.setAttribute("href","#");
  off1.setAttribute("class", "NoShow");
  off1.setAttribute("className", "NoShow");

  off1.appendChild(document.createTextNode("Regular font size "));
  ahref1.appendChild(off1);
  ahref1.appendChild(document.createTextNode("A"));
  listitem1.appendChild(ahref1);


  var listitem2 = document.createElement("li");
  var ahref2 = document.createElement("a");
  var off2 = document.createElement("span");

  listitem2.setAttribute("class", "med");
  listitem2.setAttribute("className", "med");
  ahref2.setAttribute("href","#");
  off2.setAttribute("class", "NoShow");
  off2.setAttribute("className", "NoShow");

  off2.appendChild(document.createTextNode("Medium font size "));
  ahref2.appendChild(off2);
  ahref2.appendChild(document.createTextNode("A"));
  listitem2.appendChild(ahref2);


  var listitem3 = document.createElement("li");
  var ahref3 = document.createElement("a");
  var off3 = document.createElement("span");

  listitem3.setAttribute("class", "lar");
  listitem3.setAttribute("className", "lar");
  ahref3.setAttribute("href","#");
  off3.setAttribute("class", "NoShow");
  off3.setAttribute("className", "NoShow");
  off3.appendChild(document.createTextNode("Large font size "));
  ahref3.appendChild(off3);
  ahref3.appendChild(document.createTextNode("A"));
  listitem3.appendChild(ahref3);


  ulist.appendChild(listitem1);
  ulist.appendChild(listitem2);
  ulist.appendChild(listitem3);

  var fontch = document.getElementById("SubNav");
  div.appendChild(h2);
  div.appendChild(ulist);
  fontch.appendChild(div);

  ahref1.onclick = function () {changeStyle(''); return false}
  ahref2.onclick = function () {changeStyle('med'); return false}
  ahref3.onclick = function () {changeStyle('lar'); return false}

  ahref1.onmouseover = function () {window.status=''; return true}
  ahref2.onmouseover = function () {window.status=''; return true}
  ahref3.onmouseover = function () {window.status=''; return true}
}

// Stylesheet switcher

function getAllSheets() {
	if( !window.ScriptEngine && navigator.__ice_version ) {
        return document.styleSheets;
    }
	if( document.getElementsByTagName ) {
        var Lt = document.getElementsByTagName('link'), St = document.getElementsByTagName('style');
	} else if(
        document.styleSheets && document.all ) { var Lt = document.all.tags('LINK'), St = document.all.tags('STYLE');
	} else { return []; } for( var x = 0, os = []; Lt[x]; x++ ) {
		var rel = Lt[x].rel ? Lt[x].rel : Lt[x].getAttribute ? Lt[x].getAttribute('rel') : '';
		if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) { os[os.length] = Lt[x]; }
	}
    for(var x = 0; St[x]; x++ ) {
        os[os.length] = St[x];
    }
    return os;
}

function changeStyle() {
	window.userHasChosen = window.MWJss;
	for( var x = 0, ss = getAllSheets(); ss[x]; x++ ) {
		if( ss[x].title ) { ss[x].disabled = true; }
		for( var y = 0; y < arguments.length; y++ ) { if( ss[x].title == arguments[y] ) { ss[x].disabled = false; } }
} }

function rememberStyle( cookieName, cookieLife ) {
	for( var viewUsed = false, ss = getAllSheets(), x = 0; window.MWJss && ss[x]; x++ ) {
        if( ss[x].disabled != MWJss[x] ) {
            viewUsed = true;
            break;
        }
    }
	if( !window.userHasChosen && !viewUsed ) {
        return;
    }
	for( var x = 0, outLine = '', doneYet = []; ss[x]; x++ ) {
		if( ss[x].title && ss[x].disabled == false && !doneYet[ss[x].title] ) {
            doneYet[ss[x].title] = true;
            outLine += ( outLine ? ' MWJ ' : '' ) + escape( ss[x].title );
        }
    }
	if( ss.length ) {
        document.cookie = escape( cookieName ) + '=' + escape( outLine ) + ( cookieLife ? ';expires=' + new Date( ( new Date() ).getTime() + ( cookieLife * 86400000 ) ).toGMTString() : '' ) + ';path=/';
    }
}

function useStyleAgain( cookieName ) {
	for( var x = 0; x < document.cookie.split( "; " ).length; x++ ) {
		var oneCookie = document.cookie.split( "; " )[x].split( "=" );
		if( oneCookie[0] == escape( cookieName ) ) {
			var styleStrings = unescape( oneCookie[1] ).split( " MWJ " );
			for( var y = 0, funcStr = ''; styleStrings[y]; y++ ) { funcStr += ( y ? ',' : '' ) + 'unescape( styleStrings[' + y + '] )'; }
			eval( 'changeStyle(' + funcStr + ');' );
            break;
	   }
    }
    window.MWJss = []; for( var ss = getAllSheets(), x = 0; ss[x]; x++ ) {
        MWJss[x] = ss[x].disabled;
    }
}

function EmailThisPage(href){
    window.open(href,'_blank','width=450,height=480');
    return false;
}

//### Login functions
function selectPassword(Password,rbHasPassword) {
        var rb = new getObj(rbHasPassword);
        if (Password != '') {
            rb.obj.checked = true;
        }
    }

function ValidatePasswordRequired(sender, args){
    var rb = new getObj(rbExistingUserId);
    if ((rb.obj.checked) && (args.Value == '')) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

var ControlsToValidate = new Array();
var ButtonPressed = "";

//Provides a utility to specify functions to call to validate controls
function addControlToValidate(FunctionName){
    ControlsToValidate[ControlsToValidate.length++] = FunctionName;
    }

function validateControls() {
    var PassedValidation = true;
    for (i=0; i<ControlsToValidate.length; i++){
        if (!ControlsToValidate[i]()) PassedValidation=false;
        }
    return PassedValidation;
    }
