$(document).ready(function() {
	
	
		
			function getCurrentFirstDayOfWeek(){
			   
			   today = new Date();
			   todayDay = today.getDay();
			   return(todayDay);
			}
		 
			var $calendar = $('#calendar');
			var currentFirstDay = getCurrentFirstDayOfWeek();
			var id = 10;
		 
			$calendar.weekCalendar({
			   timeslotsPerHour : 4,
			   allowCalEventOverlap : true,
			   overlapEventsSeparate: true,
			   firstDayOfWeek : currentFirstDay,
			   businessHours :{start: 8, end: 18, limitDisplay: true },
			   daysToShow : 7,
			   height : function($calendar) {
				  return $(window).height() - $("h1").outerHeight() - 1;
			   },
			   eventRender : function(calEvent, $event) {
				  if (calEvent.end.getTime() < new Date().getTime()) {
					 $event.css("backgroundColor", "#aaa");
					 $event.find(".wc-time").css({
						"backgroundColor" : "#999",
						"border" : "1px solid #888"
					 });
				  }
			   },
			   draggable : function(calEvent, $event) {
				  
				  return calEvent.readOnly != true;
			   },
			   resizable : function(calEvent, $event) {
				  return calEvent.readOnly != true;
			   },
			   eventNew : function(calEvent, $event) {
				  
				  var $dialogContent = $("#event_edit_container");
				  resetForm($dialogContent);
				  var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
				  var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
				  var titleField = $dialogContent.find("input[name='title']");
				  var bodyField = $dialogContent.find("textarea[name='body']");
		 
		 
				  $dialogContent.dialog({
					 modal: true,
					 title: "",
					 hide  : 'slide',
					 show  : 'slide',
					 close: function() {
						$dialogContent.dialog("destroy");
						$dialogContent.hide('slide');
						$('#calendar').weekCalendar("removeUnsavedEvents");
					 },
					 buttons: {
						save : function() {
						   calEvent.id = id;
						   id++;
						   calEvent.start = new Date(startField.val());
						   calEvent.end = new Date(endField.val());
						   calEvent.title = titleField.val();
						   calEvent.body = bodyField.val();
		 
						   $calendar.weekCalendar("removeUnsavedEvents");
						   $calendar.weekCalendar("updateEvent", calEvent);
						   $dialogContent.dialog("close","hide",'slide');
						},
						cancel : function() {
						   $dialogContent.dialog("close","hide",'slide');
						}
					 }
				  }).show('slide');
		 
				  $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
				  setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
		 
			   },
			   eventDrop : function(calEvent, $event) {
			   },
			   eventResize : function(calEvent, $event) {
			   },
			   eventClick : function(calEvent, $event) {
				  
				  if (calEvent.readOnly) {
					 return;
				  }
		 
				  var $dialogContent = $("#event_edit_container");
				  resetForm($dialogContent);
				  var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
				  var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
				  var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
				  var bodyField = $dialogContent.find("textarea[name='body']");
				  bodyField.val(calEvent.body);
		 
				  $dialogContent.dialog({
					 modal: true,
					 hide  : 'slide',
					 show  : 'slide',
					 title: "Edit - " + calEvent.title,
					 close: function() {
						$dialogContent.dialog("destroy");
						$dialogContent.hide('slide');
						$('#calendar').weekCalendar("removeUnsavedEvents");
					 },
					 buttons: {
						save : function() {
		 
						   calEvent.start = new Date(startField.val());
						   calEvent.end = new Date(endField.val());
						   calEvent.title = titleField.val();
						   calEvent.body = bodyField.val();
		 
						   $calendar.weekCalendar("updateEvent", calEvent);
						   $dialogContent.dialog("close");
						},
						"delete" : function() {
						   $calendar.weekCalendar("removeEvent", calEvent.id);
						   $dialogContent.dialog("close","hide",'slide');
						},
						cancel : function() {
						   $dialogContent.dialog("close","hide",'slide');
						}
					 }
				  }).show('slide');
		 
				  var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
				  var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
				  $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
				  setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
				  $(window).resize().resize(); //fixes a bug in modal overlay size ??
		 
			   },
			   eventMouseover : function(calEvent, $event) {
				  
				  if (calEvent.readOnly) {
					 return;
				  }
		 
				  var $dialogContent = $("#event_edit_container");
				  resetForm($dialogContent);
				  var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
				  var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
				  var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
				  var bodyField = $dialogContent.find("textarea[name='body']");
				  bodyField.val(calEvent.body);
		 
				  $dialogContent.dialog({
					 modal: true,
					 title: "Edit - " + calEvent.title,
					 hide  : 'slide',
					 show  : 'slide',
					 close: function() {
						$dialogContent.dialog("destroy");
						$dialogContent.hide('slide');
						$('#calendar').weekCalendar("removeUnsavedEvents");
					 },
					 buttons: {
						save : function() {
		 
						   calEvent.start = new Date(startField.val());
						   calEvent.end = new Date(endField.val());
						   calEvent.title = titleField.val();
						   calEvent.body = bodyField.val();
		 
						   $calendar.weekCalendar("updateEvent", calEvent);
						   $dialogContent.dialog("close");
						},
						"delete" : function() {
						   $calendar.weekCalendar("removeEvent", calEvent.id);
						   $dialogContent.dialog("close","hide",'slide');
						},
						cancel : function() {
						   $dialogContent.dialog("close","hide",'slide');
						}
					 }
				  }).show('slide');
				  
		  
				  var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
				  var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
				  $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
				  setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
				  $(window).resize().resize(); //fixes a bug in modal overlay size ??
				  
				 
			   },
			   eventMouseout : function(calEvent, $event) {
				  
			   },
			   noEvents : function() {
		 
			   },
			   data : function(start, end, callback) {
				  callback(getEventData());
			   }
			  
			});
		 
			function resetForm($dialogContent) {
			   $dialogContent.find("input").val("");
			   $dialogContent.find("textarea").val("");
			}
		 
		 
			function getEventData() {
			   var year = new Date().getFullYear();
			   var month = new Date().getMonth();
			   var day = new Date().getDate();
		 
			   return {
				  events : [
					 {
						"id":1,
						"start": new Date(year, month, day, 12),
						"end": new Date(year, month, day, 13, 30),
						"title":"Lunch with Mike"
					 },
					 {
						"id":2,
						"start": new Date(year, month, day, 14),
						"end": new Date(year, month, day, 14, 45),
						"title":"Dev Meeting"
					 },
					 {
						"id":3,
						"start": new Date(year, month, day + 1, 17),
						"end": new Date(year, month, day + 1, 17, 45),
						"title":"Hair cut"
					 },
					 {
						"id":4,
						"start": new Date(year, month, day - 1, 8),
						"end": new Date(year, month, day - 1, 9, 30),
						"title":"Team breakfast"
					 },
					 {
						"id":5,
						"start": new Date(year, month, day + 1, 14),
						"end": new Date(year, month, day + 1, 15),
						"title":"Product showcase"
					 },
					 {
						"id":6,
						"start": new Date(year, month, day, 10),
						"end": new Date(year, month, day, 11),
						"title":"I'm read-only",
						readOnly : true
					 }
		 
				  ]
			   };
			}
		 
		 
			/*
			 * Sets up the start and end time fields in the calendar event
			 * form for editing based on the calendar event being edited
			 */
		 
			var $endTimeField = $("select[name='end']");
			var $endTimeOptions = $endTimeField.find("option");
		 
			//reduces the end time options to be only after the start time options.
			$("select[name='start']").change(function() {
			   
			 var startTime = $(this).find(":selected").val();
			 var currentEndTime = $endTimeField.find("option:selected").val();
			 $endTimeField.html(
				   $endTimeOptions.filter(function() {
				  return startTime < $(this).val();
				   })
				   );
		   
			 var endTimeSelected = false;
			 $endTimeField.find("option").each(function() {
				 if ($(this).val() === currentEndTime) {
					$(this).attr("selected", "selected");
					endTimeSelected = true;
					return false;
				 }
			 });	
		 
			   if (!endTimeSelected) {
				  //automatically select an end date 2 slots away.
				  $endTimeField.find("option:eq(1)").attr("selected", "selected");
			   }
		 
			});
			   
		 
		 
			var $about = $("#about");
		 
			$("#about_button").click(function() {
			   $about.dialog({
				  title: "About this calendar demo",
				  width: 600,
				  close: function() {
					 $about.dialog("destroy");
					 $about.hide('slide');
				  },
				  buttons: {
					 close : function() {
						$about.dialog("close");
					 }
				  }
			   }).show('slide');
			});
			
			   
			 //REQUEST PE DOMREADY PENTRU ZILELEL CU EVENIMENTE   
				
			 var firstDay = $('table.wc-header tr td:first').attr('rel');
			 var lastDay = $('table.wc-header tr td:last').attr('rel');
			 
			 
			 //AJAX REQUEST
			  $.ajax({
				  url: 'http://www.timpul.md/eventsjson.php',
				  dataType: 'json',
				  data: "firstDay=" + firstDay + "&lastDay=" + lastDay,
				  type: "POST",
				  success: function (data) {
				  
					 window.my_data  = data;
					  
					  $("table .wc-day-column-header").each(function(i,el){
		 
						 if ( typeof window.my_data[ $(el).attr('rel') ] != 'undefined' ){
						 
							 //alert(data[$(el).attr('rel')].toSource() );
						 
							 $(el).attr('title', insertEventsInTipsy( $(el).attr('rel') , window.my_data[$(el).attr('rel')] ));
							 $(el).tipsy({ gravity: 'n', fade: true, html: true, trigger:'manual', idTipsy: $(el).attr('rel')});
							 $(el).addClass("corner");
							 $(el).mouseenter(function(){
								 $('.tipsy').remove();
								 $(el).tipsy('show');
							 })
							 
						 }
						 else{
							 $(el).removeClass("corner");
							 $(el).unbind();
						 }
					 });	
				  }
			 });
		 
			putCurrentDay();
			//showEventsOnHover();
		});



	function putCurrentDay(){
		if(myCurrentDay != '') {
			$(".wc-nav button.wc-today").append('' + myCurrentDay + '');
		}
    }
   
   function insertEventsInTipsy(date,obj){
      
         date = new Date(date);
		 now = new Date();
		 
		// alert(obj.toSource());
		 
		 if(date > now) {
		 
			txt = "<div class=\"title_date\">" + obj[0].fDate + "</div><div class=\"no_event\"></div><div class=\"delimit\"></div><ul>";
			//txt = "<div class=\"title_date\">" + 'test' + "</div><div class=\"no_event\"></div><div class=\"delimit\"></div><ul>";
         
		 }
		 else {
			
			txt = "<div class=\"title_date\">" + obj[0].fDate + "</div><div class=\"no_event\"></div><div class=\"delimit\"></div><ul class=\"past\">";
			//txt = "<div class=\"title_date\">" + 'test' + "</div><div class=\"no_event\"></div><div class=\"delimit\"></div><ul class=\"past\">";
			
		 };
		 
		if(obj.length > 0){
         
		 //alert(obj.length);
		 
	        for (i=0; i <= obj.length-1; i++){
				if(null != obj[i].link && null != obj[i].start && '' != obj[i].title) {
					txt = txt + "<li><a href=\"" + obj[i].link + "\"> ora: " + obj[i].start + '&nbsp;' + obj[i].title + "</a></li>";
				}
	  	 	}
        };
		
  	 	txt = txt + "</ul>";
		//alert(txt);
        return(txt);
    }
   
	function showEventsOnHover(my_data){

		var i = 0;
		
		$(".wc-header .wc-day-column-header").each(function(i, el) {
		
		//alert(my_data[ $(this).attr('rel') ][0].title);
		
			if( typeof my_data[ $(this).attr('rel') ] != 'undefined' && my_data[ $(this).attr('rel') ] != null &&  my_data[ $(this).attr('rel') ] != '' ){
				
				rel = $(this).attr('rel');
				tipsyId = rel;
			
			//alert( my_data[ $(this).attr('rel')] );
			
				//$(this).tipsy({ gravity: 'n', fade: true, html: true, delayOut: 5000 , idTipsy: tipsyId, title: function() { return insertEventsInTipsy( $(this).attr('rel') , my_data[$(this).attr('rel')] ); }});
				
				////PENTRU MANUAL TIPSY
				//$(this).mouseenter(function(){
				//	$(this).tipsy('show');
				//	//$('.tipsy').live('mouseover' , function(){
				//	//	$(this).tipsy('show');
				//	//});
				//	
				//	$('.tipsy').live('mouseleave' , function(){
				//		$(this).tipsy('hide');
				//	});
				//});
				
				//$(this).mouseleave(function(){
				//	$(this).tipsy('hide');
				//})
				
			};
		
		});
    }

