var equipmentSelected = 0;


function getLocation(form) {
	
	//if($F('eLocation') == 0) { $('divAddEquipmentForm').show(); $('sSerialAdd').focus(); }else{ $('divAddEquipmentForm').hide(); }
	

	$('divMessagePanel').show();

	$('divAddEquipmentLog').hide();
	$('divAddEquipment').hide();
	$('divEquipPool').show();
	$('divEquipment').show();
	$('divJobSearch').hide();


	if($F('eLocation') > 0)  { 
		
		$('divIssueEquipmentForm').show();  $('eLocationIssue').value = $F('eLocation'); 
		$('divEquipPu').show();
		$('sSerialPU').value = '';
		$('pickedUpEquipment').innerHTML = '';
		$('eLocationPU').value = $F('eLocation'); 
		$('divAddEquipmentForm').hide();
		$('boxWorkOrderActivity').show();
		$('divReturnEquipmentForm').show();
		$('divGetEquipmentForm').hide(); 
		$('divArchive').hide();
		
		$('eLocationTo').value = 0;

	}else{ 


		$('divGetEquipmentForm').show(); 
		$('eLocationGet').value = $F('eLocation'); 
		$('divIssueEquipmentForm').hide(); 
		$('divEquipPu').hide();
		$('divAddEquipmentForm').show();
		$('boxWorkOrderActivity').hide();
		$('divReturnEquipmentForm').hide();
		$('divArchive').hide();
		
	}
		
	if($F('eLocation')< 0)  { $('divArchive').show();  $('divReturnEquipmentForm').hide(); } 


	if($F('eLocation') == 0)  { $('divEquipment').hide(); }

	equipmentSelected = 0;

	new Ajax.Updater('divEquipPool', 'processEquipment.php?eLocation=' + $F('eLocation'), {
		asynchronous:true, 
		evalScripts:true, 
		parameters:Form.serialize(form),
		onComplete: function() {
			//do stuff	
		}
	});

}



function toggleCheckbox(serialCheckbox, serial) {
	var myRow;

	//eval("myRow=document.all." + trim(serial) + ";");
	myRow=$(trim(serial));
	if (serialCheckbox.checked != true) {

		if($('checkAll')) $('checkAll').checked = false;

		myRow.style.backgroundColor = "#ffffff";
		equipmentSelected--;
		document.all.divItemsSelected.innerHTML = "Items Selected: " + equipmentSelected;
	}else{
		myRow.style.backgroundColor = "#cccccc";
		equipmentSelected++;
		document.all.divItemsSelected.innerHTML = "Items Selected: " + equipmentSelected;
	}

}

function trim(str)
{
   return str.replace(/ /g, "");
}


	
function checkAllEquipment(targetform)
{

  for (i = 0; i < targetform.elements.length; i++)
  {
	 
    if (targetform.elements[i].type == "checkbox")
    {

		myString = new String(targetform.elements[i].id);
		serial = myString.replace(/checkbox/gi, '');
     
		 if ($('checkAll').checked == false && targetform.elements[i].id !='checkAll' )
		{
			$('row' + serial).style.backgroundColor = "#ffffff";
			targetform.elements[i].checked = false	
			equipmentSelected --;
		}else

	  if(targetform.elements[i].checked == false && targetform.elements[i].id !='checkAll' )
      {
		
		$('row' + serial).style.backgroundColor = "#cccccc";
        targetform.elements[i].checked = true;
		equipmentSelected ++;
      }
    }
  }

  document.all.divItemsSelected.innerHTML = "Items Selected: " + equipmentSelected;
}



function selectEquipment(checkbox, row) {

	if ($(checkbox)) {
		$(checkbox).checked = true;
		$(row).style.backgroundColor = "#cccccc";
		$('sSerial').value = "";
		$('sSerial').focus();
		equipmentSelected++; 
		$('divItemsSelected').update("Items Selected: " + equipmentSelected);

	}else{
		

		$('divPoolActivity').update($('divPoolActivity').innerHTML + "<span style=\"color:red\"><img src=\"../images/cell.gif\" width=\"1\" height=\"10\" border=\"0\" alt=\"\"><br>" + $('sSerial').value + " not found in location pool</span>");
		alert($('sSerial').value + ' not found in location pool');
		$('sSerial').value = "";
		$('sSerial').focus();
	}
}

