/*
Jquery and Rails powered default application.js
Easy Ajax replacement for remote_functions and ajax_form based on class name
All actions will reply to the .js format
Unostrusive, will only works if Javascript enabled, if not, respond to an HTML as a normal link
respond_to do |format|
  format.html
  format.js {render :layout => false}
end
*/

// jQuery no confllict
jQuery.noConflict();

// needed for google analytics
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl.": "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try {
    var pageTracker = _gat._getTracker("UA-8084172-3");
    pageTracker._trackPageview();
} catch(err) {}

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

/*
Submit a form with Ajax
Use the class ajaxForm in your form declaration
<% form_for @comment,:html => {:class => "ajaxForm"} do |f| -%>
*/
jQuery.fn.submitWithAjax = function() {
    this.unbind('submit', false);
    this.submit(function() {
        jQuery.post(this.action, jQuery(this).serialize(), null, "script");
        return false;
    })

    return this;
};

/*
Retreive a page with get
Use the class get in your link declaration
<%= link_to 'My link', my_path(),:class => "get" %>
*/
jQuery.fn.getWithAjax = function() {
    this.unbind('click', false);
    this.click(function() {
        jQuery.get(jQuery(this).attr("href"), jQuery(this).serialize(), null, "script");
        return false;
    })
    return this;
};

/*
Post data via html
Use the class post in your link declaration
<%= link_to 'My link', my_new_path(),:class => "post" %>
*/
jQuery.fn.postWithAjax = function() {
    this.unbind('click', false);
    this.click(function() {
        jQuery.post(jQuery(this).attr("href"), jQuery(this).serialize(), null, "script");
        return false;
    })
    return this;
};

/*
Update/Put data via html
Use the class put in your link declaration
<%= link_to 'My link', my_update_path(data),:class => "put",:method => :put %>
*/
jQuery.fn.putWithAjax = function() {
    this.unbind('click', false);
    this.click(function() {
        jQuery.put(jQuery(this).attr("href"), jQuery(this).serialize(), null, "script");
        return false;
    })
    return this;
};

/*
Delete data
Use the class delete in your link declaration
<%= link_to 'My link', my_destroy_path(data),:class => "delete",:method => :delete %>
*/
jQuery.fn.deleteWithAjax = function() {
    this.removeAttr('onclick');
    this.unbind('click', false);
    this.click(function() {
        if (confirm('Wollen Sie dieses Element wirklich löschen?')) {
            jQuery.delete_(jQuery(this).attr("href"), jQuery(this).serialize(), null, "script");
        }
        return false;
    })
    return this;
};

/*
Ajaxify all the links on the page.
This function is called when the page is loaded. You'll probaly need to call it again when you write render new datas that need to be ajaxyfied.'
*/
function ajaxLinks() {
    jQuery('.ajaxForm').submitWithAjax();
    jQuery('a.get').getWithAjax();
    jQuery('a.post').postWithAjax();
    jQuery('a.put').putWithAjax();
    jQuery('a.delete').deleteWithAjax();
}

jQuery(document).ready(function() {

	// All non-GET requests will add the authenticity token
	// if not already present in the data packet
	jQuery("body").bind("ajaxSend", function(elm, xhr, s) {
		if (s.type == "GET") return;
		if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
		if (s.data) {
		  s.data = s.data + "&";
		} else {
		  s.data = "";
		  // if there was no data, $ didn't set the content-type
		  xhr.setRequestHeader("Content-Type", s.contentType);
		}
		s.data = s.data + encodeURIComponent(window._auth_token_name)
		                + "=" + encodeURIComponent(window._auth_token);
	});

    ajaxLinks();
});