/* -----------------------------------------------------------
Copyright: ©22008 Terra Firma Design & Consulting. All Rights Reserved.
Author: Brian Getting
Company: Terra Firma Design & Consulting
URL: http://www.terra-firma-design.com
----------------------------------------------------------- */

var errorColor = "#fffbfb";
var errorBorder = "#c00";
var regExpEmail = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
var regExpPhone = /^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/;
var defaultTextAreaHeight = 180;
var expandedTextAreaHeight = 400;
var textAreaThreshold = 1000;

/* -------------------------------------------------------- */

Global = {
  adjustTextarea: function(e) {
  	textArea = $(Event.element(e));
  	if (textArea.value.length > textAreaThreshold) {
  		textArea.morph('height:'+expandedTextAreaHeight+'px;', {duration:0.2});
  	} else {
  		textArea.morph('height:'+defaultTextAreaHeight+'px;', {duration:0.2});
  	}
  },
  
  clearFlash: function() {
    $('flash_notice').fade({duration:0.5, delay:5});
    $('flash_notice').blindUp({duration:0.5, delay:5});
  },
  
  setup: function() {
    Global.externalLinks();
    if ($('flash_notice')) Global.clearFlash();
    if ($('contact_message')) Contact.setup();
		Listing.setup();
		if ($('post_content')) Post.setup();
		if ($('grant_report_deadline')) Report.setup();
  },
  
  externalLinks: function() {
    external_links = $$('a[rel=external]');
    external_links.each(function(l) {
      l.writeAttribute('target', '_blank');
    })
  }
}

Contact = {
  validate: function() {
    var name = $('contact_name');
    var email = $('contact_email');
    var subject = $('contact_subject');
    var message = $('contact_message');
    var contactSubmit = $('contact_submit');
    var errors = "";
    if (name.value == "") {
		  name.addClassName('fieldError');
			errors += "* Please enter your name.\n";
		}
    if ((email.value == "") || !regExpEmail.test(email.value)) {
		  email.addClassName('fieldError');
			errors += "* Please enter your email address.\n";
		}
		if (subject.value == "") {
		  subject.addClassName('fieldError');
			errors += "* Please enter a subject.\n";
		}
		if (message.value == "") {
		  message.addClassName('fieldError');
			errors += "* Please enter a brief message.\n";
		}
		if (errors == "") {
		  contactSubmit.disabled = true;
		  contactSubmit.value = "Sending..."
		  return true
		} else {
		  alert(errors);
		  return false;
		}
  },
  
  setup: function() {
    message_field = $('contact_message');
    message_field.setStyle({height: defaultTextAreaHeight +"px"});
    message_field.observe('keyup', Global.adjustTextarea.bind(contact_message));
  }
}

