var tmcLayerId = 'TMC_LINIEN';
var tmcLayer = null;

function makeTMCLayer(layerTitle, layerName, shapeName, idfLayerName)
{
    var layer = new IWLayer(map, layerTitle, layerName, idfLayerName);
    layer.addShape(new IWShape(shapeName));

    var requestLayer = new IWRequestLayer(layer);
    requestLayer.registerEvent('onclick');

    map.getLayerInfoManager().addRequestLayer(requestLayer);

    var removeListener = IWEventManager.addListener(layer, 'onremove', function(e)
		{
        	map.getLayerInfoManager().removeRequestLayer(requestLayer);
            IWEventManager.removeListener(requestListener);
            IWEventManager.removeListener(removeListener);
        }
    );
    return layer;
}

function formatTMCPro(record,firstContent,moreTargets)
{
	var div = document.createElement('div');
	div.style.position = 'relative';
	var iconDiv = document.createElement('div');
	iconDiv.style.position = 'absolute';
	iconDiv.style.width = '40px';
	iconDiv.style.top = '0px';
	iconDiv.style.left = '0px';
	
    if(firstContent == false || moreTargets==true){
		iconDiv.style.top = '10px';
	    div.appendChild(createEmptyParagraph('10px'));
	}

    div.appendChild(iconDiv);
	iconDiv.appendChild(addTMCIcon(parseInt(record.EvtEffCode)));

	var arr_date = record.DateNow.substring(0, 10).split("-");
	var arr_time = record.DateNow.substring(11).split(":");
    var arr_dateStart = record.DateStart.substring(0, 10).split("-");
	var arr_timeStart = record.DateStart.substring(11).split(":");
    var formattedDate = arr_date[2] + "." + arr_date[1] + "." + arr_date[0] + " " + arr_time[0] + ":" + arr_time[1];
    var formattedDateStart = arr_dateStart[2] + "." + arr_dateStart[1] + "." + arr_dateStart[0] + " " + arr_timeStart[0] + ":" + arr_timeStart[1];

    var text = 'Auf der <b>' + record.xmlRoad + ' von ' + record.DirFrom + ' nach ' + record.DirTo + ' </b>';
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));

    text = (record.xmlLocTo.length == 0 ? 'bei ' + record.xmlLocFrom : 'zwischen ' + record.xmlLocFrom + ' und ' + record.xmlLocTo) + ' ' ;
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));
    text =  '<b>' + record.EvtEffTxt  + '</b>' + ' '+ (record.EvtCauTxt.length == 0 ? '' : 'wegen ' + record.EvtCauTxt);
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));

    text = (record.AvSpeed == '0' ? '' : '( zu erwartende Geschwindigkeit ' + record.AvSpeed + ' km/h)')   ;
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));
     
    text = 'Beginn: ' + formattedDateStart   ;
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));
    text = 'Stand: ' + formattedDate  ;
    text = text.replace(/\u0020/g, '&nbsp;');
    div.appendChild(createTextParagraphTMC(text));

	return div;
}

/*
 * Returns an corresponding image for the TMC code.
 *
 * @param {int} code
 * @return {Image} img
 */
