// JavaScript Document

function adjustWindow() {
	var defHeight = 768;
	var defWidth = 1024;
	
	var windowHeight = getWindowHeight();
	var windowWidth = getWindowWidth();
	if (windowHeight < defHeight) {
		windowHeight -= 10;
		windowWidth -= 60;
		//var newwidth = parseInt((windowHeight * defWidth) / defHeight);
		setDims(windowWidth,
windowHeight);
	}
	else 
	{
		if (windowWidth < defWidth)
		{
			windowWidth -= 60;
			//var newheight = parseInt((windowWidth * defHeight) / defWidth);
			setDims(windowWidth,
 windowHeight);
		}
		else
		{
			setDims(defWidth,
 defHeight);
		}
	}
}

function getWindowHeight() {
  var myHeight = 0;
  if (typeof(window.innerWidth) == "number") {
    return window.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    return document.documentElement.clientHeight;
  } else if (document.body && document.body.clientHeight) {
    return document.body.clientHeight;
  }
}

function getWindowWidth() {
  var myHeight = 0;
  if (typeof(window.innerWidth) == "number") {
    return window.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
  } else if (document.body && document.body.clientWidth) {
    return document.body.clientWidth;
  }
}

function setDims(xx,yy) {
  var changeMe = $(window.resize_item);
	 if (changeMe)
	 {	
		changeMe.height = yy;
		changeMe.width = xx;
	 }

}




function MM_reloadPage(init) 
{  //reloads the window if Nav4 resized
  if (init==true) 
  {
	  with (navigator) 
	  {
			if ((appName=="Netscape")&&(parseInt(appVersion)==4)) 
			{
				document.MM_pgW=innerWidth; 
				document.MM_pgH=innerHeight; 
				onresize=MM_reloadPage; 
			}
		}
	}
  	else if (innerWidth!=document.MM_pgW || 
				innerHeight!=document.MM_pgH )
	{ 
		location.reload();
	}
}

function validate( formName, validations )
{
	clean = true;
	first_error_found = false;
	var validation_list = $(validations).value.split(',');
	validation_list.each( function(id){ 
			var question = $(id);
			if (question)
			{
				if( question.value == 0  || question.value == '')
				{ 
					question.up('.entry').addClassName("entry_error");
					clean = false;
					
				}
				else
				{
					question.up('.entry').removeClassName("entry_error");
				}
			}
			else
			{
				alert(id);
			}
		});
	if (!clean) show_notifications ("Please fill in the fields highlighted in Red", "error");
	return clean;

}

function jqvalidate( formName, validations )
{
	clean = true;
	first_error_found = false;
	var validation_list = $('#'+validations).val().split(',');
	jQuery.each(validation_list, 
		function(){ 
			var question = $("#"+this);
			if (question)
			{
				if( question.val() == 0  || question.val() == '')
				{ 
					question.parent('.entry').addClass("entry_error");
					clean = false;
					
				}
				else
				{
					question.parent('.entry').removeClass("entry_error");
				}
			}
			else
			{
				alert(id);
			}
		});
	if (!clean) alert ("Please fill in the fields highlighted in Red");
	return clean;

}


function remove_item( update_area , object, id )
{
	if (confirm("Are you sure you want to remove this item?"))
	{
		new Ajax.Updater(	update_area, 
							'/'+object+'/remove/' +id,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: function(request){
									if ($('show_disabled') && $('show_disabled').value ==2   )
									{
										$(update_area).addClassName('enabled0');
									}	
									else
									{
										Effect.Puff(update_area);	
									}
								},
								parameters: "ajax=true"
							}
						);
		return false;
	}
	return false;
}

function enable_item( update_area , object, id )
{
		new Ajax.Updater(	update_area, 
							'/'+object+'/enable/'+id,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: $(update_area).removeClassName('enabled0'),
								parameters: "ajax=true"
							}
						);
}


function disable_items (item_list)
{
	items = item_list.split(",");
	if (items.length >0)
		items.each(function(item) { 
			if ($(item)){ 
				Element.hide(item); 

			}
		});
}

function enable_items (item_list)
{
	items = item_list.split(",");
	if (items.length >0)
		items.each(function(item) { 
			if ($(item)){ 
			Element.show(item);
			}
		});
}


function remote_request( update_area, action, id, form)
{
	form_parameters = "";

	var	domain = document.location.protocol +'//'+ document.location.host;
	
	if ($(form) && $(form).tagName=='FORM')
	{
		form_parameters = Form.serialize(form);
	}
	new Ajax.Updater(   update_area,
						domain+action+'/'+id,
						{
							asynchronous:false, 
							evalScripts:true,
							onComplete: function(request){Effect.Highlight(update_area)},	
							parameters: form_parameters + "&target_id=" +update_area + "&ajax=true"
						}
					);
}



function edit_item( edit_area, object, id )
{
	new Ajax.Updater(	edit_area,
						'/'+object+'/edit/'+id,
							{
								asynchronous:true, 
								evalScripts:true,
								onComplete: function (request){ 
									Effect.Highlight(edit_area)
								},
								parameters: "target_id=" +update_area + "&ajax=true"
							}
						);
	return true;
}

