$(document).ready(function(){
	$("#frmjobseeker").formcheck({ tips: true });
	$("#frmsearchrefinement").formcheck({ tips: false });
	$("#frmlocsearch").formcheck({ tips: false });
	$("#frmcompanydetails").formcheck({ tips: true });
});

(function() {

	jQuery.fn.formcheck = function(args) {

		var args = jQuery.extend({ tips: true }, args);

		if($(this).length > 0){

			for(arg in args){ $(this).opts[arg] = args[arg]; }

			$(this).enableValidator();
			$(this).submitEvent();
			$(this).getElements();

		}

	};

	var formcheck_methods = {

		validator : null,
		opts : { showing: "", validity: "true", unique: "true" },
		elements : {},

		submitEvent : function(){

			var form = this;

			$("#run_data_check").click(function(){

				$(this).opts["validity"] = "true";
				$("#error_list").empty();
				for(e in $(form).elements){ $(form).validateElement($("#"+e)); }
				if($("#username").length > 0 && $("#username").val() == ""){ $("#username").val($(form).opts['username']); }
				if($("#email").length > 0){ $(form).uniqueSubmit($("#email").val()); }

			});

			$("#"+$(this).attr("id")+"_submit").click(function(){

				$('#create_cv_dialog').dialog("close");
				for(e in $(form).elements){ $(form).validateElement($("#"+e)); }
				if($("#username").length > 0 && $("#username").val() == ""){ $("#username").val($(form).opts['username']); }
				if($("#email").length > 0){ $(form).uniqueCheck($("#email").val()); }
				if($(form).opts["validity"] == "true"){
					$(form).submit();
				}

			});

			$("#close_display_error").click(function(){

				$('#display_error_dialog').dialog("close");

			});

		},

		continueSubmit : function(){

            if($(this).opts["validity"] == "true"){
                if ($("#frmjobseeker").attr("action") == "/job-seekers/cv-creator") {
                    $("#frmjobseeker").attr("action", "/job-seekers/cv-creator");
                    $("#create_cv_action").val("upload");
                    document.getElementById("frmjobseeker").submit();
                } else {
                    //--$('#create_cv_dialog').dialog("open");
                    document.getElementById("frmjobseeker").submit();
                }
            } else{
                $('#display_error_dialog').dialog("open");
            }

		},

		enableValidator : function(){

			var form = this;

			$(this).validator = $(this).validate({

				errorElement: "span", errorClass: "hide_error",
				showErrors: function(errorMap, errorList) {

					if($(form).opts['unique'] == "false"){
						$("#number_of_errors").html("Unfortunately your form contains " + (this.numberOfInvalids()+1) + " errors.<br />NOTE: Specified Email Address already registered.<br />");
					}else{
						$("#number_of_errors").html("Unfortunately your form contains " + this.numberOfInvalids() + " errors.");
					}

					$(errorList).each(function(i,n){
						var li = $("<li></li>").html(n.message);
						$("#error_list").append(li);
					});
					this.defaultShowErrors();

				}

			});

		},

		addValidation : function(id){

			var form = this;

			var e = $(this).elements[id];
			var rules = {};
			var messages = {};
			if(e['required'] != "" && e['required'] != "confirm"){ rules['required'] = true; }
			if(e['required'] == "email"){ rules['email'] = true; }
			else if(e['required'] == "confirm"){ rules['equalTo'] = "#"+e['confirm']; }
			else if(e['required'] == "numeric"){ rules['number'] = true; }
			if(e['min'] != ""){ rules['min'] = e['min']; }

			$("#"+id).rules("add", rules);
			$(this).addValidationEvent($("#"+id));

		},

		addValidationEvent : function(e){

			var form = this;

			if(e.type == "checkbox"){ $(e).click(function(){ $(form).validateElement($(this)); }); }
			else { $(e).keyup(function(){ $(form).validateElement($(this)); }); }
			if (e.attr("id") == "email") { $(e).change(function(){ $(form).uniqueCheck($(this).val()); }); }

		},

		validateElement : function(e){
			var id = $(e).attr("id");
			var fe = $(this).elements[id];

			var check = $(this).validate({ required : fe['label'] }).element($(e));

            //-- MOD: 2009/12/04 8:13:19
            if (fe['label'] == 'Region') {
                //alert(fe['label'] + '::' + check);
                if ($("#country_id").val() != 244 && check == false) {
                    check = true;
                }
            }
            if (fe['label'] == 'Location (Suburb, Town or City)') {
                //alert(fe['label'] + '::' + check);
                if ($("#country_id").val() != 244 && check == false) {
                    check = true;
                }
            }

            if(!check){

				if(!$("#"+id).hasClass("red")){ $("#"+id).addClass("red"); }
				if($("#msg_"+id).hasClass("info")){ $("#msg_"+id).removeClass("info"); }
				$("#msg_"+id).addClass("error");
				$("#msg_"+id).html($(this).elements[id]['error']);
				$(this).opts["validity"] = "false";

			}else{

				if($("#"+id).hasClass("red")){ $("#"+id).removeClass("red"); }
				if($("#msg_"+id).hasClass("error")){ $("#msg_"+id).removeClass("error"); }
				$("#msg_"+id).addClass("info");
				$("#msg_"+id).html($(this).elements[id]['hint']);

			}

		},

		forceStatus : function(id, msg){

			if(!$("#"+id).hasClass("red")){ $("#"+id).addClass("red"); }
			if($("#msg_"+id).hasClass("info")){ $("#msg_"+id).removeClass("info"); }
			$("#msg_"+id).addClass("error");
			$("#msg_"+id).html(msg);

		},

		addLookups : function(id){

			if($(this).elements[id]['define'] != ""){

				var form = this;
				$("#"+id).change(function(){

					var s = $(form).elements[$(this).attr("id")];
					var e = $(form).elements[s['define']];

					$(form).lookupSelect(id, $(this).val(), e['source'], s['define'], e['display']);

				});

			}

		},

		addHint : function(id){

			var form = this;

			if($(this).opts['tips']){

				var span = $("<span></span>").attr({ id:"msg_"+id }).addClass("info").html($(this).elements[id]['hint']);
				$("#"+id).after(span);
				$(span).css({ position:"absolute", zIndex: 999, marginLeft: 3, marginTop: 0 });
				$("#"+id).hover( function(){

					if(!$(form).elements[$(this).attr("id")]['hidden']){
						if($(form).opts['showing'] != ""){ $($(form).opts['showing']).hide(); }
						$("#msg_"+$(this).attr("id")).show();
						$(form).opts['showing'] = "#msg_"+$(this).attr("id");
					}

				}, function(){ $("#msg_"+$(this).attr("id")).hide(); });

			}

		},

		getElements : function(){

			var form = this;

			$.get('/javascript/includes/formcheck.php', { name: $(this).attr("id") },
			function(data){

				$(form).opts['username'] = $(data).find("time").text();
				$(data).find("element").each(function(element){

						var id = $(this).find("id").text();

						if($("*").index( $("#"+id) ) > -1){

							$(form).elements[id] = {
								label: $(this).find("label").text(),
								hint: $(this).find("hint").text(),
								error: $(this).find("error").text(),
								required: $(this).find("required").text(),
								min: $(this).find("min").text(),
								confirm: $(this).find("confirm").text(),
								source: $(this).find("source").text(),
								define: $(this).find("define").text(),
								display: $(this).find("display").text()
							};

							$(form).addHint(id);
							$(form).addValidation(id);
							$(form).addLookups(id);

						}

				});

			});

		},

		lookupSelect : function(key, value, source, define, display){

            // MOD: 2009/12/08 14:26:52
            if (key == 'country_id' && value != '244') {
                $("#region_id").find("option:first").html("Not Applicable");
                $('#region_id').val('');
                $("#region_id").attr("disabled", true);
                $("#region_id").attr("readonly", true);
                $("#location_id").find("option:first").html("Not Applicable");
                $('#location_id').val('');
                $("#location_id").attr("disabled", true);
                $("#location_id").attr("readonly", true);
            } else {
                if (key == 'country_id' && value == '244') {
                    $("#region_id").attr("disabled", false);
                    $("#region_id").attr("readonly", false);
                    $("#location_id").find("option:first").html("Please Select");
                    $("#location_id").val('');
                    $("#location_id").attr("disabled", false);
                    $("#location_id").attr("readonly", false);
                }

                var form = this;
                $.get('/javascript/includes/lookups.php', { key: key, value: value, source: source, define: define, display: display },
                function(data){
                    $("#"+define).empty();
                    $(data).find("option").each(function(element){
                        var option = $("<option></option>").attr("value", $(this).find("value").text()).html($(this).find("text").text());
                        $('#'+define).append(option);
                    });
                });
                // MOD: 2009/12/08 14:26:52
            }
		},

		uniqueCheck : function(email){
			var form = this;
			$.get('/javascript/includes/uniquecheck.php', { email: email },
			function(data){
				if(data == "false"){
					$(form).opts["validity"] = "false";
					$(form).opts["unique"] = "false";
					$(form).forceStatus("email", "Sorry, this email address is already taken. Please try again.");
				}
			});
		},

		uniqueSubmit : function(email){
			var form = this;
			$.get('/javascript/includes/uniquecheck.php', { email: email },
			function(data){
				if(data == "false"){
					$(form).opts["validity"] = "false";
					$(form).opts["unique"] = "false";
					$(form).forceStatus("email", "Sorry, this email address is already taken. Please try again.");
				}
				$(form).continueSubmit();
			});
		}


	};

	jQuery.each(formcheck_methods, function(i) {
		jQuery.fn[i] = this;
	});


})(jQuery);
