// JavaScript Document

//Globals
var browser = new Browser();
var dragObj = new Object();
dragObj.zIndex = 0;

var AJAXResponse = "";


function submitQuickContactForm(){

var qcf = document.getElementById("quickContactForm");
var frm = document.forms[0];

var name = frm.name.value;
var email = frm.email.value;
var message = frm.message.value;
var error = '';


 if(!name){
   error = error + 'The name field is required.\n';
 }

 if(!validEmail(email)){
   error = error + 'Your email is missing or invalid.\n';
 }

 if(!message){
   error = error + 'You must enter a comment or question.\n';
 }

 if(error){
  alert(error);
  return 0;
 }


 var data = "action=contact&quickContact=yes&name="+URLEncode(name)+"&email="+URLEncode(email)+"&message="+URLEncode(message);

 var url = 'scripts.php';

	var httpRequest = getHttpRequestObject();
	
	if(!httpRequest){
		//qcf.innerHTML = '<div>Could not create request object.</div>';
		updateQCCForm('Could not create request object.');

	}
	
	//Otherwise, ready to roll
	else{


		//alert(url);
		
		
		httpRequest.onreadystatechange = function() { 

			if(httpRequest.readyState == 4){
				
				if(httpRequest.status == 200){
					//qcf.innerHTML = '<div>'+httpRequest.responseText+'</div>';
					updateQCCForm(httpRequest.responseText);
				}
				else{
					//qcf.innerHTML = '<div>An error occurred.  Please try again.</div>';
					updateQCCForm('An error occurred.  Please try again.');
				}
			}
			else{
				qcf.innerHTML = '<center><img src="images/loading.gif"></center>';

			}
		
		};
			
		
		if (httpRequest.overrideMimeType) {
      		httpRequest.overrideMimeType('text/xml');
		}

		httpRequest.open("post", url, true);
		httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        	httpRequest.send(data);
    	}	
 

}



function resetQCCForm(){

var qcf = document.getElementById("quickContactForm");

var content = '<form>'+
          '<table>'+
          '<tr>'+
            '<td colspan="2"><div id="title">Quick Contact Form</div>'+
            '</td>'+
           '</tr>'+
           '<tr>'+
           '<tr>'+
            '<td colspan="2">&nbsp;'+
            '</td>'+
           '</tr>'+
           '<tr>'+
            '<td width="34%"><span id="formField">Name:</span>            </td>'+
            '<td width="66%"><input type="textbox" name="name" value="">            </td>'+
           '</tr>'+
           '<tr>'+
            '<td width="34%"><span id="formField">Email:</span>            </td>'+
            '<td width="66%"><input type="textbox" name="email" value="">            </td>'+
           '</tr>'+
           '<tr>'+
            '<td colspan="2">&nbsp;'+
            '</td>'+
           '</tr>'+
           '<tr>'+
            '<td colspan="2"><span id="formField">Comment/Question:</span>'+
            '<textarea name="message" rows="5"></textarea>'+
            '</td>'+
           '</tr>'+
           '<tr>'+
            '<td colspan="2">&nbsp;'+
            '</td>'+
           '</tr>'+
           '<tr>'+
            '<td colspan="2"><input id="sendContact" type="button" name="submit" value="Submit" onclick="submitQuickContactForm();">'+
            '</td>'+
           '</tr>'+
          '</table>'+
          
         '</form>';

qcf.innerHTML=content;

}



function updateQCCForm(status){


var qcf = document.getElementById("quickContactForm");
var content = '';

 if(status == 1){
	
	content = ''+
	'<div id="title">'+
	'Thank You!'+
	'</div><div style="color:#333; margin-top: 10px; margin-bottom: 60px;">'+
	'Your message has been sent to Brasher Technology.<br><br>We appreciate your business!'+  
	'</div><div style="padding: 5 0 5 0; margin-top: 15px; border-top: 1px solid #dedede; background-color: #efefef; text-align: right;">'+
	'<a href="javascript:resetQCCForm();">Back to Quick Contact Form</a>'+
	'</div>';
 }

 else{
	content = ''+
	'<div id="title">'+
	'Oops!'+
	'</div><div style="color:#333; margin-top: 10px; margin-bottom: 60px;">'+
	status+  
	'</div><div style="padding: 5 0 5 0; margin-top: 15px; border-top: 1px solid #dedede; background-color: #efefef; text-align: right;">'+
	'<a href="javascript:resetQCCForm();">Back to Quick Contact Form</a>'+
	'</div>';
 }

qcf.innerHTML=content;
}




function executeAJAX(url, data){

	
	var httpRequest = getHttpRequestObject();
	
	if(!httpRequest){
		AJAXResponse = 'Could not create HTTP instance.';
	}
	
	//Otherwise, ready to roll
	else{


		//alert(url);
		
		
		httpRequest.onreadystatechange = function() { 

			if(httpRequest.readyState == 4){
				
				if(httpRequest.status == 200){
					AJAXResponse = httpRequest.responseText;
				}
				else{
					AJAXResponse = 'An error occurred.  Please try again.';
				}
			}
			else{
				//AJAXResponse = 'Loading...';
			}
		
		};
			
		
		if (httpRequest.overrideMimeType) {
      		httpRequest.overrideMimeType('text/xml');
		}

		httpRequest.open("post", url, true);
		httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        	httpRequest.send(data);
    	}	
	
}

function getHttpRequestObject(){
	var httpRequest;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
                // See note below about this line
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                           try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                               } 
                             catch (e) {}
                }
        }

return httpRequest;
}



function sendContactForm(){

	showScreenMask();

}

/*
function showScreenMask(){

	var screenMask = document.getElementById("screenMask");
	
	//Set size to width and height of screen
	var h	= screen.height+"px";
	var w	= screen.width+"px";
	
	screenMask.style.width=w;
	screenMask.style.height=h;
	
	screenMask.style.visibility="visible";

}

function hideScreenMask(){

	var screenMask = document.getElementById("screenMask");
	screenMask.style.visibility="hidden";

}
*/


function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}



function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}


function validEmail(str) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

   if(reg.test(str) == false) {
	return false;
   }
   else{
	return true;
   }
}


function URLEncode( plaintext )
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			/*
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
			
				encoded += "+";
			*/
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   document.URLForm.F1.value = plaintext;
   return false;
};





