var map_2;

var list_html = "";
var points = [];
var tooltip_html = [];
var active_id;
var active_icon;
var detail_station;
var center_icon;
var active_box = 'stations';
var i = 0;
var c;

// timeouts
var t_ids = [];
var el_ids = [];
var h_ids = [];

//window.onresize = handleResize;

function doQuery(q) {
	if (q && document.getElementById(q))
		q = document.getElementById(q).value;

	if (window.pageTracker)
		pageTracker._trackPageview('/search.cgi?q=' + escape(q));

	window.location.href = '/q/' + q + '/';
}

function handleDefault(orig, t) {
	if (t.value == orig) {
		t.value = '';
		t.style.color = "#000000";
	}
}

function addEmail(q) {
	if (q && document.getElementById(q))
		q = document.getElementById(q).value;
	
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(q)) {
		return true;
	} else {
		alert("Geef een juist email-adres op!")
	}
	return false;
}

function setBrandstof(b, id) {
	var ar = document.getElementsByTagName('li');

	for (var j = 0; j < ar.length; j++) {
		if (ar[j].className == 'active_choice') {
			ar[j].className = 'choice';
		}
		if (ar[j].id == id) {
			ar[j].className = 'active_choice';
		}
	}
	setCookie('brandstof', b);
	getXML(map_2);
	handleBoxes('result_box', 'stations', false);
}

function showDetailStation(id, pixelPoint) {
	var pixelPoint = map_2.fromLatLngToDivPixel(points[id]);
	if (detail_station && tooltip_html[id]) {
		detail_station.innerHTML = tooltip_html[id];
		detail_station.style.visibility = 'visible';
		detail_station.style.left = (pixelPoint.x - 88) + 'px';
		detail_station.style.top = (pixelPoint.y - 112) + 'px';
		map_2.getPane(G_MAP_MARKER_PANE).appendChild(detail_station);
	}
}

function hideDetailStation() {
	if (document.getElementById('detail_station'))
		map_2.getPane(G_MAP_MARKER_PANE).removeChild(document.getElementById('detail_station'));

	var e = document.getElementById('detail_station');
	if (e) {
		e.innerHTML = '';
		e.style.visibility = 'hidden';
	}
}

function scrollToId(id) {
	var scr = 0;
	ar = document.getElementsByTagName('li');
	for (var j = 0; j < ar.length && scr == 0; j++) {
		if (ar[j].id == 'station_'+id) {
			scr = ar[j].offsetTop;
		}
	}

	scr -= 30;
	if (scr < 0)
		scr = 0;

	document.getElementById('results').scrollTop = scr;
}

function activateIcon(id) {
	var pixelPoint = map_2.fromLatLngToDivPixel(points[id]); 
	pixelPoint.x -= 13; 
	pixelPoint.y -= 0; 
	active_icon.style.left = pixelPoint.x + 'px' 
	active_icon.style.top = pixelPoint.y + 'px';
	active_icon.style.visibility = 'visible';

	map_2.getPane(G_MAP_MARKER_PANE).appendChild(active_icon);
}

function deactivateIcon() {
	if (document.getElementById('activepoint') && map_2)
		map_2.getPane(G_MAP_MARKER_PANE).removeChild(document.getElementById('activepoint'));
	
}

function activateId(id) {
	if (id && document.getElementById('station_'+id)) {
		showDetailStation(id);
//		activateIcon(id);

		ar = document.getElementsByTagName('li');
		for (var j = 0; j < ar.length; j++) {
			if (ar[j].id.match('^station_')) {
				ar[j].className = 'station';
			}
		}

		document.getElementById('station_'+id).className='active';
	} else {
		deactivateId();
	}
}

function deactivateId() {
	ar = document.getElementsByTagName('div');
	for (var j = 0; j < ar.length; j++) {
		if (ar[j].id.match('^station_')) {
			ar[j].className = 'station';
		}
	}
		
	hideDetailStation();
//	active_id = undefined;
//	deactivateIcon();
}

// Get the correct XML.
function getXML(map_2) {
	if (map_2) {
//		fixURL(map_2);
		var sb = document.getElementById('stations_content');
		if (sb)
			sb.innerHTML = 'Loading...';

		var bounds = map_2.getBounds();
		if (bounds) {
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();

			var kort = document.getElementById('discount');
			if (kort && kort.checked) {
				kort = 1;
			} else {
				kort = 0;
			}

			readMap("/getxml.fcgi?sort="+getCookie('sort')+"&type="+getCookie('brandstof')+"&left="+southWest.lng()+"&right="+northEast.lng()+"&top="+southWest.lat()+"&bottom="+northEast.lat()+'&korting='+kort, map_2);
		}
	}
}

