/*
 ***********************************************************************
 *
 * The following javascript code is created by ERP Guru,
 * a NetSuite Partner. It is a SuiteFlex component containing custom code
 * intented for NetSuite (www.netsuite.com) and use the SuiteScript API.
 * The code is provided "as is": ERP Guru shall not be liable
 * for any damages arising out the intended use or if the code is modified
 * after delivery.
 *
 * Company      : ERP Guru
 * Author       : samanthara.som@erpguru.com
 * File         : ERP_CUE_ShoppingList.js
 * Dt. created  : December 23rd, 2010
 * Object       :
 *
 * Modified by  :
 * Dt. modified :
 * Reason       :
 *
 ***********************************************************************/

// 
//  shoppinglist.js
//  Project: Physabek
//  
//  Created by Blaine Horrocks on 2009-12-13.
//  Copyright 2009 - 2066795 Ontario Ltd. All rights reserved.
// 

//var SUPPLY_LIST_SUITELET = "/app/site/hosting/scriptlet.nl?script=18&deploy=1&compid=935369&h=b96782cb641622de1efa&lead=";
var SUPPLY_LIST_SUITELET = "/app/site/hosting/scriptlet.nl?script=21&deploy=1&compid=611072&h=6ed400a3858c18e5dfa3&lead=";

var pbShoppingTable;
var userid = 0;
var datasource; //url for the shoppling list handler, initialized after load

// Callout from completed quantity edit
// prior to data table update

// TO CHECK - but seems to work
function updateQty(value, settings){
	//console.log(value);
	//console.log(settings);
    var aPos = pbShoppingTable.fnGetPosition(this); // [ row, cell ]
    var aOldRow = pbShoppingTable.fnGetData(aPos[0]);
	//console.log(aPos);
	//console.log(aOldRow);
	
    var re = /\d+/;
    if (re.test($.trim(value))) {
        pbShoppingTable.fnUpdate(value, aPos[0], 2);
        if (value == 0 || $.trim(value) == "0"){
			pbShoppingTable.fnDeleteRow(aPos[0]);
		} 
		  
        sendListUpdate();
        return value;
    }
    return aOldRow[2]; // set back to old value
}

// CHECK
// le petit lien en dessous de litem pour rajouter a notre supply/shopping list? pas mal sur que oui

function postItemToSupplyList(itemid, redirect){
	// Show the right message according to the language
	switch($.nsl10n.baseLocale()){
		case 'fr' :
			alert("L'article sera ajout� � votre panier d'achat.");	
			break;
		case 'en' : 
		default :			
			alert('The item will be added to your Shopping List.');
	}
    
	$.post(datasource, {
        "lang": $.nsl10n.baseLocale(),
        //"lang": "en",
        "item": itemid
    }, function(data){
        // success updating server
		if (redirect){
			window.location.href = redirect;
		} 
            			
    }, "json");
}

// TO CHECK
function addEventHandlers(){
	// for the JQuery Datatable.
	
	// only the 'quantity' column is editable
    $('.qty_col').editable(updateQty, {
        tooltip: "Click to edit",
        submit: "OK"
    });
	
	$('.remove_col').bind('click', function(){
	    var aPos = pbShoppingTable.fnGetPosition(this); // [ row, cell ]
	    var aOldRow = pbShoppingTable.fnGetData(aPos[0]);
	    pbShoppingTable.fnUpdate(0, aPos[0], 2);
	    pbShoppingTable.fnDeleteRow(aPos[0]);
	          
	    sendListUpdate();
	});
	
	/*$('.add_col').bind('click', function(){
        $.post('/app/site/backend/additemtocart.nl', {
            "buyid":"multi", "multi":"3166,10"
        }, alert('The item was added to the shopping cart.'), "json");
    });*/
	$('.add_col').bind('click', function(){
        var aPos = pbShoppingTable.fnGetPosition(this); // [ row, cell ]
        var aData = pbShoppingTable.fnGetData( aPos[0] );
		// internal id column index - 0
		// qty column index - 2
		//prepare what I need to post
		var toSendToCart = aData[0] + ',' + aData[2];
		
		var alertMsg = '';
		switch($.nsl10n.baseLocale()){
			case 'fr' :
				alertMsg = "L'article sera ajout� � votre panier d'achat.";	
				break;
			case 'en' : 
			default :			
				alertMsg = 'The item will be added to your Shopping List.';
		}
		
		$.post('/app/site/backend/additemtocart.nl', {
            "buyid":"multi", "multi" : toSendToCart
            }, alert(alertMsg), "json");
        }
    );
}

