var mdvJpMaps = new Array();
var imgPath = 'images/mdvMap/stopSymbols/';
var displayedTrip = '';

function onLoadMapHandler(type) {
    
    initMdvMapConfig(type);
	if (mdvJpMaps[type] == null){
		mdvJpMaps[type] = new MDVMapHelper(type);
	}
	if(document.getElementById('journey_0')){
        var journeys = $(".journey");
		var tripSelector = journeys.length === 1 ? 1: (openJourney > journeys.length ? 2 : openJourney);
		var sessionID = document.getElementById('sessionID').value;
		var requestID = document.getElementById('requestID').value;	
        var fullTrip = true;	
		mdvJpMaps[type].displayJourney(sessionID, requestID, tripSelector, fullTrip);
	} 
}

// This function loads the map
function MDVMapHelper(type) {
	this.mdvMap = null;
	this.markerLayer = null;
	this.type = type;
    this.trips = null;
    this.size = 'small';

    this.mdvMap = new MDVMap(document.getElementById('mdvMap'));

    this.ctxMenuArr = new Array();
    this.ctxMenuArr[0] = new MDVMapMenuItem('Route von hier', this.setCoordinatesOrigin.bind(this));
    this.ctxMenuArr[1] = new MDVMapMenuItem('Route hierher', this.setCoordinatesDestination.bind(this));
    this.ctxMenu = new MDVMapMenu(this.ctxMenuArr);
    new MDVMapContextMenu(this.mdvMap, this.ctxMenu);
    
    this.mdvMap.events.registerEvent(MDVEvent_CONTEXT_MENU, null, this.contextMenuHandler);
     
    mdvMapNav = new MDVMapNavigator(this.mdvMap);
    
    this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
    this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.submitPoint);
    this.mdvMap.events.registerEvent(MDVEvent_AJAX_CALLBACK, this, this.processPinsEx);
    this.mdvMap.events.registerEvent(MDVEvent_ZOOM_CHANGED, this, this.checkZoomLevel);
    
        
    new MDVMapEFAInfoEx(this.mdvMap, {imagePath: imgPath, alignment: new MDVPoint(0.5, 0.5)});
    
    this.trips = new MDVMapEFATrips(this.mdvMap);
    
    this.markerLayer = this.mdvMap.createLayer('layoutMarkers');
    this.markerLayer.id = 1;
    this.markerLayer.setZIndex(50);
    this.mdvMap.addLayer(this.markerLayer);
    
    new MDVMapControl(this.mdvMap, {
        posTop: '0px',
        posLeft: '0px'
    });
    
   this.execute();
}

MDVMapHelper.prototype.checkZoomLevel = function(index) {

	var zoomLevel = this.mdvMap.config.getZoomLevel(this.mdvMap.config.getZoomLevelIndex());
	var showStops = zoomLevel.get('showSTOP') == "true";
	var showPOI   = zoomLevel.get('showPOI') == "true";
    
  	if (showStops || showPOI) {
  		//alert('true')
  	} else {
        $('#displayStop').css('display', 'none')
        $('#displayPoi').css('display', 'none')
  	}  
}


MDVMapHelper.prototype.processPinsEx = function(id, gadName, request) {

  	if (gadName != 'MDVMapEFAInfoEx' || this.size=='small') {
  		return false;
    }
    
    $('#stopList').html('');
    $('#poiList').html('');
    
    var pins = request.pins;
    
    for(i=0;i <pins.length;i++){
    
        var select = 'stopList';
        
        if(pins[i].type.indexOf('POI')!='-1'){
            select = 'poiList';
        }
        var text = pins[i].desc;
        
        if(select=='stopList'){
            text += ' (' + pins[i].locality + ')';
        }
        
        var val =   pins[i].id + '$' +pins[i].omc;
        var newChild = new Option
        newChild.innerHTML = text;
        newChild.value = val;
        newChild.title = text;
        $('#' +select).append(newChild);
        //$('#' +select).append( new Option(text,val) );
    }
    
    if($('#stopList option').length > 0){
        $('#displayStop').css('display', 'inline')
    }
    else{
     $('#displayStop').css('display', 'none')
    }
    
    if($('#poiList option').length > 0){
        $('#displayPoi').css('display', 'inline')
    }
    else{
        $('#displayPoi').css('display', 'none')
    }
}


