var req;
var loadedAddEventForm=false;
var editors = new Array(2);
var form_inputs = new Array('title','start_date','end_date','start_time','end_time');
var form_selects = new Array('type','start_time_ampm','end_time_ampm','photo_album_id','link_to');
var form_checkboxes = new Array('member_only','featured');
var scroller;
var the_current_hash;

function loadEventsDOM() {
	load_calendar();
	loadEvent();
	scroller = new Fx.Scroll(window);
}

function load_calendar() {
	$$('#month a.meeting','#month a.event','#upcomming a','#past a').each(function(a) {
		a.addEvent('click',loadEvent);														 
	});
}

function loadEvent() {
	(function() {
	if( window.location.hash && the_current_hash!=window.location.hash && !(window.location.hash.length==8 && window.location.hash.test(/^#[0-9]{4}-[0-9]{2}$/)) ) {
		the_current_hash = window.location.hash;
		show_loading();
		if( $('add_event') )
			$('add_event').setStyle('display','none');
		var ename = the_current_hash.substring(1, the_current_hash.length);
		if( req ) req.cancel()
		req = new Request({
									url: 'get.php',
									method: 'get',
									data: 'name='+ename,
									onSuccess: function(text,xml) { 
													$('event-content').set('html',text);
													$('event-content').setStyle('display','block');
													req = null;
													hide_loading();
													//If this is a master event with a list of sub events, make those sub events work
													if( $('happenings') ) {
														$('happenings').getElements('a').each ( function(a) {
															a.addEvent('click',loadEvent);	
														});
													}
													//Bring User to the Event
													var pos = $('event-content').getPosition();
													scroller.start(0,pos.y-5);
													
													//Check to see if the current month is the same as the event
													var event_month   = $('event_month').get('text');
													var current_month = $('current_month').get('text');
													if( event_month!=current_month ) {
														to_month( event_month.substr(5), event_month.substr(0,4), false );
													}
												},
									onCancel:   function() { req = null; hide_loading(); },
									onFailure:  function(inst) { req = null; hide_loading(); }
									});
			hide_event();
			req.send(); 
	} else if( the_current_hash==window.location.hash ) {
		var pos = $('event-content').getPosition();
		scroller.start(0,pos.y-5);
	}
	
	}).delay(150,this);
}


function change_calendar() {
	(function() {	
		if( window.location.hash && the_current_hash!=window.location.hash ) {
			the_current_hash = window.location.hash;
			//#YYYY-MM
			//01234567
			var year = window.location.hash.substr(1,4);
			var month = window.location.hash.substr(6);
			to_month( month, year );
		}
	}).delay(150,this);
}

function change_calendar_from_select() {
	var year = $('year_choice').get('value');
	var month = $('month_choice').get('value');
	if( the_current_hash != '#'+year+'-'+month ) {
		the_current_hash = '#'+year+'-'+month;
		window.location.hash = the_current_hash;
		to_month( month, year );
	}
}

function edit_event(id) {
	hide_event();
	the_current_hash = '';
	show_loading();
	if( req ) req.cancel();
	$('edit_event_id').setProperty('value',id);
	req = new Request({
							url: 'get_edit_data.php',
							method: 'get',
							data: 'id='+id,
							onSuccess: function(text,xml) { 
											load_edit_event_form( new Hash(JSON.decode(text)) );
											req = null;
											hide_loading();
										},
							onCancel:   function() { req = null; hide_loading(); },
							onFailure:  function(inst) { req = null; hide_loading(); }
					});
	req.send();
}
function add_event(date) {	
	form_inputs.each(function(str) {
		$('add_event_'+str).getElement('input').set('value','');
	});
	
	form_selects.each(function(str) {
			$(str).selectedIndex = 0;
		});
	
	if( loadedAddEventForm ) {
		editors[0].removeInstance('event_where');
		editors[1].removeInstance('event_description');
		loadedAddEventForm = false;
	}
	$('event_where').value = '';
	$('event_description').value = '';
	
	form_checkboxes.each(function(cb) {
			$(cb).checked = false;
		});
	
	$('start_date').setProperty('value',date);
	$('end_date').setProperty('value',date);
	
	$('remove_event_link').setStyle('display','none');
	$('add_event_heading').setStyle('display','block');
	$('edit_event_heading').setStyle('display','none');
		
	$('add_event_do').setProperty('value','add_event');
	load_event_form();
}

function load_event_form() {
	hide_event();
	hide_event_form();
	if( $('add_event') )
		$('add_event').setStyle('display','block');
	
	if( !loadedAddEventForm ) {
		$$('.nicedit').each(function(ed,index) { editors[index] = new nicEditor({fullPanel : true, 
																						iconsPath: '../includes/nicEditorIcons.gif'}).panelInstance(ed); });
		$$('.datepicker').each(function(dp) { new DatePicker(dp,{format: 'yyyy-mm-dd', onChange:compare_dates}); });
		loadedAddEventForm = true;
	}
	set_event_type();
}

function load_edit_event_form(data) {
	form_inputs.each(function(str) {
			$('add_event_'+str).getElement('input').set('value',data.get(str));
		});
	
	form_selects.each(function(str) {
			var ops = $(str).options;	
			for( var i=0; i<ops.length; ++i )
					if( ops[i].value==data.get(str) )
						$(str).selectedIndex = ops[i].index;
		});
	
	if( loadedAddEventForm ) {
		editors[0].removeInstance('event_where');
		editors[1].removeInstance('event_description');
		loadedAddEventForm = false;
	}
	$('event_where').value = data.get('where');
	$('event_description').value = data.get('description');
	
	form_checkboxes.each(function(cb) {
			if(data.get(cb)=='1')
				$(cb).checked = true;
			else
				$(cb).checked = false;
		});
	
	$('add_event_heading').setStyle('display','none');
	$('edit_event_heading').set('text','Edit ' + data.get('title'));
	$('edit_event_heading').setStyle('display','block');
	$('add_event_do').setProperty('value','edit_event');
	$('remove_event_link').setStyle('display','block');
	$('remove_event_link').set('href','/events/?r='+data.get('id'));
	
	load_event_form();
	//!!!!! still need to handle image here
}

function hide_event_form() {
	if( $('add_event') )
		$('add_event').setStyle('display','none');
}

function hide_event() {
	$('event-content').setStyle('display','none');
}

function checkHash(){
	var found = false;
	$$('h4.toggler a').each(function(link, i){
		if (window.location.hash == link.hash){
			showThis = i;
			found = true;
		}
		link.myIndex = i;
	});
	return found;
}

function show_loading() {
	$('loading').setStyle('display','block');
}

function hide_loading() {
	$('loading').setStyle('display','none');
}

function compare_dates(dp) {
	if( $('type').value=='event' ) {
		var startd = parseDate($('start_date').value);
		var endd = parseDate($('end_date').value);
		if( startd>endd ) {
			if( dp.id == 'start_date' )
				$('end_date').value = dp.value;
			else
				$('start_date').value = dp.value;
		}
	}
}

function set_event_type() {
	var event_type = $('type').value;
	if( event_type=='ssc_event' )
		$('add_event_start_date').getElement('label').set('text','Start Date*:');
	else
		$('add_event_start_date').getElement('label').set('text','Date*:');
	
	if( event_type=='meeting' ) {
		$('add_event_title').getElement('label').set('text','Title:');
		$('add_event_title').getElement('.caption').setStyle('display','inline');
	} else {
		$('add_event_title').getElement('label').set('text','Title*:');
		$('add_event_title').getElement('.caption').setStyle('display','none');
	}
	
	if( event_type!='holiday' && event_type!='master' ) {
		$$('#add_event .labeled').each(function(d) { d.setStyle('display','block') });
											
		if( event_type=='meeting' ) {
			$('add_event_end_date').setStyle('display','none');
			$('add_event_album').setStyle('display','none');
			$('add_event_image').setStyle('display','none');
			$('add_event_featured').setStyle('display','none');
			$('add_event_link_to').setStyle('display','none');
		}
	} else {
		$$('#add_event .labeled').each(function(d) { d.setStyle('display','none') });
		$('add_event_type').setStyle('display','block');
		$('add_event_title').setStyle('display','block');
		if( event_type=='holiday' )
			$('add_event_start_date').setStyle('display','block');
		else {
			$('add_event_description').setStyle('display','block');
			$('add_event_featured').setStyle('display','block');
		}
	}
}

function explain_event_types() {
	scroller.toElement($('explain_event_types'));
}

function to_month(m,y,is_show_loading) {
	if( is_show_loading==null ) is_show_loading = true;
	if( req ) req.cancel();
	if( is_show_loading ) {
		$('month').setStyle('display','none');
		hide_event();
		hide_event_form();
		show_loading();
	}
	req = new Request({
							url: 'calendar.php',
							method: 'get',
							data: 'm='+m+'&y='+y,
							onSuccess: function(html,xml) { 
											$('month').set('html',html);
											load_calendar();
											if( is_show_loading ) {
												hide_loading();
												$('month').setStyle('display','block');
											}
										},
							onCancel:   function() { req = null; if( is_show_loading ) hide_loading(); },
							onFailure:  function(inst) { req = null; if( is_show_loading ) hide_loading(); }
					});
	req.send();
}

//Returns an integer so that 2 dates can be compared for before and after
// '1986-12-13' => 19,861,213
function parse_date(str) {
	//YYYY-MM-DD
  //0123456789
	return parseInt(str.substr(0,4))*10000 + parseInt(str.substr(5,2))*100 + parseInt(str.substr(8,2));
}