/*************************/
/** gmk legal :: lib.js **/
/*************************/

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var navTimerIn;
var navTimerOut;
var navDefault;
var searchDefaults = new Array();

$(document).ready(function() {
	if ($("ul#nav li.selected").length > 0) {
		navDefault = $("ul#nav li.selected");
	}

	$("ul#nav a.level1").hover(function() {
		clearTimeout(navTimerIn);
		clearTimeout(navTimerOut);
		var obj = this;
		navTimerIn = setTimeout(function() {
			resetNav(false);
			$(obj).parent().addClass('selected');
		}, 100);
	} , function() {
		navTimerOut = setTimeout('resetNav(true);', 500);
	});

	$("ul#nav ul").hover(function() {
		clearTimeout(navTimerIn);
		clearTimeout(navTimerOut);
	} , function() {
		navTimerOut = setTimeout('resetNav(true);', 500);
	});

	$("ul#searchfields li").hover(function() {
		$(this).addClass('hover');
	} , function() {
		$(this).removeClass('hover');
	});

	$(document).click(function (event) {
		$('.searchfields_dropdown').hide();
		$('#searchfields li.open').removeClass('open');
	});

	$("ul#searchfields li").each(function() {
		// set the default
		if (!searchDefaults[this.id])
			searchDefaults[this.id] = $('#' + this.id).text();
	});


	$("ul#searchfields li").click(function(e) {
		if (!$('#' + this.id + '_options').is(':visible')) {
			$('.searchfields_dropdown').hide();
			$('#searchfields li.open').removeClass('open');

			var obj = $('#' + this.id + '_options');
			ref = this;

			$(this).addClass('open');
			above = false;

			if (obj.height() > 150)
				obj.css({ height: 150, width: 250, overflow: 'auto'});

			var parent = $(ref).parent(),
			pos = $(ref).offset();

			if (!above && pos.top + ref.offsetHeight + obj.height() > window.innerHeight)
				above = true;

			var paddingX = 0;
			var paddingY = 0;
			if (jQuery.browser.msie && jQuery.browser.version < 7) {
				paddingX = 270;
				paddingY = 0;
			}
			else if (jQuery.browser.msie && jQuery.browser.version < 9) {
				paddingX = 10;
				paddingY = 10;
			}

			obj.css({ left:(pos.left - paddingX - $('#content').offset().left), top:(pos.top - paddingY - $('#content').offset().top + (above ? -obj.height() : ref.offsetHeight)) });

			obj.show();
		}
		else {
			$('.searchfields_dropdown').hide();
			$('#searchfields li.open').removeClass('open');
		}

		// cancel event bubble
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	});

	$(".searchfields_dropdown").click(function(e) {
		// cancel event bubble
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	});

	$(".searchfields_dropdown input").click(function() {
		var li_id = $(this).parent().parent().parent().attr('id').replace('_options', '');
		opt_value = $(this).parent().text();

		if ($(this).is(':checked')) {
			if ($('#' + li_id).text() == searchDefaults[li_id])
				$('#' + li_id).text(opt_value);
			else
				$('#' + li_id).text($('#' + li_id).text() + ', ' + opt_value);
		}
		else {
			var remove_item = new RegExp(", " + opt_value.replace('+', '\\+') + ", ");
			$('#' + li_id).text($('#' + li_id).text().replace(remove_item, ", "));

			var remove_item = new RegExp("(, )?" + opt_value.replace('+', '\\+') + "(, )?");
			$('#' + li_id).text($('#' + li_id).text().replace(remove_item, ""));

			if ($('#' + li_id).text() == '')
				$('#' + li_id).text(searchDefaults[li_id]);
		}

		$('#' + li_id).attr('title', $('#' + li_id).text());
	});

	if (!(jQuery.browser.msie && jQuery.browser.version < 7))
		$("#lhs div.panel").corner('round 10px');
});

function resetNav(showDefault) {
	$("ul#nav li.selected").removeClass('selected');

	if (showDefault && navDefault)
		navDefault.addClass('selected');
}

