// Rate My Placment Global jQuery Functions

// VALIDATION

//Removes Error Messages
jQuery.fn.removeErrorMessage = function() {
	$('#err_'+this.attr('id')).remove();
	this.removeClass('error');
}

//Adds Inline Error Message
jQuery.fn.addErrorMessage = function(msg) {
	msg = msg?msg:'You must complete this';
	this.addClass('error');
	$('.error:first').focus();
	this.after('<div class="error-message" id="err_'+this.attr('id')+'">'+msg+'</div>');
}

//Checks if textfield is blank
jQuery.fn.validateNotBlank = function(msg) {
	msg = msg?msg:'This cannot be left blank';
	if(jQuery.trim(this.val())=='') {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if select is not value="0"
jQuery.fn.validateIsSelected = function(msg) {
	msg = msg?msg:'You must make a selection';
	if(this.val()=='0' || this.val()=='') {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if a radio button has been selected
jQuery.fn.validateRadioIsChecked = function(msg) {
	msg = msg?msg:'You must make a selection';
	if(this.find('input:radio:checked').length==0) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.find('label:last').addErrorMessage(msg);
		} return false; // Fail
	} else this.find('label:last').removeErrorMessage();
	return true;
}

//Checks if a checkbox has been selected (apply to wrapper)
jQuery.fn.validateCheckboxIsChecked = function(msg) {
	msg = msg?msg:'You must make at least one selection';
	if(this.find('input:checkbox:checked').length==0) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if email is valid
jQuery.fn.validateEmail = function(msg) {
	msg = msg?msg:'This email address is not valid';
	if(!/^[!-'*+=?{-~\/-9A-Z^-z-]+(\.[!-'*+=?{-~\/-9A-Z^-z-]+)*@[!-'*+=?{-~\/-9A-Z^-z-]+\.[!-'*+=?{-~\/-9A-Z^-z-]{2,}/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if password is valid
jQuery.fn.validatePassword = function(msg) {
	msg = msg?msg:'This password is not valid';
	if(!/^[a-zA-Z0-9]{4,20}$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if forum username is valid
jQuery.fn.validateForumName = function(msg) {
	msg = msg?msg:'This username is not valid';
	if(!/^([A-Za-z0-9\.\_]){1,50}$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Validates two elements against each other
jQuery.fn.validateMatch = function(compare_to_this,msg) {
	msg = msg?msg:"Your passwords don't match";
	if(this.val()!=compare_to_this.val()) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Validates if one element is greater value than another
jQuery.fn.validateGreaterThan = function(compare_to_this,msg) {
	msg = msg?msg:"The value is too small";
	if(this.val()>compare_to_this.val()) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Validates if date is (today or) in the future
jQuery.fn.validateFutureDay = function(today_is_acceptable,msg) {
	msg = msg?msg:"This date is not valid";
	if(!checkDateIsAfterNow(this.val(),$('#'+this.attr('id').replace('day','month')).val(),$('#'+this.attr('id').replace('day','year')).val(),today_is_acceptable)) {
		if (!$('#err_'+this.attr('id').replace('day','year')).length>0) {
			$('#'+this.attr('id').replace('day','year')).addErrorMessage(msg);
		} return false; // Fail
	} else $('#'+this.attr('id').replace('day','year')).removeErrorMessage();
	return true;
}


// OTHER

//Limit Text in A Textarea
jQuery.fn.addCharacterCounter = function(max_char_limit) {
	max_char_limit = max_char_limit ? max_char_limit : 500 ;
	this.after('<p class="textarea-counter"><input value="'+(max_char_limit-$(this).val().length)+'" type="text" size="3" style="width:3em;" readonly="readonly"> Characters Remaining (Maximum '+max_char_limit+')</p>');
	function limiter() {
		$(this).next().children().val((max_char_limit-$(this).val().length<1?0:max_char_limit-$(this).val().length));
		if(max_char_limit-$(this).val().length<=1) {
			$(this).val($(this).val().substring(0,max_char_limit));
			$(this).next().children().addClass('limit-reached');
		} 
		if (max_char_limit-$(this).val().length>=1) $(this).next().children().removeClass('limit-reached');
	}
	this.keyup(limiter);
	this.keydown(limiter);
}

//Text Dissappears on Focus
jQuery.fn.temporaryText = function(str) {
	this.css({fontStyle:'italic',color:'#999'});
	if(this.val()=='') this.val(str);
	this.focus(function(){			
		if($(this).val()==str) $(this).val('').css({fontStyle:'normal',color:'inherit'});
	}).blur(function(){			
		if($(this).val()=='') $(this).val(str).css({fontStyle:'italic',color:'#999'});
	});
}

//Form Annotations
//Removes Error Messages
jQuery.fn.formNote = function(remove) {
	if(remove){
		this.unbind('focus');
	} else {
		this.focus(function(){
			$(this).before('<div id="note_'+$(this).attr('id')+'" class="side-notice"><div>'+$(this).attr('title')+'</div></div>');
		}).blur(function(){
			$('#note_'+$(this).attr('id')).remove();
		});
	}
}

//Generic
function checkDateIsAfterNow(day,month,year,today_is_acceptable) {
	var currentDate = new Date();
	var yearNow = currentDate.getFullYear();
	var monthNow = currentDate.getMonth()+1;
	var dayNow = currentDate.getDate();
	
	var year_check = (year < yearNow) ? true : false;
	var month_check = (month < monthNow && year == yearNow) ? true : false;
	if (today_is_acceptable) var day_check = (day < dayNow && month == monthNow && year == yearNow) ? true : false; 
	else var day_check = (day <= dayNow && month == monthNow && year == yearNow) ? true : false;
	
	if (year_check) return false;
	if (month_check) return false;
	if (day_check) return false;
	return true;
}


// Checks if there have been any changes before leaving page

jQuery.fn.checkBeforeLeavingPage = function() {
	function setConfirmUnload(on) { window.onbeforeunload = (on) ? unloadMessage : null; }
	function unloadMessage() { return 'You have made some changes. Are you sure you wish to leave this page without saving?';}
	this.find(':input').bind("change", function() { setConfirmUnload(true); }); // Prevent accidental navigation away
	this.bind("submit", function() { setConfirmUnload(false); }); // Prevent accidental navigation away
}

// Create JS Tabs
jQuery.fn.rmpTabs = function() {
	this.children('div.tab:gt(0)').hide();
	$('#tabbed a').click(function(e){
		e.preventDefault();
		$(this).parent().addClass('this-tab').siblings('.this-tab').removeClass('this-tab');
		$($(this).attr('href')).show().siblings('div.tab').hide();
	}).css({outline:0}).first().parent().addClass('this-tab');
}
