var legalCopy = createRequestObject();
var selected_products;
var year;
var legalCopyText = "";
var retries = 0;

function moveEvent(liNum, source, dest)	{
	var sourceUL = document.getElementById(source);
	var destUL = document.getElementById(dest);
	var moveLI = document.getElementById(liNum);

	var added = false;
	var arrSplit = moveLI.id.split("^^");
	var name = arrSplit[0];
	var id = arrSplit[1];
	var comment = arrSplit[2];
	var taggedname = name;
	if (comment == "is_comment") {
		taggedname = "<span class=\"products_list_comment\">" + name + "</span>";
	}
	var item;
	moveLI.innerHTML = "<a href='javascript:moveEvent(\"" + name + "^^" + id + "^^" + comment + "\", \"" + dest + "\", \"" + source + "\");'>" + taggedname + "</a>";
	// if the destination list has items in it we need to find the correct alphabetical
	// position to insert at
	if (destUL.hasChildNodes()) {
		item = destUL.firstChild;
		// just loop through each item until we find one that should be right after
		// the item to be added
		while (item != destUL.lastChild) {
			if (StrComp((item.id.toUpperCase()), (moveLI.id.toUpperCase())) > 0) {
				destUL.insertBefore(moveLI, item); // insert the item into the destination list
				added = true; // we've added the item so we don't need to process the special cases
				break; // if we let it keep looping we'll go infinite all over your pansy server
			}
			item = item.nextSibling;
		}
		// the last item in the destination list is not processed by the loop
		// so we check for it here
		if (StrComp((item.id.toUpperCase()), (moveLI.id.toUpperCase())) > 0 && added == false) { 
				destUL.insertBefore(moveLI, item);
				added = true;
		}
	}
	// if we haven't added the item yet, then it must go on the end of the list
	if (added == false) {
		destUL.appendChild(moveLI);
	}
	retries = 0;
	getLegalCopy();
}

function changeYear() {
	var destUL = document.getElementById('selectedProducts');
	if (destUL.hasChildNodes()) {
		retries = 0;
		getLegalCopy();
	}
}

function sortAssocArr(assoc) {
  var sorted = new Array();
  var num = 0;
  var tmp = new Array();
  for (i in assoc) {
  	tmp[num++] = i + "|" + assoc[i];
  }
  tmp = tmp.sort();
  for (i = 0; i < tmp.length; i++) {
     x = tmp[i].split("|");
     sorted[x[0]] = x[1];
   }
   return sorted;
}

/* The following function creates an XMLHttpRequest object... */	
function createRequestObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

/* Function called to get the legal copy*/
function getLegalCopy(){
	Processing(true);
	GetSelectedProducts();
	legalCopy.open('post', 'legal_copy.php');
	
	/* Define a function to call once a response has been received. This will be our
		handleProductCategories function that we define below. */
	legalCopy.onreadystatechange = handleLegal; 
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	legalCopy.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');	
	
	legalCopy.send('Continued=Continued&year='+year+selected_products);
}

function Processing(isProcessing){
	if (isProcessing) {
		document.getElementById('processing-flag').style.display = "block";
	} else {
		document.getElementById('processing-flag').style.display = "none";
	}
}


/* Function called to handle the list that was returned from the server.. */
function handleLegal(){
	/* Make sure that the transaction has finished. The XMLHttpRequest object 
		has a property called readyState with several states:
		0: Uninitialized
		1: Loading
		2: Loaded
		3: Interactive
		4: Finished */
	legalCopyText = "";
	if(legalCopy.readyState == 4){ //Finished loading the response
		/* We have got the response from the server-side script,
			let's see just what it was. using the responseText property of 
			the XMLHttpRequest object. */
		legalCopyText = legalCopy.responseText;
		/* And now we want to change the legal copy <div> content.
			we do this using an ability to get/change the content of a page element 
			that we can find: innerHTML. */
		if (legalCopyText != "") {
			Processing(false);
			document.getElementById('results').innerHTML = legalCopyText;
		} else { // Every so often the server returns a blank response, I don't know why, but
				// if it does we retry the same request up to three times before reporting an
				// error to the user.
			if (retries >2) {
				loading(false);
				document.getElementById('results').innerHTML = "<p>The server did not respond, please try again later.</p>"
			} else {
				retries++;
				getLegalCopy();
			}
		}
	}		
}

// This function creates a string of selected products that can be attached to the POST request
function GetSelectedProducts() {
	var destUL = document.getElementById('selectedProducts');
	selected_products = "";
	var selectedItem = document.getElementById('start_date');
	year = selectedItem.options[selectedItem.selectedIndex].value;
	
	if (destUL.hasChildNodes()) {
		var submitForm = document.getElementById("frmProducts");
		var item = null;
		do {
			if (item == null) {
				item = destUL.firstChild;	
			} else {
				item = item.nextSibling;
			}
			var arrSplit = item.id.split("^^");
			var name = arrSplit[0];
			var id = new String(arrSplit[1]);
			selected_products = selected_products + "&selected_products[" + id + "]=" + name;
		} while (item != destUL.lastChild);
	}
}

function StrComp(strOne, strTwo) {
	arrStrOne = strOne.split('^^');
	arrStrTwo = strTwo.split('^^');
	var leng = Math.min(arrStrOne[0].length, arrStrTwo[0].length);
	if (arrStrOne[0].substring(0,leng-1) == arrStrTwo[0].substring(0,leng-1)) {
		if(arrStrOne[0].length > arrStrTwo[0].length) {
			return 1;
		} else {
			return -1;
		}
	} else {
		return (arrStrOne[0] > arrStrTwo[0]);
	}
}

function checkMail(address) {
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */
	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	
	var validChars="\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	
	var quotedUser="(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	
	var matchArray=address.match(emailPat);
	
	if (matchArray==null) {
	
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
	
	//alert("Email address seems incorrect (check @ and .'s)");
	return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	
	for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
	//alert("Ths username contains invalid characters.");
	return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
	//("Ths domain name contains invalid characters.");
	return false;
	   }
	}
	
	// See if "user" is valid 
	
	if (user.match(userPat)==null) {
	
	// user is not valid
	
	//alert("The username doesn't seem to be valid.");
	return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	
	// this is an IP address
	
	for (var i=1;i<=4;i++) {
	if (IPArray[i]>255) {
	//alert("Destination IP address is invalid!");
	return false;
	   }
	}
	return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
	//alert("The domain name does not seem to be valid.");
	return false;
	   }
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
	//alert("The address must end in a well-known domain or two letter " + "country.");
	return false;
	}
	
	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
	//alert("This address is missing a hostname!");
	return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

function resetPassword(user) {
	window.location.replace('resetPassword.php?email=' + escape(user));
}

function ShowHideNotes(note){
	//alert(document.getElementById(note).style.display);
	if (document.getElementById(note).style.display == "block") {
		document.getElementById(note).style.display = "none";
	} else {
		document.getElementById(note).style.display = "block";
	}
}
