///////////////////////////////////
/////// TIMETRACKING FUNCTIONS ////
///////////////////////////////////
function getProjectTimesheet(){
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;

	if (project_id === '') { return 0; }

	var url  = 'ajax.php?m=render&a=project&project_id='+project_id;
	sendRequest(url, 'projectTimesheetGot');
}

function projectTimesheetGot(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		getElementByID('project_hours').innerHTML = htmltext;
	}else if (htmltext === "error"){
		information('An error occured while trying to get timetracking for choosen project. Please inform admin staff.');
	}
}

function calculateWorkHours(){
	var startDate = getElementByID('start_date').value;
	var endDate = getElementByID('end_date').value;

	var url  = 'ajax.php?m=render&a=calculateWorkHours&startDate='+startDate+'&endDate='+endDate;
	sendRequest(url, 'workHoursCalculated');
}

function workHoursCalculated(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		getElementByID('sum_date').value = htmltext;
	}else if (htmltext === "error"){
		information('An error occured while trying to calculate your working hours. Please inform admin staff.');
	}
}

function clearProjectHour(){
	getElementByID('timesheet_id').value = '-1';
	getElementByID('desc').value = '';
	getElementByID('comments').value = '';
	getElementByID('spent_time').value = '';
}

function editProjectHour(timesheet_id, description, comments, date, spent_time, worker){
	getElementByID('timesheet_id').value        = timesheet_id;
	getElementByID('desc').value                = description;
	getElementByID('comments').value            = comments;

	//RM08052007 Date selection
	date = date.split('.');
	day  = date[0];
	day  = parseFloat(day); //RM08052007 Remove front 0
	month= date[1];
	year = date[2];
	setDateReference('Day', day);
	setDateReference('Month', month);
	setDateReference('Year', year);

	//RM08052007 Worker selection
	getElementByID('spent_time').value      = spent_time;
	var list = getElementByID('worker');
	setSelectedIndex(list, worker);
}

function deleteProjectHour(timesheet_id){
	var url  = 'ajax.php?m=delete&a=timetracking&timesheet_id='+timesheet_id;
	sendRequest(url, 'projectHourSaved');
}

function projectHourDeleted(){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		if (htmltext != '1'){
			alert('Following error occured: '+htmltext);
		}else{
			getProjectTimesheet();
			clearProjectHour();
		}
	}else if (htmltext === "error"){
		information('An error occured while trying to delete projeect hour for choosen project. Please inform admin staff.');
	}

}

function saveProjectHour(){
	var project_id    = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	var timesheet_id  = getElementByID('timesheet_id').value;
	var description   = getElementByID('desc').value;
	var comments      = getElementByID('comments').value;
	var spent_time    = getElementByID('spent_time').value;
	var worker_id     = getElementByID('worker').options[getElementByID('worker').selectedIndex].value;
	var day           = getDateReference('Day');
	var month         = getDateReference('Month');
	var year          = getDateReference('Year');

	var url  = 'ajax.php?m=insert&a=timetracking&project_id='+project_id+'&timesheet_id='+timesheet_id+'&description='+description+'&comments='+comments+'&spent_time='+spent_time+'&worker_id='+worker_id+'&year='+year+'&month='+month+'&day='+day;
	sendRequest(url, 'projectHourSaved');

}

function projectHourSaved(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		if (htmltext != '1'){
			alert('Following error occured: '+htmltext);
		}else{
			getProjectTimesheet();
			clearProjectHour();
		}
	}else if (htmltext === "error"){
		information('An error occured while trying to get timetracking for choosen project. Please inform admin staff.');
	}
}

function getDateReference(type){
	var name    = 'Date_'+type;
	var selects = document.getElementsByTagName('select');
	for (i=0; i<selects.length; i++){
		if (selects[i].name == name){
			return selects[i].options[selects[i].selectedIndex].value;
		}
	}
}

function setDateReference(type, value){
	var name    = 'Date_'+type;
	var selects = document.getElementsByTagName('select');
	for (i=0; i<selects.length; i++){
		if (selects[i].name == name){
			setSelectedIndex(selects[i], value);
		}
	}
}

