var tracking_visible = false;
var login_visible = false;
var tote_visible = false;
var toteupdate_visible = false;
var slide_speed = "slow";
var on_color = "#F0EEEC";
var off_color = "#E2DEDA";
var hover_color = "#E9E6E3";
var tote_max = 400;
var popup_timer_close = 1500;
var popup_timer_open = 500;
var popup_timer = 0;
var input_focus = null;

$(document).ready(function() 
{
    //master handlers
    $("#trackingpopup_close, #tp_close").hover(function() {
        input_focus = null;
        closePopups();
    });

    $("#tote_popup, #tracking_popup, #wishlist_popup, #shoppingbag_menu ul li.right, #shoppingbag_menu ul li.left").hover(
    function() {
        clearTimeout(popup_timer);
    },
    function() {
        clearTimeout(popup_timer);
        popup_timer = setTimeout('closePopups()', popup_timer_close);
    });

    $('#headerbox input').focus(function() {
        clearTimeout(popup_timer);
        if (tracking_visible) {
            input_focus = 'tracking';
        } else if (login_visible) {
            input_focus = 'login';
        }
    });

    // partner sites only shown popup on click
    $("#partner_header_links #left").click(function(e) {
        e.preventDefault();
        input_focus = null;
        if (tracking_visible) {
            closePopups();
        } else {
            openPopupTracking();
        }
    });

    //tracking handlers
    $("#shoppingbag_menu ul li.left").hover(function() {
        input_focus = null;
        if (tracking_visible) {
            closePopups();
        } else {
            $(this).oneTime(1000,function(){
                openPopupTracking();
            });
        }
    },function(){
        $(this).stopTime();
    });

    $("#shoppingbag_menu ul li.left").hover(function() {
        if (login_visible)
            $(this).css("background-color", hover_color);
        else
            $(this).css("background-color", on_color);
    },
    function() {
        if (!tracking_visible)
            $(this).css("background-color", off_color);
    }
    );
    
    //login handlers
    $("#wishlistpopup_close").live('click', function() {
        input_focus = null;
        closePopups();
    });

    $("#partner_header_links #right").click(function(e) {
        e.preventDefault();
        input_focus = null;
        if (login_visible) {
            closePopups();
        } else {
            openPopupLogin();
        }
    });

    $("#shoppingbag_menu ul li.right").hover(function() {
        input_focus = null;
        if (login_visible) {
            closePopups();
        } else {
            $(this).oneTime(1000,function(){
                openPopupLogin();
            });
        }
    },function (){
        $(this).stopTime();
    });
    
    $("#shoppingbag_menu ul li.right").hover(function() {
        if (tracking_visible)
            $(this).css("background-color", hover_color);
        else
            $(this).css("background-color", on_color);
    },
    function() {
        if (!login_visible)
            $(this).css("background-color", off_color);
    }
    );

    // show account help page
    $("#wishlist_popup .features .help").live('click', function() {
        $("#wishlist_popup .description").hide();
        $(this).next().show();
    });
    
    // hide account help page
    $("#wishlist_popup .description .close").live('click', function() {
            $(this).parent().hide();
    });
    
    // account logout
    $("#wishlist_popup #log_out").live('click', function() {
        var page = location.pathname.substring(1);
        $("#wishlist_popup .loading").css('top', '100px');
        $("#wishlist_popup .loading").show();

        $.getJSON('/ajax/accountlogout', {page_id: page}, function(json) {
            switch(page) {
                case 'checkout/stepone':
                case 'checkout/steptwo':
                case 'checkout/stepthree':
                case 'checkout/stepfour':
                    top.location = 'cart';
                    break;
                case 'cart':
                    $('#ajaxclear').html(json.content);
                default:
                    $('div#shoppingbag_menu #right_text').text('LOGIN TO MY ACCOUNT ');
                    $('#wishlist_popup').html(json.account);
                    $("#account_login div").show();
                    $('#tote_quantity').html('0 items');
                    $('#tote_price').html(json.price);
                    break;
            }
        
            $("#wishlist_popup .loading").hide();
        });
    });

    // submit login form when a user presses enter in the password field
    $("form#wishlist_login #account_password").live('keyup', function(e) {
        if (e.keyCode == 13) {
            /*
             * If do not focus on this element, the account management options
             * do not load properly in IE.  The log out link will not
             * log a user out.
             */
            $("form#wishlist_login #wishlist_submit").focus();

            $("form#wishlist_login").submit();
        }
    });
    
    // account login
    $("#wishlist_popup form#wishlist_login").live('submit', function() {
        if($('#site').length > 0){
            var site = '&site=' + $('#site').val();
        }else{
            var site = '';
        }
        if($('#site').length > 0){
            var site = '&site=' + $('#site').val();
        }else{
            var site = '';
        }
        var page = location.pathname.substring(1);
        var input = $(this).formSerialize() + '&page=' + page + site;
        $("#wishlist_popup .loading").css('top', '100px');
        $("#wishlist_popup .loading").show();

        $.post('/ajax/accountlogin', input, function(json)
        {
            if (json.dealer) {
                window.location = "http://controlpanel." + json.host;
            } else if (json.tote) {
                $('div#shoppingbag_menu #right_text').text('MY ACCOUNT ');
                $('#wishlist_popup').html(json.account);
                toteRefresh(json.tote);
                if (json.content != null) {
                    if(json.content == 'cart'){
                        window.location = 'http://' + json.host + '/cart';
                    }else{
                        $('#content').html(json.content);
                    }
                }
            } else {
                $("#account_login").html(json.account);
                $("#account_login div").show();
            }
            
            $("#wishlist_popup .loading").hide();
        }, 'json');
        return false;
    });

    // account create
    $("#wishlist_popup form#wishlist_register").livequery(function() {
        $(this).ajaxForm({
            url: '/account/register_popup/format/html',
            beforeSubmit: function() {
                $("#wishlist_popup .loading").css('top', '225px');
                $("#wishlist_popup .loading").show();
            },
            success: function(response) {
                if ($(response).find('.error-notice').size() == 0) {
                    $('div#shoppingbag_menu #right_text').text('MY ACCOUNT ');
                    $("#wishlist_popup").html(response);
                    updatePageElements();
                } else {
                    $("#account_create").html(response);
                    $("#account_create div").show();
                }
                
                $("#wishlist_popup .loading").hide();
            }
        });
    });

    //tote handlers
    $("#shoppingbag span.header, #shoppingbag_image").click(function() {
        if ($('#tote_quantity').html() != '0 items') {
            openPopupTote();
        }
    });

    $("#shoppingbag span.header, #shoppingbag_image").hover(
    function() {
        if ($('#tote_quantity').html() != '0 items') {
            clearTimeout(popup_timer);
            popup_timer = setTimeout('openPopupTote()', popup_timer_open);
           
        }
    },
    function() {
        if ($('#tote_quantity').html() != '0 items') {
            clearTimeout(popup_timer);
            popup_timer = setTimeout('closePopups()', popup_timer_close);
            
        }
    });
    
    //Handles the shopping bag popup
    $("#menu_shoppingbag").hover(function() {
        if ($('#menu_shoppingbag #tote_quantity').html() != '0 items' && $('.account_menu_tab_body').css('display') == 'none' && $('#menu_cart_div').css('display') == 'none') {
            $('#menu_tote_popup').stop(false,true);
            $('#menu_tote_popup').fadeIn();
        }
    }, function(){
        $('#menu_tote_popup').stop(false,true);
        $('#menu_tote_popup').fadeOut();
    });
    
    $(".tp_rem").click(function() {
        removeToteItem($(this).attr('id'));
    });

    // show account login form
    $("#account_login > span").live('click', function() {
        $("#account_create div").slideUp();
        $("#account_login div").slideDown();
    });

    // show account creation form
    $("#account_create > span").live('click', function() {
        $("#account_create div").slideDown();
        $("#account_login div").slideUp();
    });
    
    // set up wedding date picker link
    $("#wishlist_popup #account_wedding_date, #login_popup #account_wedding_date").livequery(function() {
        var weddingDate = this;

        $(this).prev().click(function() {
            $(weddingDate).focus();
        });
    });

    //remove personalization
    $('div.tp_info .removePersonalization').live('click', function() {
        var row = $(this).parent().parent().parent().parent();
        var ptext = $(this).parent().parent();
        var code = $(this).attr('id').replace('rp_', '');
        row.slideUp('slow');
        $.post('/cart/personalizeremove', {code: code, tote: true}, function(json) {
            ptext.html('<div class="personalization_header">Not Personalized</div><br/><div class="personalization_actions">> <span class="hover edit_personalization legacy-system" id="ep_' + json.newCode + '">Edit Personalization</span></div>');
            row.html(row.html().replace(eval("/" + code + "/g"), json.newCode));
            row.slideDown('slow');
            $('#tote_price').html(json.shipping);
        }, 'json');
    });

    // edit personalization bindings - old personalization system
    $('.edit_personalization.legacy-system').livequery(function() {
        $(this).personalizeEditCart();
    });
    
    // edit personalization bindings - new personalization system
    $('.tp_info a.edit_personalization.new-system').live('click', function(event) {
        var row_id = $(this).attr('id');
        var id_parts = row_id.split('_');
        var product_lookup = id_parts[1];
        var loading_img = $(this).parent().find('img');
        var modify_links = $(this).parent().find('a');
        
        // personalized goodie bags/ merchandise bags require a minimum qty of 2 so don't proceed if qty is less
        var lookup_parts = product_lookup.split(':');
        var product_id = lookup_parts[2];
        if(product_id == '3388' || product_id == '3389') {
            var qty = parseInt($(this).attr('qty'));
            if(qty < 2) {
                return;
            }
        }
        
        event.preventDefault();
        
        $.displayDesignStudio(product_lookup, loading_img, modify_links);
    });
    
    $('a.edit_personalization.as-system').livequery('click',function(event){
        var row_id = $(this).attr('id');
        var id_parts = row_id.split('_');
        var product_lookup = id_parts[1];

        event.preventDefault();
        $.asEditCart(product_lookup);
    });
    
    
    //live chat
    $('#liveChat').click(function() {
        this.newWindow = window.open('http://service.velaro.com/visitor/requestchat.aspx?siteid=5103&showwhen=inqueue', 'VelaroChat', 'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no');
        this.newWindow.focus();
        this.newWindow.opener=window;
        return false;
    });

    //dealer logout
    $('#dealer_logout').click(function() {
        var host = location.host.split('.');
        setupPopup('Logging out...');
        $.post('/ajax/accountlogout', null, function() {
            window.location = 'http://www.' + host[1] + '.com' + "/dealerlogin/";
        });
    })
});

