$(function(){
	stylesheet();
	photoHeader();
	doclear();
	press();
	language();
	faq();
});

// array of random images
imagesArray = new Array('courthouse.jpg', 'courthouse2.jpg', 'paul.jpg', 'talking.jpg');

function stylesheet(){
	// chrome
	if (jQuery.browser.chrome) {
		$('head').append("<link type='text/css' rel='stylesheet' href='/style/chrome.css'>");
	}

	// ff 3.5, windows
	if ($.browser.mozilla && ($.browser.version.substr(0, 5) == '1.9.1') && (navigator.appVersion.indexOf("Win")!=-1)) {
		$('head').append("<link type='text/css' rel='stylesheet' href='/style/ff35win.css'>");
	}
}

function photoHeader(){
	// handle the index slideshow
	if ($('#photo').attr('class') == 'index') {
		// add the second and third images, displaying none
		$('#photo').append('<img src="/images/header/index3.jpg" style="display: none;"><img src="/images/header/index2.jpg" style="display: none;">');
		
		// preload the first image
		$('<img />').attr('src', '/images/header/index1.jpg').load(function(){
			// set the image's display to none
			$(this).css('display', 'none');
			
			// add it to the photo div
			$('#photo').append($(this));
			
			// fade in all the pictures, index first
			$(this).fadeIn('slow', function(){
				$('#photo img').css('display', 'block');
			});
			
			// wait
			$(this).animate({opacity: 1}, 2000, function(){
				// fade out the 1st image
				$('#photo img:last').fadeOut(2000, function(){
					// remove that image
					$(this).remove();

					// wait
					$('#photo img:last').animate({opacity: 1}, 2000, function(){
						// fade out the second image
						$('#photo img:last').fadeOut(2000);
					});
				});
			});
		});
	} else if ($('#photo').attr('class') == 'random') {

		// pick a random image
		image = imagesArray[Math.round(Math.random()*(imagesArray.length-1))];
		src = '/images/header/random/' + image;
		
		if (!$.browser.msie) {
			// preload and fade the new image in
			$('<img />').attr('src', src).load(function(){
				// set the image's display to none
				$(this).css('display', 'none');

				// add it to the photo div
				$('#photo').append($(this));

				// fade in the picture
				$(this).fadeIn('medium');
			});
		} else {
			// ie instructions
			src = '<img src=' + src + ' alt="heder">';
			$('#photo').append(src);
		}
	}
}

// handle input with default values
function doclear(){
	$('.doclear').each(function(){
		$(this).val($(this).attr('title'));
		
		// clear the $(this) on focus if default value
		$(this).focus(function(){
			if ($(this).val() == $(this).attr('title')) {
				$(this).val('');
			}
		});
		
		// reset the $(this) on blur if blank
		$(this).blur(function(){
			if ($(this).val() == '') {
				$(this).val($(this).attr('title'));
			}
		});
	});
}

// slideup and down press
function press(){
	$('.press').click(function(){
		content = $(this).next('.pressContent');
		if (content.css('display') == 'none') {
			content.slideDown('medium');
		} else {
			content.slideUp('medium');
		}
	});
}

// expanding and contracting faqs
function faq(){
	$('.question').click(function(){
		answer = $(this).next('.answer');
		
		if (answer.css('display') == 'none') {
			answer.slideDown('medium');
			return false;
		} else {
			answer.slideUp('medium');
			return false;
		}
	});
}





// ====================
// = Functions called =
// ====================

