var resize_config = { 'handles':'all', transparent:true, 'minWidth':300, 'minHeight':300, 'resize':autoResizeBody };
var drag_config = { 'handle': '.modal_header' }
var offset = 150;
var offset2 = 75;

function getMiddleHorizontal( node )
{
     return ( $('body').innerWidth() - node.width() ) / 2;
}

function getMiddleVertical( node, offset )
{
     return ( screen.availHeight - node.height() ) / 2 + $(window).scrollTop() - offset;
}

function getBodyHeight( node, offset )
{
    return node.height() - offset;
}

function autoResizeBody()
{   
    $(this).find('.modal_body').height( $(this).height() - 42 );
}

function resizeBody( id )
{   
    $(id).find('.modal_body').height( $(id).height() - 42 );
}

function split()
{
 	var sidemenu = $('#sidemenu');
 	var toggle = $('#sidemenu_toggle');
 	
 	if ( sidemenu.hasClass( 'hidden' ) )
 	{
 		sidemenu.removeClass( 'hidden' );
 		toggle.toggleClass( 'sidemenu_expand' );
 	}
 	else
 	{
 		sidemenu.addClass( 'hidden' ); 
 		toggle.toggleClass( 'sidemenu_expand' ); 			
 	}
}

function refreshForm( url )
{
    showLoading();
    $('#form').load( url, $('#form1').serializeArray(), refreshFormComplete );
}

function refreshFormComplete()
{
    $('input.date-picker').datepicker();
    hideLoading();
}

function refreshPosition( id )
{
	$(id).css( 'left', getMiddleHorizontal( $(id) ) );
	$(id).css( 'top', getMiddleVertical( $(id), 0 ) );
}

function refreshModal( id, fct )
{	  
	$( id + ' .close' ).click( fct );
 	//$( id + ' .modal_header' ).mousedown( function(){ $(id).draggable('enable') } );
    //$( id + ' .modal_body' ).mousedown( function(){ $(id).draggable('disable') } );

    $(id).draggable( 'destroy' );
 	$(id).draggable( drag_config );
 	 
    $(id).resizable( 'destroy' );     	
    $(id).resizable( resize_config );
	resizeBody( id );		     
	    
	$(id).show();
	hideLoading();
}

function refreshHTMLArea( id )
{
	HTMLArea.onload = function() 
	{
	  	HTMLArea.replace( id );
	};
	HTMLArea.init();
}

function updateDelete( e, f )
{
	if ( e[ 'delete' ][1].checked )
	{
		e.action = 'javascript:if(confirmDelete()) ' + f + ';';
	}
	else
	{
		e.action = 'javascript:' + f + ';';
	}
}

function confirmDelete()
{	
	return confirm( 'Voulez-vous vraiment supprimer cet item ?' );
}

// SECTION : Loading

function showLoading()
{
    hideLoading();
    $('body').append( '<div id="loading">chargement en cours...</div>' );
 	$('#loading').css( 'top', $(window).scrollTop() + 5 );
}

function hideLoading()
{
    $('#loading').remove();
}

// SECTION : Highlight

function highlightOn()
{
	if ( $(this).hasClass( 'alt' ) ) 
	{
		$(this).removeClass( 'alt' );
		$(this).addClass( 'highlight_alt' ); 
	}
	else
	{
		$(this).addClass( 'highlight' ); 
	}	
}

function highlightOff()
{		
	if ( $(this).hasClass( 'highlight_alt' ) ) 
	{
		$(this).addClass( 'alt' ); 
	}
	
	$(this).removeClass( 'highlight' );
	$(this).removeClass( 'highlight_alt' );
}

// SECTION : Correction

function showCorrection()
{	
	showLoading();
	hideCorrection();
	
	$('body').prepend( '<div id="modal_correction" class="modal"></div>' );
	$('#modal_correction').hide();
	$('#modal_correction').load( '/default/correction/', loadCorrectionComplete );
}

function loadCorrectionComplete()
{
	refreshPosition( '#modal_correction' );
    refreshModal( '#modal_correction', hideCorrection );
}

function hideCorrection()
{
	$('#modal_correction').remove();
}

// SECTION : Online Help

function showOnlineHelp( id )
{
	showLoading();
	hideOnlineHelp();

	$('body').prepend( '<div id="modal_help" class="modal"></div>' );
	$('#modal_help').hide();
	$('#modal_help').load( '/help/index/id/' + id, loadOnlineHelpComplete );
}

