var test;
var map = null;
var SIDEBAR_WIDTH = 291;
var current_shape;
var force_uncached_js = null;
var max_cluster_zoom = 15;
var current_center;
var main_map;
var map_options = new VEMapOptions();
var initial_zoom = 4;
var sites_base_url  = '/sites/zoom/'
//map_options.EnableBirdseye = false;

// Local tile root...
//var tile_root = '/tiles/'

// Imagepatch remote tile root
var tile_root = 'http://www.imagepatch.com/ImagePatch/Images/New%20Crunched%20Patches/';

window.onresize = function(){setMapDivWidth(SIDEBAR_WIDTH)}

function setMapDivWidth(sidebar_width){
    if (!sidebar_width) {sidebar_width = jQuery('#sidebar').width() }
    if (jQuery('#sidebar')[0]) {
        jQuery('#ve_map').width(jQuery('body').width() - sidebar_width);
//        jQuery('#ve_map').height(sidebar_width = jQuery('#sidebar').height());
    }
    }


var drawing = false;        // True if we're drawing a polygon
var polyPoints = [];             // The points in the current polyon
var startPin = null;        // Shape to hold the start pin
var drawingObject = null;   // Shape to hold the polyline/polygon
var enable_drawing = false;
var parcel_layer;


function filterNum(str) {
   re = /^\$|,/g;
   // remove "$" and ","
   return str.replace(re, "");
   }

function GetTiles(json) {
        var tile_url = json;
        //var bounds = [new VELatLongRectangle(new VELatLong(49,-123),new VELatLong(47,-121))];
        //var opacity = 0.9;
        var tileSourceSpec = new VETileSourceSpecification(String(Math.random()), tile_url + "/Layer_NewLayer/%4.png");
        //"http://dev.live.com/virtualearth/sdk/layers/lidar/%4.png");
        //tileSourceSpec.NumServers = 1;
        //tileSourceSpec.Bounds = bounds;
        //tileSourceSpec.MinZoomLevel = 1;
        //tileSourceSpec.MaxZoomLevel = 18;
        //tileSourceSpec.Opacity = opacity;
        //tileSourceSpec.ZIndex = 100;
        //console.log(tileSourceSpec);
        map.AddTileLayer(tileSourceSpec, true);
        }

function DeleteTiles(parcel_id)
         {
            map.DeleteTileLayer(parcel_id);
         }

function create_embed_link(feature){
    var coords = [];
    jQuery.each(feature.geometry.coordinates[0], function(i,c){
        coords.push([c[1],c[0]]);
        })
    
    var smap = 'http://maps.google.com/staticmap?'
    smap += 'size=512x512';
    smap += '&maptype=satellite';
    smap += '&key=ABQIAAAARFBfEeey0ac5JKru_9nB4BTBGMsufDkrz0DwG1Xeu8L-3MLhwRSJx7jMoGmTXRYWr8W1k16T7efVvg';
    smap += '&path=weight:8|' + coords.join('|')
    return smap;
    }
    
function createInfoWindow(feature){
    var attribs = feature.properties;
    t = '<div id="feature_' + attribs.id + '">'
    t +=  attribs.address ;
    t += '<br>Description: ' + attribs.description;
    if (attribs.price){ t += '<br>Price: $' + attribs.price; }
    t += '<br>Seller: ' + attribs.seller;
    if (attribs.lot_size) {t += '<br>Lot Size: ' + attribs.lot_size; }
    if (attribs.associated_url) {
      t += '<br><a href="' + attribs.associated_url + '"target="_blank">Website Link</a>';
      }
    if (attribs.photosynth_url) {
        t += '<br><a href="javascript:display_photosynth(' + attribs.id + ');"><img src="/static/images/photosynth_icon.png" border=0> View Photosynth</a>' 
        }
    if (attribs.display_logo) {t += '<br>' + attribs.logo; }
    t += '<br><a href="/sites/' + attribs.id + '/contact">Contact Seller</a>';
    t += '<br>&lt;<a href="/sites/' + attribs.id + '/embed">Embed Site</a>&gt;';
    t += '</div>'
    return t;
    }
    
