 /**********************************************************************/
 
/***********************************************************************      
	Copyright: 		Information Goes Here...
	
	
	FileName:		location.js
	Description: 	This script is used to call various Methods from 
					Google API.
                 	Following are the Files on which this script is dependent:
                 		1.
                 		2.
************************************************************************/      

/*??? What are these variables for - these are global variables
store current lattitude and longtitude (rather than using a hidden form variable)
keep track of the map and the memory marker 
validvalue gets set IF you actually set a position so that you don't just get the defualt
written in
mem lat and long seem to be just left over
*/
var map=null;
var marker = null;
var validvalue=false;
var latitudeValue=null;
var longitudeValue=null;
var pointConvert=null;
var memlat=null;
var memlong=null;
var hasmoved=false;
//var mapbase = 'http://www.nationsmemorybank.com';
//var mapbase = 'http://ec2-72-44-57-98.z-1.compute-1.amazonaws.com';


function addItem( item ) {
   if (( item[5] != memlat ) && (item[6] != memlong )) { 
           point =  new GLatLng( item[5] , item[6] );
           memory_title=item[0];
           memory_desc=item[1];
           memory_tag=item[3];
           memory_date=item[2];
           memory_owner=item[4];
           memory_label=item[7];
           memory_id = item[8];
          map.addOverlay(
                    createMarker(point, 
                                        memory_id,
                                        memory_title,
                                        memory_desc,
                                        memory_tag,
                                        memory_date,
                                        memory_owner , 
                                        memory_label));
    }                      
}



function addMarkers (transport){               
    var response = transport.responseText || "no";
    items = response.evalJSON();
    items.each( addItem );                  
}


function OtherMemories(forCommunity) {
    map.clearOverlays() ;
    if ( marker != null ) {
        map.addOverlay(marker);
    }        
    var bounds = map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    if(forCommunity)
        var vURL = '/location/memories/' + sw.lat()  + '/' + sw.lng() + '/' + ne.lat()  + '/' + ne.lng() + '/' + forCommunity + '/' ;
    else
        var vURL = '/location/memories/' + sw.lat()  + '/' + sw.lng() + '/' + ne.lat()  + '/' + ne.lng() + '/' ;
    
    new Ajax.Request(vURL , {
            method:'get',
            onSuccess: addMarkers ,            
             onFailure: function(){ 
                alert("Unable to contact server");
            }
            });	  	  
}
	
function makeIcon( community ) {
    var icon = new GIcon();
    icon.image = "http://ec2-72-44-57-98.z-1.compute-1.amazonaws.com/site_media/map/"+ community.toLowerCase() + ".png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    return icon
}

var icons = $H();
//var items = new Array( "family","military",
//            "fashion","food","sport", "home","transport","house","local","travel" ,
//            "general");
/*
function setCommunityList()
{   
    var strCommunity = '';
    alert($('community'));
    if($('community') != null && $('community').length != null){
        for(i=0;i < $('community').length-1; i++){
            if($('community').options[i].value != ''){
                strCommunity = strCommunity + $('community').options[i].value + ",";
            }
        }
        strCommunity = strCommunity + $('community').options[$('community').length-1].value;
        items = new Array( strCommunity);
    }
    else 
        strCommunity = "family,military,fashion,food,sport, home,transport,house,local,travel ,general";
    
    var retVal = strCommunity.split(',');
    return retVal;
}
*/
//var items = setCommunityList();



items.each(function(item) {
  icons[ item] = makeIcon( item );
});            

       

function createMarker(point,memory_id,memory_title,memory_desc,memory_tag,memory_date,
                                                                                memory_owner , memory_label )
{
    icon = icons[memory_label.toLowerCase()];
    var marker = new GMarker(point,icon);
    GEvent.addListener(marker, "click", function() {
        //var pt =marker.getPoint();
        marker.openInfoWindowHtml("<h1><a href=/memory/view/" +  memory_id + ">" +memory_title+"</a></h1> <p>" +
                            memory_date + "</p> <p>"  + memory_desc+ "</p><p>posted by " +
                            memory_owner+ ", Posted in community " +  
                            memory_label + "</p>");
    });
    return marker;
}

