var $richtext_editor = new Array();
var $code_editor = new Array();


function remove_br(html){
	html = html.replace(/\n/gi, '')
	html = html.replace(/<br\s*[\/]?>/gi, '\n');
	return html;
}

function add_br(html){
	html = html.replace(/\n/gi, '<br />')
	return html;
}

function default_editor(){
	$('.show_default-editor').click(function(event){
	  event.preventDefault();
	  var $id = $(this).attr('data-id');
	  $('.textarea-panel li').each(function(){
	  	if ($(this).attr('data-id') == $id){
	  		$(this).removeClass('current');
	  	}
	  });
	  $(this).addClass('current');
		if ($richtext_editor[$(this).attr('data-id')] === true){
	  	tinymce.get($(this).attr('data-id')+'_textarea').remove();
	  	$richtext_editor[$(this).attr('data-id')] = false;
	  	if ($(this).attr('data-type') != 'plain') $('#'+$(this).attr('data-id')+'_textarea').val(remove_br($('#'+$(this).attr('data-id')+'_textarea').val()));
	  } else if ($code_editor[$(this).attr('data-id')] === true) {
			ace.edit($(this).attr('data-id')).destroy();
			$('#'+$(this).attr('data-id')).hide();
			$('#'+$(this).attr('data-id')+'_textarea').show();
			$code_editor[$(this).attr('data-id')] = false;
	  	if ($(this).attr('data-type') != 'plain') $('#'+$(this).attr('data-id')+'_textarea').val(remove_br($('#'+$(this).attr('data-id')+'_textarea').val()));
	  }
	});
}

function richtext_editor(){
  $('.show_richtext-editor').click(function(event){
  	event.preventDefault();
	  var $id = $(this).attr('data-id');
	  $('.textarea-panel li').each(function(){
	  	if ($(this).attr('data-id') == $id){
	  		$(this).removeClass('current');
	  	}
	  });
	  $(this).addClass('current');
	  if ($(this).attr('data-type') != 'plain') $('#'+$(this).attr('data-id')+'_textarea').val(add_br($('#'+$(this).attr('data-id')+'_textarea').val()));
  	if ($code_editor[$(this).attr('data-id')] === true) {
			ace.edit($(this).attr('data-id')).destroy();
			$('#'+$(this).attr('data-id')).hide();
			$('#'+$(this).attr('data-id')+'_textarea').show();
			$code_editor[$(this).attr('data-id')] = false;
		}
		if (!$richtext_editor[$(this).attr('data-id')]){
		  tinymce.init({
				selector: '#'+$(this).attr('data-id')+'_textarea',
				license_key: 'gpl',
				language: 'de',
				menubar: 'edit view insert format table',
				plugins: 'anchor autolink emoticons image link lists media searchreplace table visualblocks gallery files',
		    toolbar: 'undo redo | bold italic underline | forecolor backcolor fontsize | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | gallery files link',
		    tinycomments_mode: 'embedded',
		    min_height: 250,
		    height: $('#'+$(this).attr('data-id')+'_textarea').height()+200,
		    promotion: false,
		    branding: false,
		    paste_as_text: true,
		    entity_encoding: "raw",
		    //visualblocks_default_state: true,
		    formats: {
	        h1: { block: 'h1', wrapper: true },
	        h2: { block: 'h2', wrapper: true },
	        h3: { block: 'h3', wrapper: true },
	        h4: { block: 'h4', wrapper: true },
	        h5: { block: 'h5', wrapper: true },
	        h6: { block: 'h6', wrapper: true },
	        div: { block: 'div', wrapper: true },
	        p: { block: 'p', wrapper: true },
	        blockquote: { block: 'blockquote', wrapper: true },
	        pre: { block: 'pre', wrapper: true },
	        code: { block: 'code', wrapper: true }
		    },
				init_instance_callback: function (editor) {
		    	editor.addShortcut("ctrl+s", "Custom Ctrl+S", "custom_ctrl_s");
		    	editor.addCommand("custom_ctrl_s", function() {
						$("button[type='submit']").click();
						event.preventDefault();
		      });
		    },
			});
			$richtext_editor[$(this).attr('data-id')] = true;
		}
	});
}


function code_editor(){
  $('.show_code-editor').click(function(event){
  	event.preventDefault();
	  var $id = $(this).attr('data-id');
	  $('.textarea-panel li').each(function(){
	  	if ($(this).attr('data-id') == $id){
	  		$(this).removeClass('current');
	  	}
	  });
	  $(this).addClass('current');
	  if ($(this).attr('data-type') != 'plain') $('#'+$(this).attr('data-id')+'_textarea').val(add_br($('#'+$(this).attr('data-id')+'_textarea').val()));
		if ($richtext_editor[$(this).attr('data-id')] === true){
	  	tinymce.get($(this).attr('data-id')+'_textarea').remove();
	  	$richtext_editor[$(this).attr('data-id')] = false;
	  }
  	if (!$code_editor[$(this).attr('data-id')]) {
			var textarea = $('#'+$(this).attr('data-id')+'_textarea');
			textarea.hide();
			$('#'+$(this).attr('data-id')).show();
    	var langTools = ace.require("ace/ext/language_tools");
	  	var editor = ace.edit($(this).attr('data-id'));
	  	editor.getSession().setTabSize(2);
    	editor.setTheme('ace/theme/textmate');
    	editor.getSession().setMode('ace/mode/'+textarea.attr('data-mode'));
			editor.getSession().setValue(textarea.val());
			if (textarea.attr('data-autocomplete').length != 0){
		    editor.setOptions({
		        enableBasicAutocompletion: true,
		        enableSnippets: true,
		        enableLiveAutocompletion: true
		    });
		  }
		  editor.resize();
			editor.getSession().on('change', function(){
  			textarea.val(editor.getSession().getValue());
			});
			$code_editor[$(this).attr('data-id')] = true;
		}
		
	});
}


function insertAtCaret(areaId, text) {
  var txtarea = document.getElementById(areaId);
  if (!txtarea) {
    return;
  }

  var scrollPos = txtarea.scrollTop;
  var strPos = 0;
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
    "ff" : (document.selection ? "ie" : false));
  if (br == "ie") {
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart('character', -txtarea.value.length);
    strPos = range.text.length;
  } else if (br == "ff") {
    strPos = txtarea.selectionStart;
  }

  var front = (txtarea.value).substring(0, strPos);
  var back = (txtarea.value).substring(strPos, txtarea.value.length);
  txtarea.value = front + text + back;
  strPos = strPos + text.length;
  if (br == "ie") {
    txtarea.focus();
    var ieRange = document.selection.createRange();
    ieRange.moveStart('character', -txtarea.value.length);
    ieRange.moveStart('character', strPos);
    ieRange.moveEnd('character', 0);
    ieRange.select();
  } else if (br == "ff") {
    txtarea.selectionStart = strPos;
    txtarea.selectionEnd = strPos;
    txtarea.focus();
  }

  txtarea.scrollTop = scrollPos;
}
