/************************************************************************************************************
Ajax poller
Copyright (C) 2006  DTHMLGoodies.com, Alf Magne Kalleland

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.

Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com
	
************************************************************************************************************/	
function gallery(url){
	var parameter="top=50,left=50,toolbar=no,scrollbars=yes,status=no,resizable=yes,width=300,height=300";
	okno=window.open(url,"gallery",parameter);
}

function forumHelp(){
	var parameter="top=50,left=50,toolbar=no,scrollbars=yes,status=no,resizable=yes,width=600,height=400";
	okno=window.open("/app/forumhelp.html","help",parameter);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function Get_Cookie( name ) {
	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
		return null;
	}
	if ( start == -1 ) return null;

	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;

	return unescape( document.cookie.substring( len, end ) );
}

function resetBlogImg(){
	document.getElementById('blfimg').value = '';
	document.getElementById('blfimgpreview').src = '/styles/lightbox/blank.gif';
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function showBanner(pos,ban){
	var seen = readCookie('bp' + pos);
	if(seen) seen = seen + '~' + ban;
	else seen = ban;
	createCookie('bp' + pos,seen,1);
}
function resetBanner(pos){
	eraseCookie('bp' + pos);
}

/* menu */

var ajaxMenuRequest = "/app/menu.php";
var ajaxMenu = new Array();

var timeout	= 300;
var closetimer	= 0;
var actmenuitem	= 0;
var initmenu = 0;

function initMenu(){
	initmenu = 1;
}

function menuOn(node){

	if(initmenu != 1) return false;

	mcancelclosetime();
	var id = node.id.replace(/[^0-9]/g, '');

	if(actmenuitem) {
		actmenuitem.parentNode.firstChild.className = actmenuitem.parentNode.firstChild.className.replace(/menuactive/g, '');
		actmenuitem.style.visibility = 'hidden';
	}
	
	if(!ajaxMenu[id]) {
		initmenu = 0;
		var params = "?id=" + id;
		ajaxMenu[id] = new sack();
		ajaxMenu[id].requestFile = ajaxMenuRequest + params;
		ajaxMenu[id].onCompletion = function() { createMenu(id) };
		ajaxMenu[id].runAJAX();
	}
	else {
		//actmenuitem = document.getElementById('ajaxmenudiv' + id);
		if(ajaxMenu[id].response.length > 2) {
			actmenuitem = document.getElementById('ajaxmenudiv' + id);
			actmenuitem.style.visibility = 'visible';
		}
	}
}

function menuOff(){
	//alert(actmenuitem)
	//actmenuitem.parentNode.firstChild.className = actmenuitem.parentNode.firstChild.className.replace(/menuactive/g, '');
	if(actmenuitem) {
		actmenuitem.parentNode.firstChild.className = actmenuitem.parentNode.firstChild.className.replace(/menuactive/g, '');
		actmenuitem.style.visibility = 'hidden';
	}
}

function createMenu(id){
	var actmenu = document.getElementById("ajaxmenu"+id);
	actmenu.className += ' menuactive';

	menuPart = document.createElement("div");
	menuPart.id = 'ajaxmenudiv' + id;
	menuPart.className = 'ajaxmenu';
	menuPart.onmouseover = function() { mcancelclosetime() };
	menuPart.onmouseout = function() { mclosetime() };
	
	actmenuitem = menuPart

	if(ajaxMenu[id].response.length > 2) {
		menuPart.innerHTML = ajaxMenu[id].response;
		//actmenuitem = menuPart;
	}
	else menuPart.style.display = "none";
	actmenu.parentNode.appendChild(menuPart);
	initmenu = 1;
}

// go close timer
function mclosetime(){
	closetimer = window.setTimeout(menuOff, timeout);
}

// cancel close timer
function mcancelclosetime(){

	if(closetimer)	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

document.onclick = menuOff; 

/* poll */

var ajaxRequest = "/app/vote.php";
var poll;

function vote(node){
	var numId = node.id.replace(/[^0-9]/g, '');
	var parentDiv = node.parentNode.parentNode.parentNode.id;
	var params = "?" + numId + "/";
	poll = new sack();
	poll.requestFile = ajaxRequest + params;
	poll.onCompletion = function() { showVote(numId,parentDiv) };	// Specify function that will be executed after file has been found
	poll.runAJAX();	// Execute AJAX function
}

function showVote(id,parentDiv){
	document.getElementById(parentDiv).innerHTML = poll.response;
}

/* uzivatelia */

var ajaxUserRequest = "/app/ajax_user.php";
var ajaxUser;

function searchUser(){
	sitem = document.getElementById('sauser');
	if(sitem.value.length > 2){
		var params = "?" + sitem.value;
		ajaxUser = new sack();
		ajaxUser.requestFile = ajaxUserRequest + params;
		ajaxUser.onCompletion = function() { showUser() };	// Specify function that will be executed after file has been found
		ajaxUser.runAJAX();	// Execute AJAX function*/
	}
}

function keyuup(arg1) { 
	searchUser();
}

function setUser(node){
	if(document.getElementById("fmto").value) document.getElementById("fmto").value += ", " + node.innerHTML;
	else document.getElementById("fmto").value += node.innerHTML;
	showFilter()
}

function showUser(){
	if(ajaxUser.response) document.getElementById('iffres').innerHTML = ajaxUser.response;
}

/* auto */

/* okresy */

var ajaxOkresRequest = "/app/ajax_okres.php";
var ajaxOkres;

function changeOkresy(node){
	var params = "?" + node.value + "/";
	ajaxOkres = new sack();
	ajaxOkres.requestFile = ajaxOkresRequest + params;
	ajaxOkres.onCompletion = function() { showOkresy() };	// Specify function that will be executed after file has been found
	ajaxOkres.runAJAX();	// Execute AJAX function*/
}

function showOkresy(){
	if(ajaxOkres.response) document.getElementById('okres').innerHTML = '<select name="okres" class="sb3">' + ajaxOkres.response + '</select>';
}

/* auto */

var ajaxModelRequest = "/app/ajax_model.php";
var ajaxModel;

function changeModel(node){

	if(node.selectedIndex == 1){
		document.getElementById('new_znacka').style.display="block";
	}
	else {
		var params = "?" + node.value + "/";
		ajaxModel = new sack();
		ajaxModel.requestFile = ajaxModelRequest + params;
		ajaxModel.onCompletion = function() { showModel() };	// Specify function that will be executed after file has been found
		ajaxModel.runAJAX();	// Execute AJAX function*/
		checkAutoForm();
	}
}

function changeModelNo(node){

	var params = "?" + node.value + "~false";
	ajaxModel = new sack();
	ajaxModel.requestFile = ajaxModelRequest + params;
	ajaxModel.onCompletion = function() { showModelNo() };	// Specify function that will be executed after file has been found
	ajaxModel.runAJAX();	// Execute AJAX function*/
	checkAutoForm();
}

function showModel(){
	if(ajaxModel.response) document.getElementById('model').innerHTML = '<select name="model" class="ac_me" onchange="checkModel(this)">' + ajaxModel.response + '</select>*';
}

function showModelNo(){
	if(ajaxModel.response) document.getElementById('model').innerHTML = '<select name="model">' + ajaxModel.response + '</select>';
}

function checkModel(node){
	//alert(node.selectedIndex);
	if(node.selectedIndex == 1){
		document.getElementById('new_model').style.display="block";
	}
	else {
		checkAutoForm();
	}
}

function newZnacka(){
	
}
function newModel(){
	
}

function checkAutoForm(){
	//alert(document.getElementById('model').firstChild.selectedIndex);
	//alert(document.getElementById('znacka').firstChild.selectedIndex);

	//if(!document.getElementById('new_model').firstChild.value) document.getElementById('new_model').style.display = "none";
	if(document.getElementById('model').firstChild.selectedIndex != 1) document.getElementById('new_model').style.display = "none";
	//if(!document.getElementById('new_znacka').firstChild.value)  document.getElementById('new_znacka').style.display = "none";
	if(document.getElementById('model').firstChild.selectedIndex != 1) document.getElementById('new_znacka').style.display = "none";
}


/* chat */

var ajaxChatRequest = "/app/chat/room.php";
var ajaxChat;
var waittime=10000;
var fchat = 1;
var showUserBox = 1;

function refreshChat(roomId){
	var params = "?room=" + roomId + "&f=" + fchat;
	ajaxChat = new sack();
	ajaxChat.requestFile = ajaxChatRequest + params;
	ajaxChat.onCompletion = function() { showChat(roomId) };	// Specify function that will be executed after file has been found
	ajaxChat.runAJAX();	// Execute AJAX function*/
}

function showForum(button){
	if(fchat == 1) {
		fchat = 0;
		button.className = "chfor";
	}
	else if(fchat == 0) {
		fchat = 1;
		button.className = "chfor_on";
	}
	button.blur();
}

function showChat(roomId){
	if(ajaxChat.response) {
		document.getElementById('chatcontent').innerHTML = ajaxChat.response;
		document.getElementById('usersnum').innerHTML = document.getElementById("achatnum").innerHTML;
		document.getElementById('chatusers').innerHTML = document.getElementById("achatusers").innerHTML;
		intUpdate = setTimeout("refreshChat(" + roomId + ")", waittime);
	}
}

function showUsers(roomId){
	if(showUserBox){
		document.getElementById('chatcontent').style.width = "100%";
		document.getElementById('chatusers').style.display = "none";
		document.getElementById('chuserb').style.background = "#5a5a5a";
		showUserBox = 0;
	}
	else {
		document.getElementById('chatcontent').style.width = "80%";
		document.getElementById('chatusers').style.display = "block";
		document.getElementById('chuserb').style.background = "#696969";
		showUserBox = 1;
	}
	document.getElementById('chuserb').blur();
}

function chatMsgUser(node){
	var msg = document.getElementById('msg');
	msg.value = "/msg " + node.innerHTML + " ";
	msg.focus();
	node.blur();
}

function resetMsg(node){
	var msg = document.getElementById('msg');
	msg.value = "";
	node.blur();
}

function submitMsg(roomId){
	var msg = document.getElementById('msg');
	if(msg.value) {
		var params = "?room=" + roomId + "&act=add";
		ajaxChat = new sack();
		ajaxChat.method = "POST";
		ajaxChat.setVar("msg", msg.value);
		msg.value = "";
		ajaxChat.requestFile = ajaxChatRequest + params;
		ajaxChat.onCompletion = function() { refreshChat(roomId) };	// Specify function that will be executed after file has been found
		ajaxChat.runAJAX();
	}
}

function keyup(arg1,roomId) { 
	if (arg1 == 13) submitMsg(roomId); 
}

function popupChat(roomId){
	alert(roomId);
}


function hi(node){
	var a = node.parentNode.getElementsByTagName("a");
	
	for(var i = 0; i < a.length; i++) {
		
		if(a[i].getAttribute('rel') == "hi") {
			//alert(a[i].innerHTML);
			a[i].className = "ritemon";
		}
	}
}
function lo(node){
	var a = node.parentNode.getElementsByTagName("a");
	for(var i = 0; i < a.length; i++) {
		if(a[i].getAttribute('rel') == "hi") a[i].className = "";
	}
}

/* order menu */

function showOrder(){
	document.getElementById('oul').style.display = "block";
	orderOpen = true;
}
function hideOrder(){
	orderOpen = false;
	setTimeout('hideOrderMenu()',2000);
}
function onOrder(){
	orderOpen = true;
	//alert('on');
}
function offOrder(){
	orderOpen = false;
	setTimeout('hideOrderMenu()',2000);
}

function hideOrderMenu(){
	if(typeof(orderOpen) != 'undefined') {
		if(orderOpen) return false;
		else document.getElementById('oul').style.display = "none";
	}
	else document.getElementById('oul').style.display = "none";
}

/* filter */
function showFilter(){
	var iform = document.getElementById('ifform');
	var ititle = document.getElementById('iftitle').firstChild;
	if(iform.style.display == "block"){
		iform.style.display = "none";
		ititle.style.background = "url(/styles/asc.gif) 4px 12px no-repeat";
	}
	else {
		iform.style.display = "block";
		ititle.style.background = "url(/styles/desc.gif) 4px 12px no-repeat";
	}
}

/* popis */

function showPopis(id){
	var popisDiv = document.getElementById('popis' + id);
	var popisButton = document.getElementById('ib_popis' + id)
	if(popisDiv.style.display == "block"){
		popisDiv.style.display = "none";
		popisButton.style.background = "#737373 url(/styles/icons/pencil2.png) center center no-repeat";
	}
	else {
		popisDiv.style.display = "block";
		popisDiv.childNodes[0].focus();
		popisButton.style.background = "#333333 url(/styles/icons/pencil2.png) center center no-repeat";
	}
}

var checkflag = false;

function check(classn) {
	allNodes = document.getElementsByClassName(classn);
	if (!checkflag) {
		for(i = 0; i < allNodes.length; i++) {
			allNodes[i].checked = true;}
			checkflag = true;
		}
	else {
		for(i = 0; i < allNodes.length; i++) {
		allNodes[i].checked = false; }
		checkflag = false;
	}
}


/* userbox */
function showTitle(node) {
	node.firstChild.style.display = "block";
}
function hideTitle(node) {
	node.firstChild.style.display = "none";
}

/* checker */

if(document.images){
	preloadImages = new Array(
		'/styles/m_clankya.gif',
		'/styles/m_clankyh.gif',
		'/styles/m_firmya.gif',
		'/styles/m_firmyh.gif',
		'/styles/m_foruma.gif',
		'/styles/m_forumh.gif',
		'/styles/m_tuneria.gif',
		'/styles/m_tunerih.gif',
		'/styles/m_akciea.gif',
		'/styles/m_akcieh.gif',
		'/styles/emoticons/smile.gif',
		'/styles/emoticons/grin.gif',
		'/styles/emoticons/happy.gif',
		'/styles/emoticons/unhappy.gif'
	);
	var preload = new Image();
	for(a=0; a < preloadImages.length; ++a)
	{
		preload.src = preloadImages[a];
	}
}

var checkBan = 0;

function banconfirm(node,id){
	var bl = document.getElementById('bl'+id).value;
	var bt = document.getElementById('bt'+id).value;
	node.href = node.href.replace(/\.html/g, '-bl' + bl + '-bt' + bt + '\.html');
	return confirm('naozaj ban?');
}

function showban(id){
	if(checkBan == id) {
		document.getElementById('ban' + checkBan).style.display = 'none';
		checkBan = 0;
		return;
	}
	if(checkBan > 0) {
		document.getElementById('ban' + checkBan).style.display = 'none';
	}
	var ban = document.getElementById('ban' + id);
	ban.style.display = 'block';
	checkBan = id;
}

/* url spaces */

function urlSpaceRemove(obj)
{
	if(typeof obj.selectionStart == 'number')
	{
		// Mozilla, Opera, and other browsers
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;
		
		obj.value = obj.value.substring(0, start) + obj.value.substring(start, end).replace(/\ /g, '%20') + obj.value.substring(end, obj.value.length);
	}
	else if(document.selection)
	{
		// Internet Explorer
		// make sure it's the textarea's selection

		///alert('ssss');

		obj.focus();
		var range = document.selection.createRange();
		if(range.parentElement() != obj) return false;

	    if(typeof range.text == 'string')
	        document.selection.createRange().text = range.text.replace(/\ /g, '%20');
	}
	else
		obj.value += text;
		
}


function pasteIntercept(evt)
{
	//alert(evt);
}


/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code);
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}

