//******************************************************************
//* 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: Shared Javascript
//* 
//* Description:
//*   Javascript for My Favorites screen
//*
var googleMap;

//*************************
// String: trim
//            
String.prototype.trim = function () 
{
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
} 

//*************************
// OnLoad event handler
//
// Handles Google Map address
function shared_onLoad() 
{                            
  // Nothing to do
} 
          
//*************************
// Load markers on the map
//
function sharedLoadGoogleMap()
{
  var elemMap = document.getElementById("googleMap"); 
  if (GBrowserIsCompatible() && elemMap!=null) 
  {
    if (googleMap == null)
    {
      googleMap = new google.maps.Map(elemMap);
    }
    else
    { 
      googleMap.clearOverlays();
      googleMap.setCenter(new GLatLng(0,0),0);
    }
    var mapBounds = new GLatLngBounds();  
    var firstRentalID = 0;						
    for (var key in rentalAddressArray)
    {  							
      if (firstRentalID == 0)
      {  			  
        firstRentalID = key;
        //alert("First RentalID =" + rentalID);
      }  						
      var rentalData = rentalAddressArray[key];	
      if (rentalData['longitude'] != 0 && rentalData['latitude'] != 0)
      {
      	// Retrieve the latitude and longitude
        var point = new GLatLng(rentalData['latitude'], rentalData['longitude']);
        // Create a marker
        marker = createMarker(point, rentalData['descriptDiv']);
        rentalData['marker'] = marker;
        // Add the marker to map
        googleMap.addOverlay(marker);	
        // Extend the boundary to include new marker
        mapBounds.extend(point);
    	}							
    }
    if (firstRentalID != 0)
    {
      // Recenter on all the markers
      googleMap.setCenter(mapBounds.getCenter(), googleMap.getBoundsZoomLevel(mapBounds));
      // Load Google Pano with the first rental ID     
      viewRental(firstRentalID);    
    }
    
    // Add Zoom/Move and Map Type controls
    googleMap.addControl(new GSmallMapControl());
    googleMap.addControl(new GMapTypeControl());   
  }
}

//****************************************************************************
// createMarker
//
// Must do this in the separate method, otherwise only the last
// flyout info will appear
function createMarker(point, rentalDiv) 
{
	var marker = new GMarker(point);    						    						
	var descHTML = document.getElementById(rentalDiv).innerHTML;
	descHTML = descHTML.replace(/REPLACE/g,"");
	GEvent.addListener(marker, "click", function()
    {  
      marker.openInfoWindowHtml(descHTML); // Show bubble
      loadPano(marker.getPoint()); // Load Panorama
    });
	return marker;
}
				
//*************************
// viewRental
//  
function viewRental(rentalID)
{						
  var rentalData = rentalAddressArray[rentalID];
  var marker = rentalData['marker'];
  GEvent.trigger(marker,"click"); 
  						
  //var savvyPoint = marker.getPoint();              
  // Load Panorama
  //loadPano(savvyPoint);	  						
}
        	
//***************************************************
//* imposeMaxLengthInput
//* USED BY EDIT_RENTAL screen, switch to jQuery
/* 
function imposeMaxLengthInput(field, maxChars)
{
  if(field.value.length >= maxChars) 
  {
    event.returnValue=false;
    alert("Maximum comment length exceeded!");
    return false;
  }
}

//***************************************************
//* imposeMaxLengthPaste
//*
function imposeMaxLengthPaste(field, maxChars)
{
  event.returnValue=false;
  if((field.value.length + window.clipboardData.getData("Text").length) > maxChars) 
  {
    alert("Maximum comment length exceeded!");
    return false;
  }
  event.returnValue=true;
}
*/
      	
//***************************************************
// loadPano
//             	
function loadPano(savvyPoint) 
{      
  panoramaOptions = { latlng:savvyPoint };  
  // Clear out contents of Pano left over from previous rental display
  document.getElementById("googlePano").innerHTML = "";  
  var googlePano = new GStreetviewPanorama(document.getElementById("googlePano"), panoramaOptions);
  GEvent.addListener(googlePano, "error", handleNoFlash);
}					

//***************************************************
// handleNoFlash
//      
function handleNoFlash(errorCode) 
{
  if (errorCode == 603) 
  {
    document.getElementById("googlePano").innerHTML = "No image available at this time.";
  }
  else if (errorCode == 600)
  {
    document.getElementById("googlePano").innerHTML = "No image available at this time.";
  }
} 

//****************************************************************************
// showRentHistory
//         
function showRentHistory(rentalID)
{      		  
  //alert("showRentHistory here");
	document.getElementById("SCREEN_ACTION").value = "ACTION_SHOW_RENT_HISTORY";
	document.getElementById("RENTAL_ID").value = rentalID;
	document.sbForm.submit();
} 

//**********************************************
// getMyHome
//
/*
function getMyHome()
{
	document.getElementById("SCREEN_ID").value = "CScrMyHome";
	document.getElementById("SCREEN_ACTION").value = "ACTION_GENERATE";
	document.sbForm.submit();
}	
*/

//**********************************************
// getMyAccount
//
/*
function getMyAccount()
{
	document.getElementById("SCREEN_ID").value = "CScrMyAccount";
	document.getElementById("SCREEN_ACTION").value = "ACTION_GENERATE";
	document.sbForm.submit();
}	
*/

