
var isPost = false;

var displayDivNo = 0;
var min = 0;
var max = 0;
var isPostHome = false;
var isAutoPin = false;
var initialize = false;
var startMessageDiv = 0;
var endMessageDiv = 2;
var activeId = null;


var map;
var markerIcon = null;
var _geocoder;
var mapPointsCollection;
var isFinalLoad = false;
var tempList;
var myBounds;
var selectedId = null;
var isJspLoaded = true;
var mapPoints2Collection=null;
var noResults = false;
var currentIndex = 0;

/*
	A class for Map points
*/
var MapPoints = Class.create();
MapPoints.prototype = {
	
	initialize : function(_id, _latitude, _longitude,_address, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location){
		this.id = _id;
		this.latitude = _latitude;
		this.longitude = _longitude;
		this.address = _address;
		this.title = _title;
		this.size = _size;
		this.price = _price;
		this.bedrooms = _bedrooms;
		this.bathrooms = _bathrooms;
		this.imageLocation = _imageLocation;
		this.type = _type;
		this.typName = _typeName;
		this.location = _location;
	},
	
	addUrl : function (url_){
		this.propertyUrl = url_;
	},
	
	addMarker : function (marker){
		this.marker = marker;
	},
	
	setCurrentIndex : function (index){
		this.currentIndex = index;
	},
	
	getHTML : function(){
		var html = '';
		html += '<div style="font-size:12px;border:1px solid white;">';
		if (this.propertyUrl){
			html += '<div style="border:0px solid black;text-align:left;margin:0 0 10px 0;"><a href="'+this.propertyUrl+'">'+this.title+'</a></div>';
		}else{
			html += '<div style="border:0px solid black;text-align:left;margin:0 0 10px 0;"><a href="#">'+this.title+'</a></div>';
		}
		
		
		html += '<div style="border:0px solid red">';
		html += '<div style="border:0px solid red;float:left;margin:0 7px 0 0;">';
		html += '<img width="100" src='+this.imageLocation+'></img>';
		html += '</div>';
		html += '<div class="googlePopUp" style="float:left;border:0px solid green;">';
		html += '<div><label>Location: '+this.location+'</label></div>';
		if(this.size != -1){
			html += '<div><label>Size: '+this.size+'&nbsp;sqft</label></div>';
		}
		if (this.type != 4){
			if(this.type >=5 && this.type <= 9){
				html += '<div><label>Price: AED '+this.price+'</label></div>';
				html += '<div><label></label></div>';
			}else{
				html += '<div><label>Price: AED '+this.price+'</label></div>';
				var plus = this.bedrooms == 10 ? '+' : ''; 
				if(plus){
					html += '<div><label>Bedrooms: '+this.bedrooms+' '+plus+'</label></div>';
				}else{
					var bedrooms = this.bedrooms;
					if(bedrooms == -1 || bedrooms == 0){
						html += '<div><label>Bedrooms: Studio</label></div>';
					}else{
						html += '<div><label>Bedrooms: '+bedrooms+'</label></div>';
					}
				}
			}
		}
		html += '<div><label>Type: '+this.typName+'</label></div>';
		html += '</div>';
		html += '<div style="clear:both"></div>';
		html += '</div>';
		html += '<div style="clear:both"></div>';
		html += '</div>';
		
		return html;
	}
}
/*
	A class for Map points2
*/
var MapPoints2 = Class.create();
MapPoints2.prototype = {
	
	initialize : function(_id, _latitude, _longitude,_address,_title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location){
		this.id = _id;
		this.lat = _latitude;
		this.lng = _longitude;
		this.address = _address;
		this.title = _title;
		this.size = _size;
		this.price = _price;
		this.bedrooms = _bedrooms;
		this.bathrooms = _bathrooms;
		this.imageLocation = _imageLocation;
		this.type = _type;
		this.typName = _typeName;
		this.location = _location;
	},
	
	addUrl : function (url_){
		this.propertyUrl = url_;
	}
}
/*
	A class for MapPointsCollection
*/
var MapPointsCollection = Class.create();
MapPointsCollection.prototype = {
	initialize : function (){
		this.properties = new Array();
		this.length = 0;
	},
	
	addPoint : function (_point){
		this.properties[_point.id] = _point;
		this.length++;
	},
	
	getById : function(_id){
		return this.properties[_id];
	},
	
	getHTML : function(){
		var str = '';
		for (var _point in this.properties){
			 if( typeof(this.properties[_point]) == "object" ) {
			 		str+=this.properties[_point].getHTML();
			 }
		}
		
		return str;
	}
}
//initialize gmap
function initializeMap(){
	if (!initialize){
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
		 	map.setMapType(G_HYBRID_MAP);
	        map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			
			
			markerIcon = new GIcon();
			markerIcon.image = "css/images/map_logo.png";
			markerIcon.shadow = "css/images/map_logo.png";
			markerIcon.iconSize = new GSize(30, 44);
			markerIcon.shadowSize = new GSize(30, 44);
			markerIcon.iconAnchor = new GPoint(6, 20);
			markerIcon.infoWindowAnchor = new GPoint(15, 22);
			
	        _geocoder = new GClientGeocoder(); 
	       GEvent.addListener(map, "load", function() {
	       		if (!isJspLoaded && $('map').style.display == "block"){
	       			if (selectedId!=null){
						clickProperty(selectedId);
					}else{
						mapSetCenter(myBounds);	
					}
					map.clearOverlays();
					if (!noResults)
	       			for (var _point in mapPointsCollection.properties){
						 if( typeof(mapPointsCollection.properties[_point]) == "object" ) {
						 		map.addOverlay(mapPointsCollection.properties[_point].marker);
						 }
					}
					isJspLoaded = true;
				}else{
					 for (var _point in mapPointsCollection.properties){
						 if( typeof(mapPointsCollection.properties[_point]) == "object" ) {
						 		map.addOverlay(mapPointsCollection.properties[_point].marker);
						 }
					}
				}
			  });
	        
        	initialize = !initialize;
		}
	}
}

function enableAlertFocus() {
	    jQuery('.profileAlert').seekAttention({
     	paddingTop: 10,
	    paddingBottom: 10,
	    paddingLeft: 10,
	    paddingRight: 10,
	    blur: true,
	    pulseSpeed : 300
     	
    });
}

function setPager(_val, _id) {
	jQuery('#pager_'+_id).pagination(parseInt(_val), {
			items_per_page:10, 
			num_edge_entries: 3,
			num_display_entries: 10,
			callback: nextPage /*,  
			isAvailable: isOnline()
			--> tuxpiper: restriction on accessing 2nd page of results disabled as per clients request */
       });
}

