﻿//   ############################################################
//   
//                    Master Javascript Document
//   
//   ############################################################



//   ############################################################
//                Mega-Dropdown Sizing and Animation 
//   ############################################################

$(document).ready(function () {

    function MouseIn() {
        var dropDownDiv = $(this).find('div');
        // if a drop down menu exists ... 
        if (dropDownDiv.length > 0) {

            // set the width relative to the number of columns / lists of links
            if ($(this).find('div>ul>li>a').css('width').replace('px', '') > 0) {
                $(this).find('div').css({ 'width':
						$(this).find('div>ul>li>a').css('width').replace('px', '')
						* $(this).find('div>ul').length
                });
            }

            // calculate the widths and position of the dropdown
            var menuOffset = $(this).offset().left - $('.container').offset().left;
            var menuMove = dropDownDiv.outerWidth() + menuOffset - $('.container').width();

            // if the dropdown will overfow on the right side, then adjust its left position
            if (menuMove > 0)
                dropDownDiv.css({ 'left': -menuMove });

            dropDownDiv.stop().fadeTo(200, .95).show();
        }
    }

    function MouseOut() {
        //$(this).find("div").css({'display' : 'block'});
        //$(this).find("div").stop().fadeTo(6000, 0).hide();
        $(this).find("div").stop().fadeTo(250, 0, function () { //Fade to 0 opactiy
            $(this).hide();  //after fading, hide it
        });
    }

    $("div#topNav>ul>li").hover(MouseIn, MouseOut);
    $("div#topNav>ul>li>div").css({ opacity: 0 }); //Fade to 0 opacity to prepare for fading in
});


//   ############################################################
//                	Left Menu expand function
//   ############################################################


$(document).ready(function () {
    if ($(".sectionmenuleft").height() > $(window).height() - 160 && $(".sectionmenuleft ul").length > 1) {
        var ulTopVisible = $(".sectionmenuleft .selected").parent();

        if ($("#superCatName").html() != "") {
            var newul = "<ul>" + $("#superCatName").html();
            $(".sectionmenuleft ul li:first-child").each(function (index, Element) {
                newul += "<li>" + $(this).html() + "</li>";
            })

            newul += "</ul>";
            $(".sectionmenuleft ul").not(ulTopVisible).detach();
            $(".sectionmenuleft").append(newul);
        }
    }
    $(".sectionmenuleft ul>li:first-child").addClass("title");
});


//   ############################################################
//                			Category Video 
//   ############################################################

$().ready(function () {

    $('#jqWindow').jqm();

    /* $('#jqWindow').jqm({ajax:'@href'}); */

    $('a.showVideo').live('click', function () {
        $('#jqWindow').jqm({ overlay: 70 });
        $('#jqWindow').jqm({ toTop: true });
        $('#jqWindow').jqmShow();
    });

    if ($('#descriptionContent').height() < $('#description').height()) {
        $('#fadeimg').hide();
        $('#readmore').hide();
        $('#readless').hide();
    }
    else {
        $('#readmore').show();
        $('#readless').hide();

        $('#productLeftBottom').css("margin-top", "10px");
    }


    if (document.getElementById("productTop"))
    { var descheight = 125; }
    else
    { var descheight = 60; }

    $("#readmore").click(function (event) {
        ReadMoreButtonSlide($("#description"), $('#descriptionContent'), descheight);
    });
    $("#readless").click(function (event) {
        ReadMoreButtonSlide($("#description"), $('#descriptionContent'), descheight);
    });
});

// CategoryBanner Text Slide
function ReadMoreButtonSlide(fromElem, totalElem, originalHeight) {

    if (fromElem.height() < totalElem.height()) {
        $('#description').animate({ height: 10 + $('#descriptionContent').height() }, 500, function () {
            $('#readmore').hide();
            $('#readless').show();
            $('#fadeimg').hide();
        });
    }
    else {
        $('#fadeimg').show();
        $('#description').animate({ height: originalHeight }, 500, function () {
            $('#readless').hide();
            $('#readmore').show();
        });
    }
}