function createParcelAtlasInfoWindow(json, x, y){
    t = '';
    if (json['sit_full_s'] && json['sit_zip'] && json['state']){
        var addy = [json['sit_full_s'],json['sit_zip'],json['state']].join(', ');
        jQuery('#id_address').val(addy);
        }
    else{
        var addy = '';
        }
    var attribs = {
        'Address' : addy
        //'Owner' : json.owner,
        // 'Assessed Land Value' : json.land_value,
        //'Total Value': json.tot_value,
        //'Lot Size': json.lot_size,
        //'Tax Record Number' : json.apn
      }
    jQuery.each(attribs, function(i,item){
        if (item) {
             t += '<br><b>' + i + '</b>: ' + item + '<br>';
            }
        });
        
     if (main_map){
        t += '<br><br><b><a href="/sites/create/?lat_lon=' + y + ',' + x +'">List this site for sale</a>' ;
        }
        
    if (t) { return t; }
    else {return 'No additional attributes <br>are available for this site';}
    }


function getZoomForBBOX(bbox){
    var max_res = 1.40625;
    var shape_width = Math.abs(bbox[0] - bbox[2]);
    var shape_height = Math.abs(bbox[1] - bbox[3]);
    var view_size = map.GetWidth();
    var idealResolution = Math.max( shape_width  / map.GetWidth(),
                                    shape_height / map.GetHeight());
    for (var i=0; i< 17; i++){
        max_res = max_res / 2; 
        if (max_res < idealResolution) {
            return i ;
            }
        }
    return(17);
    }
    
function getZoomForShape(shape){
    bbox = [shape.Boundingbox.x1, shape.Boundingbox.y1, shape.Boundingbox.x2, shape.Boundingbox.y2]
    return getZoomForBBOX(bbox) - 1;
    }
    
function ClickHandler(e){
    //click on pushpin
    if (e.eventName == "onclick" && e.elementID != null) {
        var shape = map.GetShapeByID(e.elementID);
        if (shape.overlay_id) {
          //GetTiles(shape.overlay_id);
          jQuery.get("/upload/overlay/"+ shape.overlay_id +"/",
              function(data){
              GetTiles(data);
              });

          }
        zoom = getZoomForShape(shape);
         if (map.GetZoomLevel() > zoom) {zoom = map.GetZoomLevel();} 
        map.SetCenterAndZoom(new VELatLong(shape.Latitude,shape.Longitude),zoom);
        }
    }
    
     
// custom onmouseover/hover event    
function ShapeHandler(e){
    if (e.elementID != null) {
        shape = map.GetShapeByID(e.elementID);
        shape.counter += 1;
        if (shape.Title == "cluster") {
             shape.Title = "Click to zoom";
             return;
             }
        else {
            if (shape.counter %2 == 1){
                //mousing over shape
                shape.SetLineColor(new VEColor(255,5,5,0.7)); 
                if (! shape.overlay_id){
                   shape.SetFillColor(new VEColor(0,100,150,0.2)); 
                   }
                current_shape = shape;
                map.ShowInfoBox(shape)//, new VEPixel(map.GetWidth() / 2,map.GetHeight() /2 ));
                }
            else{
                // moved off shape.  
                shape.SetLineColor(new VEColor(255,255,250,0.7)); 
                shape.SetFillColor(new VEColor(200,100,100,0.2)); 
                if (shape.overlay_id){
                   shape.SetFillColor(new VEColor(0,100,150,0.0)); 
                   }
                //map.HideInfoBox();
                }
           }   
        }
    else {
        //moved off map
        return;
        }
    }

jQuery.postJSON = function (url, data, callback) {
    jQuery.ajax({
        'url': url,
        'type': 'post',
        'processData': false,
        'data': JSON.stringify(data),
        contentType: 'application/json',
        success: function (data) { callback(JSON.parse(data)); }
    });
};

