/**
 * Functions callend on page load for all modules
 */

/**
 * Add listener for ajax start and stop events
 *
 * @return void
 */
function ajaxLoadListener(){
    // add loading indicator and change cursor to busy
    jq('div#header div#ajax-loader').
    ajaxStart(function(){
        jq(this).show();
        jq('body').css({cursor: 'progress'});
    }).
    ajaxStop(function(){
       jq(this).hide();
       jq('body').css({cursor: 'auto'});

       // reset forms for jQuery.changes plugin
       jq('form.checkChanges').changes( 'initialize' );
    });
}

/**
 * Toggle menu sublists
 *
 * @return void
 */
function toggleList(){
	jq('div.sublist div.title').
	bind('click', function(){
		// if sublist is visible hide it
		if( jq(this).hasClass('active') && jq(this).next('div.list').css('display') == 'block' ){
			jq(this).
			removeClass('active').
			next('div.list').
			hide();
		}else{
            // calculate sublist top position
            var listTop = /*parseInt(jq(this).parent().height())*/ 37 -
                          parseInt(jq(this).css('margin-bottom')) +
                          'px';


            // calculate sublist left position
            var listLeft = jq(this).position().left -
                           parseInt(jq(this).next('div.list').width()) +
                           parseInt(jq(this).parent().width()) -
                           parseInt(jq(this).css('margin-left')) -
                           parseInt(jq(this).css('margin-right')) -
                           parseInt(jq(this).css('padding-left')) -
                           1 + /* border */
                           'px';

			jq(this).
			addClass('active').
			next('div.list').
            css({
                'top': listTop,
                'left': listLeft
            }).
			show();
		}
	});

    // bind click events on list options
    jq('div#search div.list ul li a').
    bind('click', function(){
        var selOpt = jq(this).attr('rel');
        var $objTitle = jq('div#search div.sublist div.title');

        // change hidden flag
        jq('#search_paramter').val(jq(this).attr('rel'));

        // change list option
        switch( selOpt ){
            case '1':
                 $objTitle.find('div.text').text('Adherents');
                 $objTitle.find('div.icon').attr('class', 'icon adherents');
                break;
            case '2':
                 $objTitle.find('div.text').text('Suppliers');
                 $objTitle.find('div.icon').attr('class', 'icon suppliers');
                break;
            case '3':
                $objTitle.find('div.text').text('Users');
                $objTitle.find('div.icon').attr('class', 'icon users');
                break;
            case '4':
                $objTitle.find('div.text').text('Produits');
                $objTitle.find('div.icon').attr('class', 'icon products');
                break;
            case '5':
                $objTitle.find('div.text').text('Tout');
                $objTitle.find('div.icon').attr('class', 'icon tout');
                break;
        }

        jq('div#search div.sublist div.title').
        removeClass('active').
        next('div.list').
        hide();
    });
}

/**
 * Toggle search input
 *
 * @return void
 */
function toggleSearch(){
	jq('div#search div.input input').
	bind('focus', function(){   // remove generic text on focus
		if( jq(this).val() == 'Recherche...' ){
            jq(this).
            val('').
            addClass('active');
        }
	}).
    bind('blur', function(){    // put generic text back on blur if textbox is empty
		if( jq.trim(jq(this).val()) == '' ){
            jq(this).
            val('Recherche...').
            removeClass('active');
        }
	});
}

/**
 * Bind check all functionality to a checkbox
 * Check all checkboxes with some class from a form
 *
 * @param   string chkAllClassName  class name of the check all checkbox
 * @param   string chkMeClassName   class name of the other checkboxes that should be affected
 * @return  void
 */
function bindCheckAll( chkAllClassName, chkMeClassName ){
    jq('input[type="checkbox"].' + chkAllClassName).
    live('change', function(){
        jq(this).
        closest('form').
        find( 'input[type="checkbox"].' + chkMeClassName).
        attr('checked', jq(this).attr('checked')).
        button("refresh");
    });
}

/**
 * Get callback name from a form
 *
 * @param   object  form            element
 * @param   string  calbackPrefix   callback prefix (search in element class)
 * @return  string  function name or null if no callback found
 */
function calbackName( form, callbackPrefix ){
    // get callback function names
    var callbackIndex = form.attr('class').indexOf(callbackPrefix)
    var callbackRx = callbackPrefix + '(.*?)(?:\\s|$)';
    var regex = new RegExp( callbackRx, 'ig' );
    var matches = form.attr('class').match( regex );

    // clean matches
    if( matches != null ){
        for( val in matches ){
            matches[val] = jq.trim( matches[val].toString().replace( callbackPrefix, '' ) );
         }
    }

    return matches;
}

