
(function($) {

    $.fn.monogram = function(func, id) {

        // build main options before element iteration
        //var opts = $.extend({}, $.fn.monogram.defaults, options);
        var prodInfo;
        var mgChar;


        if (id) { $.fn.monogram.prodInfo = eval("json" + id); }


        switch (func) {
            case "init":
                init();
                return false;
            case "open":
                openMonogram();
                return false;
            case 'close':
                closeMonogram();
                return false;
            case 'reset':
                resetMonogram();
                return false;
            default:
                return false;
        }


        return;
    };

    function init() {
        $(".monogramDialog-holder .btn-cancel").click(function() {
            $(".monogramDialog-holder").monogram("close");
            //alert("close");
            resetMonogram()
            return false;
        });

        $(".monogramDialog-holder .txtMonogramChar").keyup(function(e) {
            $(this).val($(this).val().toUpperCase());
            $.fn.monogram.mgChar = $(this).val();

            if ((e.keyCode == 8) || (e.keyCode == 46)) {
                //delete key is pressed
                $(this).siblings(".error").text("");
                changeMonogramLetter("");
            } else if (e.keyCode == 16) {
                //shift key pressed
                return;
            } else if (((e.keyCode >= 65) && (e.keyCode <= 90)) || (e.keyCode == 32)) {
                $(this).siblings(".error").text("");
                changeMonogramLetter($.fn.monogram.mgChar);
            } else {
                // show error message

                $(this).siblings(".error").text("Please enter a letter");
                changeMonogramLetter("");
                $(this).val("");
            }
        }).focus(function() {
            $(this).val("");
        });


        $(".monogramDialog-holder .mg-letterThumb .mg-ltTh").not(".mg-ltTh-").each(function() {
            var $this = $(this);

            /*$this.hover(function() {

                changeMonogramLetter($(this).text());

            },
            function() {

                
            changeMonogramLetter("");

            }) */
            $this.click(function() {
                changeMonogramLetter($(this).text());


            });




        });

        $(".btn-saveMonogram").click(function() {

            saveMonogram();
            return false;
        });

        if (($.browser.msie) && ($.browser.version == 6)) {

            $(".monogramDialog-holder").bgiframe({ opacity: false });

        };

    };

    function changeMonogramLetter(ch) {
        $.fn.monogram.mgChar = ch;
        if (ch == "") {

            $("dl .mg-ltZm").removeClass().addClass("mg-ltZm").addClass("mg-ltZm-").text("");
            $(".mg-ProductPreview .mgPreview-ltTh").removeClass().addClass("mgPreview-ltTh mg-ltTh-").text("");
            $(".mg-ProductPreview .mgPreview-ltZm").removeClass().addClass("mgPreview-ltZm mg-ltZm-").text("");

        } else {

            $("dl .mg-ltZm").removeClass().addClass("mg-ltZm").addClass("mg-ltZm-" + ch).text(ch);
            $(".mg-ProductPreview .mgPreview-ltTh").removeClass().addClass("mgPreview-ltTh mg-ltTh-" + ch).text(ch);
            $(".mg-ProductPreview .mgPreview-ltZm").removeClass().addClass("mgPreview-ltZm mg-ltZm-" + ch).text(ch);
            $(".txtMonogramChar").val(ch);

        }


    };

    function saveMonogram() {
        var _sku = $.fn.monogram.prodInfo["sku"];

        // check input
        if ($.fn.monogram.mgChar == "") {


            // letter not entered
            $(".txtMonogramChar").siblings(".error").text("Please enter a letter");


        } else {

            // save to hidden variable for product
            $(".hiddenMonogram" + _sku).val($.fn.monogram.mgChar);
            //var _tmpaddToBagMonogramInput = $(".addToBagMonogramInput").val();
            //$(".addToBagMonogramInput").val(_tmpaddToBagMonogramInput + _sku + "|" + $.fn.monogram.mgChar + ",");


            var mgdetailsHolder = $(".mg-details" + _sku);
            var mgdetails = mgdetailsHolder.find(".mg-details");

            mgdetails.find(".mgLetter").text($.fn.monogram.mgChar);

            // close Monogram dialog box
            closeMonogram();

            //switch produt detail to display mongram selection
            $(".prod-addMonogram" + _sku).hide();
            mgdetails.show();
            mgdetailsHolder.find(".btn-editMonogram,.btn-removeMonogram").show();
            mgdetailsHolder.find(".btn-addMonogram").hide();

            // bind events to edit and remove
            mgdetailsHolder.find(".btn-editMonogram").click(function() {

                $(".monogramDialog-holder").monogram("open", $(this).attr("rel"));
                return false;

            });

            mgdetailsHolder.find(".btn-removeMonogram").click(function() {

                $(".monogramDialog-holder").monogram("reset", $(this).attr("rel"));
                return false;

            });
        }





        return false;

    }


    function resetMonogram() {
        var _sku = $.fn.monogram.prodInfo["sku"];
        var mgdetailsHolder = $(".mg-details" + _sku);
        var mgdetails = mgdetailsHolder.find(".mg-details");

        // clear to hidden variable for product
        $(".hiddenMonogram" + _sku).val("");
        //$(".addToBagMonogramInput").val("");

        //switch produt detail to display mongram selection
        mgdetails.hide();
        mgdetailsHolder.find(".btn-editMonogram:visible,.btn-removeMonogram:visible").hide();
        mgdetailsHolder.find(".btn-addMonogram:hidden").show();

    }

    function setupMgDialog() {
        var obj = $.fn.monogram.prodInfo;
        var _sku = obj["sku"];
        var _prodtype = obj["prodtype"].toLowerCase().replace(" ", "");
        var _hex = obj["hex"].toLowerCase().replace(" ", "").split(",");
        var _specialInst = obj["specialInstructionCode"].split(",");
        var _fontface = obj["fontface"] = _specialInst[0].toLowerCase();
        var _fontcolor = obj["fontcolor"] = _specialInst[2].toLowerCase();

        // populate product info
        $(".mg-options .prod-title").text(obj["prodTitle"]);

        // grab product info from drop down
        var _sizeText = ($(".size" + _sku + " option:selected").length > 0) ? $(".size" + _sku + " option:selected").text() : $(".size" + _sku).text();
        $(".mg-options .prod-info-size").text("Size: " + _sizeText);

        var _colorText = ($(".color" + _sku + " option:selected").length > 0) ? $(".color" + _sku + " option:selected").text() : $(".color" + _sku).text();
        $(".mg-options .prod-info-color").text("Color: " + _colorText);

        $(".mg-options .prod-info-quant").text("Quantity: " + $(".quant" + _sku + " option:selected").text());


        // change preview sketches
        $(".mg-ProductPreview").removeClass().addClass(_prodtype + " mg-ProductPreview");

        //console.log(_hex);
        _hex = (_hex.length > 1) ? ("0x" + _hex[0] + "0x" + _hex[1]) : "0x" + _hex;

        $(".mg-ProductPreview .mg-preview").css('backgroundImage', 'url(/images/monogram/' + _prodtype + 'Overview_' + _hex + '.jpg)');
        $(".mg-ProductPreview .mg-zoom").css('backgroundImage', 'url(/images/monogram/' + _prodtype + 'Zoom_' + _hex + '.jpg)');

        // change monogram
        if (($.browser.msie) && ($.browser.version == 6)) {

            $(".mg-ProductPreview .mgPreview-ltTh").css('backgroundImage', 'url(/images/monogram/monogramChart_' + _fontface + '_' + _fontcolor + '.gif)');
            $(".mg-ProductPreview .mgPreview-ltZm").css('backgroundImage', 'url(/images/monogram/monogramChart_' + _fontface + '_' + _fontcolor + '.gif)');


        } else {
            $(".mg-ProductPreview .mgPreview-ltTh").css('backgroundImage', 'url(/images/monogram/monogramChart_' + _fontface + '_' + _fontcolor + '.png)');
            $(".mg-ProductPreview .mgPreview-ltZm").css('backgroundImage', 'url(/images/monogram/monogramChart_' + _fontface + '_' + _fontcolor + '.png)');
        };

        //change swatches
        $(".mg-swatch").removeClass().addClass("mg-swatch swatch-" + _fontcolor);
        $(".mg-swatch").text("Color: " + $(".mg-details" + _sku + " .mgColor").text());

    }


    function openMonogram() {

        setupMgDialog();
        changeMonogramLetter($(".hiddenMonogram" + $.fn.monogram.prodInfo["sku"]).val());



        $("body").append('<div class="mgBlocker"></div>');
        $(".mgBlocker").css({ 'height': $(document).height() });
        var tmp = $(".monogramDialog-holder").clone(true);
        $("body").append(tmp);
        $(".monogramDialog-holder:last").show();
        $(".mgBlocker").show();



        return false;
    };


    function closeMonogram() {

        $.fn.monogram.prodInfo = "";
        $.fn.monogram.mgChar = "";
        $(".txtMonogramChar").val("");
        //$(".mgBlocker").remove();
        $(".monogramDialog-holder:last").hide().remove();
        $(".mgBlocker").remove();

        return false;
    };

    $.fn.monogram.defaults = {};

})(jQuery);

