function myScope(func,obj,args) {
	return function() {
		obj.args = args;
		return func.apply(obj,arguments);
	};
};

Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

function byteconvert(bytes) {
	var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
	var e = Math.floor(Math.log(bytes)/Math.log(1024));
	if (bytes > 0) {
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
	}
	return bytes +" "+s[0];
}

function getXY(oElement,reference) {
	var iReturnValue = { 'x': 0, 'y': 0 };
	while ((oElement != null) && (oElement != reference)) {
		iReturnValue.y += oElement.offsetTop;
		iReturnValue.x += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;

}

function getY(oElement,reference) {
	var iReturnValue = 0;
	while( oElement != null) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getX(oElement,reference) {
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}
var myURL = function(url) {
	
	this.url = ''+url;

	this.params = {};

	this.initQuery = function (all, name, value) {
		if (name) {
			this.params[name] = value;
		}
		return this;
	}

	this.setQuery = function (name, value) {
		if (name) {
			this.params[name] = value;
		}
		return this;
	}

	this.getQueryValue = function (name) {
		return this.params[name];
	}

	this.init = function() {
		//log.info(this.url);
		var reg1 = /(https?:\/\/)?([a-zA-Z0-9_\-\.]+)?(:[0-9]+)?\/?([^\?#]*)?(\?([^#]*)?)?(#(.*))?/;
		var result = this.url.match(reg1);
		this.scheme = result[1];
		this.host = result[2];
		this.port = result[3];
		this.path = result[4];
		this.query = result[6];
		this.hash = result[8];

		if (this.query) {
			var reg2 = /(?:^|&)([^&=]*)=?([^&]*)/g;
			var result = this.query.match(reg2);

			this.query.replace(reg2, myScope(this.initQuery,this));
		}
	}

	this.getScheme = function() {
		return ((this.scheme)?(this.scheme):(''));
	}

	this.getHost = function() {
		return ((this.host)?(this.host):(''));
	}

	this.getPort = function() {
		return ((this.port)?(':'+this.port):(''));
	}

	this.getPortValue = function() {
		return ((this.port)?(this.port):(''));
	}

	this.getPath = function() {
		return ((this.path)?('/'+this.path):(''));
	}

	this.getPathValue = function() {
		return ((this.path)?(this.path):(''));
	}

	this.addToString = function(k,v) {
		if (v !== false) { 
			this.queryString = ((this.queryString)?(this.queryString+'&'):('?')) + k + '=' +v;
		}
	}

	this.getQuery = function() {
		this.queryString = '';
		$.each(this.params,myScope(this.addToString,this));
		return this.queryString;
	}

	this.getHash = function() {
		return ((this.hash)?('#'+this.hash):(''));
	}

	this.getHashValue = function() {
		return ((this.hash)?(this.hash):(''));
	}

	this.getURL = function() {
		return this.getScheme() + this.getHost() + this.getPort() + this.getPath() + this.getQuery() + this.getHash();
	}

	this.init();
}


var eventArray = function(source,name) {

	this.source = source;
	this.name = name;
	this.size = 0;
	this.events = new Array();

	this.add = function(callback) {
		this.size++;
		this.events.push(callback);
		return true;
	}

	this.call = function() {
		var result = true;
		var index = 0;
		while ((result) && (this.size > index)) { 
			result = this.events[index](arguments);
			index++;
		}
		return result;
	}

	return this;
};

var log = false;
var logger = function() {

	this.last = '';
	this.span = false;
	this.count = 0;
	this.log = false; 
	this.make_log = false;
	//this.make_log = true;

	this.init = function() {
		if ($('#log').length == 0 && this.make_log) {
			$('head').append('<link rel="stylesheet" type="text/css" href="/js/jquery.utils.css" media="screen" />');
			$('body').append('<ul id="log"></ul>');
			this.log = $('#log').hide();
			//this.log.hide();
			this.log.dblclick(myScope(this.hide,this));
			//$(document).keypress(myScope(this.show,this));
		}
	}

	this.show = function(e) {
		/*
		if (e.keyCode == 112) {
			this.log.toggle();
			return false;
		}
		*/
		return true;
	}

	this.hide = function(e) {
		this.log.hide();
		return false;
	}

	this.error = function(message) {
		this.message(message,'error');
	}

	this.infoObjectItem = function(name,value) {
		log.info('+'+name + ':' + value);
	}

	this.infoObject = function(obj) {
		log.info('Object:');
		$.each(obj,myScope(this.infoObjectItem,this));
		return true;
	}

	this.info = function(message) {
		this.message(message,'info');
	}

	this.obj = function(obj,message) {
		this.message('[' + obj.name + ']: '+message,'info');
	}

	this.message = function(message,type) {
		if (this.log) {
			this.log.show();
			if ((message == this.last) && (this.span)) {
				this.count += 1;
				this.span.html(this.count+'x');
			} else {
				this.count = 1;
				this.log.prepend('<li class="'+type+'">'+message+'<span></span></li>');
				this.span = $('li:first span',this.log);
			}
			this.last = message;
		}
	}

	this.init();
};

var log = false;
$(document).ready(function() {
	log = new logger();
});

$.fn.settings = function() {

	this.idValues = {};
	this.objValues = {};

	this.add = function(idName,values) {
		if (typeof this.idValues[idName] == 'undefined') {
			this.idValues[idName] = {};
		}
		$.extend(this.idValues[idName],values);
	}

	this.addByObject = function(objName,values) {
		if (typeof this.objValues[objName] == 'undefined') {
			this.objValues[objName] = {};
		}
		
		$.extend(this.objValues[objName],values);
	}

	this.get = function(name) {
		if (this.values[name]) {
			return this.values[name];
		} 
		return false;
	}

	this.get = function(name) {
		if (typeof this.idValues[name] != 'undefined') {
			return this.idValues[name];
		} 
		return false;
	}

	this.getByObject = function(name) {
		if (typeof this.objValues[name] != 'undefined') {
			return this.objValues[name];
		} 
		return false;
	}
};

var settings = new $.fn['settings']();

$.fn.openers = function() {

	this.windows = new Array();

	this.open = function(obj,url,w,h,s) {
		var newWindow = window.open(url, s+"_jswin", "toolbar=no,width="+w+",height="+h+",scrollbars=yes,resizable=yes");
		this.windows.push({ 'caller': obj, 'window': newWindow });
		return newWindow;
	}

	this.call = function(w,func,data) {
		for (var i = 0; i < this.windows.length; i++) {
			if (this.windows[i]['window'] == w) {
				return this.windows[i]['caller'][func](data);
			}
		}
		return false;
		
	}

	this.close = function(obj) {
		for (var i = 0; i < this.windows.length; i++) {
			if (this.windows[i]['caller'] == obj) {
				this.windows[i]['window'].close();
				this.windows.splice(i,1);
				return true;
			}
		}
		return false;
		
	}
}

var openers = new $.fn['openers']();

$.fn.collection = function(name) {

	this.name = name;
	this.layers = new Array();

	this.add = function(layer) {
		this.layers.push(layer);
	}

	this.getValue = function(func) {
		for (var i = 0; i < this.layers.length; i++) {
			if (this.layers[i][func]()) {
				return true;
			}
		}
		return false;
	}

	this.setOnlyMe = function(layer,name_on,name_off) {
		var result = false;
		for (var i = 0; i < this.layers.length; i++) {
			if (this.layers[i] == layer) {
				result = this.layers[i][name_on]();
			} else {
				this.layers[i][name_off]();
			}
		}
		return result;
	}

	this.set = function(name,args) {
		for (var i = 0; i < this.layers.length; i++) {
			this.layers[i][name](args);
		}
	}
}

var changeItems = new $.fn['collection']('changeItems');
var bubbles = new $.fn['collection']('bubbles');

$.fn.load = function(name, callback) {
	if (!$.fn[name]) {
	}

	return false;
};

var loader = function(name,makers) {
	this.name = name;
	this.makers = makers;
	this.done = false;
	this.data = new Array();
	this.index = 0;

	this.loadDone = function() {
		this.done = true;
		this.call();
	};

	this.add = function(data) {
		this.data.push(data);
		if (this.done) {
			this.call();
		}
	}

	this.init = function() {
		log.info('Loading: /js/jquery.'+name+'.js');
		if (typeof $.fn[name] == 'undefined') {
			$.getScript('/js/jquery.'+name+'.js', myScope(this.loadDone,this));
		} else {
			this.loadDone();
		}
	};

	this.call = function() {
		var item = false;
		while (item = this.data.pop()) {
			this.create(this.index,item);
			this.index++;
		}
	}

	this.create = function(index,item) {
		var id = $(item.object).attr('id');
		if (typeof item.settings == 'undefined') {
			item.settings = {};
		}

		jQuery.extend(item.settings, settings.get(id));
		jQuery.extend(item.settings, settings.getByObject(this.name));

		if ($.fn[name]) {
			log.info('Create obj: ('+index+')' +name );
			var newObj = new $.fn[name](item.object,index,item.settings);
			if (typeof item.callback == 'function') {
				item.callback(newObj);
			}
			return true;
		}
		return false;
	}
	this.init();

	return this;
}

var makers = function() {
	
	this.names = new Array();

	this.add = function(name,data) {
		if (typeof this.names[name] == 'undefined') {
			var load = new loader(name,this);
			this.names[name] = load;
		}
		this.names[name].add(data);
	}

	return this;
}

var makers = new makers();

$.fn.make = function(name,settings,callback) {

	if (this.length == 0) { return false; }
	$.each(this,function(index,object) { makers.add(name, { 'object': object, 'settings': settings, 'callback': callback } ); });
	
	return this;
};

function make_calls(calls,local_settings,obj) {
	if (calls) {
		for (var i = 0; i < calls.length; i++) {
			//log.message(calls[i].selector + ': '+$(calls[i].selector,obj).length);
			//log.message(calls[i].name);
			$(calls[i].selector,obj).make(calls[i].name,local_settings); 
		}
	}
}

jQuery.fn.swap = function() {

	var a = this[0];
	var b = this[1];


	if (a && b) {
		var parentNode = b.parentNode;

		if (a.nextSibling == b) {
			parentNode.replaceChild(a,b);
			parentNode.insertBefore(b,a);
		} else {
			parentNode.replaceChild(b,a);
			parentNode.insertBefore(a,b);
		}
	}
 
	return this;
};

function openWindow(url,w,h) {
        window.open(url, "_tree", "toolbar=no,width="+w+",height="+h+",scrollbars=yes,resizable=yes");
};

function send_content(root_id, o) {
                var div = document.getElementById(o);
                if (div) {
                parent.recieve_content(root_id,div.innerHTML);
                }
};


Array.prototype.sum = function() {
  return (! this.length) ? 0 : this.slice(1).sum() + ((typeof this[0] == 'number') ? this[0] : 0);
};

function questCountdown(draftId, questId) {
	this.xminutes = $('#questionaireStopwatch').find('span.min');
	this.xseconds = $('#questionaireStopwatch').find('span.sec');

	this.obj = $('#questionaireStopwatch');

	this.format = function(d,type) {
		switch (type) {
		case 'time': 
				return ((d.getHours() < 10)?('0'):('')) + d.getHours() + ':' + 
				((d.getMinutes() < 10)?('0'):('')) + d.getMinutes() + ':' + 
				((d.getSeconds() < 10)?('0'):('')) + d.getSeconds();
		break
		case 'date':
			return  ((d.getDate() < 10)?('0'):('')) + d.getDate() + '. ' + 
				((d.getMonth() < 9)?('0'):('')) + (d.getMonth()+1) + '. ' + 
				d.getFullYear();
		break
		case 'hour':
			return  d.getHours()-1;
		break
		case 'min':
			return ((d.getMinutes() < 10)?('0'):('')) + d.getMinutes()
		break
		case 'sec':
			return (d.getSeconds() < 10 ? ('0') : ('')) + d.getSeconds();
		break
		}
		return d;
	}

	this.update = function () {
		//čas načtený z db
		this.initialTime = this.haveRunNo == 0 ? (1000 * ((60 * Number($('.min',this.obj).html())) + (Number($('.sec',this.obj).html())))) : this.initialTime;
		this.startWith = (this.initialTime - (500 * this.haveRunNo));
		//this.haveRunNo == 0 ? alert(this.startWith) :false;
		var d = new Date(this.startWith);
		$('.hour',this.obj).html(this.format(d,'hour'));
		$('.min',	this.obj).html(this.format(d,'min'));
		$('.sec',	this.obj).html(this.format(d,'sec'));
		//odeslat při konci limitu
		if ( Number(this.format(d,'min')) == 0 && Number(this.format(d,'sec')) == 0 ) {
			$.ajax({
				type: 'POST',
				async: false,
				dataType: 'json',
				data: ({id: draftId }),
				url: '/ajax/countdown_end/',
				context: this,
				error: function (a,b,c) {}, 
				success: function (data) {
					if (data.result == true) {
						//alert('Konec časového limitu. Anketa bude vyhodnocena.');
						$.ajax({
							type: 'POST',
							async: false,
							dataType: 'json',
							data: ({id: questId }),
							url: '/ajax/quest_finish/',
							context: this,
							error: function (a,b,c) {}, 
							success: function (data) {
								if (data.result == true) {
									/*****************/
									this.movetop = $(document).scrollTop() + 240;
									this.docHeight = $(document).height();
									$('body').append('<div class="qOverlay"></div>').fadeIn(500);
									$('div.qOverlay').css('height', this.docHeight).click(function () {
										window.location.reload();       		
									});
									$('#container').append('<div class="messageQOk messageQOk"><a href="./" class="close">Zavřít</a><div class="top">Vypršel časový limit</div><div class="sub">Anketa bude vyhodnocena</div><div class="text"></div></div>').click(function () {
										window.location.reload();
									});
									$('.messageQOk').css('top', this.movetop +'px')
									$(window).scroll(function () {
										$('.messageQOk').css('top', (window.pageYOffset + 240 +'px'));
									});
									/*****************/
								}
								else {
									alert('Nepodařilo se ukončit anketu');
								}
							}
						});
					}
					else {
						alert('Nepodařilo se ukončit anketu');
					}
					clearInterval(this.xinterval);
					$(this.obj).remove()
				}
			});
		}
		this.haveRunNo++;
	}
	
	this.initialTime = 0;
	this.haveRunNo = 0;
	this.xinterval = setInterval(myScope(this.update,this),500);

}

$(document).ready(function() {
	
	$('div.panel div.window').make('panel');
	
	//ukončení
	$('#countDownForm').submit(function () {
		$.ajax({
			type: 'POST',
			async: false,
			dataType: 'json',
			data: ({id: $(this).data('ids') }),
			url: '/ajax/quest_finish/',
			context: this,
			error: function (a,b,c) {}, 
			success: function (data) {
				if (data.result == true) {
					//$(this).remove();
				}
				else {
					alert('Nepodařilo se ukončit anketu');
				}
			}
		});
	});
	
	//ukládání odpovědí
	$('#countDownForm input, #countDownForm textarea, #countDownForm select').change(function () {
		this.xdata = $(this).data('ids');
		$(this).before('<img style="vertical-align:middle; width: 24px;position:absolute;" src="/images/loading2.gif" id="loading'+ this.xdata.question +'" />');
		$.ajax({
			type: 'POST',
			async: true,
			dataType: 'json',
			data: ({question: this.xdata.question, questionaire: this.xdata.questionaire, answer: this.xdata.answer, value: $(this).val() }),
			url: '/ajax/questionaire_save/',
			context: this,
			error: function (a,b,c) {}, 
			success: function (data) {
				if (data.result == 1) {
					$('#loading'+ this.xdata.question).remove();
				}
				if (data.result == 0) {
					alert('Odpověď již nelze uložit');
					$.ajax({
						type: 'POST',
						async: false,
						dataType: 'json',
						data: ({id: this.xdata.questionaire }),
						url: '/ajax/quest_finish/',
						context: this,
						error: function (a,b,c) {}, 
						success: function (data) {
							if (data.result == true) {
								window.location.reload();
							}
							else {
								alert('Nepodařilo se ukončit anketu');
							}
						}
					});	
				}
				if (data.result == 2) {
					$('#loading'+ this.xdata.question).remove();
					$(this).removeAttr('checked');
					alert('Vyberte prosím odpověď znovu ')
				}
			}
		});
	});
	
	//odpočet ankety
	$('#initStopwatch').click(function () {
		$.ajax({
			type: 'POST',
			async: false,
			dataType: 'json',
			data: ({id: $(this).data('id') }),
			url: '/ajax/countdown_init/',
			context: this,
			error: function (a,b,c) {}, 
			success: function (data) {
				if (data.result == true) {
					$(this).remove();
					//questCountdown( $(this).data('id') );
				}
				else {
					alert('Nepodařilo se zahájit anketu');
				}
			}
		});
	});
	
	$('#questionaireStopwatch').each(function () {
		if ( $(this).hasClass('start') ) {
			questCountdown( $(this).data('id'),  $(this).data('quest') );
		}
	});

	//řazení tabulek textExtraction: 'complex',sortList: [[this.sorting,0]]	
	$('table.sortMe').tablesorter();
	
	//plovoucí banner
	$(window).scroll(function () {
		this.xtop = ''+ Number(Number(0) + Number(window.pageYOffset)) +'px';
		if (this.xtop == 'NaNpx') {
			this.xtop = Number(Number(300) + Number(document.documentElement.scrollTop)) + 'px';
		}
		$('#floatingBanner .banner').animate({top: this.xtop}, 0);		                
  });
  
  $('div.inItemsBanner').eq(0).find('.banner').css('margin-right', '18px');
	
	//archiv - date picker
	$('.topLigaFilter input[type=text]').datepicker({
		dateFormat: 'yy-mm-dd 12:00:00',
		showButtonPanel: true, 
		showOn: 'both',
		buttonImage: '/images/calendar.gif',
		buttonImageOnly: true
	});
	
	$('.niceTable tr:even').addClass('high');
	
	//soutěž
	$('.contestDetail a.go').click(function () {
  	
  	if ( $(this).hasClass('past') || $(this).hasClass('future') || $(this).hasClass('notLogged') ) {
			return false;
   	}
  	
	});
	
	//dotazník - dialog
	$('#questionaireDetailFormMessage').dialog({
		modal: false,
		title: 'Nevyplněné položky',
		autoOpen: false,
		resizable: false,
		buttons: {Ok: function() {$(this).dialog('close');}}
	});

	//dotazník - dialog 2
	$('#questionaireDetailFormMessage2').dialog({
		modal: false,
		title: 'Přihlášení',
		autoOpen: false,
		resizable: false,
		buttons: {Ok: function() {$(this).dialog('close');}}
	});
	
	$('input[type=submit]').click(function () {
		$('.messageQOk, div.qOverlay').fadeIn(500);
  });
	
	//dotazník - odeslání
	$('input[type=submit].alreadyFilled').attr('disabled', 'disabled');
	$('input[type=submit].alreadyFilled, input.thisIsPast').closest('form').find('textarea, input, select').attr('disabled', 'disabled');
	$('.questionaireDetail form').submit(function () {
		
		//nepřihlášen
		if ( $('input[type=submit]', this).hasClass('notLogged') ) {
    	$('#questionaireDetailFormMessage2').dialog('open');
    	return false;    	
		}
		
		//již vyplňoval
		if ( $('input[type=submit]', this).hasClass('alreadyFilled') ) {
    	return false;    	
		}
		
		//ukončeno
		if ( $('input[type=submit]', this).hasClass('past') ) {    	
			return false;  	
		}
		
		//budoucí
		if ( $('input[type=submit]', this).hasClass('future') ) {
    	return false;
		}
		
		var formInputs = 'questionaire_id='+ $('[name=questionaire_id]', this).attr('value');
		var formIncomplete = false;
		
  	$('.answers', this).each(function () {
  		if ( $('textarea', this).length == 0 && $('input[type=radio]:checked', this).length == 0 ) {
      	formIncomplete = true;
    	}
			$('input[type=radio]:checked', this).each(function () { 	  
				formInputs += '&'+ $(this).attr('name') +'='+ ($(this).attr('value'));
     	});
  	})
  	$('textarea', this).each(function () {
    	formInputs += '&'+ $(this).attr('name') +'='+ $(this).attr('value');
			if ( $(this).attr('value') == '' ) {
		  	formIncomplete = true;
		  }                 
  	})
  	
  	//neúplné
  	if (formIncomplete == true) {
    	$('#questionaireDetailFormMessage').dialog('open');
			return false; 
		}
  	
  	$.ajax({
			url: "/ajax/questionaire-submit/", 
			type: "POST", 
			context: this, 
			data: formInputs, 
			cache: false,
			dataType: "json",
			error: function (XMLHttpRequest, textStatus, errorThrown) {},
			success: function (data) { 	
				this.movetop = $(document).scrollTop() + 240;
				this.docHeight = $(document).height();
				
				$('body').append('<div class="qOverlay"></div>').fadeIn(500);
				$('div.qOverlay').css('height', this.docHeight).click(function () {
					$('.messageQOk, div.qOverlay').fadeOut(500);
					$('.questionaireDetail input, .questionaireDetail textarea').attr('disabled', 'disabled');       		
				});
				$('#container').append('<div class="messageQOk messageQ'+ data.status +'">'+ data.button +'<div class="top">'+ data.heading +'</div><div class="sub">'+ data.message +'</div><div class="text">'+ data.text +'</div></div>')
					.click(function () {});
				$('.messageQOk').css('top', this.movetop +'px')
				$(window).scroll(function () {
					$('.messageQOk').css('top', (window.pageYOffset + 240 +'px'));
				});
			}
		});
  	return false;
  });
  
  
	
	//změna hesla
	$('#registerForm .passwordPlaceHolder').click(function () {
 		$(this).hide();
 		$('.passChange').css('visibility', 'visible');
	});
	
	$('#registerForm input[name=password]').showPassword('#showPassword');	
	
	//ověření username - registrace
	$('#usernameCheck').click(function () {
  	
  	$('.checkResult').remove();
		$(this).after("<img src='/images/loading2.gif' class='checkResult' />");
  	
		$.ajax({
			url: '/ajax/username/',
			type: 'GET',
			async: false,
			context: this,
			dataType: 'json',			
			data: {"q": $('#registerForm input[name=username]').attr('value') },
			error: function (XMLHttpRequest, textStatus, errorThrown) {},
			success: function (data) {
				$('.checkResult').remove();
				$(this).after(' <span class="checkResult checkResult'+ data.status +'">'+ data.message +'</span>');
      }
		});
		return false; 
  });
	
	//searchInput
	$('.focusToggle').each(function () {
		
		$(this).focus( function() {		
			if ( $(this).attr('title') == $(this).attr('value') ) {
	    	$(this).attr('value', '');
	  	}		
		});
		
		$(this).blur( function() {		
			if ( $(this).attr('value') == '' ) {
		  	$(this).attr('value', $(this).attr('title') );
			}		
		});
		
		if ( $(this).attr('value') == '' ) {
	  	$(this).attr('value', $(this).attr('title') );
		}
	});	
			
	//gallery
	$('a[rel=gallery]').fancybox({
		'mouse-wheel': false,
		hideOnContentClick: true,
		'swing': false,
		'titleShow'	: false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'showNavArrows'	: false,
		'speedIn':400, 
		'speedOut':200 
	});

	//gallery group
	$('a[rel=galleryGroup]').fancybox({
		'mouse-wheel': true,
		'swing': true,
		'transitionIn':'elastic',
		'transitionOut':'elastic',
		'speedIn':400, 
		'speedOut':200, 
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) { 
			return '<span id="fancybox-title-over">'+ lang.fotogalerie_Image +' '+ (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}

	});
	
	//newsletter
	$('form.newsletterAjax').submit( function() {
		$(this).append('<div class="loading"><div></div></div>');
		$.ajax({
			url: "/newsletter_main/",
			type: "GET",
			async: false, 
			data: {email: $('input[name=email]', this).attr('value')},
			cache: true,
			dataType: 'html',
			success: myScope(function(data) {
				$('input[name=email]', this).attr('value', '');
				$('.loading', this).remove();				
				$(this).prepend('<div class="message">'+data+'</div>');
				$('.message', this).click(function(){$(this).fadeOut(200);});				
			}, this)
		});
		return false;
	});
	
	//externi odkaz
	$('a[rel=external]').attr('target', '_blank');
	
	//go back
	$('.takeMeBack').click(function () {
  	window.history.go(-1);                      
  });  
  
  //print
  $('.printMe').click(function () {
 		window.print();
    $('body').prepend( $('.printHead').remove() );
    $('.printHead').show();
	});
	
	//searchInput
	$('.focusToggle').each(function () {
		
		$(this).focus( function() {		
			if ( $(this).attr('title') == $(this).attr('value') ) {
	    	$(this).attr('value', '');
	  	}		
		});
		
		$(this).blur( function() {		
			if ( $(this).attr('value') == '' ) {
		  	$(this).attr('value', $(this).attr('title') );
			}		
		});
		
		if ( $(this).attr('value') == '' ) {
	  	$(this).attr('value', $(this).attr('title') );
		}
	});
	
	//čas
	$('.timeBox').bind('xxx', function () {
		this.format = function(d,type) {			
			switch (type) {
			case 'time': 
					return ((d.getHours() < 10)?('0'):('')) + d.getHours() + ':' + 
					((d.getMinutes() < 10)?('0'):('')) + d.getMinutes() + ':' + 
					((d.getSeconds() < 10)?('0'):('')) + d.getSeconds();
			break
			case 'date':
				return  ((d.getDate() < 10)?(''):('')) + d.getDate() + '.' + 
					((d.getMonth() < 9)?(''):('')) + (d.getMonth()+1) + '.' + 
					d.getFullYear();
			break
			}
			return d;
		}
		this.update = function () {
			var d = new Date();
			$('#head .timeBox .time').html(this.format(d,'time'));
			$('#head .timeBox .date').html(this.format(d,'date'));
		}
		
		setInterval(myScope(this.update,this),1000);		
		
	}).trigger('xxx');	

});

