﻿$(document).ready(function()
	{
		// add the custom parser for sorting the sq.ft. values
		jQuery.tablesorter.addParser({
		  id: "fancyNumber",
		  is: function(s) {
		    return /^[0-9]?[0-9,\.]*$/.test(s);
		  },
		  format: function(s) {
		    return jQuery.tablesorter.formatFloat( s.replace(/,/g,'') );
		  },
		  type: "numeric"
		});

		// add the custom parser for sorting the address values
		jQuery.tablesorter.addParser({
		  id: "addressSort",
		  is: function(s) {
		    return false;
		  },
		  format: function(s) {

		  	var sortString = s;
		  	var street  = "";
			var unit    = "";
			var newListing = "z"; // default to no new listing image = these are arbitrary chars to force a high/low sort
			var hasUnit = false;
			var streetStart = 0;
			var numberStart = s.indexOf("#");
			var flagStart   = s.indexOf("<IMG");
			
			// remove the number sign and dash to make featured and mls addresses consistent
			if (numberStart >= 0)
			{
				hasUnit = true;
				s = jQuery.trim(s.substring(numberStart+1));
			}

			s.replace(" - ", " ");

			// look for the new flag image
			if (flagStart >= 0)
			{
				newListing = "a";  // high sort value
				s = s.substring(0,flagStart);  // remove the <IMG> tag from the address
			}

			if (hasUnit)
			{
				streetStart = s.indexOf(" "); // find the space between unit and street number
				unit = s.substring(0,streetStart);  // substring takes up to but not including streetStart position
				unit = Array(8 - unit.length).join("0") + unit; // left pad the unit number to 8 characters so the alpha sort will appear numeric
			}

			street = s.substring(streetStart);

			sortString = newListing + " " + street + " " + unit;
						 
			return sortString;
		  },
		  type: "text"
		});

		jQuery.tablesorter.addParser({
		  id: "imageFlag",
		  is: function(s) {
		  	return false;
		  },
		  format: function(s) {
			s = '' + s; //Make sure it's a string 
			//var hit = s.match(/img/); 
			if (s.length >= 1) { 
				return "a"; 
			} 
			else { 
				return "z"; 
			} 
		  },
		  type: "text"
		});


		// initialize client-side table sorting
		initializeListingSort();
		initializeBuildingSort();

		// bind the javascript event handlers
		bindAddDeleteFunctions();
		bindDisplayFunctions();

	}
);

function initializeListingSort()
{
	// favorite listings tables
	$("#favoriteListingsContent #mlslisting").tablesorter({sortList: [[5,0]], sortMultiSortKey: 'altKey' , sortInitialOrder: 'asc', headers: {0: { sorter: 'addressSort' }, 4: { sorter: 'fancyNumber' }, 7: { sorter: false}, 8: { sorter: false} }});
	$("#favoriteListingsContent #featurelisting").tablesorter({sortList: [[5,0]], sortMultiSortKey: 'altKey' , sortInitialOrder: 'asc', headers: {0: { sorter: 'addressSort' }, 4: { sorter: 'fancyNumber' }, 7: { sorter: false}, 8: { sorter: false} }});
}

function initializeBuildingSort()
{
	// favorite buildings subtables (listings within each building)	
	$("table[id^='subtable_']").each(function(i){
			$(this).tablesorter({sortMultiSortKey: 'altKey' , sortInitialOrder: 'asc', headers: { 0: { sorter: false}, 1: { sorter: 'addressSort' }, 4: { sorter: 'fancyNumber' }, 7: { sorter: false} }});
		});
}


function bindDisplayFunctions()
{
	$("#buildinginfolink").bind("click", displayBuildingsCart);
	$("#listinginfolink").bind("click", displayListingsCart);
}

function bindAddDeleteFunctions()
{
	$(".addfavorite").bind("click", addFavoriteListing);
	$(".deletefavorite").bind("click", deleteFavoriteItem);
}