$(document).ready(function() {
    //$(".btn-addMonogram").monogram($(this).attr("rel"));

    $().monogram("init");
    $(".btn-addMonogram").each(function() {
        $(this).click(function() {

            // error check - make sure a quantity is selected
            // error check - make sure a quantity is selected
            var _selectHolder;
            var skus;
            var quants;
            var hasColorOrSize = false;
            var hasQuantity = false;

            if ($(this).parents(".suite-prod-info").length > 0) {
                //if suite
                _selectHolder = $(this).parents(".suite-prod-info"); //.find(".prod-controls");

            } else {
                _selectHolder = $(this).parents("#content"); //.find(".prod-controls");
            }
            
            skus = _selectHolder.find('.hiddensku');
            quants = _selectHolder.find('.hiddenquant');

           
            if (skus.val().split("|")[1] != 0) {
                hasColorOrSize = true;
                if (quants.val() != "") {
                    if (quants.val() > 0)
                        hasQuantity = true;
                }
            }

            if (!hasColorOrSize) {
                alert("Please select a color or size for at least one item");
            }
            else if (!hasQuantity) {
                alert("Please select a quantity of 1 or greater for at least one item");
            }
            else if (hasQuantity && hasColorOrSize) {
                $(".monogramDialog-holder").monogram("open", $(this).attr("rel"));
            }


            return false;
        });

    });



});
