var DEBUG = true;

$(document).ready( function(){

	// set all forms to submit on enter
	$("form").keypress( function(e){
		if( e.keyCode == 13 ) this.submit();
	});

	// set up admin

	// setup AdminBlock to toggle visibility
	$("#CopyrightLine").hover(
		function(){
			$(".AdminBlock").toggle();
		},
		function(){}
	);

	// set error list to toggle and indicator to change
	$("span.Indicator a").click( function(){
		if( $(this).html() == '[+]' ){
			$(this).html('[-]');
		}else{
			$(this).html('[+]');
		}
		$("#Footer .GXErrors .List").toggle();
	});

	// set username to have help text
	if( $("#LoginForm input[ @type = 'text' ]").val() == '' ){
		$("#LoginForm input[ @type = 'text' ]").val('Username');
	}

	// set the username help text behavior
	$("#LoginForm input[ @type = 'text' ]").focus( function(){
		if( $(this).val() == 'Username' ){
			$(this).val('');
		}
	});
	$("#LoginForm input[ @type = 'text' ]").blur( function(){
		if( $(this).val() == '' ){
			$(this).val('Username');
		}
	});

	// enable nav
	$('#Nav dd a').hover(
		function(){
			var item = $(this).parent().attr('class');
			// only turn it off if it's not the page we're on
			if( $('body').attr('id') != item ){
				$(this).parent().addClass( item + 'Over' );
			}
		},
		function(){
			// grab the first class
			var item = $(this).parent().attr('class').split(' ')[0];
			// only turn it off if it's not the page we're on
			if( $('body').attr('id') != item ){
				$(this).parent().removeClass( item + 'Over' );
			}
		}
	);

	// enable edit links
	if( GXPage.User.length > 0 ){
		$('div[ @class *= "GXEditorContent" ], div[ @class *= "GXEditorPicture" ]').gx();
	}

	/*
	// remove the flash object and set the contents back to "listen"
	$('a.mp3stream').bind( 'reset', function(){
		$(this).empty().html('Listen');
		return false;
	});
	// load event, which does the actual creation of the flash object
	$('a.mp3stream').bind( 'load', function(){
		var url = $(this).attr('href');
		var me = this;
		$.get( GXPage.Self + '/Catalog/Stream?url=' + url, function(rxml){
			var mp3 = $('url',rxml).text();
			$(me).jmp3({
				playerpath: GXPage.Scripts,
				filepath: mp3,
				showfilename: 'false',
				backcolor: '6a7e27',
				forecolor: 'e4eccb',
				showdownload: 'false',
				autoplay: 'true'
			});
		});
		return false;
	});
	// album page streaming links ... only use the ones which end in .m3u
	$('#Catalog a[ @href $= ".m3u" ]').click( function(){
		// set all preview items back to the "listen" link
		$('a.mp3stream').each( function(){
			$(this).trigger('reset');
		});
		// load the player on this item only
		$(this).trigger('load');
		return false;
	});
	*/

});