function validateContact(){
	// get variables from form
	email = $('#contactEmail').val();
  name = $('#contactName').val();
	phone = $('#contactPhone').val();
	website = $('#contactWebsite').val();
  message = $('#contactMessage').val();
	
	// spanish or english?	
	if ($('#contactFlash').attr('class') == 'english') {
		english = true;
	} else {
		english = false;
	}
	
	// set valid flag
	valid = true;
		
	// name
  // if (name == '' || name == $('#contactName').attr('title')) {
  //  valid = false;
  //  if (english) {
  //    $('#contactNameError').html('Please enter your name.').fadeIn('medium');
  //  } else {
  //    $('#contactNameError').html('Por favor escriba su nombre.').fadeIn('medium');
  //  }
  // } else {
  //  $('#contactNameError').html('').fadeOut('medium');
  // }

	if (email == '' || email == $('#contactEmail').attr('title')) {
    if (!validateContactPhone()) {
      if (english) {
        $('#contactMessageError').html('Please enter your phone number or email address.').fadeIn('medium');
      } else {
        $('#contactMessageError').html('Por favor, introduzca su n&uacute;mero de tel&eacute;fono o direcci&oacute;n de correo electr&oacute;nico.').fadeIn('medium');
      }
      valid = false;
    } else {
      $('#contactMessageError').fadeOut('medium');
    }
  }
  
  if (phone == '' || phone == $('#contactPhone').attr('title')) {
    if (!validateContactEmail()) {
      if (english) {
        $('#contactMessageError').html('Please enter your phone number or email address.').fadeIn('medium');
      } else {
        $('#contactMessageError').html('Por favor, introduzca su n&uacute;mero de tel&eacute;fono o direcci&oacute;n de correo electr&oacute;nico.').fadeIn('medium');
      }
      valid = false;
    } else {
      $('#contactMessageError').fadeOut('medium');
    }
  }
	
	// website
	if (website != '') {
		valid = false;
	}

	// message
  // if (message == '' || message == $('#contactMessage').attr('title')) {
  //  valid = false;
  //  if (english) {
  //    $('#contactMessageError').html('Please describe your legal issue.').fadeIn('medium');
  //  } else {
  //    $('#contactMessageError').html('Por favor, describa su problema legal.').fadeIn('medium');
  //  }
  // } else {
  //  $('#contactMessageError').html('').fadeOut('medium');
  // }
	
	if (valid == false) {
		return false;
	} else {
		// append the sender's info to the message
		message += '\n\nsubmitted name: ' + name + '\nsubmitted email: ' + email + '\nsubmitted phone: ' + phone;

		// send email
		$.ajax({
			type: 'POST',
			data: "from=" + email + "&message=" + message,
			url: "/api/contactEmail.php",
			success: function(data) {
				if (data == '1') {
					if (english) {
						$('#contactFlash').css('display', 'none').css('color', 'green').html('Your message was sent successfully. Thank you!').fadeIn('medium');
					} else {
						$('#contactFlash').css('display', 'none').css('color', 'green').html('Tu mensaje ha sido enviado con &eacute;xito. &iexcl;Gracias!').fadeIn('medium');
					}
				} else {
					alert(data);
				}
			}
		});
	}
}

function validateContactEmail(){
  email = $('#contactEmail').val();

  // email
	if (email == '' || email == $('#contactEmail').attr('title')) {
		return false;
	} else {
	  if (emailIsValid(email) == false){
			if (english) {
				$('#contactEmailError').html('Your email address is invalid.').fadeIn('medium');
			} else {
				$('#contactEmailError').html('Su direcci&oacute;n de correo electr&oacute;nico no es v&aacute;lida.').fadeIn('medium');
			}
			return false;
		} else {
			$('#contactEmailError').html('').fadeOut('medium');
	    return true;
		}
	}
}

function validateContactPhone(){
	phone = $('#contactPhone').val();

	// phone
	if (phone == '' || phone == $('#contactPhone').attr('title')) {
		return false;
	} else {
		return true;
	}
}

function validatePayment(){
	if ($('#name').val() == ''){
		$('#nameError').fadeIn('medium');
		return false;
	}
}

function language(){
	$('#en').click(function(){
		$.cookie("language", "en", { expires: 30 });
		location.reload(); 
	});
	
	$('#es').click(function(){
		$.cookie("language", "es", { expires: 30 });
		location.reload(); 
	});
	
	// check url for language marker
	if (location.href.match(/lang=es/)) {
		$.cookie("language", "es", { expires: 30 });
		pageLoaded = location.pathname;
    window.location = location.protocol + '//' + location.host + pageLoaded;
	}
}

// is the string a valid email address?
function emailIsValid(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false;
	}
	if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false;
	}
 	return true;			
}