/* $Id: jquery.personalize.js 20581 2011-11-21 17:04:05Z mwall $ */
var itemNum = '';

(function($)
{
    var settings;
    
    /*
     * setupPersonalizationBindings
     *
     * Set up the bindings for the personalization dialog elements
     */
    $.setupPersonalizationBindings = function(callerSettings) {
        loadSettings(callerSettings);
    };

    $.fn.personalize = function(callerSettings)
    {
        loadSettings(callerSettings);

        return this.each(function()
        {
            $(this).click(function()
            {
                // do nothing if the checkbox is not checked
                if (!$(this).is(':checked')) {
                    return;
                }
            
                // get which product codes were chosen, (if all quantities are 0, do not go to personalization stuff)
                var retValues = new Object();
                retValues.productcodeArray = new Array();
                buildProductCodeArray(retValues, true, settings.productElement);

                // unselect personalization checkbox
                $(settings.productElement + ' #personalize_yes').parent().ezToggle();

                if($(settings.productElement + ' #quantity .error').length > 0){
                    if ($(settings.productElement + ' #quantity .error').html() != '') {
                        // scroll to error message
                        $.scrollTo(settings.productElement + ' #quantity .error');
                    }
                }

                if (retValues.doPost) {
                    if (settings.usePopup) {
                        setupPopup('');
                    }

                    $.post('/ajax/personalizearray/', {id: $(this).attr('product_id'), product_info: JSON.stringify(retValues.productcodeArray), designStyle: $('#product_design_style').val()}, function(json) {
                        setupPersonalization(json);
                    }, 'json');
                }
            });
        });
    };

    /*
     * personalizeEditCart
     *
     * Edit personalization from the cart review page
     *
     * callerSettings - settings object
     */
    $.fn.personalizeEditCart = function(callerSettings) {
        loadSettings(callerSettings);

        return $(this).each(function() {
            $(this).click(function() {
                setupPopup('');
                $.post('/ajax/personalizecartedit', {hash: $(this).attr('id').replace('ep_', ''), mode: 'edit'}, function(json) {
                    setupPersonalization(json);
                }, 'json');
            });
        });
    };

    /*
     * loadSettings
     *
     * Load settings variable
     *
     * callerSettings - settings object
     */
    var loadSettings = function(callerSettings) {
        settings = $.extend({ 
            productElement:     'body',
            personalizeElement: '#personalize_div',
            usePopup:           true
        }, callerSettings || {});
    };
        
    var setupPersonalization = function(json) {
        var data = json.html;

        if (!settings.usePopup) {
            $(settings.personalizeElement).html(data).slideDown();
        } 
        else {
            window.location.hash = json.hash;

            // build jquery elements from returned html
            var personalize_div = $(data);

            // preload all images
            var imgArray = getImgArray(personalize_div);

            var timer = window.setInterval(function() {
                if (!checkImg(imgArray))
                    return;
                window.clearInterval(timer);
                personalizeStart(personalize_div);
            }, 1000);
        }
    };

    var personalizeStart = function (personalize_div) {
        $('#ajax_loader').html("<div id='personalize_div_inner'>" +
            personalize_div.html() +
            "</div>"
        );
        var height = $('#ajax_loader').height();
        $('#personalize_div_inner').html(personalize_div);
        personalizeReapplySettings();
        $('#personalize_div').height(height);
        showPopup('#personalize_div');
        $('div.checkbox', personalize_div).click(function() {
            // change background image to checkmark once we get image
            if ($(this).attr('s') == 'false') {
                $(this).attr('s', 'true');
            } else {
                $(this).css('background-image','');
                $(this).attr('s', 'false');
            }
        });
        $('.image_select').click(function() {
            $(this).next('div').slideToggle('fast');
        });
    
        $('.image_select_dropdown div').hover(function() {
            $(this).css('border','1px solid #A66181');
        }, function() {
            $(this).css('border','');
        }).click(function() {
            $(this).parent().slideToggle('fast');
            var container = $(this).parent().parent().parent().attr('id');
            var count = 0;
            $(this).children('span').each(function() {
                if (count == 0) {
                    $(this).parent().parent().parent().children('.image_select').text($(this).text());
                    $('#' + container + ' .product_info_name').text($(this).text());
                } else if (count == 1)
                    $('#' + container + ' .product_info_designs').text($(this).text());
                else if (count == 2)
                    $('#' + container + ' .product_info_price_range').text($(this).text());
                else if (count == 3)
                    $('#' + container).children('img').attr('src', $(this).text());
                else if (count == 4)
                    $('#' + container + ' div.checkbox').attr('product_code', $(this).text());
                count++;
            });
        });
    };

    /**
     * Re-applies users settings when possible
     */
    var personalizeReapplySettings = function() {
        var id = undefined;
        var selected = undefined;

        if ($('#letter_style_selected').length) {
            id = $('#letter_style_selected').val();
            selected = '#letter_style #' + id;
        } else if ($('#design_style_selected').length) {
            id = $('#design_style_selected').val();
            selected = '#design_style #' + id;
        } else if ($('#wrapper_style_selected').length) {
            id = $('#wrapper_style_selected').val();
            selected = '#wrapper_style #' + id;
        } else if ($('#sticker_style_selected').length) {
            id = $('#sticker_style_selected').val();
            selected = '#sticker_style #' + id;
        } else if ($('#swatch_selected').length) {
            id = $('#swatch_selected').val();
            selected = '#swatch_' + id;
        } else if ($('#monogram_color_selected').length) {
            id = $('#monogram_color_selected').val();
            selected = '#monogram_color #' + id;
        } else if ($('#monogram_option_selected').length) {
            id = $('#monogram_option_selected').val();
            selected = '#monogram_option #' + id;
        }

        
    
        if (selected != undefined) {
            $(selected).addClass('letter_style_selected');
            $(selected).addClass('letter_style_selected_border');
            if ($('#swatch_second_selected').length) {
                id = $('#swatch_second_selected').val();
                selected = '#swatch_second_' + id;
                $(selected).addClass('letter_style_selected');
                $(selected).addClass('letter_style_selected_border');
            }
            return;
        }
    
        if ($('#silhouette_selected_solo').length) {
            selected = '#silhouette_solo #' + $('#silhouette_selected_solo').val();
            $(selected).addClass('letter_style_selected');
            $(selected).addClass('letter_style_selected_border');
        } else {
            if ($('#silhouette_selected_left').length) {
                selected = '#silhouette_left #' + $('#silhouette_selected_left').val();
                $(selected).addClass('letter_style_selected');
                $(selected).addClass('letter_style_selected_border');
            }
            if ($('#silhouette_selected_right').length) {
                selected = '#silhouette_right #' + $('#silhouette_selected_right').val();
                $(selected).addClass('letter_style_selected');
                $(selected).addClass('letter_style_selected_border');
            }
        }
        if ($('#silhouette_selected_bubble').length) {
            selected = '#silhouette_bubble #' + $('#silhouette_selected_bubble').val();
            $(selected).addClass('letter_style_selected');
            $(selected).addClass('letter_style_selected_border');
        }
        
        
    };

    var loadPersonalizeDiv = function (data) {
        if (!settings.usePopup) {
            $(settings.personalizeElement).html(data);
        } 
        else {
            var imgArray = getImgArray(data);
    
            var timer = window.setInterval(function() {
                if (!checkImg(imgArray))
                    return;
                window.clearInterval(timer);
                //load personalize div
                $('#personalize_div_inner').fadeTo('normal', 0, function() {
                    //$('#ajax_loader').html(data);
                    $('#ajax_loader').html("<div id='personalize_div_inner'>" +
                        data +
                        "</div>"
                    );
                    var height = $('#ajax_loader').height();
                    $('#personalize_div').animate({height: height}, 'slow', 'linear', function() {
                        $('#personalize_div_inner').html(data);
                        personalizeReapplySettings();
                        if ($('#personalize_div').height() != $('#ajax_loader').height())
                            $('#personalize_div').animate({height: $('#ajax_loader').height()}, 'fast', 'linear');
                        $('#personalize_div_inner').fadeTo('normal', 1);
                        positionPopup('#personalize_div');
                    });
                });
            }, 1000);
        }
    };

    var getImgArray = function (context) {
        var imgArray = [];
        var count = 0;
        $('img', context).each(function() {
    //        alert($(this).attr('src'));
            imgArray[count] = new Image();
            imgArray[count].src = $(this).attr('src');
            count++;
        });
        return imgArray;
    };

    var checkImg = function (imgArray) {
        for (var i = 0; i < imgArray.length; i++) {
            if (!imgArray[i].complete)
                return false;
        }
        return true;
    };

    var checkOptions = function ()
    {
        var code = '';
        if ($("#sticker_div div.checkbox").attr('s') == 'true')
            code = code + $("#sticker_div div.checkbox").attr('product_code');
        else
            code = code + '0';
        code += '|';
        if ($("#card_div div.checkbox").attr('s') == 'true')
            code = code + $("#card_div div.checkbox").attr('product_code');
        else
            code = code + '0';
        code += '|';
        if ($("#ribbon_div div.checkbox").attr('s') == 'true')
            code = code + $("#ribbon_div div.checkbox").attr('product_code');
        else
            code = code + '0';
        code += '|';
        if ($("#craftpunch_div div.checkbox").attr('s') == 'true')
            code = code + $("#craftpunch_div div.checkbox").attr('product_code');
        else
            code = code + '0';
        code += '|';
        if ($("#dazzler_div div.checkbox").attr('s') == 'true')
            code = code + $("#dazzler_div div.checkbox").attr('product_code');
        else
            code = code + '0';
        return code;
    };

    /**
     * Clones the first piece's text for all pieces
     */
    var personalizeCloneFirst = function () {
        template = new Array();
        var i = 0;
        $('#piece_wrapper_0 input[type=text]').each(function() {
            template[i++] = $(this).val();
        });
        $('.piece_text').each(function() {
            var id = '#' + $(this).attr('id');
            i = 0;
            $(id + ' input[type=text]').each(function() {
                $(this).val(template[i++]);
            });
        });
    };

    /**
     * Determines whether all pieces have the same text as the first piece
     */
    var personalizeHasSameText = function () {
        var exitCall = false;
        template = new Array();
    
        var i = 0;
        $('#piece_wrapper_0 input[type=text]').each(function() {
            template[i++] = $(this).val();
        });
        $('.piece_text').each(function() {
            var id = '#' + $(this).attr('id');
            i = 0;
            $(id + ' input[type=text]').each(function() {
                if ($(this).val() != template[i++]) {
                    $('#same_pieces').val(0);
                    $('#same_pieces_box').css('backgroundImage', box_off);
                    exitCall = true;
                    return false;
                }
            });
            if (exitCall) return false;
        });
        if (exitCall) return false;
    
        $('#same_pieces').val(1);
        $('#same_pieces_box').css('backgroundImage', box_on);
        return true;
    };

    /**
     * Updates an existing product row's quantity and prices
     */
    var personalizeUpdatedCode = function (jsonUpdatedCodes, jsonNewCodes)
    {
        if (jsonUpdatedCodes.length > 0) {
            var updatedCodes = jsonUpdatedCodes.shift();
            var row = 'row_' + updatedCodes['code'];
            row = document.getElementById(row) || document.getElementById(row.replace( /\:/, '\\:' ));
            var targetOffset = $(row).offset().top - 15;
            var allow_scroll = true;
            $('html,body').animate({scrollTop: targetOffset}, 'slow', function() {
                if (allow_scroll) {
                    allow_scroll = false;
                    $(row).children('div.qty').children('input.cart_udpate_box').val(updatedCodes['qty']).effect("pulsate", {times: 3}, 300, function() {
                        $(row).children('div.total').children('div.base_cost').html(updatedCodes['price']).effect("pulsate", {times: 3}, 300, function() {
                            //update fee if fee exists
                            if ($(row).children('div.total').children('div.fee_cost').length) {
                                $(row).children('div.total').children('div.fee_cost').html(updatedCodes['fee']).effect("pulsate", {times: 3}, 300, function() {
                                    if (jsonUpdatedCodes.length > 0) {
                                        personalizeUpdatedCode(jsonUpdatedCodes, jsonNewCodes);
                                    } else if (jsonNewCodes) {
                                        personalizeNewCode(jsonNewCodes);
                                    }
                                });
                            } else if (jsonUpdatedCodes.length > 0) {
                                personalizeUpdatedCode(jsonUpdatedCodes, jsonNewCodes);
                            } else if (jsonNewCodes) {
                                personalizeNewCode(jsonNewCodes);
                            }
                        });
                    });
                }
            });
        } 
    };

    /**
     * Adds new product rows
     */
    personalizeNewCode = function (jsonNewCodes)
    {
        if (jsonNewCodes.length > 0) {
            var newCode = $(jsonNewCodes.shift()).hide();
            var targetOffset = $('#cart').offset().top + $('#cart').height() - 15;
            var allow_scroll = true;
            $('html,body').animate({scrollTop: targetOffset}, 'slow', function() {
                if (allow_scroll) {
                    allow_scroll = false;
                    newCode.appendTo($('#cart')).slideDown('slow', function() {
                        $('#cart').append('<div class="clearfix"></div>');
                        $('.product_personalization div').css('display', 'none').css('display', 'block');
                        if (jsonNewCodes.length > 0) {
                            personalizeNewCode(jsonNewCodes);
                        }
                        
                        // show continue shopping button if no more items require personalization
                        if ($("b:contains('This item must be personalized.')", $("#cart")).length == 0) {
                            $('div.personalization_header').remove();
                            $("#proceed_to_checkout").show();
                        }
                    });
                }
            });
        }
    };

    /**
     * Apply form restrictions based on logo selection
     */
    var personalizeApplyRestrictions = function (menu)
    {
        var line2 = $(menu).parent().parent().next().next().children('input:text');
        if ($(menu).hasClass('restriction_1')) {
            $(line2).attr('disabled', 'disabled');
        } else if ($(line2).attr('disabled')) {
            $(line2).removeAttr('disabled');
        }
    };

    /**
     * Display popup for logo only option
     */
    var personalizePopupLogoOnly = function (icon)
    {
        var sel = $('#personalize_popup');
        sel.css('top', icon.position().top - icon.height() - 250);
        sel.css('left', icon.position().left);
        $('#personalize_popup div').html('<div style="text-align:center;"><img src="/images/loading.gif" alt="loading, please wait..." />');
        sel.show();
        $.post('/ajax/personalizelogoonlypopup', {id: $('#id').val()}, function(html) {
            $('#personalize_popup div').width(480).html(html);
            sel.hide().fadeIn('slow');
        });
    };

     // setup the hover on the letter style page
    $(".letter_style_option, .design_style_option, .logo_option, .wrapper_style_option, .sticker_style_option, .swatch_option, .swatch_second_option, .monogram_color_option, .monogram_option_option, .ribbon_style_option, .silhouette_option").livequery(function () {
        $(this).hover(function() {$(this).addClass('image_border')}, function() {$(this).removeClass('image_border')});
        $(this).click(function() {
            if ($(this).hasClass('silhouette_option')) {
                if ($(this).hasClass('silhouette_left_option')) {
                    $('.silhouette_left_option').each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                } else if ($(this).hasClass('silhouette_right_option')) {
                    $('.silhouette_right_option').each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                } else if ($(this).hasClass('silhouette_solo_option')) {
                    $('.silhouette_solo_option').each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                } else {
                    $('.silhouette_bubble_option').each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                }
            } else {
                if ($(this).hasClass('swatch_second_option')) {
                   $('.swatch_second_option').each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                }else{
                    $(".letter_style_option, .design_style_option, .logo_option, .wrapper_style_option, .sticker_style_option, .swatch_option, .monogram_color_option, .monogram_option_option, .ribbon_style_option").each(function() {
                        $(this).removeClass('letter_style_selected');
                        $(this).removeClass('letter_style_selected_border');
                    });
                }
            }
            $(this).addClass('letter_style_selected');
            $(this).addClass('letter_style_selected_border');
        });
    }, function() {
        $(this).unbind('mouseover').unbind('mouseout').unbind('click');
    });

    $("#waiver .checkbox").livequery('click', function() {
        if ($(this).hasClass('checked')) {
            $(this).removeClass('checked');
            $('#addtocartpersonalize').attr('src', "/images/button/addtotote_inactive.gif");
        } else {
            $(this).addClass('checked');
            $('#addtocartpersonalize').attr('src', "/images/button/addtotote.gif");
        }

    });

    //Enable "addtobag" when initials are present
    $('.rsvp_initial #initial').live('keyup', function(){        
        if($(this).val() != ''){
            $('#addtocartpersonalize').attr('src', "/images/button/addtotote.gif");
        }else{
            $('#addtocartpersonalize').attr('src', "/images/button/addtotote_inactive.gif");
        }
    });

    $('#addtocartpersonalize').livequery('click', function() {
        if ($(this).attr('src') != "/images/button/addtotote.gif") {
            return;
        }
        // show loading image
        $('#navigation_buttons img').hide();
        $('#personalize-loading').show();

        $.post('/ajax/addtototepersonalizeproduct', {hash: $('#hash').val()}, function(json) {
            if (json.error) {
                alert(json.error);
                $('#personalize_div').fadeOut('fast');
                if(!$('#shopbymag_popup')){
                    $('#overlay').fadeOut('fast');
                }
            }
            if (json.added) {
                handleCartPopup(json.added);
                $('#overlay').fadeOut('fast');
                if($('#shopbymag_popup').length > 0){
                    removeShopByMag();
                }

            }
            if (json.oldCode) {
                $('#personalize_div').fadeOut('slow', function () {
                    $('#overlay').fadeOut('slow', function() {
                        var row = 'row_' + json.oldCode;
                        row = document.getElementById(row) || document.getElementById(row.replace( /\:/, '\\:' ));
                        if (row != null) { //cart page
                            var targetOffset = $(row).offset().top - 15;
                            var allow_scroll = true;
                            $('html,body').animate({scrollTop: targetOffset}, 'slow', function() {
                                if (allow_scroll) {
                                    allow_scroll = false;
                                    $(row).slideUp('slow', function() {
                                        // remove parent product row
                                        if ($(row).hasClass('free')) {
                                            $(row).prev().remove();
                                        }

                                        $(row).remove();

                                        if (json.updatedCodes) {
                                            if (json.newCodes) {
                                                personalizeUpdatedCode(json.updatedCodes, json.newCodes);
                                            } else {
                                                personalizeUpdatedCode(json.updatedCodes);
                                            }
                                        } else if (json.newCodes) {
                                            personalizeNewCode(json.newCodes);
                                        }
                                    });
                                }
                            });

                            $('#ajax1').fadeOut('fast').html(json.shipping).fadeIn('fast');
                        }
                    });
                });
            } else if (json.multiple) {
                loadPersonalizeDiv(json.multiple);
            } else { //product page
                $('#personalize_div').hide();
                if(!$('#shopbymag_popup')){
                    $('#overlay').hide();
                }

                $('input[name=quantity]').val('');

                $.scrollTo('0', 1000);
            }
            if (json.tote) {
                toteRefresh(json.tote);
            }
        }, 'json');
    });

    // allows double clicking on some options rather than selecting and clicking next step
    $(".monogram_option_option, .design_style_option , .letter_style_option, .wrapper_style_option").livequery(function() {
        $(this).dblclick(function() {
        $("#next_step").click();
        });
    });

    // setup the next step button
    $("#next_step").livequery(function() {
        $(this).click(function() {
            var hash = $('#hash').val();
            var id = $('#id').val();
            var code = $('#code').val();

            if ($('#ps_personalize').length) {
                id = $('#ps_personalize #id').val();
                hash = $('#ps_personalize #hash').val();
                code = $('#ps_personalize #code').val();
            }

            
            var data = personalizeBuildData($(settings.personalizeElement));
            if(data) {
                // change buttons to loading image
                var prior = $('#navigation_buttons').html();

                // show loading image
                $('#navigation_buttons img').hide();
                $('#personalize-loading').show();

                $.post('/ajax/personalize', {id: id, code: code, hash: hash, data: JSON.stringify(data)}, function(json) {
                    if (json.error) {
                        $('#personalize_error').text(json.error).slideDown();
                        $('#personalize_div').height($('#personalize_div').height() + $('#personalize_error').height() + 10);
                        $('#navigation_buttons').html(prior);
                    } else {
                        loadPersonalizeDiv(json.html);
                        window.location.hash = json.hash;
                    }
                }, 'json');
            } else {
                $('#personalize_error').text(error).slideDown();
                $('#personalize_div').height($('#personalize_div').height() + $('#personalize_error').height() + 10);
            }


        });
    }, function() {
        $(this).unbind('click');
    });

    //previous step button
    $("#previous_step").livequery(function() {
        $(this).click(function() {
            // show loading image
            $('#navigation_buttons img').hide();
            $('#personalize-loading').show();

            $.post('/ajax/personalizePrevious', {id: $('#id').val(), previous: $('#previous').val(), code: $('#code').val(), hash: $('#hash').val()}, function(data) {
                loadPersonalizeDiv(data);
            });
        });
    });

    //detail popups
    $('.personalize_details').livequery(function() {
        var sel = '#personalize_popup';
        $(this).click(function() {
            var id = $(this).attr('id').replace('detail_', '');
            var icon = $(this);
            if (id == 'logo') {
                personalizePopupLogoOnly(icon);
            } else {
                popupImg = new Image();
                popupImg.src = '/images/personalization/alphabets/cropped/' + id.toLowerCase() + '.gif';
                popupImg.onload = function() {
                    $('#personalize_popup div').html(popupImg);
                    $(sel).css('top', icon.position().top + icon.height());
                    $(sel).css('left', icon.position().left - ((popupImg.width - icon.width()) / 2));
                    $(sel).hide().fadeIn('slow');
                }
            }
        });
        $(this).hover(function() {
            //handled by click instead
        }, function() {
            $(sel).fadeOut('slow');
        });
    });

    //logo popups
    $('#personalize_logos div').livequery(function() {
        var sel = '#personalize_popup';
        $(this).click(function() {
            var id = $(this).attr('id');
            var icon = $(this);
            popupImg = new Image();
            popupImg.src = '/images/personalization/alphabets/cropped/' + id.toLowerCase() + '.jpg';
            popupImg.onload = function() {
                $('#personalize_popup div').html(popupImg);
                $(sel).css('top', icon.position().top - popupImg.height - 40);
                $(sel).css('left', icon.position().left - ((popupImg.width - icon.width()) / 2) - 15);
                $(sel).hide().fadeIn('slow');
            }
        });
        $(this).hover(function() {
            //do nothing
        }, function() {
            $(sel).fadeOut('slow');
        });
    }, function() {
        $(this).unbind('mouseover').unbind('mouseout');
    });
    $('#engraving_text #personalize_logo_container').livequery(function()
    {
        $(this).hover(function()
        {
        }, function() {
            $('#logo_preview').fadeOut('slow');
            $('.piece_text, #piece_options').css('visibility', 'visible');
        });
    }, function()
    {
        $(this).unbind('mouseover').unbind('mouseout');
    });

    //breadcrumb navigation
    $('#breadcrumbs .active').livequery('click', function() {
        $.post('/ajax/personalizebreadcrumb', {id: $('#id').val(), phase: $(this).attr('id'), code: $('#code').val(), hash: $('#hash').val()}, function(json) {
            loadPersonalizeDiv(json.html);
            window.location.hash = json.hash;
        }, 'json');
    });

    //re-select menu choices
    $('.logo input[type=hidden], .swatch input[type=hidden]').livequery(function() {
        $(this).siblings('select').val($(this).val());
    });

    //edit from review
    $('.edit').livequery('click', function() {
        var itemNum = $(this).attr('id').replace('edit_', '');
        $.post('/ajax/personalizereviewedit', {id: $('#id').val(), itemNum: itemNum, code: $('#code').val(), hash: $('#hash').val()}, function(json) {
            loadPersonalizeDiv(json.html);
            window.location.hash = json.hash;
        }, 'json');
    });

    //adjust review window for scrollbars
    $('#review_scroll').livequery(function() {
        if ($(this).height() >= 400) {
            $(this).height($(this).css('max-height'));
            $(this).css('margin-top', '20px');
            $('.piece').each(function() {
                $(this).width($(this).width() - 10);
            });
            $(this).css('overflow', 'auto');
        }
    });

    //toggle "same settings"
    $('#piece_options .text_line').livequery('click', function() {
        var id = '#' + $(this).attr('id').replace('_wrapper', '');
        var box = id + '_box';
        if ($(id).val() == 1) {
            $(box).css('backgroundImage', box_off);
            $(id).val(0);
        } else {
            $(box).css('backgroundImage', box_on);
            $(id).val(1);
        }
    });

    //first piece text -> all pieces
    $('#same_pieces_wrapper').livequery('click', function() {
        var id = $('#same_pieces');
        var box = $('#same_pieces_box');
        if (id.val() == 1) {
            box.css('backgroundImage', box_off);
            id.val(0);
        } else {
            box.css('backgroundImage', box_on);
            id.val(1);
            personalizeCloneFirst();
        }
    });
    $('.piece_text input[type=text]').livequery('change', function() {
        var parent = $(this).parent().parent().parent().attr('id');
        var parentIndex = parent.split('_');
        parentIndex = parentIndex[parentIndex.length - 1];

        if (parentIndex == 0 && ($('#same_pieces').val() == 1)) {
            personalizeCloneFirst();
        } else {
            personalizeHasSameText();
        }
    });
    $('#same_pieces').livequery(function() {
        personalizeHasSameText();
    });

    //this set -> all sets
    $('#same_allitems_wrapper').livequery('click', function() {
        var qty = 1;
        var id = $('#same_allitems');
        var box = $('#same_allitems_box');
        if (id.val() == 1) {
            id.val(0);
            box.css('backgroundImage', box_off);
            if (itemNum != '') {
                $('#item_num').html(itemNum);
            } else {
                qty = $.trim($('#item_num').html()).substring(0, 1);
                $('#item_num').html('Item 1 of ' + qty);
            }
        } else {
            id.val(1);
            box.css('backgroundImage', box_on);
            itemNum = $.trim($('#item_num').html());
            qty = itemNum.substring(itemNum.length - 1);
            if (qty == '1')
                qty += ' item';
            else
                qty += ' items';
            $('#item_num').html(qty);
        }
    });
    $('#same_allitems').livequery(function() {
        itemNum = '';
        if ($(this).val() == 1) {
            $('#same_allitems_box').css('backgroundImage', box_on);
        }
    });

    //disable line 2 for restricted logos
    $('#personalize_div select.text_input').livequery(function() {
        personalizeApplyRestrictions($(this).children('option:selected'));
    });
    $('#personalize_div select.text_input').livequery('change', function() {
        personalizeApplyRestrictions($(this).children('option:selected'));
    });

    //close personalization
    $('#personalize_close').livequery('click', function() {
        $('#personalize_div').fadeOut();
        if(!$('#shopbymag_popup').length > 0){
            $('#overlay').fadeOut();
        }

    });

    //Ampersand Engraving Preview (for product 8534)
    $('#ampersand_text').livequery(function() {
        $(this).click(function() {
            $('#ampersand_preview_container').fadeIn('slow', function() {
              });
        });
    });

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

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

    $('#ampersand_close').livequery(function() {
        $(this).click(function() {
            $('#ampersand_preview_container').fadeOut('slow', function() {
            });
        });
    });

    //Image Enlargement for Invitation and RSVP's
    $('#image_preview_link').livequery(function() {
        $(this).click(function() {
            $('#image_preview_container').fadeIn('slow', function() {
            });
        });
    });

    $('#preview_close').livequery(function() {
        $(this).click(function() {
            $('#image_preview_container').fadeOut('slow', function() {
            });
        });
    });

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

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

    //Checkbox (yes/no) for important message acceptance on invites and rsvp's
    $('.checkbox_personalize').live('click',function() {
        if($('.checkbox_personalize').hasClass('checked_personalize')){
            $('.checkbox_personalize').removeClass('checked_personalize');
        }else{
            $('.checkbox_personalize').addClass('checked_personalize');
        }
    });
})(jQuery);

