
function init(){
	menu.init();
	ajaxSearch.init();
	initClickableBoxes();
	initTripHistory();
	initClickableTables();
	truncateAcco();
	// Link header image to home
	Event.observe($('header'), 'click', function(){
		window.location = '/';
	});
}

var ajaxSearch = {
	init: function(){
		if(!$('quickSearch'))
			return;
		
		var ajaxForm = $('quickSearch');
		// Hide Area and City Selectboxes
		ajaxSearch.hideOptionals();
		
		//Or show them if there was a search on area or city
		area = getGetVars('area')
		if(area !=0 ){
			city = getGetVars('city')
			if(city != 0){
				ajaxSearch.setSelectBoxes(area, city);
			}
			else{
				ajaxSearch.setSelectBoxes(area);
			}
		}
		// Attach event handlers for 'clear form' link	
		Event.observe($('quickSearch').getElementsByTagName('A')[0], 'click', ajaxSearch.clearForm, false);
		
		// Register event handlers for select boxes
		var selects = $('quickSearch').getElementsByTagName('SELECT');
		for(i=0;i<selects.length;i++){
			if(selects[i].id == 'country' ||selects[i].id == 'area' )
				Event.observe(selects[i], 'change', ajaxSearch.addNext, false);
			Event.observe(selects[i], 'change', ajaxSearch.refreshResult, false);
		}
	},
	refreshResult: function(){
		var selects = $('quickSearch').getElementsByTagName('SELECT');
		var url = '?go=trip&action=checkresults&year=0';
		for(i=0;i<selects.length;i++) {
			var value = selects[i].value;
			if (selects[i].value == '') value = 0;
			url = url + '&' + selects[i].id + '=' + value;			
		}
	
		var nrTarget = $('resultsFound').getElementsByClassName('nr')[0];
		$('resultsFound').style.opacity = '.5';
		$('resultsFound').style.filter = 'alpha(opacity=50)';
			
		new Ajax.Request(url, { 
			onLoading : function(transport) {
				nrTarget.innerHTML = '<img src="/img/layout/loading.gif" />';
			},
			onSuccess: function(transport) {
				//replace loader with nr of available results
				$('resultsFound').style.opacity = '';
				$('resultsFound').style.filter = '';
				nrTarget.innerHTML = transport.responseText;
			},
			onFailure: function(transport) {
				alert ('ajax error')
			}
		});
	},
	setSelectBoxes: function(area, city){
//		if(city)
//			alert('AREA!');

	},
	addNext: function(e){
		var trigger = Event.element(e);
		var id = trigger.value;
		
		// Set value of next select to '0'
		trigger.next(1).value = '0';
		
		if(trigger.value == '0'){
			//Hide next select(s)
			trigger.next(0).style.display = 'none';
			trigger.next(1).style.display = 'none';
			if(trigger.next(2)){
				trigger.next(2).style.display = 'none';
				trigger.next(3).style.display = 'none';
				trigger.next(3).value = '0';
			}
			return;
		}
		// Determine selectbox type
		if (trigger.id == 'country'){
			// Hide cityselect if visible
			$('city').value = '0';
			$('city').style.display = 'none';
			$('city').previous().style.display = 'none';
			type = 'area';
		}
		else
			type = 'city';
		
		var selectboxUrl = '?go=trip&action=getselectbox&type=' + type + '&id=' + id ;
		
		// Update selectbox options and show
		new Ajax.Request(selectboxUrl, { 
			onComplete: function(transport) {
				options = transport.responseXML.getElementsByTagName('option');
				trigger.next(1).options.length = 0;
				for(i=0; i<options.length; i++){
					var opt = document.createElement('option');
					opt.innerHTML = options[i].firstChild.nodeValue;
					opt.value = options[i].attributes[0].nodeValue;
					trigger.next(1).appendChild(opt);
				}
			},
			onFailure: function(){
				alert('Er is iets misgegaan, probeer opnieuw.');
			}
		});
		
		trigger.next(0).style.display = 'block';
		trigger.next(1).style.display = 'block';	
	},
	hideOptionals: function(){		
		if ($('area').className == 'optional') {
			$('area').style.display = 'none';
       			$('area').previousSiblings()[0].style.display = 'none';
       		}
		if ($('city').className == 'optional') {
			$('city').style.display = 'none';
			$('city').previousSiblings()[0].style.display = 'none';
		}
	},
	clearForm: function(){
		//reset form
		selects = $('quickSearch').getElementsByTagName('SELECT');
		for(i=0;i<selects.length;i++)
			selects[i].value = '0';
		
		ajaxSearch.hideOptionals();
		ajaxSearch.refreshResult();
	}
}

