$(document).ready(function () {
	// drop down menu
	$('div#navigation ul li').hover(function () {
		var children = $(this).children('ul.children');
		
		if (children.length > 0) {
			children.stop(true,true).slideDown('fast');
		}
	}, function () { 
		var children = $(this).children('ul.children');
		
		if (children.length > 0) {
			children.delay(1).stop(true,true).slideUp('fast');
		}
	});
	
	$('div#navigation ul li a').hover(function () {
		$(this).parent().addClass('hovered');
	}, function () {
		$(this).parent().removeClass('hovered');
	});
	
	// submit button
	$('button, input.button').hover(function () {
		$(this).toggleClass('hover');
	});
	
	// redirect form
	$('div#redirect_form input.strtoupper').keyup(function() {
		if ($(this).val() == '') {
			return;
		}
		
		$(this).val(String($(this).val()).toUpperCase());
	});
	
	$('div#redirect_form input.text').keyup(function() {
		if ($(this).val() != '') {
			$(this).next().focus();
		}
		
		var show_box = true;
		$('input.text').each(function () {
			if ($(this).val() == '') {
				show_box = false;
			}
		});
		
		if (show_box == true) {
			$('div#click').fadeIn();
		}
		else {
			$('div#click').fadeOut();
		}
	});
	
	$('div#redirect_form input.text:first-child').focus();
	
	// mobile number prefix
	if ($('input[name="mobile_number"]').length > 0) {
		var current_mobile = $('input[name="mobile_number"]').val();
		$('select[name="mobile_prefix"] option').each(function () {
			var current_prefix = $(this).val();
			
			var i = (current_mobile + '').indexOf(current_prefix, 0);
    		var position = (i === -1) ? false : i;
    
			if (position === 0) {
				$('select[name="mobile_prefix"] option').attr('selected',false);
				$(this).attr('selected','selected');
			}
		});
		
		$('select[name="mobile_prefix"]').change(function() {
			var prefix = $(this).val();
			$('input[name="mobile_number"]').val(prefix);
		});
		
		// trip on load if mobile number is empty, to populate with +1
		if ($('input[name="mobile_number"]').val() == '') {
			$('select[name="mobile_prefix"]').change();
		}
		
		$('input[name="mobile_number"]').change(function() {
			var prefix = $('select[name="mobile_prefix"]').val();
			var mobile = $(this).val();
			
			if (strpos(mobile, prefix) !== 0) {
				alert('Please leave the mobile phone prefix as is.  Simply add your mobile number after the prefix.  Thank you.');
				$(this).val(prefix);
			}
		});
	}
});

function strpos (haystack, needle, offset) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
