/*=============================================================================
    FORM FUNCTIONS
==============================================================================*/
function validateContactForm()
{
	clearError();
	var check = checkInput("contact_first_name","Wpisz Imię") &&
	checkInput("contact_last_name","Wpisz Nazwisko") &&
	checkInput("contact_email","Wpisz swój adres Email") &&
	checkEmail("contact_email","Wpisz poprawny adres Email") &&
	checkTextarea("contact_message","Wpisz Wiadomość");

	return check && sendContactForm();
}

function sendContactForm()
{
	var req = false;

	 req = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         req = new XMLHttpRequest();
         if (req.overrideMimeType) {
            req.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!req) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }

	var url = 'send.php';
    var data = "contact_first_name=" + document.getElementById("contact_first_name").value
    + "&contact_last_name=" + document.getElementById("contact_last_name").value
    + "&contact_company=" + document.getElementById("contact_phone").value
    + "&contact_phone=" + document.getElementById("contact_phone").value
    + "&contact_email=" + document.getElementById("contact_email").value
    + "&contact_message=" + document.getElementById("contact_message").value
    + "&mode=ajax";

	req.open("POST", url, true );
	
	// opera <= 8.5
	try
	{
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", data.length);
		req.setRequestHeader("Connection", "Zamknij");
	}
	catch(e)
	{
		return true;
	}

	// process function
 	req.onreadystatechange=function()
 	{
  		if (req.readyState == 4)
  			if(req.status == 200)
  			{
  				if(req.responseText=="true")
	  				myAlert("Twoja wiadomość została wysłana!<br/>Dziękujemy!");
  				else
	  				myAlert("Przepraszamy!<br/>Wystąpił błąd w trakcie wysyłania. Twoja wiadomość nie została wysłana. Jeśli błąd będzie się powtarzał, prosimy o powiadomienie nas poprzez tradycyjne formy kontaktu.<br/>Dziękujemy!");
  			}
	}

	// send request
	req.send(data);

	return false;
}

addEvent(window,'load',function() {
		document.getElementById("contact_form").onsubmit = validateContactForm;
		document.getElementById("label_contact_submit").onclick = function(e)
		{
			e = e||event;
			e.cancelBubble = true;
			if(validateContactForm())
				document.getElementById("contact_form").submit();
			return false;
		}
	} );

/*=============================================================================
    FORM VALIDATION
==============================================================================*/
function checkInput(inputId, errorMessage)
{
	var input = document.getElementById(inputId);
	if(!input)
	{
		alert( "Input " + inputId + " not found!");
		return false;
	}

	if( input.value == "" )
    	return focusFailedInput(inputId,errorMessage);

    return true;
}

function checkTextarea(inputId, errorMessage)
{
	var input = document.getElementById(inputId);
	if(!input)
	{
		alert( "Textarea " + inputId + " not found!");
		return false;
	}

	if( input.value.length <= 1 )
    	return focusFailedInput(inputId,errorMessage);

    return true;
}

function checkEmail(inputId,errorMessage)
{
	var input = document.getElementById(inputId);
	if(!input)
	{
		alert( "Input " + inputId + " not found!");
		return false;
	}

    if (!isValidEmail(input.value))
    {
        focusFailedInput(inputId,errorMessage);
        return false;
    }

    return true;
}

function isValidEmail(email)
{
 	var template = /^[0-9a-z]+[0-9a-z._-]*\@[0-9a-z]+[0-9a-z._-]*\.[0-9a-z]{2,}$/i;
  	if (template.test(email) == false) return false;
	return true;
}

function focusFailedInput(inputId, errorMessage)
{
	var labels = document.getElementsByTagName("label");

	var tmplabel;
	// set error class to correct label and remove error class from others
	for(var i = 0; i < labels.length; i++ )
	{
		var label = labels[i];
		label.className = label.className.replace("error", "");
		// if anything will be wrong, remove break statement
		if( label.htmlFor == inputId ) { label.className += " error"; break; }
	}

	myAlert(errorMessage, document.getElementById(inputId) );
	return false;
}

function clearError()
{
	var labels = document.getElementsByTagName("label");

	for(var i = 0; i < labels.length; i++ )
	{
		var label = labels[i];
		label.className = label.className.replace("error", "");
	}
	return true;
}