function search_parcels(search_term){
jQuery.getJSON("/sites/search/"+ search_term +"/",
        function(data){
        var v = new VEGeoJSON(map); 
        v.addGeoJSON(data)  ;
          
        });
 }

function displayEmbeddedSite(json){
    var v = new VEGeoJSON(map); 
    var lyr = v.addGeoJSON(json)[0];
    var shape = lyr.GetShapeByIndex(0);
    //shape.HideIcon();
        map.SetZoomLevel(getZoomForShape(shape));
        if (shape.overlay_id) {
          jQuery.get("/upload/overlay/"+ shape.overlay_id +"/",
              function(data){
              GetTiles(data);
              });
          }
    }


function zoomToParcel(){
    var parcel_id = jQuery(document).getUrlParam("site");
    if (parcel_id) {
        jQuery.get('/sites/'+parcel_id + '/',
        function(data){ 
            var json = eval('(' + data + ')');
            if (json.bbox){
                var zoom = getZoomForBBOX(json.bbox);
                map.SetCenterAndZoom(new VELatLong(json.centroid[1],json.centroid[0]),zoom);
                //draw the single parcel if this is an embed link
                if (jQuery(document).getUrlParam("site")){
                    displayEmbeddedSite(json);
                    //addParcelAtlasTiles();
                    }
                }
            });
        }
    }
    
function getMapBbox(extended){
    //Retrieve the boundaries of the mapview
    var ulPixel  = new VEPixel(0, 0);
    var brPixel  = new VEPixel(map.GetWidth(), map.GetHeight());
    var ulLatLong = map.PixelToLatLong(ulPixel);
    var ulLat = ulLatLong.Latitude;
    var ulLong = ulLatLong.Longitude;
    var brLatLong = map.PixelToLatLong(brPixel);
    var brLat = brLatLong.Latitude;
    var brLong = brLatLong.Longitude;
    //return [[ulLong, ulLat],[brLong, brLat]];
    if (extended) {return [ulLong -.5, ulLat + .5 , brLong + .5, brLat - .5].join(',');}
    return [ulLong, ulLat, brLong, brLat].join(',');
    }
    
function testBboxBuffer(){
    //checks to see if we've moved outside of our buffer, and need to re-request parcels
    
    }
    
function panHandler(e){
    // if we panned, and are at bbox zoom level, and we've moved enough since last pan, then get new parcels
    var cz = map.GetZoomLevel();
    if (cz < max_cluster_zoom) {return;}
    
    if (!current_center){
        current_center = map.GetCenter();
        return;
        }
    if ( Math.abs(map.GetCenter().Longitude - current_center.Longitude) > .5 ||
         Math.abs(map.GetCenter().Latitude - current_center.Latitude) > .5 ) {
            var url = "/sites/json?bbox=" + getMapBbox(.5);
            current_center = map.GetCenter();
            if (force_uncached_js) {url += '&random=' + Math.random();}
            
        jQuery.getJSON(url,
        function(data){
            map.DeleteAllShapes();
            var v = new VEGeoJSON(map); 
            v.addGeoJSON(data)  ;
            });
        }
    }
    
function map_style_change_handler(e){
    if (map.GetMapStyle() == 'b') {map.DeleteAllShapes();}
    else { zoomHandler(1); }
    }

function zoomHandler(e){

    var cz = map.GetZoomLevel();
    if (cz < 3) {return;}
    if (cz < max_cluster_zoom) {
        var url = sites_base_url + map.GetZoomLevel() + "/";
        if (force_uncached_js) {url += Math.random();}
        current_center = null; //don't want to re-request if we're not zoomed in to bbox level
        if (map.GetTileLayerByID("parcel atlas")) {
            map.DeleteTileLayer("parcel atlas");
            enable_parcel_assist('pan');
            }
        }
    else {
        if (!map.GetTileLayerByID("parcel atlas")) { 
            enable_parcel_assist('assist');
            }
        var url = "/sites/json?bbox=" + getMapBbox(.5);
        current_center = map.GetCenter();
        if (force_uncached_js) {url += '&random=' + Math.random();}
        }
    jQuery.getJSON(url,
    function(data){
        if (!drawing) {map.DeleteAllShapes();}
        var v = new VEGeoJSON(map); 
        jQuery.each(data.features, function(i,item){
            });
        v.addGeoJSON(data);
        });
    }

