/**
 * @author allanos | tallerdelsoho
 */

var Ajax = false;

function AjaxRequest(){	
	if(window.XMLHttpRequest){
		Ajax = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			Ajax = new ActiveXObject('Msxml.XMLHTTP');        
		} catch(e) {
			try{
				Ajax = new ActiveXObject('Msxml.XMLHTTP');        
			} catch(e) {
               try {
					Ajax = new ActiveXObject('Microsoft.XMLHTTP');                
				} catch(E) {
					Ajax = false;
				}
			}
		}
	}
}

function showProcess(){
	var mysending = document.getElementById('sending');
	var myform = document.getElementById('rightform');
	var myleft = document.getElementById('leftform');
	var mythanks = document.getElementById('formsended');

	var p = document.createElement('p');
								
	if(Ajax.readyState==4){		
		if(Ajax.status==200){
			xml = Ajax.responseXML;
			if(xml.hasChildNodes()){
				var myresp = xml.getElementsByTagName('title').item(0).firstChild.data;
				
				if (myresp == 'Sending'){
					mysending.style.display = 'none';
					myform.style.display = 'none';		
					myleft.style.display = 'none';
					mythanks.style.display = 'block';
					setTimeout('Close()',2000);
				} else {
					if(myresp == 'no_data') {
						var txt = document.createTextNode('*This is not a valid email address.');
					} else {
						var txt = document.createTextNode('*The server is too busy please try again later.')
						mysending.style.display = 'none';
						myform.style.display = 'block';
						p.style.color = 'red';
						p.appendChild(txt);					
						myform.appendChild(p);
					}
				}
			} else {
				alert ('XML: NO Nodes')
			}
		} else {
			alert('Error: '+Ajax.status);
		}
	} else {
		mysending.style.display = 'block';
		myform.style.display = 'none';		
		myleft.style.display = 'block	';
		mythanks.style.display = 'none';
	}	
}

function envia(nameto, email, bodytext, url){
	
	AjaxRequest();
	strData = 'nameto='+escape(nameto)+
		'&email='+escape(email) +
		'&bodytext='+escape(bodytext);
	if(!Ajax){
		alert('ajax its no working');
		return;
	}	
	Ajax.open('GET', url+'ajax2mail.php?'+strData, true);
	Ajax.onreadystatechange = showProcess;
	//Ajax.onreadystatechange = alertMe('ok Ajax');

	Ajax.send(null);
	//alert(strData);
}

function alertMe(mytext){
	alert(mytext);
}

function writedira(usr, dom, holder) {

//OK
//var eml = unescape(usr + dom);
//OK
//var eml = usr + dom;
var eml = escape(unescape(usr + dom));

var myholder = document.getElementById(holder);
var myp = document.createElement('p');
myp.className = "textcont";

var emltext = document.createTextNode(eml);

var myplink = document.createElement('a');
myplink.setAttribute('href', 'mailto:' + eml);
myplink.appendChild(emltext);

myp.appendChild(myplink);
myholder.appendChild(myp);

}

function writedir(usr, dom, holder) {

//OK
//var eml = unescape(usr + dom);
//OK
//var eml = usr + dom;
var eml = usr + ' (at) ' + dom + ' (dot) es ';

var myholder = document.getElementById(holder);
var myp = document.createElement('p');
myp.className = "textcont";

var emltext = document.createTextNode(eml);

myp.appendChild(emltext);
myholder.appendChild(myp);

}

//Validation

function validaext(){
	var d = document.frmcontact;
	if(d.nameto.value == "" || d.email.value == "" ||  d.bodytext.value == "") {
		alert('Todos los campos son necesarios. | All fields are required.\nPor Favor, intentalo de nuevo. | Please, try again.');
	} else {
		envia(d.nameto.value, d.email.value, d.bodytext.value, '../ajax2mail/');
	}
}

function validafrm(el){
	var d = el;
	if(d.nameto.value == "" || d.email.value == "" ||  d.bodytext.value == "") {
		alert('Todos los campos son necesarios. | All fields are required.\nPor Favor, intentalo de nuevo. | Please, try again.');
	} else {
		envia(d.nameto.value, d.email.value, d.bodytext.value, '../ajax2mail/');
	}
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

function getEmailSubmit() {
	var f = document.forms.getEmail;
	f.submit();
};

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;
  msg (ifld, 'warn', '');
  return true;
};

function checkit() {
	
	var elem;
    var errs=0;
        
    if (document.frmcontact.nameto.value == '') {
    alert("No value");
    } else {
    alert(document.frmcontact.nameto.value);
    }
 
 	if (!validatePresent (document.forms['frmcontact'].nameto, 'nameto_error_id')) errs += 1;
 	if (!validatePresent (document.forms['frmcontact'].email, 'email_error_id')) errs += 1;
 	if (!validatePresent (document.forms['frmcontact'].bodytext, 'bodytext_error_id')) errs += 1;
 		
	//if (!validateEmail (document.forms.frmcontact.email, 'email_error_id', true)) errs += 1; 

    if (errs==0) {
		//getEmailSubmit();
		envia(document.forms.frmcontact.nameto.value, document.forms.frmcontact.email.value, document.forms.frmcontact.bodytext.value, '../ajax2mail/');

		//alert("OOK");
    } else if (errs==1) {
    	alert('Revisa por favor el formulario!.Hay un error en uno de los datos introducidos.');
    } else {
    	alert('Revisa por favor el formulario!.Hay  errores en varios datos introducidos.');
    }
    
	return (errs==0);
	
};

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
	if (!document.getElementById) return true;  // not available on this browser - leave validation to the server
  
	var elem = document.getElementById(ifld);
	if (!elem.firstChild) return true;  // not available on this browser 
	
  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, 'error', 'ERROR: REQUERIDO!!');
      setfocus(vfld);
      return false;
    } else {
      msg (ifld, 'warn', '');   // OK
      return true;  
    }
  }
  return proceed;
};

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
  if (!email.test(tfld)) {
    msg (ifld, 'error', 'ERROR: REQUERIDO!!');
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, 'warn', 'ERROR: Email NO valido!!');
  else
    msg (ifld, 'warn', '');
  return true;
};
