//this function fires on the search button event and updates info on the grid

function refreshInfo(){
	var companyNameToLookFor = '';
	if($('#hdStoreLocationCode').length)
	{	
		
			companyNameToLookFor = $("#txtStoreLocation").val();
			$('.spanResults').each(function()
				{$('.spanResults').html("Results for " + companyNameToLookFor)}
			);
		
	}
	jQuery("#gridResults").setGridParam({ page:1 });
	jQuery("#gridResults").trigger("reloadGrid");
	}

//this function fires on the call back method for the function refreshing the grid.
//it updates the pager info (records per page, pagers, page number, etc).
function refreshPagers(){
var page  = jQuery("#gridResults").getGridParam("page");var totalRecords  = jQuery("#gridResults").getGridParam("records");var showingRecords = jQuery("#gridResults").getGridParam("rowNum");var startRecord = ((page-1)*showingRecords)+1;var endRecord = ((page)*showingRecords);
if(endRecord > totalRecords){endRecord = totalRecords;}
if(totalRecords == 0){$(".trResults").hide();$(".trNoResults").show();}
else{$(".trResults").show();$(".trNoResults").hide();}
$("#spStartRecord").html(startRecord);
$("#spEndRecord").html(endRecord);
$("#spTotalRecods").html(totalRecords);}

//this function is used to post data to another url.
//it requires a div with id vt_passer to exist on the page
function sendDataNoAjax(url,dataArray)
{var formDeclaration = '<form id="vt_frm_passer" action="'+url+'" method="post">';
for(var k = 0; k < dataArray.length; k++)
{formDeclaration = formDeclaration + '<input type="hidden" name="'+dataArray[k].name+'" value="'+dataArray[k].value+'" />';}
formDeclaration = formDeclaration + '</form>';$("#vt_passer").html(formDeclaration);$("#vt_frm_passer").submit();}

//this function is used to post data to another url.
//it requires a div with id vt_passer to exist on the page. It opens on a new window. 
//this function is used by the reports
function sendDataNoAjaxPopUp(url,dataArray){
var formDeclaration = '<form id="vt_frm_passer" action="'+url+'" method="post" target="_blank">';
for(var k = 0; k < dataArray.length; k++)
{formDeclaration = formDeclaration + '<input type="hidden" name="'+dataArray[k].name+'" value="'+dataArray[k].value+'" />';}
formDeclaration = formDeclaration + '</form>';$("#vt_passer").html(formDeclaration);$("#vt_frm_passer").submit();}