var Helpers = {
	disclose: function (event) {	
		var update_area = event.target.id.split("disclose_")[1];
		var index = update_area.substr(update_area.lastIndexOf('_')+1);
		var object = update_area.substr(0,update_area.lastIndexOf('_'));
		var	operation = object.substr(object.lastIndexOf('_')+1);
		var object = object.substr(0,object.lastIndexOf('_'));
		var id = event.target.id;
		
		if ($(update_area).visible())
		{
			Effect.BlindUp(update_area, {duration: 0.2});	
			event.target.src = '/images/skins/default/disclose_right.gif';
		}
		else
		{
			event.target.src = '/images/spinning-wait-icons/wait20trans.gif';
			new Ajax.Updater(   update_area,
						'/'+object+'/'+operation+"/"+index,
						{
							asynchronous:true, 
							evalScripts:true,
							onComplete: function(request){
								new Effect.BlindDown(update_area, {duration: 0.2});
								$(id).src = '/images/skins/default/disclose_down.gif';
							},	
							parameters: 'ajax=true'
						}
					);
		}

	},
	
	add: function (event) {
		var items = event.target.id.split("add_");
		update_area = items[1]+'add_'+items[2];
		var position = $('position_'+items[1]+'add_'+items[2]);
		
		var index = items[2];
		var object = items[1].substr(0,items[1].lastIndexOf("_"));
		var	operation = 'add';
		var id = event.target.id;
		
		new Ajax.Updater(   
			update_area,
				'/'+object+'/'+operation+"/"+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){},	
					parameters: 'position='+position.value+'&ajax=true',
					insertion: Insertion.Bottom
				}
		);
		position.value++;
	},
	
	change: function (event) {
		var value = event.target.value;
		if (event.target.type=="checkbox" || event.target.type =='radio')
		{
			if (!event.target.checked)
				value= 0;
		}
		var id = event.target.id
		var index = id.substr(id.lastIndexOf("_")+1);
		var items = event.target.name.split("[");
		var object = items[0];
		var	operation = 'save_item';
		var column = items[1].substr(0,items[1].lastIndexOf("]"));
		
		new Ajax.Request(   
				'/'+object+'/'+operation+'/'+index,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){},	
					parameters: 'ajax=true&'+object+'['+column+']='+value
				}
		);
	},
	
	request: function (event) {
		var id = event.target.id
		var items = event.target.id.split("-");
		var object = items[1];
		var	operation = items[2];
		var index_start = String(items[1]).length+String(items[2]).length+2;
		var remaining = event.target.id.substr(index_start).replace('-','/');
		new Ajax.Updater('flash_message',   
				'/'+object+'/'+operation+''+remaining,
				{
					asynchronous:true, 
					evalScripts:true,
					onComplete: function(request){
					},	
					parameters: 'ajax=true'
				}
		);
	}
		
}

function DisplayTeaser( infodiv, obj )
{
	
	//Position.absolutize(infodiv);
	
	//$('information_block').innerHTML = $(infodiv).innerHTML;
	$('information_block').style.left = '250px';
	$('information_block').style.top = Event.pointerY( obj );
	//Effect.BlindDown('information_block');
	//$('information_block').style.display="block";
	Element.toggle(infodiv);
}

function HideTeaser(infodiv)
{
	//Effect.BlindUp('information_block');
	//$('information_block').style.display="none";
	Element.toggle(infodiv);
}

function get_referral_id( object, activity, id)
{
	
}

function mark_check_box( mode, id )
{
	$$(id).each( 
		function(item){
			switch( mode )
			{
				case "checked":
					item.checked = true;
					break;
				case "unchecked":
					item.checked = false;
					break;
				case "swap":
					item.checked = !item.checked;
					break;
			}
		}
	);
}

function unselect( id )
{
	id = $(id);
	id.selectedIndex = 0;
}

function updating( message )
{
	if (!message) message = "Loading!";
	return '<table style="margin: 0 auto"><tr><td valign="top"><img src = "/images/spinning-wait-icons/roller.gif" style="height:20px"></td><td valign="top">'+message+'</td></tr></table>';
}
function getPageHeight() {
  var windowHeight
  if (self.innerHeight) {	// all except Explorer
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowHeight = document.body.clientHeight;
  }	
  return windowHeight
}

function getPageScroll() {
  var xScroll, yScroll;
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
    xScroll = self.pageXOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
    yScroll = document.documentElement.scrollTop;
    xScroll = document.documentElement.scrollLeft;
  } else if (document.body) {// all other Explorers
    yScroll = document.body.scrollTop;
    xScroll = document.body.scrollLeft;	
  }
  return new Array(xScroll,yScroll) 
}