function setSelectedIndex(list, value){
	for (var intI = 0; intI < list.options.length; intI++) {
		if (list.options[intI].value == value) {
			list.options[intI].selected = true;
		}
	}
}

function getSelectedIndex(list){
	return getElementByID(list).options[getElementByID(list).selectedIndex].value;
}

function exportToExcel(buyer_id, buyer_name){
	//var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	//if (project_id === '') { return 0; }

	var url  = 'ajax.php?m=excel&a=project&buyer_id='+buyer_id+'&buyer_name='+buyer_name;
	sendRequest(url, 'excelExported')
}

function excelExported(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		window.open(htmltext);
	}else if (htmltext === "error"){
		information('An error occured while trying to export project hours to excel. Please inform admin staff.');
	}
}

///////////////////////////////////
/////// PAYMENTS FUNCTIONS ////////
///////////////////////////////////
function getUnPayedProjectHours(){
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	if (project_id === '') { return 0; }
	var url  = 'ajax.php?m=render&a=unpayed_hours&project_id='+project_id;
	sendRequest(url, 'projectTimesheetGot');
	markProjectHourAsPayed(-1, project_id, -1);
}

function getUnPayedProjectHoursWithoutTempPayedHours(){
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	if (project_id === '') { return 0; }
	var url  = 'ajax.php?m=render&a=unpayed_hours_without_temp_payed_hours&project_id='+project_id;
	sendRequest(url, 'projectTimesheetGot');
	markProjectHourAsPayed(-1, project_id, -1);
}

function markProjectHourAsPayed(timesheet_id, project_id, trID){
	var url  = 'ajax.php?m=insert&a=unpayed_hours&timesheet_id='+timesheet_id+'&project_id='+project_id;
	sendRequest(url, 'projectHourMarkedAsPayed');
	
	// Removes the hour which was marked as payed
	if (trID != -1) {
		$('#'+trID).hide();
	}
}


function projectHourMarkedAsPayed(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		getElementByID('payed_project_hours').innerHTML = htmltext;
		getSumOfHoursMarkedAsPayed(); // info to show how much we must enter
	}else if (htmltext === "error"){
		information('An error occured while trying to get temp payed hours for selected project. Please inform admin staff.');
	}
}

function getSumOfHoursMarkedAsPayed() {
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	if (project_id === '') { return 0; }
		
	var url  = 'ajax.php?m=insert&a=sum_hours_marked_payed&project_id='+project_id;
	sendRequest(url, 'sumOfHoursMarkedAsPayed');
}

function sumOfHoursMarkedAsPayed(http_request) {
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		jQuery('#amountSumMarkedPayedHours').attr('innerHTML', htmltext+' €');
		
	}else if (htmltext === "error"){
		information('An error occured while trying to get sum amount of temp payed hours for selected project. Please inform admin staff.');
	}
}

function markProjectHourAsUnPayed(timesheet_id, project_id, trID){
	var url  = 'ajax.php?m=delete&a=unpayed_hours&timesheet_id='+timesheet_id+'&project_id='+project_id;
	sendRequest(url, 'projectHourMarkedAsPayed');
	
	// Unhide the tr which was hidden when clicked on add as payed
	$('#'+trID).show();
}

function savePayedHours(){
	var project_id      = getSelectedIndex('projects');
	var amount_payed    = getElementByID('amount_payed').value;
	var worker_id       = getElementByID('worker').options[getElementByID('worker').selectedIndex].value;
	var day             = getDateReference('Day');
	var month           = getDateReference('Month');
	var year            = getDateReference('Year');

	var url             = 'ajax.php?m=insert&a=payed_hours&project_id='+project_id+'&worker_id='+worker_id+'&amount_payed='+amount_payed+'&year='+year+'&month='+month+'&day='+day;
	sendRequest(url, 'payedHoursSaved');
}

function savePayedHoursRacunovodstvo(){
	var project_id      = jQuery('input[name="st_racun"]').val();
	var amount_payed    = jQuery('input[name="znesek"]').val();
	var worker_id       = 1; //TODO:getElementByID('worker').options[getElementByID('worker').selectedIndex].value;
	var tempDate        = jQuery('input[name="datum"]').val();
	tempDate            = tempDate.split('-');
	var day             = tempDate[2];
	var month           = tempDate[1];
	var year            = tempDate[0];

	var url             = 'ajax.php?m=insert&a=payed_hours_racun&racun_id='+project_id+'&worker_id='+worker_id+'&amount_payed='+amount_payed+'&year='+year+'&month='+month+'&day='+day;
	sendRequest(url, 'payedHoursSaved');
}

