function nDUnitJSON (unitElement) {

	var inc = unitElement.unit
	var incImages = (unitElement.images&&unitElement["images"]['img'])?unitElement["images"]['img']:new Array();
	if (inc == null) return null;
	this.property_id = (unitElement.property_id == null)?"":unitElement.property_id;

	this.id = (inc.id == null)?"":inc.id;
	this.cost = (inc.cost == null)?"":inc.cost;
	this.cost_max = (inc.cost_max == null)?"":inc.cost_max;
	this.features = (inc.features == null)?"":inc.features;
	this.label = (inc.label == null)?"":inc.label;

	this.beds = (inc.bedroom_count == null)?"0":inc.bedroom_count;
	this.incentive = (inc.incentive == null)?"0":inc.incentive;
	this.baths = (inc.bathroom_full_count == null)?"0":inc.bathroom_full_count;
	this.halfbaths = (inc.bathroom_half_count == null)?"0":inc.bathroom_half_count;
			
	this.deposit = (inc.deposit == null)?"":inc.deposit;
	this.size = (inc.size == null)?"":inc.size;
	this.text = (unitElement.text&&unitElement.text.length > 0)?getDOMText(unitElement.text):"";
	this.fp = (inc.unit_fp)?inc.unit_fp:0;
	this.distance = (inc.distance)?inc.distance:null;

	var address = unitElement.address;
	
	this.address_street_1 = address.street_1;
	this.address_city = address.city;
	this.address_state = address.state;
	this.address_postal = address.postal;
	this.address_lat = address.lat;
	this.address_lng = address.lng;
	

	this.feature_specs = (unitElement.feature.spec)?unitElement.feature.spec:0;
	this.feature_text = (unitElement.feature.text)?unitElement.feature.text:"";
	
	this.utility_specs = (unitElement.utility.spec)?unitElement.utility.spec:0;
	this.utility_text = (unitElement.utility.text)?unitElement.utility.text:"";

	this.accessibility_specs = (unitElement.accessibility.spec)?unitElement.accessibility.spec:0;
	this.accessibility_text = (unitElement.accessibility.text)?unitElement.accessibility.text:0;

	this.parking_specs = (unitElement.parking.spec)?unitElement.parking.spec:0;
	this.parking_text = (unitElement.parking.text)?unitElement.parking.text:0;

	this.petpolicy_specs = (unitElement.petpolicy.spec)?unitElement.petpolicy.spec:0;
	this.petpolicy_text = (unitElement.petpolicy.text)?unitElement.petpolicy.text:0;

	this.kitchen_specs = (unitElement.kitchen.spec)?unitElement.kitchen.spec:0;
	this.kitchen_text = (unitElement.kitchen.text)?unitElement.kitchen.text:0;

	this.laundry_specs = (unitElement.laundry.spec)?unitElement.laundry.spec:0;
	this.laundry_text = (unitElement.laundry.text)?unitElement.laundry.text:0;
	
	temp = unitElement.listing;
	if (temp) {
		this.listing_date_start = temp.start;
		this.listing_date_end = temp.end;
		this.listing_date_available = temp.available;
		this.listing_head_line = temp.head_line;
		this.listing_text = (temp.text&&temp.text.length > 0)?getDOMText(temp.text):"";
	} else {
		this.listing_date_start = "";
		this.listing_date_end = "";
		this.listing_date_available = "";
		this.listing_head_line = "";
		this.listing_text = "";
	}

	this.images = incImages;
		
	return this;
}
nDUnitJSON.prototype.addImage = function(asset){
	if (asset && asset.getAttribute & asset.getAttribute("image_src")) this.images.push(asset);
}

function nDFloor (inc, incImages) {
	if (inc == null) return null;
	this.id = (inc.getAttribute("floor_id") == null)?"":inc.getAttribute("floor_id");
	this.parent_id = (inc.getAttribute("building_id") == null)?"":inc.getAttribute("building_id"); 
	this.images = [];
	if (incImages != null) for (var x = 0; x < incImages.length; x++) { this.images.push(incImages[x]); }
	
	return this;
}

