var doc = document;

function eleId(id) {
	if (doc.getElementById(id)) {
		return doc.getElementById(id);
	}
	return false;
}
function focusOn(id) {
	if (eleId(id)) {
		eleId(id).focus();
	}
}
function redirectTo(url, openInNewWindow) {
	if (openInNewWindow == true) {
		window.open(url);
	} else {
		doc.location.href = url;
	}
}
function getEvent(e) {
	return (e ? e : window.event);
}
function addEvent(obj, type, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(type, fn, false);
	} else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}
function removeEvent(obj, type, fn) {
	if (obj.removeEventListener) {
		obj.removeEventListener( type, fn, false );
	} else if (obj.detachEvent) {
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}
function stopBubble(e) {
	e = getEvent(e);
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
function viewEle(ele) {
	ele.style.visibility = 'visible';
}
function hideEle(ele) {
	ele.style.visibility = 'hidden';
}


/* Zoekbalk
------------------------------------------------------------------*/
function clearForm() {
	var elements = doc.forms[0].elements;
	
	for (i = 0; i < elements.length; i++) {
		if (elements[i].type == 'select-one') {
			elements[i].selectedIndex = 0;
		} else if (elements[i].type == 'text') {
			elements[i].value = '';
		} else if (elements[i].type == 'checkbox') {
			elements[i].checked = false;
		}
	}
	getCarModels(0);
}


/* Tabel en div effecten
------------------------------------------------------------------*/
var effPrevClassName = false;
function effInit() {
	// Tables
	eList = doc.body.getElementsByTagName('table');
	for (var i = 0; i < eList.length; i++) {
		ele = eList[i];
		if (ele.className.indexOf('effhover') >= 0) {
			if (ele.className.indexOf('list') >= 0) {
				effRowHover(ele.getElementsByTagName('tbody'));
			}
		}
	}
}
function effRowHover(arr, cssClass) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i].className.indexOf('nohover') >= 0) {
			continue;
		}
		if (cssClass && arr[i].className.indexOf(cssClass) != 0) {
			continue;
		}
		
		addEvent(arr[i], 'mouseover', function() {
			effPrevClassName = this.className;
			this.className += ' hover';
		});
		
		addEvent(arr[i], 'mouseout', function() {
			this.className = this.className.replace(' hover', '');
		});
	}
}


/* Google Maps
------------------------------------------------------------------*/
var GMiFrame = false;
var GMFrame = false;
var GMDiv = false;
var GMEle = false;
var GMIcon = false;
function GMInit() {
	if (GBrowserIsCompatible() && !GMEle) {
		// Google Maps
		GMDiv = document.createElement('div');
			with (GMDiv.style) {
			height = '390px';
			width = '390px';
			margin = '5px 5px 0 5px';
		}
		
		// Frame rond Google Maps
		GMFrame = document.createElement('div');
		with (GMFrame.style) {
			height = '420px';
			width = '400px';
			border = 'solid 1px #b5b5b5';
			padding = '0';
			backgroundColor = '#ffffff';
			position = 'absolute';
			top = '0px';
			left = '50%';
			marginLeft = '-206px'; // 400 /2 = 200 + 5 padding + 1 border
			textAlign = 'center';
		}
		GMFrame.appendChild(GMDiv);
		
		GMText = document.createElement('div');
		with (GMText.style) {
			margin = '5px 0';
			fontSize = '11px';
		}
		GMText.innerHTML = '<b style=\"color: #ff0000;\">Let op:</b> Bolletje geeft plaats aan, niet de exacte locatie.';
		GMFrame.appendChild(GMText);
		
		// iFrame achter het framewerk
		GMiFrame = document.createElement('iframe');
		GMiFrame.frameBorder = '1';
		with (GMiFrame.style) {
			border = '1px';
			height = '420px';
			width = '400px';
			backgroundColor = '#ffffff';
			position = 'absolute';
			top = '0px';
			left = '50%';
			marginLeft = '-206px'; // 400 /2 = 200 + 5 padding + 1 border
		}
		document.body.appendChild(GMiFrame);
		
		// Sluit venster onder Google Maps
		var GMClose = document.createElement("a");
		GMClose.href = '#';
		GMClose.onclick = new Function('GMHide(); return false;');
		GMClose.innerHTML = 'Sluit venster';
		with (GMClose.style) {
			lineHeight = '20px';
			height = '20px';
			width = '100%';
			display = 'block';
			color = '#ffffff';
			backgroundColor = '#000000';
		}
		
		GMFrame.appendChild(GMClose);
		document.body.appendChild(GMFrame);
		
		GMEle = new GMap2(GMDiv);
		
		GMEle.enableDoubleClickZoom();
		GMEle.addControl(new GLargeMapControl());
		GMEle.addControl(new GMapTypeControl());
		GMEle.setCenter(new GLatLng(52.156160556, 5.087638889), 7);
		GMEle.setZoom(10);
			
		document.body.setAttribute('onunload', 'GUnload();');
				
		GMIcon = new GIcon();
		GMIcon.image = "/images/icon/gm_minired.png";
		GMIcon.shadow = "/images/icon/gm_minishadow.png";
		GMIcon.iconSize = new GSize(12, 20);
		GMIcon.shadowSize = new GSize(22, 20);
		GMIcon.iconAnchor = new GPoint(6, 20);
		GMIcon.infoWindowAnchor = new GPoint(5, 1);
	}
	
	if (GMEle) {
		GMFrame.style.display = 'block';
		GMiFrame.style.display = 'block';
	}
}
function GMShow(lat, lng) {
	GMInit();
	GMCenter();
	GMEle.clearOverlays();
	GMEle.addOverlay(new GMarker(new GLatLng(lat, lng), GMIcon));
	GMEle.setCenter(new GLatLng(lat, lng));
}
function GMHide() {
	if (GMFrame) {
		GMFrame.style.display = 'none';
		GMiFrame.style.display = 'none';
	}
}
function GMCenter() {
	if (GMFrame && GMFrame.style.display == 'block') {
		fs = getFrameSize(2000, 2000);
		GMFrame.style.top = (fs.sT + 210) + 'px';
		GMiFrame.style.top = (fs.sT + 210) + 'px';
	}
}