function payedHoursSaved(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		if (htmltext != 'true;'){
			information(htmltext);
		}else{
			getUnPayedProjectHours();
		}
	}else if (htmltext === "error"){
		information('An error occured while trying to get temp payed hours for selected project. Please inform admin staff.');
	}
}

function confirmChoice(href, text){
	if (window.confirm(text) === true){
		window.location = href;
		return true;
	}else{
		return false;
	}
}

// On body load check if we passed any link to timetracking URL, if yes select that value in izberi projekt select box
jQuery(document).ready(function(){
	var value		 = getURLParam('id');
	var list		 = getElementByID('projects');
	
	if (value != '') {
		setSelectedIndex(list, value);
		getProjectTimesheet();
	}
});

// RACUNOVODSTVO FUNCTIONS
function markProjectHourAsUnPayedRacun(timesheet_id, project_id, trID){
	var url  = 'ajax.php?m=delete&a=unpayed_hours&timesheet_id='+timesheet_id+'&project_id='+project_id+'&type=racunovodstvo';
	sendRequest(url, 'projectHourMarkedAsPayedRacun');
	
	// Unhide the tr which was hidden when clicked on add as payed
	$('#'+trID).show();
}

function getUnPayedProjectHoursRacun(){
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	if (project_id === '') { return 0; }
	var url  = 'ajax.php?m=render&a=unpayed_hours&project_id='+project_id+'&type=racunovodstvo';
	sendRequest(url, 'projectTimesheetGot');
	markProjectHourAsPayedOnRacun(-1, project_id, -1);
}

function markProjectHourAsPayedOnRacun(timesheet_id, project_id, trID){
	var racun_id = jQuery('input[name="ID_racuna"]').val();
	
	var url  = 'ajax.php?m=insert&a=unpayed_hours&timesheet_id='+timesheet_id+'&project_id='+project_id+'&racun_id='+racun_id+'&type=racunovodstvo';
	sendRequest(url, 'projectHourMarkedAsPayedRacun');
	
	// Removes the hour which was marked as payed
	if (trID != -1) {
		$('#'+trID).hide();
	}
}

function projectHourMarkedAsPayedRacun(http_request){
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		getElementByID('payed_project_hours').innerHTML = htmltext;
		
		getSumOfHoursMarkedAsPayedPerUserOnRacun(); // info to show how much we must enter per user
				
	}else if (htmltext === "error"){
		information('An error occured while trying to get temp payed hours for selected project. Please inform admin staff.');
	}
}

function getSumOfHoursMarkedAsPayedPerUserOnRacun() {
	var project_id = getElementByID('projects').options[getElementByID('projects').selectedIndex].value;
	if (project_id === '') { return 0; }
		
	var url  = 'ajax.php?m=insert&a=sum_hours_marked_payed_per_user&project_id='+project_id;
	sendRequest(url, 'sumOfHoursMarkedAsPayedPerUserOnRacun');
}

function sumOfHoursMarkedAsPayedPerUserOnRacun(http_request) {
	var htmltext = checkHttpRequest(http_request);
	if (htmltext !== false){
		htmltext = http_request.responseText;
		htmltext.split(';');
		
		// Init
		jQuery('#ure_0').val(0);
		jQuery('#ure_1').val(0);
		jQuery('#ure_2').val(0);
		jQuery('#urna_postavka').val(0);
		
		// Rows are delimited by ;
		var mySplitResult = htmltext.split(';');
		for(i = 0; i < mySplitResult.length; i++){
			// Each row has delimiter id:amount
			var temp = mySplitResult[i].split(':'); 
						
			jQuery('#ure_'+temp[0]).val(temp[1]);
			
			// Last value is always the same, it's eur per hour
			jQuery('#urna_postavka').val(temp[2]);
			
		}	
	}else if (htmltext === "error"){
		information('An error occured while trying to get sum amount of temp payed hours for selected project. Please inform admin staff.');
	}
}