/******************************/
/*                            */
/*      Common Functions      */
/*                            */
/******************************/
// allow only numbers in input field
function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}
// dynamicly load javascript file
function loadJs(file){
	var headTag = document.getElementsByTagName('head')[0];
	script = document.createElement('script');
	script.type = 'text/javascript'; 
	script.src = file; 
	headTag.appendChild(script);
}
/******************************/
/*                            */
/*        LightWindow         */
/*                            */
/******************************/
var LightWindow = Class.create({   
	initialize: function(options) {
		var options = options || {};
		this.params = {
			'draggable': options.draggable || false,
			'width': options.width || '800px',
			'height': options.height || 'auto',
			'url': options.url || false,
			'content': options.content || "",
			//'class': options.class || "",
			'parameters': options.parameters || {},
			'top': options.top || null,
			'left': options.left || null,
			'remove': options.remove || false
		}
		
		// create box
		this.boxObj = new Element('div',{'class': 'lightWindow'});
		this.boxObj.className = 'lightWindow';
		this.boxObj.insert('<div class="tl"></div><div class="t"></div><div class="tr"></div><div class="contentContainer"><div class="l"></div><div class="r"></div><div class="content"></div></div><div class="bl"></div><div class="b"></div><div class="br"></div>'); // insert the needed html structure
		// create close element
		this.closeObj = new Element('a',{'class': 'close', 'href': 'javascript:void(0);'}); 
		this.closeObj.className = 'close';
		if(this.params.remove){
			this.closeObj.close = function(){ // extend oject with close function
				this.previous('div.contentContainer').down('div.content').innerHTML = ""; // remove object
				this.up('div.lightWindow').hide();
			}
		}
		else{
			this.closeObj.close = function(){ // extend oject with close function
				this.up('div.lightWindow').hide(); // remove object
			}
		}
		this.boxObj.insert(this.closeObj); // insert close button
		this.closeObj.observe("click", function(){this.close()});
		// write to page
		$(document.body).insert(this.boxObj);
		// make sure the element is hidden
		this.hide();
		// define contentElement
		this.contentObj = this.boxObj.down('div.content');
		// mage draggable
		if(this.params.draggable) new Draggable(this.boxObj, { scroll: window, starteffect: "", endeffect: "", handle: this.boxObj.down('div.t') });
		// set size
		this.setWidth();
		this.setHeight();
		// load ajax
		if(this.params.url) this.ajax(this.params.url, this.params.parameters);
		else if (this.params.content) this.load(this.params.content);
	},
	ajax: function(url,params){
		this.load("<img height='16' width='86' alt='Please Wait' src='../images/icon_wait.gif'/>");
		var obj = this;
		//ayax call
		new Ajax.Request(url, {
				method: 'post',
				parameters: params,
				onSuccess: function(transport){
					obj.load(transport.responseText)
				},
				onFailure: function(transport){
					obj.load("error: " + transport.status + " - " + transport.statusText);
				}
		});
	},
	load: function(data){
		this.contentObj.innerHTML = "";
		this.insert(data);
		this.defaultPosition();
		this.show();
	},
	insert: function(data,params){
		this.contentObj.insert(data,params);
		this.boxObj.style.height = "";
		this.boxObj.style.height = this.boxObj.getHeight()+'px';
	},
	show: function(){
		this.boxObj.show();
	},
	hide: function(){
		this.boxObj.hide();
	},
	remove: function(){
		this.boxObj.remove();
	},
	clear: function(){
		this.contentObj.innerHTML = "";
	},
	getContentObj: function(){
		return this.contentObj;
	},
	setWidth: function(width){
		this.boxObj.style.width = width? width : this.params.width;
	},
	setHeight: function(height){
		//this.boxObj.style.height = height? height : this.params.height;
		//this.contentObj.style.height = height? parseInt(height)-72+"px" : parseInt(this.params.height)-72+"px";
	},
	defaultPosition: function(){
		this.center();
		if (this.params.left != null) this.boxObj.style.left = this.params.left;
		if (this.params.top != null) this.boxObj.style.top = this.params.top;
	},
	center: function(){
		var viewport = document.viewport.getDimensions();
		var scroll = document.viewport.getScrollOffsets();
		var mywindow = this.boxObj.getDimensions();
		this.setPosition((viewport.width - mywindow.width)/2, ((viewport.height - mywindow.height)/2)+scroll.top)
	},
	left: function(left){
		this.boxObj.style.left = left +'px';
		this.params.left=left+"px";
	},
	top: function(top){
		this.boxObj.style.top = top +'px';
		this.params.top=top+"px";
	},
	setPosition: function(left,top){
		this.boxObj.style.left = left +'px';
		this.boxObj.style.top = top +'px';
	}
});
function popup(url){
	new LightWindow({width: '600px', url: url, draggable: true});
}

