// ------------------
// Vars declarations
// ------------------
var selectedRow = -1;
var selectedList = null;
var currentData = null;
var currentShortlist = null;
var listings_markers = null;
var layers_markers = null;
var shortlist_markers = null;
var first_load = true;
var ajaxListingsParams;
var ajaxLayersParams;
var id_maptimer;
var searching_enabled = true;
var shortlist_enabled = true;
var page_header_height = 150; // height of the page header
var menu_heights = [47,84]; // possible heights for the top menu
var separator_heights = [35,72]; // possible heights for the vertical separator at the top menu	
var listings_jsonp_id = 0
var layers_jsonp_id = 0
var shortlist_jsonp_id = 0;
var layers_enabled = false;
var infowindow_sortby = '';
var mapBounds;
var selectedCity;
FACEBOOK = function() { return (window.location.host.split('.')[0] == 'facebook'? true : false); };
// Filter options:
var filter_options = {listing_type:'', property_type:'', minprice:'', maxprice:'', 
					  minbed:'', maxbed:'',
					  minsize:'', maxsize:'',
					  min_latitude:'', max_latitude:'', min_longitude:'', max_longitude:'',
					  tracker:'', frombound:'false', city_id:'', category:''};
// Layers:
var layers = {SUP:'', MRT:'', KDG:'', SCH:'', INT:'', AIR:'yes'};
var mgrMarker;
// ----------------
// On load actions
// ----------------
$(document).ready(function() {     					
	                        // Disable annoying IE scrollbar:
	                        if ($.browser.msie)	document.body.scroll = 'no';
                        	
	                        // Init the map (mapservices.js):
	                        init_large();	
                        	mgrMarker = new MarkerManager(map);
                        	
	                        // Fit window and handle window resize:	
                            $(window).bind("resize", windowResizeEvent);	
	                        fitWindow();
                        	searching_enabled = false;
	                        // Center the map (after fitting the window):
	                        //map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom-1); // center the map
	                        $.ajax({
                                      type: "POST",
                                      contentType: "application/json; charset=utf-8",
                                      url: "PropertyInfoWebService.asmx/getLatLonZoom",                                      
                                      data: "{}",
                                      dataType: "json",
                                      success: function(msg) {
                                        latLonZoomResults(msg);
                                      }
                                    });
                        });
// --------------
// Map Searching
// --------------
function search(type)
{
	// Map boundaries:
	var bounds = getMapBounds();
	filter_options['min_latitude'] = bounds.min_latitude.toString();
	filter_options['max_latitude'] = bounds.max_latitude.toString();
	filter_options['min_longitude']= bounds.min_longitude.toString();  
	filter_options['max_longitude']= bounds.max_longitude.toString();	
				
	// Collect the parameters:
	var args = [];
	
	for (var key in filter_options) 
	{ 
	    args.push(key + "=" + filter_options[key]); 
	}
	
	// Hide map tooltip:
    $('#map_tooltip').fadeOut('normal');		
	
	// Generate the URL:		
	ajaxListingsParams = generateURL(args);	
	$('#map_listings_ajax_loader').show(); 
	
	$.ajax({
              type: "POST",
              contentType: "application/json; charset=utf-8",
              url: "PropertyInfoWebService.asmx/getSearchResults",
              data: "{'myOption': '" + ajaxListingsParams + "'}",
              dataType: "json",
              success: function(msg) {                
                listingsResults(msg);
              }              
            });
}
function AjaxFailed(result) 
{
  alert('Error- ' + result.status + ' ' + result.statusText);
}  

