// JavaScript Document
jQuery(document).ready(function($){
	$('#ticket-form').ajaxForm( { beforeSubmit: validate, url: '/wp-content/plugins/ticket-system/action.php?Action=Insert', success: showResponse, resetForm: true } );
	$('#replyForm').ajaxForm( { beforeSubmit: repValidate, url: '/wp-content/plugins/ticket-system/action.php?Action=Reply', success: redirect, resetForm: true } );
});

function validate(formData, jqForm, options) { 
    //var form = jqForm[0]; 
    var form_fields = new Array("Company Name","Customer Name","Email Address","Domain Affected","Subject","Problem");
	var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	var watcher = 0;
	for(i=0;i<form_fields.length;i++)
	{
		if (document.getElementById(form_fields[i]).value == "") { 
			document.getElementById('TS-'+i).style.display = "inline";
			watcher = 1;
		}
		else if(i==2)
		{
			if (!emailfilter.test(document.getElementById(form_fields[i]).value)) {
				document.getElementById('TS-2').innerHTML = "Please provide a valid Email Address";
				document.getElementById('TS-2').style.display = "inline";
				watcher = 1;
			}
			else
			{
				document.getElementById('TS-2').style.display = "none";
			}
		}
		else
		{
			document.getElementById('TS-'+i).style.display = "none";
		}
	}
	if(watcher == 1) { return false; }
	//document.getElementById("Submit").value = 'Saving....';
	//document.getElementById("Submit").disabled = true;
}

function showResponse(responseText, statusText, xhr)
{
	if(responseText=='')
	{
		alert('Ticket Submitted.');
	}
	else { window.location = 'http://'+responseText; }
}

function repValidate()
{
	if(document.getElementById("response").value == "")
	{
		alert("Reply is required."); return false;
	}
	document.getElementById("Submit").value = 'Saving....';
	document.getElementById("Submit").disabled = true;
}

function redirect()
{
	window.location.reload();
}

function ticketOnOff(trig,Id)
{
	//Close ticket
	if(trig=='Close')
	{
		var tsTimeStamp = new Date().getTime();
		jQuery.get("/wp-content/plugins/ticket-system/action.php?Action=CloseTicket", { TicketId: Id, time: tsTimeStamp }, function(str){
			window.location.reload();
		});
	}
	else if(trig=='Open')
	{
		//Open ticket
		var tsTimeStamp = new Date().getTime();
		jQuery.get("/wp-content/plugins/ticket-system/action.php?Action=OpenTicket", { TicketId: Id, time: tsTimeStamp }, function(str){
			window.location.reload();
		});
	}
}