function setDocHTML(id, html){
    if (document.getElementById(id)){
        document.getElementById(id).innerHTML = html;    
    }
}

function setDocValue(id, value){
    if (document.getElementById(id)){
        document.getElementById(id).value = value;    
    }
}

function getDocValue(id, default_val){
    var val = default_val;
    if (document.getElementById(id)){
        val = document.getElementById(id).value.trim();
    }
    return val;
}

function getDocChecked(id){
    var val = 'false';
    if (document.getElementById(id)){
        val = document.getElementById(id).checked;
    }
    return val;
}

function setDocSource(id, source){
    if (document.getElementById(id)){
        document.getElementById(id).src = source;    
    }
}

/* prototype */
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

//contact form
function validateForm(){
	success = true;
	//form values
	sender_name = getDocValue('name');	
	sender_email = getDocValue('email');
	company = getDocValue('company');
	phone = getDocValue('phone');
	
	if (!validData(sender_name)){
	    setDocHTML('err_name', 'Name is required.');		
		success = false;
	}else{
	    setDocHTML('err_name', '');		
	}

	if (!validData(company)){
	    setDocHTML('err_company', 'Company is required.');		
		success = false;
	}else{
	    setDocHTML('err_company', '');		
	}
	
	if (!validPhone(phone)){
		setDocHTML('err_phone', 'Valid phone is required.');				
		success = false;
	}else{
	    setDocHTML('err_phone', '');		
	}	

	if (!validEmail(sender_email)){
		setDocHTML('err_email', 'Valid email is required.');		
		success = false;
	}else{
	    setDocHTML('err_email', '');		
	}
	if (success) submitContactForm();
}

function submitContactForm(){
	if (success){
		document.contact.submit();
	}
}


//validations
function validData(str){

	if (str && str.length > 0){
		return true;
	}
	return false;
}

function validPhone(str) 
{
	if (str){
		var stripped = str.replace(/[\(\)\.\-\ ]/g, '');
		//strip out acceptable non-numeric characters
		if (isNaN(parseInt(stripped))) {
		   return false;
		}
		if (!(stripped.length == 10)) {
			return false;
		}	
		return true;
	}
	return false;
}

function validEmail(email)
{   
	if (email){
	    email = email.trim(); 
	    
	    var dot_index = "-1"
	    var dot_index_1 = email.indexOf(".") ;
	    var dot_index_2 = email.indexOf(".", dot_index_1 + 1) ;   
	    var ampersand_index = email.indexOf("@");
	
	    if (dot_index_2 > dot_index_1) {
	         dot_index  = dot_index_2;
	    }else{
	        dot_index  = dot_index_1;   
	    }
	    
	    if  ((dot_index > 2) && (ampersand_index > 0) && (dot_index > ampersand_index + 1))
	    {
	        return true;
	    }
	}
    return false;
}

