var box_on = 'url(/images/button/checkbox_active.gif)';
var box_off = 'url(/images/button/checkbox_inactive.gif)';
var box_on_src = '/images/button/checkbox_active.gif';
var box_off_src = '/images/button/checkbox_inactive.gif';
var load_small = '<img src="/images/loading_small.gif" alt="Please wait..."/>';
var qty_0 = 'quantity must be greater than 0';

$(document).ready(function()
{
    $('#shopbymagazine_link, #magazine_free').live('click',function(){
        var width = screen.width;
        var height = screen.height;
        //alert(height);
        if(height < '900'){
            window.location = '/shopbymagazinesmall';
        }else{
            window.location = '/shopbymagazine';
        }

    });

    $('#shopbymagazine_link, #magazine_free').livequery(function(){
        $(this).hover(function(){
           $(this).css('cursor','pointer') ;
        });
    });

    $('.contest_sign_up').live('click',function(){
        $(document).scrollTo($(this), 800);
    })

    $('.contest_sign_up').livequery(function(){
        $(this).hover(function(){
            $(this).css('cursor','pointer');
        })

    })

    $("a[rel='external']").live('click',function()
    {   
        window.open($(this).attr('href'), 'popup', 'toolbar=0,scrollbars=1,location=0,status=0,menubar=0');
        return false;
    });
    
    //moved from product.js to common since we need the link to work on the front page now as well.
    $('#magazine_popup').click(function() {
        showMagazineLocations();
    }, 'json');

    $('.top_magazine_locations').click(function(e) {
        e.preventDefault();
        showMagazineLocations();
    }, 'json');
    
    // hide the extra page descriptions, this is done here, so page adjustment works correctly
    if($('#description p').length > 1) {
        $('#description p:last').after('  <nobr><span id="more">[Read More]</span></nobr>');
        $('#description p:first').nextAll('p').each(function() {
            $(this).hide();
        });
    }

    // fix content height if it's less then the sidebar
    var sidebar_height = $("#sidebar_content").height();
    var content_height = $("#content").height();

    if (sidebar_height > content_height)
        $("#content").height(sidebar_height);
 
    // setup promotions popup
    $('.promotion_details_link').live('click', function(e){
        e.preventDefault();

        $('#site_popup.popup_promotion').dialog({
            autoOpen: true,
            position: 'center',
            resizable: false,
            modal: true,
            width: '477px',
            overflow: 'visible',
            dialogClass: 'site_popup',
            close: function(){
                $('#site_popup.popup_promotion').dialog('destroy');
            }
        });

    });
    
    $('#site_popup.popup_promotion #site_popup_close').live('click',function(){
        $('#site_popup.popup_promotion').dialog('destroy');
    });
    
    // setup automatic magazine popup
    if($('.popup_magazine').is(":hidden")){
        $('#site_popup.popup_magazine').dialog({
            autoOpen: true,
            position: 'center',
            resizable: false,
            modal: true,
            width: '477px',
            overflow: 'visible',
            dialogClass: 'site_popup',
            close: function(){
                $('#site_popup.popup_magazine').dialog('destroy');
            }
        });
        
        $('#site_popup.popup_magazine #site_popup_close').live('click',function(){
            $('#site_popup.popup_magazine').dialog('destroy');
        });
    }
    
    // setup automatic magazine popup
    if($('.popup_aus_christmas').is(":hidden")){
        $('#site_popup.popup_aus_christmas').dialog({
            autoOpen: true,
            position: 'center',
            resizable: false,
            modal: true,
            width: '477px',
            overflow: 'visible',
            dialogClass: 'site_popup',
            close: function(){
                $('#site_popup.popup_aus_christmas').dialog('destroy');
            }
        });
        
        $('#site_popup.popup_aus_christmas #site_popup_close').live('click',function(){
            $('#site_popup.popup_aus_christmas').dialog('destroy');
        });
    }
    
    // setup automatic new arrivals popup
    if($('.popup_newarrivals').is(":hidden")){
        $('#site_popup.popup_newarrivals').dialog({
            autoOpen: true,
            position: 'center',
            resizable: false,
            modal: true,
            width: '477px',
            overflow: 'visible',
            dialogClass: 'site_popup',
            close: function(){
                $('#site_popup.popup_newarrivals').dialog('destroy');ma
            }
        });
        
        $('#site_popup.popup_newarrivals #site_popup_close').live('click',function(){
            $('#site_popup.popup_newarrivals').dialog('destroy');
        });
    }

//simulate a swatch click whenever new personalization has colour (swatch) options (Cart Edit and Product Page)
    $('.ui-dialog #personalization-data select[id*="swatch_colour"]').live('change',function(){
       var code = $(this).attr('value'); 
       $('#product_code-element #product_code').val(code);
    });
});

