﻿// mobile
//if (navigator.userAgent.indexOf('iPhone') != -1) {
//    addEventListener("load", function () {
//        setTimeout(hideURLbar, 0);
//    }, false);
//}

//function hideURLbar() {
//  //  window.scrollTo(0, 1);
//}
jQuery.fn.limitMaxlength = function (options) {

    var settings = jQuery.extend({
        //attribute: "maxlength",
        maxlength: 255,
        onLimit: function () { },
        onEdit: function () { }
    }, options);

    var onEdit = function () {
        var textarea = jQuery(this);
        var maxlength = parseInt(settings.maxlength);

        if (textarea.val().length > maxlength) {
            textarea.val(textarea.val().substr(0, maxlength));
            jQuery.proxy(settings.onLimit, this)();
        }
        jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
    }
    this.each(onEdit);
    return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
};

function AjaxLoginFacebook(pc, pl) {

    $.ajax({
        type: "POST",
        url: "/ajax/UtilsAjax.aspx",
        // dataType: 'json',
        data: {
            task: 'facebookconnect',
            c: pc,
            l: pl
        },
        success: function (data) {
            var obj = $.parseJSON(data);

            if (obj['success'] == 1) {
                window.location.reload();
            }
            else {

            }
        }

    });

}

function MobileScrollToContent() {
    if (document.getElementById('header') != null && document.getElementById('main_menu') != null) {
        if (document.getElementById('leftzone') != null) {
            scrollTo(0, document.getElementById('header').scrollHeight + document.getElementById('main_menu').scrollHeight + document.getElementById('leftzone').scrollHeight)
        } else {
            scrollTo(0, document.getElementById('header').scrollHeight + document.getElementById('main_menu').scrollHeight)
        }
    }
}

//*//

$(document).ready(function () {
    //  $('.required').each(function (index) {
    //   if ($('label[for="' + $(this).attr('id') + '"]').match("*$") != "*")
    //        $('label[for="' + $(this).attr('id') + '"]').append('&nbsp;*');
    // else
    //     ;
    //});

    $("a.tooltip[title]").tooltip(
			{
			    showURL: false,
			    track: true,
			    top: 10,
			    left: 5,
			    showBody: ": "
			}
		);

});

jQuery.fn.center = function () {

    return this.each(function () {
        var element = jQuery(this), win = jQuery(window);
        centerElement();
        jQuery(window).bind('resize', function () {
            centerElement();
        });


        function centerElement() {
            var elementWidth, elementHeight, windowWidth, windowHeight, X2, Y2;
            elementWidth = element.outerWidth();
            elementHeight = element.outerHeight();
            windowWidth = win.width();
            windowHeight = win.height();
            X2 = (windowWidth / 2 - elementWidth / 2) + "px";
            Y2 = (windowHeight / 2 - elementHeight / 2) + "px";
            jQuery(element).css({
                'left': X2,
                'top': Y2,
                'position': 'fixed'
            });
        } //centerElement function
    });
}


/*
jQuery.fn.center = function () {
this.css("position", "absolute");
this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");

return this;
}
*/
/****************************************************************************/
//                          skin dropdownlist
/****************************************************************************/
$(document).ready(function () {
    // select element styling
    $('select.customdropdown').each(function () {
        var title = $(this).attr('title');
        if ($('option:selected', this).val() != '') title = $('option:selected', this).text();
        $(this)
					.css({ 'z-index': 10, 'opacity': 0, '-khtml-appearance': 'none' })
					.after('<span class="customdropdown">' + title + '</span>')
					.change(function () {
					    val = $('option:selected', this).text();
					    $(this).next().text(val);
					})
    });

});

/****************************************************************************/

/********************** Auto Hide Mobile Top Nav ****************************/

$(document).ready(function () {
    if ($('.mobile #homeWrapper').length) {
        $('.mobile #megadd').css('display', 'block');
    }
});

/****************************************************************************/

/********************** MEGA DROP DOWN *************************************/


var constMaxSiteWidth = 0;