var Grant = {
  validate: function() {
    var name = $('grant_application_organization');
    var addr = $('grant_application_address1');
    var city = $('grant_application_city');
    var state = $('grant_application_province');
    var zip = $('grant_application_postal');
    var phone = $('grant_application_phone');
    var email = $('grant_application_email');
		var doc = $('grant_application_document');
    var agreed = $('agreed');
    var terms = $('terms');
    var appSubmit = $('grant_submit');
    var errors = "";
    if (name.value == "") {
			name.setStyle({backgroundColor: errorColor});
			name.setStyle({borderColor: errorBorder});
			errors += "* Please enter your organization or name.\n";
		}
		if (addr.value == "") {
			addr.setStyle({backgroundColor: errorColor});
			addr.setStyle({borderColor: errorBorder});
			errors += "* Please enter your address.\n";
		}
		if (city.value == "") {
			city.setStyle({backgroundColor: errorColor});
			city.setStyle({borderColor: errorBorder});
			errors += "* Please enter your city.\n";
		}
		if (state.value == "") {
			state.setStyle({backgroundColor: errorColor});
			state.setStyle({borderColor: errorBorder});
			errors += "* Please enter your state.\n";
		}
		if (zip.value == "") {
			zip.setStyle({backgroundColor: errorColor});
			zip.setStyle({borderColor: errorBorder});
			errors += "* Please enter your postal code.\n";
		}
		if (phone.value == "Ex: 541-555-5555") {
		  phone.value = "";
		}
		if ((phone.value == "") || !regExpPhone.test(phone.value)) {
			phone.setStyle({backgroundColor: errorColor});
			phone.setStyle({borderColor: errorBorder});
			errors += "* Please enter your phone number.\n";
		}
		if (email.value != "" && !regExpEmail.test(email.value)) {
			email.setStyle({backgroundColor: errorColor});
			email.setStyle({borderColor: errorBorder});
			errors += "* Please enter a valid email address.\n";
		}
		if (doc.value == "") {
			doc.setStyle({backgroundColor: errorColor});
			doc.setStyle({borderColor: errorBorder});
			errors += "* Please select a Word document to upload.\n";
		}
		if (!agreed.checked) {
			terms.setStyle({backgroundColor: errorColor});
			terms.setStyle({borderColor: errorBorder});
			errors += "* You must agree to our policies.\n";
		}
		if (errors == "") {
			appSubmit.value = "Submitting...";
			appSubmit.disabled = true;
			return true;
		} else {
			alert("Please fix the following errors:\n"+errors);
			return false;
		}
  },
  
  toggleAddress: function() {
    var addrLink = $('second_addr_link');
    var addFields = $('second_addr_line');
    if (addFields.style.display == 'none'){
      addFields.blindDown({duration:0.3});
      addFields.appear({duration:0.3});
      addrLink.update("Hide second address line");
    } else {
      addFields.blindUp({duration:0.3});
      addFields.fade({duration:0.3});
      addrLink.update("Use a second address line");
    }
  },
  
  clearPhone: function(evt) {
  	if ($F(Event.element(evt)) == "Ex: 541-555-5555") {
  		$(Event.element(evt)).value = "";
  	}
  },
  
  setup: function () {
    var grantForm = $('grant-form');
    if (grantForm) {
      var state = $('grant_application_province');
      if (state.value == "") {
        state.value = "OR";
      }
      var phone = $('grant_application_phone');
      if (phone.value == "") {
        phone.value = "Ex: 541-555-5555";
        phone.observe('focus', Grant.clearPhone.bind(phone));
      }
    }
  }
}