function draw_assisted_coords(json, coords, x, y){
    polyPoints = [];
    for (var i=1; i<coords.length; i++) {
        var ll = new VELatLong( coords[i][1], coords[i][0]) ;
        polyPoints.push(ll);
        }
    jQuery('#id_geometry').val(wktFromPolyPoints(polyPoints));
    drawingObject = new VEShape(VEShapeType.Polygon, polyPoints);
    //drawingObject.HideIcon();
    drawingObject.SetPoints(polyPoints);
    drawingObject.SetFillColor(new VEColor(200,100,100,0.4)); 
    infow = createParcelAtlasInfoWindow(json, x, y);
    drawingObject.SetCustomInfoBox(infow);
    //custom center icon
    var icon = new VECustomIconSpecification();
    icon.Image = "/static/images/draw_pin.png"
    drawingObject.SetCustomIcon(icon); 
    parcel_layer.AddShape(drawingObject);
    complete_polygon(false);
    map.AttachEvent("onmouseover",ShapeHandler);
    map.AttachEvent("onmouseout",ShapeHandler);
    map.ShowInfoBox(drawingObject);
    }
 
function get_address_from_ve_find(layer, resultsArray, places, hasMore, veErrorMessage) { 
    var loc = places[0].Name;
    var locs = loc.split(",");
    if (locs.length < 3){return;}
    var street = locs[0];
    var city = locs[1];
    var state = locs[2].split(" ")[1];
    var zip = locs[2].split(" ")[2];
    var url ="/parcels/assist?street=" + street + '&city=' + city + '&state=' + state + '&zip=' + zip;
    jQuery.getJSON(url, function(data){
        var json = data;
        if (!json.shape) {
         //jQuery('#address_result').html('sorry, parcel-assist is not available at this location- please continue'); 
         return;
         }
        else {
            var coords = json.shape.coordinates[0];
            draw_assisted_coords(json, coords);
            }
        });
    } 

function attempt_parcel_assist(address){
    map.Find(null,address, null, null, null, null, true, true, null, true, get_address_from_ve_find);
    }
    
function parcel_assist(e){
    parcel_layer.DeleteAllShapes();
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);
    get_parcel_from_ll(LL.Longitude, LL.Latitude);
    }

function get_parcel_from_ll(lon, lat){
    var url ="/parcels/assist?lat=" + lat + '&lon=' + lon;
    jQuery.getJSON(url, function(data){
        json = data;
        if (!json) {
            if (!main_map){
            //    alert('Please select, draw your site manually');
                }
            }
        if (json){
            var coords = json.shape.coordinates[0];
            draw_assisted_coords(json, coords, lon, lat);
            }
        });
    }
    
function addParcelAtlasTiles() {
    var guid = '64B6FB32-8BDD-DD11-AF04-0003FF70C8AE'
    var turl = 'http://services.parcelatlas.com/MapTileHandler.ashx?qkey=%4&ContractID=' + guid;
    var tileSourceSpec = new VETileSourceSpecification("parcel atlas", turl);
    tileSourceSpec.ZIndex = 100;
    map.AddTileLayer(tileSourceSpec, true);
    }
    
    