//this function initializes all common controls on every page.
function startAllControls(){
	
	
		//set current company on the results grid
		var companyNameToLookFor = '';
		if($('#hdStoreLocationCode').length)
		{	
			
				companyNameToLookFor = $("#txtStoreLocation").val();
				$('.spanResults').each(function()
					{$('.spanResults').html("Results for " + companyNameToLookFor)}
				);
			
		}

	 	$(".datepicker").mask("99/99/9999");
	 	
		//menu functionality to hover round border effects
		$('#menuFirst').mouseover(function(){
		 $('.cv_left_off').css({ backgroundImage : "url(../images/left_gray.gif)" });
		 });
	 	$('#menuFirst').mouseout(function(){
			 $('.cv_left_off').css({ backgroundImage : "url(../images/bt_main/off/left_gray_off.gif)" });
			 });
	 	$('#menuLast').mouseover(function(){
			 $('.cv_right_off').css({ backgroundImage : "url(../images/right_gray.gif)" });
			 });
		$('#menuLast').mouseout(function(){
			$('.cv_right_off').css({ backgroundImage : "url(../images/bt_main/off/right_blue_off.gif)" });
		});
		
		//submenu functionality to hover round border effects
		$('#subMenuFirst').mouseover(function(){
		 $('.cv_left').css({ backgroundImage : "url(../images/submenu_hover_left.gif)" });
		 });
	 	$('#subMenuFirst').mouseout(function(){
			 $('.cv_left').css({ backgroundImage : "url(../css/"+theme+"/images/submenu2_left.gif)" });
			 });
	 	$('#subMenuLast').mouseover(function(){
			 $('.cv_right').css({ backgroundImage : "url(../images/submenu_hover_right.gif)" });
			 });
		$('#subMenuLast').mouseout(function(){
			$('.cv_right').css({ backgroundImage : "url(../css/"+theme+"/images/submenu2_right.gif)" });
		});
	
		//allow entering of only numbers into the numeric class textfields
	 	$('.numeric').numeric();
	
	 	//prevent weird inputs on the alphanumeric textboxes

	 	$('.alphanumeric').alphanumeric({allow:"., -@¿?/#:'&¡!"});
	
		//start datepickers
	 		$(".datepicker").removeClass('hasDatepicker').datepicker({
		   	showOn: 'button', 
		   	buttonImage: '../css/'+theme+'/images/ico_calendar.gif',
		   	buttonImageOnly: true,
		   	buttonText: 'Select Date',
		   	beforeShow: function() { 
		   			$("#ui-datepicker-div").css("z-index", $(this).parents(".ui-dialog").css("z-index")+1); 
   				} 
		   	});
	 	
//	 	$(".datepicker").datepicker({showOn: 'button', buttonImage: '../css/'+theme+'/images/ico_calendar.gif', buttonImageOnly: true});
	
		//input an interval of five days into the date form fields that ends with DateFrom and DateTo
	 	$("input[id$='DateFrom']:text").each(function(i) {
				if(this.value == '')
	 	 		{
			 	 	vt_dateFrom = new Date();
					vt_dateFrom.setDate(vt_dateFrom.getDate() - 5);
					var month = (vt_dateFrom.getMonth()+1).toString();
					var day = (vt_dateFrom.getDate()).toString();
					if(month.length==1)
						month="0"+month;
					if(day.length==1)
						day="0"+day;
					this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
	 	 		}
		});
	 	
		$("input[id$='DateTo']:text").each(function(i) {
			if(this.value == '')
 	 		{
				vt_dateFrom = new Date();
				var month = (vt_dateFrom.getMonth()+1).toString();
				var day = (vt_dateFrom.getDate()).toString();
				if(month.length==1)
					month="0"+month;
				if(day.length==1)
					day="0"+day;
				this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
 	 		}
		});
		
		$("input[id$='Date2From']:text").each(function(i) {
			if(this.value == '')
 	 		{
		 	 	vt_dateFrom = new Date();
				vt_dateFrom.setDate(vt_dateFrom.getDate() - 3);
				var month = (vt_dateFrom.getMonth()+1).toString();
				var day = (vt_dateFrom.getDate()).toString();
				if(month.length==1)
					month="0"+month;
				if(day.length==1)
					day="0"+day;
				this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
 	 		}
		});
		
		//input an interval of 365 days into the date form fields that ends with YearFrom and DateTo
		$("input[id$='YearFrom']:text").each(function(i) {
			vt_dateFrom = new Date();
			vt_dateFrom.setDate(vt_dateFrom.getDate() - 365);
			var month = (vt_dateFrom.getMonth()+1).toString();
			var day = (vt_dateFrom.getDate()).toString();
			if(month.length==1)
				month="0"+month;
			if(day.length==1)
				day="0"+day;
			this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
		});
		//input an interval of 30 days into the date form fields that ends with MonthFrom and DateTo
		$("input[id$='MonthFrom']:text").each(function(i) {
			vt_dateFrom = new Date();
			vt_dateFrom.setDate(vt_dateFrom.getDate() - 30);
			var month = (vt_dateFrom.getMonth()+1).toString();
			var day = (vt_dateFrom.getDate()).toString();
			if(month.length==1)
				month="0"+month;
			if(day.length==1)
				day="0"+day;
			this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
		});
		
		//link the function to retrieve data from the server to the TD Export to Excel
		$(".tdExportToExcel").click(function(i) {
			getExcelFile();
		});
		
		//set the store location button to show the div
		$('#btnShowStoreLocation').click(function(){
				showStoreLocationDialog(true,false,false,'AEL');
	     });
		
		
		//set the store location button to show the div
		$('#btnShowStoreLocationJa').click(function(){
				showStoreLocationDialog(false,false,false,'JA');
	     });
		
		//set the store location button to show the div
		$('#btnShowStoreLocationClearance').click(function(){
				showStoreLocationDialog(false,false,true,'CLEARANCE');
	     });
		
		//set the handling button to show the div
		$('#btnShowHandling').click(function(){
				showHandlingDialog();
			 });
		
		//display urgent notifications
		for(var k = 0; k < urgentNotifications.length; k++)
		{
			showUrgentNotification(urgentNotifications[k]);
		}
		//display urgent notifications
		for(var k = 0; k < normalNotifications.length; k++)
		{
			showNormalNotification(normalNotifications[k]);
		}
		
		
		//set the filter form the key press event for the enter key
		$("form[name='filter_form']").bind("keypress", function(e)
		{
				try {
					if(!e){ 
					     e = window.event; 
					} 
					if(e.which == 13 || window.event.keyCode == 13){
						
						refreshInfo();
						return false;
					} 
						
					
				} catch (e) {

				}

	    });
		
		//set the records per page the key press event for the enter key
		$("input[id^='txtRecordsPerPage']:text").bind("keypress", function(e)
		{
			try {
				if(!e){ 
				     e = window.event; 
				} 
				if(e.which == 13 || window.event.keyCode == 13){
					
					refreshInfo();
				} 
					
				
			} catch (e) {
				
			}	
				
				
	    });
		
		
		$("#txtRecordsPerPageDown").bind("keyup", function(e)
		{
			$("#txtRecordsPerPageUp").val($("#txtRecordsPerPageDown").val());
	    });
		
		
		$("#txtRecordsPerPageUp").bind("keyup", function(e)
		{
			$("#txtRecordsPerPageDown").val($("#txtRecordsPerPageUp").val());
		
		});
		
		
		
}

