
document.observe("dom:loaded", function() {
	// Check if the check in and out buttons are available, then init calendar
	if($('reservation_reservation_date')) {
		Calendar.setup({
			dateField				: 'reservation_reservation_date',
			triggerElement	: 'btnCalendar',
			dateFormat			: '%m/%d/%y'
		});
	}
	
	// I the mailing list is located on the page
	if($('frmMailList')) {
		bindMailListSingUp();
	}
	
	if($$('ul#main_nav li.maillist a').length > 0) {
		var mailLink = $$('ul#main_nav li.maillist a')[0];
		bindMailListLinks(mailLink, $('mailLinkFooter'));
	}
});

// Called once the check in date for the calendar component has been checked
function onCheckInSelected(e) {
	e.hide();	// call the calendars own close method
	setCheckOutForward($('dateCheckIn').value, 3);
}

// Sets the check out date forward
function setCheckOutForward(checkInDate, daysForward) {
	var dtCheckIn = new Date(checkInDate);
	var dtCheckOut = new Date(checkInDate);
	dtCheckOut.setDate(dtCheckIn.getDate()+daysForward);
	
	var sCheckOut = formatDate(dtCheckOut, "MM/dd/yy");
	$('dateCheckOut').value = sCheckOut;
}

function createToolTipWrapper(width, height, content) {
	if(!width) width = "200";
	var wrapStyle = "width:" + width + "px;";
	if(height) wrapStyle += "height:" + height + "px;";
	var wrap = new Element('div', { 'class' : 'tooltip', 
																	'style' : wrapStyle}).update(content);
	return wrap;
}

// Refreshes the web cam image for the weather conditions page
function refreshSkiCam() {
	var url = "http://telrtp1.tellurideskiresort.com/website/webcam/netcam.jpg";
	var append = new Date();
	append = "?" + append.getTime();
	$('snowCamImage').src = url + append;
}

// Returns a query time stamp which may be appended to urls, generates a string like "?1234858858"
function queryTimeStamp() {
	var strdate = new Date();
	strdate = "?" + strdate;
	return strdate;
}

function restrictPhoneValues(t){
	var allowedChars = "()- .0123456789";
	var w = "";
	for (i=0; i < t.value.length; i++) {
	x = t.value.charAt(i);
	if (allowedChars.indexOf(x,0) != -1)
	w += x;
	}
	t.value = w;
}

/**
 * Creates the handlers for posting an ajax form through a pop up
 */
function bindMailListSingUp() {
	var frm = $('frmMailList');
	var closeButtonTop = $$('#mailListContainer a.closeLink')[0];
	var closeButtonBottom = $('btnCloseMailFrm');
	
	frm.writeAttribute('onsubmit', 'return false;');	// stop submission
	closeButtonTop.observe("click", closeMailForm);
	closeButtonBottom.observe("click", closeMailForm);
	
	frm.observe('submit', function(e) {
		var params = frm.serialize();
		var url = "/subscriptions";
		new Ajax.Request(url, {
			method: 'post',
			parameters: params,
			onCreate: function(e) {
				$('mailSpinner').show();
			},
			onComplete: function(e) {
				$('mailSpinner').hide();				
			}
		});
	});
}

/**
 * Adds the launch functionality to the mailing list nav
 */
function bindMailListLinks(navLink, footerLink) {
	navLink.writeAttribute('href', "#mailList");
	footerLink.writeAttribute('href', '#mailList');
	
	navLink.observe('click', openMailWindow);
	footerLink.observe('click', openMailWindow);
}

/**
 * Opens a mail window
 */
function openMailWindow() {
	var mailContainer = $('mailListContainer');
	var modal = new Control.Modal($('mailListContainer'), {
		overlayOpacity: 0.90,
		className: 'modal',
		fade: true
	});
	modal.open();
}



/**
 * Handles the server's response for the mail list
 */
function displayMailListMessage(succeeded, message) {
	var container = $$('#frmMailList .responseContainer')[0];
	container.update( new Element('p').update(message) );
	container.show();
	
	if (succeeded) {
		var ol = $$('#frmMailList ol.form')[0];
		new Effect.BlindUp(ol, {duration: 0.25});
	}
}


/**
 * Uesd to close the mail form
 */
function closeMailForm() {
	Control.Modal.close();
}




// BEGIN admin photo selector logic
// These methods are used to load and select photos for the Specials model. They allow simple
// click-based selection and modify the hidden field 'special_photo_id' in order to set an id

/**
* Selects the photo in the ajax window
* @param	photoId 		the ID of the photo recorded in the special_photos table
*/
function selectSpecialPhoto(photoId) {
	deselectAllSpecialPhotos();
	imgDomId = "special_photo_" + photoId;	
	setPhotoStroke(imgDomId);
	updateSelectedPhotoId(photoId);
	$('selectedPhoto').src = $(imgDomId).src;
}

// Applies a stroke to the image specified
function setPhotoStroke(imgId) {
	$(imgId).removeClassName("deselectedSpecialPhoto");
	$(imgId).addClassName("selectedSpecialPhoto");
}

// Sets images in the photo_picker table to the off-selected state
function deselectAllSpecialPhotos() {
	$$('#photo_picker img').each(function(img) {
		$(img).addClassName("deselectedSpecialPhoto");
	});
}

/**
* Updates the hidden variable on the form page effectively setting the new photo once form is submitted
* @param		photoId			the id of the 'special_photo' which will be linked to the Special model
*/
function updateSelectedPhotoId(photoId) {
	$('special_special_photo_id').value = photoId;
}
// END admin photo selector logic

/**
* RSVP form page logic
* used in /rsvps/new
*/
function toggleRsvpRadio(radControlId) {
	$(radControlId).checked = true;
}

// end RSVP logic

/**
* BEGIN logic for admin ajax actions
*/

/**
* Updates a publish row, change its styles based on whether the item is published or unpublished
* @param	listItemId		the id of the list item containing the pressed button
@ @param	isPublished		whether the row is published or not
*/
function updatePublishStatusRow(listItemId, isPublished) {
	//console.log("update " + listItemId + " new status, published? " + isPublished);
	var newStyle = (isPublished) ? "unpublished" : "published";
	var oldStyle = (isPublished) ? "published" : "unpublished";
	var buttonContainer = $(listItemId).down();
	buttonContainer.removeClassName(oldStyle);
	buttonContainer.addClassName(newStyle);
}

/**
* Called at the very start of a row's ajax request. This prevents subsequent ajax actions to be called until
* the server has processed the command and returned a result
* @param	recordId	The database id of the object being changed. This is used to determine the domID of the element that triggered the ajax call
*/
function onChangePublishStatusRowChanged(recordId) {
	//console.log("received change from " + recordId);
	var linkId = "record_link_" + String(recordId);
	$(linkId).onclick = $(linkId).href = "javascript:void(0);";
}



// END admin ajax actions

/*
*
* Below is logic for converting dates from a simple string
*
*/

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
