﻿var BA = (function ($) {
    var txtPrompt = "Please enter your postcode and telephone number.",
    viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'),
    ua = navigator.userAgent;

    var init = function () {

        viewport();
        homepageFeature();
        productHeader();
        productMoreInfo();
        trackingEvents();
        sortDeals();
        menu();

    };


    var viewport = function () {

        var deviceW = window.innerWidth;
 //       alert("width=" + deviceW);

        if (deviceW >= 768) {
            viewportmeta.content = "";
        }
    };


    var menu = function () {

        $("nav p").on("click", function () {
            $("#menu").toggleClass("open");

        });

        // if iOS
        if (/iPhone|iPad/.test(ua) && !/Opera Mini/.test(ua)) {
            $("#outer nav span").bind("click", function (e) {
                var $li = $(this).parent();
                if ($li.hasClass("has-sub")) {
                    $li.toggleClass("touch");
                }
            });
        }
    };

    var sortDeals = function () {
        // Broadband Deals sorting dropdown
        if ($("#content_sorting").length !== -1) {
            $("#content_sorting").bind("change", function () {
                var selIndex = this[this.selectedIndex],
                  selectText = selIndex.text,
                      selVal = selIndex.value.split(":"),
                        sort = selVal[0],
                         dir = selVal[1],
                        type = this.getAttribute("data-type");

                if (sort !== "") {
                    var $products = $("#products");
                    $products.append("<div id='wait'></div>");

                    $.ajax({
                        url: "/xhr/deals/" + type + "/" + sort + "/" + dir + "/",
                        success: function (response) {
                            var regex = new RegExp("[ ]", 'gi');
                            var regex2 = new RegExp("[\)\(]", 'gi');

                            $products[0].className = selectText.replace(regex, "-").replace(regex2, "").toLowerCase();
                            $products.find("#wait, .prodListing").remove();
                            $products.append(response);
                        }
                    });
                }
            })
        }
    };

    var trackingEvents = function () {
        // Homeapge feature click
        $(".feature a").bind("click", function () {
            _gaq.push(['_trackEvent', 'HmFeature', 'click', $(".feature h4:visible").text()]);
        });

        // goal tracking
        $("a.out, a.logo").bind("click", function () {
            _gaq.push(['_trackEvent', 'link', 'clicked out']);
        })
    };

    var verifyCheckerForm = function () { // public method
        if (document.getElementById("txtPostcode").value === '' || document.getElementById("txtPhone").value === '') {
            $("#message").html(txtPrompt);
            return false;
        }
    };

    // fixes the position of the column titles as the user scrolls the page
    var productHeader = function () {

        if (window.innerWidth > 480) {
            if ($("#prodHd").length === 0) { return; }

            var $header = $("#prodHd"),
            headerHeight = $header.height(),
            headerOffset = Math.ceil($header.offset().top),
            // bottom of the products div
            lowerLimit = Math.ceil($("#products").offset().top + $("#products").height()),
            scrollPos;

            $(window).bind("scroll", function () {
                scrollPos = $(document).scrollTop();

                // scrolled past top of products
                if (scrollPos >= headerOffset) {
                    $header.css("position", "fixed");

                    // scrolled below products so hide header
                    if (scrollPos >= (lowerLimit - headerHeight)) {
                        $header.fadeOut();
                    }
                    // within products so show header
                    if (scrollPos <= lowerLimit) {
                        $header.fadeIn();
                    }

                } else {

                    $header.css("position", "relative");
                }

            });
        }

    };

    var homepageFeature = function () {
        // Homepage ISP Feature
        $(".feature h4").bind("mouseover", function () {
            var $wrap = $(this).parents(".feature");
            $wrap.find(".tabContent").hide();
            $wrap.find("h4").css({ "backgroundPosition": "0 -62px", "color": "#000" });
            $(this).next("div").show();
            $(this).css({ "backgroundPosition": "0 0", "color": "#186BAE" });
            // click thru URL
            var href = $("#moreInfo", $wrap).attr("href").split("=")[0];
            $("#moreInfo", $wrap).attr("href", href + "=" + $(this).parent()[0].id.substring(4));
        });
    };

    // show more info for a deal
    var productMoreInfo = function () {

        $("#products").delegate(".more", "mouseover", function (e) {
            $(this).next().toggleClass("show");
        }).delegate(".more", "mouseout", function (e) {
            $(this).next().toggleClass("show");
        });

    };


    var getRandomBanners = function (isp) {

        if (window.innerWidth > 320) {
            if ($("#headerBanner").length == 1 || $("#skyscraper").length == 1) {
                // get banners
                $.get("/content/banners/getRandomBannersJSON", { isp: isp }, function (data) { banners(data) }, "json");

                // callback
                var banners = function (data) {
                    var banner486 = data.banner[0].Standard;
                    if (banner486 !== null || banner486 !== "") {

                        if (banner486.indexOf("script") > 0) {


                            var src = banner486.match(/http:\/\/(.+?)\"/g, '$1').toString().replace("\"", "");

                            var script = document.createElement("script");
                            script.src = src;
                            document.getElementById("headerBanner").appendChild(script);
                            //    $("#headerBanner").html(banner486);
                        } else {
                            $("#headerBanner")[0].innerHTML = banner486;
                        }
                    }

                    var skyscraper = data.banner[0].Skyscraper;
                    if ($("#skyscraper").length == 1) {
                        if (skyscraper !== null || skyscraper !== "") {
                            $("#skyscraper")[0].innerHTML = skyscraper;
                        }
                    }
                }
            }
        }
    }

    return {
        init: init,
        getRandomBanners: getRandomBanners
    }
} (jQuery));


