// *********************************************************************
// Global vars
// *********************************************************************
var allListings;           // Array of all the loaded listings
var allListingsCount;

// *********************************************************************
// Property class
// *********************************************************************
function property(mlsid, price, ppsf, ppa, oper, beds, bath, sqft, acres, hoa, taxes, pcount, zone, subd, legal, description, broker, office, phone, lat, lng)
{
   this.mlsid  = ""+mlsid;
   this.price  = price.strToNum();
   this.ppsf  = ""+ ppsf;
   this.ppa  = ""+ ppa;
   this.oper  = ""+ oper;
   this.beds  = ""+ beds;
   this.bath  = ""+ bath;
   this.sqft  = ""+ sqft;
   this.acres  = ""+ acres;
   this.hoa  = hoa.strToNum();
   this.taxes  = taxes.strToNum();
   this.pcount  = pcount.strToNum();
   this.pictures = Array();
   this.zone  = ""+ zone;
   this.subd  = ""+ subd;
   this.legal  = ""+ legal;
   this.description = ""+ description;
   this.broker = ""+ broker;
   this.office = ""+ office;
   this.phone = ""+ phone;
   this.html = '<center><b>' + mlsid + '</b><br><b>' + price + '</b><br>Listing Broker: ' + broker + '<br><br></center>' + description;
   this.lat = parseFloat(lat) / 100;
   this.lng = parseFloat(lng) / 100;
   this.downpayment = 0;
   this.total_payment = 0;
   this.calculateMonthlyPayment = calculateMonthlyPayment;
   this.preloadImages = preloadImages;
}

function calculateMonthlyPayment()
{
   var dpp = document.getElementById("downpayment_percent").value;
   this.downpayment = this.price * dpp / 100;
   var loan = this.price * (1 - (dpp / 100));    // Loan amount
   var i = document.getElementById("interest_rate").value / 100 / 12;                        // Monthly interest rate
   var num_pay = document.getElementById("loan_length").value * 12;                                // Number of payments
   var mort_payment = Math.floor((loan * i) / (1 - Math.pow((1 + i), (-1 * num_pay))) * 100) / 100;

   this.total_payment = Math.floor( (mort_payment + ((this.taxes + this.hoa) / 12)) * 100) / 100;

   return this.total_payment;
}

function preloadImages()
{
   for(i = 1; i <= this.pcount; i++)
   {
      this.pictures[i] = new Image();
      this.pictures[i].src = 'http://www.grandcountyforsale.com/data/pictures.php?mlsid=' + this.mlsid + '&index=' + i; 
   }
}

// *********************************************************************
// Functions
// *********************************************************************
function load()
{
	changeView("listings");
   // Set all the values in the selection table to initial values
   resetArgs();
   // Read the url arguments and set the values from there to the selection table
   var retval = showTheArgs();

   if(retval == "showrequest")
   {
      var text = "To send us a property request, fill in the selection criteria fields on the left.  When you have narrowed down your search, click the 'Notify me when new listings like this are available' link or the 'Contact me now about these listings' link below the selection criteria fields.";
      show_working("status", text);
   }
   else if(retval == "args")
      showListings();
   else if(retval != "map")
   {
      var text = "Fill in the selection criteria fields on the left to see all of the current Grand County MLS Listings that match your criteria.";
      show_working("status", text);
   }

	if(retval == "map")
   	changeView("map");
}

function GUnload()
{
	//Empty function so IE doesn't throw error when this function does not exist.
}

function getURLArguments()
{
   var mainURL = window.location.search;
   var URLparts = mainURL.split('?');

   var pair = URLparts[1];

   return pair;
}

function resetArgs()
{
   document.getElementById("scope").selectedIndex = 0;
   document.getElementById("type").selectedIndex = 1;
   document.getElementById("area").selectedIndex = 0;
   document.getElementById("oper").selectedIndex = 0;
   document.getElementById("min_price").value = 0;
   document.getElementById("max_price").value = 99999999;
   document.getElementById("min_acres").value = 0;
   document.getElementById("max_acres").value = 99999;
   document.getElementById("min_beds").value = 0;
   document.getElementById("max_beds").value = 99;
   document.getElementById("min_bath").value = 0;
   document.getElementById("max_bath").value = 99;
   document.getElementById("min_sqft").value = 0;
   document.getElementById("max_sqft").value = 99999;
   document.getElementById("max_list").value = 25;
   document.getElementById("mlsid").value = "";
}

