jQuery.extend(
  jQuery.expr[ ":" ],
  { reallyvisible : "(jQuery(a).is(':visible') && jQuery(a).parents(':hidden').length == 0)" }
);

// max length plugin
$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
    	var parts = el.value;
    	if ( settings.words )
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	$charsLeft = $form.find(settings.feedback);

    	function limitCheck(event) {
        	var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;

        	if ( !exceeded )
        		return;

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37: 
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }


        var updateCount = function () {
            var len = length(field),
            	diff = limit - len;

            $charsLeft.html( diff || "0" );

            // truncation code
            if (settings.hardLimit && diff < 0) {
            	field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit*2)-1).join('') :
            		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

$.fn.maxlength.defaults = {
    useInput : false,
    hardLimit : true,
    feedback : '.charsLeft',
    words : false
};

$.fn.copyTo = function(to) {
    var to = $(to);
    for ( var i = 1; i < arguments.length; i++ )
        to.set( arguments[i], this.get(0)[ arguments[i] ] );
    return this;
};

new function() {
       // $.fn.validate = validate() {};
    $.fn.validate = {
        init: function(o) {
          if(o.name == 'username') { this.username(o); }
          else if(o.name == 'password') { this.password(o); }
          else if(o.name == 'email') { this.email(o); }
          else if(o.name == 'date_of_birth') { this.dob(o); }
		  else { this.blank(o);};
        },
        username: function(o) {
          var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(user)) {
             doValidate(o);
            } else {
             doError(o,'no special characters allowed');
            };
        },
        password: function(o) {
          var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
           if (!o.value.match(pass)) {
             doValidate(o);
            } else {
             doError(o,'no special characters allowed');
            };
        },
        email: function(o) {
          var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (o.value.match(email)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid email');
            };
        },
        dob: function(o) {
          var dob  = /(0[1-9]|1[012])+\/(0[1-9]|[12][0-9]|3[01])+\/(19|20)\d\d/;
            if (o.value.match(dob)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid date');
            };
        },
        blank: function(o) {
            if (o.value.replace(/^\s+|\s+$/g,"") != '') {
              doSuccess(o);
            } else {
              doError(o,'This field can not be left blank');
            };
        }
     };

     function doSuccess(o) {
              $('#' + o.id + '_img').html('<img src="images/formvalidation/accept.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').removeClass("error");
              $('#' + o.id + '_msg').html("");
              $('#' + o.id + '_li').addClass("success");
     }

     function doError(o,m) {
              $('#' + o.id + '_img').html('<img src="images/formvalidation/exclamation.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').addClass("error");
              $('#' + o.id + '_msg').html(m);
              $('#' + o.id + '_li').removeClass("success");
     }
     //private helper, validates each type after check
     function doValidate(o) {
        	$('#' + o.id + '_img').html('<img src="images/formvalidation/loading.gif" border="0" style="float:left;" />');
        	$.post('ajax.php', { id: o.id, value: o.value }, function(json) {
                  	eval("var args = " + json);
                    if (args.success == true)
                  	{
						doSuccess(args);
                  	}
                  	else
                  	{
						doError(args,args.msg);
                  	}
                  });
    };

};

