// jrails extention
(function($) {
    $.ajaxSettings.accepts._default = "text/javascript, text/html, application/xml, text/xml, */*";
})(jQuery);


App = {
	
	init: {
		// Observer functions loaded automatically when App.initialize() is called
		observers: {}
	},
	
	// Observer functions loaded with App.observe("observerName")
	observers: {}, 
	
	// Helper functions
	// Not loaded anywhere, you called them explicitly with App.helpers.nameOfTheHelper(params)
	helpers: {}
};

// Use this function in your ready (onload) event to define what to observe
// IE: App.observe("hideHiddenInputFields", "someOfMyLinks", "somethingElse")
App.observe = function() {
	$.each(arguments, function() { App.observers[this](); });
};

// Use this function in your ready (onload) event to call functions defined like 
// App.init.observers.nameOfTheFunction
App.initialize = function() {
	for(param in App.init.observers) { App.init.observers[param]();	}
};


// ======================================================================
// DEFAULT OBSERVERS
// ======================================================================
// Observers defined here will be called application wide whenever App.initialize() is used


// Removes outline from links after click
// for more info see http://kolodvor.net/2007/12/08/blurring-links-with-jquery/
App.init.observers.blurLinksAfterClick = function() {
	$("a, button").livequery("click", function() { $(this).blur(); });
};

// Hides / shows state select box depending of selected country
// US selected => shows
// Any other country selected => hides
App.init.observers.countrySelectBox = function() {
	$("select#user_country").change(function() {
		var country = $(this).attr("value");
		var stateLabel = $("label[for=user_state]");
		var stateSelectBox = $("select#user_state");
		if(country=="US") {
			stateLabel.show();
			stateSelectBox.show();
		} else {
			stateLabel.hide();
			stateSelectBox.hide();
		}
	});
}

// ======================================================================
// OBSERVERS USED APPLICATION WIDE
// ======================================================================
// Define specific observers in separate file that you will use with specific layout our view
// Define it like (App.init.observers.myObserver = function() { ... }) and then call App.initialize() in you ready (onload) event


// We don't know the logo width so we need this to set minimum width to header
App.observers.setMinHeaderWidth = function() {
  var header = $("#header");
  var logoWidth = header.find("h1").width();
  var searchFormWidth = header.find("form").width();
  var minHeaderWidth = logoWidth+searchFormWidth+60; // 60 = h1 padding
  header.css("min-width", minHeaderWidth+"px");
};

// Sets focus on first field with 'focus' class.
// If none is found focus is set to first text field
App.observers.focusFirstTextField = function() {
	var el = $(".focus");
	if(el.size() > 0)
		el.get(0).focus();
	else
		$("input:text:first").focus();
};

// Firefox 3 on Mac has problem with hidden fileds ???
App.observers.hideHiddenInputFields = function() {
	$("input[type=hidden]").hide();
};


// close link used to hide additional options for job (save, email, more ...)
App.observers.closeLink = function() {
	$(".closeable a.close").livequery("click", function() {
		$(this).closest('.closeable').slideUp();
		return false;
	});
};

// saves job to saved jobs
App.observers.saveJobLink = function() {
	$("div.job ul.job-tools li a.save-job").click(function() {
		var link = $(this);
		var jobId = App.helpers.getJobIdFromToolLink(link);
		var container = App.helpers.getContainerFromToolLink(link);
		var options = {
			url: "/saved_jobs",
      type: "post",
      data: {job_id: jobId},
			complete: function(request, textStatus) {
				if (request.status == 200) { // saved
					link.parents("li").html(request.responseText);
				} else if (request.status == 202) { // need to register
					container.html(request.responseText);
					container.slideDown();
				}
			}
		};
		$.ajax(options);
		return false;
	});
};

// shows more options for job (permanent link, ...)
App.observers.moreJobOptionsLink = function() {
	$("div.job ul.job-tools li.more-for-job a").click(function() {
		var link = $(this);
		var jobId = App.helpers.getJobIdFromToolLink(link);
		var container = App.helpers.getContainerFromToolLink(link);
    var params = App.helpers.getJobAttrsFromToolLink(link);
		container.load("/jobs/show_more_options/"+jobId, params, function() { container.slideDown(); });
		return false;
	});
};