//set elements binds events
jQuery(document).ready(function(){

	jQuery('.default').click( function () {
		jQuery(this).val("");
	});

	var pagerUrl = window.location.href;
	if ($('entity0') && (pagerUrl.match('buy') || pagerUrl.match('rent'))){
	 	for (var i = 0; i <= parseInt($('entitySize').value); i++) {
	 		setPager($('entity'+i).value, i);
	 	}
       
	}

 	 jQuery('.messageWrapper').bind("click", function(){
         jQuery('.messageWrapper').each(function(index) {
	      	jQuery(this).removeClass('selected');
	  	});
	  	jQuery(this).addClass('selected');
	  	activeId = jQuery(this).attr('id');
	  	document.getElementById('messageId').value = jQuery('.active:eq('+activeId+')').attr('id');
     });
     
 	 jQuery('.messageWrapper').hover(function() {
    	jQuery(this).addClass('hover');
 	 }, function() {
    	jQuery(this).removeClass('hover');
  	 });
 
 	 //jQuery('#messagesContainer .messageWrapper:gt(0)').hide();
 	 
 	 jQuery('table tbody tr:odd').addClass('odd');
 	 jQuery('table tbody tr:even').addClass('even');
 	 
 	 jQuery('#myListingTab').bind("click", function(){
            jQuery('#profileSummary').css('display','none');
             jQuery('#myListing').css('display','block');
     });
     
     jQuery('#summaryTab').bind("click", function(){
            jQuery('#profileSummary').css('display','block');
             jQuery('#myListing').css('display','none');
     });
     
     jQuery('#tabSubscribe').bind("click", function(){
            jQuery('#subscribe').css('display','block');
            jQuery('#purchase').css('display','none');
            jQuery('#upgrade').css('display','none');
     });
     
     
     jQuery('#tabUpgrade').bind("click", function(){
            jQuery('#subscribe').css('display','none');
            jQuery('#upgrade').css('display','block');
            jQuery('#purchase').css('display','none');
     });
     
     jQuery('#tabPurchase').bind("click", function(){
            jQuery('#subscribe').css('display','none');
            jQuery('#upgrade').css('display','none');
            jQuery('#purchase').css('display','block');
     });
     
     jQuery('#tabSummary').bind("click", function(){
            jQuery('#summary').css('display','block');
            jQuery('#map').css('display','none');
     });
     
      jQuery('#tabPropertyMap').bind("click", function(){
            jQuery('#summary').css('display','none');
            jQuery('#map').css('display','block');
     });
 
 	 jQuery('.delete').bind("click", function(){
            jQuery('#popupFeatured').css('display','block');
     });
     
     jQuery('.popupClose').bind("click", function(){
            jQuery('#popupFeatured').css('display','none');
            jQuery('#popupAnswer').css('display','none');
            jQuery('#popupRegister').css('display','none');
            jQuery('#popupEditProfile').css('display','none');
     });
     
     jQuery('.popupClose').bind("click", function(){
            jQuery('#popupFeatured').css('display','none');
            jQuery('#popupPassword').css('display','none');
     });
     
     jQuery('.popupClose').bind("click", function(){
            jQuery('#popupSaveListing').css('display','none');
     });
     
       jQuery('.deleteConfirm').bind("click", function(){
            jQuery('#popup').css('display','none');
            jQuery('#modal').hide();
            jQuery('#popupWrapper').hide();
            jQuery('#popupDelete').hide();
     });
     
      jQuery('.sendListing').bind("click", function(){
          	showModal("popupSaveListing");
     });
     
     // jQuery('.questionAnswer').click( function(){
     // 		showModal("popupAnswer");
     //});
     
     
      jQuery('.deletebuttonLink').click( function(){
     	 showModal("popupDelete");
     });
     
       jQuery('.forgotPass').click( function(){
       		clearField('fpusername');
      		showModal("popupPassword");
     });
     
      jQuery('.popupClose').click( function(){
            jQuery('#popup').hide();
            jQuery('#modal').hide();
            jQuery('#popupWrapper').hide();
            jQuery('#popupContactSeller').hide();
            jQuery('#popupFeedback').hide();
            jQuery('#popupDelete').hide();
            
     });
     
	 jQuery('.listingClose').bind("click", function(){
            jQuery(this).parent().remove();
     });
      jQuery('.discussionClose').bind("click", function(){
            jQuery(this).parent().remove();
     });
     
     jQuery('.close').bind("click", function(){
            jQuery(this).parent().parent().remove();
     });
     
     jQuery('.groupClose').bind("click", function(){
            jQuery(this).parent().remove();
     });
     
     jQuery('#tabMenu ul li').click(function() {
     	for (var i = 0; i<=4 ;i++){
     		if (this.id == "_listSearchTab"+i){
     			if (i == 0){
	     			tabContentDisplay('#allResults',i);
	     			continue;
	     		}
     			tabContentDisplay('#propertyList'+i,i);
     		}
     	}
      	
      	jQuery('#tabMenu ul li').each(function(index) {
      		if(this.id == "_liopen_map" || this.id == "_liclose_map"){
      			jQuery(this).removeClass();
	      		jQuery(this).addClass('tabMap');
      		}
	      	else{
	      		jQuery(this).removeClass();
	      		jQuery(this).addClass('tab');
	      	}
	      	
	  	});
		  	jQuery(this).removeClass();
		  	if (isPost) {
		  		jQuery(this).addClass('tabActive2');
		  	} else {
		  		jQuery(this).addClass('tabActive');
		  	}
		 	 
	  });
	  
      jQuery('#mapMenu ul li').click(function() {
     	
    		jQuery('#mapMenu ul li').each(function(index) {
	    			if (this.id == "summaryTab" || this.id == "myListingTab"){
	    				jQuery(this).removeClass();
		      			jQuery(this).addClass('tab');
	    			}
		  	});
		  		if (this.id == "summaryTab" || this.id == "myListingTab"){
				  	jQuery(this).removeClass();
			  		jQuery(this).addClass('tabActive2');
		  		}
	  });
    
	   jQuery(".thumbs").click(function(){
	
		var largePath = jQuery(this).attr("src");
		jQuery("#largeImg").attr({ src: largePath });
	 });
	  
      if (jQuery.browser.msie) {
     	jQuery('#roundMain').css('margin-top','1px');
     	jQuery('#postMain').css('margin-top','6px');
   	  }
   	  
   	   jQuery('#loginPassword').bind("keypress", function(e){
	    if ((e.which && e.which == 13) ||(e.keyCode && e.keyCode == 13)) {
			onLoginBeeyootSubmit();
		}
     });

  });

function tabContentDisplay(_id,index){
	jQuery('#map').css('display','none');
	if (jQuery(_id)){
		for (var i=0; i<=4 ;i++){
			if (index == i){
				jQuery(_id).show();
			}else{
				if (jQuery("#propertyList"+i)){
					jQuery("#propertyList"+i).hide();
					if (index !=0)
						jQuery("#allResults").hide();
				}
			}
		}
	}
}  
  
//hides or show contents
function contentDisplay(_id,_style){
	jQuery('#map').css('display','none');
	jQuery(_id).css('display',_style);
}

function showPopupRegister() {
	showModal('popupRegister');
}

