/* toggles the content view of an event*/
function evt_toggle(key)
{
	event_block = $('more'+key);
	if (event_block.visible()) {
		Effect.BlindUp(event_block, {duration:0.15, afterFinish:ec_twist($('twist'+key))});
	} else {
		Effect.BlindDown(event_block, {duration:0.15, afterFinish:ec_twist($('twist'+key))});
	}
}

// set up
var mon_RExp = new RegExp("(this[ ]+)*mon[a-z]*","i");
var tue_RExp = new RegExp("(this[ ]+)*tue[a-z]*","i");
var wed_RExp = new RegExp("(this[ ]+)*wed[a-z]*","i");
var thu_RExp = new RegExp("(this[ ]+)*thu[a-z]*","i");
var fri_RExp = new RegExp("(this[ ]+)*fri[a-z]*","i");
var sat_RExp = new RegExp("(this[ ]+)*sat[a-z]*","i");
var sun_RExp = new RegExp("(this[ ]+)*sun[a-z]*","i");

var msecsInADay  = 86400000;

// Time String
function getTimeStringer(theTime)
{
	tHours    = theTime.getHours();
	tAmPm     = ' am';
	if(tHours>12) { 
		tHours = tHours-12 
		tAmPm  = ' pm'
	}

	return ' ' + tHours + ':' + theTime.getMinutes() + tAmPm;
}

// function to produce a date string tAddedDays from today
tabberOptions = {tabCaps:true};

/* New Event Form */
var hideShow = function hideshow() {
	untilBox  = $('until_check')
	endingBox = $('ending')
	if(endingBox.visible()){
		endingBox.hide()
		untilBox.checked = false
	}else{
		untilBox.checked = true
		endingBox.show()
	}
}

function getDateStringer(thenow,addedDays)
{
	tEndDate = new Date(thenow.getTime() + msecsInADay*addedDays);
	return '' + (tEndDate.getMonth()+1) + '/' + tEndDate.getDate() + '/' + tEndDate.getFullYear();
}

// function to try and force a text field to have a proper formatted string
function be_date(field)
{
	str = field.value;
	if(str.length < 1){return;}

	tNow        = new Date();
	tDayOfWeek  = tNow.getDay()

	sun_AddDays = tDayOfWeek == 0 ? 7 : 7 - tDayOfWeek
	mon_AddDays = tDayOfWeek < 1 ? 1 - tDayOfWeek : (tDayOfWeek == 1 ? 7 : 7 - tDayOfWeek + 1);
	tue_AddDays = tDayOfWeek < 2 ? 2 - tDayOfWeek : (tDayOfWeek == 2 ? 7 : 7 - tDayOfWeek + 2);
	wed_AddDays = tDayOfWeek < 3 ? 3 - tDayOfWeek : (tDayOfWeek == 3 ? 7 : 7 - tDayOfWeek + 3);
	thu_AddDays = tDayOfWeek < 4 ? 4 - tDayOfWeek : (tDayOfWeek == 4 ? 7 : 7 - tDayOfWeek + 4);
	fri_AddDays = tDayOfWeek < 5 ? 5 - tDayOfWeek : (tDayOfWeek == 5 ? 7 : 7 - tDayOfWeek + 5);
	sat_AddDays = tDayOfWeek < 6 ? 6 - tDayOfWeek : (tDayOfWeek == 6 ? 7 : 7 - tDayOfWeek + 6);

	str = str.replace(/@|\sat\s/i,' ');
	str = str.replace(/today|tonight|tonite/i,getDateStringer(tNow,0));
	str = str.replace(/tomorrow/i,getDateStringer(tNow,1));
	str = str.replace(/now/i,getDateStringer(tNow,0) + getTimeStringer(new Date()));
	str = str.replace(mon_RExp, getDateStringer(tNow, mon_AddDays))
	str = str.replace(tue_RExp, getDateStringer(tNow, tue_AddDays))
	str = str.replace(wed_RExp, getDateStringer(tNow, wed_AddDays))
	str = str.replace(thu_RExp, getDateStringer(tNow, thu_AddDays))
	str = str.replace(fri_RExp, getDateStringer(tNow, fri_AddDays))
	str = str.replace(sat_RExp, getDateStringer(tNow, sat_AddDays))
	str = str.replace(sun_RExp, getDateStringer(tNow, sun_AddDays))
	str = str.replace(/^\s*(\d{1,2})\s*$/i,'$1 pm'); // assume just a number is a pm time
	str = str.replace(/^\s*(\d{1,2}:\d{1,2})\s*$/i, getDateStringer(tNow,0) +' $1 pm'); // assume just a time is a pm time
	str = str.replace(/^\s*(\d{1,2})\s*([ap]\.*m\.*)\s*$/i,getDateStringer(tNow,0) + ' $1:00 $2'); // make just an am/pm time into a full date
	str = str.replace(/^\s*(\d{1,2})\s*([-.\/])\s*(\d{1,2}){1}([^/\-.]*$)/i,'$1$2$3$2'+tNow.getFullYear()+' $4'); // add year
	str = str.replace(/(\d{1,4}\s*[-.\/]\s*\d{1,2}\s*[-.\/]\s*\d{1,4}){1}(\s+[^0-9]*)(\d{1,2})([^:]*$)/i,'$1$2$3:00 $4'); // make sure there is an :00, assume pm
	str = str.replace(/:(\d{1,2}\s*)$/i,':$1 pm'); // assume pm

	field.value = str;
}