//   ############################################################
//                		Equalize height
//   ############################################################

function GlobalEqualizeElements() {
    $('[equalize]').each(function () {
        if (/_done123456$/.test($(this).attr("equalize")) == false) {


            var curEqualize = $(this).attr("equalize");
            var allCurEqualize = $('[equalize="' + curEqualize + '"]');
            if (allCurEqualize.length > 1) {
                var height = 0;
                var reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";
                var oldHeight = allCurEqualize.css("height");

                allCurEqualize.css("height", reset);

                allCurEqualize.each(function () {
                    height = Math.max(height, this.offsetHeight);
                });

                allCurEqualize.css("height", height);

                allCurEqualize.each(function () {
                    var h = this.offsetHeight;
                    if (h > height)
                        $(this).css("height", height - (h - height));
                });
            }
            allCurEqualize.attr("equalize", curEqualize + "_done123456");

        }
    });

    $(".equalizeDivGroup").each(function () {
        var height = 0;
        var reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";

        $(this).find(".equalizeDiv").css("height", reset);

        $(this).find(".equalizeDiv").each(function (i) {
            height = Math.max(height, this.offsetHeight);
        });

        $(this).find(".equalizeDiv").css("height", height);

        $(this).find(".equalizeDiv").each(function (i) {
            var h = this.offsetHeight;
            if (h > height)
                $(this).css("height", height - (h - height));
        });
    });
}

$(document).ready(function () {
    GlobalEqualizeElements();
});


//   ############################################################
//                		Cookie Functions
//   ############################################################

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = '; expires=' + date.toGMTString();
    }
    else var expires = '';
    document.cookie = name + '=' + value + expires + '; path=/;domain=loccitane.com';
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


//   ############################################################
//                		Mobile Scroll function
//   ############################################################

function MobileScrollToContent() {
    if (document.getElementById('headerContainer') != null && document.getElementById('topNav') != null) {
        if (document.getElementById('menuLeft') != null) {
            scrollTo(0, document.getElementById('breadcrumbsContainer').scrollHeight + document.getElementById('logo-container').scrollHeight + document.getElementById('headerContainer').scrollHeight + document.getElementById('topNav').scrollHeight + document.getElementById('menuLeft').scrollHeight)
        } else {
            scrollTo(0, document.getElementById('logo-container').scrollHeight + document.getElementById('headerContainer').scrollHeight + document.getElementById('topNav').scrollHeight)
        } if (document.getElementById('Product_Left') != null || document.getElementById('menuLeft') == null) {
            scrollTo(0, 1)
        }
    }
}


//   ############################################################
//							Form Validation
//   ############################################################

$(document).ready(function () {
    $("#aspnetForm").validate({
        onsubmit: false
        , errorClass: 'validationerror'
        , validClass: 'validationvalid'
		, errorPlacement: function (error, element) {
		    if (element.hasClass('accountNumber')
            || element.hasClass('bankCode')
            || element.hasClass('accountHolderName')
            || element.hasClass('accountHolderAddress')) {
		        error.appendTo(element.parent('td').next('td'));
		    }
		    else if (element.hasClass('zipCode')
		            || element.hasClass('city')) {
		        error.appendTo(element.parent('td').next('td'));
		    }
		    else {
		        error.appendTo(element.parent());
		    }
		}
    });

    $('.validationGroup .causesValidation').click(DefaultValidateGroup);

    $.extend($.validator.messages, {
        required: '<img src="/img/error-anim.gif"/>'
        , email: '<img src="/img/error-anim.gif"/>'
        , minlength: '<img src="/img/error-anim.gif"/>'
        , equalTo: '<img src="/img/error-anim.gif"/>'
        , number: '<img src="/img/error-anim.gif"/>'
        , digits: '<img src="/img/error-anim.gif"/>'
    });
});