function closePopups(popup)
{
    clearTimeout(popup_timer);

    if ((tote_visible) && (popup != 'tote')) {
        $("#tote_popup").slideUp(slide_speed);
        tote_visible = false;
    }
    if ((tracking_visible) && (input_focus != 'tracking')) {
        $("#tracking_popup").slideUp(slide_speed, function() {
            $("#shoppingbag_menu ul li.left").css("background-color", off_color);
        });
        tracking_visible = false;
    }
    if ((login_visible) && (input_focus != 'login')) {
        $("#account_create div").hide();
        $("#account_login div").hide();
        $("#wishlist_popup").slideUp(slide_speed, function() {
            $("#shoppingbag_menu ul li.right").css("background-color", off_color);
        });
        login_visible = false;
    }
    if (toteupdate_visible) {
        $("#cart_div").slideUp(slide_speed);
        $('#menu_cart_div').delay(500).fadeOut();
        toteupdate_visible = false;
    }
    
    // remove active class from header links on partnership sites
    $("#partner_header_links > a").removeClass("active");

    // hide wish list help descriptions
    $("#wishlist_popup .description").hide();
}

function openPopupTote()
{
    input_focus = null;
    closePopups('tote');

    if ((!tote_visible) && ($('#tote_quantity').html() != '0 items')) {
        if ($('#tp_item_wrapper').height() > tote_max) {
            $("#tp_close").css('margin-top', '5px');
            $("#tp_close").css('margin-right', '30px');
        } else {
            $("#tp_item_wrapper").css('height', 'auto');
            $("#tp_close").css('margin-top', '0px');
            $("#tp_close").css('margin-right', '10px');
        }

        $("#tote_popup").slideDown(slide_speed);
        tote_visible = true;
    }
}

