 jQuery.noConflict();
 jQuery(document).ready(function()
		{
			// Set these variables to change beginning map location
			var beginLatitude = 47.6;
			var beginLongitude = -122.33;
			var beginZoom = 10;
			var initialPropertiesPerPage = 10;
			var propertiesPerPage = initialPropertiesPerPage;
			var currentPage = 1;
			//1 based
			var startPropertyNumber = 1;
			var maxPropertyNumber = initialPropertiesPerPage;
			// Url for accessing data from database
			var pinServiceUrl = "/assets/php/processMapRequest.php";
			
			// Global variable to initialize VEMap in
			var map = null;
			// Global variable to track current pinId
			var pinid = 0;
			// Should we render the map now or wait for call back
			var waitingForCallback = false;
			// Global variable to track city and state
			var city = getURLParam("city");
			var state = getURLParam("state");
			var allow = bannedProps();
			resizePropertyMap();
			var iver = getIESix();
			if(!iver){
				jQuery("#loadin").css("z-index","100");	
			}
			
			
			
			if(city != "" && state != "" && allow){
				getPropertySearch(camelCase(city),camelCase(state));
			}
			
			// Initialize map
			// mapDivName - Div container for map
			function GetMap(mapDivName) {
				if( window.VEMap !=undefined){
				    map = new VEMap(mapDivName);
				    map.LoadMap();
				}
				else{
					mapServiceUnavailable();
				}
			    
			}
			
			// Add Pushpin at desired latitude & longitude
			// Title - Title of Pushpin
			// Description - Description to set on Pushpin
			// latLon - VELatLong object of location to set PushPin
			// p - Position of Pushpin in search result
			function AddPushpin(title, latLon, pos, path, description) {
			    var shape = new VEShape(VEShapeType.Pushpin, latLon);
			    if( pos < 9 ){
			    shape.SetCustomIcon("<img src='/assets/new/images/icon_map_label.gif'/><span class='maptxt'>" + (pos+1) + "</span>");
				}
				else{
				shape.SetCustomIcon("<img src='/assets/new/images/icon_map_label.gif'/><span class='maptxt2'>" + (pos+1) + "</span>");
				}

			    shape.SetTitle("<a title='"+title+"' href='"+ path +"'>"+title+"</a>");
			    shape.SetDescription(description);
			    //pinid++;
			    map.AddShape(shape);
			}
			
			function AddPushpin2(latLon) {
			    var shape = new VEShape(VEShapeType.Pushpin, latLon);
			    shape.SetCustomIcon("<img src='/assets/new/images/icon_map_label.gif'/>");
			    //shape.SetTitle(title);
			    //shape.SetDescription(description);
			    map.AddShape(shape);
			}
			function getPropertySearch(city_name, state_name) {
				city = city_name;
				state = state_name;
				if(!iver){
					jQuery("#loadin").show();	
				}
               if(inlineJsonData.length>0)
               {
            	   RenderInitialResults(inlineJsonData);
               }

			}
			
			function displayProperty(property_path) {

				jQuery.getJSON(pinServiceUrl, { FCxx: "displayPropertyAjax", arg1: property_path }, GetPinsCallback2);
			}
			
			//Render Initial results for page
			function RenderInitialResults() {
				if(map != null)
				{
				map.Clear();
				}
			     
		    	 
			     createSelectPropertiesPerPage();
			     createPageControl();
			     setupHideMap();
			     
				 window.setTimeout(function(){ RenderMap();},50); 
			}
			function RenderMap() {
				if(window.VELatLong != undefined){
					if(map != null)
					{
					map.Clear();
					}
					var count = null;
					var link = null;
				   	var velatlong = new Array();			    
				   	jQuery("#loadin").css("display","none");
					GetMap("map");   
					var latLongIndex = 0;
					for(var i = startPropertyNumber-1; i<maxPropertyNumber && i<inlineJsonData.length; i++)
					    {	
						    var item  = inlineJsonData[i];
					    	velatlong[latLongIndex] = new VELatLong(item.latitude, item.longitude);
					    	var link = rewritelink(item.path);
					    	var d = "<div>"+ item.address + ", <br/>" + item.city + ", "+item.state+" "+item.zip+"</div>";		    	
							AddPushpin(item.name, velatlong[latLongIndex], i, link, d);
							latLongIndex = latLongIndex +1;
					    };
					    map.SetMapView(velatlong);
					}
				else{
					mapServiceUnavailable();
				}
					

			}
			
			// Call back from JSON displayProperty command.  Parse JSON response and adds pins to map.
			function GetPinsCallback2(jsonData) {
				if(map != null)
				{
					map.Clear();					
				}
				else{
					GetMap("map");
					}
				//map.Resize();
				
				if(jsonData != null){
					var velatlong = new Array();
			    	velatlong[0] = new VELatLong(jsonData.latitude, jsonData.longitude);			    	
					AddPushpin2(velatlong[0]);
				   
				    map.SetMapView(velatlong);
				}
			}
								
			// Repopulates maps with push pins on map change events
			function MapChangeHandler(e) {
			    if(!waitingForCallback)
			    {
			       // LoadPushPins();
			    }
			}
			
			function rewritelink(path){
				var st = path.indexOf("/", 1);
				var nlink = path.substr(st)+".php";
				return nlink;
			}
			
			function getURLParam(strParamName){
				var strReturn = "";
				var strHref = window.location.href;
				if ( strHref.indexOf("?") > -1 ){
					var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
					var aQueryString = strQueryString.split("&");
					for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
						if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
							var aParam = aQueryString[iParam].split("=");
							strReturn = unescape(aParam[1]).replace(/\+/g, " ");
							break;
						}
					}
				}
				return strReturn;
			}
			function resizePropertyMap(){
				jQuery("#content-inner-bottom #top-bar span:eq(2)").click(function () {
					if(map != null){
						map.Resize();	
					}
					
					if(jQuery("#content-inner-bottom .tabs span.mappath").get(0) != null){
						var ppath = jQuery("#content-inner-bottom .tabs span.mappath").html();
						displayProperty(ppath);
					}
				});
			}
			
			function camelCase( s ) { 
				var newS = '';
				var QS = s.split(" ");
				for ( var i = 0; i < QS.length; i++ ){
					if( QS[i] == 'dc'){
						newS += QS[i].toUpperCase();
					}
					else{
					var t = QS[i].charAt(0);
					var temp = t.toUpperCase() + QS[i].substr(1);
					newS += temp;
					}
					if(QS.length != (i+1)){newS += ' ';}
				}
				return newS;
				
		    }
		    
		    function bannedProps(){
		    	if(state == "washington" && city == "washington"){
		    		return false;	
		    	}
		    	return true;
		    }
		    
		    function getInternetExplorerVersion()
			// Returns the version of Internet Explorer or a -1
			// (indicating the use of another browser).
			{
			  var rv = -1; // Return value assumes failure.
			  if (navigator.appName == 'Microsoft Internet Explorer')
			  {
			    var ua = navigator.userAgent;
			    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
			    if (re.exec(ua) != null)
			      rv = parseFloat( RegExp.$1 );
			  }
			  return rv;
			}
		   
		   function getIESix(){
			   	var ver = getInternetExplorerVersion();
				if ( ver > -1 )
				 {
				    if ( ver >= 6.0 && ver < 7.0){
				    	return true;
				    }
				 }
				 return false;
		   }

			function createSelectPropertiesPerPage()
			{
				
				if(inlineJsonData!=null && inlineJsonData.length > initialPropertiesPerPage){
				   jQuery("#bottom-map-rslt").append('<div id="navigation-container"><div id="properties-per-page">View <select id="select-properties-per-page"><option value="10">10&nbsp;&nbsp;&nbsp;&nbsp;</option><option value="20">20&nbsp;&nbsp;&nbsp;&nbsp;</option><option value="50">50&nbsp;&nbsp;&nbsp;&nbsp;</option></select> Per Page</div></div>');
				   jQuery("#select-properties-per-page").change(function(){
					   var strPropertiesPerPage = jQuery("#select-properties-per-page option:selected").val();
					    propertiesPerPage = parseInt(strPropertiesPerPage);
					    startPropertyNumber = 1;
					    maxPropertyNumber = propertiesPerPage;
					   	refreshResults();
					   }
				   );
				    
				}
			}
			function createPageControl(){
				
			  jQuery("#page-navigation").remove();
			  if(inlineJsonData!=null){
				  var maxPages = determineMaxPages();
				  if(maxPages>1){
					  var currentPage = determineCurrentPage();
					  
					  var back = currentPage>1 ? '<li id="previous-arrow"><a>previous</a></li>': "";
					  var next = currentPage <maxPages? '<li id="next-arrow"><a>next</a></li>' : "";
					  var firstPage = back.length>1 && currentPage!=1?'<li id="first-page"><a>1</a></li>': "";
					  var lastPage = next.length>1  && currentPage!=maxPages? '<li id="last-page"><a>'+maxPages+'</a></li>':"";
					  var previousPage = currentPage>=3?'<li id="previous-page"><a>'+(currentPage-1)+'</a></li>':"";
					  var currentPageButton = '<li id="current-page">'+currentPage+'</li>';
					  var nextPage = (currentPage + 1) <maxPages?'<li id="next-page"><a>'+(currentPage+1)+'</a></li>':"";
					  var pageAfterNext = (currentPage == 1 || currentPage+3 == maxPages) && (currentPage+2)<maxPages ?'<li id="page-after-next"><a>'+(currentPage+2)+'</a></li>': "";
					  var pageBeforePrevious = (currentPage ==maxPages || (currentPage-3==1)) && (currentPage>=4)?'<li id="page-before-previous"><a>'+(currentPage-2)+'</a></li>':"";
					  var spacerAfter = currentPage + 3 <maxPages? "<li>...</li>":"";
					  var spacerBefore = currentPage -3 >1?"<li>...</li>":"";
					  
					  
					  
					  jQuery("#navigation-container").append('<div id="page-navigation"><ul id="page-list">'+back+firstPage+spacerBefore+pageBeforePrevious+previousPage+currentPageButton+nextPage+pageAfterNext+spacerAfter+lastPage+next+'</ul>');
					  
					  //assign click events
					  jQuery("#bottom-map-rslt #previous-arrow, #bottom-map-rslt #previous-page").click(function(){
						        changeToPage(currentPage-1);
					  		}
					  );
					  jQuery("#bottom-map-rslt #next-arrow, #bottom-map-rslt #next-page").click(function(){
					        changeToPage(currentPage+1);
				  		}
					  );
					  jQuery("#bottom-map-rslt #page-after-next").click(function(){
						    changeToPage(currentPage+2);  
					   }
					  );
					  jQuery("#bottom-map-rslt #page-before-previous").click(function(){
						    changeToPage(currentPage-2);  
					   }
					  );
					  jQuery("#bottom-map-rslt #first-page").click(function(){
						    changeToPage(1);
					  	}  
					  );
					  jQuery("#bottom-map-rslt #last-page").click(function(){
						    changeToPage(maxPages);
					  	}  
					  );
						    
					  
				  }
			  }
			}
			function refreshResults() {
				
				//clear map
				if(map != null)
				{
					map.Clear();
				}
				var link = null;
				var item = null;
				//clear map result section
				jQuery("#properties-results").empty();
				var startIndex =startPropertyNumber - 1; 
				for (var i = startIndex; i<maxPropertyNumber && i<inlineJsonData.length; i++)	
				{
					item = inlineJsonData[i];
			    	link = rewritelink(item.path);
			    	var marshaLink = "";
			    	//leave email unescaped to ensure processing. escape needed to ensure apostrophe doesn't mess up link
			    	var contactRepLink="<a href='/reservations/contact.php?destination-city="+escape(item.city)+"&destination-state="+escape(item.state)+"&neighborhood="+escape(item.neighborhood)+"&property-display-name="+escape(item.name)+"&contact-email="+item.email+"&contact-phone="+escape(item.phone)+"&source=Search' class='slnk2'>Contact a Representative</a>";
					if( item.marsha != ''){
						marshaLink = "<a href='/reservations/reserve-engine.php?name="+ escape(item.name) +"&#38;add="+ escape(item.address) +"&#38;city="+ escape(item.city) +"&#38;state="+ escape(item.state) +"&#38;zip="+ escape(item.zip) +"&#38;resv="+ escape(item.phone) +"&#38;code="+ escape(item.marsha) +"&#38;property-path="+item.path+"'><img src='/assets/new/images/checkrates.png' alt='Check Property Rates'/></a>";
     				}
					jQuery("#properties-results").append("<div class='map-result-row'><div class='col-one'><span class='txt'>" + (i+1) + "</span></div><div class='col-two'><a href='"+ link +"' class='slnk'>"+ item.name +"</a>"+ item.address + ", " + item.city + ", "+item.state+" "+item.zip+" USA</div><div class='col-three'>"+ item.mile +" miles</div><div class='col-four'>"+marshaLink+contactRepLink+"</div><div class='clear'></div></div>");

					if( i >= 9 ){
						var rowPosition = i-startIndex;
						jQuery("#properties-results .map-result-row:eq("+rowPosition+") .col-one span").removeClass("txt");
						jQuery("#properties-results .map-result-row:eq("+rowPosition+") .col-one span").addClass("txt2");
					}

				 }
				createPageControl();
				RenderMap();

			}
			function determineMaxPages(){
			  if(propertiesPerPage >0){
				  var pages = Math.ceil(inlineJsonData.length/propertiesPerPage);
				  return pages;
			  }
			  return 0;
			}
			function determineCurrentPage(){
			   var currentPage = maxPropertyNumber/propertiesPerPage;
			   return currentPage;
			}
			function changeToPage(desiredPage){
				
				startPropertyNumber = (desiredPage - 1)*propertiesPerPage+1;
				maxPropertyNumber  = desiredPage*propertiesPerPage;
				refreshResults();
				
			}
			function mapServiceUnavailable(){
				jQuery("#map-top .select").remove();
				jQuery("#map-container").empty();
				jQuery("#map-container").append('<div id="map-service-unavailable">Sorry, no maps are available at this time.</div>');
			}
			function setupHideMap(){
				jQuery("#map-toggle input:eq(0)").attr("checked", "checked");
				jQuery("#map-toggle input:radio").click(function() {				
					var selected = jQuery("#map-toggle input[@name='map-tog']:checked").val();
					if(selected == "Map" )
					{
						jQuery("#map-container").show();
						RenderMap();
						
					}
					else{
						jQuery("#map-container").hide();
					}
				});
			}
			
				
		}
	);			