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


// 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 job alert box
App.observers.jobAlertCloseLink = function() {
	$("div.job-alert-container a.job-alert-close").livequery("click", function() {
		$(this).parent().slideUp();
		return false;
	});
}

// close link used to hide additional options for job (save, email, more ...)
App.observers.jobToolsCloseLink = function() {
	$("div.job div.job-tools-container a.job-tools-close").livequery("click", function() {
		$(this).parent().slideUp();
		return false;
	});
}

// job alert
App.observers.jobAlertLink = function() {
	$("ul#content-top-links li.job-alert a").click(function() {
		var link = $(this);
		var container = link.parents("div").find("div.job-alert-container");
		options = {
			url: "/alerts/new?"+link.attr("query"),
			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;
	});
}

// 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);
		container.load("/jobs/show_more_options/"+jobId, null, 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);
		container.load("/found_job_emails/new?job_id="+jobId, null, 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)) {
					return true;
				} else {
					form.prepend('<p style="color:red"><strong>To</strong> must be valid email address</p>');
					return false;
				}
			}
		};
		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).next('div').slideDown();
		return false;
	});
	$("#show-job .apply form .submit a").livequery("click", function() {
		$(this).closest('.apply_info').slideUp();
		return false;
	});
};

// close link used to hide additional options for job (save, email, more ...)
App.observers.remoteIframeForm = function() {
	$("form.remote").ajaxForm({
      iframe: true,
      beforeSubmit: function(data, form){
        form.find(':submit').hide().next('span').show();
      },
      success: function(responseText, statusText){
        $("form.remote :submit").show().next('span').hide();
      }
  });
};


// ======================================================================
// 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.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);}));
}

