if(!PB) var PB = {};

var ScheduleWidget = Class.create({
	initialize:function(element)
	{
		$$('body')[0].insert('<div id="todays_date" style="display:none">'+new Date()+'</div>');
		this.element = $(element);
		this.createWidget();
		this.savedDays = Array();
		if($('event_add_day'))
			{
				this.calendar = Calendar.setup({
					triggerElement : 'event_add_day',
					selectHandler : this.addDay.bindAsEventListener(this),
					dateField:'todays_date'
				});
			}
			this.days = new Array();

			this.dayCount = $$('.schedule_day').length;
	},
	createWidget:function()
	{

	},
	setRecurring:function()
	{
		switch($('events[recurring]').value)
		{
			case "0":
				if($('recurring_settings').down('#is_recurring'))
				$('recurring_settings').down('#is_recurring').remove();
				$('recurring_settings').hide();
			break;
			case "1":
				if($('recurring_settings').down('#is_recurring'))
				$('recurring_settings').down('#is_recurring').remove();
				$('recurring_settings').show();
				$('recurring_settings').insert('<input type="hidden" id="is_recurring" value="1"/>');
				$('recurring_weekly').show();
				$('recurring_monthly').hide();
			break;
			case "2":
				if($('recurring_settings').down('#is_recurring'))
				$('recurring_settings').down('#is_recurring').remove();
				$('recurring_settings').show();
				$('recurring_settings').insert('<input type="hidden" id="is_recurring" value="1"/>');
				$('recurring_monthly').show();
				$('recurring_weekly').hide();
			break;
		}
	},
	reinitCalendar:function(day)
	{
		this.calendar = Calendar.setup({
			triggerElement : 'date',
			closeHandler : this.addDay.bindAsEventListener(this)
		});
	},
	addDay:function(calendar)
	{
		if(!calendar.shouldClose)
			return;

		var day = this.newDayNum();

		$('event_schedule_days').insert(this.createStaticDayMarkup(day));

		$('schedule_day_date_'+day).update(calendar.date.strftime('%a %b %d, %Y'));

	},
	getSchedule:function()
	{
		$$('.schedule_day').each(function(day)
					 {
						 var day_num = day.readAttribute('id').gsub('schedule_day_','');

						 var the_date = (new Date(Number($('schedule_day_date_'+day_num).innerHTML.trim())).getUnix() > 0) ? new Date(Number($('schedule_day_date_'+day_num).innerHTML.trim())).getUnix() : new Date($('schedule_day_date_'+day_num).innerHTML.trim()).getUnix();
						 if(!this.days[day_num])
							 this.days[day_num] = {};

						 this.days[day_num].date = the_date;
						 this.days[day_num].start_time = this.formatTime($('schedule_day_start_time_'+day_num) ? $('schedule_day_start_time_'+day_num).innerHTML : '');
						 this.days[day_num].end_time = this.formatTime($('schedule_day_end_time_'+day_num) ? $('schedule_day_end_time_'+day_num).innerHTML : '');
						 this.days[day_num].comment = $('schedule_day_comment_'+day_num).innerHTML;
					 }.bind(this));

					 return this.days;
	},
	addDayComment:function(day)
	{
		$('add_comment_btn_'+day).hide();
		$('schedule_day_comment_wrap_'+day).show();
	},
	newDayNum:function()
	{
		return this.dayCount++;
	},
	editDay:function(day)
	{
		if(this.savedDays[day])
			$('schedule_day_'+day).replace(this.savedDays[day]);

		else
			this.createDayMarkup(day);
	},
	showComment:function(day)
	{
		$('schedule_day_comment_wrap_'+day).show();

		$('show_comment_'+day).hide();
		$('hide_comment_'+day).show();
	},
	cancelDay:function(day)
	{
		$('schedule_day_'+day).remove();
	},
	deleteDay:function(day)
	{
		$('schedule_day_'+day).remove();
	},
	hideComment:function(day)
	{
		$('schedule_day_comment_wrap_'+day).hide();

		$('show_comment_'+day).show();
		$('hide_comment_'+day).hide();
	},
	saveDayComment:function(day){},
	formatTime:function(time)
	{

		switch(time.gsub(':','').length)
		{
			case 1:
				return String(time.gsub(':','')) + ':00';
			break;
			case 2:
				return String(time.gsub(':','')) + ':00';
			break;
			case 3:
				return String(time.gsub(':','')[0]) + ':' + String(time.gsub(':','')[1]) + String(time.gsub(':','')[2]);
			break;
			case 4:
				return String(time.gsub(':','')[0]) + String(time.gsub(':','')[1]) + ':' + String(time.gsub(':','')[2]) + String(time.gsub(':','')[3]);
			break;
			default:
				return '';
		}
	},	
	saveDay:function(day)
	{
		regular_day = this.createRegularDayMarkup(day);
		if(!regular_day)
			return;

		the_date = new Date($('schedule_day_date_'+day).innerHTML);
		unix_time = the_date.getUnix();

		if(!this.days[day])
			this.days[day] = {};

		this.days[day].start_time = this.formatTime($('schedule_day_start_time_'+day).value+$('schedule_day_start_time_ampm_'+day).value);
		this.days[day].date = unix_time;
		this.days[day].end_time  = this.formatTime($('schedule_day_end_time_'+day).value+$('schedule_day_end_time_ampm_'+day).value);
		this.days[day].comment = $('schedule_day_comment_'+day).value;
		this.savedDays[day] = $('schedule_day_'+day).replace(regular_day);
	},
	createStaticDayMarkup:function(day)
	{
		var day_count = day;

		return '<div class="schedule_day clearfix" id="schedule_day_'+day_count+'">'+
			'<div class="schedule_day_date" id="schedule_day_date_'+day_count+'"></div>'+
				'<div class="schedule_day_start_end_time" style="margin-left:1em">'+
					'from: <input id="schedule_day_start_time_'+day_count+'" type="text" maxlength="5" size="3"/>'+
						'<select id="schedule_day_start_time_ampm_'+day_count+'"style="font-size:.9em;margin-right:2.5em">'+
							'<option value="">am/pm</options>'+
								'<option value="am">am</option>'+
									'<option value="pm">pm</option>'+
										'</select>'+
											'to: <input type="text" id="schedule_day_end_time_'+day_count+'" maxlength="5" size="3"/>'+
												'<select id="schedule_day_end_time_ampm_'+day_count+'" style="font-size:.9em;">'+
													'<option value="">am/pm</options>'+
														'<option value="am">am</option>'+
															'<option value="pm">pm</option>'+
																'</select>'+
																	'</div>'+
																		'<div style="display:none;text-align:center;padding-top:12px;padding-bottom:10px" id="schedule_day_comment_wrap_'+day_count+'" class="schedule_day_comment_wrap">'+
																			'<textarea rows="4" cols="48" id="schedule_day_comment_'+day_count+'" class="schedule_day_comment"></textarea>'+
																				'</div>'+
																					'<div class="edit_btns float-right">'+
																						'<a onclick="window.eventSchedule.addDayComment('+day_count+');" id="add_comment_btn_'+day_count+'" href="javascript:Prototype.emptyFunction();">add comment</a>'+
																							'<a onclick="window.eventSchedule.cancelDay('+day_count+');" href="javascript:Prototype.emptyFunction();">cancel day</a>'+
																								'<a onclick="window.eventSchedule.saveDay('+day_count+');" href="javascript:Prototype.emptyFunction();">create day</a>'+
																									'</div>'+
																										'</div>';
	},
	createRegularDayMarkup:function(day)
	{
		var day_count = day;
		if(($('schedule_day_start_time_'+day_count).value.match(/[^\d:]/g)) || ($('schedule_day_end_time_'+day_count).value.match(/[^\d:]/g)))
			{
				window.growler.error('invalid time format. ex 12:00',{header:'Error.'});
				return;
			}


			return '<div class="schedule_day clearfix" id="schedule_day_'+day_count+'">'+
				'<div class="schedule_day_date" id="schedule_day_date_'+day_count+'">'+$('schedule_day_date_'+day_count).innerHTML+'</div>'+
					'<div class="schedule_day_start_end_time" style="margin-left:1em">'+
						'<span id="schedule_day_start_time_'+day_count+'">'+this.formatTime($('schedule_day_start_time_'+day_count).value)+'</span>'+
							'<span>'+$('schedule_day_start_time_ampm_'+day_count).value+'</span>'+
								'- <span id="schedule_day_end_time_'+day_count+'">'+this.formatTime($('schedule_day_end_time_'+day_count).value)+'</span>'+
									'<span>'+$('schedule_day_end_time_ampm_'+day_count).value+'</span>'+
										'</div>'+
											'<div style="display:none;padding-top:12px;padding-bottom:10px" id="schedule_day_comment_wrap_'+day_count+'" class="schedule_day_comment_wrap">'+
												'<p class="schedule_day_comment" id="schedule_day_comment_'+day_count+'" style="font-style:italic;font-size:.75em;width:90%;margin-left:5%;">'+$('schedule_day_comment_'+day_count).value+'</p>'+
													'</div>'+
														'<div class="white_btn">'+
															'<a id="show_comment_'+day_count+'" onclick="window.eventSchedule.showComment('+day_count+');" href="javascript:Prototype.emptyFunction();">show comment</a>'+
																'<a style="display:none" id="hide_comment_'+day_count+'" onclick="window.eventSchedule.hideComment('+day_count+');" href="javascript:Prototype.emptyFunction();">hide comment</a>'+
																	'<a onclick="window.eventSchedule.editDay('+day_count+');" href="javascript:Prototype.emptyFunction();">edit</a>'+
																		'<a onclick="window.eventSchedule.deleteDay('+day_count+');" href="javascript:Prototype.emptyFunction();">delete</a>'+
																			'</div>'+
																				'</div>';
	},
	replaceDay:function(content)
	{
		$('schedule_day_'+day).replace(content);
	},
	createDayMarkup:function(day)
	{

		var params = {
			day_num:day,
			day_date:$('schedule_day_date_'+day).innerHTML,
			day_start_time: $('schedule_day_start_time_'+day) ? this.formatTime($('schedule_day_start_time_'+day).innerHTML.gsub('am','')) : '',
			day_end_time: $('schedule_day_end_time_'+day) ? this.formatTime($('schedule_day_end_time_'+day).innerHTML.gsub('pm','')) : '',
			day_comment: $('schedule_day_comment_'+day) ? $('schedule_day_comment_'+day).innerHTML : ''
		};

		document.observe('template:schedule_day',function(event)
				 {
					 $('schedule_day_'+day).replace(event.memo);
					 document.stopObserving('template:schedule_day');
				 });
				 my_tpl = new PB.Template('schedule_day',{params:params,onFetch:this.replaceDay.bind(this,day)});
	}
});