/*
jQuery.GXEditor = function(elm,options){

	elm.debug();

	this.editme = elm;
	this.getme = function(){
		return this.editme;
	}

	this.page	= $('body').id();
	this.type	= this.getme().attr('class').replace(/GXEditor/,'');
	this.id		= this.getme().id();
	this.xpath	= this.getme().attr('alt');

	$.log( this.xpath);

	var self 	= this;

	this.defaults	= {
		page:	this.page,
		type:	this.getme().attr('class').replace(/GXEditor/,''),
		id:		this.getme().id(),
		xpath:	this.getme().attr('alt'),
		edit:	{
			url:	GXPage.Self + '?Page=CMS&Action=EditContent',
			params:	{
				source: this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		},
		save:	{
			url:	GXPage.Self + '?Page=CMS&Action=SaveContent',
			params:	{
				source: this.page,
				content: '',
				id:		this.id,
				xpath:	this.xpath
			}
		},
		refresh:	{
			url:	GXPage.Self + '?Page=CMS&Action=GetContent',
			params:	{
				source: this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		}
	}
	jQuery.extend(this.defaults,options);

	// build the controlbar
	this.control = function(mode){
		// create the bar if we can't find it
		if( !self.getme().prev().is('.GXEditor') ){
			self.bar = this.getme().before( '<label id="' + self.id + '_bar" class="GXEditor" for="' + self.xpath + '"></label>' ).prev();
		}
		switch(mode){
			case 'edit':
				self.bar.html(
					'[<a href="javascript:void(0);" class="GXEditButton">edit</a>]'
				);
				self.bar.find('a').click( this.edit );
				break;
			default:
				self.bar.html(
					'[<a href="javascript:void(0)">save</a>]'
					+ '[<a href="javascript:void(0)">cancel</a>]'
				);
				self.bar.find('a').contains('save').click( self.save );
				self.bar.find('a').contains('cancel').click( self.unedit );
		}
	}

	// save the content and send it back to the server
	// use "self" because this will be called as a callback
	this.save = function(){
		var params = self.defaults.save.params;
		params.content = tinyMCE.getContent(self.id+'_data');
		// request the saveurl, which saves the content and returns the saved content
		self.getme().load(
			self.saveurl,
			params,
			self.unedit
		);
	}

	// convert the element to an editable region
	// use "self" because this will be called as a callback
	this.edit = function(){
		// load the editable content
		self.getme().load( self.defaults.edit.url, self.defaults.edit.params, function(){
			// enable tinymce
			$('#' + self.id + '_data',self.getme()).tinymce();
			// update control actions
			self.control('save');
			return false;
		});
	}

	// return the element to its prior state
	// use "self" because this will be called as a callback
	this.unedit = function(str){
		// if we have a string, replace the block with it;
		// otherwise, get the content from the server
		if( str ){
			toggleTinyMCE(self.id + '_data');
			self.getme().empty();
			self.getme().html(str);
		}else{
			self.getme().load( self.unurl );
		}
		// reset the bar
		self.control('edit');
		return false;
	}

	// create the control bar
	this.control('edit')
}

jQuery.fn.GXEdit = function(options){
	new jQuery.GXEditor($(this),options);
}
*/

function editPicture( savePage, refElement, dim ){
	var pixBlock = document.createElement('div');
	pixBlock.setAttribute('id',refElement.id + '_editor');
	pixBlock.className = 'ImageList';
	// set the xpath to the Picture element in the source xml file for use in the updatePicture() function
	pixBlock.xpath = escape(refElement.getAttribute('xpath'));
	pixBlock.style.cssText = 'position: absolute; top: ' + dim.top + 'px; left: ' + dim.left + 'px; width: ' + dim.width + 'px; height: ' + dim.height + 'px;';

	// add it to the block
	refElement.appendChild(pixBlock);

	// fill the div with pictures
	var url = '/?Page=CMS&Action=ShowImageList';
	var myAjax = new Ajax.Updater(
		{success: pixBlock},
		url,
		{method: "get", onFailure: reportError});
}

function updatePicture( obj ){
	var pixBlock = getParent(obj,null,'xpath');
	var pars;
	var xpath = 'Picture[' + escape(pixBlock.getAttribute('xpath')) + ']';

	$('_GXPictureXpath').value = xpath.escapeHTML();
	$('_GXPictureXpath').value = obj.getElementsByTagName('img').item(0).name;

	var url =	'/?Page=CMS&Action=UpdatePicture'
				+ '&SavePage=' + document.getElementsByTagName('body').item(0).id
				+ '&' + escape(xpath) + '=' + obj.getElementsByTagName('img').item(0).name;

	// send requested picture to gxpage
	var myAjax = new Ajax.Updater(
		{success: pixBlock},
		url,
		{method: "get", onFailure: reportError});
}




/*
 * GXEditor encapsulated object
 */