function reconcileEquipment() {
	$('eLocationTo2').value=$F('eLocationTo');
	new Ajax.Updater('divEquipPool', 'processEquipment.php', {asynchronous:true, evalScripts:true, parameters:Form.serialize(frmEquipPool)}); return false;
}


function reconcilePUEquipment() {
	document.all.eLocationPU.value = document.all.location.options[document.all.location.options.selectedIndex].value;
}

function showEquipmentHistory(ePoolId) {

var left = event.clientX + document.body.scrollLeft + 90; 
var top = event.clientY + document.body.scrollTop + 10; 

$('divEquipHistory').style.display='block'
$('divEquipHistory').style.top = top

new Ajax.Updater('divEquipHistory', 'processEquipment.php?mode=showEquipmentHistory&ePoolId=' + ePoolId, {asynchronous:true, evalScripts:true });

}

function showEquipmentNotes(ePoolId, userId) {

var left = event.clientX + document.body.scrollLeft - 350; 
var top = event.clientY + document.body.scrollTop + 10; 

$('divEquipNotes').show();

if (userId) $('divEquipNotes').style.left = left;
if (ePoolId) $('divEquipNotes').style.left = 420;

$('divEquipNotes').style.top = top;


new Ajax.Updater('divEquipNotes', 'processEquipment.php?mode=showEquipmentNotes&ePoolId=' + ePoolId + '&userId=' + userId, {asynchronous:true, evalScripts:true });

}

function deleteEquipmentNotes(equipNoteId, ePoolId, userId) {


var left = event.clientX + document.body.scrollLeft; 
var top = event.clientY + document.body.scrollTop + 10; 

new Ajax.Updater('divEquipNotes', "processEquipment.php?mode=deleteEquipmentNote&equipNoteId=" + equipNoteId + "&ePoolId=" + ePoolId + "&userId=" + userId + "&left=" + left + "&top=" + top, {asynchronous:true, evalScripts:true});

}

function confirmWorkOrder(workOrderId, techId)
{
	new Ajax.Updater('divWorkOrderActivity', 'processEquipment.php?mode=confirmWO&techId=' + techId + '&workOrderId=' + workOrderId, {asynchronous:true, evalScripts:true});

}

function buildSummary(equipmentType)
{

	$('divEquipPool').hide();
	$('divAddEquipment').show();
	//alert('div' + equipmentType);
	$('div' + equipmentType).show();
	$('typeQuantity' + equipmentType).show();
	$('divTotal').show();

	$('typeQuantity' + equipmentType).innerHTML++;
	$('divTotal').innerHTML++;
	
}

function searchEquipment(form)
{
	var archive = '';

	//alert($('archive').checked);
	if($('divEquipment')) { $('divEquipment').show(); } 
	$('divEquipPool').show(); 

	new Ajax.Updater('divEquipPool', 'processEquipment.php?mode=searchEquipment', {asynchronous:true, evalScripts:true, parameters:Form.serialize(form)}); 
	$('searchSerial').value = '';
	$('searchSerial').focus();
	
	return false;
}


function searchWorkOrders(form)
{
	$('divEquipment').style.display='none'; 
	$('divMessagePanel').style.display='none';  
	$('divJobSearch').style.display='block';
	$('divJobList').style.display='block'; 
	showLoading('divJobList'); 
	new Ajax.Updater('divJobList', 'processWo.php', {asynchronous:true, evalScripts:true, parameters:Form.serialize(form)}); 
	return false;

}


function unarchiveEquipment(form)
{

	new Ajax.Updater('divEquipPool', 'processEquipment.php', {asynchronous:true, evalScripts:true, parameters:Form.serialize(form)}); 

	
	return false;
}


/////////////////////////////

function getLostEquipment() {

	equipmentSelected = 0;
	clearAddActivity();
	$('divEquipPool').show();
	new Ajax.Updater('divEquipPool', 'processEquipment.php?mode=selectLostLocation&eLocation=0&eStatus=' + $F('eLocation'), {asynchronous:true, evalScripts:true});

}

