/*
----------------- 3. Hide the secondry nav for user with JS enabled -----------------------------*/

var hide = {
    hideLinks: function () {
        if (!document.getElementById || !g.id("products")) {
            return false;
        }
        g.id("products").style.display = "none";
    }
};

/*
-----------------  4. Set up Tabindex -------------------------------------------------------*/

var setTabIndex = {

    /** Give top area a tabindex in increments of 1 so this is always the area tabbed through first **/
    topArea: function () {

    /*Give first link in page tabindex1, this is required as the myaccounts popup run off this,
    Then find out how many links will be within the generated popup box so that the next links tabindex will be one more than the 
    last link within the popup box*/
        if (!document.getElementById || !g.id("orientation") || !g.id("accounts") || !g.id("accounts-products") || !g.tn || !g.tn("a") || !g.idTn("skiplink", "a")) {
            return false;
        }
        var skip = g.idTn("skiplink", "a");
        skip[0].setAttribute("tabIndex", 1);
        var myaccounts = g.id("accounts").setAttribute("tabIndex", 2);
        var myaccoutspoplinks = g.idTn("accounts-products", "a");		
        var localTabindex = myaccoutspoplinks.length + 2;
        var topSectionLinks = g.idTn("orientation", "a");
        for (var i = 0; i < topSectionLinks.length; i++) {
            topSectionLinks[i].setAttribute("tabIndex", localTabindex);
            localTabindex ++;
        }
    },

/** Give top links a tabindex value in increments of 100 **/
    primNav: function () {
        if (!document.getElementById || !g.id("nav-primary") || !g.id("wrapper") || !document.getElementsByTagName || !g.tn("a")) {
            return false;
        }
        var topTabLinks = g.idTn("nav-primary", "a");
        var parent = g.id("wrapper");
        var tabTabindex = 100;
        for (var i = 0; i < topTabLinks.length; i++) {
            topTabLinks[i].setAttribute("tabIndex", tabTabindex);
            tabTabindex = tabTabindex + 100;
        }
    }
};

/*
-----------------  5. Round corners - Buttons & Boxes ------------------------------------------------------*/	

// Get links that are buttons, place these links within a <span> and <div> then append back in page
// Also change the name of the parent contaier div to allow for styling of button without JavaScript

var roundCorners = {
    /** Buttons **/
    buttons: function () {
        var links = /*g.tn("a");*/ document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if ((links[i].className && (' ' + links[i].className + ' ').indexOf(' round ') !== -1) && (links[i].className && (' ' + links[i].className + ' ').indexOf(' tcbutton ') === -1)) {
                // Create Button and surrounding elements
                var emptyDiv = g.ceCn("div", "emptybut");
                var button = g.ceCn("div", "button");
                var span = g.ce("span");
                // Assign current link to a variable and give its parent an id, replace the divs className
                var parentTest = links[i];
                var buttonContainer = roundCorners.getButtonContainer(parentTest);
                buttonContainer.setAttribute("id", "container" + i);
                var getCurrentClass = buttonContainer.className;
                var startPos = getCurrentClass.indexOf(getCurrentClass);
                var restOfString = getCurrentClass.substr(startPos + 17);			
                var containerDiv = g.id("container" + i);			
                containerDiv.className = "js-button-container " + restOfString;
                // Apend elements to their parents
                span.appendChild(links[i]);
                button.appendChild(span);
                containerDiv.appendChild(emptyDiv);
                containerDiv.appendChild(button);
            }
        }				
    },

/** Boxes **/
    boxes: function () {
        var div = g.tn("div");
        for (var i = 0; i < div.length; i++) {
        // Find the Divs witht the className corners
            if ((div[i].className && (' ' + div[i].className + ' ').indexOf(' corners ') !== -1) && (div[i].className && (' ' + div[i].className + ' ').indexOf(' tccontainer ') === -1)) {
                // Create elements to be appended to page
                var emptyDiv = g.ceCn("div", "empty");
                var inner = g.ceCn("div", "inner");
                inner.setAttribute("id", "inner" + [i]);
                // Get the element from the document.  (Corresponds to the className)
                // Get all of the child elements and store in an array called "boxContentArray"
                if (!g.id(div[i].id)) {
                    return false;
                }
                var container = g.id(div[i].id);
                container.style.border = "0";
                var boxContentArray = g.elementWrap(container);
                // Append Elements back on page and Loop through "boxContentArray" array appending a new child on each loop
                var boxContent = g.ceCn("div", "box-content clearing");
                for (var k = 0; k < boxContentArray.length; k++) {
                    boxContent.appendChild(boxContentArray[k]);
                }
                inner.appendChild(boxContent);
                container.appendChild(inner);

                // Insert an empty div before the newly created inner Div element			
                var currentInner = g.id("inner" + [i]);
                var parentDiv = currentInner.parentNode;				
                parentDiv.insertBefore(emptyDiv, currentInner);
            }
        }
    },

    // Get parent node until DIV with className button-container
    getButtonContainer: function (node) {
        if (node.nodeName === "DIV" && node.className.indexOf("button-container") !== -1) {
            return node;
        }
        if (node.className.indexOf("button-container") === -1) { 
            return roundCorners.getButtonContainer(node.parentNode);
        }
        return null;
    }

};

/*
-----------------  6. Convert lists to to Select box -------------------------------------------------------*/
// Take an unordered list and convert it to a select box.
// This function will also take the nearest header and use it as the select box label 

