(function($) {
$.fn.siteControl = function( options ){
	var opts = $.extend({}, $.fn.siteControl.defaults, options);
	$.siteController = this;
	this.loading =  false;
	this.previous = null;
	this.defaults = {
		iconContainer	: 'icoBouncner', // this is the DOM element that holds the UL/LI containing the icons
		contentContainer: 'pagecontent',
		bounceOnce		: false,  // if false the icon will bounce repeatedly while the content is loading/ being fetched
		options			: { up	: 75, down	: 250 },
		content			: false,
		errorMess		: '<div class="error"><p>De pagina kan niet worden geladen, excusses voor het ongemak.</p></div>'
	}
	var idMarker 		= '#';
	this.screen			= $( idMarker.concat( this.defaults.contentContainer ) );
	this.screenHolder	= $( this.screen ).parent();
	this.contentId		= this.defaults.content;
	this.formValidators = {};

// initialize
	this.initialize = function() {
		if( $( "li .active" ).length >= 1 ) {
			this.active = $( "li .active" );
			this.active.id = this.active[0].id;
			this.previous = this.active; //load the previous with the start active one on first page load
		}
		this.loading = this.loader();
	}
// end initialize		

	this.showError = function(){
		var Error = $( '#overlay' )
		Error.empty().append('De pagina kon niet worden geladen').addClass( 'error' ).fadeTo( 150 , 80 , function(){
			});
	}
		

	this.openExternal = function ( source ){
		if( window.open( source , 'new' , '_blank' ) ){
			return true;
		} else {
			return false;
		}
	}
	
	this.loader = function () {
		$.siteController.active.id = $.siteController.active[0].id;
		$.siteController.active.title = $.siteController.active[0].title;
		var request = $.siteController.active.id;
		if( $.siteController.contentId ){
			request = $.siteController.contentId;
		}
		if( $.siteController.getContent( request ) ){;
			return !($.siteController.defaults.bounceOnce);
		}
		else {
			return false;
		}
	}
	
	this.getContent = function ( request ){
		//emulate loading script this temporarily replaces the actual ajax call;
		$.siteController.screen.fadeOut( 20 ).empty();
		$.siteController.resetUI();
		$.siteController.bounceMe();
		$.siteController.active.addClass( 'loading' );
		$.siteController.screenHolder.addClass( 'loading' );
		$.ajax({
			url		: request,
			type	: $.siteController.requestype || 'GET',
			dataType : 'json',
			data	: $.siteController.data || null,
			success	: function( response , error , success ) {
						try{
							if( response ) {
								returned = response;
								$.siteController.previous = $.siteController.active;
								$.siteController.screenHolder.removeClass( 'loading' );
								
								// append the new content to screen
								for( Obj in returned[ 'content' ] ) {
									var contentObj = returned[ Obj ];
									for( domObj in contentObj ) {
										$.siteController.screen.append( contentObj[domObj] ,
																{ className : domObj }
															);
									}
								}
								// check the content for links and attach the listener
								$.siteController.bindScreenlistener();
								
								// select the form(s) and initialise validators;
								var Forms = $( 'form' , $.siteController.screen );
								$.siteController.initiateFormVal( Forms );
								$.siteController.setActive();
								$.siteController.loading = false;							
								$.siteController.screen.fadeIn( 100 );
								return true;
								
							} else {
								$.siteController.handleLoadError( 'no data returned' , response );
								return false;
							}
						}
						catch( error ){
						 	$.siteController.handleLoadError( error, response );
								return false;
						}
					},
			error	:	function( response, error ) {
						 	$.siteController.handleLoadError( error, response );
							return false;
						}
		});
		return false;
		}
		
	this.scriptBuild =function( scriptObj ){
		for( scripting in scriptObj ) {
			$( 'body' ).append( '<script>' + scriptObj[ scripting ] + '</script>' );
		}
	}
	
	this.initiateFormVal = function ( Forms ){
		//step thru the found fields and create a validation for each one
		for( var frm=0 ; frm < Forms.length ; frm++ ){
			$.siteController.formValidators[ Forms[ frm ].id + 'Form' ] = $( '#' + Forms[ frm ].id );
			$.siteController.formValidators[ Forms[ frm ].id + 'Form' ].validation();
		}
	}

	this.handleLoadError = function( err, loaded ){
		if( console.log ) {
			console.log( 'error found' , err  );
		//	console.log( 'handleLoadError : ' , loaded  );
			$.siteController.showError();
		}		
		if( $.siteController.previous !== null ) {
		//	$.siteController.active = $( '#' + $.siteController.previous );
		//	$.siteController.setActive();
		}
	}
	
	this.showError = function(){
		$.siteController.screenHolder.removeClass( 'loading' );
		$.siteController.screen.append( $.siteController.defaults.errorMess );
		$.siteController.screen.fadeIn( 100 );
	}
	
	this.resetUI = function() {
	 	$( '.loading' ).removeClass( 'loading');
	 	$( '.active' ).removeClass( 'active');
		return true;
	}
		
	this.setActive = function() {
		$.siteController.active.removeClass( 'loading' );
		$.siteController.active.addClass( 'active' );
	}
	
	this.bounceMe = function( options ) {
				if (jQuery.browser.msie) {
					return false;
				}
				options = options || $.siteController.defaults.options;
				$.siteController.animating = true;
				$.siteController.active.parent().animate({
					marginTop	:'-=20'
					},
					options.up ).animate({
					marginTop	:'+=20'
					},
					options.down, function() {
						if( $.siteController.loading === true ){
							 bounceMe( {up : 250 , down : 150 } );
					} else {
						$.siteController.animating = false;
						}
				});
	}
	
	this.showTitle = function( title ) {
		$( '#title' ).fadeOut( 120 , function() {
											 $( this ).html( "<h2>" + title + "<\/h2>" ).fadeIn( 240 );
											});
	}

	this.showActive = function( title ) {
		$( '#activetitle' ).fadeOut( 120 , function() {
											 $( this ).html( "<h2>" + title + "<\/h2>" ).fadeIn( 240 );
											});
	}
		
/* interaction listners*/
	$(this).mouseover( function( e ) {
		$.siteController.animating = $.siteController.animating ? $.siteController.animating : false;
		if( $.siteController.animating === false && e.target.nodeName === 'A' ) {
			var title = e.target.title;
			$.siteController.showTitle( title );
		} else {
			$( '#activetitle' ).html( '' );
		}
	});

	
	$(this).bind( 'click' , function( e ) {
		e.preventDefault();
		$.siteController.animating = $.siteController.animating?$.siteController.animating:false;
		if( $.siteController.animating === false && e.target.nodeName === 'A' && $.siteController.loading === false ) {
			// if the active page is clicked ignore
			if( $.siteController.active === $( e.target ) ){
				return false;
			} else {
			// set the content to default to enable a return to the parent page
				$.siteController.contentId = $.siteController.defaults.content;
				$.siteController.active = $( e.target );
				$.siteController.loading = $.siteController.loader();
			}
		}
	});

	this.bindScreenlistener = function(){
		var screenLinks = $( 'a' , this.screen );
		for( var Link = 0 ; Link < screenLinks.length ; Link++ ){
			$( screenLinks[ Link ] ).bind( 'click' , function( e ){
				e.preventDefault();
				//analyse the link external od internal
				var regEx = /(http:\/\/|https:\/\/|ftp:\/\/|ftps:\/\/)/;
				var Href = $( e.target ).attr( 'href' );
				if( regEx.test( Href ) ){
					return $.siteController.openExternal( e.target.href );
				}
				else {
					// use a regular expressing to filter faulty content hrefs ( must follow page(alpha)/subcontent(numeric) ) if found the default content is loaded.
					var regEx = /([a-z]+){1}([\/]){1}([0-9])/;
					if( regEx.test( Href ) ){
						var activeParent = Href.split( '/' )|| Href;
						$.siteController.contentId = Href;
						$.siteController.active = $( '#' +  activeParent[0] );
						$.siteController.loading = $.siteController.loader();
					}
					else{
						return false;
					}
				}
			});
		}
		return true;
	}
	
	//start the controller
	this.initialize();
	};
})(jQuery);