var Listing = {
  validate: function() {
	  var organization = $('listing_organization');
    var addr = $('listing_address1');
    var city = $('listing_city');
    var state = $('listing_province');
    var zip = $('listing_postal');
    var phone = $('listing_phone');
    var fax = $('listing_fax');
    var email = $('listing_email');
	  var website = $('listing_website');
	  var description = $('listing_description');
	  var agreed = $('agreed');
    var terms = $('terms');
    var appSubmit = $('listing-submit');
    var errors = "";
	  if (organization.value == "") {
		  organization.setStyle({backgroundColor: errorColor});
		  organization.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your name or organization.\n";
	  }
	  if (addr.value == "") {
		  addr.setStyle({backgroundColor: errorColor});
		  addr.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your address.\n";
	  }
	  if (city.value == "") {
		  city.setStyle({backgroundColor: errorColor});
		  city.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your city.\n";
	  }
	  if (state.value == "") {
		  state.setStyle({backgroundColor: errorColor});
		  state.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your state.\n";
	  }
	  if (zip.value == "") {
		  zip.setStyle({backgroundColor: errorColor});
		  zip.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your postal code.\n";
	  }
	  if (phone.value == "Ex: 541-555-5555") {
	    phone.value = "";
	  }
	  if ((phone.value == "") || !regExpPhone.test(phone.value)) {
		  phone.setStyle({backgroundColor: errorColor});
		  phone.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your phone number.\n";
	  }
	  if (fax.value == "Ex: 541-555-5555") {
	    fax.value = "";
	  }
	  if ((fax.value != "") && !regExpPhone.test(fax.value)) {
		  fax.setStyle({backgroundColor: errorColor});
		  fax.setStyle({borderColor: errorBorder});
		  errors += "* Please enter a valid fax number.\n";
	  }
	  if ((email.value != "") && !regExpEmail.test(email.value)) {
		  email.setStyle({backgroundColor: errorColor});
		  email.setStyle({borderColor: errorBorder});
		  errors += "* Please enter your email address.\n";
	  }
	  if (website.value == "http://") {
	    website.value = "";
	  }
	  if ((website.value != "") && !regExpUrl.test(website.value)) {
		  website.setStyle({backgroundColor: errorColor});
		  website.setStyle({borderColor: errorBorder});
		  errors += "* Please enter a valid website address.\n";
	  }
	  if (description.value == "") {
		  description.setStyle({backgroundColor: errorColor});
		  description.setStyle({borderColor: errorBorder});
		  errors += "* Please enter a brief description of your work.\n";
	  } else if (description.value.split(" ").length > 1000) {
			description.setStyle({backgroundColor: errorColor});
			description.setStyle({borderColor: errorBorder});
			errors += "* Please limit your description to 500 words.\n(You have " + description.value.split(" ").length + " words now)\n";
		}
	  if (!agreed.checked) {
			terms.setStyle({backgroundColor: errorColor});
			terms.setStyle({borderColor: errorBorder});
			errors += "* You must agree to our policies.\n";
		}
	  if (errors == "") {
		  appSubmit.value = "Submitting...";
		  appSubmit.disabled = true;
		  return true;
	  } else {
		  alert("Please fix the following errors:\n"+errors);
		  return false;
	  }
  },

  toggleAddress: function() {
    var addrLink = $('second_addr_link');
    var addFields = $('second_addr_line');
    if (addFields.style.display == 'none'){
      addFields.blindDown({duration:0.3});
      addFields.appear({duration:0.3});
      addrLink.update("Hide second address line");
    } else {
      addFields.blindUp({duration:0.3});
      addFields.fade({duration:0.3});
      addrLink.update("Use a second address line");
    }
  },
  
  toggleOther: function(evt) {
    var other = $('other_field');
    if (Event.element(evt).options[Event.element(evt).selectedIndex].value == "other") {
      if (other.style.display == 'none') {
        other.show();
      }
    } else {
      if (other.style.display != 'none') {
        other.hide();
      }
    }
  },
  
  clearAmount: function (evt) {
    if ($F(Event.element(evt)) == "Live Search...") {
  		$(Event.element(evt)).value = "";
  	}
  },

  clearPhone: function(evt) {
  	if ($F(Event.element(evt)) == "Ex: 541-555-5555") {
  		$(Event.element(evt)).value = "";
  	}
  },
  
  clearSearch: function (evt) {
    if ($F(Event.element(evt)) == "Live Search...") {
  		$(Event.element(evt)).value = "";
  	}
  },

  setup: function () {
    var liveSearch = $('livesearch');
    if (liveSearch) {
      var query = $('query');
      if (query.value == "") {
        query.value = "Live Search...";
      }
      query.observe('focus', Listing.clearSearch.bind(query));
    }
	  var listingForm = $('listing-form');
    if (listingForm) {
      var state = $('listing_province');
      if (state.value == "") {
        state.value = "OR";
      }
      var phone = $('listing_phone');
      if (phone.value == "") {
        phone.value = "Ex: 541-555-5555";
        phone.observe('focus', Listing.clearPhone.bind(phone));
      }
      var fax = $('listing_fax');
      if (fax.value == "") {
        fax.value = "Ex: 541-555-5555";
        fax.observe('focus', Listing.clearPhone.bind(fax));
      }
      var website = $('listing_website');
      if (website.value == "") {
        website.value = "http://";
      }
      var description = $('listing_description');
      description.setStyle({height: "150px"});
      description.observe('keyup', Global.adjustTextarea.bind(description));
    }
  }
}

