var NIBOCustomers = 
{
	PagerSort:function(psort){$('csort').value=psort;$('p').value=0;$("customersIndexForm").submit();},
	PagerLink:function(pgnum){$("p").value=pgnum;$("customersIndexForm").submit();},
	SearchStart:function(){$('p').value=0;},
	MPT:function(){location.href=$F('mpturl');},
	MIO:function(){location.href=$F('miourl');},
	
	
	
	UpdateInvoiceOption:function(optid){var opid = ("" + optid).trim();if(opid.length > 0){if($('ioptTitle_'+opid) != null){$('ioptTitleOrg_'+opid).hide();$('ioptTitle_'+opid).disabled = false;$('ioptTitleUpdate_'+opid).show();}}else{alert("Please update an existing Invoice Option");}},
	SaveInvoiceOption:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			var ot = ("" + $F('ioptTitle_'+opid)).trim();
			if(ot.length == 0){alert("Please enter an Invoice Option");$('ioptTitle_'+opid).focus();return false;}
			$('save_'+id).hide();
			new Ajax.Request($F('ioptionURL'), {
				method:'post',
				parameters:{mode:'update',id:opid,optidhash:$F('ioptHash_'+id),title:ot},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if(json.error != null){NIBOCustomers.InvoiceOptionTitleFailed(id, json.error);}
					else
					{
						if( json.updated != null )
						{$('ioptTitleOrg_'+id).update(ot);new Effect.Highlight("IOptRow_"+id);Messenger.notice("Invoice Option updated", Messenger.timeout);}
						else{NIBOCustomers.InvoiceOptionTitleFailed(id);}
					}
					$('save_'+id).show();$('ioptTitleOrg_'+opid).show();$('ioptTitleUpdate_'+opid).hide();
				},
				onFailure:function(transport){NIBOCustomers.InvoiceOptionTitleFailed(opid);}
			});
		}
		else
		{	alert("Please update an existing Invoice Option");	}
	},
	CreateInvoiceOptionFailed:function(id,error){var jerror = "Unable to create Invoice Option";if(error != null){jerror = "" + error;}new Effect.Highlight("IOptRow_"+id,{startcolor:'#E9AADE',duration:1});Messenger.notice(jerror, Messenger.timeout);},
	InvoiceOptionTitleFailed:function(id,error)
	{
		var jerror = "Unable to update Invoice Option title";
		if(error != null){jerror = "" + error;}
		new Effect.Highlight("IOptRow_"+id,{startcolor:'#E9AADE',duration:1});
		Messenger.notice(jerror, Messenger.timeout);
		$('save_'+id).show();$('ioptTitleOrg_'+id).show();$('ioptTitleUpdate_'+id).hide();
	},
	SuspendActivateInvoiceOption:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			$('status_'+id).hide();
			new Ajax.Request($F('ioptionURL'), {
				method:'post',
				parameters:{mode:'activatesuspend',id:opid,optidhash:$F('ioptHash_'+id)},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if( json.error != null )
					{	NIBOCustomers.InvoiceOptionActivationSuspensionFailed(id,json.error);	}
					else
					{
						if(json.updated != null)
						{$('ioptStatus_'+id).update(json.updated);new Effect.Highlight("IOptRow_"+id);Messenger.notice("Invoice Option updated", Messenger.timeout);}
						else
						{	NIBOCustomers.InvoiceOptionActivationSuspensionFailed(id);	}
					}
					$('status_'+id).show();
				},
				onFailure:function(transport)
				{	NIBOCustomers.InvoiceOptionActivationSuspensionFailed(id);	}
			});
		}
		else
		{	alert("Please update an existing Invoice Option");	}
	},
	InvoiceOptionActivationSuspensionFailed:function(id,error){new Effect.Highlight("IOptRow_"+id,{startcolor:'#E9AADE',duration:1});Messenger.notice("Unable to update Invoice Option status", Messenger.timeout);$('status_'+id).show();},
	DeleteInvoiceOption:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			if(confirm('Deleting Invoice Option permanently. Proceed?'))
			{
				$('opdelid').value = opid;
				$('opdelhash').value = $F('ioptHash_'+opid);
				$('opDeleteForm').submit();
			}
		}
	},
	
	
	CreatePaymentTermFailed:function(id,error){var jerror = "Unable to create Payment Term";if(error != null){jerror = "" + error;}new Effect.Highlight("pTermRow_"+id,{startcolor:'#E9AADE',duration:1});Messenger.notice(jerror, Messenger.timeout);},
	UpdatePaymentTerm:function(optid){var opid = ("" + optid).trim();if(opid.length > 0){if($('pTermTitle_'+opid) != null){$('pTermTitleOrg_'+opid).hide();$('pTermTitle_'+opid).disabled = false;$('pTermTitleUpdate_'+opid).show();}}else{alert("Please update an existing Payment Term");}},
	SavePaymentTerm:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			var ot = ("" + $F('pTermTitle_'+opid)).trim();
			if(ot.length == 0){alert("Please enter a Payment Term");$('pTermTitle_'+opid).focus();return false;}
			$('save_'+id).hide();
			new Ajax.Request($F('ptermURL'), {
				method:'post',
				parameters:{mode:'update',id:opid,ptidhash:$F('pTermHash_'+id),title:ot},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if(json.error != null){NIBOCustomers.PaymentTermTitleFailed(id, json.error);}
					else
					{
						if( json.updated != null )
						{$('pTermTitleOrg_'+id).update(ot);new Effect.Highlight("pTermRow_"+id);Messenger.notice("Payment Term updated", Messenger.timeout);}
						else{NIBOCustomers.InvoiceOptionTitleFailed(id);}
					}
					$('save_'+id).show();$('pTermTitleOrg_'+opid).show();$('pTermTitleUpdate_'+opid).hide();
				},
				onFailure:function(transport){NIBOCustomers.PaymentTermTitleFailed(opid);}
			});
		}
		else
		{	alert("Please update an existing Payment Term");	}
	},
	PaymentTermTitleFailed:function(id,error)
	{
		var jerror = "Unable to update Payment Term title";
		if(error != null){jerror = "" + error;}
		new Effect.Highlight("pTermRow_"+id,{startcolor:'#E9AADE',duration:1});
		Messenger.notice(jerror, Messenger.timeout);
		$('save_'+id).show();$('pTermTitleOrg_'+id).show();$('pTermTitleUpdate_'+id).hide();
	},
	SuspendActivatePaymentTerm:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			$('status_'+id).hide();
			new Ajax.Request($F('ptermURL'), {
				method:'post',
				parameters:{mode:'activatesuspend',id:opid,ptidhash:$F('pTermHash_'+id)},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if( json.error != null )
					{	NIBOCustomers.PaymentTermActivationSuspensionFailed(id,json.error);	}
					else
					{
						if(json.updated != null)
						{$('pTermStatus_'+id).update(json.updated);new Effect.Highlight("pTermRow_"+id);Messenger.notice("Payment Term updated", Messenger.timeout);}
						else
						{	NIBOCustomers.PaymentTermActivationSuspensionFailed(id);	}
					}
					$('status_'+id).show();
				},
				onFailure:function(transport)
				{	NIBOCustomers.PaymentTermActivationSuspensionFailed(id);	}
			});
		}
		else
		{	alert("Please update an existing Payment Term");	}
		
	},
	PaymentTermActivationSuspensionFailed:function(id,error){new Effect.Highlight("pTermRow_"+id,{startcolor:'#E9AADE',duration:1});Messenger.notice("Unable to update Payment Term status", Messenger.timeout);$('status_'+id).show();},
	DeletePaymentTerm:function(id)
	{
		var opid = ("" + id).trim();
		if(opid.length > 0)
		{
			if(confirm('Deleting Payment Term permanently. Proceed?'))
			{
				$('ptdelid').value = opid;
				$('ptdelhash').value = $F('pTermHash_'+opid);
				$('ptDeleteForm').submit();
			}
		}
	},
		
	
	
	
	
	
	
	SubmitCustomer:function(){NIBOCustomerCats.SelectAll('scats');},
	CopyBillingAddress:function(chkbox){if($('badd1')!=null&&$('sadd1')!=null){$('sadd1').value=$F('badd1');}if($('badd2')!=null&&$('sadd2')!=null){$('sadd2').value=$F('badd2');}if($('bcity')!=null&&$('scity')!=null){$('scity').value=$F('bcity');}if($('bprov')!=null&&$('sprov')!=null){$('sprov').value=$F('bprov');}if($('bcountry')!=null&&$('scountry')!=null){$('scountry').value=$F('bcountry');}if($('bpostal')!=null&&$('spostal')!=null){$('spostal').value=$F('bpostal');}if(chkbox!=null){chkbox.checked=false;}},
	UpdateCustomer:function(id){url=$F('customerUpdateURL');location.href=url+'/'+id;},
	UpdateCustomerByRep:function(id){url=$F('customerUpdateRepURL');location.href=url+'/'+id;},
	PaymentTermsSelect:function(){if($F('paymentTerms')=='Other'){$('pTermOther').show();$('paymentTermsOther').focus();}else{$('pTermOther').hide();$('paymentTermsOther').value='';}},
	SaveCustomerProducts:function(){$('updateCustomerStub').disabled = false;NIBOCustomerCats.SelectAll('scats');$('cUpdateFrm').submit();},
	updateCountriesSelect:function(data){var sels=$$('select.countriesSelect');for(var i=0; i<sels.length; i++){var option = new Option (data['name'], data['name']);var el = sels[i];el.options[el.options.length] = option;}var ctns = $$('div.addCountryContainer');for(var i=0; i<ctns.length; i++){ctns[i].style.display = 'none';}},
	updateProvincesSelect:function(data)
	{		
		//get all select elements that list provinces		
		var sels = $$('select.provincesSelect');
		
		
		//add our new option to each of them		
		for (var i=0; i<sels.length; i++) 
		{
			var option = new Option (data['name'], data['name']);
			var el = sels[i];			
			
			el.options[el.options.length] = option;						
		}
		
		//now hide all of the 'add new province' containers
		var ctns = $$('div.addProvinceContainer');		
		for (var i=0; i<ctns.length; i++)
		{			
			ctns[i].style.display = 'none';
		}	
	
	
	},
	
	//inputEl is the id of the element we are getting the country name (value) from	 
	addNewCountry:function(inputEl)
	{
		if (!inputEl) 
		{ Messenger.notice('Error: Please enter a country name', Messenger.timeout); return false;}
	
		//new country name
		var country = $F(inputEl);
		
		//id of user making this change
		var userId = $F('userId');		
	
		url = "" + $F('userURL');
		hash= $F('userHash');
		
		new Ajax.Request(url, {
			method:'post',
			parameters:{'userid':userId,'country':country,userhash:hash,mode:'addcountry'},
			onSuccess:function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if( json.error != null )
				{	Messenger.notice("" + json.error);	}
				else
				{
					// error
					if( json.error != null )
					{
						$(inputEl).style.border = '1px solid red';
						Messenger.notice(json.error, Messenger.timeout);
					}
					
					// success
					else if( json.success != null )
					{
						//update all country select elements
						NIBOCustomers.updateCountriesSelect(json.data);
						Messenger.notice(json.success, Messenger.timeout);
					}
				}
			},
			onFailure:function(transport)
			{				
				Messenger.notice("Unable to add new country", Messenger.timeout);
			}
		});		
	},
	
	//inputEl is the input text field that contains the new country name
	//countryEl is the country select element so we can determine what country they are add this prov/state to
	addNewProvince:function(inputEl, countryEl) 
	{
		if (!inputEl) 
		{ Messenger.notice('Error: Please enter a province name', Messenger.timeout); return false; }
		
		if (!countryEl)
		{ alert("You must first select a country"); return false; }

		//country value
		var country = $F(countryEl);		
		
		//new province name
		var province = $F(inputEl);

		//id of user making this change
		var userId = $F('userId');
	
		url = "" + $F('userURL');
		hash= $F('userHash');
		
		new Ajax.Request(url, {
			method:'post',
			parameters:{'userid':userId,'country':country,'province':province,'userhash':hash,'mode':'addprovince'},
			onSuccess:function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if( json.error != null )
				{	Messenger.notice("" + json.error);	}
				else
				{
					// error
					if( json.error != null )
					{
						$(inputEl).style.border = '1px solid red';
						Messenger.notice(json.error, Messenger.timeout);
					}
					
					// success
					else if( json.success != null )
					{	
						NIBOCustomers.updateProvincesSelect(json.data);											
						Messenger.notice(json.success, Messenger.timeout);
					}
				}
			},
			onFailure:function(transport)
			{				
				Messenger.notice("Unable to add new province", Messenger.timeout);
			}
		});	
	
	},
	
	//when selecting a country or province, if the users selects 'other', it will hide 
	//the select form input (it's container id sent as the value of 'toHide' and show
	//a blank text box (whose container id is sent as the value of toShow)
	//the value field is the value of the country /province select box
	toggleCountryProvinceInput:function(origContainer, targetContainer, value){if(!origContainer || !targetContainer){return;}if(parseInt(value) == -1){$(targetContainer).show();}else{$(targetContainer).hide();}								},
	SuspendActivateCustomer:function(id)
	{
		url = "" + $F('customerURL');
		hash= $F('customerHash_'+id);
		$('status_'+id).hide();$('wait_'+id).show();
		
		new Ajax.Request(url, {
			method:'post',
			parameters:{customerid:id,customerhash:hash,mode:'activatesuspend'},
			onSuccess:function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if( json.error != null )
				{	Messenger.notice("" + json.error);	}
				else
				{
					// suspended
					if( json.suspended != null )
					{
						$("CustomerSCell_"+id).update('Suspended');
						new Effect.Highlight("CustomerSCell_"+id,{startcolor:'#E9AADE',duration:1});
						Messenger.notice("Customer suspended", Messenger.timeout);
					}
					
					// activated
					else if( json.activated != null )
					{
						$("CustomerSCell_"+id).update('Active');
						new Effect.Highlight("CustomerSCell_"+id,{startcolor:'#9AC466',duration:1});
						Messenger.notice("Customer activated", Messenger.timeout);
					}
					
					else
					{
						new Effect.Highlight("CustomerRow_"+id);
						Messenger.notice("Unable to update Customer record", Messenger.timeout);
					}
				}
				$('wait_'+id).hide();$('status_'+id).show();
			},
			onFailure:function(transport)
			{
				new Effect.Highlight("CustomerRow_"+id,{startcolor:'#E9AADE',duration:1});
				Messenger.notice("Unable to update Customer record", Messenger.timeout);
				$('wait_'+id).hide();$('status_'+id).show();
			}
		});
	},
	
	DeleteCustomer:function(id)
	{
		if( confirm("Are you sure you want to permanently delete this Customer?") )
		{
			url = "" + $F('customerURL');
			hash= $F('customerHash_'+id);
			new Ajax.Request(url, {
				method:'post',
				parameters:{customerid:id,customerhash:hash,mode:'deletecustomer'},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if( json.error != null )
					{	Messenger.notice("" + json.error);	}
					else
					{
						if( json.error != null )
						{
							Messenger.noticewithoutfade("" + json.error);
							new Effect.Highlight("CustomerRow_"+id);
						}
						else if( json.deleted != null )
						{
							new Effect.Fade("CustomerRow_"+id);
							Messenger.notice("Customer deleted", Messenger.timeout);
						}
						else
						{	Messenger.notice("Unable to delete Customer", Messenger.timeout);	}
					}
				},
				onFailure:function(transport)
				{	Messenger.notice("Unable to delete Customer", Messenger.timeout);	}
			});
		}
	},
	
	
	
	SearchProducts:function()
	{
		var pval = "" + $F('cdcp');
		if(pval.length == 0)		
		{	$('cdcp').focus();	}
		else
		{
			url = "" + $F('customerURL');
			new Ajax.Request(url, {
				method:'post',
				parameters:{customerid:$F('customerId'),customerhash:$F('customerHash'),cdcp:pval,mode:'productmatches'},
				onSuccess:function(transport)
				{
					var json = transport.responseText.evalJSON(true);
					if( json.error != null )
					{	Messenger.notice("" + json.error);	}
					else
					{
						if( json.error != null )
						{
							Messenger.noticewithoutfade("" + json.error);
							$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
						}
						
						else if( json.pmatches != null )
						{
							$('cdcpres').update(json.pmatches);
							new Effect.Appear('cdcpres');new Effect.Appear('cdcpadd');
						}
						else
						{
							Messenger.notice("Unable to retrieve matching Products", Messenger.timeout);
							$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
						}
					}
				},
				onFailure:function(transport)
				{
					Messenger.notice("Unable to retrieve matching Products", Messenger.timeout);
					$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
				}
			});
		}
	},
	
	AddProducts:function()
	{
		var total = 0;
		if($('pdid_total') != null)
		{	total = parseInt($F('pdid_total'));	}
		if( total > 0)
		{
			var added = false;
			var url = $F('customerURL');
			var cid = $F('customerId');
			var chash = $F('customerHash');
			
			for(i=0;i<total;i++)
			{
				chkbox = $('pdid_'+i);
				if(chkbox != null && chkbox.disabled == false)
				{
					if(chkbox.checked == true)
					{
						cpid = chkbox.value;
						new Ajax.Request(url, {
							method:'post',
							parameters:{customerid:cid,customerhash:chash,pid:cpid,mode:'addproductdiscount'},
							onSuccess:function(transport)
							{
								var json = transport.responseText.evalJSON(true);
								if( json.error != null )
								{
									Messenger.notice("" + json.error);
									Messenger.gotonotice();
								}
								else
								{
									if( json.error != null )
									{
										Messenger.noticewithoutfade("" + json.error);
										$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
									}
									
									else if( json.added != null )
									{
										if($('pdid_'+i) != null)
										{	$('pdid_'+i).disabled = true;	}

										var txt = json.added;
										new Insertion.After($('cdinsertafter'),txt);
										
										var cpdid = json.cpdid;
										new Effect.Highlight('DiscountRow_'+cpdid);
										
										if($('cdnone') != null)
										{	$('cdnon').hide();	}
									}
									
									else if( json.exists != null )
									{
										Messenger.notice("Unable to add Product to Customer Discounts", Messenger.timeout);
										$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
									}
								}
							},
							onFailure:function(transport)
							{
								Messenger.notice("Unable to add Product to Customer Discounts", Messenger.timeout);
								$('cdcpres').update('');new Effect.Fade('cdcpres');new Effect.Fade('cdcpadd');
							}
						});

						added = true;		
					}
				}
			}
			
			if(added == false)
			{	alert("Please select at least one Product to add to Customer Discount");	}
		}
		else
		{	alert('No matching products found to add to Customer Discounts');	}
	},
	
	RemoveDiscount:function(id)
	{		
		var url = $F('customerURL');
		var cid = $F('customerId');
		var chash = $F('customerHash');
			
		new Ajax.Request(url, {
			method:'post',
			parameters:{customerid:cid,customerhash:chash,cpdid:id,mode:'removeproductdiscount'},
			onSuccess:function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if( json.error != null )
				{	Messenger.notice("" + json.error);	Messenger.gotonotice();	}
				else
				{
					if( json.error != null )
					{	Messenger.noticewithoutfade("" + json.error);	}
					else if( json.removed != null )
					{	new Effect.Fade('DiscountRow_'+id);	}
					else
					{	Messenger.notice("Unable to remove Product from Customer Discounts", Messenger.timeout);	}
				}
			},
			onFailure:function(transport)
			{	Messenger.notice("Unable to remove Product from Customer Discounts", Messenger.timeout);	}
		});
		
	},
	
	UpdateDiscount:function(id)
	{
		var url = $F('customerURL');
		var cid = $F('customerId');
		var chash = $F('customerHash');
		var cdprcn= $('cpd_dprcnt_' + id).checked == true ? 1 : 0;
		var cdprce= $('cpd_dprice_' + id).checked == true ? 1 : 0;
		var cdcomm= $('cpd_comm_'+id) != null ? $F('cpd_comm_'+id) : -100; 
		$('cpd_save_'+id).hide();
		$('cpd_wait_'+id).show();
		
		new Ajax.Request(url, {
			method:'post',
			parameters:{customerid:cid,customerhash:chash,cpdid:id,discount:$F('cpd_disc_'+id),dpercent:cdprcn,dprice:cdprce,commission:cdcomm,mode:'updateproductdiscount'},
			onSuccess:function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if( json.error != null )
				{	Messenger.notice("" + json.error);	Messenger.gotonotice();	}
				else
				{
					if( json.error != null )
					{	Messenger.noticewithoutfade("" + json.error);	}
					else if( json.updated != null )
					{	new Effect.Highlight('DiscountRow_'+id);	}
					else
					{	Messenger.notice("Unable to remove Product from Customer Discounts", Messenger.timeout);	}
				}
				
				$('cpd_save_'+id).show();$('cpd_wait_'+id).hide();
			},
			onFailure:function(transport)
			{
				$('cpd_save_'+id).show();$('cpd_wait_'+id).hide();
				Messenger.notice("Unable to remove Product from Customer Discounts", Messenger.timeout);
			}
		});
	},
	
	ToggleBusinessCategoryOther:function(val){if(val == 'Other'){$('business_category_other_row').show();}else{$('business_category_other_row').hide();}}
}