function enable_parcel_assist(type){
    if (type == 'assist'){
        map.AttachEvent("onclick",parcel_assist);
        enable_drawing=false;
        addParcelAtlasTiles();
        document.getElementById("ve_map").childNodes[0].style.cursor = "crosshair"; 
        }
    if (type == 'draw') {
        try {
            map.DetachEvent("onclick",parcel_assist);
            map.DeleteTileLayer("parcel atlas");
            }catch(e){}
        enable_drawing=true;
        map.DetachEvent('onclick',parcel_assist);
        map.DetachEvent('onclick',ClickHandler);
        map.DetachEvent('onendzoom',zoomHandler);
        map.AttachEvent('onclick', OnPolyDrawingMouseClick);
        document.getElementById("ve_map").childNodes[0].style.cursor = "crosshair"; 
        }
        
    if (type == 'pan'){
        try {
            map.DetachEvent("onclick",parcel_assist);
            map.DeleteTileLayer("parcel atlas");
            }catch(e){}
        enable_drawing = false;
        map.DetachEvent('onclick', OnPolyDrawingMouseClick);
        map.AttachEvent('onclick',ClickHandler);
        map.AttachEvent('onendzoom',zoomHandler);
        document.getElementById("ve_map").childNodes[0].style.cursor = "";
        if (map.GetZoomLevel() >=max_cluster_zoom) {  enable_parcel_assist('assist')}; 
        }

    }

function enableBirdsEye(){
    if(map.IsBirdseyeAvailable()) {
        map.SetBirdseyeScene(map.GetCenter());
        jQuery('#birdsEyeRotate')[0].style.display ='block';
        jQuery('#birdsEyeControl')[0].style.display ='none';
        jQuery('#mapEmbedControl')[0].style.display ='block';
        }
    else{alert('birds eye not currently available here');}
    }

function enableMapMode(){
    map.SetMapStyle(VEMapStyle.Hybrid);
        jQuery('#birdsEyeControl')[0].style.display ='block';
        jQuery('#birdsEyeRotate')[0].style.display ='none';
        jQuery('#mapEmbedControl')[0].style.display ='none';
    }



function rotateBirdsEye(){
   var cd = map.GetBirdseyeScene().GetOrientation();
   switch(cd) {
       case 'North': map.SetBirdseyeOrientation(VEOrientation.East);
    break;
       case 'East': map.SetBirdseyeOrientation(VEOrientation.South);
        break;
       case 'South':  map.SetBirdseyeOrientation(VEOrientation.West);
        break;
       default:      map.SetBirdseyeOrientation(VEOrientation.North);
        break;
     } 
   
   }

function addBirdsEyeEmbedded(){
    var loscontrol = document.createElement("div"); 
    loscontrol.id = "BirdsEyeEmbedded";
    loscontrol.style.top ="70px"; 
    loscontrol.style.left = "15px"; 
    loscontrol.style.background = 'transparent';
    loscontrol.style.color = 'white';
    loscontrol.innerHTML = '<div id="birdsEyeControl"><a href="#" onclick="enableBirdsEye(); return false;"><img src="/static/images/Oblique1.jpg" border=0></a></div>'
    map.AddControl(loscontrol);
    
    var loscontrol2 = document.createElement("div"); 
    loscontrol2.id = "BirdsEyeRotate";
    loscontrol2.style.top ="95px"; 
    loscontrol2.style.left = "15px"; 
    loscontrol2.style.background = 'transparent';
    loscontrol2.style.color = 'white';
    loscontrol2.innerHTML = '<div id="birdsEyeRotate"><a href="#" onclick="rotateBirdsEye(); return false;"><img src="/static/images/oblique_rotate.jpg" border=0></a></div>'
    map.AddControl(loscontrol2);
    }
    
function addMapEmbedded(){
    var loscontrol = document.createElement("div"); 
    loscontrol.id = "MapEmbedded";
    loscontrol.style.top ="70px"; 
    loscontrol.style.left = "15px"; 
    loscontrol.style.background = 'transparent';
    loscontrol.style.color = 'white';
    loscontrol.innerHTML = '<div id="mapEmbedControl"><a href="#" onclick="enableMapMode(); return false;"><img src="/static/images/Oblique2.jpg" border=0></a></div>'
    map.AddControl(loscontrol);
    }

function addLOSAttribute(){
    var loscontrol = document.createElement("div"); 
    loscontrol.id = "LOSAttribution";
    loscontrol.style.top ="15px"; 
    loscontrol.style.left = "110px"; 
    loscontrol.style.background = 'transparent';
    loscontrol.innerHTML = '<div id="losControl"><a href="http://lineofsite.com" target="_blank">www.lineofsite.com</a></div>'; 
    map.AddControl(loscontrol);
    }
    