function nDBuilding (inc, incImages) {
	if (inc == null) return null;
	this.id = (inc.getAttribute("building_id") == null)?"":inc.getAttribute("building_id");
	this.parent_id = (inc.getAttribute("property_id") == null)?"":inc.getAttribute("property_id"); 
	this.images = [];
	if (incImages != null) for (var x = 0; x < incImages.length; x++) { this.images.push(incImages[x]); }
	return this;
}


function nDPropertyJSON (inc, incImages) {
	
	if (inc == null) return null;
	var address = inc.address;
	var prop = inc.property;
	this.id = (prop.id == null)?"":prop.id;
	this.parent_id = (prop.portfolio_id == null)?"":prop.portfolio_id;
	this.images = inc.images;
	this.label = (prop.property_label == null)?"":prop.label;
	this.head_line = (prop.head_line == null)?"":prop.head_line;
	this.type = (prop.type == null)?"":prop.type;
	this.incentive = (prop.incentive == null)?"":prop.incentive;
	this.min_age = (prop.min_age == null)?"":prop.min_age;
	this.listing_type = (prop.listing_type == null)?"0":prop.listing_type;
	this.text = (inc.text&&inc.text.length > 0)?getDOMText(inc.text):"";
	this.street_1 = address.street_1;
	this.city = address.city;
	this.state = address.state;
	this.postal = address.postal;
	this.lat = address.lat;
	this.lng = address.lng;
	this.feature_specs = (inc.feature&&inc.feature.spec)?inc.feature.spec:"";
	this.feature_text = (inc.feature&&inc.feature.text)?inc.feature.text:"";
	
	if (incImages != null) for (var x = 0; x < incImages.length; x++) { this.images.push(incImages[x]); }

	return this;
}

function getObjectSpecs(xml, feature) {
	var spec = xml.getElementsByTagName(feature);
	if (spec.length > 0) return [((spec[0].getAttribute(feature + "_specs"))?  spec[0].getAttribute(feature + "_specs"):spec[0].getAttribute('spec') ), ((spec[0].getElementsByTagName("text").length > 0)?getDOMText(spec[0].getElementsByTagName("text")[0]):"")];
	else return [0, ""];
}

function listSingle(inc){ $.post("/property/list/u" + inc.getAttribute("unit"), function(data){listHandler(data, inc);}); }
function delistSingle(inc){ $.post("/property/delist/u" + inc.getAttribute("unit"), function(data){listHandler(data, inc);}); }
function setExpLoading(inc) { $(inc).parent().prev().html("<img src=\"/images/loading_sm.gif\" style=\"float: left;\" />&nbsp; Loading"); }
function deleteSingle(inc){ $.post("/property/delete/unit", "id=" + $(inc).attr("unit"), function(data){deleteHandler(data, inc);}); }
function deleteProperty(inc){$(inc).parent().parent().hide(); $(inc).parent().parent().next().hide(); $.post("/property/delete/property", "id=" + $(inc).attr("property"), function(data){deleteHandler(data, inc);});}

function listHandler(data, inc) {
	if (!data || !inc) return;
	var json = eval(data);
	if (json.success) {
		if (json.date.match("00-00")) {
			$(inc).parent().prev().html("<span style=\"color: #bbb;\">Not Listed</span>");
			$(inc).removeClass("delistbtn o").addClass("listbtn").html("List");
		}else {
			$(inc).parent().prev().html("<span>Exp.: " + json.date.substring(5) + "</span>");
			$(inc).removeClass("listbtn").addClass("o delistbtn").html("Unlist");
		}
	} else {
		
	}
}

function deleteHandler(data, inc) {
	if (!data || !inc) return;
	var json = eval(data);
	if (json.success) $(inc).parent().parent().empty().remove();
}

