// JavaScript Document

// Check to see if given string is a valid e-mail
	
	function verifyRemove( message )
	{
		if ( typeof( message ) == "undefined" )
			message = "Are you sure you want to delete this item?";
			
		return confirm( message );
	}
	
	function isEmail(str) {
		
	  // are regular expressions supported?
	  var supported = 0;
	  if (window.RegExp) {
	    var tempStr = "a";
	    var tempReg = new RegExp(tempStr);
	    if (tempReg.test(tempStr)) supported = 1;
	  }
	  if (!supported) 
	    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	    
	  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
	  return (!r1.test(str) && r2.test(str));
	}
	
	function isDollar(element)
	{
		var r = new RegExp("^[-+]?[0-9\.]+$");
		
		var s = element.value;
		var dollar = "";
		
		for( var i = 0; i < s.length; i++ )
		{
			if ( r.test(s.charAt(i)))
				dollar += s.charAt(i);
		}
		
		element.value = dollar;
		
		return r.test(dollar);
	}
	
	function isFloat(value)
	{
		var r1 = new RegExp("^[-+]?[0-9\.]+$");
		
		return (r1.test(value));
	}
	
	function isInt(value)
	{
		var r1 = new RegExp("^-?[0-9]+$");
		
		return (r1.test(value));
		
	}
	
	
	// Check to see if a number is a valid credit card
	
	function isCreditCard( element )
	{
		var s = element.value;
			
		var i, n, c, r, t, sNew;

		// First, reverse the string and remove any non-numeric characters.

		r = "";
		sNew = "";
		for (i = 0; i < s.length; i++) {
			c = parseInt(s.charAt(i), 10);
			if (c >= 0 && c <= 9)
			{
				r = c + r;
				sNew += c;
			}
		}

		// Check for a bad string.

		if (r.length <= 1)
			return false;

		element.value = sNew;

		// Now run through each single digit to create a new string. Even digits
		// are multiplied by two, odd digits are left alone.

		t = "";
		for (i = 0; i < r.length; i++) {
			c = parseInt(r.charAt(i), 10);
			if (i % 2 != 0)
				c *= 2;
			t = t + c;
		}

		// Finally, add up all the single digits in this string.

		n = 0;
		for (i = 0; i < t.length; i++) {
			c = parseInt(t.charAt(i), 10);
			n = n + c;
		}

		// If the resulting sum is an even multiple of ten (but not zero), the
		// card number is good.

		if (n != 0 && n % 10 == 0)
			return true;
		else
			return false;
	}
	
	function isImageFile(filename)
	{
		var ext = filename.substr( filename.indexOf('.'), filename.length );
		
		return ( ext == '.gif' || ext == '.jpg' || ext == '.jpeg' || ext == '.png' );
	}
	

	function checkedRadio( radio_object )
	{
		if ( radio_object.length == undefined )
		{
			return radio_object.checked;
		}
		
		for( var i = 0; i < radio_object.length; i++) 
		{
			if ( radio_object[i].checked )
				return true;
		}
		
		return false;
		
	}	

	function convertEncoding(s)
	{
		// invalid characters from word... add them as you see fit
		var invalidChars = new Array();
		invalidChars[8211] = "-";
		invalidChars[8216] = "'";
		invalidChars[8217] = "'";
		invalidChars[8220] = "\"";
		invalidChars[8221] = "\"";
		invalidChars[8230] = "...";
		
		var newS = "";
		
		for ( var i = 0; i < s.length; i++ )
		{
			if ( invalidChars[s.charCodeAt(i)] != "" && invalidChars[s.charCodeAt(i)] != undefined )
				newS += invalidChars[s.charCodeAt(i)];
			else if ( s.charCodeAt(i) > 255 )
				newS += "";
			else
				newS += s.charAt(i);
		}
		
		return newS;
	}

	function checkFormFields(form)
	{
		return formHandler(form, true, false );
	}
	
	// Check all the form fields of a given form
	// Return false if its not filled in (or not filled in properly)
	
	function formHandler(form, doValidation, ajax ) 
	{
		var captcha = false;
		var i;
		var elements = form.elements;
	
		for ( i = 0; i < elements.length; i++ ) 
		{
			if ( elements[i].type == 'hidden' )
				continue;

			var datatype = elements[i].getAttribute('datatype');
							
			if ( elements[i] && elements[i].type == 'textarea' )
				elements[i].value = convertEncoding(elements[i].value);
	
			if ( !doValidation || ( datatype && datatype == 'notRequired' ) )
				continue;
		  	else if ( datatype && datatype == "cc" && !isCreditCard( elements[i] ) )
		  		customAlert("Please enter a valid Credit Card Number");
			else if ( datatype && datatype == "captcha" )
			{
				captcha = true;
				captchaKey = elements[i].value;
				continue;
			}
			else if ( elements[i] && elements[i].type == 'button' )
				continue;
		  	else if ( elements[i].value == "" )
		  		customAlert ("Please fill in all required form fields" );
		  	else if ( datatype && datatype == "image" && !isImageFile(elements[i].value) )
		  		customAlert("Sorry, only JPEG, GIF and PNG images can be uploaded");
		  	else if ( datatype && datatype == "email" && !isEmail(elements[i].value ) )
		  		customAlert("Please input an e-mail in the correct format");
		  	else if ( datatype && datatype == "confirmEmail" && elements['Email'].value != elements[i].value )
		  		customAlert("Please ensure your confirmation email matches your email address");
		  	else if ( datatype && datatype == 'double' && !isFloat(elements[i].value) )
		  		customAlert("Please input a number, without characters or '%'");
		  	else if ( datatype && datatype == 'dollar' && !isDollar(elements[i]) )
		  		customAlert("Please input an appropriate dollar figure, without characters or the '$' symbol");
		  	else if ( datatype && datatype == 'integer' && !isInt(elements[i].value) )
		  		customAlert("Please input an integer, without characters or decimals");
		  	else if ( datatype && datatype == 'requiredSelect' && ( elements[i].value == "" || elements[i].value < 0 ) )
		  		customAlert("Please choose an item from the drop down list");
		  	else if ( datatype && datatype == 'requiredSelectMultiple' && elements[i].value == "" )
				customAlert("Please select strategies from the list");
		  	else if ( datatype && datatype == 'requiredChoice' && !checkedRadio(elements[elements[i].name]) )
		  		customAlert("Please fill in all questions" );
			else if ( datatype && datatype == 'requiredRadio' && !checkedRadio(elements[elements[i].name]) )
		  		customAlert("Please fill in all Yes/No questions" );
		  	else
		  		continue;		  
		  		
		  	elements[i].focus();
		  	return false;
		}
		
		if ( captcha )
		{
			var myAjax = new Ajax.Request( 'captcha/check.php', { method:'post', parameters: "captchaKey=" + captchaKey, asynchronous:false } );
			
			if ( myAjax.transport.responseText == "" ) 
			{
				myCustomPrompt.end();
				customAlert("Sorry, this code does not match.  Please try again with the new code"); 
				$("captchaImg").src = "captcha/captcha.php?" + (++imgNum); 
				return false;
			}
		}

		
		if ( ajax === true )
		{
			// do ajax stuff
			
			new Ajax.Request( '../formHandler.php', { method:'post', parameters: Form.serialize(form), onSuccess: function(transport){ formSuccess(form,transport); }, onFailure: function(){ formFailure(form); } } ); 			
			return false;
		}
		else
		{
			return true;
		}
	}
	
	function submitToFormHandler(form, executeOnSuccess )
	{
		if ( executeOnSuccess === undefined || executeOnSuccess === "" )
			executeOnSuccess = "void(0);";
			
		new Ajax.Request( 'mailer.php', { method:'post', parameters: Form.serialize(form), onSuccess: function(transport){ myCustomPrompt.end(); eval(executeOnSuccess); }} ); 			
		
		myCustomPrompt.formLoading();
		return false;
	}
	
	function customAlert(message)
	{
		//customPrompt("Alert", message, new Array( { label: 'OK', callback: function() { myCustomPrompt.end(); } } ) );
		alert( message );
	}

	function customMessage( message )
	{
		customPrompt("Alert Message", message, new Array( { label: 'OK', callback: function() { myCustomPrompt.end(); } } ) );
	}

	function checkWordCount( instance, counter, max )
	{
		var passed = true;

		if ( wc(instance.value) > max ) 
		{
			alert ("You have reached the maximum limit of words");
			instance.value = clip(instance.value, max );
		}

		var counter = document.getElementById( counter );

		counter.innerHTML = "" + wc( instance.value );

		return passed;
	}
	

	function wc( text )
	{
		var word_count = 0;
		var words = text.replace('\n',' ');
		words = words.split(' ');

		for ( i = 0; i < words.length; i++) 
		{
			if (words[i].length > 0) 
				word_count++;
		}

		return word_count;
	}
	
	function clip( text, max_words )
	{
		var i = 0;
		var word_count = 0;
		var words = text.replace('\n',' ');
		words = words.split(' ');

		for ( ; i < words.length; i++) 
		{
			if (words[i].length > 0) 
				word_count++;
				
			if (word_count > max_words)
				break;
		}
		
		text = "";
		
		for ( j = 0; j < i; j++ )
			text += words[j] + " ";

		return text;
	}
	
	
	function formSuccess(form,transport)
	{
		myCustomPrompt.end();
		
		var lines = transport.responseText.split("\n");
		var returnCode = lines[0];
		
		if ( returnCode == "updateRow" )
		{
			var table = lines[1];
			var id = lines[2];
			
			// row object
			eval( lines[3] );
			
			for( var i = 0; i < form.elements.length; i++ )
			{	
				if ( form.elements[i].type != "submit" && form.elements[i].type != "hidden" )
				{
					if ( field = $( table + id + form.elements[i].name ) )
					{
						var fieldValue = unescape(rowObject[form.elements[i].name]);
						
						if ( field.getAttribute("maxChars") > 0 && fieldValue.length > field.getAttribute("maxChars") )
							fieldValue = fieldValue.substr( 0, field.getAttribute("maxChars") ) + "&hellip;";
							
						field.innerHTML = fieldValue;
					}
				}
			}			
		}
		else if ( parseInt(returnCode) !== 0 )
		{
			alert( transport.responseText );
		}
		
		if ( form.hideAfter )
		{
			form.style.display = "none";
			form.reset();
		}
	}
	
	function formFailure(form)
	{
		myCustomPrompt.end();
		alert( "fail" );
	}
	
	
	Ajax.Responders.register(
	{   
		onCreate: function()
		{   
			void(0);
			//myCustomPrompt.formLoading();   
		}
	}); 
	