function validate_search() {
	var result = true;
	/*
	if ($("input[name='locations[]']:checked").val() !== undefined) {
		$('#locations').removeClass('error_input');
	}
	else {
		$('#locations').addClass('error_input');
		result = false;
	}

	if ($("input[name='sectors[]']:checked").val() !== undefined) {
		$('#sectors').removeClass('error_input');
	}
	else {
		$('#sectors').addClass('error_input');
		result = false;
	}

	if ($("input[name='titles[]']:checked").val() !== undefined) {
		$('#titles').removeClass('error_input');
	}
	else {
		$('#titles').addClass('error_input');
		result = false;
	}

	if ($("input[name='specialisms[]']:checked").val() !== undefined) {
		$('#specialisms').removeClass('error_input');
	}
	else {
		$('#specialisms').addClass('error_input');
		result = false;
	}

	if ($("input[name='pqes[]']:checked").val() !== undefined) {
		$('#pqes').removeClass('error_input');
	}
	else {
		$('#pqes').addClass('error_input');
		result = false;
	}
	*/
	if ($('#contract_all:checked').val() !== undefined || $('#contract_perm:checked').val() !== undefined || $('#contract_temp:checked').val() !== undefined) {
		$('#contract_all_lbl').removeClass('error_text');
		$('#contract_perm_lbl').removeClass('error_text');
		$('#contract_temp_lbl').removeClass('error_text');
	}
	else {
		$('#contract_all_lbl').addClass('error_text');
		$('#contract_perm_lbl').addClass('error_text');
		$('#contract_temp_lbl').addClass('error_text');
		result = false;
	}

	return result;
}

function show_salary() {
	$('table.salary').hide();
	$('p.salary').hide();

	if ($('#salary_location').val() == 'london' && $('#salary_type').val() == 'uk') {
		$('#salary_top20').show();
		$('#salary_mid').show();
		$('#salary_west').show();
	}
	else if ($('#salary_location').val() == 'london' && $('#salary_type').val() == 'us') {
		$('#salary_atlantic').show();
		$('#salary_nyc').show();
	}
	else if ($('#salary_location').val() == 'international' && $('#salary_type').val() == 'uk') {
		$('p.salary').show();
	}
	else if ($('#salary_location').val() == 'international' && $('#salary_type').val() == 'us') {
		$('p.salary').show();
	}
}

function publication_step2(obj) {
	if ($('input.pub_options:checked').val() !== undefined) {
		$('.pub_lbl').removeClass('error_text');
		$(obj).hide();
		$('#publication_step2').show();
	}
	else {
		$('.pub_lbl').addClass('error_text');
	}

	return false;
}

function validate_publications() {
	var result = true;

	if ($('input.pub_options:checked').val() !== undefined) {
		$('.pub_lbl').removeClass('error_text');
	}
	else {
		$('.pub_lbl').addClass('error_text');
		result = false;
	}

	if ($('#first_name').val() != '') {
		$('#first_name').removeClass('error_input');
	}
	else {
		$('#first_name').addClass('error_input');
		result = false;
	}

	if ($('#last_name').val() != '') {
		$('#last_name').removeClass('error_input');
	}
	else {
		$('#last_name').addClass('error_input');
		result = false;
	}

	if ($('#email').val() != '' && check_email($('#email').val())) {
		$('#email').removeClass('error_input');
	}
	else {
		$('#email').addClass('error_input');
		result = false;
	}

	if ($('#telephone').val() != '') {
		$('#telephone').removeClass('error_input');
	}
	else {
		$('#telephone').addClass('error_input');
		result = false;
	}

	if ($('#contract_tel:checked').val() !== undefined || $('#contract_email:checked').val() !== undefined) {
		$('#contract_tel_lbl').removeClass('error_text');
		$('#contract_email_lbl').removeClass('error_text');
	}
	else {
		$('#contract_tel_lbl').addClass('error_text');
		$('#contract_email_lbl').addClass('error_text');
		result = false;
	}

	if (result)
		$('#uid').val($('#uid').val().toUpperCase());

	return result;
}