function getDefaultToolPrice(toolId)
{

	$('issueQuantity').value = 1;

	url = "processEquipment.php";
	pars = "mode=getDefaultToolPrice&toolId=" + toolId;
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'post', 
				parameters: pars, 
				onComplete: showDefaultToolPrice
			});
		
	}


	function showDefaultToolPrice(originalRequest)
	{
		//put returned XML in the textarea
		$('usedPrice').value = originalRequest.responseText;
	}

function moveTools(myForm){
	
	var mychecked = false;

	for (i=0; i<frmToolList.elements.length; i++) {

		if (frmToolList.elements[i].type == "checkbox") {
			 if (frmToolList.elements[i].checked) {
			  mychecked = true;
			}
		 }
	}

	if (mychecked) {

	//$('frmToolList').locationTo.value=myForm.locationTo.options[myForm.locationTo.options.selectedIndex].value
	
	new Ajax.Updater('divEquipPool', 'processEquipment.php', {asynchronous:true, evalScripts:true, parameters:Form.serialize($('frmToolList'))});
	//$('frmToolList').submit();

	}else{
		return;
	}
}

function showToolHistory(e, id) {

var coords = getMouseCoords(e);

$('divEquipHistory').style.display='block';
$('divEquipHistory').style.top = coords['top'];

new Ajax.Updater('divEquipHistory', 'processEquipment.php?mode=showToolHistory&id=' + id, {asynchronous:true, evalScripts:true});


}
/*
function showToolHistory(id) {

var left = event.clientX + document.body.scrollLeft + 90; 
var top = event.clientY + document.body.scrollTop + 10; 
$('divEquipHistory').style.display='block';
$('divEquipHistory').style.top = top;

new Ajax.Updater('divEquipHistory', 'processEquipment.php?mode=showToolHistory&id=' + id, {asynchronous:true, evalScripts:true});


}

*/


function getTechToolTypeOptions(userId)
{


	url = "processEquipment.php";
	pars = "mode=getTechToolReturnOptions&userId=" + userId;
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onComplete: fillTechToolTypeoptions
			});
		
	}


function fillTechToolTypeoptions(request, json )
	{		
		var counter=0;
		$("returnToolOptions").update();

		json.each(function(option) {   
			
		  var y=document.createElement('option');
		  y.value=json[counter][0];
		  y.text=json[counter][1];
		  var x=$("returnToolOptions");
		  try
			{
			x.add(y,null); // standards compliant
			}
		  catch(ex)
			{
			x.add(y); // IE only
			}
		  
			counter++;
		
		}); 
		
	}


function getTechIssueToolTypeOptions()
{

	new Ajax.Updater('issueToolOptionsContainer', 'processEquipment.php?mode=getWarehouseToolTypeOptions', {asynchronous:true, evalScripts:true});

	return;

	url = "processEquipment.php";
	pars = "mode=getWarehouseToolTypeOptions";
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onComplete: fillTechIssueTypeOptions
			});
		
	}


function fillTechIssueTypeOptions(request, json )
	{		
		var counter=0;
		$("issueToolOptions").update();

		json.each(function(option) {   
			
		  var y=document.createElement('option');
		  y.value=json[counter][0];
		  y.text=json[counter][1];
		  var x=$("issueToolOptions");
		  try
			{
			x.add(y,null); // standards compliant
			}
		  catch(ex)
			{
			x.add(y); // IE only
			}

		  
			counter++;
		
		}); 
		
	}

	function getWarehouseToolTypeOptions(locationId)
{

/*
	url = "processEquipment.php";
	parms = "mode=getWarehouseToolTypeOptions&locationId=" + locationId;
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: parms, 
				onComplete: fillWarehouseTypeOptions
			});
	*/
		parms = "mode=getWarehouseToolTypeOptions&locationId=" + locationId;
		new Ajax.Updater('warehouseToolTypes', 'processEquipment.php', {asynchronous:true, evalScripts:true, parameters: parms});

	}


	


