// JavaScript Document

var sequence6 = '';  // will hold a string of 6 random characters;
var myReferrer = document.URL;
var eParam = '';
var webSite = '';

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function callAH(url, postParam, callMessage) {
	postMessage(callMessage);
	try {
		req = new XMLHttpRequest();   // firefox
	} catch(e) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");	// some versions of IE
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP"); // other versions of IE	
			} catch(e) {
				alert("Server error: " + e);
				req = false;	
			}
		}
	}
	req.onreadystatechange = function() {responseAH();}
	req.open("POST", url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", postParam.length);
	req.setRequestHeader("Connection", "close");
	req.send(postParam);
}

function responseAH() {
	var output = '';
	if(req.readyState == 4) {
		if(req.status == 200) {
			output = req.responseText;
			followUP(output);
		}
	}
}

function followUP(response) {
	zCount = 1;
	var s = response.substr(0,5);
	if(s != 'Error') {
		setCookie();
		boxObj = document.getElementById('registerYou');
		boxObj.innerHTML = '<div id="msg"> </div>';
//		postMessage(response);
		postMessage('Your request has been sent!<br />You will shortly be receiving an email, containing a link to your free report!<br /><br />Thank you!');
	} else {
		s = response.substr(5,1);
		if(s == '1') reportError('emailValid');
		if(s == '2') reportError('internetError');
		if(s == '3') reportError('noCodeInjection');
	}
}

function setCookie() {
	return Set_Cookie('lakeBurtonOnline','LakeReport',365,'/','','');
}