function latLonZoomResults(data) 
{		
	currentData = data;						 		
	$.each(currentData, function(i,item){	                            	                                
                                if (item.center_lat && item.center_long) 
                                {				                            
	                                var point = new GLatLng(item.center_lat, item.center_long);								                            
	                                map.panTo(point);
	                                map.setCenter(point);
	                                if (item.zoom_level) map.setZoom(parseInt(item.zoom_level));
                                }		 	                                                       
                            });
                            mapBounds = new GLatLngBounds();                        			
	                        // Refresh listings when the change of map view ends (includes zoom changes):
	                        GEvent.addListener(map,"moveend",function() {												  
	                                                                    if (searching_enabled) 
	                                                                    {											  
		                                                                    clearTimeout(id_maptimer); 
		                                                                    id_maptimer = setTimeout(search,1000);	// wait a bit to really stop
	                                                                    }
                                                                    }); 
	                        GEvent.addListener(map,"move", function() {
                                                                    clearTimeout(id_maptimer); // cancel search until move really stops
                                                                });                        	
	                        // Zoom control (enable/disable layers):
	                        GEvent.addListener(map, "zoomend", function() {												
		                                                                layers_enabled = (map.getZoom() >= min_layers_zoom);		
		                                                                removeMarkers(layers_markers);			
		                                                                $('#mapsidebarlayers_header').html('Places of Interest&nbsp;&nbsp;<span class="smallfont">(you need to zoom in first)</span>');
		                                                                if ($('#mapsidebarlayers').is(":visible")) toggleMapSidebarOption('#mapsidebarlayers');                                                                				
	                                                                    });
	                        filter_options['tracker'] = 'true'	                        
	                        search();
}

function listingsResults(data) 
{	
	var batch = [];
	// Clear selection:
	clearSelection();
	// Clear markers:
	mgrMarker.clearMarkers();
	removeMarkers(listings_markers);
	listings_markers = new Array();		

	// Save retrieved data into a global variable:		
	currentData = data;						 
	
	// Loop through the listings creating rows and markers:
	var listings_html = '';			
	mgrMarker = new MarkerManager(map);
	$.each(currentData, function(i,item){		
		                            // First slot brings common data, the rest are listings:	
		                            			  
		                            if (i == 0) 
		                            { 		                            
		                                searching_enabled = false;
		                                if (item.total == 0) 
		                                {
		                                    count_html = 'No Properties Found At This Location';
		                                    first_load = false;
		                                }
		                                else
		                                {
		                                    count_html = 'Found ' + item.total + ' properties';
		                                }		                                
		                                $('#mapsidebar_footer').html(count_html);   		                                
		                            }
		                            else if (i <= 100) 
		                            {	 		 		                                                                                
			                            processArrayListing(item);		
                            			
                            			var point = new GLatLng(item.latitude, item.longitude);
			                            if(first_load)
                                        {	
                                            searching_enabled = false;
			                                mapBounds.extend(point);                                                
                                        }
			                            var tooltip = item.property_name ? item.property_name : item.address;
			                            var id = item.property_id;			
			                            if (!id) id = 'T' + item.id;
			                            listings_markers[id] = createMapSearchMarker(point, item.property_type_group, tooltip, currentData, i); 
				                        batch.push(listings_markers[id]);
			                            listings_html += createRow(item,'listings','currentData',i);
		                            }
		                            else
		                            {		                                
		                                return false;
		                            }
	                            });			
	// Replace Listings:
	mgrMarker.addMarkers(batch,5);
	mgrMarker.refresh();
	$('#mapsidebarlistings').html("");
	$('#mapsidebarlistings').html(listings_html);

	// Show results and Hide ajax loader:	
	$('#map_listings_ajax_loader').hide(); 	
	if(first_load)
    {	
        map.setZoom((map.getBoundsZoomLevel(mapBounds)-1));
        map.setCenter(mapBounds.getCenter());  
        mapOptionLocate();                                            
    }	
	setBounds = false;
	filter_options['frombound']= 'true';
	first_load = false;
	searching_enabled = true;
	// Reset the jsonp ids:
	listings_jsonp_id = 0;	
}		

function disableSearchs() 
{ 
	// Temporary disable searchs:
	searching_enabled = false;
	setTimeout(function() {searching_enabled = true}, 100); 
}
// ----------------
// Window handling
// ----------------
function fitWindow() {
	// try to set fullscreen:
	//window.resizeTo(screen.width,screen.height-30);
	// get real dimensions:
    var w = windowWidth();
    //var w = 925;
    var r = w / 2; 
	var h = windowHeight() - (page_header_height) - 30;		
	// Map:	
	if ($('#mapsidebarcont').is(":visible")) $('#mapcont').width(w - $('#mapsidebar').width());
	else $('#mapcont').width(w);
	$('#mapcont').height(h);
	map.checkResize();
	
	// Side bar:	
	$('#mapsidebar').css("right", '1px');
	
	$('#mapsidebar').height(h);	
	
	// Side bar elements:
	var listings_top = $('#mapsidebar_header').height() + 31; // top header 
	
	$('#mapsidebarlistingscont').height(h - listings_top - 33 - $('#mapsidebar_footer').height());	 // remaining height - listing header - footer	
	$('#mapsidebar_footer').css("top", (h - $('#mapsidebar_footer').height() - $('#mapsidebar_header').height())+"px");
}
function windowResizeEvent()
{
    fitWindow();    	
	mapOptionLocate();
    mapOptionLocateExpand();    
}