/**
 * Overwrite submit event on forms and if the form has the class "ajax" make
 * an ajax request instead of submit the form
 *
 * @return void
 */
function executeSubmit(){
    jq('form').
    live('submit', function(event){
        if(jq(this).hasClass('ajax')){
            // check for callbacks
            preCallbackPrefix = 'before_';          // execute before submit
        	postCallbackPrefix = 'callback_';       // execute after submit

            callback = {
                pre:    calbackName( jq(this), preCallbackPrefix ),
                post:   calbackName( jq(this), postCallbackPrefix )
            }

            ajaxFormSubmit(jq(this).attr('action'), jq(this).attr('id'), callback);
            event.stopImmediatePropagation();
            return false;
        }

        return true;
    });
}

/**
 * Call submit if enter key is pressed on a form input or a button (link) with
 * class submit is pressed
 *
 * @return void
 */
function submitOnEnter(){
    jq('form').         // check if enter was pressed
    live('keydown', function(e){
        if( !jq(e.target).hasClass('ui-pg-input') && !jq(e.target).hasClass('ui-pg-selbox') && //pagination for jqGrid must not call submit on enter
            !jq(e.target).hasClass('no-submit') && e.target.nodeName != 'TEXTAREA' && e.keyCode == 13){
            jq(this).submit();
        }
    }).
    find('a.submit, button.submit').   // check if button link with submit class was pressed
    live('click', function(){
        jq(this).
        closest('form').
        submit();
    });
}


/**
 * Add hover effect and close functionality to tabs
 *
 * @return void
 */
function handleTabs(){
    // get this method name
	var this_url    = window.location.href;
    var from        = base_url.length;
    var to          = this_url.indexOf('/', base_url.length + 1);

    if( to == -1 ){
        to = this_url.length;
    }

	var method = this_url.substring(from, to);

    jq('div.nav li a').
    bind('mouseover', function(){   // mouseover (change background)
        jq(this).
        next('div').
        addClass('hover');
    }).
    bind('mouseout', function(){    // mouseout (restore background)
        jq(this).
        next('div').
        removeClass('hover');
    }).
    next('div').
    bind('click', function(){       // click on close button
        var thisTab = jq(this).parent();
        jq.ajax({
            url: base_url + method + '/ajax_deleteTab',  // @TODO dynamic controller name
            type: 'post',
            data: 'id=' + jq(this).attr('class'),
            success: function( resp ){
                if( resp == 'true' ){
                    // remove tab
                    var goTo = thisTab.parent().find('li:first a').attr('href');
                    thisTab.remove();

                    // if current tab is closed go to first tab
                    if(thisTab.hasClass('active')){
                        window.location = goTo;
                    }
                }
            }
        });
    });
}

/**
 * Click functionality on edit all button
 *
 * @return void
 */
function bindSelected(){
    jq('div.actions').
    each(function(){
        // remember actions div
        var actions = jq(this);

        // change click functionality on buttons to collect id's from checked checkboxes
        actions.
        find('ul li a.button').
        bind('click', function(){
            var chk = '';

            actions.
            parent().
            find('form input.chk:checked').
            each(function(){
                // add id's separated by colon
                chk += jq(this).attr('name').replace( /(chk\[)|(\])/gi, '' ) + ':';
            });

            // create url and redirect to it
            if( chk.length ){
                var url = jq(this).attr('href') + '/' + chk.substring(0, chk.lastIndexOf( ':' ) );
                window.location = url;
            }

            return false;
        });
    });
}

/**
 * Hide profiler and add show hide functionality
 *
 * @return void
 */
function bindProfiler(){
    // hide profiler by default
    jq('div#codeigniter_profiler').
    hide();

    // add open close functionality
    jq('a#profiler-switch').
    bind('click', function(){
        if(jq('div#codeigniter_profiler').css('display') == 'none'){
            jq('div#codeigniter_profiler').
            slideDown();
            jq(this).text('« hide profiler');
        }else{
            jq('div#codeigniter_profiler').
            slideUp();
            jq(this).text('» show profiler');
        }
    });
}

/**
 * Check if a form was changed before unload page
 *
 * @param   string  selectorParam           selector of the form to check
 * @param   string  messageParam            message to show on page unload
 * @param   string  excludeTriggerParam     class of the trigger to exclude from check
 * @param   array   excludeElementsParam    array of selectors to exclude
 * @return  object  instance of the selected elements
 */
