// JavaScript Document

	var objTakePaymentButton;
	var objMoveServerButton;

	$(document).ready (function ()
	{

		
			$( "#frmTakePayment" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Take Payment": function()
				{
					
					
					$.ajax({
						url: 'ajax/ajax.takePayment.php',
						data: "customerProductPeriodID=" + $(this).attr("customerProductPeriodID") + "&paymentReference=" + $("#paymentReference").val(),
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
//							alert(response);
							$( "#frmTakePayment" ).dialog( "close" );

							var panel_detail = $(objTakePaymentButton).parents(".customer_product_row").children(".customer_product_detail");
							loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)
						},
						error: function(data)
						{
							alert("Error taking payment: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});			




			$( "#frmChangeServer" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Move Server": function()
				{

					
					$.ajax({
						url: 'ajax/ajax.customerProduct.moveServer.php',
						data: "customerProductID=" + $("#frmChangeServerCustomerProductID").val() + "&serverID=" + $("#frmChangeServerID").val() + "&pleskID=" + $("#frmChangePleskID").val(),
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
						//	alert(response);
							$( "#frmChangeServer" ).dialog( "close" );

							var panel_detail = $(objMoveServerButton).parents(".customer_product_row").children(".customer_product_detail");
							loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)
						},
						error: function(data)
						{
							alert("Error moving server: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});			



		$( "#frmAddProduct" ).dialog({
			autoOpen: false,
			height: 400,
			width: 550,
			modal: true,
			buttons: {
				"Add Product": function()
				{

					var form = $(this).find("form");
					var data = form.serialize();
					
					$.ajax({
						url: 'ajax/ajax.customerProduct.add.php',
						data:  data,
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
//							alert(response);
							$( "#frmAddProduct" ).dialog( "close" );
							
							window.location.href = window.location.href;

							/*var panel_detail = $(objTakePaymentButton).parents(".customer_product_row").children(".customer_product_detail");
							loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)*/
						},
						error: function(data)
						{
							alert("Error adding product: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});		




		$( "#frmAddCustomer" ).dialog({
			autoOpen: false,
			height: 400,
			width: 550,
			modal: true,
			buttons: {
				"Add Customer": function()
				{

					var form = $(this).find("form");
					var data = form.serialize();

					
					$.ajax({
						url: 'ajax/ajax.customer.add.php',
						data:  'msoaCustomerID=' + $("#msoaCustomerID").val(),
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
							alert(response);
							$( "#frmAddCustomer" ).dialog( "close" );
							
							window.location.href = window.location.href;

						},
						error: function(data)
						{
							alert("Error adding customer: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});		

			$( "#frmRenew" ).dialog({
			autoOpen: false,
			height: 400,
			width: 550,
			modal: true,
			buttons: {
				"Add Period": function()
				{
					var customerProductID = $(this).attr("customerProductID")
					
	//				alert(customerProductID);
					
					$.ajax({
						url: 'ajax/ajax.renew.complete.php',
						data: "customerProductID=" + customerProductID + "&period=" + $("#renewalPeriod").val() + "&invoiceNumber=" + $("#invoiceNumber").val() + "&startDate=" + $("#finalStartDate").val() + "&endDate=" + $("#finalEndDate").val() + "&price=" + $("#renewalPeriodPrice").val(),
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
							$( "#frmRenew" ).dialog( "close" );
							
							var panel_detail = $(objTakePaymentButton).parents(".customer_product_row").children(".customer_product_detail");
							loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)
						},
						error: function(data)
						{
							alert("Error renewing: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});	





		$( "#frmAddGrace" ).dialog({
			autoOpen: false,
			height: 400,
			width: 550,
			modal: true,
			buttons: {
				"Add Grace Period": function()
				{
					var customerProductID = $(this).attr("customerProductID")
					
	//				alert(customerProductID);
					
					$.ajax({
						url: 'ajax/ajax.grace.complete.php',
						data: "customerProductID=" + customerProductID + "&period=" + $("#gracePeriod").val() + "&startDate=" + $("#graceFinalStartDate").val() + "&endDate=" + $("#graceFinalEndDate").val(),
						cache: false,
						async:   false,
					  
						success: function(response) 
						{
							alert(response);
							$( "#frmAddGrace" ).dialog( "close" );
							
							var panel_detail = $(objTakePaymentButton).parents(".customer_product_row").children(".customer_product_detail");
							loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)
						},
						error: function(data)
						{
							alert("Error adding grace: " + data.status);
						}				
				   });

					
					
				},
				Cancel: function()
				{
					$( this ).dialog( "close" );
				}
			},
			close: function()
			{
				//alert("close");
			}
		});	



		
		$(".btnUpdateServerExpiry").live("click", function ()
		{
			var objButton = this;
			
			
			var intDateExpiry = (parseInt($(this).attr("greatestPaidOrGraceExpiryDateStamp"))) * 1000;
			var friendlyDateExpiry = ($(this).attr("greatestPaidOrGraceExpiryDate"));

			dateNow = new Date();
			dateExpiry = new Date(intDateExpiry);
			
			var confirmed = false;
			var turnOff = false;
			
			if (dateExpiry > dateNow)
			{
				confirmed = confirm("Update server hosting turn off date to " + friendlyDateExpiry + " and TURN-ON hosting immediately?");
			}
			else
			{
				confirmed = confirm("New turn off date " + friendlyDateExpiry + " is in the past. Setting server to this date will turn off hosting now. Are you sure you wish to update expiration date and TURN OFF hosting immediately?");
				turnOff = true;
			}
			
			if (confirmed)
			{
			
				$.ajax({
					url: 'ajax/ajax.pleskSetExpiration.php',
					data: "customerProductID=" + $(this).attr("customerProductID") + "&turnoff=" + turnOff ,
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
						if (response == "error")
						{
							alert("Error setting expiration date: " + response);								
						}
							alert("" + response);								
						
						var panel_detail = $(objButton).parents(".customer_product_row").children(".customer_product_detail");

						loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)

					},
					error: function(data)
					{
						alert("Error setting expiration date: " + data.status);
					}				
				   });

			}
			
			
		});


		$(".btnDeleteCustomer").live("click", function ()
		{
			var objButton = this;
			var rowToRemove = $(this).parents(".customer_row");


	
			if (confirm("Are you sure you wish to delete this customer?"))
			{
				
			
				$.ajax({
					url: 'ajax/ajax.customer.delete.php',
					data: "customerID=" + $(this).attr("customerID"),
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
						var res = response.split("@@");
						
						if (res[0] == "OK")
						{
							window.location.href = window.location.href;
						}
						else
						{
							alert("Error deleting customer: " + res[1]);
							
						}


					},
					error: function(data)
					{
						alert("Error deleting customer: " + data.status);
					}				
				   });

			}
			
			
		});




		$(".btnDeleteProduct").live("click", function ()
		{
	
			if (confirm("Are you sure you wish to delete this product?"))
			{
				
			
				$.ajax({
					url: 'ajax/ajax.customerProduct.delete.php',
					data: "customerProductID=" + $(this).attr("customerProductID"),
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
						var res = response.split("@@");
						
						if (res[0] == "OK")
						{
							window.location.href = window.location.href;
						}
						else
						{
							alert("Error deleting customer product: " + response);
							
						}


					},
					error: function(data)
					{
						alert("Error deleting customer product: " + data.status);
					}				
				   });

			}
			
			
		});



		$(".btnDeletePeriod").live("click", function ()
		{
			var objButton = this;
			var rowToRemove = $(this).parents(".customer_product_period_row");


	
			if (confirm("Are you sure you wish to delete this period?"))
			{
				
			
				$.ajax({
					url: 'ajax/ajax.period.delete.php',
					data: "customerProductPeriodID=" + $(this).attr("customerProductPeriodID"),
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
					//	alert(response);
						
//						rowToRemove.remove();

						var panel_detail = $(objButton).parents(".customer_product_row").children(".customer_product_detail");

						loadCustomerProductDetail(panel_detail.attr("customerProductID"),  panel_detail)


					},
					error: function(data)
					{
						alert("Error deleting period: " + data.status);
					}				
				   });

			}
			
			
		});



		$("#serverID").live("change", function ()
		{
			pleskRetrieveDomains(this, "#pleskID", -1);
		});
		$("#frmChangeServerID").live("change", function ()
		{
			pleskRetrieveDomains(this, "#frmChangePleskID", -1);
		});


		$("#startDate").live("change", function ()
		{
			updateDates();
		});


		$(".invoiceNumber").live("change", function ()
		{
//			updateDates();
//			alert("update inv number");
			
					$.ajax({
					url: 'ajax/ajax.period.update.php',
					data: "customerProductPeriodID=" + $(this).attr("customerProductPeriodID") + "&invoiceNumber=" + $(this).val() ,
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
	//					alert(response);
					},
					error: function(data)
					{
						alert("Error updating invoice number: " + data.status);
					}				
				   });
			

		});


		function updateDates ()
		{
			
			var dString = $("#startDate").val();
			var period = $("#renewalPeriod").val().split("@@");
			var y = parseInt(period[4]);
			var m = parseInt(period[5]);
			var d = parseInt(period[6]);

			var ds = Date.parse(dString);
			var startDate = ds.toString("dd/MM/yyyy");
			
			var de = ds.addYears(y);
			
		//	alert("y=" + y + ", res=" + de.toString("dd/MM/yyyy"));
			
			de = de.addMonths(m);
			//alert(",=" + m + ", res=" + de.toString("dd/MM/yyyy"));

			de = de.addDays(d);
			//alert("d=" + d + ", res=" + de.toString("dd/MM/yyyy"));
			
			var endDate = de.toString("dd/MM/yyyy");
			
			
			$("#renewalPeriodDisplay").html(startDate + " to " + endDate);
			
			$("#finalStartDate").val(startDate);
			$("#finalEndDate").val(endDate);
	
		}


		function updateDatesGrace ()
		{
			
			var dString = $("#graceStartDate").val();
		//	alert(dString);
			
			var period = $("#gracePeriod").val().split("@@");

			var y = parseInt(period[4]);
			var m = parseInt(period[5]);
			var d = parseInt(period[6]);

			var ds = Date.parse(dString);
			var startDate = ds.toString("dd/MM/yyyy");
			
			var de = ds.addYears(y);
			
		//	alert("y=" + y + ", res=" + de.toString("dd/MM/yyyy"));
			
			de = de.addMonths(m);
			//alert(",=" + m + ", res=" + de.toString("dd/MM/yyyy"));

			de = de.addDays(d);
			//alert("d=" + d + ", res=" + de.toString("dd/MM/yyyy"));
			
			var endDate = de.toString("dd/MM/yyyy");
			
			
			$("#gracePeriodDisplay").html(startDate + " to " + endDate);
			
			$("#graceFinalStartDate").val(startDate);
			$("#graceFinalEndDate").val(endDate);
	
		}

		$(".btnTakePayment").live("click", function ()
		{
			$( "#frmTakePayment" ).attr("customerProductPeriodID", $(this).attr("customerProductPeriodID"));
			
			objTakePaymentButton = this;
			
			$( "#frmTakePayment" ).dialog( "open" );
		});
		
		$(".btnAddProduct").live("click", function ()
		{
			$( "#customerID" ).val($(this).attr("customerID"));
			
			objTakePaymentButton = this;

			updateAddProductUI();

			$( "#frmAddProduct" ).dialog( "open" );
		});



		$(".btnAddCustomer").live("click", function ()
		{
			$( "#frmAddCustomer" ).dialog( "open" );
		});

		$("#btnChangeServer").live("click", function ()
		{
			
			objMoveServerButton = this;
//			alert($(this).attr("serverID") );
			
//			$("#frmChangeServerID").val(-1);
			$("#frmChangeServerID").val($(this).attr("serverID"));

			pleskRetrieveDomains($("#frmChangeServerID"), "#frmChangePleskID", $(this).attr("pleskID") );

			$("#frmChangeServerCustomerProductID").val( $(this).attr("customerProductID") );
			
			$( "#frmChangeServer" ).dialog( "open" );
		});

		

		
		

		$("#renewalPeriod").live("change", function ()
		{
			$val = $(this).val().split("@@");

			$("#renewalPeriodPrice").val($val[3]);
			updateDates();
		});

		$("#gracePeriod").live("change", function ()
		{
			updateDatesGrace();
		});

		$("#product").live("change", function ()
		{
			updateAddProductUI();
		});

		$("#pleskID").live("change", function ()
		{
			$("#name").val( $("#pleskID option:selected").text() );
		});


		function pleskRetrieveDomains(objServerID, resultElementID, selectedPleskID)
		{
		

				$(".frmAddProduct_serverID").css("display", "block");
				
				$.ajax({
					url: 'ajax/ajax.server.listDomains.php',
					data: "serverID=" + $(objServerID).val() + "&selectedPleskID=" + selectedPleskID,
					cache: false,
					async:   false,
				  
					success: function(response) 
					{
//						alert(response);
						$(resultElementID).html(response);

					},
					error: function(data)
					{
						alert("Error talking to server: " + data.status);
					}				
				   });
		
		}

		function updateAddProductUI()
		{
			val = $("#product").val().split("@@");
			
			$("#productID").val(val[0]);
			$("#productType").val(val[1]);
			$("#description").val( $("#product option:selected" ).text() );
			
//			alert(val[1]);
			
			$(".frmAddProduct_serverID").css("display", "none");
			$(".frmAddProduct_registrarID").css("display", "none");
			
			if (val[1] == "hosting") {
				
				pleskRetrieveDomains($("#serverID"), "#pleskID", -1);
				

				
				
				
				$("#frmAddProductLabelName").html("Website Name");
				
				
			}
			else if (val[1] == "domain") {
				$(".frmAddProduct_registrarID").css("display", "block");
				$("#frmAddProductLabelName").html("Domain Name");
			}
			else {
				$("#frmAddProductLabelName").html("Name");
			}
			
			

		}





		$(".btnRenew").live("click", function ()
		{
			$( "#frmRenew" ).attr("customerProductID", $(this).attr("customerProductID"));

			objTakePaymentButton = this;

//			$( "#frmRenew" ).attr("customerProductID", $(this).attr("customerProductID"));

			$.ajax({
				url: 'ajax/ajax.renew.start.php',
				data: "customerProductID=" + $(this).attr("customerProductID"),
				cache: false,
				async:   false,
			  
				success: function(response) 
				{
					//	alert(response);


					$("#renewalPeriod").html(response);
					
					if (response == "")
					{
						alert("ERROR: There are no billing periods and prices set up for this product. Cannot subscribe to this product.");
						$( "#frmRenew" ).dialog( "close" );
						return;
					}
					
					$val = $("#renewalPeriod").val().split("@@");
					
					$("#renewalPeriodDisplay").html($val[1] + " to " + $val[2]);
					$("#renewalPeriodPrice").val($val[3]);
					
					$("#renewStartDate").css("display", "none");
					
					if ($val[1] == 0)
					{
						$("#renewStartDate").css("display", "block");
						var d = new Date();
						$("#startDate").val(d.toString("dd/MM/yyyy"));
					}
					else
					{
						$("#startDate").val($val[1]);
					}
					updateDates();
	
					$( "#frmRenew" ).dialog( "open" );

						
				},
				error: function(data)
				{
					alert("Error getting renewal information: " + data.status);
				}				
			   });

			
	
			
		});




		$(".btnAddGracePeriod").live("click", function ()
		{
			$( "#frmAddGrace" ).attr("customerProductID", $(this).attr("customerProductID"));

			objTakePaymentButton = this;

//			$( "#frmRenew" ).attr("customerProductID", $(this).attr("customerProductID"));

			$.ajax({
				url: 'ajax/ajax.grace.start.php',
				data: "customerProductID=" + $(this).attr("customerProductID"),
				cache: false,
				async:   false,
			  
				success: function(response) 
				{
						//alert(response);


					$("#gracePeriod").html(response);
					
					
					$val = $("#gracePeriod").val().split("@@");
					
					$("#gracePeriodDisplay").html($val[1] + " to " + $val[2]);

					
					
					$("#graceStartDate").val($val[1]);
	
					$( "#frmAddGrace" ).dialog( "open" );
					updateDatesGrace();

						
				},
				error: function(data)
				{
					alert("Error getting grace period information: " + data.status);
				}				
			   });

			
	
			
		});

		
		
		$(".customer_product_row_expand_contract").click ( function ()
		{
			expandContractCutomerProduct(this);
			

		});
	
	});


	function loadCustomerProductDetail(customerProductID,  panel_detail)
	{
		$.ajax({
			url: 'ajax/ajax.customerProductDetail.php',
			data: "customerProductID=" + customerProductID,
			cache: false,
			async:   false,
		  
			success: function(response) 
			{
//				alert(response);
				response = response.split("@@@@");

				panel_detail.html(response[2]);
				
				var objSummaryRowExpiryDate = panel_detail.parents(".customer_product_row").children(".customer_product_row_expiry");
				
				objSummaryRowExpiryDate.html(response[0] + " " + response[1] );
//				$(".customer_product_row_expiry").attr("class", response[0]);
			},
			error: function(data)
			{
				alert("Error retrieving product detail: " + data.status);
			}				
	   });
	
	}

	function expandContractCutomerProduct(objCalling)
	{
		var panel_detail = $(objCalling).parent().children(".customer_product_detail");
		var customer_row = panel_detail.parent();

		if (panel_detail.css("height") == "0px")
		{

			customer_row.css("height", "auto");
//		alert(customer_row.css("height"));
			panel_detail.css("overflow","scroll");
			panel_detail.css("border","1px solid #999");

			panel_detail.animate({height : "500px"}, 300, function ()
			{
				loadCustomerProductDetail( $(objCalling).attr("customerProductID"), panel_detail );
			});
			
			
		}
		else
		{
			panel_detail.css("overflow","hidden");

			panel_detail.html("");

			panel_detail.animate({height : "0px"}, 500, function ()
			{
				panel_detail.html("<div class='loading'>loading...</div>");
				panel_detail.css("border","none");
				customer_row.css("height", "22px");
			});
			
		}
		
		
		
	}

