﻿/*  GEO WEB MapTools Class for Using the GEO WEB Core Components
 *  (c) 2006 GEO Informatics <houghost@geo.com.tw> 
 *  Version 0.3.7
 *	Create Date:2007.01.23      
 *  Modified Date:2007.05.24
/*--------------------------------------------------------------------------*/

// Abstract Class
var GWMapObject = new Class({
    initialize: function (){
        this.id = '';
        this.ClassType = '';
    },
    
    _sendRequest: function (url,opt,onCom,onFail){ 
        var options = {};
        if (opt) {
            options = opt;
        } else {
            options.method = 'post';
        }
        
        if (onCom) {    
            options.onComplete = onCom.bind(this);
        }
        
        if (onFail) {    
            options.onFailure = onFail.bind(this);
        }
	    
	    //console.log(url);   
        //console.log(options);
	    var aj = new Ajax.Request(url, options); 
    },
    
    _toQueryString: function (cont){
        var h = $H(cont);
        return h.toQueryString();
    },        
    
    _generateID: function() {
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
      var string_length = 10;
      if (arguments[0]) string_length = arguments[0];
      var maxTry = 10;
      nbTry = 0;
      while (nbTry < 1000) 
      {
          var id = '';
          // generate string
          for (var i=0; i<string_length; i++) 
          {
              var rnum = Math.floor(Math.random() * chars.length);
              id += chars.substring(rnum,rnum+1);
          }
          // check if there
          elem = $(id);
          if (!elem) {
                var item = document.createElement('input');                
                item.id = id;
                item.type = 'hidden';
                document.body.appendChild(item);                
                return id;
          }
          nbTry += 1;
      }
      return null;
    }
});

// Point Class
var Point = new Class({
    initialize: function (x,y){
        this.x = x;
        this.y = y;
    },
    
    setFromWGS: function (lat,lon){
        var pt = this._WGStoTM2(lat,lon);
        this.x = pt[0];
        this.y = pt[1];
    },
    
    getTM2: function (){
        return [this.x, this.y]
    },
    
    getWGS: function (){
        return _TM2toWGS(this.x,this.y);
        //return this._WGStoTM2(this.lat,this.lon);
    },
    
    _WGStoTM2: function (lat, lon){
        var x, y;
        return [x,y];
    },
    
    _TM2toWGS: function (x,y) {
        var lat,lon;
        return [lat,lon];
    }
});

// Extent Class
var GWPointBound = new Class({
    initialize: function (nw,se){
        if (typeof(nw) != 'undefined') this.nw = nw; else this.nw = new Point(0,0);
        if (typeof(se) != 'undefined') this.se = se; else this.se = new Point(0,0);
    },
    
    getArea: function (){        
        return (Math.abs(this.se.x-this.nw.x) * Math.abs(this.se.y-this.nw.y));
    },
        
    getCenter: function (){
        return new Point(((Math.abs(this.se.x - this.nw.x)/2) + this.nw.x),((Math.abs(this.se.y - this.nw.y)/2) + this.se.y));
    }
});

var GWIconObject = new Class({
    initialize: function (i,s){
        this.icon = i;
        this.shad = s;
    }
});

var DefaultIcon = new GWIconObject(new GWMapIcon('image/MIcon01.png',26,43,5,20), new GWMapIcon('image/MIcon02.png',26,43,5,20));
var EmptyIcon   = new GWIconObject(new GWMapIcon('',0,0,0,0), new GWMapIcon('',0,0,0,0));

// Geometry Feature Class - Super Class
var GWFeature = GWMapObject.extend({
    initialize: function (){
        this.parent();
        this.fid = -1;
    }
});