function removeCookie() {
	Delete_Cookie('lakeBurtonOnline','/','');	
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function postMessage(ss) {
	msgObj = document.getElementById('msg');
	msgObj.style.color = "#FFFFFF";
	msgObj.style.backgroundColor = "#333333";
	msgObj.innerHTML = ss;
}

function reportError(what) {
	submitObj = document.getElementById('sendBtn');
	submitObj.style.display = 'block';	
	var err = '';
	switch (what) {
		case 'matrix':
			err = 'Error: Incorrect letter sequence! Try again!';
			displaySequence();
			break;
		case 'Name':
			err = 'Error: Full name required! Try again!';
			displaySequence();
			break;
		case 'emailMatch':
			err = 'The email addresses do not match</br /> Please re-enter them again, and re-submit!';
			displaySequence();
			break;
		case 'emailValid':
			err = 'A valid email address is required!</br /> Please re-enter and send again!';
			displaySequence();
			break;
		case 'internetError':
			err = 'Internet problems. Please try again later';
			displaySequence();
			break;
		case 'noCodeInjection':
			err = "Code injection attempt denied! Please don't use the following sequences in your message: 'TO:', 'CC:', 'CCO:' or 'Content-Type'.";
			displaySequence()
			break;
		default:
			displaySequence();
	}
	if(err.length > 0) {
		errObj = document.getElementById('msg');
		errObj.style.color = 'red';
		errObj.style.backgroundColor = 'white';
		errObj.innerHTML = err;
	}
	return 
}

function displaySequence() {
	if(!parentValid()) {
		parent.location.replace('http://www.sellrabun.com');	
	}
	var pick;
	var myChar;
	sequence6 = '';
	var abc = ['a', 'b', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
	for(var i = 0; i < 6; i++) { 
		pick = Math.floor(Math.random()*26+1)-1;
		sequence6 += abc[pick];
	}
	var seqObj = document.getElementById("showSeq");
	seqObj.innerHTML = sequence6;
	seqObj = document.getElementById('control');
		seqObj.value = "";
}

function validateMatrix(){
	var seq = document.getElementById("control").value;
	var myMatrix = document.getElementById("showSeq").innerHTML;
	if(myMatrix != seq) return false;	
	return true;
}

function nameValid() {
	fname = document.getElementById("Name").value;
	var a = 0;
	var hyphCnt = 0;
	var hyphIndex = -2;
	var comaCnt = 0;
	var comaIndex = -2;
	var blankCnt = 0;
	var blankIndex = -2;
	var maxLength = 40;
	var periodCnt = 0;
	var periodIndex = -2;
	if(fname == '' || fname == null) return false;
	fname = fname.trim();
	if(fname.length < 1) return false;
	if(fname > maxLength) return false;
	for(var i = 0; i < fname.length; i++) {
		a = fname.charCodeAt(i);
		if((a == 32) ||(a > 64 && a < 91) || (a > 96 && a < 123) || (a >= 44 && a <= 46)) {
			if((a > 64 && a < 91) || (a >96 && a < 123)) {
				if(i - comaIndex == 1) return false;
				if(i - periodIndex == 1) return false;
			}
			if(a == 46) {           // period check
				if(i == 0) return false;
				if(i-periodIndex == 1) return false;
				if(i-blankIndex == 1) return false;
				if(i-hyphIndex == 1) return false;
				if(periodCnt > 1 && i < fname.length-1) return false;
				periodCnt++;
				periodIndex = i;
			}
			if(a == 44) {             // comma check
				if(i == 0  || i == fname.length-1) return false;
				if(i-hyphIndex == 1) return false;
				if(i-blankIndex == 1) return false;
				if(comaCnt >= 1) return false;
				comaCnt++;
				comaIndex = i;
			}
			if(a == 45) {			  // hyphen check
				if(i == 0  || i == fname.length-1) return false;
				if(i-periodIndex == 1) return false;
				if(i-comaIndex == 1) return false;
				if(i-blankIndex == 1) return false;
				if(hyphCnt >= 1) return false;
				if(comaCnt > 0) return false;
				hyphCnt++;
				hyphIndex = i;
			}
			if(a == 32) {             // blank check
				if(blankCnt > 4) return false; 
				if(i - hyphIndex == 1) return false;
				if(i - blankIndex > 1) blankCnt++;
				blankIndex = i;
			}
		} else {
			return false;
		}
	}
	if(blankIndex == 0) return false;
	eParam += 'yourName=' + escape(encodeURI(fname));
	return true;
}

function emailValid() {
	var a = 0;
	var atC = 0;
	var atIndex = 0;
	var perIndex = -2;
	var email = document.getElementById('EmailMe').value;
	if(email == '' || email == null) return false;
	email = email.trim();
	if(email.length > 0) {
		var atPos = email.indexOf("@");
		var stopPos = email.lastIndexOf(".");
		if(atPos == -1 || stopPos == -1) return false;	// period and @ must be present
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
		if(!emailPattern.test(email)) return false;  
		for (var i = 0; i < email.length-1; i++) {
			if(email.charAt(i) == '@') {
				atIndex = i;
				atC++;
			}
			if(atC > 1) return false;					// only one @
		}
		for (var i = 0; i < email.length-1; i++) {
			if(email.charAt(i) == '.') {
				if(i - perIndex == 1) return false;		// no two periods next to eachother
				perIndex = i;
				if(Math.abs(perIndex - atIndex) == 1 ) return false;  // no adjacent @ and period
			}
		}
		if(atPos == 0 || atPos == email.length-1) return false;
		if(stopPos == 0 || stopPos == email.length-1) return false;
		eParam += "&yourEmail=" + escape(encodeURI(email));
		return true;	
	}
	return false;	
}

function emailMatch() {
	var email = document.getElementById('EmailMe').value;
	var repeat = document.getElementById('EmailMe2').value;
	if(email != repeat) return false;
	return true;	
}

function submitIt() {
	eParam = '';
	if(!validateMatrix()) {
		reportError('matrix');
		return false;
	}
	if(!nameValid()) {
		reportError('Name');
		return false;		
	} 
	if(!emailValid()) {
		reportError('emailValid');
		return false;
	}
	if(!emailMatch()) {
		reportError('emailMatch');
		return false;
	}
	errObj = document.getElementById('msg');
	errObj.className = 'green';
	submitObj = document.getElementById('sendBtn');
	submitObj.style.display = 'none';
	cancelObj = document.getElementById('cancelBtn');
	cancelObj.style.display = 'none';
	eParam += '&webSite=' + escape(encodeURI(website));
	eParam += '&sendTo=' + escape(encodeURI('howard@sellrabun.com'));
	callAH('myReg.php', eParam,'Your request is being processed. Please wait!');
	return true;
}

function cancelAll() {
	postMessage('Receive a Free, Quarterly<br />Lake Report!');
	fNameObj = document.getElementById("Name");
		fNameObj.value = "";
	fMailObj = document.getElementById("EmailMe");
		fMailObj.value = "";
	fMailObj2 = document.getElementById("EmailMe2");
		fMailObj2.value = "";
	displaySequence();
}

function initSeq(site) {
	website = site;
	displaySequence();
	if(Get_Cookie("lakeBurtonOnline") == 'LakeReport') {
		var regObj = document.getElementById("registerYou");
		regObj.style.display = "none";
	}
//	setCookie();
//	removeCookie();
}

