IncludeJavascript("config.js");
  
var failedValidates = 0;
var failedValidateMessage = "";

var IFrameObj; // our IFrame object
var formArray = Array();


function IncludeJavascript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>'); 
}

function wait(msecs){
   var start = new Date().getTime();
   var cur = start;
   while(cur - start < msecs)
   {
      cur = new Date().getTime();
   }
}



function setFailedValidateMessage() {	
	
  /**
  if (failedValidates > 2)
    failedValidateMessage = "It looks like you are having some trouble with our form.\nFeel free to contact one of our representatives at 417-991-2449.";
  else if (failedValidates > 0)
    failedValidateMessage = "Valid contact information is required.\nFeel free to contact one of our representatives for a quote at 417-991-2449.";

   **/
}
var count = 0;
//Create iFrame - set source from servePage
function callToServer() {
  if (!document.createElement) {return true};
  var IFrameDoc;
  if (!IFrameObj && document.createElement) {
    // create the IFrame and assign a reference to the
    // object to our global variable IFrameObj.
    // this will only happen the first time 
    // callToServer() is called
   try {
	   //alert("in the try");
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id','RSIFrame');
      tempIFrame.style.border='0px';
      tempIFrame.style.width='0px';
      tempIFrame.style.height='0px';
      IFrameObj = document.body.appendChild(tempIFrame);
      
      if (document.frames) {
   	   //alert("in the mac");

        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
        IFrameObj = document.frames['RSIFrame'];
      }
    } catch(exception) {
    	//alert("in the catch");
      // This is for IE5 PC, which does not allow dynamic creation
      // and manipulation of an iframe object. Instead, we'll fake
      // it up by creating our own objects.
      iframeHTML='\<iframe id="RSIFrame" style="';
      iframeHTML+='border:0px;';
      iframeHTML+='width:0px;';
      iframeHTML+='height:0px;';
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      IFrameObj = new Object();
      IFrameObj.document = new Object();
      IFrameObj.document.location = new Object();
      IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
      IFrameObj.document.location.replace = function(location) {
        this.iframe.src = location;
      };
    }
  }
  
  if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
	  
	 // alert("in the Gecko");
    // we have to give NS6 a fraction of a second
    // to recognize the new IFrame
    setTimeout('callToServer()',10);
    return false;
  }
  
  if (IFrameObj.contentDocument) {
	   //alert("ns6");
	   //wait(1000);
    // For NS6
    IFrameDoc = IFrameObj.contentDocument; 
  } else if (IFrameObj.contentWindow) {
	   //alert("in ie5.5");

    // For IE5.5 and IE6
    IFrameDoc = IFrameObj.contentWindow.document;
  } else if (IFrameObj.document) {
    // For IE5
	   //alert("in the ie5 part");

    IFrameDoc = IFrameObj.document;
  } else {
    return true;
  }
  //alert(URL);
  if (IFrameDoc.location == null){
	//alert ("IFrameDoc.location is null, try again?"); 
    // attempt it one more time but thats it.  Once I put this code in, including 'count'
	// this IFrameDoc.location has never been null again ??????
	if (count == 0){
		//alert ("count is " + count);
		count+=1;
	   callToServer();
	}
  }
  IFrameDoc.location.replace(URL);

  window.status = "";
  //alert("should call handleResponse now");
  window.setTimeout(callback, 100);  
  return false;
}

//Called after callToServer() is complete
function handleResponse() {
   //alert("This is called after callToServer is done ");
   window.location="moving_quote_thanks.html";
    
}

//Send data to serverPage
// This creates a string URL with all the elements of the form and the company name
function createUrlString (form) {
   var elem = form.elements;
    str = source+"{}";
    for(var i = 0; i < elem.length; i++)
    {
	   if (!elem[i].name || elem[i].name == 'hdwemail' || elem[i].name=='hdwok' || elem[i].name=='Submit' || elem[i].name=='hdwnook' || elem[i].name=='select') continue;
       str += elem[i].type+"{name}"+elem[i].name+"{value}"+elem[i].value+"{}"
       var temp = Array();
       temp.name= '"'+elem[i].name+'"';
       temp.value = '"'+elem[i].value+'"';
       formArray.push(temp);
    }
    URL = serverPage + "?company=" + str + "&limit=12"; 
    //Method called after send is complete
    callback = 'handleResponse();';
    //alert(URL);
    return callToServer();
    //return false;
}