function init_edit_parcel_map(){
    map = new VEMap('ve_map');
    setMapDivWidth(SIDEBAR_WIDTH);
    map.LoadMap(new VELatLong(38, -100, 0, VEAltitudeMode.RelativeToGround), initial_zoom, 
                                VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false, 0, map_options);
    parcel_layer = new VEShapeLayer();
    map.AddShapeLayer(parcel_layer);
    map.AttachEvent("onclick", ClickHandler);
    var parcel_id = jQuery('#parcel_id')[0].innerText;
    jQuery.getJSON("/sites/" + parcel_id + "/?random=" + Math.random(),
        function(data){
        var v = new VEGeoJSON(map); 
        var l = v.addGeoJSON(data, null,null );
        var shape = l[0].GetShapeByIndex(0);
        zoom = getZoomForShape(shape);
        map.SetCenterAndZoom(new VELatLong(shape.Latitude,shape.Longitude),zoom + 1);
        });
    setGeomFromDiv();
    }
    
function init_create_parcel_map(){
    map = new VEMap('ve_map');
    setMapDivWidth(SIDEBAR_WIDTH);
    
    map.LoadMap(new VELatLong(38, -100, 0, VEAltitudeMode.RelativeToGround), initial_zoom, 
                                VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false, 0, map_options);
    parcel_layer = new VEShapeLayer();
    var url = sites_base_url + map.GetZoomLevel() + "/";
    jQuery.getJSON(url,
        function(data){
        var v = new VEGeoJSON(map); 
        jQuery.each(data.features, function(i,item){
            });
        v.addGeoJSON(data)  ;
        });
    map.AddShapeLayer(parcel_layer);
    //map.AttachEvent("onclick", OnPolyDrawingMouseClick);
    map.AttachEvent("onclick", ClickHandler);
    map.AttachEvent("onmousemove", OnMouseMove);
    zoomToParcel();
     jQuery('#id_description').change(function(){
          if (this.value.length > 150) {
               alert('Your description cannot be more than 150 characters long')
               this.value = this.value.substring(0,150);
               }
          });
    if (jQuery('#id_geometry').val()) {
        setGeomFromDiv();
        }
    else {
    // This event seems to trip up digitizing
    map.AttachEvent("onendzoom",zoomHandler);
    map.AttachEvent("onendpan",panHandler);
    map.AttachEvent("onmouseover",ShapeHandler);
    map.AttachEvent("onmouseout",ShapeHandler);

        }
    var lat_lon = jQuery(document).getUrlParam("lat_lon");
        if (lat_lon){
            ll = lat_lon.split(',');
            lat = ll[0]
            lon = ll[1]
            map.SetCenterAndZoom(new VELatLong(lat,lon),16);
            get_parcel_from_ll(lon,lat);
        }
    }


    
