﻿var Harrods = function(){}
var h = Harrods;
h.prototype.init = function() {
    var _self = this;
    var theHash = window.location.hash;
    if (theHash != "") {
        theHash = theHash.replace(/#/g, '').substr(0, 2).replace(/_/g, '') - 1;
        $('.managed_content dl.accordion dt').eq(theHash).addClass('active');
        $('.managed_content dl.accordion dd').eq(theHash).show();
        var targetOffset = $('.managed_content dl.accordion dt').eq(theHash).offset().top;
        $('html,body').animate({ scrollTop: targetOffset }, "slow");
    } else {
        $('.managed_content dl.accordion dt').eq(0).addClass('active');
        $('.managed_content dl.accordion dd').eq(0).show();
    };
    if ($("form[action^='login']").length > 0) {
        $('.login a').eq(0).addClass('selected');
    };
    if ($("form[action^='register']").length > 0) {
        $('.login a').eq(1).addClass('selected');
    };
    if ($("body").hasClass('experience')) {
        $('.header_nav2 li').eq(0).children('a').addClass('selected');
    } else if ($("body").hasClass('brands')) {
        $('.header_nav2 li').eq(1).children('a').addClass('selected');
    } else if ($("body").hasClass('events')) {
        $('.header_nav2 li').eq(2).children('a').addClass('selected');
    } else if ($("body").hasClass('contactus')) {
        $('.header_nav2 li').eq(3).children('a').addClass('selected');
    } else if ($("body").hasClass('launches')) {
        $('.header_nav2 li').eq(4).children('a').addClass('selected');
    } else if ($("body").hasClass('Christmas')) {
        $('.header_nav2 li').eq(5).children('a').addClass('selected');
    };
    if ($(".product_features").length > 0) {
        $(".product_features > ul").tabs();
    }
    if ($("table.sv-products").length > 0) {
        $("table.sv-products > tbody > tr").each(function() {
            $(this).children("td").eq(3).addClass("last");
        })
    };
    $('.footer_search_field').focus(function() { $(this).addClass('focused'); });
    this.leftNavOpenClose();
    this.altImages();
    this.collectionThumbs();
    this.searchValidation();
    this.newsLetterValidation();
    this.fadeProdList();
    this.accordion();
    this.internationalDelivery();

    if ($("#TrackingNumber").length > 0) {
        var trackingNumber = this.getQueryVariable("trackingnumber");
        if (!isNaN(trackingNumber) && trackingNumber.length <= 10) {
            $("#TrackingNumber").text("Your order number is: " + trackingNumber);
        }
    }
}
h.prototype.internationalDelivery = function() {
    $(".inter_delivery_box a").click(function() {
        hamperModal($(this), 510, 540, $("#inter_delivery_modal"));
        return false;
    });
    function hamperModal(ele, mdw, mdh, cont) {
        var theTitle = ele.attr("title");
        var theContent = cont.html();
        $("#email_box").text("");
        $("#harrods_experience").hide();
        $('.fullhomepage > object').hide();

        $("#email_box").dialog({
            width: mdw,
            height: mdh,
            title: theTitle,
            modal: true,
            overlay: {
                opacity: 0.9,
                background: "#000000"
            }
        }).fadeIn("slow");
        $(".ui-dialog-titlebar-close").text('');
        $("#email_box").append(theContent).fadeIn("slow");
        $('.ui-dialog-titlebar a').click(function() {
            $('.fullhomepage > object').show(); $("#harrods_experience").show();
        });
    }
}
h.prototype.accordion = function() {
    $('.accordion dt').live("click", function() {
        if ($(this).next('dd').is(':hidden')) {
            $(this).addClass('active');
            $(this).next('dd').slideDown('fast');
        } else {
            $(this).removeClass('active');
            $(this).next('dd').slideUp('fast');
        };
    });
    if ($('.to_tabs').length > 0) { $('.to_tabs').tabs(); };
}
h.prototype.leftNavOpenClose = function() {
    var _self = this;
    if ($(".sub_left_nav > li > dl").length > 0) {
        $(".sub_left_nav > li > dl > dt.selected").addClass("open_dt");
        $(".sub_left_nav > li > dl > dt.selected").next("dd").show();

        $(".sub_left_nav > li > dl").find("dt").click(function() {
            $(this).next("dd").slideToggle("slow");
            $(this).toggleClass("open_dt");
        });
    };
}
h.prototype.collectionThumbs = function(){
    $(".itemImg > a.zoom").hover(
        function(){
            $(this).css("cursor", "pointer"); 
            var this_src = $(this).children("img").attr("src");
            this_src = this_src.substring(0,this_src.indexOf("?"));
            this_src +="?wid=245&hei=245&fmt=jpeg&qlt=100,0&op_sharpen=1&resMode=sharp2&op_usm=1.0,0.25,0,0&iccEmbed=0";
            var this_alt = $(this).children("img").attr("alt");
            var big_thumb = "<img class='big_thumb' src='"+this_src+"' alt='"+this_alt+"' />";
            $(this).parent("div.itemImg").append(big_thumb);
            $(".big_thumb").hide().css("border", "1px solid #e0e0e0").fadeIn("slow");
        }, function(){
            $(".big_thumb").fadeOut("slow").remove();
        }
     ); 
}
h.prototype.altImages = function() {
    var _self = this;
    $(".prod_thumb > li").eq(0).children("a").children("img").addClass("image_on1");
    $(".prod_thumb > li > a > img").hover(
        function() {
            if ($(this).hasClass("image_on1")){ } else { $(this).removeClass("image_off").addClass("image_on"); }
        }, function() {
            if ($(this).hasClass("image_on1")){ } else { $(this).removeClass("image_on").addClass("image_off"); }
        });
    $(".prod_thumb > li > a > img").click(function() {
            var new_src = $(this).parent("a").attr("href");
        if ($("#product_hamper_landscape").length > 0) {
            var new_big_src = new_src.replace(/(\$productdetail_hamper_landscape\$)/g, "$productdetail_hamper_landscape_zoom$");
        } else if ($("#product_hamper_portrait").length > 0) {
        var new_big_src = new_src.replace(/(\$productdetail_hamper_portrait\$)/g, "$productdetail_hamper_portrait_zoom$");
        } else {
            var new_big_src = new_src.replace(/(\$productdetail_main_new\$)/g, "$productdetail_zoom_new$");
        }
        $(".main_prod_img_wrap > a > img").hide();
        $(".main_prod_img_wrap > a > img").attr("src", new_src);
        $(".main_prod_img_wrap > a").attr("href", new_big_src);
        $(".main_prod_img_wrap > a > img").fadeIn("slow");
        $(".mojomagnify_zoom").parent('div').remove();
        var theImage = $(".main_prod_img > img");
        MojoMagnify.init(theImage);
        $(this).parent("a").parent("li").siblings("li").children("a").children("img").removeClass("image_on1").addClass("image_off");
        $(this).removeClass("image_off").addClass("image_on1");
        return false;
    })
}
h.prototype.searchValidation = function() {
    var searchBt = $("#search_go");
    var searchErr = "<span class='search_msg'>Please enter a Keyword or Product Code</span>";
    $("#search_field").focus(function() {
        $(this).val("");
        $(this).addClass("focus_on");
        if ($(".search_msg").length > 0) {
            $(".search_msg").remove();
        }
    })
    $("#search_field").blur(function() {
        if ($(this).val() == '') {
            $(this).val("Keyword or Product Code");
            $(this).removeClass("focus_on");
        }
        if ($(".search_msg").length > 0) {
            $(".search_msg").remove();
        }
    })
    function trim(str, chars) {
        return ltrim(rtrim(str, chars), chars);
    }
    function ltrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }
    function rtrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }

    function replaceSpecialChar(str) {
        var cleanStr = "";
        cleanStr = str.replace("%", "");
        cleanStr = cleanStr.replace("&", "+");
        cleanStr = cleanStr.replace(" ", "+");
        return cleanStr;
    }
    searchBt.click(function() {
        var url = "/HarrodsStore/find/k/";
        var keyWord = trim(document.getElementById("search_field").value, " ");
        if ((keyWord == "") || (keyWord == "Keyword or Product Code")) {
            if ($(".search_msg").length > 0) {
                return false;
            } else {
                $("#search_field").css("border", "1px solid red");
                setTimeout(function() {$("#search_field").css("border", "1px solid #ccc");}, 700)
                return false;
            }
        }
        keyWord = replaceSpecialChar(keyWord);
        var searchText = "";
        if (keyWord.length > 4) {
            var IsInt = parseInt(keyWord, 10);
            if (IsInt) {
                searchText = url + padLeft(keyWord, "0", 18);
            }
        }
        if (searchText == "") {
            searchText = url + keyWord;
        }
        if ((keyWord != "") && (keyWord != "Keyword or Product Code")) {
            window.location.href = searchText;
        }
    })

    function padLeft(str, pad, count) {
        while (str.length < count)
            str = pad + str;
        return str;
    }
    function check(e) {
        var code;
        if (!e) var e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        if (code == 13) {
            return true;
        }
        return false;
    }
    $("#search_field").keypress(function(event) {
        if (check(event)) {
            searchBt.click();
        }
    })
}
h.prototype.newsLetterValidation = function() {
    var _self = this;
    $(".footer_search_field").focus(function() {
        $(this).val("");
        $(this).addClass("focus_on");
    })
    $(".footer_search_field").blur(function() {
        if ($(this).val() == '') {
            $(this).val("Enter email address");
            $(this).removeClass("focus_on");
        };
    })
    $("#SignUp_field").keypress(function(e) {
        if (e.which == 13) {
            news_click($(this).attr("id"));
        }
    })
    $("#SignUp_go").click(function(e) {
        news_click("SignUp_field");
    })
    function news_click(id) {
        var news_success = '<p class="success1">You\'ve successfully subscribed to the harrods.com e-newsletter.</p><p class="success_copy clearfix"><strong>Harrods catalogues</strong> Offer another great way to shop the best of our collections from home. Simply complete our quick sign-up form below to receive upcoming catalogues.<br /><a href="/HarrodsStore/user/request-catalogue?email=yes">Sign me up</a></p><p class="return_to_shop"><a href="/HarrodsStore/default.aspx?email=yes">Return to shop</a></p>';
        var news_error = '<p>We were not able to add your email address to our mailing list, please try with a different email address.</p>';
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var field_val = $("#" + id).val();
        if (!emailReg.test(field_val)) {
            hasError = true;
        }
        if (field_val == '' || field_val == 'enter email address' || hasError == true) {
            $("#news_letter_dialog").text("");
            $("#harrods_experience").hide();
            $('.fullhomepage > object').hide();
            $("#news_letter_dialog").dialog({
                width: 395,
                height: 140,
                title: "SORRY",
                modal: true,
                buttons: {
                    "Try again": function() { $('.fullhomepage > object').show(); $(this).dialog("close"); $("#harrods_experience").show(); }
                },
                overlay: {
                    opacity: 0.9,
                    background: "#000000"
                }
            }).fadeIn("slow");
            $(".ui-dialog-titlebar-close").text('');
            $("#news_letter_dialog").append(news_error).fadeIn("slow");
            return false;
        } else {
            $.ajax({
                type: "POST",
                url: "/harrodsstore/Services/UserProfiles.asmx/SubScribeNewsLetter",
                data: "{'emailAddress':'" + field_val + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    if (msg) {
                        $("#news_letter_dialog").text("");
                        $("#harrods_experience").hide();
                        $('.fullhomepage > object').hide();
                        $("#news_letter_dialog").dialog({
                            width: 395,
                            height: 280,
                            title: "THANKS!",
                            modal: true,
                            overlay: {
                                opacity: 0.9,
                                background: "#000000"
                            }
                        }).fadeIn("slow");
                        $(".ui-dialog-titlebar-close").text('');
                        $("#news_letter_dialog").append(news_success).fadeIn("slow");


                    } else {
                        $("#news_letter_dialog").text("");
                        $("#news_letter_dialog").dialog({
                            width: 395,
                            height: 140,
                            title: "SORRY",
                            modal: true,
                            buttons: {
                                "Try again": function() { $('.fullhomepage > object').show(); $(this).dialog("close"); $("#harrods_experience").show(); }
                            },
                            overlay: {
                                opacity: 0.9,
                                background: "#000000"
                            }
                        }).fadeIn("slow");
                        $(".ui-dialog-titlebar-close").text('');
                        $("#news_letter_dialog").append(news_error).fadeIn("slow");
                    }
                }
            });
        }
    }
}
h.prototype.fadeProdList = function(){
    setTimeout('$("div.inner > a > img").fadeIn()',300);
}
h.prototype.makeModal = function(el, modalWidth, modalHeight, type, ifId){
    var _self = this;
    var el = el;
    var modalWidth =  modalWidth;
    var modalHeight =  modalHeight;
    var type = type;
    var ifId = ifId;
    if($(".product_image > div > a > img" )[0] != undefined){
        var enlarged_src = $(".product_image > div > a > img").attr("src").replace(/(\$productDetailMain\$)/g, "wid=680&hei=680&fmt=jpeg&qlt=100,0&op_sharpen=1&resMode=sharp2&op_usm=1.0,0.25,0,0&iccEmbed=0");
    }
    el.click(function(){
        $("#email_box > iframe").remove();
        $("#email_box > .enlarge_img_c").remove();
        $("#email_box > .emailPrefForm_in").remove(); 

        var the_title = $(this).attr("title"); 
        var iframe_url = $(this).attr("href");
        var email_iframe = "<iframe frameborder='0' id='"+ifId+"' src='"+iframe_url+"'></iframe>";
        var the_enlarge_img = "<div class='enlarge_img_c'><img src='"+enlarged_src+"'alt='"+the_title+"' /></div>"; 
    
        $("#email_box").dialog({ 
            width: modalWidth,
            height: modalHeight,
            title: the_title,
            modal: true,
            overlay: { 
                opacity: 0.5, 
                background: "#ffffff" 
                     } 
        }).fadeIn("slow");
        $(".ui-dialog-titlebar-close > span").text('');
        if(type == 1){$("#email_box").append(email_iframe).fadeIn("slow");}else{$("#email_box").append(the_enlarge_img).fadeIn("slow");} 
        
        return false;
    })
}
h.prototype.getQueryVariable = function(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
}
$(document).ready(
    function() {
        myHarrods = new Harrods();
        myHarrods.init();
    }
);