var map, m, os, parishB, tithe, aerial, currFeat, popup, isCymraeg, mkrs, fieldB, medievalPOI, prehistoricPOI;
data = [];
var dummyIcon = {size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)};
var langIndex = 0;
var I18NCopyright = ["&copy; Crown copyright. Cyngor Gwynedd - 100023387 – 2008","&copy; Hawlfraint y Goron. Cyngor Gwynedd - 100023387 – 2008"];
var I18NField = ["Field","Cae"]; //Need Welsh xlation
var I18NSiteName = ["Site Name",""]; 
var I18NSiteType = ["PRN",""]; 
var I18NParish = ["Parish","Plwyf"]; 
var I18NNoInfo = ["No information available for this area.",""]; // Need Welsh xlation
AutoSizeFramedCloudMinSize = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
            'minSize': new OpenLayers.Size(300,200),
            'maxSize': new OpenLayers.Size(300,300)
});

function convertGridRef(fE,fN,nD){nL=Math.floor(nD*0.5);rE=fE+1000000;rN=fN+500000;pE=Math.floor(rE/500000);pN=Math.floor(rN/500000);mE=Math.floor((rE-pE*500000)/100000);mN=Math.floor((rN-pN*500000)/100000);return lS(pE,pN)+lS(mE,mN)+" "+(fE%100000).toString().slice(0,nL)+" "+(fN%100000).toString().slice(0,nL)}
function lS(E,N){return"ABCDEFGHJKLMNOPQRSTUVWXYZ".charAt(E+5*(4-N))};
function redrawOSGR(evt){var lonLat;if(evt==null){lonLat=new OpenLayers.LonLat(0,0);}else{if(pos.lastXy==null||Math.abs(evt.xy.x-pos.lastXy.x)>pos.granularity||Math.abs(evt.xy.y-pos.lastXy.y)>pos.granularity){pos.lastXy=evt.xy;return;}lonLat=pos.map.getLonLatFromPixel(evt.xy);if(!lonLat){return}if(pos.displayProjection){lonLat.transform(pos.map.getProjectionObject(),pos.displayProjection);}pos.lastXy=evt.xy;}var newHtml=pos.formatOutput(lonLat);if(newHtml!=pos.element.innerHTML){pos.element.innerHTML=convertGridRef(map.baseLayer.getLonLatFromViewPortPx(pos.lastXy).lon,map.baseLayer.getLonLatFromViewPortPx(pos.lastXy).lat,6)}};


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

function checkCookie(){
    if(document.cookie){
    langFromCookie = document.cookie.split("I18N_LANGUAGE=\"")[1].split("\"")[0];
    langIndex = langFromCookie == "en" ? 0:1;
    } else {
    //alert("no cookie");
    }
}

