var Site = new Class({
	initialize: function(){
		
		//Referrer
		if(!Cookie.read('referrer')){
			var referrer = document.referrer;
			var url = new URI(referrer);
			if(url.get('host').contains('.google.') && url.getData('q')) referrer = url.get('host')+' request: '+url.getData('q');
			else if(url.get('host').contains('.yahoo.') && url.getData('p')) referrer = url.get('host')+' request: '+url.getData('p');
			else if(url.get('host').contains('.bing.') && url.getData('q')) referrer = url.get('host')+' request: '+url.getData('q');
			else if(url.get('host').contains('.seznam.') && url.getData('q')) referrer = url.get('host')+' request: '+url.getData('q');
			
			Cookie.write('referrer', referrer, {path: '/'});
		}
	
		this.loadMap();
		this.openProductsMenu();
		this.setLanguagesMenu();
		this.setSchoolMenu();
		this.cleanSchoolElements();
		this.fixDestinationsBox();
		this.menuFollower = new MenuFollower();
		
		if ($('form')) {
			formcheck = new FormCheck('form');
			new Formular({server: 'ldt'});
		}
		
		if($('quickquote') != null)
			qq = new QuickQuote({
				ID:$('schoolID').value,
				CID:$('schoolCID').value,
				year:$('usedyear').value,
				lang:$('lang').value,
				sectionId:$('ID_section').value,
				'server' : 'ldt'
			});
		
		if($$('#school-finder a').length) {
			// init the finder
			finder = new Finder({
				selector : '#school-finder a',
				lang : 'ldde',
				year : '2012',
				stepsParams : {	
					1 : 'orderby=desc&m=Finder&lstonly=1&valid=1'
				},
				server_ID : '5',
				server : 'ldt',
				autostart : false,
				schoolDetail : false,
				language : {
					schoolfinder	: 'SchoolFinder',
					schooldetail 	: 'Einzelheiten der Schule',
					select			: 'Anzeige...',
					change			: 'Ändern...',
					quickquote		: 'Online Offerte',
					steps : [
						'Sprache',
						'Länder',
						'Städte',
						'Schulen',
						'Details'
					]
				}
			});
		}
		
		//Jobs / Specialoffers / Links slider
		if ($$('.MGroupContent').length > 0) this.loadSlider();
		
		//assign squeezebox
		SqueezeBox.assign($$('a.squeezebox'), {
			parse: 'rev'
		});
		
		if($('search')){
		//Search Form
			$('search').addEvent('submit', function(e){
				e.preventDefault();
				SqueezeBox.open('/data/search/search.htm', {handler: 'iframe'});
			});
		
			$('searchinput').addEvent('focus', function(){
					this.value = '';
			});
		}
		
		//Galleries
		if($$('.gallerybox').length>0) gall = new Gallery({opener: '.gallerybox .gallery', unlinkedOpener : true});
		
		//Feedback page
		if($('feedback')) new FeedBack();
		
		//tabs multi years
		if($$('.years-toggle').length) new Price();
		
	},
	
	openProductsMenu : function(){
		if($$('.sprachreisen, .studynwork, .beruf, .familie').length) $$('.menucat ul').addClass('opened');
	},
	
	setLanguagesMenu : function(){
		$$('.box-destinations > ul > li > a').addEvent('click', function(e){
			//if accordion is open => go to page
			if(!this.getNext().getHeight()) new Event(e).stop();
		});
		new Fx.Accordion($$('.box-destinations > ul > li > a'), $$('.box-destinations li div'), {
			display: -1,
			alwaysHide: true
		});
	},
	
	loadMap : function(){
		if(typeof googlePoints != 'undefined') {
			new Map({points : googlePoints});
		}
	},
	
	setSchoolMenu : function(){
		if($('menu-school') != null) {
			var opened = false;
			var tabac = false;
			$('menu-school').getChildren().each(function(tab){
				var box = $(tab.id.split('_')[1]);
				opened = !opened ? box : opened;
				tabac = !tabac ? tab : tabac;
				tab.addEvent('click', function(e){
					new Event(e).stop();
					opened.addClass('hidden');
					opened = box.removeClass('hidden');
					tabac.removeClass('s');
					tabac = tab.addClass('s');
				});
			});
		}
	},
	
	cleanSchoolElements : function(){
		if($('menu-school')) {
			//einem blick, keypoints, accreditations
			$$('.schoolglance, .box-keypoints, #accreditations').each(function(element){
				if(element.getChildren().length <= 1) element.destroy();
			});
			
			if($('wifidisabled').getChildren().length < 1) $('wifidisabled').destroy();
			
			//remove identical unterkunfte
			if ($('accommodations-table')) {
				$('accommodations-table').getElements('td.label').each(function(acc){
					//compare acc content with accommodation-xx
					$$('span[id^=accommodation-]').each(function(ref){
						if(ref.get('html').trim() == acc.get('html').trim()) {
							acc.getParent().destroy();
						}
					});
				});
			}
						
			//remove empty options
			$$('.options table').each(function(table){
				if(!table.getElements('td').length) table.destroy();
			});
			
			//clear every two courses
			$$('#prices .boxprices').each(function(box, i){
				if(i%2 == 0) box.addClass('clear');
			});
		}
	},
	
	loadSlider : function() {
		$$('.MGroupContent').setStyle('display', 'block');
		var itemID = $get('#', document.URL );
		var selected = $('boxbody' + itemID);
		var current = (selected) ? selected : false;
	
		$$('div.MGroup').each(function(div){
			var block = div.getElement('a').getNext();
			var fx = new Fx.Slide(block);
			if (block != current) fx.hide();
			if ($(itemID) == div || (div.hasClass('open'))) fx.toggle();
			 
			div.getElement('a').addEvent('click', function(){
				fx.toggle();
			});
			
		});
	},
	
	fixDestinationsBox : function(){
		$$('.box-dest').each(function(box, i){
			if(i%2) box.addClass('last');
		});
	}
});