//redirects to community profile edition
function gotoEditProfile(id,path,isGroup,groupId){
	window.location=path+"board.jsp?groupId="+ groupId+"&userId="+ id+"&tab=1&content=content9";
}
//switch to map tab
function showPropertyMap(){
	document.getElementById('tabSummary').className ="tab";
	document.getElementById('tabPropertyMap').className ="tabActive2";
}
//switch to summary tab
function showSummary(){
	document.getElementById('tabSummary').className ="tabActive2";
	document.getElementById('tabPropertyMap').className ="tab";
}
//close map view
function hideCloseMap(){
	document.getElementById('close_map').style.display ="none";
}
//loads data to map
//_title, size, price, _bedrooms, _bathrooms
function loadMap(latitude, longitude, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location){
	var _latitude = latitude.toDegreeFormat(true);
	var _longitude = longitude.toDegreeFormat(false);
	
	//alert("latitude"+ _latitude + " _longitude " + _longitude);
	var _address = _latitude +" " + _longitude;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
        map.setMapType(G_HYBRID_MAP);
        map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		markerIcon = new GIcon();
		markerIcon.image = urlPath + "css/images/map_logo.png";
		markerIcon.shadow = urlPath + "css/images/map_logo.png";
		
		markerIcon.iconSize = new GSize(30, 44);
		markerIcon.shadowSize = new GSize(30, 44);
		markerIcon.iconAnchor = new GPoint(6, 20);
		markerIcon.infoWindowAnchor = new GPoint(15, 22);
	
		var geocoder = new GClientGeocoder(); 
		if (geocoder){
        	  geocoder.getLatLng(_address,
			      function(point) {
				      if (!point) {
				       	 // alert(_address + " not found LOAD MAP");
				      } else {
					      var bound=new GLatLngBounds();
						  bound.extend(point);
					      
					      //var newZoom = map.getBoundsZoomLevel(bound);
						  map.setCenter(bound.getCenter(),15);
						  
					 	 // var marker = new GMarker(point, {draggable: false});  
					 	  var marker = new GMarker(point, markerIcon);  
						  map.addOverlay(marker);  
						  var html = '';
						  html += '<div style="font-size:12px;border:1px solid white;">';
							  html += '<div style="border:0px solid black;text-align:left;margin:0 0 10px 0;"><a href="#">'+_title+'</a></div>';
							  html += '<div style="border:0px solid red;float:left;margin:0 7px 0 0;">';
							  	html += '<img width="100" src='+_imageLocation+'></img>';
							  html += '</div>';
							  html += '<div class="googlePopUp" style="float:left;border:0px solid green;">';
							  html += '<div><label>Location: '+_location+'</label></div>';
								  if(_size != -1){
								 	 html += '<div><label>Size: '+_size+'&nbsp;sqft</label></div>';
								  }
								  if (_type != 4){
								  	  html += '<div><label>Price: AED '+_price+'</label></div>';
								  	if (!(_type >= 5 && _type <= 9)){
									  var plus = _bedrooms == 10 ? '+' : ''; 
									  if(plus){
									  	html += '<div><label>Bedrooms: '+_finalRooms+' '+plus+'</label></div>';
									  }else{	
								  	  	var bedrooms  = _bedrooms;
									 	if(bedrooms == -1 || bedrooms == 0){
											html += '<div><label>Bedrooms: Studio</label></div>';
										}else{
											html += '<div><label>Bedrooms: '+bedrooms+'</label></div>';
										}
									  }
									}  
								  }
							  html += '<div><label>Type: '+_typeName+'</label></div>';  
							  html += '</div>';
							   html += '<div style="clear:both"></div>';
						  html += '</div>';
						 	
						  GEvent.addListener(marker, "mouseover", function() {
							  marker.openInfoWindowHtml(html);
						  });
				      }
			      }
			   );
        }
	}
}
//load city or area to map by address
function loadMapByAddress(_address){
	if (map==null || map =='undefined')
		return;
	
	if (GBrowserIsCompatible()) {
		var geocoder = new GClientGeocoder(); 
		if (geocoder){
        	  geocoder.getLatLng(_address,
			      function(point) {
				      if (!point) {
				       	  //alert(_address + " not found LOAD MAP BY ADDRESS");
				      } else {
					      var bound=new GLatLngBounds();
						  bound.extend(point);
					      
					      //var newZoom = map.getBoundsZoomLevel(bound);
						  map.setCenter(bound.getCenter(),15);
						  
							markerIcon = new GIcon();
							markerIcon.image = "css/images/map_logo.png";
							markerIcon.shadow = "css/images/map_logo.png";
							markerIcon.iconSize = new GSize(30, 44);
							markerIcon.shadowSize = new GSize(30, 44);
							markerIcon.iconAnchor = new GPoint(6, 20);
							markerIcon.infoWindowAnchor = new GPoint(15, 22);
							
						  if (isAutoPin){
						  		var marker = new GMarker(point, markerIcon);
						  		var pointY = point.y+'';
						  		var pointX = point.x+'';
						  		$('latitude').value = pointY.parseDeg().toLat();
					        	$('longitude').value = pointX.parseDeg().toLon();
					        	
								GEvent.addListener(marker, "mouseover", function() {
					           		var html = '';
					           		 var _cityName = $('city').options[$('city').selectedIndex].text;
						     		 var _areaName = $('neighborhood').options[$('neighborhood').selectedIndex].text;
									html += "<b>City: </b>" + _cityName + " <br> <b>Area : </b>" + _areaName;		
					           	  	map.openInfoWindow(point, html);
							 	});
						  		map.addOverlay(marker);
						  }	
						  
						  if (isPostHome){
						  	 var pointY=point.y +'';
						      var pointX=point.x +'';
						      //_title, _size, _price,_bedrooms, _bathrooms, _imageLocation
						      var _title = $('hid_title').value;
						      var _price = $('hid_price').value;
						      var _bedrooms = $('hid_bedrooms').value;
						      var _bathrooms = $('hid_bathrooms').value;
						      var _imageLocation = $('hid_primaryPhoto').value;
						      var _type = $('hid_proptype').value;
						      var _size = $('hid_size').value;
						      var _cityName = $('city').options[$('city').selectedIndex].text;
						      var _areaName = $('areaName').value;
						      var _propType = $('propType').options[$('propType').selectedIndex].text;
						      var _location = _cityName + " " + _areaName;
						      if (_type == 4)
						      	_size = $('hid_lotsize').value;
						       
						      var marker = new GMarker(point, markerIcon);
							  GEvent.addListener(marker, "mouseover", function() {
					           		var html = '';
									html += '<div style="font-size:12px;min-height:120px;margin-bottom:20px;border:1px solid white;">';
									html += '<div style="border:0px solid black;text-align:left;margin:0 0 5px 0;"><a href="javascript:void(0)">'+_title+'</a></div>';
									html += '<div  style="border:0px solid yellow;">';
									html += '<div style="border:0px solid red;float:left;margin:2px 7px 0 0;">';
									html += '<img width="100" src='+_imageLocation+'></img>';
									html += '</div>';
									html += '<div class="google_popup" style="float:left;border:0px solid green;min-height:30px;">';
									html += '<div><label>Location: '+_location+'</label></div>';
									if(_size != -1){
										html += '<div><label>Size: '+_size+'&nbsp;sqft</label></div>';
									}
									if (_type!=4){
										html += '<div><label>Price: AED '+_price+'</label></div>';
										if(!(_type >= 5 && _type <= 9)){
											var plus = _bedrooms == 10 ? '+' : ''; 
											if(plus){
												html += '<div><label>Bedrooms: '+_finalRooms+' '+plus+'</label></div>';
											}else{
												var bedrooms = _bedrooms;
												if(bedrooms == -1 || bedrooms == 0){
													html += '<div><label>Bedrooms: Studio</label></div>';
												}else{
													html += '<div><label>Bedrooms: '+bedrooms+'</label></div>';
												}
											}
										}
									}
									html += '<div><label>Type: '+_propType+'</label></div>';
									html += '</div>';
									html += '<div style="clear:both"></div>';
									html += '</div>';
									html += '<div style="clear:both"></div>';
									html += '</div>';
											
					           	  map.openInfoWindow(point, html);
							  });
							  
							  map.addOverlay(marker);
						  } 
				      }
			      }
			   );
        }
	}
}
//loads default map view on post home
function loadAddListingMap(){
	 if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("googlemap"));
        var geocoder = new GClientGeocoder(); 
        //dummy
        var address = '25\u00B0 5\' 42.5106"N 55 11\'0.9198"E';
        
        if (geocoder){
        	  geocoder.getLatLng(address,
			      function(point) {
				      if (!point) {
				       //alert(address + " not found LOAD ADD LISTING MAP");
				      
				      } else {
				      var bound=new GLatLngBounds();
					  bound.extend(point);
				      
				      var newZoom = map.getBoundsZoomLevel(bound);
					  map.setCenter(bound.getCenter(), newZoom>18 ? 18:newZoom);
				      }
			      }
			   );
        }
        
        markerIcon = new GIcon();
		markerIcon.image = "css/images/map_logo.png";
		markerIcon.shadow = "css/images/map_logo.png";
		markerIcon.iconSize = new GSize(30, 44);
		markerIcon.shadowSize = new GSize(30, 44);
		markerIcon.iconAnchor = new GPoint(6, 20);
		markerIcon.infoWindowAnchor = new GPoint(15, 22);
		
        map.setMapType(G_HYBRID_MAP);
        map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		GEvent.addListener(map,"click", function(overlay,latlng) {    
		  if (latlng){
		  		map.clearOverlays();
	          	var pointY=latlng.lat() +'';
		        var pointX=latlng.lng() +'';
		        var marker = new GMarker(latlng, markerIcon);
			  	var message = ["This","is","the","secret","message"];
			  	GEvent.addListener(marker, "click", function() {
			  		var myHtml = "Google Coordinates : Latitude = " +pointY.parseDeg().toLat() +" <br/>and Longitude = "+pointX.parseDeg().toLon();
	            	//map.openInfoWindow(latlng, myHtml);
			 	});
			 	
			 	map.addOverlay(marker);
			 	
			 	$('latitude').value = pointY.parseDeg().toLat();
	        	$('longitude').value = pointX.parseDeg().toLon();
	       }
	        	
        });
        
   } 
}
//close pop up
function closePopup() {
	jQuery('#popupAnswer').css('display','none');
	jQuery('#popupAnswerQuestion').css('display','none');
	//$('messageContentDiv').innerHTML = '<img src="css/images/loader.gif" style="margin-left: 70px;">';
	jQuery('#modal').hide();
}

