/*
	Ziggo Dealer Locator. All js is included within 1 class.
*/
function Zdl(){
	this.box = this.$('zdl_box');
	this.content = this.$('zdl_content');

	// preview value for input fields
	this.$('zdl_postcode').orgText = this.$('zdl_postcode').value;
	this.$('zdl_postcode').className = 'zdlPreview';
	this.$('zdl_postcode').onfocus = this.delegate(this, this.tfHandleFocus, this.$('zdl_postcode'));
	this.$('zdl_postcode').onblur = this.delegate(this, this.tfHandleBlur, this.$('zdl_postcode'));
	this.$('zdl_huisnr').orgText = this.$('zdl_huisnr').value;
	this.$('zdl_huisnr').className = 'zdlPreview';
	this.$('zdl_huisnr').onfocus = this.delegate(this, this.tfHandleFocus, this.$('zdl_huisnr'));
	this.$('zdl_huisnr').onblur = this.delegate(this, this.tfHandleBlur, this.$('zdl_huisnr'));

	// terug zetten van de kleur
	this.$('zdl_postcode').onkeydown = this.delegate(this, this.tfHandleKeyDown, this.$('zdl_postcode'));
	this.$('zdl_huisnr').onkeydown = this.delegate(this, this.tfHandleKeyDown, this.$('zdl_huisnr'));
	this.$('zdl_huisnr').onkeyup = this.delegate(this, this.tfHandleKeyUp, this.$('zdl_huisnr'));
	
	// preload
	var img1 = new Image();
	var img2 = new Image();
	var img3 = new Image();
	var img4 = new Image();	
	img1.src = '/images/zdl/button_beschikbaarheid_lite.gif'
	img2.src = '/images/zdl/button_beschikbaarheid.gif'
	img3.src = '/images/zdl/button_vindwinkel_lite.gif'
	img4.src = '/images/zdl/button_vindwinkel.gif'

	this.init();
}

Zdl.prototype.box = null;
Zdl.prototype.content = null;
Zdl.prototype.map = null;
Zdl.prototype.lat = 0;
Zdl.prototype.lon = 0;
Zdl.prototype.zip = '';
Zdl.prototype.huisnr = '';
Zdl.prototype.state = 0;
Zdl.prototype.lastRequest = null;

Zdl.prototype.init = function(){
	this.state = 0;
	this.show('zdl_form');
	this.show('zdl_sbmt1', 'inline');
	this.hide('zdl_sbmt2');
	this.hide('zdl_msg2');
	this.hide('zdl_dealers_box');

	this.$('zdl_postcode').value = this.$('zdl_postcode').orgText;
	this.$('zdl_huisnr').value = this.$('zdl_huisnr').orgText;

	this.setText('zdl_title', 'Bestel nu online de Ziggo HD-ontvanger.');
	this.setText('zdl_msg', '<strong>Vandaag voor 15.00 uur besteld, morgen in huis</strong><br />Doe de postcodecheck en kijk of jij binnen het verzorgings-gebied van Ziggo woont. Je kunt dan direct online bestellen. Je ziet ook de verkooppunten bij jou in de buurt.');
}

Zdl.prototype.check = function(){
	var zip = this.$('zdl_postcode');
	var huisnr = this.$('zdl_huisnr');
	if(this.isValid(zip.value) && huisnr.value != '' && huisnr.value != huisnr.orgText){
		this.zip = zip.value.replace(/\s+/, '');
		this.huisnr = huisnr.value;
		
		var url = '/zdl.php';
		var query = 'ac=cz';
		query += '&zip=' + this.zip;
		query += '&nr=' + huisnr.value;
		this.ajax(url, query, 'onCheck');
		
		this.setText('zdl_msg2', 'Bezig met controleren van de postcode');
	} else {
		var msg = '';
		if(!this.isValid(zip.value) && (huisnr.value == '' || huisnr.value == huisnr.orgText)){
			msg = 'Vul je je volledige postcode en huisnummer nog even in?';
			zip.style.borderColor = '#ff0000';
			huisnr.style.borderColor = '#ff0000';
		}
		else if(!this.isValid(zip.value)){
			msg = 'Vul je je postcode nog even in?';
			zip.style.borderColor = '#ff0000';
		}
		else if(huisnr.value == '' || huisnr.value == huisnr.orgText){
			msg = 'Vul je je huisnummer nog even in?';
			huisnr.style.borderColor = '#ff0000';
		}
		
		if(this.state == 1){
			msg += this.getMapLink();
			this.hide('zdl_dealers_box', true);
		} else {
			this.hide('zdl_dealers_box');
		}

		this.show('zdl_msg2');
		this.setText('zdl_msg2', msg, 'zdl_error');
	}
	return false;
}

