﻿var isIE6 = $.browser.msie && $.browser.version == 6.0;
var currentAddressContainer;

$(document).ready(function() {

    // track partner signup progress
    $(window).load(function(){
       if($("body.Partner_Signup_Page div.partner-sign-up").length>0) {
            if (pageTracker) {
                var className = new String($("body.Partner_Signup_Page div.partner-sign-up").attr('class'));
                pageTracker._trackPageview("/partners/"+className.replace(/(\s)/gi,"/"));
            }
       }
    });
    
    // fix IE7 focus bug
    $("body.OpalDialog div.availability-checker input[type=text]:first, body.OpalDialog table#id_matrix input[type=text]:first").each(function(){
        $(this).focus();
    });


    $("a[href$=.pdf],a[href$=.docx],a[href$=.mp3]").click(function() {
        var Matches = $(this).attr("href").match(/^(.+)\.([a-zA-Z0-9]{2,4})$/);
        if (pageTracker && Matches.length > 0) {
            pageTracker._trackPageview("/files/" + Matches[2] + Matches[1]);
        }
    });

    // add a simple flag to allow for js-specific css
    $("body").addClass("scripted");
    $("#sel").attr("id", "jsel");
    $(".acc-inner").attr("class", "");

    $(".hoverable").mouseenter(function() {
        $(this).addClass("hover");
    }).mouseout(function() {
        $(this).removeClass("hover");
    });

    $("div.button").mouseenter(function() {
        $(this).addClass("hover");
    }).mouseout(function() {
        $(this).removeClass("hover");
    });

    // add even/odd classes to "alternate" classed elems
    $("ul.alternate li:even, table.alternate tr:even, tbody.alternate tr:even").addClass("even");
    $("ul.alternate li:odd, table.alternate tr:odd, tbody.alternate tr:odd").addClass("odd");


    // search autocomplete
    $("input.AutoComplete").autocomplete("/Templates/Opal/Services/SearchTermSuggest.ashx", { cacheLength: 1, max: 10, minChars: 3, selectFirst: false });

    // allow use of selector for rubbish browsers
    $("blockquote p:first-child").addClass("first-child");

    $("li:first-child").addClass("first");
    $("li:last-child").addClass("last");
    $("legend").wrapInner("<span></span>");

    navEl = $("#lhsnav ul .expanded").get(0);
    if (navEl != undefined) {
        listItems = navEl.getElementsByTagName("LI");
        if (listItems.length > 0) {
            $(listItems[listItems.length - 1]).addClass("vlast");
        }
    }

    // enable clearing/resetting of form field prompts
    $(".LoginForm input").focus(function() {
        if ($(this).attr("defaultValue") == $(this).val()) {
            $(this).val("");
        }
    });
    $(".LoginForm input").blur(function() {
        if ($(this).val() == "" && $(this).attr("defaultValue") != "") {
            $(this).val($(this).attr("defaultValue"));
        }
    });

    // Setup cross-links within tabs
    $("div.ui-tabs-panel a[href^=#tab]").click(function() {
        var id = $(this).attr("href");
        $("ul.ui-tabs-nav li a[href=" + id + "]").trigger("click");
    });

    $(".accordion:not(#SectionAccordion ul.accordion)").accordion({ autoHeight: true, fillSpace: true });
    $("#SectionAccordion ul.accordion").accordion({ autoHeight: true, fillSpace: true, active: $("#SectionAccordion ul.accordion > li").length - 1 });

    // css popup for links to xform page
    $("#XFormPopupWrapper").css("display", "block").dialog({
        bgiframe: true,
        autoOpen: false,
        buttons: {
            Close: function() {
                $(this).dialog('close');
            }
        },
        modal: true,
        dialogClass: "general-dialog",
        resizable: false,
        title: 'Enquiry Form'
    });

    // clicking any class'd link will open the wrapper. assumes Many:1 Links:Wrapper			
    $("a.XFormWrapped").click(function(event) {
        event.preventDefault();
        var src = $(this).attr("href");
        $("#XFormPopupWrapper").dialog('open');

        $("#XFormPopupWrapper iframe").attr("src", src);
        $(".ui-dialog-buttonpane").insertBefore("#XFormPopupWrapper");
        $(".ui-dialog-buttonpane").hide();
        $(".ui-dialog-buttonpane:last").show();
    });

    // ensure required fields (eg postcode) are uppercase to help with validation
    $("input.forceupper, input.postcode").blur(function() {
        $(this).val($(this).val().toUpperCase());
    });

    // show/hide an element depending on whether a separate checkbox is checked
    // hacked a bit with two events for IE
    $(".Revealer input[type=checkbox]").bind("click", RevelationHandler);
    $(".Revealer input[type=checkbox]").bind("change", RevelationHandler);
    // initialize all (un)revealed elements
    $(".Revealer input[type=checkbox]").trigger("change");
    $(".Revealer input[type=checkbox]").unbind("change", RevelationHandler);


    // horizontal accordion
    var expanded;
    var flapWidth = 56;
//var flapWidth = 56;
//  var panelWidth = 487;
	var panelWidth = 775;

    if ($("#BusinessTypeAccordion").length > 0) {

        $("#BusinessTypeAccordion ul li a.flap img").css("opacity", "0.4");
        $("#BusinessTypeAccordion ul li div.content").hide();

        expanded = $("#BusinessTypeAccordion ul li:last");

        $("a.flap img", expanded).css("opacity", "1");
        $("div.content", expanded).show(1, function() { this.innerHTML = this.innerHTML }); //includes fix for IE6 to refresh content after animation
        expanded.addClass("expanded");

        var newTabIndex = expanded.attr("id").substr(6, 1);
        $("#BusinessTypeAccordion ul li").each(function() {
            var tabIndex = $(this).attr("id").substr(6, 1);
            if (tabIndex < newTabIndex) {
                $(this).css("left", ((panelWidth - (flapWidth * tabIndex)) * -1) + "px");
            } else {
                $(this).css("left", (flapWidth * (tabIndex - 1)) + "px");
            }
        });

        $("#BusinessTypeAccordion ul li a.flap").hover(function() {
            if (!$(this).parent("li").hasClass("expanded")) {
                $("img", this).stop().animate({ "opacity": "1", duration: 5 });
            }
        }, function() {
            if (!$(this).parent("li").hasClass("expanded")) {
                $("img", this).stop().animate({ "opacity": "0.4", duration: 5 });
            }
        });

        $("#BusinessTypeAccordion ul li a.flap").click(function(event) {
            if (!$(this).parent("li").hasClass("expanded")) {

                $("a.flap img", expanded).stop().animate({ "opacity": "0.4", duration: 5 });
                $("div.content", expanded).hide();
                expanded.removeClass("expanded");

                expanded = $(this).parent();

                $("a.flap img", expanded).css("opacity", "1");
                $("div.content", expanded).show(1, function() { this.innerHTML = this.innerHTML }); // Need to work out why fadeIn doesn't work correctly on IE
                expanded.addClass("expanded");

                var newTabIndex = expanded.attr("id").substr(6, 1);
                $("#BusinessTypeAccordion ul li").each(function() {
                    var tabIndex = $(this).attr("id").substr(6, 1);
                    if (tabIndex < newTabIndex) {
                        $(this).stop().animate({ "left": ((panelWidth - (flapWidth * tabIndex)) * -1) + "px", duration: 5 });
                    } else {
                        $(this).stop().animate({ "left": (flapWidth * (tabIndex - 1)) + "px", duration: 5 });
                    }
                });
            }
        });
    }

    // Postcode lookup
    $("input.postcode").after("<a class='pa_lookup linkbtn'><span>Lookup</span></a>");
    $("a.pa_lookup").click(function() {
        setCurrentAddressContainer(this);
        var postcode = $("input.postcode", $(currentAddressContainer)).val();
        doPostcodeLookup(postcode);
        return false;
    });


    // Blank targets
    $("a[target=_blank][class!=linkbtn]").after("<span class='newwindow'><a title='Opens in a new window'>&nbsp;</a></span>");

    // FAQs
    $(".faqs dd").hide();
    $(".faqs dt").wrapInner("<a></a>");
    $(".faqs dt a").css("cursor", "pointer").attr("title", "Click to show/hide").click(function() {
        var parent = $("+ dd", $(this).parent());
        $(".faqs dd").each(function() {
            if ($(this).attr("id") == $(parent).attr("id")) {
                slideToggle(this);
            } else {
                slideToggle(this, false);
            }
        });
        return false;
    });

    // Hub 'accordion' 
    $("ul#Challenges li.challenge").mouseenter(function(event) {
        event.preventDefault();
        var thisid = $(this).attr("id");
        $("ul#Challenges li").removeClass("selected");
        $(this).addClass("selected");
        $("#ChallengeFocus li").css("visibility", "hidden");
        $("#ChallengeFocus li." + thisid).css("visibility", "visible");
    });
    $("ul#Challenges li:first").addClass("selected");
    $("#ChallengeFocus li.challenge0").css("visibility", "visible");

    // Hide and Reveal
    $("a[name=hide-and-reveal]").each(function() {
        $(this).text("Read more").css("cursor", "pointer").click(function(e) {
            e.preventDefault();
            $(this).parent("p").next("div.hide-and-reveal-content").slideDown("slow");
            $(this).remove();
        }).parent("p").nextAll().wrapAll("<div class='hide-and-reveal-content' style='display: none;'></div>");
    });

    // webstore product tab bband comparison tables: expects link href and table id naming convention
    $("#WebstoreProductTabs .tab table.comparison").hide();
    $("#WebstoreProductTabs .tab table.comparison:first").show();
    $("#WebstoreProductTabs .tab ul.comparelist li a:first").addClass("selected");
    $("#WebstoreProductTabs .tab ul.comparelist li a").click(function(event) {
        event.preventDefault();
        var tablenamematch = this.href.match(/\#(.+)$/);
        if (tablenamematch.length > 0) {
            $("#WebstoreProductTabs .tab ul.comparelist li a").removeClass("selected");
            $(this).addClass("selected");
            $("#WebstoreProductTabs .tab table.comparison").hide();
            $("#WebstoreProductTabs .tab table#compare_" + tablenamematch[1]).fadeIn();
        }
    });

    // Basket
    $(".ws-basket-options:not(.ignore)").hide();
    $(".ws-basket-options.active").show();
    $(".ws-basket-product:not(.ignore) h2").wrapInner("<a></a>").css("cursor", "pointer").attr("title", "Click to show/hide").click(function() {
        $(".ws-basket-options:not(.ignore)", $(this).parent().parent()).each(function() {
            slideToggle(this);
        });
    });


    // preload hover img for order button
    if($("input.orderbutton").attr("src") == "/Templates/Opal/Images/buttons/place-order-hover.gif") {
        image = new Image(); image.src="/Templates/Opal/Images/buttons/place-order.gif";
    }
    $("input.orderbutton").mouseenter(function() {
        $(this).attr("src","/Templates/Opal/Images/buttons/place-order-hover.gif");
    });
    $("input.orderbutton").mouseout(function() {
        $(this).attr("src","/Templates/Opal/Images/buttons/place-order.gif");
    });
    $("input.orderbutton").click(function(event) {
        if ($("#TCAgreeHldr :checkbox[checked]").length == 0) {
            $("#TCErr").css("display","block");
            event.preventDefault();
        }
        else {
            $("#TCErr").css("display","none");            
            if (Page_ClientValidate('BankDetailsGrp') == false) {
                event.preventDefault(); 
            }
            else {
                // we can't disable or "hide" the button or .NET won't submit from it, so...
                $("input.orderbutton").css("position","absolute").css("top","-1000px").css("opacity","0");
                $("p#orderConfirmMsg").css("display","block");
            }
         }
    });
    
    


    // webstore popup
    $("a[href*=/webstore-content/]").click(function(event) {
        if (window.location.href.indexOf("/webstore-content/") == -1) {
            event.preventDefault();
            launchWebstore($(this).attr("href"));
        }
    });

    $(".prod-list li:first").addClass("active");
    $(".prod-list-content li:first").siblings().hide();
    $(".prod-list li a").click(function(e) {
        if ($(this).attr("href").indexOf("#") > -1) {
            e.preventDefault();
            $(this).parents("li").addClass("active").siblings().removeClass("active");
            $(".prod-list-content li:has(a[name='" + $(this).attr("href").replace("#", "") + "'])").show().siblings().hide();
            $(".prod-list-content li:has(a[name='" + $(this).attr("href").replace("#", "") + "'])").get(0).innerHTML += "";
        }
    });

    ShowPremises();
    $(".seladdr input:radio").click(ShowPremises);

    // Availability checker launcher
    $(".availability-checker-launcher a.linkbtn, .availability-checker-launcher :submit").attr("onclick", "").click(function(e) {
        e.preventDefault();
        var wrapper = $(this).parents(".availability-checker-launcher");
        var url = $("input[type=hidden][id$=hdnRedirectUrl]", $(wrapper)).val();
        var telephone = $("input[type=text][id$=txtTelephoneNumber]", $(wrapper)).val();
        var postcode = $("input[type=text][id$=txtPostcode]", $(wrapper)).val();

        url = url + "?telephone=" + escape((telephone == undefined) ? "" : telephone) + "&postcode=" + escape((postcode == undefined) ? "" : postcode);

        launchWebstore(url);
    });

    // Speed checker 
    $("a[href*=/speed-checker/]").unbind("click").click(function(event) {
        event.preventDefault();

        if (document.getElementById("SCPopupWrapper")) {
            $("#SCPopupWrapper").remove()
        }

        $("body div#wrapper").before("<div id='SCPopupWrapper'><iframe id='PopupFrame'></iframe></div>");
        $("#SCPopupWrapper").css("display", "block").dialog({
            bgiframe: true,
            autoOpen: false,
            buttons: {
                Close: function() {
                    $(this).dialog('close');
                }
            },
            modal: true,
            resizable: false,
            title: 'Speed Checker',
            dialogClass: "speed-checker-dialog"
        });

        $("#PopupFrame").attr("src", $(this).attr("href"));
        $("#SCPopupWrapper").dialog('open');
        $(".ui-dialog-buttonpane").insertBefore("#SCPopupWrapper");
        $(".ui-dialog-buttonpane").hide();
        $(".ui-dialog-buttonpane:last").show();
    });

    $("a[href *= /forms/]").unbind("click").click(function(event) {
        event.preventDefault();

        if (document.getElementById("PopupWrapper")) {
            $("#PopupWrapper").remove()
        }

        $("body div#wrapper").before("<div id='PopupWrapper'><iframe id='PopupFrame'></iframe></div>");
        $("#PopupWrapper").css("display", "block").dialog({
            bgiframe: true,
            autoOpen: false,
            buttons: {
                Close: function() {
                    $(this).dialog('close');
                }
            },
            modal: true,
            resizable: false,
            title: 'Speed Checker',
            dialogClass: "general-dialog-small"
        });

        var href = $(this).attr("href");
        if (href.indexOf("interest=") < 0) {
            if (href.indexOf("?") > -1) {
                href += "&interest=" + pageName;
            } else {
                href += "?interest=" + pageName;
            }
        }

        $("#PopupFrame").attr("src", href);
        $("#PopupWrapper").dialog('open');
        $(".ui-dialog-buttonpane").insertBefore("#PopupWrapper");
        $(".ui-dialog-buttonpane").hide();
        $(".ui-dialog-buttonpane:last").show();
    });

    $(".OpalDialog .availability-checker .linkbtn").click(function(event) {
        $(".OpalDialog .availability-checker .col2").css("background", "#ffffff url(/Templates/Opal/Images/loading-trans.gif) no-repeat center center");
        $(".OpalDialog .availability-checker .col2 *").css("visibility", "hidden");
    });

    $(".printbtn").html("<a href=\"#\" class=\"linkbtn\"><span>Print this page</span></a>").click(function(event) {
        $(".ws-basket-options").show();
        window.print();
    });
    
    $(".resource a[href*='?video=']").click(function(event) {

        event.preventDefault();

        if (document.getElementById("PopupWrapper")) {
            $("#VideoPopupWrapper").remove()
        }

        $("body div#wrapper").before("<div id='VideoPopupWrapper'><iframe id='PopupFrame'></iframe></div>");
        $("#VideoPopupWrapper").css("display", "block").dialog({
            bgiframe: true,
            autoOpen: false,
            buttons: {
                Close: function() {
                    $(this).dialog('close');
                }
            },
            modal: true,
            resizable: false,
            title: 'Video Player',
            dialogClass: "video-dialog",
            close: function(ev, ui) {
                $(this).remove();
            }
        });

        var href = $(this).attr("href");

        $("#PopupFrame").attr("src", href);
        $("#VideoPopupWrapper").dialog('open');

        return false;
    });

});

function DoBreakout(){
    $("#WebstorePopupWrapper").dialog('close');
}

function SwapLightbox(url){
    $("#SCPopupWrapper").dialog('close');
    launchWebstore(url);
}

function setCurrentAddressContainer(el) {
    var addressContainer = $(el).parents(".address-container");
    currentAddressContainer = (addressContainer == undefined || addressContainer.length == 0) ? $("body") : addressContainer;
}

function doPostcodeLookup(postcode) 
{
    var strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?";
    strUrl += "&action=lookup";
    strUrl += "&type=by_postcode";
    strUrl += "&postcode=" + escape(postcode);
    strUrl += "&account_code=" + escape(paAccountCode);
    strUrl += "&license_code=" + escape(paLicenseCode);
    strUrl += "&callback=doPostcodeLookup_Complete";

    $.getScript(strUrl);
}

function doPostcodeLookup_Complete() 
{
    if (pcaIsError) {
        alert(pcaErrorMessage);
    } else {
        //Check if there were any items found
        if (pcaRecordCount == 0) {
            alert("Sorry, no matching items found. Please try another postcode.");
        } else {
            $(".pa_results", $(currentAddressContainer)).remove();
            var isXForm = $("input.postcode", $(currentAddressContainer)).parents("#id-matrix").length > 0;
            if (isXForm) {
                $("input.postcode", $(currentAddressContainer)).parents("tr").after("<tr class='pa_results'><td><label>Found addresses</label><select class='pa_addresslist'></select><a class='pa_fetch linkbtn'><span>Select</span></a> <a class='pa_cancel linkbtn'><span>Cancel</span></a></td></tr>");
            } else {
            $("input.postcode", $(currentAddressContainer)).parents("fieldset").after("<fieldset class='pa_results text'><div class='cf'><label>Found addresses</label><select class='pa_addresslist'></select></div><a class='pa_fetch linkbtn'><span>Select</span></a> <a class='pa_cancel linkbtn'><span>Cancel</span></a></fieldset>");
            }
            for (i = 0; i < pca_id.length; i++) {
                $(".pa_addresslist", $(currentAddressContainer)).append("<option value='" + pca_id[i] + "'>" + pca_description[i] + "</option>");
            }

            $("a.pa_fetch", $(currentAddressContainer)).click(function() {
                setCurrentAddressContainer(this);
                var id = $("select.pa_addresslist", $(currentAddressContainer)).val();
                doAddressFetch(id);
                return false;
            });

            $("a.pa_cancel", $(currentAddressContainer)).click(function() {
                $(".pa_results", $(currentAddressContainer)).remove();
                return false;
            });
        }
    }
}

function doAddressFetch(id) 
{
    var strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?";
    strUrl += "&action=fetch";
    strUrl += "&id=" + escape(id);
    strUrl += "&account_code=" + escape(paAccountCode);
    strUrl += "&license_code=" + escape(paLicenseCode);
    strUrl += "&callback=doAddressFetch_Complete";

    $.getScript(strUrl);
}

function doAddressFetch_Complete() 
{
    if (pcaIsError) {
        alert(pcaErrorMessage);
    } else {
        if (pcaRecordCount == 0) {
            alert("Sorry, no matching items found");
        } else {
            $("input.company", $(currentAddressContainer)).val(pca_organisation_name[0]);
            $("input.address1", $(currentAddressContainer)).val(pca_line1[0]);
            $("input.address2", $(currentAddressContainer)).val(pca_line2[0]);
            $("input.address3", $(currentAddressContainer)).val(pca_line3[0]);
            $("input.address4", $(currentAddressContainer)).val(pca_line4[0]);
            $("input.address5", $(currentAddressContainer)).val(pca_line5[0]);
            $("input.town", $(currentAddressContainer)).val(pca_post_town[0]);
            $("input.county", $(currentAddressContainer)).val(pca_county[0]);
            $("input.postcode", $(currentAddressContainer)).val(pca_postcode[0]);
        }
    }

    $(".pa_results", $(currentAddressContainer)).remove();
}

// handles reveals triggered by external elems
function RevelationHandler(e) {
    var jqElem = $(e.target);
    var classname = jqElem.parent().attr("class");
    var matches;
    if(matches = classname.match(/Reveals_(\d+)/)) {
        var RevealedElem = $(".RevealedBy_"+matches[1]);
        if(jqElem.attr('checked')) { RevealedElem.css("display",""); } else { RevealedElem.css("display","none"); } 
    }
}

// this is a fix for the jQuery slide effects
function slideToggle(el, bShow) {
    var $el = $(el), height = $el.data("originalHeight"), visible = $el.is(":visible");

    // if the bShow isn't present, get the current visibility and reverse it
    if (arguments.length == 1) bShow = !visible;

    // if the current visiblilty is the same as the requested state, cancel
    if (bShow == visible) return false;

    // get the original height
    if (!height) {
        // get original height
        height = $el.show().height();
        // update the height
        $el.data("originalHeight", height);
        // if the element was hidden, hide it again
        if (!visible) $el.hide().css({ height: 0 });
    }

    // expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
    if (bShow) {
        $el.show().animate({ height: height }, { duration: 250 });
    } else {
        $el.animate({ height: 0 }, { duration: 250, complete: function() {
            $el.hide();
        }
        });
    }
}

function SwapHomeMessage(index) {
    $("#msg" + index).fadeIn("normal").siblings().fadeOut("normal");
}

function ShowPremises(){
    if ($(".seladdr input:radio").length > 0) {
        if ($(".seladdr input:radio").get(0).checked) {
            $("#premisesaddr").hide();
        } else {
            $("#premisesaddr").show();
        }
    }
}

function launchWebstore(url) {

    if (document.getElementById("WebstorePopupWrapper")) {
        $("#WebstorePopupWrapper").remove();
    }
    
    $("body div#wrapper").before("<div id='WebstorePopupWrapper'><iframe id='WebstoreFrame'></iframe></div>");
    $("#WebstorePopupWrapper").css("display", "block").dialog({
        bgiframe: true,
        autoOpen: false,
        buttons: {
            Close: function() {
                $(this).dialog('close');
            }
        },
        modal: true,
        resizable: false,
        title: 'Webstore Product',
        dialogClass: "webstore-dialog"
    });
    
    $("#WebstoreFrame").attr("src", url);
    $("#WebstorePopupWrapper").dialog('open');
    $(".ui-dialog-buttonpane").insertBefore("#WebstorePopupWrapper");
    $(".ui-dialog-buttonpane").hide();
    $(".ui-dialog-buttonpane:last").show();
}