/**
 * Esl user tracking
 */
var cookieSource = '';
var cookieAdword = '';
var cookieTerm = '';
var cookieEslID = '';


/**
 * Create a cookie if not yet present
 * 
 * Requires mootools
 */
function __eslSetTrack() {
	var cookieTmp = __eslGetTag();
	
	// Test if we've been here before
	if(__eslGetTrack('tag_first') == false) { // Create
		var ef = Cookie.write('tag_first', cookieTmp, {duration: 60});
	}
	
	if(__eslGetTrack('tag_current') == false) { // Current one. duration 1
		// Write the current one
		var ec = Cookie.write('tag_current', cookieTmp, {duration: 1});
	}
	return false;
}

/**
 * Set tag fields in hidden forms if available
 */
function __eslSetForm() {
	if(document.getElementById('roi_first')) {
		document.getElementById('roi_first').value = __eslGetTrack('tag_first');
		document.getElementById('roi_current').value = __eslGetTrack('tag_current');
	}
}


/**
 * Get values of cookie, returned as an array
 */
function __eslGetTrack(sCookieName) {
	var eslCookie = Cookie.read(sCookieName);
	
	if(eslCookie ) {
		return eslCookie;
	}
	return false;
}

/**
 * Get the current campaign tag if it's available
 */
function __eslGetTag() {
	
	__eslReadJA();
	
	var currentTime = new Date();
	var month 		= currentTime.getMonth() + 1 //0=jan, 11=dec;
	if(month < 10) 	month = "0" + month;
	var day 		= currentTime.getDate();
	if(day < 10) 	day = "0" + day;
	var year 		= currentTime.getFullYear();
	var hours		= currentTime.getHours();
	var minutes 	= currentTime.getMinutes();
	if(minutes < 10) minutes = "0" + minutes;
	
	var cookieTime = year + '-' + month + '-' + day + ';' + hours + ':' + minutes;
	
	
	// Find idEsl
	var url = location.href;
	if(url.indexOf('#') > 0) {
		url = url.split('#');
		params = url[1].split("&");
		for(var i = 0; i < params.length; i++) { // find idesl
			//alert('param: ' + params[i]);
			if(params[i].indexOf('desl') > 0) {
				cookieEslID = params[i].replace('idesl=', '');
			}
		}
	}
	
	
	/*if(cookieEslID != '') {
		return cookieTime + ';' +cookieEslID;
	}*/
	
	return cookieTime + ';' + cookieSource + ';' + cookieAdword + ';' + cookieTerm + ';' + cookieEslID;
}

function __eslReadJA() {
	var jaCookie = Cookie.read('__utmz');
	var result='';
	
	if(jaCookie ) {
		var cookieSplit = jaCookie.split('|');
		
		for(var a = 0; a<cookieSplit.length; a++) {
			// Junk anything before the utm values
			var sTmp = cookieSplit[a];
			sTmp = sTmp.substr(sTmp.indexOf('utm'));
		
			var aTmp = sTmp.split('=');
		
			if(aTmp[0] == 'utmcsr') { //referrer
				cookieSource = aTmp[1];
			} else if(aTmp[0] == 'utmcmd') {
				cookieAdword = aTmp[1];
			} else if(aTmp[0] == 'utmctr') {
				cookieTerm = aTmp[1];
			} else if(aTmp[0] == 'utmesl') {
				cookieEslID = aTmp[1];
			}
		}	
	}
}

function __eslRoiInit() {
	__eslSetTrack();
	__eslSetForm();
	
	/* tag each external link */
	if(cookieEslID.length > 0) {
	 $$('a').each(function(link) {
	  if(link.hostname != window.location.host) {
	   link.href = link.href + '#idesl=' + cookieEslID;
	  }
	 });
	}
}

window.addEvent('domready', function(){
	var roiTimer = setTimeout('__eslRoiInit()', 400);
	new Site();
});

/* Remote Control */
window.addEvent('load', function(){ 
	if(!publish && document.location.href.contains('http://ldt.')){
		try {
			new Remote({'lang' : ['ldde'], 'server': 'ldt', 'default_lang': 'ldde'});
		}
		catch (e) {}
	}
	 
});
















