$ektron(function() {

    if ($ektron("#contactComponent").length) {
        categoryName = $ektron("#contactComponent dt").addClass("categoryName");
        subCategoryName = $ektron("#contactComponent dd > p").addClass("subCategoryName");
        subCategoryContent = $ektron("#contactComponent dd > ul").addClass("subCategoryContent");

        $ektron(".categoryName,.subCategoryName").wrapInner("<a href='#'></a>");

        $ektron(subCategoryName).hide();
        $ektron(subCategoryContent).hide();

        $ektron(".categoryName a").click(function() {
            if ($ektron(".subCategoryContent:visible")) {
                $ektron(".subCategoryContent:visible").slideToggle();
            }
            $ektron(this).parent().toggleClass("open");
            $ektron(".subCategoryName").slideToggle();

            return false;
        });
        $ektron(".subCategoryName").click(function() {
            $ektron(this).toggleClass("open");
            $ektron(this).next().slideToggle();

            return false;
        });
    }

    // Decorate show/hide components
    $ektron(".freqAskedQ div div h3").addClass("show");
    $ektron(".freqAskedQ .sectionQuestions .questionList h4").addClass("showQuestion");
    $ektron(".details .fullContent").addClass("showHideContent");
    $ektron(".freqAskedQ .sectionQuestions .answer").addClass("showHideContent_Answer");
    $ektron(".freqAskedQ .sectionQuestions").addClass("showHideContent");
    $ektron(".show,.showQuestion").wrapInner("<a href='#'></a>");

    // Close up topics
    $ektron(".freqAskedQ div div h3").addClass("show");
    // Close up questions
    $ektron(".freqAskedQ .sectionQuestions .questionList h4").addClass("showQuestion");
    $ektron(".showHideContent").hide();

    if ($ektron(".fullContent").length > 0) {
        // Special processing for 'In page highlight' and Our Prices pages
        $ektron(".showHideContent_Answer").hide();
        if ($ektron(".ourPricesContent").length) {
            $ektron(".ourPricesContent .fullContent").before("<p class='show'><a>View our tariff table</a></p>");
            $ektron(this).find(".productFullWidth:first .show").toggleClass("open");
            $ektron(this).find(".productFullWidth:first .show").text("Hide our tariff table");
            $ektron(this).find(".productFullWidth:first .showHideContent").slideToggle();
        }
        else {
            $ektron(".fullContent").before("<p class='show'><a>More</a></p>");
        }
    }
    else if (location.href.toLowerCase().indexOf("forcehide=y") > 0) {
        // Close up all questions
        $ektron(".showHideContent_Answer").hide();
    }
    else if (location.href.toLowerCase().indexOf("forceshow=y") > 0) {
        // Open up all questions - no action needed
    }
    else {
        // Close questions for a section if more than 2
        $ektron(".sectionQuestions").each(function() {
            var $question = $ektron(this),
                $answers = $question.find(".showHideContent_Answer");

            // for each set of questions
            if ($answers.length > 2) {
                $answers.hide();
            } else {
                $question.find("h4").addClass("open");
            }
        });

    }

    // show/hide script	
    if ($ektron(".showHideContent").length) {

        $ektron(".show,.showQuestion").click(function() {
            $ektron(this).next().slideToggle();
            $ektron(this).toggleClass("open");
            if ($ektron(".ourPricesContent").length) {
                if ($ektron(this).text() == "View our tariff table") // toggle innerText 
                {
                    $ektron(this).text("Hide our tariff table");
                }
                else if ($ektron(this).text() == "Hide our tariff table") {
                    $ektron(this).text("View our tariff table");
                }
                return false;
            }

            else {
                if ($ektron(this).text() == "More") // toggle innerText 
                {
                    $ektron(this).text("Less");
                }
                else if ($ektron(this).text() == "Less") {
                    $ektron(this).text("More");
                }
                return false;
            }
        }
					);
    }

    // Create default text for Search text field
    $ektron(".siteSearch input[type=text]").each(function() {
        var labelVal = $ektron(".siteSearch label.searchLabel").text();

        $ektron(this).each(function() {
            createText(labelVal, $ektron(this));
        });
        // Removal of text on user-focus
        $ektron(this).focus(function() {
            removeText(labelVal, $ektron(this));
        });
        // Restoration of default text on input blur, if no user input.
        $ektron(this).blur(function() {
            restoreText(labelVal, $ektron(this));
        });
    });





    // toolTip
    if ($ektron(".whatOurPeersSay").length) {
        $ektron(".peerTxt").wrap('<div class="peerTxtContainer"></div>');

        $ektron(".peerContent img").each(
						   function() {
						       $ektron(this).attr("alt", ""); // remove IE alt tooltip 
						   }
						   );

        $ektron(".peerContent").hover(
				function() {
				    $ektron(this).addClass("selectedToolTip");
				},
				function() {
				    $ektron(this).removeClass("selectedToolTip");
				}
				);
    }

    // Search results page - give link urls max number of characters
    $ektron(".searchResults dl dd p a").each(function() {
        var searchLink = $ektron(this).eq(0);
        var searchLinkText = $ektron(this).eq(0).text();

        var maxChar = $ektron(this).text().substr(0, 72);

        if (searchLinkText.length > 70) { // check character length of each search result link
            $ektron(this).text(maxChar + "...");
        }
    });


    // FAQ list - compare query string with question IDs (category type and question) on FAQ page...
    if ($ektron(".freqAskedQ").length) {
        var categoryID = location.href.match(/#.+$ektron/);

        $ektron(".freqAskedQ .question").each(function() {

            questionAsked = $ektron(this).attr("ID");
            answer = $ektron(this).find(".showHideContent");

            if (categoryID == "#" + questionAsked) { // if question ID matches querystring select that question...
                selectCategory = $ektron(this).parents(".FAQcontent").find(".show").toggleClass("open");
                showQuestions = $ektron(this).parents(".showHideContent").show();
                selectAnswer = $ektron(this).find(".answer").show();
                location.href = location.href;
            }
        });

    }

});


// Create default text for text field on page load
function createText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    //alert(inpType);

    if (inpType != "submit") {

        if (thisObj.attr("value")) {
            if (thisObj.attr("value") == defVal || thisObj.attr("value").length == 0) {

                thisObj.attr("value", defVal);
                thisObj.addClass("empty");
            }
        } else {

            thisObj.attr({
                value: defVal
            });
            thisObj.addClass("empty");
        }




    }
}