Zdl.prototype.onCheck = function(req){
	if(req){
		this.lastRequest = req;
		
		this.hide('zdl_msg2');
		
		var response = req.responseText.parseJSON();
		if(response.status == 1){
			if(response.data.isZiggo == 1){
				this.hide('zdl_sbmt1');
				//this.show('zdl_sbmt2', 'inline');
				this.hide('zdl_form');
				
				//var msg = '<strong><a href="#" onclick="zdl.order();return false;" title="Bestel online">Bestel online</a></strong><p style="font-style:0.9em;margin:0;">Vandaag voor 15.00 besteld, morgen in huis!</p><br /><strong><a href="#" onclick="zdl.dealerlocator();return false;" title="Vind winkels">Vind winkels</a></strong><p style="font-style:0.9em;margin:0;">Of vind de dichtstbijzijnde verkooppunten bij jou in de buurt</p>';
				  var msg = '<strong><a href="#" onclick="zdl.order();return false;" title="Bestel online">Bestel online</a></strong><br /><span style="font-style:0.9em;margin:0;">Vandaag voor 15.00 besteld, morgen in huis!</span><br /><br /><strong><a href="#" onclick="zdl.dealerlocator();return false;" title="Vind winkels">Vind winkels</a></strong><br /><span style="font-style:0.9em;margin:0;">Of vind de dichtstbijzijnde verkooppunten bij jou in de buurt</span>';
				
				this.setText('zdl_title', 'Ja, Ziggo levert in jouw regio');
				this.setText('zdl_msg', msg);
				
				this.lat = response.data.lat;
				this.lon = response.data.lon;
				
				//this.dealerlocator();
			} else {
				var msg = '';
				if(this.state == 0){
					this.show('zdl_sbmt1');
					this.hide('zdl_form');
					this.hide('zdl_sbmt2');
					this.hide('zdl_dealers_box');
					this.setText('zdl_title', 'Helaas!');
					msg += 'Ziggo is niet beschikbaar op jouw adres.<br /><br />';
					msg += 'Tip: Ga naar <a href="http://www.nlkabel.nl" target="_blank">www.nlkabel.nl</a> en klik op \'uw kabelbedrijf\'. ';
					msg += 'Wie weet heeft de kabelmaatschappij op jouw adres ook een HD-aanbieding.'
					msg += this.getReturnLink();
					this.setText('zdl_msg', msg);
				} else {
					this.hide('zdl_dealers_box', true);
					msg += 'Deze postcode ligt buiten het verzorgingsgebied van Ziggo.';
					msg += this.getMapLink();
					this.setText('zdl_msg2', msg, 'zdl_error');
				}
			}
		} else {
			this.setText('zdl_msg2', 'Er kan geen contact worden gemaakt met de server. Probeer het over 5 minuten nog eens. Onze exuses voor het ongemak.', 'zdl_error');
		}
	} else {
		this.setText('zdl_msg2', 'Er kan geen contact worden gemaakt met de server. Probeer het over 5 minuten nog eens. Onze exuses voor het ongemak.', 'zdl_error');
	}
}	

Zdl.prototype.isValid = function (zip){
	return zip.match(/^\d\d\d\d\s*[a-z][a-z]$/i)
}

Zdl.prototype.setText = function (id, s, c){
	var el = this.$(id);
	if(el){
		this.show(id)
		el.className = c ? c : '';
		el.innerHTML = s;
	}
}

Zdl.prototype.hide = function(id, doHide) {
	var el = this.$(id);
	if(el){
		if(!doHide){
			el.style.display = 'none';
		} else {
			el.style.visibility = 'hidden';
		}
	}
}

Zdl.prototype.show = function(id, m, unHide) {
	var el = this.$(id);
	if(el){
		if(!unHide){
			el.style.display = !m ? 'block' : m;
		} else {
			el.style.visibility = 'visible';
		}
	}
}

Zdl.prototype.getReturnLink = function(m){
	if(!m){
		return '<a href="#" onfocus="blur()" class="zdlBottomLink" onclick="zdl.init();return false;">Terug naar de postcodecheck.</a>';
	} else {
		return '<a href="#" onfocus="blur()" class="zdlBottomLink" onclick="zdl.init();zdl.onCheck(zdl.lastRequest);return false;">Terug naar vorige scherm.</a>';
	}
}

Zdl.prototype.getMapLink = function(){
	return '<a href="#" onfocus="blur" class="zdlBottomLink" onclick="zdl.returnToMap();return false;">Terug naar het kaartje.</a>';
}

Zdl.prototype.tfHandleFocus = function(argv, tf) {
	if(tf.value == tf.orgText){
		tf.value = '';
		tf.className = 'zdlActive';
	}
}

Zdl.prototype.tfHandleBlur = function(argv, tf) {
	if(tf.value == tf.orgText || tf.value == ''){
		tf.value = tf.orgText;
		tf.className = 'zdlPreview';
	}
}

Zdl.prototype.tfHandleKeyDown = function(argv, tf) {
	if(tf.style.borderColor != '#43A6F9'){
		tf.style.borderColor = '#43A6F9';
		this.hide('zdl_msg2');
	}
}

Zdl.prototype.tfHandleKeyUp = function(argv, tf) {
	if(tf.id == 'zdl_huisnr'){
		var n = parseInt(tf.value);
		tf.value = isNaN(n) ? '' : n.toString();
	}
}

