/**************************************************************
Event attacher
Voorbeeld van gebruik: document.attachEvent("onload", functieNaamHier);
***************************************************************/
document.events = [];
document.attachEvent = function(type, reference) {
	
    var evt = this.events;
    if(!evt[type]) evt[type] = [];
    evt[type][evt[type].length] = reference;

    document[type] = function(e) { 
        document.executeEvents(type, e);        
    }
}    


document.executeEvents = function(type, e) {
    for(var i in this.events[type]) {
        this.events[type][i](e);
    }
}

window.onunload = function() { document.executeEvents('onunload'); }
window.onload = function() { document.executeEvents('onload'); }
window.onresize = function() { document.executeEvents('onresize'); }

/**********************************************************************
Statistieken teller.  -> deze functie staat al in generic.js van GeoStart!!
**********************************************************************/
/*
function pageHit(sUrl){
	
	
	if(sUrl != ''){
		p = sUrl;
	} else {
		p = escape(document.location.href);
	}
	rfr = escape(document.referrer);
	if (rfr == "undefined"){ rfr = "";}
	sx = screen.width;
	sy = screen.height;
	sc = (navigator.appName.indexOf("Microsoft") > -1) ? screen.colorDepth : screen.pixelDepth;
	src = 'stats.php?p=' + p + '&rfr=' + rfr + '&sx=' + sx + '&sy=' + sy + '&sc=' + sc;
	src = '<img style="position:absolute;left:-10px;top:-10px;" src="' + src + '" width="1" height="1" border="0" alt="" />';
	document.getElementById('counter').innerHTML = src;  	
}
*/
//document.attachEvent("onload", pageHit);

/**********************************************************************
jQuery functies
**********************************************************************/
jQuery(document).ready(function(){
	
	// Statistieken
	pageHit(null);
	
	// IE6 fix
	if (jQuery.browser.msie && jQuery.browser.version.substr(0,1)=="6") {
		jQuery('#searchHand').css("background-image","url(../images/bg-hand.gif)");
		
	}

	// Geostart onload
	onLoad();
		
	// De zoekhand 	
	jQuery('.btn-nogmaals').click(function () {
		handOmlaag();				
    });
	
	// Link naar de homepage
	jQuery(".homelink").click(function(event){
		event.preventDefault();
		openHome();
	});
	
	// Zoek button
	jQuery(".btn-zoeken").click(function () {
		submitSearch();		
    });
	
	// Zoekveld
	sQdefault = 'Zoeken op naam, plaats, adres, postcode, provincie, omschrijving';
	
	jQuery("#sQ").focus(function(){
		if(jQuery("#sQ")[0].value == sQdefault){
			jQuery("#sQ")[0].value = '';
		}
	});
	
	jQuery("#sQ").blur(function(){
		if(jQuery("#sQ")[0].value == ''){
			jQuery("#sQ")[0].value = sQdefault;
		}
	});
	
	// Links met rel="external" moeten in een nieuw venster worden geopend
	targetBlank();
	
});

/**********************************************************************
Links met rel="external" moeten in een nieuw venster worden geopend
**********************************************************************/
function targetBlank(){
	jQuery('A[rel="external"]').click( function() {
        window.open(jQuery(this).attr('href') );
        return false;
    });
}

/**********************************************************************
De zoek functie via het zoekformulier aanroepen
**********************************************************************/
function submitSearch(){
	// Zoekwoord(en)
	sQ = jQuery("#sQ")[0].value;
	
	// array maken met de values van de aangevinkte types
	aType = new Array;
	jQuery("#searchform input:checked").each(function(id) {
		myVar = jQuery("input:checked").get(id);
		aType.push(myVar.value); 
	});
	
	// Pagina
	iPage = 1;
	
	zoek(sQ, aType, iPage);
}