function checkChanges(selectorParam, messageParam, excludeTriggerParam, excludeElementsParam){
    // make parameters default
    if(typeof(selectorParam) == 'undefined' || selectorParam == null){
        selectorParam = 'form';
    }
    if(typeof(messageParam) == 'undefined' || messageParam == null){
        messageParam = 'All changes will be lost!';
    }
    if(typeof(excludeTriggerParam) == 'undefined'){
        excludeTriggerParam = null;
    }
    if(typeof(excludeElementsParam) == 'undefined' || excludeElementsParam == null){
        excludeElementsParam = new Array();
    }

    // check forms
    var forms = jq(selectorParam).changes({
        message:        messageParam,           // message to show if changes were made
        excludeTrigger: excludeTriggerParam,    // class name of the trigger to be excluded
        excludeFields:  excludeElementsParam    // exclude this fields from check
    });

    return forms;
}

/**
 * Open account form on button click or hide if it is opened
 *
 * @return void
 */
function bindCreateAccount(){
    jq('div#contacts div.form a.button.create-account, div#new_contact div.form a.button.create-account').
    live('click', function(){
        $button = jq(this);

        $button.
        parents('form').
        find('fieldset').
        slideToggle('slow', function(){
            if( jq(this).css('display') == 'none' ){
                $button.
                find('span').
                text('Create Account');

                // on cancel empty form
                jq(this).
                find('input[type="text"], input[type="password"]').
                val('');
            }else{
                $button.
                find('span').
                text('Cancel Create');
            }
        });
    });
}

/**
 * Execute ajax to delete account for one contact
 */
function bindDeleteAccount(){
    jq('div#contacts div.form a.button.delete-account').
    live('click', function(){
        // get this contact id from form id
        var contactFormId = jq(this).parents('form').attr('id');
        contactId = contactFormId.substr(contactFormId.lastIndexOf('_') + 1, contactFormId.length - contactFormId.lastIndexOf('_'));

        thisButton = jq(this);

        // call ajax to delete contact
        jq.ajax({
            url: base_url + 'operations/ajax_deleteAccount/',
            type: 'post',
            data: 'id=' + contactId,
            success: function(resp){
                eval( 'var objResp = ' + resp + ';' );

                // if any messages show them in messages box
                if( objResp.messages != null && objResp.messages != undefined ){
                    showMessages( objResp.messages );
                    delete objResp.messages;
                }

                if( objResp.deleted ){
                    // hide this button
                    thisButton.hide();

	                // clean form and hide
	                thisButton.
                    parents('form').
                    find('fieldset').
                    replaceWith(objResp.account_view).
                    end().
                    find('a.button.create-account span').
                    text('Creer utilisateur').
                    parent().
                    // show create button
                    show();
                }
            }
        });
    });
}

/**
 * Order contacts into database
 *
 * @return void
 */
function ajaxOrderContacts(){
    // get ordered contacts id's
    var allIds = '';

    jq('div#contacts').
    find('form').
    each(function(){
        var thisFormId = jq(this).attr('id');
        allIds += thisFormId.substr(thisFormId.lastIndexOf('_') + 1, thisFormId.length - thisFormId.lastIndexOf('_')) + ':';
    });

    allIds = allIds.substring(0, allIds.lastIndexOf( ':' ) );

    // change order in database
    jq.ajax({
        url: base_url + 'operations/ajax_orderContact/',
        type: 'post',
        data: 'allIds=' + allIds,
        success: function(resp){
            // show response messages
            eval( 'var objResp = ' + resp );

            // if any messages show them in messages box
            if( objResp.messages != null && objResp.messages != undefined ){
                showMessages( objResp.messages );
                delete objResp.messages;
            }

            // refresh contacts actions
            refreshContactsActions();
        }
    });
}

/**
 * Add jquery UI sort functionality to contacts boxes
 * Add events on order arrows
 *
 * @return void
 */
function bindDragOrderContacts(){
    // order only if number of contacts > 1
    if(jq('div#contacts div.form').length > 1){
        jq('div#contacts').
        sortable({
            scroll: true,
            revert: 'true',
            update: function(event, ui){
                // order contacts into database
                ajaxOrderContacts();
            }
        });

        // add click events on order arrows for contacts
        jq('div#contacts div.form div.toolbar div.right a.up').     // up event
        bind('click', function(){
            var thisButton = jq(this);

            bindClickOrderContacts(thisButton, true);
        });

        jq('div#contacts div.form div.toolbar div.right a.down').   // down event
        bind('click', function(){
            var thisButton = jq(this);

            bindClickOrderContacts(thisButton, false);
        });
    }
}