// finish off closing the popup
function finishClose()
{   
    $('#overlay').fadeOut('fast');
    $('#overlay').css('height', 0);
    $(document).unbind('keydown', handleKeypress);
}

// takes care of closing the window on pressing esc
function handleKeypress(e)
{
    // To ie
    if ( e == null ) {
        keycode = event.keyCode;
        escapeKey = 27;
    // To Mozilla
    } else {
        keycode = e.keyCode;
        escapeKey = e.DOM_VK_ESCAPE;
    }
    
    if (keycode == escapeKey)
    {
        $('.quick_popup').hide();
        finishClose();
    }
}

/**
 * Prepares an overlayed popup
 */
function setupPopup(note)
{
    if ($('#loading_note').length) {
        if (note == '')
            note = 'Loading...';
        $('#loading_note').html(note);
    } else {
        $('body').append('<div id="overlay"></div>');
        $('#overlay').bgiframe();
        if (note == '')
            note = 'Loading...';
        $('body').append('<div id="loading"><img src="/images/loading.gif" /><div id="loading_note">' + note + '</div></div>');
    }

    startPopup();
}

function destroyPopup()
{
	
		if ($('#loading_note').length > 0) {
	        $('#loading_note').html('<br/>returning you to the page...');
            if($('#shopbymag_popup').length == 0){
                $("#overlay").fadeOut('fast');
            }
	        $("#loading").fadeOut('slow');
	    }

}

// shows the overlay and the loading div
function startPopup()
{
    $("#overlay").css('height', $(document).height());
    $("#overlay").css('opacity', 0.5).fadeIn('fast');
    
    // calculate some dimensions
    var scrollTop = $(document).scrollTop();
    var scrollLeft = $(document).scrollLeft();
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    
    // show loading div
    $("#loading").fadeIn('fast');
    $("#loading").css('left', Math.round((windowWidth - $("#loading").width())/2) + scrollLeft)
    $("#loading").css('top', Math.round((windowHeight - $("#loading").height())/2) + scrollTop);

    //click outside to close
    $("#overlay").click(function() {
        $('.quick_popup').hide();
        $("#loading").fadeOut('slow');
        finishClose();
    });
}

// shows the quick look popup
function showPopup(id)
{    
    // get rid of the loading div
    $('#loading').fadeOut('fast', function() 
    {
       // show div and reposition
        $(id).fadeIn('slow');
        positionPopup(id);    
            
        // bind keyboard
        $(document).keydown(function(e)
        {
            handleKeypress(e);
        }); 
    });
}

function positionPopup(id)
{
    // calculate some dimensions
    var scrollTop = $(document).scrollTop();
    var scrollLeft = $(document).scrollLeft();
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    
    var top = Math.round((windowHeight - $(id).height())/2) + scrollTop;
    if (top < 0)
        top = 0;
    
    var left = Math.round((windowWidth - $(id).width())/2) + scrollLeft;
    if (left < 0)
        left = 0;
    
    if($('#shopbymag_popup').length > 0){
        $(id).css('top',top);
        $(id).css('left',left);
    	$(id).show('slow',function(){
        	$(document).scrollTo($('#shopbymag_popup'),200,{offset: {top:-25, left:0}});
        });
    }else{
    	$(id).animate({
            left: left,
            top: top
        }, 'normal', 'linear');
    }
    
}