function show_notifications( content, mode ) {
	mode = mode || 'info';
	jQuery('#notifications').append(content).addClass( mode + ' ui-corner-all').css('top',getPageScroll()[1] + (getPageHeight() / 3)).css('left',(jQuery(window).width() - jQuery('#notifications').width() -20) / 2).show();
}

function hide_notifications( ) {
	jQuery('#notifications').html('').removeClass('info').removeClass('success').removeClass('warning').removeClass('error').hide();
}

String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}


function sqlDate(date)
{
	var year = date.getFullYear();
	var month = String(date.getMonth()+1);
	var day = String(date.getDate());
	var current_date = year+"-"+month.lpad("0",2)+"-"+day.lpad("0",2);
	
	return current_date;
}

function checkDate(date){
	var id = this.id.split("-")[1]*1;	
	curDate = sqlDate(date);
	
	var active  = !unit_dates[id][sqlDate(date)];
	var ret_obj = {};
	
	ret_obj.selectable = active;
	var booked = new RegExp(/book|block|held/);
	var notInQuery = new RegExp(/not_in_query/);

	if (typeof(unit_dates[id][curDate])!="undefined")
	{
		if (booked.test(unit_dates[id][curDate].status))
			ret_obj.dateClass = 'unavailable';
		else
			ret_obj.dateClass = 'available';
			
		if(notInQuery.test(unit_dates[id][curDate].status))	
			ret_obj.dateClass += ' not_in_query';
	}
	else
	{
		ret_obj.dateClass = active?'available':'unavailable';	
	}
	/*if (!active)
	{
		ret_obj.content = "<span class='unavailable'>X</span>";
	}*/	
	return ret_obj;
}

function adminCheckDate(date){
	
	var item = unit_dates[sqlDate(date)];
	var ret_obj = {};
	if (item){
		ret_obj.dateClass = item.status;	
	}
		
	return ret_obj;
}


function checkRange(dates) {
	var id = this.id.split("-")[1]*1;	
	if (dates.length>1 && dates[0]!=dates[1])
	{
		min_stay = unit_mins[id][sqlDate(dates[0])].min_stay;
		var date = new Date(dates[0]);
		var date_end = dates[1];
		var num_days=0;
		while (date < date_end)
		{
			num_days++;
			if (unit_dates[id][sqlDate(date)])
			{
				alert("A date in your date range has already been booked, \r\n Please reselect");
				dates[1] = date[0];//date.setDate(date.getDate()-1);;
				return;	
			}
			date.setDate(date.getDate()+1);
		}
		
		if (num_days < min_stay)
		{
			alert("You must select "+(min_stay+1)+" or more nights");
			dates[1] = date[0];
			return;	
		}	
		
		jQuery('.Book').show();
		return;
	}	
	jQuery('.Book').hide();
}

function getHoldDates( res )
{
	var startDate = null, endDate = null;
	for( d in unit_dates)
	{
		if(unit_dates[d].hold_id== res.hold_id)
		{
			if (!startDate)
				startDate = d;
			endDate = d;			
		}
	}
	starts = new Date(startDate.replace(/-/g,"/"));
	starts.setDate(starts.getDate());
	ends = new Date(endDate.replace(/-/g,"/"));
	ends.setDate(ends.getDate());
	return {starts: starts, ends: ends};
}

function adminCheckRange(dates) {
	var date = new Date(dates[0]);
	
	// Check to see if this date is a reservation
	var reservation = unit_dates[sqlDate(date)];
	if (reservation && reservation.reservation_id >0)
	{
		// If it is a reservation go get the reservation from the server and display in in the Overview Box....
		jQuery.ajax({
				url: '/reservations/overview/'+reservation.reservation_id,
				success: function(html){
					jQuery('#overview_box').html(html);
					jQuery('#overview_box').dialog('open').dialog('option','width','600');
				}
			});
	}
	else
	{
		var showDates;
		if (reservation && reservation.hold_id > 0)
		{
			showDates=getHoldDates(reservation);
		}
		else
		{
			showDates={starts: date, ends: date};
		}
		var checkInDate = (showDates.starts.getMonth()+1)+"/"+(showDates.starts.getDate())+"/"+showDates.starts.getFullYear();
		var checkOutDate = (showDates.ends.getMonth()+1)+"/"+(showDates.ends.getDate())+"/"+showDates.ends.getFullYear();
		jQuery('#dialog_box').dialog('open');
		jQuery('#startDate').val(checkInDate);
		jQuery('#endDate').val(checkOutDate);	
		jQuery('#dateRange').val(jQuery('#startDate').val()+"-"+jQuery('#endDate').val());	
		if (reservation ){
			jQuery('#unit_dates_note_').val(reservation.note);
			jQuery('#unit_dates_expires_at_').val(reservation.expires_at);
			jQuery('#unit_dates_status_').val(reservation.status);
		}
		else
		{
			jQuery('#unit_dates_note_').val("");
			jQuery('#unit_dates_expires_at_').val("");
			
		}
	}


		
}	

function adjustDates(dates)
{
	jQuery('.datepick-today').parent().addClass("datepick-outline");
}