//**********************************************
// getAboutUs
//
/*
function getAboutUs()
{
	document.getElementById("SCREEN_ID").value = "CScrAboutUs";
	document.getElementById("SCREEN_ACTION").value = "ACTION_GENERATE";
	document.sbForm.submit();
}	
*/
		
//**********************************************
// getLogout
//
/*
function getLogout()
{
	document.getElementById("SCREEN_ID").value = "CScrLogin";
	document.getElementById("SCREEN_ACTION").value = "ACTION_GENERATE";
	document.sbForm.submit();
}		
*/

//***************************************************
// createMySQLDate
//
// Format dates as YYYY-MM-DD
function createMySQLDate(l_elemName)
{
  var l_myDate=new Date(document.getElementById(l_elemName).value);	
  return l_myDate.getFullYear()+"-"+(l_myDate.getMonth()+1)+"-"+l_myDate.getDate();
}

//***************************************************************************   
// validator_isAlphaNumOnly
//   		
// Custom validator.  Returns FALSE for anything other than alphanum and ".", "-"         
function validator_isAlphaNumOnly(value, element) 
{	      
	if (this.optional(element)) return true;  // if this line is absent, the rule is always applied even if optional
	     
	var regEx = /[^.a-zA-Z0-9- ]/;
	if (regEx.test(value)) { return false; }
	return true;
}

//***************************************************************************
// validator_isValidDate
//
// Custom validator.  Checks that a date is valid                     
function validator_isValidDate(value, element) 
{	     
	if (this.optional(element)) return true;  // if this line is absent, the rule is always applied even if optional
	     
	var checkDate=new Date(value);
	var checkArray = value.split("/");
	if(isNaN(checkDate.getFullYear())) { return false; }	 
	if(checkDate.getFullYear() < 2000 || checkDate.getFullYear() > 2010) { return false; }
	if((checkDate.getMonth()+1)!=checkArray[0] || checkDate.getDate()!=checkArray[1] || checkDate.getFullYear()!=checkArray[2]) { return false; } 
  return true;    
}

//***************************************************************************
// validator_isValidFromToDate
//    
// a custom method for to make sure from Date is before after date
function validator_isValidFromToDate(value, element, param)     
{
  if (this.optional(element)) return true;   // if this line is absent, the rule is always applied even if optional
  var fromDate=new Date(value);
  var toDate=new Date($(param).val());
  return (fromDate < toDate);
}
      
//***************************************************************************
// validator_isDateDiffLessOneYear
//    
// a custom method for to make sure from Date is before after date
function validator_isDateDiffLessOneYear(value, element, param)       
{
  if (this.optional(element)) return true;   // if this line is absent, the rule is always applied even if optional
  var fromDate=new Date(value);
  var toDate=new Date($(param).val());
  return ((toDate.getFullYear()-fromDate.getFullYear())<=1);
}
    
//******************************
//* validateRentDates
//*            
function validateRentDates(elemDisplayFromDate, elemDisplayToDate, elemSubmitFromDate, elemSubmitToDate)
{
  var regExValidDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
  
  // Validate dates first since its the most complicated
  // Check for format (MM/DD/YYYY) and validity
  var dispRentFrom = document.getElementById(elemDisplayFromDate).value;     
  var dispRentTo = document.getElementById(elemDisplayToDate).value;    
  if (! regExValidDate.test(dispRentFrom) || ! regExValidDate.test(dispRentTo))
  {
    alert("Please enter rented from and to dates using MM/DD/YYYY format.");
    return false;              
  }
  var fromDate=new Date(dispRentFrom);
  var toDate=new Date(dispRentTo);
  var fromArray = dispRentFrom.split("/");
  var toArray = dispRentTo.split("/");
  //alert ("Entered: " + dispRentFrom + ", Saved: " + fromDate);
	if(isNaN(fromDate.getFullYear()) || isNaN(toDate.getFullYear()))
	{
    alert("Rented from or to dates are invalid.  Please correct rent dates before saving.");
    return false;
  }    
  else if (fromDate.getMonth()+1 != fromArray[0] || fromDate.getDate()!=fromArray[1] || fromDate.getFullYear()!=fromArray[2])    
  {
    alert("Rented from date is invalid.  Please correct rented from date before saving.");
    return false;            
  }
  else if (toDate.getMonth()+1 != toArray[0] || toDate.getDate()!=toArray[1] || toDate.getFullYear()!=toArray[2])    
  {
    alert("Rented to date is invalid.  Please correct rented to date before saving.");
    return false;            
  }                
  else if (fromDate.getFullYear() < 2000 || toDate.getFullYear() > 2009)
  {
    alert("Please enter rental information between years 2000 and 2009.");
    return false;
  }       
  else if(fromDate >= toDate)
  {
    alert("Rented from date must be before rented to date.  Please enter correct rented from and to dates.");
    return false;
  }    
  else if((toDate.getFullYear()-fromDate.getFullYear())>1)  
  {
    alert("Rented from and rented to dates must not be more than 1 year apart.  Please enter correct rented from and to dates.");
    return false;            
  }   

  // Field validation is OK, format dates for MySQL entry      						  
	var fromDate=new Date(dispRentFrom);			              
	document.getElementById(elemSubmitFromDate).value = fromDate.getFullYear()+"-"+(fromDate.getMonth()+1)+"-"+fromDate.getDate();
	var toDate=new Date(dispRentTo);	
	document.getElementById(elemSubmitToDate).value = toDate.getFullYear()+"-"+(toDate.getMonth()+1)+"-"+toDate.getDate();
  
  return true;        
}