//display messages
/*
function displayMessage() {
	for (var i=startMessageDiv;i<=endMessageDiv; i++) {
		jQuery('#messagesContainer .messageWrapper:eq('+i+')').fadeIn('slow');
	}
}
//hide messages
function hideMessage() {
	for (var i=startMessageDiv;i<=endMessageDiv; i++) {
		jQuery('#messagesContainer .messageWrapper:eq('+i+')').hide();
	}
}
//set active message
function setActiveMessage(_pos){
	displayMessage();
	max = jQuery('#messagesContainer .messageWrapper:last').attr('id');
	if (_pos != null) {
		hideMessage();
		startMessageDiv = _pos;
		endMessageDiv = startMessageDiv + 2;
		for (var i=startMessageDiv;i<=endMessageDiv; i++) {
			jQuery('#messagesContainer .messageWrapper:eq('+i+')').fadeIn('slow');
		}
	}
	setPageNo();
}

//sets page no
function setPageNo() {
	if (isNaN(parseInt(max))) {
		document.getElementById('pageNo').innerHTML = "No Questions";
		jQuery('#messagesContainer').removeClass('messagesContainer');
		return;
	}
}

//move to next messages
function moveNext(){
	if (endMessageDiv >= max) {
		return;
	}
	
   	hideMessage();
   	startMessageDiv = endMessageDiv + 1;
   	endMessageDiv = endMessageDiv + 3;
   	displayMessage();
}

//move to previous messages
function movePrevious() {
   	if (startMessageDiv <= min){
   		return;
   	}
   	
   	hideMessage();	
   	endMessageDiv = startMessageDiv - 1;
   	startMessageDiv = startMessageDiv - 3;
}*/

//validates messages
function isValidated(_isOwner){
	
	if (isEmpty(document.message.messageContent.value)) {
		alert("Message must not be empty...");
		return false;
	} else if (jQuery('#messagesContainer .messageWrapper:eq(0)').attr('id') == undefined && _isOwner) {
		alert("No question found...");
		return false;
	} else if (_isOwner) { 
		if (activeId == null){
			alert("Please select question...");
			return false;
		} 
	} 
	return true;
}
//submits messages
function submitMessageForm(infoId, isOwner) {
	var messageDetails = "";
	var separator = "|";
	if (isOwner){
		document.getElementById('activeMessage').value = startMessageDiv;
	} else {
		document.getElementById('activeMessage').value = 0;
	}
	if (!isValidated(isOwner)) 
		return;

	messageDetails += infoId+separator;
	messageDetails += document.getElementById('messageTitle').innerHTML + separator;
	messageDetails += document.getElementById('messageContent').value;
	document.getElementById('messageDetails').value = messageDetails;
	document.message.submit();
}
//show pop up message failed
function showMessageFailedPopup() {
	jQuery('#popupMessageFailed').css('display','block');
	showModal("popupMessageFailed");
}
//switch to map view
function openMapSearch(){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	for (var i=0; i<=4 ;i++){
		if (i == 0){
			elementHide('allResults');
		}else{
			if ($('propertyList'+i)){
				elementHide('propertyList'+i);
			}
		}
		if ($('_listSearchTab'+i)){
			$('_listSearchTab'+i).className="tab";
		}
	}
}
//close map view
function closeMap(_obj){
	elementHide('map');
	elementHide('close_map');
	elementHide('_liclose_map');
	elementShow('allResults');
	elementShow('open_map');
	elementShow('_liopen_map');
	
	document.getElementById('_listSearchTab0').className ="tabActive";
	
}

function loadSpecificTabData(_index){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	if (_index==0){
		elementHide('allResults');
	}else{
		elementHide('propertyList'+_index);	
	}
	document.getElementById('_listSearchTab'+_index).className="tab";
}

/*
//loads map
function loadMapForSale(){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('propertyListSale');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	document.getElementById('_listSale').className="tab";
}
//loads map
function loadMapForRent(){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('propertyListRent');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	document.getElementById('_listRent').className="tab";
}
//loads map
function loadMapForClosure(){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('propertyListClosure');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	document.getElementById('_listClosure').className="tab";
}
//loads map
function loadMapForTimeShare(){
	elementShow('map');
	elementShow('close_map');
	elementShow('_liclose_map');
	elementHide('propertyListTimeShare');
	elementHide('open_map');
	elementHide('_liopen_map');
	
	document.getElementById('_listTimeShare').className="tab";
}

*/