function addTMCIcon(code)
{
	var img = document.createElement('img');

	if (code == 26 || code == 27)
	{
		img.src = iwconst.GLOBAL_APP_URL+'/img/symbols/tmc/tmc_verengung.png';
	}
	else if (code == 28 || code == 44 || code == 45 || (code >= 62 && code <= 65))
	{
		img.src = iwconst.GLOBAL_APP_URL+'/img/symbols/tmc/tmc_sperrung.png';
	}
	else if (code >= 30 && code <= 38)
	{
		img.src = iwconst.GLOBAL_APP_URL+'/img/symbols/tmc/tmc_baustelle.png';
	}
	else if (code == 51 || (code >= 74 && code <= 174))
	{
		img.src = iwconst.GLOBAL_APP_URL+'/img/symbols/tmc/tmc_vorsicht.png';
	}
	else
	{
		img.src = iwconst.GLOBAL_APP_URL+'/img/symbols/tmc/tmc_stau.png';
	}

	return img;
}
 
	function isControlPositionOverlap(addressSearchControl, infoBalloon) {

	       var offset = 15;
	        if (addressSearchControl && infoBalloon.getContainer().parentNode != null) {

	            var positionAddressSearchControl = iw.absolute(addressSearchControl.getContainer(), map.getContainer());
	            var addressSearchControl_X1 = positionAddressSearchControl.getX();
	            var addressSearchControl_X2 = positionAddressSearchControl.getX() + addressSearchControl.getSize().getWidth();
	            var addressSearchControl_Y1 = positionAddressSearchControl.getY() + 70 ;    // 70 von Oben bis zum Combobox
	            var addressSearchControl_Y2 = positionAddressSearchControl.getY() + addressSearchControl.getSize().getHeight() - 100;    // 100Stift Größe

	           
	            var positionInfoBalloon = iw.absolute(infoBalloon.getContainer(), map.getContainer());

	            var infoBalloon_X1 = positionInfoBalloon.getX()+ offset;
	            var infoBalloon_X2 = positionInfoBalloon.getX() + infoBalloon.getSize().getWidth()- offset;
	            var infoBalloon_Y1 = positionInfoBalloon.getY();
	            var infoBalloon_Y2 = positionInfoBalloon.getY() + infoBalloon.getSize().getHeight() - 70;


	            if (addressSearchControl_X1 >= infoBalloon_X2  ||
	                addressSearchControl_X2 <= infoBalloon_X1  ||
	                addressSearchControl_Y2 <= infoBalloon_Y1 ||
	                addressSearchControl_Y1 >= infoBalloon_Y2) {
	                return false;
	            }
	           return true;

	        }
	       return false;

	    }
		
	function openInfoBalloon()
	{
		var innerHTML = '<b>Willkommen bei der <br>Map and Route GmbH & Co. KG</b>' +
	            '<table style="margin-top:15px">' +
	            '<tr><td><div class="bgControls MaR_Luftbild"></div></td>' +
	            '<td style="padding-left:3px"><p>Map and Route GmbH & Co. KG</p>' +
	            'Pretzfelder Straße 7-11<br>' +
	            '90425 Nürnberg' +
	            '</td></tr></table>';

		var div = document.createElement('div');
		div.style.width = '260px';
		div.style.height = '150px';
		div.style.position = 'relative';

		div.innerHTML = innerHTML;
	    marInfoBalloon =  createMarInfoBalloon(marker.getCoordinate(), div);
	    IWEventManager.addListener(marInfoBalloon.getCloseElement(), 'onclick',
	            function(e) {
	                marInfoBalloon.setVisible(false);
	                addressSearchControl.setCoutryCB();
	                map.removeWindowOverlay(marInfoBalloon);
	            }
	            );
	    map.addWindowOverlay(marInfoBalloon);
		
	}
 
    function createInfoBalloon(coordinate, content,moreTargets)
    {
        var myContent = updateContent(content);
        var left = myContent.style.left == '' ? 0 : parseInt(myContent.style.left);
        var top = myContent.style.top == '' ? 0 : parseInt(myContent.style.top);
        var contentSize = updateContentSize(myContent);

        // remove other infoballoon
        if (infoBalloon != null) {
            map.removeWindowOverlay(infoBalloon);
            infoBalloon.destroy();
            infoBalloon = null;
        }

        // create a new infoballoon and put it on the map
        infoBalloon = new MarInfoBallonPOI(map, coordinate, myContent,moreTargets);  
        infoBalloon.setSize(new IWSize(contentSize.getWidth() + 20 + left, contentSize.getHeight()  + 58 + top));

        return   infoBalloon;

    };

    function closeTooltip()
    {
        window.clearTimeout(tooltipTimeout);
        map.removeTooltip();
    }
    
    function createTextParagraph(text,paddingLeft)
    {
        var p = document.createElement('p');
        p.style.margin = '0px';
        p.style.padding = '0px';
        p.style.color='#1B57B1';
        if(paddingLeft){
        	p.style.paddingLeft = paddingLeft;     
        }
        text = trim(text);		
        p.innerHTML = text;
        return p;
    }
    function createEmptyParagraph(lineHeight){
    	 var p = document.createElement('p');

         p.style.margin = '0px';
         p.style.padding = '0px';
 		 p.style.lineHeight = lineHeight;
         p.innerHTML = '&nbsp;';
         return p;

        
    }
    function createTextParagraphTMC(text)
    {
        var p = document.createElement('p');

        p.style.margin = '0px';
        p.style.padding = '0px';
        p.style.paddingLeft = '40px'; 
        p.style.color='#1B57B1';       
        p.innerHTML = text;
        return p;
    }
            
    function updateContent(content) {
        var myContent = null;

       
        if (content.constructor == String)
        {
            var elem = iw.checkElem(content);

            myContent = iw.create('div');
            myContent.style.top = '0px'
            myContent.style.left = '0px';
            myContent.style.overflow = 'auto';

            iw.append(myContent, elem);
        }
        else
        {
            myContent = content;
        }

        // we need relative positioning...
        myContent.style.position = 'relative';
        return myContent;
    }
	function formatZusatzContent(record,firstContent,moreTargets){
		
	     var ovlType = record.OVL_TYP;
	     if(ovlType == 'Geldautomaten'){
	    	var div =  formatGeldautomatenContent(record,firstContent,moreTargets);
	    	return div; 
	     }
	     if(ovlType == 'Apotheken'){
		    	var div =  formatApothekenContent(record,firstContent,moreTargets);
		    	return div; 
		     }

	     if(ovlType == 'Kino'){
	    	 var div =  formatKinoContent(record,firstContent,moreTargets);
		    	return div; 
		 }
		 if(ovlType == 'Event'){
	    	 var div =  formatEventContent(record,firstContent,moreTargets);
		    	return div; 
		 }
	     
	}
