var priceList;
$(document).ready(function(){
    var catalog = new Array();
    catalog["Fiyat ve Numune Talepleri"] = {'tr': "Fiyat ve Numune Talepleri",
                                            'en': "Price and Sample Demands",
                                            'fr': "Demandes de prix et d’échantillon",
                                            'ru': "Цена и образцы" };

    catalog["Lütfen uzunluk değerini giriniz."] = {'tr': "Lütfen uzunluk değerini giriniz.",
                                                   'en': "Please enter length value",
                                                   'fr': "S.V.P entrez la valeur de longueur",
                                                   'ru': "Пожалуйста, введите  меру длины" };
    catalog["Lütfen renk kodunu giriniz."] = {'tr': "Lütfen renk kodunu giriniz.",
                                              'en': "Please enter color code",
                                              'fr': "S.V.P entrez le code de couleur",
                                              'ru': "Пожалуйста, введите  код цвета" };
    catalog["Uzunluk olarak sadece sayı giriniz."] = {'tr': "Uzunluk olarak sadece sayı giriniz.",
                                                      'en': "Only enter number for length",
                                                      'fr': "Pour la longueur écrivez seulement en nombre",
                                                      'ru': "Введите длину" };
    catalog["Renk kodunu bilmiyorsanız karteladan seçiniz."] = {'tr': "Renk kodunu bilmiyorsanız karteladan seçiniz.",
                                                                'en': "If you don't know the color code, Please use the swatch card",
                                                                'fr': "Si vous ne connaissez pas le code de couleur utilisez la carte d’échantillon pour choisir",
                                                                'ru': "Если Вы не знаете код цвета, выберите из палитры" };
    catalog["Sil"] = {'tr' : "Sil",
                      'en' : "Remove",
                      'fr' : "Supprimer",
                      'ru' : "Удалить"};
                                                                
function gettext(msg){
    return catalog[msg][window.lang_code];
}
    var modal_width = 500;
    if(window.lang_code == "fr")modal_width=620;
    priceList = {
        setup: function(appendTo, logName, msgOpacity) {
            $('#priceList').dialog({modal: true, 
                                autoOpen : false,
                                resizable : false,
                                draggable : false,
                                width: modal_width,
                                title : gettext("Fiyat ve Numune Talepleri"),
                                open: function(event, ui){
                                    $('.ui-widget-overlay').click(priceList.hide)
                                },
                                beforeclose: function(event, ui){
                                    $('.ui-widget-overlay').unbind('click', priceList.hide);
                                    if(priceList.length > 0){
                                        $('#sideLink').show();
                                    }
                                    else{
                                        $('#sideLink').hide();
                                    }
                                }
                               }
            );
            priceList.length = 0;
            priceList.table = $('#priceTable');
            priceList.obj = $.JSONCookie("nazik_pricelist");
            for (var i in priceList.obj){
                var seriNo = /^(.+)_\d+$/.exec(i)[1];
                var newItem = $('<tr></tr>').append('<td class="serino">'+seriNo+'</td>').
                                             append('<td class="qty">'+priceList.obj[i].qty+'</td>').
                                             append('<td class="colorcode">'+priceList.obj[i].color+'</td>').
                                             append('<td class="del">\
                                                <a id ="'+i+'" onclick="priceList.removePrice(this);return false;">'+gettext("Sil")+'</a></td>');
                priceList.table.append(newItem);
                priceList.length++;
            }
            if(priceList.length > 0){
                $('#sideLink').show();
            }
            else{
                $('#sideLink').hide();
            }
        },
        show: function(){
            $('#priceList').dialog('open');
        },
        hide: function(){
            $('div.ui-dialog').fadeOut(200);
            setTimeout(function(){$('#priceList').dialog('close');}, 200);
        },
        _insertData: function (seriNo, qty, colorCode){
            //determine id
            var id = seriNo + "_0"; //first try serino
            var i = 0;
            while( priceList.obj[id] ){
                i = i + 1;
                id = seriNo + "_" + i;
            }
            //while broke! heres our unique id
            priceList.obj[id] = {'qty' : qty, 'color': colorCode};
            return id; //we'll use this precious id
        },
        _removeData: function (id){
            delete priceList.obj[id];
        },
        addPrice: function (seriNo, qty, colorCode){
            //prepare data
            var id = priceList._insertData(seriNo, qty, colorCode);
            $.JSONCookie("nazik_pricelist", priceList.obj, {path: '/'});
            
            //show our stuff
            priceList.show();
            var newItem = $('<tr class="item"></tr>').append('<td class="serino">'+seriNo+'</td>').
                                         append('<td class="qty">'+qty+'</td>').
                                         append('<td class="colorcode">'+colorCode+'</td>').
                                         append('<td class="del"><a id ="'+id+'" onclick="priceList.removePrice(this);return false;">'+gettext("Sil")+'</a></td>');
            priceList.table.append(newItem);
            color = newItem.css('color');
            newItem.animate({color:"#FFCC11"}, 1000);
            setTimeout(function(){newItem.animate({color:color})}, 1000);
            priceList.length++;
            return false;
        },
        removePrice: function (elem){
            $(elem).attr('onclick', '');//defensive for double click
            
            //behind the scenes
            priceList._removeData($(elem).attr('id'));
            $.JSONCookie("nazik_pricelist", priceList.obj, {path: '/'});
            //html show
            $(elem).parents('tr').fadeOut('slow', function() { $(this).remove();});
            priceList.length--;
            if(priceList.length == 0){
                priceList.hide();
            }
            return false;
        },
        reset: function(){
            $.JSONCookie("nazik_pricelist", {}, {path: '/'});
            priceList.obj = {};
            priceList.table.find('tr.item').remove();
            priceList.length=0;
            priceList.hide();
        }
    };
    priceList.setup();
    $('#price-tabs').tabs();
    
    $('#sideLink a').click(function(){
        priceList.show();
        return false;
    });
    
    $('a.addPriceReq').click(function(){
        var serino = $(this).siblings('h1').text();
        var qty = $('input#qty').val();
        var color = $('input#colorcode').val();
        if(qty==""){
            humanMsg.displayMsg(gettext("Lütfen uzunluk değerini giriniz."));
            $('input#qty').focus();
            return false;
        }
        if(color==""){
            humanMsg.displayMsg(gettext("Lütfen renk kodunu giriniz."));
            $('input#colorcode').focus();
            return false;
        }
        priceList.addPrice(serino, qty, color);
        return false;
    });
    
    $('#priceRequestForm').submit(function(){
        $('#priceRequestSubmit').after('<img id="formLoading" src="/static/images/loading2.gif" style="vertical-align:middle;margin-left:10px;" />')
        $.post('/urunler/fiyat-istek/', $(this).serialize(), function(data){
                                                                $('#priceRequestForm').html(data);
                                                             }, "html");
        return false;
    });
    
    $('#qty').keyup(function(){
        var d=$(this).attr('numeric');
        var value=$(this).val();
        var orignalValue=value;
        val= value.replace(/[0-9]*/g, "");
       	
       	var msg= gettext("Uzunluk olarak sadece sayı giriniz.");
        
        if (val!=''){
            orignalValue=orignalValue.replace(/([^0-9].*)/g, "")
            $(this).val(orignalValue);
            humanMsg.displayMsg(msg);
        }
    });
    
    $('#colorcode').keyup(function(){
        var d=$(this).attr('numeric');
        var value=$(this).val();
        var orignalValue=value;
        val= value.replace(/[0-9]*/g, "");
       	
       	var msg= gettext("Renk kodunu bilmiyorsanız karteladan seçiniz."); 
        
        if (val!=''){
            orignalValue=orignalValue.replace(/([^0-9].*)/g, "")
            $(this).val(orignalValue);
            humanMsg.displayMsg(msg);
        }
    });
});
