//var strURLBase = "https://beta.ebaratech.com/sales";
//strURLBase = "http://localhost/ebara";
var strURLBase = "https://www.ebaratech.com/sales";
var strGenericErrorMessage = "An error has occurred.  Please try your transaction again.";
var divLogin;
var divAjaxSection;
var divProgressBar;

// ***************************************************************************************

var cArray = new Array();
var userArray = new Array(Array('id','userID','IDToEdit',''),Array('ln','lastName','tbLastName','Last Name'),Array('fn','firstName','tbFirstName','First Name'),Array('a1','address1','tbAddress1','Address1'),Array('a2','address2','xAddress2','Address 2'),Array('cty','city','tbCity','City'),Array('st','state','tbState','State'),Array('cntry','country','tbCountry','Country'),Array('pc','postalCode','tbPostalCode','Postal Code'),Array('e','emailAddress','tbEmailAddress','Email Address'),Array('pwd','password','tbPassword','Password'),Array('opwd','password','hdPWD','Password'),Array('wp','workPhone','tbWorkPhone','Work Phone'),Array('mp','mobilePhone','xMobilePhone','Mobile Phone'),Array('fx','fax','xFax','Fax'),Array('g','groupID','selGroup','Group'),Array('s','status','selStatus','Status'),Array('t','title','tbTitle','Job Title'),Array('cmpy','company','tbCompany','Company'));
var documentArray = new Array(Array('id','documentID','IDToEdit',''),Array('dn','documentName','xDocumentName','Document Name'),Array('dc','documentCategoryID','selDocumentCategoryID','Document Category'),Array('ds','documentSeriesID','selDocumentSeriesID','Document Series'),Array('dt','documentTypeID','selDocumentTypeID','Document Type'),Array('dm','documentModelID','selDocumentModelID','Document Model'),Array('dp','documentProductID','selDocumentProductID','Document Product'));
//				   Description, code, Array,   Widget Name, Save Action Field, Containing DIV, 	 Write Output To,  Callback Variable
cArray[0] = Array('User','usr', userArray, 'salesRepWidget', 'saveAction', 'divAjaxSection', 'divTableSection', 'saveCallback');
cArray[1] = Array('Document','doc',documentArray,'salesRepWidget','saveAction','divAjaxSection','divTableSection','saveCallback');

var handleFailure = function(o) {
	divProgressBar.hide();
	alert(strGenericErrorMessage);
};

