// My Rec Global jQuery Functions

// VALIDATION

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

//Adds Inline Error Message
jQuery.fn.addErrorMessage = function(msg) {
	msg = msg?msg:'You must complete this';
	$('.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 blank or null
jQuery.fn.validateIsSelected = function(msg) {
	msg = msg?msg:'You must make a selection';
	if(this.val()==''||this.val()==null) {
		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.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if a 1 out of 1 tick box has been ticked
jQuery.fn.validateCheckboxIsChecked = function(msg) {
	msg = msg?msg:'You must tick this box';
	if(!this.next().attr('id')) this.next().attr('id','r_'+this.attr('id'));
	if(this.parent().find(':checked').length==0) {
		if (!$('#err_'+this.next().attr('id')).length>0) {
			this.next().addErrorMessage(msg);
		} return false; // Fail
	} else this.next().removeErrorMessage();
	return true;
}

//Checks if a 1 out of many tick box has been ticked
jQuery.fn.validateCheckboxIsCheckedFromMany = function(msg) {
	msg = msg?msg:'You must tick at least one box';
	if(this.find(':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 digits only
jQuery.fn.validateNumeric = function(msg) {
	msg = msg?msg:'The number is not valid, it should be written in numbers only, no spaces';
	if(!/^[0-9]+$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks min value
jQuery.fn.validateMinimumNumeric = function(min_value,msg) {
	msg = msg?msg:'The number is not valid, it should be written in numbers only and be greater than '+min_value;
	if(!/^[0-9]+$/.test(this.val())||this.val()<min_value) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if sortcode is valid
jQuery.fn.validateSortCode = function(msg) {
	msg = msg?msg:'The sort code is not valid, it should be written 98-76-54 (numbers seperated with dashes)';
	if(!/^[0-9]{2}-[0-9]{2}-[0-9]{2}$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if account number is valid
jQuery.fn.validateAccountNumber = function(msg) {
	msg = msg?msg:'The account number is not valid, it should be written 87654321 (numbers only, no spaces)';
	if(!/^[0-9]{7,10}$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if url slug is valid
jQuery.fn.validateUrlSlug = function(msg) {
	msg = msg?msg:'The url slug is not valid. It must only contain numbers, letters and dashes (-)';
	if(!/^[0-9a-z\-]{1,200}$/.test(this.val())) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}

//Checks if alias is valid in realtime
jQuery.fn.validateDuplicateAliases = function(site_url,msg_valid,msg_duplicated) {
	msg_valid = msg_valid?msg_valid:'Aliases must be between 2 and 20 characters long, only containing numbers and letters'; 
	msg_duplicated = msg_duplicated?msg_duplicated:'This alias is already in use';
	if (!/^[a-zA-Z0-9-]{2,20}$/.test(this.val())) {
		$('#alias_status').attr('class','state-bad');
		$('#alias').removeErrorMessage();
		$('#alias').addErrorMessage(msg_valid);
		return false;
	} else {
		$.ajax({
			type:'POST',
			url: site_url+'ajaxcalls/check-alias',
			data:'alias='+$(this).val(),
			beforeSend: function() {
				if (!($('#alias_status').length>0)) $('#alias').before('<span id="alias_status"></span>');
				$('#alias_status').attr('class','state-wait');
				$('#alias').removeErrorMessage();
			},
			success: function(data) {
				if(data=='invalid-format') {
					$('#alias_status').attr('class','state-bad');
					$('#alias').addErrorMessage(msg_valid);
				} else if(data=='exists') {
					$('#alias_status').attr('class','state-bad');
					$('#alias').addErrorMessage(msg_duplicated);
				} else {
					$('#alias_status').attr('class','state-good');
					$('#alias').removeErrorMessage();
				}
			}
		});
	}
	if($('#alias_status.state-bad').length>0) return false;
	else 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 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;
}

//Validates if text input date is presented as dd/mm/yyyy
jQuery.fn.validateDate_ddmmyyyy = function(msg,allow_blank) {
	msg = msg?msg:"The date must be writen as dd/mm/yyyy e.g. 31/05/1985";
	if(!/^([0-9]{2})(\/)([0-9]{2})(\/)([0-9]{4})$/.test(this.val())&&!(allow_blank||this.val()=='')) {
		if (!$('#err_'+this.attr('id')).length>0) {
			this.addErrorMessage(msg);
		} return false; // Fail
	} else this.removeErrorMessage();
	return true;
}


// OTHER

// Changing flag image next to a select box
jQuery.fn.flagSelect = function() {
	var id = this.attr('id')+'_flag_select';
	if(!($('#'+id).length>0)) this.after('<span id="'+id+'" class="flag-select"></span>');
	if($(this).val()) $('#'+id).html('<img src="/images/'+$(this).val().toLowerCase()+'-flag-icon.png" width="19" height="13" alt="Flag.">');
	this.change(function(){			
		if($(this).val()) $('#'+id).html('<img src="/images/'+$(this).val().toLowerCase()+'-flag-icon.png" width="19" height="13" alt="Flag.">');
		else $('#'+id).html('');
	})
}

// Create URL Slug from text
jQuery.fn.safeURLFromText = function(target_url_element) {
	var url_slug = function(){
		$(target_url_element).val($(this).val().toLowerCase().replace(/( |\-|\!|\"|\#|\$|\%|\&|\'|\(|\)|\*|\+|\,|\.|\/|\:|\;|\<|\=|\>|\?|\@|\[|\]|\_|\`|\{|\||\}|\~)/g,'-'));			
	}
	this.keyup(url_slug).keydown(url_slug);
}

//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><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.keyup(limiter);
	this.keydown(limiter);
}

//Text Dissappears on Focus
jQuery.fn.temporaryText = function(str) {
	if (this.val()=='') this.val(str);
	this.focus(function(){			
		if($(this).val()==str) $(this).val('');
	}).blur(function(){			
		if($(this).val()=='') $(this).val(str);
	});
}

//Form Annotations
//Removes Error Messages
jQuery.fn.formNote = function() {
	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();
	});
}

//Checks if alias is valid in realtime
jQuery.fn.getRegionSelect = function(site_url,element_to_replace) {
	function getRegion(site_url,element_to_replace,base_element){
		$.ajax({
			type:'POST',
			url: site_url+'ajaxcalls/get-region-select',
			data:'country_code='+$(base_element).val()+'&region='+$(element_to_replace).val(),
			beforeSend: function() {
				$(base_element).attr('disabled',true);
			},
			success: function(data) {
				$(base_element).removeAttr('disabled');
				if(data!='invalid-code') $(element_to_replace).parent().html(data);
			}
		});
	};
	this.change(function() {getRegion(site_url,element_to_replace,this);});
	
}

//Get the calculated placement fee in GBP on the fly
jQuery.fn.getPlacementFeeGBP = function(site_url) {
	function getPlacementFeeGBPfunc(site_url,this_element) {
		$.ajax({
			type:'POST',
			url: site_url+'ajaxcalls/get-placement-fee-gbp',
			data:'local_currency_code=GBP&local_salary='+$(this_element).val(),
			beforeSend: function() {
				//$(base_element).attr('disabled',true);
			},
			success: function(data) {
				//$(base_element).removeAttr('disabled');
				if(data!='invalid-code') $('#fee_to_pay').html('The Referral Fee you would pay on this listing would be &pound;'+data+' (GBP)');
			}
		});
	}
	this.after('<div id="fee_to_pay">Enter the actual (or median) base salary to see the Referral Fee</div>').keyup(function() { getPlacementFeeGBPfunc(site_url,this); } )
																											 .blur(function() { getPlacementFeeGBPfunc(site_url,this); } )
																											 .change(function() { getPlacementFeeGBPfunc(site_url,this); } );
	if(this.val()>0) getPlacementFeeGBPfunc(site_url,this);
}

// Makes a piece of text fit into a box with a CSS width defined by changing the font-size
jQuery.fn.fitTextToBox = function() {
	var current_font_size = parseFloat(this.css('font-size'));
	var max_font_size = 50;
	var character_width_in_pixels = (current_font_size/2)+1; // Extra '1' Guarentees a fit
	var cash_total_length = this.text().length;
	var actual_cash_total_width = cash_total_length*character_width_in_pixels;
	var cash_total_factor = this.width()/actual_cash_total_width;
	var new_font_size = parseFloat(current_font_size*cash_total_factor);
	if(new_font_size > max_font_size)  new_font_size = max_font_size;
	this.css('font-size',new_font_size);
}


//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
}

// Help Tooltips
function helpTooltips() {
	$('span.help[title]').each(function(){
		$(this).after('<div class="help-tip">'+$(this).attr('title')+'</div>')
		.attr('title','').hover(function(){
			$(this).next().fadeIn('slow');		
		},
		function(){
			$(this).next().fadeOut('slow');		
		});
	});
}
$(function(){helpTooltips();});

