﻿var currentSelection = 0;
var currentUrl = '';

function openPopup(url, w, h) {
    width = w;
    height = h;
    x = parseInt(screen.width / 2.0) - (width / 2.0);
    y = parseInt(screen.height / 2.0) - (height / 2.0);

    var win = window.open(url, "editorPopup", "top=" + y + ",left=" + x + ",scrollbars=no,dialog=yes,minimizable=no,modal=yes,width=" + width + ",height=" + height + ",resizable=no");
}

function deleteZoneContent(ZoneArea, PageID) {

    ret = vmcms.DeleteContent.DeleteZone(ZoneArea, PageID, OnComplete, OnTimeOut, OnError);
    return (true);

}

function OnComplete(args) {
    alert(args);
}

function OnTimeOut(args) {
    alert("ERROR : Service call timed out. Possbily content area has no content.");

}

function OnError(args) {
    alert("Error calling service method.");
}

function checkTerms(obj, args) {
    var checkbox = $('#ctl00_ContentPlaceHolder1_terms');
    args.IsValid = checkbox.attr('checked');
}

$(document).ready(function () {

    if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
        $(".promo").hide();
    }

    $("#charts").tabs();
    $("#chartTab1").hide();
    $("#chartTab2").attr("style", "border-right:1px solid white");

    $("#chartTab1 a").click(function () {
        $("#chartTab1").attr("style", "border-right:0px");
        $("#chartTab2").attr("style", "border-right:1px solid white");
        $("#chartTab3").attr("style", "border-right:0px");
        $("#chartTab1").hide();
        $("#chartTab2").show();
        $("#chartTab3").show();
    });
    $("#chartTab2 a").click(function () {
        $("#chartTab1").attr("style", "border-right:1px solid white");
        $("#chartTab2").attr("style", "border-right:0px");
        $("#chartTab3").attr("style", "border-right:0px");
        $("#chartTab2").hide();
        $("#chartTab1").show();
        $("#chartTab3").show();
    });
    $("#chartTab3 a").click(function () {
        $("#chartTab1").attr("style", "border-right:1px solid white");
        $("#chartTab2").attr("style", "border-right:0px");
        $("#chartTab3").attr("style", "border-right:0px");
        $("#chartTab3").hide();
        $("#chartTab1").show();
        $("#chartTab2").show();
    });

    $("#carouselHP").CloudCarousel(
		{
		    xPos: 128,
		    yPos: 32,
		    autoRotate: 'left',
		    altBox: $("#carouselPriceHP"),
		    autoRotateDelay: 5000,
		    titleBox: $("#carouselTitleHP")
		}
	);

    $("#carouselBS").CloudCarousel(
		{
		    xPos: 128,
		    yPos: 32,
		    autoRotate: 'left',
		    altBox: $("#carouselPriceBS"),
		    autoRotateDelay: 5000,
		    titleBox: $("#carouselTitleBS")
		}
	);



    jQuery.oauthpopup = function (options) {
        options.windowName = options.windowName || 'ConnectWithOAuth'; // should not include space for IE
        options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=600';
        var that = this;
        that._oauthWindow = window.open(options.path, 'Twitter', 'location=0,status=0,width=800,height=600');
    };

    $('#ctl00_ContentPlaceHolder1_regTwitterPublish').change(function () {
        if ($('#ctl00_ContentPlaceHolder1_regTwitterPublish').is(':checked')) {
            $.oauthpopup({ path: '/twitterAuth.aspx' });
        }
    });

    jQuery('#alsoBoughtCarousel').jcarousel({
        auto: 4,
        wrap: 'last',
        visible: 4,
        initCallback: mycarousel_initCallback
    });
    jQuery(".newsletterName").Watermark("Name");
    jQuery(".newsletterEmail").Watermark("Email");
    Cufon.replace('span.price', { fontFamily: 'Kabel' });
    Cufon.replace('div#search label', { fontFamily: 'Kabel', fontSize: '22px' });
    Cufon.replace('div#search a.searchBut', { fontFamily: 'Kabel' });
    Cufon.replace('div#newsletter a', { fontFamily: 'Kabel', hover: { color: 'Black'} });

    jQuery(".ajax__tab_panel textarea").Watermark("Enter your review here. You have 500 characters. No bad language please!");

    $('#featureBanners').cycle({
        fx: 'fade',
        timeout: 5000,
        pager: '#nav',
        pagerAnchorBuilder: function (idx, slide) {
            // return selector string for existing anchor 
            return '#nav li:eq(' + idx + ') a';
        }
    });

    $('a[rel=gallery]').colorbox();

    $('#preorder ul').cycle({
        fx: 'scrollRight',
        timeout: 5000
    });

    jQuery(document.body).click(function (event) {
        var clicked = jQuery(event.target);
        if (!(clicked.is('#searchresults') || clicked.parents('#searchresults').length || clicked.is('input'))) {
            $('#searchresults').slideUp(400);
        }
    });

    //$('a.moreBut').bind({
    //click: function () {
    //$(this).next().next().slideDown();
    //$(this).hide();
    //}
    //});

    $('#ctl00_ContentPlaceHolder1_ctl00_payBut').live('click', function () {
        if (Page_ClientValidate("card")) {
            $(this).html("<img src=\"/graphics/basket_loading.gif\">");
            $(this).attr("style", "background-image: none; text-align:center;");
            $(this).attr("disabled", "disabled");
        }
    });

    $('#clear_billing').live('click', function () {
        $(".billingTable").find(':input').each(function () {
            switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });
    });

    $('#clear_delivery').live('click', function () {
        $(".deliveryTable").find(':input').each(function () {
            switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });
    });

    $(".stockCheck").click(function (event) {
        event.preventDefault;
        if ($(this).attr("rel") == "soldout") {
            alert('Sorry, this product is unavailable in all of our stores');
        } else if ($(this).attr("rel") == "preorder") {
            alert('This product is for pre-order delivery only');
        }
        else {
            if ($("input#postcode").val() != '') {
                $.fn.colorbox({ width: "480px", height: "410px", iframe: true, href: "/stockCheck.aspx?loc=" + $("input#postcode").val() + "&id=" + $(this).attr("rel") });
                $("#")
            } else {
                alert('Please enter a Postcode, Town or Store Name');
            }
        }
    });

    $('div.reviewContent').expander({
        slicePoint: 217,  // default is 100
        expandText: 'Read more', // default is 'read more...'
        collapseTimer: 5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
        userCollapseText: 'Read less...'  // default is '[collapse expanded text]'
    });

    $(".add").click(function (event) {
        $(this).attr('class', 'add loading');
        $(this).children().hide();
        var aObj = $(this);
        event.preventDefault();
        request = jQuery.ajax({
            type: "GET",
            url: $(this).attr('href').replace("basket", "ajaxBasket.aspx"),
            cache: false,
            success: function (html) {
                jQuery("#basketSummary").html(html);
                aObj.attr('class', 'add complete');
                aObj.children().fadeIn(2000);
            }
        });
        return false;
    });

    function updateBasket(html) {
        jQuery("#basketSummary").html(html);
    }

    $(".basketLogin").click(function (event) {
        $("#basketAddresses").animate({ marginLeft: '-793px' }, 'slow');
        event.preventDefault();
    });

    $(".cancelLogin").click(function (event) {
        $("#basketAddresses").animate({ marginLeft: '0px' }, 'slow');
        event.preventDefault();
    });

    $("div#breadcrumb div:last-child").addClass("on");
    $("div#breadcrumb div:last-child a").each(function () {
        $(this).replaceWith($(this).text());
    });
    $("div.prices div.price:first-child").addClass("first");
    $("div.prices div.price:first-child span").addClass("first");
    $("div.prices div.price:last-child span").addClass("last");
    $("div.result:nth-child(4n)").addClass("lastrow");

    $('.search').bind('keypress', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            if ($('.search').val() != "") {
                e.preventDefault();
                window.location = "/search?k=" + $('.search').val();
            }
        }
    });
});

