function validateContact() {
	fields  = [['name', '-Please enter your name'],
			   ['phone', '-Please enter your phone number'],
			   ['message', '-Please enter a message']
			  ];
	customs = [['email', 'email']]
	
	return validateForm(fields, customs);
}

function validateBooking() {
	fields  = [['name', '-Please enter your name']
			  ,['phone', '-Please enter your phone number']
//			  ,['date', '-Please enter the move-in date']
			  ];
	customs = [['email', 'email']]

	return validateForm(fields, customs);
}

function validateRegistration() {
	fields = [['username', '-Please enter a username'],
			  ['password', '-Please enter a password'],
			  ['phone', '-Please enter your phone number'],
			  ['firstname', '-Please enter your first name'],
			  ['lastname', '-Please enter your last name'],
			  ['address1', '-Please enter your address'],
			  ['city', '-Please enter your city'],
			  ['state', '-Please enter your state'],
			  ['zip', '-Please enter your zipcode'],
			  ['cardnumber', '-Please enter your credit card number']
			 ];
			 
	customs  = [['email', 'email'],
				['confirm', 'email', 'cemail', '-Your email addresses do not match'],
				['confirm', 'password', 'cpassword', '-Your passwords do not match']
			   ];
	
	return validateForm(fields, customs);
}

function validateLogin() {
	fields = [['username', '-Please enter a username'],
			  ['password', '-Please enter a password']
			 ];
			 
	return validateForm(fields, []);
}

function validatePayform() {
	fields = [['firstnameonroom', '-Please enter the first name on the room'],
			  ['lastnameonroom', '-Please enter the last name on the room'],
			  ['phone', '-Please enter your phone number'],
			  ['unitnumber', '-Please enter your room number'],
			  ['amount', '-Please enter a payment amount'],
			  ['address1', '-Please enter your address'],
			  ['city', '-Please enter your city'],
			  ['state', '-Please select your state'],
			  ['zip', '-Please enter your zipcode'],
			  ['cardnumber', '-Please enter your credit card number'],
			  ['cvv', '-Please enter your credit card\'s CVV code']
			 ];
	
	customs = [['email', 'email'],
			   ['confirm', 'email', 'cemail', '-Your email addresses do not match'],
			   ['mustBeChecked', 'acceptterms', '-You must accept the payment terms']
			  ];
			  
	if (validateForm(fields, customs))
	{
		if (!($("#firstnameonroom").val() == $("#firstname").val() && $("#lastnameonroom").val() == $("#lastname").val()))
		{
			alert('Name On Room must be the same as the name on your credit card');
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
}

function payForm() {
	$(document).ready(function(){
		$('#firstnameonroom').change(function(){$('#firstname').val($(this).val())});
		$('#lastnameonroom').change(function(){$('#lastname').val($(this).val())});
	});
}

function addFriend() {
	friends++;
	newFriend   = document.createElement('div');
	newFriend.setAttribute('class', 'new_friend');
	newSection  = '<a href="javascript: void(0);" onClick="removeFriend(this)">X</a>' + "\n";
	newSection += '<div class="friend_separator"></div>' + "\n";
	newSection += '<div class="row">' + "\n";
	newSection += '	<label>Friend\'s Name:</label>' + "\n";
	newSection += '	<input type="text" id="friendsname" name="friend[' + friends + '][name]" class="inp03" />' + "\n";
	newSection += '</div>' + "\n";
	newSection += '<div class="row">' + "\n";
	newSection += '	<label>Friend\'s E-mail  Address:</label>' + "\n";
	newSection += '	<input type="text" id="friendsemail" name="friend[' + friends + '][email]"  class="inp03" />' + "\n";
	newSection += '</div>' + "\n";
	newFriend.innerHTML = newSection;
	document.getElementById('friends').appendChild(newFriend);
}

function removeFriend(x) {
	var f = x.parentNode;
	var d = f.parentNode;
	d.removeChild(f);
}

function validateReferral() {
	fields  = [['yourname', '-Please enter your name'],
			   ['youremail', '-Please enter your email address'],
			   ['friendsname', '-Please enter your friend\'s name'],
			   ['friendsemail', '-Please enter your friend\'s email address']
			  ];
	customs = [['email', 'youremail', '-Your email address must be valid'],
			   ['email', 'friendsemail', '-Your friend\'s email address must be valid']
			  ]
	
	return validateForm(fields, customs);
}


var map;
var geocoder;

function load() {
  if (GBrowserIsCompatible()) {
    geocoder = new GClientGeocoder();
    map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(40, -100), 4);
    
    $("#addressInput").focus(function(){
    	if ($(this).val() == $(this).attr("defaultValue")) {$(this).val('');}
    });
    
    $("#addressInput").blur(function(){
    	if ($(this).val() == '') {$(this).val($(this).attr("defaultValue"));}
    });
    
    $("#zipcodeSearch").click(function(){searchLocations();});
    
    searchLocations(true);
  }
}

function searchLocations(init) {
	$('#resultsFilter li[rel=0]').click();
  if (init)
  {
  	searchLocationsNear(true);
  } else {
  	  var address = document.getElementById('addressInput').value;
	  geocoder.getLatLng(address, function(latlng) {
	    if (!latlng) {
	      alert(address + ' not found');
	    } else {
	      searchLocationsNear(false, latlng);
	    }
	  });
  }
}

function searchLocationsNear(init, center) {
  if (init)
  {
  	var searchUrl = siteurl + '/location_search.php?init=1&loc=' + loc;
  } else {
  	var radius = 2000;  // Unlimited radius
  	var searchUrl = siteurl + '/location_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&loc=' + loc;
  }
  
  GDownloadUrl(searchUrl, function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName('marker');
    map.clearOverlays();

    var sidebar = document.getElementById('sidebar');
    sidebar.innerHTML = '';
    if (markers.length == 0) {
      sidebar.innerHTML = 'No results found.';
      map.setCenter(new GLatLng(40, -100), 4);
      return;
    }

    var bounds = new GLatLngBounds();
    for (var i = 0; i < markers.length; i++) {
      var id = markers[i].getAttribute('id');
      var name = markers[i].getAttribute('name');
      var address = markers[i].getAttribute('address');
      var phone = markers[i].getAttribute('phone');
      var directions = markers[i].getAttribute('directions');
      var distance = parseFloat(markers[i].getAttribute('distance'));
      var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                              parseFloat(markers[i].getAttribute('lng')));
      
      var marker = createMarker(point, name, address, phone);
      map.addOverlay(marker);
      var sidebarEntry = createSidebarEntry(id, marker, name, address, phone, directions, distance, i);
      sidebar.appendChild(sidebarEntry);
      bounds.extend(point);
    }
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);
  });
}

