
function fileSize(bytes){
	var size = "";
	if (bytes == 0) { 
		size = "-";
	}else { 
		if (bytes > 1024) { 
			size = Math.round(bytes/1024) + " KB";
		}else { 
			if (bytes > 1024*1024) { 
				size = Math.round(bytes / ((1024*1024)*100)/100) + " MB";
			}else { 
				if (bytes > 1024*1024*1024) {
						size = Math.round(bytes / ((1024*1024)*100)/100) + " GB";			
				} else {
					size = bytes + " bytes";	
				} 
			}
		}
	}
return size;
}

function refreshPage(){
	window.location.reload(true);	
}

function deleteItem(class_, table, itemtodelete){
	$(".delete_"+class_).click(function(e){
		var deleteID=$(this).attr('id').substr(4,10);
		if(confirm("Are you sure you want to delete this "+itemtodelete)){
			$("#"+class_+"_box_"+deleteID).fadeOut();
			$.post("/scripts/delete_item.php", {id: deleteID, table: table}, function(data){
				//alert(data);
				if(data=="refresh"){
					refreshPage();
				}
			});
		}
	});
}	
function updateNote(class_,status){
	$(class_).click(function(e){
		var id=$(this).attr('id').substr(4,10);
		//alert("status: "+status+" id:"+id);
		$.post("/scripts/update_note.php", {id: id, status: status}, function(data){
			refreshPage();
		});
	});
}

function sendMessage(msg){
	$.post("/scripts/add_msg.php", "msg="+msg, function(data){
//				alert(data);
	});
}

//function_call,vars,file_path,selectedFileArray[i].name,selectedFileArray[i].size,editedDate

function addPhoto(vars,path,filename,filesize,datemod){
	//window.location.reload(true);
}

var filenames = Array();

function loadingFile(percent,filename){
	var found = -1;
	for(var i=0;i<filenames.length;i++){
		if(filenames[i][0]==filename){
			found = i;
		}
	}
	if(found==-1){
		filenames.push([filename,percent]);	
	}else{
		filenames[found][1]=percent;	
	}
	buildLoading();
}

function buildLoading(){
	$("#fileprogress").html("");
	var contains = "";
	for(var i=0;i<filenames.length;i++){
		contains = $("#fileprogress").html();
		$("#fileprogress").html(contains+filenames[i][0]+": "+filenames[i][1]+"<br/>");	
	}
}
	
function addFile(filenum,path,filename,filesize,datemod){
	$("#filelist").show();
	var linkTo = root+path+"/"+filename;
	var ext = filename.split(".");
	ext = ext[ext.length-1];
	size = fileSize(filesize);
	$("#filelist").html($("#filelist").html()+"<div class='file_full' id='image_"+filenum+"' title='"+linkTo+"'><a class='file_link' href='"+linkTo+"'><div class='filename'><img src='"+root+"includes/admin/icons/"+ext+".png' /> "+filename+" </div><div class='filesize'> "+size+" </div><div class='lastmodified'></div></a><div class='clear'></div></div>");
}

function confirmation(){
	var confirmation=confirm("I confirm that all information I entered into this form is entirely correct and understand that after pressing OK I won't be able to come back and make any changes.");
	if (confirmation){
		return true;
	} else {
		return false ;
	}									 
};

//__________________________________________________________________________________________________________________________________________________________
//																																		   	JQUERY FUNCTIONS	