// Point Feature Class
var GWPointFeature = GWFeature.extend({
    initialize: function (){
        this.parent();
        if ((arguments[0]) && (arguments[1])){
            this.pt = new Point(arguments[0],arguments[1]);            
        } else {
            this.pt = new Point(0,0);
        }        
        this.attribute  = new Object();
        if (arguments[2]) this.attribute = arguments[2];
        
        this.ClassType  = 'PointFeature';
        this.symbol     = DefaultIcon;
        this.hasInfo    = 0;
        this.btnType    = 1;
    },
    
    setSymbol: function (IconObject){
        this.symbol = IconObject;
    },
    
    convertAttributeToQS: function (){
        return this._toQueryString(this.attribute);
    }
});

// Polyline Feature Class
var GWPolylineFeature = GWFeature.extend({
    initialize: function (){
        this.ClassType = 'PolylineFeature';
    }
});

// Polygon Feature Class
var GWPolygonFeature = GWFeature.extend({
    initialize: function (){
        this.ClassType = 'PolygonFeature';
    }
});


// Layer Class - SuperClass
var GWLayer = GWMapObject.extend({
    initialize: function (name){
        this.id             = this._generateID();
        this.name           = name;
        this.index          = 0;
        this.layertype      = 0;                    // {0:point,1:polyline,2:polygon}
        this.FeatureMembers = new Array();
        this.BufferMembers  = new Array();          // [{fid,x,y}]        
        this.param          = new Object(); 
        this.dynamicReflash = false;
        this.visible        = true;
        this.maxScale       = 5;
        this.searchBean     = '';
        this.maxCount       = 100;
        this.allrange       = false;
        this.cusAtt         = false;
        this._DebugObj      = null;
        this.hasInfo    = 0;
        
        this.Events = {
            newIndex:       function (){},
            isLoadingData:  function (){},  
            isLoadedData:   function (){},
            isOverlayed:    function (){}
        };
        this.ClassType = 'Layer';
    },
    
    // Set Event Listener
    setEventListener: function (eventName,fFunName){
        switch(eventName)
        {
          case 'isLoadingData':
            this.Events.isLoadingData = fFunName;
            break;
		  case 'isLoadedData':
            this.Events.isLoadedData = fFunName;
            break;
          case 'isOverlayed':
            this.Events.isOverlayed = fFunName;
            break;
          default:
            ;
        }
    },

    // Visible Properties  
    setFeaturesLimit: function (m){
        this.maxCount = m;
    },
    
    getFeaturesLimit: function (){
        return this.maxCount;
    },

    // MaxCount Properties  
    setMaxCount: function (v){
        this.maxCount = v;
    },
    
    sethasInfo: function(atype){
        this.hasInfo = atype;
    },
    
    gethasInfo: function(){
        return this.hasInfo;
    },
    
    getMaxCount: function (){
        return this.maxCount;
    },

    // Visible Properties  
    setMaxScale: function (v){
        this.maxScale = v;
    },
    
    getMaxScale: function (){
        return this.maxScale;
    },
      
    // Visible Properties  
    setVisible: function (v){
        if (typeof(v) == 'boolean') {
            this.visible = v;
        } else {
            return 'Type mismatch!';
        }
    },
    
    getVisible: function (){
        return this.visible;
    },
    
    // Index Properties
    setIndex: function (i){
        this.index = i;
    },
    
    getIndex: function (){
        return this.index;
    },
    
    // Index Properties
    setDynamicReflash: function (d){
        if (typeof(d) == 'boolean') {
            this.dynamicReflash = d;
        } else {
            return 'Type mismatch!';
        }
    },
    
    getDynamicReflash: function (){
        return this.dynamicReflash;
    },
    
    
    // Layer ID Properties    
    getLayerId: function (){
        return this.id;
    },
    
    // Layer Name Properties    
    setLayerName: function (name){
        this.name = name;
    },
    
    getLayerName: function (){
        return this.name;
    },
    
    setParameters: function (param){
        this.param = param;
        this.Events.newIndex;
    },
    
    setSearchBean: function (sb){
        this.searchBean = sb;       
    },
    
    getQueryString: function (){
        var h = $H(this.param);
        return h.toQueryString();
    },
    
    getFeatureCount: function (){
        return this.FeatureMembers.length;
    },
    
    // Add Feature
    add: function (f){
        // 判斷Feature與Layer是否為同一類型
        this.FeatureMembers.push(f);
    },
    
    // Get Best Map Display Range to display all the data in this layer
    getBestMapRange: function (mapVisExtent){        
        var ext = this.getExtent(); 
    	var needw,needh;    	
    	var cx, cy, cs;
    	cs = 10;
    	cx = 249326;
    	cy = 2620417;
        needw = Math.ceil(Math.abs(ext.se.x - ext.nw.x));
        needh = Math.ceil(Math.abs(ext.nw.y - ext.se.y));
        for(i=mapVisExtent.length-1;i>=1;i--) {
            if ((mapVisExtent[i].w * 0.85) > needw && (mapVisExtent[i].h * 0.85) > needh)
                cs = i;                
        }
        var c = new Point(249326,2620417);
        c = ext.getCenter();
        var ans = {};
        ans.CX = c.x;
        ans.CY = c.y;
        ans.CS = cs;
        return {CX:c.x,CY:c.y,CS:cs};   
    },
    
    // Getting Data with Ajax
    getData: function (mapStatus){
        this.Events.isLoadingData(this);
        var url, pm;
        url = this.searchBean;
        
        pm = this.getQueryString();
        
        pm += '&lid=' + this.id;
        pm += '&SMax=' + this.maxCount;        
         
        if ((!this.allrange) && (mapStatus)) {
            
            pm += '&CX=' + Math.floor(mapStatus.CX);
            pm += '&CY=' + Math.floor(mapStatus.CY);

        } 
        var options = {};
        options.method = 'post';
        options.parameters = pm;
        
        this._sendRequest(url,options,this._loadData,this.Events.onLoadFail);        
        
        /*
        if (this.Events.onLoadFail) {    
            this.Events.onFailure = options.Events.onFailure;
            options.onFailure = this.Events.onFailure.bind(this);
        }
        //this.onComplete = options.onComplete;
	    options.onComplete = this._loadData.bind(this);
	     
	    var aj = new Ajax.Request(url, options); 
	    */
    },
    
    // Load the AJAX result into this.DataMembers
    _loadData: function (req){
        eval(req.responseText);        
        if (!Err) {
            this.FeatureMembers = res;             
        } else {
            this.Events.isLoadedData(Err);
            //console.log(Err);            
        }
        this.Events.isLoadedData(this);
    },
    
    overlayFeature: function (){
    },
    
    // Remove Feature from screen
    removeFeature: function (map){
        if (this.BufferMembers.length > 0){                             
            switch (this.layertype) {
                case 0:
                    for (i=0;i<this.BufferMembers.length;i++) 
                        map.RemovePlacard(this.BufferMembers[i]);                         
                    break;
                default:
                    ; 
            }           
            map.ReflashPlacard(); 
            this.BufferMembers = new Array();
        }    
    },    
    
    overlayFeature: function (){     
    },
    
    // Having some problems
    destroy: function (){
        elem = $(this.id);
        document.body.removeChild(elem);
        delete this;
    }    
});


