//******************************************************************
//* Copyright 2/16/2008, Anthony Burdin, All rights reserved.
//* No part of this content or the data or information included therein may be reproduced,
//* republished or redistributed without the prior written consent of Anthony Burdin.
//* 
//* Stylesheet: Login
//* 
//* Description:
//*   Javascript for Login screen
//*
//*********************************************************************
var geocoder;
var rentalAddressArray=[];
var clRentalArray=[];

var defaultValAddress = "Search address (ie. 2 Oak St, Main, PA 19070)";
var defaultValRent = "$ Rent";

// Array of possible initial locations 
var startLocArray = new Array();
startLocArray[0] = {"latitude": 42.339493,  "longitude": -71.079011}; // BOS
startLocArray[1] = {"latitude": 40.761545,  "longitude": -73.975038}; // NYC
startLocArray[2] = {"latitude": 41.920333,  "longitude": -87.631653}; // CHI
startLocArray[3] = {"latitude": 37.782744,  "longitude": -122.406496}; // SFO
startLocArray[4] = {"latitude": 34.057191,  "longitude": -118.400332}; // LA
startLocArray[5] = {"latitude": 33.83942,  "longitude": -118.400332}; // ATL

//*************************
// Error Handling
//
window.onerror = function(msg, err_url, line) { 
  alert("An error occured: " + msg + "\nLine: " + line); 
}                

//*************************
// OnLoad event handler
//
function onLoad() 
{  
  $(document).ready(function() {

    // Init fancybox
    shared_onLoad();
    
    // Show spinning fancybox
    $.fancybox.showActivity();                
                                
    $.validator.addMethod("defaultInvalid", validator_defaultInvalid, "Please enter property address.");    
    
    // Setup form validator for sbSrch
    var validator = $("#sbSrch").validate({
      rules: {
        displayAddress: {
          required: true,
          defaultInvalid: defaultValAddress
        },
        displayRent: {
          required: true,
          maxlength: 5,
          digits: true,   
          range: [300, 10000]
        },
        displayBedroom: {
          required: true,
          min: 0
        }      
		  },
		  messages: {
			  displayAddress: "",
			  displayRent: "",
			  displayBedroom: ""
			},
		  invalidHandler: function(e, validator) {
			   var errors = validator.numberOfInvalids();
			   if (errors) {
				    var message = errors == 1 ? "You missed 1 field" : "You missed " + errors + " fields";
            $("div.error span").html(message);
				    $("div.error").show();
			   } else {
				    $("div.error").hide();
			   }
		  },
		  submitHandler: function() {        
        if (! $("#sbSrch").valid()) {
          return false;
        } else {
          $("div.error").hide();
        }
        
        // Show spinning fancybox  
        $.fancybox.showActivity();
        
        // Use Google geocoder that decodes address into Latitude and Longitude  
        var geocoder = new google.maps.Geocoder();                  
      	if (geocoder) {		  
       		geocoder.geocode({ 'address': $("#displayAddress").val() }, rentalAddressCallback);
      	}  
      	return false;
		  }
		});    
    
    // Choose one starting location at random 
    var startLoc = startLocArray[Math.floor(Math.random()*6)];
    firstRentalLatitude = startLoc["latitude"]+Math.floor(Math.random()*0.1);
    firstRentalLongitude = startLoc["longitude"]+Math.floor(Math.random()*0.1);
    
    // Use geolocaiton service to get user Lat/Long and query Savvy database for nearby rentals
    // Cached location is OK forever but don't take longer than a second to get location
    if (navigator.geolocation) {  
      navigator.geolocation.getCurrentPosition(foundMyLocation, locationNotFound, {maximumAge:Infinity, timeout:1000});
    }   
    else {
      var addressObj = new Object();
      addressObj.latitude = firstRentalLatitude;
      addressObj.longitude = firstRentalLongitude;
      getAJAXRentals(addressObj, null, null, null); 
    }         
      
    // Bind Keydown event on 'searchEvt' class to search   
    $(".searchEvt").bind("keydown", function(event) {
      // track enter key
      var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
      if (keycode == 13) { // keycode for enter key
        $("#sbSrch").submit();
        return false;
      }
    });           
  
		//* create jQuery Dialog widget for Google Street View window
    var dialogOptions = {
      "title":"Street View", 
      "width":200, 
      "height":200, 
      "open":true, 
      "position":[390, 65] 
      //"position":['right', 'bottom']
      //position: {my:'top', at:'top', of:'#googleMap'}
    };
    //dialog-extend options
    var dialogExtendOptions = {
      "maximize":true,
      "minimize":true
    };
    $("#googlePano").dialog(dialogOptions).dialogExtend(dialogExtendOptions);  
    $("#googlePano").bind("dialogresizestop", function(event, ui) { 
      google.maps.event.trigger(googlePano, "resize"); 
    });	
           
    // Create vertical splitter between Search pane and Google Map pane
  	$("#MySplitter").splitter({
  		type: "v",
  		outline: true,
  		sizeLeft: 370, 
  		minLeft: 100, 
      minRight: 100,
      resizeToWidth: true
  	});	     
  	
  	// Setup example value event handlers for search
    $("#displayAddress").focus(function(eventObject)       { evtOnFocus(eventObject, defaultValAddress); });  
    $("#displayAddress").blur(function(eventObject)        { evtOnBlur(eventObject, defaultValAddress); });
    $("#displayAddress").blur();
    $("#displayApt").focus(function(eventObject)       { evtOnFocus(eventObject, "Apt#"); });  
    $("#displayApt").blur(function(eventObject)        { evtOnBlur(eventObject, "Apt#"); });
    $("#displayApt").blur();
    $("#displayRent").focus(function(eventObject)       { evtOnFocus(eventObject, defaultValRent); });  
    $("#displayRent").blur(function(eventObject)        { evtOnBlur(eventObject, defaultValRent); });
    $("#displayRent").blur();  
    $("#displayBedroom").change(function(eventObject)     { evtOnChange(eventObject, -1); });
    $("#displayBedroom").change();    
    
    // select all desired input fields and attach tooltips to them
    $(".srchTip").qtip({
       content: "Please enter the address of the rental, number of bedrooms, and monthly rent",
       position: {
          my: "top left",  // Position my top left...
          at: "bottom left", // at the bottom left of...
          target: $("#displayApt") // this element
       }
    });
    
  });          
}