function myalert(string){
	new LightWindow({width: '400px', content: "<pre>"+string+"</pre>", draggable: true});
}
/******************************/
/*                            */
/*          STATION           */
/*            BOX             */
/*                            */
/******************************/
var currentStationTab = 0;
function updateStation(id){
	new Effect.Parallel([
			new Effect.Appear('stationBoxWait',{sync: true}),
			new Effect.Move('extraInfoImage', {sync: true, y: 200, mode: 'absolute' }),
			new Effect.Move('extraInfoAddress', {sync: true, x: -232, mode: 'absolute'})
		],{
			queue:{scope:'Station',position:'end'},
			duration:1,
			afterFinish: function(){
			new Ajax.Request('functions/getStation.cfm', {
				method: 'get',
				parameters: {id: id},
				contentType: 'application/xml',
				onSuccess: function(transport) {
					var xml = transport.responseXML.documentElement;
					
					$('extraInfoAddress').innerHTML =  xml.getElementsByTagName("location")[0].firstChild.nodeValue;
					$('extraInfoImage').innerHTML =  xml.getElementsByTagName("image")[0].firstChild.nodeValue;
					
					$('tabbedInfoContent').innerHTML =  xml.getElementsByTagName("tabs")[0].firstChild.nodeValue;
					showStationTab(currentStationTab);
			
					new Effect.Parallel([
							new Effect.Fade('stationBoxWait',{sync: true}),
							new Effect.Move('extraInfoImage', {sync: true, y: 63, mode: 'absolute' }),
							new Effect.Move('extraInfoAddress', {sync: true, x: 0, mode: 'absolute'})
						],{
							queue:{scope:'Station',position:'end'},
							duration:1,
							delay:1}
					);
				}
			});
		}
		}
	);
}
function showStationTab(id){
	var tabcontent = $('tabbedInfoContent').childElements();
	tabcontent.each(
		function(s){
			s.hide();
		}
	)
	$(tabcontent[id]).show();
	
	var tabbuttons = $('tabbedInfoTabs').childElements();
	tabbuttons.each(
		function(s){
			s.removeClassName('active');
		}
	)
	$(tabbuttons[id]).addClassName('active');
	
	currentStationTab = id;
}
function calculatePrice(el){
	var mytab = $(el).up('div.tab');
	var officialPrice = parseFloat(mytab.down('div.priceBox1').down('span.price').innerHTML);
	var lukoilPrice = parseFloat(mytab.down('div.priceBox2').down('span.price').innerHTML);
	var advantage = parseFloat(mytab.down('div.priceBox3').down('span.price').innerHTML);
	//alert("off: "+officialPrice+"   luk: "+lukoilPrice+"   adv: "+advantage);
	var kilometers = parseFloat(mytab.down('input.kilometer').value) || 0;
	var liters = parseFloat(mytab.down('input.liter').value) || 0;
	
	var totalAdvantage = ((kilometers*(liters/100))*officialPrice)-((kilometers*(liters/100))*lukoilPrice);
	
	new Effect.Appear(mytab.down('div.priceWait'),{
		duration:0.5,
		afterFinish: function(){
			var mycalc = mytab.down('div.priceCalculator');
			var mytotal = mycalc.down('div.priceTotal').down('span.euro');
			var mytotalbef = mycalc.down('div.priceTotal').down('span.bef');
			var mytext = mycalc.down('h1').down('span');
			mytotal.innerHTML = totalAdvantage.toFixed(0)+"<small>&euro;</small>";
			mytotalbef.innerHTML = (totalAdvantage*40.3399).toFixed(0)+"<small> BEF</small>";
			
			mycalc.down('div.priceTotal').show();
			mytext.hide();
			mytext.next('span').show();
			
			new Effect.Fade(mytab.down('div.priceWait'),{duration:0.5,delay:1});
		}
	});
}
/******************************/
/*                            */
/*          SEARCH            */
/*                            */
/******************************/
var searchWindow;
function initAutocomplete(){
	new Ajax.Autocompleter("zip", "autocomplete_choices", "functions/getAutocompleteZip.cfm", { 
		minChars: 2,
		afterUpdateElement: function(text,li){
			if (li.id){
				getStationsByLocation($('zip').value,li.id);
			}else{
				
				$('zip').value = "";
			}
		}
	});
}
function getStationsByLocation(zip,id){
	//document.location = 'getStationsByLocation.cfm?zip='+zip+'&id'+id;
	if(!searchWindow) searchWindow = new LightWindow({width: '872px', draggable: true});
	searchWindow.ajax('functions/getStationsByLocation.cfm',{zip: zip, id: id});
}
function submitStationsByLocationForm(form){
	if($(form).zip.value.length == 4){
		getStationsByLocation($(form).zip.value, 0);
	}else{
		if(!searchWindow) searchWindow = new LightWindow({width: '872px', draggable: true});
		searchWindow.load("Gelieve een postcode bestaande uit 4 cijfers in te geven.")
	}
	return false
}
function submitStationsByFeaturesForm(form){
	//document.location = 'getStationsByLocation.cfm?zip='+zip+'&id'+id;
	if(!searchWindow) searchWindow = new LightWindow({width: '872px', draggable: true});
	searchWindow.ajax('functions/getStationsByFeatures.cfm',$(form).serialize(true));
}
document.observe("dom:loaded", function() { 
	  // initially hide all containers for tab content 
	  if($('zip') && !document.forms.mycform) initAutocomplete();
});