// A function to read the data
function readMap(url, map_2) {
	list_html = "";
	points = [];
	i = 0;

	var n = document.getElementById('number_stations');
	if (n)
		n.innerHTML = '';

	GDownloadUrl(url, function(data, responseCode) {
		var xmlDoc = GXml.parse(data);

		// obtain the array of markers and loop through it
		var markers = xmlDoc.documentElement.getElementsByTagName("marker");

		// hide the info window, otherwise it still stays open where the removed marker used to be
		map_2.getInfoWindow().hide();
		map_2.clearOverlays();

		// reset the list
		list_html = "";

		if (n)
			n.innerHTML = markers.length + (markers.length==100 ? '+' : '');

		if (markers.length == 0) {
			list_html = 'geen ';
			if (getCookie('brandstof')) {
				list_html += getCookie('brandstof')+' ';
			}
			list_html += 'tankstations gevonden op deze kaart, <a href="javascript:map_2.zoomOut();">zoom uit</a> voor een groter bereik';
			if (getCookie('brandstof')) {
				list_html += ', of kies een ander brandstoftype';
			}
			list_html += '.';
		}

		for (var i = 0; i < markers.length; i++) {
			map_2.addOverlay(createMarker(markers[i]));
		}

		// put the assembled list_html contents into the list div
		var listdoc = document.getElementById("results");
		if (listdoc) 
			listdoc.innerHTML = list_html;

		if (active_id) {
			activateId(active_id);
			scrollToId(active_id);
		}
	});
}

function createMarker(marker) {
	var id = marker.getAttribute('id');

	var icon = new GIcon();
	icon.iconSize = new GSize(12, 15);
	icon.iconAnchor = new GPoint(6, 6);
	icon.infoWindowAnchor = new GPoint(6, 6);
	icon.image = '/icon/' + marker.getAttribute("type").toLowerCase() + '_' + marker.getAttribute("prijs") + '.png';

	var lat = parseFloat(marker.getAttribute("latitude"));
	var lng = parseFloat(marker.getAttribute("longitude"));
	var point = new GLatLng(lat,lng);
	points[id] = point;

	var tooltip = '';
	tooltip += '<h2><span class="price2">&euro; ' + marker.getAttribute("prijs") + '</span><img src="' + icon.image + '"/> ';
	if (marker.getAttribute("keten"))
		tooltip += marker.getAttribute("keten") + ' ';

	tooltip += marker.getAttribute("naam") + '</h2>';
	tooltip += '<ul>';
	tooltip += '<li>' + marker.getAttribute("adres")+', '+marker.getAttribute("plaats") + '</li>';
	tooltip += '<li>' + marker.getAttribute("type") + ': &euro; ' + marker.getAttribute("prijs");
	if (marker.getAttribute("uc") && marker.getAttribute("uc") == "1") {
		tooltip += " <strong>incl. "+marker.getAttribute("korting")+" ct/l korting</strong>";
	}
	tooltip += '</li>';
	if (marker.getAttribute("url")) {
		tooltip += "<li><a href=\"/station/" + marker.getAttribute("url") + "/\">Meer informatie over dit tankstation &raquo;</a></li>";
	}
	tooltip += '</ul>';
	tooltip_html[id] = tooltip;

	var html = '';
	html += '<h2><span class="price">&euro; ' + marker.getAttribute("prijs") + '</span><img src="' + icon.image + '"/> ';
	if (marker.getAttribute("keten"))
		html += marker.getAttribute("keten") + ' ';

	html += marker.getAttribute("naam") + '</h2>';
	html += '<ul>';
	html += '<li>' + marker.getAttribute("adres")+', '+marker.getAttribute("plaats") + '</li>';
	html += '<li>' + marker.getAttribute("type") + ' &euro; ' + marker.getAttribute("prijs") + ' <span>' + marker.getAttribute("datum") + '</span></li>';

	if (marker.getAttribute("uc") && marker.getAttribute("uc") == "1") {
		html += "<li><strong>incl. "+marker.getAttribute("korting")+" ct/l korting via <a href=\"/link/11/\" target=\"_blank\" rel=\"nofollow\">UnitedConsumers</a></strong></li>";
	} else {
		html += "<li>Nog niet aangesloten bij <a href=\"/link/54/\" target=\"_blank\" rel=\"nofollow\">UnitedConsumers</a></li>";
	}

	if (marker.getAttribute("url")) {
		html += "<li style=\"text-align:right; padding-right: 5px\"><a href=\"/station/" + marker.getAttribute("url") + "/\">Meer informatie over dit tankstation &raquo;</a></li>";
	}

	html += '</ul>';

	list_html += '<li class="goedkoop" id="station_'+id+'" onclick="myclick(' + id + ')" onmouseover="activateId('+id+');return false;" onmouseout="deactivateId();return false;">';
	list_html += html;
	list_html += '</li>';

	var m = new GMarker(point,icon);
	GEvent.addListener(m, "click", function() { myclick(id) } );
	GEvent.addListener(m, "mouseover", function() { showStation(id) } );
	GEvent.addListener(m, "mouseout", function() { hideStation(id) } );
	return m;
}