function buildProductCodeArray(retValues, personalize, containerId)
{
    var container = $('body');
    if (containerId) {
        container = $(containerId);
    }
    // check productpage type (dropdown or input)  
    var type = container.find('#productpage_type').val();
    
    retValues.doPost = false;

    //set qty to validate against
    var min_quantity = 1;
    if (personalize) {
        min_quantity = Math.max(container.find('#personalize_min_quantity').val(), container.find('#product_min_quantity').val());
    } else {
        min_quantity = container.find('#product_min_quantity').val();
    }
    min_quantity = parseInt(min_quantity);
    var multiple_of = container.find('#product_multiples_of').val();
    var boxValue = 0;

    var quantitySelector = "input[name='quantity'], .quantity_box";

    //validate
    container.find("input[name='quantity']").each(function() {
        if ($(this).attr('productcode') == 'choose') {
            $(this).parent().find('.error').html('please choose valid menu options');
        } else {
            var errorElement = $(this).siblings().filter('.error');
        
            boxValue = parseInt($(this).val(), 10);
            if (isNaN(boxValue)) {
                boxValue = 0;
            }
            if (boxValue <= 0) {
                errorElement.html(qty_0);
            } else if (min_quantity > 0 && boxValue < min_quantity) {
                errorElement.html('quantity must be ' + min_quantity + ' or more');
            } else if (multiple_of > 0 && boxValue % multiple_of != 0) {
                errorElement.html('quantity must be a multiple of ' + multiple_of);
            } else if ($(this).attr('productcode') == undefined) {
                errorElement.html('productcode error, please refresh the page');
            } else {
                var code = $(this).attr('productcode') + '_' + boxValue;
                retValues.productcodeArray[retValues.productcodeArray.length] = code;
                retValues.doPost = true;
                errorElement.html('');
            }
        }
    });
    // if valid qty found, unset errors for empty boxes
    if (retValues.doPost) {
        container.find(quantitySelector).each(function() {
            if ($(this).val() == 0) {
                $(this).siblings().filter('.error').html('');
            }
        });
    } else if (type == 'dropdown') {
        container.find('.quantity_box').each(function() {
            if ($(this).attr('productcode') == 'choose') {
                $(this).parent().find('.error').html('please choose valid menu options');
            } else {
                var errorElement = $(this).siblings().filter('.error');

                boxValue = parseInt($(this).val(), 10);
                if (isNaN(boxValue)) {
                    boxValue = 0;
                }
                if (phpEmpty(boxValue)) {
                    errorElement.html(qty_0);
                } else if (boxValue < min_quantity) {
                    errorElement.html('quantity must be ' + min_quantity + ' or more');
                } else if (boxValue % multiple_of != 0) {
                    errorElement.html('quantity must be a multiple of ' + multiple_of);
                } else if ($(this).attr('productcode') == undefined) {
                    errorElement.html('productcode error, please refresh the page');
                } else {
                    retValues.doPost = true;
                    retValues.productcodeArray[retValues.productcodeArray.length] = $(this).attr('productcode') + '_' + boxValue;
                    errorElement.html('');
                }
            }
        });
        //if valid qty found, unset errors for empty boxes
        if (retValues.doPost) {
            container.find('.quantity_box').each(function() {
                if ($(this).val() == 0) {
                    $(this).siblings().filter('.error').html('');
                }
            });
        }
    }

}


/*
 * isEmpty 
 *
 * This function verifies that an Object is empty.  An object is empty
 * if it does not have any variables.
 * 
 * return boolean
 */
function isEmpty(obj) 
{
    for (value in obj) {
        return false;
    }

    return true;
}


/**
 * objSize 
 * 
 * This function returns the size of an object.
 *
 * return int
 */
function objSize(obj) 
{
    var size = 0;

    for (var i in obj) {
        size++;
    }

    return size;
}

/**
 * Attempts to simulate php's empty()
 * Returns true for zero, blank, undefined
 */
function phpEmpty($var)
{
    if ($var === undefined) {return true;}
    if ($var == '') {return true;}
    if ($var == 0) {return true;}

    return false;
}

/**
 * this is the new way of displaying overlay windows on the website
 * this one function handles everything.
 *
 * you can run your own user function on the returned data to do any updates before
 * the data is displayed.  The returned data must be in json format with an html
 * member, this is the code which is displayed in the popup.
 *
 * note: this is the loading message that is displayed while the ajax call is in
 *       progress
 * url: location for the ajax request
 * params: data to be passed via ajax to the server
 * closeId: id for the element that will close the dialog
 * preFunc[optional]: a user function that can massage the returned data, called before html is shown.
 * postFunc[optional]: a user function that to add interactivity to the resulting HTML (after is is shown).
 */