//*************************
// foundMyLocation: Make AJAX search call
//
function foundMyLocation(position)
{
  firstRentalLatitude = position.coords.latitude;
  firstRentalLongitude = position.coords.longitude; 
  var addressObj = new Object();
  addressObj.latitude = firstRentalLatitude;
  addressObj.longitude = firstRentalLongitude;  
  getAJAXRentals(addressObj, null, null, null); 
}

//*************************
// locationNotFound: Fallback to default location
//
function locationNotFound(error)
{
  switch(error.code) {
  case error.TIMEOUT:
  case error.POSITION_UNAVAILABLE:
  case error.PERMISSION_DENIED:
  default:    
    var addressObj = new Object();
    addressObj.latitude = firstRentalLatitude;
    addressObj.longitude = firstRentalLongitude; 
    getAJAXRentals(addressObj, null, null, null);         
  }
}

//******************************
//* rentalAddressCallback
//*  
//* Use this URL to test: http://maps.google.com/maps/geo?q=245%20E%2058th%20St,%20New%20York,%20NY%2010022&output=json&oe=utf8&sensor=true&key=your_api_key
//*
function rentalAddressCallback(results, status) 
{
  $.fancybox.hideActivity();
  
  var addressObj = new Object();
  addressObj.addressType = "";
  addressObj.streetNumber = "";
  addressObj.streetName = "";
  addressObj.city = "";
  addressObj.state = "";
  addressObj.zip = "";
  addressObj.latitude = "";
  addressObj.longitude = "";   
  var result = extractGeocoderResponse(results, status, addressObj);
  if (result == false) {
 		alert("The address you entered is invalid.  Please re-enter the address.");
  } 
  else if (addressObj.addressType != "street_address") {
    alert("Please enter a house or a building street address.");
  }
	else {
    var rent = $("#displayRent").val();
    var apt = $("#displayApt").val();
    var bedroom = $("#displayBedroom").val();
    // Make AJAX search call
    getAJAXRentals(addressObj, rent, apt, bedroom);  
  }
}