//$(' :button[value|="Add to cart"]').unbind('click');
//$(' :button[value|="Add to cart"]').bind('click',
    


// Send the current data for item internal id and qty to server
// CHECKED
function sendListUpdate(){
    // do not panick when tracing aoData,
	// the data does not appear as you see it in the datatable in the web browser
	var aoData = pbShoppingTable.fnGetData();
    //console.log('aoData');
	//console.log(aoData);
	var srvData = aoData.length > 0 ? $.trim(aoData[0][0]) + ',' + $.trim(aoData[0][2]) : '';
    
	for (var j = 1; j < aoData.length; j++) {
        srvData += ';' + $.trim(aoData[j][0]) + ',' + $.trim(aoData[j][2]);
    }
    //console.log(srvData)
	// basically, srvData contains the items internal id + qty in your datatable
	// it will be in this format : "internalid,qty;internalid,qty;..." 
	
	// dans le fond, on fait juste poster ces informations la a la suitelet(datasource)
	// lang et itemlist sont les params que la suitelet va catcher
	$.post(datasource, {
        "lang": $.nsl10n.baseLocale(),
		//"lang": "en",
        "itemlist": srvData,
		"lead": $('#integration').html() // pogner le id du client courant :addition de sam
        }, function(data){
            // success updating server
            addEventHandlers(); // in case we just added a row
        }, 
		"json");
}

/**
 *
 * A function returns the current html row(in html)
 *
 * @author      : samanthara.som@erpguru.com
 * @version     : 1.0
 * @param       : oTableLocal{string:html}, the target html table
 * @return      : {string:html}, the selected row in html form
 *
 */
// TO CHECK
function fnGetSelected(oTableLocal){
    var aReturn = [];
    var aTrs = oTableLocal.fnGetNodes();
    
    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).hasClass('row_selected')) {
            aReturn.push(aTrs[i]);
        }
    }
    return aReturn;
}

// TO CHECK
function set_multi_input(){
    var m = '';
    var row;
    var anSelected;
    try {
        anSelected = fnGetSelected(pbShoppingTable);
		
        if (anSelected.length == 0){
			anSelected = pbShoppingTable.fnGetNodes();
		} 
            
        for (var i = 0; i < anSelected.length; i++) {
            row = pbShoppingTable.fnGetData(pbShoppingTable.fnGetPosition(anSelected[i]));
            m += row[0] + ',' + row[2] + ';';
        }
		
        m = m.substr(0, m.length - 1);
        document.addlisttocart.multi.value = m;
		
    } catch (e) {
        return false;
    }
    return true;
}


// called from quick order form to add to shopping list

// CHECKED

function addToShoppingList(){
	//console.log('add btn click - addToShoppingList() - begin');
	
    var buyid = $.trim($('#buyid').val());
	
    if (null == buyid || "" == buyid){
		//console.log('there is nothing to add, return false');
		return; // nothing to add
	} 
        
    var qty = $('#qty').val();
    var item_num = $('#item_id').val();
    //console.log('buyid : ' + buyid);
	//console.log('qty : ' + qty);
	//console.log('item_num : ' + item_num);
	
    var aoData = pbShoppingTable.fnGetData(); // get the data that is currently in the datatable
    //console.log('Currently in the datatable');
	//console.log(aoData);
	
    var existingRow = -1;
    // just change quantity if item exists
	
	//console.log('parse the datatable');
    for (var i = 0; i < aoData.length; i++) {
		// basically, we only update the line of the item
        if ($.trim(aoData[i][0]) == buyid) {
            pbShoppingTable.fnUpdate(qty, i, 2, false); // params order : qty, line, column, redraw table
            existingRow = i;
        }
    }
	
	// if we didn't find the line, we add the line
    if (existingRow < 0) {
        // its a new item
        //pbShoppingTable.fnAddData([buyid, item_num, qty, $('#storedisplayname').val(), $('#onlinecustomerprice').val(), '<input type="button" value="Add to cart"></input>', '<input type="button" value="Remove"></input>'], true);
		pbShoppingTable.fnAddData([buyid, item_num, qty, $('#storedisplayname').val(), $('#onlinecustomerprice').val(), '<input type="button" value="+" name="btnAddTocart"></input>', '<input type="button" value="-" name="btnRemoveFromShoppingList"></input>'], true);		
    }
	
    sendListUpdate();
	
	//console.log('add btn click - addToShoppingList() - end');
}