//edit property listing
function editMyListing(_array){
	if (_array.length!=0){
		var _photos = _array.split("#--#");
		for (var i=0;i<_photos.length;i++){
			var _img = _photos[i].split("|--|");
			var isPrimary = _img[3]==0 ? false:true;
			photoCollection.addPhoto(new PhotoObject(_img[0],_img[1],_img[2]));
			if (isPrimary)
				photoCollection.setAsPrimary(_img[1]);
		}
		$('pictureList').innerHTML = photoCollection.getHTML();
	}

	loadOpenHouse();
	var hiddenCity = $('hiddenCity').value;
	var hiddenCityLat = $('hiddenCityLat').value;
	var hiddenCityLong = $('hiddenCityLong').value;
	$('city').value = hiddenCity +"-"+hiddenCityLat+"|"+hiddenCityLong;
	
	var hiddenNeighborhood = $('hidden_neighborhood').value;
	var hiddenNeigh_lat = $('hidden_neigh_lat').value;
	var hiddenNeigh_long = $('hidden_neigh_long').value;
	var neighborhood = hiddenNeighborhood +"-"+hiddenNeigh_lat+"|"+hiddenNeigh_long;
	
	var hiddenLatitude = $('hid_lat').value;
	var _latitude = hiddenLatitude.toDegreeFormat(true);
	var hiddenLongitude = $('hid_long').value;
	var _longitude = hiddenLongitude.toDegreeFormat(false);
	var lat = $('latitude');
	var long = $('longitude');
	
	showAndSelectArea(hiddenCity,neighborhood);
	isPostHome = true;
	loadAreaToMap(hiddenNeighborhood +"-"+hiddenLatitude+"|"+hiddenLongitude);
	
	lat.value = _latitude;
	long.value = _longitude;
	
	var hiddenStreet = $('hid_address').value;
	var street = $('txtAddress');
	street.value = hiddenStreet;
	
	var hid_listtype = $('hid_listtype').value;
	var hid_proptype = $('hid_proptype').value;
	var hid_readtype = $('hid_readtype').value;
	var hid_entityType = $('hid_entitytype').value;
	
	var lstType = $('lstType');
	var propType = $('propType');
	var readType = $('readType');
	var entityType = $('entityType');
	
	lstType.value = hid_listtype;
	propType.value = hid_proptype;
	entityType.value = hid_entityType;
	readType.value = hid_readtype;
	
	var hid_price = $('hid_price').value;
	var hid_lotsize = $('hid_lotsize').value;
	var hid_bedrooms = $('hid_bedrooms').value;
	var hid_size = $('hid_size').value;
	var hid_bathrooms = $('hid_bathrooms').value;
	var hid_builtyear = $('hid_builtyear').value;
	
	var price = $('txtPrice');
	var lotsize = $('txtLotSize');
	var bedrooms = $('txtBedRooms');
	var size = $('txtSize');
	var bathrooms = $('txtBathRooms');
	var builtyear = $('buildYear');
	
	price.value = hid_price;
	bedrooms.value = hid_bedrooms;
	size.value = hid_size;
	bathrooms.value = hid_bathrooms;
	builtyear.value = hid_builtyear;
	
	if($('propType').value =="4"){
		$('txtLotSize').disabled = false;
		$('txtPrice').disabled = false;
		$('txtBathRooms').disabled = true;
		$('txtBedRooms').disabled = true;
		$('txtSize').disabled = true;
		$('buildYear').disabled = true;
		$('building').disabled = true;
		$('txtAddress2').disabled = true;
		
		if(hid_lotsize != null){
			$('txtLotSize').value = hid_lotsize;
		}
		if(hid_bathrooms != null && hid_bathrooms == "-1"){
			$('txtBathRooms').value = "";
		}
		if(hid_bedrooms == "0" || hid_bedrooms == "" || hid_bedrooms == "-1"){
			bedrooms.selectedIndex = "0";
		}
		if(hid_size != null && (hid_size == "-1" || hid_size == "1")){
			$('txtSize').value = "";
		}
		if(hid_builtyear != null && (hid_builtyear == "-1" || hid_builtyear == "1999")){
			$('buildYear').value = "";
		}
		
		var hid_building = $('hid_building').value;
		var building = $('building');
		building.selectedIndex = "0";
		
		var hid_customBuilding = $('hid_customBuilding').value;
		var customBuilding = $('txtAddress2');
		customBuilding.value = hid_customBuilding;
		
		setElementBackgroundColor('txtLotSize','white');
		setElementBackgroundColor('txtPrice','white');
		setElementBackgroundColor('txtBathRooms','#D4D0C8');
		setElementBackgroundColor('txtBedRooms','#D4D0C8');
		setElementBackgroundColor('txtSize','#D4D0C8');
		setElementBackgroundColor('buildYear','#D4D0C8');
		setElementBackgroundColor('building','#D4D0C8');
		setElementBackgroundColor('txtAddress2','#D4D0C8');
		
	}else{
		if($('propType').value =="2"){
			elementMode('txtLotSize',true);
		 	elementMode('txtPrice',false);
		 	elementMode('txtBathRooms',false);
		 	elementMode('txtBedRooms',false);
		 	elementMode('txtSize',false);
		 	elementMode('buildYear',false);
		 	elementMode('building',false);
		 	elementMode('txtAddress2',false);
		 	
		 	if(hid_bedrooms == "0" || hid_bedrooms == "" || hid_bedrooms == "-1"){
				bedrooms.selectedIndex = "0";
			}
		 	
			var hid_building = $('hid_building').value;
			var building = $('building');
			if ($('hid_building').value == "0" ||$('hid_building').value == ""){
				building.selectedIndex = "None";
			}else{
				building.value = hid_building;
			}
			processEditElementBehaviour(hid_lotsize,'txtLotSize');
			processEditElementBehaviour(hid_bathrooms,'txtBathRooms');
			processEditElementBehaviour(hid_bedrooms,'txtBedRooms');
			processEditElementBehaviour(hid_size,'txtSize');
			processEditElementBehaviour(hid_builtyear,'buildYear');

			var hid_customBuilding = $('hid_customBuilding').value;
			var customBuilding = $('txtAddress2');
			customBuilding.value = hid_customBuilding;
						
			setElementBackgroundColor('txtLotSize','#D4D0C8');
			setElementBackgroundColor('txtPrice','white');
			setElementBackgroundColor('txtBathRooms','white');
			setElementBackgroundColor('txtBedRooms','white');
			setElementBackgroundColor('txtSize','white');
			setElementBackgroundColor('buildYear','white');
			setElementBackgroundColor('building','white');
			setElementBackgroundColor('txtAddress2','white');
			
		}else if($('propType').value >= 5 && $('propType').value <= 9){
			elementMode('txtLotSize',true);
		 	elementMode('txtPrice',false);
		 	elementMode('txtBathRooms',true);
		 	elementMode('txtBedRooms',true);
		 	elementMode('txtSize',false);
		 	elementMode('buildYear',false);
		 	elementMode('building',false);
		 	elementMode('txtAddress2',false);
		 	
		 	if(hid_bedrooms == "0" || hid_bedrooms == "" || hid_bedrooms == "-1"){
				bedrooms.selectedIndex = "0";
			}
		 	
			var hid_building = $('hid_building').value;
			var building = $('building');
			if ($('hid_building').value == "0" ||$('hid_building').value == ""){
				building.selectedIndex = "None";
			}else{
				building.value = hid_building;
			}
			processEditElementBehaviour(hid_lotsize,'txtLotSize');
			processEditElementBehaviour(hid_bathrooms,'txtBathRooms');
			processEditElementBehaviour(hid_bedrooms,'txtBedRooms');
			processEditElementBehaviour(hid_size,'txtSize');
			processEditElementBehaviour(hid_builtyear,'buildYear');

			var hid_customBuilding = $('hid_customBuilding').value;
			var customBuilding = $('txtAddress2');
			customBuilding.value = hid_customBuilding;
						
			setElementBackgroundColor('txtLotSize','#D4D0C8');
			setElementBackgroundColor('txtPrice','white');
			setElementBackgroundColor('txtBathRooms','#D4D0C8');
			setElementBackgroundColor('txtBedRooms','#D4D0C8');
			setElementBackgroundColor('txtSize','white');
			setElementBackgroundColor('buildYear','white');
			setElementBackgroundColor('building','white');
			setElementBackgroundColor('txtAddress2','white');
			
		}else{
			lotsize.value = hid_lotsize;
			elementMode('txtLotSize',false);
		 	elementMode('txtPrice',false);
		 	elementMode('txtBathRooms',false);
		 	elementMode('txtBedRooms',false);
		 	elementMode('txtSize',false);
		 	elementMode('buildYear',false);
		 	elementMode('building',false);
		 	elementMode('txtAddress2',false);
		 	
		 	processEditElementBehaviour(hid_lotsize,'txtLotSize');
			processEditElementBehaviour(hid_bathrooms,'txtBathRooms');
			processEditElementBehaviour(hid_bedrooms,'txtBedRooms');
			processEditElementBehaviour(hid_size,'txtSize');
			processEditElementBehaviour(hid_builtyear,'buildYear');
		 	
			if(hid_bedrooms == "0" || hid_bedrooms == "" || hid_bedrooms == "-1"){
				bedrooms.selectedIndex = "0";
			}
			
			var hid_building = $('hid_building').value;
			var building = $('building');
			if ($('hid_building').value == "0" ||$('hid_building').value == ""){
				building.selectedIndex = "None";
			}else{
				building.value = hid_building;
			}
			
			var hid_customBuilding = $('hid_customBuilding').value;
			var customBuilding = $('txtAddress2');
			customBuilding.value = hid_customBuilding;
	
			setElementBackgroundColor('txtLotSize','white');
			setElementBackgroundColor('txtPrice','white');
			setElementBackgroundColor('txtBathRooms','white');
			setElementBackgroundColor('txtBedRooms','white');
			setElementBackgroundColor('txtSize','white');
			setElementBackgroundColor('buildYear','white');
			setElementBackgroundColor('building','white');
			setElementBackgroundColor('txtAddress2','white');
		}
	}
		
	var hid_title = $('hid_title').value;
	var hid_desc = $('hid_desc').value;
	
	var title = $('txtTitle');
	var desc = $('txtDescription');
	
	title.value = hid_title;
	desc.value = hid_desc;
	
	var hid_openhouse = $('edit_openhouse').value;
	var openhouse = $('openHouse_date');
	openhouse.value = hid_openhouse;
	
	var hid_month = $('hid_month').value;
	var txtdateMonth = $('txtdateMonth');
	txtdateMonth.selectedIndex = hid_month - 1;
	
	var hid_day = $('hid_day').value;
	var txtdateDay = $('txtdateDay');
	txtdateDay.value = hid_day;
	
	var hid_year = $('hid_year').value;
	var txtdateYear = $('txtdateYear');
	txtdateYear.value = hid_year;
	
	var hid_hour = $('hid_hour').value;
	var txttimeHours = $('txttimeHours');
	txttimeHours.value = hid_hour;
	
	var hid_min = $('hid_min').value;
	var txttimeMinutes = $('txttimeMinutes');
	txttimeMinutes.value = hid_min;
	
	var hid_isOpenHouse = $('hid_isOpenHouse').value;
	var isOpenHouse = $('isOpenHouse');
	isOpenHouse.value = hid_isOpenHouse;
	
	var op_address = $('txtAddress').value;
	if(!isEmpty($('txtAddress').value)){
		$('txtatAddress').value = op_address;
	}
	
}
//changes text ui and behaviours
function processEditElementBehaviour(_obj,_id){
	if (!isElementNull(_obj) &&  _obj == "-1"){
		clearField(_id);
		setElementStyleColor(_id,'black');
	}
}
//process building name change
function buildingNameChange(){
	if($('building').value == "0"){
		$('txtAddress2').disabled = false;
		if(navigator.appName =="Microsoft Internet Explorer"){
			document.all['txtAddress2'].style.backgroundColor="white";
		}else{
			$('txtAddress2').style.backgroundColor="white";
		}
	}else{
		$('txtAddress2').disabled = true;
		if(navigator.appName =="Microsoft Internet Explorer"){
			document.all['txtAddress2'].style.backgroundColor="#D4D0C8";
		}else{
			$('txtAddress2').style.backgroundColor="#D4D0C8";
		}
	}
}
//subsmit update property info
function updatePropertyInfo(){
	var formUpdateInfo = document.updateForm;
	$('propertyData').value = info.toString();
	formUpdateInfo.submit();
}
//disable fields
function disabledFields(){
	elementMode('txtatAddress',true);
 	elementMode('txtdateDay',true);
 	elementMode('txtdateMonth',true);
 	elementMode('txtdateYear',true);
 	elementMode('txttimeHours',true);
 	elementMode('txttimeMinutes',true);
	$('isOpenHouse').value = "No";
	
	setElementBackgroundColor('txtatAddress','#D4D0C8');
	setElementBackgroundColor('txtdateDay','#D4D0C8');
	setElementBackgroundColor('txtdateMonth','#D4D0C8');
	setElementBackgroundColor('txtdateYear','#D4D0C8');
	setElementBackgroundColor('txttimeHours','#D4D0C8');
	setElementBackgroundColor('txttimeMinutes','#D4D0C8');
	
}
//sets mark flag
function markedFlag(){
	$('flag').innerHTML  = "Property marked on map";
	$('flag').style.color = "Green";
	$('flag').style.fontWeight = "normal";
}
//set mark unflag
function unmarkedFlag(){
	$('flag').innerHTML  = "Property not marked on map";
	$('flag').style.color = "Red";
	$('flag').style.fontWeight = "normal";
}
//removes title test
function removeDefaultTitleText(){
	var title = "Enter Title";
	
	if(isEqualTo($('txtTitle').value,title)){
		clearField('txtTitle');
		$('txtTitle').focus();
	}
	
}
//remove default desc text
function removeDefaultDescText(){
	var desc = "For example: Spacious Garden Home with Private Pool";
	
	if(isEqualTo($('txtDescription').value,desc)){
		clearField('txtDescription');
		$('txtDescription').focus();
	}
}
//enable fields
function enableFields(){
	elementMode('txtatAddress',false);
 	elementMode('txtdateDay',false);
 	elementMode('txtdateMonth',false);
 	elementMode('txtdateYear',false);
 	elementMode('txttimeHours',false);
 	elementMode('txttimeMinutes',false);
 	
 	setElementBackgroundColor('txtatAddress','white');
	setElementBackgroundColor('txtdateDay','white');
	setElementBackgroundColor('txtdateMonth','white');
	setElementBackgroundColor('txtdateYear','white');
	setElementBackgroundColor('txttimeHours','white');
	setElementBackgroundColor('txttimeMinutes','white');
	
}
//load open house
function loadOpenHouse(){
	var isOpenHouse = $('hid_isOpenHouse').value;
	
	if(isOpenHouse == "Yes"){
		enableFields();
		setChecked('yes',true);	
	}else{
		setChecked('no',true);	
	}
}

