//dict stuff for IE
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
//
$(document).ready(function () {
	// vars
	$.fn.Forms = {}; //holds a link to each type=formValidator by id
	$.fn.RequiredFields = {}; //holds an array of links to each field with required=true by form id
	//
	$.fn.States = {}; //holds all the states by country
	$.fn.States['usa'] = "<option value=''>Select State</option><option value='AL'>Alabama</option><option value='AK'>Alaska</option><option value='AZ'>Arizona</option><option value='AR'>Arkansas</option><option value='CA'>California</option><option value='CO'>Colorado</option><option value='CT'>Connecticut</option><option value='DE'>Delaware</option><option value='DC'>DC</option><option value='FL'>Florida</option><option value='GA'>Georgia</option><option value='HI'>Hawaii</option><option value='ID'>Idaho</option><option value='IL'>Illinois</option><option value='IN'>Indiana</option><option value='IA'>Iowa</option><option value='KS'>Kansas</option><option value='KY'>Kentucky</option><option value='LA'>Louisiana</option><option value='ME'>Maine</option><option value='MD'>Maryland</option><option value='MA'>Massachusetts</option><option value='MI'>Michigan</option><option value='MN'>Minnesota</option><option value='MS'>Mississippi</option><option value='MO'>Missouri</option><option value='MT'>Montana</option><option value='NE'>Nebraska</option><option value='NV'>Nevada</option><option value='NH'>New Hampshire</option><option value='NJ'>New Jersey</option><option value='NM'>New Mexico</option><option value='NY'>New York</option><option value='NC'>North Carolina</option><option value='ND'>North Dakota</option><option value='OH'>Ohio</option><option value='OK'>Oklahoma</option><option value='OR'>Oregon</option><option value='PA'>Pennsylvania</option><option value='RI'>Rhode Island</option><option value='SC'>South Carolina</option><option value='SD'>South Dakota</option><option value='TN'>Tennessee</option><option value='TX'>Texas</option><option value='UT'>Utah</option><option value='VT'>Vermont</option><option value='VA'>Virginia</option><option value='WA'>Washington</option><option value='WV'>West Virginia</option><option value='WI'>Wisconsin</option><option value='WY'>Wyoming</option>";
	$.fn.States['ca'] = "<option value=''>Select State</option><option value='AB'>Alberta</option><option value='BC'>British Columbia</option><option value='MB'>Manitoba</option><option value='NB'>New Brunswick</option><option value='NL'>Newfoundland and Labrador</option><option value='NT'>Northwest Territories</option><option value='NS'>Nova Scotia</option><option value='NU'>Nunavut</option><option value='ON'>Ontario</option><option value='PE'>Prince Edward Island</option><option value='QC'>Quebec</option><option value='SK'>Saskatchewan</option><option value='YT'>Yukon</option>";
	// vars
	
	//checks if given string is a valid email address, returns true or false
	$.fn.CheckEmail = function(email) {
		AtPos = email.indexOf("@");
		StopPos = email.lastIndexOf(".");
		//
		if( email.length == 0 ) {
			return false;
		}
		if( AtPos == -1 || StopPos == -1 ) {
			return false;
		}
		if( StopPos < AtPos ) {
			return false;
		}
		if( StopPos - AtPos == 1 ) {
			return false;
		}
		if( StopPos+2 >= email.length ) {
			return false;
		}
		
		return true;
	};
	
	//returns the integer of an item by id in the RequiredFields array
	$.fn.getRequiredField = function(formid, attrid) {
		returnVal = -1;
		$.fn.RequiredFields[this_id].forEach(function(curValue, curIndex, curArray) {
			if( curValue.attr("id") == attrid ) {
				returnVal = curIndex;
			}
		});
		return returnVal;
	};
	
	//adds our default actions to an element handed to it
	$.fn.addActions = function(element) {
		element.blur( function() {
			if ( element.val().length == 0 ) {
				//alert( $(this).attr("style") );
				//$(this).attr("style", "background:gray;");
				//element.css({"border-color":"red"});
				//alert("blur");
				element.css({"background":"#CC6666"});
			}
			else {
				//$(this).attr("style", "margin-bottom: 0px;border-color:black");
				//$(this).removeAttr("style");
				element.css({"background":"white"});
			}
		});
		//
		element.change( function() {
			if ( element.val().length == 0 ) {
				element.css({"background":"#CC6666"});
			}
			else {
				element.css({"background":"white"});
			}
		});
	};
	
	//adds verification of contents to field
	$.fn.addFieldVerification = function(element) {
		element.blur( function() {
			if (element.val() == "submit") {
				element.css({"background":"white"});
			}
			else {
				element.css({"background":"#CC6666"});
			}
		});
		
		element.keyup( function() {
			if (element.val() == "submit") {
				element.css({"background":"white"});
			}
			else {
				element.css({"background":"#CC6666"});
			}
		});
	};
	
	//adds properfy to contents of a field
	$.fn.addProperfy = function(element) {
		element.keyup( function() {
			mystr = element.val();
			//uppercase the first char
			if (mystr.length > 0) {
				mystr = mystr.charAt(0).toUpperCase() + mystr.substr(1).toLowerCase();
			}
			//if there are spaces, upper case the next word
			space = mystr.indexOf(" ");
			while (space > 0) {
				if (space+1 < mystr.length) {
					mystr = mystr.substr(0,space+1) + mystr.charAt(space+1).toUpperCase() + mystr.substr(space+2);
				}
				space = mystr.indexOf(" ", space+1);
			}
			
			element.val(mystr);
		});
	};
	
	//find each form on the document and link it to $.fn.Forms
	$(this).find("*[type=formValidator]").each( function() {
		//add this form to Forms
		this_id = $(this).attr("id");
		if (this_id != "") {
			$.fn.Forms[this_id] = $(this)
		}
		
		//add an array of required=true fields to RequiredFields by form id
		//add events to each object we discover
		var reqArray = new Array();
		$(this).find("*[required=true]").each( function() {
			reqArray.push( $(this) );
			//
			$.fn.addActions($(this));
		});
		$.fn.RequiredFields[this_id] = reqArray;
		
		//check the secret cap thing if we need it.
		$(this).find("#secret").each( function() {
			//alert("found one!");
			$.fn.addFieldVerification($(this));
		});
		
		$(this).find("*[properfy=true]").each( function() {
			$.fn.addProperfy($(this));
		});
		
		//add customization to any reset buttons
		$(this).find(":input[type=reset]").each( function() {
			$(this).click( function(event) {
				$.fn.RequiredFields[this_id].forEach(function(curValue, curIndex, curArray) {
					//set each border to black since we are resetting
					curValue.css({"background":"white"});
				});
				
				$("#secret").css({"background":"white"});
			});
		});
		
		//setup formatting for type=phone
		$(this).find(".phone").each( function() {
			$(this).keyup( function(event) {
				cur_val = $(this).val();
				//
				if (cur_val.length >= 4 && cur_val.charAt(3) != "-") {
					cur_val = cur_val.substr(0,3) + '-' + cur_val.substr(3);
				}
				if (cur_val.length >= 8 && cur_val.charAt(7) != "-") {
					cur_val = cur_val.substr(0,7) + '-' + cur_val.substr(7);
				}
				//
				if (cur_val != $(this).val() ) {
					$(this).val(cur_val);				
				}
			});
		});
		
		//setup class="country"
		$(this).find(".country").each( function() {
			target_div = $(this).attr("effect");
			target_div_o = $("#"+target_div);
			field_id = target_div_o.children().attr("id");
			req_field_pos = $.fn.getRequiredField(this_id, field_id);
			//
			$(this).change( function() {
				switch( $(this).val() ) {
					case "usa":
						target_div_o.html("<select id=\"" + field_id + "\" required=true>" + $.fn.States['usa'] + "</select>");
						$.fn.RequiredFields[this_id][req_field_pos] = target_div_o.children();
						$.fn.addActions( target_div_o.children() );
						break;
					case "ca":
						target_div_o.html("<select id=\"" + field_id + "\" required=true>" + $.fn.States['ca'] + "</select>");
						$.fn.RequiredFields[this_id][req_field_pos] = target_div_o.children();
						$.fn.addActions( target_div_o.children() );
						break;
					case "other":
						target_div_o.html("<input id=\"" + field_id + "\" required=true />");
						$.fn.RequiredFields[this_id][req_field_pos] = target_div_o.children();
						$.fn.addActions( target_div_o.children() );
						break;
					default:
						target_div_o.html("<select id=\"" + field_id + "\" required=true><option value=''>Select State</option></select>");
						$.fn.RequiredFields[this_id][req_field_pos] = target_div_o.children();
						$.fn.addActions( target_div_o.children() );
				}
			});
		});
		
		//setup class="email"
		$(this).find(".email").each( function() {
			$(this).keyup( function() {
				email_address = $(this).val();
				email_field = $(this)
				//
				if( $.fn.CheckEmail(email_address) == false ) {
					email_field.css({"background":"#CC6666"});
				}
				else {
					email_field.css({"background":"white"});
				}
			});
		});
	});

	//intercept post events for type=formValidator
	$("*[type=formValidator]").submit( function(event) {
		//event.preventDefault();
		this_id = $(this).attr("id");
		var form_correct = true;
		//
		$.fn.RequiredFields[this_id].forEach(function(curValue, curIndex, curArray) {
			if ( curValue.val().length == 0) {
				curValue.css({"background":"#CC6666"});
				form_correct = false;
			}
			else {
				curValue.css({"background":"white"});
			}
		});
		//
		if ($("#secret").val() != "submit") {
			form_correct = false;
			$("#secret").css({"background":"#CC6666"});
		}
		//
//		if (form_correct) {
//			event.preventDefault();
//			//alert("send email");
//			this_o = $(this);
//			//
//			this_o.animate({ height:"toggle", opacity:"toggle" }, 550, function() {
//				this_o.html("<br /><p>Thank you for your interest.  You should hear from us within on hour.</p><br />");
//				this_o.animate({ height:"toggle", opacity:"toggle" }, 700);
//			});
//		}
//		else {
//			event.preventDefault();
//		}
		if (!form_correct) {
			event.preventDefault();
		}
	});
	
});