//
// Parse the arguments passed in the URL, and set the values passed in selection table
//
function showTheArgs()
{
   var theArgs = getURLArguments();
   var i, pair;
   var retval = "suppress";

   if(theArgs)
   {
      var a = theArgs.split('&');
      for(i in a)
      {
         pair = a[i].split('=');
         switch(pair[0])
         {
            case 'scope':
               setSelect("scope", pair[1]);
               retval = "args";
               break;
            case 'type':
               setSelect("type", pair[1]);
               retval = "args";
               break;
            case 'area':
               setSelect("area", pair[1]);
               retval = "args";
               break;
            case 'oper':
               setSelect("oper", pair[1]);
               retval = "args";
               break;
            case 'min_price':
               document.getElementById("min_price").value = pair[1];
               retval = "args";
               break;
            case 'max_price':
               document.getElementById("max_price").value = pair[1];
               retval = "args";
               break;
            case 'min_acres':
               document.getElementById("min_acres").value = pair[1];
               retval = "args";
               break;
            case 'max_acres':
               document.getElementById("max_acres").value = pair[1];
               retval = "args";
               break;
            case 'min_beds':
               document.getElementById("min_beds").value = pair[1];
               retval = "args";
               break;
            case 'max_beds':
               document.getElementById("max_beds").value = pair[1];
               retval = "args";
               break;
            case 'min_bath':
               document.getElementById("min_bath").value = pair[1];
               retval = "args";
               break;
            case 'max_bath':
               document.getElementById("max_bath").value = pair[1];
               retval = "args";
               break;
            case 'min_sqft':
               document.getElementById("min_sqft").value = pair[1];
               retval = "args";
               break;
            case 'max_sqft':
               document.getElementById("max_sqft").value = pair[1];
               retval = "args";
               break;
            case 'max_list':
               document.getElementById("max_list").value = pair[1];
               retval = "args";
               break;
            case 'mlsid':
      		   document.getElementById("mlsid").value = pair[1];
               retval = "args";
               break;
            case 'mlsid':
      		   document.getElementById("mlsid").value = pair[1];
               retval = "args";
               break;
            case 'showrequest':
               if(pair[1] == 'yes')
                  retval = "showrequest";
               break;
            case 'maps':
               if(pair[1] == 'yes')
                  retval = "map";
               break;
            default:
               break;
         }
      }
   }

   return retval;
}

// Set the item selected in a select box
function setSelect(div, val)
{
   var x = document.getElementById(div);
   var i = 0;

   while(i < x.length)
   {
      if(x.options[i].value == val)
         x.selectedIndex = i;
      i++;
   }
}

function showListButt()
{
		document.getElementById("butt_show").style.display = "inline";
}

function showMortgage()
{
   var x = document.getElementById("mortgage").style;

   x.display = (x.display == "inline") ? "none" : "inline";
}

function toggleHeader(hide)
{
	if(document.getElementById("butt_header").innerHTML == "Hide header")
	{
		document.getElementById("butt_header").innerHTML = "Show header";
		document.getElementById("header").style.display = "none";
	}
	else
	{
		document.getElementById("butt_header").innerHTML = "Hide header";
		document.getElementById("header").style.display = "block";
	}

	window.onresize();
}

function changeView()
{
	var view = "";
	var a = changeView.arguments;

	if(a.length > 0)
		view = a[0];

	if( ( (document.getElementById("butt_view").innerHTML == "Map view") && (view == "") ) || (view == "map") )
	{
		document.getElementById("butt_view").innerHTML = "Listing view";
		document.getElementById("nav_map").style.display = "block";
		document.getElementById("nav_list").style.display = "none";

		document.getElementById("map").style.display = "block";
		document.getElementById("listings").style.display = "none";
      // Force window to draw correct size

      window.onresize();

      load_map();      
      // ===== determine the zoom level from the bounds =====
      map.setZoom(map.getBoundsZoomLevel(bounds));
      // ===== determine the centre from the bounds ======
      map.setCenter(bounds.getCenter());
	}
	else
	{
		document.getElementById("butt_view").innerHTML = "Map view";
		document.getElementById("nav_map").style.display = "none";
		document.getElementById("nav_list").style.display = "block";

		document.getElementById("map").style.display = "none";
		document.getElementById("listings").style.display = "block";
	}
}

