//created on sep 14 2012
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */

	dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
	var newYear = new Date(this.getFullYear(),0,1);
	var day = newYear.getDay() - dowOffset; //the day of week the year begins on
	day = (day >= 0 ? day : day + 7);
	var daynum = Math.floor((this.getTime() - newYear.getTime() - 
	(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
	var weeknum;
	//if the year starts before the middle of a week
	if(day < 4) {
		weeknum = Math.floor((daynum+day-1)/7) + 1;
		if(weeknum > 52) {
			nYear = new Date(this.getFullYear() + 1,0,1);
			nday = nYear.getDay() - dowOffset;
			nday = nday >= 0 ? nday : nday + 7;
			/*if the next year starts before the middle of
 			  the week, it is week #1 of that year*/
			weeknum = nday < 4 ? 1 : 53;
		}
	}
	else {
		weeknum = Math.floor((daynum+day-1)/7);
	}
	return weeknum;
};


var calendarAPI = function(){
	c = this;
	this.event_create_div = $("#event_create");
	this.event_quick_view_div = $("#event_quick_view");
	this.today = new Date();
	this.cur_month = c.today.getMonth()+1;
	this.cur_year = c.today.getFullYear();
	this.cur_week = c.today.getWeek();
	this.view = null;
	this.monthlist = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
	this.initialize = function(){
		$(window).load(function(){
			// c.loadMonthView(c.cur_month,c.cur_year);
			c.loadWeekView(c.cur_week,c.cur_year);
			bindHandlers();
		})
		var bindHandlers = function(){
			$(".event").live("click",function(){
				c.displayEvent($(this));
			})
			
			$("#create_event_btn").click(function(){
				if(!$(this).hasClass("active")){
					c.newEvent($(this).attr("href"),$(this).attr("ref"),c.today.getDate(),c.today.getMonth()+1,c.today.getFullYear());
				}else{
					c.event_create_div.hide().empty();
				}
				$(this).toggleClass("active");
				return false;
			})
			$("td.click_event").live("click",function(){
				c.newEvent($(this).attr("link"),$(this).attr("ref"),$(this).attr("date"),c.cur_month,c.cur_year);
				$("#create_event_btn").toggleClass("active");
			})
			
			$('.mode_switch').click(function(){
				var target = $(this).text();
				switch(target){
					case 'month':
						c.loadMonthView(c.cur_month,c.cur_year);
					break;
					case 'week':
						c.loadWeekView(c.cur_week,c.cur_year);
					break;
					case 'day':
						c.loadDayView();
					break;
					case 'agenda':
						c.loadAgendaView();
					break;
				}
			})
			$("button#prev_month_btn").click(function(){
				switch (c.view){
					case "month":
						var m,y;
						if(c.cur_month == 1){
							m = 12;
							y = c.cur_year-1;
						}else{
							m = c.cur_month-1;
							y = c.cur_year;
						}
						c.loadMonthView(m,y);
					break;
					case "week":
						var w,y;
						if(c.cur_week == 1){
							w = 52;
							y = c.cur_year - 1;
						}else{
							w = c.cur_week - 1;
							y = c.cur_year;
						}
						c.loadWeekView(w,y);
					break;
				}
				
			})
			$("button#next_month_btn").click(function(){
				switch (c.view){
					case "month":
						var m,y;
						if(c.cur_month == 12){
							m = 1;
							y = c.cur_year+1;
						}else{
							m = c.cur_month+1;
							y = c.cur_year;
						}
						c.loadMonthView(m,y);
					break;
					case "week":
						var w,y;
						
						if(c.cur_week == 52){
							w = 1;
							y = c.cur_year + 1;
						}else{
							w = c.cur_week + 1;
							y = c.cur_year;
						}
						c.loadWeekView(w,y);
					break;
				}
			})
			$("button#today_btn").click(function(){
				switch (c.view){
					case "week":
						c.loadWeekView();
					break;
					case "month":
						c.loadMonthView();
					break;
				}
			})
		}
	}
	this.loadMonthView = function(month,year){
		c.view = "month";
		if(!month){
			var dt = new Date();
			month = dt.getMonth()+1;
			year = dt.getFullYear();
		}
		// month = 10;
		// year = 2008;
		c.cur_month = month;
		c.cur_year = year;
		$('#view_holder').load("cals/month_view?month="+month+"&year="+year, function() {
			c.getEventsForMonth(month,year);
			$('.current_day_title').text(c.monthlist[c.cur_month]+" "+c.cur_year);
			if($('#calendar_month').length > 0){
				var $c_table = $('#calendar_month');
				var sum_h = 0;
				var context_h = $(window).height() - $('#orbit-bar').height();
				$('#main-wrap > *').not('#orbit_calendar, .modal').each(function(){
					sum_h += $(this).outerHeight();
				});

				$c_table
					// .height(context_h-sum_h-64)
					.find('.month_row')
					.not('.month_row.header')
					.height((context_h-sum_h-92) / 6);
				
				$(window).resize(function(){
					$c_table
						.find('.month_row')
						.not('.month_row.header')
						.height(($('#main-sidebar').outerHeight()-sum_h-92) / 6);
				});
			}
		})
		
	}
	
	
	this.getEventsForMonth = function(month,year){
		$.getJSON("cals/getMonthEvents",{"month":month,"year":year},function(events){
			makerow(events);
		})
		var doneEventArray = new Array();		
		var makerow = function(events){
			var $eventrow =null;
			var currow = 0;
			var curdate = 0;
			var allow = false;
			var curparent = null;
			var lastno = 0;
			var indexcount = events.length;
			$.each(events,function(i,evnt){
				indexcount++;
				if($.inArray(evnt.index,doneEventArray) == -1){
					
					var daydom = $("#calendar_month td[date="+evnt.start_date+"]");
					var thisparent = daydom.parent().parent().parent(); 
					var thisrow = thisparent.attr("row");
					var pos = parseInt(daydom.attr("position"));
					var thisno = daydom.attr("no"); 
					if(thisrow != currow){
						if(curparent){
							curparent.append($eventrow);	
						}
						$eventrow = null;
						$eventrow = $("<tr class='event_row'></tr>");
						allow = true;
					}else if(evnt.start_date > curdate){
						allow = true;
						
					}
					var recordcurdate = true;
				
					if(allow){
						if(pos == 1){
							var colspan = 0;
							if(evnt.total_days>7){
								colspan = 7;
								var totaldays = parseInt(evnt.total_days) - colspan;
								var stardate = parseInt(evnt.start_date) + colspan;
								var index = i + 1;
								var tempArray = {"index":indexcount,"id":evnt.id,"start_date":stardate,"total_days":totaldays,"title":evnt.title,"color":evnt.color,"show_link":evnt.show_link};
								events.splice(index,0,tempArray);
								//recordcurdate = false;
							}else{
								colspan = evnt.total_days;
							}
							$eventrow.html('<td colspan="'+colspan+'" class="main_td" pos="'+pos+'"><div class="event" link="'+evnt.show_link+'" style="background-color: '+evnt.color+';">'+evnt.title+'</div></td>');
						}else{
							if($eventrow.html()==""){
								$eventrow.append('<td colspan="'+(pos-1)+'"></td>');
							}else{
								if((lastno+1)!=thisno){
									var inposition = parseInt($eventrow.find("td.main_td:last").attr("pos"));
									var curcolspan = $eventrow.find("td.main_td:last").attr("colspan");
									var colspan = pos - (inposition+parseInt(curcolspan));
									$eventrow.append('<td colspan="'+colspan+'"></td>');
								}
							}
							var colspan = 0;
							if((pos + parseInt(evnt.total_days))-1 > 7){
								colspan = 7-(pos-1);
								var totaldays = parseInt(evnt.total_days) - colspan;
								var stardate = parseInt(evnt.start_date) + colspan;
							
								var index = i + 1;
								var tempArray = {"index":indexcount,"id":evnt.id,"start_date":stardate,"total_days":totaldays,"title":evnt.title,"color":evnt.color,"show_link":evnt.show_link};
								events.splice(index,0,tempArray);								
							//	recordcurdate = false;
								
							}else{
								colspan = evnt.total_days;
							}
							// if(evnt.title == "Again")
							// 	console.log(colspan);
							$eventrow.append('<td colspan="'+colspan+'" class="main_td" pos="'+pos+'"><div link="'+evnt.show_link+'" class="event" style="background-color: '+evnt.color+';">'+evnt.title+'</div></td>');
						}
						lastno = (parseInt(thisno) + parseInt(evnt.total_days)) - 1;
						currow = thisrow;
						curdate =(evnt.start_date + evnt.total_days) - 1;
						allow = false;
						curparent = thisparent;
						if(recordcurdate)
							doneEventArray.push(evnt.index);
						
					}
				}

			})
			if(curparent){
				curparent.append($eventrow);
			}
			if(events.length != doneEventArray.length){
				makerow(events);
			}
		}
	}

	this.loadWeekView = function(week,year){
		c.view = "week";
		if(!week){
			var dt = new Date();
			week = dt.getWeek();
			year = dt.getFullYear();
		}

		c.cur_week = week;
		c.cur_year = year;

		$('#view_holder').load("cals/week_view?week="+week+"&year="+year, function() { 
			$('.current_day_title').text($("#week_range").text());
			c.getEventsForWeek(week,year);
		})
	}
	this.getEventsForWeek = function(week,year){
		$.getJSON("cals/getWeekEvents",{"week":week,"year":year},function(events){
			$.each(events,function(i,evnt){
				if(evnt.all_day){
					$(".week_day_header[date="+evnt.start_date+"]").append('<div class="event half" link="'+evnt.show_link+'" style="background-color: '+evnt.color+';color:#fff;"><dl><dt>'+evnt.title+'</dt><dd></dd></dl></div>');
				}else{
					var starttime,endtime,displaystarttime,displayendtime;
					if(evnt.start_am_pm == "AM")
						starttime = evnt.start_time;
					else
						starttime = evnt.start_time + 12;

					if(evnt.end_am_pm == "AM")
						endtime = evnt.end_time;
					else
						endtime = evnt.end_time + 12;
					
					var temp = parseInt(evnt.start_time);
					
					if (evnt.start_time > temp)
						displaystarttime = temp + ":30 " + evnt.start_am_pm;
					else
						displaystarttime = temp + ":00 " + evnt.start_am_pm;

					temp = parseInt(evnt.end_time);
					
					if (evnt.end_time > temp)
						displayendtime = temp + ":30 " + evnt.end_am_pm;
					else
						displayendtime = temp + ":00 " + evnt.end_am_pm;

					var toppx = ((starttime * 2) * 19) + starttime;
					var eventdom = $('<div class="event" link="'+evnt.show_link+'" style="background-color: '+evnt.color+';color:#fff; top:'+toppx+'px;"><dl><dt>'+displaystarttime+' - '+displayendtime+'</dt><dd>'+evnt.title+'</dd></dl></div>');
					$(".week_day_body[date="+evnt.start_date+"] .inner").append(eventdom);
				}

			})
		})
	}
	this.loadDayView = function(){
		$('#view_holder').load("cals/day_view", function() { 
			$('.current_day_title').text('September 2, 2012');
		})
	}
	this.loadAgendaView = function(){
		$('#view_holder').load("cals/agenda_view", function() { 
			$('.current_day_title').text('September 2, 2012');
		})
	}
	this.newEvent = function(url,ref,date,month,year){
		var bindHandlers = function(){
			c.event_create_div.find("button.btn-close").click(function(){
				c.event_create_div.hide().empty();
				$("#create_event_btn").removeClass("active");
			})
			c.event_create_div.find("input[for=all_day][type=checkbox]").click(function(){
				if($(this).is(":checked"))
					c.event_create_div.find("#non_all_day").hide()
				else
					c.event_create_div.find("#non_all_day").show()
			})
		}

		c.event_create_div.load(url+"?ref="+ref+"&date="+date+"&month="+month+"&year="+year,function(){
			c.event_create_div.show();
			bindHandlers();
		})
		
	}
	this.newCalendars = function(){
		if($('.color-picker').length > 0){
			$('.color-picker').miniColors(); // just in category view
		}
		$(".btn-del-a").live("ajax:success",function(){
			var domfor = $(this).attr("data-content");
			$("tr[for="+domfor+"]").remove();
		})
	}
	this.displayEvent = function(dom){
		var url = dom.attr("link");
		c.event_quick_view_div.load(url,function(){
			c.event_quick_view_div.show()
			c.event_quick_view_div.find(".event-close-btn").click(function(){
				c.event_quick_view_div.empty().hide();
			})
		})
	}
	
	c.initialize();
}