function showStoreLocationDialog(showAEL,showJA,showClearance,list){
	
	//initialize grid for the store location control
	//grid initialization
	jQuery("#tblStoreLocation").jqGrid({ 
			// the url parameter tells from where to get the data from server 
			// adding ?nd='+new Date().getTime() prevent IE caching 
			//url:'../companies/list_subwholesalers_json.do',
			url:'../companies/list_wholesaler_and_subwholesalers_json.do?list='+list,
			// path to image location needed for the grid
			imgpath: '../css/'+theme+'/images',
			//specify pager and sorting images
			sortascimg: "sort_asc.gif",
			sortdescimg: "sort_desc.gif",
			firstimg: "first.gif",
			previmg: "prev.gif",
			nextimg: "next.gif",
			lastimg: "last.gif",
			width:340,
			// datatype parameter defines the format of data returned from the server 
			// in this case we use a JSON data 
			datatype: "json", 
			// colNames parameter is a array in which we describe the names 
			// in the columns. This is the text that apper in the head of the grid. 
			colNames:[	
			          	'Name',
						'Account',
						'JA Account',
						'Clearance Acc',
						'encryptedCode',
						'id'
					], 
			// colModel array describes the model of the column. 
			// name is the name of the column, 
			// index is the name passed to the server to sort data 
			// note that we can pass here nubers too. 
			// width is the width of the column 
			// align is the align of the column (default is left) 
			// sortable defines if this column can be sorted (default true) 
			colModel:[ 
						{name:'Name',index:'name', width:240, align:"left", sortable:false}, 
						{name:'Code',index:'code', width:110, align:"left", sortable:false, hidden: !showAEL},
						{name:'JaAccount',index:'jaAccount', width:110, align:"left", sortable:false, hidden: !showJA},
						{name:'ClearanceCode',index:'clearanceCode', width:100, align:"left", hidden: !showClearance},
						{name:'encryptedCode',index:'encryptedCode', width:100, align:"left", hidden:true},
						{name:'Id',index:'id', width:100, align:"left", hidden:true}
					], 
			// pager parameter define that we want to use a pager bar 
			// in this case this must be a valid html element. 
			// note that the pager can have a position where you want 
			//pager: jQuery('#pager2'),
			pgtext : false, 
			// rowNum parameter describes how many records we want to 
			// view in the grid. We use this in example.php to return 
			// the needed data. 
			rowNum:20, 
			// rowList parameter construct a select box element in the pager 
			//in wich we can change the number of the visible rows 
			//rowList:[10,20,30], 
			// sortname sets the initial sorting column. Can be a name or number. 
			// this parameter is added to the url 
			sortname: 'name', 
			//viewrecords defines the view the total records from the query in the pager 
			//bar. The related tag is: records in xml or json definitions. 
			viewrecords: false,
			height: "340",  
			//sets the sorting order. Default is asc. This parameter is added to the url 
			sortorder: "desc",
			onSelectRow:setSelectedCustomer
			}
		);
	
	$('#dvStoreLocation').dialog({
			autoOpen: false,
		 	closeOnEscape: true,
		 	resizable: false,
		 	modal:false
		 	});
	$('#dvStoreLocation').dialog('option', 'width', 400);
	$('#dvStoreLocation').dialog('option', 'height', 520);
	$('#dvStoreLocation').dialog('option', 'title', 'Select Store/Location');
	$('#dvStoreLocation').dialog("open");
}