function MegaDDMouseIn(elem) {
    var dropDownDiv = $(this).find('div');
    dropDownDiv.stop().fadeTo(100, .97).show();

    if (dropDownDiv.length > 0) {
        if (/_done123456$/.test($(this).find('div').attr("id")) == false) {

            var marginLeftRight = parseInt($(this).find('div').css("padding-left")) + parseInt($(this).find('div').css("padding-right"));

            var widthDrop = ($(this).find('div>ul').outerWidth(true) * $(this).find('div>ul').length) + marginLeftRight;


            if (widthDrop > constMaxSiteWidth)
                widthDrop = constMaxSiteWidth - marginLeftRight;

            dropDownDiv.css('width', widthDrop);

            var headerOffsetRight = ($('#header').offset().left + constMaxSiteWidth);


            var elemOffsetRight = ($(this).offset().left + $(this).find('div').outerWidth(true));

            if (elemOffsetRight > headerOffsetRight) {
                var move = elemOffsetRight - headerOffsetRight;
                dropDownDiv.css('left', -move);
            }

            $(this).find('div').attr("id", $(this).find('div').attr("id") + "_done123456");

        }


    }
}
function MegaDDMouseOut(elem) {
    $(this).find("div").stop().fadeTo(100, 0, function () {
        $(this).hide();
    });
}

function GenerateTopMenu() {

    constMaxSiteWidth = $('#header').width();

    $("div#megadd>ul>li").hover(MegaDDMouseIn, MegaDDMouseOut);
    $("div#megadd>ul>li>div").css({ opacity: 0 });

    $("div#megadd>ul>li[subid]").each(
                    function (index) {
                        var subid = $(this).attr("subid");

                        var wrapUl = !$("#" + subid).children(":first-child").is("ul");
                        var wrapLi = !$("#" + subid).children(":first-child").children(":first-child").is("li");

                        if (wrapLi == true)
                            $("#" + subid).children(":first-child").wrap("<li />");
                        if (wrapUl == true)
                            $("#" + subid).children(":first-child").wrap("<ul />");

                        $(this).append($("#" + subid));
                    });

    var liWidth = 0;
    var visibleWidth = 0;

    $("div#megadd>ul>li").each(function () {
        if (constMaxSiteWidth < (liWidth + $(this).outerWidth(true))) {
            $(this).css('display', 'none');
        }
        else {
            visibleWidth += $(this).outerWidth(true) - 10;
            //   console.log($(this).innerWidth() );
        }
        liWidth += $(this).outerWidth(true);
    });

    //  alert(visibleWidth);
    if (visibleWidth < constMaxSiteWidth) {

        //alert(visibleWidth);

        var pad = ((((constMaxSiteWidth - visibleWidth) / $("div#megadd>ul>li:visible").length)) / 2);
        var padFloor = Math.floor(pad);
        var padRest = (pad - padFloor) * $("div#megadd>ul>li:visible").length * 2;
        //alert("padRest:" + padFloor + Math.floor(padRest));

        $("div#megadd>ul>li>a").css("padding-left", padFloor).css("padding-right", padFloor);
        //var orig = (pad * $("div#megadd>ul>li:visible").length * 2) - ( visibleWidth);
        var lastElem = padFloor + Math.floor(padRest) - 2;
        //  alert(lastElem);
        $("div#megadd>ul>li:visible:last>a").css("padding-right", lastElem);
        //$("div#megadd>ul>li:visible:last>a").css("padding-left", pad - 1);
    }


    $("div#megadd").css("visibility", "visible");

}


/********************************************************************/

/* ************************************* BAG MANAGMENT  **************************************/


var _timeout;
function ShowPopupAddToBag() {

    $("#popupAddToBag").fadeIn("fast");
    $("#popupAddToBag").width($("#popupAddToBag #link1AddToBag").outerWidth(true) + $("#popupAddToBag #link2AddToBag").outerWidth(true) + 40);
    $("#popupAddToBag").center();
    clearTimeout(_timeout);
    _timeout = setTimeout('HidePopupAddToBag()', 4000);
    return false;
}

function HidePopupAddToBag() {
    $("#popupAddToBag").fadeOut("fast");
}