/* toggles display of events in calendar list*/
function cal_toggle(divid)
{
	blk=$(divid+'events');
	if(blk.hasClassName('eopen')){
		blk.hide();
		blk.removeClassName('eopen');
	}
	else{
		blk.addClassName('eopen');
		blk.show();
	}
	// spin the wisty
	ec_twist($(divid+'twist'));
	
	return false;
}

/* Twists the twisty */
function ec_twist(twisty)
{
	if(twisty)
	{
		if(twisty.hasClassName('twistopen'))
			twisty.removeClassName('twistopen');
		else
			twisty.addClassName('twistopen');
	}
}

/* custom event form code */
function be_int(field_obj,target)
{
	force_int(field_obj)

	if('tevt'.match(target))
	{
		if(new_val =! '')
			$('radio_count').checked = true;
		if(new_val == '' || parseInt(new_val) == 1)
			$(target).innerHTML = 'event';
		else
			$(target).innerHTML = 'total events';
	}else if('ourcal_event[recurrence]_units'.match(target))
	{
		pops = $(target)
		for(i=0;i < pops.length;i++)
		{
			if(new_val == '' || parseInt(new_val) == 1)
			{
				if( pops.options[i].text.match(/(.*)s+$/) )
					pops.options[i].text = pops.options[i].text.replace(/(.*)s+$/,'$1');
			}
			else
				pops.options[i].text += 's';
		}
	}
}

/*Show/hide edit/subscribe buttons for events*/
var toggleEventEditing = function ()
{
	$$('.evt-edt').each(function(element,idx) {
		if(element.visible()) {
			new Effect.BlindUp(element,{duration: .2,scaleX:true});
		} else {
			new Effect.BlindDown(element,{duration: .2,scaleX:true});
		}
	})
};

/*show more info form elements on new event*/
var twistMoreEventInfo = function(){
		moreInfo = $('event-more-info');
		if(moreInfo){
			if(moreInfo.visible()) {
				$('wide-btm').hide();
				new Effect.BlindUp(moreInfo,{duration: .2});
				$('eftwist').removeClassName('twistopen');
			} else {
				$('eftwist').addClassName('twistopen');
				$('wide-btm').show();
				new Effect.BlindDown(moreInfo,{duration: .2});
			}
		}
}
/*location search*/
var performLocationSearch = function(){
searchForm = $('loc_search');
//if searchForm{
searchForm.country = $F('pub-country-picker');
searchForm.state   = $F('pub-here-state');
searchForm.term    = $F('pub-here-term');
new Ajax.Request(searchForm.action, {asynchronous:true, evalScripts:true, parameters:Form.serialize(searchForm)})
//}

}