//this function fires when a store location is selected on any page
function setSelectedCustomer(rowId)
{
	var store = $("#tblStoreLocation").getRowData(rowId);
	$('#txtStoreLocation').val(store.Name);
	$('#hdStoreLocationCode').val(store.Code);
	$('#hdJaAccount').val(store.JaAccount);
	$('#hdClearanceCode').val(store.ClearanceCode);
	$('#hdEncryptedCode').val(store.encryptedCode);
	$('#hdStoreLocationId').val(store.Id);
	hideStoreLocationWindow();
}

//function to hide the Store/Location window
function hideStoreLocationWindow()
{$('#dvStoreLocation').dialog("close");}



function showHandlingDialog(){
	
	//initialize grid for the store location control
	//grid initialization
	jQuery("#tblHandling").jqGrid({ 
			// the url parameter tells from where to get the data from server 
			// adding ?nd='+new Date().getTime() prevent IE caching 
			//url:'../companies/list_subwholesalers_json.do',
			url:'../companies/list_shipper_and_handlers_json.do',
			// path to image location needed for the grid
			imgpath: '../css/'+theme+'/images',
			//specify pager and sorting images
			sortascimg: "sort_asc.gif",
			sortdescimg: "sort_desc.gif",
			firstimg: "first.gif",
			previmg: "prev.gif",
			nextimg: "next.gif",
			lastimg: "last.gif",
			width:340,
			// datatype parameter defines the format of data returned from the server 
			// in this case we use a JSON data 
			datatype: "json", 
			// colNames parameter is a array in which we describe the names 
			// in the columns. This is the text that apper in the head of the grid. 
			colNames:[	
			          	'Name',
						'Account',
						'clearanceCode',
						'encryptedCode',
						'id'
					], 
			// colModel array describes the model of the column. 
			// name is the name of the column, 
			// index is the name passed to the server to sort data 
			// note that we can pass here nubers too. 
			// width is the width of the column 
			// align is the align of the column (default is left) 
			// sortable defines if this column can be sorted (default true) 
			colModel:[ 
						{name:'Name',index:'name', width:240, align:"left", sortable:false}, 
						{name:'Code',index:'code', width:100, align:"left", sortable:false},
						{name:'ClearanceCode',index:'clearanceCode', width:100, align:"left", hidden:true},
						{name:'encryptedCode',index:'encryptedCode', width:100, align:"left", hidden:true},
						{name:'Id',index:'id', width:100, align:"left", hidden:true}
					], 
			// pager parameter define that we want to use a pager bar 
			// in this case this must be a valid html element. 
			// note that the pager can have a position where you want 
			//pager: jQuery('#pager2'),
			pgtext : false, 
			// rowNum parameter describes how many records we want to 
			// view in the grid. We use this in example.php to return 
			// the needed data. 
			rowNum:20, 
			// rowList parameter construct a select box element in the pager 
			//in wich we can change the number of the visible rows 
			//rowList:[10,20,30], 
			// sortname sets the initial sorting column. Can be a name or number. 
			// this parameter is added to the url 
			sortname: 'name', 
			//viewrecords defines the view the total records from the query in the pager 
			//bar. The related tag is: records in xml or json definitions. 
			viewrecords: false,
			height: "340",  
			//sets the sorting order. Default is asc. This parameter is added to the url 
			sortorder: "desc",
			onSelectRow:setSelectedHandler
			}
		);
	
	$('#dvHandling').dialog({
			autoOpen: false,
		 	closeOnEscape: true,
		 	resizable: false,
		 	modal:false
		 	});
	$('#dvHandling').dialog('option', 'width', 400);
	$('#dvHandling').dialog('option', 'height', 520);
	$('#dvHandling').dialog('option', 'title', 'Select Handler');
	$('#dvHandling').dialog("open");
}


