// JavaScript Document

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function validateLogin(my_form){
	if(!isEmail(my_form.elements['username'].value.trim())){
		my_form.elements['username'].focus();
		alert("You must provide a valid email.");
	}
	else if(my_form.elements['password'].value.trim() == ""){
		my_form.elements['password'].focus();
		alert("You must provide a password.");
	}
	else{
		php_get("","","/login/check.php","checkLogin","username=" + encodeURIComponent(my_form.elements['username'].value) + "&password=" + encodeURIComponent(my_form.elements['password'].value));
	}
	return false;
}

function php_return(action, value){
	var result = value.getElementsByTagName("result")[0].firstChild.nodeValue.trim();

	if(action == "checkLogin"){
		if(result == "1"){
			document.getElementById("frm_login").submit();
		}
		else{
			document.getElementById('frm_login').elements['password'].focus();
			alert("Invalid login provided.");
		}
	}
	else if(action == "checkPasscode"){
		if(result == "1"){
			document.getElementById('frm_passcode').submit();	
		}
		else{
			alert("Invalid Passcode Provided.");	
		}
	}
}


function focusLabels() {
  if (!document.getElementsByTagName) return false;
  var labels = document.getElementsByTagName("label");
  for (var i=0; i<labels.length; i++) {
    if (!labels[i].getAttribute("for")) continue;
    labels[i].onclick = function() {
      var id = this.getAttribute("for");
      if (!document.getElementById(id)) return false;
      var element = document.getElementById(id);
      element.focus();
    }
  }
}

function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == this.defaultValue) {
	  if (this.getAttribute("type") == "text" || this.getAttribute("type") == "textarea") {
        this.value = "";
	  }
     }
    }
    element.onblur = function() {
      if (this.value == "") {
        this.value = this.defaultValue;
      }
    }
  }
}



function isFilled(field) {
  if (field.value.length < 1 || field.value == field.defaultValue) {
    return false;
  } else {
    return true;
  }
}

function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
    resetFields(thisform);
    
  }
}

addLoadEvent(focusLabels);
addLoadEvent(prepareForms);