/*operations*/
var locOptOver = function(e) {
	var elt = Event.element(e);
	elt.addClassName('hover');
}
var locOptOut = function(e) {
	var elt = Event.element(e);
	elt.removeClassName('hover');
}

var hideLastLocation = function(element,v){
	if(element.visible()) {
		//element.hide();
		Effect.BlindUp(element, {duration:0.05});
	}
}

var toggleLoc = function(e) {
	var elt       = Event.element(e);

	if(elt.type == 'radio'){ 
		elt.checked = 'checked';
		elt = elt.parentNode; 
	}else{
		elt = elt.parentNode; 
		$(elt.id+'-btn').checked   = 'checked';
	}
	showLocType(elt.id)
}

var showLocType = function(id){
	var box = $(id+'-content');

	if (!box.visible()) {
		$$('.loc-category').each( function(e,i){e.removeClassName('picked-loc')} );
		$$('.place-tab').each( hideLastLocation );
		$(id).addClassName('picked-loc');
		Effect.BlindDown(box, {duration:0.2});
	}
	
}

var toggleAllDay = function(e) {
	var elt       = Event.element(e);

	if(elt.id != 'all_day_check')
	{
		allDayCheck = $('all_day_check');
		if(allDayCheck){
			allDayCheck.checked = !allDayCheck.checked;
		}
	}
}

/*caled when My Place popup changes*/
var myPlaceChosen = function(){
	myPlace = $F('our_location_key');

	if(myPlace=='0'){myPlace = '';}

	$('found_key').value = myPlace;
}

/*caled when Public Place link chosen*/
var publicPlaceChosen = function(place){
	$('our_location_key').selectedIndex = 0;
	$('found_key').value = place;
}

var myCountryChosen = function(){
	currentCountry = $F('country-picker');
	toggleCountry(currentCountry, 'state-box', 'region-box');
}

var toggleCountry = function(currentCountry, stateID, intlID)
{
	stateBox       = $(stateID);
	intlBox        = $(intlID);
	stateCtrl      = stateBox.down('select');
	intlCtrl       = intlBox.down('input');

	if( currentCountry.length < 2 || currentCountry.match(/US|CA/i) ){
		if(stateCtrl.disabled){
			stateCtrl.disabled = false
			stateBox.visualEffect("blind_down", {duration:0.2});
		}
		if(!intlCtrl.disabled)
		{
			intlCtrl.disabled = true
			intlBox.visualEffect("blind_up", {duration:0.2});
		}
	}else{
		if(!stateCtrl.disabled){
			stateCtrl.disabled = true
			stateBox.visualEffect("blind_up", {duration:0.2});
		}
		if(intlCtrl.disabled)
		{
			intlCtrl.disabled = false
			intlBox.visualEffect("blind_down", {duration:0.2});
		}
	}
}

var initializeEventForm = function(){
	untilBox = $('until_box')
	Event.observe(untilBox,'click', hideShow);
	Event.observe(untilBox,'mouseover', locOptOver);
	Event.observe(untilBox,'mouseout', locOptOut);

	allDayBox = $('all_day_box')
	if(allDayBox){
		Event.observe(allDayBox,'click', toggleAllDay);
		Event.observe(allDayBox,'mouseover', locOptOver);
		Event.observe(allDayBox,'mouseout', locOptOut);
	}

	Event.observe($('our_location_key'),'change', myPlaceChosen);

  $('loc-search-link').onclick = performLocationSearch;

	$$('.loc-category').each( function(e,v){
		Event.observe(e,'click', toggleLoc);
		Event.observe(e, 'mouseover', locOptOver);
		Event.observe(e, 'mouseout', locOptOut);
	} )

	Event.observe($('country-picker'),'change', myCountryChosen);

	be_int($('repeat_interval_field'),'ourcal_event_repeat_units');

	if(display_extra_info){
		twistMoreEventInfo();
	}
	
}

