﻿var act_page = "http://www.tpc-camera.tw/camera/resource_act.ashx";
var cdl=new Object();
cdl.res=new Object();
cdl.res.ctrl=function(model, map, view){
	this.classN="cdl.res.ctrl";
	this.model=model;
	this.model.onResourceLoad=
		delegate({scope:this}, function (data){ this.scope.model_resourceLoaded(data); } );				 
	this.map=map;	
	this.map.onZoomEnd=
		delegate(this, function() {this.map_zoomEnd();});
	this.map.onDragEnd=
		delegate(this, function() {this.map_dragEnd();});
	this.map.setController(this);
	this.view=view;
	this.ddlCounty=document.getElementById("ddlCounty");
	
	this.init=function (){
		this.view.setSearchCondition("MAP", "220");
	}
	
	this.setSearchByMap= function (){
		this.view.setSearchCondition("MAP", null);
	}
	this.setSearchByArea= function (){
		this.view.setSearchCondition("AREA", null);
	}	
	this.beginSearch=function(){
		this.clearResources(true);
		this.curSearchType=this.view.searchType;
		if(this.curSearchType=="MAP"){
			this.displayResourcesByMap();
		}else{
			this.displayResourcesByArea();
		}
	}
	this.clearResources= function(displayLoading){		
		this.map.clearMapEventListener();
		this.view.clearResourceList(displayLoading ? "<div style='text-align:center;'>loading...</div>" : "");
		this.map.clearResourceMarks();
		this.selectedResourceId=null;
	}
	this.displayResourcesByArea=function(){
		var zip = this.ddlCounty.options[this.ddlCounty.selectedIndex].value;
		var addr=this.view.getCurrentAddress("AREA");
		model.loadResourcesByArea(act_page, zip);
		this.map.getAddressLatLng(
			addr,
			delegate(this, this.displayResourcesByArea_p2)
			);
	};
	this.displayResourcesByArea_p2=function(obj){
		this.map.panTo(obj);
		// 不需要loading resources list ，因為已經在phase 1 就做了
	};
	this.displayResourcesByMap=function(){
		var addr=this.view.getCurrentAddress("MAP");
		this.map.getAddressLatLng(
			addr,
			delegate(this, this.displayResourcesByMap_p2)
			);
	};
	this.displayResourcesByMap_p2= function (obj){
		this.map.panTo(obj);
		this._displayResourcesByMap();
	}
	this._displayResourcesByMap= function(){
		this.clearResources(true);
		var locRect=this.map.getLocationRect();
		//alert(locRect.latMin+","+locRect.latMax+","+locRect.lngMin+","+locRect.lngMax);		
		this.model.loadResourcesByMap(act_page, locRect);
	}
	
	this.model_resourceLoaded=function (data){
		view.createResourceList(data);
		map.createResourceMarks(data);
		this.refreshTypesSelected();
		if(this.curSearchType=="MAP") this.map.registerMapEventListener();
	};
	
	this.refreshTypesSelected=function (){
		model.setTypesSelected(view.getTypesSelected(true));
		var t=model.getResourceDisplayList(true);
		view.adjustResourceListDisplay(t, this.selectedResourceId);
		map.adjustResourceMarkDisplay(t, this.selectedResourceId);
	};
	
	this.selectResource=function (id){
		this.selectedResourceId=id;
		var t=model.getResourceDisplayList(false);
		view.adjustResourceListDisplay(t, this.selectedResourceId);
		map.adjustResourceMarkDisplay(t, this.selectedResourceId);
		map.showResource(this.model.getResource(id));
	};
	this.map_dragEnd= function(){
		this._displayResourcesByMap();
	}
	this.map_zoomEnd= function(){
		this._displayResourcesByMap();
	}
}

