/* ************************************************************

	Script		: Page Loader
	Version		: 1.2
	Authors		: Samuel Birch
	Desc		: load pages via AJAX with mootools 1.2,
				  implements digitaralds HistoryManager,
				  which has been upgraded to moo 1.2 by anobii
	Licence		: Open Source MIT Licence

	* http://primel.net *
	*               2009-02-10                *

	
************************************************************ */

var pageLoader = new Class({

	Implements: [Options, Events],

	options: {
		links: 		'.loadMe',
		loadInTo: 	'content',
		loadFrom: 	'content',
		onStart: 	$empty,
		onComplete: $empty
    },

	initialize: function(firstPage, loadFirst) {
	
		this.HStarted = false;

		this.historyKey = '';
		this.history = HistoryManager.register(
			this.historyKey,
			[firstPage],
			function(values) {
				if (!this.HStarted && values[0] == "/") return;
				this.to(values[0]);
			}.bind(this),
			function(values) {
				return [this.historyKey, values[0]].join('');
			}.bind(this),
			this.historyKey + '(.+)'
		);

		this.rewrite();

	},

	rewrite: function() {
		// console.log('rewrite init');
		var url = window.location;
		var prot = window.location.protocol;
		var host = window.location.host;
		var path = window.location.pathname;
		// console.log( url );
		// console.log( prot );
 		if( location.href.indexOf("#") == -1 ) {
			var _href = url;
			var _val = path;
			// console.log(_val);
			if(path != '/') location = prot+'//'+host+'/#'+path;
		}
	},

	setpagetitle: function( title ) {
		// console.log( title );
		mytitle = title + ' : PRIMEL interaktiv - new media in style';
		document.title = mytitle;
	},

	to: function(page) {
		if (page === undefined || page === null /*|| dCond*/) { this.history.setValue(0, this.page); return; }

		page = page.replace(/^http:\/\/[^\/]+/, '');
		this.page = page;
		// startpage
		if( page == '/' ){
			//location.reload();
			location.href = '';
		}

		var req = new Request({
			url:page,
			onRequest:	function(el) {

								$('content').set('tween', {duration: '256'});
								$('content').tween('opacity', 0);
								// delay the layout functions a little
								(function(){ 
									// url contains projects
									if( page.toLowerCase().contains('projekte') ) {
										document.getElement('body').set('id','projects');
									}
									// url contains agency
									else if( page.toLowerCase().contains('agentur') ) {
										document.getElement('body').set('id','agency');
									}
									// other pages
									else {
										document.getElement('body').set('id','index');
									}
								}).delay(256);
			},
			onComplete: function(result) {

								myresult = result;
								this.setContent(myresult);
								// explicitly wait some time for stupid ie
 								(function(){ 
									//$('content').fade('in');
											// local links have to be inserted inthe BE manually!
											// $$(this.links).removeEvent('click', function(e) { e.stop(); myPageLoader.to(this.href); });				// if(DEBUG==1)console.log("removeEvent complete." );
											// $$(this.links).addEvent('click', function(e) { e.stop(); myPageLoader.to(this.href); });				// if(DEBUG==1)console.log("addEvent complete." );
											
									$('content').set('tween', {duration: '512'});
									$('content').tween('opacity', 1);
								}).delay(512);
			}.bind(this),
			autoCancel: true
		}).get(page,{'type':'0','rand':$random(0, 4096)});
		
		this.history.setValue(0, this.page);
	},

	setContent: function(reqResponse){

 		var tempContent = $(this.options.loadInTo).set({ id:'tempContent' });
		var temp = new Element('div').set({ id:'temp', display:'none' }).injectInside(document.body);
		temp.set({html:reqResponse});
		var newEl = $('temp').getElement('#'+this.options.loadFrom);
		newEl.replaces(tempContent);
		newEl.set({ id:this.options.loadInTo });

		var getFirstElClass = $(this.options.loadInTo).getFirst().get('class');
		if( getFirstElClass == 'hline' ) { 
			if ( $('startpage') != null )  $('startpage').destroy(); 
		}

		var scroller = new Fx.Scroll(document.body);
		if ( $('totop') != null ) {
			$('totop').addEvent('click', function(e){
				e.stop();
				scroller.toTop();
			}.bind(this));
		}

		// no realurl
		if( location.href.toLowerCase().contains('scrollto') ) {

			var link = location.href;
			var parameters = false;
			if(link.contains('?')){
				query = link.split('?')[1];
				if(query != ""){
					var parameters = new Hash();
					params = query.split('&');
					params.each(function(param){
						param = param.split('=');
						parameters.set(param[0],param[1]);
					});
				}
			}
			// console.log("hash.get('scrollto') :"+parameters.get('tx_prmtagmenu_pi1%5Bscrollto%5D') );
			var myFx = new Fx.Scroll(document.body).toElement( parameters.get('tx_prmtagmenu_pi1%5Bscrollto%5D') );

		} else if( location.href.toLowerCase().contains('scroll/') ) {
			var link = location.href;
			query = link.split('scroll/')[1];
			str = query.toString();
			str = str.substring(0, str.length-1);
			
			// console.log("hash.get('scrollto') :"+parameters.get('tx_prmtagmenu_pi1%5Bscrollto%5D') );
			var myFx = new Fx.Scroll(document.body).toElement( str );
		}



		if( $('team') ) {

			$$('#team').addEvents({
				mouseenter: function(){
					$$('#team .inactive').set('opacity', 0.5);
				},
				mouseleave: function(){
					$$('#team .inactive').set('opacity', 1);
				}
			});
			$$('#team img').addEvents({
				mouseenter: function(){
					this.set('class', 'active')
					this.set('opacity', 1);
				},
				mouseleave: function(){
					this.set('class', 'inactive')
					this.set('opacity', 0.5);
				}
			});

		}

		temp.destroy();

	}

});






window.addEvent('domready', function(){

	if( Browser.Engine.trident4!=true ) {
		HistoryManager.initialize();

//		var firstPage = '/index.php?id=1';
		var firstPage = '/';
//		var firstPage = '';
//		var firstPage;

		var myPageLoader = new pageLoader(firstPage);
		
		var projectContainer;

		$$(myPageLoader.options.links).addEvent('click', function(e) {
			e.stop();
			myPageLoader.setpagetitle(this.get('alt'));
			myPageLoader.to(this.href);
		});
		
		HistoryManager.start();
		myPageLoader.HStarted = true;
	}
	
});
