var blueIcon;
var greenIcon;
var orangeIcon;
var yellowIcon;
var homeIcon;
var clsIcon;
var alertDogIcon;
var alertCatIcon;
var alertOtherIcon;
var bounds;
var map;
var geocoder;
var addressArray = new Array();
var temp_country='';
var current_address_temp;var temp_location;var temp_flag;
jQuery(document).ready(function(){
    
    if(jQuery('#neighborhoodMap').length < 1)
        return false;

    blueIcon = createIcon('blue');    
    greenIcon = createIcon('green');    
    orangeIcon = createIcon('orange');
    yellowIcon = createIcon('yellow');
    homeIcon = createIcon('home');
    clsIcon = createIcon('green');
    alertDogIcon = createIcon('redblock');
    alertCatIcon = createIcon('blueblock');
    alertOtherIcon = createIcon('yellowblock');    
    //hideShadow2();
});

function createMap(){
    if(jQuery('#neighborhoodMap').length < 1)
        return false;
    map = new GMap2(document.getElementById("neighborhoodMap"));
    map.setUIToDefault();
    map.disableScrollWheelZoom();
    geocoder = new GClientGeocoder();
    bounds = new GLatLngBounds();
}

function clearMap(){
	    map.clearOverlays();
}


function updateGoogleMap(options){
    options = jQuery.extend({'address':'', 'urlPostfix':'', 'mapFor': 0, 'zoom': 0, 'center':0}, options);
    if(map == undefined){        
        createMap();
    }    
    temp_flag=0;
    if(options.address){
        address_temp = bindAddress(options.address);
        current_address_temp = options.address;
        temp_flag=geocoder.getLocations(address_temp, addAddressToMap);
        
    }
    map.clearOverlays();      
    
    //var url = options.mapFor?'/main/refreshGroupMap':'/main/refreshNeighborhoodMap';
    var url = '/main/refreshNeighborhoodMap' + (options.urlPostfix.length?("?urlPostfix=" + options.urlPostfix):'');
    
    jQuery.post(url, '', function(data){ 
        jQuery.each(data.items, function(index, item){
            if(typeof item == 'object'){
            return_marker = map_createMarker({ 
                'pointTitle'  : item.title,
                'pointLatLng' : item.location,
                'pointHTML'   : (item.type=='online'?undefined:item.desc),
                'pointIcon'   : item.type=='alert_other'? alertOtherIcon :(item.type=='alert_cat'? alertCatIcon :(item.type=='alert_dog'? alertDogIcon :(item.type=='home'? homeIcon :(item.type=='online'?orangeIcon:(item.type=='group'?yellowIcon:(item.type=='friend'?blueIcon:(item.type=='cls'?clsIcon:greenIcon))))))),
                'pointCustomFunction': ["infowindowopen", infoWindowOpenFunction],
                'pointMinZoom': 1, 
                'pointMaxZoom': 17,
                'online'      : (item.type=='online'?item.street:undefined)
            });
            if(item.type=='home')
                temp_location = item.location;
            /**
            * code for set map bounds
            *
            */           
                bounds.extend(new GLatLng(item.location[0],item.location[1]));
            }
        });
       
       if(!temp_flag)
       {    
            map.setCenter(options.center ? (new GLatLng(options.center[0], options.center[1])) : (temp_location?(new GLatLng(temp_location[0], temp_location[1])):bounds.getCenter()));//bounds.getCenter());
            var level_m =(options.zoom)? options.zoom : map.getBoundsZoomLevel(bounds);        
            level_m = (level_m < 1) ? 1 : level_m;
            map.setZoom(level_m);
        }
       // alert(options.address);
      
          
    }, "json"); 
    
    
    
    
}

function bindAddress(address){
    var temp_return ='';
    switch(address){
        case 'subdivision': temp_return += ", " + addressArray[0];
        case 'city': temp_return += ", " + addressArray[1];
        case 'county': temp_return += ", " +addressArray[2];
        case 'state': temp_return += ", " + addressArray[3];
        case 'country': temp_return += ", " + addressArray[5];break;
        case 'zipcode' : temp_return = ", " + addressArray[3] + ", " + addressArray[4] + ", " + addressArray[5];break;
    }
    temp_country =temp_return.substr(1); 
    return temp_country;
}

/**
* code to create colored Icons. 
*
*/  
function createIcon(val){
    var tempIcon = new GIcon(G_DEFAULT_ICON);
    
    if(val=='home'){
        tempIcon.iconSize = new GSize(24, 24);    
        tempIcon.iconAnchor = new GPoint(12, 24);
        tempIcon.infoWindowAnchor = new GPoint(12, 12);
    }
    else{
        if(val =='cls'){
            tempIcon.iconSize = new GSize(18, 18);    
            tempIcon.iconAnchor = new GPoint(12, 18);
            tempIcon.infoWindowAnchor = new GPoint(12, 12);
        }else{
            if(val =='yellowblock' || val =='redblock' || val =='blueblock'){
                tempIcon.iconSize = new GSize(7, 7);    
                tempIcon.iconAnchor = new GPoint(5, 12);
                tempIcon.infoWindowAnchor = new GPoint(5, 1);
            }else{
                tempIcon.iconSize = new GSize(10, 12);    
                tempIcon.iconAnchor = new GPoint(5, 12);
                tempIcon.infoWindowAnchor = new GPoint(5, 1);
            }
        }
    }
    tempIcon.shadow = '';
    if(val=='home')
        tempIcon.image = "/images/icons/house24.png";
    else{
        if(val=='cls')
            tempIcon.image = "/images/business.png";
        else
            tempIcon.image = "/images/"+ val +".png";
    }
    
    return tempIcon;
}

