//
//  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 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
function updateQty(value, settings) {
	var aPos = pbShoppingTable.fnGetPosition( this );  // [ row, cell ]
	var aOldRow = pbShoppingTable.fnGetData( aPos[0] );
	var re = /\d+/;
	if (re.test($.trim(value)))
	{
		pbShoppingTable.fnUpdate( value, aPos[0], 2 );
		if (!value || $.trim(value) === "0") pbShoppingTable.fnDeleteRow( aPos[0] );
		sendListUpdate();
		return value;
	}
	return aOldRow[2];  // set back to old value
}

function postItemToSupplyList (itemid, redirect) {
	$.post(datasource, { "lang": $.nsl10n.baseLocale(), "item": itemid }, function(data){
		// success updating server
		if (redirect) window.location.href = redirect;
	}, "json");
}


function addEventHandlers () {
	$('.qty_col').editable( updateQty ,{tooltip: "Click to edit", submit: "OK"});
}
// Send the current data for item internal id and qty to server
function sendListUpdate () {
	var aoData = pbShoppingTable.fnGetData();
	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]);
	}
	$.post(datasource, { "lang": $.nsl10n.baseLocale(), "itemlist": srvData }, function(data){
		// success updating server
		addEventHandlers();   // in case we just added a row
	}, "json");
}

function fnGetSelected( oTableLocal )
{
	
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();

	for ( var i=0 ; i<aTrs.length ; i++ )
	{
		if ( $(aTrs[i]).hasClass('row_selected') )
		{
			aReturn.push( aTrs[i] );
		}
		
	}
	
	
	return aReturn;
	
	
}

function set_multi_input () {
	var m = '';
	var row;
	var anSelected;
	try{
		anSelected = fnGetSelected(pbShoppingTable);
		if(!anSelected.length) 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
function addToShoppingList() {
	var buyid = $.trim($('#buyid').val());
	if (!buyid) return;   // nothing to add
	var qty = $('#qty').val();
	//var qty = "<input type='text' value='"+$('#qty').val()+"'>";
	var item_num = $('#item_id').val();
	var add_to_cart ="<form name='" + "formadditem_" +buyid + "' action='/app/site/backend/additemtocart.nl?c=935369&buyid='"+buyid+"'"+ "&qty='"+qty+"'"+ "&id='additem' method='post'><span class='cart_button'><input type='button' value='Add' nsl10n='19' onkeypress='window.event.cancelBubble=true;' onclick='document.formadditem_"+buyid+".submit();' tabindex='4'></span></form>"; // Add to cart URL
	var delete_from_list ="<span class='cart_button'><input type='button' value='Delete' nsl10n='19' onkeypress='window.event.cancelBubble=true;' onclick='addToShoppingList();' tabindex='5'></span>";// Delete from List button

	var aoData = pbShoppingTable.fnGetData();
	var existingRow = -1;
	// just change quantity if item exists
	for (var i=0; i < aoData.length; i++) {
		if ($.trim(aoData[i][0]) == buyid)
		{
			pbShoppingTable.fnUpdate(qty, i, 2, false);
			existingRow = i;
		}
	}
	if (existingRow < 0)
	{
		// its a new item
		pbShoppingTable.fnAddData( [ buyid, item_num, qty, $('#storedisplayname').val(), $('#onlinecustomerprice').val(), add_to_cart, delete_from_list ], true);
	}
	sendListUpdate();
}

var dtLocaleSetting = $.nsl10n.baseLocale() + '&callback=?';

$(document).ready(function() {

	userid = $('#integration').html();
	datasource = "/app/site/hosting/scriptlet.nl?script=18&deploy=1&compid=935369&h=b96782cb641622de1efa&lead="+userid+"&lang="+$.nsl10n.baseLocale();
	
	if (userid) {
		pbShoppingTable  = $('#shopping_list').dataTable( {			
			"bPaginate": false,
			"bLengthChange": false,
			"bFilter": true,
			"bSort": true,
			"bInfo": false,
			"bAutoWidth": false,
			"bProcessing": true,
			"bStateSave": true,
			"iCookieDuration": 60*60*24*30,
			"sAjaxSource": datasource,
			"aoColumns": [
			/* Internal ID */   { "bVisible": false, "bSearchable": false, "sClass": "internalid" },
			/* Item num */  { },
			/* Quantity */ { "sClass": "qty_col" },
			/* Description */  { },
			/* Price */    { },
			/* Add to Cart */ {"sClass": "addtocart_col"},
			/* Delete from List */ {"sClass": "delete_col"},
			],
			"oLanguage" : { "sUrl" : "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=17&deploy=1&compid=935369&h=aa2a02e33f98de2c3732&group=datatable&lang="+dtLocaleSetting },
			"fnDrawCallback": function ( oSettings ) {
				addEventHandlers();
				set_multi_input();
			},
			"sDom": 'T<"clear">lfrtip',
			//"sSwfPath": "http://www.physabek.com/c.935369/site/swf/ZeroClipboard.swf",
			"oTableTools": {
						"sSwfPath": "http://shopping.netsuite.com/c.935369/site/swf/copy_cvs_xls_pdf.swf"
					}

		} );

		//Comment the Line Selected Feature
		
		/*
		$('#shopping_list tbody tr').live("click", function() {
			if ( $(this).hasClass('row_selected') )
			$(this).removeClass('row_selected');
			else
			$(this).addClass('row_selected');
			set_multi_input();
		} );
		*/
		
		
		$('#shopping_list tbody td').live("click", function() {
			if ( $(this).hasClass('delete_col') )
			{	
				var aPos = pbShoppingTable.fnGetPosition(this);				
				pbShoppingTable.fnDeleteRow(aPos[0]);
				
			}
			else
			{
				
			}
		
			set_multi_input();
		} );
		
		
		$('#shopping_list tbody td').live("click", function() {
			if ( $(this).hasClass('addtocart_col') )
			{	
				// process addto cart
				
			}
			else
			{
				
			}
		
		} );
		

	}
//	else  // user not logged in
//	{
//
//	}

	$('input[name=item_id]').autoComplete({
		ajax: '/app/site/hosting/scriptlet.nl?script=16&deploy=1&compid=935369&h=60226459e020eab3a325&displaykey=itemid',
		postVar: 'itemid',
		requestType: 'get',
		onSelect: function(event,ui){
			try
			{
				$('#buyid').val(ui.data.internalid);
				$('#onlinecustomerprice').val(ui.data.onlinecustomerprice);
				$('#storedisplayname').val(ui.data.storedisplayname);
			}
			catch(e)
			{
				// sloppy ignore, but we shouldn't see missing fields or data
			}
		},
		onBlur:function(e, ui){
			if(ui.val){
				$(ui.ul).find("li").filter(function(){ return $(this).text() == ui.val;}).eq(0).each(function(){
					try{
						var cache = $(this).data()['ac-data'];
						if(cache){
							$('#buyid').val(cache.internalid);
							$('#onlinecustomerprice').val(cache.onlinecustomerprice);
							$('#storedisplayname').val(cache.storedisplayname);
						}
					}catch(e) {
						if(window.console && window.console.log) console.log(e.message || e.toString());
					}

				});
			}
		}
	});

});