// Point Layer
var GWPointLayer = GWLayer.extend({
    initialize: function (name){
        this.parent(name);
        this._layertype      = 0;
        this.ClassType      = 'PointLayer';
        this.LayerSymbol    = null;
    },
    
    // Overlay features on the map
    overlayFeature: function (map, mapVisExtent){
        if (!map)
            return 'No Map Object!';        

        // Remove Old Objects 
        this.removeFeature(map);

        // Overlay Point Feature
        for (i=0;i<this.getFeatureCount();i++){            
            
            var s = this.FeatureMembers[i].symbol;
            if (this.LayerSymbol) s = this.LayerSymbol;
            var f = this.FeatureMembers[i];
            
            var c = '';
            
            if (!this.cusAtt) {
                var h = $H(f.attribute);
                for (k=0;k<h.keys().length;k++)
                    c = c + '<p class="' + h.keys()[k] + '">' + h.values()[k] + '</p>';            
            }
            
            f.fid = map.AddPlacard(this.hasInfo,s.icon,s.shad,f.btnType,f.pt.x,f.pt.y,c,'','');
            this.BufferMembers.push(f.fid);
        }
        if ((this.allrange) && (mapVisExtent)) {				
            var br = this.getBestMapRange(mapVisExtent);
            map.MoveToRXY(br.CX,br.CY,br.CS,false);              
        }         
        map.ReflashPlacard();  
        this.Events.isOverlayed();
        return null;
    },
    
    // Get the Extend of all feature   {sx,sy,ex,ey}
    getExtent: function (){
        var b = new PointBound();
        if (this.getFeatureCount() > 0) {
            b.nw.x = this.FeatureMembers[0].pt.x;
            b.nw.y = this.FeatureMembers[0].pt.y;
            b.se.x = this.FeatureMembers[0].pt.x;
            b.se.y = this.FeatureMembers[0].pt.y;            
            for (i=0;i<this.getFeatureCount();i++){
                b.nw.x = Math.min(b.nw.x,this.FeatureMembers[i].pt.x);
                b.nw.y = Math.max(b.nw.y,this.FeatureMembers[i].pt.y);
                b.se.x = Math.max(b.se.x,this.FeatureMembers[i].pt.x);
                b.se.y = Math.min(b.se.y,this.FeatureMembers[i].pt.y);
            }
        }
        return b;
    },
    
    // Set Point Layer Symbol
    setLayerSymbol: function (IconObject){
        this.LayerSymbol = IconObject;
    }
});