function openPopupTracking()
{
    if (input_focus != 'tracking') {
        input_focus = null;
    }
    closePopups();

    if (!tracking_visible) {
        $("#shoppingbag_menu ul li.left").css("background-color", on_color);
    
        // add active class to left header link on partnership sites
        $("#partner_header_links #left").addClass("active");

        $("#tracking_popup").slideDown(slide_speed);

        tracking_visible = true;
    }
}

function openPopupLogin()
{
    //Use the legacy wishlist popup to login (used for partner sites).
    if($("#wishlist_popup").length > 0){
        if (input_focus != 'login') {
            input_focus = null;
        }
        closePopups();

        if (!login_visible) {
            $("#shoppingbag_menu ul li.right").css("background-color", on_color);

            // add active class to left header link on partnership sites
            $("#partner_header_links #right").addClass("active");

            $("#account_create div").hide();
            $("#wishlist_popup").slideDown(slide_speed, function() {
                $("#account_login div").slideDown(slide_speed);
            });

            login_visible = true;
        }
    }else{
        //Use the new Weddingstar login popup.
        weddingstarLoginPopup();
    }
        
}

function openPopupToteUpdate()
{
    input_focus = null;
    closePopups();
    
    if (!toteupdate_visible) {
        $("#menu_cart_div").fadeIn();
        $("#cart_div").slideDown(slide_speed);
        popup_timer = setTimeout('closePopups()', popup_timer_close);

        toteupdate_visible = true;
    }
}

