var highlighted; //GLOBAL relates to var where, memorizes highlighted row
var propertyRow = []; //GLOBAL contains key/value pairs for selected properties
var mapRequest;
var mapCallback = false;

function evenOut() {
	$("#specs").css("height", "auto");
	if($("#lower-panel .sidebar").height() < $("#specs").height()) {
		$("#lower-panel .sidebar").css("height", $("#specs").height()+"px");
	} else if($("#lower-panel .sidebar").height() > $("#specs").height()) {
		$("#specs").css("height", $("#lower-panel .sidebar").height()-2+"px");
	}
}
function tableEvents(firstLoad) { //must be reset each time data is loaded (by sorting)
	var where; //kind of like highlighted, but local to this function
	for(var i=0; i<propertyRow.length; i++) {
		$("#"+propertyRow[i].propId).addClass(propertyRow[i].propClass);//add selected classes right away
	}
	$(".sidebar tr:not(.red)").hover(function() {
		$(this).addClass("quickhighlight");
	}, function() {
		$(this).removeClass("quickhighlight");
	});
	$("#property-list tr").click(function() {
		closeMap();
		var which = this.className;
		$("#dynamic").removeClass("inviz");
		$("#request-form").addClass("inviz");
		$("#"+highlighted).removeClass("highlighted");
		where = highlighted = this.id;
		$("#"+highlighted).addClass("highlighted");
		$("#property-image").removeClass("noimage");
		$("#property-image").load("inc/image.php?im=image1&i="+where, function() {verifyImage();}); //also loads initial info/images here
		$("#specs #dynamic").load("inc/info.php?i="+where, function() {specEvents(where)});
		pageTracker._trackPageview('/properties-for-sale.php?id='+where.substring(1));
	});
	if(firstLoad) {
		if(defaultTo != 0) {
			$("#P"+defaultTo).trigger("click");
		} else {
			where = $("#property-list tr:eq(0)")[0].id;
			highlighted = where;
		}
	} else {
		where = highlighted;
	}
	$("#"+highlighted).addClass("highlighted"); //rehighlight saved row each time
	$("#property-image").removeClass("noimage");
	$("#property-image").load("inc/image.php?im=image1&i="+where, function() {verifyImage();}); //also loads initial info/images here
	$("#specs #dynamic").load("inc/info.php?i="+where, function() {specEvents(where)});
}

function verifyImage() { //checks to see if an image exists, then removes loading class from div if not;
	if($("#property-image img").length==0) {
		$("#property-image").addClass("noimage");
	}
}

function specEvents(whe) { //callback function for load of specs to define events and make equal columns
	$("#lower-panel .sidebar").css("height", "auto");
	var thisStr = $(".selectproperty")[0].id;
	thisStr = thisStr.replace(/select/, ""); //check current ID against array to see if it is selected
	var isSelected = [];
	//alert("P"+thisStr);
	$("#property-list tr").each(function() {
		//alert(this.className);
		if(this.className == "selected" || this.className == "selected highlighted" || this.className == "selected quickhighlight highlighted") {
			/*if(this.id == "P"+thisStr) {
				var str=this.id;
				//isSelected = true;
				isSelected.push(str.replace(/P/, "select"));
			}*/
			//$("#"+this.id+" input").attr("checked", "checked");
			unBindSelect("#"+$("#"+this.id+" .selectproperty")[0].id);
		}
	});
	evenOut();
	$(".thumbnail").click(function() {
		$("#property-image").load("inc/image.php?im="+this.id+"&i="+whe, function() {verifyImage();});
		return false;
	});
	$("#map-single").click(function() {//map single property
		mapRequest="single";
		var myLat = $("#latitude").html();
		var myLong = $("#longitude").html();
		var myTitle = $("#my-title").html();
		var location = $("#thisaddress").html();
		var myDescription = "<p>TYPE: "+$("#my-type").html()+'<br />'+location+'<br /><a id="lat:'+myLat+'" name="long:'+myLong+'" title="'+myTitle+'" rel="TYPE: '+$("#my-type").html()+'|'+location+'" class="birds-eye" href="#" onclick="zoomTo(this.id, this.name, this.title, this.rel)">Click to see location on map</a></p>';
		openMapSingle({lat: myLat, long: myLong, view: "birdseye"});
		//ChangeMapStyle("road");
		CreateLayer();
		AddPushpin(myTitle, myDescription);
		return false;
	});
	if(mapCallback) {
		$("#map-single").trigger("click");
		mapCallback=false;
	}
	function bindSelect(thisElement) {//toggles different event handler whether property is selected or not -this one selects property
		$(thisElement).click(function() {
			var str=this.id;
			str = str.replace(/select/, "");
			$("#P"+str).addClass("selected");
			//selected[selected.length] = str;
			//$(this).html("Deselect this property");
			$("#select-buttons").removeClass("inviz");
			unBindSelect("#"+this.id);
		});
	}
	bindSelect(".selectproperty"); //initial state is with this handler
	//if(isSelected) { //but it can be overridden by this one
		//$(".selectproperty").html("Deselect this property");
	
	//}
	function unBindSelect(thisElement) {//toggles different event handler whether property is selected or not -this one deselects property
		$(thisElement).unbind("click");
		$(thisElement).click(function() {
			$(this).unbind("click");
			var str=this.id;
			str = str.replace(/select/, "");
			$("#P"+str).removeClass("selected");
			//selected[selected.length] = str;
			//$(this).html("Select this property");
			if($(".selected").length == 0) {
				$("#select-buttons").addClass("inviz");
			}
			bindSelect("#"+this.id);
		});
	}
}