function init_map(){
    map = new VEMap('ve_map');
    main_map = true;
     if (jQuery(document).getUrlParam("embed")){
        map.SetDashboardSize(VEDashboardSize.Tiny);
        map.LoadMap(new VELatLong(38, -100, 0, VEAltitudeMode.RelativeToGround), 15, 
                                VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false, 0, map_options);
        }
    else{
        map.LoadMap(new VELatLong(38, -100, 0, VEAltitudeMode.RelativeToGround), initial_zoom, 
                                VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false, 0, map_options);
        setMapDivWidth(SIDEBAR_WIDTH);
        var cur_user = jQuery(document).getUrlParam("user");
        if (cur_user) { 
            sites_base_url = '/sites/' + cur_user + '/zoom/'; 
            if (jQuery(document).getUrlParam("display_links")){
                jQuery('#site_links')[0].style.display = 'none';
                }
            try{
                jQuery("#welcome_banner")[0].style.display = 'none';
                jQuery("#hid")[0].style.display='none';
            }catch(e){}
            }

        map.AttachEvent("onendzoom",zoomHandler);
        map.AttachEvent("onendpan",panHandler);
        map.AttachEvent("onchangemapstyle", map_style_change_handler);
        map.AttachEvent("onmouseover",ShapeHandler);
        map.AttachEvent("onmouseout",ShapeHandler);
        map.AttachEvent("onclick", ClickHandler);
            }

    parcel_layer = new VEShapeLayer();
    map.AddShapeLayer(parcel_layer);
    if (jQuery(document).getUrlParam("site")){
        map.DetachEvent("onendzoom",zoomHandler);
        map.DetachEvent("onendpan",panHandler);
        map.DetachEvent("onchangemapstyle", map_style_change_handler);
        zoomToParcel();
        }
    else {
        var url = sites_base_url + map.GetZoomLevel() + "/";
        jQuery.getJSON(url,
        function(data){
            var v = new VEGeoJSON(map); 
            v.addGeoJSON(data);
            if (cur_user) {
                var ez = getZoomForBBOX(data.bbox[0]);
                var ctr = data.centroid;
                map.SetCenterAndZoom(new VELatLong(ctr[1],ctr[0]),ez - 1);
                }
            });
      }

     if (jQuery(document).getUrlParam("embed")){ 
        addLOSAttribute();
        addBirdsEyeEmbedded();
        addMapEmbedded();        
        jQuery('#mapEmbedControl')[0].style.display ='none';
        jQuery('#birdsEyeRotate')[0].style.display ='none';
        };
}   
    
    
/////////////////////////////// FOR DRAWING    
function wktFromPolyPoints(pp){
    pts = [];
    wkt ='SRID=4326;POLYGON(('
    jQuery.each(pp, function(i,p){
        pts.push(p.Longitude.toFixed(6) + ' ' + p.Latitude.toFixed(6))
        });
    pts.push(pp[0].Longitude.toFixed(6) + ' ' + pp[0].Latitude.toFixed(6))
    return wkt + pts.join(',') + '))';
    }
    
    
// http://totusterra.com/index.php/2008/09/29/drawing-a-polygon-on-to-a-virtual-earth-
// Mouse click handler that controls over-all state
function OnPolyDrawingMouseClick(e) {
    // Get the latitude & longitude where the map was clicked
    var clickLatLong = map.PixelToLatLong( new VEPixel( e.mapX, e.mapY ) );
    if ((e.rightMouseButton && !drawing) || 
        (!drawing && enable_drawing)) {
            StartDrawing(clickLatLong);
            }
    else if ((startPin != null) && (e.elementID != null) &&
            (e.elementID.indexOf(startPin.GetID()) == 0) && 
            (polyPoints.length >= 3)) 
         complete_polygon(true);
    else if (e.leftMouseButton && drawing) {
        AddPoint(clickLatLong);}
    else if (e.rightMouseButton && drawing) 
        AbandonDrawing();
    }

function getArea(points) {
    points.push(points[0]);
    var area = 0.0;
    var sum = 0.0;
    for (var i=0; i<points.length - 1; i++) {
        var b = points[i];
        var c = points[i+1];
        sum += (b.Longitude + c.Longitude) * (c.Latitude - b.Latitude);
    }
    area = - sum / 2.0;
    return area;
    }

function validateArea(wkt) {
    jQuery.post('/geoajax/fetcharea/',
      {'geometry':wkt},
      // 300 Acres = 1214056.92672 Square Meter
      // 840581841943.0
      function(data){
       var area = eval(data);
       var acres = area / 4046.85;
       if (acres > 1500) {
             alert('This site is too large, and cannot be saved. If your site is over 1500 acres, please email us at Support@Lineofsite.com for additional information.');
             jQuery('#id_geometry').val('');
           } else {
             jQuery('#id_geometry').val(wkt);
           }
      }, "text")    
    }

    function setGeomFromDiv() {
        var ewkt = jQuery('#id_geometry').val();
        if (ewkt){
            jQuery.post('/geoajax/getbbox/',
              {'geometry':ewkt},
              function(data){
                  var bbox = eval(data);
                  var zoom = getZoomForBBOX(bbox);
                  map.SetCenterAndZoom(new VELatLong(bbox[1],bbox[0]),zoom);
              
              // add the shape
              jQuery.post('/geoajax/asjson/',
                  {'geometry':ewkt},
                    function(data){
                      var v = new VEGeoJSON(map);
                      var json = eval('(' + data + ')')
                      v.addGeoJSON(json);
                      //var shape = map.GetShapeLayerByIndex(0)
                      //zoom = getZoomForShape(shape);
                      //map.SetCenterAndZoom(new VELatLong(shape.Latitude,shape.Longitude),zoom);
              
                  });
            });
        }      
        
    }