// Remove default text on focus. Ignore user-inserted text
function removeText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal == defVal) {
            thisObj.attr("value", "");
            thisObj.removeClass("empty")
        }
    }
}

// Restore default text on focus. Ignore user-inserted text
function restoreText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal != undefined && currVal != '') {
            thisObj.attr("value", currVal);
        }
        else if (currVal == undefined || currVal == '') {
            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}

/* This function toggles the tariff type / meter type based on the product selected */

function ToggleTariffsLayering() {
    var containerRef = document.getElementById("ctl00_ContentPlaceholder_productSignupControl_productTypesCheckBoxList");
    var inputRefArray = containerRef.getElementsByTagName("input");
    var checkCount = 0;
    var elecCheck = 4;
    var gasCheck = 2;
    var telCheck = 1;
    //addding 
    //elec
    if (inputRefArray[0].checked) {
        checkCount = checkCount + elecCheck;
    }
    //gas
    if (inputRefArray[1].checked) {
        checkCount = checkCount + gasCheck;
    }
    //tel
    if (inputRefArray[2].checked) {
        checkCount = checkCount + telCheck;
    }

    var sChargeContainer = document.getElementById("ctl00_ContentPlaceholder_productSignupControl_standingChargeRadioButtonList");
    var eMeterTypeContainer = document.getElementById("ctl00_ContentPlaceholder_productSignupControl_electricityMeterTypeRadioButtonList");

    var sChargeArray = sChargeContainer.getElementsByTagName("input");
    var eMeterTypeArray = eMeterTypeContainer.getElementsByTagName("input");


    if (checkCount == 7 || checkCount == 6 || checkCount == 5 || checkCount == 4 || checkCount == 0) {
        sChargeArray[0].disabled = false;
        sChargeArray[1].disabled = false;
        eMeterTypeArray[0].disabled = false;
        eMeterTypeArray[1].disabled = false;
    }

    if (checkCount == 3 || checkCount == 2) {
        //gas + tel or only gas
        sChargeArray[0].disabled = false;
        sChargeArray[1].disabled = false;
        eMeterTypeArray[0].disabled = true;
        eMeterTypeArray[1].disabled = true;
    }

    if (checkCount == 1) {
        //only tel
        sChargeArray[0].disabled = true;
        sChargeArray[1].disabled = true;
        eMeterTypeArray[0].disabled = true;
        eMeterTypeArray[1].disabled = true;
    }
}