function gx(elm){

	// reference to this instance of gx
	var self = this;
	// reference the supplied element
	this.source = $(elm);

	// get the current page
	this.page = $('body').id();

	// store the xpath for the supplied element
	this.xpath = this.source.attr('alt');
	this.id = this.source.id();

	// create the defaults for this instance
	this.config = {
		page: this.page,
		edit: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'EditContent',
				source:	this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		},
		save: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'SaveContent',
				source:	this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		},
		refresh: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'GetContent',
				source:	this.page,
				xpath:	this.xpath
			}
		}
	}

	this.init = function(){
		this.source.before('<label rel="' + this.source.id() + '" class="GXEditor" for="' + this.xpath + '"></label>');
		this.bar = $('[@rel="' + this.source.id() + '"]');
		this.mode('enable');

		$.log(this.config.toSource());

		return false;
	}

	this.mode = function(mode){
		switch(mode){
			case 'enable':
				$.log('switching mode to ENABLE for ' + this.source.id());
				this.bar.html('[<a href="javascript:void(0);">edit</a>]');
				$('a',this.bar).click( this.edit );
				break;
			case 'edit':
				$.log('switching mode to EDIT for ' + this.source.id());
				this.bar.html(
					'[<a href="javascript:void(0);">save</a>]'
					+ '[<a href="javascript:void(0);">cancel</a>]');
				$('a:contains("save")',this.bar).click( self.save );
				$('a:contains("cancel")',this.bar).click( this.unedit );
				break;
			case 'save':
				$.log('switching mode to SAVE for ' + source.id());
				break;
			case 'cancel':
				$.log('switching mode to CANCEL for ' + source.id());
				break;
			default:
				$.log('switching mode to DEFAULT for ' + source.id());
		}
	}

	this.edit = function(){
		$(this).load( self.config['edit'].url, self.config['edit'].params, function(){
			$(this).css('border','2px purple dashed;');
			return false;
		});
		return false;
	}

	this.init();

}

function foo(elm){

	// reference to this instance of ooptest for use in anonymous functions
	var self = this;

	// reference to the supplied element
	this.source = $(elm);
	this.xpath = this.source.attr('alt');
	this.id = this.source.attr('id');

	// get the current page
	this.page = $('body').attr('id');

	// create the defaults for this instance
	this.config = {
		page: this.page,
		edit: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'EditContent',
				source:	this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		},
		save: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'SaveContent',
				source:	this.page,
				id:		this.id,
				xpath:	this.xpath
			}
		},
		refresh: {
			url: GXPage.Self,
			params: {
				Page:	'CMS',
				Action:	'GetContent',
				source:	this.page,
				xpath:	this.xpath
			}
		}
	}

	// mode switch
	this.mode = function(what){
		$.log('...about to ' + what + ' ' + this.id);
		switch(what){
			case 'enable':
				this.enable()
				break;
			case 'edit':
				this.edit();
				break;
			case 'save':
				this.save();
				break;
			default:
				this.deactivate();
		}
	}

	// enable the control bar
	this.enable = function(){
		$.log('switching mode to ENABLE for ' + this.source.attr('id'));
		this.bar.html('[<a href="javascript:void(0);">edit</a>]');
		$('a',this.bar).click( this.edit );
	}

	// edit ... pull content from server, then call tinymce
	this.edit = function(){
		$.log('EDIT for ' + this.source.attr('id'));
		this.bar.html(
			'[<a href="javascript:void(0);">save</a>]'
			+ '[<a href="javascript:void(0);">cancel</a>]');
		$('a:contains("save")',this.bar).click( this.save );
		$('a:contains("cancel")',this.bar).click( this.unedit );

		// get the content
		$(this).load( this.config['edit'].url, this.config['edit'].params, this.runtiny );
		return false;
	}

	this.runtiny = function(){
		$( '#' + this.id + '_data', self.source ).css('border','5px orange solid');
		return false;
	}

	// create the control bar as the sibling previous to this.source
	this.source.before('<label rel="' + this.source.attr('id') + '" class="GXEditor" for="' + this.xpath + '"></label>');
	this.bar = $('[@rel="' + this.source.attr('id') + '"]');
	this.mode('enable');

	// enable the control bar
	this.mode('enable');

};


			/*
			// enable tinymce
			//$('#' + this.id + '_data').tinymce();
			// update control actions
			//self.control('save');
			*/

$.fn.gx = function(options){
	return this.each( function(){
		new foo(this);
	});
}
