/**
 * Advanced, robust set of sales and support modules.
 * Extensions to OpenSales for SugarCRM
 * @package Advanced OpenSales for SugarCRM
 * @subpackage Products
 * @copyright SalesAgility Ltd http://www.salesagility.com
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author Greg Soper <greg.soper@salesagility.com>
 */

/**
 * Copy address right
 */
 var lineno;
 var itemLine = 0;
 var module = "AOS_Products"
 var uniqueProducts = [];
 
 
 function setModule(mod){
 	module = mod;
 }



function showItemHeader(bool){
    if(bool){
        $('#itemHeader').show();
            //document.getElementById("itemHeader").style.display="table-row";
    }else{
          $('#itemHeader').hide();
            //document.getElementById("itemHeader").style.display="none";
	}
}

/**
 * Insert item line
 */
 
function insertItemLine(ln){

    
    if(itemLine == 0){
	showItemHeader(true);
    }
    
    sqs_objects["item_name["+ln+"]"]=
    {
        "form":"EditView",
   	"method":"query",
   	"modules":["AOS_Products"],
   	"group":"or",
   	"field_list":["name","id"],
   	"populate_list":["item_name["+ln+"]","item_id["+ln+"]"],
   	"required_list":"item_id["+ln+"]",
   	"conditions":[{"name":"name","op":"like_custom","end":"%","value":""}],
   	"order":"name",
   	"limit":"30",
   	"no_match_text":"No Match"
    };
		
    
                
    var html='',
        idTr="item_line"+ln;
        
    html+='<tr id='+idTr+'><td class="dataField"></td><td></td><td class="dataField"></td></tr>'
    $("table#itemLine tr").last().after($(html));            
    
    $($("#"+idTr).children("td")[0]).html("<input class='sqsEnabled' autocomplete='on' type='text' name='item_name[" + ln + "]' id='item_name" + ln +"' size='16' maxlength='50' value='' title='' tabindex='116' value=''><input type='hidden' name='item_id[" + ln + "]' id='item_id" + ln + "' size='20' maxlength='50' value=''>");
    $($("#"+idTr).children("td")[1]).html("<button title='" + selectButtonTitle + "' accessKey='" + selectButtonKey + "' type='button' tabindex='116' class='button' value='" + selectButtonValue + "' name='btn1' onclick='openItemPopup(" + ln + ");'><img src='themes/default/images/id-ff-select.png' alt='" + selectButtonValue + "'></button>");
    $($("#"+idTr).children("td")[2]).html("<input type='hidden' name='item_deleted[]' id='item_deleted" + ln + "' value='0'><input type='hidden' name='itemKit_id[]' value=''><button type='button'  class='button deleteKit' value='" + deleteButtonValue + "' tabindex='116' onclick='markItemLineDeleted("+ln+")'><img src='themes/default/images/id-ff-clear.png' alt='" + deleteButtonValue + "'></button><br>");
        
    enableQS(true);
    ln++;
    itemLine++;

    $("#addItemLine").get(0).onclick = function(){
       insertItemLine(ln); 
    }
    
    
}

/**
 * Delete product line
 */
function deleteItemLine(ln)
{
	var obj = ln.parentNode.parentNode.rowIndex;
        
	document.getElementById('productLine').deleteRow(obj);
	// delete product note line
	//document.getElementById('productLine').deleteRow(obj);
	// calculate product line total
	//calculateProductLineTotal();
	itemLine--;
	
	if(itemLine == 0)
	{
		showItemHeader(false);
	}
}

/**
 * Mark product line deleted
 */
function markItemLineDeleted(ln){
	// collapse product line; update deleted value
        $('#item_line'+ln).hide();
        $('#item_deleted'+ln).val("1");
	itemLine--;
	if(itemLine == 0){
            showItemHeader(false);
	}
}

/**
 * Open product popup
 */
function openItemPopup(ln){
    
    /*if (document.getElementById('producto_grupo_c').value==""){
        alert("La linea selecionada no tiene un grupos asignado");
        return false;
    }*/
    
    lineno=ln;
	var popupRequestData = {
		"call_back_function" : "setProductReturn",
		"form_name" : "EditView",
		"field_to_name_array" : {
			"id" : "item_id" + ln,
			"name" : "item_name" + ln
		}
	};
        open_popup('AOS_Products', 800, 850, '', true, true, popupRequestData);
	//open_popup('AOS_Products', 800, 850, '&grupo='+ document.getElementById('producto_grupo_c').value, true, true, popupRequestData);

}

/**
 * The reply data must be a JSON array structured with the following information:
 *  1) form name to populate
 *  2) associative array of input names to values for populating the form
 */
var fromPopupReturn  = false;

function validarCaracteristicaPadre (valor){
    var cant=document.getElementsByName("cara_padre[]").length;
    if(cant==0){
        return 1;
    }
    var contador=0;
    for(var i=0;i<cant;i++){
        if(document.getElementById("cara_padre"+i).value==valor && document.getElementById("cara_deleted"+i).value==0){
             contador++;
        } 
    }
    return contador;
}

function setProductReturn(popupReplyData)
{
	fromPopupReturn = true;
        
	var formName = popupReplyData.form_name;
	var nameToValueArray = popupReplyData.name_to_value_array;
        var index=0;
	var i=0;
	for (var theKey in nameToValueArray)
	{
		if(theKey == 'toJSON')
		{
			/* just ignore */
		}
		else
		{
                    
                      
                        
                        
                        
                        
                        var displayValue = nameToValueArray[theKey].replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');;
                        
                        if(theKey.split(/(\d+)/g)[0]=='item_id'){
                            if (uniqueProducts.indexOf(displayValue) < 0) {
                                uniqueProducts.push(displayValue);
                            }
                            else{
                                return false;
                            }
                        }
                        $("#"+theKey).val(displayValue);
                        
                        //index=theKey.substring(theKey.length-1);
                        /*if(i==2){
                            if(validarCaracteristicaPadre(displayValue)>1){
                                document.getElementById("cara_id"+index).value="";
                                document.getElementById("cara_name"+index).value="";
                                document.getElementById("cara_padre"+index).value="";
                                //markProductLineDeleted(theKey.substring(theKey.length-1))
                            }
                        }*/
		}
                i++
	}
}