function setupmap( mapmode , showmem , forCommunity)
{
    var mapedit = false;
    if (mapmode == 'edit') {
        mapedit = true;
    };
    if ( showmem ) {
        ll = opener.getlonglat()
        if ( ll != undefined )
        {    
            load( ll[0], ll[1], mapedit , showmem );
        } else {
            showMap( mapedit , showmem );
        }
    } else {
        if(forCommunity)
            showMap( mapedit , showmem , forCommunity);
        else
            showMap( mapedit , showmem, false);
    }
}


function showMap( mapeditmode , showmem , forCommunity)
{
	if (GBrowserIsCompatible())
	{
	        // uk for now
	 
                var point = new GLatLng(53.3962494366,-2.97913880546);
		map = new GMap2(this.document.getElementById("map"));
		map.addControl(new GMapTypeControl(), 
		            new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 20)));
		map.addControl(new GOverviewMapControl(),
		        new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20,20))); 
		map.addControl(new GLargeMapControl() , 
		        new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20,20))); 		
                map.setCenter(point , 5);                               
                if (!mapeditmode) { 
                        if ( showmem ) {
                            marker = new GMarker(point, {draggable: false});
                        } 
                if(forCommunity)
                    OtherMemories(forCommunity);  	
                else
                    OtherMemories(false);  	
                
        		addViewListeners( map , marker );
                }  else { 
                    marker = new GMarker(point, {draggable: true});
                    map.addOverlay( marker );
                    addEditListeners( map , marker );			
                };                    
	}
}


 function load(latitude,longitude , mapeditmode , showmem )
 {
	var point = new GLatLng(latitude,longitude);
	memlat = latitude;	memlong = longitude;
	if (GBrowserIsCompatible()) 
	{
		map = new GMap2(this.document.getElementById("map"));
		map.addControl(new GMapTypeControl(), 
		        new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 20)));
		map.addControl(new GOverviewMapControl(),
		        new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20,20))); 
		map.addControl(new GLargeMapControl() , 
		        new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20,20))); 
		//map.setCenter(new GLatLng(21.219957936771163,79.59024537577767), 5);
		map.setCenter( point ,14) ;
		map.clearOverlays();
		if (!mapeditmode) {
		    canmove=false;
		} else {
		    canmove=true;
		}
		if ( showmem ) {
        		marker = new GMarker(point, {draggable: canmove});
	        	map.addOverlay(marker);	
                }            
		if (!mapeditmode ) {
                if($('community') != null && $('community').value.length > 0)
                    OtherMemories($('community').value); 
                else
                    OtherMemories(false); 
        		addViewListeners( map , marker );
                } else {        		
                    addEditListeners( map , marker );
                };                    
	}
}


function addEditListeners(map , marker ) {    
    GEvent.addListener(marker, "dragend", function()  {
            var pt =marker.getPoint();
            map.panTo(pt);
            storePosition(pt);
    });// drag end
    GEvent.addListener(map, "click", function( cmarker , point ) {        
            marker.setPoint( point );
            map.panTo(point);
            storePosition(point);
    });  
}

var holdon = false;

function addViewListeners(map , marker ) {    
    GEvent.addListener(map, "click", function( cmarker , point ) {
            if (!cmarker) {
                map.panTo(point);
                hasmoved=true;
                holdon = false;                    
            } else {
                holdon = true;
            };                
            //OtherMemories(point); 
    });  
    GEvent.addListener(map, "moveend", function( ) {
            if (!holdon ) {
                if($('community') != null && $('community').value.length > 0) {
                    OtherMemories($('community').value); 
                } else {
                    OtherMemories(false); 
                }    
                hasmoved=true;
            } else {
                holdon = false;
            };
    });      
    /*
    GEvent.addListener(map, "zoomend", function( olvl , nlvl ) {
             alert('zoomend');    
            if (!holdon ) {
                if($('community') != null && $('community').value.length > 0) {
                    OtherMemories($('community').value); 
                } else {
                    OtherMemories(false); 
                }
                hasmoved=true;
            } else {
                holdon = false;
            };
    });
    */
}