$(document).ready(function() {	

	$.ajaxSetup({cache: false}); 

    $(".flat").blur(function () {
		$(this).removeClass('flat_focus');
		$(this).addClass('flat_unfocus');
    });
	
	$(".flat").focus(function () {					  
		$(this).removeClass('flat_unfocus');
		$(this).addClass('flat_focus');
    });		
	
	$(".display_img").click(function () {				
		var displayID=$(this).attr('id').substr(4,10);
		$.post("/scripts/display_image.php", {id: displayID}, function(data){
			//alert(data);
		});
    });
	
	$(".cms_icons").hide();
	$("table tr").mouseleave(function(){
		$(".cms_icons").hide();
	});
	$("table tr").mouseenter(function(){
		$(".cms_icons").hide();
		var showbox=("#"+$(this).attr('id'));
		$(showbox+" .cms_icons").show();
	});
	$(".clear_on_focus").focus(function() {
        if (this.value == "Enter Text") {
            this.value = "";
        }
    }).blur(function() {
		if (this.value != "Enter Text"){
			this.value = "Enter Text";
		}
	});
	
//__________________________________________________________________________________________________________________________________________________________
//																																				AVAILABILITY
	var availability = ["m","t","w","h","f","s","u"];
	var boxes = ["a_1","a_2","a_3","a_4","a_5"];
	
	for(var l=0;l<boxes.length;l++){
		var b = boxes[l];
		for(var i=0;i<availability.length;i++){
			var letter = availability[i];
			var turnto = true;
		//	alert("#"+letter+"a"+boxes[l]);
			$("#"+letter+"a"+b).attr('letter',letter);
			$("#"+letter+"a"+b).attr('b',b);
			$("#"+letter+"a"+b).click(function(){
				if($(this).is(":checked")){
					turnto = true;
				}else{
					turnto = false;
				}
				for(var j=1;j<13;j++){	
					$("#"+$(this).attr('letter')+j+$(this).attr('b')).attr('checked',turnto);
				}
			});
			for(var j=1;j<13;j++){
				$("#"+letter+j+b).attr('letter',letter);
				$("#"+letter+j+b).attr('b',b);
				$("#"+letter+j+b).click(function(){
					if(!$(this).is(":checked")){
						$("#"+$(this).attr('letter')+"a"+$(this).attr('b')).attr('checked',false);
					}
					onCount = 0;
					for(var k=1;k<13;k++){
						if($("#"+$(this).attr('letter')+k+$(this).attr('b')).is(":checked")){
							onCount++;
						}
					}
					if(onCount==12){
						$("#"+$(this).attr('letter')+"a"+$(this).attr('b')).attr('checked',true);	
					}
				});
			}
		}
	}

//__________________________________________________________________________________________________________________________________________________________
//																																			  EVENT CALENDAR	
	$(".eventmonthselect").click(function(){
		window.location = $(this).attr('value');
	});
	
	$(".eventCol").mouseenter(function(){
		$(".eventCol").removeClass("eventhover");
		$(this).addClass("eventhover");
	}).mouseleave(function(){
		$(this).removeClass("eventhover");
	});
	
	$(".timechange").blur(function(){
		var val = parseFloat($(this).attr('value').substr(0,4));
		val=isNaN(val)?0:val;
		val = (val>=2400) ? 2359 : val;
		val = val.toString();
		var zeros = "0000".substr(0,(4-val.length));
		val=zeros+val;
		$(this).attr('value',val);
		setEmployees();
	});
	
	$(".timechange").keyup(function(){
		setEmployees();				 
	});
	
	$("select#dateid").change(function(){
		setEmployees();
	});
	
	$("select#userid").change(function(){
		checkSelected();
	});
	
	$("select#dateid").click(function(){
		checkSelected();
	});
	
	//red_highlight
	
	function checkSelected(){
		if($("select#userid").children(":selected").hasClass('red_highlight')){
			$("select#userid").addClass('red_highlight');
		}else{
			$("select#userid").removeClass('red_highlight');
		}
	}
	setEmployees();
	function setEmployees(){
		var date = $("#dateid").children(":selected").attr('rel');
		var starttime = $("#starttime").attr('value');
		var endtime = $("#endtime").attr('value');
//		alert("Start Time: "+ starttime + "\n"+"End Time: "+ endtime + "\ndate:"+date);
		var selecteduser = $("select#userid").children(":selected").attr('value');
		if($("select#userid").attr('rel') == 'checkstaff'){
			$.post("/scripts/available_staff.php", "ajax_date="+date+"&ajax_starttime="+starttime+"&ajax_endtime="+endtime+"&ajax_selecteduser="+selecteduser, function(data){
	//					alert(data);
				$("#userid").html(data);
				checkSelected();
			});
		}
	}

//__________________________________________________________________________________________________________________________________________________________
//																																				 SMS MESSAGE
	var maxChars = 160;
	$("#message_input").keyup(function(e) {
		if(this.value.length>maxChars-1){
			this.value = this.value.substr(0,160);	
		}
		$("#message_size").html(maxChars-this.value.length);
	});

//__________________________________________________________________________________________________________________________________________________________
//																																		 FLASH UPLOAD BUTTON
	$("#flash_upload_button").mouseenter(function(e){
		$(".file_upload_link").removeClass("link_normal");
		$(".file_upload_link").addClass("link_hover");
    }).mouseleave(function(e){
		$(".file_upload_link").addClass("link_normal");
		$(".file_upload_link").removeClass("link_hover");
    });

//__________________________________________________________________________________________________________________________________________________________
//																																		   	   ACCREDITATION

	var incorrectResults = 0;
	var correctResults = 0;
	$(".quizradio").click(function(){
		var creditid = $('#quiz').attr('name').substr(3,10);
		var id=$(this).attr('id').substr(3,10);	
		$("#answer_"+id).css("display","block");
		if($("#answer_"+id+" img").hasClass("incorrect")){
			incorrectResults++;
			// alert('That answer is incorrect.\nPlease try again.');
		}else{
			correctResults++;
			$.cookie('c_results',correctResults);
			var showid=$("#answer_"+id).attr('name').substr(3,10);
			var totalq=$("#answer_"+id+" img").attr('name').substr(3,10);
			$("#quizquestion_"+showid).removeClass('hidden');
			if(parseInt(showid)==(parseInt(totalq)+1)){
				var percent = Math.round(100-(((100 / correctResults) / 5) * (incorrectResults)));
				$.post("/scripts/quiz_completed.php", "creditid="+creditid+"&percent="+percent, function(data){
					//alert(data);									   
			   	});
			}			
		}
	});
	
	$(".creditacheived").click(function(){
										
		var creditid=$(this).attr('id').substr(3,10);	
		$.post("/scripts/quiz_completed.php", "creditid="+creditid+"&percent="+100, function(data){
//			alert(data);
			if(confirm("Please confirm you have acheived this qualification")){
				refreshPage();
			}
		});
										
	});

//__________________________________________________________________________________________________________________________________________________________
//																																		   	        CONTACTS	
	$(".add_msg").click(function(e){
		var id=this.id.substr(4,10);
		$.post("/scripts/add_contact.php", {id: id}, function(data){
			alert("Details has been added to your contacts module.");
		});
	});

//__________________________________________________________________________________________________________________________________________________________
//																																		   	    FILE MANAGER
	
	if(Number($(".file_full").size())==0){
		$("#filelist").hide();
	}
	var removedFiles = $(".file_full").size();
	$(".delete_image").click(function(){
		var vars = this.id.split("%?%");
		//alert(vars[0] + "     " + vars[1] + "     " +vars[2] + "     " +vars[3]+ "     ");
		msg = "Are you sure you want to delete the file '"+vars[2]+"'?";
		if(vars[3]=="Folder"){
		msg = "Are you sure you want to delete folder '"+vars[2]+"' and it's contents?";
		}
		if(confirm(msg)){
			$("#"+vars[0]).fadeOut();
			$.post("/scripts/delete_file.php", "path=/"+vars[1]+"/&file="+vars[2]+"&ext="+vars[3],function(data){
				//alert(data);
				removedFiles--;
				if(removedFiles==0){
					refreshPage();
				}														
			});
		}
	});
	
	$(".renamefile").click(function(){
		var vars = this.id.split("%?%");
		var name = prompt("Rename file or folder",vars[2]);
		if(name){
			names = name.split(" ");
			name = "";
			for(var i=0;i<names.length;i++){
				name +=	names[i];
				if(i<names.length-1){
					name += "-";
				}
			}
			$.post("/scripts/rename_file.php", "path="+vars[1]+"&oldname="+vars[2]+"&newname="+name,function(data){
				 //alert(data);	
				 refreshPage();
			});
		}
	});
	
	$(".newfolder").click(function(){	
       	var path=$(this).attr('id').substr(4,1942)+"/";
		var name = prompt("Please select a name for your new folder ","New-Folder");
		if(name){
			$.post("/scripts/create_folder.php", "path="+path+"&name="+name,function(data){
				//alert(data);	
				refreshPage();
			});	
		}
	});
	
//__________________________________________________________________________________________________________________________________________________________
//																																		   	   NOTIFICATIONS	
	$(".replynote").click(function(){
		var noteid=$(this).attr('id').substr(4,10);
		var msg = prompt("Reply to notification","");
		if(msg){
			$.post("/scripts/send_note.php", "noteid="+noteid+"&msg="+msg,function(data){
				 //alert(data);	
				 refreshPage();
			});
		}
	});

	$(".addnewnote").click(function(){
		var msg = prompt("Add item to your notification list","");
		if(msg){
			$.post("/scripts/add_note.php", "admin=no&msg="+msg,function(data){
				 //alert(data);	
				 refreshPage();
			});
		}
	});
	
	$(".addadminnote").click(function(){
		var msg = prompt("Send notification to admin","");
		if(msg){
			$.post("/scripts/add_note.php", "admin=yes&msg="+msg,function(data){
				 //alert(data);	
				 refreshPage();
			});
		}
	});	


//__________________________________________________________________________________________________________________________________________________________
//																																		   	   PHOTO GALLERY
	$(".delete_photo").click(function(){
		var vars = this.id.split("%?%");
		if(confirm("Are you sure you want to delete "+vars[2]+"?")){
			$("#"+vars[0]).fadeOut();
			$.post("/scripts/delete_photo.php", "path="+vars[1]+"&image="+vars[2],function(data){
				alert("removed "+vars[2]);
			});
		}
	});	
	
//__________________________________________________________________________________________________________________________________________________________
//																																		   	   		  QUOTES	
	
	
	$(".paidinvoice").click(function(){
		var vars=$(this).attr('id').substr(4,10);
		if(confirm("By pressing OK you confirm that this client has paid for their booking.")){
			$.post("/scripts/paid_invoice.php", "bookingid="+vars,function(data){
				alert("Account settled.");
				refreshPage();
			});
		}					  
	});		
	
	$(".sendinvoice").click(function(){
		var vars=$(this).attr('id').substr(4,10);
		if(confirm("Are you sure you want to send this Invoice?\nNOTE: Once you send this invoice you will not be able to make futher changes.")){
			$.post("/scripts/approve_invoice.php", "bookingid="+vars,function(data){
				alert("Invoice successfully sent!");
				refreshPage();
			});
		}					  
	});	
	
	$(".approvequote").click(function(){
		var vars=$(this).attr('id').substr(4,10);
		if(confirm("Are you sure you want to approve this quote?\nNOTE: This cannot be edited again until final invoice.")){
			$.post("/scripts/approve_quote.php", "bookingid="+vars,function(data){
				alert("Quote successfully sent!");
				refreshPage();
			});
		}					  
	});	
	
	$(".c_approvequote").click(function(){
		var vars=$(this).attr('id').substr(4,10);
		if(confirm("By pressing OK you agree to the prices set within the associated quote and would like to hire Emergency Medics services.")){
			$.post("/scripts/c_approve_quote.php", "bookingid="+vars,function(data){
				alert(data+"Quote approved!");
				refreshPage();
			});
		}					  
	});
	
	$(".preparequote").click(function(){
		var vars=$(this).attr('id').substr(4,10);
		if(confirm("Are you sure you want to send this quote?\nNOTE: This cannot be edited again until final invoice.")){
			$.post("/scripts/approve_quote.php", "bookingid="+vars,function(data){
				alert("Quote successfully sent!");
				refreshPage();
			});
		}					  
	});
	
	var showInvoice = 2;
	var totalQuote = 0;
	
	$('.pricemodifier').keyup(function(){
		checkPrice();
	});
	
	checkPrice();
	
	function checkPrice(){
		var	totalQuote = 0;
		var gst = 0;
		for(var i=0;i<20;i++){
			totalQuote += $("#qty_"+i).attr('value') * $("#price_"+i).attr('value');
		}
		//gst = (totalQuote/10);
		var combined = (totalQuote+gst).toFixed(2);
		totalQuote = totalQuote.toFixed(2);
		//gst = (gst).toFixed(2);
		$('#subtotal').html(totalQuote);
		//$('#gst').html(gst);
		$('#totalcost').html(combined);
	}
	
	$(".invoiceitem").hide();
	$(".invoiceitem_1").show();
	
	for(var i=0;i<20;i++){
		if($("#qty_"+i).attr('value')!=""||$("#desc_"+i).attr('value')!=""||$("#price_"+i).attr('value')!=""||$("#unit_"+i).attr('value')!=""){
			$(".invoiceitem_"+i).show();
			showInvoice++;
		}
	}
	
	$("#addinvoiceitem").click(function(){	
		$(".invoiceitem_"+showInvoice).show();
		showInvoice++;
	});
	
//__________________________________________________________________________________________________________________________________________________________
//																																		  	   DOCUMENTATION

function showDocumentItem(str){
	var otherid = str.substr(0,3);
	$(".d_"+str).hide();
	$(".d_"+str+"0").show();
	var showDocument=1;
	for(var i=0;i<20;i++){
		var found = false;
		for(var j=0;j<3;j++){
			if($("."+otherid+"_"+j+"_"+i).attr('value')!=""){
				//found=true;
			}
		}
		if(found){
			$(".d_"+str+i).show();
			showDocument++;
		}
	}
	
	$("#add"+str+"item").click(function(){	
		$(".d_"+str+showDocument).show();
		showDocument++;
	});
}

showDocumentItem("phar");
showDocumentItem("ivio");
showDocumentItem("clin");

function showSeriousEmergency(show){
	if(show){
		$(".seriousEmergency").parent().parent().show();
		$(".seriousEmergency").parent().show();	
		$(".seriousEmergency").show();	
		$(".seriousEmergency_row").show();
		showDocumentItem("phar");
		showDocumentItem("ivio");
		showDocumentItem("clin");
	}else{
		$(".seriousEmergency").parent().parent().hide();
		$(".seriousEmergency").parent().hide();	
		$(".seriousEmergency").hide();	
		$(".seriousEmergency_row").hide();	
	}
}

if($("#out_18").attr('value')=='Minor'){
	showSeriousEmergency(false);
}

$("#out_18").change(function(){
	if($(this).attr('value')=='Minor'){
		showSeriousEmergency(false);
	}else{
		showSeriousEmergency(true);
	}
});

//__________________________________________________________________________________________________________________________________________________________
//																																		   DATABASE DELETION

	deleteItem("svc","pages","Page?");
	deleteItem("acc","accreditations","Accreditation?");	
	deleteItem("cnt","contacts","Person?");
	deleteItem("img","gallery","Image?");	
	deleteItem("tes","testimonials","Testimonial?");
	deleteItem("not","notifications","Notification?");
	deleteItem("msg","messages","Enquiry?");	
	deleteItem("tme","timesheets","Timesheet?");
	deleteItem("qiz","quiz","Quiz Question?");
	deleteItem("sft","roster","Shift?");	
	deleteItem("bkk","bookings","Booking? \nNOTE: this can not be reversed.");
	deleteItem("doc","patients","Report? \nNOTE: this can not be reversed.");
	
	updateNote(".flag_note",1);//pinned
	//updateNote(".flag_note",2);//overdue
	//updateNote(".flag_note",3);//gettingclose
	updateNote(".unflag_note",4);//standard
	updateNote(".complete_note",5);//completed	
});
