function validateContactForm(currentForm) {
    var elementsToValidate = $(".required"),
        formHasErrors = false;
		
	var fullTelephone = $("#contact_telephone").val();
	var trimmedTelephone = fullTelephone.replace(/ /g,'');
	//trimmedTelephone = $.trim(trimmedTelephone);
	$("#contact_telephone").val(trimmedTelephone);
    
	
	
    for (var i=0; i < elementsToValidate.length; i++) {
        if (!elementsToValidate[i].value) {
            formHasErrors = true;
            $("#error_" + elementsToValidate[i].name).removeClass("hidden-error");
        } else {
            if (elementsToValidate[i].name == "contact_name") { 
                $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
            }
            
            if (elementsToValidate[i].name == "contact_message") { 
                $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
            }

            if (elementsToValidate[i].name == "contact_email") {
                if (!(validateEmail(elementsToValidate[i].value))) {
                    formHasErrors = true;
                    $("#error_" + elementsToValidate[i].name).text("A valid email address");
                    $("#error_" + elementsToValidate[i].name).removeClass("hidden-error");
                } else {
                    $("#error_" + elementsToValidate[i].name).text("Your email address");
                    $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
                }
            }

            if (elementsToValidate[i].name == "contact_telephone") {              				
				if (!(validatePhone(elementsToValidate[i].value))) {
                    formHasErrors = true;
                    $("#error_" + elementsToValidate[i].name).text("A valid UK phone number");
                    $("#error_" + elementsToValidate[i].name).removeClass("hidden-error");
                } else {
                    $("#error_" + elementsToValidate[i].name).text("Your phone number");
                    $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
                }
            }

            if (elementsToValidate[i].name == "contact_budget_min") {
                if (!(validateBudget(elementsToValidate[i].value))) {
                    formHasErrors = true;
                    $("#error_" + elementsToValidate[i].name).text("A valid minimum budget");
                    $("#error_" + elementsToValidate[i].name).removeClass("hidden-error");
                } else {
                    $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
                }
            }

            if (elementsToValidate[i].name == "contact_budget_max") {
                if (!(validateBudget(elementsToValidate[i].value))) {
                    formHasErrors = true;
                    $("#error_" + elementsToValidate[i].name).text("A valid maximum budget");
                    $("#error_" + elementsToValidate[i].name).removeClass("hidden-error");
                } else {
                    $("#error_" + elementsToValidate[i].name).addClass("hidden-error");
                }
            }
        }

        if ($("#property-to-sell").length > 0) {
            var toSell = $("input[name='property_to_sell']:checked").val();

            if (!toSell) {
                formHasErrors = true;
                $("#error_property_to_sell").removeClass("hidden-error");
            } else {    
                $("#error_property_to_sell").addClass("hidden-error");
            }   
        }
    }
    
    // spam protection
    /**
    if ($(".noshow").val().length > 0) {
        formHasErrors = true;
    }
    **/
    if (currentForm.name == "contact-single-agent") {
        if (validateEmail($("#contact_email").val())) {
            $("#error_contact_emailphone").addClass("hidden-error");
        } else {
            formHasErrors = true;
            $("#error_contact_emailphone").removeClass("hidden-error");
        }
        
        if (($("#contact_name").val().length > 0) && ($("#contact_message").val().length > 0) && (validateEmail($("#contact_email").val()))) {
        //if (($("#contact_name").val().length > 0) && ($("#contact_message").val().length > 0) && ($("input[name='property_to_sell']:checked").length) && (validateEmail($("#contact_email").val()))) {
            formHasErrors = false;
        } else {
            formHasErrors = true;
        }
    }

    if (!formHasErrors) {
        var adwordsCode = "<div style=\"display:inline;\"><img height=\"1\" width=\"1\" style=\"border-style:none;\" alt=\"\" src=\"http://www.googleadservices.com/pagead/conversion/1017855653/?label=yrJ2CMOm-QEQpf2s5QM&amp;guid=ON&amp;script=0\"/></div>";

        $("#adwords-tracking").html(adwordsCode);
        $(".errorBox").hide();
        submitContactForm(currentForm);
    } else  {
        $(".errorBox").show();
    }
    
    return false;
}

function validateEmail(elementValue) {
    var emailPattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return emailPattern.test(elementValue);
}