function windowWidth() 
{
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerWidth)
		return self.innerWidth;
	// IE 6
	if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	// IE 5
	if (document.body)
		return document.body.clientWidth;
	// Just in case.
	return 0;
}

function windowHeight() 
{
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}
// -----------------
// Listing Handling
// -----------------
function createRow(pointData, type, list_name, row) 
{
	var title = '', lister = '', customerName = '', listing_type = '', monthly = '', price = '', bedrooms = ''; 
	var bathrooms = '', advertiser = '', furnishing_floorarea = '';
	var abslink = (FACEBOOK())? true : false;
	
	// title:
	if (pointData.property_name) title = pointData.property_name;
	else title = pointData.address;
	
	//Lister type
	lister = pointData.listerType;	
	
	//CustomerName
	customerName = pointData.agent_name;	
	
	// listing_type and monthly:
	if (pointData.listing_type == 'Rent') 
	{
		listing_type = 'Rent';
		monthly = ' per month';
    }
    else if (pointData.listing_type == 'Share') {
        listing_type = 'Share';
        monthly = ' per month';
    }
    else if (pointData.listing_type == 'Lease') {
        listing_type = 'Lease';        
    }
	else listing_type = 'Sale';		
	
	// price:
	price = 'Rs. ' + pointData.price;		
	
	// bedrooms:
	if (parseInt(pointData.bedrooms) > 0) bedrooms = (type == 'infowindow') ? pointData.bedrooms : (pointData.bedrooms  + ' bedroom(s)');
	
	// bathrooms:
	if (parseInt(pointData.bathrooms) > 0) bathrooms = (type == 'infowindow') ? pointData.bathrooms : (pointData.bathrooms  + ' bathroom(s)');	
	
	// furnishing and floorarea:
	if (pointData.furnishing) 
	{
		//furnishing_floorarea = pointData.furnishing;
		//if (pointData.floorarea) furnishing_floorarea += " | ";
	}	
	if (pointData.floorarea) furnishing_floorarea += pointData.floorarea + ' ' + pointData.areaType;
	
	// advertiser:
	advertiser = pointData.agent_name;
	if (pointData.agent_mobile != '') advertiser +=  ' (' + pointData.agent_mobile + ')';	

	// returned html:
	if (type == "listings")
	{
		html    =	'<div id="map'+type+'_item_' + row + '" class="maplistings_item" onclick="clickHandler(' + list_name + ',' + row + ')" onmouseover="mouseOverHandler(' + list_name + ',' + row + ')" onmouseout="mouseOutHandler(' + list_name + ',' + row + ')">'
	            +   '<table class="maplistings_item" style="width: 240px; font-family: Verdana;">'
	            +   '<tr><td colspan="2" style="width: 240px; text-align: left"><div style="font-size: 12px; font-family: Verdana;"><b><a target="_new" onclick="cancelProp(event)" href="' + getListingDetailURL(pointData) + '">' + pointData.propertyType+ '</a></b></div></td></tr>'
	            +   '<tr><td rowspan="4" style="width: 75px; border-width: thin;"><div style="font-family: Verdana;"><img src="' + pointData.thumb + '" /></div></td>'
	            +   '<td style="width: 165px; border-width: thin;"><div style="font-family: Verdana;">' + truncate(title,25) + '</div></td></tr>'
	            +   '<tr><td style="width: 165px; border-width: thin;"><div style="font-family: Verdana;">' + lister + ' - ' + truncate(customerName,15) + '</div></td></tr>'
	            +   '<tr><td style="width: 165px; border-width: thin;"><div style="font-family: Verdana;">' + furnishing_floorarea + '</div></td></tr>';
	   
	   if (price != 'Rs. 0')
	   {
	   html     +=  '<tr><td style="width: 165px; border-width: thin;"><div style="font-family: Verdana;">' + price + monthly + '</div></td></tr>';
	   }
	   else
	   {
	   html     +=  '<tr><td style="width: 165px; border-width: thin;"><div style="font-family: Verdana;"></div></td></tr>';
	   }
	   
	   html     +=  '<tr><td colspan="2" style="width: 240px; border-width: thin;"><div class="bluelinksml" onclick="cancelProp(event)" style="font-family: Verdana;"><a target="_new" href="' + getListingDetailURL(pointData) + '">View Details</a></div></td></tr>'
	            +   '</table></div><div class="separator-light"></div>';
	}	
	else if (type == "infowindow") 
	{
		html    =   '<div id="mapdetail_item_' + row + '" class="maplistings_item">'
                +   '<table style="width: 350px; font-size: 15px; color: white; font-family: Verdana; font-weight: bold; background-color: #009dd6;">'
                +   '<tr><td style="width: 350px; text-align: center"><div style="font-family: Verdana;">' + pointData.propertyType + '</div></td></tr></table>'
                +   '<table style="width: 350px; font-size: 12px; color: #1A2C90; font-family: Verdana; background-color: White;">'
                +   '<tr><td rowspan="6" style="width: 150px; border-width: thin;"><div style="font-family: Verdana;"><img src="' + pointData.image + '" /></div></td>'
                +   '<td style="width: 200px; border-width: thin;"><div style="font-family: Verdana;"><b>' + truncate(title,25) + '</b></div></td></tr>'
                +   '<tr><td style="width: 200px; border-width: thin;"><div style="font-family: Verdana;">' + lister + ' - ' + truncate(customerName,15) + '</div></td></tr>'
                +   '<tr><td style="width: 200px; border-width: thin;"><div style="font-family: Verdana;">' + furnishing_floorarea + '</div></td></tr>';
                    
        if (price != 'Rs. 0')
        html    +=  '<tr><td style="width: 200px; border-width: thin;"><div style="font-family: Verdana;">' + price + monthly + '</div></td></tr>';
    
        if (bedrooms)
        {
        html    +=  '<tr><td style="width: 200px; border-width: thin;"><div class="bedroomicon" style="font-family: Verdana;">' + bedrooms + '</div>';
          
        if (parseInt(bathrooms) > 0)
        {
        html    +=  '<div class="bathroomicon" style="font-family: Verdana;">' + bathrooms + '</div></td></tr>';
        }
        else
        {
        html    +=  '</td></tr>';
        }
        }        
        
        html    +=  '<tr><td style="width: 200px; border-width: thin;"><div class="btnsmall" style="font-family: Verdana; font-weight:bold;"><a target="_new" href="' + getListingDetailURL(pointData) + '">View Details</a></div><div class="btnsmallEnding"></td></tr>'
                +   '</table>'
                +   '</div>';
	}	
	return html;
}