//sets open house
function isOpenHouse(){
	var yes = $('yes').checked;
	var no = $('no').checked;
	
	var yes_value = $('yes').value;
	var no_value = $('no').value;
	
	var isOpenHouse = $('isOpenHouse');
	var now = new Date();
	var curr_month = now.getMonth() + 1;
	
	if(yes){
		
		var hours = new Date();
		var op_hours = hours.getHours();
		
		var minutes = new Date();
		var op_minutes = minutes.getMinutes();
		
		$('txtdateMonth').value = curr_month;
		$('txttimeHours').value = op_hours;
		$('txttimeMinutes').value = op_minutes;
		
		var op_address = $('txtAddress').value;
		if(!isEmpty($('txtAddress').value)){
			$('txtatAddress').value = op_address;
		}
		enableFields();
		isOpenHouse.value = yes_value;
	}else{
		$('txtdateMonth').value = curr_month;
		disabledFields();
		isOpenHouse.value = no_value;
	}		
}

//keep house address and open house address consistent
//parameter widget updated:
//  'add1': house address in tab 1
//  'add2': open house address in tab2
function addListingSynchronizeAddresses(widget) {
	if (widget == 'add1')
		$('txtatAddress').value = $('txtAddress').value;
	else if (widget == 'add2')
		$('txtAddress').value = $('txtatAddress').value;
}

//clear open house fields
function clearOpenHouseFields(){
	clearField('txtdateMonth');
	clearField('txtdateDay');
	clearField('txtdateYear');
	clearField('txttimeHours');
	clearField('txttimeMinutes');
}