// Polyline Layer
var GWPolylineLayer = GWLayer.extend({
    initialize: function (){
        this.parent();        
        this._layertype      = 1;   
        this.ClassType      = 'PolylineLayer';   
    }
});


// Polygon Layer
var GWPolygonLayer = GWLayer.extend({
    initialize: function (){
        this.parent();        
        this._layertype      = 2;
        this.ClassType      = 'PolygonLayer';
    }
});

// Data Frame Class (Layers Group)===============================================================
var GWDataFrame = GWMapObject.extend({
    initialize: function (map, div){
        this.Layers         = new Array();
        this.map            = map;     
        this.name           = 'DataFrame';
        this.id             = this._generateID(5);
        this.ClassType      = 'DataFrame';
          
        this.properties     = {
            mapVisExtent:   new Array(),
            mapCStatus:     {},
            visible:        true,
            coordSys:       'TM2-67',
            updating:       0,
            redrawing:      0
        };
        
        this.Events         = {
            isLoadingData:  function (){},
            isLoadedData:   function (){}
        };
        
        // Get the map extent in all scale level
        for(i=1;i<MG_MAP_LOCACTION_SW.length;i++) {
            var wid,hei;
            wid = Math.abs(MG_MAP_LOCACTION_SW[i] / MG_MAP_LOCACTION_W[i] * parseInt($(div).clientWidth));
            hei = Math.abs(MG_MAP_LOCACTION_SH[i] / MG_MAP_LOCACTION_H[i] * parseInt($(div).clientHeight));
            this.properties.mapVisExtent.push({w:wid,h:hei});
        }
        
        // Set Map Flash Event Listener
        this.flashMap = this._getMapCStatus.bind(this);
        this.moveMap = this._updateMapStatus.bind(this);
        this.updateMap = this._actionFinished.bind(this);        
        this.map.SetCBFunction('MapMove',this.moveMap);	  
        this.map.SetCBFunction('FlashMap',this.flashMap);
        this.map.SetCBFunction('MapDragOver',this.updateMap);        
    },
    
    _actionFinished: function (){
        this.updateData();
    },
    
    _updateMapStatus: function (ir,isx,isy,iex,iey){
        this.properties.mapCStatus.CX = isx + (iex - isx) / 2;
        this.properties.mapCStatus.CY = isy - (isy - iey) / 2;
        this.properties.mapCStatus.TX = isx;
        this.properties.mapCStatus.TY = isy;
        this.properties.mapCStatus.BX = iex;
        this.properties.mapCStatus.BY = iey;
        this.properties.mapCStatus.Sc = ir;
    },
    
    // Set Event Listener
    setEventListener: function (eventName,fFunName){
        switch(eventName)
        {
          case 'isLoadingData':
            this.Events.isLoadingData = fFunName;
            break;
		  case 'isLoadedData':
            this.Events.isLoadedData = fFunName;
            break;
          default:
            ;
        }
    },
    
    setName: function (n){
        this.name = n;
    },
    
    getName: function (){
        return this.name;
    },
    
    setCoordSys: function (cs){
        this.properties.coordSys = cs;
    },
    
    getCoordSys: function (){
        return this.properties.coordSys;
    },
    
    getLayerCount: function (type){
        switch(type){
            case 'Visible':
                var i = this.Layers.length;
                for (i=0;i<this.Layers.length;i++)
                    if (!this.Layers[i].visible) i--;
                return i
                break;
            default:
                return this.Layers.length;
        }
    },
    
    zoomToLayer: function (lid){
        var L = this.Layers;
        for (i=0;i<this.getLayerCount();i++){
            if (((L[i].id == lid) || (L[i].index == lid)) && (!L[i].getDynamicReflash())){
                var e = L[i].getBestMapRange(this.properties.mapVisExtent);
                this.map.MoveToRXY(e.CX,e.CY,e.CS,false); 
            }
        }
    },
    
    swapLayer: function (index1,index2){
        this.Layers[index1].index = index2;
        this.Layers[index2].index = index1;
        this._sortLayer();
        this.redraw();
    },
    
    // Redraw Map
    redraw: function (){
        this.properties.redrawing = 0;
        this.Events.isLoadingData(this);
        if (this.getLayerCount() > 0) {
            this._redrawDataFrame();
        } else {
            this.Events.isLoadedData(this);
        }
    },
    
    // Update Data
    updateData: function (up){
        this.properties.updating = 0;
        this.Events.isLoadingData(this);
        if (this.getLayerCount() > 0) {
            this._updateLayers(up);
        } else {
            this.Events.isLoadedData(this);
        }    
    },
    
    // Set the visible property of the Data Frame
    setVisible: function (vis) {
        if (!arguments[1]) {            
            this.properties.visible = vis;
        } else {
            var id = arguments[1];
            for (i=0;i<this.Layers.length;i++){
                if (this.Layers[i].id == lid) {
                    this.Layers[i].setVisible(vis);                    
                }    
            }
        }
        this.redraw();
    },
    
    setAlpha: function (alpha){
    },
    
    setMap: function (map) {
        this.map = map;
    },    
    
    // Get Data Frame Extent
    getExtent: function (){
        var b = new PointBound(); 
        if (this.Layers.length > 0) {
            b = this.Layers[0].getExtent();        
            for (i=0;i<this.Layers.length-1;i++){
                Temp = this.Layers[i].getExtent();
                b.nw.x = Math.min(b.nw.x,Temp.nw.x);
                b.nw.y = Math.max(b.nw.y,Temp.nw.y);
                b.se.x = Math.max(b.se.x,Temp.se.x);
                b.se.y = Math.min(b.se.y,Temp.se.y);
            }  
        }      
        return b;    
    },
    
    // Add a layer to Data Frame
    addLayer: function (layer){
        layer.index = this.getLayerCount();
        this.Layers.push(layer);        
        this.properties.redrawing = 0;
        //layer.Events.newIndex = this._sortLayer.bind(this); 
        if ((layer.param) && (layer.maxScale >= this.properties.mapCStatus.Sc)) {       
            layer.setEventListener('isLoadedData', this._redrawDataFrame.bind(this));
            layer.getData(this.properties.mapCStatus);
        }
        //if (layer.visible) layer.overlayFeature(this.map, this.properties.mapVisExtent);
    },
    
    // Remove a Layer from Data Frame
    removeLayer: function (lid){
        var L = this.Layers;
        var rl = null;
        var r = -1;
        var c = this.getLayerCount();
        this.Layers = new Array();        
        for (i=0;i<c;i++){
            if ((L[i].id == lid) || (L[i].index == lid)){
                r = i;
                rl = L[i];
            } else {
                this.Layers.push(L[i]);
            }
        }
        if (rl) {
            rl.removeFeature(this.map);
        }        
    },
    
    // Remove All Layers in the data frame
    removeAllLayers: function (){
        for (i=0;i<this.getLayerCount();i++){
            this.Layers[i].removeFeature(this.map);            
        }
        this.Layers = new Array();
    },
    
    // Get the current Map information
    _getMapCStatus: function (ir,isx,isy,iex,iey){        
        this.properties.mapCStatus.SX = isx;
        this.properties.mapCStatus.SY = isy;
        this.properties.mapCStatus.EX = iex;
        this.properties.mapCStatus.EY = iey; 
        if (ir != this.properties.mapCStatus.Sc) {
            this._actionFinished();
        }
    },
    
    // ReDraw the content in the 
    _redrawDataFrame: function (){
        var i = this.properties.redrawing;
        if (i < this.getLayerCount()) { 
            ++this.properties.redrawing;
            if ((this.properties.visible) && (this.Layers[i].visible) && (this.Layers[i].maxScale >= this.properties.mapCStatus.Sc)){
                if ((this.Layers[i].BufferMembers.length < 1) || (this.Layers[i].getDynamicReflash())){
                    this.Layers[i].setEventListener('isOverlayed', this._redrawDataFrame.bind(this));
                    this.Layers[i].overlayFeature(this.map, this.properties.mapVisExtent);
                } else {
                    this._redrawDataFrame();    
                }
            } else {                
                this.Layers[i].removeFeature(this.map);
                this._redrawDataFrame();
            }
        } else {
            if (this.Layers[i-1]) this.Layers[i-1].setEventListener('isOverlayed', function (){});
            this.Events.isLoadedData(this);
        }
    },
    
    // Update the data of all layers
    _updateLayers: function (up){        
        var i = this.properties.updating;
        if (i < this.getLayerCount()) {            
            ++this.properties.updating;
            if ((this.Layers[i].maxScale >= this.properties.mapCStatus.Sc) && ((this.Layers[i].dynamicReflash) || (up)) && (this.Layers[i].param) && (this.Layers[i].searchBean)){
                this.Layers[i].setEventListener('isLoadedData', this._updateLayers.bind(this));
                this.Layers[i].getData(this.properties.mapCStatus);
            } else {
                this._updateLayers();
            }
        } else {
            if (this.Layers[i-1]) this.Layers[i-1].setEventListener('isLoadedData', function (){});           
            this.redraw();
        }
    },
    
    _sortLayer: function (){
        this.Layers.sort(this._sortFunc);        
    },
    
    _sortFunc: function (l1,l2){
        return l1.index - l2.index;
    }
});