function fillWarehouseTypeOptions(request, json )
	{		
		var counter=0;
		$("transferToolOptions").update();

		json.each(function(option) {   
			
		  var y=document.createElement('option');
		  y.value=json[counter][0];
		  y.text=json[counter][1];
		  var x=$("transferToolOptions");
		  try
			{
			x.add(y,null); // standards compliant
			}
		  catch(ex)
			{
			x.add(y); // IE only
			}

		  
			counter++;
		
		}); 
		
	}


	function getToolReturnForm(id)
	{

		$('divReturnTools').show();
		url = "processEquipment.php";
		pars = "mode=getToolReturnRecord&toolIssuedId=" + id;
		var myAjax = new Ajax.Request(
				url, 
				{
					method: 'get', 
					parameters: pars, 
					onComplete: function (request, json) {

						$('returnQuantity').value =  json['quantity'];
						$('returnPrice').value =  json['price'];
						$('toolType').update(json['toolName']);
						$('toolIssuedId').value =  json['toolIssuedId'];
						

					}
				});
			
		}
	
	function showWarehouseEquipment()
	{
	
		$('divEquipment').show();
		new Ajax.Updater('divEquipPool', 'processEquipment.php?mode=showWarehouseEquipment', {asynchronous:true, evalScripts:true});
	}


	function stopEquipmentScan(message)
	{

		//popUp('badscan.php?m=' + message, 200, 200, 'scan');
		
		if(confirm(message + '\nCancel to continue')) { stopEquipmentScan(message); }else{ return;}

	}

	function deleteEquipment(id, div)
	{	
		if(confirm('delete equipment?') ) {
			new Ajax.Updater(div, 'processEquipment.php?mode=deleteEquipment&ePoolId=' + id, {asynchronous:true, evalScripts:true});
		}

	}

	function deleteTool(id, div)
	{
		//if(!confirm('Are you f*ckin nuts!!??')) return;
		if(confirm('delete tool?') ) {
			new Ajax.Updater(div, 'processEquipment.php?mode=deleteTool&toolIssuedId=' + id, {asynchronous:true, evalScripts:true});
		}
		
		return;
	}

	function chooseVendor(vendorId)
	{
		new Ajax.Updater('divVendorForm', 'processEquipment.php?mode=editVendor&action=showEditVendorForm&vendorId=' + vendorId, {asynchronous:true, evalScripts:true});
	}
	
	function recieveTool(form)
	{	
		
		var valid = true;
		var error_message = '';
		
		if(!$j('#receiveToolId').val())
		{	
			valid = false;
			error_message += 'Tool type required!<br />';
		}

		if(!$j('#po').val())
		{
			valid = false;
			error_message += 'PO required!<br />';
		}

		
		if(!$j('#receiveQuantity').val())
		{	
			valid = false;
			error_message += 'Qty required!<br />';
		}


		
		if(!valid) { $('divReceiveTool').update(error_message); return false; }
		
		new Ajax.Updater('divEquipPool', 'processEquipment.php', {asynchronous:true, evalScripts:true, parameters:Form.serialize(form),
			onComplete: function () 
			{
				$(form).reset();
			}
		}); 

		$('toolSerial').value = ''; 

		return false;
	}

	function resetReceiveToolsForm()
	{
		$('receiveQuantity').value = 1;
		$('toolSerial').value = '';
		$('vendorId').value = '';

	}

	function resetIssueToolsForm()
	{
		$('receiveQuantity').value = 1;
		$('toolSerial').value = '';
		$('vendorId').value = '';

	}

	function retireTool(checkbox)
	{	
		//alert($(checkbox).value); return;
		$('divRetireContainer').hide(); 
		if ($j("input[@type='checkbox'][@name='toolIssuedId[]']:checked").length) { 
			$('divRetireContainer').show(); 
			$j('#retireComments').focus(); 
			
		}			
	}

	function retireSelectedTools()
	{
		if(!confirm('retire slected tools?')) { return false; }		
		$j('#toolListMode').val("retireTools");

		//alert( $j('form#frmToolList').serialize());

		var data = $j('form#frmToolList').serialize();

		$j.ajax( 
				{ 
					type: "POST", 
					url: "processEquipment.php", 
					data: data , 
					success: 
						function(t) 
						{ 
							$j("div#divRetire").empty().append(t); 
							showToolList();
						}, 
					error: 
						function() 
						{ 
							$j("div#divRetire").append("An error occured during processing"); 
						} 
				}); 
		

	}

	function showToolList()
	{	

		var  data = "mode=selectToolsLocation&toolLocationId=" + $F('toolLocationId');

		$j.ajax( 
				{ 
					type: "POST", 
					url: "processEquipment.php", 
					data: data, 
					success: 
						function(t) 
						{ 
							$j("div#divEquipPool").empty().append(t);
						}, 
					error: 
						function() 
						{ 
							$j("div#divEquipPool").append("An error occured during processing"); 
						} 
				}); 
		
		return false;
	
	}