function setSelectedRow(list, row) 
{
	clearSelection();
	selectedList = list;
	selectedRow = row;	
	var type = 'listings';
	$('#map' + type + '_item_' + row).addClass("maplistings_item_highlight");	
}

function clearSelection() 
{
	if (selectedRow >= 0) 
	{	
		var type ='listings';
		$('#map' + type + '_item_' + selectedRow).removeClass("maplistings_item_highlight");

		var data = selectedList[selectedRow];
		var marker = getMarker(selectedList, selectedRow);
		
		marker.setImage((marker.list == currentShortlist) ? icons[marker.type].shortlist : icons[marker.type].image);
		
		selectedList = null;
		selectedRow = -1;
	}
}
// -----------------
// Markers handling
// -----------------
function createMapSearchMarker(point, type, tooltip, list, row) {
	// Choose the layer for the marker:
	var marker_layer = "properties";
	
	// Create the marker:
	var marker = createMarker(point, type, marker_layer);	
	marker.tooltip = tooltip;
	marker.list = list;
	
	// Events handling:
	GEvent.addListener(marker, "click", function() { clickHandler(list, row, marker) });
	GEvent.addListener(marker, "mouseover", function() { mouseOverHandler(list, row, marker) });		       
	GEvent.addListener(marker, "mouseout", function() { mouseOutHandler(list, row, marker) });
		
	return marker;
}

