var map, mkrs, p, m, None, True, False, help;
var langIndex = 0;
var testVar;
var I18N_AJAXFail = ["Sorry we could not get details from the server.","Sorry we could not get details from the server. (cym)"];
var I18N_Loading = ["Loading, Please wait...","Loading, Please wait..."]; //***Need translation
var I18N_NoCouncil = ["No Council Found","Ni ddarganfuwyd Cyngor"];
var I18N_StartCouncil = ["Start a community/town council","Sefydlu cyngor cymuned neu thref"];
var I18N_StartCouncilURL = ["/allabout-councils/set-up-a-council","/gwybodaethamgynghorau/sefydlu-cyngor"]
var I18N_NoneFound = ["",""]; 
var I18N_ViewCouncil = ["View council information","Gwybodaeth am y Cyngor"]; 
var I18N_PleaseEnter = ["Please enter a placename/postcode to search for","Please enter a placename/postcode to search for"]; //***Need Translation


var dummyIcon = {size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)};

AutoSizeFramedCloudMinSize = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
            'autoSize': true, 
            'minSize': new OpenLayers.Size(300,150),
            'maxSize': new OpenLayers.Size(300,250)
});



function checkCookie(){
    langFromCookie = "en";
    if(document.cookie){
        var nameEQ = "I18N_LANGUAGE=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0){
                   langFromCookie = c.substring(nameEQ.length,c.length).replace(/"/g,"");
                }
	}
        langIndex = langFromCookie == "en" ? 0:1;
    } else {
    //alert("no cookie");
    //remain as default value (0)
    }
}

function AJAXfail(e) {
	alert(I18N_AJAXFail[langIndex]);
}
function showHelp(){
}

function reset(e) {

	if (p && (p !== null)) { 
                map.removePopup(p);
		p.destroy(); 
                p = null;
	}      
	if (m && (m !== null)) { 
                mkrs.removeMarker(m);
		m.destroy(); 
                m = null;
	}
if (e) {OpenLayers.Event.stop(e);}
}

function showCouncil(lonlat) {

        reset();

	m = new OpenLayers.Marker(lonlat);
        m.dummyIcon = dummyIcon;
	mkrs.addMarker(m);
	p = new AutoSizeFramedCloudMinSize('Council', lonlat, new OpenLayers.Size(220,130), I18N_Loading[langIndex],m.dummyIcon, true,reset);
	map.addPopup(p);
	if (map.zoom == 0) {
		map.zoomTo(1);
	}  
        map.panTo(lonlat);
}

     
function setPopupContentFromDictionary(r) {
        if (r[0] == null) { //if we don't have any data
		var content = "<h3>"+I18N_NoCouncil[langIndex]+"</h3><img src=\"http://www.unllaiscymru.org.uk/local_councils/index_html/group_add.png\" height=\"16px\" width=\"16px\" /> <a href=\"http://www.unllaiscymru.org.uk"+I18N_StartCouncilURL[langIndex]+"\"><span class=\"emphasis\">"+I18N_StartCouncil[langIndex]+"</span></a>";
	}
	else {
		
                //set the council name depending on language
		var content = document.getElementById('lang').value == 'cy' ? "<h3 id='popTitle'>"+ decodeURIComponent(escape(r[0].welsh_name)) +"</h3>" : "<h3 id='popTitle'>"+ decodeURIComponent(escape(r[0].name)) +"</h3>";
                //find out if the user is admin, so we can print additional information
                
                var additionalData = "";

                var telephone = r[0].telephone === "" ? I18N_NoneFound[langIndex] : r[0].telephone;
                var cname = r[0].cname === "" ? I18N_NoneFound[langIndex] : decodeURIComponent( escape( r[0].cname.split(",")[0]));

                content += "<ul class=\"detail\"><li class=\"contact\"><img src=\"http://www.unllaiscymru.org.uk/local_councils/index_html/clerk.png\" height=\"16px\" width=\"16px\" /> <span>" + cname + "</span></li><li class=\"phone\"><img src=\"http://www.unllaiscymru.org.uk/local_councils/index_html/telephone.png\" height=\"16px\" width=\"16px\" /> <span> " + telephone + "</span></li>";
                content += ((r[0].username !== null) && (r[0].username !== "") && (r[0].username !== None) && escape(r[0].username)) ? "<li><img src=\"http://www.unllaiscymru.org.uk/local_councils/index_html/information.png\" height=\"16px\" width=\"16px\" /> <a href=\"http://www.unllaiscymru.org.uk/local councils/" + r[0].username + "\">"+I18N_ViewCouncil[langIndex]+"</a></li>" : "" 
                content += "</ul>"; 

	}

	p.setContentHTML(content);
}