function showProperty(inc){
	if (!parseInt(inc.id)) return;
	hideTT();
	if ($(inc).parent().parent().next().is("tr.collapsed.child")) {
		$(inc).parent().parent().attr("class", "expanded parent").next().attr("class", "expand-child expanded child loading");
		$.post(
				"/property/get/p" + parseInt(inc.id),
				function(data) {
				data = $.parseJSON(data);
					//showPropertyHandler(inc, data);
					drawProperty(data, inc, 1);
				}
		);
	} else {
		hideProperty(inc);
	}
}

function hideProperty(inc) { 
	$(inc).parent().parent().attr("class", "collapsed parent").next().attr("class", "expand-child collapsed child").find("td").html("&nbsp;");
	$(inc).css("background", "");
}

function showPropertyHandler(inc, data) {
	var tokens = "";
	var code = 1;
	var displaymode = 0;
	var editmode = 0;
	var return_message = null;
	var param = null;

	var doc = data.getElementsByTagName("document")[0];
	displaymode = doc.getAttribute("display");
	editmode = doc.getAttribute("edit");
	doc = null;
	var info = data.getElementsByTagName("info");
	info = info[0];
	code = parseInt(info.getAttribute("return_code"));
	if(info.getAttribute("return_message")) return_message = info.getAttribute("return_message");

	switch(code){
		case 1: 
			drawProperty(data, inc, editmode);
			break;
		default: 
			break;
	}
}

function drawPropertyLine(data, display, edit) {
	var property = new nDPropertyJSON(data);
	var text = "<tr class='collapsed parent'><td class='collapsible'><a id='" + property.id  + "' href='#' class='collapsed'>&nbsp;</a></td>";
	text += "<td>"+property.street_1+"</td>";
	text += "<td>"+property.state+"</td>";
	text += "<td>"+property.city+"</td>";
	text += "<td>"+property.postal+"</td>";
	text += "<td>&nbsp;</td></tr><tr class='expand-child collapsed child loading'><td colspan='6'>&nbsp;</td></tr>";
	$("#property_table tbody tr.alert-empty").remove();
	$(text).prependTo("#property_table tbody");
}

function drawProperty(data, inc, mode){
	var units = data.units;
	var property = new nDPropertyJSON(data.property);
	var row = $(inc).parent().parent().next().removeClass("loading").find("td")[0];
	/*var propText = "<div class='propImage'><img src='' style='max-width: 180px; max-height: 120px;' /></div>" ;
	propText += "<div class='propBox'><h6><b>Basic Info</b></h6><div class='prop_stat'></div><div class='prop_stat'></div><div class='prop_stat'></div></div>";
	propText += "<div class='propBox'><h6><b>Analytics</b></h6>";
		propText += "<div class='propStat interest'><b>Interest: </b><img src='/images/loader.gif' alt='loading' /></div>";
		propText += "<div class='propStat views'>Views: <img src='/images/loader.gif' alt='loading' /></div>";
		propText += "<div class='propStat email'>Email leads: <img src='/images/loader.gif' alt='loading' /></div>";
	propText += "</div>";
	propText += "<div class='propBox'>";
		propText += "<h6><b>&nbsp;</b></h6>";
		propText += "<div class='propStat phone'>Phone: <img src='/images/loader.gif' alt='loading' /></div>";
		propText += "<div class='propStat saved'>Saved by <img src='/images/loader.gif' alt='loading' /></div>";
		propText += "<div class='propStat shared'>Shared by <img src='/images/loader.gif' alt='loading' /></div>";
	propText += "</div>";
	propText += "<div class='propBox'>";
		propText += "<h6><b>Actions</b></h6>";
		propText += "<div class='propStat preview'><a href='#'>Preview Listing</a></div>";
		propText += "<div class='propStat edit'><a href='#'>Edit Listing</a></div>";
		propText += "<div class='propStat'><a id='manage' href='#'>Manage Tenants</a></div>";
		propText += "<div class='propStat'><a id='deactivate' href='#'>Deactivate Property</a></div>";
	propText += "</div>";
	
	$(propText).appendTo($(row));
	*/
	$(inc).css("background", "url('/images/16-square-blue-remove.png') no-repeat scroll 0 0 transparent");
	
	var tabletext = '<table class="sortable"><thead><tr><th class="header">Name</th><th class="header">Price</th><th class="header">BD</th><th class="header">BA</th><th class="header">&frac12;BA</th><th class="header">Size</th><th class="header"><img src="../images/chrystal_ball.png" alt="Interest" /></th><th class="header"><img src="../images/magnifier.png" alt="Views" /></th><th class="header"><img src="../images/mail_view.png" alt="Email" /></th><th class="header"><img src="../images/phone.png" alt="Phone" /></th><th class="header"><img src="../images/star_yellow.png" alt="Starred" /></th><th class="header"><img src="../images/earth_view.png" alt="Shared" /><th>List Date</th><th colspan="2"><a class="fn addunit nd-btn xsm bl" href="'+property.id+'">&#43; Add a ';
	if (property.listing_type > 0) tabletext += 'floorplan';
	else tabletext += 'listing';
	tabletext += '</a></th></tr></thead><tbody></tbody></table>';

	$(tabletext).appendTo($(row));
	var innerBody = $(row).find('tbody');
	$.each(units, function(){
		drawUnit(new nDUnitJSON(this), innerBody, mode);
	});
		
	
}