//******************************
//* getAJAXRentals
//*    
//* Retrieves rental records from SavvyRent database and from external source(s)   
function getAJAXRentals(addressObj, rent, apt, bedroom)
{   
  // Reset the map boundry
  resetGoogleMap();
  
  // Get rentals from SavvyRent database  
  $.post(self.location.href,
  //$.post("http://ton2518.byethost16.com/testSavvyAjax.php",
    { 
      SCREEN_ACTION:  "ACTION_SEARCH",
      SCREEN_ID:      "cScrLogin",
      number:         addressObj.streetNumber, 
      street:         addressObj.streetName,
      city:           addressObj.city,
      state:          addressObj.state,
      zip:            addressObj.zip,
      latitude:       addressObj.latitude,
      longitude:      addressObj.longitude,
      rent:           rent,
      apt:            apt,
      bedroom:        bedroom     
    }, 
    processAjaxSavvyRentals, 
    "html"
  ); 

  bedroom = (bedroom==null ? "" : bedroom);
  //* Get CL rental records withing close distance of the location
  //var reqURL = "http://www.rentrent.org/RENT/Ads.aspx?callback=?"; // 
  //reqURL  = reqURL + "&xmin=" + (addressObj.longitude-0.02) + "&ymin=" + (addressObj.latitude-0.02) + "&xmax=" + (addressObj.longitude-(-0.02)) + "&ymax=" + (addressObj.latitude-(-0.02));
  //reqURL  = reqURL + "&bd=" + (bedroom==null ? "" : bedroom) + "&ba=&pets=-1&type=2&throwErrorIfOverLimit=false";
  //$.getJSON(reqURL, processExternalRentals);
  //alert("Address=" + addressObj.longitude + ", Latitude=" + addressObj.latitude + ",Bedroom=" + (bedroom==null ? "" : bedroom)); 
  
  $.ajax({
    type: "GET",
    url: "http://www.rentrent.org/RENT/Ads.aspx?callback=?",
    contentType: "application/json; charset=utf-8",
    data: { 
      "xmin": (addressObj.longitude-0.02),
      "ymin": (addressObj.latitude-0.02), 
      "xmax": (addressObj.longitude-(-0.02)),
      "ymax": (addressObj.latitude-(-0.02)),
      "bd":   bedroom,
      "ba":   "",
      "pets": -1,
      "type": 2,
      "throwErrorIfOverLimit": false
    },
    dataType: "json",
    success: processExternalRentals,
    error: function (xhr, ajaxOptions, thrownError){
      //alert(xhr.status);
      //alert(xhr.statusText);
      //alert(thrownError);
      // Clear out results table for CL
      $("#tableCLResults").find("tr:gt(0)").remove();
    }  
  });           
}

//******************************
//* processAjaxSavvyRentals
//*  
//* Callback function the processes AJAX search results
//*
function processAjaxSavvyRentals(response, textStatus, jqXHR) {
  $.fancybox.hideActivity();

  // Clear all markers and Reset rental array
  for (var key in rentalAddressArray) {  							  						
    var marker = rentalAddressArray[key].marker;	
    marker.setMap(null);
  }  
  // Clear rental array
  rentalAddressArray = [];
  // Set the response HTML into visible DIV
  $("#rentalSearchResults").html(response);
  // Recurse through HTML response and execute all JavaScript snippets
  //recurseEvalJavaScript(response, 0);
  // Load map markers
  sharedLoadGoogleMap(rentalAddressArray, firstRentalID, false);    
  
  // Send event to Google analytics to mark new rental creation
  // or an edit of an existing rental               
  //var pageTracker = _gat._getTracker("UA-3802537-1");
  //pageTracker._initData();              
  //pageTracker._trackPageview("CScrLogin-NewRental-Save");  
}

