//Javascript Document
(function($){
$(window).load(function(){
	$("input.clearText").focus(function(){
		clearTextInput(this);
	}).blur(function(){
		checkInputField(this);
	})
	$("input").each(function(i){
		this.txt = this.value;
	})
	
	$("textarea.clearText").focus(function(){
		clearTextInput(this);
	}).blur(function(){
		checkInputField(this);
	});
	$("textarea").each(function(i){
		this.txt = this.value;
	});
	$("input.password").focus(function(){
		changePass(this);
	});
});
//changes a password field from plain text to password so that I can put text in the field exclaiming Password: prior to focus
function changePass(t){
	var p = "<input type='password' name='"+$(t).attr("name")+"' class='"+$(t).attr("class")+"' value='' onblur='resetPass(this)'/>";
	$(t).after(p).remove();
	$(".password").focus();	
}
//changes a password input field back to plain text with a value of Password: if the field is empty so users know what is required.
function resetPass(t){
	if(t.value != "")return;
	var p = "<input type='text' name='"+$(t).attr("name")+"' class='"+$(t).attr("class")+"' value='Password:' onfocus='changePass(this)'/>";
	$(t).after(p).remove();
}
//usage: form input text element onfocus="clearTextInput(this);" | Clears the form element of any default text and stores that text in a txt property
function clearTextInput(Input){
	if(!Input.txt)
		Input.txt = Input.value;
	if(Input.txt == Input.value)
		Input.value = "";
}
//usage: form input text element onblur="checkInputField(this)"; | Checks the form element and replaces it with default text if the field was left empty by the user
function checkInputField(Input){
	if(Input.value == "")
		Input.value = Input.txt;
}






//setup variables and randomly pick 2 numbers between 1 and 10 to use a captcha device
var aa = Math.ceil(Math.random() * 10);
var bb = Math.ceil(Math.random() * 10);
var cc = aa + bb;
var isCaptcha = false;
//outputs the html for the simple match captcha
function DrawBotBoot(){
	isCaptcha = true;
	///document.write("<label for='BotBootInput'>What is "+ aa + " + " + bb +"? </label><span class='captcha'></span>");
	document.write("<input id='BotBootInput' class='clearText required' type='text' size='2' value='What is "+ aa + " + " + bb +"?'/>");
}
//a function that validates the captcha element. Run this on submit or check it in any submit function.
function ValidBotBoot(){
	var dd = document.getElementById('BotBootInput').value;
	if (dd == cc) return true;
	document.getElementById('BotBootInput').value = "What is "+ aa + " + " + bb +"?";
	return false;
}

//email/string validation functions compressed to save space. I don't really need to see them all out.
function Validate_String(string){valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';invalid_chars = '';if(string == null || string == '')return(true);for(index = 0; index < string.length; index++){char = string.substr(index, 1);if(valid_chars.indexOf(char) == -1){if(invalid_chars.indexOf(char) == -1){if(invalid_chars == '')invalid_chars += char;else invalid_chars += ', ' + char;}}}   }
function Validate_Email_Address(email_address){at = email_address.indexOf('@');dot = email_address.lastIndexOf('.');if(at == -1 || dot == -1 || dot <= at + 1 || dot == 0 || dot == email_address.length - 1)return false;user_name = email_address.substr(0, at);
domain_name = email_address.substr(at + 1, email_address.length);if(Validate_String(user_name) === false || Validate_String(domain_name) === false)return false;   return true;}

$.fn.validate = function(o){
    return Validate_func(o.form);
};

function Validate_func(Form, extra){//requires jquery
	console.log(this);
	var err = false;
	var Form = Form;
	if(extra)
		err = complyForm(Form);
	
	/*
	if($("input.captcha")){
		if(!validateLoop(Form, err))return false;
		var captchaForm = $("input.captcha");
		$.ajax({ 
			type: "POST"
			,url: "scripts/securimage/captchaAjax.php"
			,data: "captcha="+$("input.captcha").val()
			,success: function(msg){
				if(!msg){
					err = true;
					$(captchaForm).val("Incorrect Code").addClass("error");
				}else
					Form.submit();
				
	      	}
		});
		
	}else */if(validateLoop(Form, err)){
		console.log("SUBMIT");
		Form.submit();
	}else{
		return false;
	}
	//return false;
}

function validateLoop(Form, err){
	var radChecked = [];
	var num = Form.length;
	
	
	for(i=0;i<num;i++){
		if($(Form[i]).hasClass("required")){			
			if( !Form[i].txt || Form[i].value == Form[i].txt || Form[i].value == Form[i].txt || Form[i].value == "Invalid Email" ){
				
				if($(Form[i]).hasClass("select")){
					if(!Form[i].value){
						err = true;
						$(Form[i]).before("<div class='selectError error"+i+"'>"+$(Form[i]).attr("title")+"</div>");
					}
					continue;
				}
				
				if($(Form[i]).hasClass("radio")){
					var found = false;
					if(!$(":checked", Form[i]).val()){
						var name = $(Form[i]).attr("name");						
						if($("[name="+name+"]:checked",Form).val()){
							continue;
						}
						for(var e = 0;e<radChecked.length;e++)
							if($(Form[i]).attr("name") == radChecked[e]){
								found = true;
								break;
							}
						if(found)continue;
						radChecked.push($(Form[i]).attr("name"));
						err = true;
						
						$(Form[i]).before("<div class='radioError error"+i+"'>"+$(Form[i]).attr("title")+"</div>");
					}
					continue;
				}
				
				if(!Form[i].txt)
					Form[i].txt = Form[i].value;
				
				Form[i].value = Form[i].txt; 
				
				$(Form[i]).addClass("error");
				$(Form[i]).bind("focus", function(e){
					$(this).removeClass("error");
					$(this).attr({"value":""});
				});
				err = true;
			}
		}
		if($(Form[i]).hasClass("email")){
			if(!Validate_Email_Address(Form[i].value)){
				Form[i].value = "Invalid Email";
				$(Form[i]).addClass('error');
				err = true;
			}
		}
	}
	
	if(isCaptcha)
		if( ValidBotBoot() == false ){ 
			alert("Please tell us what "+ aa + " + " + bb +" is. This is a device to help keep spam down.");
			err = true;
		}
	
	$(".radioError").each(function(e){
		$(this).hover(function(){
			$(this).animate({opacity:0},600,function(){$(this).remove()});
		});
	});
	$(".selectError").each(function(e){
		$(this).hover(function(){
			$(this).animate({opacity:0},600,function(){$(this).remove()});
		})
	});
		
	if(err){
		$("body").prepend("<div class='formErrorMsg'>Form elements marked in red are required.</div>");
		$(".formErrorMsg").animate({marginTop:"0px"});
		$(".formErrorMsg").hover(function(){
			$(this).animate({opacity:0},600,function(){$(this).remove()});
		});
		return false;
	}else
		return true;
	
}


function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';

            case '':
                return '';
            default:
                return n1;
        }
    });
}

function onlyNumbers(e){
	var keynum
	var keychar
	var numcheck

	if(window.event){// IE
		keynum = e.keyCode;
	}
	else if(e.which){// Netscape/Firefox/Opera
		keynum = e.which;
	}
	var character = String.fromCharCode(keynum);
	keychar = String.fromCharCode(keynum)
	numcheck = /[^0-9.,]/;//restrict to only numbers
	if (!e.ctrlKey && keynum!=9 && keynum!=8 && (keynum!=39 || (keynum==39 && character=="'")) && keynum){
		return !numcheck.test(keychar);
	}
	return true;
}



function ConfirmDelete(){
	if( confirm("Are you sure you want to delete this?\n\nOK=Yes - Cancel=No") ){
		return true;
	}else{
		return false;
	}
}

}(jQuery));