function getStationsByIds(ids,lang,path){
	if(ids.indexOf(",") == -1){
		if(lang == 'nl') document.location = path + "/go/nl/lukoil_station.cfm?id="+ids;
		else if(lang == 'fr') document.location = path + "/go/fr/station_lukoil.cfm?id="+ids;
	}
	else{
		//document.location = 'getStationsByLocation.cfm?zip='+zip+'&id'+id;
		if(!searchWindow) searchWindow = new LightWindow({width: '872px', draggable: true});
		searchWindow.ajax('functions/getStationsByIds.cfm',{id: ids});
	}
}
function getAllStations(){
		//document.location = 'getStationsByLocation.cfm?zip='+zip+'&id'+id;
		if(!searchWindow) searchWindow = new LightWindow({width: '872px', draggable: true});
		searchWindow.ajax('functions/getAllStations.cfm');
}


function createMarker(point,id){
	// setup icon
	var lukoilIcon = new GIcon(G_DEFAULT_ICON);
	lukoilIcon.image = 'http://'+siteHost+'/'+siteSite+ "images/lukicon.png";
	lukoilIcon.iconSize = new GSize(12,20);
	lukoilIcon.iconAnchor = new GPoint(6,20);
	lukoilIcon.shadow = "";
	markerOptions = { icon:lukoilIcon };
	
	// create marker	
	var marker = new GMarker(point,markerOptions);
    marker.myID = id;
    // add events to marker
	 GEvent.addListener(marker, "click", function() {
    	if(siteSubsite.indexOf("nl") == 0 ){
    		document.location ='http://'+siteHost+'/'+siteSite+'go/'+siteSubsite+ "lukoil_station.cfm?id="+this.myID;
 		}else{
 			document.location ='http://'+siteHost+'/'+siteSite+'go/'+siteSubsite+ "station_lukoil.cfm?id="+this.myID;
 		}
    });
    GEvent.addListener(marker, "mouseover", function() { 
    	var element = $('myStation'+this.myID);
    	var container = $('stationResultContainer')
    	this.showMapBlowup();
    	container.childElements().each(function(e){e.removeClassName('active')});
    	element.addClassName('active');
    	
    	var elementOffset = element.positionedOffset().top;
    	var elementHeight = element.getHeight();
    	var containerScroll = container.scrollTop;
    	var containerHeight = container.getHeight();
    	
    	if(elementOffset < containerScroll){ // bovenaan buiten beeld
    		container.scrollTop = elementOffset;
 		}else if ((elementOffset + elementHeight) > (containerScroll + containerHeight)){ //onderaan buiten beeld
    		container.scrollTop = elementOffset - containerHeight + elementHeight;
    	}else{
    		// in beeld niets doen
    	}
    	
    }); 
    GEvent.addListener(marker, "infowindowclose", function() {
    	var element = $('myStation'+this.myID);
    	element.removeClassName('active');
    }); 
    
	//setup sidebar events
    $('myStation'+id).onmouseover = function(){GEvent.trigger(marker,'mouseover')};
    //$('myStation'+id).onmouseout = function(){GEvent.trigger(marker,'infowindowclose')};
    return marker;
}

function createMarker2(point,id){
	// setup icon
	var lukoilIcon = new GIcon(G_DEFAULT_ICON);
	lukoilIcon.image = 'http://'+siteHost+'/'+siteSite+ "images/lukicon.png";
	lukoilIcon.iconSize = new GSize(12,20);
	lukoilIcon.iconAnchor = new GPoint(6,20);
	lukoilIcon.shadow = "";
	markerOptions = { icon:lukoilIcon };
	
	// create marker	
	var marker = new GMarker(point,markerOptions);
    marker.myID = id;
    // add events to marker
	 GEvent.addListener(marker, "click", function() {
	 	if(siteSubsite.indexOf("nl") == 0 ){
    		document.location ='http://'+siteHost+'/'+siteSite+'go/'+siteSubsite+ "lukoil_station.cfm?id="+this.myID;
 		}else{
 			document.location ='http://'+siteHost+'/'+siteSite+'go/'+siteSubsite+ "station_lukoil.cfm?id="+this.myID;
 		}
    });
    
    GEvent.addListener(marker, "mouseover", function() { 
    	this.openInfoWindowHtml("<iframe width=220 height=58  frameborder=0 scrolling='no' src='functions/getStationPopup.cfm?iframe=yes&ID=" + this.myID + "'></iframe>");
    }); 
    GEvent.addListener(marker, "infowindowclose", function() {
    	//var element = $('myStation'+this.myID);
    	//element.removeClassName('active');
    }); 
    
	//setup sidebar events
    //$('myStation'+id).onmouseover = function(){GEvent.trigger(marker,'mouseover')};
    //$('myStation'+id).onmouseout = function(){GEvent.trigger(marker,'infowindowclose')};
    return marker;
}