function removeMarkers(markers, type) {
	//if (markers) 
		var count = 0;
		for (var key in markers) {
			//if (markers == shortlist_markers) alert(markers[key])
			if (!type || markers[key].type == type) {
				markers[key].closeInfoWindow(); // need to close marker's infowindow (if it belongs to the marker) before removing the marker
				map.removeOverlay(markers[key]);
				count++;
			}
		}
		//if (markers == shortlist_markers) alert(count +' shortlist markers removed');
		/*jQuery.each(markers, function() { 
			if (!type || this.type == type) map.removeOverlay(this); 
		});*/
}

function getMarker(list, row) 
{
	// Choose the proper data:
	var data = list[row];
	var id = data.property_id;
	if (!id) id = 'T' + data.id;
	
	return listings_markers[id];
}

function getMarkerHTML(list, row) 
{		
	var properties_html = createRow(list[row],'infowindow','currentData',row);		
	
    var html = '<div style="width:355px; height:140px; margin:5px; text-align:left">' + properties_html +  '</div>';    
	
	return html;
}

function zoomMarker(list, row, zoom, block_searching, select_marker) 
{
	// Get the point:
	var data = list[row];
	var point = new GLatLng(data.latitude, data.longitude);

	// Center the map without searching again:
	if (block_searching) disableSearchs();	// temporary disable searchings during map view changes
	if (zoom) map.setZoom(zoom);
	map.panTo(point);
	map.setCenter(point);
	
	// If requested select the marker opening the infowindow, etc:
	if (select_marker) setTimeout(function() { clickHandler(list,row); }, 1500);
}

function showTooltip(marker) 
{
	// Set the text for the tooltip:
	$('#map_tooltip').html(marker.tooltip);
	
	// Calculate the tooltip position:
	var map_top = page_header_height+30; //+ $('#map_topmenu').height()
	var point = map.fromLatLngToContainerPixel(marker.getLatLng());
	//alert(point.x + ',' + point.y);	
	var left = point.x - $('#map_tooltip').width()/2;
	var top = point.y + map_top - icons[marker.type].iconSize[1] - 20;
	
	// Check if the tooltip is out of the map limits [top, right, bottom, right]:
	var limits = [map_top + 2, $('#mapcont').width() - $('#map_tooltip').width() - 12, 
				  map_top + $('#mapcont').height() - $('#map_tooltip').height() - 2, 2];
	if (top < limits[0]) top = limits[0];
	if (left > limits[1]) left = limits[1];
	if (top > limits[2]) top = limits[2];
	if (left < limits[3]) left = limits[3];
	
	// Set the tooltip position:
	$('#map_tooltip').css("left",left+"px"); // center with the marker
	$('#map_tooltip').css("top",top+"px"); // put over the marker
	
	// Show the tooltip:
	$('#map_tooltip').fadeIn('normal');
}
// ----------------
// Events Handling
// ----------------
function clickHandler(list, row, marker) 
{
	if (row) 
	{
		// Get marker if not set:
		if (!marker) marker = getMarker(list, row); 
		
		// Open info window or center the map to the marker:
		disableSearchs(); // temporary disable searchs while moving the map
		marker.openInfoWindowHtml(getMarkerHTML(list, row),{noCloseOnClick:true}); // open info window	
		marker.infoWindowClose_listener = GEvent.addListener(marker, "infowindowclose", clearSelection);
		
		// Set selected row:
		setSelectedRow(list, row);
		
		// Hide tooltip:
		$('#map_tooltip').fadeOut('normal'); 		
				
		// Highlight marker:
		marker.setImage(icons[marker.type].image_h); 		
	}
}
	
function mouseOverHandler(list, row, marker) 
{
	// Check the list type:
	var type = 'listings';
	
	// If row and marker are set, scroll the sidebar:
	if (row) { 
		if (marker) $('#mapsidebar' + type + 'cont').scrollTo($('#map'+type+'_item_'+row), {duration:300, easing:'swing'});
		$('#map'+type+'_item_'+row).addClass("maplistings_item_highlight"); // highlight listing item
	}
	
	// Other behaviours only if infowindow is hidden:	
	if (map.getInfoWindow().isHidden()) 
	{	
		if (row) 
		{		
			// Get associated marker if not set:	 
			if (!marker) marker = getMarker(list, row);			
			
			// Highlight marker:		
			marker.setImage(icons[marker.type].image_h); 
		}
		
		// Show marker tooltip if no info window showed:
		if (marker) showTooltip(marker);	
	}
}