/* eGain Web Chat */
var eglvchathandle = null;
function OpenHelp() {
    try {
        if (eglvchathandle != null && eglvchathandle.closed == false) {
            eglvchathandle.focus();
            return;
        }
    }
    catch (err) { }
    var refererName = "";
    refererName = encodeURIComponent(refererName);
    var refererurl = encodeURIComponent(document.location.href);
    var hashIndex = refererurl.lastIndexOf('#');
    if (hashIndex != -1) {
        refererurl = refererurl.substring(0, hashIndex);
    }
    var w = 630, h = 440;
    var t = 100, l = 0;
    if (window.screen) {
        if (window.screen.availWidth == 800)
            w = window.screen.availWidth * 41 / 100;
        else {
            w = window.screen.availWidth * 31 / 100;
        }
        h = window.screen.availHeight * 90 / 100;
        l = (window.screen.availWidth - w) * 98 / 100;
    }

    var brand;
    var eglvepid;
    if (document.URL.toLowerCase().match('southern')) {
        brand = 'southern-electric';
        eglvepid = 1003;
    }
    else if (document.URL.toLowerCase().match('hydro')) {
        brand = 'hydro';
        eglvepid = 1002;
    }
    else if (document.URL.toLowerCase().match('atlantic')) {
        brand = 'atlanticeg';
        eglvepid = 1004;
    }
    else if (document.URL.toLowerCase().match('swalec')) {
        brand = 'swalec';
        eglvepid = 1001;
    }
    else if (document.URL.toLowerCase().match('sse')) {
        brand = 'sse';
        eglvepid = 1005;
    }
    var params = "width=" + w + ",height=" + h + ",left=" + l + ",top=" + t + ",resizable=no,scrollbars=yes,toolbar=no";
    eglvchathandle = window.open('https://ems00910.egain.net/system/LiveCustomerServlet.egain?eglvcmd=CustEntry&entryPointName=' + brand + '&eglvepid=' + eglvepid + '&departmentid=999&eglvpartid=1&referer=' + refererurl + '&eglvrefname=' + refererName, '', params)
}
/* End eGain Web Chat */

/* eGain Web Chat & CoBrowse using ems00920 */
var eglvchathandle = null;
function StartChat() {
    try {
        if (eglvchathandle != null && eglvchathandle.closed == false) {
            eglvchathandle.focus();
            return;
        }
    }
    catch (err) { }
    var refererName = "";
    refererName = encodeURIComponent(refererName);
    var refererurl = encodeURIComponent(document.location.href);
    var hashIndex = refererurl.lastIndexOf('#');
    if (hashIndex != -1) {
        refererurl = refererurl.substring(0, hashIndex);
    }
    var w = 630, h = 440;
    var t = 100, l = 0;
    if (window.screen) {
        if (window.screen.availWidth == 800)
            w = window.screen.availWidth * 41 / 100;
        else {
            w = window.screen.availWidth * 31 / 100;
        }
        h = window.screen.availHeight * 90 / 100;
        l = (window.screen.availWidth - w) * 98 / 100;
    }

    var brand;
    var eglvepid;
    if (document.URL.toLowerCase().match('southern')) {
        brand = 'Southern';
        eglvepid = 1004;
    }
    else if (document.URL.toLowerCase().match('hydro')) {
        brand = 'hydro';
        eglvepid = 1006;
    }
    else if (document.URL.toLowerCase().match('atlantic')) {
        brand = 'atlantic';
        eglvepid = 1005;
    }
    else if (document.URL.toLowerCase().match('swalec')) {
        brand = 'swalec';
        eglvepid = 1007;
    }
    else {
        brand = 'SSE';
        eglvepid = 1008;
    }

    var eglvcaseid = (/eglvcaseid=[0-9]*/gi).exec(window.location.search);
    var params = "width=" + w + ",height=" + h + ",left=" + l + ",top=" + t + ",resizable=no,scrollbars=yes,toolbar=no";
    eglvchathandle = window.open('https://ems00920.egain.net/system/LiveCustomerServlet.egain?eglvcmd=CustEntry&entryPointName=' + brand + '&eglvepid=' + eglvepid + '&departmentid=999&eglvpartid=1&referer=' + refererurl + '&eglvrefname=' + refererName + '&' + eglvcaseid, '', params)

}