/**
 * Add delete contact functionality
 *
 * @return  void
 */
function bindDeleteContact(){
    jq('div#contacts div.form div.toolbar div.right a.close').
    unbind('click').
    bind('click', function(){
        if( confirm( lang.delete_element ) == false )
            return false;
        else {
            // get this contact type (supplier, distributor) if any
            type = jq(this).parent().parent().parent().find('form').find('input[type="hidden"][name="form[objType]"]').val() || '';
            if( type != '' ){
                type = '&type=' + type;
            }

            // get this contact id from form id
            var contactFormId = jq(this).parent().parent().parent().find('form').attr('id');
            contactId = contactFormId.substr(contactFormId.lastIndexOf('_') + 1, contactFormId.length - contactFormId.lastIndexOf('_'));

            // call ajax to delete contact
            jq.ajax({
                url: base_url + 'operations/ajax_deleteContact/',
                type: 'post',
                data: 'id=' + contactId + type,
                dataType: 'json',
                success: function(objResp){
                    // if any messages show them in messages box
                    if( objResp.messages != null && objResp.messages != undefined ){
                        showMessages( objResp );
                    }

                    if( objResp.deleted ){
                        // delete this contact form
                        jq('form#' + contactFormId).
                        parent().
                        remove();
                    }

                    // refresh contacts actions
                    refreshContactsActions();
                }
            });
        }
    });
}

/**
 * Transform buttons to jQuery UI style
 *
 * @return void
 */
function bindButtons(){
    jq('a.button').
    button();
}

/**
 * Transform radios to jQuery UI style
 *
 * @return void
 */
function bindRadios(){
    jq('.radio-group').
    buttonset();
    jq('.radio').
    button();
}

/**
 * Transform checkboxes to jQuery UI style
 *
 * @return void
 */
function bindCheckboxes(){
    jq('.checkbox-group').
    buttonset();
    jq('.checkbox').
    button();
}

/**
 * Add close functionality on messages close button
 *
 * @return void
 */
function bindCloseMessages(){
    jq('div#messages div.close a').
    bind('click', function(){
        jq(this).
        parents('div#messages').
        remove();
    });
}

function bindContactsSubmit( method, formName, params ){
	var contact_id = jq(this).find('input[type="hidden"]').val();
	jq('form:not(#frmAdherent) a.button').
	bind('click', function(){ajaxFormSubmit(method, formName + contact_id, params);});
}

/**
 * Expand contact details to show other fields
 *
 * @return  void
 */
function expandContactDetails(){
	jq('a.to_show_details').
	live('click', function(){
		jq(this).
        next().
        slideToggle();
	});
}

/**
 * Generate category tree using treeThis plugin
 *
 * @access  public
 * @param   checkbox    show checkboxes
 * @return  void
 */
function initCatTree( checkbox ){
    // default param
    var check = checkbox;
    if( typeof( check ) == 'undefined' ){
        check = false;
    }

    $objCategories = jq('div#catTree').
    treeThis({
        rel: null,
        url: base_url + 'category/ajax_initCatTree/',
        close: true,
        speed: 500,
        loader: root_url + 'resources/img/ajax_loader2.gif', //bbatea
        loadOnCollapse: true,
        callback: function( rel ){
            // show category details
            showCategory( rel );
        },
        check: check
    });
}

/**
 * Generate all category tree
 *
 * @access  public
 * @return  void
 */
function initAllCatTree(){
    jq.ajax({
        type: 'post',
        url: base_url + 'category/ajax_initAllCatTree/',
        success: function( data ) {
            jq('div#catTree').html(data);
        }
    });
}

/**
 * Show errors from php
 *
 * Read errors from global object "submitErrors" set in header
 * Expected format:
 * {"errors":[{"name":"field_name","message":"message to show next to field"}]}
 *
 * @return  void
 */
function showSubmitErrors(){
    if( typeof( submitErrors ) == 'undefined' ){
        return false;
    }

    errors = submitErrors.errors;

    // for each field with error
    for( field in errors ){
        jq('form [name="' + errors[field].name + '"]').
        removeClass('error').
        addClass('error').
        after('<label class="error" style="display:inline;">' + errors[field].message + '</label>');
    }
}

/**
 * Toggle (show/hide) email boxes excepting first email in thread and replay form
 *
 * @return void
 */
