$(document).ready(function() {
	PureGenie.init();
});



var PureGenie = {
	
	init: function()
	{
		// send to friend
		$("a.sendShare").fancybox();
		
		// clear text boxes on focus
		$("input.searchFld").clearDefault();
		
		// main nav - submenus
		$(".mainNavigation>li.drop").hover(
			function () {
				$(this).children("ul.secondLvlMenu").show();
				$(".mainNavigation>li ul li.drop").hover(
						function () {
							$(this).addClass("active");
						}, 
						function () {
							$(this).removeClass("active");
				});
			}, 
			function () {
				$(this).children("ul.secondLvlMenu").hide();
		});
		
		/* Set target="_blank" to all rel="external" links */
		$("a[rel='external']").attr('target', '_blank');
		
		
		//focus for form fields
		PureGenie.setupForms();
			
		//footer last element - remove the bullet
		$('.footerLinks li').last().addClass('last');

		// hover for jobs listings
		$('.jobs tr:odd').addClass('stripe');
		$('.jobs tr').hover(
			function() {
				$(this).addClass('highlight');
			},
			function() {
				$(this).removeClass('highlight');
			}
		);


		// hover effect for footer lateral logo
		$(".logoLateral2").hide();
		$(".lateral a").hover(
			function () {
				$(".logoLateral1").fadeOut();
			$(".logoLateral2").fadeIn();


			}, 
			function () {
					$(".logoLateral2").fadeOut();
				$(".logoLateral1").fadeIn();

			}
		);
		
		// job alerts
		if ($("#subscribe-job-alerts-email").length)
		{
			PureGenie.setupJobAlerts();
		}
		
		// jobs search alerts subscribtion
		$(".emailLnk").click(function() {
			$(this).hide().parent().find('form').show().find('.textFld').focus();
			return false;
		});
		$(".cancelLnk").click(function() {
			$(this).parents('.emailSubscribe').find('form').hide().prev('.emailLnk').show();
			return false;
		});
		
		PureGenie.setupJobSearchAlerts();
		
		
		// job search filters
		PureGenie.setupJobSearchFilters();
		
		
		$("form#job-search-form input:submit").click(function() {
			if ($("#q").val().length > 2 || $("#l").val().length > 2)
			{
				return true;
			}
			return false;
		});
		
		$("form#job-search-form").submit(function() {
			if ($("#q").val().length > 2 || $("#l").val().length > 2)
			{
				return true;
			}
			return false;
		});
		
	},
	
	setupForms: function()
	{
		$('.textFld').focus(function(){
			$(this).addClass("focused")
			$(this).parent().find('label').addClass("selected")
		})
		$('.textFld').blur(function(){
			$(this).removeClass("focused")
			$(this).parent().find('label').removeClass("selected")
			
		})
		
		$('.textArea').focus(function(){
			$(this).addClass("focused")
			$(this).parent().find('label').addClass("selected")
			
		})
		$('.textArea').blur(function(){
			$(this).removeClass("focused")
			$(this).parent().find('label').removeClass("selected")
			
		})
	},
	
	setupJobSearchAlerts: function()
	{
		// ajaxify form
		$('#search_email_subscribe_form').ajaxForm({
			'type': 'POST', 
			'dataType': 'json', 

			// form submitted
			success: function(response){
				if (response == 1)
				{
					$('#search_email_subscribe_form #subscribe_email').attr("value", "");
					$('#search_email_subscribe_form').hide();
					$('#subscribe_thx').show();
				}
				$('#subscribe_wait').hide();
				$('#subscribe_actions').show();
			}, 

			beforeSubmit: function(arr, form, options)
			{
				$('#subscribe_wait').show();
				$('#subscribe_actions').hide();
			},

			// validate form before submit
			beforeSerialize: function(){
				email = $('#search_email_subscribe_form #subscribe_email').val();
				if (email == '' || email == 'Please enter your email' || !PureGenie.validate_email(email))
				{
					alert('Please enter a real email address');
					return false;
				}
				return true;
			}, 

			// some error occured
			error: function(a, b, c){
				//$('#subscribe_wait').hide();
				//$('#subscribe_form a.button').show();
			}
		});
		
		
		$(".emailSubscribe .submitEmail").click(function() {
			$('#search_email_subscribe_form').submit();
			return false;
		});
	},
	
	setupJobAlerts: function()
	{
		// ajaxify form
		$('#subscribe_form').ajaxForm({
			'type': 'POST', 
			'dataType': 'json', 

			// form submitted
			success: function(response){
				if (response == 1)
				{
					$('#subscribe-job-alerts-email').attr("value", "Your e-mail here")
					$('#subscribe_thx').show();
				}
				$('#subscribe_wait').hide();
				$('#subscribe_form a.button').show();
			}, 

			beforeSubmit: function(arr, form, options)
			{
				$('#subscribe_wait').show();
				$('#subscribe_form a.button').hide();
			},

			// validate form before submit
			beforeSerialize: function(){
				if ($('#subscribe-job-alerts-email').val() == '' || $('#subscribe-job-alerts-email').val() == 'Your e-mail here')
				{
					alert('Please fill in your email')
					return false;
				}
				return true;
			}, 

			// some error occured
			error: function(a, b, c){
				$('#subscribe_wait').hide();
				$('#subscribe_form a.button').show();
			}
		});
		
		
		$('#subscribe_form a.button').click(function() {
			$('#subscribe_form').submit();
			return false;
		});
	},
	
	setupSTF: function()
	{
		PureGenie.setupForms();
		setTimeout(function() { $("#stf_name").focus(); }, 1000);
		
		// ajaxify form
		$('#stf-form').ajaxForm({
			'type': 'POST', 
			'dataType': 'json', 

			// form submitted
			success: function(response){
				if (response == 1)
				{
					$('#stf_thx').show();
				}
				$('#stf_wait').hide();
				$('#stf-form .sendMessageBtn').show();
			}, 

			beforeSubmit: function(arr, form, options)
			{
				$('#stf_wait').show();
				$('#stf-form .sendMessageBtn').hide();
			},

			// validate form before submit
			beforeSerialize: function(){
				if ($('#stf_name').val() == '' || $('#stf_email').val() == '' || $('#stf_friend_name').val() == '' || $('#stf_friend_email').val() == '')
				{
					alert('Please fill-in all the fields')
					return false;
				}
				
				$("#stf_url").val(window.location.href);
				
				return true;
			}, 

			// some error occured
			error: function(a, b, c){
				$('#stf_wait').hide();
				$('#stf-form .sendMessageBtn').show();
			}
		});
	},
	
	setupJobSearchFilters: function()
	{
		var url = window.location.href;

		$("input.filter_location").bind("click", function(e) {
			if (url.match(/l=((.)*?)/))
			{
				var existing_locations = decodeURI(url.match(/l=((.)*)/g));
				if (existing_locations.indexOf("&") != -1)
				{
					existing_locations = existing_locations.split("&");
					existing_locations = existing_locations[0];
				}
				
				var no_location_url = url.replace(existing_locations, "");
				if (no_location_url.indexOf("?&") != -1)
				{
					no_location_url = no_location_url.replace("?&", "?");
				}
			}
			else
			{
				var existing_locations = "";
				var no_location_url = url;
			}

			// add location
			if (this.checked)
			{
				var new_location_params = (existing_locations != "") ? (existing_locations + "," + this.value) : (this.value);
			}
			// remove location
			else
			{
				var tmp = existing_locations + ",";
				var remove_selected_loc = tmp.replace(new RegExp(this.value + "," ,"i"), "");
				var new_location_params = (remove_selected_loc.indexOf(",") != -1) ? remove_selected_loc.substring(0, remove_selected_loc.length - 1) : remove_selected_loc.substring(0, remove_selected_loc.length - 2);
			}

			if (new_location_params == "")
			{
				window.location.href = no_location_url;	
			}
			else
			{
				new_url = no_location_url;
				if (no_location_url[no_location_url.length - 1] == '/')
				{
					new_url += '?';
				}
				else if (no_location_url[no_location_url.length - 1] != '&')
				{
					new_url += '&';
				}
				
				if (new_location_params.indexOf("l=") == -1)
				{
					new_location_params = "l=" + new_location_params;
				}
				
				new_url += new_location_params;
				window.location.href = new_url;
			}
		});
		
		$("input.filter_type").bind("click", function(e) {
			if (url.match(/t=((.)*?)/))
			{
				var existing_locations = decodeURI(url.match(/t=((.)*)/g));
				if (existing_locations.indexOf("&") != -1)
				{
					existing_locations = existing_locations.split("&");
					existing_locations = existing_locations[0];
				}
				
				var no_location_url = url.replace(existing_locations, "");
				if (no_location_url.indexOf("?&") != -1)
				{
					no_location_url = no_location_url.replace("?&", "?");
				}
			}
			else
			{
				var existing_locations = "";
				var no_location_url = url;
			}

			// add location
			if (this.checked)
			{
				var new_location_params = (existing_locations != "") ? (existing_locations + "," + this.value) : (this.value);
			}
			// remove location
			else
			{
				var tmp = existing_locations + ",";
				var remove_selected_loc = tmp.replace(new RegExp(this.value + "," ,"i"), "");
				var new_location_params = (remove_selected_loc.indexOf(",") != -1) ? remove_selected_loc.substring(0, remove_selected_loc.length - 1) : remove_selected_loc.substring(0, remove_selected_loc.length - 2);
			}

			if (new_location_params == "")
			{
				window.location.href = no_location_url;	
			}
			else
			{
				new_url = no_location_url;
				if (no_location_url[no_location_url.length - 1] == '/')
				{
					new_url += '?';
				}
				else if (no_location_url[no_location_url.length - 1] != '&')
				{
					new_url += '&';
				}
				
				if (new_location_params.indexOf("t=") == -1)
				{
					new_location_params = "t=" + new_location_params;
				}
				
				new_url += new_location_params;
				window.location.href = new_url;
			}
		});

	},
	
	unsubscribeFromJobAlerts: function(email)
	{
		$.post(
			"/ajax", 
			{ email: email, action: 'email-unsubscribe' },
			function (response)
			{
				if (response == 1)
				{
					window.location = "/";
				}
			},
			"json"
		);	
	},
	
	// validate email (regex from jquery validate plugin)
	validate_email: function(email)
	{
		return (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email))
	}
};

// clear default value in text fields
(function($){  
    $.fn.clearDefault = function(){  
        return this.each(function(){  
            var default_value = $(this).val();  
            $(this).focus(function(){  
                if ($(this).val() == default_value)  
                              $(this).val("");  
            });  
            $(this).blur(function(){  
                if ($(this).val() == "")  
                              $(this).val(default_value);  
            });  
        });  
    };  
})(jQuery);