//text address onchange event
function addressOnChange(event,_obj){
	$('txtatAddress').value = _obj.value;
}
//validates open house data
function validateOpenHouseData(){
	if(!validateListingField())
		return false;
	if($('yes').checked){
		
		if (isEmpty($('txtatAddress').value)){
			messageInfoDisplay('errorMsg',"Address is required.","block");	
			messageInfoDisplay('errorListingMsg',"Address is required.","block");	
			$('txtatAddress').focus();
			return false;
		}else if (isEmpty($('txtdateMonth').value)){
			messageInfoDisplay('errorMsg',"Month is required.","block");	
			messageInfoDisplay('errorListingMsg',"Month is required.","block");	
			$('txtdateMonth').focus();
			return false;
		}else if (!($('txtdateMonth').value >0 && $('txtdateMonth').value < 13)){
			messageInfoDisplay('errorMsg',"Month is from 1 - 12 only.","block");
			messageInfoDisplay('errorListingMsg',"Month is from 1 - 12 only.","block");	
			$('txtdateMonth').focus();
			return false;
		}else if (isEmpty($('txtdateDay').value)){
			messageInfoDisplay('errorMsg',"Day is required.","block");	
			messageInfoDisplay('errorListingMsg',"Day is required.","block");	
			$('txtdateDay').focus();
			return false;
		}else if (!($('txtdateDay').value >0 && $('txtdateDay').value < 32)){
			messageInfoDisplay('errorMsg',"Day is from 1 - 31 only.","block");	
			messageInfoDisplay('errorListingMsg',"Day is from 1 - 31 only.","block");	
			$('txtdateDay').focus();
			return false;
		}else if (isEmpty($('txtdateYear').value)){
			messageInfoDisplay('errorMsg',"Year is required.","block");	
			messageInfoDisplay('errorListingMsg',"Year is required.","block");	
			$('txtdateYear').focus();
			return false;
		}else if (!($('txtdateYear').value >1908 && $('txtdateYear').value <= 9999)){
			messageInfoDisplay('errorMsg',"Year is from 1909 - 9999 only.","block");	
			messageInfoDisplay('errorListingMsg',"Year is from 1909 - 9999 only.","block");	
			$('txtdateYear').focus();
			return false;
		}else if (isEmpty($('txttimeHours').value)){
			messageInfoDisplay('errorMsg',"Hour is required.","block");	
			messageInfoDisplay('errorListingMsg',"Hour is required.","block");	
			$('txttimeHours').focus();
			return false;
		}else if (!($('txttimeHours').value >=1 && $('txttimeHours').value <= 24)){
			messageInfoDisplay('errorMsg',"Hour is from 1 - 24 only.","block");	
			messageInfoDisplay('errorListingMsg',"Hour is from 1 - 24 only.","block");	
			$('txttimeHours').focus();
			return false;
		}else if (isEmpty($('txttimeMinutes').value)){
			messageInfoDisplay('errorMsg',"Minute is required.","block");	
			messageInfoDisplay('errorListingMsg',"Minute is required.","block");	
			$('txttimeMinutes').focus();
			return false;
		}else if (!($('txttimeMinutes').value >=0 && $('txttimeMinutes').value <= 59)){
			messageInfoDisplay('errorMsg',"Minutes is from 00 - 59 only.","block");	
			messageInfoDisplay('errorListingMsg',"Minutes is from 00 - 59 only.","block");	
			$('txttimeMinutes').focus();
			return false;
		}
	}
	messageInfoDisplay('errorMsg',"","none");
	return true;
}
//show Modal
function showModal(_id) {
        var popupDiv = jQuery('#'+_id);
	    var height = jQuery(window).height();
	    var width = jQuery(window).width();
	
	    popupDiv.css({
	        'left' : jQuery(window).scrollLeft() + (width/2 - (popupDiv.width() / 2)),  
	        'top' : jQuery(window).scrollTop() + (height/2 - (popupDiv.height() / 2))
	    });
	    
	    var referenceHeight = jQuery('#reference').height();
	    jQuery('#modal').css({
	    	'min-height': referenceHeight,
	    	'display':'block'
	    });
	    
        jQuery('#'+_id).css('display','block');
}
//close mark;	
function closeMark() {
	jQuery('#popupMark').hide();
    jQuery('#modal').hide();
    jQuery('#popupWrapper').hide();
    if (jQuery('#popup')){
    	jQuery('#popup').hide();
    }
    if (jQuery('#popupFavorite2')){
    	jQuery('#popupFavorite2').hide();
    }
}
//checks index
function checkIndex(_index, size) {
	var disabledNextSrc = urlPath + "css/images/disabled_next.jpg";
	var disabledPreviousSrc = urlPath + "css/images/disabled_previous.jpg";
	
	if (_index == 0) {
		jQuery('.previousProperty').css(
			{
				'backgroundImage':'url('+disabledPreviousSrc+')'
			}
		);
		
		jQuery('.previousProperty a').css(
			{
				'text-decoration'	: 'none',
				'color'     : '#C1C1C1',
				'cursor'	: 'default'
			}
		);
	}
	
	if (_index == size-1 || size == 0) {
		jQuery('.nextPropertyDetails').css(
			{
				'backgroundImage':'url('+disabledNextSrc+')'
			}
		);
		
		jQuery('.nextPropertyDetails a').css(
			{
				'text-decoration'	: 'none',
				'color'     : '#C1C1C1',
				'cursor'	: 'default'
			}
		);
	}
}
//confirm purchase
function confirmPurchase(){
	if (isEmpty($('featuredListing').value)){
		$('featuredListing').focus();
		return;
	}else if (isEmpty($('propertyListing').value)){
		$('propertyListing').focus();
		return;
	}else if ($('propertyListing').value + $('featuredListing').value + $('premiumListing').value == 0){
		$('propertyListing').focus();
		return;
	}
	
	document.purchase.submit();
}

//crete marker
function createMarker(point,html, _icon){
	var marker = new GMarker(point,{icon: _icon});
	GEvent.addListener(marker, "mouseover", function() {
		map.openInfoWindow(point, html);
	});
	
	return marker;
	
}
//laod all properties to map
function loadAllProperties(id,latitude, longitude,address, isEOF, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location, url_){
	if (!mapPointsCollection)
		mapPointsCollection = new MapPointsCollection();
		
		
	var _latitude = latitude.toDegreeFormat(true);
	var _longitude = longitude.toDegreeFormat(false);	
	var mapPoints = new MapPoints(id, _latitude, _longitude, address, _title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location);
	mapPoints.addUrl(url_);
	mapPoints.setCurrentIndex(currentIndex);
	var point = new GLatLng(latitude.toDecimalFormat(),longitude.toDecimalFormat());
	
	markerIcon = new GIcon();
	markerIcon.image = "css/images/map_logo.png";
	markerIcon.shadow = "css/images/map_logo.png";
	markerIcon.iconSize = new GSize(30, 44);
	markerIcon.shadowSize = new GSize(30, 44);
	markerIcon.iconAnchor = new GPoint(6, 20);
	markerIcon.infoWindowAnchor = new GPoint(15, 22);
	
 	var marker = createMarker(point,mapPoints.getHTML(), markerIcon); 
 	//alert("mapPoints--------> " + mapPoints.getHTML());
 	mapPoints.addMarker(marker);
	mapPointsCollection.addPoint(mapPoints);
	myBounds[myBounds.length] = point;
	
	if (isEOF){
  		if (initialize)
  			mapSetCenter(myBounds);
  		
  		if (selectedId!=null){
  			clickProperty(selectedId);
  		}
      		
   		if (!isJspLoaded && initialize){
			map.clearOverlays();
      			for (var _point in mapPointsCollection.properties){
				 if( typeof(mapPointsCollection.properties[_point]) == "object" ) {
				 		map.addOverlay(mapPointsCollection.properties[_point].marker);
				 }
			}
   		}
	}
}
//map sets center
function mapSetCenter(_list){
	var _bounds =_list;
	
	var boundss=new GLatLngBounds();
	for(var i=0;i<_bounds.length;i++){
		boundss.extend(_bounds[i]);
	}
	
	var newZoom = map.getBoundsZoomLevel(boundss);
	newZoom = newZoom -1;
	map.setCenter(boundss.getCenter(), newZoom>18 ? 17:newZoom);

	return true;
}
//invove on click on property
function clickProperty(_id){
	if (_id==null)
		return;
	var property = mapPointsCollection.getById(_id);
	if (property == null)
		return;
	
	map.setCenter(property.marker.getPoint(),18);
	map.openInfoWindow(property.marker.getPoint(), property.getHTML());
}
//load search map
function loadSearchMap(_city,_area,_building,_id){
	selectedId = _id;
	if (!initialize){
		initializeMap();
	}
	if (initialize){
		if (mapPointsCollection){
			if (_id!=null){
				clickProperty(_id);
			}else{
				mapSetCenter(myBounds);	
				if (!isJspLoaded && $('map').style.display == "block"){
					map.clearOverlays();
					if (!noResults)
	       			for (var _point in mapPointsCollection.properties){
						 if( typeof(mapPointsCollection.properties[_point]) == "object" ) {
						 		map.addOverlay(mapPointsCollection.properties[_point].marker);
						 }
					}
					isJspLoaded = true;
				}
			}
			return;
		}
		
	}
	refreshMap(_city,_area,_building);
}
//refresh gmap
function refreshMap(_city,_area,_building){
	if (initialize && isJspLoaded){
		map.clearOverlays();
		mapPointsCollection = new MapPointsCollection();
	}
	myBounds =new Array();
	
	if (!isJspLoaded){
		map.clearOverlays();
		mapPointsCollection = new MapPointsCollection();
	}
	
	var isBuy = true;
	
	if (!(String(window.location).match("buy.jsp"))){
		isBuy = !isBuy;
	}
	
	new Ajax.Request(loadMaps, { 
		asynchronous:true, method: 'post', parameters: 'buildingName='+_building+'&city='+_city+'&area='+_area+'&isBuy='+isBuy,
			onComplete: function(transport){
				var json = transport.responseText;
				if (json != "-1"){
					
					json = json.evalJSON();
					tempList = json.maps;
					
					for (var i=0;i<json.maps.length;i++){
						var id = json.maps[i].id;
						var lat = json.maps[i].lat;
						var lng = json.maps[i].lng;
						var address = json.maps[i].address;
						var last = false;
						var _title = json.maps[i].title;
						var _size = json.maps[i].size;
						var _price =json.maps[i].price;
						var _bedrooms = json.maps[i].bedrooms;
						var _bathrooms = json.maps[i].bathrooms;
						var _imageLocation = json.maps[i].primaryPhoto;
						var _type = json.maps[i].type;
						var _typeName = json.maps[i].typeName;
						var _location = json.maps[i].location;
						var url_ = json.maps[i].validUrl;
						currentIndex = i;
						if (i==json.maps.length-1){
							last = !last;
						}
						loadAllProperties(id,lat,lng,address,last,_title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type,_typeName,_location, url_);
						//alert(_typeName +" "+ _location);
					}
				}
			}
	});
}
//load coordinatest to temporary collections
function loadToCollections(){
	if (initialize && mapPoints2Collection.length==0)
     	map.clearOverlays();
     	
	for (var i=0;i<mapPoints2Collection.length;i++){
		var id = mapPoints2Collection[i].id;
		
		var lat = mapPoints2Collection[i].lat;
		var lng = mapPoints2Collection[i].lng;
		var address = mapPoints2Collection[i].address;
		var last = false;
		var _title = mapPoints2Collection[i].title;
		var _size = mapPoints2Collection[i].size;
		var _price = mapPoints2Collection[i].price;
		var _bedrooms = mapPoints2Collection[i].bedrooms;
		var _bathrooms = mapPoints2Collection[i].bathrooms;
		var _imageLocation = mapPoints2Collection[i].imageLocation;
		var _type = mapPoints2Collection[i].type;
		var _typeName = mapPoints2Collection[i].typName;
		var _location = mapPoints2Collection[i].location;
		var url_ = mapPoints2Collection[i].propertyUrl;
		
		currentIndex = i;
		
		if (i==mapPoints2Collection.length-1){
			last = !last;
		}
		loadAllProperties(id,lat,lng,address,last,_title, _size, _price,_bedrooms, _bathrooms, _imageLocation,_type, _typeName, _location, url_);
	}
}
//set active tab
function setActiveTab(_tab) {
	if (_tab != null) {
		resetMyBeeyootTabs();
		jQuery('#summaryTab').addClass("tab");
		jQuery('#myListingTab').addClass("tabActive2");
		hideNotActiveTabBody("profileSummary");
        displaySelectedTabBody("myListing");
	}
}
//resets my beeyoot tabs
function resetMyBeeyootTabs() {
	jQuery('#myListingTab').removeClass();
	jQuery('#summaryTab').removeClass();
}
//display selected tab body
function displaySelectedTabBody(_id) {
	jQuery('#'+_id).css('display','block');
}
//hide not active tab body
function hideNotActiveTabBody(_id) {
	jQuery('#'+_id).css('display','none');
}