function mouseOutHandler(list, row, marker) 
{	
	if (row && (list != selectedList || row != selectedRow)) 
	{
		// Remove listing item highlighting:
		var type ='listings';
		$('#map'+type+'_item_'+row).removeClass("maplistings_item_highlight"); 
		
		// Remove marker highlighting:
		if (!marker) marker = getMarker(list, row);
		marker.setImage(icons[marker.type].image);		
	}	
	// Hide tooltip:
	$('#map_tooltip').hide(); 
}
// ---------------
// Value Toggles 
// ---------------
var setBounds = false;

function togglePriceOption()
{    
    clearTimeout(id_maptimer);    
    if (first_load == false) {        
		id_maptimer = setTimeout(callPriceOption,750);
    }
}
function callPriceOption()
{            
    if (first_load == false) {
        filter_options['minprice'] = $('#tbPriceFrom').val();
        filter_options['maxprice'] = $('#tbPriceTo').val();
        filter_options['listing_type'] = $("#ddlListingType").val();
        setBounds = true;
        filter_options['frombound'] = 'true';
        clearTimeout(id_maptimer);                 
		id_maptimer = setTimeout(search,750);
    }
}

function toggleAreaOption()
{
    clearTimeout(id_maptimer);    
    if (first_load == false) {        
		id_maptimer = setTimeout(callAreaOption,750);
    }    
}
function callAreaOption()
{
    if (first_load == false) {
        filter_options['minsize'] = $('#tbAreUnitFrom').val();
        filter_options['maxsize'] = $('#tbAreUnitTo').val();
        setBounds = true;
        filter_options['frombound'] = 'true';
        clearTimeout(id_maptimer);         
        id_maptimer = setTimeout(search,750);
    }
}

function toggleBedOption()
{
    clearTimeout(id_maptimer);    
    if (first_load == false) {        
		id_maptimer = setTimeout(callBedOption,750);
    } 
}
function callBedOption()
{
    if (first_load == false) {
        filter_options['minbed'] = $('#tbnobedroomFrom').val();
        filter_options['maxbed'] = $('#tbnobedroomTo').val();
        setBounds = true;
        filter_options['frombound'] = 'true';
        clearTimeout(id_maptimer);         
        id_maptimer = setTimeout(search,750);
    }
}

function toggleListingType() 
{	
    filter_options['listing_type'] = $("#ddlListingType").val();
	setBounds = true;
	filter_options['frombound'] = 'true';	
	search();
}

function togglePropertyType() 
{
    filter_options['property_type'] = $("#ddlPropertyType").val();
	setBounds = true;
	filter_options['frombound'] = 'true';	
	search();
}

function toggleCity()
{ 
    filter_options['city_id'] = $("#tbcity_id").val();
    myLatitude = resultLatLon.split(',')[0];
    myLongitude = resultLatLon.split(',')[1];
    $("#tbCity").val('');
    first_load = true;
	setBounds = true;
	filter_options['frombound'] = 'false';
	setMapCenter = true;
	search();
}
// ----------------------
// Visualization Toggles 
// ----------------------
function toggleSidebar() 
{
	$('#mapsidebarcont').slideToggle('normal',function() {
		if ($('#mapsidebarcont').is(":visible")) 
		{
			$('#mapsidebar_header').removeClass('sidebaroff');
        	$('#mapsidebar_header').addClass('sidebaron');
		}
		else 
		{
			$('#mapsidebar_header').removeClass('sidebaron');
        	$('#mapsidebar_header').addClass('sidebaroff');
		}
		fitWindow();
	});
}

function toggleMapSidebarOption(option) 
{
	var showing = !$(option).is(":visible");
	if (showing) 
	{
		$(option + '_header').removeClass('off');
		$(option + '_header').addClass('on');
	}
	
	$(option).slideToggle('normal', function() {
	                                        if (!showing) 
	                                        { 
	                                            // hiding			
		                                        $(option + '_header').removeClass('on');
		                                        $(option + '_header').removeClass('off');
	                                        }
	                                        fitWindow();
                                    		
	                                        // Check if it's necessary to scroll the shown list:
	                                        if (selectedList && selectedRow) 
	                                        {
		                                        var type = (selectedList == currentData) ? 'listings' : 'shortlist';
		                                        if ((option == "#mapsidebar" + type + "cont") && showing) $(option).scrollTo($('#map'+type+'_item_'+selectedRow), {duration:300, easing:'swing'});
	                                        }
                                        });	
	return showing;
}