/* Pagina frame informatie
------------------------------------------------------------------*/
function getFrameSize(dW, dH) {
	doc = document;
	
	// Scrollbar
	var x,y;
	if (self.pageYOffset) {
		// all except Explorer
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (doc.documentElement && doc.documentElement.scrollTop) {
		// Explorer 6 Strict
		x = doc.documentElement.scrollLeft;
		y = doc.documentElement.scrollTop;
	} else if (doc.body) {
		// all other Explorers
		x = doc.body.scrollLeft;
		y = doc.body.scrollTop;
	}
	
	// Page frame size
	if (self.innerWidth) {
		// all except Explorer
		fWidth = self.innerWidth;
		fHeight = self.innerHeight;
	} else if (doc.documentElement && doc.documentElement.clientWidth) {
		// Explorer 6 Strict
		fWidth = doc.documentElement.clientWidth;
		fHeight = doc.documentElement.clientHeight;
	} else if (document.body) {
		// all other Explorers
		fWidth = doc.body.clientWidth;
		fHeight = doc.body.clientHeight;
	}
	
	if (fWidth && fHeight) {
		return {fW: fWidth, sW: fWidth + x, fH: fHeight, sH: fHeight + y, sL: x, sT: y};
	}
	return {fW: dW, sW: dW + x, fH: dH, sH: dH + y, sL: x, sT: y};
}


/* Picture view
------------------------------------------------------------------*/
function PicView() {
	this.pointerX = false;
	this.pointerY = false;
	this.allow = (document.images ? true : false);
	
	this.div = false;
	this.img = false;
	this.src = false;
	
	this.ele = false;
	this.hide = false;
	
	this.frame = false;
	this.funcError = false;
}
PicView.prototype.show = function(e, src, hide, funcError) {
	this.src = src;
	this.hide = hide;
	if (funcError) {
		this.funcError = new Function(funcError);
	}
	
	if (this.allow) {
		if (!e) var e = window.event;
		this.pointerX = e.clientX;
		this.pointerY = e.clientY;
		
		this.ele = (e.srcElement ? e.srcElement : e.target);
		if (!this.ele.onmouseout) {
			this.ele.onmouseout = function() { pV.div.style.display = 'none'; };
		}
		
		if (!this.div) {
			// Afbeelding frame
			this.div = document.createElement('div');
			with (this.div.style) {
				position = 'absolute';
				backgroundColor = 'white';
				border = 'solid 1px #d5d5d5';
				padding = '5px';
			}
						
			document.body.appendChild(this.div);
		}
		
		// Browser frame grootte
		this.frame = getFrameSize(2000, 2000);
	
		// Afbeelding frame tonen
		with (this.div.style) {
			top = (this.pointerY + this.frame.sT) + 'px';
			left = (this.pointerX + 15 + this.frame.sL) + 'px';
			display = '';
		}
		
		this.div.innerHTML = 'Bezig met laden...';
		this.img = document.createElement('img');
		this.img.onload = function() { pV.loaded();	}
		this.img.onerror = function() { pV.error(); }
		this.img.src = this.src;
	}
}
PicView.prototype.loaded = function() {
	// Maximale afbeelding grote
	imgShrink(this.img, 194, 145);
	
	// Overschrijding browser frame verticaal
	picHeight = (this.img.height + 12);
	picBottom = (picHeight + (this.pointerY + this.frame.sT));
	if (picBottom > this.frame.sH) {
		newTop = (this.pointerY + this.frame.sT);
		newTop -= (picBottom - this.frame.sH);
		this.div.style.top = (newTop - 24) + 'px';
	}
	
	// Overschrijding browser frame horizontaal
	if (this.pointerX > 194) {
		picWidth = (this.img.width + 32);
		picRight = (picWidth + (this.pointerX + this.frame.sL));
		if (picRight > this.frame.sW) {
			newLeft = (this.pointerX + this.frame.sL);
			newLeft -= picWidth;
			this.div.style.left = (newLeft - 15) + 'px';
		}
	}

	while (this.div.hasChildNodes()) {
		this.div.removeChild(this.div.firstChild);
	}
	this.div.appendChild(this.img);
}
PicView.prototype.error = function() {
	if (this.hide) {
		this.ele.style.display = 'none';
	}
	
	if (this.funcError) {
		this.funcError();
	} else {
		this.div.innerHTML = 'De afbeelding is niet gevonden...';
	}
}

pV = new PicView();


/* Zoeken voortgang
------------------------------------------------------------------*/
function searchProgressValue(progress, totalresult) {
	for (i = 0; i <= progress; i += 10) {
		if (eleId('searchprogress_' + i)) {
			eleId('searchprogress_' + i).style.backgroundColor = '#ff8000';
		}
	}
	
	if (eleId('searchprogress-right') && totalresult != false) {
		eleId('searchprogress-right').innerHTML = 'Occasions gevonden: <b>'+totalresult+'</b>';
	}
}
function searchProgressName(name) {
	if (eleId('searchprogress-left') && name) {
		eleId('searchprogress-left').innerHTML = 'Bezig met zoeken op <b>'+name+'</b>';
	}
}


/* Zoekopdracht
------------------------------------------------------------------*/
function searchDelete(nr, type, subtype) {
	if (jxLoad('/jx?search=delete&'+type+'='+nr, false)) {
		if (eleId(type+'-'+nr)) {
			trEle = eleId(type+'-'+nr);
			tbodyParent = trEle.parentNode;
			tbodyParent.removeChild(trEle);
			
			tableParent = tbodyParent.parentNode;
			
			trElements = tableParent.getElementsByTagName('tr');
			if (trElements.length == 0) {
				eleId('searchedlist-'+type+(subtype ? subtype : '')).style.display = 'none';
			}
		}
	}
	
	return false;
}
function searchSave(nr, type) {
	if (!allowAll) {
		needLoginDialog();
	} else {
		if (jxLoad('/jx?search=save&'+type+'='+nr, false)) {
			if (eleId('searchsave')) {
				html = '';
				if (type == 'mail') {
					html = '<span class="text">E-mailnotificatie ingesteld</span><img src="/images/icon/accept.gif" />';
				} else if (type == 'action') {
					if (tabSelected == 'car') {
						html = '<a href=\"/mijngaspedaal?mailuls='+nr+'" title="Blijf op de hoogte van nieuwe resultaten" onclick="return searchSave('+nr+', \'mail\');\">E-mailnotificatie</a><img src="/images/icon/email.gif\" /><span>|</span>';
					}
					html += '<span class="text">Opgeslagen</span><img src="/images/icon/accept.gif" />';
				}
				eleId('searchsave').innerHTML = html;
			}
		}
	}
	
	return false;
}


/* Occasion
------------------------------------------------------------------*/
// Occasion bekijken
function occasionView(nr, isSaved) {
	for (i = 0; i < resultArray.length; i++) {
		if (resultArray[i].nr == nr) {
			occasionOpen(nr, resultArray[i].title, resultArray[i].sites, isSaved);
			break;
		}
	}
}

// Naar occasion detail pagina gaan
function occasionOpen(nr, title, sites, isSaved) {
	if (sites.length == 1) {
		// Occasion is op 1 site gevonden
		dialogEle.hide();
		ocassionVisit(nr, sites[0].nr, isSaved);
		redirectTo(sites[0].url, true);
	} else {
		// Occasion is op meerdere sites gevonden
		html = 'Deze occasion is op meerdere autosites gevonden. Klik op de autosite waar je de auto wilt bekijken:';
		html += '<ul>';

		for (i = 0; i < sites.length; i++) {
			html += '<li>- ';
			html += '<a href="' + sites[i].url + '" target="_gaspedaal" ';
			html += 'onclick="dialogEle.hide(); ocassionVisit(\'' + nr + '\', \'' + sites[i].nr + '\', ' + isSaved + ');" title="Klik hier om naar de site van ' + sites[i].name + ' te gaan.">' + sites[i].name + '</a>';
			html += '</li>';
		}

		html += '</ul>';
		
		dialogEle.show(title, html);
	}
}

// Occasion bezoek registreren
function ocassionVisit(nr, srsNr, isSaved) {
	jxLoad('/jx?occasion=visit&nr=' + nr + '&srsnr=' + srsNr + '&issaved=' + (isSaved ? '1' : '0'), false);
	
	if (visitUpdate) {
		if (eleId('b-' + nr)) {
			eleId('b-' + nr).className = 'visited';
		}
	}
}

function goTo(url, newWindow) {
	if (newWindow) {
		window.open(url);
	} else {
		doc.location.href = url;
	}
}

// Ad bezoek registreren
function adVisit(cp, br, ele) {

	jxLoad('/trackad.php?cp=' + cp + '&br=' + br + '&tp=c', false);
	
	if (typeof ele != 'undefined' && ele) {
		setTimeout( function() { goTo(ele.href); }, 150);
		return false;
	}
	return true;
}


// Occasion opslaan
function occasionSave(nr) {
	if (!allowAll) {
		needLoginDialog();
	} else {
		if ( jxLoad('/jx?occasion=save&nr=' + nr, (viewIsSaved ? 'occasionIsSaved()' : false) ) ) {
			eleId('save-'+nr).innerHTML = '<img src="/images/icon/accept.gif" style="position: relative; top: 3px;" />';
			eleId('save-'+nr).className = 'grey';
		}
	}
	return false;
}

function occasionIsSaved() {
	if (!inFrame) {
		html = '<div style="line-height: 15px;">De occasion is opgeslagen en zal worden gevolgd.<br /><br />';
		html += 'Je ontvangt automatisch een e-mail als er zich wijzigingen voordoen in prijs, km.stand of status.<br /><br />';
		html += '<a href="/opgeslagen" style="color: #ffffff;"><u>Bekijk alle opgeslagen occasions.</u></a><br /><br />';
		html += '<div style="font-size: 11px; text-align: center; line-height: 20px;"><input type="checkbox" onclick="occasionIsSavedView(this.checked);" id="viewnomore" /><label for="viewnomore">Dit bericht niet meer weergeven</label></div>';
		html += '</div>';
	
		dialogEle.show('Occasion is opgeslagen', html);
	}
}

function occasionIsSavedView(ch) {
	viewIsSaved = !ch;
	
	jxLoad('/jx?setting=displaysaved&vl=' + (ch ? 0 : 1), false);
}

/* Inloggen nodig
------------------------------------------------------------------*/
function needLoginDialog() {
	html = '<div style="line-height: 15px;">Om deze functie te kunnen gebruiken is het noodzakelijk ingelogd te zijn.<br /><br />';
	html += '<a href="/login?ref=1" style="color: #ffffff;"><u>Login</u></a> of <a href="/registreren" style="color: #ffffff;"><u>meld je gratis aan</u></a>.';
	html += '</div>';
		
	dialogEle.show('Inloggen op Mijn Gaspedaal', html);
}


/* Dialoog scherm
------------------------------------------------------------------*/
function Dialog() {
	this.div = doc.createElement('div');
	this.div.setAttribute('id', 'dialog');
	this.div.style.zIndex = 1002;
	this.div.style.display = 'none';
		
	this.appended = false;
}
Dialog.prototype.flow = function() {
	if (this.div.style.display == '') {
		fs = getFrameSize(2000, 2000);
		this.div.style.top = (fs.sH - (fs.fH / 2)) + 'px';
	}
}
Dialog.prototype.show = function(title, text) {
	if (!this.appended) {
		this.appended = true;
		doc.body.appendChild(this.div);
	}
	
	html = '<a href="#" onclick="return dialogEle.hide();" class="closeicon" title="Venster sluiten">&nbsp;</a>';
	html += '<h3>'+title+'</h3>';
	html += '<div class=\"textframe\">'+text+'</div>';
	html += '<a href="#" onclick="return dialogEle.hide();" class="close" title="Venster sluiten">Venster sluiten</a>';
	
	this.div.innerHTML = html;
	this.div.style.display = '';
	this.flow();
}
Dialog.prototype.hide = function() {
	this.div.style.display = 'none';
	return false;
}
var dialogEle = new Dialog();


/* Afbeelding
------------------------------------------------------------------*/
function imgShrink(ele, usewidth, useheight, checksize) {
	if (usewidth == 0) {
		usewidth = 70;
	}
	if (useheight == 0) {
		useheight = 60;
	}
	
	if (ele.width > usewidth) {
		ele.height = ((usewidth / ele.width) * ele.height); 
		ele.width = usewidth; 
	}
	
	if (ele.height > useheight) {
		ele.width = ((useheight / ele.height) * ele.width); 
		ele.height = useheight; 
	}
	
	if (checksize) {
		var checkImage = new Image();
		checkImage.src = ele.src;
			
		if (checkImage.width < ele.width) {
			ele.width = checkImage.width;
		}
		if (checkImage.height < ele.height) {
			ele.height = checkImage.height;
		}
	}
}

function imgNo(ele, size) {
	ele.src = '/images/list/noimage_'+size+'.gif';
	ele.style.width = size+'px';
	if (size == 160) {
		ele.style.height = '120px';
	} else {
		ele.style.height = '60px';
	}
	ele.onmouseover = 'return false';
	ele.onmouseout = 'return false';
}

function imgError(sNr, size) {
	tbodyId = 'tbody-' + sNr;
	tbodyEle  = eleId(tbodyId);
	
	imgId = 'img-' + sNr;
	imgEle = eleId(imgId);
	if (tbodyEle && imgEle) {
		imgNo(imgEle, size);
		
		if (pV && pV.div) {
			pV.div.style.display = 'none';
		}
	}
}


/* AJAX
------------------------------------------------------------------*/
var jxReq;
var jxCallFunc;
var jxResp;
function jxLoad(u, f) {
	jxCallFunc = f;
	
    if (window.XMLHttpRequest) {
        jxReq = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        jxReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

	if (jxReq) {
		if (jxCallFunc) {
			jxReq.onreadystatechange = jxProcess;
		}
		
		jxReq.open("GET", u, true);
		jxReq.send("");
		
		return true;
	}
	return false;
}
function jxProcess() {
    if (jxReq.readyState == 4) {
        if (jxReq.status == 200) {
			jxResp = new Function("return "+jxReq.responseText)();
			lf = new Function(jxCallFunc);
			lf();
        }
    }
}



/* Meer opties */
function OptionsDisplay() {
	optionsOpen = !optionsOpen;
	eleId('moreoptions').style.display = (optionsOpen ? '' : 'none');
	eleId('searchshadow').style.display = (optionsOpen ? 'none' : '');
	eleId('o').value = (optionsOpen ? 1 : 0);
	jxLoad('/jx?setting=moretab&value='+(optionsOpen ? 1 : 0), false);
}

function OptionsHref(ele) {
	if (pos = ele.href.lastIndexOf("&o=")) {
		ele.href = ele.href.substring(0, pos) + '&o=' + (optionsOpen ? '1' : '0');
	}
}

/* Tweedehandsgedeelte */
function geoSelectCheck(ele) {
	eleId(ele).selectedIndex = 0;
}


/* Overige */
function anClick(t, u, s) {
	jxLoad('/jx.php?anclick=1&t=' + t + '&u=' + u + '&s=' + s, false);
}

/*Bericht verbergen */
function hideNew() {
	document.getElementById('show_new').style.display = 'none';
	jxLoad('/jx.php?setting=hidenew', false);
}

/* Afab clicks */
function afabClick() {
	jxLoad('/jx.php?afab=1', false);
}