//var dtLocaleSetting = $.nsl10n.baseLocale() + '&callback=?';

/**
 *
 * This function JQuery handles the form 'ready' event. 
 *
 * @author      : samanthara.som@erpguru.com
 * @version     : 1.0
 *
 */
$(document).ready(function(){
    // pogner le user id de l'suager courant
    userid = $('#integration').html();
	//datasource = "/app/site/hosting/scriptlet.nl?script=18&deploy=1&compid=935369&h=b96782cb641622de1efa&lead=" + userid + "&lang="
    //datasource = SUPPLY_LIST_SUITELET + userid + "&lang=" + $.nsl10n.baseLocale();
    datasource = SUPPLY_LIST_SUITELET + userid + "&lang=" + $.nsl10n.baseLocale();
    
	if (userid) {
		// CHECKED
        pbShoppingTable = $('#shopping_list').dataTable({
            "bPaginate": false,
            "bLengthChange": false,
            "bFilter": true,
            "bSort": true,
            "bInfo": false,
            "bAutoWidth": false,
            "bProcessing": false,
            "bStateSave": true,
            "iCookieDuration": 60 * 60 * 24 * 30, /* 1 month */
            "sAjaxSource": datasource, //happens when we 'instanciate' the datatable :we load the current
            // user item(stored in the field on the entity record)
            "aoColumns": [            /* Internal ID */
                            {
                                "bVisible": false,
                                "bSearchable": false,
                                "sClass": "internalid"
                            },            /* Item num */
                            {
						   	"sWidth": "20%"
						    },            /* Quantity */
							{
                                "sClass": "qty_col"
                            },            /* Description */
                            {
						   	    
						   },            /* Price */
                           {
						   	    "sClass": "right"
						   },            /* test */
                           {
                                "sClass": "add_col"
                           },            /* test */
                           {
                                "sClass": "remove_col"
                           }],
            //"oLanguage": {
                //"sUrl": "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=17&deploy=1&compid=935369&h=aa2a02e33f98de2c3732&group=datatable&lang=" + dtLocaleSetting
			//	"sUrl": "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=17&deploy=1&compid=935369&h=aa2a02e33f98de2c3732&group=datatable&lang="
            //},
            "fnDrawCallback": function(oSettings){
                addEventHandlers();
                set_multi_input();
				$(':input[name=btnAddTocart]').parent().attr('align', 'center')
                $(':input[name=btnRemoveFromShoppingList]').parent().attr('align', 'center')
				
				$('.sorting').attr('style',"font-size:small"); // reduce the size of the header columns

            }
			,
            "sDom": 'T<"clear">lfrtip',
            "sSwfPath": "/site/swf/ZeroClipboard.swf"
        });
		
        // TO CHECK
        $('#shopping_list tbody tr').live("click", function(){
            if ($(this).hasClass('row_selected')){
				$(this).removeClass('row_selected');
			} else {
			    $(this).addClass('row_selected');	
			} 
            
            set_multi_input();
        });
        
    } else // user not logged in
    {
    
    }
    
	// CHECKED
	$('input[name=item_id]').autoComplete({
		ajax: '/app/site/hosting/scriptlet.nl?script=22&deploy=1&compid=611072&h=64502b6323f76fb86a90&displaykey=itemid'+ "&lang=" + $.nsl10n.baseLocale(),
		postVar: 'itemid',
        requestType: 'get',
        onSelect: function(event, ui){
        try {
			$('#buyid').val(ui.data.internalid);
            $('#onlinecustomerprice').val(ui.data.onlinecustomerprice);
            $('#storedisplayname').val(ui.data.display);
			//console.log('Item selected in the AutoComplete textbox : ');
			//console.log('internalid : ' + ui.data.internalid);
			//console.log('onlinecustomerprice : ' + ui.data.onlinecustomerprice);
			//console.log('storedisplayname : ' + ui.data.storedisplayname);
			//console.log('storedisplayname : ' + ui.data.longdisplayname);
			
        } catch (e) {
            // sloppy ignore, but we shouldn't see missing fields or data
        }
	   }
    });
});