function openMapSingle(params) {
	$("#map-canvas").removeClass("inviz");
	$("#close-map").removeClass("inviz");
	$("#property-panel").addClass("inviz");
	$("#property-image").addClass("inviz");
	if(params.view == "birdseye") {
		GetMap(params.lat, params.long, 18, "o");
	} else {
		GetMap(params.lat, params.long, 15, "r");
	}
	//$("#map-canvas").load("inc/map.php?"+params+"&height=100&width=100");
	//more here
}

function closeMap() {
	$("#map-canvas").addClass("inviz");
	$("#close-map").addClass("inviz");
	$("#property-panel").removeClass("inviz");
	$("#property-image").removeClass("inviz");
}

var map = null;
var layer;
var shape;
var mapType = "";
function GetMap(thisLat, thisLong, zoom, maptype) {
	map = new VEMap('map-canvas');
	if(maptype != "o") {
		//map.SetDashboardSize(VEDashboardSize.Small);
		map.SetDashboardSize(VEDashboardSize.Large);
	} else {
		//map.SetDashboardSize(VEDashboardSize.Tiny);
		map.SetDashboardSize(VEDashboardSize.Large);
	}
	map.LoadMap(new VELatLong(thisLat, thisLong), zoom ,maptype ,false);
	map.onLoadMap = function(){
		//$(".MSVE_PoweredByLogo").hide(); 
		//setMapEvents();
		/*if(mapType == "birdseye") {
			ChangeMapStyle("birdseye");
			map.SetCenterAndZoom(new VELatLong(thisLat, thisLong), 18);
			mapType = "";
		}*/
	}
	CreateLayer();
}

function zoomTo(lat, long, titletext, reltext) {
	//$(".birds-eye").click(function() {
		//alert("hello");
		//var lat = this.id;
		lat = lat.replace(/lat:/, "");
		//var long = this.name;
		long = long.replace(/long:/, "");
		//var zoo = 18;
		if(mapRequest == "single") {
			mapType="road";
			GetMap(lat, long, 15, "r");
			//ChangeMapStyle("birdseye");
			CreateLayer();
			var thisText=reltext.split("|");
			AddPushpin(titletext, '<p>'+thisText[0]+'<br />'+thisText[1]+'<br /><a class="map-view" href="#" onclick="zoomAway()">Click to return to birds-eye view</a></p>');
		} else {
			mapType="birdseye";
			GetMap(lat, long, 18, "o");
			//ChangeMapStyle("birdseye");
			CreateLayer();
			AddPushpin(titletext, reltext+'<br /><a class="map-view" href="#" onclick="zoomAway()">Click to return to map</a>');
		}

		//ChangeMapStyle("birdseye");
		//map.SetCenterAndZoom(new VELatLong(lat, long), zoom);
		//$(this).removeClass("birds-eye");
		//$(this).addClass("map-view");
		//$(this).html("Click to switch to map view");
	//});
	/*$(".map-view").click(function() {
		ChangeMapStyle("road");
		$(this).addClass("birds-eye");
		$(this).removeClass("map-view");
		$(this).html("Click to switch to bird's eye view");
	});*/
}
function zoomAway() {
	if(mapRequest=="single") {
		var thisTitle = $(".VE_Pushpin_Popup_Title").html();
		$("td.title").each(function() {
			if(this.innerHTML == '<a href="#highlight">'+thisTitle+'</a>') {
				mapCallback=true;
				$(this).parents("tr").trigger("click");
			}
		});
		//$("#map-single").trigger("click");
	} else {
		$("#map").trigger("click");
	}
}

function CreateLayer() {
	layer = new VEShapeLayer();
	map.AddShapeLayer(layer);
}

