/**
 * @todo
 *   - udělat s tímhle zbylým bordelem něco,
 *   - OŠETŘIT VŠECHNY AJAXOVÉ REQUESTY NA OPRÁVNĚNÍ.
 */

/**
 * @namespace globální namespace
 */
var Eleda = {};


/* Global function declarations */

var showCenterDialog = function(dialogSelector){
  var dialog = $(dialogSelector).detach();
  $('body').append(dialog);

  $(dialog).css('visibility', 'hidden').show();
  showOverlayBackground();

  var dialogWidth = dialog.width();
  var dialogHeight = dialog.height();
  var screenWidth = $(window).width();
  var screenHeight = $(window).height();

  dialog.hide().css({
	left: screenWidth / 2 - dialogWidth / 2,
	top: screenHeight / 2 - dialogHeight / 2,
	visibility: 'visible'
  }).show();

}
var showOverlayBackground = function(){
  var ovrl = $('#lean_overlay2');
  if(ovrl.length < 1){
	ovrl = $('<div id="lean_overlay2"> </div>');
	$('body').append(ovrl);
  }
  ovrl.css({opacity:0.5}).show();
}

/* Main initialization */

$(document).ready(function(){

	/* DatePicker */
	$( ".date" ).datepicker();

	/* spell checker for inputs */
	$('.withSpellchecker input').spellcheck({
		url: BASE_PATH + '/spellcheck.php'
	});


	/* Unknown script - looking for authorship */
	$('select[multiple]').css('min-width', '400px').chosen();

	/* Development code, try to remove on production */
	$(".todo").live("click", function(e){
		e.preventDefault();
		alert('Sorry, not implemented yet!');
	});

	$("a.ajax").live("click", function (event) {
		event.preventDefault();
		return false;
	});


	/* Tab navigation control */
	$('nav.tabs-nav').each(function(){
	  var nav = this;
	  var fragments = $(nav).parent().find('.tab-fragment');
	  var links = $(nav).find('a[href]');

	  /* TODO Push state to history */
	  $(links).click(function(e){
      	if($(this).attr('href') == '#')
        	e.preventDefault();
	  	try {
		    $(links).removeClass('active');
		    $(fragments).addClass('tab-hide');

		    $(this).addClass('active');
		    var choose = $(fragments).filter($(this).attr('href').replace('#', '.'));
		    $(choose).removeClass('tab-hide');
		} catch(err) {}
	  });

	});

	var z = 100;
	/* Popup navigation control */
	$('div.popupbox a.trigger').click(function(e){
	  e.preventDefault();
	  var $this = $(this);
	  var $cont = $this.parent();
	  var $box = $($this.siblings('.box')[0]);
	  $cont.css({'position': 'relative', 'z-index': z++});
	  $box.parents().css({'z-index': z});
	  $box.css({'z-index': z});
	  $box.removeClass('hidden');
	  $box.mouseleave(function(){
	  	$box.addClass('hidden');
	  	$box.css({'z-index': 1});
	  });
	});

	/* Tree */
	var $treeRoot = $('div.item-folder > ul > li');
	if($treeRoot.size()) {
		var $active = $treeRoot.find('li.active');

		var openLi = function(el, st) {
			if (st == 0)
				return;
			var $el = $(el);
			var $ico = $el.children('a').children('span.ico-arrow-right');
			var $uls = $el.children('ul');
			$uls.css({'display': 'block'});
			$ico.addClass('ico-arrow-down')
				.removeClass('ico-arrow-right');
			var $parentLi = $el.parent().closest('li');
			if($parentLi.size())	
				openLi($parentLi, st--);
		};

		var closeLi = function(el) {
			var $el = $(el);
			var $ico = $el.children('a').children('span.ico-arrow-down');
			var $uls = $el.children('ul');
			$uls.css({'display': 'none'});
			$ico.addClass('ico-arrow-right')
				.removeClass('ico-arrow-down');
		}

		// open
		$treeRoot.find('span.ico-arrow-right').live('click', function(e){
			e.preventDefault();
			openLi($(this).closest('li'));
		});
		// close
		$treeRoot.find('span.ico-arrow-down').live('click', function(e){
			e.preventDefault();
			closeLi($(this).closest('li'));
		});


		closeLi($treeRoot.find('li'));
		openLi($active, 50);
	}

	/* Modules list hover AJAX content */
	$('div.modules-list span.item').hover(function(){
	  var li = $(this).parent();
	  var previewBox = li.children('.preview-box');

	  if(previewBox.length < 1){
		previewBox = $('<div class="preview-box"> </div>');
		li.append(previewBox);
                previewBox.addClass('active');

		var moduleId = $(this).data('modulid');
		var urlparams = "type=getPreviewModule&modul_id=" + moduleId;
		var url = BASE_PATH + "/ajax-processing-request/?" + urlparams;
                               
		previewBox.load(url, function(){                                     
                    previewBox.css({visibility:'hidden'}).show();
                    var previewBoxHeight = previewBox.height();
                    previewBox.css({marginTop: - previewBoxHeight / 2});
                    // Active box handling, because response take some time and mouse could be somewhere else
                    if(previewBox.hasClass('active')){
                        previewBox.css({visibility: 'visible'});
                    } else {
                        previewBox.hide().css({visibility: 'visible'});
                    }
		});

	  } else {
		previewBox.addClass('active');
                previewBox.show();
	  }
	}, function(){
	  var li = $(this).parent();
	  var previewBox = li.children('.preview-box');
	  previewBox.hide();
          previewBox.removeClass('active');
	});
        
        // Little bit messy preview box close forcing, only for ensure all are hidden
        window.forcePreviewBoxesClose = setInterval(function(){
            $('div.modules-list .preview-box').not('.active').hide();
        }, 3000);



	/********************************** todos ************************************/

	$("a.denyRequest").live("click", function(){ $(".reply").show(); return false; });
	/*
	$("a#replyClose").live("click", function(){ $(".reply").hide(); return false; });
	$("a#addToClass").live("click", function(){ $("#myCourseForm").show(); return false;});
	*/
	$("a#showMessageForTeacherForm").live("click", function(){
		$("#messageForTeacherForm").show();
		$("#showMessageForTeacherForm").hide();
	});
	$("a#closeMessageForTeacherForm").live("click", function(){
		$("#messageForTeacherForm").hide();
		$("#showMessageForTeacherForm").show();
	});
});