//validate forgot password
function validateForgotPassword(){
	if (isEmpty($('fpusername').value)){
		$('fpusername').focus();
		return;
	}
	document.getElementById("forgot_password").submit();
	
}
//sets selected role
function setSelectedRole(path,_id){
	$('popupHeaderCommon').innerHTML = "Save Changes"+' <a href="javascript:closeMark();setDefaultRoleComboIndex()" class="popupClose"><img alt="close" src="css/images/popup_close.gif" width="14" height="16" border="0"></a>';
	$('popupContent').innerHTML = "Save Changes"+'?<br><a id="confirmDelete" href="'+path+'" class="deleteConfirm yes" onClick="javascript:showLoaderPopup(\'Updating Profile\')">YES</a><a href="javascript:closeMark();setDefaultRoleComboIndex()" class="deleteConfirm">CANCEL</a>';
	showModal("popup");
}

function setDefaultRoleComboIndex() {
	var roleCombo = document.getElementById('roles');
	var role = document.getElementById('role');
	
	defaultIndex = role.selectedIndex;
	roleCombo.options[defaultIndex-1].selected = true;
		
}

//validate offline payment
function validateOfflinePayment(){
	if($('offline_payment').checked){
		if (isEmpty($('nameOfBuyer').value)){
			messageInfoDisplay('paymentErrorMsg',"Name is required.","block");	
			$('nameOfBuyer').focus();
			return false;
		}else if (!isValidEmail($('emailOfBuyer'))){
			messageInfoDisplay('paymentErrorMsg',"Please enter a valid email address.","block");
			$('emailOfBuyer').focus();
			return false;
		}else if (isEmpty($('phoneOfBuyer').value)){
			messageInfoDisplay('paymentErrorMsg',"Telephone no. is required","block");	
			$('phoneOfBuyer').focus();
			return false;
		}else if (!isNumeric($('phoneOfBuyer').value)){
			messageInfoDisplay('paymentErrorMsg',"Numbers are only accepted.","block");	
			$('phoneOfBuyer').focus();
			return false;
		}else if (isEmpty($('addressOfBuyer').value)){
			messageInfoDisplay('paymentErrorMsg',"Address is required.","block");	
			$('addressOfBuyer').focus();
			return false;
		}
	}
	messageInfoDisplay('paymentErrorMsg',"","none");
	return true;
}

function setPaymentMethod(value_){
	$('paymentMethod_').value = value_;
}

//set payment option
function setPaymentOption(){
	if($('online_payment').checked){
		$('online_payment').checked = true;
		$('admin').show();
		$('_offline').hide();
		$('paymentOptionId').value = 1;
		$('paymentMethod').options[0].selected=true
		$('paymentMethod').show();
	}else{
		$('offline_payment').checked = true;
		$('admin').hide();
		$('paymentOptionId').value = 0;
		$('_offline').show();
		$('paymentMethod').hide();
	}
	$('paymentMethod_').value = 0;
}
//validaton payment option
function paymentOption(){
	if (!validateOfflinePayment())
		return;
		
	document.confirm.submit();
}

function checkServices(isFree_){
	if (isFree_ == 1){
		$('services_').hide();
		$('propertyListing').value = 0;
		$('featuredListing').value = 0;
		return;
	}
	
	$('services_').show();
}

function getCityId(_cityId){
	var cId =  $('city')
	var cityLat = $('cityId');
	var val = cId.options[cId.selectedIndex].value;
		
	var _address = _cityId.substring(_cityId.indexOf("-")+1).split("|");
	if (!_address[1])
		return;
	_address = _address[0].toDegreeFormat(true) +" "+_address[1].toDegreeFormat(false);
	
	cityLat.value = val;
	
	loadMapForCity(_address);
}

function loadMapForCity(_address){
	if (map==null || map =='undefined')
		return;
	
	if (GBrowserIsCompatible()) {
		var geocoder = new GClientGeocoder(); 
		if (geocoder){
        	  geocoder.getLatLng(_address,
			      function(point) {
				      if (!point) {
				       	  //alert(_address + " not found LOAD MAP BY ADDRESS");
				      } else {
					      var bound=new GLatLngBounds();
						  bound.extend(point);
					      
					      //var newZoom = map.getBoundsZoomLevel(bound);
						  map.setCenter(bound.getCenter(),13);
						  
				      }
			      }
			   );
        }
	}
}

//key filterring
function keyFiltering(event,value,page,combo){
	if ((event.which && event.which == 37)||(event.which && event.which == 38) ||
		(event.which && event.which == 39) ||(event.which && event.which == 40)||
		(event.keyCode && event.keyCode == 37)||(event.keyCode && event.keyCode == 38)||
		(event.keyCode && event.keyCode == 39)||(event.keyCode && event.keyCode == 40)) {

//1 = country -> for now we dont need this but just put todo for country
//2=city
//3=area
		if (combo == 2){
		//functions needed by city
			if (page == "post_home"){
			//copy onchange function on post home
					showArea(value,false);
					getCityId(value);
					emptyMap();
			}else if (page == "map_search"){
				showArea(value,true);
				setCityValue(value);
			}else{
			//copy onchange function on index and home city combo or area combo
				showArea(value,true);
				setCityValue(value);
			}
		}else if (combo == 3){
		//functions needed by area
			if (page == "post_home"){
			//copy onchange function on post home
				loadAreaToMap(value);
				emptyMap();
			}else if (page == "map_search"){
			//copy onchange function on map_searh
				setAreaValue(value);
			}else{
			//copy onchange function on index and home city combo or area combo
				setAreaValue(value);
			}
		}else{
			
		//functions needed by country combo
		//for now just right todo:s here
		}
		
		return true;
	}
}

function isOnline() {
	if ($('beeyootUser').value == "") 
		return false;
	return true;
}


