var RESET_COLOR = 'transparent';
var ERROR_COLOR = '#ffd8d8';
var SITE_ROOT = '/';

var EMAIL_FIELD = 'EMAIL';
/**
 * Validates the given form against the rules set forth. Submits the form if no errors, otherwise displays errors.
 * @author vic <vic@newlegendmedia.com>
 * @param form_id The ID of the form (the attribute id, not the value set up in the configuration) to validate.
 * @retval bool Returns true.
 */
function validateFormMC(form_id, directory) {
  SITE_ROOT = directory;
	var form = $$(form_id);

	var error_count = 0;
	
	if ( !form ) {
		return false;
	}
	
	/**
	 * Take care of password and text inputs.
	*/
	var inputs = form.getElementsByTagName('input');
	var i = 0;
	var len = inputs.length;

	var radio_errors = new Object();
	var temp_error = false;
	
	for ( i=0; i<len; ++i ) {
		switch ( inputs[i].type ) {
			case 'file':
			case 'password':
			case 'text': {
				inputs[i].style.backgroundColor = RESET_COLOR;
				inputs[i].className = "text";

				resetError(inputs[i].name);
				
				temp_error = false;
				if ( true == isRequired(inputs[i]) ) {
					// If it's an email address, it requires further validation
					// otherwise, it just has to have a value.
					if ( -1 != inputs[i].name.indexOf(EMAIL_FIELD) ) {
						if ( false == isEmail(inputs[i].value) ) {
							temp_error = true;
						}
					} else {
						if ( inputs[i].value.length < 1 ) {
							temp_error = true;
						}
					}
					
					if ( true == temp_error ) {
						//inputs[i].style.backgroundColor = ERROR_COLOR;
						inputs[i].className += ' warning';
						error_count++;
						showError(inputs[i].name);
					}
				}

				break;
			}

			case 'radio': {
				if ( 'undefined' == typeof radio_errors[inputs[i].name] ) {
					radio_errors[inputs[i].name] = true;
				}

				// First, you have to see if any of the radio buttons were checked
				if ( true == reqRadio(inputs[i]) ) {
					radio_errors[inputs[i].name] = false;
				}

				break;
			}
		}
	}
	
	// Foreach radio button group, if any are unchecked, show an error
	for ( var name in radio_errors ) {
		resetError(name);
		if ( true == radio_errors[name] ) {
			error_count++;
			showError(name);
		}
	}
	
	/**
	 * Take care of selects/dropdowns.
	*/
	var selects = form.getElementsByTagName('select');
	len = selects.length;
	for ( i=0; i<len; ++i ) {
		selects[i].style.backgroundColor = RESET_COLOR;
		resetError(selects[i].name);
		
		if ( false == isValid(selects[i]) ) {
			selects[i].style.backgroundColor = ERROR_COLOR;
			showError(selects[i].name);
			error_count++;
		}
	}
	
	/**
	 * And text areas.
	*/
	var tas = form.getElementsByTagName('textarea');
	len = tas.length;
	for ( i=0; i<len; ++i ) {
		tas[i].style.backgroundColor = RESET_COLOR;
		resetError(tas[i].name);
		
		if ( false == isValid(tas[i]) ) {
			tas[i].style.backgroundColor = ERROR_COLOR;
			showError(tas[i].name);
			error_count++;
		}
	}
	
	
	if ( 0 == error_count ) {
		//form.submit();
		signup(form);
	}
}

/**
 * Display an error element.
 * @author vic <vic@newlegendmedia.com>
 * @param name The name of the field to show the error for.
 * @retval boolean Returns true.
 */
function showError(name) {
	//$$('error_' + name).style.display = 'block';
	return true
}

function resetError(name) {
	var e = $$('error_' + name);
	
	if ( e != null ) {
		e.style.display = 'none';
	}
}

function $$(e) { return document.getElementById(e); }

function isValid(e) {
	if ( true == isRequired(e) ) {
		if ( e.value.length > 0 ) {
			return true;
		}
	} else {
		return true;
	}
	
	return false;
}


