/**
 * This code tries to write some text in the Firebug console. If it fails (no
 * Firebug plug in installed or under IE), it instantiate an object called
 * 'console' that has a method called 'log' that does nothing !
 */
// try { hlogger.info('init console... done'); } catch(e) { console = { log:
// function() {},info: function() {},dir: function() {} } }
var muffler_ajax = {};

muffler_ajax.comm = {

    sendRequest : function(url, options) {

	    // alert('request url=' + url);

	    var request = new Object();

	    request.url = url;

	    /* basic communication defaults */
	    request.method = "GET";
	    request.async = true;
	    request.postBody = null;

	    /* standard callbacks */
	    request.received = false;
	    request.onSuccess = function() {
	    };
	    request.onFail = function() {
	    };

	    /* output handling */
	    request.outputTarget = null;

	    /* apply options defined by user */
	    for (option in options) {
		    request[option] = options[option];
	    }

	    /* Send the request now */
	    muffler_ajax.comm._sendXHR(request);

    },

    /**
	 * **************************************** Private Methods
	 * *****************************************
	 */

    /**
	 * _createXHR - private method acting as a wrapper to make an XMLHttpRequest
	 * object. Trys native object first and then ActiveX control. Returns null
	 * if fails.
	 * 
	 * @private
	 * @return {object} Either the native XHR Object or the most current ActiveX
	 *         version supported.
	 */
    _createXHR : function() {

	    try {
		    return new XMLHttpRequest();
	    }
	    catch (e) {
	    }
	    try {
		    return new ActiveXObject("Msxml2.XMLHTTP.7.0");
	    }
	    catch (e) {
	    }
	    try {
		    return new ActiveXObject("Msxml2.XMLHTTP.6.0");
	    }
	    catch (e) {
	    }
	    try {
		    return new ActiveXObject("Msxml2.XMLHTTP.3.0");
	    }
	    catch (e) {
	    }
	    try {
		    return new ActiveXObject("Msxml2.XMLHTTP");
	    }
	    catch (e) {
	    }
	    try {
		    return new ActiveXObject("Microsoft.XMLHTTP");
	    }
	    catch (e) {
	    }

	    return null;
    },

    /**
	 * Private method that sends an XHR request. It creates the XHR, fallsback
	 * if any problems are encountered, sets appropriate headers, and sends the
	 * requesst.
	 * 
	 * @private
	 * @param {Object}
	 *            request The request that contains the options that we wish to
	 *            send.
	 * 
	 */

    _sendXHR : function(request) {

	    request.xhr = muffler_ajax.comm._createXHR();
	    if (!request.xhr) {
		    return;
	    }

	    /* open the request */

	    try {
		    request.xhr.open(request.method, request.url, request.async);

	    }
	    catch (e) {
		    // alert('error' + e);
		    return;
	    }
	    request.xhr.setRequestHeader("If-Modified-Since", "Wed, 15 Nov 1995 04:58:08 GMT");
	    /* bind the success callback */
	    request.xhr.onreadystatechange = function() {
		    muffler_ajax.comm._handleReadyStateChange(request);
	    };

	    /* set header(s) for POST */
	    if (request.method.toUpperCase() == "POST") {
		    request.xhr.setRequestHeader("Content-Type", request.requestContentType);
		    if (request.requestContentTransferEncoding != "") {
			    request.xhr.setRequestHeader("Content-Transfer-Encoding",
			            request.requestContentTransferEncoding);
		    }
	    }

	    /* send the request */
	    request.xhr.send(request.postBody);
	    // alert('sent');
    },

    /**
	 * _handleReadyStateChange
	 */
    _handleReadyStateChange : function(response) {
	    // alert('response.readyState=' + response.xhr.readyState);
	if (response.xhr.readyState == 4 && !response.received) {
		response.received = true;

		/* Danger: Firefox problems so we try-catch here */
		try {
			response.httpStatus = response.xhr.status;
			response.httpStatusText = response.xhr.statusText;
		}
		catch (e) {
			response.httpStatus = 3507;
			response.httpStatusText = "Unknown Loss";
		}
		response.responseText = response.xhr.responseText;
		// alert('response.responseText:' + response.responseText);
		response.responseXML = response.xhr.responseXML;
		// alert('response.responseText:' + response.responseXML);

		/* call either success or fail callback */
		if (response.httpStatus == 200) {
			// alert('success');
			response.onSuccess(response);
		}
		else {
			response.onFail(response, 'There was an issue getting event information');
		}

		/* clear response */
		response = null;
	}
}
};