/**
* code to hide info. window shadow
*
*/
function hideIt()
{
    for (j=0;j<=80;j++)
	{
		setTimeout("hideShadow()",j*25);
	}	
}
function hideShadow()
{
	jQuery('DIV.gmnoprint DIV IMG[src=http://maps.gstatic.com/intl/en_ALL/mapfiles/iws3.png]').hide();	
}

function hideShadow2()
{
	if(!jQuery('#logocontrol').next().hasClass('gmnoprint'))
	{
		jQuery('#logocontrol').next().hide();
		setTimeout("hideShadow2()",50);
	}	
}

function zipCodeSearch(q){
    var zoom=7;    
    addressArray = ['', '', '', '', q, 'US'];
    jQuery.post('/main/loginMap', 'q=,,,'+q+',', function(data){updateGoogleMap({'address' : 'zipcode'});},"json");
}

var infoWindowOpenFunction = function() { /*noupdate=false; hideIt();*/map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.visibility="hidden";}
var maploadcomplete = function(){
    jQuery('#lmc3d').find('#lmcslider').css('height', '24px');
    jQuery('#lmc3d').find('#lmczo').css('top', '79px');
    jQuery('#lmc3d').show();
}

function map_createMarker(test) {    
   	
   var options = jQuery.extend({}, {
			'pointLatLng': undefined,
			'pointHTML': undefined,
			'pointOpenHTMLEvent': 'click',
			'pointIsDraggable': false,
			'pointIsRemovable': false,
			'pointRemoveEvent': 'dblclick',
			'pointMinZoom': 4,
			'pointMaxZoom': 17,
			'pointIcon': undefined,
			'centerMap': false,
			'centerMoveMethod':'normal',
            'online': undefined
		}, test);
	
	var markerOptions = {}
	
	if (typeof options.pointIcon == 'object')
		jQuery.extend(markerOptions, {'icon': options.pointIcon, 'title': options.pointTitle});
		
	if (options.pointIsDraggable)
		jQuery.extend(markerOptions, {'draggable': options.pointIsDraggable});
			
	/*if (options.centerMap) {
		switch (options.centerMoveMethod) {
			case 'normal':
				map.setCenter(new GLatLng(options.pointLatLng[0],options.pointLatLng[1]));
			break;
			case 'pan':
				map.panTo(new GLatLng(options.pointLatLng[0],options.pointLatLng[1]));
			break;
		}
	}*/
		
		
	// Create marker, optional parameter to make it draggable
	var marker = new GMarker(new GLatLng(options.pointLatLng[0],options.pointLatLng[1]), markerOptions);
		
	// If it has HTML to pass in, add an event listner for a click
	if(options.pointHTML)
		GEvent.addListener(marker, options.pointOpenHTMLEvent, function(){
			marker.openInfoWindowHtml(options.pointHTML);
		});
        
    // If it has status online, add an event listner for a click to open chat window
	if(options.online)
		GEvent.addListener(marker, options.pointOpenHTMLEvent, function(){
			chatWith(options.online);
		});
        
	// If it is removable, add dblclick event
	if(options.pointIsRemovable)
		GEvent.addListener(marker, options.pointRemoveEvent, function(){
			map.removeOverlay(marker);
		});
        
    if(options.pointCustomFunction)
        GEvent.addListener(marker, options.pointCustomFunction[0], options.pointCustomFunction[1]);


    GEvent.addListener(map, 'load', maploadcomplete);
    GEvent.addListener(map, 'moveend', maploadcomplete);
    GEvent.addListener(map, 'dragend', maploadcomplete);
    GEvent.addListener(map, 'zoomend', maploadcomplete);
    
	// If the marker manager exists, add it
	map.addOverlay(marker);		
	
    return marker;
}

function trim (myString)
{
return myString.replace(/^s+/g,'').replace(/s+$/g,'')
}

// addAddressToMap() is called when the geocoder returns an
    // answer.  It adds a marker to the map with an open info window
    // showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {      
      if (!response || response.Status.code != 200) {
        return false;
      } else {
        place = response.Placemark[0];
        // Define the two corners of the bounding box
        var sw_temp = new GLatLng(place.ExtendedData.LatLonBox.south, place.ExtendedData.LatLonBox.west);
        var ne_temp = new GLatLng(place.ExtendedData.LatLonBox.north, place.ExtendedData.LatLonBox.east);
        var bounds_temp = new GLatLngBounds(sw_temp, ne_temp);
        
        temp_center = bounds_temp.getCenter();
        temp_zoom = map.getBoundsZoomLevel(bounds_temp);
        
        temp_zoom=(jQuery.trim(temp_country.toLowerCase())=='united state' || jQuery.trim(temp_country.toLowerCase())=='us' || jQuery.trim(temp_country.toLowerCase())=='united states')?temp_zoom+1:temp_zoom;         
        if(current_address_temp=='subdivision' || current_address_temp=='county')
            map.setCenter(new GLatLng(temp_location[0],temp_location[1]), temp_zoom);
        else
            map.setCenter(temp_center, temp_zoom);
            
         temp_flag=1;                 
      }
     
                
    }