function ajaxLoading() {
    $(".search").addClass("loading");
}

function ajaxHover() {
    
}

function itemSelected(ev) {
    var index = $find("AutoCompleteEx")._selectIndex;

    if (index != -1) {

        var title = $find("AutoCompleteEx").get_completionList().childNodes[index].innerText;

        if (title != null) {
            if (title != "null") {
                document.getElementById("ctl00_ajaxSearch").value = title.substring(0, title.indexOf("(") - 1);
            }
        }

            if ($('.search').val() == "null") {
                $('.search').val('');
            }

        window.location = $find("AutoCompleteEx").get_completionList().childNodes[index]._value;

    }
}

function onClientPopulated(sender, e) {
    var completionList = $find("AutoCompleteEx").get_completionList();
    for (i = 0; i < completionList.childNodes.length; i++) {
        var _value = completionList.childNodes[i]._value;
        var text = completionList.childNodes[i].innerHTML;
        completionList.childNodes[i].innerHTML = "<a href='" + _value + "'><b>" + text.replace("(", "</b><br/>(") + "</a>";
        jQuery(".search").removeClass("loading");
        if (xhr != null) {
            xhr.abort();
        }
        var xhr = $.ajax({
            type: "POST",
            url: "/ajaxSearch.aspx?k=" + $('.search').val()
        });
    }
}

function mycarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function () {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function () {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function () {
        carousel.stopAuto();
    }, function () {
        carousel.startAuto();
    });
};

function navigate(direction) {
    // Check if any of the menu items is selected
    if (jQuery("#searchresults ul li.itemhover").size() == 0) {
        currentSelection = -1;
    }

    if (direction == 'up' && currentSelection != -1) {
        if (currentSelection != 0) {
            currentSelection--;
        }
    } else if (direction == 'up' && currentSelection == -1) {
        $(".search").focus();
    } else if (direction == 'down') {
        if (currentSelection != jQuery("#searchresults ul li").size() - 1) {
            currentSelection++;
        }
    }
    setSelected(currentSelection);
}

function setSelected(menuitem) {
    jQuery("#searchresults ul li").removeClass("itemhover");
    jQuery("#searchresults ul li").eq(menuitem).addClass("itemhover");
    currentUrl = jQuery("#searchresults ul li a").eq(menuitem).attr("href");
}

function resetjQuery() {
    Cufon.replace('div#newsletter a', { fontFamily: 'Kabel', hover: { color: 'Black'} });
    jQuery(".newsletterName").Watermark("Name");
    jQuery(".newsletterEmail").Watermark("Email");
}