// This function picks up the click
function myclick(i) {
	if (!active_id || active_id != i) {
		active_id = i;
		activateId(i);
		scrollToId(i);
		handleBoxes('result_box', 'stations', false);
		map_2.panTo(points[i]);

	} else if (active_id) {
		active_id = undefined;
		deactivateId();
	}
}

function showStation(i) {
	activateId(i);
}

function hideStation(i) {
	deactivateId();
}

function selectBrandstof() {
	var br = document.getElementById('brandstofselect');
	var brandstof = getCookie('brandstof');
	if (br && brandstof) {
		if (br.options.length != 0) {
			for (var n = 0; n < br.options.length; n++) {
				if (br.options[n].value == brandstof ){
					br.selectedIndex=n;		
				}
			}
		}
	}
}

function setCookie(cookieName, value) {
	var expires = new Date();
	var today = new Date();
	expires.setTime(today.getTime() + 7*24*60*60*1000)
		if (value != null) {
			cookie = value
			cookie = cookie.substr(0,3000);
		} else {
			cookie = '';
		}
	document.cookie = cookieName + "=" + escape(cookie) + '; path=/' + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()));
}

function getCookie(cookieName) {
	var search = cookieName + "=";
	if (document.cookie.length > 0) { // if there are any cookies
		var offset = document.cookie.indexOf(search) ;
		if (offset != -1) { // if cookie exists
			offset += search.length ;
			// set index of beginning of value
			var end = document.cookie.indexOf(";", offset) ;
			// set index of end of cookie value
			if (end == -1)
				end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		}
	}
	return '';
}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function windowWidth() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerWidth)
		return self.innerWidth;
	// IE 6
	if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	// IE 5
	if (document.body)
		return document.body.clientWidth;
	// Just in case.
	return 0;
}

function handleResize() {
	if (map_2)
		c = map_2.getCenter();

	var mw = document.getElementById('map-wrapper');
	var bc = document.getElementById('breadcrumb');
	var ex = document.getElementById('explanation');
	var ds = document.getElementById('detail_station');
	var ab = document.getElementById('ads_banner');

	var height = 
		windowHeight() - 
		document.getElementById('header').offsetHeight - 
		15;

	var res_height = height - 5 + 9;

	if (document.getElementById('search')) 
		res_height -= document.getElementById('search').offsetHeight;

	if (document.getElementById('results')) {
		document.getElementById('results').style.overflow = 'hidden';
		document.getElementById('results').style.height = res_height + 'px';
	}

	if (mw && ab) {
		var map_height = height;
//		if (ab && ab.offsetHeight < 60) {
//			map_height -= ab.offsetHeight;
//		} else {
//			map_height -= 60;
//		}
		if (map_height > 0) 
			mw.style.height = map_height + 'px';
	}

	if (mw) {
		var map_height = height;
		map_height += 9;
		map_height -= 20 + 1;
//		map_height -= (60 - 5);

		if (map_height > 0)  {
			mw.style.height = map_height + 'px';
//			ab.style.top = (map_height - 60) + 'px';
		}
	}

	if (document.getElementById('search') && document.getElementById('results')) {
		var search_top = document.getElementById('results').offsetHeight + 5;
		document.getElementById('search').style.top = search_top + 'px';
	}

	var width = windowWidth() - 2;
	
	if (width < 1000)
		width = 1000;

	document.getElementById('header').style.left = '125px';
	document.getElementById('header').style.width = (width-125) + 'px';

	if ((mw && width > (468 + mw.offsetLeft + 10)) || width > (468 + 10)) {
		document.getElementById('skyscraper').style.width = '120px';
		document.getElementById('skyscraper').style.visibility = 'visible';
		width -= (6 + document.getElementById('skyscraper').offsetWidth);
	} else {
		document.getElementById('skyscraper').style.width = '0px';
		document.getElementById('skyscraper').style.visibility = 'none';
	}

	if (bc) 
		width -= bc.offsetLeft;

	var re = new RegExp("http://[^/]+/$");
	var loc = new String(document.location);
	if (ex && loc.match(re)) {
		var w = width - 190 - 2;
		document.getElementById('map').style.width = w + 'px';
		ex.style.left = w + 'px';
		ex.style.width = '190px';
//		ex.style.visibility = 'visible';
		ex.style.display = 'inline';
	} else if (ex) {
		ex.style.width = '0px';
//		ex.style.visibility = 'none';
		ex.style.display = 'none';
	}

	if (mw)
		mw.style.width = width + 'px';

//	if (ab)
//		ab.style.width = (width+2) + 'px';

	if (ds && mw) {
		ds.style.left = (mw.offsetWidth/2 + mw.offsetLeft) + 'px';
		ds.style.top  = (mw.offsetHeight/2 + mw.offsetTop - 70) + 'px';
	}

	if (windowHeight() > 614) {
		var top = windowHeight() - 614;
		if (document.getElementById('content').offsetTop < top)
			top = document.getElementById('content').offsetTop;

		document.getElementById('skyscraper').style.top = top + 'px';
	} else {
		document.getElementById('skyscraper').style.top = '0px';
	}

	setTimeout("handleBoxes('result_box', active_box, false);", 100);
	setTimeout("if (map_2 && c) map_2.panTo(c)", 200);
	setTimeout("focusOnSearch()", 400);
}

