﻿
//var feedInfoTemplate = new esri.InfoTemplate("${title}", "${summary}");
//var feedInfoTemplate = new esri.InfoTemplate("<a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>", "<span style='font-weight:bold;'>通告編號:</span>${title}<br><span style='font-weight:bold;'>事由:</span>${principal} - ${reason}<br><span style='font-weight:bold;'>地點:</span>${location}<br><span style='font-weight:bold;'>開始日期:</span>${startday}　　<span style='font-weight:bold;'>為期:</span>${period}日<br><span style='font-weight:bold;'>通告詳情:</span>${summary}<p>&nbsp;</p>");


var feedInfoTemplate_IE = new esri.InfoTemplate("<a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>", "<span style='font-weight:bold;'>通告詳情:</span><table><tr><td>${summary}</td></tr></table><br><br><br>");
var feedInfoTemplate_IE_Pic = new esri.InfoTemplate("<a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>", "<span style='font-weight:bold;'>位置詳圖:</span><table><td><a href='${img}' target='blank'><img src='${img}' style='width:40px; height:40px ;border:1px solid black;'></a></td></table><span style='font-weight:bold;'>通告詳情:</span><table><tr><td>${summary}</td></tr></table><br><br><br>");

//var feedInfoTemplate_IE = new esri.InfoTemplate("<a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>"," ");

var feedInfoTemplate_OTHER = new esri.InfoTemplate("<span style='font-weight:bold;'>通告詳情:</span>", "<a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>");

//2009.11.12 Modify
//**************************************

var feedInfoTemplate_IE_PT = new esri.InfoTemplate("<a style='font-size:8pt;' target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>", "<div style='font-size:10pt;'><span style='font-weight:bold;'>Informações:</span><table><tr><td>${summary}</td></tr></table></div><br><br><br><br>");
var feedInfoTemplate_IE_Pic_PT = new esri.InfoTemplate("<a style='font-size:8pt;' target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a>", "<div style='font-size:10pt;'><span style='font-weight:bold;'>Detalhes:</span><table><td><a href='${img}' target='blank'><img src='${img}' style='width:40px; height:40px ;border:1px solid black;'></a></td></table><span style='font-weight:bold;'>Informações:</span><table style='font-size:10pt;'><tr><td>${summary}</td></tr></table></div><br><br><br><br>");

var feedInfoTemplate_OTHER_PT = new esri.InfoTemplate("<span style='font-weight:bold;font-size:8pt;'>Informações:</span>", "<div style='font-size:8pt;'><a target='blank' href=${link}>${title} - ${principal} - ${reason} (${location})</a></div>");

//***************************************

var _aGraphic = new Array();
var isShowRss = false;
var browser_type = 1;
var FeedInfo;
var Long_Term = new Array();
var Short_Term = new Array();
var FeedItems_R = false;

function ProcessFeed(xmlDocSource,map){
	
	
	var xmlDoc = parseGeoRss(xmlDocSource);
	if (xmlDoc == null)
		return false;

	var items = xmlDoc.getElementsByTagName("entry");
	if ( items.length == 0 )
		return false;

    for( var i = 0; i < items.length; i++ ) {          
      var itemtags = items.item(i).getElementsByTagName("*");
      var obj=new GeoRSSItem(itemtags);
	  if (obj.category_level == LONG_TERM)
	  	Long_Term.push(obj);
	  else if(obj.category_level == SHORT_TERM)
		Short_Term.push(obj);
	}
	
	
	FeedInfo = new FeedInfoItem(xmlDoc);
	
	addGeoRssToList("longPane");
	addGeoRssToList("shortPane");
	GraphicObjPack(map);
	

}

function FeedInfoItem(xmlDoc){
	this.date;
	this.time;
	
	var temp = xmlDoc.getElementsByTagName("updated")[0].firstChild.nodeValue;
	if(temp!=null){
		this.date = temp.split('T')[0];
		temp = temp.split('T')[1].split('+')[0];
		temp = temp.split(':')[0] + ":" + temp.split(':')[1];
		this.time = temp;
	}
}

function parseGeoRss(xmlDocSource) {
	var xmlDoc;
	if(browser_type !=2)//Internet Explorer
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
        xmlDoc.loadXML(xmlDocSource);
    }
    else
    {
        try //Firefox, Mozilla, Opera, etc.
        {
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmlDocSource,"text/xml");
        }
        catch (e) {
			alert(e.message);
			return null;
		}
    }
	return xmlDoc;
}