function AddPushpin(thisTitle, thisDescription, theLat, theLong) {
	if(theLat != null && theLong != null) {
		shape = new VEShape(VEShapeType.Pushpin, new VELatLong(theLat, theLong));
	} else {
		shape = new VEShape(VEShapeType.Pushpin, map.GetCenter());
	}
	shape.SetTitle(thisTitle);
	shape.SetDescription(thisDescription);
	layer.AddShape(shape);
}

function start() {	
	$(".sidebar th a").click(function() {
		propertyRow.length = 0; //reset the set so that data doesn't become jumbled
		$("#property-list tr").each(function() {//keeps track of where the classes are so that selected properties remain intact
			propertyRow[propertyRow.length] = {
				propId: this.id,
				propClass: this.className
			};
		});
		if(this.className == "up") {
			this.className="down"; //only sort table by column here
			$("#property-list").load("inc/property-list.php?sort="+this.id, function() {tableEvents()});//this.id contains data for sort
		} else if(this.className == "down") {
			this.className="up"; //else sort by title, since both are up
			$("#property-list").load("inc/property-list.php?order=up&sort="+this.id, function() {tableEvents()});
		} else {
			$(".sidebar th a").removeClass("up");
			$(".sidebar th a").removeClass("down");
			if(this.id=="type") {
				this.className="up";
				$("#property-list").load("inc/property-list.php?order=up&sort="+this.id, function() {tableEvents()});
			} else {
				this.className="down";
				$("#property-list").load("inc/property-list.php?sort="+this.id, function() {tableEvents()});
			}
		}
		var thisId = this.id;
		var thisClass = this.className;
		$(".sidebar th a").each(function() {
			if(this.id!=thisId && this.className == thisClass) { //check the other sort column and change it, if needed.
				if(this.className == "down") {
					this.className="up";
				}
			}
		});
		return false;
	});
	$("#request").click(function() {//request selected properties
		$("#request-form").removeClass("inviz");
		$("#dynamic").addClass("inviz");
		var i=1;
		$("#property-list tr").each(function() {
			if(this.className == "selected" || this.className == "selected highlighted" || this.className == "highlighted selected") {
				evenOut();
				//alert(this.id);
				//$.post("inc/buildlist.php", {property: this.id},
				//function(data) {
					$("#property-request").append("<b>- "+$("#"+this.id+" td.title a")[0].innerHTML+"</b><br /><br />");
				//});
				$("#hidden-fields").append('<input type="hidden" id="PP'+i+'" name="P'+i+'" value="'+this.id+'" />');
			}
			i++;
		});
		return false;
	});
	$("#cancel").click(function() {
		$("#dynamic").removeClass("inviz");
		$("#request-form").addClass("inviz");
		$("#property-request").html(" ");
		$("#hidden-fields").html(" ");
		evenOut();
		return false;
	});
	var formValues = [];
	$("#request-form form").submit(function() {
		var formValid = true;
		$("#request-form form input").each(function() {
			if(this.id != "contact-submit") {
				if (this.value.length == 0) {
					$("#request-form form").append("<label id='error-message' class='left'><strong>Please fill out every field</strong></label>");
					formValid = false;
					return false;
				}
			}
		});
		if(formValid) {
			var requested = {};
			var varRequested = 'var requested = {firstname: $("#firstname")[0].value, lastname: $("#lastname")[0].value, email: $("#email")[0].value, phone: $("#phone")[0].value, type: $("#type")[0].value,';
			var i=1;
			var more = true;
			$("#hidden-fields input").each(function() {
					
					varRequested += 'P'+i+': "'+this.value+'", ';
					i++;
				});
			varRequested += '}';
			varRequested = varRequested.replace(",}", "}");
			//alert(varRequested);
			//var requested = {firstname: $("#firstname")[0].value, lastname: $("#lastname")[0].value, email: $("#email")[0].value, phone: $("#phone")[0].value, type: $("#type")[0].value,P1: $("#PP1")[0].value}
			//alert(requested);
			eval(varRequested);//evil
			requested.emailupdates = $("#emailupdates")[0].checked;
                        requested.seed = $('input[name=seed]').attr('value');
			
			$.post("inc/sendmail.php", requested, function(data) {
				//return name of agent and success message here.
				//$("#error-message").remove();
				$("#request-form").html(data);
				$("#request-form").hide();
				$("#request-form").fadeIn("medium");
			});
		}
		return false;
	});
	$("#map").click(function() {
		var multipleProps = null;
		var multipleProps = [];
		var points = [];//seperate array for points on map to calculate zoom level
		$("#property-list tr").each(function() {//build array of properties that are eligible for map(have latitude and longitude)
			if(this.className == "selected" || this.className == "selected highlighted" || this.className == "highlighted selected") {
				var lati=$("#"+this.id+" .title")[0].id;
				lati=lati.replace(/latitude:/, "");
				var longi=$("#"+this.id+" .location")[0].id;
				longi=longi.replace(/longitude:/, "");
				var thisTitle=$("#"+this.id+" .title").html().replace(/<a href="#highlight">/, "");
				thisTitle=thisTitle.replace(/<\/a>/, "");
				var thisDescription = $("#"+this.id+" .type").html().replace(/<a href="#highlight">/, "");
				thisDescription = thisDescription.replace(/<\/a>/, "");
				//if(!isNaN(Number(thisDescription))) {thisDescription=Number(thisDescription);}
				//thisDescription +=	$("#"+this.id+" .type").html();
				
				thisDescription=(/\d/.test(thisDescription))?"<p>Units: "+thisDescription:"<p>Type: "+thisDescription;
				
				var address = $("#"+this.id+" .price")[0].id;
				var lines = new Array();
				lines = address.split("_");
				//lines[lines.length] += "<br />"+"Price: "+$("#"+this.id+" .price").html().replace(/<a href="#highlight">/, "");
				//lines[lines.length] = lines[lines.length].replace(/<\/a>/, "");
				thisDescription += "<br />";
				for(var i=1; i<lines.length; i++) {//starts at 1 because the 0 isn't used here.
					lines[i]=lines[i].replace(/nbsp/, "&nbsp;");
					if(i<3) {
						if(lines[i] != "&nbsp;") {
							lines[i]+= "<br />";
						}
					} else if(i == 3) {
						lines[i]+=", ";
					} else if(lines[i] != "&nbsp;") {
						lines[i]+=" ";
					}
					if(lines[i] != "&nbsp;") {
						thisDescription += lines[i];
					}
				}
				thisDescription += "<br />Price: "+$("#"+this.id+" .price").html().replace(/<a href="#highlight">/, "");
				thisDescription = thisDescription.replace(/<\/a>/, "");
				thisDescription += "</p>";
				//thisDescription=thisDescription.replace(/<a href="#highlight">/, "");
				//thisDescription=thisDescription.replace(/<\/a>/, "");
				//alert(thisDescription);
				if(lati.substring(0, 4) != "none" && longi.substring(0, 4) != "none") {
					//alert(longi);
					//alert(lati+" "+longi);
					multipleProps[multipleProps.length] = {
						title: thisTitle,
						latitude: lati,
						longitude: longi,
						description: thisDescription+'<br /><a id="lat:'+lati+'" name="long:'+longi+'" title="'+thisTitle+'" rel="'+thisDescription+'" class="birds-eye" href="#" onclick="zoomTo(this.id, this.name, this.title, this.rel)">Click to see birds-eye view of property</a>'
					}
					points[points.length] = new VELatLong(lati, longi);
				}
			}
		});
		//alert(multipleProps[0].length);
		mapRequest="multiple";
		
		for(var i=0; i<multipleProps.length; i++) {
			if(!i) {
				openMapSingle({lat: multipleProps[i].latitude, long: multipleProps[i].longitude});
				CreateLayer();
			} else {
				//map.SetCenterAndZoom(new VELatLong(multipleProps[i].latitude, multipleProps[i].longitude), 15);
			}
			CreateLayer();
			AddPushpin(multipleProps[i].title, multipleProps[i].description, multipleProps[i].latitude, multipleProps[i].longitude);
		}
		map.SetMapView(points);
		//CreateLayer();
		//alert("opening");
		return false;
	});
	
	$("#close-map").click(function(){
		closeMap();
	});
	
	var qString;
	$("#print").hover(function() {
		qString = this.href;
		var newQ = qString;
		$("#property-list tr").each(function() {
			if(this.className == "selected" || this.className == "selected highlighted" || this.className == "highlighted selected") {
				newQ += "|"+this.id;
			}
		});
		this.href=newQ;
	}, function() {this.href=qString;});
	
	$("#agents-login").click(function() {
		$("#agents-login").unbind("click");
		$.getScript("/js/thickbox.js", function(){
			$("#agents-login").trigger("click");
		});
		return false;
	});
}

$(document).ready(function() {
	$(".sidebar tr th:eq(4)").css("border-right", "none"); //cell-spacing hack (cuz I hate inline crap)
        $.get('/inc/seed.php', function(data){
            $("#request-form form").append('<input type="hidden" name="seed" value="'+data+'">');
        });
	$("#property-list").load("inc/property-list.php?sort=price&order=up", function() {tableEvents(true)}); //callback function must set events each time
	start();
});