// Copyright 2005-2009 Enzon
// design by Enzon.cz [http://www.enzon.cz]

/**
 * RISE statický objekt, který se používá pro "zapouzdření"
 * všech definic a deklarací. V podmínce se nalezá pro
 * jistotu, protože může být definován ještě před svou
 * deklarací při použití slovníků, nebo konfigurací. 
 * @namespace
 * @name RISE
 * @static {Object} 
 *   
*/
if(typeof RISE != 'object'){
	var RISE = {NAME:"RISE",debug: true};
};

RISE.randomPass = function(number){
	var allowedLetter= new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0");
	var pass="";
	for(var i=0;i<number;i++){
		pass+=allowedLetter[Math.round(Math.random()*(allowedLetter.length-1))];
	}
	return pass;
}

RISE.console = function(msg){
	if(RISE.debug && typeof console != 'undefined') console.debug(msg);
}

RISE.preload = function(file)
{
	img = new Image();
	img.src = file;
}

RISE.confirm = function(text){
	if(!confirm(text)){
		return false;
	}
	return true;
}
RISE.removediak = function(text){
	sdiak="áäčďéěíĺľňóôőöŕšťúůűüýřžÁÄČĎÉĚÍĹĽŇÓÔŐÖŔŠŤÚŮŰÜÝŘŽ ";
	bdiak="aacdeeillnoooorstuuuuyrzAACDEEILLNOOOORSTUUUUYRZ-";
	tx="";
	for(p=0;p<text.length;p++){
		if (sdiak.indexOf(text.charAt(p))!=-1)
		tx+=bdiak.charAt(sdiak.indexOf(text.charAt(p)));
		else tx+=text.charAt(p);
	}
	return tx;
}

RISE.location = function(url){
	window.location = url;
}
RISE.intval = function(number,base){
	if(number==true) number=1;
	if(number==false) number=0;
	number = parseInt(number,base);
	if(isFinite(number)) return number;
	else return 0;
}