//$j(document).ready(function(){ 	$j('#startDate').datepicker(); });


	function getRetireReportOptions(radio)
	{
		if($F(radio) == 'office')
		{	

			$('retireReportDateForm').hide();
			$('retireReportLocationForm').show();
		}

		if($F(radio) == 'date')
		{	
			$('retireReportLocationForm').hide();
			$('retireReportDateForm').show();

			
			 

		}


	}

	function runRetiredToolsReport()
	{
		
		if($('retireReportByOffice').checked && $('locationId[]').value == '') { alert('please choose one or more offices'); return false;}
		if($('retireReportByDate').checked && $('startDate').value == '') { alert('please enter a start date'); return false;}


	}

	function loadToolSummaryBox(userId, locationId)
	{
		var  data = "mode=loadToolSummaryBox&userId=" + userId + '&locationId=' + locationId;

		$j.ajax( 
				{ 
					type: "POST", 
					url: "processEquipment.php", 
					data: data, 
					success: 
						function(t) 
						{ 
							$j("div#divEquipPoolStatus").empty().append(t);
						}, 
					error: 
						function() 
						{ 
							$j("div#divEquipPoolStatus").append("An error occured during processing"); 
						} 
				}); 

	}

	function issueTools(form)
	{

		$('issueLocationId').value = $F('toolLocationId'); 

		new Ajax.Updater('divEquipPool', 'processEquipment.php', {
				asynchronous:true, 
				evalScripts:true, 
				parameters:Form.serialize(form), 
				onComplete: function() { 
					loadToolSummaryBox($('issueLocationId').value, $('issueLocation').value);
				}
			
		
		}); 

		return false;

	}


	function returnTool(form)
	{
		$('userId').value = $F('toolLocationId'); 

		new Ajax.Updater('divEquipPool', 'processEquipment.php', {
			asynchronous:true, 
			evalScripts:true, 
			parameters:Form.serialize(form),
			onComplete: function() {
				equipmentSelected = 0;
				$('divMessagePanel').show();
				loadToolSummaryBox($('userId').value, $('returnLocationId').value);

			}

		}); 


		return false;
	}

	function showToolTypeTransactions(e, toolId, locationId)
	{
		
		var coords = getMouseCoords(e);
		
		if($j('#divToolTypeTransactions')) { $j('#divToolTypeTransactions').remove(); }

		div = document.createElement('div');
		div.id = 'divToolTypeTransactions';
		div.style.position = 'absolute';
		div.style.top =  coords['top']  + 'px'; 
		div.style.left =  (coords['left'] -500) + 'px';
		div.style.width = '500px'; 
		div.style.border = '1px solid #000000';
		document.body.appendChild(div);	

		
		$(div).addClassName('popin');
	
		
		var data = 'mode=showToolTypeTransactionsByDate&toolId=' + toolId + '&locationId=' + locationId;
		$j.ajax( 
				{ 
					type: "POST", 
					url: "processEquipment.php", 
					data: data, 
					success: 
						function(t) 
						{ 
							$j('div#divToolTypeTransactions').empty().append(t);
							$j(div).prepend("<div class=\"myHandle\"><div style=\"float: right\"><a href=\"javascript: //\" onmousedown=\"$j('#divToolTypeTransactions').remove();\" class=\"x_link\">[x]</a></div></div>");
							$j(div).draggable({ handle:  '.myHandle' });
						}, 
					error: 
						function() 
						{ 
							$j('div#divToolTypeTransactions').append("An error occured during processing"); 
						} 
				}); 



	}


	function showEquipmentManager(link)
	{	
		$j("#consumablesContainer").hide();
		$j('#equipmentContainer').show();
		resetLinks('menu', link); 
		new Ajax.Updater('divSelectors', 'processEquipment.php?mode=getEquipmentSelectors', {asynchronous:true, evalScripts:true});

	}

	function showToolManager(link)
	{	
		$j("#consumablesContainer").hide();
		$j('#equipmentContainer').show();
		resetLinks('menu', link); 
		new Ajax.Updater('divSelectors', 'processEquipment.php?mode=getToolSelectors', {asynchronous:true, evalScripts:true});

	}

	