function drawUnit(unit, root, mode) {
	if (!root) return;
	if (!mode) mode = 0;
	var r, temp = "";
	r = $("<tr id='u"+unit.id+"'></tr>").prependTo(root);
	if (mode>0) temp += "<a style=\"color:#343434\" href='/listing/edit/u" + unit.id + "/step1'>";
	if (unit.label == "") temp += "<strong style=\"color: #d00\">[Add listing details]</strong>";
	else temp += unit.label;
	if (mode>0) temp += "</a>";
	$('<td>'+temp+'</td>').appendTo($(r));
	if (parseInt(unit.cost) <= "0") temp = "<span style=\"color: red;\">$" + unit.cost + "/m</span>"; 
	else temp = "$" + unit.cost + "/m";
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.beds == 7) temp = "Room";
	else if (unit.beds == 0) temp = "Studio";
	else temp = unit.beds;
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.baths == 0) temp = "Shared"; 
	else temp = unit.baths;
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.halfbaths) temp = unit.halfbaths;
	else temp = 0;
	$('<td>'+temp+'</td>').appendTo($(r));
	
	////size needed//////
	if (unit.size) $("<td>"+unit.size+"</td>").appendTo($(r)); 
	else $("<td><span style='color:red'>?</span></td>").appendTo($(r));
	$("<td colspan='6' style='text-align:center;'><em>Metrics coming soon!</em></td>").appendTo($(r));
	/*$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));*/
	var listed = /^\d{4}-\d{2}-\d{2}/;
	var listTools = "";
	var listDate = "";
	//HUH?
	var ldate = new Date(unit.listing_date_start);
	var edate = new Date(unit.listing_date_end);
	var ndate = new Date();
	if (listed.test(unit.listing_date_start) && !((unit.listing_date_start).match("00-00")) && ndate.getTime()>=ldate.getTime() && ndate.getTime()<=edate.getTime()) {
		if (mode>0) listTools = "<a class='fn delistbtn nd-btn xsm o' title=\"\" unit='" + unit.id + "'>Unlist</a>";
		listDate += "<span>Exp.: " + (unit.listing_date_end).substring(5).replace(/ 00:00:00/, "") + "</span>";
	}else {
		if (mode > 0) listTools = "<a class='fn listbtn nd-btn xsm' unit='" + unit.id + "'>List</a>";
		listDate += "<em style=\"color: #bbb;\">Not Listed</em>";
	}
	$('<td>' + listDate + '</td').appendTo($(r));
	$('<td>' + listTools + '</td').appendTo($(r));

	temp = "<a class='l but'  target=\"_blank\" href='/listing/U" + unit.id + "' ><span class=\"tt l icon-16 listing_view\" title=\"View Listing\" ></span></a>";
	if (mode >0) temp += "<a class='l but'  href='/listing/edit/u" + unit.id + "/step1'><span class=\"tt l icon-16 listing_edit\" title=\"Edit Listing\" ></span></a>";
	if (mode == 2) temp += "<a class='l but'  unit='" + unit.id + "' onclick=\"if (confirm('Are you sure you want to delete this listing?')) { deleteSingle(this); }\"><span class=\"tt l icon-16 cross\" title=\"Delete this unit\" ></span></a>";
	$('<td>' +temp+"</td></div><div class='cleaner'>&nbsp;</div>").appendTo($(r));
	
}