function addGeoRssToList(id) {
	var ulNode = document.createElement("ul");
    var x,y;

	//2009.11.12 Modify
	//***********************************
	if(browser_type == 2){
		document.getElementById("longPane_content").style.fontSize = '8pt';
		document.getElementById("shortPane_content").style.fontSize = '8pt';
	}
	
	//************************************

	if (id == "longPane"){		
	  var pane_date = document.getElementById("longPane_date");
	  
    //2009.11.23 Modify
	//*************************************
	if(params.lang == 'C')
	  pane_date.innerHTML = "資料更新日期：" + FeedInfo.date + " " + FeedInfo.time;
	else
	  pane_date.innerHTML = "Data da Actualizção：" + FeedInfo.date + " " + FeedInfo.time;
	
	//*************************************	

	  for(x in Long_Term) {          
		  var li=createLiNode(Long_Term[x]);
		  if (li!=null) 
			ulNode.appendChild(li);
	  }
		var pane = document.getElementById("longPane_content");
		pane.className = "finished_pane";
		if(pane.hasChildNodes()){
			var pane_child = pane.firstChild;
			RemoveLiNode(pane_child);
			pane.removeChild(pane_child);
		}
		pane.appendChild(ulNode);
		
	} else if (id == "shortPane"){
	  	var pane_date = document.getElementById("shortPane_date");
		
  	  //2009.11.23 Modify
		//*************************************
		if(params.lang == 'C')   
		  pane_date.innerHTML = "資料更新日期：" + FeedInfo.date + " " + FeedInfo.time;
		else
		  pane_date.innerHTML = "Data da Actualizção：" + FeedInfo.date + " " + FeedInfo.time;

		//*************************************	
		
		for(y in Short_Term) {          
		  var li=createLiNode(Short_Term[y]);
		  if (li!=null) 
			ulNode.appendChild(li);
	 	 }
		var pane = document.getElementById("shortPane_content");
		pane.className = "finished_pane";
		if(pane.hasChildNodes()){
			var pane_child = pane.firstChild;
			RemoveLiNode(pane_child);
			pane.removeChild(pane_child);
		}
		pane.appendChild(ulNode);
	}

}

function RemoveLiNode(pane_child){
	while (pane_child.hasChildNodes()){
		if(pane_child.firstChild != null)
			pane_child.removeChild(pane_child.firstChild);
	}
}

function createLiNode(obj) {
	if (obj == null)
		return null;
	var liNode = document.createElement("li");
	switch(parseInt(obj.category_type)){
		case 1:
			liNode.id = "a";
			break;
		case 2:
			liNode.id = "b";
			break;
		case 3:
			liNode.id = "c";
			break;
	}
	var resultNode = document.createElement("a");
	resultNode.href = "";
	resultNode.name = obj.lon+","+obj.lat;
	resultNode.onclick = function() {centerAndZoom(this.name.split(",")[0],this.name.split(",")[1],11);return false;};
	resultNode.appendChild(document.createTextNode(obj.title));
	liNode.appendChild(resultNode);
	liNode.appendChild(document.createElement("br"));
	liNode.appendChild(document.createElement("br"));
	//liNode.appendChild(document.createTextNode(obj.summary));
	return liNode;
}

function addGraphics(map) {
	
	dijit.byId("identify").setDisabled(false);	

	if (!FeedItems_R)
		setTimeout("addGraphics(gMap);",1000);
		//addGeoRssToMap(map);
	//else {
		processFeedGraphics("remove", map);
		for (var i=0; i<_aGraphic.length; i++)
			map.graphics.add(_aGraphic[i]);
		isShowRss = true;
	//}
}

function removeGraphics(map) {
	
	dijit.byId("identify").setDisabled(true);

	for (var i=0; i<_aGraphic.length; i++) {
		map.graphics.remove(_aGraphic[i]);
	}
		//processFeedGraphics("remove", map);
}

// Process the the graphics by adding or removing
function processFeedGraphics(actionType, map) {
    var gfs = map.graphics;
    if (gfs==null) return;
    var iSize=gfs.length;
    for( var i = iSize -1; i >=0 ; i-- ) {        
        processAGraphic(actionType, gfs[i], map);
    }
}

function processAGraphic(actionType, graf, map) {
    if (actionType=="show") {
        graf.show();
    } else if (actionType=="hide") {
        graf.hide();
    } else if (actionType=="remove") {
        map.graphics.remove(graf);
        graf=null;        
    }
}