var listSelectConversion = {
    listToDrop: function () {
        listSelectConversion.convertMeToDrop("retrieve", "rquote");
        listSelectConversion.convertMeToDrop("bm", "landc");
    },

    convertMeToDrop: function (a, b) {
        if (!document.getElementById || !g.id(a) || !g.id(b) || !document.createElement) {
            return false;
        }
        var box = g.id(a);
        var innerBox = g.id(b);
        // Get all the links within the retrieve list and store them in an array to allow us to build them up for the select box
        var links = [];
        var listItemLinks = g.idTn(b, "a");
        for (var i = 0; i < listItemLinks.length; i++) {
            links.push(listItemLinks[i]);
        }

    // Create select box
        var selectElement = g.ce("select");
        selectElement.setAttribute("id", a + "-quote");
        selectElement.setAttribute("name", a + "page");
        selectElement.setAttribute("autocomplete", "off");
        for (var j = 0; j < links.length; j++) {
            var option = g.ceA("option", "value", links[j].href);
            var optionText = document.createTextNode(links[j].lastChild.nodeValue);
            option.appendChild(optionText);	
            selectElement.appendChild(option);
        }

        // Create input button
        var inputElement = g.ceA("input", "type", "submit");
        inputElement.setAttribute("value", "Go");
        inputElement.setAttribute("autocomplete", "off");
        inputElement.onclick = function () {
            var getSelectedItem = g.id(a + "-quote");
            var getForm = g.id(a + "-form");
            var getUrl = (getSelectedItem[getSelectedItem.selectedIndex].value);
            window.open(getUrl);
        };

    // Append elements back to page
        box.replaceChild(selectElement, innerBox);
        var dropDown = g.id(a + "-quote");
        g.insertAfter(inputElement, dropDown);

// Get all elements within the retrieve div and place them within a div, if their is an h3 wrap it in a label

        var contentArray = g.elementWrap(box);

        var form = g.ceA("form", "action", "");
        form.setAttribute("id", a + "-form");
        form.setAttribute("method", "get");

// Check for a heading element and wrap the contents of the h3 within a label
        for (var k = 0; k < contentArray.length; k++) {
            if (contentArray[k].nodeName === "H1" || contentArray[k].nodeName === "H2" || contentArray[k].nodeName === "H3" || contentArray[k].nodeName === "H4") {
                contentArray[k].setAttribute("id", "title" + k);
                var label = g.ceA("label", "for", a + "-quote");
                var headerKids = contentArray[k].childNodes;
                for (var n = 0; n < headerKids.length; n++) {
                    label.appendChild(headerKids[n]);
                }
                var header = g.id("title" + k);
                header.appendChild(label);
            }
            form.appendChild(contentArray[k]);	
        }
        box.appendChild(form);	
    }
};

/*
-----------------  7. Navigation Popups  -------------------------------------------------------*/

// Pass the array as an argument, with the parent container and wrapper values also

/** Create popups box areas and append to page **/
var nav = {


// Create array which is a reference to the tabs id
    tabs: ["ins", "cards", "loan", "mort", "save", "tra"],

/** Build the popup nav **/
    constructPop: function () {
    // Loop through the links array getting all the list items and adding them to the paretnLink Array
        for (var i = 0; i < nav.tabs.length; i++) {				
            var parentLink = [];
            var area = nav.tabs[i] + "-products";
            if (!document.getElementById(area)) {
                return false;
            }
            var li = document.getElementById(area).getElementsByTagName("li");
            for (var k = 0; k < li.length; k++) {
                var findTheUL = g.getParentUL(li[k]);
                if (findTheUL.parentNode.id === area) {
                    var copyOfLI = li[k].cloneNode(true);
                    parentLink.push(copyOfLI);
                }
            }	

        // Create all page elements 
            var boxStyle = area + "-box";
            var div1 = document.createElement("div");
            div1.className = boxStyle;
            div1.style.visibility = "hidden";
            var div2 =  document.createElement("div");
            div2.className = "innerbox";
            var div3 =  document.createElement("div");
            div3.className =  "productslinks clearing";
            var div4 =  document.createElement("div");
            div4.className = "prodleft";
            var ulLeft = document.createElement("ul"); 		
            for (var m = 0; m < parentLink.length; m = m + 2) {
                var liLeft = parentLink[m];
                ulLeft.appendChild(liLeft);
            }
            var div5 = document.createElement("div");
            div5.className = "prodright";
            var ulRight = document.createElement("ul"); 		
            for (var n = 1; n < parentLink.length; n = n + 2) {
                var liRight = parentLink[n];
                ulRight.appendChild(liRight);
            }	
// Append Elements to each other and page 
            var parent = g.id("content");
            div5.appendChild(ulRight);
            div4.appendChild(ulLeft);
            div3.appendChild(div4);
            div3.appendChild(div5);					
// Loop through the links and add a tabindex, starting from the value of the tabindex in the top tab
            var ttIndex = document.getElementById(nav.tabs[i]).getAttribute("tabIndex");
            var localIndex = parseInt(ttIndex, 10) + 1;
            var a = div3.getElementsByTagName("a");
            for (var j = 0; j < a.length; j++) {
                a[j].setAttribute("tabIndex", localIndex);
                localIndex++;
            }
// Finish appending elements to each other and page 
            div2.appendChild(div3);
            div1.appendChild(div2);
            parent.appendChild(div1);
        }
    },

// Hide navs if user is in the top section or the body section
    hideNavOffTab: function () {	
        var parent = g.id("wrapper");
        if (!g.id("ask")) {
            return false;
        }
        // Hide popup when user moves to first link before Nav
        var topLinks = g.idTn("ask", "a");
        topLinks[0].onfocus = function () {
            var sectionDiv = getElementsByClassName(parent, "div", nav.tabs[0] + '-products-box');
            sectionDiv[0].style.visibility = "hidden";
        };

        // Hide popup when user tabs off last link in last product
        var lastProduct = getElementsByClassName(parent, "div", nav.tabs[5] + '-products-box');
        var links = lastProduct[0].getElementsByTagName("a");
        var arraryLength = (links.length) - 1;
        links[arraryLength].onblur = function () {
            lastProduct[0].style.visibility = "hidden";
        };
    },

    /** Listen for mouse and keyboard events  **/
    navPopListeners: function () {	
        if (!document.getElementById) {
            return false;
        }
        for (var i = 0; i < nav.tabs.length; i++) {
            if (!g.id(nav.tabs[i])) {
                return false;
            }            
            var currentTab = g.id(nav.tabs[i]);
            g.addEvent(currentTab, 'mouseover', nav.showHideNav, false);
            g.addEvent(currentTab, 'focus', nav.showHideNav, false);
        }
    },


/** Display Nav popup **/
    showHideNav: function (e) {

        var parent = g.id("wrapper");		

// Check no other sections are open

        for (var i = 0; i < nav.tabs.length; i++) {	
            var sectionDiv  = getElementsByClassName(parent, "div", nav.tabs[i] + '-products-box');
            if (sectionDiv[0].style.visibility === "visible") {
                sectionDiv[0].style.visibility = "hidden";
            }		
        }

        var links = g.getTarget(e).id;
        g.stopBubble(e);


// Get the section associated with the tab and make the section visible

        var currentSection = links + "-products-box";
        var section  = getElementsByClassName(parent, "div", currentSection);	
        if (section[0].style.visibility !== "visible") {
            section[0].style.visibility = "visible";
        }

// Close popup if mouse moves off Tab
        g.id(links).onmouseout = function () {
            section[0].style.visibility = "hidden";
        };
//Find out where the mouse is in relation to the popup nav, close if the mouse is not over the popup
        section[0].onmouseover = function () {
            this.style.visibility = "visible";
        };
        section[0].onmouseout  = function () {
            this.style.visibility = "hidden";
        };
    }
};