function dialog(note, url, params, closeId, preFunc, postFunc)
{
    // display loading box
    $('body').append('<div id="overlay"></div>');
    $('#overlay').bgiframe();
    //click outside to close
    var close = function() {
        if(!$('#shopbymag_popup').length > 0){
            $('#ajax_display').fadeOut('fast', function() {
                // reset ajax_display width to defaults.
                $('#ajax_display').css('width', 300);
                $('#ajax_display').css('height', 58);
                positionPopup('#ajax_display');
            });
            $("#ajax_display_content").html('');
            $("#ajax_display_content").hide();

            $('#overlay').fadeOut('fast');
            $('#overlay').remove();
        }else{
             $('#ajax_display').fadeOut('fast', function() {
            // reset ajax_display width to defaults.
            //$('#ajax_display').css('width', 300);
            //$('#ajax_display').css('height', 58);
            //positionPopup('#ajax_display');
        });
            $("#ajax_display_content").html('');
            $("#ajax_display_content").hide();

            //$('#overlay').fadeOut('fast');
            //$('#overlay').remove();
        }
       
        
        
    }
    $("#overlay").click(close);
    $(closeId).live('click', close);
    $("#overlay").css('height', $(document).height());
    $("#overlay").css('opacity', 0.5).fadeIn('fast');
    if (note == '')
        note = 'Loading...';
    $('#ajax_display_content').html('<img src="/images/loading.gif" /><div id="loading_note">' + note + '</div>');
    positionPopup('#ajax_display');
    $("#ajax_display").fadeIn('fast');

    // run function
    $.post(url, params, function(data) {
        // process user data
        if (preFunc != undefined)
            preFunc(data);
        $('#ajax_loader').html(data.html);
        $('#ajax_display_content').html('');

        // calculate some dimensions
        var scrollTop = $(document).scrollTop();
        var scrollLeft = $(document).scrollLeft();
        var windowHeight = $(window).height();
        var windowWidth = $(window).width();

        var top = Math.round((windowHeight - $('#ajax_loader').height())/2) + scrollTop;
        if (top < 0)
            top = 0;

        // put in place to stop the magazine popup from being so long
        var ajax_height = $('#ajax_loader').height();
        if( ajax_height > 1400) // note magazine list was coming in at 1625
            ajax_height = 971;


        $('#ajax_display').animate({
            width: $('#ajax_loader').width(),
            height: ajax_height,
            left: Math.round((windowWidth - $('#ajax_loader').width())/2) + scrollLeft,
            top: top
        }, 1000, "easeOutBounce", function() {
            positionPopup('#ajax_display');
            $('#ajax_display_content').html(data.html);
            $('#ajax_loader').html('');
            $('#ajax_display_content').fadeIn('fast');

            // add interactivity to the final HTML
            if (postFunc != undefined)
                postFunc($('#ajax_display_content'));
        });
    }, 'json');
}

/*
 * confirmationDialog 
 *
 * Display confirmation dialog and set up confirmation
 * bindings
 * 
 * message    - message that is displayen in the dialog 
 * yes_action - function that is executed when users clicks "Yes"
 */
function confirmationDialog(message, yes_action)
{
    var dialog = '#confirm_dialog';

    if ($(dialog).length > 0) {
        $(dialog).show();
    } else {
        var div = '<div id="confirm_dialog">'
            + '<div>' + message + '</div>'
            + '<div>'
            + '<div class="buttons" id="confirm_yes">Yes</div>'
            + '<div class="buttons" id="confirm_no">No</div>'
            + '<div class="clearfix"></div>'
            + '</div>'
            + '</div>';
        $('body').append(div);
        $(dialog).bgiframe();
    }

    var scrollTop = $(document).scrollTop();
    var scrollLeft = $(document).scrollLeft();
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    $(dialog).css('left', Math.round((windowWidth - $(dialog).width())/2) + scrollLeft)
    $(dialog).css('top', Math.round((windowHeight - $(dialog).height())/2) + scrollTop);

    $('#confirm_no').click(function() {
        $(dialog).hide();
    });
    
    $('#confirm_yes').click(function() {
        $(dialog).hide();
        yes_action.apply()
    });

   
}

$('.contest_sign_up').live('click',function(){
    $(document).scrollTo($(this), 800);
})

$('.contest_sign_up').livequery(function(){
    $(this).hover(function(){
        $(this).css('cursor','pointer');
    })
    
})

/**
 * This function swaps images on any tag that contians an altsrc tag.
 * This was setup to solve IE7 image swapping issues.
 * 
 * @param image The current image object that you want to swap images on, provided that the tag contains an additional 'altsrc' parameter.
 */
function swapImage(image){
    var altImage = image.attr('altsrc'); 
    var currentImage = image.attr('src'); 
    image.attr('altsrc', currentImage); 
    image.attr('src', altImage); 
}

/**
 * Logout the current user (non-dealer logout)
 */
function userLogout()
{
    var page = location.pathname.substring(1);

    $.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:
                location.reload(true);
                break;
        }
    });
}

function showMagazineLocations()
{
    dialog("", "/magazineretailer", {}, "#magazine-retailers-close");
}

/**
 * Display the new login popup
 */
function weddingstarLoginPopup()
{
    if($('.flap_account_status').children('img').length > 0){
        $('#login_popup').dialog({
            autoOpen: true,
            position: 'center',
            resizable: false,
            modal: true,
            width: '677px',
            dialogClass: 'as',
            close: function(){
                    $('#login_popup').dialog('destroy');
            }
        });
    }
}