function getPicHTML(mlsid, current, pcount, height, div)
{
   var text = "<p>There are no pictures available for this property</p>";

   height = (height == 0) ? 150 : height;

   if(pcount > 0)
      text = "<img id=\""+mlsid+"img\" height=\""+height+"px\"src=\"http://www.grandcountyforsale.com/data/pictures.php?mlsid=" + mlsid + "&index=" + current + "\" /><p><input type=\"button\" onclick=\"changePic('" + mlsid + "', '" + pcount + "', '" + current + "','prev')\" value=\"&lt; Prev\"> (" + current + " of " + pcount + ") <input type=\"button\" onclick=\"changePic('" + mlsid + "', '" + pcount + "', '" + current + "','next')\" value=\"Next &gt;\"><br /><input type=\"button\" onclick=\"changeImgSize('+', '"+mlsid+"')\" value=\"+20%\"><input type=\"button\" onclick=\"changeImgSize('-', '"+mlsid+"')\" value=\"-20%\"></p>";

	if(div)
		text = '<div id="' + mlsid + 'pic" class="pic">' + text + '</div>';

	return text;
}

function changeImgSize(plus, mlsid)
{
	var obj = document.getElementById(mlsid+"img");

	if(plus == "+")
	{
		obj.height = obj.height * 1.2;
		obj.width  = obj.width  * 1.2;
	}
	else
	{
		obj.height = obj.height * .8;
		obj.width  = obj.width  * .8;
	}

//	alert("Set " + mlsid+"pictd to width "+Math.max(obj.width, 300));
//	document.getElementById(mlsid+"pictd").width = Math.max(obj.width, 300) + "px";
	document.getElementById("pictd").width = Math.max(obj.width, 300) + "px";
}

function changePic(mlsid, pcount, current, dir)
{
	var current_height = document.getElementById(mlsid + "img").height;

	if(dir == "next")
		current++;
	else
		current--;

	if(current == 0)
		current = pcount;
	else if(current > pcount)
		current = 1;
	
	var obj = document.getElementById(mlsid + "pic");
	obj.innerHTML = getPicHTML(mlsid, current, pcount, current_height, 0);
}

function changeControls()
{
	var obj = document.getElementById("type");
	var type = obj.options[obj.selectedIndex].value;

	if( (type == "vacant") || (type == "ranch") || (type == "commercial") )
	{
		document.getElementById("acres_div").style.display = "block";
		document.getElementById("beds_div").style.display = "none";
		document.getElementById("bath_div").style.display = "none";
		document.getElementById("sqft_div").style.display = "none";
		document.getElementById("oper_div").style.display = "none";
	}
	else if(type == "residential")
	{
		document.getElementById("acres_div").style.display = "block";
		document.getElementById("beds_div").style.display = "block";
		document.getElementById("bath_div").style.display = "block";
		document.getElementById("sqft_div").style.display = "block";
		document.getElementById("oper_div").style.display = "block";
	}
	else if(type == "condo")
	{
		document.getElementById("acres_div").style.display = "none";
		document.getElementById("beds_div").style.display = "block";
		document.getElementById("bath_div").style.display = "block";
		document.getElementById("sqft_div").style.display = "block";
		document.getElementById("oper_div").style.display = "block";
	}
}

function doChangeType()
{
	changeControls();
//	showListings();
}

//
// Query all the elements to collect the arguments for sending somewhere else
//
function getArgs()
{
   var args = "";
	var mlsid = document.getElementById("mlsid").value;
	var obj = document.getElementById("type");
	var type = obj.options[obj.selectedIndex].value;

	if(!mlsid)
	{
		obj = document.getElementById("scope");
		var scope = obj.options[obj.selectedIndex].value;
		
		obj = document.getElementById("area");
		var area  = obj.options[obj.selectedIndex].value;
	
		obj = document.getElementById("oper");
		var oper  = obj.options[obj.selectedIndex].value;
	
		var min_price = document.getElementById("min_price").value;
		var max_price = document.getElementById("max_price").value;
		var min_acres = document.getElementById("min_acres").value;
		var max_acres = document.getElementById("max_acres").value;
		var min_beds = document.getElementById("min_beds").value;
		var max_beds = document.getElementById("max_beds").value;
		var min_bath = document.getElementById("min_bath").value;
		var max_bath = document.getElementById("max_bath").value;
		var min_sqft = document.getElementById("min_sqft").value;
		var max_sqft = document.getElementById("max_sqft").value;
		var max_list = document.getElementById("max_list").value;
	
		args = "scope=" + scope + "&type=" + type + "&oper=" + oper + "&area=" + area + "&min_price=" + min_price + "&max_price=" + max_price + "&min_acres=" + min_acres + "&max_acres=" + max_acres + "&min_beds=" + min_beds + "&max_beds=" + max_beds + "&min_bath=" + min_bath + "&max_bath=" + max_bath + "&min_sqft=" + min_sqft + "&max_sqft=" + max_sqft + "&max_list=" + max_list;
	}
	else
		args = "type=" + type + "&mlsid=" + mlsid;

   //show_working("status", args);
   //alert(args);
   return args;
}