muffler_ajax.util = {

    /** */
    parseJsonText : function(jsonText) {
	    return eval(jsonText);
    },

    /**
	 * replaces all the string holders within the sTemplate within the
	 * jsonObject keys eg. if sTemplate contains $firstName it will be replaced
	 * by the value of jsonObject[firstName]
	 */
    renderTemplate : function(jsonObject, sTemplate) {
	    while ((match = /\$\{(.*?)\}/.exec(sTemplate)) != null) {
		    if (jsonObject[match[1]] != null) {
			    sTemplate = sTemplate.replace(match[0], jsonObject[match[1]]);
		    }
		    else {
			    sTemplate = sTemplate.replace(match[0], '');
		    }

	    }
	    return sTemplate;
    },

    /**
	 * 
	 */
    renderBits128Template : function(bits128String, bits128Template, tagColoursArray) {
	    var defaultOffColour = '#ffffff';
	    var defaultOnColour = '#00ff00';
	    for ( var i = 0; i < bits128String.length; i++) {
		    if (bits128String.charAt(i) == 0) {
			    // if this bit has not been set
			    bits128Template = bits128Template.replace('${bit' + i + '}',
			            ' class="sysTagTabletd"');
		    }
		    else if (tagColoursArray[i] == null) {
			    bits128Template = bits128Template.replace('${bit' + i + '}',
			            ' bgcolor="' + defaultOnColour + '"');
		    }
		    else {
			    bits128Template = bits128Template.replace('${bit' + i + '}',
			            ' bgcolor="' + tagColoursArray[i] + '"');
		    }
	    }
	    return bits128Template;
    },

    serializeForm : function(form) {
	    if (typeof (form) == "string") {
		    var formObject = document.forms[form];
		    if (formObject == null)
			    formObject = document.getElementById(form);

		    form = formObject;
	    }

	    var formValues = "";
	    for ( var i = 0; i < form.elements.length; i++) {
		    var currentField = form.elements[i];
		    var fieldName = currentField.name;
		    var fieldType = currentField.type;

		    /*
			 * Disabled and unnamed fields are not sent by browsers so ignore
			 * them
			 */
		    if ((!currentField.disabled) && fieldName) {
			    switch (fieldType) {
			    case "text":
			    case "password":
			    case "hidden":
			    case "textarea":
				    formValues = muffler_ajax.util._encode(formValues, fieldName, currentField.value);
				    break;
			    case "radio":
			    case "checkbox":
				    if (currentField.checked)
					    formValues = muffler_ajax.util
					            ._encode(formValues, fieldName, currentField.value);
				    break;
			    case 'select-one':
			    case 'select-multiple':
				    for ( var j = 0; j < currentField.options.length; j++) {
					    if (currentField.options[j].selected) {
						    formValues = muffler_ajax.util._encode(formValues, fieldName,
						            currentField.options[j].value);
						    // formValues = muffler_ajax.util._encode(formValues,
						    // fieldName, (currentField.options[j].value != null
						    // && currentField.options[j].value != "") ?
						    // currentField.options[j].value :
						    // currentField.options[j].text);
					    }
				    }
				    break;
			    default:
				    continue; /* everything else like fieldset you don't want */
			    }
		    }

	    }
	    // pull of last &
	    if (formValues.length > 0) {
		    formValues = formValues.substring(0, formValues.length - 1);
	    }
	    return formValues;
    },

    _encode : function(payload, fieldName, fieldValue) {
	    payload += fieldName + "=" + encodeURIComponent(fieldValue) + "&";
	    return payload;
    }

};

var submitQuestion = function(){
	
	if(!validateForm()){
		return;
	}
	var el = document.getElementById("spinner");
	el.innerHTML = '<img src="cutUpImages/spinner.gif"/>';
	var serializedForm = muffler_ajax.util.serializeForm("freeQuote");
	//console.log(serializedForm);
	options = {
			onSuccess :showThanks,
			postBody :serializedForm,
			method:"POST",
			requestContentType :"application/x-www-form-urlencoded"
		};
    muffler_ajax.comm.sendRequest("submit.php", options);
}

var showThanks = function(){
	var el = document.getElementById("spinner");
	el.innerHTML = '';
	$("#popUpDiv").html("<span class=\"thankYou\">Thank you for your enquiry. We will endeavour to get back to you soon.</span>");
	var t=setTimeout("disablePopup();",4000);
	
}


var validateForm = function(){

		var str = document.freeQuote.email.value;
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		if (str.indexOf(at)==-1){
		   alert("Invalid email address");
		   return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid email address");
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid email address");
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid email address");
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid email address");
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid email address");
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid email address");
		    return false;
		 }

 		 return true;				
}