var GWMapTools = GWMapObject.extend({
    initialize: function (mp, div){
        if (!mp)
	        alert("No Map In the page.");
	    this.map = mp;
	    this.mapTagName = div;
	    this.ClassType      = 'MapTools';
	    
	    this.properties = Object.extend({
	        hasloadingTag:      true,
	        loadingTagID:       '_MLTag',
	        loadingPos:         {h:10,v:-10},
	        loadingText:        'Loading...',
	        loadingTextColor:   '#ffffff',
	        loadingBGColor:     '#ff0000',	        
	        locationBean:          'func/LocationSet.aspx'
	    }, arguments[2] || {});
	    
	    this.datafram   = new Array();
	    
	    // Creating Loading Tag
	    if (this.properties.hasloadingTag) {
            var loadimg = $(div);
            loadimg = document.createElement('div');
            this.properties.loadingTagID = this._generateID(3) + this.properties.loadingTagID;
            loadimg.id = this.properties.loadingTagID;
            var h = this.properties.loadingPos.h;
            var v = this.properties.loadingPos.v;
            var pos = '';
            if (h > 0) pos = 'left:' + h + 'px;'; else pos = 'right:' + Math.abs(h) + 'px;';
            if (v > 0) pos += 'top:' + v + 'px;'; else pos += 'bottom:' + Math.abs(v) + 'px;';
            loadimg.style.cssText='text-align:center;position:absolute;' + pos + 'width:70px; height:16px;z-index:100;';
            loadimg.style.visibility = 'hidden';
            loadimg.style.fontSize = '10pt';
            loadimg.style.color = this.properties.loadingTextColor;
            loadimg.style.backgroundColor = this.properties.loadingBGColor;
            loadimg.innerHTML = this.properties.loadingText;
            $(div).appendChild(loadimg);
            this.loadingTag = $(this.properties.loadingTagID);
        }
    },
    
    _attachDataFrame: function (df){        
        df.setEventListener('isLoadingData',this._showMapLoader.bind(this));
        df.setEventListener('isLoadedData',this._hideMapLoader.bind(this));
        this.datafram.push(df);
    },
    
    _attachLayer: function (l,df){
        return df.addLayer(l);        
    },
    
    _createDataFrame: function (name){
        var df = new DataFrame(name);
        return df;
    },
        
    _createPointLayer: function (name){
        var l = new PointLayer(name);
        return l;
    },
    
    // Show the 'Loading...' Text when loading
    _showMapLoader: function (){   
        if (this.loadingTag) 
            this.loadingTag.style.visibility = '';
    },
    
    // Hide the 'Loading...' Text after loading
    _hideMapLoader: function (){      
        if (this.loadingTag) 
            this.loadingTag.style.visibility = 'hidden';
    },
    
    get2ptDistance: function (p1,p2){
        if ((p1) && (p2)) {
            return (Math.sqrt(Math.pow((p1.x - p2.x),2) + Math.pow((p1.y - p2.y),2)));
        } else {
            return 0;
        }
    }
});