function toggleMailBoxes(){
    // hide all first
    jq( 'div.form.multiple table:not(:first):not(:last)' ).hide();

    // toggle on toolbar click
    jq( 'div.form.multiple div.toolbar:not(:first):not(:last)').
    bind( 'click', function(){
        jq(this).
        parents( 'div.form.multiple' ).
        find('table').
        toggle();
    });
}

/**
 * Autocomplete to field for emails
 *
 * @return void
 */
function toAutocomplete(){
    jq('#replay_to, #email_to').
    autocomplete({
        source: function( request, response ){
            jq.ajax({
                type: 'post',
                url: base_url + 'operations/ajax_contactAutocomplete/',
                dataType: 'json',
                data: {text: request.term.split(/,\s*/).pop()},
                success: function( data ) {
                    // map data from database with label and value
                    response( jq.map(data, function(item) {
                            items = {
                                label: item.name,
                                value: item.email,
                                id: item.id
                            };

                            return items;
                        })
                    )
                }
            })
        },
        minLength: 3,
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ){
            var terms = this.value.split(/,\s*/);
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( ui.item.value );
            // add placeholder to get the comma-and-space at the end
            terms.push( '' );
            this.value = terms.join( ', ' );
            return false;
        }

    });
}


/**
 * Add new attachment input to emails page
 *
 * @return void
 */
function addNewEmailAttachment(){
    jq( 'input[type="file"].email_attachments:last' ).
    live( 'change', function(){

        var attch_name = jq(this).attr('name');

        jq(this).
        after('<input type="file" class="email_attachments" name="'+attch_name+'" />');
        jq(this).
        after(' <a style ="float:right !important;" class="button-delete" href = "javascript:void(null)" onclick="deleteEmailAttachement(this)"></a>');
    });
}



function addNewEmailAttachmentMoreSuppliers(){
    jq( 'input[type="file"].email_attachments_for_fill' ).
    live( 'change', function(){

        var attch_name = jq(this).attr('name');
        jq(this).removeClass('email_attachments_for_fill');

        jq(this).
        before('<input type="file" class="email_attachments_for_fill" name="'+attch_name+'" /><br/>');
        jq(this).
        after(' <a style ="float:right !important;" class="button-delete" href = "javascript:void(null)" onclick="deleteEmailAttachementCustom(this)"></a>');
    });
}


function deleteEmailAttachement(my_this)
{
    jq(my_this).prev().remove();
    jq(my_this).remove();
}

function deleteEmailAttachementCustom(my_this)
{
    jq(my_this).prev().remove();
    jq(my_this).prev().remove();
    jq(my_this).remove();
}

/**
 * Autocomplete supplier field
 *
 * @param   string  selector    what element to autocomplete
 * @param   string  url         what ajax function to call
 * @param   string  callback    function to call on success
 * @return  void
 */
function autocompleteField( selector, url, callback ){
    jq(selector).
    autocomplete({
        source: function( request, response ){
            jq.ajax({
                type: 'post',
                url: base_url + url,
                dataType: 'json',
                data: {text: request.term.split(/,\s*/).pop()},
                success: function( data ) {
                    // map data from database with label and value
                    response( jq.map(data, function(item) {
                            return {
                                label: item.name,
                                value: item.email,
                                id: item.id
                            };
                        })
                    )
                }
            })
        },
        minLength: 3,
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ){
            if( typeof( callback ) != 'undefined' && callback != '' && typeof( window[callback] ) == 'function' ){
                window[callback]( this, ui );
            }
        }

    });
}


/**
 * Change hidden field from autocomplete
 *
 * This function is a callback called from autocompleteField
 *
 * @param   myThis  this value from caller function
 * @param   ui      ui object from caller function
 * @return  boolean false
 */
function autocompleteHidden( myThis, ui ){
    myThis.value = ui.item.value;
    jq(myThis).parent().find('input[type="hidden"]').val( ui.item.id );
    return false;
}

/**
 * Change hidden field from autocomplete and clean the cas div
 *
 * This function is a callback called from autocompleteField
 *
 * @param   myThis  this value from caller function
 * @param   ui      ui object from caller function
 * @return  boolean false
 */
function autocompleteHiddenFacture( myThis, ui ){
    myThis.value = ui.item.value;
    jq(myThis).parent().find('input[type="hidden"]').val( ui.item.id );

    jq('#caTable').html('');

    return false;
}

/**
 * Generate category tree using treeThis plugin and a callback
 *
 * @return  void
 */