var menu = {
	mouseover: false,
	currentUl: '',
	init: function() {
		// Attach event handler to all 'withSub' elements
		dropdowns = $('mainNav').select('.withSub');
		
		dropdowns.each(function(i, index){
			var el = dropdowns[index];
			// Attach events to both anchors and sublists
			Event.observe(el, 'mouseover', menu.handleEvent.bindAsEventListener(menu), false);
			Event.observe(el, 'mouseout', menu.handleEvent.bindAsEventListener(menu), false);
			Event.observe(el.next(), 'mouseover', menu.handleEvent.bindAsEventListener(menu), false);
			Event.observe(el.next(), 'mouseout', menu.handleEvent.bindAsEventListener(menu), false);
		})

  	},
	handleEvent: function(event){
		// Handles events on A and UL 
		var trigger = Event.element(event);

		// Find submenu that belongs to trigger
		if (trigger.className == 'withSub')
			ul = trigger.next();
		else{
			var anc = trigger.ancestors()
			trigger.ancestors().each(function(el){
				if(el.previous() && el.previous().hasClassName( 'withSub'))	{	ul = el.previous().next(); }
			})
		}
		
		if(event.type == 'mouseover'){
			menu.mouseover = true;
			if(ul.style.visibility != 'visible')
				this.showSubmenu(trigger, ul);
		}
		else{
			menu.mouseover = false;
			setTimeout(function(){menu.hideSubmenu(ul)}, 300)
		}
	},
	showSubmenu:function(trigger, ul){
		// Get position of a, to determine position of dropdown
		triggerPos = Position.page(trigger);
		Position.absolutize(ul);

		// Position submenu(ul) and remove 'visibility: hidden'
		ul.style.left = triggerPos[0] + 'px';
		ul.style.top = '174px';
		ul.style.visibility = 'visible';
	},
	hideSubmenu:function(ul){
		if(menu.mouseover == false)
			ul.style.visibility = 'hidden';
	}
};

function initClickableBoxes() {
	if($('specials')){
	   	// Make specials on homepage clickable
		var divs = $('specials').select('.specialBox');
		divs.each(function(div){
			Event.observe(div, 'click', function(){
				// Make div link to url in anchor
				url = div.getElementsByTagName('H3')[0].getElementsByTagName('A')[0].href;
				window.location = url;
			}, false);
		})
		
	}
	if($('contentleftSearch')){
	   	// Make searchresultboxes clickable
		var results = $('contentleftSearch').select('.sResult');
		
		results.each(function(div){
			
			// Make searchresultboxes clickable
			Event.observe(div, 'click', function(){
				// Make div link to url in anchor
				url = div.getElementsByTagName('H3')[0].getElementsByTagName('A')[0].href;
				window.location = url;
				}, false);
			
			// Make searchresultboxes highlight on hover
			Event.observe(div, 'mouseover', function(){
				// Make div link to url in anchor
				div.style.borderColor = '#d2d2d2';
				}, false);
			
			Event.observe(div, 'mouseout', function(){
				// Make div link to url in anchor
				div.style.borderColor = '#ebebeb';
				}, false);
		})

	}
}

