// JavaScript Document
/**
main hosers' script


**/

var months = [31,28,31,30,31,30,31,31,30,31,30,31];
var monthNames = ['January','February','March','April','May','June','July','August','September','October', 'November','December'];
var currentDate = new Date();
var currentMonth, currentYear;
var globalEvents = [];
var scheduleType = 'crew';

$(document).ready(
	function(){
		$('#message').keyup(function(e){
			var str = $(this).val();
			//alert($(this).val());	
			if(str.length > 500 ){
				var str = str.substr( 0, 500);
				$(this).val(str);
			}
		});
		if($('#calendar').length > 0){
			currentMonth = currentDate.getMonth();
			currentYear = currentDate.getFullYear();
			buildCalendar();
			$('span#prior_month').click(function(){
				currentMonth--;
				if(currentMonth < 0){
					currentMonth = 11;
					currentYear--;
				}
				buildCalendar();
			});
			$('span#next_month').click(function(){
				currentMonth++;
				if(currentMonth > 11){
					currentMonth = 0;
					currentYear++;
				}
				buildCalendar();
			});
		}
		if($('#teamlist').length > 0){
			$('#teamlist').change(updateCrewListing);
			$('#userlist').attr('size', 11);
		}
		$.datepicker.formatDate( 'yy-mm-dd');
		if($('#rsuperdate').length == 1){
			$('#rsuperdate').datepicker({ dateFormat: 'yy-mm-dd' });
		}
	}
);

function emptyCalendar(){
	$('table#calendar tbody').empty();
}

function clearEntries(){
	
}

function showLoading(){
	$("#overlay").show();
}

function hideLoading(){
	$("#overlay").hide();
}

function buildCalendar(){
	emptyCalendar();
	//get the month and year from the drop down lists
	var calDate = new Date();
	calDate.setDate(1);
	calDate.setMonth(currentMonth);
	calDate.setYear(currentYear);
	var currentDay = 1;
	var firstDay = calDate.getDay();
	var lastDay = months[currentMonth];
	calDate.setDate(lastDay);
	var lastDOW = calDate.getDay();
	var monthName = monthNames[currentMonth];
	//set caption text
	$('caption span#dateLabel').text(monthName + ' ' + currentYear);
	var totalCells = (firstDay + lastDay + (6-lastDOW ));
	var numRows = (totalCells / 7);
	//6 2 31 4
	//alert(totalCells + ' ' + numRows + ' ' + firstDay + ' ' + lastDay + ' ' + lastDOW);
	var tbody = $('#calendar tbody').get(0);
	for(r=0; r<numRows; r++){
		var tr = document.createElement('tr');
		for(d=0; d<7;d++){
				var td = document.createElement('td');
				var span = document.createElement('span');
				span.className = 'day';
				td.appendChild(span);
				tr.appendChild(td);
				//now decide what to put in the span
				if(r==0){
					//first row
					if(d<firstDay){
						span.appendChild(document.createTextNode('\u0020'));
					}else{
						span.appendChild(document.createTextNode(currentDay));
						currentDay++;
					}
				}else if(r == numRows-1){
					//last row
					if(d <= lastDOW){
						span.appendChild(document.createTextNode(currentDay));
						currentDay++;
					}else{
						span.appendChild(document.createTextNode('\u0020'));
					}
				}else{
					span.appendChild(document.createTextNode(currentDay));
					currentDay++;
				}
		}
		tbody.appendChild(tr);
	}
		styleCalendar();
		getListOfEvents()
}

function styleCalendar(){
	//apply the weekend styling
	$('table#calendar tbody tr td:first-child').addClass('weekend');
	$('table#calendar tbody tr td:last-child').addClass('weekend');
	//apply the style for the non days
	$('table#calendar td span.day').each(
		function(){
			var num = parseInt($(this).text());
			//alert(num);
			if(isNaN(num)){
				$(this).parent().addClass('nonday');
				$(this).parent().unbind('click');
			}
		});	
}

function getListOfEvents(){
	showLoading();
	var pg = "/data/get.entries.php";
	m = currentMonth + 1;
	var dat = 'month=' + m + '&year=' + currentYear + '&type=' + scheduleType + '&rnd=' + Math.random();
	//alert(dat);
	$.ajax({
		dataType: 'json',
		url: pg,
		type: 'GET',
		data: dat,
		success: function(xhr, status){
			//add the events to the calendar and save the addtional details to the global event object
			globalEvents = xhr.entries;
			hideLoading();
			addEventsToCalendar();
		},
		error: function(xhr){
			//could not get events
			hideLoading();
			alert("Problem retrieving events from database.");
		}
	});
	
}

function addEventsToCalendar(){
	//fetch the list of events for the selected month
	var numEvents = globalEvents.length;
	for(e=0; e<numEvents; e++){
		var sp = document.createElement('span');
		sp.className = 'event';
		sp.id = "event_" + globalEvents[e].event_id;
		var txt = document.createTextNode( globalEvents[e].event_title );
		var eid = globalEvents[e].event_id
		sp.appendChild( txt );
		var day = parseInt(globalEvents[e].event_day);
		$('table#calendar tbody tr td span:contains(' + day + '):first').parent().append(sp).effect("highlight", {color:'#ffcc33'}, 5000);
		sp.onclick = showEventDetails;
		sp.onmouseover = highlightEvent;
		sp.onmouseout = unHighlightEvent;

	}
}