function validate_register() {
	var result = true;

	if ($('#first_name').val() != '') {
		$('#first_name').removeClass('error_input');
	}
	else {
		$('#first_name').addClass('error_input');
		result = false;
	}

	if ($('#last_name').val() != '') {
		$('#last_name').removeClass('error_input');
	}
	else {
		$('#last_name').addClass('error_input');
		result = false;
	}

	if ($('#email').val() != '' && check_email($('#email').val())) {
		$('#email').removeClass('error_input');
	}
	else {
		$('#email').addClass('error_input');
		result = false;
	}

	if ($('#telephone').val() != '') {
		$('#telephone').removeClass('error_input');
	}
	else {
		$('#telephone').addClass('error_input');
		result = false;
	}

	if ($('#contract_tel:checked').val() !== undefined || $('#contract_email:checked').val() !== undefined) {
		$('#contract_tel_lbl').removeClass('error_text');
		$('#contract_email_lbl').removeClass('error_text');
	}
	else {
		$('#contract_tel_lbl').addClass('error_text');
		$('#contract_email_lbl').addClass('error_text');
		result = false;
	}

	// Diversity form
	if ($('#dive_age').val() != '') {
		$('#dive_age').removeClass('error_input');
	}
	else {
		$('#dive_age').addClass('error_input');
		result = false;
	}

	if ($('#dive_gender_male:checked').val() !== undefined || $('#dive_gender_female:checked').val() !== undefined  || $('#dive_gender_decline:checked').val() !== undefined) {
		$('#dive_gender_male_lbl').removeClass('error_text');
		$('#dive_gender_female_lbl').removeClass('error_text');
		$('#dive_gender_decline_lbl').removeClass('error_text');
	}
	else {
		$('#dive_gender_male_lbl').addClass('error_text');
		$('#dive_gender_female_lbl').addClass('error_text');
		$('#dive_gender_decline_lbl').addClass('error_text');
		result = false;
	}

	if ($('#dive_faith').val() != '') {
		$('#dive_faith').removeClass('error_input');
	}
	else {
		$('#dive_faith').addClass('error_input');
		result = false;
	}

	if ($('#dive_orientation').val() != '') {
		$('#dive_orientation').removeClass('error_input');
	}
	else {
		$('#dive_orientation').addClass('error_input');
		result = false;
	}

	if ($('#dive_background').val() != '') {
		$('#dive_background').removeClass('error_input');
	}
	else {
		$('#dive_background').addClass('error_input');
		result = false;
	}

	if ($('#dive_background_2').is(':visible')) {
		if ($('#dive_background_2').val() != '') {
			$('#dive_background_2').removeClass('error_input');
		}
		else {
			$('#dive_background_2').addClass('error_input');
			result = false;
		}
	}

	if ($('#dive_background_other').is(':visible')) {
		if ($('#dive_background_other').val() != '') {
			$('#dive_background_other').removeClass('error_input');
		}
		else {
			$('#dive_background_other').addClass('error_input');
			result = false;
		}
	}

	if ($('#dive_disabled_yes:checked').val() !== undefined || $('#dive_disabled_no:checked').val() !== undefined  || $('#dive_disabled_decline:checked').val() !== undefined) {
		$('#dive_disabled_yes_lbl').removeClass('error_text');
		$('#dive_disabled_no_lbl').removeClass('error_text');
		$('#dive_disabled_decline_lbl').removeClass('error_text');
	}
	else {
		$('#dive_disabled_yes_lbl').addClass('error_text');
		$('#dive_disabled_no_lbl').addClass('error_text');
		$('#dive_disabled_decline_lbl').addClass('error_text');
		result = false;
	}

	if ($('#terms:checked').val() !== undefined) {
		$('#terms_lbl').removeClass('error_text');
	}
	else {
		$('#terms_lbl').addClass('error_text');
		result = false;
	}

	if (result)
		$('#uid').val($('#uid').val().toUpperCase());

	return result;
}