/**
 *********************************** Moduly ***********************************
 * @namespace
 */
var Modules = {};

(function() {
	// submoduly
	Modules.Gap = {ID: 1};
	Modules.Bubble = {ID: 2};

	$(document).ready(function() {
		/**
		 * @type {string} ID editovaného modulu
		 */
		Modules.id = $('#frmcontentForm-id').val();
	});

	/**
	 * Eventy pro výpis gapů a bublin k modulu
	 */
	$('#tabs[name="gaps"]').live('click', function() {
		Modules.Gap.list();
	});
	$('#tabs[name="bubbles"]').live('click', function() {
		Modules.Bubble.list();
	});


	/**
	 * AJAXový požadavek s přímým vkládáním do DOMu
	 * @private
	 */
	var ajaxSendRequest = Modules.ajaxSendRequest = function(params, dom, success) {

	  	var method = params.method;

	  	if(method != 'POST')
		{
		  method = 'GET';
		}

		return $.ajax({
			type: method,
			url: BASE_PATH + "/ajax-processing-request/",
			data: params,
			dataType: "html",

			success: function(result) {
				if (typeof dom !== undefined && dom !== null) {
					$(dom).html(result);
					var yScroll=document.body.scrollTop;
					location.hash = dom;
					document.body.scrollTop=yScroll;
				}
				// podpora pro dodatečný callback
				if (typeof success === 'function') {
					success();
				}
			},
			error: function(e, xhr, settings, exception) {
				if (e.statusText != "abort" && e.status == 500) {
					alert("Requested function is not currently available! " + settings);
				}
			}
		});
	};

	/**
	 * Odebere daný element z TinyMCE editoru
	 * @private
	 */
	var stripElementOutOfEditor = function(elementId, type) {
		// bez obalení do divu jQuery zahodí obsah, který není v žádném tagu
		var frame = $('<div>' + tinyMCE.activeEditor.getContent() + '</div>');
		var className = (parseInt(type) === 1) ? 'gap' : 'bubble';
		var element = frame.find('span[id=' + elementId + '][class=' + className + ']');
		// stripneme tag gapfillu
		element.replaceWith(element.text());

		var content = frame.unwrap().html();

		var range = tinyMCE.activeEditor.selection.getRng();
		// vrátíme obsah TinyMCE
		tinyMCE.activeEditor.setContent(content);
		tinyMCE.activeEditor.selection.setRng(range);

		// posleme autosavem
		try {
			ajaxSendRequest({
					type: 'autosaveText',
					text: content,
					modul_id: $('#frmcontentForm-id').val(),
					method: 'POST'
			}, null, function() {
				Modules.Gap.list();
				Modules.Bubble.list();
			});
		} catch(err) {
			alert(err.message);
		}
	};



	/****************************** Gapfilly ******************************/

	/**
	 * Výpis gapů
	 */
	Modules.Gap.list = function() {
		ajaxSendRequest({
			type: 'gapfillListEditing',
			modul_id: Modules.id
		}, '#gaps');
	};

	/**
	 * Editace gapu - formulář
	 */
	Modules.Gap.edit = function(elementId) {
		ajaxSendRequest({
			type: 'gapfillEditForm',
			element_id: elementId
		}, '#gapfill_' + elementId);
		return false;
	};

	/**
	 * Smazání gapu
	 */
	Modules.Gap.remove = function(gapId, elementId) {
		ajaxSendRequest({
			type: 'deleteGapfill',
			element_id: gapId,
			modul_id: Modules.id
		}, '#gaps', function() {
			stripElementOutOfEditor(elementId, Modules.Gap.ID);
		});
		return false;
	};


	/**
	 * Uložení gapu - zpracování formuláře
	 */
	Modules.Gap.saveForm = function() {
		// data z formuláře
		/**
		 * Počet vygenerovaných levelů
		 * @type int
		 */
		var countLevels = $('#frmgapfillEditForm-count_levels').val();
		var weight = $('#frmgapfillEditForm-weight').val();
		var description = $('#frmgapfillEditForm-description').val();
		var extensionId = $('#frmgapfillEditForm-extension_id').val();
		var modulId = $('#frmgapfillEditForm-modul_id').val();

		var attributeLevels = [];
		for (var i = 0; i <= countLevels ; i++) {
			var checkbox = $('#frmgapfillEditForm-level_' + i + ':checked');

			if (checkbox.length > 0) {
				attributeLevels[i] = 'level_' + i;
			}
		}

		ajaxSendRequest({
			type: 'gapfillSaveForm',
			weight: weight,
			description: description,
			levels: attributeLevels.join(':'),
			extension_id: extensionId,
			modul_id: modulId
		}, null, function() {
			Modules.Gap.list();
		});
		return false;
	};


	/**
	 * Zavření formuláře - zrušení všech změn
	 */
	Modules.Gap.closeForm = function() {
		// opětovný výpis
		Modules.Gap.list();
		return false;
	};



	/****************************** Alternativy ******************************/

	Modules.Gap.Alternative = {};

	/**
	 * Editace alternativy gapu - formuláře
	 */
	Modules.Gap.Alternative.edit = function(extensionId, alternativeId) {
		ajaxSendRequest({
			type: 'alternativeAnswerForm',
			extension_id: extensionId,
			alternative_id: alternativeId
		}, '#alternativeForm_' + extensionId);
		return false;
	};

	/**
	 * Smazání alternativy gapu
	 */
	Modules.Gap.Alternative.remove = function(extensionId, alternativeId) {
		ajaxSendRequest({
			type: 'deleteAlternative',
			extension_id: extensionId,
			alternative_id: alternativeId
		}, '#alternativeForm_' + extensionId, function() {
		});

		return Modules.Gap.edit(extensionId);
	};


	/**
	 * Uložení alternativy gapu - zpracování formuláře
	 */
	Modules.Gap.Alternative.saveForm = function(extensionId) {
		// data z formuláře
		var text = $('#frmalternativeAnswerForm-text').val();
		var description = $('#frmalternativeAnswerForm-description').val();
		var mark = $('#frmalternativeAnswerForm-mark').val();
		var alternativeId = $('#frmalternativeAnswerForm-alternative_id').val();

		ajaxSendRequest({
			type: 'saveAlternative',
			text: text,
			description: description,
			mark: mark,
			extensionsId: extensionId,
			id: alternativeId
		}, null, function() {
			Modules.Gap.Alternative.closeForm(extensionId);
			Modules.Gap.edit(extensionId);
		});
		return false;
	};


	/**
	 * Zavření formuláře - zrušení všech změn
	 */
	Modules.Gap.Alternative.closeForm = function(extensionId) {
		$('#alternativeForm_' + extensionId).html('');
		return false;
	};



	/****************************** Opravy ******************************/

	Modules.Gap.Assess = {};

	Modules.Gap.Assess.saveForm = function(callback) {
		var extensionId = $('#gapfillAssessExtensionId').val();
		var alternative = $('#gapfillAssessAlternative').val();
		var comment = $('#gapfillAssessComment').val();
		var grade = parseFloat($('#gapfillAssessGrade').val());

		ajaxSendRequest({
			type: 'saveAlternative',
			text: alternative,
			description: comment,
			mark: grade,
			extensionsId: extensionId
		}, null, function() {
			if (typeof callback === 'function') {
				callback();
			}
		});
		return false;
	};



	/****************************** Bubliny ******************************/

	/**
	 * Výpis bublin
	 */
	Modules.Bubble.list = function() {
		ajaxSendRequest({
			type: 'bubbleListEditing',
			modul_id: Modules.id
		}, '#bubbles');
	};

	/**
	 * Editace bubliny - formulář
	 */
	Modules.Bubble.edit = function(elementId) {
		ajaxSendRequest({
			type: 'bubbleEditForm',
			element_id: elementId
		}, '#bubble_' + elementId);
		return false;
	};

	/**
	 * Smazání bubliny
	 */
	Modules.Bubble.remove = function(gapId, elementId) {
		ajaxSendRequest({
			type: 'deleteBubble',
			element_id: gapId,
			modul_id: Modules.id
		}, '#bubbles', function() {
			stripElementOutOfEditor(elementId, Modules.Bubble.ID);
		});
		return false;
	};

	/**
	 * Uložení bubliny - zpracování formuláře
	 */
	Modules.Bubble.saveForm = function() {
		// data z formuláře
		var description = $('#frmbubbleEditForm-description').val();
		var extensionId = $('#frmbubbleEditForm-extension_id').val();
		var modulId = $('#frmbubbleEditForm-modul_id').val();

		ajaxSendRequest({
			type: 'bubbleSaveForm',
			description: description,
			extension_id: extensionId,
			modul_id: modulId
		}, null, function() {
			Modules.Bubble.list();
		});
		return false;
	};

	/**
	 * Zavření formuláře - zrušení všech změn
	 */
	Modules.Bubble.closeForm = function() {
		// opětovný výpis
		Modules.Bubble.list();
		return false;
	};

})();


