var modules = $({});
modules.list = {};
tinyInitialized = false;
// Extending the function prototype to be able to bind data to an anonymous function
Function.prototype.data = function() {
	if ( arguments.length <= 0 ) return this;
	var oFunction = this;
	var aArguments = arguments;
	return function() {
		return oFunction.apply( aArguments );
	}
}

// Ie6 transparent png fix
if (navigator.appVersion.indexOf("MSIE")!=-1){
	var tempIeVersion=navigator.appVersion.split("MSIE");
	var ieVersion=parseFloat(tempIeVersion[1]);
}
if (ieVersion < 7){ 
	try{
		document.tags.img.behavior = 'url(/media/css/iepngfix.htc);';
	}
	catch(event){
	}
}

function Module_Login(){
	this.init = function(){
		alert( 'init' );
	}
}

var oInstances = {};

/**
 * Ajax wrapper, to do it the way we want!
 */
function Ajax(){
	this.request = function( sRequest, oParams, oCallback ){
		oParams[ 'vessie-ajax-html' ]	= sRequest;
		var sModule 	= sRequest.split( '.' ).shift();
		var sFunction	= sRequest.split( '.' ).pop();
		$.post( '/'+sModule + '-' + sFunction + '.html', oParams, function( sResponse ){
			oCallback( sResponse );
		});
	}
	
	this.json = function( sRequest, oParams, oCallback ){
		oParams[ 'vessie-ajax-json' ]	= sRequest;
		var sModule 	= sRequest.split( '.' ).shift();
		var sFunction	= sRequest.split( '.' ).pop();
		$.post( '/'+sModule + '-' + sFunction + '.html', oParams, function( sResponse ){
			oCallback( sResponse );
		});
	}
	
	this.parseResponse = function( sResponse ){
		return eval( "(" + sResponse + ")" );
	}

}
/**
 * Form ajax poster
 */
function Form(){
	this.submit = function( el ){
		var oParams = {};

		$( el ).find( 'input,select,textarea' ).each( function(){
			var id;
			if( $( this ).attr( 'id' ) ){ id = $( this ).attr( 'id' ); }
			else{ id = $( this ).attr( 'name' ); }
			if( $( this ).attr( 'type' ) == 'checkbox' ){
				if( $( this ).attr( 'checked' ) )oParams[ id ] = $( this ).attr( 'value' );
				else oParams[ id ] = '';
			}
			else{
				oParams[ id ] = $( this ).attr( 'value' );
			}
			if( oParams[ id ] == undefined )oParams[ id ] = '';
			oParams[ 'vessie-ajax-html' ] = 'yes';
		});
		$.post( $( el ).attr( 'action' ), oParams, function( sResponse ){
			$( el ).replaceWith( $( sResponse ) );
			$( document ).trigger( 'dom_ready' );
		});
	}	
}

function Dialog( nr ){
	var id = nr;
	var blocking = false;
	var blockingDialog;
	
	addEvents();
	
	function addEvents(){
		$( document ).bind( 'close_blocking_dialog', {},unlockWindow );
	}
	
	function unlockWindow(){
		if( blockingDialog ){
			blocking = false;
			blockingDialog.remove();
			blockingDialog = undefined;
		}
	}
	
	this.blocking = function( dialog, options ){
	
		if( blocking )return false;
		if( options == undefined )options = {};
		blocking = true;
		
		var scripts = dialog.find( 'script' );
		var wrapper = $( '<div class="dialogWrapper"></div>' );
		dialog.find( 'script' ).remove();
		wrapper.append( dialog );
		$( 'body' ).append( wrapper );
		$( 'body' ).append( scripts );

		options.width = 'auto';
		options.height = 'auto';
		options.modal	= true;
		options.zIndex = 99969;
		options.resizable = ' ';
		options.draggable = false;
		options.close = unlockWindow;
		
		
		blockingDialog = wrapper.dialog( options );
		
		$( document ).trigger( 'dom_ready' );
	}
	this.floating = function(){
		if( blocking )return false;
	}
	this.alert = function(){
		if( blocking )return false;
	}
	this.choose = function(){
		if( blocking )return false;
	}
}
var dialog = new Dialog( '1' );
var form = new Form();
var ajax = new Ajax();

// We use our own dom_ready event to bind to, we trigger this event on dom ready but also after stuff has been 
// Added to the dom using javascript!
$( document ).ready( function(){ 
	$( document ).trigger( 'dom_ready' ); 
});