function showTT(inc){
	var tt = $("#tt");
	$(tt).hide();
	if (inc.title) {
		$("#ttcontent").html(inc.title);
		var pos = $(inc).offset();
		var leftpos = pos.left + ($(inc).width() / 2) - ($(tt).width() / 2) - 4;
		var toppos = pos.top;
		toppos -= ( $(tt).height() + 18 );
		$(tt).css({left: leftpos, top: toppos}).show();
	}
}
function hideTT() {
	var tt = $("#tt");
	$(tt).hide();
}

function selectEvent(inc){
	if (inc.value == null) return false;
	if (inc.value > 6) {
		$("#unit_count_div").css({display: "block"});
		$("#listing_type_floorplan").removeAttr("disabled").parent().css("color", "#222");
	} else {
		$("#unit_count_div").css({display: "none"});
		$("#floorplan_count_div").css({display: "none"});
		$("#listing_type_floorplan").attr("disabled", "true").parent().css("color", "#aaa");   
		$("#listing_type_unit").attr("checked", "checked");
		$("#floorplan_count").val("");
		$("#unit_count").val("");
	}
}

function radioEvent(inc){            
	switch(inc.name) {
		case "listing_type":
			if (inc.value == "0") {
				$("#floorplan_count_div").css({display:"none"});
				$("#floorplan_count").val("");
			} else {
				$("#floorplan_count_div").css({display:"block"});
			}
		break;
	}
}

function addSingleProperty(inc) {
	$.post(
		"/property/add/property",
		inc.serialize(),
		function(data) {
			alert(data);
		}
	);
}

function addSingleUnit(inc) {
	var href = $(inc).attr("href");
	if ($.browser.msie && $.browser.version < 8) {
		href = href.split("/");
		href = href[href.length-1];
	}
	$.post(
		"/property/add/unit",
		"id=" + href,
		function(data) {
			data = $.parseJSON(data);
			addUnitHandler(data, inc);
		}
	);
}

function addUnitHandler(data, inc) {
	if (!data) return;
	var code = 0;
	var displaymode = 0;
	var editmode = 0;
	var return_message = null;
	var param = null;
	var doc = data;
	displaymode = doc.display;
	editmode = doc.edit;
	code = parseInt(doc.code);

	var unit = new nDUnitJSON(data.unit);
	
	switch(code){
		case 1: drawUnit(unit, $(inc).parent().parent().parent().next(), editmode); break;
		default: break;
	}
}




// NEW ===========================================

function showPropertyNew(inc){
	if (!parseInt(inc.id)) return;
	hideTT();
	showLoading();
	
	$.post(
		"/property/get/p" + parseInt(inc.id),
		function(data) {
			data = $.parseJSON(data);
			drawPropertyNew(data, inc, 1);
		}
	);
}

function drawPropertyNew(data, inc, mode){
	var address = data.property.address;
	var units = data.units;
	var property = data.property.property;
		
	if(property.label != "" && property.label != null) label = property.label;
	else label = address.street_1;
	
	phead = "<b>"+label+"</b>";
	tbody = "";
	
	$("#property_info h4").html(phead);
	$("#unit_table tbody").html(tbody);
	
	var innerBody = $("#unit_table tbody");
	$.each(units, function(){
		u = new nDUnitJSON(this);
		drawUnitNew(u, innerBody, mode);
	});
	
	$("#property_container").animate({"left":"-608px"}, 200);
	hideLoading();
}