function loadOnlineHelpComplete()
{
	refreshPosition( '#modal_help' );
    refreshModal( '#modal_help', hideOnlineHelp );
}

function hideOnlineHelp()
{
	$('#modal_help').remove();
}

// SECTION : Info

function showInfo( id )
{	
	showLoading();
	hideInfo();

    $('body').prepend( '<div id="modal_info" class="modal"></div>' );
	$('#modal_info').hide();	
	$('#modal_info').load( '/help/info/id/' + id, loadInfo );
}

function loadInfo()
{
	refreshPosition( '#modal_info' );
    refreshModal( '#modal_info', hideInfo );
}

function hideInfo()
{
	$('#modal_info').remove();
}

// BDC autocomplete

function setup_bdc_ac() {
	$('#bdc-input').autocomplete('/default/comment/bdc-search', {
		minChars: 2,
		width: 130
	}).result(function(e, item) {
		$.get('/default/comment/bdc-find', {id: item[1]}, function(r) {
			var textarea = $('#comment');
			textarea.val(textarea.val() + r + "\n\n");
		});
		$('#bdc-input').val('');
	});
}

// SECTION : Comment

function showComment( id, line, sheet )
{	
	showLoading();
	hideComment();
	
	$('body').prepend( '<div id="modal_comment" class="modal"></div>' );
	$('#modal_comment').hide();		
	$('#modal_comment').load( '/default/comment/index/id/' + id + '/line/' + line + '/sheet/' + sheet, loadComment );
}

function loadComment()
{
	setup_bdc_ac();
	refreshPosition( '#modal_comment' );
    refreshModal( '#modal_comment', hideComment );
 }

function hideComment()
{
	$('#modal_comment').remove();
}

function deleteComment(id) {
	if (confirm('Supprimer ce commentaire ?'))
	{
		$.getJSON('/default/comment/delete/id/' + id, function(data) {
			if (data.id)
			{
				$('#item-comment-'+data.id).slideUp('fast');
			}
			else
			{	
				alert('ERREUR: impossible de supprimer ce commentaire');
			}
		});
	}
}

// SECTION : Comment Add

function showCommentEdit( id, line, sheet )
{	
	showLoading();
	hideCommentEdit();
    
	$('body').prepend( '<div id="modal_comment" class="modal"></div>' );
	$('#modal_comment').hide();		
	$('#modal_comment').load( '/default/comment/edit/id/' + id + "/line/" + line + '/sheet/' + sheet, loadCommentEdit );
}

function loadCommentEdit()
{
	setup_bdc_ac();
	refreshPosition( '#modal_comment' );
    refreshModal( '#modal_comment', hideCommentEdit );			
}

function hideCommentEdit()
{
	$('#modal_comment').remove();
}

function submitCommentEdit(rcon)
{
	var $id = $('#form_comment input[name="id"]').val();
	var $line = $('#form_comment input[name="line"]').val();
	var $sheet = $('#form_comment input[name="sheet"]').val();
    $('#modal_comment').load( '/default/comment/submit', $('#form_comment').serializeArray(), function() { showComment($id, $line, $sheet); } );
    
    if (rcon) {
    	$('form#form1').data('lock', true);
    }
}

// SECTION : Confirmation

function showConfirmation( id, type, response )
{
	if ( response == 0 )
	{
        showLoading();
        hideConfirmation();

        $('body').prepend( '<div id="modal_confirmation" class="modal"></div>' );
        $('#modal_confirmation').hide();
        $('#modal_confirmation').load( '/default/correction/reject/id/' + id + '/type/' + type, loadConfirmation );
    }
    else
    {
        if ( confirm( 'Acceptez-vous cette correction ?' ) )
        {
            $.getJSON( '/default/correction/accept/id/' + id + '/type/' + type, submitConfirmationComplete );
        }
	}
}

function showConfirmationMultiple( id, type, line, response )
{
	if ( response == 0 )
	{
        showLoading();
        hideConfirmation();

        $('body').prepend( '<div id="modal_confirmation" class="modal"></div>' );
        $('#modal_confirmation').hide();
        $('#modal_confirmation').load( '/default/correction/reject-multiple/id/' + id + '/type/' + type + '/line/' + line, loadConfirmation );
    }
    else
    {
        if ( confirm( 'Acceptez-vous cette correction ?' ) )
        {
            $.getJSON( '/default/correction/accept-multiple/id/' + id + '/type/' + type + '/line/' + line, submitConfirmationComplete );
        }
	}
}

function loadConfirmation()
{
	refreshPosition( '#modal_confirmation' );
    refreshModal( '#modal_confirmation', hideConfirmation );
}