/* End eGain Web Chat & CoBrowse using ems00920 */

/* eGain Web Chat using ems00940 */
var eglvchathandle = null;
function openHelp00940() {
    try {
        if (eglvchathandle != null && eglvchathandle.closed == false) {
            eglvchathandle.focus();
            return;
        }
    } catch (err) { }
    var refererName = "";
    refererName = encodeURIComponent(refererName);
    var refererurl = encodeURIComponent(document.location.href);
    var hashIndex = refererurl.lastIndexOf('#');
    if (hashIndex != -1) {
        refererurl = refererurl.substring(0, hashIndex);
    }
    var w = 400, h = 600;
    var t = 0, l = 0;
    if (window.screen) {
        l = (window.screen.availWidth - w) * 98 / 100;
    }
    var brand;
    var eglvepid;
    if (document.URL.toLowerCase().match('southern')) {
        brand = 'energy_Southern';
        eglvepid = 1020;
    } else if (document.URL.toLowerCase().match('hydro')) {
        brand = 'energy_hydro';
        eglvepid = 1021;
    } else if (document.URL.toLowerCase().match('atlantic')) {
        brand = 'energy_atlantic';
        eglvepid = 1019;
    } else if (document.URL.toLowerCase().match('swalec')) {
        brand = 'energy_swalec';
        eglvepid = 1022;
    } else {
        brand = 'energy_SSE';
        eglvepid = 1018;
    }
    var eglvcaseid = (/eglvcaseid=[0-9]*/gi).exec(window.location.search);
    var params = "width=" + w + ",height=" + h + ",left=" + l + ",top=" + t + ",resizable=no,scrollbars=yes,toolbar=no";

    eglvchathandle = window.open('https://ems00940.egain.net/system/web/view/live/templates/' + brand + '/chat.html?entryPointId=' + eglvepid + '&referer=' + refererurl + '&eglvrefname=' + refererName + '&' + eglvcaseid, '', params)
}

/* End eGain Web Chat & CoBrowse trial using ems00940 */