function storePosition(point) {
    latitudeValue=point.lat()
    longitudeValue=point.lng()
    pointConvert="GEO:LA:"+latitudeValue+";LN:"+longitudeValue;
    validvalue=true;
}

function saveData() {

	if ( validvalue ) {
    		opener.setLonLat( longitudeValue , latitudeValue , pointConvert );
	}
	else if(marker != null)
	{
		var point =marker.getPoint();
    		latitudeValue=point.lat()
    		longitudeValue=point.lng()
    		pointConvert="GEO:LA:"+latitudeValue+";LN:"+longitudeValue;
    		opener.setLonLat( longitudeValue , latitudeValue , pointConvert );
	}
   	self.close();
	return false;
}

var mzvl = 16;
var pcoder = new RegExp( "(?:PO\\:)?((?:(?:B|E|G|L|M|N|S|W)(?:\\d[ABCDEFGHJKSTUW]|\\d{1,2}))|(?:(?:AB|AL|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|EC|EH|EN|EX|FK|FY|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|LA|LD|LE|LL|LN|LS|LU|ME|MK|ML|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(?:\\d[ABEHMNPRVWXY]|\\d{1,2})))\\s*(\\d[ABDEFGHJLNPQRSTUWXYZ][ABDEFGHJLNPQRSTUWXYZ])" ,'i' );
var geocoder = new RegExp( "GEO:LA:(-?\\d+\\.\\d*);LN:(-?\\d+\\.\\d*)" );

function MoveTo( lat , lng ) {
      var point = new GLatLng( lat , lng );
      map.clearOverlays() ;
      map.setCenter( point , 12 ) ;
      
	 if($('maplookupmode') != null && $('maplookupmode').value == 'edit')
	 {
            marker = new GMarker(point, {draggable: true});
            map.addOverlay(marker);	
            addEditListeners( map , marker );
  	 }
  	 else
  	 {
        if($('community') != null && $('community').value.length > 0)
            OtherMemories($('community').value); 
        else
            OtherMemories(false); 
  	 }
      hasmoved=true;
}

function MoveToAndClear( lat , lng ) {
    MoveTo( lat , lng );
    $("placeshere" ).replace( '<div id="placeshere"></div>' );
}

function ClearPlaceshare() {
    $("placeshere" ).replace( '<div id="placeshere"></div>' );
}

function MoveToPostCode(code)
{
    var lat = 0;
    var lng = 0; 
    new Ajax.Request('/location/postcode/' + code + '/',
      {
        method:'get',
            onSuccess: function(transport){
              var response = transport.responseText || "no";
              crds = response.evalJSON();
              if ( crds == "no" ) {
                alert("That is not a valid postcode");
              } else {                  
                  var point = new GLatLng( crds[0] , crds[1] );
                  map.clearOverlays() ;
                  map.setCenter( point , mzvl) ;

		 	if($('maplookupmode') == null || $('maplookupmode').value != 'edit')
		 	{
                    if($('community') != null && $('community').value.length > 0)
                        OtherMemories($('community').value); 
                    else
                        OtherMemories(false); 
	         	}
              };
            },
            onFailure: function(){ 
                alert("Unable to contact server");
            }
      });
  }
  


function TryPlace( term ) {
    new Ajax.Request('/location/place/' + term + '/',
      {
        method:'get',
            onSuccess: function(transport){
              var response = transport.responseText || "no";
              crds = response.evalJSON();
              if ( crds == "no" ) {
                alert("That is not a valid place");
              } else {
                 if ( crds.length == 1 ) {
                    MoveTo( crds[0][2] , crds[0][3] );
                 } else {
			 if(crds.length > 1){
				outp = "<h3>Did you mean?</h3>"  
				crds.each( function( item ) { 
				outp += '<div><a href="';
				outp += 'javascript:MoveToAndClear(' + item[2] + ',' + item[3] + ');">';
				outp += item[0] + ',' + item[1] + '</a></div>';                        
                      } );
			 }
			else
			{
                      outp = "<br><p>No location found with name - <b>"+term +"</b> - try zooming out using the map controls and browse around.</p>"  
			}
                      new Insertion.Top($("placeshere" ), outp );
                };                                          
              };
            },
            onFailure: function(){ 
                alert("Unable to contact server");
            }
      });

}