var onSuccess = function (o) {
	divProgressBar.hide();
	var bIsJSON = true;
	try {
		var objResult = YAHOO.lang.JSON.parse(o.responseText);
	}
	catch (objError) {
		bIsJSON = false;
	}
	if (bIsJSON) {
		switch (objResult.resultCode) {
			case 200 :
				document.getElementById("divItemTable").innerHTML = objResult.resultText;
				break;
			default :
				alert(objResult.resultText);
		}
	}
	else {
		alert('An error has occurred.  Please try your transaction again.');
	}
}
var handleSuccess = function(o) {
	divProgressBar.hide();
    if (o.status = "200") {
		var bIsJSON = true;
		try {
			var objResult = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (objError) {
			bIsJSON = false;
		}
		if (bIsJSON) {
			switch (objResult.resultCode) {
				case 200 :
					document.getElementById("divItemTable").innerHTML = objResult.resultText;
					break;
				default :
					alert(objResult.resultText);
			}
		}
		else {
			document.getElementById(cArray[o.argument[0]][6]).innerHTML = o.responseText;
			if (cArray[o.argument[0]][5].length > 0)
				eval(cArray[o.argument[0]][5]).hide();
			if (o.argument[1].length > 0) {
				eval(o.argument[1]);
			}
		}
	}
    else
		alert("Unable to complete request.  Please try your transaction again.");
};

var saveCallback = {success:handleSuccess,failure:handleFailure,argument:[0,'']};
var documentCallback = {success:onSuccess,failure:handleFailure};

function onload_Users() {
	divAjaxSection = new YAHOO.widget.Panel('divAjaxSection', { modal:false, width:'400px', visible:false, draggable:true, close:true, iframe:true, constraintoviewport:true, zIndex:99}); 
	divAjaxSection.render();
	
	divProgressBar = new YAHOO.widget.Dialog("divProgressBar", {
	    width: "240px", 
	    fixedcenter: true, 
	    constraintoviewport: true, 
		draggable: false,
		visible: false,
		close: false,
	    underlay: "shadow",
		modal: true	
	});
	
	divProgressBar.render();
}

function onload_Documents() {
	divAjaxSection = new YAHOO.widget.Dialog("divAjaxSection", {
	    width: "500px", 
	    fixedcenter: true, 
	    constraintoviewport: true, 
		draggable: true,
		visible: false,
		close: true,
	    underlay: "shadow",
		modal: true,
		buttons : [ { text:"Save", handler:submitForm, isDefault:true }, { text:"Cancel", handler:closeDialog } ]
	
	});
	
	divAjaxSection.render();
	
	divProgressBar = new YAHOO.widget.Dialog("divProgressBar", {
	    width: "240px", 
	    fixedcenter: true, 
	    constraintoviewport: true, 
		draggable: false,
		visible: false,
		close: false,
	    underlay: "shadow",
		modal: true	
	});
	
	divProgressBar.render();
}

function onload_HQAdmin() {
	divProgressBar = new YAHOO.widget.Dialog("divProgressBar", {
	    width: "240px", 
	    fixedcenter: true, 
	    constraintoviewport: true, 
		draggable: false,
		visible: false,
		close: false,
	    underlay: "shadow",
		modal: true	
	});
	
	divProgressBar.render();
}

function submitForm() {
	document.getElementById('xDocumentName').disabled = false;
	if (validateItem(1)) {
		
		divAjaxSection.callback.success = onSuccess;
		divAjaxSection.callback.upload = onUpload;
		divAjaxSection.callback.failure = onFailure;
		this.submit();
		divProgressBar.show();
	}
}

function closeDialog() {
	this.cancel();
}
var onFailure = function (o) {
	divProgressBar.hide();
	alert('Failure!');
}
var onUpload = function (o) {
	var bIsJSON = true;
	try {
		var objResult = YAHOO.lang.JSON.parse(o.responseText);
	}
	catch (objError) {
		bIsJSON = false;
	}
	//alert(o.responseText);
	if (bIsJSON) {
		switch (objResult.resultCode) {
			case 200 :
				var strURL = strURLBase + "/save.php";
				var postData = "a=getdocs";
				var request = YAHOO.util.Connect.asyncRequest('POST', strURL, documentCallback, postData);
				break;
			default :
				divProgressBar.hide();
				alert(objResult.resultText);
		}
	}
	else {
		divProgressBar.hide();
		alert('An error has occurred. '+ (objError.number & 0xFFFF) + ' - ' + objError.description);
	}	
}

function newItem(arrayIndex) {
	if (arrayIndex == 1) {
		document.getElementById('rowDocumentName').style.display = 'none';
		document.getElementById('xDocumentName').disabled = true;
		document.getElementById('rowDocumentFile').style.display = '';
		document.getElementById('tbDocumentFile').disabled = false;
	}
	
	for (i=0; i<cArray[arrayIndex][2].length; i++) {
		if (((cArray[arrayIndex][2][i][2]).substring(0,1) == "t") || ((cArray[arrayIndex][2][i][2]).substring(0,1) == "x"))
			document.getElementById(cArray[arrayIndex][2][i][2]).value = '';
		else
			if ((cArray[arrayIndex][2][i][2]).substring(0,1) == "s") {
				if (arrayIndex == 13) {
					document.getElementById(cArray[arrayIndex][2][i][2]).value = document.getElementById(cArray[arrayIndex][2][i][1]).value;
				}
				else
					document.getElementById(cArray[arrayIndex][2][i][2]).selectedIndex = 0;
			}
	}
	document.getElementById(cArray[arrayIndex][4]).value = 'ADD';
	eval(cArray[arrayIndex][5]).center();
	eval(cArray[arrayIndex][5]).show();
}

function editItem(arrayIndex, id) {
	if (arrayIndex == 1) {
		document.getElementById('rowDocumentName').style.display = '';
		document.getElementById('xDocumentName').disabled = true;
		document.getElementById('rowDocumentFile').style.display = 'none';
		document.getElementById('tbDocumentFile').disabled = true;
	}
	
	for (i=0; i<cArray[arrayIndex][2].length; i++) {
		//alert(cArray[arrayIndex][2][i][2]);
		//alert(cArray[arrayIndex][2][i][1]+id);
		document.getElementById(cArray[arrayIndex][2][i][2]).value = document.getElementById(cArray[arrayIndex][2][i][1]+id).value
	}
	document.getElementById(cArray[arrayIndex][4]).value = 'EDIT';
	eval(cArray[arrayIndex][5]).center();
	eval(cArray[arrayIndex][5]).show();
	if (arrayIndex == 1 && document.getElementById('xDocumentName').value == 'TEMPORARY FILENAME')
		document.getElementById('xDocumentName').disabled = false;
}

function validateItem(arrayIndex)
{
	strErrors = "";
	for (i=0; i<cArray[arrayIndex][2].length; i++) {
		//alert(cArray[arrayIndex][2][i][2]);
		if ((cArray[arrayIndex][2][i][2]).substring(0,1) == "t") {
			if (document.getElementById(cArray[arrayIndex][2][i][2]).value.length < 1)
				strErrors = strErrors + "- " + cArray[arrayIndex][2][i][3] + " cannot be blank.\n";
		}
		else {
			if ((cArray[arrayIndex][2][i][2]).substring(0,1) == "s")
				if (document.getElementById(cArray[arrayIndex][2][i][2]).value == "0")
					strErrors = strErrors + "- You must choose a value for " + cArray[arrayIndex][2][i][3] + ".\n";
		}
	}
	if (strErrors.length > 0) {
		alert('Correct the error(s) below and submit again.\n' + strErrors);
		return false;
	}
	return true;
}

function saveItem(arrayIndex) {
	var callbackFunction = eval(cArray[arrayIndex][7]);
	if (validateItem(arrayIndex)) {
		var strURL = strURLBase + "/save.php";
		var postData;
		if (document.getElementById(cArray[arrayIndex][4]).value == "ADD")
			postData = "a=a"+cArray[arrayIndex][1];
		else {
			postData = "a=e"+cArray[arrayIndex][1];
		}
		for (i=0; i<cArray[arrayIndex][2].length; i++) {
				postData = postData + "&" + cArray[arrayIndex][2][i][0] + "=" + escape(document.getElementById(cArray[arrayIndex][2][i][2]).value);
		}
		divProgressBar.show();
		var request = YAHOO.util.Connect.asyncRequest('POST', strURL, callbackFunction, postData);
	}
}
function deleteItem(arrayIndex, id) {
	var callbackFunction = eval(cArray[arrayIndex][7]);
	if (confirm('Are you sure you want to delete this item?')) {
		var strURL = strURLBase + "/save.php";
		var postData = "a=d" + cArray[arrayIndex][1] + "&id=" + document.getElementById(cArray[arrayIndex][2][0][1]+id).value;
		divProgressBar.show();
		var request = YAHOO.util.Connect.asyncRequest('POST', strURL, callbackFunction, postData);
	}
}

// ***************************************************************************************

var handleFailure = function(o) {
	alert(strGenericErrorMessage);
};


// *************** LOGIN
function onload_Login(){
	divLogin = new YAHOO.widget.Panel('divLogin', { width:'300px', context:['anchor','tl','bl'], visible:true, draggable:false, close:false, constraintoviewport:true}); 
	divLogin.render();
}
function processLogin() {
	var strURL = strURLBase + "/save.php";
	var postData = "a=l&u=" + document.getElementById("tbUsername").value;
	postData = postData + "&p=" + document.getElementById("tbPassword").value;
	if (document.getElementById("chkRemember").checked)
		postData = postData + "&r=1";
	else
		postData = postData + "&r=0";
	document.getElementById("divMessage").innerHTML = "<b>Processing Login...</b>";
	var request = YAHOO.util.Connect.asyncRequest('POST', strURL, loginCallback, postData);
}

var handleSuccess_Login = function(o) {
    if (o.status = "200") {
		if (o.responseText == 0)
			document.location.href = strURLBase + "/index.php?target=welcome";
		else
			document.getElementById("divMessage").innerHTML = "<b><font style='color:red'>Username/Password Incorrect</font></b>";
	}
    else
		alert("Unable to complete request.  Please try your transaction again.");
};

var loginCallback =
{
  success:handleSuccess_Login,
  failure:handleFailure
};

function IsEnterKey(e) {
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else{
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}

	if(characterCode == 13) //if generated character code is equal to ascii 13 (if enter key)
		processLogin();
	else
		return false; 
}
