﻿//JSON.eval = JSON.parse;
var map, escaper;
var lastFeaturePopup;
var routeLayer;
var pointer;
/*var POICATEGORIES=[
{"id":1,"name":"Εστιατόριο","iconUrl":"assets/poi_icons/small/1_small.png","iconWidth":28,"iconHeight":28,"iconDx":-14,"iconDy":-14},
{"id":2,"name":"Καφέ","iconUrl":"assets/poi_icons/small/2_small.png","iconWidth":28,"iconHeight":28,"iconDx":-14,"iconDy":-14}
];*/
var poiLayers=[];
var poiLayersById = {};

function setText(el, s)
{
    if ("textContent" in el)
        el.textContent = s;
    else
        el.innerText = s;
}

function map_init()
{
	var oldOnWheelEvent = OpenLayers.Control.MouseDefaults.prototype.onWheelEvent;
	OpenLayers.Control.MouseDefaults.prototype.onWheelEvent = function(e) {
		var elem = OpenLayers.Event.element(e);
		while (elem) {
			if (elem.className && elem.className.indexOf && elem.className.indexOf("olControlLayerSwitcher") >= 0)
				return;
			elem = elem.parentNode;
		}
		oldOnWheelEvent.apply(this, [e]);
	};
	var mouseDefaults = new OpenLayers.Control.MouseDefaults();
	
	var layerSwitcher = new OpenLayers.Control.LayerSwitcher({
		'ascending': true,
		'activeColor': "#D07327"
		});
		
    var mapDiv = document.getElementById("mapDiv");
    if (!mapDiv)
        return;

    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.Util.onImageLoadErrorColor = "transparent";
    
	var options = {
	//TODO: put greece and europe bounds here
			maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
            numZoomLevels: 18,
            maxResolution: 156543.03390625,
            units: 'm',
            projection: new OpenLayers.Projection("EPSG:41001"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
			controls: [
				mouseDefaults,
				layerSwitcher,
				new OpenLayers.Control.ScaleLine(),
				//new OpenLayers.Control.MousePosition(),
				new OpenLayers.Control.PanZoomBar(),
				new MyRoute.Control.Logo("assets/infotrip.png", new OpenLayers.Size(93, 32))
			]
		};

	map = new OpenLayers.Map("mapDiv", options);

	var baselayer = new OpenLayers.Layer.TMS(
		"backgr",
		["http://tms1.infotrip.gr/"],
		{ layername: "europe0909", type: 'png', displayInLayerSwitcher: false}
		);
    baselayer.transitionEffect = 'resize';
	map.addLayer(baselayer);
	
	/* STRATEGY */
	OpenLayers.Strategy.BBOX.prototype.merge = function(resp) {
		
		var newFeaturesByDataId = {};
		var newFeatures = resp.features;
		
		if (newFeatures && newFeatures.length > 0)
		{
			var reallyNewFeatures = [], reallyOldFeatures = [];
			for(var i=0, len=newFeatures.length; i<len; i++)
			{
				var newFeature = newFeatures[i];
				var did = newFeature.attributes.id;
				
				var mustAdd = true;
				if (this.featuresByDataId)								// If there are old features
				{
					var oldFeature = this.featuresByDataId[did];		// Get the old feature with the same data id
					
					if (oldFeature)										// If it exists
					{
						newFeature.destroy();							// destroy the new feature
						newFeaturesByDataId[did] = oldFeature;			// keep the old feature as new
						mustAdd = false;
					}
				}
				if (mustAdd)
				{
					newFeaturesByDataId[did] = newFeature;
					reallyNewFeatures.push(newFeature);
				}
			}
			
			// Remove all old features that doesn't exist still
			for(var i=0, len=this.layer.features.length; i<len; i++)
			{
				var oldFeature = this.layer.features[i];
				var did = oldFeature.attributes.id;
				
				if (!newFeaturesByDataId[did])
				{
					reallyOldFeatures.push(oldFeature);
					if (oldFeature.popup)					// if the feature has a popup, destroy it
					{
						this.layer.map.removePopup(oldFeature.popup);
						oldFeature.popup.destroy();
						oldFeature.popup = null;
					}
				}
			}
			this.layer.destroyFeatures(reallyOldFeatures);
			
			// Reproject and add the new features
            var remote = this.layer.projection;
            var local = this.layer.map.getProjectionObject();
            if(!local.equals(remote)) {
                var geom;
                for(var i=0, len=reallyNewFeatures.length; i<len; ++i) {
                    geom = reallyNewFeatures[i].geometry;
                    if(geom) {
                        geom.transform(remote, local);
                    }
                }
            }
            this.layer.addFeatures(reallyNewFeatures);
			this.featuresByDataId = newFeaturesByDataId;
		}
		else
		{
			this.layer.destroyFeatures();
			this.featuresByDataId = null;
		}
		
        this.layer.events.triggerEvent("loadend");
    };
	
	//
	// Markers
	//
	var markers;
	var pc=POICATEGORIES;
	var pclen = pc.length;
	for(var i=0; i<pclen; i++) {
	    //SHOW THE HOTELS ONLY
	    if(pc[i].id == 11)
	    {
		    var c = pc[i];
		    //addPOIs(c.name, makeIcon(c.iconUrl, c.iconWidth, c.iconHeight, c.iconDx, c.iconDy), c.id);
		    var l = addPOIs(c.name, c.iconUrl, c.id);
		    poiLayers.push(l);
		    poiLayersById[c.id] = l;
		}
	}
	
	//
	// Pointer
	//
	pointer=new OpenLayers.Layer.Vector(
		"Pointer",
		{
			isBaseLayer: false,
			displayInLayerSwitcher: false
			//,rendererOptions: { yOrdering: true }
			,styleMap: new OpenLayers.StyleMap({
			    "default": new OpenLayers.Style({
					    externalGraphic: "assets/poi_icons/small/pinpoint.png",
					    pointRadius: 18,
					    graphicXOffset: -2,
					    graphicYOffset: -48
				    }),
				"select": {
				    pointRadius: 20
				}
			})
		}
	);
	map.addLayer(pointer);
	
    var tmp=poiLayers.concat([pointer]);

	var selector = new OpenLayers.Control.SelectFeature(
		tmp, {
			hover: false,
			toggle: true,
			onSelect: onFeatureSelect,
			onUnselect: onFeatureUnselect
		}
	);
	map.addControl(selector);
	selector.activate();

	var centerPoint = OpenLayers.Projection.transform(new OpenLayers.Geometry.Point(23.80258, 38.30758), map.displayProjection, map.projection);
	map.setCenter(
		new OpenLayers.LonLat(centerPoint.x, centerPoint.y),
		7,
		false,
		false);
		
	//
	//
	//
	OpenLayers.Rico.Corner.changeOpacity(layerSwitcher.layersDiv, 0.85);
	layerSwitcher.baseLayersDiv.style.cssFloat = "left";
	layerSwitcher.baseLayersDiv.style.styleFloat = "left";
	layerSwitcher.layersDiv.className="lsLayersDiv";
	layerSwitcher.dataLbl.innerHTML = "σημεία ενδιαφέροντος";
	layerSwitcher.dataLbl.className = "lsTitle";
	layerSwitcher.dataLayersDiv.id = "lsdataLayersDiv";
	layerSwitcher.maximizeDiv.innerHTML = '<div id="OpenLayers_Control_MaximizeDiv_inner">βρείτε&nbsp;στο&nbsp;χάρτη...</div>';
	OpenLayers.Rico.Corner.round(layerSwitcher.maximizeDiv, {corners: "tl bl",
									bgColor: "transparent",
									color: layerSwitcher.activeColor,
									blend: false});
									
}

function transformCoords(wgsX, wgsY)
{
	var mapProj = map.getProjectionObject();
	var point = OpenLayers.Projection.transform(
		new OpenLayers.Geometry.Point(wgsX, wgsY), 
		map.displayProjection, 
		mapProj);
	return point;
}
function invertTransformCoords(mapx, mapy){
	var mapProj = map.getProjectionObject();
	var point = OpenLayers.Projection.transform(
		new OpenLayers.Geometry.Point(mapx, mapy),
		mapProj,
		map.displayProjection);
	return point;
}

function setPointer(ll, markerName)
{
	pointer.removeFeatures(pointer.features);
	if (ll) {
	    var f = new OpenLayers.Feature.Vector(
				new OpenLayers.Geometry.Point(ll.lon, ll.lat)
			);
		var tmp=(markerName)?markerName:"";
		f.attributes = {name: markerName, id: -1};
		var features = [f];
		pointer.addFeatures(features);
	}
}
function setPointerPOI(ll, poiID, markerName)
{
	pointer.removeFeatures(pointer.features);
	if (ll) {
	    var f = new OpenLayers.Feature.Vector(
				new OpenLayers.Geometry.Point(ll.lon, ll.lat)
			);
		var tmp=(markerName)?markerName:"";
		f.attributes = {name: markerName, id: poiID};
		var features = [f];
		pointer.addFeatures(features);
	}
}
function centerAndZoomAt(thex, they, addMarker, markerAddress){
    var p=transformCoords(thex, they);
    var ll=new OpenLayers.LonLat(p.x, p.y);
	map.setCenter(
		ll,
		15,
		false,
		false);
	if(addMarker)
	    setPointer(ll, markerAddress);
}
function centerAndZoomAtPOI(thex, they, poiID, markerName){
    var p=transformCoords(thex, they);
    var ll=new OpenLayers.LonLat(p.x, p.y);
	map.setCenter(
		ll,
		15,
		false,
		false);
    setPointerPOI(ll, poiID, markerName);
}

function openHotelsCategory(){
    poiLayersById[11].setVisibility(true);
}

function onFeatureSelect(f)
{
	if (!f.popup)
	{
	    var hasData=(f.attributes.id==-1);
	    var n=htmlEscape(f.attributes.name);
	    var p=invertTransformCoords(f.geometry.x, f.geometry.y);
	    var setAsParam=n+'|'+p.x+'|'+p.y;
        var s=(hasData)?'<div class="poiPopupSimple">':'<div class="poiPopupContent">'+n;
        if(!hasData)
            s+='<br /><span><img src="images/ajax-loader.gif"></span><br /></div>';
        else{
            s+='<span class="popTitle">'+n+'</span></div>';
            //s+='<div><a href="#" onclick="setAsO(\''+setAsParam+'\')" >από εδώ: <img width="16" height="16" src="assets/setorigin.png"/></a>&nbsp;|&nbsp;';
            //s+='<a href="#" onclick="setAsD(\''+setAsParam+'\')" >έως εδώ: <img width="16" height="16" src="assets/setdestination.png"/></a></div>';
        }
        var anchor=null;
        if(f.layer==pointer)
            anchor={size: new OpenLayers.Size(36, 36), offset: new OpenLayers.Pixel(18, -18)};
		f.popup = new OpenLayers.Popup.ShadowFramedCloud(null, 
			new OpenLayers.LonLat(f.geometry.x, f.geometry.y), 
			new OpenLayers.Size(300, 200), 
			s, 
			anchor, 
			false, 
			null);
		f.popup.disableFirefoxOverflowHack=false;
		f.popup.feature = f;
		map.addPopup(f.popup, true);
		f.popup.hasData=hasData;
	}
	else
	{
		f.popup.show();
	}
	
	if(!f.popup.hasData)
    {
        //var params={mode: "poipopup", pid: f.attributes.id};
        var params='mode=poipopup&pid='+f.attributes.id;
        var _f = f;
        ajax('myroute/olPOIs.aspx', 'POST', params, function(result){
            if (_f.popup)
            {
                _f.popup.setContentHTML(result);
                _f.data.overflow='auto';
                /*var div=_f.popup.contentDiv.firstChild;
                div.innerHTML = result;*/
                //_f.popup.contentHTML=result;
                _f.popup.hasData = true;
                window.f=_f;
            }
        });
    }
}
function flashMovie(movieName) {
  if (navigator.appName.indexOf("Microsoft") != -1) {
      return window[movieName];
  } else {
      return document[movieName];
  }
}
function setAsO(value){
    flashMovie('OLroutes').jscrSetAsO(value);
}
function setAsD(value){
    flashMovie('OLroutes').jscrSetAsD(value);
}
function onFeatureUnselect(f)
{
	if (f.popup)
	{
		map.removePopup(f.popup);
		f.popup.destroy();
		f.popup = null;
	}
}

function addPOIs(name, icon, catId)
{
	var bbox = new OpenLayers.Strategy.BBOX();
	bbox.resFactor = 1.5;
	
	var format = new MyRoute.Format.JSONPOI({
//				internalProjection: new OpenLayers.Projection("EPSG:4326"),
//				externalProjection: map.getProjectionObject()
			});
	var url = "myroute/olPOIs.aspx?mode=pois&cat="+catId;
	
	poiLayer = new OpenLayers.Layer.Vector(name,{
		projection: new OpenLayers.Projection("EPSG:4326"),
		rendererOptions: {yOrdering: true},
		strategies: [bbox],
		protocol: new OpenLayers.Protocol.HTTP({
			url: url,
			params:{
				insrs: "4326",
				maxfeatures: 100,
				bbox: [-20037508.34,-20037508.34,20037508.34,20037508.34]
			},
			format: format
		}), 
		styleMap: new OpenLayers.StyleMap({
			"default": new OpenLayers.Style({
					externalGraphic: icon,
					pointRadius: 10,
					graphicTitle: "${tooltip}"
					/*
					graphicWidth
					graphicHeight
					graphicOpacity
					graphicXOffset
					graphicYOffset
					graphicName
					graphicTitle
					*/
				}, {
					context: {
						tooltip: function(feature) {
							return feature.data.name;
						}
					}
				}),
			"select": {
				pointRadius: 12
			}
		})
	});
	poiLayer.setVisibility(true);

	map.addLayer(poiLayer);
	return poiLayer;
}
function displayCategories(splitCategories){
    var parts=splitCategories.split('|');
    for(var i=0;i<parts.length;i++){
        var l=poiLayersById[id];
        if(l){
            l.setVisibility(true);
        }
    }    
}
function displayNoCategory(){
    var l;
    for(var i=0;i<poiLayers.length;i++){
        l=poiLayers[i];
        l.setVisibility(false);
    }
}
function displayRoot(theRootID)
{
    if(routeLayer)
    {
        map.removeLayer(routeLayer);
        routeLayer.destroy();
        routeLayer=null;
    }
    
    routeLayer = new Mpk.RouteLayer(
	    "Route",
	    "myroute/olProxy.aspx?routeid="+ theRootID+"&srs=EPSG:41001",
	    []);
    map.addLayer(routeLayer);
    routeLayer.events.register("loadend", routeLayer, zoomToRoute);
    zoomToRoute();
}
function zoomToRoute()
{
    if(routeLayer)
	    map.zoomToExtent(routeLayer.getDataExtent());
}

function makeIcon(imageUrl, sizeX, sizeY)
{		
	var icon = new OpenLayers.Icon(imageUrl, new OpenLayers.Size(sizeX, sizeY));
	icon.offset = new OpenLayers.Pixel(-sizeX/2, -sizeY);
	return(icon);
}

function showFeaturePopup(f)
{
    if (lastFeaturePopup != null
        && lastFeaturePopup != f)
    {
        if (lastFeaturePopup.popup.visible())
             lastFeaturePopup.popup.hide();
    }
    
    if (f.popup == null)
    {
        f.popup = f.createPopup(true);
        map.addPopup(f.popup);
        f.popup.show();
    }
    else
    {
        f.popup.toggle();
    }
    lastFeaturePopup = f;    
}
function htmlEscape(html)
{
    if (escaper == null)
        escaper = document.createElement("div");
	escaper.innerHTML = html;
	if ("textContent" in escaper)
	    return (escaper.textContent);
	else
	    return (escaper.innerText);
}
function REQ()
{
	var req;
	
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
			}
		}
	} 
	return(req);
}
function ajax(url, method, data, f)
{
	var req = REQ();
	if (req)
	{
		method = method || "GET";
		data = data || '';
		var isPost = method.toLowerCase && method.toLowerCase() == "post";
		if (f) {
			req.onreadystatechange = function() { ajaxRSC(req, f); };
			req.open(method, url, true);
			if (isPost)
			{
				req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				req.setRequestHeader("Content-length", data.length);
				req.setRequestHeader("Connection", "close");
			}
			req.send(data);
		} else {
			req.open(method, url, false);
			if (isPost)
			{
				req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				req.setRequestHeader("Content-length", data.length);
				req.setRequestHeader("Connection", "close");
			}
			req.send(data);
			if (req.status == 200)
				return(req.responseText);
			return (null);
		}
    }
}
function ajaxRSC(req, f)
{
	if (req.readyState == 4) {
		if (req.status == 200) {
			f(req.responseText);
		}
	}
}