var myAccountsPop = {

// Create array which is a reference to the tabs id
    tabs: ["accounts"],

    createPopup: function () {
        for (var i = 0; i < myAccountsPop.tabs.length; i++) {				
            var parentLink = [];
            var area = myAccountsPop.tabs[i] + "-products";
            if (!document.getElementById(area)) {
                return false;
            }
            var li = document.getElementById(area).getElementsByTagName("li");
            for (var k = 0; k < li.length; k++) {
                var findTheUL = g.getParentUL(li[k]);		
                if (findTheUL.parentNode.id === area) {
                    var copyOfLI = li[k].cloneNode(true);
                    parentLink.push(copyOfLI);
                }
            }	

// Create all page elements 
            var boxStyle = area + "-box";
            var div1 = document.createElement("div");
            div1.className = boxStyle;
            div1.style.visibility = "hidden";
            var div2 =  document.createElement("div");
            div2.className = "innerbox";
            var div3 =  document.createElement("div");
            div3.className =  "productslinks clearing";
            var div4 =  document.createElement("div");
            div4.className = "prodleft";
            var ulLeft = document.createElement("ul"); 		
            for (var m = 0; m < parentLink.length; m = m + 2) {
                var liLeft = parentLink[m];
                ulLeft.appendChild(liLeft);
            }
            var div5 = document.createElement("div");
            div5.className = "prodright";
            var ulRight = document.createElement("ul"); 		
            for (var n = 1; n < parentLink.length; n = n + 2) {
                var liRight = parentLink[n];
                ulRight.appendChild(liRight);
            }	
// Append Elements to each other and page 
            var parent = g.id("orientation");
            div5.appendChild(ulRight);
            div4.appendChild(ulLeft);
            div3.appendChild(div4);
            div3.appendChild(div5);	
//Missed tabindex stuff
// Finish appending elements to each other and page 
            var ttIndex = document.getElementById(myAccountsPop.tabs[i]).getAttribute("tabIndex");
            var localIndex = parseInt(ttIndex, 10) + 1;
            var a = div3.getElementsByTagName("a");
            for (var j = 0; j < a.length; j++) {
                a[j].setAttribute("tabIndex", localIndex);
                localIndex++;
            }
            div2.appendChild(div3);
            div1.appendChild(div2);
            parent.appendChild(div1);
        }
    },


// Hide navs if user is in the top section or the body section
    hideNavOffTab: function () {	
        var parent = g.id("orientation");

// Hide popup when user moves to first link before Nav
        if (!g.id("skiplink") || !g.idTn("skiplink", "a")) {
            return false;
        }
        var topLinks = g.idTn("skiplink", "a");
        topLinks[0].onfocus = function () {
            var sectionDiv = getElementsByClassName(parent, "div", 'accounts-products-box');
            sectionDiv[0].style.visibility = "hidden";
        };

// Hide popup when user tabs off last link in last product
        var lastProduct = getElementsByClassName(parent, "div", 'accounts-products-box');
        var links = lastProduct[0].getElementsByTagName("a");
        var arraryLength = (links.length) - 1;
        links[arraryLength].onblur = function () {
            lastProduct[0].style.visibility = "hidden";
        };

    },	

/** Listen for mouse and keyboard events  **/
    navPopListeners: function () {	
        if (!document.getElementById) {
            return false;
        }
        for (var i = 0; i < myAccountsPop.tabs.length; i++) {
            if (!g.id('accounts')) {
                return false;
            }
            var currentTab = g.id('accounts');
            g.addEvent(currentTab, 'mouseover', myAccountsPop.showHideNav, false);
            g.addEvent(currentTab, 'focus', myAccountsPop.showHideNav, false);
        }
    },


/** Display Nav popup **/
    showHideNav: function (e) {
        var parent = g.id("orientation");		

// Check no other sections are open

        for (var i = 0; i < myAccountsPop.tabs.length; i++) {	
            var sectionDiv  = getElementsByClassName(parent, "div", myAccountsPop.tabs[i] + '-products-box');
            if (sectionDiv[0].style.visibility === "visible") {
                sectionDiv[0].style.visibility = "hidden";
            }		
        }

        var links = g.getTarget(e).id;
        g.stopBubble(e);
        g.stopDefault(e);


// Get the section associated with the tab and make the section visible

        var currentSection = links + "-products-box";
        var section  = getElementsByClassName(parent, "div", currentSection);	
        if (section[0].style.visibility !== "visible") {
            section[0].style.visibility = "visible";
        }

// Close popup if mouse moves off Tab
        g.id(links).onmouseout = function () {
            section[0].style.visibility = "hidden";
        };
//Find out where the mouse is in relation to the popup nav, close if the mouse is not over the popup
        section[0].onmouseover = function () {
            this.style.visibility = "visible";
        };
        section[0].onmouseout  = function () {
            this.style.visibility = "hidden";
        };
    }	
};

/*
-----------------  8. Man in Blue Resolution Dependent Layout Script & ecmascript.stchur.com IE resize script -----------------------------------*/	


