﻿/// <reference path="jquery-vsdoc.js"/>
/// <reference path="hfs.lib.js"/>

var _expertType = null;
var _expertTypeIdx = 0;
var _expertTypes = null;

//function pokeServer() {
//	setTimeout(function() {
//		$.pageMethod("Default.aspx/PokeServer", "{}", function(r) {
//			if (r.d == '')
//				alert("sesja wygasła");
//		});
//	}, 300000)
//}

$(function() {
	$('textarea.resizable:not(.processed),iframe[src*=fckeditor]:not(.processed)').TextAreaResizer();
});

function showConfirm(message, onConfirm, onQuit) {
	var d = $('<div id="dialogConfirm" title="Reedukacja.pl">' + message + '</div>').appendTo($("body:first"));
	d.dialog({ bgiframe: true, resizable: false, modal: true, overlay: { backgroundColor: '#84C225', opacity: 0.5 },
		buttons: {
			'Tak': function() {
				onConfirm.call(null);
				$(this).dialog('close');
			},
			'Nie': function() {
				if (onQuit != null) onQuit.call(null);
				$(this).dialog('close');
			}
		},
		close: function() {
			d.dialog('destroy').remove();
		}
	});
}

function initSiteMaster() {
	_expertType = $("span#expertType");
	_expertTypeIdx = 0;
	_expertTypes = ["Poradnia Pedagogiczna", "Gabinet EEG Biofeedback", "Psycholog", "Logopeda", "Pracownik naukowy"]; // przy zmianie tutaj zmienić też 44:|if (_expertTypeIdx == 5)

	correctLayout();
	$(document).resize(correctLayout);
	initExpertTypeFader();

	$("a#btnLogoff").click(function() {
		showConfirm("Na pewno chcesz się wylogować?", function() {
			$.pageMethod("Default.aspx/Logoff", "{}", function() {
				window.location.reload();
			});
		});
		return false;
	});
}

function correctLayout() {
	var co = $("div#contentOuter");
	var menu = co.find("div#menu");
	var ci = co.find("div#contentInner");
	var menu_h = menu.height();
	if (ci.height() < menu_h)
		ci.height(menu_h);
}

function initExpertTypeFader() {
	setTimeout(hideExpertType, 3000);
	
	function hideExpertType() {
		_expertType.fadeOut("slow", function() {
			_expertTypeIdx++;
			if (_expertTypeIdx == 5) _expertTypeIdx = 0;
			_expertType.text(_expertTypes[_expertTypeIdx]);
			showExpertType();
		});
	}
	function showExpertType() {
		_expertType.fadeIn("slow", function() {
			setTimeout(hideExpertType, 3000);
		});
	}
}

function showLoggedOnUserMenu() {
	$("div#userMenu").slideDown("fast", correctLayout);
}

function initSupporters() {
	var _s = $("div.support:first");
	var _head = _s.find("th:first");
	var _items = _s.find("td");
	_cascadeCallbackCt = 6;
	if (_head.length == 1) _cascadeCallbackCt = 5;

	if (_items.length <= _cascadeCallbackCt) {
		_items.show();
		setTimeout(function() { cascadeFadeIn(_items, 0); }, 1000);
	} else {
	_cascadeCallbackIdx = 0;
		setTimeout(function() { partialCascadeFadeInLoop(_items); }, 1000);
	}
}

var _cascadeCallback = null;
var _cascadeCallbackIdx = 0;
var _cascadeCallbackCt = 0;

function partialCascadeFadeInLoop(items) {
	var r = items.slice(_cascadeCallbackIdx, _cascadeCallbackIdx + _cascadeCallbackCt);
	_cascadeCallbackIdx += _cascadeCallbackCt;
	if ((_cascadeCallbackIdx) >= items.length) _cascadeCallbackIdx = 0;	
	//var t = 'ct:' + _cascadeCallbackCt + ' -> '; r.each(function() { t += $(this).attr("id") + ";"; }); window.status = t;
	r.show();
	_cascadeCallback = function() { partialCascadeFadeInLoop(items); };

	cascadeFadeIn(r, 0);
}

function cascadeFadeIn(items, idx) {
	$(items[idx++]).find("div:first").fadeIn(500, function() {
		if (items.length > idx)
			cascadeFadeIn(items, idx);
		else if (_cascadeCallback != null) {
			setTimeout(function() {
				var ct = 0;
				items.find("div:first").fadeOut(1000, function() {
					if (++ct == items.length) {

						items.hide();
						_cascadeCallback.call(null);
					}
				});
			}, 2000);
		}
	});
}

function initItemSurvey() {
	$("button#addQuestion").click(addQuestion);
	$("button#btnSectionAdd").click(addSection);
	$("button#btnSummaryAdd").click(addSummary);
}

