var do_over=1; //whether or not to allow the user to select a row for editing
var loc; //will contain the current location
var html; //will contain the ajax results
var id; //will contain current resource

$(document).ready(function(){
						   
	$(".resources tr:even").addClass("alt"); //add table striping
	
	//perform row hover
	$(".resources tr").hover(function() {
		if (do_over) {
			$(this).addClass("over");
		}
	}, function() {
		if (do_over) {
			$(this).removeClass("over");
		}
	});
	
	
	//initialize location
	loc=$("#loc_id").val();
	
	
	$(".resources tr").click(function() {
	  	//load contents of editable row
		if((do_over)&&($(this).hasClass("first")==false)){
			$(this).removeClass("over");
			$(this).addClass("sel");
			do_over=0; //row is selected so don't allow selecting anything else
			id=$(this).children(".rid").html();
			
			html = $.ajax({
			url: "resource-action.php?location_id=" + loc + "&action=get_input&rid=" + id,
			async: false
			}).responseText;	
			if(html.slice(0,2)=="<!"){
				//go back to the login page if the user has timed out/is no longer logged in
				window.location="login.php";
			}
			$(this).html(html);
		}
	});
});

function cancel() {
	do_over=1;
	html = $.ajax({
	url: "resource-action.php?location_id=" + loc + "&action=get_resource&rid=" + id,
	async: false
	}).responseText;	
	if(html.slice(0,2)=="<!"){
			window.location="login.php";
		}
	$(".sel").html(html);
	$(".sel").removeClass("sel");
}

function save() {
	do_over=1;
	html = $.ajax({
		url: "resource-action.php",
		global: false,
		type: "POST",
		async: false,
		data: ({location_id: loc,
				action: "save", 
				rid: id,
				rsc: $("#in-rsc").val(),
				icef: $("#in-icef").val(),
				leader: $("#in-leader").val(),
				status: $("#in-status").val(),
				loc: $("#in-loc").val(),
				remark: $("#in-remark").val()}),
		dataType: "html"
		}
	).responseText;
	if(html.slice(0,2)=="<!"){
			window.location="login.php";
		}

	$(".sel").html(html);
	$(".sel").removeClass("sel");
}

function del() {
	if(confirm("Are you sure you want to delete the selected resource?")){
		do_over=1;
		html = $.ajax({
			url: "resource-action.php",
			global: false,
			type: "POST",
			async: false,
			data: ({location_id: loc,
					action: "del", 
					rid: id}),
			dataType: "html"
			}
		).responseText;
		if(html.slice(0,2)=="<!"){
			window.location="login.php";
		}
	
		$(".sel").remove();
	}
}