function toggleClassOn(divID)
{    
    $(divID).removeClass('option_header');
	$(divID).addClass('option_header_mouseOver');
}
function toggleClassOff(divID)
{    
    $(divID).removeClass('option_header_mouseOver');
	$(divID).addClass('option_header');
}
// ---------------
// Utilities
// ---------------
function generateURL(args) 
{
	var urlParams = ""; //(args.length > 0) ? "&" : "";
              
    for (var x=0; x<args.length; x++)
    {
        if (x > 0) urlParams += "&";
        urlParams += args[x];
    } 
    return urlParams;
}

function getListingDetailURL(pointData) 
{	
	var servername = 'Property_ViewDetails.aspx?property_security_code=';			
	return servername + pointData.property_security ;	
}

function getMapBounds() 
{
	var bounds = map.getBounds();
	var top_right = bounds.getNorthEast();
	var bottom_left = bounds.getSouthWest();
	
	return {min_latitude: bottom_left.lat(),
			max_latitude: top_right.lat(),
			min_longitude: bottom_left.lng(),
			max_longitude: top_right.lng()};	 
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) 
	{
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function removeCommas(s)
{
	var d= "" 
	len= s.length 
	for(x=0;x<len;++x)
	{ 
  		if	(s.charAt(x)!=","){d=d +s.charAt(x)} 
	}
	return d;
}

function sorting_func(a,b) 
{	
	// Convert to integer removing the commas:								 
	var a_clean = parseInt(removeCommas(a[s_o[0]]));
	var b_clean = parseInt(removeCommas(b[s_o[0]]));			

	// Compare the two values:			
	if (s_o[1] == "asc") return (a_clean - b_clean);
	else return (b_clean - a_clean);								 
}

function processArrayListing(item) 
{    
	var arrayListing = item.listing.split('^');			
	item.id = arrayListing[0];		
	item.property_id = arrayListing[1];
	item.property_security = arrayListing[2];
	item.furnishing = arrayListing[3]; 
	item.listing_type = arrayListing[4];
	item.property_type_group = arrayListing[5];
	item.property_name = arrayListing[6];
	item.latitude = arrayListing[7];
	item.longitude = arrayListing[8];
	item.bedrooms = arrayListing[9];
	item.bathrooms = arrayListing[10];
	item.price = arrayListing[11];
	item.floorarea = arrayListing[12];
	item.areaTypeID
	item.areaType = arrayListing[13];	
	item.address = arrayListing[14];	
	item.agent_name = arrayListing[15];
	item.agent_mobile = arrayListing[16];
	item.thumb = arrayListing[17]; 
	item.image = arrayListing[18];	
	selectedCity = arrayListing[19];
	item.listerType = arrayListing[20];
	item.propertyType = arrayListing[21];
	//	return item ?	
}

function mapOptionLocate()
{	
	var h = windowHeight() - 35;
	var left = 215;
	var top = h;
	$('#map_option_locate').css("left",left+"px");
	$('#map_option_locate').css("top",top+"px");
	$('#map_option_locate').fadeIn('normal');
	mapOptionLocateExpand();
	
	left = left + 85;
	$('#map_category').css("left",left+"px");	
	$('#map_category').css("top",top+"px");
	$('#map_category').fadeIn('normal');

	left = 9;
	$('#map_category_middle').css("left",left+"px");
	left = left + 229;
	$('#map_category_right').css("left",left+"px");
	
}

var map_option_locate_expand_display =0;
function mapOptionLocateClickEvent()
{
    if(map_option_locate_expand_display == 0)
    {
        $('#map_option_locate_expand').fadeIn('normal');
        map_option_locate_expand_display = 1;
        $('#map_option_legend_expand').fadeOut('normal');
        map_option_legend_expand_display = 0;
    }
    else
    {
       $('#map_option_locate_expand').fadeOut('normal');
        map_option_locate_expand_display = 0;
    }
}

function mapOptionLocateExpand()
{
	var h = 40;
	var left = 115;
	var top = h;	
	$('#map_option_locate_expand').css("left",left+"px");
	$('#map_option_locate_expand').css("bottom",top+"px");
}
//function Category_Residential()
//{
//    filter_options['category']= "1";
//    search();
//}
//function Category_Commercial()
//{
//    filter_options['category']= "2";
//    search();
//}