// shows send to friend form
App.observers.sendJobViaEmailLink = function() {
	$("div.job ul.job-tools li.email-job a").click(function() {
		var link = $(this);
		var jobId = App.helpers.getJobIdFromToolLink(link);
		var container = App.helpers.getContainerFromToolLink(link);
    var params = App.helpers.getJobAttrsFromToolLink(link);
    params['_method'] = 'get';
		container.load("/found_job_emails/new?job_id="+jobId, params, function() { container.slideDown(); });
		return false;
	});
};

// sends email with link to job to friend
App.observers.sendToFriendForm = function() {
	$("div.job div.job-tools-container div.job-tool-email form").livequery("submit", function() {
		var form = $(this);
		var options = { 
			target:	form.parents("div.job").find("div.job-tool-email"),
			beforeSubmit: function(formData, jqForm, options) {
				if(App.helpers.isValidEmail(jqForm[0].to.value)) {
          form.find(':submit').hide().next('span').show();
					return true;
				} else {
					form.prepend('<p style="color:red"><strong>To</strong> must be valid email address</p>');
					return false;
				}
			},
      success: function(responseText, statusText){
        form.find(':submit').show().next('span').hide();
      }
		};
		form.ajaxSubmit(options);
		return false;
	});
};

// close link used to hide additional options for job (save, email, more ...)
App.observers.jobApply = function() {
	$("#show-job .apply .apply_button").livequery("click", function() {
    $(this).hide();
    var container = $(this).next('div');
    container.slideDown();
    container.load("/job_applications/new?job_id="+container.attr("data-job_id"), null, function(){ App.observers.remoteIframeForm() });
    $("#content .flash-msg").remove();
		return false;
	});
	$("#show-job .apply form .submit a").livequery("click", function() {
		$('body').trigger('apply-job:close');
		return false;
	});
  $('body').bind("apply-job:close", function(){
    $("#show-job .apply .apply_button").show();
    $("#show-job .apply_info").slideUp();
    $("#job-apply-form-placeholder").html("Loading...");
  });
  $('.toggle-for-class').livequery("click", function() {
    $('.' + $(this).attr('data-class')).slideToggle();
		return false;
	});
  $('a.remove-linkedin-profile').livequery("click", function() {
    $('#linkedin-placeholder').load($(this).attr('href'));
		return false;
	});
};

App.observers.doJobUrlApply = function(url){
  App.helpers.trackJobApply();
  window.open(url, "_blank");
};
App.helpers.trackJobApply = function(){
  try {
    pageTracker._trackEvent("Job", "Applied")
  } catch(err) {}
};

// set form values if currently field is empty
App.observers.formValues = function(){
  $('body').bind("form:set_values", function(e, object_name, form){
    var prefix = object_name && object_name != '' ? '#' + object_name + '_' : '#';

    for(var key in form){
      var f = $(prefix + key);
      if(f.val() == ''){
        f.val(form[key]);
      }
    }
  });
};

App.observers.remoteIframeForm = function() {
  var showSubmit = function() {
    $("form.remote-iframe :submit").show().next('span').hide();
  };
  $("form.remote-iframe").ajaxForm({
      iframe: true,
      beforeSubmit: function(data, form){
        form.find(':submit').hide().next('span').show();
        setTimeout(showSubmit, 5000);
      },
      success: showSubmit
  });
};


// ======================================================================
// HELPERS USED APPLICATION WIDE
// ======================================================================
// Define specific helpers same way as here (App.helpers.myHelper = function(params) { ... })
// but in separate file that you will use with specific layout our view


// Returns true if str is valid email address, false otherwise
// Credits: SmartWebby.com (http://www.smartwebby.com/dhtml/)
App.helpers.isValidEmail = function(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
 	return true;
};

App.helpers.getJobIdFromToolLink = function(link) {
	return link.parents("div.job").attr("id").replace("job-", "");
}
App.helpers.getJobAttrsFromToolLink = function(link) {
  var attrs = {};
  link.parents("div.job").find("input[type=hidden]").each(function(){ attrs[$(this).attr('name')] = $(this).val(); });
  return attrs;
}
App.helpers.getContainerFromToolLink = function(link) {
	return link.parents("div.job").find("div.job-tools-container");
}

// safe method of displaying email address, using ROT13 encryption and decrypting using js
// http://techblog.tilllate.com/2008/07/20/ten-methods-to-obfuscate-e-mail-addresses-compared/
function decrypt_mail_to( email ){
	var mail_to = "<n uers=\"znvygb:" + email + "\" ery=\"absbyybj\">" + email + "</n>";
	document.write( mail_to.replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<='Z'?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}));
}

