var gOriginalEditableContents = {};

$(document).ready(function() { 
	if (location.search.match(/edit/)) {
		// Dynamically modify the toolbar. It starts off static-css display:none'd and we
		// dynamically display:block it but hide it by setting its top to its negative height.
		$('#edit-page-toolbar').css('display', 'block');
		$('#edit-page-toolbar-header-margin').css('height',$('#edit-page-toolbar').height());
		$('.edit-page-editable-section').css({
			'background-color':'#eedfff',
			'-webkit-user-modify': 'read-write'
		}).each(function(){
			var inner = this.id.match(/-text$/) ? this.innerText : this.innerHTML;
			gOriginalEditableContents[this.id] = inner;
		});
		//console.log(gOriginalEditableContents);
	}
	
	$('#edit-page-save-changes-button').click(function(event) {
		var changes = {},
			hasChanges = false;
		$('.edit-page-editable-section').each(function(){
			var inner = this.id.match(/-text$/) ? this.innerText : this.innerHTML;
			if (gOriginalEditableContents[this.id] !== inner) {
				changes[this.id] = inner;
				hasChanges = true;
			}
		});
		if (hasChanges) {
			$.ajax({
				type:'POST',
				url:'/cgi-bin/WebObjects/CaravanApp.woa/-2000/wa/editPageSaveChanges',
				data:changes,
				success:function(msg){
					location = location.pathname;
				},
				error:function(msg){						
					alert('Saving Changes Failed\n\n'+msg);
				}
			});
		} else {
			alert('No changes have been made.');
			location = location.pathname;
		}
	});
	$('#edit-page-busy').ajaxStart(function(){
		$('#edit-page-busy').show();
	});
	$('#edit-page-busy').ajaxStop(function(){
		$('#edit-page-busy').hide();
	});
});

function editPage() {
	//alert('<' + $('#edit-page-toolbar-header-margin').height() + '>');
	if ($('#edit-page-toolbar-header-margin').height() != 0) {
		//	Turn off editing.
		$('#edit-page-toolbar').animate({
			top: '-'+$('#edit-page-toolbar').height(),
			'border-style': 'none'
		})
		$('#edit-page-toolbar-header-margin').animate({
			height: '0px'
		})
		$('.is-content-editable').attr('contentEditable','false');
	} else {
		//	Turn on editing.
		$('#edit-page-toolbar').animate({
			top: '0px',
			'border-style': 'solid'
		})
		$('#edit-page-toolbar-header-margin').animate({
			height: $('#edit-page-toolbar').height()
		})
		$('.is-content-editable').attr('contentEditable','true');
	}
}

//--

var imgMin = 0, imgStep = 25, imgMax = 100;

function setRating( form, name, value ) {
	form[name].value = value;
	showRating( form, name );
}

function hintRating( name, value ) {
	for( var i = imgMin ; i <= imgMax ; i += imgStep )
		document.images[name+"_"+i].src = "/images/s9/star" + (i <= value ? "-" : "0.0") + ".png";
}

function showRating( form, name ) {
	var value = form[name].value;
	if ( value == '' ) value = -1;
	else value = parseInt(value);
	for( var i = imgMin ; i <= imgMax ; i += imgStep )
		document.images[name+"_"+i].src = "/images/s9/star" + (i <= value ? "1.0" : "0.0") + ".png";
}