$(document).ready(function() {
    /* reset input on focus/blur */
    $('.reset-focus').focusClearsDefault();
    
    /* Ajax tricks */
    $('form.ajaxify').bind('submit', function(e) {
        e.preventDefault();
        AJAX.ajaxify($(this), {
           'params' : AJAX.hashifyForm($(this))
        });
    });
    
    /* Stylize tabs */
    $('div.box-fbox-table').stylise();
    
    /* Tipster */
    if (typeof(tooltip) != "undefined") {
        tooltip('.tipster');
    }
});


var AJAX = {
    /*
     * Make a request ajax to el.attr url.
     * @params el : Element binded
     * @params settings : Hash of options
     * @return N/A
    */
    ajaxify: function(el, settings) {
        options =  {
            'attr': 'auto',
            'confirmation_message': '',
            'params': {},
            'type': 'POST',
            'dataType': 'html',
            'callback_success': false,
            'callback_error': false,
            'callback_complete': false
        };
        var options = $.extend(options, settings);
        
        ajax_options = {
            'ajax': 1
        }
        var ajax_options = $.extend(ajax_options, options.params);
        
        var el_is_form = false;
        if(options.attr == 'auto') {
            switch($(el).tagName()) {
                case 'form' :
                    options.attr = 'action';
                    el_is_form = true;
                break;
                case 'a':
                default:
                    options.attr = 'href';
                break;
            }
        }
        
        var url = $(el).attr(options.attr);
        if ( !url ) 
            url = window.location.href;

        var action = function() {
            
            $.ajax({
                type: options.type,
                data: ajax_options,
                dataType: options.dataType,
                url: url,
                success: function(response) {
                    if(options.callback_success) {
                        options.callback_success($(el), response);
                    }
                    if(el_is_form && options.params.callback_success) {
                        eval(options.params.callback_success)($(el), response);
                    }
                    AJAX.hideError();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    if(options.callback_error) {
                        options.callback_error($(el), XMLHttpRequest, textStatus, errorThrown);
                    }
                    else if(el_is_form && options.params.callback_error) {
                        eval(options.params.callback_error)($(el), XMLHttpRequest, textStatus, errorThrown);
                    }
                    else {
                        AJAX.showError(XMLHttpRequest.responseText);
                    }
                },
                complete: function(XMLHttpRequest, textStatus) {
                    if(options.callback_complete) {
                        options.callback_complete($(el), XMLHttpRequest, textStatus);
                    }
                    if(el_is_form && options.params.callback_complete) {
                        eval(options.params.callback_complete)($(el), XMLHttpRequest, textStatus);
                    }
                }
            });
        }
        
        options.confirmation_message = options.confirmation_message || options.params.confirmation_message;
        if (!options.confirmation_message || confirm(options.confirmation_message)) {
            action();
        }
    },
    
    /*
     * Return a hash from a $(form) element.
     * @params el : Form
     * @return hash
    */
    hashifyForm: function(el) {
        var fields = Object();
        $.each($(el).serializeArray(), function(i, object) {
            /* make an array if multiple same input name */
            if (fields[object.name]) {
                if (!$.isArray(fields[object.name])) {
                    var array = new Array();
                    array.push(fields[object.name]);
                    array.push(object.value);
                    fields[object.name] = array;
                }
                else {
                    fields[object.name].push(object.value);
                }
            }
            else {
                fields[object.name] = object.value;
            }
        });
        return fields;
    },
    
    /*
     * Show a nicely errors in the container #ajax-error.
     * The layout must contain an empty fbox error.
    */
    showError: function(mssg) {
        if ($$ = $('#ajax-error')) {
            $$.fadeIn('fast').find('.i3').html(mssg);
        }
        else {
            if(g_dev) {
                alert('#ajax-error not found.');
            }
            alert(mssg);
        }
    },
    
    /*
     * Hide ajax errors
    */
    hideError: function(mssg) {
        if ($$ = $('#ajax-error')) {
            $$.fadeOut();
        }
    }
}


var FORMAT = {
    /*
     * Return the price according to the current currency
     * @params price : float
     * @return string
     */
    currency: function(_price){
        var price_string;
        switch (g_currency) {
            case 'EUR':
                price_string = _price.toFixed(2) + '&nbsp;€';
                price_string = price_string.replace(/\./g, ',');
                break;
            case 'USD':
                price_string = '$' + _price.toFixed(2);
                break;
            case 'GBP':
                price_string = '£' + _price.toFixed(2);
                break;
            default:
                price_string = _price.toFixed(2) + '&nbsp;€';
                price_string = price_string.replace(/\./g, ',');
                break;
        }
        return price_string;
    },
    
    /*
     * Return the size with the unit
     * @params price : float
     * @return string
     */
    size: function(_size, _multiplier){
        switch(_multiplier) {
            case 1:         /* o */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'o' : 'b');
            break;
            case 1024:      /* Ko */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'Ko' : 'Kb');
            break;
            case 1024^2:    /* Mo */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'Mo' : 'Mb');
            break;
            case 1024^3:    /* Go */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'Go' : 'Gb');
            break;
            case 1024^4:    /* To */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'To' : 'Tb');
            break;
            default:        /* Mo */
                return _size + '&nbsp;' + (g_lang == 'fr' ? 'Mo' : 'Mb');
            break;
        }
    }
}
    

/* For IE8 compatibility (which doesn't implement document.getElementByClassName) */
function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
            node = document;
    if ( tag == null )
            tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (var i = 0, j = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
                classElements[j] = els[i];
                j++;
            }
    }
    return classElements;
}

/**
 * Submit d'un form quand click sur pager
 * un seul form par "main"
 * @TODO A pluginiser pour jQuery
 */
function attach_pagers_events(sub) {
    var divs = $('#main div');

    var pagers = new Array();
    
    /* Sub par défaut .. */
    if ( typeof(sub) == "undefined" ) {
        sub = function() { return _submitForm(this) };
    }

    divs.each(function() {
        if($(this).attr('className') == 'pager') {
            pagers.push($(this).find('a'));
        }
    });
    
    for (var i = 0; i < pagers.length; i++) {
        pagers[i].each(function() {
            $(this).click(sub);
        });
    }
}

/**
 * Generic method to raise a warning when clicking links
 *
 * Takes a hash as parameter, associating a classname to an alert message
 * Every link with that class will have a a confirm message bound to the onclick event
 * Call this after the page has been loaded
 */
function confirmActions( messages ) { 
    if (!document.getElementsByTagName) return; 
        /* Regexp to match class name(s) */
        var rega = Array();
        for ( var name in messages ) { 
                if ( typeof(messages[name]) == "string" )
                        rega.push( '(?:^|\s)' + name + '(?:\s|$)' );
        }   

        var reg = new RegExp( rega.join('|'),  'i');
        delete rega;

        /* Function generating functions, to attach to the onclick event */
    var cfm = function(message) {
                return function() {
                        return window.confirm('\n' + message + '\n');   
                }   
        };  

            
        /* Then check every link an attach the function if one class name matches */
        var links = document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
                var match;
                var cls = links[i].className;
    
                if ( cls && (match = reg.exec(cls)) ) { 
                        links[i].onclick = cfm(messages[match[0]]);
                }
        }
}
