//******************************************************************
//* 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
//*
//* Sample icon: http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png
var googleMap = null;
var googlePano = null;
var infowindow = null;
var mapBounds = null;
var firstRentalID = 0; 		
var firstRentalLatitude;
var firstRentalLongitude;

//*************************
// OnLoad event handler
//
// Handles Google Map address
function shared_onLoad() 
{                            
  // Setup About Us dialog 
  $("#aboutUsFancybox").fancybox({
    'scrolling':'no'
  });
  
  // Create fancybox for Login/Password
  $("#anchorLogin").fancybox({
  	'scrolling'		: 'no',
  	'titleShow'		: false,
  	'onClosed'		: function() {
  	    $("#login_error").hide();
  	}
  });      
} 

//*************************
// Load markers on the map
//
function sharedLoadGoogleMap(rentalArray, clickRentalID, isForRent)
{
  if (rentalArray.length>0) 
  {
    if (googleMap == null) {        
        infowindow = new google.maps.InfoWindow({ content: "none" });  
        var latlng = new google.maps.LatLng(0, 0);
        var myOptions = { 
          zoom: 8, 
          center: latlng, 
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          panControl: false,
          zoomControl: true,
          zoomControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
          }  
        };
        googleMap = new google.maps.Map(document.getElementById("googleMap"), myOptions);                 
    }     
         
    for (var key in rentalArray) {  							  						
      var rental = rentalArray[key];	
      if (rental["longitude"] != 0 && rental["latitude"] != 0)
      {
      	// Retrieve the latitude and longitude
        var savvyLatLng = new google.maps.LatLng(rental["latitude"], rental["longitude"]);
        // Extend the boundary to include new marker
        mapBounds.extend(savvyLatLng);        
        // Create a marker : 
        //rental["marker"] = createMarker(savvyLatLng, document.getElementById(rental["descriptDiv"]).innerHTML, isForRent);
        rental["marker"] = createMarker(savvyLatLng, $("#" + rental["descriptDiv"]).html(), isForRent);
    	}							
    }
    googleMap.setCenter(mapBounds.getCenter());
    googleMap.fitBounds(mapBounds);
    // Load Google Pano with the first rental ID  
    if (clickRentalID != 0) {         
      viewRental(firstRentalID);    
    }
  }
}

//*************************
// resetGoogleMap
//
// Clear out the map
function resetGoogleMap(){
  mapBounds = new google.maps.LatLngBounds();
}

//****************************************************************************
// createMarker
//
// Must do this in the separate method, otherwise only the last
// flyout info will appear
function createMarker(savvyLatLng, descriptDivHTML, isForRent) 
{
  //alert("DIV HTML: " + descriptDivHTML);
	descriptDivHTML = descriptDivHTML.replace(/REPLACE/g,"");
	
	if (isForRent) {
	  iconImage = 'http://maps.google.com/mapfiles/marker_purple.png';
	} else {
    iconImage = 'http://maps.google.com/mapfiles/marker.png';
  }
  var marker = new google.maps.Marker({ map: googleMap, position: savvyLatLng, icon: iconImage });
  google.maps.event.addListener(marker, 'click', function() {  
    if (infowindow) infowindow.close();      
    infowindow.setContent(descriptDivHTML);          
    infowindow.open(googleMap, marker);
    loadPano(marker.getPosition()); // Load Panorama
  });
	return marker;
}

//**************************************************
// viewRental
//  
function viewRental(rentalID, argRentalArray)
{	
  var rentalData = null;				
  if (argRentalArray == null)
  {
    rentalData = rentalAddressArray[rentalID];
  }
  else
  {
    rentalData = argRentalArray[rentalID];
  }
  var marker = rentalData["marker"];
  google.maps.event.trigger(marker,"click"); 						
}

//**************************************************
// extractGeocoderResponse
// 
function extractGeocoderResponse(results, status, addressObj) 
{
  //alert("Geocode result type: " + results[0].types[0]);
  if (status != google.maps.GeocoderStatus.OK) {
 		alert("The address you entered is invalid.  Please re-enter the address.");
 		return false;
  } 
	else {
	  addressObj.addressType = results[0].types[0];
	  
    $.each(results[0].address_components, function(index1, address_component) {
      $.each(address_component.types, function(index2, type) {
        //alert(type + "=" + address_component.long_name);
        switch(type)
        {
          case "street_number":   addressObj.streetNumber = address_component.long_name; break;
          case "route":           addressObj.streetName = address_component.long_name; break;
          case "locality":        addressObj.city = address_component.long_name; break;
          case "administrative_area_level_1": addressObj.state = address_component.short_name; break;
          case "postal_code":     addressObj.zip = address_component.long_name; break;                           
        }                        
      });
    });
    
    if (addressObj.addressType == "street_address") {
  	  //alert("Exact street address!");
		  addressObj.latitude = results[0].geometry.location.lat();
		  addressObj.longitude = results[0].geometry.location.lng(); 								    
    }           
  }  
  return true;
}