/**********************************************************************
Zoeken
**********************************************************************/
function zoek(sQ,aType,iPage){
	// controleren of de zoektermen in orde zijn
	if(sQ != sQdefault && sQ != ''){
		
		// de active tabjes bovenaan de site uitzetten
		jQuery('#header ul a').removeClass("active");
		// home tab aanzetten
		jQuery('#header .tab1 a').addClass("active");
		
		// De zoekparameters die in de url worden gezet
		sUrlParameters = 'sQ='+sQ+'&iPage='+iPage
		if(aType.length > 0){
			for(i=0; i<aType.length; i++){
				sUrlParameters = sUrlParameters + '&aType[]='+aType[i];
			}
		} else {
			// als er geen types zijn geselecteerd, moet er een lege aType aan de url worden toegevoegd
			sUrlParameters = sUrlParameters + '&aType[]=';
		}
		
		// resultaten opvragen
		GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getSearchResults.php?' + sUrlParameters, function(sJson, responseCode) {
			// To ensure against HTTP errors that result in null or bad data,
			// always check status code is equal to 200 before processing the data
			if(responseCode == 200) {
				
				aJson = eval('(' + sJson + ')');
				
			
				if(aJson.iAantalResultaten > 0){
					// zoekhand omhoog als er resultaten zijn gevonden
					handOmhoog();					
				}
				
				// html in searchResults div inladen
				document.getElementById('searchResults').innerHTML = aJson.sHtml;
								
				// Statistieken bijhouden
				pageHit(sBaseUrl + '?page=zoeken&'+ sUrlParameters);
				
			} else if(responseCode == -1) {
				alert("Data request timed out. Please try later.");
			} else { 
				alert("Request resulted in error.");
			}
		});
	} else {
		alert('Vul a.u.b. een zoekterm in!');	
	}
}

/**********************************************************************
Zoekformulier verbergen
**********************************************************************/
function handOmhoog(){
	jQuery("#searchHand").animate({ 
		top: "-140px"
	}, 1000, 'swing',function(){			
		jQuery("#searchWrap").css({height:"116px"});					// de wrap div waarin de hand zit verkleinen, zodat de eerste zoekresultaten ook aanklikbaar zijn
		jQuery("#searchHand .btn-zoeken").css({display:"none"});		// zoeken knop verbergen
		jQuery("#searchHand .btn-nogmaals").css({display:"block"});		// nogmaals zoeken knop tonen
	});
	jQuery("#searchResults").animate({ 
		height: "453px"
	}, 1000);
}

/**********************************************************************
Zoekformulier tonen
**********************************************************************/
function handOmlaag(){
	jQuery("#searchWrap").css({height:"256px"});
	jQuery("#searchHand .btn-zoeken").css({display:"block"});
	jQuery("#searchHand .btn-nogmaals").css({display:"none"});
	jQuery("#searchHand").animate({ 
		top: "0px"
	}, 1000);
	jQuery("#searchResults").animate({ 
		height: "313px"
	}, 1000);
}


/**********************************************************************
Homepage openen
**********************************************************************/
function openHome(){
	// searchhand omlaag
	handOmlaag();
	
	// de active tabjes bovenaan de site uitzetten
	jQuery('#header ul a').removeClass("active");
	// home tab aanzetten
	jQuery('#header .tab1 a').addClass("active");
	
	// de best beoordeelde locaties inladen
	loadBestBeoordeeld();	
}

/**********************************************************************
Best beoordeelde locaties inladen
**********************************************************************/
function loadBestBeoordeeld(){
	GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getBestBeoordeelde.php', function(sJson, responseCode) {
		// To ensure against HTTP errors that result in null or bad data,
		// always check status code is equal to 200 before processing the data
		if(responseCode == 200) {
				
			aJson = eval('(' + sJson + ')');
			
			// html in searchResults div inladen
			document.getElementById('searchResults').innerHTML = aJson.sHtml;
			
			// Statistieken bijhouden
			pageHit(sBaseUrl);
			
		} else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		} else { 
			alert("Request resulted in error.");
		}
	});
}

/**********************************************************************
Tekstpagina openen
**********************************************************************/
function openPage(sPageKey){
	// searchhand omhoog
	handOmhoog();
	
	// de active tabjes bovenaan de site uitzetten
	jQuery('#header ul a').removeClass("active");
	
	if(sPageKey == 'over_deze_site'){
		jQuery('#header .tab2 a').addClass("active");
	}
	
	GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getPaginatekst.php?key='+sPageKey, function(sJson, responseCode) {
		// To ensure against HTTP errors that result in null or bad data,
		// always check status code is equal to 200 before processing the data
		if(responseCode == 200) {
				
			aJson = eval('(' + sJson + ')');
			
			// html in searchResults div inladen
			document.getElementById('searchResults').innerHTML = aJson.sHtml;
			
			// Statistieken bijhouden
			pageHit(sBaseUrl + sPageKey);
			
		} else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		} else { 
			alert("Request resulted in error.");
		}
	});
}

