var Navnemaskinen = {

  // Sets the value of node to text if the existing value is blank
  setHelpText: function(node, text) {
    node = $(node)
    if (node.getValue() == '') {
      node.setValue(text)
    }
  },

  clearHelpText: function(node, text) {
    node = $(node)
    if (node.getValue() == text) {
      node.setValue('')
    }
  },

  applyHelpTexts: function() {
    helpText = 'Skriv evt. efternavn'
    node = $('#crit_last_name')
    node.bind('focus', function(event) { 
      Navnemaskinen.clearHelpText(event.target, helpText)
    })
    node.bind('blur', function(event) { 
      Navnemaskinen.setHelpText(event.target, helpText)
    })
    this.setHelpText('#crit_last_name', helpText)
  },

  // Makes the help links toggle the help text of their fieldset
  enableHelpLinks: function() {
    // Remove old event handlers, hook up new ones, and show the Help links
    $('fieldset a.help').show().unbind('click').bind('click', function(event) {
			// Find the help text and show it
      $(event.target).parents('fieldset').each(function(index, element){
				help_id = element.id + '_help'

				// Position the help text
				helpElement = $('#' + help_id)
				Navnemaskinen.placeCenteredAbove(helpElement, event.target)

				// Show the help text 
				helpElement.toggle()
			})

      // Make sure the link doesn't actually trigger
      return false
    })
    // Hook up all the Close links and show them
    $('div.help a.close').show().unbind('click').bind('click', function(event) {
      // Find the help text of the parent and show it
      $(event.target).parents('div.help').toggle()

      // Make sure the link doesn't actually trigger
      return false
    })
  },
  
  // Makes the reset links reset the relevant form fields
  enableResetLinks: function() {
    // Hook up all the Reset links and show them
    $('fieldset a.reset').show().bind('click', function(event) {
      // Find the form fields of the parent and reset them - or rather, set them to a blank value
      $(event.target).parents('fieldset').find('input').setValue('')
      $(event.target).parents('fieldset').find('select').each(function(index, element) { element.selectedIndex = 0 })

      // Reinsert any inline help texts
      Navnemaskinen.applyHelpTexts()

      // Make sure the link doesn't actually trigger
      return false
    })
  },
  
	// Runs validations, returns false if an error occurs
	validate: function() {
		// Remove "helpful" text messages from the fields
		this.clearHelpText('#crit_last_name', 'Skriv evt. efternavn')

		errors = new Array()

		criteriaFound = false
		// Mindst én søgemulighed skal være valgt
		$('fieldset input, fieldset select').each(function(index, element) {
			criteriaFound = criteriaFound || ($(element).getValue() != '')
		})
		if (!criteriaFound) {
			errors.push('Du skal vælge mindst én søgemulighed for at lave en søgning')
		}

		// Søgemulighed "Korte navne": Det indtastede skal være et heltal større end nul.
		field = $($('#crit_max_len')[0])
		if (field.getValue() && !Validations.isPositiveInteger(field.getValue())) {
			errors.push('For at søge på korte navne, skal du udfylde et tal større end nul')
		}

		// Søgemulighed "Lange navne":  Det indtastede skal være et heltal større end nul.
		field = $($('#crit_min_len')[0])
		if (field.getValue() && !Validations.isPositiveInteger(field.getValue())) {
			errors.push('For at søge på lange navne, skal du udfylde et tal større end nul')
		}

		// Søgemulighed "Sjældne navne":  Det indtastede skal være et heltal større end nul.
		field = $($('#crit_rarity')[0])
		if (field.getValue() && !Validations.isPositiveInteger(field.getValue())) {
			errors.push('For at søge på sjældne navne, skal du udfylde et tal større end nul')
		}

		// Søgemulighed "Numerologi": 
		selector = $($('#crit_expr_num')[0])
		field = $($('#crit_last_name')[0])

		// Efternavn udfyldt med navnetal ikke valgt.
		if (selector.getValue() == '' && field.getValue() != '') {
			errors.push('Du skal også vælge et navnetal for at søge på numerologi')
		}
		
		if (errors.length > 0) {
			// Build the error messages
			messages = ''
			$(errors).each(function(index, message){
				messages = messages + '<li>' + message + '</li>'
			})
			messages = '<ul>' + messages + '</ul>'
			
			// Add them to the error element
			errorsElement = $('#validation .messages').empty().append(messages)

			Navnemaskinen.placeCenteredAbove('#validation', 'form .actions input:image')

			// Show the error element
			$('#validation').show()
			return false
		} else {
			// Everything went well, please continue
			return true
		}
	},

	placeCenteredAbove: function(elementToPlace, aboveElement) {
		elementToPlace = $(elementToPlace)
		aboveElement = $(aboveElement)
		
		// Position the element relative to #content
		contentOffset = $('#content').offset()

		elementToPlace.css('left', (aboveElement.offset().left + aboveElement.width() / 2 - contentOffset.left - elementToPlace.width() / 2) + 'px')
		elementToPlace.css('top', (aboveElement.offset().top - contentOffset.top - elementToPlace.height()) + 'px')
	},

  // pre-submit callback 
  validateRequest: function(formData, jqForm, options) { 
		$('#validation').hide()
		return Navnemaskinen.validate()
  },

  // Turns the form into an Ajax form
  ajaxify: function() {
    var options = { 
      target:        '#results',   // target element(s) to be updated with server response 
      beforeSubmit:  Navnemaskinen.validateRequest,  // pre-submit callback 
      success:       function() {
				Navnemaskinen.enableHelpLinks()
				if (pageTracker) {
					pageTracker._trackPageview("/resultat")
				}
			}
    }; 

    // bind form using 'ajaxForm' 
    $('#navnemaskinen form').ajaxForm(options); 
  },

  // Makes the Navnemaskinen search interface work
	initForm: function() {
    this.applyHelpTexts()
    this.enableHelpLinks()
    this.enableResetLinks()
  },

	updateEmailValue: function(valueElement, targetElement, defaultText) {
		value = $(valueElement).getValue()
		
		if (value && value != '') {
			$(targetElement).text(value)
		} else {
			$(targetElement).text(defaultText)
		}
	},

	updateEmailBody: function() {
		this.updateEmailValue('#send_names #name', "#mail_body .sender", '<dit navn her>')
		this.updateEmailValue('#send_names #email', "#mail_body .recipient", '<modtagers email her>')
	},
	
	initSendNames: function() {
    // Ajaxify the form
    $('#send_names form').ajaxForm({
      target: '#send_names_response',
			beforeSubmit: function() {
				$('#send_names_response').text('').hide()
				$('#send_names_errors').text('').hide()
			},
      success: function(responseText) {
				// The request succeeded and there was much rejoicing
				$('#send_names_response').text(responseText).show();
				setTimeout("Navnemaskinen.closeSendNames()", 4000)
			},
      error: function(request, textStatus, errorThrown) { 
				// An error occurred, show the failure message
				$('#send_names_errors').text(request.responseText).show();
			}
    })

		// Allow the window to close
    $('#send_names a.close').bind('click', function() {
			Navnemaskinen.closeSendNames()
      // Make sure the link doesn't actually trigger
      return false
    })

		// Make the email body update when the name changes
		$('#send_names #name, #send_names #email').bind('keyup', function() {
			Navnemaskinen.updateEmailBody()
		}).bind('blur', function() {
			Navnemaskinen.updateEmailBody()
		})
	},

	// Closes the Send Names window
	closeSendNames: function() {
		$('#send_names_response').text('').hide()
		$('#send_names_errors').text('').hide()
		Navnemaskinen.hideOverlay()
	},

	showOverlay: function(element) {
		if ($.browser.msie) {
			// IE6 always render select boxes topmost, which looks terrible
			$('select').css('visibility', 'hidden')
		}
		
		$('#overlay .contents').hide()
		
    // Position the overlay properly
    $('#overlay').height($(document).height())

    // Show the overlay
    $('#overlay').show()

		if (element) {
			// and the specified element
			$(element).show()
		}
	},

	hideOverlay: function() {
		if ($.browser.msie) {
			// Bring the IE6 select boxes back
			$('select').css('visibility', '')
		}

		$('#overlay > .contents').hide()
		$('#send_names_window').hide()
		$('#overlay').hide()
	}
}