function addToBagV2(sku, id, qty, idCountry, idLang, gotobag, showpopup) {

    createCookie('ecomBag' + idCountry + '_' + sku, qty + '^1^p^' + id, 30);
    if (gotobag == true) {
        document.location.href = '/ecomBag.aspx?c=' + idCountry + '&l=' + idLang;
    }
    if (showpopup == true) {
        ShowPopupAddToBag();
    }

    updateEcombagTotalProducts();

    return false;
}



function updateEcombagTotalProducts() {
    var country = $("#spEcombagTotalProducts").attr("country");
    var total = 0;
    if (country != undefined) {
        var cookName = 'ecomBag' + country + '_';
        var cookContent = document.cookie, cookEnd, i, j;

        for (i = 0, c = cookContent.length; i < c; i++) {
            j = i + cookName.length;

            if (cookContent.substring(i, j) == cookName) {
                cookEnd = cookContent.indexOf(";", j);
                if (cookEnd == -1) {
                    cookEnd = cookContent.length;
                }
                var skuContent = cookContent.substring(j, cookEnd).split('=');
                if (skuContent.length == 2) {
                    var ContentTab = skuContent[1].split('^');
                    if (ContentTab.length > 0)
                        total += new Number(ContentTab[0]);
                }

            }

        }
    }
    $("#spEcombagTotalProducts").html(total);
}

$(document).ready(function () {
    updateEcombagTotalProducts();
});
/*
function addToBag(sku, price, id) {
if (arguments.length == 3) {
//sku,price,id
createCookie('ecomBag19_' + arguments[0], '1^1^p^' + arguments[2], 30);
} else {
//sku,price,id,qty
createCookie('ecomBag19_' + arguments[0], arguments[3] + '^1^p^' + arguments[2], 30);
}
document.location.href = '/ecomBag.aspx?c=19&l=1';
}*/
/********************************************************************/

/************************************** COOKIES *************************************/
function createCookieMinutes(name, value, minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime() + (minutes * 60 * 1000));
        var expires = '; expires=' + date.toGMTString();
    }
    else var expires = '';
    document.cookie = name + '=' + value + expires + '; path=/';
}

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=/';
}