function display_photosynth(site_id){
    w = jQuery('body').width();
    h = jQuery('body').height();
    $('#photosynth_pop')[0].style.width = (w - 100) + 'px';
    $('#photosynth_pop')[0].style.height = (h - 200) + 'px';
    $('#photosynth_pop').load('/sites/' + site_id + '/photosynth/?width=' + (w - 200) + '&height=' + (h - 100) );
    $('#photosynth_pop')[0].style.display = 'block';
    
    }
function close_photosynth(){
    $('#photosynth_pop')[0].style.display = 'none';
    }
    
        
// Starts a new polygon
function StartDrawing(ll) {
    parcel_layer.DeleteAllShapes()
    // Set the flag to true and create a new list of points and 
    // initialize at the current location
    drawing = true;             
    polyPoints = [ ll ];
    // set custom pushpin
    var icon = new VECustomIconSpecification();
    icon.Image = "/static/images/draw_pin.png"
    // create a start pin
    startPin = new VEShape(VEShapeType.Pushpin, ll);
    startPin.SetTitle("Move your mouse and click around to draw.<br /><br />Click on green square to complete.<br /><br />Right click to start over.");
    startPin.SetCustomIcon(icon); 
    map.AddShape(startPin);

    // Polygons require 3 points, until we have them, just draw a line 
    drawingObject = new VEShape(VEShapeType.Polyline, [polyPoints[0], polyPoints[0]]);
    drawingObject.SetLineWidth(2);
    drawingObject.SetFillColor(new VEColor(200,100,100,0.4)); 
    parcel_layer.AddShape(drawingObject);
    drawingObject.HideIcon();
}

// When the user clicks on the start icon, it completes the polygon.
function complete_polygon(check_area) {
    // Complete the polygon
    drawingObject.SetPoints(polyPoints);
    // remove the start icon
    if(startPin) { map.DeleteShape(startPin);}
    //var parea = Math.abs(getArea(polyPoints));
    if (check_area) {validateArea(wktFromPolyPoints(polyPoints));}
    //v = new VEGeoJSON(map)
    //v.getGeoJSON(polyPoints);
    drawing = false;
    polyPoints = [];
    drawingObject = null;
    startPin = null;
    
    }


// Add a point to the polygon.
function AddPoint(ll) {
    // add the point to the list of points for polygon
    polyPoints.push(ll);

    // if we are up to 2 fixed points, replace the line segment
    // with a polygon.
    if (polyPoints.length == 2) 
    {
        // delete the line
        map.DeleteShape(drawingObject);

        // create the polygon
        drawingObject = new VEShape(VEShapeType.Polygon, polyPoints.concat([polyPoints[1]]));
        drawingObject.SetFillColor(new VEColor(200,100,100,0.5)); 
        drawingObject.HideIcon();
        parcel_layer.AddShape(drawingObject);
    }
}

// The user abandoned this polygon, so clear everything out
function AbandonDrawing() {
    drawing = false;
    parcel_layer.DeleteShape(drawingObject);
    drawingObject = null;
    map.DeleteShape(startPin);
    startPin = null;
    }

            
// Mouse Move handler.  Update the polygon everytime the mouse moves.
function OnMouseMove(e) 
{
    // if we're currently drawing a polygon, then update the last data point
    // to reflect where the mouse currently is.
    if (drawing) {
        var mouseLatLong = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
        drawingObject.SetPoints(polyPoints.concat([mouseLatLong]));
        }
    }
    
