/**
 * Functions for all modules
 */

// overwrite jquery default object ($) with "jq" (jQuery is still available)
var jq = jQuery.noConflict();

/**
 * Sumbmit a form through ajax.
 * All elements in to form will be submited through post method.
 *
 * @param   string  method  name of the php method to call (e.g: controller/method/)
 * @param   string  formId  id of the form to serialize and send to php
 * @param   object  callback  an object with extra parameters to send to php
 */
function ajaxFormSubmit(method, formId, callback){
    // if any pre callback function call it
    if( callback.pre != null && callback.pre.length > 0 ){
        for( thisCall in callback.pre ){
            window[callback.pre[thisCall]]();
        }
    }

    // execute ajax request
	jq.ajax({
        url: method,
        type: 'post',
        data: jq('#' + formId).serialize(),
        dataType: 'json',
        success: function(objResp){
            showMessages( objResp );

            // if any errors show them in forms
            // clean up errors first
            jq('form').
            find('label.error').
            remove().
            end().
            find('.error').
            removeClass('error');

            // if we have errors show them
			if( typeof( objResp.errors ) != 'undefined' ){
				showErrors( objResp.errors, formId );
				delete objResp.errors;
			}else{
                // if any post callback function call it
                if( callback.post != null && callback.post.length > 0 ){
                    for( thisCall in callback.post ){
                          if( typeof( window[callback.post[thisCall]] ) != 'undefined' ){
                        	  window[callback.post[thisCall]]( objResp );
                          }
                    }
                }
            }

			// @TODO debug this
//            jq('form.checkChanges').
//            changes.
//            setInitialValues();
        }
    });

    return false;
}

/**
 * Add messages box to page
 */
function showMessages(objResp){
	// if any messages show them in messages box
    // clean up messages first

    jq('div#messages').remove();

	if( typeof( objResp.messages ) != 'undefined' ){
	    // original top distance
	    var top = 120;
	
	    // remove any messages box and add new one
	    jq('body').
	    find('div#messages').
	    remove().
	    end().
	    append(objResp.messages).
	    find('div.close a').
	    bind('click', function(){
	        jq(this).
	        parent().
	        parent().
	        remove();
	    });

        positionFixed( 'div#messages', top );
	}
    
    delete objResp.messages;
}

/**
 * Add messages box to page
 */
function showJSMessages(msg, type){
    if( typeof( type ) == 'undefined' || ( type != 'errors' && type != 'warnings' ) ){
        type = 'notices';
    }

	// if any messages show them in messages box
    // clean up messages first
    jq('div#messages').remove();
	if( typeof( msg ) != 'undefined' ){
	    // original top distance
	    var top = 118;

        var msgHtml = '<div id="messages">\n\
                            <ul>\n\
                                <li class="'
                       + type +
                                '">\n\
                                    <div></div>\n\ '
                       + msg +
                                '</li>\n\
                            </ul>\n\
                            <div class="close">\n\
                                <a href="javascript:void(null);" title="Close"></a>\n\
                            </div>\n\
                        </div>';

	    // remove any messages box and add new one
	    jq('body').
	    find('div#messages').
	    remove().
	    end().
	    append(msgHtml).
	    find('div.close a').
	    bind('click', function(){
	        jq(this).
	        parent().
	        parent().
	        remove();
	    });

        positionFixed( 'div#messages', top );
	}
}

/**
 * Show errors from php through ajax
 *
 * Expected format:
 * {"errors":[{"name":"field_name","message":"message to show next to field"}]}
 *
 * @param   object  errors  all errors returned from php
 * @param   string  form id that executed ajax
 * @return  void
 */
function showErrors( errors, formId ){
    // for each field with error
    for( field in errors ){
        jq('form#' + formId + ' [name="' + errors[field].name + '"]').
        removeClass('error').
        addClass('error').
        after('<label class="error" style="display:inline;">' + errors[field].message + '</label>');
    }

    jq('form#' + formId + ' :hidden').has('label.error').show();
}

/**
 * Change tab name when name modified with ajax
 * OBS: this is a callback function
 *
 * @return void
 */
function changeTabName(resp){
    if( typeof( resp.name ) != 'undefined' ){
        jq('div.tabs div.nav ul li.active a:first').
        html(resp.name).
        attr('title', resp.name).
        text(resp.name);
    }
}

/**
 * Callback function called after contacts update to change account buttons
 *
 * @return void
 */
function afterUpdateContact(resp){
    if(resp.account){
        // switch create/delete buttons for account
        jq('form[name="form' + resp.contact + '"]').
        find('a.create-account').
        hide().
        end().
        find('a.delete-account').
        show().
        end().
        find('fieldset').
        replaceWith(resp.account_view);
        
        executeSubmit();
        bindButtons();
    }
}

/**
 * Load contacts on adherent page
 *
 * @return void
 */
