var ic_tagInputField;

var ic_tagInputTO = null;
var ic_tag_noSubmit = false;

$(document).ready(function() {
    
    $('#tagFilter').keyup(function(event){
                    
	$('.tagWord').each(function() {
	    re = new RegExp($('#tagFilter').val());
	    m = re.exec($(this).text());

	    if(m != null)
	    {
			    $(this).parent('.tag').prevAll('h3').first().show();
			    $(this).parent('.tag').show();
	    }
	    else
	    {
			    $(this).parent('.tag').prev('h3').first().hide();
			    $(this).parent('.tag').hide();
	    }
	});
      })
    
    
    $('.tagging').keydown(function(event) {
        
        ic_tagInputField = $(this);
        if($(this).val().length < 2)
            return true;

        code = event.which;
        
        if(code == 13 || code == 37 || code == 38 || code == 39 || code == 40 )
        {
            
            event.preventDefault();
            manageTagListEvent(code);
            return true;
        }
        
        if(ic_tagInputTO != null)
            clearTimeout(ic_tagInputTO);
       
       if(code == 0)
            key = '%'
        else
            key = String.fromCharCode(event.which);
       // + String.fromCharCode(event.which)
        $.get('/ic_serve/tagSuggestions', { currentValue: escape($(this).val()) +key}, function(data) {
            if(data != '')
            {
                if($('#ic_tagsList').length > 0)
                    $('#ic_tagsList').replaceWith(data);
                else
                    ic_tagInputField.after(data);
                    
                
                if(ic_tagInputField.parents('form').first().hasClass('ic_fe'))
                {
                    $('#ic_tagsList').css('position', 'relative');
                     $('#ic_tagsList').css('top', '-16px');
                    $('#ic_tagsList').css('left', '205px');
                }
                else
                {
                    $('#ic_tagsList').css('top', ic_tagInputField.outerHeight() + ic_tagInputField.offset().top - 1 +'px');
                    $('#ic_tagsList').css('left', ic_tagInputField.offset().left+'px');
                }
            }
            else
            {
                if($('#ic_tagsList').length > 0)
                    $('#ic_tagsList').remove();
            }
        });
        
        return true;
    })

    $('.ic_tagChoice').live('mouseover', function(){
	
	$('.ic_tagChoice').removeClass('selected');
	$(this).addClass('selected');
    })

    
    $('.ic_tagChoice').live('click', function() {
        //alert($(this).text())
        $('.tagging').val($(this).text());
        $('.ic_tagChoice').removeClass('selected');
        $(this).addClass('selected');
        $('#ic_tagsList').slideUp(500);
        ic_tagInputTO = setTimeout("$('#ic_tagsList').remove();", 600)
    })
    
    
    $('.taggingForm').submit(function() {
	
	
        ic_tag_noSubmit = false;
	ic_tagInputField = $(this).children('.tagging');

	
        if($(this).children('.tagging').val().length < 3)
        {
//            $("#ic_tag_notif").html("<br /><div class=error_notification><p>Une erreur s&apos;est produite.</p> Les mots-cl&eacute;s doivent contenir au minimum 3 caract&egrave;res</div>").fadeIn('slow').animate({opacity: 1.0}, 5000).fadeOut('slow');
	    $.growlUI("Le mot-cl&eacute; doit comporter au minimum 3 lettres", "Veuillez choisir un autre mot-cl&eacute;", 3000, 'error');
            return false;
        }
	
	
        
        $.getJSON('/ic_serve/addTag', {table: $(this).children(".ic_tag_table").val(), rowId: $(this).children('.ic_tag_id').val(), tag: $(this).children('.tagging').val()}, function(data) {
	    
	    addTag(data);
	    
	    ic_tagInputField.val("");
	    
	    if(ic_tagInputField.parents('form').hasClass('ic_fe'))
	    {
		$('#ic_tagsList').slideUp(100).remove(); 
		$('#ic_blockUI_holder').hide();
		$('#ic_blockUI_msgPosition').replaceWith($('#ic_blockUI_holder')).hide()
		$('#ic_blockUI_holder').attr('id', '');
		//$.unblockUI();
	    }
        })
        
        return false;
        
    })
    
    $('.ic_tag_remove').live('click', function(){
        
        var ic_tagUrl = $(this).attr('href');
        $(this).parent('.currentTag').remove();;
        $(this).attr('href', '');
        $.get(ic_tagUrl);
        
        return false;
    })
    
    $(".topTag").draggable({ revert: true });
    
    $(".topTag").dblclick(function() {
	
	$.getJSON('/ic_serve/addTag', {table: $('#ic_tag_table').val(), rowId: $('#ic_tag_id').val(), tag: $(this).text()}, function(data) {
				    addTag(data)
                                })
    })
    
    $('#tagDrop').droppable({
                        accept: ".topTag",
                        hoverClass: 'ic_tag_hover',
			drop: function(event, ui) {
                            
				$.getJSON('/ic_serve/addTag', {table: $('#ic_tag_table').val(), rowId: $('#ic_tag_id').val(), tag: ui.draggable.text()}, function(data) {
				    addTag(data)
                                })
			}
		});
    
    
    $('.ic_tagIcon').click(function() {
        
	$(this).siblings('.ic_addTag').first().attr('id', 'ic_blockUI_holder');
        $.blockUI({ css: { cursor: 'default'}, message: $(this).siblings('.ic_addTag').first(), timeout: 0, showOverlay: false, baseZ: 150})
        $(this).after('<span id=ic_blockUI_msgPosition></span>');
        
    })
    
    $('.ic_tagClose').live('click', function() {
        $('#ic_tagsList').slideUp(100).remove(); 
        $.unblockUI();
	$('#ic_blockUI_holder').hide();
	$('#ic_blockUI_msgPosition').replaceWith($('#ic_blockUI_holder')).hide()
	$('#ic_blockUI_holder').attr('id', '');
        
    })
    
    
    $('.currentTag').live('mouseover mouseout', function(event) {
	if (event.type == 'mouseover') {
	  $(this).find('img').css('visibility', 'visible');
	} else {
	  $(this).find('img').css('visibility', 'hidden');
	}
      });
    
})