function initCatTreeWithCallback( callbackFunc ){
    $objCategories = jq('div#catTree').
    treeThis({
        rel: null,
        url: base_url + 'category/ajax_initCatTree/',
        close: true,
        speed: 500,
        loader: root_url + 'resources/img/ajax_loader2.gif',
        loadOnCollapse: true,
        callback: callbackFunc
    });
}





function set_year_quarter_min(month)
{
	switch(month)
	{
		case 12:
		{
			return "Q1";
		}
		case 3:
		{
			return "Q2";
		}
		case 6:
		{
			return "Q3";
		}
		case 9:
		{
			return "Q4";
		}
		default:
		{
			return "Q1";
		}
	}
}


function set_year_by_month(min_year, min_month, step)
{
	if (step == 0 && min_month != 12)
		{
			return min_year;
		}
	else if (step == 0 && min_month == 12)
		{
			return min_year + 1;
		}
	if (min_month == 12)
	{
		return min_year + 1 + parseInt(step - (step%4)) / 4;
	}
	else if (min_month == 3)
	{
		return min_year + parseInt(step+1 - ((step+1)%4)) / 4;
	}
	else if (min_month == 6)
	{
		return min_year + parseInt(step+2 - ((step+2)%4)) / 4;
	}
	else if (min_month == 9)
	{
		return min_year + parseInt(step+3 - ((step+3)%4)) / 4;
	}
}

function set_month(min_month, step)
{
	if (step == 0)return min_month;
	if (min_month == 12)
	{
		return (step%4)* 3;
	}
	else
	{
		if ((min_month + (step%4)* 3) > 12)
		{
			return (min_month + (step%4)* 3) - 12;
		}
		else
		{
			return (min_month + (step%4)* 3);
		}

	}
}

function periodSlider( selector, min, max, step, leftValue, rigthValue )
{
	leftValue = parseInt(leftValue);
	rigthValue = parseInt(rigthValue);
	date_min = jq('input#date_min').attr('value');
	date_max = jq('input#date_max').attr('value');
	year_min_to_show = 2010;
	year_max_to_show = 2010;
	month_min_to_show = "Q1";
	month_max_to_show = "Q2";
	min_value = '2009 Q1';
	max_value = '2010 Q2';

	month_min = parseInt(date_min) % 100;
	month_max = parseInt(date_max) % 100;

	year_min = parseInt(date_min - month_min) / 100;
	year_max = parseInt(date_max - month_max) / 100;

    jq(selector + ' div').slider({
        range: true,
        min: 0,
        max: max,
        step: step,
        values: [leftValue,rigthValue],
        slide: function(event, ui) {

    		if (year_min == year_max)
    			{
    				year_min_to_show = year_min;
    				year_max_to_show = year_min;
    				if(ui.values[0] == 0)
    				{
    					month_min_to_show = set_year_quarter_min(month_min);
    				}
    				else if (ui.values[0] == 1)
					{
    					if (month_min == 1)
						{
    						month_min_to_show = set_year_quarter_min(3);
						}
    					else
    					{
    						month_min_to_show = set_year_quarter_min(parseInt(month_min) + 3);
    					}
					}
    				else if (ui.values[0] == 2)
					{
    					if (month_min == 1)
						{
    						month_min_to_show = set_year_quarter_min(6);
						}
    					else
						{
    						month_min_to_show = set_year_quarter_min(parseInt(month_min) + 6);
						}
					}
    				else if (ui.values[0] == 3)
					{
    					if (month_min == 1)
						{
    						month_min_to_show = set_year_quarter_min(9);
						}
					}

    				if(ui.values[1] == 0)
    				{
    					month_max_to_show = set_year_quarter_min(month_min);
    				}
    				else if (ui.values[1] == 1)
					{
    					if (month_min == 1)
						{
    						month_max_to_show = set_year_quarter_min(3);
						}
    					else
    					{
    						month_max_to_show = set_year_quarter_min(parseInt(month_min) + 3);
    					}
					}
    				else if (ui.values[1] == 2)
					{
    					if (month_min == 1)
						{
    						month_max_to_show = set_year_quarter_min(6);
						}
    					else
						{
    						month_max_to_show = set_year_quarter_min(parseInt(month_min) + 6);
						}
					}
    				else if (ui.values[1] == 3)
					{
    					if (month_min == 1)
						{
    						month_max_to_show = set_year_quarter_min(9);
						}
					}

    			}
    		else
    			{
    				year_min_to_show = set_year_by_month(year_min,month_min,ui.values[0]);
    				year_max_to_show = set_year_by_month(year_min,month_min,ui.values[1]);
    				month_min_to_show = set_year_quarter_min(set_month(month_min,ui.values[0]));
    				month_max_to_show = set_year_quarter_min(set_month(month_min,ui.values[1]));
    			}
//
//            var maxval = ui.values[1];
//            if(maxval == '200') maxval = '200+';
//            if (maxval == '1000000') maxval = '1000000+';
            jq(this).prev().val(ui.values[0]);
            jq(this).next().val(ui.values[1]);
            jq(selector + ' input#date_start').val(year_min_to_show + ' ' + month_min_to_show);
            jq(selector + ' input#date_end').val(year_max_to_show + ' ' + month_max_to_show);
        }
    });

    //jq( selector + ' div' ).slider( "option", "values", [jq(selector + ' input:first').val(),jq(selector + ' input:last').val()] );


	year_min_to_show = set_year_by_month(year_min,month_min,min);
	year_max_to_show = set_year_by_month(year_min,month_min,max);
	month_min_to_show = set_year_quarter_min(set_month(month_min,min));
	month_max_to_show = set_year_quarter_min(set_month(month_min,max));

    //jq(selector + ' input#date_start').val(year_min_to_show + ' ' + month_min_to_show);
    //jq(selector + ' input#date_end').val(year_max_to_show + ' ' + month_max_to_show);



}

