﻿var ideaBoard = {
    init: function() {
        //if cookis not empty then load name and email
        if (g.cookie.get('name') != '' && g.cookie.get('email') != '') {
            $('#txtebName').val(g.cookie.get('name'));
            $('#txtebEmail').val(g.cookie.get('email'));
        }
        $('.ideaBar .barTitle').text(ss.msg(299));
        $('ul.jd_menu').jdMenu();

        $('.ideaBoard .mnuInventory').click(function() {
            //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Inventory');
            if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Inventory']);
            //var x = prompt(ss.msg(314), 0);
            $('#lblInventory').text(ss.msg(314));
            //ideaBoard.inventory(x);
        });

        $('#btnCheckIdeaInventory').click(function() {
            ideaBoard.inventory(Number($('#txtInventory').val()));
            $('#winIdeaInventory').dialog('close');
        });

        $('#txtInventory').keyup(function(e) {
            if (e.keyCode == 13) {
                ideaBoard.inventory(Number($('#txtInventory').val()));
                $('#winIdeaInventory').dialog('close');
            }
        });

        $('.ideaBoard .mnuEmail').click(function() {
            $('#btnSendBoard').unbind('click');
            $('#btnSendBoard').click(function() {
                $('#btnSendBoard').disable();
                $.post('/ideaboard/saveBoard', {}, function(data) {
                    if (data != 0) {
                        //save email and name to cookie
                        g.cookie.setg('name', $('#txtebName').val(), 365);
                        g.cookie.setg('email', $('#txtebEmail').val(), 365);
                        var v = '&name=' + $('#txtebName').val();
                        v += '&email=' + $('#txtebEmail').val();
                        v += '&rname=' + $('#txtebRName').val();
                        v += '&remail=' + $('#txtebREmail').val();
                        v += '&cc=' + ($('#txtebCC').val() || "");
                        v += '&msg=' + $('#txtebMsg').val();
                        v += '&loc=' + ss.core.get.loc();
                        v += '&lang=' + ss.lang.get.current();
                        v += '&guid=' + data;
                        $.post('/util/emailIdeaBoard/', v, function() {
                            $('#btnSendBoard').enable();
                            $('#winEmailBoard').dialog('close');
                            //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Email');
                            if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Email']);
                        });
                    } else { alert(ss.msg(298)); $('#btnSendBoard').enable(); }
                });
            });
        });
        $('.ideaBoard .mnuBookmark').click(function() {
            $('#overlay').show();
            $.post('/ideaboard/saveBoard', {}, function(guid) {
                $('#overlay').hide();
                if (guid != 0) {
                    var href = 'http://' + (ss.lang.get.current() == 'fr-ca' ? 'fr' : ss.core.get.loc()) + '.' + sl.biz.domain + '/catalog/view/' + (ss.lang.get.current() == 'fr-ca' ? 'Nouveaux-Produits' : 'New-Products') + '/all/pg1' + '?ideaBoard=' + guid;
                    g.fav.add(href, 'Starline Idea Board');
                    //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Bookmark');
                    if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Bookmark']);
                } else { alert(ss.msg(298)) }
            });
        });
        $('.ideaBoard .mnuLink').click(function() {
            $('#overlay').show();
            $.post('/ideaboard/saveBoard', {}, function(guid) {
                $('#overlay').hide();
                if (guid != 0) {
                    $('#winLink').dialog({ autoOpen: false, resizable: false, modal: true, width: 500, height: 295 });
                    $('.ui-dialog').wrap('<div class="silver-theme win"></div>');
                    $('#winLink').dialog('open');
                    $('.ui-widget-overlay').wrap('<div class="silver-theme win"></div>');
                    var href1 = 'http://' + (ss.lang.get.current() == 'fr-ca' ? 'fr' : ss.core.get.loc()) + '.' + sl.biz.domain + '/catalog/view/' + (ss.lang.get.current() == 'fr-ca' ? 'Nouveaux-Produits' : 'New-Products') + '/all/pg1' + '?ideaBoard=' + guid;
                    var href2 = 'http://' + (ss.lang.get.current() == 'fr-ca' ? 'fr' : ss.core.get.loc()) + '.' + sl.biz.domain + '/ideaBoard/view/' + guid;
                    $('#winLink a.link1').attr('href', href1).text(href1);
                    $('#winLink a.link2').attr('href', href2).text(href2);
                    $('#winLink div.msgLink1').text(ss.msg(301));
                    $('#winLink div.msgLink2').text(ss.msg(302));

                    $('#bookmark1').click(function() {
                        g.fav.add(href1, 'Starline Idea Board');
                    });
                    $('#bookmark2').click(function() {
                        g.fav.add(href2, 'Starline Idea Board');
                    });

                    //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Link');
                    if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Link']);
                } else { alert(ss.msg(298)) }
            });
        });
        $('.ideaBoard .mnuPdf').click(function() {
            $('#overlay').show();
            $.post('/ideaboard/saveBoard', {}, function(guid) {
                $('#overlay').hide();
                if (guid != 0) {
                    var href = 'http://' + (ss.lang.get.current() == 'fr-ca' ? 'fr' : ss.core.get.loc()) + '.' + sl.biz.domain + '/ideaBoard/view/' + guid + '?pdf=1';
                    window.open(href);
                    //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Pdf');
                    if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Pdf']);
                } else { alert(ss.msg(298)) }
            });
        });

        function orderSample(res) {
            //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Sample');
            if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Sample']);
            var args = 'lang=' + ss.lang.get.current() + '&ideas=';

            $('.ideaBoard .prodImg').each(function(i) {
                var itemNo = $(this).closest('.product-cell').find('.itemNo').text();
                var color = /\d+_(\d+)\.jpg$/.exec($(this).attr('src'));
                color = color != null ? color[1] : 0;
                if (i == 0) args += itemNo + '|' + color;
                else args += '*' + itemNo + '|' + color;
            });

            g.log(args);


            $.get('/util/addIdeasToCart/?' + args, function() {
                if (res != false) window.location = '/view/page/cform/secure/cart';
            });

            if (res == false) {
                $('.loading').show();
                $.get('/view/content/cform/quicklogin', function(html) {
                    $('.loading').hide();
                    ss.core.customRedirect = '/view/page/cform/secure/cart';
                    $('#winIdeaLogin').html(html);
                    g.init.exec();
                });
            } else { $('#winLogin').remove(); }
        }

        $('.ideaBoard .mnuOrderSamples').click(function() {
            ss.core.is.loggedIn(orderSample);
        });
        $('.ideaBoard .mnuQuickPick').click(function() {
            function createQP() {
                var codes = '';
                $('.ideaBoard .productCode').each(function(i) {
                    if (i <= 7) {
                        if (i == 0) codes += $(this).text();
                        else codes += '*' + $(this).text();
                    }
                });
                //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'QuickPick');
                if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'QuickPick']);
                var url = 'http://www.starlinequickpick.com/default.aspx?from=' + ss.core.get.loc() + '&lang=' + ss.lang.get.current() + '&pid=' + codes;
                window.open(url);
            }
            if (ideaBoard.item.array.length > 7) {
                if (confirm(ss.msg(297))) {
                    createQP();
                }
            } else {
                createQP();
            }
        });
        $('.ideaBoard .mnuClear').click(function() {
            ideaBoard.clear();
        });
        $('#ideaBoard .mnuRefresh').click(function() {
            ideaBoard.fill();
        });
        ideaBoard.grid = new ss.ui.productGrid('#grdIdeas', 0, 3, 'ib');
        ideaBoard.item.array = new Array();

        if (cx.arg.ideaBoard != null) {

            function msg(res) {
                $('#btnAppendBoard').click(function() {
                    $('.ideaBoard input').disable();
                    $('#overlay').show();
                    $.post('/ideaboard/appendBoardToBuffer?guid=' + cx.arg.ideaBoard, {}, function() {
                        $('#overlay').hide();
                        $('.ideaBoard input').enable()
                        $('#winLoadBoard').dialog('close');
                        $('.ideaBar').click();
                        $('.emptyBoard').hide();
                    });
                });
                if (res) {
                    $('#winLoadBoard').dialog({ autoOpen: false, resizable: false, width: 500, height: 75 });
                    $('.ui-dialog').wrap('<div class="silver-theme win"></div>');
                    $('#winLoadBoard').dialog('open');
                    $('.ui-widget-overlay').wrap('<div class="silver-theme win"></div>');

                    $('#btnReplaceBoard').click(function() {
                        $('.ideaBoard input').disable();
                        ideaBoard.clear(function() {
                            $('#overlay').show();
                            $.post('/ideaboard/appendBoardToBuffer?guid=' + cx.arg.ideaBoard, {}, function() {
                                $('#overlay').hide();
                                $('.ideaBoard input').enable()
                                $('#winLoadBoard').dialog('close');
                                $('.ideaBar').click();
                                $('.emptyBoard').hide();
                            });
                        });
                    });
                } else {
                    $.post('/ideaboard/appendBoardToBuffer?guid=' + cx.arg.ideaBoard, {}, function() {
                        $('#winLoadBoard').dialog('close');
                        $('.ideaBar').click();
                        $('.emptyBoard').hide();
                    });
                }
            }

            ideaBoard.full(msg);
        } else {
            ideaBoard.fill();
        }
    },
    rowHeight: 300,
    bind: function() {
        if (cx.ua.intranet) ideaBoard.inventory();

        $('.addIdea').unbind('click');
        $('.addIdea').click(function() {
            //change if ss.ui.productCell changes
            var img = $(this).prev().prev().find('.prodImg');
            var idea = img.clone();
            $('body').prepend(idea);
            idea.css({ 'border': 'solid black 1px' });
            idea.css('top', (img.offset().top - img.height()) + 'px').css('left', img.offset().left + 'px');
            idea.css('position', 'absolute').css('z-index', 3000).animate({
                top: ($('.ideaBar span').offset().top) + 'px',
                left: ($('.ideaBar span').offset().left) + 'px'
            }, 1000
            ).animate({
                width: '0px', height: '0px'
            }, 250, 'linear', function() {
                idea.remove();
                var itemNo = $(img).closest('.product-cell').find('.itemNo').text();
                var color = /\d+_(\d+)\.jpg$/.exec($(img).attr('src'));
                color = color != null ? color[1] : 0;
                var closeout = false;
                if ($(img).closest('.product-cell').find('a[href]').attr('href').indexOf('_') >= 0) closeout = true;
                ideaBoard.item.add(itemNo, color, closeout);
                //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Add', itemNo);
                if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Add', itemNo]);
            });

        });


        $('.addPPIdea').unbind('click');
        $('.addPPIdea').click(function() {
            var color = 0;
            var closeout = false;
            if (product.closeout >= 0) {
                closeout = true;
                color = product.closeout;
            }
            ideaBoard.item.add(product.itemNo, color, closeout);
            //if (pageTracker) pageTracker._trackEvent('IdeaBoard', 'Add', product.itemNo);
            if (_gaq) _gaq.push(['_trackEvent', 'IdeaBoard', 'Add', product.itemNo]);
            alert(ss.msg(308));
        });

        $('.ideaBar').unbind('click');
        $('.ideaBar').toggle(function() {
            $('.ideaBoard').css('top', ($(this).offset().top + $(this).height()) + 'px');
            $('.ideaBoard').css('left', $(this).offset().left + 'px');
            ideaBoard.open();
        }, function() {
            ideaBoard.close();
        });
    },
    inventory: function(x) {
        var selector = '';
        var invFilter = 0;
        var prefix = '';

        if (x) {
            selector = '#grdIdeas .prodImg';
            invFilter = x;
            if (isNaN(invFilter)) invFilter = 0;
            prefix = 'is_';
        } else {
            selector = '.prodImg';
            invFilter = $('#txtInvFilter').val();
            prefix = 'tn_';
        }

        g.log(invFilter);
        
        $.each($(selector), function() {
            if (invFilter > 0) {
                $(this).attr('src', $(this).attr('src').replace('tn_', prefix));
                ss.data.inventory($(this).attr('itemno'), $(this).attr('color'), function(itemNo, color, inv, ele) {
                    if (isNaN(inv)) inv = 0;
                    if ($(this) && Number(inv) < invFilter) {
                        //g.log('itemNo=' + itemNo + ' color=' + color + ' inv=' + inv);
                        $(ele).attr('src', $(ele).attr('src').replace(prefix, 'gs_'));
                    } else {
                        $(ele).attr('src', $(ele).attr('src').replace('gs_', prefix));
                    }
                }, this);
            } else {
                $(this).attr('src', $(this).attr('src').replace(prefix, 'tn_'));
            }
        });

    },
    open: function() {
        if (ideaBoard.item.array.length > 0) $('.emptyBoard').hide();
        $('.ideaBar .barTitle').text(ss.msg(300));
        $('.ideaBar div').css('background', "url('/content/image/closeIdeaBar.gif')");
        var h = ideaBoard.grid.rows * ideaBoard.rowHeight
        if (ideaBoard.item.array.length == 0) h = 75;
        $('.ideaBoard').show().animate(
            { height: h + 'px' }, 700
        , 'linear', function() { ideaBoard.fill(); });
    },
    close: function() {
        $('.ideaBar .barTitle').text(ss.msg(299));
        $('.ideaBar div').css('background', "url('/content/image/openIdeaBar.gif')");
        $('#grdIdeas .product-cell').draggable('destroy');
        $("#grdIdeas .product-cell").droppable('destroy');
        $('.ideaBoard').animate(
            { height: '0px' }, 700, 'linear', function() { $('.ideaBoard').hide(); }
        );
    },
    clear: function(fn) {
        ideaBoard.grid.clear();
        $.post('/ideaboard/clear', {}, function() {
            if (fn) fn();
        });
    },
    full: function(fn) {
        $.post('/ideaboard/isBufferFull', {}, function(res) {
            if (fn) fn(eval(res));
        });
    },
    save: function() {

    },
    item: {
        add: function(itemNo, color, closeout) {
            $.post('/ideaboard/addidea?itemNo=' + itemNo + '&color=' + color + '&closeout=' + closeout, {}, function() {
                ideaBoard.fill();
            }, 'json');
        },
        remove: function(i) {

        },
        array: []
    },
    fill: function(fn) {
        $.post('/ideaboard/getbuffer', {}, function(data) {
            ideaBoard.item.array = data.ideas;
            var arr = ideaBoard.item.array;
            $('.ideaBar .boardTotal').text('(' + arr.length + ')');
            ideaBoard.grid = new ss.ui.productGrid('#grdIdeas', Math.ceil(arr.length / ideaBoard.grid.cols), ideaBoard.grid.cols, 'ib');

            for (var i = 0; i < arr.length; i++) {
                ideaBoard.grid.fillCell(i, ss.ui.productCell(arr[i].itemNo, arr[i].code, arr[i].name, arr[i].price, arr[i].priceCode, '', arr[i].color == 0 ? '' : '_' + arr[i].color, arr[i].closeout));
            }
            $('#grdIdeas .addIdea').hide();
            $('#grdIdeas .removeIdea').show();
            if (arr.length > 0) {
                $('.emptyBoard').hide();
                var h = ideaBoard.grid.rows * ideaBoard.rowHeight
                if ($('.ideaBoard').css('height') != '0px') $('.ideaBoard').css('height', h + 'px');
            } else {
                $('.emptyBoard').show();
            }

            $('.removeIdea').unbind('click');
            $('.removeIdea').click(function() {
                //change if ss.ui.productCell changes
                var img = $(this).prev().prev().prev().find('.prodImg');
                var itemNo = $(img).closest('.product-cell').find('.itemNo').text();
                var color = /\d+_(\d+)\.jpg$/.exec($(img).attr('src'));
                color = color != null ? color[1] : 0;
                $(this).closest('.product-cell').html('');
                $.post('/ideaboard/removeidea?itemNo=' + itemNo + '&color=' + color, {}, function() {
                    ideaBoard.fill();
                }, 'json');
            });


            $('#grdIdeas .product-cell').unbind('hover');
            $('#grdIdeas .product-cell').hover(function() {
                $(this).css({ 'border-color': 'black' });

            }, function() {
                $(this).css({ 'border-color': 'white' });
            });

            $('#grdIdeas .product-cell').draggable({ zIndex: 2000, revert: true });
            $("#grdIdeas .product-cell").droppable({
                drop: function(event, ui) {
                    var itemNo = $(ui.draggable).find('.itemNo').text();
                    var color = /\d+_(\d+)\.jpg$/.exec($(ui.draggable).find('.prodImg').attr('src'));
                    color = color != null ? color[1] : 0;
                    var itemNo2 = $(this).find('.itemNo').text();
                    var color2 = /\d+_(\d+)\.jpg$/.exec($(this).find('.prodImg').attr('src'));
                    color2 = color2 != null ? color2[1] : 0;

                    g.log('itemNo=' + itemNo);
                    g.log('color=' + color);
                    g.log('itemNo2=' + itemNo2);
                    g.log('color2=' + color2);

                    var dragHtml = $(ui.draggable).html();
                    var dropHtml = $(this).html();
                    $(this).html(dragHtml);
                    $(ui.draggable).html(dropHtml);

                    $.post('/ideaboard/swapIdeaSeq?itemNo=' + itemNo + '&color=' + color + '&itemNo2=' + itemNo2 + '&color2=' + color2, {}, function(data) {
                        if (eval(data) == false) alert('error occured in swaping items.');
                    });

                    //g.log($(ui.draggable).closest('td').attr('id') + ' dropped on ' + $(this).closest('td').attr('id'));
                }
            });
            if (cx.ua.intranet && (Number($('#txtInventory').val()) < 1)) ideaBoard.inventory();
            else ideaBoard.inventory(Number($('#txtInventory').val()));

            if (fn) fn();
        }, 'json');

    },
    grid: {}
}