//******************************
//* recurseEvalJavaScript
//*
//* Recurses thourgh the given HTML and executes any Javascript it finds
//*
function recurseEvalJavaScript(sourceHTML, count)
{
  startString = "<script type=\"text/javascript\">";
  startPosition = sourceHTML.indexOf(startString) + startString.length;
  endPosition = sourceHTML.indexOf("</script>");
  if (startPosition>=0 && endPosition>=0 && count<100)
  {
    strScript = sourceHTML.substring(startPosition, endPosition);
    
    /* DEBUG CODE
    if (strScript.indexOf("savvyFancybox")) {
      alert("Recurse eval: " + strScript);
    }
    */
    eval(strScript);
    recurseEvalJavaScript(sourceHTML.substring(endPosition + 10), count+1);    
  }
}
//***************************************************
// loadPano
//             	
function loadPano(savvyLatLng) 
{        
  // Create new Google panorama object and set it to marker's LatLng
  if (googlePano == null)
  {
    var startLatLng = new google.maps.LatLng(0, 0);
    var panoramaOptions = {
      position: startLatLng,
      pov: {
        heading: 34,
        pitch: 10,
        zoom: 1
      }
    };
    googlePano = new google.maps.StreetViewPanorama(document.getElementById("googlePano"), panoramaOptions);
  }
  googlePano.setPosition(savvyLatLng);
}				
//***************************************************
// 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.";
  }
} 
//****************************************************************************
// showRentalHistory
//         
function showRentalHistory(rentalID)
{
  $.fancybox.showActivity();
  // Make AJAX search call    
  $.ajax({
       url:     "ajax_rent_history.php",
       type:    "POST",
       cache:   false,
       data:    {'rentalID':rentalID},
       async:   false,             
       success: function(result) {
            //alert("Response: " + result);
            $.fancybox(result);
              //$.fancybox.resize();          
          },
       error:   function(xhr, ajaxOptions, thrownError){
              alert(xhr.status);
              alert(thrownError);
          }                   
  });                
}

//****************************************************************************
//* showFancyboxImage
//*
//* Overrides Fancybox target href and triggers fancybox  
//*
function showFancyboxImage(imageSrc)
{
   var ctlFB = document.getElementById("ctlFancybox");
   ctlFB.href = imageSrc;
   $("#ctlFancybox").trigger('click');
}

//***************************************************
// 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_defaultInvalid
//   		
// Custom validator.           
function validator_defaultInvalid(value, element, params) {	      
	if (this.optional(element)) return true;  // if this line is absent, the rule is always applied even if optional
	
	if (value == params.defaultVal) { // if matches default, FAIL
	  return false;  
  }
	return true;
}

//***************************************************************************   
// 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() > 2020) { 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;        
}

//******************************
//* evtOnFocus
//*
function evtOnFocus(eventObject, defaultTest)
{
  l_elemID = eventObject.currentTarget.id;
  //alert("evtOnFocus: " + l_elemID + ", val=" + defaultTest);
  if (l_elemID != undefined && document.getElementById(l_elemID).value == defaultTest) {
    document.getElementById(l_elemID).value = "";
    document.getElementById(l_elemID).style.color = "black";
    document.getElementById(l_elemID).style.fontStyle = "normal";
  }
}

//******************************
//* evtOnBlur
//*
function evtOnBlur(eventObject, defaultTest)
{
  l_elemID = eventObject.currentTarget.id;
  if(l_elemID != undefined && document.getElementById(l_elemID).value == "") { 
    document.getElementById(l_elemID).value = defaultTest;
    document.getElementById(l_elemID).style.color = "silver";
    document.getElementById(l_elemID).style.fontStyle = "italic";    
  }
}

//******************************
//* evtOnChange
//*
function evtOnChange(eventObject, defaultTest)
{
  l_elemID = eventObject.currentTarget.id;
  //alert("evtOnFocus: " + l_elemID + ", val=" + defaultTest);
  if (l_elemID == undefined) { return false; }
    
  if (document.getElementById(l_elemID).value == defaultTest) {
    document.getElementById(l_elemID).style.color = "silver";
    document.getElementById(l_elemID).style.fontStyle = "italic";
  }
  else {
    document.getElementById(l_elemID).style.color = "black";
    document.getElementById(l_elemID).style.fontStyle = "normal";  
  }
}

//*************************
// String: trim
//            
String.prototype.trim = function () {
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
} 