function hideConfirmation()
{
	$('#modal_confirmation').remove();
}

function submitConfirmation()
{
     $.getJSON( '/default/correction/submit-reject', $('#form_reject').serializeArray(), submitConfirmationComplete );
}

function submitConfirmationMultiple()
{
     $.getJSON( '/default/correction/submit-reject-multiple', $('#form_reject_multiple').serializeArray(), submitConfirmationComplete );
}

function submitConfirmationComplete( data )
{
    if ( data.response == 'reload' )
    {
        location.reload();
    }
    else if ( data.response == 'success' )
    {    
        $(data.id).html( '&nbsp;' );
        if (data.previous)
        {
        	$('#' + data.element_id).val(data.previous);
        	$('#' + data.element_id + '-' + data.previous).attr('checked', true);
        }
        hideConfirmation();
        location.reload();
    }
    else
    {
        $('#modal_confirmation').html( data.response );
        loadConfirmation();
    }
}

// SECTION : Wand

function showWand( type, line, reference, column )
{	
	showLoading();
	hideWand();
	
	$('body').prepend( '<div id="modal_wand" class="modal"></div>' );
	$('#modal_wand').hide();
	$('#modal_wand').load( '/default/wand/index/type/' + type + '/line/' + line + '/reference/' + reference + '/column/' + column, loadWandComplete );
}

function loadWandComplete()
{
	refreshPosition( '#modal_wand' );
	refreshModal( '#modal_wand', hideWand );
}

function hideWand()
{
	$('#modal_wand').remove();
}

function selectWand( item, item_value, label, label_value )
{
    $('#'+item).val( item_value );
    $('#'+label).val( label_value );

    hideWand();
}

function switchAccount( type, mode )
{
    var result;

    if ( mode == 1 )
    {
        result = confirm( 'Attention, vous allez perdre toutes les ' + type + ' de votre comptabilité annuelle !' )

        if ( result && confirm( 'Souhaitez-vous vraiment passer à une comptabilité mensuelle pour vos ' + type + ' ?' ) )
        {
            location = '/balance/mensuelle/reset-' + type;
        }
    }
    else
    {
        result = confirm( 'Attention, vous allez perdre toutes les ' + type + ' de votre comptabilité mensuelle !' )

        if ( result && confirm( 'Souhaitez-vous vraiment passer à une comptabilité annuelle pour vos ' + type + ' ?' ) )
        {
            location = '/balance/annuelle/reset-' + type;
        }
    }
}

// SECTION : Remove

function showRemove( type, form, item )
{
    if ( confirm( 'Confirmez-vous la suppression de cet élément ?' ) )
    {
        showLoading();
        $.getScript( '/default/line/remove/item/' + item + '/type/' + type + '/form/' + form, showRemoveComplete );
    }
}

function showRemoveComplete( data )
{
    hideLoading();

    if ( data != 'ko' )
    {
        $( '#item' + data + ', .item' + data ).remove();
    }
}

function form_setup_lock(form) {
	$(':input', form).change(function() { form.data('lock', true); });
	
	form.submit(function() { form.data('lock', false); });
	
	window.onbeforeunload = function (e) {
		var e = e || window.event;
		var msg = 'ATTENTION : Vous êtes sur le point de perdre les modifications apportées à ce formulaire.\nPour que vos changements soient enregistrés, vous devez restez sur la page en cours\net valider le formulaire à l\'aide du bouton en bas de page.';
		
		if (form.data('lock')) {

			// For IE and Firefox
			if (e) {
				e.returnValue = msg;
			}

			// For Safari
			return msg;
		}
	};
};

$.fn.hoverClass = function(c) {
	return this.each(function(){
		var e = $(this);
		e.hover(function(){e.addClass(c)},function(){e.removeClass(c)});
	});
}

$(function() {
	$(':input[readonly]').addClass('readonly');
	$('select[readonly], :radio[readonly], :checkbox[readonly]').attr('disabled', true).addClass('readonly');
	
	if (document.location.hash)
	{
		var el = $(document.location.hash);
		if (!el.length)
		{
			var name = document.location.hash.substr(1);
			el = $('a[name="'+name+'"]');
		}
		if (document.location.hash == '#soumettre')
		{
			$('#bouton_soumettre').effect('pulsate', { times: 1 }, 400);
		}
		else if (!el.parent().hasClass('print'))
		{
			el.closest('tr').effect('pulsate', { times: 1 }, 400);
		}
	}
});