Login = {
  validate: function() {
    var username = $('user_session_login');
    var password = $('user_session_password');
    var loginSubmit = $('login_submit');
    var loadIcon = $('loadicon');
    var errors = "";
    if (username.value == "") {
	    username.addClassName('fieldError');
			errors += "* Please enter a username.\n";
		} else if (username.value.length < 3 || username.value.length > 40) {
		  username.addClassName('fieldError');
			errors += "* Username must be between 3 and 40 characters.\n";
		}
		if (password.value == "") {
		  password.addClassName('fieldError');
			errors += "* Please enter a password.\n";
		}
		if (errors == "") {
		  loginSubmit.disabled = true;
		  loadIcon.show();
		  return true
		} else {
		  alert(errors);
		  return false;
		}
  },
  
  forgot: function() {
    var email = $('email');
    var loadIcon = $('loadicon');
    var loginSubmit = $('forgot_submit');
    var errors = "";
    if ((email.value == "") || !regExpEmail.test(email.value)) {
		  email.addClassName('fieldError');
			errors += "* Please enter your email address.\n";
		}
		if (errors == "") {
		  loginSubmit.disabled = true;
		  loadIcon.show();
		  return true
		} else {
		  alert(errors);
		  return false;
		}
  },
  
  reset: function() {
    var password = $('user_session_password');
    var confirm = $('user_session_password_confirmation');
    var loginSubmit = $('reset_submit');
    var loadIcon = $('loadicon');
    var errors = "";
    if (password.value == "") {
		  password.addClassName('fieldError');
			errors += "* Please enter a password.\n";
		} else if ((password.value != "") && (password.value != confirm.value)) {
		  password.addClassName('fieldError');
			errors += "* Password and confirmation do not match.\n";
		}
    if (errors == "") {
		  loginSubmit.disabled = true;
		  loadIcon.show();
		  return true
		} else {
		  alert(errors);
		  return false;
		}
  }
}

var Map = {
  initialize: function() {
  	if (GBrowserIsCompatible()) {
  	  // Set the variables needed.
  	  var lat = $F('listing_latitude');
		  var lng = $F('listing_longitude');
		  if ((lat && lat != '') && (lng && lng != '')) {
		    var centerLocation = new GLatLng(lat, lng);
		    var zoom = 14;
		  } else {
		    var centerLocation = new GLatLng(44.63519251645426, -124.0524673461914);
		    var zoom = 10;
		  }
		  // Initialize the map
		  map = new GMap2(document.getElementById("map-canvas"));
		  map.addControl(new GSmallMapControl());
		  map.setCenter(centerLocation, zoom);
		  // Set the marker
			geocoder = new GClientGeocoder();
			// Set the observers
			var listingForm = $('listing-form');
			if (listingForm) {
			  $('listing_address1').observe('change', Map.showLocation);
  			$('listing_city').observe('change', Map.showLocation);
  			$('listing_province').observe('change', Map.showLocation);
  			$('listing_postal').observe('change', Map.showLocation);
  			marker = new GMarker(centerLocation, {draggable:true});
  			GEvent.addListener(marker, "dragstart", function() {
  				map.closeInfoWindow();
  			});
  			GEvent.addListener(marker, "dragend", function() {
  				Map.updateCoords(marker.getPoint());
  				Map.provideFeedback(marker.getPoint());
  			});
		  } else {
		    // set listeners to open up the bubble with a link to directions, maybe?
		    marker = new GMarker(centerLocation, {draggable:false});
		  }
		  map.addOverlay(marker);
  	}
  },
  
  provideFeedback: function(point) {
    if (point) {
			$('feedback').update("<p>Location updated!</p>");
		} else {
			$('listing_latitude').value = "";
    	$('listing_longitude').value = "";
			$('feedback').update("<p>Sorry, we were unable to locate that address.</p>");
		}
		$('feedback').appear({queue:{scope:'mapfb'}, duration:0.3});
		$('feedback').highlight({queue: {scope:'mapfb'}});
		$('feedback').fade({queue:{scope:'mapfb', position:'end'}, duration:0.3, delay:3});
  },
  
  updateCoords: function(point) {
  	$('listing_latitude').value = point.lat();
  	$('listing_longitude').value = point.lng();
  },
  
  showLocation: function() {
  	var address1 = $F('listing_address1');
  	var city = $F('listing_city');
  	var state = $F('listing_province');
  	var zip = $F('listing_postal');
  	var fullAddress = address1+", "+city+", "+state+" "+zip+", USA";
  	geocoder.getLocations(fullAddress, Map.addAddressToMap);
  	if (address1 != "") {
			map.setZoom(17);
		}
  },
  
  addAddressToMap: function(response){
  	if (!response || response.Status.code != 200){ 
  		alert("Sorry, we could not find that location.");
  	} else {
  		var place = response.Placemark[0];
  		var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
  		Map.updateCoords(point);
  		marker.setLatLng(point);
  		map.panTo(point);
  		Map.provideFeedback(marker.getPoint());
  	}	
  }
}


