/* Just a simple script define various small functions.
 */

/* Simple function that uses the ajax_translate page to let
   Plone manage the translation of some strings.
 */
ajax_translate = function(msg) {
    var res = '';
    jq.ajax({url: 'ajax_translate?msg=' + msg,
		success: function(d) {
		             res = d;
	                 },
		async: false});

    return res;
};

bind_improvement_inline_edit = function($) {
    /* Bindings for JobPerformance edit. */
    here = window.location;

    $('div#improvement-areas').pyproxy('click',
				       here +'/jq_show_improvement_edit_form');
    $('form.inlineForm input[name=improvement-save]').pyproxy('click',
							      here + '/jq_hide_improvement_edit_form',
							      '#improvement-areas-edit');
    
    $('form.inlineForm input[name=improvement-cancel]').pyproxy('click',
								here + '/jq_hide_improvement_edit_form');	
};

/* Hides messages which have the 'no_js_warning' class.*/
hide_no_js = function() {
	jq('.no_js_warning').remove();
}

/* Transforms a URL to a dictionnary where keys are the GET parameters
   with associated values.*/
url_to_dict = function(url) {
    res = {};
    /* Regular expression splitting the url in three parts:
       - everything before the ?
       - everything between ? and #
       - everything afer # (included)
       We just need the second part.
     */
    reg = new RegExp('^(http(s)?://.*)\\\?([A-Za-z0-9_&=\\\-]*)(#.*)?$');

    if (reg.exec(url) == null) {
	return res;
    }

    params = reg.exec(url)[3].split('&')
    for (i = 0; i < params.length; i++) {
	param_s = params[i].split('=');
	if (param_s.length == 2) {
	    res[param_s[0]] = param_s[1];
	}
    }
    return res;
};

(function ($) {
    /* http://remysharp.com/2008/01/21/fixing-ie-overflow-problem/ */
    $.fn.fixOverflow = function () {
	if ($.browser.msie) {
	    return this.each(function () {
		if (this.scrollWidth > this.offsetWidth) {
		    $(this).css({ 'padding-bottom' : '20px', 'overflow-y' : 'hidden' });
		}
	    });            
	} else {
	    return this;
	}
    };
})(jQuery);

jq(document).ready(function() {
    /* Fix display bug when bad files are submitted in employee edit page.*/
    jq('#archetypes-fieldname-idScan.error, #archetypes-fieldname-portrait.error').append('<div class="visualClear"></div>');

    bind_improvement_inline_edit(jQuery);
    hide_no_js();

    /* Display or hide spinner when a Ajax call is performed.*/
    jQuery('#kss-spinner').ajaxStart(
    function() {
        $(this).show();
    });

    /* Display or hide spinner when a Ajax call is performed.*/
    jQuery('#kss-spinner').ajaxStop(
    function() {
        $(this).hide();
        hide_no_js();
    });

    /* Fix overflow problems with IE*/
    jQuery('.overflow_container').fixOverflow();
});