$( document ).bind( 'dom_ready', function(){
	// We traverse the dom and if an element matches the right class or type bind the behaviour.
	// This is a lot faster the doing multiple jquery selectors!
	jQuery().find( '*' ).each( function(){
		function isApplied( el, className ){
			var el = $(el);
			var rel = el.attr( 'rel' );
			if( rel ){
				var rels = rel.split( ' ' );
				for( var i = 0; i < rels.length; i++ ){
					if( rels[ i ] == className )return true;
				}
				
				el.attr( {'rel':rel + ' ' + className} );
				return false;
			}
			el.attr( {'rel':className} );
			return false;
		}
		
		if( this.className != undefined ){
			var classes = this.className.split( ' ' );
			for( var i =0; i < classes.length; i++ ){
				switch( classes[ i ] ){
					case 'Wysiwyg':
						if( !isApplied( this, 'Wysiwyg' ) ){
							// We bid the this to the timout function with data!
							// If we do not use a timeout it breaks pages that have a Wysiwyg editor in the normal body.
							// It seems even 1 ms works fine...
							setTimeout( function(){
								if( !tinyInitialized ){
									tinyInitialized = true;
									tinyMCE.init({
										// General options
										mode : "exact",
										theme : "advanced",
										relative_urls : 0,
										plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
									
										// Theme options
										theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
										theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
										theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
										theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
										theme_advanced_toolbar_location : "top",
										theme_advanced_toolbar_align : "left",
										theme_advanced_statusbar_location : "bottom",
										theme_advanced_resizing : true
									});
								}
								tinyMCE.editors[ $( this ).attr( 'id' ) ] = undefined;
								tinyMCE.execCommand('mceAddControl', false, $( this ).attr( 'id' ) );							
							}.data( this ), 1 );
						}
					break;
					case 'PopUp':
						if( !isApplied( this, 'PopUp' ) ){
							// Opening links to modules inside jquery dialogs!
							$( this ).bind( 'click', {}, function(){
								var oParams = {};
								oParams[ 'vessie-ajax-html' ]   = 'yes';
								$.post( $( this ).attr( 'href' ), oParams, function( sResponse ){
									dialog.blocking( $( sResponse ), {} );
								});
								return false;	
							});
						}
					break;
					case 'Refresh':
						if( !isApplied( this, 'Refresh' ) ){
							// Opening links to modules inside jquery dialogs!
							$( this ).bind( 'click', {}, function(){
								var oParams = {};
								oParams[ 'vessie-ajax-html' ]   = 'yes';
								$.post( $( this ).attr( 'href' ), oParams, function( sResponse ){
									document.location = document.location;
								});
								return false;	
							});
						}
					break
					case 'AjaxForm':
						if( !isApplied( this, 'AjaxForm' ) ){
							// All forms are now submitted using ajax
							$( this ).bind( 'submit', {}, function(event){
								var test = this;
								// We need to wait a short time to let the WYSIWYG code catch up.
								setTimeout( function(){form.submit( test );},400 );
								event.preventDefault();
							});
						}
					break;
					case 'AjaxLink':
						if( !isApplied( this, 'AjaxLink' ) ){
							// All links are now opened using ajax
							$( this ).bind( 'click', {}, function( event ){
								oParams = {};
								oParams[ 'vessie-ajax-html' ] = 'yes';
								$.post( $( this ).attr( 'href' ), oParams, function( sResponse ){
									var oResponseObject =  ajax.parseResponse( sResponse );
									dialog.blocking( $( oResponseObject.string ) );
									var oResponse = $( '<div id="ajaxLinkResponder">'+ oResponseObject.string +'</div>' );
									var oScripts = oResponse.find( 'script' );
									oResponse.find( 'script' ).remove();
									$( 'body' ).append( oResponse );
									$( '#ajaxLinkResponder' ).append( oScripts );
									$( '#ajaxLinkResponder' ).remove();
								});
								return false;
							});
						}
					break;
					case 'ForwardLink':
						if( !isApplied( this, 'ForwardLink' ) ){
							// Automatic link forwarding. If a link is provided with this class
							$( this ).each( function( data ){
								var url = $( this ).attr( 'href' );
								var forwardTimeout = setTimeout( function( data ){
									document.location = url;
								}.data( url ) ,4500);
							});
						}
					break;
					case 'Confirm':
						if( !isApplied( this, 'Confirm' ) ){
							// We like the windows confirm boxes on deletes!
							$( this ).bind( 'click',{}, function( event ) {
								if (confirm("Are you sure?"))return true ;
								else return false ;
							});
						}
					break;
					case 'ExternalLink':
						if( !isApplied( this, 'ExternalLink' ) ){
							// Opening links in a new window complying to the xhtml strict standards
				        	$( this ).attr( {target : "_blank"} );
						}
					break;
					default:
					break;
				}
			}
		}
	}); 
});