function addFavoriteListing()
{
	var urlstring = $(this).attr("href").substr(($(this).attr("href").indexOf("?") + 1));
	//var urlstring = "favorites_update.php?" + urlstring ;

	$.ajax({
	    url: "favorites_update.php?" + urlstring ,
	    type: 'GET',
	    dataType: 'xml',
	    //timeout: 1000,
	    error: function(){ alert('Error updating favorite'); },
	    success: refreshFavorites
	});

	$(this).parent().html("<img src=\"shared/icons/checkmark.gif\" alt=\"Favorite\">");

	// return false to prevent the default action of the anchor tag	
	return false;

}


function deleteFavoriteItem()
{

	var urlstring = $(this).attr("href").substr(($(this).attr("href").indexOf("?") + 1));
	//var urlstring = "favorites_update.php?" + urlstring ;
	//alert("url: " + urlstring );


	if (confirm("Do you want to delete this Favorite?"))
	{		
		$.ajax({
		    url: "favorites_update.php?" + urlstring ,
		    type: 'GET',
		    dataType: 'xml',
		    //timeout: 1000,
		    error: function(){
		        alert('Error deleting favorite');
		    },
		    success: refreshFavorites
		});

		return false;

	}

	// return false to prevent the default action of the anchor tag	
	return false;
		
}


function updateFavoriteCounts(xml)
{
	var totalListings	= 0;
	var totalBuildings	= 0;
	var totalFavorites	= 0;

	if (xml)
	{
		totalListings  = parseInt($(xml).find('listings > count').text(), 10);
		totalBuildings = parseInt($(xml).find('buildings > count').text(), 10);
		totalFavorites = totalListings + totalBuildings;
		totalFavoritesLabel = "My Favorites";
		if (totalFavorites > 0) totalFavoritesLabel += " (" + totalFavorites + ")";
	
		$("#buildinginfolink").html("Buildings (" + totalBuildings + ")");
		$("#listinginfolink").html("Listings (" + totalListings + ")");
		$("#topNavFavorites").html(totalFavoritesLabel);
	}

}


function refreshFavorites(xml)
{
	//alert("refreshFavorites");
	updateFavoriteCounts(xml);
	
	if ($("listings > html", xml).length > 0)
	{
		displayFavoriteListings($("listings > html", xml).text());
	}

	if ($("buildings > html", xml).length > 0)
	{
		displayFavoriteBuildings($("buildings > html", xml).text());
	}
	
}


function displayFavoriteListings(html_table)
{
	if (html_table != "")
	{
		$("#favoriteListingsContent").html(html_table);
		bindAddDeleteFunctions();
		initializeListingSort();
	}
	else
	{
		$("#favoriteListingsContent").html("<p>There are no listings in your favourites.</p>");
	}
}


function displayFavoriteBuildings(html_table)
{
	//alert("displayFavoriteBuildings");

	if (html_table != "")
	{
		$("#favoriteBuildingsContent").html(html_table);
		bindAddDeleteFunctions();
		initializeBuildingSort();
	}
	else
	{
		$("#favoriteBuildingsContent").html("<p>There are no buildings in your favourites.</p>");
	}
}



function childrenOf(node)
{
	return $("table.treeTable tbody tr." + options.childPrefix + node[0].id);
};


function toggleTable(building_id)
{
	if ($("#"+building_id).hasClass("expand"))
	{
		$("#"+building_id).removeClass("expand").addClass("collapse");
		$("#child_of_"+building_id).toggle();
	}
	else if ($("#"+building_id).hasClass("collapse"))
	{
		$("#"+building_id).removeClass("collapse").addClass("expand");
		$("#child_of_"+building_id).toggle();
	}
}

function displayListingsCart()
{
	$("#favoritebuildings").hide();
	$("#buildinginfolink").removeClass("current");
	$("#listinginfolink").addClass("current");

	$("#favoritelistings").show();

	return false;  // return false to prevent the default action
}

function displayBuildingsCart()
{
	$("#favoritelistings").hide();
	$("#favoritebuildings").show();
	$("#buildinginfolink").addClass("current");
	$("#listinginfolink").removeClass("current");
	return false; // return false to prevent the default action
}