function initClickableTables(){
	if(!($('accoTrips') || $('top10')) )
		return;
	
	if($('accoTrips')){
		var rows = $('accoTrips').select('.row');
		

		rows.each(function(row){
				row.style.cursor = 'pointer';
				tds = row.getElementsByTagName('TD');
				for(i=0;i<tds.length;i++)
						tds[i].style.backgroundColor = '#f9f9f0';

				// Event Handlers
				Event.observe(row, 'mouseover', function(){
					tds = row.getElementsByTagName('TD');
					for(i=0;i<tds.length;i++)
						tds[i].style.backgroundColor = '#f2f1d3';
				}, false);
				
				Event.observe(row, 'mouseout', function(){
					tds = row.getElementsByTagName('TD');
					for(i=0;i<tds.length;i++){
						tds[i].style.backgroundColor = '#f9f9f0';
					}
				}, false);
				
				Event.observe(row, 'click', function(){
				// Get link from A in first TD
					window.location = row.getElementsByTagName('TD')[0].getElementsByTagName('A')[0].href;
				}, false);
		})

	}
	if($('top10')){
		var rs = $('top10').select('.row');
		
		rs.each(function(r){
			r.style.cursor = 'pointer';
			// Event Handlers
			Event.observe(r, 'mouseover', function(){
				tds = r.getElementsByTagName('TD');
				for(i=0;i<tds.length;i++)
					tds[i].style.backgroundColor = '#3a6d9a';
			}, false);

			// Event Handlers
			Event.observe(r, 'mouseout', function(){
				tds = r.getElementsByTagName('TD');
				for(i=0;i<tds.length;i++)
					tds[i].style.backgroundColor = '';
			}, false);

			Event.observe(r, 'click', function(){
				window.location = r.getElementsByTagName('TD')[0].getElementsByTagName('A')[0].href;
			}, false);
		})

	}

}
 // Cookie Stuff
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setCookie(accoId, accoName){
	// Creates cookie or if it already exists adds new accoId
	if(readCookie('LMA') != null){
		var oldValue = readCookie('LMA');
		var newValue = oldValue + '|' + accoId + '>' + accoName;
	}
	else
		var newValue = accoId + '>' + accoName;
	
	createCookie('LMA', newValue, 30);
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function initTripHistory(){
	// Displays cookie info
	if (!readCookie('LMA') ||!$('tripHistory'))
		return;
	
	// Retrieve stored acco Information
	var historyCookie = readCookie('LMA');

	// Write trips to target
	var targetDiv = $('tripHistory');
	ul = '<ul>\n'
	
	var trips = historyCookie.split('|');

	ids = new Array();
	count = 0;
	for (i=0;i<trips.length;i++){
    	var accoAttrs =	trips[i].split('>');
    	accoId = accoAttrs[0];
    	accoName = accoAttrs[1];
    	
    	if( ids.indexOf( accoId ) == -1  && accoName != '' && accoId != ''){
    	    ul = ul + '<li><a href="?go=trip&action=accommodation&id=' + accoId + '">' + accoName + '</a></li>\n';
    		count += 1;
    	}
		ids[i] = accoId;
	}
	if(count > 0){
		ul = ul + '</ul>\n' ;
		new Insertion.Top (targetDiv, ul);
		h3 = '<h3>Eerder bekeken(' + count + '):</h3>'
		new Insertion.Top(targetDiv, h3);
		// Insert link to clear list
		clearLink = '<a id="clearHistory" href="#">Leeg deze lijst</a>';
		new Insertion.Bottom(targetDiv, clearLink);
		Event.observe($('clearHistory'), 'click', function(){
			eraseCookie('LMA');
			targetDiv.innerHTML = '';
		})
	}
}

function truncateAcco(readMore){
	// Shortens accommodation paragraph
	if (!$('accoInfo'))
		return;
	
	readMore = typeof(readMore) != 'undefined' ? readMore : 0;
	
	var maxLength = 500;	
	var p = $('accoInfo');
	var contents = p.innerHTML;
	
	if(readMore == 1){
		// Show original p and remove truncated p
		p.show();
		Element.remove($('truncated'));
		return;
	}
	if (contents.length> maxLength) {
		// Insert new p and hide original p
	    newContents = contents.substring(0, maxLength);
	    p.hide();
	    newP = '<p id="truncated">' + newContents + '...<br /><a id="untruncate">Lees meer...</a></p>' ;
	    new Insertion.After($('accoInfo'), newP)		
		Event.observe($('untruncate'), 'click', function(){
			truncateAcco(1);
		});
  }

}

function getGetVars(id){
	var s=location.search.match('(?:\\?|\&)'+id+'=([^\&]*)');
	return s?unescape(s[1].replace(/\+/g," ")):false
	}


function submitSimple(type) {
	if (type == 'country') {
		document.searchPlusForm.area.value = 0; 
		document.searchPlusForm.city.value = 0;
	} else if (type == 'area') {
		document.searchPlusForm.city.value = 0;
	}	
	document.searchPlusForm.page.value = '0';
	document.searchPlusForm.submit();
}
Event.observe(window, 'load', init, false);


function trackOutgoing(url) {
	if (pageTracker) {
		pageTracker._trackPageview('/outgoing/'+url);
	}
	return true;
}