/*______________________________________
EVENT INVITER
*/

var Inviter = Class.create(
	{
	initialize:function(element)
	{

	},
	updateInviteWidget:function()
	{
		$$('.friend_check').each(function(item)
					 {
						 if(item.checked)
							 {
								 count = Number($('rsvp_count').innerHTML);
								 $('rsvp_count').update(++count);
								 item.up('.friend_request').up('li').remove();

							 }
					 }.bind(this));
					 this.friendsToInvite = '';
	},
	invite:function(element_id)
	{
		//this.what = element_id.split('_')[0];
		//this.which = element_id/split('_')[1];

		this.area = $$('.friend_select_area')[0];

		var good_toss = this.area.descendants('.friend_check').partition(function(item){return item.checked;});
		this.friendsToInvite = new Array();
		good_toss[0].each(function(item)
				  {
					  this.friendsToInvite += ','+item.value.gsub('friend_','');
				  }.bind(this));

				  if(this.friendsToInvite.length <=1)
					  {
						  window.growler.error('you must select someone to invite.',{header:'Error.'});
						  return;
					  }
					  $ajax('/user.php',{action:'invite',invitees:this.friendsToInvite,to_what:element_id},this.handleServerResponse.bind(this));
		
		PB.FriendSelecter.close();
	},
	handleServerResponse:function(response)
	{
		switch(response.code)
		{
			case 200:
				window.growler.info(response.info,{header:'Success.'});
			this.updateInviteWidget();
			break;	
		}
	}
}); 
function initInviter()
{

	PB.Inviter = new Inviter();

}
/*_______________________________________
EVENTS FORM
*/
var eventsForm = Class.create(PB.Form,{
	initialize:function($super,element,options)
	{
		$super(element,options);
		this.onkeyups['events[title]'] = function(){$('event_title').update($('events[title]').value);};
		//this.initScheduleWidget();
	},
	preSubmit:function()
	{
		//PHPSerializer.serialize(window.eventSchedule.days);
		//PHPSerializer.serialize(eval(window.eventSchedule.days.toJSON()));
		var form_data = $(this.element).serialize(true);
		var schedule = window.eventSchedule.getSchedule();
		form_data['events_calendar[schedule]'] = schedule;

		this.form_data = PHPSerializer.serialize(form_data);
		return true;
	}
});


/*
EVENTS FORM
*/
function initeventsForm(){
	if($$('.event_form').length >0)
		{
			event_form = $$('.event_form')[0].readAttribute('id');
			if(event_form == 'user_new_events_form')
				PB.Forms.user_new_events_form = new eventsForm(event_form);

			if(event_form == 'user_events_edit_form')
				PB.Forms.user_events_edit_form = new eventsForm(event_form);
		}
}

/*
EVENT SCHEDULE
*/	
function initEventSchedule()
{
	window.eventSchedule = new ScheduleWidget('event_schedule_widget');
}


PB.addToDomLoad('initEventSchedule','');
//PB.addToDomLoad('initNicEdit','events[description]');

PB.addToDomLoad('initeventsForm','');

PB.addToDomLoad('initInviter','');