// GeoRSS Item
function GeoRSSItem(itemtags) {    
      this.lat="";
      this.lon="";
      this.fType="point"; // by default the feature type is point      
      this.title="";
      this.link="";
	  this.img="";
      this.id="";
	  this.summary="";
	  this.category_level="";
	  this.category_type="";
	  this.updated="";
	  this.previousnotice="";
	  this.location="";
	  this.startday="";
	  this.period="";
	  this.reason="";
	  this.principal="";

      for ( var j = 0; j < itemtags.length; j++ ) {
        var v="";
		var t=itemtags[j];
        if (t.firstChild) v=t.firstChild.data;
        
        var tag = t.nodeName;
        if (tag == 'georss:point') {
          var ptArr=v.split(" ");
          //this.lat = ptArr[0]; orginal code.
          //this.lon = ptArr[1];
		  this.lon = ptArr[0]; //DSAT GeoRSS Point corrd. order.
		  this.lat = ptArr[1]; 
        } else if (tag == 'title') {
          this.title= (v==null? "":v);
        } else if (tag == 'category') {
		  var c_label= t.getAttribute('label');
		  var c_term = t.getAttribute('term');
			if (c_label == 'level'){
				this.category_level = (c_term==null? "":c_term);
			} else if (c_label =='type') {
				this.category_type = (c_term==null? "":c_term);
			}
        } else if (tag == 'updated') {
          this.updated= (v==null? "":v);
        } else if (tag == 'previousnotice') {
          this.previousnotice= (v==null? "":v);
        } else if (tag == 'id') {
          this.id= (v==null? "":v);
        } else if (tag == 'summary') {
			this.summary = (v==null? "":v);
		} else if (tag == 'link') {
		  var type = t.getAttribute('type');
		  if (type == 'text/html') {
			  var href = t.getAttribute('href');
			  this.link = (href==null? "":href);
		  }
		  else if (type == 'image/jpeg') {
			  var href = t.getAttribute('href');
			  href = (href.indexOf("http://")==-1? "none":href);
			  //this.img = "<image src='" + href + "' border='0'>";
			  this.img = href;

		  }
        } else if (tag == 'content') {
			var info = t.getElementsByTagName("additionalinfo")[0].getElementsByTagName("*");
			for ( var k = 0; k < info.length; k++ ) {
				var v2="";
				var t2=info[k];
        		if (t2.firstChild) v2=t2.firstChild.data;
        
        		var tag2 = t2.nodeName;
				if (tag2 == 'location') {
				  this.location = (v2==null?"":v2);
				} else if (tag2 == 'startday') {
				  this.startday = (v2==null?"":v2);
				} else if (tag2 == 'period') {
				  this.period = (v2==null?"":v2);
				} else if (tag2 == 'reason') {
				  this.reason = (v2==null?"":v2);
				} else if (tag2 == 'principal') {
				  this.principal = (v2==null?"":v2);
				} else if (tag2 == 'undertaker') {
				  this.undertaker = (v2==null?"":v2);
				}
			}
		}
      } //end for
}    

// Create the point, line, polygon
function createGraphicObject(obj, map) {
    var g;    
    var s_sym;
	
    if (obj.fType=="point") { 
		switch(parseInt(obj.category_type)){
			case 1:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
        		s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/TrafficWeb/images/trans_icon/no_entry.png", 20, 20); 
				break;
			case 2:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
				s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/TrafficWeb/images/trans_icon/no_parking.png",20,20);
				break;
			case 3:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
        		s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/TrafficWeb/images/trans_icon/constructed.png", 20, 20); 
				break;
		}		
		//s_sym=new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND,20,new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,new dojo.Color([255,255,0,1]),1),new dojo.Color([255,255,0,1]));
  /*  }else if (obj.fType=="point" && gMap.getLevel() < 6){ 
		alert(gMap.getLevel());
		switch(parseInt(obj.category_type)){
			case 1:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
        		s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/DSATWeb/images/trans_icon/no_entry.png", 20, 20); 
				break;
			case 2:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
				s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/DSATWeb/images/trans_icon/no_parking.png",20,20);
				break;
			case 3:
				g=new esri.geometry.Point(obj.lon,obj.lat,map.spatialReference);
        		s_sym=new esri.symbol.PictureMarkerSymbol(SERVER_ADD+"/DSATWeb/images/trans_icon/constructed.png", 20, 20); 
				break;
		}		
	*/
	}else if (obj.fType=="line") {    
        var pts=toPointArray(obj.coords);
        g=new esri.geometry.Polyline();
        g.addPath(pts);
        s_sym=new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 1);     
    } else if (obj.fType=="polygon") {    
        var pts=toPointArray(obj.coords);
        g=new esri.geometry.Polygon();
        g.addRing(pts);
        s_sym= new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, 
                        new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, 
                        new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
    }
     
    //var feedAttributes = { type: obj.feedType, title: obj.title, link: obj.link, description: obj.description, published: obj.pubDate, id: obj.id };
	var feedAttributes = { title: obj.title, link: obj.link, summary: obj.summary, img: obj.img, id: obj.id, category: obj.category, updated: obj.updated, previousnotice: obj.previousnotice, location: obj.location, startday: obj.startday, period: obj.period, reason: obj.reason, principal: obj.principal };
  
  	//2009.11.12 Modify
	//******************************
	if(params.lang == 'C'){   
   		if (browser_type == 1 && obj.img =="none")
   			//return new esri.Graphic(g, s_sym, feedAttributes);
   			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_IE);
		else if (browser_type ==1)
   			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_IE_Pic);
    	else
			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_OTHER);
	}
	else {
   		if (browser_type == 1 && obj.img =="none")
   			//return new esri.Graphic(g, s_sym, feedAttributes);
   			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_IE_PT);
		else if (browser_type ==1)
   			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_IE_Pic_PT);
    	else
			return new esri.Graphic(g, s_sym, feedAttributes, feedInfoTemplate_OTHER_PT);
	}
	//*******************************			
			
}    