function addQuestion() {
	$("input#currentItem").val("-1");

	var btn = $(this).enabled(false);

	var d = $("div#questionEdit").dialog({ title: "Nowe pytanie", bgiframe: true, modal: true, width: '450px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			btn.enabled(true);
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Dodaj");
	btns.find(".cancelButton:first").click(function() { d.dialog('close'); return false; });
	return false;
}
function editQuestion(btnId, id, type, index, section) {
	$("input#currentItem").val(id);
	var tr = $("img[rel=" + btnId + "]").parent().parent();

	$(_tbQuestionNew_Text).val(tr.find("td:eq(1)").text());
	$(_tbQuestionNew_TypeSingle).checked(type == 0);
	$(_tbQuestionNew_TypeMulti).checked(type == 1);
	$(_tbQuestionNew_TypeInput).checked(type == 2);
	$(_tbQuestionNew_Priority).val(index);

	var d = $("div#questionEdit").dialog({ title: "Edytuj pytanie", bgiframe: true, modal: true, width: '450px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			d.find(".cancelButton:first").unbind('click.dialog');
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Zapisz");
	btns.find(".cancelButton:first").bind('click.dialog', function() { d.dialog('close'); return false; });

	return false;
}

function addSection() {
	$("input#currentItem").val("-1");
	var d = $("div#sectionEdit").dialog({ title: "Nowa grupa pytań", bgiframe: true, modal: true, width: '500px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Dodaj");
	btns.find(".cancelButton:first").click(function() { d.dialog('close'); return false; });
	return false;
}
function editSection(btnId, id, qFrom, qTo) {
	$("input#currentItem").val(id);
	var tr = $("img[rel=" + btnId + "]").parent().parent();

	$(_tbSectionText).val(tr.find("td:first").text());
	$(_tbSectionQuestionFrom).val(qFrom);
	$(_tbSectionQuestionTo).val(qTo);

	var d = $("div#sectionEdit").dialog({ title: "Edytuj grupę pytań", bgiframe: true, modal: true, width: '500px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Zapisz");
	btns.find(".cancelButton:first").click(function() { d.dialog('close'); return false; });
	return false;
}

function addSummary() {
	$("input#currentItem").val("-1");
	var d = $("div#summaryEdit").dialog({ title: "Nowe podsumowanie", bgiframe: true, modal: true, width: '500px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Dodaj");
	btns.find(".cancelButton:first").click(function() { d.dialog('close'); return false; });
	return false;
}
function editSummary(btnId, id, limitTop, limitBottom) {
	$("input#currentItem").val(id);
	var tr = $("img[rel=" + btnId + "]").parent().parent();

	setFCKValue(_fckSummaryText, tr.next().find("td:first").text());
	$(_tbSummaryPointsFrom).val(limitTop);
	$(_tbSummaryPointsTo).val(limitBottom);

	var d = $("div#summaryEdit").dialog({ title: "Edytuj podsumowanie", bgiframe: true, modal: true, width: '450px', resizable: false,
		close: function() {
			d.find(".btns:first").removeClass("ui-dialog-buttonpane");
			d.find(".cancelButton:first").unbind('click.dialog');
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));
	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	btns.find("input:first").val("Zapisz");
	btns.find(".cancelButton:first").bind('click.dialog', function() { d.dialog('close'); return false; });

	return false;
}

function deleteConfirm(type, btnId, id) {
	$("input#currentItem").val(id);
	var d = $("div#confirmDelete").dialog({ bgiframe: true, modal: true, width: '450px', resizable: false,
		close: function() {
		d.find(".btns:first").removeClass("ui-dialog-buttonpane");
		d.find(".cancelButton:first").unbind('click.dialog');
			d.dialog('destroy');
		}
	});
	d.parent().appendTo($("form:first"));

	var btns = d.find(".btns:first").addClass("ui-dialog-buttonpane");
	var tr = $("img[rel=" + btnId + "]").parent().parent();
	var txt = '';
	if (type == '_q_') {
		btns.find(":not(.cancelButton)").hide();
		btns.find("._q_:first").show();
		txt = 'pytanie "' + tr.find("td:eq(1)").text() + '"';
	}
	else if (type == '_a_') {
		btns.find(":not(.cancelButton)").hide();
		btns.find("._a_:first").show();
		txt = 'odpowiedź "' + tr.find("td:first").text() + '"';
	}
	else if (type == '_g_') {
		btns.find(":not(.cancelButton)").hide();
		btns.find("._g_:first").show();
		txt = 'grupę "' + tr.find("td:first").text() + '"';
	}
	else if (type == '_s_') {
		btns.find(":not(.cancelButton)").hide();
		btns.find("._s_:first").show();
		txt = 'podsumowanie dla zakresu ' + tr.find("td:first").text();
	}
	btns.find(".cancelButton:first").bind('click.dialog', function() { d.dialog('close'); return false; });


	d.find("p:first").text('Na pewno chcesz usunąć ' + txt + '?');
	return false;
}

function getFCKValue(id) {
	return $(id + '_fckContent___Frame').contents().find('#xEditingArea iframe').contents().find('body').html();
}
function setFCKValue(id, value) {
	return $(id + '_fckContent___Frame').contents().find('#xEditingArea iframe').contents().find('body').html(value);
}

function createQuestionGroup(text, idxFrom, idxTo) {
	var qs = $("div#surveyQuestions div.question");

	var qFrom = qs.index(qs.filter("[rel=" + idxFrom + "]"));
	var qTo = qs.index(qs.filter("[rel=" + idxTo + "]"));

	if (qFrom > -1 && qTo > -1) {
		if (qFrom > qTo) {
			var q = qFrom;
			qFrom = qTo;
			qTo = q;
		}

		qs.slice(qFrom, qTo + 1).wrapAll("<fieldset></fieldset>").parent().prepend("<legend>" + text + "</legend>");
	}
}

function initItemArticlesEdit(id) {
	var _c = $("iframe#content");
	var t = $(".tabs").tabs({
		select: function(event, ui) {
			var p = $(ui.panel);
			if (ui.index == 1 && !p.hasClass('loaded')) {
				$("iframe#content").attr("src", "ContentEditor.aspx?id=" + id + "&t=" + (new Date()).getTime());
				p.addClass('loaded');
				var x = $("#content:not(.processed)");
				x.TextAreaResizer(function() {
					$("iframe#content").contents().find("iframe:first").height(x.height() - 33);
				});
			}
		}
	});
	if (id <= 0) {
		t.tabs('disable', 1);
	}
}

function ClientValidate_CheckBoxRequired_AcceptRegulations(sender, e) {
	e.IsValid = $(_chAcceptRegulations).is(':checked');
}
function ClientValidate_DropDownRequired_ArticleTypes(sender, e) {
	e.IsValid = ($(_ddlArticleType + " option:checked").length > 0);
}

function initCmsItemsArticlesTypes() {
	$("button#btnAddItem").click(function() {
		alert('a');
	});
	var _items = $("div#items").html(_progressbar);
	$.pageMethod("CmsItemsArticlesTypes.aspx/GetItems", "{}", function(r) {
		_items.html(r.d);
	});
}

function showSuccessfulNewSave(msg, redirectUrl) {
	$('<div title="Reedukacja.pl">' + msg + '</div>').appendTo($("body:first")).dialog({
		bgiframe: true, resizable: false, modal: true,
		buttons: {
			'OK': function() {
				$(this).dialog('close');
				window.location = redirectUrl;
			}
		}
	});
} 
function showSuccessfulSave(msg) {
	$('<div title="Reedukacja.pl">' + msg + '</div>').appendTo($("body:first")).dialog({
		bgiframe: true, resizable: false, modal: true,
		buttons: {
			'OK': function() {
				$(this).dialog('close');
			}
		}
	});
}

function showAdminOptionsTab() {
	$("li.tabs-admin:first").show();
}
function initContentEditor(id) {
	var overlay = protectEditor();

	var editor = new FCKeditor('editor');
	editor.BasePath = "fckeditor/";
	editor.ToolbarSet = 'MyDefault';
	editor.Height = '367px';
	editor.ReplaceTextarea();

	$("#btnOk").click(function() {
		var editor = FCKeditorAPI.GetInstance('editor');
		var attr = "{'id':'" + id + "','c':'" + editor.GetHTML(true) + "'}";
		$.pageMethod("ContentEditor.aspx/SaveContent", attr, function(r) {
		
			alert(r.d);
		});
		return false;
	});

	$("#btnRevert").click(loadContent);

	loadContent();

	function loadContent() {
		var api = null;
		try { api = FCKeditorAPI; } catch (x) { };
		if (api == null) {
			setTimeout(loadContent, 100);
			return;
		}
		var editor = api.GetInstance('editor');
		var attr = "{'id':'" + id + "'}";
		$.pageMethod("ContentEditor.aspx/LoadContent", attr, function(r) {
//			alert("treść pobrana");
//			try {
				editor.SetHTML(r.d);
//				alert("treść wstawiona");
//			} catch (ex) {
//				alert("Błąd:\r\n"+ex);
//			}
			$("div.editorOverlay:first").remove();
//			alert("overlay usunięty");
		});
		return false;
	}

	function protectEditor() {
		var b = $("body:first");
		return $('<div class="editorOverlay ui-widget-overlay"></div>').appendTo(b).css({ width: b.width(), height: b.height(), top: 0, left: 0, opacity: 0.15 });
	}
}

function initCmsItemsArticles() {
	$("#table").datatable({
		getHeadersFn: "CmsItemsArticles.aspx/GetHeaders",
		getDataFn: "CmsItemsArticles.aspx/GetData",
		setDataFn: "CmsItemsArticles.aspx/SetData",
		pageCapacity: 20,
		columnsResizable: true,
		loaded: processBody
	});

	function processBody() {
	}
}