function highlightEvent(){
	this.style.backgroundColor = '#ffcc33';
	this.style.fontWeight = 'bold';
	this.title = 'Click for details';
}

function unHighlightEvent(){
	this.style.backgroundColor = '#ffffff';
	this.style.fontWeight = 'normal';
	this.title = '';
}

function showEventDetails(){
	//animate the event box to appear over the calendar
	var id = this.id.split('_')[1];
	var numEvents = globalEvents.length;
	for(e=0; e<numEvents; e++){
		if(parseInt(globalEvents[e].event_id) == parseInt(id) ){
			//we've found all the data
			//populate the box
			$('#eventDetailBox').fadeIn().animate({
				top: '300px',
				left: '200px',
				opacity: 1.0
			});
			$('#event_title').html(globalEvents[e].event_title);
			$('#event_desc').html(globalEvents[e].event_desc);
			$('#event_date').text(globalEvents[e].event_dt);
			if(globalEvents[e].event_url == ""){
				$('#event_url').html("");
			}else{
				$('#event_url').html('<a href="' + globalEvents[e].event_url + '" title="' + globalEvents[e].event_title + '" target="_blank" >' + globalEvents[e].event_url + '</a>');
			}
			break;
		}
	}
}

function closeBox(){
	//animate
	$('#eventDetailBox').animate({
		top: '1500px',
		left: '0px'
	}).fadeOut();
	//clear the fields
	$('#eventDetailBox #event_title').text("");
	$('#eventDetailBox #event_desc').text("");
	$('#eventDetailBox #event_url').html("");
	$('#eventDetailBox #event_date').text("");
}

function removeFromCrew(){
	//move from crewmembers list to the userlist via ajax call
	var uid = $('#crewmembers').val();
	var user = $('#crewmembers option:selected').text();
	var tid = $('#teamlist').val();
	if(tid == 0){
		alert('You must select a crew first.');
		return false;
	}
	if(uid < 1){
		alert('You must select a crew member to move.');
		return false;
	}
	var dat = 'user_id=' + uid + '&team_id=' + tid + 'rnd=' + Math.random();
	//alert(dat + ' with name ' + user);
	$.ajax({
		   data:dat,
		   url:'../data/removeFromCrew.php',
		   type:'POST',
		   dataType:'json',
		   success:function(resp){
			   //move the entry from the one list to the other
			   alert(resp.msg);
			   if( parseInt(resp.error_code) == 0){
					//all good
					//add to new list
					var newStr = '<option value="' + uid + '">' + user + '</option>';
					$('#userlist').append(newStr);
					//remove from old list
					//document.getElementById('userlist').removeChild(document.getElementById('userlist').options[document.getElementById('userlist').selectedIndex]);
					$('#crewmembers option:selected').remove();
			   }else{
					//error   
					alert('Error: ' + resp.error_code + ' ' + resp.msg);
			   }
		   },
		   error:function(xhr){
				alert(xhr.responseText + 'Unable to remove the user from a crew.');
		   }
		   });
}

function addToCrew(){
	//move from the user list to the crewmembers list via an ajax call
	var uid = $('#userlist').val();
	var user = $('#userlist option:selected').text();
	var tid = $('#teamlist').val();
	if(tid == 0){
		alert('You must select a crew first.');
		return false;
	}
	var dat = 'user_id=' + uid + '&team_id=' + tid;
	//alert(dat + ' ' + user);
	$.ajax({
		   data:dat,
		   url:'../data/addToCrew.php',
		   type:'POST',
		   dataType:'json',
		   success:function(response){
			   //move the entry from the one list to the other
			   alert(response.msg);
			   if( parseInt(response.error_code) == 0){
					//all good
					//add to new list
					var newStr = '<option value="' + uid + '">' + user + '</option>';
					$('#crewmembers').append(newStr);
					//remove from old list
					//document.getElementById('userlist').removeChild(document.getElementById('userlist').options[document.getElementById('userlist').selectedIndex]);
					$('#userlist option:selected').remove();
			   }else{
					//error   
					alert('Error: ' + response.error_code + ' ' + response.msg);
			   }
		   },
		   error:function(xhr){
				alert('Unable to add the user to a crew.');
		   }
		   });
}

function updateCrewListing(){
	//take the selected crew and load the list of members into the ddlist "crewmembers"
	$('#crewmembers').empty();
	var tid = $('#teamlist').val();
	$.ajax({
		   url:'../data/getCrewList.php',
		   data:'team_id=' + tid,
		   type:'POST',
		   dataType:'json',
		   success:function(response){
			   var ul = response.users;
			   var nl = ul.length;
			   for(u=0;u<nl;u++){
					var newStr =   '<option value="' + ul[u].user_id + '">' + ul[u].user_name + '</option>';
					$('#crewmembers').append(newStr); 
			   }
		   },
		   error:function(xhr){
			   alert('unable to retrieve the list of crew members.');
		   }
		   });
}