function validatePhone(elementValue) {
    var phonePattern = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
	//var phonePattern = /^((\+\d{1,3}(-|\s+)?\(?\d\)?(-|\s+)?\d{1,5})|(\(?\d{2,6}\)?))(-|\s+)?(\d{3,4})(-|\s+)?(\d{4})((\s+x|\s+ext)\d{1,5}){0,1}$/;
    return phonePattern.test(elementValue);
}

function validateBudget(elementValue) {
    var budgetPattern = /[0-9]$/;
    return budgetPattern.test(elementValue);
}

$(document).ready(function() {
    $(".noshow").hide();
    if ($('#contact_type').length > 0) {
        $('#contact_type').change(function() {
            if ($('#contact_type').val() == "schedule") {
                $(".address-drop").show();
            } else {
                $(".address-drop").hide();
            }
        });
    }
});


function recordSTRUQConversion(){
	
	var rnd = parseInt(Math.random() * 10000000000000000);
	var protocol = (document.location.protocol == "https:" ? "https:" : "http:");

	var furl = protocol + "//app.struq.com/s/g/YuDqa-bxw0mBtXDTsV8lMA/?v=2&qs=conversion"
		+ "&rnd=" + rnd;

	$("body").append('<ifr'+'ame src="' + furl + '" style="width:0px; height:0px; border: 0px"></ifr'+'ame>');
	
}


function hitOmniture() {
    s=s_gi('newsquests1homesprod,newsquests1homess1rentalprod,newsquests1groupprod');
    s.prop16=document.location.hostname;
    s.linkInternalFilters="javascript:,s1homes.com,www.s1homes.com";
    s.campaign=s.getQueryParam('p_cid');
    s.linkTrackVars="events";
    s.linkTrackEvents="event17";
    s.events="event17";
    s.tl(this,'o','Property contact');
	
	// DoubleClick Floodlight Action Tags
	var randomNum = Math.ceil(Math.random()*100000);
	var homesConfirmContact = '<iframe src="https://fls.doubleclick.net/activityi;src=3341045;type=s1hom572;cat=s1hom933;ord=' + randomNum + '" width="1" height="1" frameborder="0" style="display:none"></iframe>';
	$("#homesConfirmContactDoubleClickFloodlightTag #doubleClickFloodlightReplace").html(homesConfirmContact); 
	// END: DoubleClick Floodlight Action Tags
	
	// STRUQ conversion tracking
	recordSTRUQConversion();
	// END: STRUQ conversion tracking
	
}

function submitContactForm(currentForm) {
    currentForm.submit.disabled = true; // disable the submit button
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if ($("#contact-details").length > 0) {
                $("#contact-details").html(xmlhttp.responseText);
                if ($(currentForm).attr("id") == "contact-form-detail") {
                    hitOmniture();
                }
            } else if  ($("#contact-details-all-agents").length > 0) {
                $("#contact-details-all-agents").html(xmlhttp.responseText);
            } else {
                $("#contact-details-agent").html(xmlhttp.responseText);
            }
        }
    };

    $("#contact_message").val($("#contact_message").val().replace(/\n\r?/g, '<br />'));

    var urlToSend = "/property-for-sale/contact_agents.cgi?";

    if ($(currentForm).attr("id") == "contact-form-detail") {
        urlToSend = "/property-for-sale/contact-per-property.cgi?";
    }

    elementsInputs = currentForm.getElementsByTagName("input");
    elementsTextareas = currentForm.getElementsByTagName("textarea");

    for (var i=0; i < elementsInputs.length; i++) {
        if (elementsInputs[i].value) {
            if ((elementsInputs[i].type == "checkbox") || (elementsInputs[i].type == "radio")) {
                if (elementsInputs[i].checked == true) {
                    urlToSend += elementsInputs[i].name + "=" + elementsInputs[i].value + "&";
                }
            } else {
                urlToSend += elementsInputs[i].name + "=" + elementsInputs[i].value + "&";
            }
        }
    }

    for (var i=0; i < elementsTextareas.length; i++) {
        if (elementsTextareas[i].value) {
            urlToSend += elementsTextareas[i].name + "=" + elementsTextareas[i].value + "&";
        }
    }

    if ($("#property_summary").val()) {
        urlToSend += "property_summary=" + $("#property_summary").val() + "&";
    }
    urlToSend += "submit=1";

    xmlhttp.open("GET", urlToSend, "true");
    xmlhttp.send();
}