//this function fires when a handler is selected on any page
function setSelectedHandler(rowId)
{
	var store = $("#tblHandling").getRowData(rowId);
	$('#txtHandler').val(store.Name);
	$('#hdHandlerCode').val(store.Code);
	$('#hdClearanceCode').val(store.ClearanceCode);
	$('#hdEncryptedCode').val(store.encryptedCode);
	$('#hdHanlderId').val(store.Id);
	hideHandlingWindow();
}

//function to hide the Handling window
function hideHandlingWindow()
{$('#dvHandling').dialog("close");}

var newwindow;
function openPopUpFaq(url)
{

	newwindow=window.open(url,'FAQ','height=800,width=800');
	if (window.focus) {newwindow.focus()}
}		



//this function clears all filter inputs
function clearForm(formName)
{
	$('#hdStoreLocationCode').val("");
	$('#hdConsigneeCode').val("");
	document.forms[formName].reset();
}



//this is a new function that clears all filters and then places the default values on all fields
function resetForm(){
	$("input[id$='DateFrom']:text").each(function(i) {
		vt_dateFrom = new Date();
		vt_dateFrom.setDate(vt_dateFrom.getDate() - 5);
		var month = (vt_dateFrom.getMonth()+1).toString();
		var day = (vt_dateFrom.getDate()).toString();
		if(month.length==1)
			month="0"+month;
		if(day.length==1)
			day="0"+day;
		this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
	});
	$("input[id$='DateTo']:text").each(function(i) {
		vt_dateFrom = new Date();
		var month = (vt_dateFrom.getMonth()+1).toString();
		var day = (vt_dateFrom.getDate()).toString();
		if(month.length==1)
			month="0"+month;
		if(day.length==1)
			day="0"+day;
		
		this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
	});
	$("input[id$='YearFrom']:text").each(function(i) {
		vt_dateFrom = new Date();
		vt_dateFrom.setDate(vt_dateFrom.getDate() - 365);
		var month = (vt_dateFrom.getMonth()+1).toString();
		var day = (vt_dateFrom.getDate()).toString();
		if(month.length==1)
			month="0"+month;
		if(day.length==1)
			day="0"+day;
		this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
	});
	$("input[id$='MonthFrom']:text").each(function(i) {
		vt_dateFrom = new Date();
		vt_dateFrom.setDate(vt_dateFrom.getDate() - 30);
		var month = (vt_dateFrom.getMonth()+1).toString();
		var day = (vt_dateFrom.getDate()).toString();
		if(month.length==1)
			month="0"+month;
		if(day.length==1)
			day="0"+day;
		this.value = month + '/' + day + '/' + vt_dateFrom.getFullYear();
	});
	$("input[id$='txtStoreLocation']:text").each(function(i) {
		$('#hdStoreLocationCode').val("");
		this.value = companyName;
	});
}