function formatEventContent(record,firstContent,moreTargets){
		
		var div = document.createElement('div');
		div.style.position = 'relative';	    
		var iconDiv = document.createElement('div');
		iconDiv.style.position = 'absolute';
		iconDiv.style.width = '40px';
		iconDiv.style.top = '5px';
		iconDiv.style.left = '0px';
		
		var img = document.createElement('img');			
		img.src = 'img/poi/event_luftballon.gif';
		iconDiv.appendChild(img); 
		
		if(firstContent== false || moreTargets == true){
			div.appendChild(createEmptyParagraph('10px'));
			iconDiv.style.top = '15px';
			iconDiv.style.paddingTop ='7 px';
		}
		if(firstContent == false &&  moreTargets==true){
	    	
			var divLine = getCutLine();
			div.appendChild(divLine);
			div.appendChild(createEmptyParagraph('10px'));
			iconDiv.style.top = '20px';
			iconDiv.style.paddingTop ='7 px';
		}
				
		div.appendChild(iconDiv);
			
		var location = record.location;
		
		var name = location.name ;
		
        var boldName = createTextParagraph(name.replace(/\u0020/g, '&nbsp;'),'40px');
        boldName.style.fontWeight = 'bold';
        boldName.style.color ='black';
        div.appendChild(boldName);
        	
        var id = location.id;
        var strasse = location.str;
        var hnr = location.hnr;
        var zip = location.zip;
        var city = location.city;
       
        var infofax = location.infofax;
        var infofax2 = location.infofax2;
        var infourl = location.infourl;
        if(infourl.length >0 && infourl.substring(0, 4)!='http'){
        	infourl = 'http://'+infourl;
        }
        var infourl2 = location.infour2;
        if(infourl2.length >0 && infourl2.substring(0, 4)!='http'){
        	infourl2 = 'http://'+infourl2;
        }
        var infomail = location.infomail;
        var infomail2 = location.infomail2;
        var infophone = location.infophone;
        var infophone2 = location.infophone2;

       
        
        	
       div.appendChild(createTextParagraph(strasse.replace(/\u0020/g, '&nbsp;') + '&nbsp;' + hnr,'40px'));
       div.appendChild(createTextParagraph(zip + '&nbsp;' + city.replace(/\u0020/g, '&nbsp;'),'40px'));
       div.appendChild(createEmptyParagraph('7px'));

      
       	
       var table = iw.create('table');
       table.style.cellspacing = '0';
       table.style.position ='relative';
       div.appendChild(table);
       var r =0;
		
      	var additionData = false;
      	
		if(infophone != undefined && infophone.length >0){
			additionData=true;	
			getAddData('Telefon: ',infophone,r,table);
			r++;
		}
		if(infophone2 != undefined && infophone2.length >0){
			additionData=true;	
			getAddData('Telefon: ',infophone2,r,table);
			r++;
		}
		 
		if(infofax != undefined && infofax.length >0){	
			additionData=true;	
			getAddData('Fax: ',infofax,r,table);	
			r++;
		}
		if(infofax2 != undefined && infofax2.length >0){	
			additionData=true;	
			getAddData('Fax: ',infofax2,r,table);	
			r++;
		}
		
		if(infourl != undefined && infourl.length >0){
			
			additionData=true;								
			getAddData('Internet: ','<a href="' + infourl + '" target="_blank">' + infourl + '</a>',r,table);
			r++;
		}
		
		if(infourl2 != undefined && infourl2.length >0){
			additionData=true;				
			getAddData('Internet: ', '<a href="' + infourl2 + '" target="_blank">' + infourl2 + '</a>',r,table);
			r++;
		}
		
		
		  	if(infomail != undefined && infomail.length >0){	
				additionData=true;	
				getAddData('E-Mail: ',infomail,r,table);	
				r++;
			}
		  	
		  	if(infomail2 != undefined && infomail2.length >0){	
				additionData=true;	
				getAddData('E-Mail: ',infomail2,r,table);	
				r++;
			}
		  	div.appendChild(createEmptyParagraph('5px'));	
		  		
		  	
		  	var url = 'http://'+document.domain+'/'+appName+'location.html?ID='+id+'&name='+name;	
		  	  	
		  	var a = '<a href="#" style="text-decoration:underline;" onclick="return showMoreInfo(\''+url+'\');">Mehr Information</a>'	;
		  	  
			var info = createTextParagraph(a,'10px');	
			info.style.textDecoration='underline';
			
			div.appendChild(info);		
		if(additionData==true){
			div.appendChild(createEmptyParagraph('5px'));			
		}
		 
		
		return div;

	}