function createMarker(point, name, address, phone) {
  var marker = new GMarker(point);
  var html = '<b>' + name + '</b> <br/>' + address + '<br />' + phone;
  
  html += '<br /><a href="http://maps.google.com/maps?f=d&hl=en&geocode=&daddr=' + encodeURI(address) + '" style="color: #000;" target="_newwin">Get Directions</a>';
  
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

function createSidebarEntry(id, marker, name, address, phone, directions, distance, i) {
  var li = document.createElement('li');  

  var html  = '<div class="title">' + "\n";
  html += '<strong>' + (i + 1) + '.</strong> ' + name + "\n";
  html += '</div>' + "\n";
//  html += '	<p><strong>Phone:</strong> ' + phone + '</p>' + "\n";
  
  if (distance)
  {
  	html += '<p><strong>Distance:</strong> ' + distance.toFixed(1) + ' miles</p>' + "\n";
  }
  
  html += '	<p><strong>Directions:</strong> ' + directions + '</p>';
  html += '	<p class="check-room"><a href="javascript: void(0);" onclick="selectLocationLink(\'' + id + '\')">Check Room Availability</a></p>';
  html += '	<p class="get-directions"><a href="http://maps.google.com/maps?f=d&hl=en&geocode=&daddr=' + encodeURI(address) + '" target="_newwin">Get directions from Google Maps.</a>';
  li.innerHTML = html;
  li.style.cursor = 'pointer';
  li.style.marginBottom = '5px'; 
  GEvent.addDomListener(li, 'click', function() {
    GEvent.trigger(marker, 'click');
  });
  GEvent.addDomListener(li, 'mouseover', function() {
    li.style.backgroundColor = '#eee';
  });
  GEvent.addDomListener(li, 'mouseout', function() {
    li.style.backgroundColor = '#fff';
  });
  return li;
}


/* get an estimate page */
var locationArea;
var locationId;
var room;

$(function(){
	if($("#select_room").length > 0) {
		
		$("#selectRoom").change(function(){
			$("#room_1").css('display', 'none');
			$("#room_2").css('display', 'none');
			$("#room_3").css('display', 'none');
			$("#room_4").css('display', 'none');
			$("#room_5").css('display', 'none');
			$("#room_6").css('display', 'none');
			
			$("#room_" + $(this).val()).css('display', '');
			
			room = $(this).val();
			
			doEstimate();
		});
		
		$("#selectLocationArea").change(function(){
			$("#price_estimate_default").show();
			$("#price_estimate").css('display', 'none');
			var loc = $(this).val();
			$.getJSON(siteUrl + '/getLocations.php', {location_area_id:loc}, function(data) {
				populateLocations(data, loc);
			});
		});
		
		$("#addressInput").focus(function(){
	    	if ($(this).val() == $(this).attr("defaultValue")) {$(this).val('');}
	    });
		
		$("#estimateZip").submit(function(){
			var zip = $("#addressInput").val();
			if (parseInt(zip) > 0)
			{
				$("#price_estimate_default").show();
				$("#price_estimate").css('display', 'none');
				var loc = $("#selectLocationArea").val();
				$.getJSON(siteUrl + '/self-storage-estimates/', {location_area_id:loc,zip:zip}, function(data) {
					populateLocations(data, loc);
				});
			}
			return false;
		});
		
		$("#selectRoom").change();
		$("#selectLocationArea").change();
	}
	
	$('.select_room_link').click(function(){
		$("#room_id").val($(this).attr('id'));
		$("#estimate_post").submit();
	});
});

function doEstimate(){
	if  (parseInt(locationArea) > 0 && parseInt(locationId) > 0 && parseInt(room) > 0)
	{
		$.getJSON(siteUrl + '/getPrice.php', {location_id:locationId,room_id:room}, function(data) {
      var html = 'Limited Availability, Please Inquire for Pricing.<br /><small>(or choose another room size)</small>';

      if ((data.price != null) && (parseInt(data.price) > 0)) {
        html = 'Estimated Price: <strong>$' + data['price'] + ' / Month</strong>';
      }
			$("#price_estimate_default").hide();
			$("#price_estimate").css('display', 'block');
			$("#thePrice").html(html);
      
      $("#thePhone").html('');
      if (data.phone != null) {
  			// $("#thePhone").html('Call <strong>' + data['phone'] + '</strong> to book or <a href="contact" id="book">Reserve Now</a>!');
			$("#thePhone").html('Call <strong> 866-549-4740 </strong> to book or <a href="contact" id="book">Reserve Now</a>!');
      } else {
        $("#thePhone").html('<a href="contact" id="book">Reserve Now</a>!');
      }

      book_url = 'contact/book/'
               + '?l=' + escape($('.location_selected .address').text()+', '+$('#selectLocationArea option:selected').text())
               + '&s=' + escape($('#selectRoom option:selected').text())
               + '&p=' + data.price;

      $('#book').attr('href', book_url)
                .attr('class', 'iframe')
                .fancybox({ width: 500, height: 550, scrolling: 'no' });

//      console.log(book_url);
		});
	}
}

function selectLocationLink(id){
	$("#location_id").val(id);
	$("#estimate_post").submit();
}

function populateLocations(data, loc)
{
	var html  = '';
	var first = true;
	var locNum;
	for (i in data){
		/*
		if (first) {
			first = false;
		} else {
			html += '<div class="location_separator"></div>' + "\n";
		}
		*/
		
		locNum = parseInt(i) + 1;
		
		html += '<div class="location_info" id="' + data[i]['id'] + '" rel="' + data[i]['location_area_id'] + '">' + "\n";
//		html += '	<p><strong>' + locNum + '.</strong> <span class="address">' + data[i]['name'] + '</span></p>' + "\n";
		html += '	<p><span class="address">' + data[i]['name'] + '</span></p>' + "\n";
		html += '	<p><strong>Phone:</strong> ' + data[i]['phone'] + '</p>' + "\n";
		
		if (undefined != data[i]['distance'])
		{
			var distance = parseFloat(data[i]['distance']);
			html        += '	<p><strong>Distance:</strong> ' + distance.toFixed(1) + ' miles</p>' + "\n";
		}
		
		html += '</div>' + "\n";
	}
	
	$("#locationList").html(html);
	locationArea = loc;
	
	
	$(".location_info").click(function(){
		$(".location_info").removeClass('location_selected');
		$(this).addClass('location_selected');
		
		locationId = $(this).attr('id');
		doEstimate();
	});
	
	if ((undefined != window.locationPreset) && (window.selectedPresetLocation == false))
	{
		$("#" + window.locationPreset).click();
		window.selectedPresetLocation = true;
	}
	
	$('#resultsFilter li[rel='+loc+']').click();
}

$(document).ready(function(){
	if ($('#addressInput').val() != 'Enter Zip Code') {
		$('#estimateZip').submit();
	}
});