function getFeatureInfoFor(event, lalo) {
	var councilname;
	var theX = 0;
	var theY = 0;
	layerlist = "council_boundaries";
	//reset();

	if (!lalo) { //if there isn't any data on the event object we need to carry out a query using the click points
		if (event.xy){
                     mouseLoc = map.getLonLatFromPixel(event.xy);
                    } else {
                      mouseLoc = new OpenLayers.LonLat(event.x, event.y);
                    }
		var url = "http://www.unllaiscymru.org.uk/MapArea/john/searchPoints?lon=" + mouseLoc.lon + "&lat=" + mouseLoc.lat;
                
                //check we're in bounds before displaying a popup:


		OpenLayers.loadURL(url, '', this, function(e){ if (e.responseText !== "INVALID POINTS\n") { showCouncil(mouseLoc); setPopupContentFromDictionary(eval(e.responseText)); } }, AJAXfail);




	}else { //if we've been returned data, get what we want and make a new object
       
        //if there are no results
                if (event[0] == null){
                         document.getElementById("search").className = "error";
                         document.getElementById("notfound").style.visibility="visible";
                   } else {
                         document.getElementById("search").className = "";
                         document.getElementById("notfound").style.visibility="hidden";
                   }


		var i = 0;
		for (i = 0; i < event.length && event[i] !== null; i++) {
                       //get xy from data
			var tempstring = event[i].point.replace("POINT(", "");
			tempstring = tempstring.replace(")", "");
			var tempxy = tempstring.split(" ");
			mouseLoc = new OpenLayers.LonLat(tempxy[0], tempxy[1]);
			theX = tempxy[0];
			theY = tempxy[1];
 			mouseLoc = new OpenLayers.LonLat(theX, theY);

			showCouncil(mouseLoc);
			setPopupContentFromDictionary(event);

		}
	}

}

function init() { 
        var xp, gp, bounds, mo, nav, grp, panBar;
        checkCookie();
	//for auto suggest:
   	var options = {
		script: "http://www.unllaiscymru.org.uk/local_councils/index_html/searchSuggest?",
                shownoresults: false,
		varname: "searchString",
		json: true,
                maxentries: 10,
                callback: function(e){getFeatureInfoFor(e, false);}
                
        };
        var as = new AutoSuggest('searchText', options);
        as.oP.shownoresults = false; //doesn't seem to work via options
        document.getElementById("notfound").style.visibility = "hidden";
        //end auto suggest stuff

	lang = 0;
	xp = new OpenLayers.Format.XML();
	gp = new OpenLayers.Format.GML({extractAttributes:true});
	bounds = new OpenLayers.Bounds(151538,158738, 383538,  398738);
        panBar = new OpenLayers.Control.PanZoomBar();
        nav = new OpenLayers.Control.Navigation();

	mo = {maxResolution:'400',controls: [panBar, nav], numZoomLevels:6,resolutions:[400, 200, 25, 5, 2.5, 1.25],maxExtent: bounds, projection: 'EPSG:27700', restrictedExtent: bounds};
	map = new OpenLayers.Map('map', mo);
        panBar.setMap(map);
        nav.disableZoomWheel();
	grp = new OpenLayers.Layer.WMS("Main Layer", "http://ovw-live.eryr.net/maps", {layers: 'base', format: 'png'});
	mkrs = new OpenLayers.Layer.Markers("Markers");
      
	map.events.register('click', map, function(e) {  getFeatureInfoFor(e, false);
                 /*//ajax request to check bounds, if check successful, create a popup box

                 var points = map.getLonLatFromPixel(e.xy);

		var url = "http://www.unllaiscymru.org.uk/MapArea/john/checkBounds?lon=" + points.lon + "&lat=" + points.lat;

		OpenLayers.loadURL(url, '', this, function(a){ if (a.responseText == "True\n"){ getFeatureInfoFor(e, false); } }, AJAXfail);     */                                
                 });


	map.addLayers([grp, mkrs]);
	map.zoomToMaxExtent();
}

function getPoints(searchstring){

	if (searchstring.length < 1) { 
		alert(I18N_PleaseEnter[langIndex]); 
		return; 
	}
	
	var url = "http://www.unllaiscymru.org.uk/local_councils/index_html/search?searchString=" + searchstring;
	OpenLayers.loadURL(url, '', this, function(e){ getFeatureInfoFor(eval(e.responseText), true);}, AJAXfail);          
}