$(document).ready(function()
{
	$(".datepicker").datepicker();
	$("#for_presenters").hide();
	
	$("#inline_form").hide();
	$("#pre_loader_img").hide();
	$("#email_found").hide();
	
	
	
	$("input[name='consider']").click(function(){
		if($("#paper").val().replace(/^\s+|\s+$/g,"") == '')
		{
			alert("You can not be considered for travel unless you have uploaded your paper");
			$("input[name='consider']:last").attr('checked', true);
			$("#paper").trigger('blur');;
		}
	});
	
	$("input[name='presenting_a_paper']").click(function(){											 	
		if($(this).val() == "yes")
		{
			$("#for_presenters").fadeIn();
			$("#for_other_participants").fadeOut();									  
		}
		else
		{
			$("#for_presenters").fadeOut();
			$("#for_other_participants").fadeIn();									  
		}
	});
	
	//$("//[@class=validated]/input").blur(function() 
													
	$(".validated input").blur(function() {	
		if ($(this).is (':visible') && $(this).parents (':hidden').length == 0)
		{
			$(this).validate.init(this);
		}
	});
	
	$("#email").change(function() {$(this).trigger('keyup')});
	$("#email").blur(function() {$(this).trigger('keyup')});
	$("#email").keyup(function() {
		   var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
           if (!$("#email").val().match(email)) {
              return;
            };
				
		this.timer = setTimeout(function () {
		$("#inline_form").slideDown();
		$("#pre_loader_img").show();
        $.ajax({
          url: 'index.php',
          data: 'option=com_call_for_papers&task=ajax_option&email='+$("#email").val(),
          dataType: 'json',
          type: 'post',
          success: function (j) {
			  	if(j.rows_returned == 0)
				{	
					$("#inline_form").hide();
					$("#pre_loader_img").hide();
					$("#email_found").hide();
					return;
				}
			  	$("#pre_loader_img").hide();
				$("#email_found").show();
				$("#update_current").click(function(){
						$.each( j, function(index, indexValue)
						{
							//alert(index);
							$("[name=" + index + "]").val(indexValue);
						});
						$("#inline_form").slideUp();
						$('.validated  :input').trigger('blur');
				});
			  }
        });
      }, 200);

	});
	
	$("#re_register").click(function(){
			$("#inline_form").slideUp();
	});
	
	//consider_for_funding
	
	$(".validated textarea").blur(function() {	
		if ($(this).is (':visible') && $(this).parents (':hidden').length == 0)
		{
			$(this).validate.init(this);
		}
	});
	
	
	$(".validated input.date").change(function() {								
		   $(this).validate.init(this);
	});
	
	// This Used To Be HOVER, But I.E. Didnt Like It
	//$(".form li").hover(function(){$(this).addClass("selected");},function(){$(this).removeClass("selected");});
	$("#warsaw li").mouseover(function() {
		  $(this).addClass("selected");
	});
	$("#warsaw li").mouseout(function() {
		  $(this).removeClass("selected");
	});
	
	// This Used To Be HOVER, But I.E. Didnt Like It
	//$(".form li").hover(function(){$(this).addClass("selected");},function(){$(this).removeClass("selected");});
	$("#questioner li:not(.plain)").mouseover(function() {
		  $(this).addClass("selected");
	});
	$("#questioner li:not(.plain)").mouseout(function() {
		  $(this).removeClass("selected");
	});
	
	$("#warsaw input.checkbox").click(function() {									
		  var se = $('#warsaw input.checkbox:checked').length;
		  var oid = "checkbox";
		  if(se > 2)  {
			  $('#' + oid + '_img').html('<img src="images/formvalidation/exclamation.gif" border="0" style="float:left;" />');
              $('#' + oid + '_li').addClass("error");
              $('#' + oid + '_msg').html("Please pick a maximum of two Thematic areas");
              $('#' + oid + '_li').removeClass("success");
		  }   else {
			  $('#' + oid + '_img').html('');
			  $('#' + oid + '_li').removeClass("error");
              $('#' + oid + '_msg').html("");
              $('#' + oid + '_li').addClass("success");
		  }
		  
	});
	  
	$('form').submit(function() {
							  
		$('.validated  :input').trigger('blur');
		$("#warsaw input.checkbox").trigger('blur');
		
		var numWarnings = $('.error', this).length;
		if(numWarnings){
			alert("Please correct errors with " + numWarnings + " fields, please fix them before resubmitting your details");
			return false;	
		}
	});
	
	$('#toggleSection').hide();
	$('#toggleButton').click(function() {
		if ($('#toggleSection').is(":hidden"))
		{
			$('#toggleSection').slideDown("Fast");
			$("#toggleButton").html("");
		}
	});	
	
	$('#toggleSection2').hide();
	$('#toggleButton2').click(function() {
		if ($('#toggleSection2').is(":hidden"))
		{
			$('#toggleSection2').slideDown("Fast");
			$("#toggleButton2").html("");
		}
	});

	$("select[id^=status]").change(function(){
		var text = this.id;	
		var wildcard = "status";
		var suffix = "";
		suffix = text.substring(wildcard.length,text.length);
		if($('#status' + suffix).val() == "Pipe Line")
		{
			$("#end_date" + suffix + "_label").html("Possible End Date<em>*</em>");
			$("#start_date" + suffix + "_label").html("Possible Start Date<em>*</em>");
		}
		else
		{
			$("#end_date" + suffix + "_label").html("End Date<em>*</em>");
			$("#start_date" + suffix + "_label").html("Start Date<em>*</em>");
		}
	});  
});