function personalizeBuildData(personalizeElement) {
    var selected = undefined;
    var data = undefined;
    var id = $('#id').val();
    var error = undefined;
    var index = 0;
    var swatch = null;
    var swatchSecond = null;
    var logo = undefined;
    var silhouette = undefined;

    //$('#personalize_error').text('');

    if ($('#silhouettes').length) {
        selected = true;
        var solo = '';
        var left = '';
        var right = '';
        var bubble = '';
        $('.silhouette_solo_option').each(function() {
            if ($(this).hasClass('letter_style_selected')) {
                solo = $(this).attr('id');
            }
        });
        $('.silhouette_left_option').each(function() {
            if ($(this).hasClass('letter_style_selected')) {
                left = $(this).attr('id');
            }
        });
        $('.silhouette_right_option').each(function() {
            if ($(this).hasClass('letter_style_selected')) {
                right = $(this).attr('id');
            }
        });
        $('.silhouette_bubble_option').each(function() {
            if ($(this).hasClass('letter_style_selected')) {
                bubble = $(this).attr('id');
            }
        });
        silhouette = {solo: solo, left: left, right: right, bubble: bubble};
        data = {paramName: "silhouette", silhouette: silhouette};
    }

    //letter, design, wrapper, sticker, swatch, monogram settings
    $('.letter_style_option, .design_style_option, .logo_option, .wrapper_style_option, .sticker_style_option, .swatch_option, .swatch_second_option, .monogram_color_option, .monogram_option_option').each(function() {
        if ($(this).hasClass('letter_style_selected')) {
            selected = true;
            if ($(this).hasClass('design_style_option')) {
                data = {paramName: "design", design: $(this).attr('id')};
            } else if ($(this).hasClass('wrapper_style_option')) {
                data = {paramName: "wrapper", wrapper: $(this).attr('id')};
            } else if ($(this).hasClass('sticker_style_option')) {
                data = {paramName: "sticker", sticker: $(this).attr('id')};
            } else if ($(this).hasClass('swatch_option')) {
                swatch = $(this).attr('id').replace('swatch_', '');
            } else if ($(this).hasClass('swatch_second_option')) {
                swatchSecond = $(this).attr('id').replace('swatch_second_', '');
            } else if ($(this).hasClass('monogram_color_option')) {
                data = {paramName: "monogramColor", monogramColor: $(this).attr('id')};
            } else if ($(this).hasClass('monogram_option_option')) {
                data = {paramName: "monogramOption", monogramOption: $(this).attr('id')};
            } else {
                data = {paramName: "style", style: $(this).attr('id')};
            }
        } else {
            error = 'You must select one of the styles.';
        }
    });

    /**
     * detects text section exists.
     * must follow swatch detection.
     * must precede all other detection so it can be easily overriden.
     * persists if only static text is present. (dropdowns and text fields are absent)
     */
    if ($('.text_line').length) {
        selected = true;
        switch ($('#type').val()) {
            case 'ribbons':
                data = {paramName: "text", swatch: swatch, sameAll: $('#same_allitems').val()};
                break;
            default:
                data = {paramName: "text", sameAll: 1};
        }
    }

    //logo settings
    if (personalizeElement.find('li.logo').length > 0) {
        selected = true;
        index = 0;
        logo = new Array();
        personalizeElement.find('li.logo select').each(function(i, item) {
            if ($(item).val() != 'no icon') {
                logo[index] = $(item).val();
                index++;
            }
        });
        data = {paramName: "logo", logo: logo, sameAll: $('#same_allitems').val(), type: $('#type').val()};
    }

    //multi-swatch settings
    if (personalizeElement.find('li.swatch').length > 0) {
        selected = true;
        swatch = new Array();
        personalizeElement.find('li.swatch select').each(function(i, item) {
            swatch[i] = $(item).val();
            index++;
        });
    }

    //text settings
    if (personalizeElement.find('input:text, select.list').size() > 0) {
        selected = true;
        index = 0;
        var text = new Array();
        personalizeElement.find('input:text, select.list').each(function() {
            var id = $(this).attr('name');
            //clear values for disabled elements
            if ($(this).attr('disabled')) {
                $(this).val('');
            }
            text[index] = id + '_' + $(this).val();
            index++;
        });

        switch ($('#type').val()) {
            //different text
            case 'candles':
                data = {paramName: "text", text: text, sameAll: $('#same_allitems').val()};
                break;
            //engraving with or w/o logo
            case 'engraving':
                if (logo === undefined) {
                    data = {paramName: "text", text: text, sameAll: $('#same_allitems').val()};
                } else {
                    data = {paramName: "text", text: text, logo: logo, sameAll: $('#same_allitems').val()};
                }
                break;
            //different text, with swatch
            case 'embroidery':
            case 'ribbons':
                data = {paramName: "text", text: text, swatch: swatch, sameAll: $('#same_allitems').val()};
                break;
            //same text, with swatch
            case 'bags':
            case 'napkins':
            case 'coffee':
            case 'chocolate_bars':
                data = {paramName: "text", text: text, swatch: swatch, swatchSecond: swatchSecond, sameAll: 1};
                break;
            case 'cards':
            	data = {paramName: "text", text: text, sameAll: 1, message: "true"};
            //same text
            default:
                data = {paramName: "text", text: text, sameAll: 1};
        }
    }

    //detect invite-rsvp important message
   
    if ($('#important_message').length > 0) {
    	try{
    		
    		if($('.checkbox_personalize').hasClass('checked_personalize')){
        		selected = true;
                data = {paramName: 'importantMessage'};
        	}else{
        		throw "The checkbox must be selected in order to continue with this personalization.";
        	}
    	}catch(error){
    		
    		if($('#personalize_error').text().length == ""){
    			$('#personalize_error').text(error).slideDown();
	    		$('#personalize_div').height($('#personalize_div').height() + $('#personalize_error').height() + 10);
	    		return false;
    		}
	    		
    	}
    }
   
    
    //detect preface
    if ($('#personalize_preface').length > 0) {
        selected = true;
        data = {paramName: 'preface'};
    }
    
    

    if (selected) {
        return data;
    } else {
        return false;
    }
};


