var WarehousesLabels = {
    setStockAsQty: false,
    stockFieldExp: 'qty_',
    editIndex: undefined,
    
    init: function (url)
    {
        this.url = url;
        this.initCaptureEvent('sku_1',true);
        this.initCaptureLabels();
    },
    
    initCaptureEvent: function(elem_id,getVendor){
        jQuery("#" + elem_id).on('keypress', function(e) {
            var code = e.keyCode || e.which;
            if(code == 13) { //Enter keycode
                WarehousesLabels.keyupEvent(elem_id, getVendor);
            }
        });
    },
    
    initCaptureLabels: function(){  
        jQuery('#qty_1').on('keypress', function(e){
            var code = e.keyCode || e.which;
            if(code == 13) { //Enter keycode
            	WarehousesLabels.addRowToTable();
                $("sku_1").focus();
            }                
        });        
    },
    
    keyupEvent: function(elem_id, getVendor){
        init_vendor = '';
        if(getVendor) {
            if ($('warehouse_request')) {
                var my_vendor = $('warehouse_request').value;
            } else {
                var my_vendor = $('warehouse_peticion').value;   
            }
            if (my_vendor != '-1' && my_vendor != '1')
            {
                var aux = my_vendor.split('_');
                my_vendor = aux[1];
            }
            if ($$('select[name=filter_vendor_id]').length > 0)
            {
                init_vendor = $$('select[name=filter_vendor_id]')[0].get('value');
            }
        } else {
            var my_vendor = '1';   
        }
                    
        var aux = elem_id.split('_');
        
        if (init_vendor) {
            my_vendor = init_vendor;
        }
        
        xajax_vmAdminWarehousesAjax.searchBySkuLabels($(elem_id).value, aux[1], my_vendor,$('prod_asigned').value);
    },
    
    addLabelsProduct: function (product_id, name, tipo, grupo, qty, product_code, ean, ident)
    {
        jQuery('#sname_' + ident).combobox('reset');
        jQuery('#sname_' + ident).combobox('setValue',ean);
        jQuery('#sname_' + ident).combobox('setText',name);

        jQuery("#tipo_" + ident).val(tipo);
        jQuery("#grupo_" + ident).val(grupo);
        jQuery("#producto_" + ident).val(product_id);
        jQuery("#qty_" + ident).val(qty);
        
        jQuery('#sname_' + ident).combobox('reset');
        jQuery('#sname_' + ident).combobox('setValue',ean);
        jQuery('#sname_' + ident).combobox('setText',name);

        jQuery("#tipo_1").val(tipo);
        jQuery("#grupo_1").val(grupo);
        jQuery("#producto_1").val(product_id);
        jQuery("#qty_1").val(qty);

        // jQuery("#real_stock").focus();
        // this.addRowToTable();
        jQuery("#qty_1").focus();
    },
    
    clearSearchSku: function() {
        // jQuery('#sku_1').textbox('setText','');
        // jQuery('#sku_1').textbox('setValue','');
    },

    preProccessFormToSubmit: function() {
        var rows = jQuery('#table_labels').datagrid('getRows');
        
        jQuery('#hidden_fields').html('');
        
        $('current_lines').value = '';

        jQuery.each(rows, function (index, value) {
        	var indexAux = (index+2);
        	$('current_lines').value += ($('current_lines').value == '' ? indexAux : ('~'+indexAux) ); 
            jQuery('#hidden_fields').append('<input type="hidden" name="grupo_' + indexAux + '" id="grupo_' + indexAux + '" value="' + value.group_id + '" />');
            jQuery('#hidden_fields').append('<input type="hidden" name="producto_' + indexAux + '" id="producto_' + indexAux + '" value="' + value.product_id + '" />');
            jQuery('#hidden_fields').append('<input type="hidden" name="tipo_' + indexAux + '" id="tipo_' + indexAux + '" value="' + value.tipo + '" />');
            jQuery('#hidden_fields').append('<input type="hidden" name="qty_' + indexAux + '" id="qty_' + indexAux + '" value="' + value.qty + '" />');
            jQuery('#hidden_fields').append('<input type="hidden" name="sname_' + indexAux + '" id="sname_' + indexAux + '" value="' + value.product_name + '" />');
            jQuery('#hidden_fields').append('<input type="hidden" name="sku_' + indexAux + '" id="sku_' + indexAux + '" value="' + value.product_ean + '" />');
        });
    },
    
    addRowToTable: function() {
    	var ident = jQuery("#producto_1").val() + '_' + jQuery("#grupo_1").val();
    	var ind = jQuery('#table_labels').datagrid('getRowIndex', ident);
    	
    	if (ind >= 0) {
    		var currentRow = jQuery('#table_labels').datagrid('getRows')[ind];
    		var newQty = parseFloat(currentRow.qty) + parseFloat(jQuery("#qty_1").val());
    		currentRow.qty = newQty;
    		jQuery('#table_labels').datagrid('updateRow',{
    			index: ind,
    			row: currentRow
    		});
    	} else {
            var newRow = {
                    ck: 0,
                    product_ean: jQuery('#sku_1').val(),
                    product_name: jQuery('#sname_1').combobox('getText'),
                    qty: jQuery("#qty_1").val(),
                    tipo: jQuery("#tipo_1").val(),
                    product_id: jQuery("#producto_1").val(),
                    group_id: jQuery("#grupo_1").val(),
                    ident: jQuery("#producto_1").val() + '_' + jQuery("#grupo_1").val()
                };
            
            jQuery('#table_labels').datagrid('insertRow', {
                index: 0,
                row: newRow
            });
    	}
        
        jQuery('#sku_1').val('');

        jQuery('#sname_1').combobox('setText','');
        jQuery('#sname_1').combobox('setValue','');
        jQuery('#sname_1').combobox('clear');
        jQuery('#sname_1').combobox('reload');
        
        jQuery("#tipo_1").val('');
        jQuery("#grupo_1").val('');
        jQuery("#producto_1").val('');
        jQuery("#qty_1").val('1');

        $('sku_1').focus();
    },
    
    numberFormat: function (value,row,index){
        var cellContent = '<div style="display: inline-flex;">';

        if (row.qty == '') {
            cellContent += '';
        } else {
	        if (row.tipoventa == "1"){
	            cellContent += row.qty;
	        } else {
            	cellContent += parseInt(row.qty);
	        }
	        
	        cellContent += '&nbsp;<span class="ui-icon ui-icon-pencil"></span>';
        }
        
        cellContent += '</div>';
        
        return cellContent;
    },
    
    onClickCell: function(indice, field){
        if (field == 'qty') {
            if (this.editIndex != indice) {
                if (this.endEditing()){
                    var editingRow = jQuery('#table_labels').datagrid('getRows')[indice];

                    jQuery('#table_labels').datagrid('selectRow', indice)
                            .datagrid('beginEdit', indice);
                            
                    var ed = jQuery('#table_labels').datagrid('getEditor', {index:indice, field:'qty'});
                    var tx = jQuery(ed.target);
                    if (editingRow.tipoventa == "1") {
                        tx.numberbox({precision: 3});    
                    } else {
                        tx.numberbox({precision: 0});
                    }
                    
                    tx.textbox('textbox').focus();
                    
                    var that = this;
                    tx.textbox('textbox').on('keydown', function(e){
                        if (e.keyCode == 13){    // when press ENTER key, accept the inputed value.
                            tx.textbox('setValue', jQuery(this).val());
                            that.endEditing();
                        }
                    });
                    
                    this.editIndex = indice;
                }
            }
        } else {
            if (this.editIndex != indice) {
            	this.endEditing();
            }
        }
    },
    
    endEditing: function(){
        if (this.editIndex == undefined){return true;}

        var dg = jQuery('#table_labels');
        if (dg.datagrid('validateRow', this.editIndex)){
            // jQuery('#table_order').datagrid('acceptChanges');
            dg.datagrid('endEdit', this.editIndex);
			this.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    },
    
    removeLabelLines: function()
    {
    	var dg = jQuery('#table_labels');
    
        var rowsToRemove = dg.datagrid('getChecked');
        
        if(rowsToRemove.length == 0) {
            alert('Debe seleccionar alguna fila para borrar.');
        } else {
            var rowsToRemoveIdents = rowsToRemove.map(function(val) {
	              	return { ident: val.ident, producto: val.producto, grupo: val.grupo };
	          	});

            var ids = [];
            for (var i = 0;i < rowsToRemove.length;i++) {
                var row = rowsToRemove[i];
                var index = dg.datagrid('getRowIndex', row);
                
                // dg.datagrid('deleteRow', index);
                ids.push(index);
            }
            
            // ids.sort();
            ids.sort(function (a, b) {  return a > b ? 1 : a < b ? -1 : 0;  }); // sort index
            ids.reverse();  // sort reverse
            for(var i=0; i<ids.length; i++){
            	dg.datagrid('deleteRow',ids[i]);
            }
        	
            dg.datagrid('clearChecked');
            dg.datagrid('acceptChanges');
        }
    },
    
    showModel: function()
    {
        $('select_cell').style.display = "block";
        $('select_cell').style.visibility = "visible";

        var old_cell = $('coord_cell').value;
        var old_row = $('coord_row').value;
        $('coord_cell').value = '';
        $('coord_row').value = '';
        if ($('model_small').checked || $('model_03052').checked || $('model_03052_attrib').checked) {
            $('table_small').style.display = "block";
            $('table_big').style.display = "none";
        	$('table_small').style.visibility = "visible";
            $('table_big').style.visibility = "hidden";
            if (old_cell != '' && old_row != '')
                $('bcell_'+old_row+old_cell).className = '';

            $('labels_form_model_image_div').style.display = "block";
            $('labels_form_model_image_div').style.visibility = "visible";
            
            var imgChecked = "";
            if ($('model_small').checked) {
            	imgChecked = "model_small";
            } else if ($('model_03052').checked) {
            	imgChecked = "model_03052";
            } else if ($('model_03052_attrib').checked) {
            	imgChecked = "model_03052_attrib";
            }
            $('labels_form_model_image_img').src = "/administrator/components/com_virtuemart/assets/images/barcodes/"+imgChecked+".png";
        }
        
        if($('model_big').checked) {
            $('table_big').style.display = "block";
            $('table_small').style.display = "none";
            $('table_big').style.visibility = "visible";
            $('table_small').style.visibility = "hidden";
            if (old_cell != '' && old_row != '')
                $('scell_'+old_row+old_cell).className = '';
            
            $('labels_form_model_image_div').style.display = "block";
            $('labels_form_model_image_div').style.visibility = "visible";
            $('labels_form_model_image_img').src = "/administrator/components/com_virtuemart/assets/images/barcodes/model_big.png";
        }
        
        try {
            if($('model_label').checked || $('model_label2').checked || $('model_label3').checked || $('model_label4').checked || $('model_label5').checked || $('model_label6').checked || $('model_label7').checked){
            	/*
                $('table_big').style.display = "none";
                $('table_small').style.display = "none";
                $('select_cell').style.display = "none";
                $('labels_form_model_image_div').style.display = "none";
                */
                $('table_big').style.visibility = "hidden";
                $('table_small').style.visibility = "hidden";
                $('select_cell').style.visibility = "hidden";
                $('labels_form_model_image_div').style.visibility = "hidden";
                $('labels_form_model_image_img').src = "";
                
                if (old_cell != '' && old_row != '')
                    $('bcell_'+old_row+old_cell).className = '';
                
                if (old_cell != '' && old_row != '')
                    $('scell_'+old_row+old_cell).className = '';
            }
        } catch (exc) {
        	// console.log(exc);
        }
    },
        
    setCell: function(prex,row,col)
    {
        $$('.selProducto').each(function(el){
            el.className = '';
        });
        
        /*var old_cell = $('coord_cell').value;
        var old_row = $('coord_row').value;
        
    
        
        if (old_cell != '' && old_row != '')
        {
            if ($(prex+old_row+old_cell))
                $(prex+old_row+old_cell).className = '';
        }*/
        //$(prex+row+col).addClass('selProducto');
        
        if (prex == 'bcell_')
        {
              lastcol = 3;
        }
        if (prex == 'scell_')
        {
              lastcol = 2;
        }

        for (var i = 1; i<= row; i++)
        {
            for (var j = 1 ; j<= lastcol; j++)
            {
                if (i == row && j == col)
                    break;
                $(prex+i+j).addClass('selProducto');
            }
        }
        
        $('coord_cell').value = col;
        $('coord_row').value = row;
    },
    
    selectProducts: function(form,selectType)
    {
        if(selectType == 'sku') {
            var lines = $('current_lines').value.split('~');
            if (lines.length) {
                for (var i = 0; i < lines.length; i++) {
                    if ($('sku_'+lines[i]) && ($('sku_'+lines[i]).value != '')) {
                    	return true;
                    }
            	}
            	return false;
            } else {
            	return false;
            }
        }
    },
};