function drawUnitNew(unit, root, mode) {
	if (!root) return;
	if (!mode) mode = 0;
	var r, temp = "";
	r = $("<tr id='u"+unit.id+"'></tr>").prependTo(root);
	if (mode>0) temp += "<a style=\"color:#343434\" href='/listing/edit/u" + unit.id + "/step1'>";
	if (unit.label == "") temp += "<strong style=\"color: #d00\">[Add listing details]</strong>";
	else temp += unit.label;
	if (mode>0) temp += "</a>";
	$('<td>'+temp+'</td>').appendTo($(r));
	if (parseInt(unit.cost) <= "0") temp = "<span style=\"color: red;\">$" + unit.cost + "/m</span>"; 
	else temp = "$" + unit.cost + "/m";
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.beds == 7) temp = "Room";
	else if (unit.beds == 0) temp = "Studio";
	else temp = unit.beds;
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.baths == 0) temp = "Shared"; 
	else temp = unit.baths;
	$('<td>'+temp+'</td>').appendTo($(r));
	if (unit.halfbaths) temp = unit.halfbaths;
	else temp = 0;
	$('<td>'+temp+'</td>').appendTo($(r));
	
	////size needed//////
	if (unit.size) $("<td>"+unit.size+"</td>").appendTo($(r)); 
	else $("<td><span style='color:red'>?</span></td>").appendTo($(r));
	//$("<td style='text-align:center;'><em>Metrics coming soon!</em></td>").appendTo($(r));
	/*$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));
	$("<td><img src='/images/loader.gif' alt='loading' /></td>").appendTo($(r));*/
	var listed = /^\d{4}-\d{2}-\d{2}/;
	var listTools = "";
	var listDate = "";
	//HUH?
	var ldate = new Date(unit.listing_date_start);
	var edate = new Date(unit.listing_date_end);
	var ndate = new Date();
	if (listed.test(unit.listing_date_start) && !((unit.listing_date_start).match("00-00")) && ndate.getTime()>=ldate.getTime() && ndate.getTime()<=edate.getTime()) {
		if (mode>0) listTools = "<a class='fn delistbtn nd-btn xsm o' title=\"\" unit='" + unit.id + "'>Unlist</a>";
		listDate += "<span>Exp.: " + (unit.listing_date_end).substring(5).replace(/ 00:00:00/, "") + "</span>";
	}else {
		if (mode > 0) listTools = "<a class='fn listbtn nd-btn xsm' unit='" + unit.id + "'>List</a>";
		listDate += "<em style=\"color: #bbb;\">Not Listed</em>";
	}
	$('<td>' + listDate + '</td').appendTo($(r));
	$('<td>' + listTools + '</td').appendTo($(r));

	temp = "<a class='l but'  target=\"_blank\" href='/listing/U" + unit.id + "' ><span class=\"tt l icon-16 listing_view\" title=\"View Listing\" ></span></a>";
	if (mode >0) temp += "<a class='l but'  href='/listing/edit/u" + unit.id + "/step1'><span class=\"tt l icon-16 listing_edit\" title=\"Edit Listing\" ></span></a>";
	if (mode == 2) temp += "<a class='l but'  unit='" + unit.id + "' onclick=\"if (confirm('Are you sure you want to delete this listing?')) { deleteSingle(this); }\"><span class=\"tt l icon-16 cross\" title=\"Delete this unit\" ></span></a>";
	$('<td>' +temp+"</td></div><div class='cleaner'>&nbsp;</div>").appendTo($(r));
	
}

function hidePropertyNew(){
	$("#property_container").animate({"left":"0"}, 200);
	$("#unit_table tbody").html('<tr><td colspan="9" style="padding:20px; text-align:center;">There don\'t seem to be any units here.</td></tr>');
}

function showLoading(){
	if($("#loading_basic").length == 0){
		$loading = $("<div id='loading_basic'><div></div></div>");
		$loading.css({
			"top": ((($(window).height() - $loading.outerHeight()) / 2) + $(window).scrollTop() + "px"),
			"left": ((($(window).width() - $loading.outerWidth()) / 2) + $(window).scrollLeft() + "px")
		});
		$("body").append($loading);
	}
}

function hideLoading(){
	$("#loading_basic").empty().remove();
}