var resDepLayout = {
		
/** Check initial size and provide suitable CSS **/
    checkBrowserWidth: function () {
        var theWidth = resDepLayout.getBrowserWidth();
        if (theWidth === 0)	{
            var resolutionCookie = document.cookie.match(/(^|;)tmib_res_layout[^;]*(;|$)/);
            if (resolutionCookie !== null) {
                resDepLayout.setStylesheet(unescape(resolutionCookie[0].split("=")[1]));
            }
            g.addLoadEvent(resDepLayout.checkBrowserWidth);
            return false;
        }

        if (theWidth > 994)	{
            resDepLayout.setStylesheet("1024");
            document.cookie = "tmib_res_layout=" + escape("1024");
        } else {
            resDepLayout.setStylesheet("");
            document.cookie = "tmib_res_layout=";
        } 
        return true;
    },


    getBrowserWidth: function () {
        if (window.innerWidth)	{
            return window.innerWidth;
        } else if (document.documentElement && document.documentElement.clientWidth !== 0) { 	
            return document.documentElement.clientWidth;
        } else if (document.body) {
            return document.body.clientWidth;
        }	
        return 0;
    },

    setStylesheet: function (styleTitle) {
        var currTag;
        if (document.getElementsByTagName) {
            for (var i = 0; (currTag = document.getElementsByTagName("link")[i]); i++) {
                if (currTag.getAttribute("rel").indexOf("style") !== -1 && currTag.getAttribute("title")) {
                    currTag.disabled = true;
                    if (currTag.getAttribute("title") === styleTitle) {
                        currTag.disabled = false;
                    }
                }
            }
        }
        return true;
    },		

    xBrowserResize: function () {
        window.g_prevSize = resDepLayout.getViewportSize();
        var theSize = window.g_prevSize;
        setInterval(resDepLayout.resize, 10);
        return theSize;
    },

    resize: function () {
       /*extern g_prevSize */ /* This allows validation in JS Lint for global variables */
        var currentSize = resDepLayout.getViewportSize();		
        if (currentSize[0] !== g_prevSize[0] || currentSize[1] !== g_prevSize[1]) {
            g_prevSize = currentSize;
            var theWidth = currentSize[0];
            if (theWidth > 994) {
                resDepLayout.setStylesheet("1024");
                document.cookie = "tmib_res_layout=" + escape("1024");
            } else {
                resDepLayout.setStylesheet("");
                document.cookie = "tmib_res_layout=";
            }
        }
    },
  
   // This function will validate in js lint, however strange bug occurs in FF for mortgages dropdown.
   /*
    resize: function () {
        var currentSize = resDepLayout.getViewportSize();
        var g_prevSize = resDepLayout.xBrowserResize;
		
        if (currentSize[0] !== g_prevSize[0] || currentSize[1] !== g_prevSize[1]) {
            g_prevSize = currentSize;
            var theWidth = currentSize[0];
            if (theWidth > 994) {
                resDepLayout.setStylesheet("1024");
                document.cookie = "tmib_res_layout=" + escape("1024");
            } else {
                resDepLayout.setStylesheet("");
                document.cookie = "tmib_res_layout=";
            }
        }
    },*/

    getViewportSize: function () {
        var size = [0, 0];
        if (typeof window.innerWidth !== 'undefined') {
            size = [ window.innerWidth, window.innerHeight ];
        } else if (typeof	document.documentElement !== 'undefined' && typeof document.documentElement.clientWidth !== 'undefined' && document.documentElement.clientWidth !== 0) {
            size = [ document.documentElement.clientWidth, document.documentElement.clientHeight ];
        } else {
            size = [ document.getElementsByTagName('body')[0].clientWidth, document.getElementsByTagName('body')[0].clientHeight ];
        }
        return size;				
    }
};


/*
-----------------  9. Event delegation -----------------------------------*/	