function showChart( cas, xText ){
    var r = Raphael( 'raphaChart' );
    r.g.txtattr.font = '12px "Fontin Sans", Fontin-Sans, sans-serif';

    // prepare chart input arrays
    var labels = new Array();
    var xAxis = new Array();
    var yAxis = new Array();

    for( ca in cas ){
        labels.push( ca );
        xAxis.push( cas[ca].x );
        yAxis.push( cas[ca].y );
    }

//    console.dir( xAxis );
//    console.dir( yAxis );
//    console.dir( labels );

    r.g.linechart(
        100, 100, 600, 350,
           xAxis,
           xText,
           yAxis,
        {
            axis: '0 0 1 1',
            symbol: 'o',
            smooth: false,
            legend: labels,
            width: 2
        }
    ).
    hoverColumn(function(){
        this.tags = r.set();
        for (var i = 0, ii = this.y.length; i < ii; i++) {
            this.tags.push(
                r.g.tag( this.x, this.y[i], 'value: ' + this.values[i], 0, 3 ).
                insertBefore( this ).
                attr(
                    [
                        {fill: '#000', color: '#fff', opacity: 0.7},
                        {fill: '#fff'}
                    ]
                )
            );
        }
    }, function () {
        this.tags && this.tags.remove();
    }).
    symbols.
    attr( {r: 3} );
}

/**
 *
 * Create 2 datePickers (start and end)
 *
 * @return void
 */
function initializeDatePickers(){
    jq('#datepicker1, #datepicker2').datepicker({'dateFormat': dpDateFormat});
}

/**
 * Autocomplete adherent field
 *
 * @param   string  selector    what element to autocomplete
 * @param   string  url         what ajax function to call
 * @param   string  callback    function to call on success
 * @return  void
 */
function autocompleteFieldCustom( selector, url, callback, limit, clearFields ){
    jq(selector).
    autocomplete({
        source: function( request, response ){
            jq.ajax({
                type: 'post',
                url: base_url + url,
                dataType: 'json',
                data: {text: request.term.split(/,\s*/).pop()},
                success: function( data ) {
                    // map data from database with label and value
                    response( jq.map(data, function(item) {
                            return {
                                label: item.name,
                                value: item.name,
                                id: item.id

                            };
                        })
                    )
                }
            })
        },
        minLength: limit,
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ){
            // if callback exists call function
            if( typeof( callback ) != 'undefined' && callback != '' && typeof( window[callback] ) == 'function' ){
                window[callback]( this, ui );
            }

            // if clear fields selected make clear
            if( typeof( clearFields ) != 'undefined' ){
                for( var i = 0; i < clearFields.length; i++ ){
                    jq('#'+clearFields[i]).val('');
                }
            }
        }

    });
}

/**
*
* Create 24 datePickers (start and end)
*
* @return void
*/
function initializeDatePickersArray(datePickers)
{
    for (k in datePickers)
        {
            jq('#'+datePickers[k]).datepicker({'dateFormat': dpDateFormat});
        }

}

/**
 * Delete supplier from email list on adherent email page
 *
 * @return void
 */