function showMoreInfo(url){
	
	var contentString = "<iframe id='popupIframe' src='"+url+"' width='100%' marginwidth='0' height='100%' marginheight='0' scrolling='auto' allowtransparency='true' frameborder='0' style='position:absolute; left:0px; top:0px'></iframe>";
	showPopup(new IWSize(520, 360), null, contentString, true);

	

}

function showPopup(size, coordinate, contentString, centered){

	
	if (popupWindow != null)
	{
		iw.remove(popupWindow.getContainer());
		popupWindow = null;
	}
	
	if (coordinate == null)
		coordinate = map.getCenter();
	
	
	popupWindow = new IWWindowOverlayGS(map, coordinate, contentString);
	
    popupWindow.setVisible(false);
	popupWindow.setSize(size);
	
	if (centered == true)
		popupWindow.setCentered(true);

	
	iw.append(map.getWindowOverlayContainer(),popupWindow.getContainer());
	
	popupWindow.redraw();
	popupWindow.setVisible(true);
	
};
function  removePopups (){

	
	if (popupWindow && popupWindow.getContainer().parentNode)
	{
		iw.remove(popupWindow.getContainer());
		popupWindow = null;
	}
}

function updateContentSize(myContent) {
    
    var contentSize = IWDOMHelper.getSize(myContent, map.getContainer());

    
    var mapsize = map.getOptions().getSize();
    var maxHeight = Math.ceil(mapsize.getHeight() - 80);
    var maxWidth = Math.ceil((mapsize.getWidth() / 2) - 50);
	
    if (contentSize.getHeight() < 80)
    {
        contentSize.setHeight(80);
    }
    else if (contentSize.getHeight() > maxHeight)
    {
        contentSize.setHeight(maxHeight);
    }
    if (contentSize.getWidth() < 260)
    {
        contentSize.setWidth(260);
    }
    else if (contentSize.getWidth() > maxWidth)
    {
        contentSize.setWidth(maxWidth);
    }


   myContent.style.height = contentSize.getHeight()-20+ 'px';//- 15 
   myContent.style.width = contentSize.getWidth() +5+ 'px';


    
    
    var w = parseInt(myContent.style.width);
    if( w <250 ){
   	myContent.style.width=250+'px';
    }
   
    return contentSize;
}

function trim(string){
	if(typeof string!='undefined'&& string !=null){
		return string.replace (/^\s+/, '');
	}
	return "";
}

function tmcInit()
{
	tmcLayer = makeTMCLayer('Verkehrsinfo (TMCPro)', 'TMC', 'tmc', tmcLayerId);
    map.addLayer(tmcLayer);    
    tmcLayer.triggerOnStateChange();
}
