/*
*= require jquery

*= require jquery_ujs

*= require ./note_files/ajquery.ui.widget
*= require ./note_files/jquery.fileupload

*= require ./shared/ace.js
*= require ./shared/mode-markdown.js
*= require ./shared/theme-textmate.js

*/

var editor = new Array();

function init_user_images(){
	
	$(".message_form").find(".images .user_image").click(function(){
		
		var src;
		src = $(this).data("src");
		
		r= $(this).closest(".message_form").find("textarea.markdown").data("id");
		editor[r].focus();
		editor[r].insert("\n\n![](<usrimg:"+src+">)\n\n");
		editor[r].focus();
			
		
			
			
		return false;
			
		
	});
}

$(document).ready(function(){
	
	$("textarea.markdown").each(function(){
		var r;
		var ed;
		
		
		
		r = Math.floor((Math.random()*1000)+1);
	
		$(this).data("id", r);


		$(this).attr("id", r+"-textarea");
		$(this).after('<div id="'+r+'-editor" class="ace_editor">bla</div>');
		
		
		
		
		editor[r] = ace.edit(r+"-editor");
		editor[r].setTheme("ace/theme/textmate");
		editor[r].getSession().setMode("ace/mode/markdown");
		
		editor[r].setPrintMarginColumn(0);
		
		editor[r].session.setUseWrapMode(true);
	
		
		
		
		
		
		editor[r].setHighlightActiveLine(false);
		
		editor[r].renderer.setShowGutter(false);
		editor[r].renderer.setShowPrintMargin(false);
		
		editor[r].setFontSize("14px");	
	
		

		var textarea = $('#'+r+'-textarea').hide();
		editor[r].getSession().setValue(textarea.val());
	
		editor[r].getSession().on('change', function(){

		textarea.val(editor[r].getSession().getValue());

	
		});
		
		
	});
	
	//upload
	
	drop = $('.user_images');
	
    $('.user_images .fileupload').fileupload({
		url: $(this).attr("action"),
        dropZone: drop,
		autoUpload: true,
		progressall: function (e, data) {
		        var progress = parseInt(data.loaded / data.total * 100, 10);
		        if(progress == 100){
				$(this).find('.progress').html('traitement en cours.');
				}
				else{
				$(this).find('.progress').html(progress + '% téléchargé.');}
		    },
		always: function (e, data) {
		       	$(this).find('.progress').html("");
		    },
				
		drop: function (e, data) {
			
			drop.css("background", "transparent");
			}
    });
		
		
	drop.bind('dragover', function (e) {
		$(this).css("background", "#B7DF63");
		    
	});
		
	drop.bind('dragleave', function (e) {
		$(this).css("background", "transparent");
		    
	});
	
	$(".user_images .add_files").live("click",function(){
		
		$(this).next('input').click();
		return false;
	});
	
	
});