function init(lang)
{
        isCymraeg = lang;
        
        checkCookie();

        
        document.getElementById('mapCopyright').innerHTML=I18NCopyright[langIndex]
	allBounds = new OpenLayers.Bounds(253000, 315123, 280860, 350143);
	aerialBounds = new OpenLayers.Bounds(25500, 315000, 281000, 351000);
	res = "44";
	baseOptions =   {maxResolution: res, projection: 'EPSG:27700', maxExtent: allBounds, resolutions: ["44", 25, 5, 1.25], restrictedExtent:allBounds }
	aerialOptions = {maxResolution: "15", projection: 'EPSG:27700', maxExtent: allBounds, resolutions: ["4", "3", "2", "1"], restrictedExtent:allBounds }
	
	map = new OpenLayers.Map('map', {numZoomLevels:4,controls: [new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar()], units: 'km', restrictedExtent:allBounds});

        pos = new OpenLayers.Control.MousePosition({numdigits:0});
        map.addControl(pos);
        map.events.unregister( 'mousemove', pos, pos.redraw);
        map.events.register( 'mousemove', pos, redrawOSGR);

  	os = new OpenLayers.Layer.WMS( "OS Layer", "http://eryr.net/tilecache", {layers: 'ardudwy-os'}, baseOptions );
	tithe = new OpenLayers.Layer.WMS( "Tithe Maps", "http://eryr.net/tilecache", {layers: 'ardudwy-tithe'}, aerialOptions );
	aerial = new OpenLayers.Layer.WMS( "Aerial Photography","http://eryr.net/maps", {layers: 'ardudwy-aerial'}, aerialOptions );
        parishB = new OpenLayers.Layer.WMS( "Parish Boundries","http://eryr.net/maps", {layers: 'parishBounds',transparent: 'true'}, baseOptions );
        prehistoricPOI = new OpenLayers.Layer.WMS( "HER Prehistoric","http://eryr.net/maps", {layers: 'herPrehistoric',transparent: 'true'}, baseOptions );
        medievalPOI = new OpenLayers.Layer.WMS( "HER Medieval","http://eryr.net/maps", {layers: 'herMedieval',transparent: 'true'}, baseOptions );
        romanPOI = new OpenLayers.Layer.WMS( "HER Roman","http://eryr.net/maps", {layers: 'herRoman',transparent: 'true'}, baseOptions );

        parishB.setVisibility(false);
        prehistoricPOI.setVisibility(false);
        medievalPOI.setVisibility(false);
        romanPOI.setVisibility(false);

        mkrs = new OpenLayers.Layer.Markers("Markers");
        aerialButton = document.getElementById('aerial');
        osButton = document.getElementById('os');
        osButton.firstChild.className = "selected";

        titheButton = document.getElementById('tithe');
        mpoiButton = document.getElementById('medievalpoi');
        ppoiButton = document.getElementById('prehistoricpoi');
        rpoiButton = document.getElementById('romanpoi')
        pbButton = document.getElementById('parishbounds');
        OpenLayers.Event.observe(aerialButton , "click", onAerial);
        OpenLayers.Event.observe(osButton , "click", onOS);
        OpenLayers.Event.observe(titheButton , "click", onTithe);
        OpenLayers.Event.observe(pbButton , "click", onParishBounds);
        OpenLayers.Event.observe(mpoiButton , "click", onMedievalPOI);
        OpenLayers.Event.observe(ppoiButton , "click", onPrehistoricPOI);
        OpenLayers.Event.observe(rpoiButton , "click", onRomanPOI);

	map.addLayers([os, tithe, aerial, parishB, prehistoricPOI, medievalPOI, romanPOI]);
	map.zoomToMaxExtent(allBounds);

        map.events.register('click', map, clickFn);

        map.events.register('moveend', map, function (e) {OpenLayers.Event.stop(e);});

}
//map.events.register('click', map, function (e) {
function clickFn(e){
							// Start of mouse click


							var url = os.getFullRequestString({
								REQUEST: "GetFeatureInfo",
								EXCEPTIONS: "application/vnd.ogc.se_xml",
								BBOX: map.getExtent().toBBOX(),
								X: e.xy.x,
                						Y: e.xy.y,
				        	               	INFO_FORMAT: 'text/plain',
					                       	QUERY_LAYERS: 'poi',
						                FEATURE_COUNT: 1,
					                        WIDTH: map.size.w,
					                       	HEIGHT: map.size.h
							}, "/maps");

				            		

				           	 	var pixel = new OpenLayers.Pixel(e.xy.x,e.xy.y);
  							var lonlat = map.getLonLatFromPixel(pixel);
                                                        map.panTo(lonlat);
                                                        
                                                        reset();

                                                        m = new OpenLayers.Marker(lonlat);
                                                        m.dummyIcon = dummyIcon;
	                                                mkrs.addMarker(m);
                                                        popup = new AutoSizeFramedCloudMinSize('FieldInfo', lonlat, new OpenLayers.Size(220,250), "<div id=\"innerPopup\"></div>",m.dummyIcon, true,reset);
                                                        OpenLayers.loadURL(url, '', this, setHTML);
							map.addPopup(popup);
							popup.show();

		           	 			OpenLayers.Event.stop(e);

		           	 			//end of mouse click

//						});


}

 
function setHTML(response)
{
        var res = response.responseText;
        popupText = document.getElementById('innerPopup');
        if (response.responseText.match(/fieldBounds/)){
             res.match(/fieldname = \'(.*)\'/);
             var fieldname = RegExp.$1;
             res.match(/farm = \'(.*)\'/);
             var farm = RegExp.$1;             
             res.match(/parish = \'(.*)\'/);
             var parish = RegExp.$1;
             if (fieldname){
                 popupText.innerHTML = "<h2>"+I18NField[langIndex]+"</h2><span>"+fieldname+"</span><br /><h2>"+I18NParish[langIndex]+"</h2><span>"+parish+"</span>";
             }else{
                 popupText.innerHTML = "<h2>"+I18NNoInfo[langIndex]+"</h2>";
             }
        }else
        if (response.responseText.match(/hermedieval/) ||
           response.responseText.match(/herPrehistoric/) || 
           response.responseText.match(/herRoman/)) {
            res.match(/sitename = \'(.*)\'/);
            var sitename = RegExp.$1;
            res.match(/prn = \'(.*)\'/);
            var prn = RegExp.$1;
            popupText.innerHTML = "<h2>"+I18NSiteName[langIndex]+"</h2><span>"+sitename +"</span><br /><h2>"+I18NSiteType[langIndex]+"</h2><span>"+prn +"</span>";
        }else{
            popupText.innerHTML = "<h2>"+I18NNoInfo[langIndex]+"</h2>";
        }
       
}

function onAerial(){
    aerialButton.firstChild.className="selected"; osButton.firstChild.className=""; titheButton.firstChild.className="";
    map.setBaseLayer(aerial);
    aerial.setVisibility(true);
    os.setVisibility(false);
    tithe.setVisibility(false);
    document.getElementById('mapCopyright').innerHTML="Imagery supplied by Bluesky copyright COWI A/S & Bluesky International Limited";
}

function onOS(){
    aerialButton.firstChild.className=""; osButton.firstChild.className="selected"; titheButton.firstChild.className="";
    map.setBaseLayer(os);
    aerial.setVisibility(false);
    os.setVisibility(true);
    tithe.setVisibility(false);
    document.getElementById('mapCopyright').innerHTML=I18NCopyright[langIndex];
}

function onTithe(){
    aerialButton.firstChild.className=""; osButton.firstChild.className=""; titheButton.firstChild.className="selected";
    map.setBaseLayer(tithe);
    aerial.setVisibility(false);
    os.setVisibility(false);
    tithe.setVisibility(true);
    document.getElementById('mapCopyright').innerHTML="";
}

function onParishBounds() {
	parishB.visibility ? parishB.setVisibility(false) : parishB.setVisibility(true);
}

function onPrehistoricPOI() {
	prehistoricPOI.visibility ? prehistoricPOI.setVisibility(false) : prehistoricPOI.setVisibility(true);
}

function onMedievalPOI() {
	medievalPOI.visibility ? medievalPOI.setVisibility(false) : medievalPOI.setVisibility(true);
}

function onRomanPOI() {
	romanPOI.visibility ? romanPOI.setVisibility(false) : romanPOI.setVisibility(true);
}