//*******************************
//* processExternalRentals
//*    
function processExternalRentals(jsonObj) 
{      
  $("#tableCLResults").find("tr:gt(0)").remove();
  
  // Clear all markers and reset rental array
  for (var key in clRentalArray) {  							  						
    var marker = clRentalArray[key].marker;	
    marker.setMap(null);
  }
  clRentalArray = [];
         
  // Create an array to hold statistics by bedroom size for each apt's price, min, max and total count
  var avgRentArray = new Array(6);
  for (var bed = 0; bed <= 5; bed++) {
    avgRentArray[bed] = {"count":0, "sum":0, "avg":0, "min":999999, "max":0};
  }  
  
  var clIndex = 1;      
  for (i in jsonObj.Data) { 
    var jsonRental = jsonObj.Data[i];
    var rentalPrice = parseInt(jsonRental.AdPrice);
    var rentalBedroom = jsonRental.AdBedroom;
    if (isNaN(rentalBedroom)) {
      rentalBedroom = 1;
    } 
    else {
      rentalBedroom = Math.round(rentalBedroom);
      rentalBedroom = Math.min(5, rentalBedroom);    
    }
    
    if (rentalPrice > 100 && rentalPrice < 10000) {
      // Compile statistics around rental average/min/max prices
      var avgRent = avgRentArray[rentalBedroom];
      //if (avgRent == null) {
      //  alert("Got NULL, Bed=" + rentalBedroom);
      //} else {            
        //alert("Count: " + avgRent["count"] + ", CL Bed:" + rentalBedroom);
        avgRent["count"]++;
        avgRent["sum"]+=rentalPrice;
        avgRent["min"]=Math.min(avgRent["min"], rentalPrice);
        avgRent["max"]=Math.max(avgRent["max"], rentalPrice);
      //}
      
      // First 15 rentals are displayed in the table
      if (clIndex <= 15) {
        // Build a dynamic table row HTML    
        var adAddress = jsonRental.AdAddress;
        if (adAddress.length == 0) {
          adAddress = jsonRental.AdCity;
        } 
        var dynHTML = "";     
        dynHTML = dynHTML + "<tr class='tableRow' onclick='viewRental(" + clIndex + ", clRentalArray);return false;'>";
        dynHTML = dynHTML + "<td style='width:100%'>" + adAddress + "</td>";
        dynHTML = dynHTML + "<td style='text-align:center'>$" + rentalPrice + "</td>";
        dynHTML = dynHTML + "<td style='text-align:center'>" + (rentalBedroom == 0 ? "Std." : rentalBedroom) + "";      
        dynHTML = dynHTML + "<div id='clBubble" + clIndex + "' name='clBubble" + clIndex + "' style='display:none'>"; 
        dynHTML = dynHTML + jsonRental.AdAddress + "<br/>" + jsonRental.AdCity;
        dynHTML = dynHTML + "<br/>" + rentalBedroom + " bedroom, $" + rentalPrice + "<br/>";
        dynHTML = dynHTML + "<a href='" + jsonRental.AdUrl + "' target='_blank'>" + jsonRental.AdUrl.substr(0, 32) + " ...</a>";
        dynHTML = dynHTML + "</td></div></tr>"; 
        
        // Insert row HTML after table header 
        $("#headerCLSearchResults").after(dynHTML);
        
        // Compile an array of map marker bubbles      
        var clRental = new Array(); 			
      	clRental["latitude"] = jsonRental.Y;
      	clRental["longitude"] = jsonRental.X;
      	clRental["descriptDiv"] = "clBubble" + clIndex;
      	clRentalArray[clIndex] = clRental;
        
      	clIndex++;    	      
      }             
    } 
  }  
  
  // Load results into Google map and create a chart
  if (clIndex > 0) {
    // Load rentals onto map
    sharedLoadGoogleMap(clRentalArray, 0, true);
  
    ///* Calculate average rents and product a chart
    for (var bed = 0; bed <= 5; bed++) {
      avgRentArray[bed]["avg"] = (avgRentArray[bed]["count"]==0)?0:Math.round(avgRentArray[bed]["sum"]/avgRentArray[bed]["count"]);
    }    
    drawChart(avgRentArray, "Available For Rent Average Prices", "clChart");
    
    $.fancybox.hideActivity();
    //* Post CL JSON to SavvyRent for post processing
    $.post("ajax_login_CL_JSON.php", { json: JSON.stringify(jsonObj.Data) });
  }    
}        

//**************************
// drawChart
// 
// If more than one apartment size found in the rental array, show a bar chart
// Otherwise show a guage chart
function drawChart(avgRentArray, chartTitle, chartDivTarget)
{ 
  var displayBed = $("#displayBedroom").val();
   
  var dataTable = new google.visualization.DataTable();
  var options = null;

  if (displayBed==-1) {  
    dataTable.addColumn('number');
    dataTable.addRows([
      [avgRentArray[0]["avg"]],
      [avgRentArray[1]["avg"]],
      [avgRentArray[2]["avg"]],
      [avgRentArray[3]["avg"]],
      [avgRentArray[4]["avg"]],
      [avgRentArray[5]["avg"]]
    ]);
    
    var optChm = "";
    for (var bed = 0; bed <= 5; bed++) {
       optChm = optChm + "t$"+avgRentArray[bed]["avg"]+",000000,0," + bed + ",10";
       if (bed < 5) { optChm = optChm + "|"; }
    }
    
    options = {cht: "bvs", 
      chs: "350x250", 
      colors:['#FFC6A5|#FFFF42|#00A5C6|#DEBDDE|#FFC6A5|#FFFF42'],
      chxt:"x", 
      chxl:"0:|Studio|1 Beds|2 Beds|3 Beds|4 Beds|5+ Beds", 
      chtt: chartTitle, 
      chm: optChm};
  }
  else {   
    var displayRent = $("#displayRent").val();
    var minRent = avgRentArray[displayBed]["min"];
    var maxRent = avgRentArray[displayBed]["max"];  
  
    dataTable.addColumn('number');
    dataTable.addRows([ [(displayRent-minRent)/(maxRent-minRent)*100] ]);  
   
    options = {cht: "gom", chs: "350x200", chco:"00C000,ffff00,ff0000",
      chxt:"x,y", 
      chxl:"0:|$"+displayRent+"|1:|min: $"+minRent+"|max: $"+maxRent, 
      chtt:"Your rent vs. neighborhood's " + (displayBed==0?"studio":displayBed+" bedroom") + " apartments"};         
  }
    
  var chart = new google.visualization.ImageChart(document.getElementById(chartDivTarget));
  chart.draw(dataTable, options);  
}



//*************************
// showFancyDiv
//
// Create a fancy box and show a div inside
function showFancyDiv(divName) {
   $.fancybox({
    scrolling: 'no',
    titleShow: false,
    href: divName
  });
  return false;
}