function WriteCookie(name, value, expdate) {
    var argv = WriteCookie.arguments;
    var argc = WriteCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;

    var date = new Date();
    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
    expires = 1;

    if (expdate != null) date = expdate;
    document.cookie = name + "=" + escape(value) +
    ((expires == null) ? "" : ("; expires=" + date.toUTCString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

function ReadCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function DeleteCookie(name) {
    date = new Date;
    date.setFullYear(date.getFullYear() - 1);
    WriteCookie(name, 'ko', date);
}

function eraseCookie(name) {
    createCookie(name, "", -1);
    document.location.href = document.location.href;
}

function eraseCookieNoRefresh(name) {
    createCookie(name, "", -1);
}



/********************************************************************/

/* ********************************** POP UP LOADING **************************************/


function showLoading() {
    // var showDiv = function () {
    $("#popupLoading").center();
    $("#popupLoading").fadeIn("fast");
    //}
    //setTimeout(showDiv, 50);
}
function showLoadingWithMask() {
    $("#globalMask").css({ "opacity": "0.5" }).fadeIn("fast");
    showLoading();
}

function hideLoading() {
    $("#globalMask").fadeOut("fast");
    $("#popupLoading").fadeOut("fast");
    //  $('#popupLoading').removeClass('fixed');
}

/********************************************************************/

/********************** SEARCH ***************************/
function goSearchpage(defaultValue, c, l) {
    if (document.getElementById('searchfield').value.length > 0 && document.getElementById('searchfield').value != defaultValue) {
        location.href = "/Search.aspx?search='" + encodeURI(document.getElementById('searchfield').value) + "'&c=" + c + "&l=" + l;
    }
}
function searchPress(e, defaultValue, c, l) {
    if (e.keyCode == 13)
        goSearchpage(defaultValue, c, l);
}

function disableEnterKey(e) {
    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox
    return (key != 13);
}

/**************************************************************************/

/********************** FROM FO.js ***************************/

function ChangeUrl() {
    location.href = document.forms[0].ListeUrl.options[document.forms[0].ListeUrl.selectedIndex].value;
}


function changeSecTab(tab) {
    document.getElementById('divSecType').style.display = 'none';
    document.getElementById('divSecRange').style.display = 'none';
    document.getElementById(tab).style.display = 'block';
    //TODO : write cookie : active TAB
}

/**************************************************************************/
function TextAreaCheckLength(txtArea, limit, spanToRefresh) {

    var realLength = txtArea.val().length;
    var length = txtArea.val().replace(/\r/ig, "").length;

    if (length > limit) {
        var tail = length - limit;
        //length = 500;
        txtArea.val(txtArea.val().substring(0, realLength - tail));
    }
    spanToRefresh.html(limit - length);
}

function formatPrice(culture, total, ctrl) {
    $.ajax({
        type: "POST",
        url: "/ajax/ecombag_ajax.aspx",
        data: "task=formatprice&price=" + total + "&culture=" + culture,
        success: function (msg) {
            ctrl.html(msg);
        }
    });
}

function ManageReadMoreButton(readmorelink, elemContent, elemExpand) {
    var originalSize = elemExpand.height();

    if (elemContent.outerHeight(true) >= (elemExpand.height() + readmorelink.height() + 5)) {
        readmorelink.fadeIn(400);
        readmorelink.click(function (e) {
            e.preventDefault();
            if (ReadMoreButtonAnimate(elemExpand, elemContent, originalSize, readmorelink) == true) {
                //   $("#fadeimg").fadeOut(400);
                $("#fadeimg").hide();
            }
            else {
                //$("#fadeimg").fadeIn(400);
                $("#fadeimg").show();
            }
            /*
            $("#imgBLUp").fadeOut(400);
            $("#imgBLDown").fadeIn(400);
            */
        });
    }
    else {
        readmorelink.hide();
        $("#fadeimg").hide();
        elemExpand.height(elemExpand.height() + readmorelink.height());
    }
}

function ReadMoreButtonAnimate(fromElem, totalElem, originalHeight, readmorelink) {

    if (fromElem.height() > originalHeight) {

        readmorelink.find(".imgBLDown").fadeIn(400);
        readmorelink.find(".imgBLUp").fadeOut(400);

        fromElem.animate({ height: originalHeight }, 400, function () {
            //imgElem.attr("src", "/img/OCC/new/moreBTN.png");

        });
        return false;

    }
    else {
        readmorelink.find(".imgBLUp").fadeIn(400);
        readmorelink.find(".imgBLDown").fadeOut(400);

        fromElem.animate({ height: totalElem.css("height") }, 400, function () {
            //imgElem.attr("src", "/img/OCC/new/lessBTN.png");

        });
        return true;
    }
}


function ReadMoreButton(elemDisplay, readmorelink) {
    if (elemDisplay.is(":hidden")) {
        readmorelink.find(".imgBLUp").fadeIn(400);
        readmorelink.find(".imgBLDown").fadeOut(400);

        elemDisplay.slideDown(700, "linear", function () {
            //    imgButton.attr("src", "/img/OCC/new/lessBTN.png");

        });

    }
    else {
        readmorelink.find(".imgBLDown").fadeIn(400);
        readmorelink.find(".imgBLUp").fadeOut(400);

        elemDisplay.slideUp(600, "linear", function () {
            //  imgButton.attr("src", "/img/OCC/new/moreBTN.png");

        });

    }
}


/******************************************************************************/

/*********************        VALIDATION                      **************************/

$(document).ready(function () {
    $("#aspnetForm").validate({
        onsubmit: false
        , errorClass: 'validationerror'
        , validClass: 'validationvalid'
    });

    $('.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();
}



/************************************************************************/

/*********************       EQUALIZE                    ***********************/
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();
});

/*-------------------------------------------------------------------- */
/********************** MENU LEFT BEGIN *********************************/

function GenerateMenuleft() {
    // if ($("#menuleft").height() > $(window).height() - 160 && $("#menuleft ul").length > 1) {
    var isSub = $("#menuleft ul>li:nth-child(2)").length;
    if ($("#menuleft ul").length > 5 || $("#menuleft ul").length == 0 || isSub == 0) {

        var ulTopVisible = $("#menuleft .selected").parent();
        var ulTopVisibleChildsLength = ulTopVisible.find("li:nth-child(2)").length;

        if ($("#superCatName").length > 0) {
            var newul = "<ul>" + $("#superCatName").html();
            $("#menuleft ul li:first-child").each(function (index, Element) {

                if (ulTopVisibleChildsLength == 0 && $(this).hasClass("selected"))
                    newul += "<li class='selected'>" + $(this).html() + "</li>";
                else
                    newul += "<li>" + $(this).html() + "</li>";
            })

            newul += "</ul>";

            if (ulTopVisibleChildsLength == 0)
                $("#menuleft ul").detach();
            else
                $("#menuleft ul").not(ulTopVisible).detach();

            $("#menuleft").append(newul);

            if (ulTopVisible.length == 0) {
                $("#menuleft ul>li:first-child").addClass("selected");
            }

            $("#superCatName").detach();
        }

    }

    $("#menuleft ul>li:first-child").addClass("title");
    $("#menuleft").css("visibility", "visible");
}


/********************** MENU LEFT END *********************************/

/********************** BOTTOM LAYER BEGIN *********************************/

var BottomLayerBreak = 0;
var currentBottomLayerDisplayed = 0;
var BottomLayerPosition = 0;

var BottomLayertotalHeight = 20;
var BottomLayerIntervalIdentifier;
var BottomLayerHeightEachItemTab = new Array();

function BottomLayerMove() {
    if (BottomLayerPosition == 0) {
        if (BottomLayerHeightEachItemTab[currentBottomLayerDisplayed] > 20) {
            StopRotationBottomLayer();

            $("#BottomLayer .imgBLUp").fadeOut(400);
            $("#BottomLayer .imgBLDown").fadeIn(400);

            BottomLayerBreak = 1;

            $("#BottomLayer").animate({ height: BottomLayerHeightEachItemTab[currentBottomLayerDisplayed] }, 400, function () {
                BottomLayerPosition = 1;
            });
        }
    }
    else {

        $("#BottomLayer .imgBLUp").fadeIn(400);
        $("#BottomLayer .imgBLDown").fadeOut(400);


        $("#BottomLayer").animate({ height: 25 }, 400, function () {
            BottomLayerPosition = 0;
            BottomLayerBreak = 0;

            LaunchRotationBottomLayer();
        });
    }
}

function BottomLayerUpFixed() {
    if (currentBottomLayerDisplayed != 0) {
        $("#bottomLayerElem_" + currentBottomLayerDisplayed).insertBefore($("#bottomLayerElem_0"));
    }
    $("#ContentBottomLayer>div").css("position", "static").css("display", "");
}

function BottomLayerClose() {
    $("#BottomLayer").animate({ height: 0 }, 400);
    createCookieMinutes('hidebottomlayer', '1', 5);
}


function BottomLayerShowNext() {
    if (BottomLayerBreak == 0 && $("#bottomLayerElem_1").length > 0) {
        var nextBottomLayerDisplayed = currentBottomLayerDisplayed + 1;
        if ($("#bottomLayerElem_" + nextBottomLayerDisplayed).length == 0)
            nextBottomLayerDisplayed = 0;


        $("#bottomLayerElem_" + currentBottomLayerDisplayed).fadeOut(200, function () { $("#bottomLayerElem_" + nextBottomLayerDisplayed).fadeIn(400); });

        currentBottomLayerDisplayed = nextBottomLayerDisplayed;
        if (BottomLayerHeightEachItemTab[currentBottomLayerDisplayed] > 20) {
            $("#linkUpBottomLayer").fadeIn(400);
        }
        else {
            $("#linkUpBottomLayer").fadeOut(400);
        }
    }
}

function LaunchRotationBottomLayer() {
    BottomLayerIntervalIdentifier = setInterval(BottomLayerShowNext, 5000);
}

function StopRotationBottomLayer() {
    clearInterval(BottomLayerIntervalIdentifier);
}

function InitBottomLayer() {
    //  $("#linkUpBottomLayer").hide();
    $(".main_content").css("margin-bottom", "40px");

    BottomLayertotalHeight = 0;
    var ContentBottomLayerCount = 0;

    $("#ContentBottomLayer>div").each(function (i, item) {
        BottomLayerHeightEachItemTab.push($(item).outerHeight(true));
        ContentBottomLayerCount++;
    });

    $("#BottomLayerCennterContent").height(BottomLayertotalHeight);

    if (BottomLayerHeightEachItemTab[currentBottomLayerDisplayed] > 20) {
        $("#linkUpBottomLayer").fadeIn(200);
    }
    if (ContentBottomLayerCount > 1) {
        LaunchRotationBottomLayer();
    }
}

$(document).ready(function () {
    $("#BottomLayer").waitForImages(function () {
        InitBottomLayer();
    });
});


/********************** BOTTOM LAYER END *********************************/



/********************** FAQ BEGIN ******************************************/

$(document).ready(function () {
    if ($(".FAQQuestion").length > 0 && $(".FAQAnswer").length > 0) {
        $(".FAQQuestion").click(function () {

            $('.FAQAnswer').slideUp(350);

            if ($(this).next('.FAQAnswer').css('display') == 'none') {
                $(this).next().slideDown(350);
            }
            return false;
        });
    }
});

/********************** FAQ END ******************************************/

/********************** NEWSLETTER POPUP******************************************/


var CanHideNewsletterAuto = true;
var UrlNewsletterPopupPage = "";
var DefaultEmailValNewsletterPopup = "";
$(document).ready(function () {
    $("#NewsletterPopupEmail").focus(function (event) {
        if (CanHideNewsletterAuto == true) {
            $("#NewsletterPopupEmail").val("");
        }
        CanHideNewsletterAuto = false;
    });
    $("#NewsletterPopupValid").click(function (event) {
        CanHideNewsletterAuto = false;
        if (GetDefaultValidationResult($("#NewsletterPopup"))) {
            event.preventDefault();
            HideNewsletterPopup(false);
            document.location.href = UrlNewsletterPopupPage + $("#NewsletterPopupEmail").val();
        }
        else
            event.preventDefault();
    });
});

function ShowNewsletterPopup(url) {

    if (url != "" && $.cookie('NewsletterPopupCookie') == null) {
        UrlNewsletterPopupPage = url;
        $("#globalMask").css({ "opacity": "0.5" }).show();
        $("#NewsletterPopup").center().show();
        setTimeout("HideNewsletterPopupAuto()", 35000);
    }
}

function HideNewsletterPopupAuto() {
    if (CanHideNewsletterAuto == true)
        HideNewsletterPopup(true);
}

function HideNewsletterPopup(auto) {
    $("#globalMask").css({ "opacity": "0" }).hide();
    $("#NewsletterPopup").hide();
    if (auto == false)
        $.cookie('NewsletterPopupCookie', 'true', { expires: 30 });
}
/********************** NEWSLETTER POPUP END ******************************************/


function BrazilIsStateZipCodeValid(zip, state) {
    var allArray = new Array();
    allArray["AC"] = "6";
    allArray["AL"] = "5";
    allArray["AP"] = "6";
    allArray["AM"] = "6";
    allArray["BA"] = "4";
    allArray["CE"] = "6";
    allArray["DF"] = "7";
    allArray["ES"] = "2";
    allArray["GO"] = "7";
    allArray["MA"] = "6";
    allArray["MT"] = "7";
    allArray["MS"] = "7";
    allArray["MG"] = "3";
    allArray["PA"] = "6";
    allArray["PB"] = "5";
    allArray["PR"] = "8";
    allArray["PE"] = "5";
    allArray["PI"] = "6";
    allArray["RJ"] = "2";
    allArray["RN"] = "5";
    allArray["RS"] = "9";
    allArray["RO"] = "7";
    allArray["RR"] = "6";
    allArray["SC"] = "8";


    allArray["SE"] = "4";
    allArray["TO"] = "7";

    if (state == "SP" && (zip == "1" || zip == "0")) {
        return true;
    }
    if (allArray[state] != undefined && allArray[state] == zip) {
        return true;
    }
    return false;
}


//post with data passed as params and redirect
//path : url to post to
//params is a JSON collection of key/value pair as follow : var parameter = {'key1','param1':'key2','value2':'key3','value3'}
function post_to_url(path, params, method) {
    //default method is post
    method = method || "post";

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for (var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form.submit();
}

//   ############################################################
//							Facebook Rules 
//   ############################################################

$(document).ready(function () {
    if (top != self && top.name == 'OrderWindow') {
        $('link[href*="OCMS.css"]').attr('href', '/css/OCC/mobile.css');
        $("#header").hide();
        $("#main_bottom").hide();
        $(".megaddsub").hide();
        $(".megaddSubElem").hide();

    }

    if (top != self && top.name != 'OrderWindow' && document.documentElement.clientWidth <= 760) {

        var cssObj = {
            'backgroundColor': '#FFF !important',
            'backgroundImage': 'none !important'
        }
        $("html").css(cssObj);

        // HomePage modification
        var homeLeftFb = $('a.homeLeftFacebookOffer');
        var homeRightFb = $('a.homeRightFacebookOffer');
        var homeLeftFbImg = $('img.homeLeftFacebookOffer');
        var homeRightFbImg = $('img.homeRightFacebookOffer');
        var mapFbRight = $('#homeRight map');
        var mapFbLeft = $('#homeLeft map');

        if (mapFbLeft.length > 0) {
            $("#homeWrapper").append(mapFbLeft);
        }
        if (mapFbRight.length > 0) {
            $("#homeWrapper").append(mapFbRight);
        }

        if (homeLeftFb.length > 0) {
            $("#homeLeft").replaceWith(homeLeftFb);
            homeLeftFb.wrap('<div id="homeLeft" />');
            homeLeftFb.show();
        }
        else if (homeLeftFbImg.length > 0) {
            $("#homeLeft").replaceWith(homeLeftFbImg);
            homeLeftFbImg.wrap('<div id="homeLeft" />');
            homeLeftFbImg.show();
        }
        if (homeRightFb.length > 0) {
            $("#homeRight").replaceWith(homeRightFb);
            homeRightFb.wrap('<div id="homeRight" />');
            homeRightFb.show();
        }
        else if (homeRightFbImg.length > 0) {
            $("#homeRight").replaceWith(homeRightFbImg);
            homeRightFbImg.wrap('<div id="homeRight" />');
            homeRightFbImg.show();
        }
        else {
            var alternateContent = $('#homeLeft object img');
            var alternateContentLink = $('#homeLeft object a');

            if (alternateContentLink.length > 0) {
                $('#homeLeft object').hide();
                $('#homeLeft').append(alternateContentLink);
            }
            else if (alternateContent.length > 0) {
                $('#homeLeft object').hide();
                $('#homeLeft').append(alternateContent);
            }

            var alternateRightContent = $('#homeRight object img');
            var alternateRightContentLink = $('#homeRight object a');

            if (alternateRightContentLink.length > 0) {
                $('#homeRight object').hide();
                $('#homeRight').append(alternateRightContentLink);
            }
            else if (alternateRightContent.length > 0) {
                $('#homeRight object').hide();
                $('#homeRight').append(alternateRightContent);
            }
        }

        setTimeout("GenerateTopMenu()", 300);

        FB.init({
            appId: '275368459143160',
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true, // parse XFBML
            oauth: true // enables OAuth 2.0
        });

        function resize() {
            if ($.browser.webkit) {
                FB.Canvas.setSize({ height: $(document.body).height() + 30 });
            } else {
                FB.Canvas.setSize({ height: document.body.scrollHeight + 30 });
            }
        }
        setTimeout(resize, 500);
        FB.Canvas.setAutoResize(true);
    }
});

function shareFbThumbnail(page) {
    window.open(page, 'Facebook', 'width=500, height=400');
};