var GWMapToolsBasic = GWMapTools.extend({
    initialize: function (mp, div){
	    this.parent(map, div, arguments[2]);
	    this.sURL = 'http://geoweb.tw/'; 
	    this.ClassType = 'MapToolsBase';
	    //this.mapTagName = div;
	    
	    this.tools = {
	        cityCenter: [{Name:'台北市', x:305542 , y:2778293}, {Name:'基隆市', x:322211, y:2779153}, {Name:'台北縣', x:304285, y:2750048}, {Name:'桃園縣', x:265127, y:2764071}, {Name:'新竹縣', x:264862, y:2730205}, {Name:'新竹市', x:245415, y:2742706}, {Name:'苗栗縣', x:237477, y:2713139}, {Name:'台中市', x:213135, y:2672393}, {Name:'台中縣', x:246606, y:2677552}, {Name:'彰化縣', x:195937, y:2650631}, {Name:'南投縣', x:242438, y:2637402}, {Name:'雲林縣', x:189058, y:2624636}, {Name:'嘉義市', x:193291, y:2597582}, {Name:'嘉義縣', x:177152, y:2594076}, {Name:'台南縣', x:181716, y:2562061}, {Name:'台南市', x:163592, y:2546451}, {Name:'高雄市', x:177482, y:2503522}, {Name:'高雄縣', x:216707, y:2546649}, {Name:'屏東縣', x:213466, y:2490756}, {Name:'台東縣', x:257189, y:2542284}, {Name:'花蓮縣', x:290395, y:2627612}, {Name:'宜蘭縣', x:318242, y:2717240}]
	    };
    },
    
    addDataFrame: function (df){
        this._attachDataFrame(df);
    },
    
    createDataFrame: function (name){
        var df = new DataFrame(this.map, this.mapTagName);
        this._attachDataFrame(df);
    },
        
    searchLocation: function (type, word) {
        var options = {};
        var url = this.sURL + this.properties.locationBean;
        options.method = 'post';
        options.parameters = 'event=' + type + '&all_search_string=' + word;
        this._sendRequest(url,options,this.showLocation);
    },
    
    showLocation: function (req){
        eval(req);
        if (!Err) {
            var s = 2;
            this.map.MoveToRXY(res[0].pt.x,res[0].pt.y,s,false);
        } else {
            alert(Err);
        }
    },
        
    locateByCity: function (CityName){
        var mp = this.map;
        this.tools.cityCenter.each(function(item){if (item.Name == CityName) mp.MoveToRXY(item.x,item.y,7,false);});
    },
    
    /*
    _createPointLayer: function (name,ms,mc,sb){
        var l = new PointLayer(name);
        l.setSearchBean(sb);
        l.setFeaturesLimit(mc);
        l.setMaxScale(ms);        
        return l;
    },
    
    _createLocateResult: function (name, param){
        var df = null;
        for (i=0;i<this.datafram.length;i++) {
            if (this.datafram[i].name == name) df = this.datafram[i];
        }
        if (!df) {
            this.datafram.push(_createDataFrame(name));
            df = this.datafram.last();
        }
        var l = _createPointLayer('Location',10,1,this.sURL + 'func/LocationBean.aspx');
        l.setParameters(param);
        df.addLayer(l);
        return df;
    },
    
    parseKeywords: function (kw){
        
    },
    
    locateByAddress: function (add){
        var pm = new Object();
        pm.type = 'ByAddress';
        var df = this._createLocateResult('LocationResult',pm);
        df.zoomToLayer(0);
    },
    
    locateByIntersect: function (road1,road2){
        var pm = new Object();
        pm.type = 'ByIntersect';
        var df = this._createLocateResult('LocationResult',pm);
    },
    
    locateByRoad: function (){
        var pm = new Object();
        pm.type = 'ByRoad';
        var df = this._createLocateResult('LocationResult',pm);
    },
    
    locateByPosCode: function (){
        var pm = new Object();
        var df = this._createLocateResult('LocationResult',pm);
    },
    
    */
    //-----------Other assisted function group End----------------                                  
    // Get the Coordinates of one pixel in the screen, it'll return a APoint Object
    getXY: function (px,py) {  
    	var pt = new GWPoint(GetCenterHX(px),GetCenterHY(py));
    	return pt;
    },
    
    // Get the current document size
    getCurrentWinSize: function (){
        var winW;
        var winH;
        if (parseInt(navigator.appVersion) > 3){
            if (navigator.appName == "Netscape") {
                winW = window.innerWidth;
                winH = window.innerHeight;
            }
            if (navigator.appName.indexOf("Microsoft") != -1){
                winW = document.body.offsetWidth;
                winH = document.body.offsetHeight;                
            }
        }
        return [winW, winH];
    },
    
    adjustWindowSize: function (){
        var wSize = getCurrentWinSize();
        var w,h;
        this.map.style.width = w;
        this.map.style.height = h;
    },
    
    // Convert TM2 to WGS84
    TMtoWGS:function (x,y){
    },
    
    // Convert WGS84 to TM2
    WGStoTM:function (lat,lon){
    } 
});


//===========//===========//===========//===========//===========//===========//===========//===========//===========