function handleBoxes(classname, default_id, clicked) {
	if (clicked && default_id && default_id == active_box) {
		var ar = document.getElementById('results').childNodes;

		for (var j = 0; j < ar.length; j++) {
			if (ar[j].className == classname) {
				deactivateBoxRecursive(ar[j], height);
			}
		}
		active_box = undefined;
		return;
	}

	if (default_id) 
		active_box = default_id;

	if (!document.getElementById('results')) 
		return;

	var ar = document.getElementById('results').childNodes;
	var height = document.getElementById('results').offsetHeight - 4;

	for (var j = 0; j < ar.length; j++) {
		if (ar[j].className == classname) {
			deactivateBoxRecursive(ar[j]);
		}

		if (ar[j].childNodes[0] && ar[j].childNodes[0].className == 'result_header') {
			height -= ar[j].childNodes[0].offsetHeight;
		}
		if (ar[j].childNodes[1] && ar[j].childNodes[1].className == 'result_header2') {
			height -= ar[j].childNodes[1].offsetHeight;
		}
	}

	for (var j = 0; j < ar.length; j++) {
		if (ar[j].className == classname) {
			if (ar[j].id == active_box) {
				activateBoxRecursive(ar[j], height);
			}
		}
	}
}

function deactivateBoxRecursive(el) {
	var kids = el.childNodes;
	for (var k = 0; k < kids.length; k++) {
		if (kids[k].className && kids[k].className == 'box_wrapper') {
			kids[k].style.overflow = 'hidden';
			kids[k].style.visibility = 'hidden';
			slowResize(kids[k], 1);
		}
		if (kids[k].className && kids[k].className == 'arrow') {
			kids[k].src = '/icon/icon_15x15-right.gif';
		}
		deactivateBoxRecursive(kids[k]);
	}
}

function activateBoxRecursive(el, height) {
	var kids = el.childNodes;
	for (var k = 0; k < kids.length; k++) {
		if (kids[k].className && kids[k].className == 'box_wrapper') {
			slowResize(kids[k], height);
			kids[k].style.overflow = 'auto';
			kids[k].style.visibility = 'visible';
		}
		if (kids[k].className && kids[k].className == 'arrow') {
			kids[k].src = '/icon/icon_15x15-down.gif';
		}
		activateBoxRecursive(kids[k], height);
	}
}

function slowResize(el, to) {
	if (el) {
		for (i = 0; i < el_ids.length; i++) {
			if (el_ids[i] == el && t_ids[i]) {
				clearTimeout(t_ids[i]);
			}
		}

		var g = el_ids.length;
		el_ids[g] = el;

		var from = el.offsetHeight;
		if (from == to || to < 0) {
			return;
		}

		var diff = Math.round((from - to) / 10);

		t_ids[g] = setTimeout("slowResize2(" + g + ", " + to + ", " + diff + ");", 45);
	}
}

function slowResize2(g, to, diff) {
	var el = el_ids[g];
	var from = el.offsetHeight;

	if (from == to || to < 0) {
		clearTimeout(t_ids[g]);
		return;
	}

	if (Math.abs(diff) > Math.abs(from - to))
		diff = from - to;

	// If ('from'-'diff') is further from 'to', than 'from', we're going the wrong way!
	if (Math.abs((from - diff)-to) > Math.abs(from - to))
		diff = from - to;

	from -= diff;
	el.style.height = from + "px";
	t_ids[g] = setTimeout("slowResize2(" + g + ", " + to + ", " + diff + ");", 45);
}

function focusOnSearch() {
	var q = document.getElementById('q2');
	if (!q)
		q = document.getElementById('q1');
//	if (q)
//		q.focus();
}

function fixURL(m) {
	var url = location.href;
	if (location.hash)
		url = url.replace(location.hash, '');
	
	url = url + '#/' + m.getZoom() + '/';
	url = url + m.getCenter().lat() + '/';
	url = url + m.getCenter().lng() + '/';
	location.href = url;
}