function handleCartPopup(div)
{
    $('#cart_div').html(div);

    $("#cart_close").click(function() {
        closePopups();
    });
    
    clearTimeout(popup_timer);
    popup_timer = setTimeout('openPopupToteUpdate()', popup_timer_open);
}

function removeToteItem(id)
{
    var page = location.pathname.substring(1);

    $.getJSON('/ajax/removetoteitem', {rem_id: id, page_id: page}, function(json) {
        $('#tp_item_wrapper').html(json.tote);
        if ($('#quantity_update').val() == 1) {
            $('#tote_quantity').html('1 item');
        } else {
            $('#tote_quantity').html($('#quantity_update').val() + ' items');
        }
        $('#tote_price').html($('#price_update').val());

        if ($('#quantity_update').val() == 0) {
            if (page == 'checkout')
                top.location = 'cart';
            closePopups();
        } else {
            $(".tp_rem").click(function() {
                removeToteItem($(this).attr('id'));
            });
        }

        if (page == 'cart') {
            $('#content').html(json.content);
            cartInitActions();
        }
    });
}

function toteRefresh(data)
{
    $('#tp_item_wrapper').html(data);
    $('.tp_rem').click(function() {
        removeToteItem($(this).attr('id'));
    });
    if ($('#quantity_update').val() == 1) {
        $('#tote_quantity').html('1 item');
    } else {
        $('#tote_quantity').html($('#quantity_update').val() + ' items');
    }
    $('#tote_price').html($('#price_update').val());
}