cdl.res.view=function(){
	this.classN="cdl.res.view";
	this.liPrefix="liRes_";
	this.setSearchCondition=function(searchType, zip){
		if(searchType=="MAP"){
			document.getElementById("filterType_bymap").click();
			document.getElementById("divAddress").style.display="";
			document.getElementById("btnRefresh").style.display="";
			this.searchType="MAP";
		}else{
			document.getElementById("filterType_byarea").click();
			document.getElementById("divAddress").style.display="none";
			document.getElementById("btnRefresh").style.display="none";
			this.searchType="AREA";
		}
		if(zip!=null && zip.length>0){
			document.getElementById("ddlCounty").value=zip;
		}
	}
	this.getCurrentAddress=function(type){
		var addr="台北縣";
		var ddlCounty=document.getElementById("ddlCounty");
		addr+=ddlCounty.options[ddlCounty.selectedIndex].text;
		if(type=="MAP"){
			var txtAddress=document.getElementById("txtAddress");
			addr+=txtAddress.value;
		}
		return addr;
	}
	this.clearResourceList=function(txt){
		var resource_list_part=document.getElementById("resource_list");
		resource_list_part.innerHTML=txt;
	}
	
	this.createResourceList=function (data){
		var resource_list_part = document.getElementById("resource_list");
		var html = "";
		for(var i=0; i<data.length; i++)
		{
			html += "<li id='"+this.liPrefix+data[i].id + "'>";
			html += "<a href='javascript: ctrl.selectResource(" + data[i].id + ")'>"
			html += data[i].name;
			html += "</a>";
			html += "</li>";
		}
		resource_list_part.innerHTML = html;
	};
	this.getTypesSelected=function (forceNew){
		if(!forceNew && this.typesSelected!=null) return this.typesSelected;
		var ts=this.typesSelected=new Object();
		var crt=document.getElementsByName("chkResourceType");
		if(crt!=undefined){
			if(crt.length){
				for(var i=0;i<crt.length;i++){
					if(crt[i].checked) ts[crt[i].value]=true;
				}
			}else{ 
				selected[crt.value]=true;
			}
		}
		return ts;
	};
	this.adjustResourceListDisplay=function(resStates, selectedId){
		var t=document.getElementById("resource_list");
		for(var i in resStates){
			var liId=this.liPrefix+i;
			o=resStates[i];
			var html=document.getElementById(liId);
			html.className=(o.id==selectedId)? "selected" : (o.hilit)? "hilit" : "";
		}
	};
	
}
cdl.res.markerWrapper=function (mapObj, id, lat, lng, iconSet, ctrl){
	this.mapObj=mapObj;
	this.id=id;
	this.lat=lat;
	this.lng=lng;
	this.state="normal";
	this.iconSet=iconSet;
	this.ctrl=ctrl;
	
	this.clickMarker= function(){
		this.ctrl.selectResource(this.id);
	}
	
	this.mark1=new GMarker(new GLatLng(lat, lng), {icon: this.iconSet.normal});
	GEvent.addListener(this.mark1, "click", 
					   delegate(this, this.clickMarker)
					   );	
	this.mapObj.addOverlay(this.mark1);
		
	this.setState=function(state){
		this.state=state;
		switch(state){
			case "normal":
				this.mark1.setImage(this.iconSet.normal.image);
				break;
			case "hilit":
				this.mark1.setImage(this.iconSet.hilit.image);
				break;
			case "selected":
				this.mark1.setImage(this.iconSet.selected.image);
				break;	
		}
		//this.mark1.show();
	}
	this.showMessage= function(html){
		this.mark1.openInfoWindowHtml(html);
	}
}
cdl.res.map=function(htmlObjForMap){
	this.classN="cdl.res.map";
	this.mapObj = new GMap2(htmlObjForMap);
    this.mapObj.setCenter(new GLatLng(25.012085, 121.465701), 16);
    this.mapObj.addControl(new GLargeMapControl());
    this.geocoder = new GClientGeocoder();
	this.iconSet=new Object();
	this.iconSet.normal=new GIcon(G_DEFAULT_ICON, "http://www.google.com/mapfiles/markerR.png");
	this.iconSet.hilit=new GIcon(G_DEFAULT_ICON, "/camera/imgs/map/rHilit.png");
	this.iconSet.selected=new GIcon(G_DEFAULT_ICON, "/camera/imgs/map/rSelected.png");
	
	this.setController= function(ctrl){
		this.ctrl=ctrl;
	}
	
	this.getAddressLatLng= function (addr, callback){
		var cache=this.geocoder.getCache();
		var cachedAddress=cache.get(addr);
		if(cachedAddress==null){
			this.geocoder.getLatLng(addr, callback);
		}else{
			callback(cachedAddress);
		}
	}
	this.getLocationRect= function(){
		var bounds=this.mapObj.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		var o=new Object();
		o.latMin = Math.min(sw.lat(), ne.lat());
		o.latMax = Math.max(sw.lat(), ne.lat());
		o.lngMin = Math.min(sw.lng(), ne.lng());
		o.lngMax = Math.max(sw.lng(), ne.lng());
		return o;
	}
	this.panTo=function (locObj){
		if(locObj==null){
			alert("地圖上找不到這個地址的座標！");
			return;
		}
		if(locObj instanceof GLatLng){			
			this.mapObj.panTo(locObj);
		}else if(locObj.Placemark!=null){
			var coordinates=String(locObj.Placemark[0].Point.coordinates).split(",");
			this.mapObj.panTo(new GLatLng(coordinates[1], coordinates[0]));
		}else{
			printObj(obj);
		}
	}
	this.showResource= function(resource){
		if(this.marksHash[resource.id]){
			var o=this.marksHash[resource.id];
			this.mapObj.panTo(new GLatLng(o.lat, o.lng));
			var html = resource.name + "<br>"; 
    		html += resource.tel + "<br>";
    		html += resource.address + "<br>";
			o.showMessage(html);
		}
		
	}
	this.clearResourceMarks= function(){
		this.mapObj.clearOverlays();	
	}
	this.createResourceMarks= function (data){
		this.marksHash=new Object();
		for(var i=0;i<data.length;i++){			
			var markWrapper=new cdl.res.markerWrapper(this.mapObj, data[i].id, data[i].lat, data[i].lng, this.iconSet, this.ctrl);
			this.marksHash[markWrapper.id]=markWrapper;
		}
	}
	this.adjustResourceMarkDisplay= function(resStates, selectedId){
		for(var i in resStates){
			if(!this.marksHash[i]) continue;
			var o=resStates[i];
			var state=(o.id==selectedId)? "selected" : (o.hilit) ? "hilit" : "normal";
			this.marksHash[i].setState(state);
		}
	}
	this.clearMapEventListener= function(){
		if(this.dragEndHandler!=null){
			GEvent.removeListener(this.dragEndHandler);
			this.dragEndHandler=null;
		}
		if(this.zoomEndHandler!=null){
			GEvent.removeListener(this.zoomEndHandler);
			this.zoomEndHandler=null;
		}
	}
	this.registerMapEventListener= function(){
		if(this.dragEndHandler==null) {
			this.dragEndHandler=GEvent.addListener(this.mapObj, "dragend", delegate(this, this.mapObj_dragEnd));
		}
		if(this.zoomEndHandler==null){
			this.zoomEndHandler=GEvent.addListener(this.mapObj, "zoomend", delegate(this, this.mapObj_zoomEnd));
		}
	}
	this.mapObj_dragEnd=function (){
		if(this.onDragEnd) this.onDragEnd();
	}
	this.mapObj_zoomEnd=function(){
		if(this.onZoomEnd) this.onZoomEnd();
	}
		
}
cdl.res.model=function(){
	this.classN="cdl.res.model";
	this.resource_onLoad=function(data){
		this.currentResources=new Object();
		for(var i=0;i<data.length;i++){
			this.currentResources[data[i].id]=data[i];
		}
		this.onResourceLoad(data);
	};
	this.loadResourcesByArea= function(act_page, zip){
		//alert(this.onResourceLoad);
		if(zip!=""){        
			var dataString = 'act=GET_RESOURCES_BY_ZIP&zip=' + zip;
			$.ajax({
				type: "POST",
				url: act_page,
				data: dataString,
				dataType: "json",
				success: delegate({scope:this}, function (data){this.scope.resource_onLoad(data);})
				});
			}
	};
	this.loadResourcesByMap= function(act_page, locRect){		
		var dataString = 'act=GET_RESOURCES_BY_LATLNG&latMin=' + locRect.latMin + '&latMax=' + locRect.latMax + '&lngMin=' + locRect.lngMin + '&lngMax=' + locRect.lngMax;
    	$.ajax({
			type: "POST",
			url: act_page,
			data: dataString,
			dataType: "json",
			success: delegate({scope:this}, function (data){this.scope.resource_onLoad(data);})
			});
	};
	this.getResource=function (id){
		if(this.currentResources[id]) return this.currentResources[id];
		return null;
	};
	this.setTypesSelected=function (ts){
		this.typesSelected=ts;
	}
	this.getResourceDisplayList= function(force){
		if(!force && this.resourcesSelected) return this.resourcesSelected;
		var rs=this.resourcesSelected=new Object();
		if(this.currentResources==null) return rs;
		for(var i in this.currentResources){
			var o=this.currentResources[i];
			rs[o.id]={id:o.id};
			for(var j=0;j<o.types.length;j++){
				if(this.typesSelected[o.types[j].id]) rs[o.id].hilit=true;
			}
		}
		return rs;
	}
}
