/*
--------------------------------------------------

Regis - Stylist
application.js

Joe Morrow [joe.morrow@acquitygroup.com]
7/10/2008

Copyright © 2008 Acquity Group LLC

--------------------------------------------------
*/

function errorMessage(messageText) {
    alert(messageText);
}


$(document).ready(function() {
    initializeAddressShowHide();
    initializeCCShowHide();

    var sleep = function(obj) {
        obj.w.show();
        var fader = ($.browser.msie) ? function() {obj.w.css("background-color", "#fff").fadeOut("slow", function() {obj.w.jqmHide();});} : function() {obj.w.fadeOut("slow", function() {obj.w.jqmHide();});};
        setTimeout(fader, 10000);
    };

    // setup for IE6-specific treatments
    if (($.browser.name == "ie") && (($.browser.versionNumber) <= 6)) {

        // png fix (for IE6 only)
        $.ifixpng("images/blank.gif");
        $("img[@src$=png], #footerContainer, #mainPreviewImage, #sidebarBilling, #sidebarShipping, #sidebarPayment").ifixpng();
        $(".promoModalContainer, .promoModalBottom").ifixpng();

        // ie6 doesn't seem to like jqm, so we take a different approach to
        // the home page popouts for ie6
        $("#homePromoTrigger1").mouseover(function () {
            $("#promoModal1").show();
            return false;
        });

        $("#homePromoTrigger2").mouseover(function () {
            $("#promoModal2").show();
            return false;
        });

        $(".promoModalContainer .jqmClose").click(function () {
            $(this).parent().parent().fadeOut();
            return false;
        });

        //checkout modals
        $("#saveCardModalTrigger").click(function () {
            $("#saveCardModal").show();
            $("#saveCardModal").bgiframe();
            return false;
        });

        $("#cnvModal1Trigger").click(function () {
            $("#cnvModal1").show();
            $("#cnvModal1").bgiframe();
            return false;
        });

        $("#cnvModal2Trigger").click(function () {
            $("#cnvModal2").show();
            $("#cnvModal2").bgiframe();
            return false;
        });

        $(".modalContainer .jqmClose").click(function () {
            $(this).parent().parent().fadeOut();
            return false;
        });

        //Error Pop Up Modal
        //ie 6 no fade
        $("div#errorContainer").jqm({
            modal: true,
            overlay: 50,
            toTop: true,
            closeClass: 'jqmErrorClose',
            nocache: true
        });


    } else {

        // load a mac-specific CSS to fix font size discrepancies between platforms
        if ($.os.name == "mac")
            $("link[@href*=mac.css]").attr("rel", "stylesheet");

        $("#homePromoTrigger1").mouseover(function() {
            $("#promoModal1").jqmShow();
        })

        $("#homePromoTrigger2").mouseover(function() {
            $("#promoModal2").jqmShow();
        })

        //Error Pop Up Modal
        //fade for other browsers
        $("div#errorContainer").jqm({
            modal: true,
            overlay: 50,
            toTop: true,
            closeClass: 'jqmErrorClose',
            onShow: sleep,
            nocache: true
        });

    }

    // load custom select fields
    //$("select").selectbox();



    // homepage promo modals -- the position is set dynamically based on the coordinates of the corresponding rects
    $(".promoModalContainer").each(function() {
        var thisID = $(this).attr("id");				//   The modal's ID
        var thisNum = thisID.charAt(thisID.length - 1);	//   The modal's number
        if ($("#homePromoMap #homePromoTrigger" + thisNum).attr("coords") != null) {
            var thisCoords = $("#homePromoMap #homePromoTrigger" + thisNum).attr("coords").split(",");

            // Different positioning math for downward-positioned version
            if ($(this).hasClass("down"))
            {
                $(this).css("margin-top", (thisCoords[3] - parseInt($(this).css("padding-top")) + 1) + "px");
            }
            else
            {
                // Special adjustment for ie6's temperamental positioning
                if (($.browser.name == "ie") && (($.browser.versionNumber) <= 6)) {
                    paddingOffset = parseInt($(this).css("padding-top")) - 13;
                }
                else
                {
                    paddingOffset = parseInt($(this).css("padding-top")) + 1;
                }

                $(this).css("margin-top", (thisCoords[3] - $(this).height() - paddingOffset) + "px");
            }

            $(this).css("margin-left", (thisCoords[2] - $(this).width() + 1) + "px");

            if (!(($.browser.name == "ie") && (($.browser.versionNumber) <= 6))) {
                $(this)
                    .jqm({
                        trigger: "#homePromoTrigger" + thisNum,
                        overlay: 0,
                        modal: false ,
                        onShow: function(h) {
                            h.w.fadeIn(600);
                        },
                        onHide: function(h) {
                            h.w.fadeOut(400);
                        }
                    });
            }
        }
    });

    $(".modalContainer").each(function() {

        var thisID = $(this).attr("id");				//   The modal's ID

        if (!(($.browser.name == "ie") && (($.browser.versionNumber) <= 6))) {
            $(this)
                .jqm({
                    trigger: "#" + thisID + "Trigger",
                    overlay: 0,
                    modal: false ,
                    onShow: function(h) {
                        var curleft = curtop = 0;
                        var obj = h.t;
                        // calculate offset because offset() does not seem to work with jquery.browser
                        if (obj.offsetParent) {
                            do {
                                curleft += obj.offsetLeft;
                                curtop += obj.offsetTop;
                            } while (obj = obj.offsetParent);
                        }
                        var modalTop = curtop - 50;
                        var modalLeft = curleft - 30;
                        if (modalTop > 0 && modalLeft > 0) {
                            h.w.css("top", modalTop + "px");
                            h.w.css("left", modalLeft + "px");
                        }
                        h.w.fadeIn(600);
                    },
                    onHide: function(h) {
                        h.w.fadeOut(400);
                    }
                });
        }

    });

    // homepage sliding quick order functions
    function slideSidebarQuickOrderOut() {
        $(".home #sidebarQuickOrder").animate({marginLeft: "207px"}, 500, "easeInCubic");
        $(".home #sidebarQuickOrderControl").html('<img src="/media/REG001/images/static/stylist/backgrounds/en/quickOrderControl-closed.png" alt="open quick order" />').unbind("click").bind("click", slideSidebarQuickOrderIn).show();
    }
    function slideSidebarQuickOrderIn() {
        $(".home #sidebarQuickOrder").animate({marginLeft: "0"}, 300, "easeOutCubic");
        $(".home #sidebarQuickOrderControl").html('<img src="/media/REG001/images/static/stylist/backgrounds/en/quickOrderControl-opened.png" alt="close quick order" />').unbind("click").bind("click", slideSidebarQuickOrderOut);
        if (($.browser.name == "ie") && (($.browser.versionNumber) <= 6))
            $("a#sidebarQuickOrderControl img").css({'float' : 'left'});
    }
    // initial preset
    setTimeout(slideSidebarQuickOrderOut, 1000);

    function initializeCCShowHide() {
        // set onclicks for check box
        $('.checkImage').click(function() {
            toggleSaveCC();
        });
        // run upon page load to determine initial state
        toggleSaveCC();
    }
    function toggleSaveCC() {
        if ($('input.saveCard:checkbox:checked').length > 0) {
            $('div.ccName').show();
        } else {
            $('div.ccName').hide();
        }
    }
    function initializeAddressShowHide() {
        // set onclicks for check box
        $('.saveThisAddress').click(function(){
            toggleSaveAddress();
    });
        // run upon page load to determine initial state
        toggleSaveAddress();
    }
    function toggleSaveAddress() {
        if ($('input.bill_save:checkbox:checked').length > 0) {
            $('div.baddressName').show();
        }
        else {
            $('div.baddressName').hide();
        }
        if ($('input.ship_save:checkbox:checked').length > 0) {
            $('div.saddressName').show();
        }
        else {
            $('div.saddressName').hide();
        }
    }

    //images on product detail page
    var defaultImg = $("#productPreviews #mainPreviewImage img").attr("src");
    $("#multiPreviewImages a").click(function() {
        var newImgSrc = $(this).attr("href");
        $("#productPreviews #mainPreviewImage img").attr("src", newImgSrc);
        $(this).unbind("mouseout");
        return false;
    });
    $("#multiPreviewImages a").mouseover(function() {
        var newImgSrc = $(this).attr("href");
        $("#productPreviews #mainPreviewImage img").attr("src", newImgSrc);
        $(this).mouseout(function() {
            $("#productPreviews #mainPreviewImage img").attr("src", defaultImg);
        });
    });

    $("div#errorContainer").jqmShow();
    $("div#errorContainer").bgiframe();

    // my account menu item - Change Currency
    $("#changeCurrency").click(function() {
        $("#currencyDialog").fadeIn();
    })

    $("#currencyDialog .dialogBody a").click(function() {
        $("#currencyDialog").fadeOut();
    })

});