/**********************************************************************
Infobox openen met de informatie over een vermelding
iMarkerId = int id van de marker
iTab = int 0 of 1. 0 = tablad "over ons", 1 = tablad "recensies"
**********************************************************************/
function openInfobox(iMarkerId, iTab){
	
	oPoint = oGeoStart.oPoints[iMarkerId].getPoint();
	
	oGeoStart.oMap.setCenter(oPoint, 13);
	
	GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getVermelding.php?id='+iMarkerId, function(sJson, responseCode) {
		// To ensure against HTTP errors that result in null or bad data,
		// always check status code is equal to 200 before processing the data
		if(responseCode == 200) {
				
			aJson = eval('(' + sJson + ')');
			
			// de div tonen
			jQuery("#infobox").css({display:"block"});

			// De informatie in de infobox div zetten
			document.getElementById('infobox').innerHTML = aJson.sHtml;
			
			
			// bind recensieform using 'ajaxForm' -> http://malsup.com/jquery/form/#code-samples
			jQuery('#recensieform').ajaxForm({ 
				beforeSubmit: checkRecensieform, 
				success: showResponse,
				dataType: 'json',
				resetForm: true
			}); 
			
			// Bij klikken op het close icoontje de infobox sluiten (die over de kaart heenligt)
			jQuery("#sluiten").click(function () {
				jQuery("#infobox").fadeOut("slow");
			});
			
			// De 2 tabbladen in de infobox
			var $tabs = jQuery("#infobox .tabset").tabs();
			
			$tabs.tabs('select', iTab); // het juiste tabblad openen
			
			
			// tekstlink om naar de recensies tab te gaan
			jQuery('#tab1 .tab2').click(function() { // bind click event to link
				$tabs.tabs('select', 1); // switch to second tab
				return false;
			});
			
			// Links in een nieuw venster
			targetBlank();
			
			// Naam veld
			sNaamdefault = 'uw naam';
			
			jQuery("#naam").focus(function(){
				if(jQuery("#naam")[0].value == sNaamdefault){
					jQuery("#naam")[0].value = '';
				}
			});
			
			jQuery("#naam").blur(function(){
				if(jQuery("#naam")[0].value == ''){
					jQuery("#naam")[0].value = sNaamdefault;
				}
			});
			
			// Statistieken bijhouden
			pageHit(sBaseUrl + aJson.sPermUrl);
			countHit(aJson.iVermeldingId,'infobox');
			
		} else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		} else {
			alert("Request resulted in error.");
		}
	});
}



/**********************************************************************
In de infobox kan je met behulp van deze functie door de foto's bladeren
**********************************************************************/
function changeImg(sFilename){
	jQuery('#fullimg')[0].src = 'crop/200/150/'+sFilename;
}


/**********************************************************************
Waarderingssterren bij recensie
**********************************************************************/
function punten(sPrefix, iNumber){
	
	// sterren aanzetten
	for(i=1; i<=iNumber; i++){
		re=new RegExp('off.gif','gi');
		ele = document.getElementById(sPrefix+i);
		ele.src = ele.src.replace(re,"on.gif");
	}
	
	// overige sterren uitzetten
	for(i=iNumber+1; i<=5; i++){		
		re=new RegExp('on.gif','gi');
		ele = document.getElementById(sPrefix+i);
		ele.src = ele.src.replace(re,"off.gif");
	}
	
	// in het hidden field het aantal punten zetten
	jQuery('#waardering')[0].value = iNumber;
}


/**********************************************************************
Controleer of alle velden ingevuld zijn voordat de recensie wordt opgeslagen
**********************************************************************/
function checkRecensieform(formData, jqForm, options) { 
    
	if(formData[0].value == ''){
		alert('Vul a.u.b. een recensie in');
		return false;
	}
	
	if(formData[1].value == '' || formData[1].value == 'uw naam'){
		alert('Vul a.u.b. een naam in');
		return false;
	}
	
	if(formData[2].value == '0' || formData[2].value < 0 || formData[2].value > 5){
		alert('Geef een waardering door met de muis over de sterren te gaan');
		return false; 
	}
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true;
}