// Utils
function toPointArray(coords) {
    var ptArr=coords.trim().split(" ");
    var iSize=ptArr.length;
    var pts=new Array(iSize/2);
    for (i=0; i<iSize; i=i+2) {
        var g=new esri.geometry.Point(ptArr[i+1], ptArr[i]);
        pts[i/2]=g;
    }
    return pts;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function readFeedtoShow(strUrl,map) {
    var xmlHttp=GetXmlHttpObject();
    
	//var start = new Date();
	
    xmlHttp.onreadystatechange= function() { 
        if (xmlHttp.readyState==4) {            
            if (xmlHttp.status==200) {
               var xmlDoc=xmlHttp.responseText;
                if (xmlDoc==null) { // || xmlDoc.nodeValue==null) {
                    //display feed error
                    errMsg=xmlHttp.responseText;
                    alert(errMsg);
                } else {
					//alert(start +' , ' + new Date());
					
                    ProcessFeed(xmlDoc,map);
                }
            } else {
                //display feed error
                errMsg=xmlHttp.statusText;
                alert(errMsg);
            }
        }
    }
   
    xmlHttp.open("GET",strUrl,true);
    xmlHttp.send(null);
	

	//setTimeout("UpdateGraphic(GEORSS_PATH,gMap);",43200000); //Update GeoRSS For every 12Hr.

	//setTimeout("UpdateGraphic(GEORSS_PATH,gMap);",5000); //Update GeoRSS For every 12Hr.

} 


function GetXmlHttpObject() {
    var xmlHttp=null;
	try{ 
		//Internet Explorer
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} 
	catch(e) {
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					// Firefox, Opera 8.0+, Safari
					xmlHttp = new XMLHttpRequest();
					browser_type = 2;
					}
				}
				
    if (xmlHttp==null) {
      alert ("Your browser does not support AJAX!");
      return;
    } 
	
	//Set the Info Windows Size, base on the browser type
	setInfoWinSize();
	
    return xmlHttp;
}

function toggleGeoRSS(map) {
	var show = (gMap.getLevel() > 4);
	if (show != isShowRss) {
		if (show)
			addGraphics(map);
		else
			//if(_aGraphic.length != 0)
				removeGraphics(map);
		isShowRss = show;
	}
}

function setInfoWinSize(){
	
	//2009.11.12 Modify
	//**************************************
	if(params.lang == 'C'){
		if(browser_type == 1)
			//Internet Explorer
			gMap.infoWindow.resize(400, 200);
		else
			//Firefox, Opera 8.0+, Safari
			gMap.infoWindow.resize(400, 100);	
	}
	else{
		if(browser_type == 1)
			//Internet Explorer
			gMap.infoWindow.resize(420, 230);
		else
			//Firefox, Opera 8.0+, Safari
			gMap.infoWindow.resize(400, 130);	
	}
	//****************************************
	
}

function UpdateGraphic(strUrl,map){
	
	Long_Term = [];
	Short_Term = [];
	FeedItems_R = false;
	
	processFeedGraphics("remove", map);
	readFeedtoShow(strUrl,map);
	if(isShowRss)
		addGraphics(map);
	
}

function GraphicObjPack(map){
	_aGraphic.length = 0;

	if(Long_Term == null && Short_Term == null)
		return false;
		
	if(Long_Term.length == 0 && Short_Term.length == 0)
		return false;
	
	if(Long_Term != null)
		if(Long_Term.length != 0){
			for(x in Long_Term){
				var gf = createGraphicObject(Long_Term[x],map);
				if(gf != null){
					_aGraphic.push(gf);
				}
			}
			Long_Term.length = 0;
		}
	if(Short_Term != null)
		if(Short_Term.length != 0){
			for(y in Short_Term){
				var gf = createGraphicObject(Short_Term[y],map);
				if(gf != null){
					_aGraphic.push(gf);
				}
			}
			Short_Term.length = 0;
		}
	
	FeedItems_R = true;
}
	
	
	
	