// form validation -------------------------------
function order_validation(Form)
{
	//if (browserTag = "MSIE") alert("order_validation");
	if(Form.fname.value == "")
	{ 
		failedValidates++;
		setFailedValidateMessage();		
		alert("You must enter a first and last name to process quote.\n" + failedValidateMessage);
		Form.fname.focus();
		/**
                Form.fname.style.backgroundColor= '#00ffff';
        **/
		return (false);
	}
	if(Form.email.value != "")
	{
		if(!testEmail(Form.email.value))
		{
			failedValidates++;
			setFailedValidateMessage();
			alert("Invalid email address.\n" + failedValidateMessage);
			Form.email.focus();
			Form.email.select();
			return (false);
		}	
	} else {
			failedValidates++;
			setFailedValidateMessage();
			alert("Please enter an email address.\n" + failedValidateMessage);
			/** Form.email.style.backgroundColor= '#00ffff'; */
			Form.email.focus();
			Form.email.select();
			return (false);
	}
	if (Form.dphone.value != "")
	{
		// does java script except 0 as false
		if(!phoneIsValid(Form.dphone.value)){
			failedValidates++;
			setFailedValidateMessage();
			alert("Invalid phone number.\n" + failedValidateMessage);
			Form.dphone.focus();
			Form.dphone.select();
			return (false);
		}
	} else {
			failedValidates++;
			setFailedValidateMessage();
			alert("Please enter a phone number.\n" + failedValidateMessage);
			Form.dphone.focus();
			Form.dphone.select();
			return (false);
	}
	if (Form.shipdate.value == "" )
	{ 
		alert("Please enter a ship date");
		return false;
	}
	if (Form.fcity.value != "" && Form.fstate.value != "XX") {	  
	} else {
			failedValidates++;
			setFailedValidateMessage();
			alert("Please enter a pickup city and state.\n" + failedValidateMessage);
			Form.fcity.focus();
			Form.fcity.select();
			return (false);
	}
	if (Form.tcity.value != "" && Form.tstate.value != "XX") {
	} else {
			failedValidates++;
			setFailedValidateMessage();
			alert("Please enter a delivery city and state.\n" + failedValidateMessage);
			Form.tcity.focus();
			Form.tcity.select();
			return (false);
	}
	
	if (Form.numBedrooms.value != "0") {
	} else {
	   alert("Please choose the number of rooms to move");
	   Form.numBedrooms.focus();
	   /** this was causing it to submit for some reason Form.numBedrooms.select(); **/
	   return (false);
	}
	if (Form.shipdate.value == ""){
	  alert ("Please enter a move date. mm/dd/yyyy");
	  return false;
	}
	else {
		
       var regex = new RegExp(/^\d{2}(\/)\d{2}\1\d{4}$/);
	   var date = Form.shipdate.value;

	   var m = regex.exec(date);
	   if (m == null) {
		  alert("Please enter a valid date mm/dd/yyyy");
		  return (false);
		} 

	}
	
	//Data is valid - send to serverPage
    //alert ("everthing looks good, uncomment next line");
	createUrlString(Form);
	return false;
}

function testEmail(addr) {

  var regex = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i );

  var m = regex.exec(addr);
  if (m == null) {
    //alert("Please enter a valid email");
    return false;
  } else {
    //alert("this is a good email");
    return true;
  }
}

function phoneIsValid(textToTest) {
    //var  = phoneObjectToCheck.value;
    var pattern = /(\d{3}).{0,2}(\d{3}).{0,2}(\d{4})(.*)/;
    var result  = textToTest.match(pattern)
    if(result != null){
	    //alert ("Phone is " + '('+result[1]+')'+result[2]+'-'+result[3]+' '+result[4]);
		//return true;
        return '('+result[1]+')'+result[2]+'-'+result[3]+' '+result[4];
    }
    return 0;
}                           
  