$(function() {
    //homepage carousel functionality
    function homeSlideShow() {
        var images = window.bannerImages;
        var numberOfImages = images.length;

        if (!images || (numberOfImages <= 1))
            return;

        var timer = images.timer || 3000;
        var index = 0;
        var link = $(".carouselImage a");
        var image = $("img", link);
        var loadingImage = new Image();
        var timerID = null;

        $(".carouselImage").click(function() {
            if (images[index].eventTrackingValue1 != null && images[index].eventTrackingValue2 != null && images[index].eventTrackingValue3 != null) {
                if (images[index].eventTrackingValue1.length > 0 && images[index].eventTrackingValue2.length > 0 && images[index].eventTrackingValue3.length > 0) {
                    pageTracker._trackEvent(images[index].eventTrackingValue1, images[index].eventTrackingValue2, images[index].eventTrackingValue3);
                }
            }
        })

        var dots = null;
        dotBar();

        image.load(function() {
            $(this).show()
        });

        var inTransition = false;

        function imageLoaded() {
            link.css("background-image", 'url(' + loadingImage.src + ')');

            image.fadeOut(1000, function() {
                image.attr({ alt: images[index].alt, title: images[index].alt, src: loadingImage.src });
                link.attr({ title: images[index].alt, href: images[index].href });

                if (timerID != null) {
                    timerID = setTimeout(function() { advanceBanner(); }, timer);
                }
                inTransition = false;
            });
        }

        function imageFail() {
            inTransition = false;
            advanceBanner();
        }

        loadingImage.onload = imageLoaded;
        loadingImage.onerror = imageFail;

        function dotBar() {
            var strDots = "<div class='carouselDotOuter'><div class='carouselDotHolder'><a class='carouselArrow prevSlide' href='#'><img src='/cssImages/nav_arrow_blue.gif' alt='previous slide' /></a><div class='bullets'>";
            for (i = 0; i < numberOfImages; i++) {

                strDots += "<a data-slideIndex='" + i + "' class='carouselDot" + (i == 0 ? " carouselDotActive" : "") + "'></a>";

            }

            strDots += "</div><a class='carouselArrow nextSlide' href='#'><img src='/cssImages/nav_arrow_blue_right.gif' alt='next slide' /></a></div></div>";
            $(strDots).appendTo($('.carouselImage'));
            dots = $('.carouselDotHolder .carouselDot').click(function() {
                advanceBanner($(this).attr("data-slideIndex") * 1, true);
                return false;
            });
        }

        function advanceBanner(movement, isAbsolute) {
            if (inTransition) return false;
            inTransition = true;
            if (!movement && isNaN(movement)) movement = 1;
            if (isAbsolute) {
                index = movement;
            }
            else {
                index = ((index + (images.length + movement)) % images.length);
            }

            loadingImage.src = images[index].src;
            dots.removeClass('carouselDotActive').eq(index).addClass('carouselDotActive');

        }

        $('.prevSlide,.nextSlide').click(function() {
            advanceBanner(this.className.match(/prevSlide/i) ? -1 : 1);
            return false;
        });

        $(".carouselImage").mouseover(function() {
            clearTimeout(timerID);
            timerID = null;
        })


        .mouseout(function() {
            timerID = setTimeout(function() { advanceBanner(); }, timer);
        });

        timerID = setTimeout(function() { advanceBanner(); }, timer);
    }

    if (window.bannerImages) {
        homeSlideShow();
    }

    //homepage news element
    function homeNews() {
        var newsItems = window.newsItems;
        var total = newsItems.length;

        if (total <= 1) return;

        var container = $(".newsElement");
        var titleObj = $(".title a", container);
        var descriptionObj = $(".description a", container);

        var index = Math.floor(Math.random() * total);
        
        function buildItem() {
            var item = newsItems[index];
            titleObj.html(item.title);
            descriptionObj.html('<img src="' + item.src + '" alt="' + item.alt + '"/>' + item.text);
            titleObj.add(descriptionObj).attr("href", item.href);
        }

        //for PageLoad
        buildItem();

        $('<a data-index="-1" href="#"><img class="arrowLeft" src="/CssImages/button_arrow_left.gif" alt="previous news item" /></a><a data-index="1" href="#"><img class="arrowRight" src="/CssImages/button_arrow_right.gif" alt="next news item" /></a>')
                .appendTo(container)
                .click(function() {
                    var movement = $(this).attr("data-index") * 1;
                    index = ((index + (total + movement)) % total);
                    buildItem();
                    return false;
                });
    }
    if (window.newsItems) {
        homeNews();
    }


    //end news

    //homepage tabs functionality
    var bar = $('<ul></ul>');
    $(".contentFrame h2").each(function(index) {

        $(this).hide();

        var tab = $(this).parent();
        if (!index)
            tab.show();
        $('<li><a href="#">' + $(this).text() + '</a></li>').click(function() {
            $(".contentFrame").hide();
            $("li", bar).removeClass("activeTab");
            tab.show();
            $(this).addClass("activeTab");
            return false;
        }).appendTo(bar);
    });
    $('<div class="navBar"/>').append(bar).prependTo('.homepageTabs');
    $("li:first", bar).click();
    //end tabs 
});