if( typeof sIFR == "function" ) {
    sIFR.replaceElement( named( {sSelector:"h1.heading", sFlashSrc:"/media/REG001/fonts/stylist/itc-garamond-light-bold.swf", sColor: "#1C6491", sCase: "lower"} ) );
}

if( typeof sIFR == "function" ) {
    sIFR.replaceElement( named( {sSelector:".prodDetail #productPromoContainer .promoText", sFlashSrc:"/media/REG001/fonts/stylist/itc-garamond-book.swf", sColor: "#015183", sWmode: "transparent"} ) );
}

// Image Preloader
jQuery.preloadImages = function() {
    for (var i=0; i<arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

/* Shopping cart functions that handle Edit and Cancel actions */
function editCartLine(rowToEditID) {
    //cancel edit on currently edited cart line (if any)
    cancelEditCartLine();
    //edit the current cart line
    $("tr#" + rowToEditID).addClass("selected");
    $("tr#" + rowToEditID + " div.edited").show();
    $("tr#" + rowToEditID + " div.not-edited").hide();
}
function cancelEditCartLine() {
    $("table#cartTable tr.selected div.edited").hide();
    $("table#cartTable tr.selected div.not-edited").show();
    $("table#cartTable tr.selected").removeClass("selected");
}

/* Filter Products */
function selectLink(target) {
    location.href = $(target).children('option:selected').val();
}

function submitBrandSearch(brand) {
    $("form#brandSearchForm input#keyword").val(brand);
    $("form#brandSearchForm input#submitButton").click();
}

function popupWindow(lnk, h, w) {
     var topOffset = (screen.height - h) / 2;
     var leftOffset = (screen.width - w) / 2;
    settings='width='+w+',height='+h+',top='+topOffset+',left='+leftOffset;
    name='_blank';
    var win = window.open(lnk,name,settings);
}

function newWindow(lnk) {
    var win = window.open(lnk, "fullscreen");
}

function setAddressShippingLines() {
    cForm = document.getElementById('addressForm');
    newState = cForm.elements['SHIP_TO_ADDRESS<>indSameAsBillTo'].checked;
    cForm.elements['SHIP_TO_ADDRESS<>firstName'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>firstName'].value = '';
    cForm.elements['SHIP_TO_ADDRESS<>lastName'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>lastName'].value = '';
    cForm.elements['SHIP_TO_ADDRESS<>address1'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>address1'].value = '';
    cForm.elements['SHIP_TO_ADDRESS<>address2'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>address2'].value = '';
    cForm.elements['SHIP_TO_ADDRESS<>city'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>city'].value = '';
    cForm.elements['SHIP_TO_ADDRESS<>postal'].disabled = newState;
    cForm.elements['SHIP_TO_ADDRESS<>postal'].value = '';
}
function submit_forgot_password() {
    var loginForm = document.getElementById('loginForm');
    user = loginForm.elements['LOGIN<>userid'].value;
    passwordForm = document.getElementById('forgot_password');
    passwordForm.elements['FORGOT_PASSWORD<>email'].value = user;
    passwordForm.submit();
}

var formValid = true;
function checkIfFormValid(targetBtn) {
    if (formValid == true) {
        formValid = false;
        return true;
    } else {
        targetBtn.disabled = true;
        return false;
    }
}


