function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl; 
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj);  
}
JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}
function roundNum(Num , Places){
   if (Places > 0) {
      if ((Num.toString().length - Num.toString().lastIndexOf('.')) > (Places + 1)) {
         var Rounder = Math.pow(10, Places);
         return Math.round(Num * Rounder) / Rounder;
      }
      else return Num;
   }
   else return Math.round(Num);
	
}
function site (site_element) {
	//this.site_id = site_element.id;
	this.site_id = site_element.loc_id;
	this.name = site_element.name;
	this.address_1 = site_element.address_1;
	this.address_2 = site_element.address_2;
	this.address_3 = site_element.address_3;
	this.town = site_element.town;
	this.postcode = site_element.postcode;
	this.address = site_element.address_2;
	this.materials = site_element.materials;
	this.lat = site_element.lat1;
	this.lng = site_element.long1;
	this.glat_lng = new GLatLng(site_element.latitude, site_element.longitude);
	this.distance = site_element.distance;
}

geocode = {
	
	setMaterials : 0,
	mapId : 'recyclingMap',
	listingData : null,
	materialData : new Array(),
	postcode : null,
	prefix : '',
	conn : null,
	data : null ,
	returnDataObj : null ,
	longitude : null,
	latitude : null,
	closest : 'http://www.recycling.co.uk/images/locations/bin-closest.png',
	selected : 'http://www.recycling.co.uk/images/locations/bin.png',
	deselected : 'http://www.recycling.co.uk/images/locations/bin_deselect.png',
	loadingImage : 'http://www.recycling.co.uk/images/lightbox-ico-loading.gif',
	url : 'http://www.recycling.co.uk/recycling-locations',
	callback : 'setMap',
	uniqueMaterials : new Array(),
	councilData : new Array(),
	locationList : new Array(),
	map: null,
	closestDistance : 10000000,
	closestCount : null,
	directions : null,

	init: function(){
		if (GlocalSearch) { this.conn = new GlocalSearch(); }
	},
	
	submitPostcodeSearch: function(value){
		this.postcode=value.toUpperCase();
		this.setMaterials = 0;
		this.usePointFromPostcode();
		return false;
	},
	
	parseQueryString: function(variable) {
	  var query = window.location.search.substring(1);
	  var vars = query.split("&");
	  for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) {
	      return pair[1];
	    }
	  }
	 return false;
	}, 
	load: function(){
		if (this.parseQueryString('postcode')){
			this.postcode = this.parseQueryString('postcode');
			this.usePointFromPostcode();
		} else {
			return false;
		}
	},	
	checkForm : function(value){
		if (value == ''){
		 alert('Please enter your postcode');
		 return false;
		}
	},
	
	handleError : function(){ 
		setMaterials = 0;
		document.getElementById(this.mapId).style.background = '#ffffff';
		document.getElementById(this.mapId).innerHTML = '<p style="color:#6C6A14;margin:10px;line-height:40px;vertical-align:middle;font-size:14px">Sorry, there is no data for this postcode</p>';
		document.getElementById('councilDetails').innerHTML = '';
		document.getElementById('councilDetails').style.display = 'none';
		document.getElementById('councilData').innerHTML = '';
		document.getElementById('councilData').style.display = 'none';
		
		return false;
		
	},
	usePointFromPostcode:function() {	
		document.getElementById(this.mapId).style.background = '#ffffff';
		document.getElementById(this.mapId).innerHTML = '<p style="color:#6C6A14;margin:10px;line-height:40px;vertical-align:middle;font-size:14px"><img src="' + this.loadingImage + '" style="margin-right:5px;vertical-align:middle"/> Updating the map - please wait a moment.</p>';
		if (this.postcode == ''){ return false; }
		geocode.init();
		var that = this;
		this.conn.setSearchCompleteCallback(null, 
			function() {
				if (that.conn.results[0]) {
					that.latitude = that.conn.results[0].lat;
					that.longitude = that.conn.results[0].lng;					
					that.data = that.conn.results[0];
					that.getaddressData();
				} else {
					document.getElementById(that.mapId).style.background = '#ffffff';
					document.getElementById(that.mapId).innerHTML = '<p style="color:#6C6A14;margin:10px;line-height:40px;vertical-align:middle;font-size:14px">Sorry, there is no data for this postcode</p>';
					document.getElementById('councilDetails').innerHTML = '';
					document.getElementById('councilDetails').display = 'none';
					document.getElementById('councilData').innerHTML = '';
					document.getElementById('councilData').display = 'none';
					return false;
				}
			});
		this.conn.execute(this.postcode + ", UK");
	},
	getaddressData:function(){
		var that = this;
		var path = this.url + '?postcode=' + this.postcode + '&longitude=' + this.longitude + '&latitude=' + this.latitude + '&option=com_recycling_locations&view=getDataRemote&callback=' + this.callback + '&materials=' + this.setMaterials + '&materialId=' + document.getElementById('materialSelecter').value;	
		var obj = new JSONscriptRequest(path);     
		  	obj.buildScriptTag(); // Build the script tag     
		  	obj.addScriptTag(); // Execute (add) the script tag
	},
	showPointLatLng:function(){
		var results = this.data;
	},
	setMap : function(){
		var results = this.data;
		this.longitude = results.lng;
		this.latitude = results.lat;
		this.loadMap();
	},
	setMaterialList : function(){
		elSel = document.getElementById('materialSelecter');
		 for(var id in this.uniqueMaterials){   
			  elSel.options[elSel.options.length]= new Option(this.uniqueMaterials[id], id, false, false)
		} 
	},
	setCouncilList : function (){
	
		if (!this.councilData.details){
			return false;
		}
		var address = this.councilData.details;
		var addressArr = new Array();
		if (address.address_1 != '' ){
			addressArr.push(address.address_1);
		}
		if (address.address_2 != '' ){
			addressArr.push(address.address_2);
		}
		if (address.address_3 != '' ){
			addressArr.push(address.address_3);
		}
		var addressDesc = addressArr.join(', ');
	
	
		var data =  '<dl class="councilDetails">';
			data += '<dt>'+ address.company_name  +'</dt>';
			data += '<dd>' + addressDesc + '</dd>';
			data += '<dd><strong>Tel:</strong><br/>'+ address.telephone_number  +'</dd>';
			data += '<dd><strong>Web:</strong><br/><a href="'+address.web_address +'">'+ address.web_address  +'</a></dd>';
			data += '<dd><strong>Email:</strong><br/><a href="mailto:'+address.contact_email +'">'+ address.contact_email  +'</a></dd>';
			data += '</dl>';
		document.getElementById('councilDetails').innerHTML = data;
		document.getElementById('councilDetails').style.display = '';
	
	},
	setCouncilMaterials : function(){
		if (!this.councilData.materials){
			return false;
		}
		var materials = this.councilData.materials.door;
		var data =  '<ul class="councilMaterials">';
			for (i in materials){
				data += '<li>'+ materials[i]  +'</li>';
			}
			data += '</ul>';
		document.getElementById('councilData').innerHTML = data;	
		document.getElementById('councilData').style.display = '';
	},
	distanceArr: new Array(),
	defineBounds: function (locationArr) {
		var boundsArray = locationArr.slice();
		var minLng = null;
		var minLat = null;
		var maxLng = null;
		var maxLat = null;	
		boundsArray.push( {longitude : this.longitude , latitude : this.latitude} );
		for ( var i = 0; i < boundsArray.length; i++ ) {			
			if ( boundsArray[i].longitude == 0 || boundsArray[i].latitude == 0)
			continue;
			minLng =  minLng == null || boundsArray[i].longitude > minLng ? minLng = boundsArray[i].longitude : minLng;
			maxLng =  maxLng == null || boundsArray[i].longitude < maxLng ? maxLng = boundsArray[i].longitude : maxLng;
			minLat =  minLat == null || boundsArray[i].latitude > minLat ? minLat = boundsArray[i].latitude : minLat;
			maxLat =  maxLat == null || boundsArray[i].latitude < maxLat ? maxLat = boundsArray[i].latitude : maxLat;	
		}
		delete boundsArray;	
		return new GLatLngBounds(new GLatLng(minLat, minLng), new GLatLng(maxLat, maxLng));;
	},
    getMarkerLatLong: function (location, icon) {
        var marker = new PdMarker(location.glat_lng, icon);
        marker.setUserData(location.site_id);
		var that = this;
        GEvent.addListener(marker, "click", function() {
			var directions = new GDirections(null , null , {locale : 'en_UK'});
			GEvent.addListener(directions, "load", function(){
				var directionObj = directions.getDistance();
				location.distance = roundNum((directions.getDistance().meters * 0.000621371192237334) , 2);
				if (location.distance < this.closest){
					this.closestDistance = location.distance;
				}
				this.closestCount ++;
				marker.openInfoWindowHtml(that.buildLocationText(location),{maxHeight:300, width:500, autoScroll: true});
				marker.distance = location.distance;
			});
			var pointsArray = [new GLatLng(that.latitude,that.longitude),location.glat_lng]; 
	  		directions.loadFromWaypoints(pointsArray);
        });
        return marker;
    },
	buildLocationText:function(data){
		var html = '<div class="locationMaterials">';
			html += '<h3>'+data.name+'</h3>';
			html += '<h4>';
			html += data.address_1 != undefined && data.address_1 != ''  ? data.address_1+', ' : '';
			html += data.address_2 != undefined && data.address_2 != ''  ? data.address_2+', ' : '';
			html += data.address_3 != undefined && data.address_3 != ''  ? data.address_3+', ' : '';
			html += data.town != undefined && data.town != '' ? data.town+', ' : '';
			html += data.postcode != undefined && data.postcode != '' ? data.postcode+'' : '';
			html += '</h4>';
			html += '<h5>Waste that this location can recycle:</h5>';
			html += '<ul>';
			if (data.materials.length == 0) {
				html += 'No data provided';
			} else {
				html += '<li>';
				html += data.materials.join('</li><li>');	
			}
			html += '</li></ul>';
			html += '<h4 class="distance">Approx distance: <strong>'+data.distance+' miles</strong></h4>';
			html += '</div><br/><br/>';
		return html;
	},
	buildMaterials: function(materialData){
		var cur = null;
		var count = 0;
		var tempMaterialArr = new Array();
		for (i in materialData){
			for (t in materialData[i]){
				cur = materialData[i][t];
				tempMaterialArr[count] = cur;
				count++;
			}
		}
		this.uniqueMaterials = tempMaterialArr;
	},
	collectSiteMaterials : function (location) {	
	
		for (var t = 0; t < location.materials.length; t++) {
			var key = "__" + location.materials[t];
			if (!this.locationList[key]) {
				this.locationList[key] = new Array();
			}		
			this.locationList[key].push(location.site_id);
		}
	},
	setMaterialsDisplay:function(obj) {	
		document.getElementById('materialUpdate').submit();		
	},
	setMarker: function (marker, show) {
		if (show) {
			marker.setImage(this.selected);
		} else {
			marker.setImage(this.deselected);
		}
	},	
	buildIcon:function () {
		var icon = new GIcon();
		icon.image = this.selected;
		icon.iconSize = new GSize(29, 34);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(8, 1);
		return icon;
	},
	
	loadMap : function(){
							
		var point;
		var pointArr = new Array();
		var locationId;
		var materialText;
		var directions;
	 	var data = this.listingData;
	    var materialData = this.materialData;
		
		this.buildMaterials(materialData);
		    
	    if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById(this.mapId));
			map.addControl(new GLargeMapControl());
			var bounds = this.defineBounds(data);
			var zoom = map.getBoundsZoomLevel(bounds);
						
			//if (zoom < 7 ){
			//	zoom = 12;
			//	map.setCenter(new GLatLng(this.latitude, this.longitude), 12);
			//} else {
				map.setCenter(bounds.getCenter(), zoom);
			//}			
			//map.setCenter(new GLatLng(this.latitude, this.longitude), 12);
			//map.setCenter(bounds.getCenter(), zoom);
			
			var blueIcon = new GIcon(G_DEFAULT_ICON);
			var icon = this.buildIcon();
			markerOptions = {icon: blueIcon};
			var point = new GLatLng(this.latitude, this.longitude);
			map.addOverlay(new GMarker(point, markerOptions));
			var icon = this.buildIcon();
			var markerArr = new Array();
			var directionArr = new Array();
			markerArr = new Array();
			var counter = 0;			
			for (var i in data) {
				locationId = data[i].loc_id;
				if (materialData[locationId] == undefined) {
					data[i].materials = '';
				}
				else {
					data[i].materials = materialData[locationId];
				}
				var location = new site(data[i]);
				if (location.site_id != undefined) {
					directions = new GDirections(null , null , {locale : 'en_UK'});
					directionArr[0] = point;
					directionArr[1] = location.glat_lng;
					this.collectSiteMaterials(location);
					marker = this.getMarkerLatLong(location, icon);
					map.addOverlay(marker);
					if (counter > 0) {
						marker.setImage(this.selected);
					}
					else 
					{			
						marker.setImage(this.closest);		
					}
					this.map = map;	
					counter++;
				}	
			}
			this.buildNearest(data[0]);
		}
	},
	noLocations: function(){
		var html = 'Sorry, there are no locations that recycle these items in your vicinity.';
		document.getElementById('map').innerHTML = html;
		document.getElementById('closestLocation').innerHTML = '';
	},
	buildNearest : function (data){
		var content = '<h3>Your nearest location: <strong>' + data.name + '</strong></h3>';
			content += '<p>' + data.address_1;
			if (data.address_2 !=''){content += ', ' + data.address_2;}
			if (data.address_3 !=''){content += ', ' + data.address_3;}
			if (data.town !=''){content += ', ' + data.town;}
			if (data.postcode !=''){content += ', ' + data.postcode;}
			if (data.telephone_number !=''){content += '<br/>Tel: ' + data.telephone_number;}
			content += '</p>';
		document.getElementById('closestLocation').innerHTML = content;		
	}
}