function loadContacts(resp){
	jq('div#contacts').
    append(resp.contacts);

    // refresh contacts actions
    refreshContactsActions();

    // hide new contact form and display button instead
	jq('div#new_contact').hide();
	jq('a.btn_new_contact').show();
	
	// transform buttons
	bindButtons();
	bindRadios();
    bindCheckboxes();
	
	// toggle contact details modules/adherent/onload.js
	//expandContactDetails();
}

/**
 * Change contact boxes title (called after delete contact or after order contacts)
 *
 * @return void
 */
function refreshContactBoxesTitle(){
    // change toolbar title with the new order
    jq('div#contacts div.form div.toolbar div.left').
    each(function(i){
        jq(this).
        html((i + 1) + '. ' + jq(this).parent().parent().find('input[name="contact[name]"]').val());
    });
}

/**
 * Show box for add new contact
 *
 * @return  void
 */
function addNewContact(){
	var box = jq('#new_contact');

	box.
    show().
	find('label.error').
    remove().
	end().
	find('input[type!=hidden]').
	removeClass('error').
	end().
	find('input[type!=hidden]').
	each(function(){
        if( jq(this).attr('type') != 'radio' ){
            jq(this).
            val('');
        }else if( jq(this).val() == 0 ){
            jq(this).attr('checked', 'checked');
        }
    });

    jq('a.btn_new_contact').
    hide();
}

/**
 * Add buttons in contacts toolbar
 *
 * @return void
 */
function refreshContactsButtons(){
    if(jq('div#contacts div.form').length > 1){
        var drag    = '<a href="javascript:void(null);" class="drag"></a>';
        var up      = '<a href="javascript:void(null);" class="up"></a>';
        var down    = '<a href="javascript:void(null);" class="down"></a>';
        var close   = '<a href="javascript:void(null);" class="close"></a>';

        // for each contact box
        jq('div#contacts div.form div.toolbar div.right').
        each(function(i){
            var myUp    = '';
            var myDown  = '';

            // do not show up arrow for the first contact
            if(i > 0){
                myUp = up;
            }

            // do not show down arrow for the last contact
            if(i < jq('div#contacts div.form div.toolbar div.right').length - 1){
                myDown = down;
            }

            // add buttons
            jq(this).
            html(drag + myUp + myDown + close);
        });
    }else{
        // if number of contacts <= 1 do not show any button
        jq('div#contacts div.form div.toolbar div.right').empty();
    }
}

/**
 * Move contact up one position
 *
 * @param   thisButton  object  jquery object with pressed button selector
 * @param   direction   boolean true: move up, false: move down
 * @return  void
 */
function bindClickOrderContacts(thisButton, direction){
    var thisBox = thisButton.parent().parent().parent();
    // change contacts order
    if(direction){  // move up
        thisBox.
        prev().
        before(thisBox);
    }else{          // move down
        thisBox.
        next().
        after(thisBox);
    }

    // refresh contacts actions
    refreshContactsActions();

    // order contacts into database
    ajaxOrderContacts();
}

/**
 * Refresh all actions on contact boxes
 * - refresh titles;
 * - refresh buttons;
 * - refresh drag and drop event;
 * - refresh delete event;
 * - validate
 *
 * @return void
 */
function refreshContactsActions(){
    // refresh boxes title
    refreshContactBoxesTitle();

    // refresh buttons
    refreshContactsButtons();

    // refresh order
    bindDragOrderContacts();

    // refresh delete contacts
    bindDeleteContact();

    // refresh number of contacts when add or delete
    refreshNumberOfContacts();

    // render buttons
    bindButtons();

    // validate again contacts
    refreshValidation();
}

/**
 * Refresh number of contacts when add or delete
 *
 * @return void
 */
function refreshNumberOfContacts(){
    jq('div.content div.title.contacts').
    html(jq('div#contacts div.form').length + ' Contacts');
}

/**
 * Refresh validation by calling validation functions based on controler and method name
 *
 * @return void
 */
function refreshValidation(){
    var queryString = window.location.href.substring( base_url.length );
    // get controller
    var controller  = queryString.substring( 0, queryString.indexOf( '/' ) );
    // get method
    var method      = queryString.substring( queryString.indexOf( '/' ) + 1, queryString.indexOf( '/', queryString.indexOf( '/' ) + 1 ) );

    // call validation generated function
    eval( 'validation_' + controller + '_' + method + '__();' );
}

/**
 * Empty fields after email replay sent
 *
 * @return void
 */
function emailReplaySent(){
    jq('#replay_subject').val('');
    //jq('#replay_from').val('');
    jq('#replay_body').val('');
    jq('#replay_to').val('');
}

/**
 * Refresh page
 *
 * @return void
 */
function refresh(){
    window.location = window.location;
}

function get_adherent_history_details(obj)
{
	eval( 'var obj = ' + obj + ';' );
	
	var test = 'div#details_'+obj.id;
	var url = base_url + 'adherent/history_details/';
	jq(test).toggle();
	if (jq(test).css('display') != 'none')
	jq.ajax({
        url: url,
        type: 'post',
        data: obj,
        success: function( resp ){
        	jq(test).
            html(resp)}});
}