/**
 * Determines if an input is required.
 * @author vic <vic@newlegendmedia.com>
 * @retval boolean True if an element is required, false otherwise.
 */
function isRequired(e) {
	if ( null != e.getAttribute('required') ) {
		if ( 1 == e.getAttribute('required') ) {
			return true;
		}
	}
	
	return false;
}

/**
 * Determines if a radio button is required and has a value.
 * @author vic <vic@newlegendmedia.com>
 * @param e The element of type radio button check.
 * @retval boolean True if a radio button is required and is checked, true if it's not required, false if its required and not checked.
 */
function reqRadio(e) {
	if ( true == isRequired(e) ) {
		if ( true == e.checked ) {
			return true;
		}
	} else {
		return true;
	}
	
	return false;
}

/**
 * Determines if a string is a valid email or not, handles most email addresses according to the RFC's.
 * @author vic <vic@newlegendmedia.com>
 * @param email The email string to test against.
 * @retval boolean True if the string is an email, false otherwise.
 */
function isEmail(email) {
	var email_regex = /([a-z0-9-_.!#$%^&*~`]+)(@[a-z0-9-]+\.[a-z]+)/i;
	var regex = new RegExp(email_regex);
	
	return regex.test(email);
}



//-------------------


var ajaxRequest;

function makeRequest() { 
  try {
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				//alert("Your browser broke!");
				return false;
			}
		}
	}
}

function signup(form) {
  makeRequest();
  
  var EMAIL;
  var FNAME;
  var LNAME;
  var mode;
  
  if ( form.FNAME.value == 'First Name' ) {
    form.FNAME.className += ' warning';    
    return false;
  }
  else if ( form.LNAME.value == 'Last Name' ) {
    form.LNAME.className += ' warning';
    return false; 
  }
  
  if( form.EMAIL ) {
    EMAIL = form.EMAIL.value;
  } else {
    EMAIL = form.EMAILupper.value;
    mode = 'upper';
  }
  
  if( form.FNAME ) {
    FNAME = form.FNAME.value;
  } else {
    FNAME = form.FNAMEupper.value;
    mode = 'upper';    
  }
  
  if( form.LNAME ) {
    LNAME = form.LNAME.value;
  } else {
    LNAME = form.LNAMEupper.value;
    mode = 'upper';    
  }  
  
  responseLocation = 'live-response';
  if ( 'upper' == mode ) {
    responseLocation = 'live-response-upper'; 
  }
  
  
  ajaxRequest.onreadystatechange = function(){
   	if(ajaxRequest.readyState == 0){ //uninitialized
     }
   	
     else if(ajaxRequest.readyState == 1){ //loading 
       $$(responseLocation).className = 'going-good';
       $$(responseLocation).innerHTML = 'Signing up...';
     }
     
     else if(ajaxRequest.readyState == 2){ } //loaded
     
     else if(ajaxRequest.readyState == 3){ } //interactive
   
     else if(ajaxRequest.readyState == 4){ //complete
      result = ajaxRequest.responseText;
      
      if ( 1 == result ) {
     	  $$(responseLocation).innerHTML = 'Thank you for signing up!';
     	  //window.location='/pages/bonus.html';
      }
      else if ( 214 == result ) { // Already signed up for MC List
        $$(responseLocation).className = 'going-bad';        
        $$(responseLocation).innerHTML = 'You are already signed up for the newsletter!';
        //window.location='/pages/bonus.html';
      }
      else {
        $$(responseLocation).className = 'going-bad';        
        $$(responseLocation).innerHTML = 'Something went wrong, please try again later';
      }
     }
   }
     
   var query = SITE_ROOT + 'mc_signup.php?EMAIL=' + EMAIL + ( ('' != FNAME) ? '&FNAME=' + FNAME : '') + ( ('' != LNAME) ? '&LNAME=' + LNAME : '');
   
   //alert(query);
     
   ajaxRequest.open('GET', query, true);
   ajaxRequest.send(null); 
}