function validate_diversity() {
	var result = true;

	if ($('#dive_age').val() != '') {
		$('#dive_age').removeClass('error_input');
	}
	else {
		$('#dive_age').addClass('error_input');
		result = false;
	}

	if ($('#dive_gender_male:checked').val() !== undefined || $('#dive_gender_female:checked').val() !== undefined  || $('#dive_gender_decline:checked').val() !== undefined) {
		$('#dive_gender_male_lbl').removeClass('error_text');
		$('#dive_gender_female_lbl').removeClass('error_text');
		$('#dive_gender_decline_lbl').removeClass('error_text');
	}
	else {
		$('#dive_gender_male_lbl').addClass('error_text');
		$('#dive_gender_female_lbl').addClass('error_text');
		$('#dive_gender_decline_lbl').addClass('error_text');
		result = false;
	}

	if ($('#dive_faith').val() != '') {
		$('#dive_faith').removeClass('error_input');
	}
	else {
		$('#dive_faith').addClass('error_input');
		result = false;
	}

	if ($('#dive_orientation').val() != '') {
		$('#dive_orientation').removeClass('error_input');
	}
	else {
		$('#dive_orientation').addClass('error_input');
		result = false;
	}

	if ($('#dive_background').val() != '') {
		$('#dive_background').removeClass('error_input');
	}
	else {
		$('#dive_background').addClass('error_input');
		result = false;
	}

	if ($('#dive_background_2').is(':visible')) {
		if ($('#dive_background_2').val() != '') {
			$('#dive_background_2').removeClass('error_input');
		}
		else {
			$('#dive_background_2').addClass('error_input');
			result = false;
		}
	}

	if ($('#dive_background_other').is(':visible')) {
		if ($('#dive_background_other').val() != '') {
			$('#dive_background_other').removeClass('error_input');
		}
		else {
			$('#dive_background_other').addClass('error_input');
			result = false;
		}
	}

	if ($('#dive_disabled_yes:checked').val() !== undefined || $('#dive_disabled_no:checked').val() !== undefined  || $('#dive_disabled_decline:checked').val() !== undefined) {
		$('#dive_disabled_yes_lbl').removeClass('error_text');
		$('#dive_disabled_no_lbl').removeClass('error_text');
		$('#dive_disabled_decline_lbl').removeClass('error_text');
	}
	else {
		$('#dive_disabled_yes_lbl').addClass('error_text');
		$('#dive_disabled_no_lbl').addClass('error_text');
		$('#dive_disabled_decline_lbl').addClass('error_text');
		result = false;
	}

	return result;
}

// check if input is a valid email address
// By Cal Henderson <cal@iamcal.com>
// http://code.iamcal.com/php/rfc822/
function check_email(input) {
	if (input && window.RegExp) {
		var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]',
		dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]',
		atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+',
		quoted_pair = '\\x5c[\\x00-\\x7f]',
		quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22',
		// Use simplified domain matching, because we need to allow Unicode characters here
		// So, e-mail address should be validated also on server side after idn_to_ascii() use
		//domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d',
		//sub_domain = '('+atom+'|'+domain_literal+')',
		domain = '([^@\\x2e]+\\x2e)+[a-z]{2,}',
		word = '('+atom+'|'+quoted_string+')',
		delim = '[,;\s\n]',
		local_part = word+'(\\x2e'+word+')*',
		addr_spec = local_part+'\\x40'+domain,
		reg1 = new RegExp('^'+addr_spec+'$', 'i');

		return reg1.test(input) ? true : false;
	}

	return false;
}

function validate_login() {
	var result = true;

	if ($('#username').val() != '') {
		$('#username').removeClass('error_input');
	}
	else {
		$('#username').addClass('error_input');
		result = false;
	}

	if ($('#password').val() != '') {
		$('#password').removeClass('error_input');
	}
	else {
		$('#password').addClass('error_input');
		result = false;
	}

	return result;
}