/**************** OPEN TASK CORRECTION ***************/
/** @author: Michal Kvasničák */

var OpenTask = {};

OpenTask.id = $('#id').val();


(function() {

	// definicia subclass
	OpenTask.Notes = {};
	OpenTask.Answer = {};

	OpenTask.Notes.container = '.box-notes .box-inner';

	$(".tabs-nav a[name='opentask-notes']").live('click', function() {
		OpenTask.Notes.list();
	});


	/**
	 * Zoznam poznámok od učiteľa v študentovej odpovedi
	 */
	OpenTask.Notes.parseResultForNotes = function()
	{
		$('.box-learn-more .box-notes').remove(); //vymaze poznamky
		$('.box-learn-more .box-inner').append('<div class="box-notes"></div>');

		var container = $('.box-modul .box-content'); //container s ohodnotenymi odpovedami
		var notes = container.find('span');

		//pridanie poznamok do panelu
		notes.each(function() {

			var data = {},
			template = '<p class="note-{{ type}}" data-id="{{ id}}" data-parent="{{ parent}}"><strong>{{ title}} {{ stars}}</strong>{{ note}}</p>';

			data = {
				'id': $(this).attr('id'),
				'type': $(this).data('type'),
				'stars': '',
				'note': $(this).data('note'),
				'title': $(this).data('title'),
				'valuation': $(this).data('valuation'),
				'parent': $(this).parent().attr('id')
			};

			if (data.valuation < 0) {
				//puntiky
				for (var i = 0; i > data.valuation; i--) {
					data.stars = data.stars + '<span class="ico ico-bull"></span>';
				}
			} else {
				for (var i = 0; i > data.valuation; i++) {
					data.stars = data.stars + '<span class="ico ico-star1"></span>';
				}
			}

			$.each(['id', 'parent', 'type', 'title', 'stars', 'note'], function (index, key) {
				template = template.replace(new RegExp('{{ ' + key + '}}'), data[key]);
			});

			$('.box-learn-more .box-inner .box-notes').append(template);
		});
	}


	/**
	 * Zoznam poznámok k OpenTasku od učiteľa
	 */
	OpenTask.Notes.list = function() {
		$('.box-notes .box-inner p').remove(); // vymazem stare poznamky

		for (var inst in tinymce.editors) {
			// v podmienke je inst.length > 1 pretoze to prechadzalo duplicitne, netusim preco
		    if (tinymce.editors[inst].getContent && inst.length > 1) {
				var html = '<div>' + tinymce.editors[inst].getContent() + '</div>';

				$(html).find('span').each(function() {
					var template = '<p class="note-{{ type}}"><strong>{{ title}} {{ stars}}</strong>{{ note}}</p>',
						data = {};

					data = {
						'type' : $(this).data('type'),
						'stars' : '',
						'note' : $(this).data('note'),
						'title' : $(this).data('title'),
						'valuation' : $(this).data('valuation')
					};

					if (data.valuation < 0) {
						//puntiky
						for (var i = 0; i > data.valuation; i--) {
							data.stars = data.stars + '<span class="ico ico-bull"></span>'
						}
					} else {
						for (var i = 0; i < data.valuation; i++) {
							data.stars = data.stars + '<span class="ico ico-star1"></span>';
						}
					}

					$.each(['type', 'title', 'stars', 'note'], function(index, key) {
						template = template.replace(new RegExp('{{ ' + key + '}}'), data[key]);
					});

					$('.box-notes .box-inner').append(template);
				});
		    }
		}
	};

	/**
	 * Odošle na server ohodnotené odpovede (alebo update)
	 */
	OpenTask.Answer.saveAnswers = function(url, student_id, finishedtask_id) {
		//poslem ajaxom odpovede a tie
		for (var i = 0; i < tinymce.editors.length; i++) {
			$.post(url, {
				'answer_id' : $('.box-content textarea:eq(' + i + ')').data('answerid'),
				'answer' : tinymce.editors[i].getContent(),
				'student_id' : student_id,
				'finishedtask_id' : finishedtask_id
			}, function(response) {
				if (response.status) {
					$('span.save-status').text('changes successfully saved');
				}
			}, 'json');
		}
	};

	/**
	 * Odošle na server alebo updatne hodnotenie
	 */
	OpenTask.Answer.saveEvaluation = function(url, note, evaluation, finishedtask_id, student_id) {
		$.post(url, {
			'student_id' : student_id,
			'finishedtask_id' : finishedtask_id,
			'note' : note,
			'evaluation' : evaluation
		}, function(response) {
			if (response.status) {
				$('.box-results').show();
				$('.box-results p.l').text(note);
				$('.box-results p.r').text('Grade: ' + evaluation.replace("%", "") + '%');
				$('span.save-status').text('changes successfully saved');
			}
		}, 'json');
	};

})();