function deleteSupplierEmail(){
    jq('#suppliersEmail a.button-delete').
    live('click', function(){
        jq(this).parent().parent().remove();
    });
}

function shouldHideDistributors() {
    var hide_distribs = 1;
    if (jq('#commerciale1').is(':checked')) hide_distribs = 1;
    else if (jq('#commerciale2').is(':checked')) hide_distribs = 1;
    else if (jq('#commerciale3').is(':checked')) hide_distribs = 1;
    else if (jq('#commerciale4').is(':checked')) hide_distribs = 1;
    else if (jq('#commerciale5').is(':checked')) hide_distribs = 0;
    else if (jq('#commerciale6').is(':checked')) hide_distribs = 0;
    return hide_distribs;
}

/**
 * Add supplier to list from sending email formular
 *
 * Add client code and distributor too
 * html template is loaded from supplier views
 *
 * @return  void
 */
function callbackAddSupplier( myThis, ui ){
    jq.ajax({
        url: base_url + 'supplier/ajax_getSupplierInfoForEmail/0/'+shouldHideDistributors(),
        type: 'post',
        dataType: 'json',
        data: {
            'suppName': ui.item.label,
            'suppId': ui.item.id,
            'adhId': rsegment_array[2]
        },
        success: function( resp ){
            jq('#suppliersEmail tbody').
            append(resp.view);

            jq('#supplier_name').val('');
        }
	});

    return false;
}

function methodAddSupplier( suppId ){
    jq.ajax({
        url: base_url + 'supplier/ajax_getSupplierInfoForEmail/0/'+shouldHideDistributors(),
        type: 'post',
        dataType: 'json',
        data: {
            'suppName': '',
            'suppId': suppId,
            'adhId': rsegment_array[2]
        },
        success: function( resp ){
            jq('#suppliersEmail tbody').
            append(resp.view);

            jq('#supplier_name').val('');
        }
	});

    return false;
}

/**
 * Add supplier to list from sending email formular
 *
 * Add client code and distributor too
 * html template is loaded from supplier views
 *
 * @return  void
 */
function callbackReplaceSupplier( myThis, ui ){
    jq.ajax({
        url: base_url + 'supplier/ajax_getSupplierInfoForEmail/1/'+shouldHideDistributors(),
        type: 'post',
        dataType: 'json',
        data: {
            'suppName': ui.item.label,
            'suppId': ui.item.id,
            'adhId': rsegment_array[2]
        },
        success: function( resp ){

            var existent_suppliers = jq('input.email_suppliers');
            var existent = false;

           jq.each(existent_suppliers, function(key, value){

            if (jq(value).val() == ui.item.id) existent = true;

            });
//            jq('#suppliersEmail tbody').html(resp.view);

            if (existent == false)
            {
                jq('#supplier_name').val('');
                jq('#email_supplier_id').val(ui.item.id);
                jq('#suppliers_div').prepend(resp.view_content);
            }
        }
	});

    return false;
}

function methodReplaceSupplier( suppId ){
    jq.ajax({
        url: base_url + 'supplier/ajax_getSupplierInfoForEmail/1/'+shouldHideDistributors(),
        type: 'post',
        dataType: 'json',
        data: {
            'suppName': '',
            'suppId': suppId,
            'adhId': rsegment_array[2]
        },
        success: function( resp ){
//            jq('#suppliersEmail tbody').html(resp.view);

            jq('#supplier_name').val('');
            jq('#email_supplier_id').val(suppId);
            jq('#suppliers_div').prepend(resp.view_content);
        }
	});

    return false;
}

/**
 * Add supplier to list from sending email formular
 *
 * Add client code and distributor too
 * html template is loaded from supplier views
 *
 * @return  void
 */
function callbackAddSupplierForMercuriales( myThis, ui ){
    jq.ajax({
        url: base_url + 'supplier/ajax_getSupplier_for_mercuriales/',
        type: 'post',
        dataType: 'json',
        data: {
            'suppName': ui.item.label,
            'suppId': ui.item.id,
            'adhId': rsegment_array[2]
        },
        success: function( resp ){
            jq('#suppliersEmail tbody').
            append(resp.view);

            jq('#supplier_name').val('');
        }
	});

    return false;
}

function confirmDelete(){
    jq('a.button-delete, div#contacts a.close, a.supprimer_pop_up').
    unbind('click').
    bind('click', function(e){
        if( confirm( lang.delete_element ) == false ){
            e.stopImmediatePropagation();
            return false;
        }
    });
}

function get_ca_compare_default()
{
    jq('#button_submit_ca_compare').click();
}

