﻿$(function () {
    function InitVideo(element, autoplay) {
        var currentWidth = element.width();
        var currentHeight = element.height();
        var href = element.attr("href");
        var code = "";
        var newHtml = "";
        if (href.indexOf("youtube") != -1) {
            code = href.split("=")[1];
            newHtml = "<object width='" + currentWidth + "' height='" + currentHeight + "'><param name='movie' value='http://www.youtube.com/v/" + code + "&hl=en_GB&fs=1&autoplay=" + autoplay + "'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/" + code + "&hl=en_GB&fs=1&autoplay=" + autoplay + "' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='" + currentWidth + "' height='" + currentHeight + "'></embed></object>";
        } else if (href.indexOf("vimeo") != -1) {
            var finalSlash = href.lastIndexOf('/');
            var code = href.substr(finalSlash + 1, href.length - finalSlash - 1);
            newHtml = "<object width='" + currentWidth + "' height='" + currentHeight + "'><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id=" + code + "&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF&amp;fullscreen=1&amp;autoplay=" + autoplay + " &amp;loop=0' /><embed src='http://vimeo.com/moogaloop.swf?clip_id=" + code + "&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF&amp;fullscreen=1&amp;autoplay=" + autoplay + "&amp;loop=0' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='" + currentWidth + "' height='" + currentHeight + "'></embed></object>";
        }

        element.html(newHtml);
    }


    function GetImageData(element) {
        var imageData = new Object();
        var eWidth = element.parent().width();
        var eHeight = element.parent().height();
        var info = element.attr("data-imageData").split("|");
        imageData.id = info[0];
        imageData.alt = info[1];
        imageData.width = Math.floor(parseFloat(info[4]) * eWidth);
        imageData.height = Math.floor(parseFloat(info[5]) * eHeight);
        return imageData;
    }

    function RefreshHotButtons() {
        $(".hot-button .inner").each(function () {
            var isVideo = $(this).parent().parent().parent().parent().hasClass("video");
            var isWisebuys = $(this).parent().parent().hasClass("wisebuys-button");
            if (isVideo) {
                RefreshVideo($(this));
            } else if (isWisebuys) {
                RefreshWisebuysButton($(this));
            } else {
                RefreshHotButton($(this));
            }
        });

        $(".hot-button-image").each(function () {
            var eWidth = $(this).parent().width();
            var eHeight = $(this).parent().height();
            var info = $(this).attr("data-image-data");
            info = info.replace("{width}", eWidth);
            info = info.replace("{height}", eHeight);
            $(this).attr("src", info);
        });

        $(".hot-button .image").each(function () {
            var imageData = GetImageData($(this));
            if (imageData == null) alert("WTF");
            var img = '<img src="/AdminContent/FittedImage?imageId=' + imageData.id + '&width=' + imageData.width + '&height=' + imageData.height + '&fromCache=true" alt="' + imageData.alt + '">';
            $(this).html(img);
        });

        $(".hot-button .header-text").each(function () {
            var imageData = GetImageData($(this));
            if (imageData == null) alert("WTF");
            var img = '<img src="/AdminContent/HotButtonText?lines=' + imageData.id + '&width=' + imageData.width + '&height=' + imageData.height + '&fromCache=true" alt="' + imageData.alt + '">';
            $(this).html(img);
        });

        $(".hot-button .go-button").each(function () {
            var imageData = GetImageData($(this));
            if (imageData == null) alert("WTF");
            var img = '<img src="/AdminContent/FittedImage?imageId=CmsImageEa544230f8854936ad22c057b6655290&width=' + imageData.width + '&height=' + imageData.height + '&fromCache=true" alt="' + imageData.alt + '">';
            $(this).html(img);
        });

        $(".hot-button .video-button").each(function () {
            var imageData = GetImageData($(this));
            if (imageData == null) alert("WTF");
            var img = '<img src="/AdminContent/FittedImage?imageId=' + imageData.id + '&width=' + imageData.width + '&height=' + imageData.height + '&fromCache=true" alt="' + imageData.alt + '">';
            $(this).html(img);
        });
    }

    var count = 0;

    function RefreshHotButton(button) {
        button.height(button.width() * 0.78125);
        //var fontsize = ( ( button.width() / 163 ) * 0.7 ) * 100;
        //$( "#content .hot-button .inner .small-text" ).css( { "font-size" : fontsize + "%" } );
    }

    function RefreshVideo(button) {
        button.height(button.width() * 0.56);
    }

    function RefreshWisebuysButton(button) {
        button.height(button.width() * 0.9);
    }

    function PageShadows() {
        var contentWidth = $('#header').width();
        var windowWidth = $(window).width();
        var width = windowWidth - contentWidth;
        if (width > 0) {
            width /= 2;
            $('.constrained-shadow').css(
      {
          "display": "block",
          "width": width,
          "height": $('#page .constrained').height()
      }
    );
            $('.constrained-shadow.left').css(
      {
          "left": -width
      }
    );
            $('.constrained-shadow.right').css(
      {
          "right": -width
      }
    );
        } else {
            $('.constrained-shadow').css(
      { "display": "none" }
    );
        }

        if (browserLteIE7) {
            $(".header-shadow").remove().clone().prependTo(".backgrounds");
        }
    }

    function RedistributeNavigationItems() {
        //IE8 either fucks this up completely by not redrawing afterwards, or if
        //you force a redraw (ie $("navigation").hide(1).show(1); then it doesn't 
        //fuck up but it does nothing! so just return if IE 8 :(
        //if( browserLteIE8 && !browserLteIE7 ) return;
        if (browserLteIE8 && !browserLteIE7) return;

        var containerSelector = "#navigation li";
        if (browserLteIE7) {
            containerSelector = "#navigation td";
        }

        if ($("#navigation span").length < 1) {
            $(containerSelector + " a, #navigation .current").wrapInner("<span></span>");
        }

        $("#navigation span").css(
    {
        "padding-left": "0",
        "padding-right": "0"
    }
  );

        var navigationCount = $(containerSelector).length;

        var containerWidths = new Array(navigationCount);
        var textWidths = new Array(navigationCount);

        var index = 0;
        $(containerSelector).each(
    function () {
        containerWidths[index++] = $(this).width();
    }
  );

        index = 0;
        $("#navigation span").each(
    function () {
        textWidths[index++] = $(this).width();
    }
  );

        var textWidthTotal = 0;
        var containerWidthTotal = 0;
        for (var i = 0; i < navigationCount; i++) {
            containerWidthTotal += containerWidths[i];
            textWidthTotal += textWidths[i];
        }
        var difference = containerWidthTotal - textWidthTotal;
        var paddingAmount = Math.floor(difference / (navigationCount * 2));
        $("#navigation span").css(
    {
        "display": "inline-block",
        "padding-left": paddingAmount + "px",
        "padding-right": paddingAmount + "px",
        "text-align": "center"
    }
  );
    }

    function CorrectColumnRoundingBugs() {
        var oneWidth = $("#content .one").width();
        var twoWidth = $("#content .two").width();
        var threeWidth = $("#content .three").width();
        var constrained = $('#page .constrained').width();

        var total = oneWidth + twoWidth + threeWidth;

        if (!browserLteIE7) {
            var header = $('#header').width();
            var footer = $('#footer').width();

            if (total < footer) {
                $('#content').width(header + 1);
            }

            return;
        }


        if ($(window).width() < 600) {
            $("html").css({
                "overflow-x": "scroll"
            });
        } else {
            $("html").css({
                "overflow-x": "hidden"
            });
        }

        if (total > constrained) {
            while (total > constrained) {
                twoWidth -= 1;
                total = oneWidth + twoWidth + threeWidth;
            }
        } else if (total < constrained) {
            while (total < constrained) {
                twoWidth += 1;
                total = oneWidth + twoWidth + threeWidth;
            }
        } else return;

        $("#content .two").width(twoWidth);
    }

    function FixSafariTextRendering() {
        //fix ugly text rendering in Safari
        //browser sniffing OK here, no bad side effects, doesn't really matter if it fails
        var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
        var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        if (isSafari && !isChrome) {
            $("body").addClass("safariTextFix");
        }
    }

    function FixOperaPositioningBug() {
        //in opera, there is a bug with positioning see http://nrkn.com/opera9Bug
        $(".shadow-shim .middle").each(
    function () {
        var parentHeight = $(this).parent().height();
        var topHeight = $(this).parent().find(".top").height();
        var bottomHeight = $(this).parent().find(".bottom").height();
        var middleHeight = parentHeight - (topHeight + bottomHeight);

        //test for opera bug without browser sniffing :)
        if ($(this).height() != middleHeight) {
            $(this).height(middleHeight);
        }
    }
  );
    }

    function SpecialFormatting() {
        $("strong:contains(LIFEWISE)")
  .replaceWith(
    "<strong class='lifewise-text'>"
    + "L<span class='i'><span></span>I</span>FEW<span class='i'><span></span>I</span>SE"
    + "</strong>"
  );

        //$('a[href^="mailto:"]').addClass( "email-link" );
    }

    function ResizeActions() {
        RefreshHotButtons();
        //NewsItemSignatureFix();
        CorrectColumnRoundingBugs();
        RedistributeNavigationItems();
        PageShadows();
        FixOperaPositioningBug();
    };

    function NewsItemSignatureFix() {
        if (browserLteIE7) return;
        $(".letter").each(
    function () {
        $(this).find(".temp-spacer").remove();
        $(this).find(".sig").hide();
        var height = $(this).height();
        var sigHeight = $(this).find(".sig").height();
        var spacerClass = "spacer-" + height + "-" + sigHeight;
        var spacer = "<div class='temp-spacer " + spacerClass + "'></div>";
        $(this).find(".sig").remove().clone().prependTo($(this)).show().css({
            "float": "right",
            "clear": "right",
            "margin": "1em",
            "margin-top": "1.5em"
        });
        $(this).prepend(spacer);
        $("." + spacerClass).css({
            "width": "1px",
            "height": height - sigHeight + "px",
            "float": "right",
            "clear": "right"
        });
    }
  );
    }

    function Guides() {
        $("#page").css({
            "position": "relative"
        }).append("<div id='guides'></div>");

        HorizontalGuide(184);
        HorizontalGuide(202);
        HorizontalGuide(218);
        HorizontalGuide(781);

        VerticalGuide(415);
        VerticalGuide(437);
        VerticalGuide(655);
        VerticalGuide(700);
        VerticalGuide(721);

        VerticalGuide(1166);
        VerticalGuide(1187);
        VerticalGuide(1199);
        VerticalGuide(1210);
        VerticalGuide(1243);
        VerticalGuide(1251);
        VerticalGuide(1297);
        VerticalGuide(1462);
        VerticalGuide(1488);
    }

    function HorizontalGuide(position) {
        var id = "horizontal-" + position;
        $("#guides").append(
    "<div id='" + id + "'></div>"
  );
        $("#" + id).css({
            "background": "#0ff",
            "position": "absolute",
            "top": position + "px",
            "height": "1px",
            "left": "0",
            "right": "0"
        });
    }

    function VerticalGuide(position) {
        var id = "vertical-" + position;
        $("#guides").append(
    "<div id='" + id + "'></div>"
  );
        $("#" + id).css({
            "background": "#0ff",
            "position": "absolute",
            "left": position + "px",
            "width": "1px",
            "top": "0",
            "bottom": "0"
        });
    }

    function SetupVideoSwap() {
        $(".video-hot-button .inner").each(
        function () {
            $(this).click(
              function () {
                  InitVideo($(this), 1 );
                  return false;
              }
            );
        }
      );
    }
    /**/

    ResizeEvents.eventElement.bind(
    'x-initial-sizes x-text-resize x-window-resize x-window-width-resize x-window-height-resize',
    function (eventObj, emPixels, textHeight, windowWidth, windowHeight) {
        ResizeActions();
    }
  );

    ResizeEvents.initialise();
    //SpecialFormatting();
    FixSafariTextRendering();
    ResizeActions();
    //Guides();
    SetupVideoSwap();

    $(".showVideo").each(
    function () {
        InitVideo($(this), 0 );
    }
  );

    var cartContents = $(".cart-contents").length > 0;
    var cartDetails = $(".cart-details").length > 0;

    if (cartContents) {
        $(".cart-contents input[type='submit']").hide();
        $(".cart-contents .quantity a").hide();

        $(".cart-contents .quantity").each(function () {
            var productId = $(this).attr("data-product-id");
            var quantityControl = '<a href="javascript:void(0);" id="{productId}-{control}" title="{control}" class="quantity-control {control}">{text}</a>';
            var increaseControl = quantityControl.replace(/{text}/g, "+").replace(/{productId}/g, productId).replace(/{control}/g, "increase");
            var decreaseControl = quantityControl.replace(/{text}/g, "−").replace(/{productId}/g, productId).replace(/{control}/g, "decrease");
            var removeControl = quantityControl.replace(/{text}/g, "X").replace(/{productId}/g, productId).replace(/{control}/g, "remove");
            var controls = '<label for="' + productId + '-quantity" class="quantity-controls">' + increaseControl + '<span class="separator">/</span>' + decreaseControl + " " + removeControl + '</label>';

            $("#" + productId + "-form").append(controls);

            AddControlClick(productId, "increase", "IncrementQuantity");
            AddControlClick(productId, "decrease", "DecrementQuantity");
            AddControlClick(productId, "remove", "Remove");

            $("#" + productId + "-quantity").change(function () {
                var url = "/Shopping/JsonSetQuantity/" + productId + "/" + $(this).val();
                $.ajax({
                    url: url,
                    cache: false,
                    dataType: "json",
                    success: UpdateCart
                });
            });

            function AddControlClick(productId, controlType, action) {
                $("#" + productId + "-" + controlType).click(function () {
                    $.ajax({
                        url: "/Shopping/Json" + action + "/" + productId,
                        cache: false,
                        dataType: "json",
                        success: UpdateCart
                    });
                });
            }

            function UpdateCart(data) {
                if (data.total == "$0.00") window.location.reload();
                if (data.quantity < 1) {
                    $("#" + data.id + "-cart-content-item").remove();
                } else {
                    var currentQuantity = $("#" + data.id + "-quantity").val();
                    if (data.quantity != currentQuantity) {
                        $("#" + data.id + "-quantity").val(data.quantity);
                    }
                    $("#" + data.id + "-subtotal").html(data.subtotal);
                }
                $("#total").html(data.total);
            }

            $("#" + productId + "-quantity").change();
        });
    }

    if (cartDetails) {
        function FormSubmitOptions() {
            return {
                dataType: 'json',
                success: UpdateDetails,
                url: "/Shopping/DetailsJsonResult"
            }
        }

        $("input[name='PaymentType']").change(function () {
            $('.paymentMethod').hide();
            if ($(this).attr('checked')) {
                $("#paymentMethod" + $(this).attr('value')).show();
            }
        });

        $(".required").change(function () {
            $(".cart-details").ajaxSubmit(FormSubmitOptions());
        });

        function GetKeys(obj) {
            var keys = [];
            for (var propertyName in obj) {
                keys.push(obj[propertyName].name);
            }
            return keys;
        }

        /*  
        function UpdateDetails( data ) {
        if ( data.Supported != null ){
        $( "#ShippingMethod input" ).removeAttr( 'disabled', 'disabled' );
        if ( data.Supported.length == 1 ){
        var supportedId = data.Supported[ 0 ];
        $( "#ShippingMethod input" ).attr( 'disabled', 'disabled' );
        $( "#ShippingMethod input" ).removeAttr( 'checked' );
        $( "#ShippingMethod #" + supportedId ).removeAttr( 'disabled' );
        $( "#ShippingMethod #" + supportedId ).attr( 'checked', 'checked' );
        }
        }      

        var valid = false;
      
        $( ".required" ).removeClass( "invalid" );
        if( data.ErrorFields.length > 0 ) {
        $( "#message" ).show();
        $( "#message" ).html( data.Message );
        for( var i in data.ErrorFields ) {
        var formField = data.ErrorFields[ i ];
        $( "#" + formField ).addClass( "invalid" );
        }
        } else {
        $( "#message" ).hide();
        valid = true;
        }
      
        $.each( data.OrderSummary, function( key, value ) {
        $( "#" + key ).html( value );
        });
      
      
        if( valid ) {
        $( "input[type='submit']" ).removeAttr( 'disabled' );
        } else {
        $( "input[type='submit']" ).attr( 'disabled', 'disabled' );
        }
        }
    
        $( "input[name='PaymentType']" ).change();
        */
    }
});