function manageTagListEvent(code, el)
{
    // Ugly next - prev trick is just to avoid going out of bounds without if'ing
    if(code == 40)
        $('#ic_tagsList .selected').next('.ic_tagChoice').addClass('selected').prev('.selected').removeClass('selected');
        
    if(code == 38)
        $('#ic_tagsList .selected').prev('.ic_tagChoice').addClass('selected').next('.selected').removeClass('selected');
    
    if(code == 39)
    {
        $('.tagging').val($('#ic_tagsList .selected').text())
        $('#ic_tagsList').slideUp(500).remove();    
    }
    
    if(code == 13)
    {
        if($('#ic_tagsList .selected').text().length > 0)
        {
            ic_tag_noSubmit = !ic_tag_noSubmit;
            $('.tagging').val($('#ic_tagsList .selected').text());
            $('#ic_tagsList').slideUp(500);
            if(!ic_tag_noSubmit)
                $('.taggingForm').submit();
        }
        else
            $('.taggingForm').submit();
    }
}


function addTag(data)
{
     if(data.id == 0)
    {
	$.growlUI("Mot-cl&eacute; en double", "&Ecirc;tes-vous sur que vous n&apos;avez pas d&eacute;j&agrave; ce mot-cl&eacute;?", 5000);
	return false;
    }
    else if(data.id == -1)
    {
	$.growlUI("Vous avez atteint votre limite de mots-cl&eacute;s", "Vous ne pouvez pas avoir plus de trois mots-cl&eacute;s en attante d&apos;approbation.", 5000);
	return false;
    }
    else if(data.id == -2)
    {
	$.growlUI("Ce mot-cl&eacute; ressemble &agrave; un autre", "Cet article contient d&eacute;j&agrave; ce mot-cl&eacute; ou un mot-cl&eacute; tr&egrave;s similaire.", 5000);
	return false;
    }
    else if(data.id == -3)
    {
	$.growlUI("Ce mot-cl&eacute; n'est pas accept&eacute;", "Seul les noms communs peuvent servir de mot-cl&eacute;. Les noms propres tels les lieux, OBV, sigles, r&eacute;gions, etc., sont r&eacute;serv&eacute;s pour la navigation par carte ou par fiche d'organisme.", 5000);
	return false;
    }
    else
    {
	if(data.approved == 1)
	{
	    $.growlUI("Votre mot-cl&eacute; a &eacute;t&eacute; ajout&eacute;", "", 5000);
	    $('#tagDrop').append("<div class=currentTag><a class='ic_tag_remove' href='/ic_serve/removeTag/?id="+data.id+"'><img class=tooltip src='/ressources/images/two/delete_small.gif' title='Supprimer ce mot-cl&eacute;' /></a> "+data.tag+"</div>")
	}
	else
	    $.growlUI("Approbation requise", "Un courriel a &eacute;t&eacute; envoy&eacute; &agrave; l&apos;auteur pour qu&apos;il approuve votre mot-cl&eacute;. Merci.", 5000);
	return true;
    }

}