function validate_users() {
	var result = true;

	if ($('#username').val() != '') {
		$('#username').removeClass('error_input');
	}
	else {
		$('#username').addClass('error_input');
		result = false;
	}

	if ($('#password').length > 0) {
		if ($('#password').val() != '') {
			$('#password').removeClass('error_input');
		}
		else {
			$('#password').addClass('error_input');
			result = false;
		}

		if ($('#password').val() != '' && $('#password').val() == $('#cpassword').val()) {
			$('#password').removeClass('error_input');
			$('#cpassword').removeClass('error_input');
		}
		else if ($('#password').val() != '') {
			$('#password').addClass('error_input');
			$('#cpassword').addClass('error_input');
			result = false;
		}
	}

	return result;
}

function validate_password() {
	var result = true;

	if ($('#opassword').val() != '') {
		$('#opassword').removeClass('error_input');
	}
	else {
		$('#opassword').addClass('error_input');
		result = false;
	}

	if ($('#password').val() != '') {
		$('#password').removeClass('error_input');
	}
	else {
		$('#password').addClass('error_input');
		result = false;
	}

	if ($('#password').val() != '' && $('#password').val() == $('#cpassword').val()) {
		$('#password').removeClass('error_input');
		$('#cpassword').removeClass('error_input');
	}
	else if ($('#password').val() != '') {
		$('#password').addClass('error_input');
		$('#cpassword').addClass('error_input');
		result = false;
	}

	return result;
}

function select_dive_background(obj) {
	var options = new Array();
	options['asian'] = new Array('Indian', 'Pakistani', 'Bangladeshi', 'Any other Asian background');
	options['black'] = new Array('Caribbean', 'African', 'Any other Black background');
	options['chinese'] = new Array('Chinese', 'Any other Chinese background');
	options['mixed'] = new Array('White & Black Caribbean', 'White & Black African', 'White & Asian', 'Any other Mixed background');
	options['white'] = new Array('British', 'Irish', 'Any other White background');

	if ($(obj).val() != '' && $(obj).val() != 'Declined') {
		$('#dive_background_2').find('option:gt(0)').remove();

		if ($(obj).val() == 'Asian or Asian British')
			values = options['asian'];
		else if ($(obj).val() == 'Black or Black British')
			values = options['black'];
		else if ($(obj).val() == 'Chinese or other ethnic group')
			values = options['chinese'];
		else if ($(obj).val() == 'Mixed')
			values = options['mixed'];
		else if ($(obj).val() == 'White')
			values = options['white'];

		for (var i in values) {
			if (values[i].indexOf('Any other') > -1)
				$('#dive_background_2').append($("<option></option>").attr("value", "Other").text(values[i]));
			else
				$('#dive_background_2').append($("<option></option>").attr("value", values[i]).text(values[i]));
		}

		$('#dive_background_2_row').show();
	}
	else {
		$('#dive_background_2_row').hide();
	}

	$('#dive_background_other_row').hide();
}

function select_dive_background_2(obj) {
	if ($(obj).val() == 'Other')
		$('#dive_background_other_row').show();
	else
		$('#dive_background_other_row').hide();
}

function load_search() {
	$(".searchfields_dropdown input:checked").trigger('click').attr('checked', true);
}

function validate_adds() {
	var result = true;

	if ($('#title').val() != '') {
		$('#title').removeClass('error_input');
	}
	else {
		$('#title').addClass('error_input');
		result = false;
	}

	return result;
}

function validate_pubs() {
	var result = true;

	if ($('#title').val() != '') {
		$('#title').removeClass('error_input');
	}
	else {
		$('#title').addClass('error_input');
		result = false;
	}

	return result;
}

function viewbio(obj) {
	$('p.teambio').hide();
	$('p.teambio_lnk').show();

	$(obj).parent().hide();
	$(obj).parent().next('p.teambio').show();
}