function submitMapList(objType, usage){

	var form = document.forms[0];

	var name 		= document.getElementById('nameInfo_' + usage);
	var place 		= document.getElementById('placeInfo_' + usage);
	var placeState 	= document.getElementById('placeState_' + usage);
	var type 		= document.getElementById('typeInfo_' + usage);
	var deleteAssignedStops = document.getElementById('deleteAssignedStops_' + usage);
    

	switch (objType.toLowerCase()) {
		case 'stop':
			name.value = $('#stopList option:selected').val().split('$')[0];
			type.value = 'stopID';
			placeState.value = 'empty';
			place.value = '';
			deleteAssignedStops.value='1';
			break;
		case 'poi':
		case 'poi_point':
		case 'poi_area':
			place.value = $('#poiList option:selected').val().split('$')[1] + ':-1';
			name.value = $('#poiList option:selected').val().split('$')[0].substring(4,20);
			type.value = 'poiID';
			break;
	}
	
    document.forms[0].submit();

}


MDVMapHelper.prototype.execute = function () {

    this.mdvMap.execute(mdvMapConfig);

    var mdvMapSlider = new MDVMapSlider(this.mdvMap, {
        sliderOffsetTop: 57,
        sliderOffsetLeft: 20,
        tickOffsetLeft: 5
   });
   
   if($('#nameX_origin').val() > 0 && $('#nameState_destination').val()!='identified'){
        var x =$('#nameX_origin').val()
        var y = $('#nameY_origin').val()
        var name = $('#nameDisplay_origin').val()
   
        var tool = this.mdvMap.createToolTip(new MDVPoint(218, 120), name);
        var coord = new MDVCoordinates(this.mdvMap.config.params.mapName, x,y);
        var origMarker = this.mdvMap.createMarker(coord, new MDVPoint(0.1, 0.9), this.getImage('origin'));
        
       this.markerLayer.addMarker(origMarker); 
       
       var zoomLvl = 5;
       
       if($('#place_origin').val() == jQuery.trim($('#name_origin').val())){
        zoomLvl = 3
       }
       
       this.zoomCoord(x,y, zoomLvl)
   }
   
   if($('#nameX_destination').val() > 0 && $('#nameState_origin').val()!='identified'){
        var x =$('#nameX_destination').val()
        var y = $('#nameY_destination').val()
        var name = $('#nameDisplay_destination').val()
   
        var tool = this.mdvMap.createToolTip(new MDVPoint(218, 120), name);
        var coord = new MDVCoordinates(this.mdvMap.config.params.mapName, x,y);
        var destMarker = this.mdvMap.createMarker(coord, new MDVPoint(0.1, 0.9), this.getImage('destination'));
        
       this.markerLayer.addMarker(destMarker); 
       
       var zoomLvl = 5;
       
       if($('#place_destination').val() == jQuery.trim($('#name_destination').val())){
        zoomLvl = 3
       }
       
       this.zoomCoord(x,y, zoomLvl)
   }
    
}


// This function returns the marker image.
MDVMapHelper.prototype.getImage = function(usage) {
	var img = '/mdv/mdvStandardLayout2/images/mdvMap/transparent.gif';
	
	if(!usage){
		usage= 'transparent';
	}

	switch(usage) {
		case 'origin':
			img = '/mdv/mdvStandardLayout2/images/mdvMap/origin.gif';
			break;
		case 'destination':
			img = '/mdv/mdvStandardLayout2/images/mdvMap/destination.gif';
			break;
		case 'via':
			img = '/mdv/mdvStandardLayout2/images/mdvMap/via.gif';
			break;
		default:
		img = '/mdv/mdvStandardLayout2/images/mdvMap/' +usage +'.gif'
	}
	
	var i = new Image();
	i.src = img;

	return img;
};


//function ContextMenuHandler(id, status, obj) {
MDVMapHelper.prototype.contextMenuHandler = function (id, status, obj) {

	if(status == true) {
		ctxCoords = obj;
	}
}