var eventDelegation = {

    bodyTest: function () {
        if (!document.getElementById || !document.createElement) {
            return;
        }
        var docBody = document.getElementById("top-border");
        if (!docBody) {
            return false; 
        }
        g.addEvent(docBody, 'click', eventDelegation.popupClickHandler, false);
        g.addEvent(docBody, 'click', eventDelegation.toggleClickHandler, false);
    },
	
/* ------------------ POPUPS ------------------------------------*/   
	
    popupClickHandler: function (e) {
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        var triggerParent = trigger.parentNode;
        var thisLink, uniqueLink;

// Get target href or target parent href.  This will be used to determine what page is opened
        if (trigger.nodeName.toLowerCase() === "a") {
            thisLink = trigger.href;
            uniqueLink = trigger;
        } else if (triggerParent.nodeName.toLowerCase() === "a") {
            thisLink = triggerParent.href;
            uniqueLink = triggerParent;
        } else {
            return;
        }		

// Site intelligence link info.  Pass up the link text, link area within the site and link URL
        var fullURL = thisLink.indexOf(thisLink);
        if (!uniqueLink) {
            return false;
        }
        var siteArea = g.getParentWithIdAttribute(uniqueLink);
        var linkText = uniqueLink.firstChild.nodeValue;
        var siteIntelOverlay = "Linktext:" + linkText + "~Area:" + siteArea.id + "~URL:" + thisLink;
		//alert(siteIntelOverlay)
						
//Standard Popups
        if ((trigger.className && (" " + trigger.className + " ").indexOf(" popup ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" popup ") !== -1)) {			
            window.open(thisLink); 
            g.stopDefault(e);
            return false;
        }
			
//Metafaq Popups
        if ((trigger.className && (" " + trigger.className + " ").indexOf(" metafaq ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" metafaq ") !== -1)) {
            window.open(thisLink, 'mypop', "height=650, width=780, status, resizable, scrollbars, toolbar"); 
            g.stopDefault(e);
            return false;
        }    

//Demo Popups
        if ((trigger.className && (" " + trigger.className + " ").indexOf(" demowindow ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" demowindow ") !== -1)) {
            window.open(thisLink, 'mypop', "height=500, width=660, status, resizable, scrollbars, toolbar"); 
            g.stopDefault(e);
            return false;
        }    

//Segala Popup
        if ((trigger.className && (" " + trigger.className + " ").indexOf(" segala ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" segala ") !== -1)) {
            window.open(thisLink, 'mypop', "height=780, width=500, status, resizable, scrollbars, toolbar"); 
            g.stopDefault(e);
            return false;
        }			

        if ((trigger.className && (" " + trigger.className + " ").indexOf(" caopopup ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" caopopup ") !== -1)) {
            window.open(thisLink, 'mypop', "height=685, width=995, status, location, menubar, resizable, scrollbars, toolbar"); 
            g.stopDefault(e);
            return false;
        }			


    },

/* ------------------ TOGGLES ------------------------------------*/

    toggleClickHandler: function (e) {
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        //g.stopDefault(trigger);
		var triggerParent = trigger.parentNode;

        if ((trigger.className && (" " + trigger.className + " ").indexOf(" togglelink ") !== -1) || (triggerParent.className && (" " + triggerParent.className + " ").indexOf(" togglelink ") !== -1)) {			
            g.stopDefault(trigger);
			var startPos = trigger.className.indexOf("box");
            var restOfString = trigger.className.substr(startPos + 3);
            var boxNumber = parseInt(restOfString, 10);
            var toggleSection = g.id("box" + boxNumber);
// Switch class depending on current toggle state
            if (toggleSection.className && (" " + toggleSection.className + " ").indexOf(" showtoggle ") !== -1) {
                g.addClass(toggleSection, "hidetoggle");
                g.removeClass(toggleSection, "showtoggle");
                g.removeClass(trigger, "up");
            } else if (toggleSection.className && (" " + toggleSection.className + " ").indexOf(" hidetoggle ") !== -1) {
                g.removeClass(toggleSection, "hidetoggle");
                g.addClass(toggleSection, "showtoggle");
                g.addClass(trigger, "up");
            } else {
                return;
            }

        }
    }
};
// end event delegation


/********************* slide **********************/

var slider = {
/** Prepare sections **/
//Area of page, element surrounding the element which causes the toggele, 
//element that is toggled, event trigger element that causes the toggle, 
    prepareToggles: function () {
        slider.toggleSections("main", "dt", "dd", "a");
        slider.toggleSections("nav-secondary", "dt", "dd", "a");
        slider.toggleSections("main", "h4", "div", "a");
        slider.toggleSections("main", "h3", "ul", "a");
        slider.toggleSections("main", "h5", "ul", "a");
        slider.toggleSections("wide", "dt", "dd", "a");
    },

// Hide all sections with the class togglebox by adding the class hidetoggle to the associated show hide section
    toggleSections: function (pageArea, toggleTriggerParent, toggleElement, toggleTrigger) {
        if (!document.getElementById || !document.getElementsByTagName || !g.id(pageArea) || !g.tn(toggleTriggerParent) || !g.tn(toggleElement) || !g.tn(toggleTrigger)) {
            return false;
        }
        var parent = g.id(pageArea);
        var toggleSection = getElementsByClassName(parent, toggleElement, "togglebox");
        for (var i = 0; i < toggleSection.length; i++) {
// If the toggleSection already has a class of hidetoggle then exit
            if (toggleSection[i].className && (" " + toggleSection[i].className + " ").indexOf(" hidetoggle ") !== -1) {
                return false;
            }
            g.addClass(toggleSection[i], "hidetoggle");
            var prevSib = g.closestSibling(toggleSection[i], -1);			
// Check previousSibling element type, if it is not a link then get the last child text node of the parent and
// Wrap this content in a link and assign the className togglelink to set up toggle functionality
            if (prevSib.firstChild.nodeName !== "A") {
                if (prevSib.className && (" " + prevSib.className + " ").indexOf(" togglelink ") === -1) {
                    return false;
                }
                g.removeClass(prevSib, "togglelink");
                var a = document.createElement("a");
                a.className = "togglelink";
                a.setAttribute("href", "#");
                var atext = document.createTextNode(prevSib.lastChild.nodeValue);
                a.appendChild(atext);
                prevSib.replaceChild(a, prevSib.lastChild);
            }
        }
    },	

    setUpToggleLInks: function () {
// Initiialise variables
        var boxCounter = 0;

        var primaryContent = g.id("content");
        if (!primaryContent) {
            return;
        } 
        var secondaryContent = g.id("nav-secondary");
        if (!secondaryContent) {
            return;
        } 
        var tertiaryContent = g.id("wide");
// Get al elements with the class togglelink				
        var primarylinks = getElementsByClassName(primaryContent, "*", "togglelink");
        var secondarylinks = getElementsByClassName(secondaryContent, "*", "togglelink");
// Check if he page has a wide layout, if so get all the togglelinks elements within the wide layout and concentenate the arrays.
        var links;
        if (!tertiaryContent) {
            links = primarylinks.concat(secondarylinks);
        } else {
            var tertiarylinks = getElementsByClassName(tertiaryContent, "*", "togglelink");
            links = primarylinks.concat(secondarylinks, tertiarylinks);
        }
// Loop through the joined array attaching a unique value to each toggelink and the next element.
        for (var i = 0; i < links.length; i++) {
            g.addClass(links[i], "box" + boxCounter);
            var linkParent = links[i].parentNode;
            var toggleSection = g.closestSibling(linkParent, 1);
            toggleSection.setAttribute("id", "box" + boxCounter);
            boxCounter = boxCounter + 1;
        }		
    }
};


var keepOpenToggledSection = {
    toggledSection: function () {
        if (!g.id || !g.id("current-elh")) {
            return false;
        }

        var toggleSection = g.idTn("nav-secondary", "dd");
        for (var i = 0; i < toggleSection.length; i++) {
            if ((toggleSection[i].className && (" " + toggleSection[i].className + " ").indexOf(" togglebox hidetoggle ") !== -1) && (toggleSection[i].className && (" " + toggleSection[i].className + " ").indexOf(" hidetoggle ") !== -1)) {
                var toggleId = toggleSection[i].getAttribute("id");
                var currentSection = g.id(toggleId);
                var links = g.idTn(toggleId, "a");
                for (var k = 0; k < links.length; k++) {
                    var currentlyClosed = g.id(toggleId);
                    g.removeClass(currentSection, "hidetoggle");
                    g.addClass(currentSection, "showtoggle");
                }	
            }
        }    

        var toggleTitle = g.idTn("nav-secondary", "a");
        for (var j = 0; j < toggleTitle.length; j++) {
            if ((toggleTitle[j].className && (" " + toggleTitle[j].className + " ").indexOf(" togglelink ") !== -1) && (toggleTitle[j].className && (" " + toggleTitle[j].className + " ").indexOf(" up ") === -1)) {
                toggleTitle[j].className = toggleTitle[j].className + " up";
            }
        }
    }
};

var inputButtons = {		
    inputStyle: function () {
        if (!g.id || !g.id("acc-pol")) {
            return false;
        }
        var inputElements = g.idTn("acc-pol", "input");
        inputElements[0].onmouseover = function () {
            this.style.color = "#cc0000";
            this.style.textDecoration = "underline";
        };

        inputElements[0].onmouseout = function () {
            this.style.color = "#0e6fcd";
            this.style.textDecoration = "none";
        };
    }
};		

// DTSL - Dynamic text submission links written by Chris Heilmann (http://www.icant.co.uk)
// scans a document for submit buttons and replaces them with text links with the same ID and text value and a predefined class 

var dtsl = {
    buttonClass: 'round popup',
    init: function () {
        var i, newa, inputs;
        if (!document.getElementById || !document.createTextNode) {
            return;
        }
        inputs = document.getElementsByTagName('input');
        for (i = 0; i < inputs.length; i ++) {
            if (inputs[i].parentNode.className && (" " + inputs[i].parentNode.className + " ").indexOf(" button-container-form ") !== -1) {
                if (inputs[i].getAttribute('type') !== 'submit') {
                    continue;
                }
                newa = document.createElement('a');
                newa.setAttribute('href', '#');
                newa.setAttribute('id', inputs[i].getAttribute('id'));
                newa.appendChild(document.createTextNode(inputs[i].getAttribute('value')));
                newa.className = dtsl.buttonClass;
                newa.f = inputs[i].form;
                g.addEvent(newa, 'click', dtsl.sendForm, false);
                newa.onclick = function () {
                    return false;
                }; // Safari
                inputs[i].parentNode.insertBefore(newa, inputs[i]);
                inputs[i].parentNode.removeChild(inputs[i]);
                if (i < inputs.length) {
                    i--;
                }
            }
        }
    },
// you may have to alter sendForm when there is more than one form 
// in the document
    sendForm: function (e) {
        g.cancelClick(e);
        var t = g.getTarget(e);
        var f = t.f;
        var newel = document.createElement('input');
        newel.name = t.id;
        newel.value = t.innerHTML;
        f.appendChild(newel);
        f.submit();
    }
};


/*
-----------------  10. Customer Account Opening -----------------------------------*/	

var cao = {

    // Create HTML forms to replace the Links currently on the CAO pages.
    createForms: function () {

        // Identify that this is a CAO page before carrying out any functionality
        if (!document.getElementById || !document.createElement || !document.getElementById("cao")) {
            return false;
        }


	    // Loop through DIV's on page to check for matches of the 3 product list
        var divSwap = document.getElementsByTagName("div");
        for (var i = 0; i < divSwap.length; i++) {		
        
		   if (divSwap[i].getAttribute("id") === "cao-internetsaver") {
			// Swap intro text to indicate that each field must be selected
               var introSwap = document.getElementById("cao-intro");
               introSwap.innerHTML = "Please complete the details below. Required fields are indicated with a *.";
               var saveList = document.getElementById("cao-internetsaver");
               var saveFormContent = '<form action="" name="" method="post" id="internetSaverCao"><div class="formarea clearing"><div class="row radiocheck"><h3 class="labeltxt longlabel">All Applicants &#42;</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input name="personalcustomer" value="existingyes" checked="checked" type="radio"><span id="span1">I am an existing TPF Savings or Clubcard Plus customer</span></span></label><label class="clearing"><span class="inputwrapper"><input name="personalcustomer" value="existingno" type="radio"><span id="span2">I am <strong>not</strong> an existing TPF Savings or Clubcard Plus customer</span></span></label></div></div></div><p>Please press <strong>Next</strong> to continue your application.</p><p><strong>PLEASE NOTE</strong>: To navigate through this application form please use the ‘Next’ and ‘Previous’ buttons at the bottom of each screen. Using the arrow keys in your browser will result in your application content being lost.</p><div class="buttonarea clearing"><input value="Next" id="next" class="button fright" type="submit"></form>';
			   saveList.innerHTML = saveFormContent;
            }

	

		//BONUS CARD FORM
            
			if (divSwap[i].getAttribute("id") === "cao-selection-bonus") {
                var bonusList = document.getElementById("cao-selection-bonus");
                var bonusFormContent =  '<form action="" name="" method="post" id="bonusCardCaoForm"><div class="formarea"><div class="row radiocheck"><h3 class="labeltxt">Please select your Tesco Bonus Credit Card design</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input type="radio" name="carddesign" value="design1" checked="checked" /><span><img src="/personal/finance/images/cao/bonus-shimmer.gif" alt="Bonus Credit Card - Shimmer design" width="97" height="63" /></span> </span> </label><label class="clearing"><span  class="inputwrapper"><input type="radio" name="carddesign" value="design2" /><span><img src="/personal/finance/images/cao/bonus-swirl.gif" alt="Bonus Credit Card - Swirl design" width="97" height="63" /></span></span></label></div></div><div class="row radiocheck"><h3 class="labeltxt">Please select your card type</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input type="radio" name="cardtype" value="mastercard" checked="checked" /><span>Mastercard</span></span></label><label class="clearing"><span class="inputwrapper"><input type="radio" name="cardtype" value="visa" /><span>Visa</span></span> </label></div></div></div><p>Please press &#39;<strong>Next</strong>&#39; to continue your application.</p><div class="buttonarea clearing"><input type="submit" value="Next" id="next" class="button fright" /></div></form>';
                bonusList.innerHTML = bonusFormContent;
            }

        //CLUBCARD FORM
			if (divSwap[i].getAttribute("id") === "cao-selection-club") {
                var clubList = document.getElementById("cao-selection-club");
                var clubFormContent = '<form action="" name="" method="post" id="clubCardbuttonSelection"><div class="formarea"><div class="row radiocheck"><h3 class="labeltxt">Please select your Tesco Clubcard Credit Card design</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input type="radio" name="carddesign" value="design1" checked="checked" /><span><img src="../images/cao/clubcard-strawberry.gif" alt="Clubcard Credit Card - Strawberry design" width="97" height="63" /></span> </span> </label><label class="clearing"><span  class="inputwrapper"><input type="radio" name="carddesign" value="design2" /><span><img src="../images/cao/clubcard-blue.gif" alt="Clubcard Credit Card - Blue radial design" width="97" height="63" /></span></span> </label></div></div></div><p>Please press &#39;<strong>Next</strong>&#39; to continue your application.</p><div class="buttonarea clearing"><input type="submit" value="Next" id="next" class="button fright" /></div></form>';
                clubList.innerHTML = clubFormContent;
            }

        //SAVINGS FORM
            if (divSwap[i].getAttribute("id") === "cao-selection-savings") {
            // Swap intro text to indicate that each field must be selected
               	var introSwap = document.getElementById("cao-intro");
                introSwap.innerHTML = "Please complete the details below. Required fields are indicated with a *.";
                var saveList = document.getElementById("cao-selection-savings");
                var saveFormContent = '<form action="" name="" method="post" id="savingsCaoForm"><div class="formarea"><div class="row radiocheck"><h3 class="labeltxt longlabel">All Applicants &#42;</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input name="personalcustomer" value="existingyes" checked="checked" type="radio"><span id="span1">I am an existing TPF Savings or Clubcard Plus customer</span></span></label><label class="clearing"><span class="inputwrapper"><input name="personalcustomer" value="existingno" type="radio"><span id="span2">I am <strong>not</strong> an existing TPF Savings or Clubcard Plus customer</span></span></label></div></div><div class="row radiocheck"><h3 class="labeltxt longlabel">Before applying, please indicate whether you wish to receive your interest annually or monthly? &#42;</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input name="interestchoice" value="annualinterest" checked="checked" type="radio"><span id="span1">Annual interest</span></span></label><label class="clearing"><span class="inputwrapper"><input name="interestchoice" value="monthlyinterest" type="radio"><span id="span2">Monthly interest</span></span></label></div></div></div><p>Please press <strong>Next</strong> to continue your application.</p><p><strong>PLEASE NOTE</strong>: To navigate through this application form please use the ‘Next’ and ‘Previous’ buttons at the bottom of each screen. Using the arrow keys in your browser will result in your application content being lost.</p><div class="buttonarea clearing"><input value="Next" id="next" class="button fright" type="submit"></div></form>';
				saveList.innerHTML = saveFormContent;
            }
			
        //SAVINGS INTEREST CHOICE FORM
            
			if (divSwap[i].getAttribute("id") === "cao-selection-savings-interest") {
            // Swap intro text to indicate that each field must be selected
                var introSwap = document.getElementById("cao-intro");
                introSwap.innerHTML = "Please complete the details below. Required fields are indicated with a *.";
                var saveList = document.getElementById("cao-selection-savings-interest");
                var saveFormContent = '<form action="" target="_blank" name="" method="post" id="savingsSelectionCaoForm"><div class="formarea"><div class="row radiocheck"><h3 class="labeltxt">Before applying, please indicate whether you wish to receive your interest annually or monthly? *</h3><div class="inner clearing"><label class="clearing"><span class="inputwrapper"><input type="radio" name="interestchoice" value="annualinterest" checked="checked" /><span id="span1">Annual interest</span> </span> </label><label class="clearing"><span  class="inputwrapper"><input type="radio" name="interestchoice" value="monthlyinterest" /><span id="span2">Monthly interest</span></span> </label></div></div><div class="buttonarea clearing"><input type="submit" value="Apply now (new window)" id="next" class="button fright" /></div></form>';
                saveList.innerHTML = saveFormContent;
            }		
			
        }
    },


    // Set up event delegation for CAO screens    
    bodyTest: function () {
        if (!document.getElementById || !document.createElement || !document.getElementById("cao")) {
            return false;
        }	
        var docBody = document.getElementById("cao");
        g.addEvent(docBody, 'click', cao.savingsPreCAO, false);
		g.addEvent(docBody, 'click', cao.internetSaverPreCAO, false);
		//g.addEvent(docBody, 'click', cao.bonusCardPreCAO, false);
		
        g.addEvent(docBody, 'click', cao.bonusCardbuttonSelection, false);
        g.addEvent(docBody, 'click', cao.clubCardbuttonSelection, false);
		g.addEvent(docBody, 'click', cao.savingsInterestChoiceSelection, false);
    },	

	
	internetSaverPreCAO: function (e) {
        if (!document.getElementById("internetSaverCao")) {
            return;
        }
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("internetSaverCao");
			var customer = document.getElementById("internetSaverCao").personalcustomer;			
			
			for (var i = 0; i < customer.length; i++) {
                if (customer[i].checked === true && customer[i].value === "existingyes") {
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K8&CS=C");
                } 					
                if (customer[i].checked === true && customer[i].value === "existingno") {
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K8&CS=N%20");
                } 					
            }
        }
    },

	
	// SAVINGS FORM CHOICES
    /*
	savingsButtonSelection: function (e) {
        
        if (!document.getElementById("savingsCaoForm")) {
            return;
        }
				
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("savingsCaoForm");
            var existingCustomer = caoForm.personalcustomer;

            // Loop through the first choice of radio buttons
            for (var i = 0; i < existingCustomer.length; i++) {

            // If an existing customer then check secondary set of radio buttons
                if (existingCustomer[i].checked === true && existingCustomer[i].value === "yes") {
                    //var cardDesign = document.forms["savingsCaoForm"]["carddesign"];
                    var cardDesign = document.getElementById("savingsCaoForm").carddesign;

					// Card choice will determie the URL
                    for (var k = 0; k < cardDesign.length; k++) {
                        if (cardDesign[k].checked === true && cardDesign[k].value === "design1") {
                            caoForm.action = "savings_2.html";
                        } 					
                        if (cardDesign[k].checked === true && cardDesign[k].value === "design2") {
                            caoForm.action = "https://www.cao.rbos.com/cao/external/rbs/launchChannelHandler.do?CID=INT&BRD=RBS&PF=DEP&PI=11&CS=C";
                        }
                    }
                }

            // If not a customer then no need to check secondary set of buttons
                if (existingCustomer[i].checked === true && existingCustomer[i].value === "no") {
                    caoForm.action = "https://www.cao.rbos.com/cao/external/rbs/launchChannelHandler.do?CID=INT&BRD=RBS&PF=DEP&PI=11&CS=N";
                }
            }
        }
    },*/

    // BONUS CARD FORM CHOICES
    
	bonusCardbuttonSelection: function (e) {
		
		
        var thisCardDesign;
        var thisCardType;
		
        if (!document.getElementById("bonusCardCaoForm")) {
            return;
        }	

        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("bonusCardCaoForm");
            var cardDesign = document.getElementById("bonusCardCaoForm").carddesign;
            var cardType = document.getElementById("bonusCardCaoForm").cardtype;

            // Loop through the first choice of radio buttons
            for (var i = 0; i < cardDesign.length; i++) {
                if (cardDesign[i].checked === true) {
                    thisCardDesign = cardDesign[i].value; 
                }
            }

            // Loop through the second choice of radio buttons
            for (var k = 0; k < cardType.length; k++) {
                if (cardType[k].checked === true) {
                    thisCardType = cardType[k].value; 
                }
            }

        // Assign both selected radio button values to a variable, which can be used to match the in the switch statement.
            var cardSelection = thisCardDesign + ", " + thisCardType;
            switch (cardSelection) {
            case "design1, mastercard":
                caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y4&CS=N%20");
                break;   
            case  "design1, visa":
                caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y5&CS=N%20");
                break;
            case  "design2, mastercard":
                caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y3&CS=N%20");
                break;
            default:
                caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y6&CS=N%20");
            }
        }
    },

    // CLUBCARD CARD FORM CHOICES
    
	clubCardbuttonSelection: function (e) {
        if (!document.getElementById("clubCardbuttonSelection")) {
            return;
        }
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("clubCardbuttonSelection");
            var cardDesign = document.getElementById("clubCardbuttonSelection").carddesign;
            for (var i = 0; i < cardDesign.length; i++) {
                if (cardDesign[i].checked === true && cardDesign[i].value === "design1") {
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y2&CS=N%20");
                } 					
                if (cardDesign[i].checked === true && cardDesign[i].value === "design2") {
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y1&CS=N%20");
                } 					
            }
        }
    },
	
    // SAVINGS INTEREST FORM CHOICES
    /*
	savingsInterestChoiceSelection: function (e) {
        alert('hi')
		if (!document.getElementById("savingsSelectionCaoForm")) {
            return;
        }
		
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("savingsSelectionCaoForm");
            var cardDesign = document.getElementById("savingsSelectionCaoForm").interestchoice;
            for (var i = 0; i < cardDesign.length; i++) {
                if (cardDesign[i].checked === true && cardDesign[i].value === "annualinterest") {
					//alert("hi 1");
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K5&CS=N%20");
                } 					
                if (cardDesign[i].checked === true && cardDesign[i].value === "monthlyinterest") {
                    //alert("hi 2");
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K6&CS=N%20");
                } 					
            }
        }
    },*/
    // SAVINGS INTEREST FORM CHOICES
    savingsInterestChoiceSelection: function (e) {
        if (!document.getElementById("savingsSelectionCaoForm")) {
            return;
        }
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("savingsSelectionCaoForm");
            var cardDesign = document.getElementById("savingsSelectionCaoForm").interestchoice;
            for (var i = 0; i < cardDesign.length; i++) {
                if (cardDesign[i].checked === true && cardDesign[i].value === "annualinterest") {
					//alert("hi 1");
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K5&CS=N%20");
                } 					
                if (cardDesign[i].checked === true && cardDesign[i].value === "monthlyinterest") {
                    //alert("hi 2");
					caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K6&CS=N%20");
                } 					
            }
        }
    },
	
    // Savings interest choice 
    savingsPreCAO: function (e) {
		
        var existingCust;
        var monthlyAnnual;
		
		if (!document.getElementById("savingsCaoForm")) {
            return;
        }	
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("savingsCaoForm");
            var customer = document.getElementById("savingsCaoForm").personalcustomer;
            var interest = document.getElementById("savingsCaoForm").interestchoice;

            // Loop through the first choice of radio buttons
            for (var i = 0; i < interest.length; i++) {
                if (interest[i].checked === true) {
                    monthlyAnnual = interest[i].value; 
                }
            }

            // Loop through the second choice of radio buttons
            for (var k = 0; k < customer.length; k++) {
                if (customer[k].checked === true) {
                    existingCust = customer[k].value; 
                }
            }

        // Assign both selected radio button values to a variable, which can be used to match the in the switch statement.
            var customersChoice = existingCust + ", " + monthlyAnnual;
            switch (customersChoice) {
            case "existingyes, annualinterest":
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K5&CS=C");
                break;   
            case "existingno, annualinterest":
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K5&CS=N%20");
                break;
           case "existingyes, monthlyinterest":
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K6&CS=C");
                break;
            default:
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=DEP&PI=K6&CS=N%20");
            }
        }
    },	
	
    // Bonuscard card choice 
    bonusCardPreCAO: function (e) {
		
        var cardDesign;
        var cardType;
		if (!document.getElementById("bonusCardCaoForm")) {
            return;
        }	
        var theEvent = e || window.event;	
        var trigger = theEvent.target || theEvent.srcElement;
        if (trigger.id === "next") {
            var caoForm = document.getElementById("bonusCardCaoForm");
            var design = document.getElementById("bonusCardCaoForm").carddesign;
            var provider = document.getElementById("bonusCardCaoForm").cardtype;

            // Loop through the first choice of radio buttons
            for (var i = 0; i < provider.length; i++) {
                if (provider[i].checked === true) {
                    cardType = provider[i].value; 
                }
            }

            // Loop through the second choice of radio buttons
            for (var k = 0; k < design.length; k++) {
                if (design[k].checked === true) {
                    cardDesign = design[k].value; 
                }
            }

        // Assign both selected radio button values to a variable, which can be used to match the in the switch statement.
            var customersChoice = cardDesign + ", " + cardType;
            switch (customersChoice) {
            case "design1, mastercard":
				//alert("shimmer & mastercard");
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y4&CS=N%20");
                break;   
            case "design1, visa":
				//alert("shimmer & visa");
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y5&CS=N%20");
                break;
           case "design2, mastercard":
				//alert("swirl & mastercard");
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y3&CS=N%20");
                break;
            default:
				//alert("swirl & visa");
				caoForm.setAttribute("action", "https://www.cao.tescofinance.com/cao/external/tpf/launchChannelHandler.do?CID=INT&BRD=TPF&PF=CC1&PI=Y6&CS=N%20");
            }
        }
    }
};


var socialBookmarking = {
		
		bookmark: function () {
		if (!g.id("bookmarking-sites")) return false;
		var bookmarkingSites = g.idTn("bookmarking-sites", "a");
		var bookmarkIntro = g.id("bookmark-into");
		if (!bookmarkIntro) return false;
		g.addClass(bookmarkIntro, "hide");

		/* Use metadescripton for population of social description */
		//if (!g.tn("title")) return false;
		//var description = g.tn("title")[0].lastChild.nodeValue;
		
		/*
		var metadata = g.tn("meta");
		for (var j = 0; j < metadata.length; j++) {
			if (metadata[j].getAttribute("name") === "description") {
				var description = metadata[j].getAttribute("content");
			}
		}*/
		
		
		for (var i = 0; i < bookmarkingSites.length; i++) {
			/* Get page header to be used in URL string */
			if (!g.idTn("lead", "h2")) return false;
			var pageHeader = g.idTn("lead", "h2");
			var titleText = encodeURIComponent(pageHeader[0].firstChild.nodeValue);
			/* Build URL based on what link is selected */
			bookmarkingSites[i].onclick = function () {	
				var socialBookmarkSite = this.href;
				var thisPageURL = encodeURIComponent(location.href);			
				switch (socialBookmarkSite) {
				case "http://www.newsvine.com/_tools/seed":
					var socialLink = socialBookmarkSite+ '?u=' + thisPageURL + '&h=' + titleText;
					break;   
				case "http://www.stumbleupon.com/":
					var socialLink = socialBookmarkSite+ 'submit?url=' + thisPageURL + '&title=' + titleText;
					break;   
				case "http://www.facebook.com/sharer.php":
					var socialLink = socialBookmarkSite+ '?u=' + thisPageURL + '&=' + titleText;
					break;   
				default:
					var socialLink = socialBookmarkSite+ '?url=' + thisPageURL + '&title=' + titleText;
					//var socialLink = socialBookmarkSite+ '?url=' + thisPageURL + '&title=' + titleText + '&notes=' + description;
					break;
				}
				var thisLink = this.href;
				window.open(socialLink); 
				g.stopDefault(thisLink);
				return false;
			}
		}
	}
};

/*
----------------- 11. Load events on page load -----------------------------*/


if (is_mac && is_ie) {
    g.addEvent(window, 'load', inputButtons.inputStyle, false);
    g.addEvent(window, 'load', eventDelegation.bodyTest, false);
} else {
    //g.addEvent(window, 'load', nav.navPopListeners, false);
    //g.addEvent(window, 'load', nav.hideNavOffTab, false);
    g.addEvent(window, 'load', resDepLayout.checkBrowserWidth, false);
    g.addEvent(window, 'load', resDepLayout.xBrowserResize, false);
    //g.addEvent(window, 'load', myAccountsPop.navPopListeners, false);
    //g.addEvent(window, 'load', myAccountsPop.hideNavOffTab, false);
    g.addEvent(window, 'load', eventDelegation.bodyTest, false);
    g.addEvent(window, 'load', cao.bodyTest, false);
	g.addEvent(window, 'load', socialBookmarking.bookmark, false);
}