/*this section manages export to excel logic*/
function getExcelFile()
{
 	var data = getDataFilters();
	sendDataNoAjax("list_excel.do",data);
	
}


function setHomePage(homePage)
{

	$.ajax({
        url: "../user/set_home_page.do",
        async:true,
        dataType: "json",
        data:'homePage='+homePage,
        error: function(xhr, quepaso, otroobj){
        	showErrorMessage("The request to the server failed: "+quepaso);
        },
        success: succesSetHomePage,
        timeout: 20000,
        type: "POST"
	});
	
}

function succesSetHomePage(response)
{
	showMessage(response.message);
	//showMessage('This page will continue loading for default after signing in.');
}


 function validateUpload(extensions,fileValue)  
 {  
	 var image_length = fileValue.length;  
	 var pos = fileValue.lastIndexOf('.') + 1;  
	 var ext = fileValue.substring(pos, image_length);  
	 var final_ext = ext.toLowerCase();  
	 for (i = 0; i < extensions.length; i++)  
	 {  
	     if(extensions[i] == final_ext)  
	     {return true;}  
	 }  
	 return false;  
 }  

function showErrorMessage(errorMessage)
{
	var html = '<table widht="100%" heigth="80%">';
	html += '<tr><td><b>ERROR</b></td></tr>';
	html += '<tr><td>'+errorMessage+'</td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '</table>';
	
	jQuery.noticeAdd({
        text: html,
        stay: false,
        type: 	'errorNotification',
        stayTime: 7000
	});
}
function showMessage(message)
{
	var html = '<table widht="100%" heigth="80%">';
	html += '<tr><td>&nbsp</td></tr>';
	html += '<tr><td><center>'+message+'</center></td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '</table>';
	
	jQuery.noticeAdd({
        text: html,
        stay: false,
        stayTime: 7000
	});
}

function showUrgentNotification(notification)
{
	var html = '<table widht="100%" heigth="80%">';
	html += '<tr><td><center><b>'+notification.title+'</b></center></td></tr>';
	html += '<tr heigth="1px"><td></td></tr>';
	html += '<tr><td>'+notification.content+'</td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '<tr><td align="right"><a id="hrefMarkU'+notification.userNotificationId+'" href="javascript:markNotificationAsRead('+notification.userNotificationId+',\'hrefMarkU'+notification.userNotificationId+'\');">Mark as Read</a></td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '</table>';
	
	jQuery.noticeAdd({
        text: html,
        stay: true,
        type: 	'errorNotification'
	});
}
function showNormalNotification(notification)
{
	var html = '<table widht="100%" heigth="80%">';
	html += '<tr><td><center><b>'+notification.title+'</b></center></td></tr>';
	html += '<tr heigth="1px"><td></td></tr>';
	html += '<tr><td>'+notification.content+'</td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '<tr><td align="right"><a id="hrefMarkN'+notification.userNotificationId+'" href="javascript:markNotificationAsRead('+notification.userNotificationId+',\'hrefMarkN'+notification.userNotificationId+'\');">Mark as Read</a></td></tr>';
	html += '<tr><td>&nbsp;</td></tr>';
	html += '</table>';
	
	jQuery.noticeAdd({
        text: html,
        stay: false,
        type: 	'notification',
        stayTime: 10000
        
	});
}
function markNotificationAsRead(userNotificationId, elmId)
{
	var itemToClose =$('#'+elmId).parent().parent().parent().parent().parent(); 
	jQuery.noticeRemove(itemToClose);
	
	$.ajax({
        url: '../notification/delete_user_notification.do',
        async:true,
        data: 'userNotificationId='+userNotificationId,
        error: function(objeto, quepaso, otroobj){
			showErrorMessage("The request to the server failed: "+quepaso);
        },
        timeout: 50000,
        type: "POST"
	});
}
//the following function encodes data in HTML using the own web browser
function escapeHTML(str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};