//this function create a tooltip
MDVMapHelper.prototype.onToolTip = function(id, msg, obj) {
    var txt = obj.innerHTML;
    var container = obj.container;
    if (!container){
        return;
    }
    var size = container.getSize();
    
    if(this.size=='small'){
        size = new MDVPoint(150, 80)
        obj.setPin(false);
    }  
    
    // correct MOT text
    if (txt === '100') {
        obj.setInnerHTML(means_100);
    }
    
    if(obj.container){
        obj.container.setSize(size);
        obj.container.update();
        obj.container.updateBubble();
    }
        
	if(!obj.getParent().objectId || this.size=='small'){
		return false;
	}
    
    var type = obj.getParent().objectId.type;
	
    if( type=='STOP' || type=='BUS_POINT'){
        
        var dmId = obj.getParent().objectId.id
        
      if (obj.processed == null) {
         var text = '<div class="fixed">' + obj.getInnerHTML() + '</div>';
            text += '<br/>';
            text += '<div id="dm_'+ dmId + '" class="dm_content">Loading... </div>'; 
            obj.setInnerHTML(text);
            obj.update();

            obj.dm = new MDVEFADepartureMonitor(dmId, 'XSLT_DM_REQUEST'); 
            obj.dm.getDepartures(dmId);  
            obj.processed = true; 
        }
        else { 
            obj.dm.getDepartures(dmId);
        } 
    
        return;
    }
	// POIS with Links and Address
	else if (type.toLowerCase()=='poi_area' || type.toLowerCase()=='poi_point' || type.toLowerCase()=='poi') {
		
			var link ='';
	
			for (var i=0; i < obj.getParent().getObjectId().attrs.length; i++) {
				var a = obj.getParent().getObjectId().attrs[i];

				if (a.name == 'POI_LINK') { 		
					link = link + '<a href="' + a.value.substring(a.value.indexOf('$') +1) 
						   + '" target="_blank">' 
						   + a.value.substring(0, a.value.indexOf('$')) + '</a><br/>';
				}
			} 
			
			for (var i=0; i < obj.getParent().getObjectId().attrs.length; i++) {
				var a = obj.getParent().getObjectId().attrs[i];

				if (a.name == 'POI_ADDRESS') {
					link += '<br/>Adresse: ' + a.value;
				}							
			}	
			
			obj.setInnerHTML('<b>'
				+ obj.getParent().objectId.desc
				+ '</b><br/>'
				+ link
				+''); 
	} 

};

// this function submit a point from the tooltip
MDVMapHelper.prototype.submitPoint = function(id, msg, obj) {

    if(obj.marker.objectId.right==true){
        return false;
    }

	var form = document.forms[0];
    
    var usage ='origin';
    
    if($('#nameState_origin').val()=='identified'){
        usage ='destination';
    }

	var name 		= document.getElementById('nameInfo_' + usage);
	var place 		= document.getElementById('placeInfo_' + usage);
	var placeState 	= document.getElementById('placeState_' + usage);
	var type 		= document.getElementById('typeInfo_' + usage);
	var deleteAssignedStops = document.getElementById('deleteAssignedStops_' + usage);
	
	switch (obj.type.toLowerCase()) {
		case 'stop':
			name.value = obj.id;
			type.value = 'stopID';
			placeState.value = 'empty';
			place.value = '';
			this.mdvMap.mapper.style.cursor = 'wait';
			deleteAssignedStops.value='1';
			break;
		case 'poi':
		case 'poi_point':
		case 'poi_area':
			place.value = obj.omc + ':-1';
			name.value = obj.id.substring(4,20);
			type.value = 'poiID';
			this.mdvMap.mapper.style.cursor = 'wait';

			break;
		case 'coord':
			if (obj.id)
				return;
			name.value = obj.x + ':' + obj.y + ':' + obj.mapName + ':' + obj.name;
			type.value = 'coord';
			placeState.value = 'empty';
			place.value = '';
			this.mdvMap.mapper.style.cursor = 'wait';
			break;
	}
	
    document.forms[0].submit();
};

// This context menu functions submits a selected point.
MDVMapHelper.prototype.setCoordinatesOrigin = function() {
	this.setCoordinates('origin');
};