function get_supplier_history_details(obj)
{
	eval( 'var obj = ' + obj + ';' );
	
	var test = 'div#details_'+obj.id;
	var url = base_url + 'supplier/history_details/';
	jq(test).toggle();
	if (jq(test).css('display') != 'none')
	jq.ajax({
        url: url,
        type: 'post',
        data: obj,
        success: function( resp ){
        	jq(test).
            html(resp)
        }
	});
}

function get_history_details( history_id, object_type, operation_type)
{
	var tr = 'tr#tr_details_'+history_id;
	var test = 'div#details_'+history_id;
	var url = base_url + 'history/history_details/'+history_id+'/'+object_type+'/'+operation_type;
	
	jq(tr).toggle();
	if (jq(tr).css('display') != 'none')
	jq.ajax({
        url: url,
        type: 'get',
        success: function( resp ){
        	jq(test).
            html(resp)}});
}

function undoHistory(obj, control)
{
	var url = base_url + control + '/undoHistory/'+obj;
	jq.ajax({
        url: url,
        type: 'get',
        success: function( resp ){
			var objResp = json_parse( resp );
			showMessages( objResp );
        }});
}

function undoHistoryDetail(obj, control)
{
	var url = base_url + control + '/undoHistory/_'+obj;
	jq.ajax({
        url: url,
        type: 'get',
        success: function( resp ){
			var objResp = json_parse( resp );
			showMessages( objResp );
        }});
}

/**
 * This function is called by "initCatTreeWithCallback" function as a callback
 *
 * @param   selected element rel
 * @return  void
 */
function callbackForCategoryTree( value ){
    // write rel to hidden to be passed to php through ajax
    jq('input[type="hidden"]#category_id').
    val(value);
}

function getCAForFacture()
{
	
	var date_end = Date.parse(jq('#datepickerCA2').val());
	
	var valid = true;
	
	if (parseInt(jq('#supplier_autocomplete_hidden').val()))
	{
		var supplier_id = parseInt(jq('#supplier_autocomplete_hidden').val());
		jq('#supplier_id_error').css('display','none');
	}
	else
	{
		jq('#supplier_id_error').css('display','inline');
		valid = false;
	}
	
	if (valid == true)
	{
		if (Date.parse(jq('#datepickerCA1').val()))
		{
			var date_start = Date.parse(jq('#datepickerCA1').val());
			jq('#date_start_error').css('display','none');
		}
		else
		{
			jq('#date_start_error').css('display','inline');
			valid = false;
		}
	}
	
	if (valid == true)
	{
		if (Date.parse(jq('#datepickerCA2').val()))
		{
			var date_end = Date.parse(jq('#datepickerCA2').val());
			jq('#date_end_error').css('display','none');
		}
		else
		{
			jq('#date_end_error').css('display','inline');
			valid = false;
		}
	}
	
	if (valid == true)
		{
		var div = 'div#caTable';
		var url = base_url + 'facture/ajax_get_CA/' + supplier_id + '/' + date_start + '/' + date_end;
		jq.ajax({
	        url: url,
	        type: 'post',	
	        success: function( resp ){
	        	jq(div).
	            html(resp)}});
		}
}

/**
 * Keep element fixed on screen on page scroll
 *
 * @access  public
 * @return  void
 */
function positionFixed( elementSelector, topDistance ){
    //BBATEA: setting it as a fixed position
    jq(elementSelector).
    css('position', 'fixed').
    css('right', '10px').
    css('top', topDistance + 'px');

    /*
    // scroll distance from top
    if( jq.browser.msie ){
        scrollY = document.body.scrollTop;
    }else{
        scrollY = window.scrollY;
    }

    // if page is scrolled down and the header is not visible move message box down
    var initTopDistance = topDistance;
    if( scrollY > topDistance ){
        initTopDistance = scrollY;
    }

    // set initial top
    jq(elementSelector).
    css('top', initTopDistance + 'px');

    // move box up/down on page scroll
    window.onscroll = function(){
        // scroll distance from top
        if(jq.browser.msie){
            scrollY = document.body.scrollTop;
        }else{
            scrollY = window.scrollY;
        }

        if( scrollY > topDistance ){
            jq(elementSelector).
            css('top', scrollY + 'px');
        }else{
            jq(elementSelector).
            css('top', topDistance + 'px')
        }
    }
    */
}


function get_cas_for_compare(resp)
{
    jq('div#cas_compare_div').html(resp.content);
    jq('div#page').append( resp.loyalty );
}

function show_hide_cas_compare_periods(period_type)
{
    if (period_type == 0)
    {
        jq('#years_periods').hide();
        jq('#trimestre_periods').hide();
    }
    else if (period_type == 1)
    {
        jq('#years_periods').show();
        jq('#trimestre_periods').hide();
    }
    else if (period_type == 2)
    {
        jq('#years_periods').hide();
        jq('#trimestre_periods').show();
    }
}