RISE.getCookie = function(c_name){
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
RISE.setCookie = function(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/";
}
RISE.gup = function( url,name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

/**
 * @class Obecná třída objektu
 * @constructor
 */
RISE.Object = SZN.ClassMaker.makeClass({
	NAME: "Object",
	VERSION: "1.0",
	CLASS: "class"
});
RISE.Object.prototype.Object = function() {
	
}
RISE.Object.prototype.$destructor = function(elm,event) {
	for (var p in this) { this[p] = null; }
}


/**
 * @class Obecná třída modulu
 * @param {string} mn Název modulu
 * @param {string} mp Cesta k modulu
 * @constructor
 */
RISE.Module = SZN.ClassMaker.makeClass({
	NAME: "Module",
	VERSION: "1.0",
	CLASS: "class",
	EXTEND: RISE.Object
});
RISE.Module.prototype.Module = function(mn,mp) {
	this.Object();
	var self = this;
	self.mn = mn;
	self.mp = mp;
	self.t = [];

	
	//-- mapovani callbacku ajaxu
	self.ajaxErrorCallback = function(XMLHttpRequest,textStatus,errorThrown){ self.ajaxError(this,XMLHttpRequest,textStatus,errorThrown); }
	self.ajaxSuccessCallback = function(response,textStatus){ self.ajaxSuccess(this,response,textStatus); }
	self.ajaxCompleteCallback = function(XMLHttpRequest,textStatus){ self.ajaxComplete(this,XMLHttpRequest,textStatus); }
	self.ajaxBeforeSendCallback = function(XMLHttpRequest){ self.ajaxBeforeSend(this,XMLHttpRequest); }
	self.ftSuccessCallback = function(response,textStatus){ self.ftSuccess(this,response,textStatus); }

	//-- mapovani zpracovani udalosti
	self.$destructorEvent = function(event){ self.$destructor(this,event); }
	self.ajaxSetAttributeEvent = function(event){ return self.ajaxSetAttribute(this,event); }
	
	//-- naveseni udalosti
	$(window).unload(self.$destructorEvent);
	$('.ajaxSetAttribute').live('change',self.ajaxSetAttributeEvent);
	
	//-- 
	//self.ft();
	
}
RISE.Module.prototype.ft = function(){
	
	var data = { action: "t" };
	var custom = { errorMsg: 'Nepovedlo se načíst texty administračního modulu.' };
	var options = { success: this.ftSuccessCallback, dataType: "json", cache: !RISE.debug };
	this.ajax(options,data,custom);
	
}
RISE.Module.prototype.ftSuccess = function(options,response,textStatus){
	this.t = response;
}

RISE.Module.prototype.ajax = function(options,data,custom){ 
	var _data = {
		t: this.mn,
		p: this.mp,
		location: 'ajax',
		action: 'undefined'
	};
	$.extend(_data, data);
	var _custom = {
		errorMsg: 'Request failed.'
	}
	$.extend(_custom, custom);
	var _options = {
		type: 'GET',
		url: './',
		cache: false,
		dataType: 'text',
		success: this.ajaxSuccessCallback,
		error: this.ajaxErrorCallback,
		beforeSend: this.ajaxBeforeSendCallback,
		complete: this.ajaxCompleteCallback,
		data: _data,
		custom: _custom
	}
	$.extend(_options, options);
	
	if(_options.async==false) return $.ajax(_options).responseText;
	else $.ajax(_options);
}
RISE.Module.prototype.ajaxError = function(options,XMLHttpRequest,textStatus,errorThrown){
	// alert(options.custom.errorMsg+' '+this.t.error+' '+XMLHttpRequest.status);
	layoutMessages.fetchMessages();
}
RISE.Module.prototype.ajaxSuccess = function(options,response,textStatus){ }
RISE.Module.prototype.ajaxComplete = function(options,XMLHttpRequest,textStatus){ }
RISE.Module.prototype.ajaxBeforeSend = function(options,XMLHttpRequest){ }

RISE.Module.prototype.ajaxSetAttribute = function(elm){
	var value = '';
	if(elm.nodeName=='INPUT' && elm.type=='text') value = elm.value;
	else if(elm.nodeName=='INPUT' && elm.type=='checkbox') value = RISE.intval(elm.checked);
	else if(elm.nodeName=='SELECT') value = elm.value;
	else value = elm.innerHTML;

	eval('var data = { action: "setAttribute",'+elm.name+':value };');
	//RISE.console(elm.name+'='+value);
	var custom = { errorMsg: 'Nepovedlo se nastavit atribut.' };
	var options = { };
	this.ajax(options,data,custom);
	return true;
	
}

/**
 * @class Třída pro vytváření záložek
 * @param {string} id ID prvku do kterého záložky vložit
 * @constructor
 */
RISE.Tabs = SZN.ClassMaker.makeClass({
	NAME: "Tabs",
	VERSION: "1.0",
	CLASS: "class"
});
RISE.Tabs.prototype.$constructor = function(id) {

	this.dom = SZN.gEl(id);
	if(!this.dom) return false;
	SZN.Dom.addClass(this.dom,'tabs');
	this.legends = SZN.cEl('div',this.dom.id+'Legends','legends');
	this.contents = SZN.cEl('div',this.dom.id+'Contents','contents');
	SZN.Dom.append(Array(this.dom,this.legends));
	SZN.Dom.append(Array(this.dom,this.contents));
	
	this.tabs = [];
	this.active = false;
	this.reloadTinyMce = false;
	this.timer = false;
	this.timeout = 10000;
	
	/*this.setTabs();*/
	
	this.eventsCache = [];
	this.eventsCache.push(SZN.Events.addListener(window,"unload",this,"$destructor",false,true));

}
RISE.Tabs.prototype.$destructor = function() {
	for (var i=0;i<this.eventsCache.length;i++) {
		SZN.Events.removeListener(this.eventsCache[i]);
	}
	for (var p in this) { this[p] = null; }
}
RISE.Tabs.prototype.addTab = function(legend,idContent,url){
	for(t=0;t<this.tabs.length;t++) if(this.tabs[t].content.id == idContent) return false;

	var tab = new RISE.Tab(this,legend,idContent,url);
	this.tabs.push(tab);
	SZN.Dom.append(Array(this.legends,tab.legend));
	SZN.Dom.append(Array(this.contents,tab.content));
	
	if(this.active==false) this.active = this.tabs[0];
	//this.setTabs();
	return true;
}
RISE.Tabs.prototype.setTabs = function(){
	var activeTab = RISE.getCookie(this.dom.id+'ActiveTab');
	var someActive = 0;
	if(this.timer) this.start(this.timeout);
	
	for(t=0;t<this.tabs.length;t++){
		if(this.tabs[t].content.id==activeTab){
			this.active = this.tabs[t];
			//$(this.tabs[t].content).fadeIn("slow");
			this.tabs[t].content.style.display = 'block';
			SZN.Dom.removeClass(this.tabs[t].legend,'deactive');
			this.tabs[t].fetch();
			someActive = 1;
		}else{
			//$('#'+this.tabs[t].content.id+' *').stop(true,true);
			//if(this.tabs[t].content.style.display == 'block') $(this.tabs[t].content).fadeOut("slow");
			//else this.tabs[t].content.style.display = 'none';
			//$(this.tabs[t].content).fadeOut("slow");
			this.tabs[t].content.style.display = 'none';
			SZN.Dom.addClass(this.tabs[t].legend,'deactive');
		}
	}
	if(!someActive) this.setActiveByKey(0);
}
RISE.Tabs.prototype.setActive = function(tab){
	this.active = tab;
	RISE.setCookie(this.dom.id+'ActiveTab',tab.content.id,365);
	this.setTabs();
	if(this.reloadTinyMce && tinyMCE) tinymce.each(tinyMCE.editors, function(e){ tinyMCE.execCommand('mceRemoveControl', false,e.id); tinyMCE.execCommand('mceAddControl', false,e.id); });
}
RISE.Tabs.prototype.setActiveByKey = function(key){
	if(this.tabs[key]) this.setActive(this.tabs[key]);
}
RISE.Tabs.prototype.setReloadTinyMce = function(value){
	this.reloadTinyMce = value;
}
RISE.Tabs.prototype.start = function(timeout){
	this.timeout = timeout;
	this.stop();
	var mThis = this;
	this.timer = setInterval(function(){ mThis.next(); },this.timeout);
}
RISE.Tabs.prototype.stop = function(){
	clearInterval(this.timer);
}
RISE.Tabs.prototype.next = function(){
	var key = 0;
	for(t=0;t<this.tabs.length;t++){
		if(this.tabs[t]==this.active){
			key = t+1;
			if(key>=this.tabs.length) key=0;
			break;
		}
	}
	this.setActiveByKey(key);
}
/**
 * @class Třída jedné záložky
 * @param {object} tabs objekt RISE.Tab
 * @param {string} legend Text na záložce
 * @param {string} idContent ID obsahu záložky
 * @constructor
 */
RISE.Tab = SZN.ClassMaker.makeClass({
	NAME: "Tab",
	VERSION: "1.0",
	CLASS: "class"
});
RISE.Tab.prototype.$constructor = function(tabs,legend,idContent,url) {

	this.tabs = tabs;
	this.url = false;
	this.fetched = false;
	if(url){
		this.content = SZN.cEl('div',idContent);
		this.url=url;
	}else{
		this.content = SZN.gEl(idContent);
	}
	
	if(!this.content) return false;
	
	this.legendTitle = legend;
	this.legend = SZN.cEl('span',this.content.id+'Legend','legend');
	//this.legend.href='#';
	this.legend.innerHTML = '<span class="title">'+this.legendTitle+'</span><span class="left"></span><span class="right"></span>';
	
	
	this.eventsCache = [];
	this.eventsCache.push(SZN.Events.addListener(window,"unload",this,"$destructor",false,true));
	
	this.eventsCache.push(SZN.Events.addListener(this.legend,"click",this,"activate",false,true));

}
RISE.Tab.prototype.$destructor = function() {
	for (var i=0;i<this.eventsCache.length;i++) {
		SZN.Events.removeListener(this.eventsCache[i]);
	}
	for (var p in this) { this[p] = null; }
}
RISE.Tab.prototype.activate = function(e,elm) {
	SZN.Events.cancelDef(e);
	elm.blur();
	this.fetch();
	this.tabs.setActive(this);
}
RISE.Tab.prototype.activateResp = function(txt, status) {
 	if(status == 200){
 		this.content.innerHTML = txt;
 		this.fetched = true;
 	}else{
 		this.content.innerHTML = 'Nepovedlo se načíst data.';
 	}	
}
RISE.Tab.prototype.fetch = function() {
	if(this.url && !this.fetched){
		var rq = new SZN.HTTPRequest();
		rq.setMethod("get");
		rq.setFormat("txt");
		rq.setMode("async");
		rq.send(this.url,this,'activateResp');	
		this.content.innerHTML = 'Načítám obsah záložky...';
		//if(typeof console != 'undefined') console.debug('test');
	}
}


RISE.loadImage = function(elm,src){
	var img = new Image();
	img.src = src;
	elm.parentNode.replaceChild(img, elm);
}