function moveMapToTerm( term ) {
  // is there a postcode
    if ( match = pcoder.exec(term)) {
           MoveToPostCode( match[1] + match[2] );
    } else  if ( match = geocoder.exec(term )) {
       geoSplit=match[0].split(';');
       lat=geoSplit[0].split("LA:")[1];    
       lng=geoSplit[1].split(":")[1];    
        var point = new GLatLng( lat , lng );
         map.setCenter( point , mzvl );
	
	 if($('maplookupmode') != null && $('maplookupmode').value == 'edit')
	 {
         	marker = new GMarker(point, {draggable: true});
         	map.addOverlay(marker);
  	   	addEditListeners( map , marker );
  	 }
  	 else
  	 {
        if($('community') != null && $('community').value.length > 0)
            OtherMemories($('community').value); 
        else
            OtherMemories(false); 
  	 }
         
    } else {
       TryPlace( term );
    }
}

function SearchMap() {
    term = $( 'mapsearch' ).value;
    moveMapToTerm( term );
}

function uploadMemory(username) {
    if (hasmoved) {
        pt = map.getCenter()
		
        lat = pt.lat();
        lng = pt.lng();
        if ($('mapsearch').value.length > 0 ) {
            extra = '&label=GEO:LA:'+lat+';LN:'+lng
        } else {
            extra = '';
        }
        window.location = '/'+username+'/memory/create/?lat='+lat+'&long='+ lng;
    } else {
        window.location = '/'+username+'/memory/create/';
    }
}

/*
function jsChkLocation(vFldVal)
{
	if(vFldVal.length > 0)
	{

		outp = "<h3>Did you mean?</h3>"  ;
		new Ajax.Request('/location/place/' + vFldVal + '/',{
			
			method:'get',
			onSuccess: function(transport){
				var response = transport.responseText || "no";
				crds = response.evalJSON();
		 		if(crds.length == 1)
			 	{
					document.createMemoryform.nmm_location_lat.value=crds[0][2];
					document.createMemoryform.nmm_location_lon.value=crds[0][3];
         				$("ambiguation").value ='';
					window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
				}
		 		else if(crds.length > 1)
			 	{
					crds.each( function( vFldVal ){ 
						//alert(outp);		
						outp = outp + '<div><a href=';
						outp = outp + '"javascript:MoveToAndClear(\'' +vFldVal[2] + '\',\'' +vFldVal[3] + '\');">';
						outp = outp + vFldVal[0] + ',' + vFldVal[1] + '</a></div>';                        
					});
					
					window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
					$('ambiguation').value = outp;	
			 	}
				//--
				else  if(vFldVal.length > 0)//check for postcode stuff
				{
    					var lat = 0;
					var lng = 0; 
					new Ajax.Request('/location/postcode/' + code + '/',
      					{
        					method:'get',
						onSuccess: function(transport){
							var response = transport.responseText || "no";
							crds = response.evalJSON();
							if ( crds == "no" ) {
              		  				alert("The location you've entered cannot be found, please click on the map button to choose the location.");
								return true;
							} 
					 		else if ( crds.length > 0 )
			 				{
								alert(crds[0]+  '|'+crds[1]);
								$('nmm_location_lat').value=crds[0];
								$('nmm_location_lon').value=crds[1] ;
								window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
								return true;
							}
		              			else if(confirm("The location you've entered cannot be found, do you want to select the loaction from Map?"))
							{
								window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
								return true;
							}
						},
					});
				} //Else ended of checking Postcode
				//--
             			else if(confirm("Do you want to select the exact loaction from Map?"))
				{
					window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
					return true;
				}
			},
		          
			onFailure: function(){ 
                		//alert("Unable to contact server");
              		if(confirm("The location you've entered cannot be found, do you want to select the loaction from Map?"))
				{
					window.open('/location/edit/','imagewindow','status=0,toolbar=0,top=10,left=10,resizable=yes,scrollable=yes, height=600px,width=510px;');
				}
			}
		});
	}    
	else
	{
		$("ambiguation").value ='';
	}
}
*/