Zdl.prototype.dealerlocator = function (){
	if(this.state == 1){
		this.show('zdl_dealers_box', '', true);
	} else {
		this.show('zdl_dealers_box');
	}
	this.show('zdl_form');
	this.state = 1;
	this.loadMap(this.lat, this.lon);
	this.setText('zdl_title', 'Winkel vinden');
	this.setText('zdl_msg', 'Bezig met het zoeken van alle winkels bij jouw in de buurt.');
	var url = '/zdl.php';
	var query = 'ac=gd';
	query += '&lat=' + this.lat;
	query += '&lon=' + this.lon;
	this.ajax(url, query, 'onDealerLocator');
}

Zdl.prototype.onDealerLocator = function(req){
	if(req){
		this.hide('zdl_msg2');

		var response = req.responseText.parseJSON();
		var a = [];
		if(response.status == 1){
			this.show('zdl_sbmt2', 'inline');
			this.setText('zdl_msg', 'Hieronder vind je een overzicht van de winkels bij jou in de buurt die de Ziggo HD-ontvanger verkopen.' + this.getReturnLink(true));
			
			this.$('zdl_dealers').innerHTML = '';
			for(var i = 0; i < response.data.result.length; i++){
				var dealer =  response.data.result[i];
				try {
					var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(dealer.lat,dealer.lon));
					shape.SetTitle(dealer.name);
					shape.SetDescription(dealer.description);
					shape.SetCustomIcon('http://ziggozomer.fornax.site4u.nl/images/zdl/zdl_pin.png');
					this.map.AddShape(shape);
					if(i <= 3){
						a.push(shape);
					}
				} catch (e) {
				}
				this.$('zdl_dealers').innerHTML += '<strong>' + (i+1) + ': ' + dealer.name + '</strong>' + dealer.description;
			}
			
			var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(this.lat,this.lon));
			shape.SetTitle('Uw huis');
			shape.SetDescription(this.zip);
			shape.SetCustomIcon('http://ziggozomer.fornax.site4u.nl/images/zdl/zdl_hpin.png');
			this.map.AddShape(shape);
			a.push(shape);
			this.map.SetMapView(a);
		} else {
			this.setText('zdl_msg', 'Er kan geen contact worden gemaakt met de server. Probeer het over 5 minuten nog eens. Onze exuses voor het ongemak.', 'zdl_error');
		}
	} else {
		this.setText('zdl_msg', 'Er kan geen contact worden gemaakt met de server. Probeer het over 5 minuten nog eens. Onze exuses voor het ongemak.', 'zdl_error');
	}
}

Zdl.prototype.order = function (){
	//window.location.href = 'http://www.onlinebestellen.nl/sd?postcode=' + this.zip + '&huisnummer=' + this.huisnr;
	pageTracker._trackPageview('bestellen');
	this.$('zdl_order_form').elements['postcode'].value = this.zip;
	this.$('zdl_order_form').elements['huisnummer'].value = this.huisnr;
	this.$('zdl_order_form').submit();
}

Zdl.prototype.loadMap = function (lat, lon){
	this.map = new VEMap('zdl_map');
	this.map.SetDashboardSize(VEDashboardSize.Tiny);
	try {
		this.map.LoadMap(new VELatLong(lat, lon), 14 ,'r');
	} catch(e){
		this.map.LoadMap(new VELatLong(lat, lon), 10, 'r');
	}
}

Zdl.prototype.returnToMap = function (){
	zdl.show('zdl_dealers_box', '', true);
	zdl.hide('zdl_msg2');
}

/* AJAX functions */
Zdl.prototype.ajax = function(url, query, returnFunction, argObj){
	var req;
    if(window.XMLHttpRequest){
        req = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if(req != null){
    	var argvObj = {};
    	argvObj.req = req;
    	argvObj.returnFunction = returnFunction;
    	argvObj.argObj = argObj;
        req.onreadystatechange = this.delegate(this, this.ajax_process, argvObj);
        req.open("POST", url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(query);
    } else {
    	this.setText('zdl_msg', 'Je browser kent geen ondersteuning voor deze functionaliteit.', 'zdl_error');
    }
}
Zdl.prototype.ajax_process = function(argv, argv2){
	var req = argv2.req;
	var returnFunction = argv2.returnFunction;
	var argObj = argv2.argObj;

    if(req.readyState == 4){
        if(req.status == 200){
			if(returnFunction){
				if(typeof(returnFunction) == 'string'){
					this[returnFunction](req, argObj);
				} else {
					returnFunction(req, argObj);
				}
			}
        } else {
            alert("ajax error");
        }
    }
}
/* Tools */
Zdl.prototype.$ = function(id){
	return document.getElementById(id);
}

Zdl.prototype.delegate = function(that, thatMethod, args){
	return function() { return thatMethod.call(that, arguments, args); }
}

Zdl.prototype.broll = function(input, m){
	input.src = m ? input.src.replace(/_lite/, '') : input.src.replace(/\.gif/, '_lite.gif');
}