function showListings()
{
   var args = getArgs();

   // Get rid of the update listings button
   document.getElementById("butt_show").style.display = "none";
   document.getElementById("listings").style.opacity = ".3";

   asProcess("data/listings.php", args, "Searching for Your Listings ...", handleListingXML);
}

function showAutoEmail(type)
{
   var args = getArgs();

   if(type)
      args = args + "&aetype=" + type;

   window.open("/email.php?"+args, "_self");
}

function handleListingXML()
{
	if(xmlHttp.readyState == 4)
	{
      // Reset the listing global variables
      allListings = new Array();
      allListingsCount = 0;

		var xmlDoc = xmlHttp.responseXML;
 //     document.write(xmlHttp.responseText);

      // The result tag holds a summary of the listings returned (if any)
		var r = xmlDoc.getElementsByTagName("result");
		var count    = r[0].getAttribute("count");
		var returned = r[0].getAttribute("returned");
		var type     = r[0].getAttribute("type");
		var max_list = r[0].getAttribute("max_list");

      // ========= Now process the polylines ===========
		var result = "";
      var listings = xmlDoc.getElementsByTagName("listing");
   
      // read each line
      for (var a = 0; a < listings.length; a++)
      {
         // read all the property attributes
         p = new property(listings[a].getAttribute("mlsid"),      listings[a].getAttribute("price"), listings[a].getAttribute("ppsf"),
                          listings[a].getAttribute("ppa"),        listings[a].getAttribute("oper"),  listings[a].getAttribute("beds"),
                          listings[a].getAttribute("bath"),       listings[a].getAttribute("sqft"),  listings[a].getAttribute("acres"),
                          listings[a].getAttribute("hoa"),        listings[a].getAttribute("taxes"), listings[a].getAttribute("pcount"),
                          listings[a].getAttribute("zone"),       listings[a].getAttribute("sub"),   listings[a].getAttribute("legal"),
                          listings[a].getAttribute("description"),listings[a].getAttribute("broker"),listings[a].getAttribute("office"),
                          listings[a].getAttribute("phone"),      listings[a].getAttribute("lat"),   listings[a].getAttribute("lng"));
         p.preloadImages();
         allListings[allListingsCount] = p;
         allListingsCount++;

			var pic_div = getPicHTML(p.mlsid, 1, p.pcount, 192, 1);

			result += '<div class="listing">' + pic_div;
         result += '<div id="' + p.mlsid + 'data"><p>' + p.description + '</p><div class="listdata">';
         result += 'MLS ID: <span class="data">' + p.mlsid + '</span><br />';
         result += 'Price: <span class="data">' + p.price.numToDollar() + ' ' + p.oper + '</span><br />';
         result += 'Monthly cost of ownership: <span class="data">' + p.calculateMonthlyPayment().numToDollar() + '</span>, ';
         result += 'Downpayment: <span class="data">' + p.downpayment.numToDollar() + '</span><br />';
         if((type == "residential") || (type == "condo"))
         {
            result += 'Price per sq. ft.: <span class="data">' + p.ppsf + '</span><br />';
            result += 'Beds: <span class="data">' + p.beds + '</span>, Baths: <span class="data">' + p.bath + '</span><br />';
            result += 'Finished sqft: <span class="data">' + p.sqft + '</span><br />';
         }
         if(type == "vacant")
            result += 'Price per acre.: <span class="data">' + p.ppa + '</span><br />';
         result += 'Acres: <span class="data">' + p.acres + '</span><br />';
         result += 'Monthly HOA: <span class="data">' + p.hoa.numToDollar() + '</span><br />';
         result += 'Taxes: <span class="data">' + p.taxes.numToDollar() + '</span><br />';
         result += 'Zoning: <span class="data">' + p.zone + '</span><br />';
         result += 'Subdivision: <span class="data">' + p.subd + '</span><br />';
         result += 'Legal Descr.: <span class="data">' + p.legal + '</span><br />';
         result += 'Offered by: <span class="data">' + p.broker + ' of ' + p.office + '.</span>';
         result += '</div><br /></div></div>';
		}

      // All the listings have been read from the XML, now display them
		var x = document.getElementById("listings");
		x.style.display = "block"; 		
      x.style.opacity = "1";
		if(returned < count)
			x.innerHTML = "<br />Change the selection crteria on the left to return fewer listings or increase the number of listings displayed";
      else
   	   x.innerHTML = result;

      show_working("status", returned + " of " + count + " listings displayed");
   }
	else
		show_working("status", "Searching for your listings...");
}