MDVMapHelper.prototype.setCoordinatesDestination = function() {
	this.setCoordinates('destination');
};

MDVMapHelper.prototype.setCoordinates = function(usage) {

	if (this.mdvMap) {
		var text = '';

		document.getElementById('nameInfo_' + usage).value = parseInt(ctxCoords.x) + ':' + parseInt(ctxCoords.y) + ':' + ctxCoords.mapName + ':' + text; 

		document.getElementById('typeInfo_' + usage).value = 'coord';
		document.getElementById('nameState_' + usage).value = 'notidentified';

		if (document.getElementById('placeState_' + usage)){
			document.getElementById('placeState_' + usage).value = 'notidentified';
        }

		if (document.getElementById('placeInfo_' + usage)){
			document.getElementById('placeInfo_' + usage).value = '';
        }
		
		this.mdvMap.mapper.style.cursor = 'wait';

		document.getElementById('execInst').value = 'normal';
		document.forms[0].submit();
	}

};

MDVMapHelper.prototype.zoomCoord = function (x, y, zoomLvl) {

    if(!zoomLvl){
        zoomLvl = 5
    }

    this.mdvMap.setCentre(new MDVCoordinates(this.mdvMap.config.get('mapName'), x, y));
    this.mdvMap.setZoomLevel(zoomLvl);
	this.mdvMap.update()
}

MDVMapHelper.prototype.displayJourney = function(sessionID, requestID, tripIndex, fullTrip) {

	if(!sessionID){
		sessionID = document.getElementById('sessionID').value
	}
	
	if(!requestID){
		requestID = document.getElementById('requestID').value
	}
	
	if(!tripIndex){
		tripIndex ='1'
	}
	
	this.trips.loadTrip(sessionID, requestID, tripIndex, fullTrip);
	this.mdvMapTripsLoaded = true;
    
    displayedTrip = tripIndex;
    
    // set label
    if (document.getElementById('openedJourney') && document.getElementById('journeyValue_' + tripIndex)) {
        document.getElementById('openedJourney').innerHTML = document.getElementById('journeyValue_' + tripIndex).innerHTML;
    }
}

// Clears all journeys on the map.
MDVMapHelper.prototype.clearJourneys = function () {
    // clear all journeys
	this.trips.clear();
    
    displayedTrip = '';
    
    // set label
    if (document.getElementById('openedJourney')) {
        document.getElementById('openedJourney').innerHTML = '';
    }
}



//departure board
function MDVEFADepartureMonitor(id, url) {
    this.id 	= id;
    this.url 	= url;
}

// request departures (AJAX)
MDVEFADepartureMonitor.prototype.getDepartures = function(identifier) {

	var stopID = this.id;
    
	if(isNaN(stopID) && stopID.indexOf('|')!='-1'){
		stopID = stopID.substring(0,stopID.indexOf('|'));
	}

	var _params = { 
		language: mapLanguage, 
		name_dm: stopID, 
		type_dm: 'stopID', 
		mode: 'direct', 
        limit: '5',
	    limitEachStop: '1', 
	    itdLPxx_id: identifier , 
		itdLPxx_page: 'tooltip', 
		deleteAssignedStops_dm:'1'
		};
 
    var _ajax = mdvLib.ajax({ host: this.url, parameters: _params, 
                                  onComplete: MDVEFADepartureMonitor_onAjaxComplete.bind(this) });
}

// get the HTML code for departure monitor
function MDVEFADepartureMonitor_onAjaxComplete(request) {

    if (request.responseText) {
		var target = document.getElementById('dm_'+ this.id);
        if(target){
            target.innerHTML = request.responseText;
        }
     }
     
}

// This function sets the parameters for the request and submits the form
function submitStop(id, usage){

    
	var type = 'stopID';
	var odvID = id;

    if(document.getElementById('nameInfo_' + usage)){
        document.getElementById('placeInfo_' + usage).value = '';	
        document.getElementById('typeInfo_' + usage).value = type;
        document.getElementById('nameInfo_' + usage).value = odvID;

                
    	if (document.forms[0].execInst){
    		document.forms[0].execInst.value = 'verifyOnly';
    	}
    		
    	document.forms[0].submit();
    }
};