function GetDefaultValidationResultWithoutHidden(elem) {
    var isValid = true;

    elem.find(':input').each(function (i, item) {
        if ($(item).is(":hidden") == false) {
            if (!$(item).valid())
                isValid = false;
        }
    });

    return isValid;
}

function GetDefaultValidationResult(elem) {
    var isValid = true;

    elem.find(':input').each(function (i, item) {
        if (!$(item).valid())
            isValid = false;
    });

    return isValid;
}

function DefaultValidateGroup(evt) {

    isValid = GetDefaultValidationResult($(this).parents('.validationGroup'));

    if (!isValid)
        evt.preventDefault();
    else
        showLoading();
}

function switchValidationMessageDisplay(isValid, message, id, validationControlClientID) {
    if (!isValid) {
        if ($('#' + id).length == 0) {
            $('<div id=' + id + '>' + message + '</div>').prependTo('#' + validationControlClientID);
        }
        $('#' + validationControlClientID).css('display', 'block');
    }
    else {
        if ($('#' + id).length == 1) {
            $('#' + id).remove();
        }
        if ($('#' + validationControlClientID).children().size() == 0) {
            $('#' + validationControlClientID).css('display', 'none');
        }
    }
}

//   ############################################################
//							Facebook Rules 
//   ############################################################

$(document).ready(function () {
    if (top != self && document.documentElement.clientWidth <= 760) {
        // back to top on product Page
        if ($('#productTop').length) {
            scrollTo(0, 1);
        }

        // fbCom - Coremetrics tags 
        //if (document.getElementById('en-US') != null) {
        //    $("body").append('<div id="fbCoremetricsTag"><img height= "1" width="1" border="0" alt="" src="http://data.cmcore.com/imp?tid=17&vn1=4.3.5&vn2=e4.0&ec=UTF-8&ci=90139823&cm_mmc=FBCommerce-_-Sales-_-Tab-_-iFrame" /></div>');
        //}
        //if (document.getElementById('en-GB') != null) {
        //    $("body").append('<div id="fbCoremetricsTag"><img height= "1" width="1" border="0" alt="" src="http://data.cmcore.com/imp?tid=17&vn1=4.3.5&vn2=e4.0&ec=UTF-8&ci=90145761&cm_mmc=FBCommerce-_-Sales-_-Tab-_-iFrame" /></div>');
        //}

        // fbCom - macOS and IE9 fix
        if ((navigator.userAgent.indexOf("Mac") != -1) || (navigator.userAgent.indexOf("MSIE 9.0") != -1)) {
            $('div#topNav>ul>li>a').css('padding', '0.55em');
        }

        // fbCom - HPOffer & resize
        if ((navigator.userAgent.indexOf("MSIE") == -1)) {
            var flashAltContent = $('#alternateContent').html();
            $('#homeHero object').replaceWith(flashAltContent);
        }
		
		if ($('#fbComOffer').length > 0)
		{
			var tempOfferHTML = $('#fbComOffer').html();
			$('#homeOffer').replaceWith(tempOfferHTML);
		}

        window.fbAsyncInit = function () {
            FB.init({
                appId: '262953687054879',    //(expFBAppId) ? expFBAppId :
                status: true, // check login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true // parse XFBML
            });


            //Make sure to automatically resize the iFrame
            //FB.Canvas.setAutoResize();
            //Make sure the iframe sizes to content
            var rz = setTimeout(resize, 500);
        };

        function resize() {
            if ($.browser.webkit) {
                FB.Canvas.setSize({ height: $(document.body).height() + 30 });
            } else {
                FB.Canvas.setSize({ height: document.body.scrollHeight + 30 });
            }
        }

        FB.Canvas.setAutoResize(true);
    }
});

//   ############################################################
//						    iFrame Detection
//   ############################################################

$(document).ready(function () {
    if (top != self && document.documentElement.clientWidth > 800) {
        window.open(location.href, '_top'); 
    }
});