/**********************************************************************
post-submit callback 
De infobox opnieuw inladen zodat de nieuwe recensie erbij staat
**********************************************************************/
function showResponse(oJson, statusText)  {
	if(statusText == 'success'){
		if(oJson.sResult == 'success'){
		    openInfobox(oJson.iMarkerId,1);

			// de best beoordeelde locaties opnieuw inladen
			//loadBestBeoordeeld();
		} else if(oJson.sResult == 'doublevote'){
		    alert('Voor deze locatie heb je al een recensie geplaatst. Je kan slechts een beoordeling per locatie geven!');
		}
	} else {
		alert('Er is iets mis gegaan bij het opslaan van de recensie');	
	}	
}

/**********************************************************************
Beoordeling 
De infobox opnieuw inladen zodat de nieuwe recensie erbij staat
**********************************************************************/
function saveBeoordeling(iPunten,iVermelding){
	if(iPunten < 1 || iPunten > 5) return false;
	
	// resultaten opvragen
	GDownloadUrl(sBaseUrl + 'GeoStart/ajax/postBeoordeling.php?punten='+iPunten+'&vermelding='+iVermelding, function(sJson, responseCode) {
		// To ensure against HTTP errors that result in null or bad data,
		// always check status code is equal to 200 before processing the data
		if(responseCode == 200) {
				
			aJson = eval('(' + sJson + ')');
			
			if(aJson.sResult == 'success'){
				openInfobox(aJson.iMarkerId,0);
				
				// de best beoordeelde locaties opnieuw inladen
				//loadBestBeoordeeld();
			} else if(aJson.sResult == 'doublevote'){
				alert('Voor deze locatie heb je al een beoordeling geplaatst. Je kan slechts een beoordeling per locatie geven!');
			}
						
		} else if(responseCode == -1) {
			alert("Request timed out. Please try later.");
		} else { 
			alert("Request resulted in error.");
		}
	});
}

/**************************************************************
Hits tellen op het openen van pagina's, versturen van formulier enz.
iID: (int) 0 / banner id / formulier id
sObject: (string) omschrijving van het object waarop is geklikt (optin geopend / banner / formulier verzonden)
***************************************************************/
function countHit(iID,sObject){
	jQuery.get("GeoStart/ajax/counthit.php", {iID: iID, sObject: sObject}, function(data){
		//alert(data);
	});
}

/**************************************************************
De kaart naar de opgegeven provincie in laten zoomen
***************************************************************/
function showProvincie(sProvincie){
	
	switch(sProvincie){
		case 'drenthe':
			oPoint = new GLatLng(52.8691297276852, 6.64947509765625);
			break;
		case 'flevoland':
			oPoint = new GLatLng(52.549636074382285, 5.5426025390625);
			break;
		case 'friesland': 
			oPoint = new GLatLng(53.09237469097508, 5.9271240234375);
			break;
		case 'gelderland':
			oPoint = new GLatLng(52.12505765485123, 6.06719970703125);
			break; 
		case 'groningen':
			oPoint = new GLatLng(53.16982647814065, 6.68243408203125);
			break;
		case 'limburg':
			oPoint = new GLatLng(51.2206474303833, 5.9381103515625);
			break;
		case 'noord-brabant':
			oPoint = new GLatLng(51.590722643120145, 5.22674560546875);
			break;
		case 'noord-holland':
			oPoint = new GLatLng(52.48779793992096, 4.822998046875);
			break;
		case 'overijssel':
			oPoint = new GLatLng(52.44429203405363, 6.41876220703125);
			break;
		case 'utrecht':
			oPoint = new GLatLng(52.118312197617946, 5.16082763671875);
			break;
		case 'zeeland':
			oPoint = new GLatLng(51.474540439419755, 3.83697509765625);
			break;
		case 'zuid-holland':
		default:
			oPoint = new GLatLng(51.97642166216334, 4.49615478515625);
			break;
	}	

	oGeoStart.oMap.setCenter(oPoint, 9);	
}