var News = {
  toggle: function(open) {
    var targetOpen = $(open);
    $$('.opened').each(function(o) {
      if (o !== targetOpen) {
        o.blindUp({duration:0.3});
        o.fade({duration:0.3});
        o.addClassName('collapsed');
        o.removeClassName('opened');
      }
    });
    if (targetOpen.classNames().toArray().indexOf('collapsed') != -1) {
      targetOpen.blindDown({duration:0.5});
      targetOpen.appear({duration:0.5});
      targetOpen.addClassName('opened');
      targetOpen.removeClassName('collapsed');
    }
  }
}

var Report = {
	validate: function() {
		var organization = $('grant_report_organization');
    var award = $('grant_report_award');
    var deadline = $('grant_report_deadline');
    var report = $('grant_report_document');
    var reportSubmit = $('report_submit');
    var loadIcon = $('loadicon');
    var errors = "";
    if (organization.value == "") {
	    organization.addClassName('fieldError');
			errors += "* Please enter your name/organization.\n";
		} 
		if (award.value == "") {
		  award.addClassName('fieldError');
			errors += "* Please enter the grant amount.\n";
		}
		if (deadline.value == "") {
		  deadline.addClassName('fieldError');
			errors += "* Please enter the report deadline.\n";
		}
		
		if (errors == "") {
		  reportSubmit.disabled = true;
		  loadIcon.show();
		  return true
		} else {
		  alert(errors);
		  return false;
		}
	},
	
	setup: function() {
		// set up the calendars
    Calendar.setup({dateField:'grant_report_deadline'});
	}
}

// -------------------------
// Multiple File Upload
// -------------------------
function MultiSelector(list_target, max) {
  this.list_target = list_target;this.count = 0;this.id = 0;if( max ){this.max = max;} else {this.max = -1;};this.addElement = function( element ){if( element.tagName == 'INPUT' && element.type == 'file' ){element.name = 'attachment[file_' + (this.id++) + ']';element.multi_selector = this;element.onchange = function(){var new_element = document.createElement( 'input' );new_element.type = 'file';this.parentNode.insertBefore( new_element, this );this.multi_selector.addElement( new_element );this.multi_selector.addListRow( this );this.style.position = 'absolute';this.style.left = '-1000px';};if( this.max != -1 && this.count >= this.max ){element.disabled = true;};this.count++;this.current_element = element;} else {alert( 'Error: not a file input element' );};};this.addListRow = function( element ){var new_row = document.createElement('li');var new_row_button = document.createElement( 'a' );new_row_button.title = 'Remove This Image';new_row_button.href = '#';new_row_button.innerHTML = 'Remove';new_row.element = element;new_row_button.onclick= function(){this.parentNode.element.parentNode.removeChild( this.parentNode.element );this.parentNode.parentNode.removeChild( this.parentNode );this.parentNode.element.multi_selector.count--;this.parentNode.element.multi_selector.current_element.disabled = false;return false;};new_row.innerHTML = element.value.split('/')[element.value.split('/').length - 1];new_row.appendChild( new_row_button );this.list_target.appendChild( new_row );};
}

Event.observe(window, 'dom:loaded', Global.setup);