if (typeof(DEBUG) == "undefined") {
	var DEBUG = false;
}




/********************************************************/
/*			Support functions - "design" style			*/
/********************************************************/
var isHrefClick=false;

// Show/hide Object
function ExpandColapse(id) {
  var obj=document.getElementById(id);
  obj.style.display=(obj.style.display=='none')?'':'none';
}

//Hideline the object
function Hideline(obj, hideline) {
  if (hideline){
	obj.className += " hidelined";
  }else{
	obj.className = obj.className.replace(" hidelined", " ");
  }
}

// Send confirmed (confirmed=1) request to opener window and close current window,
// if user confirm message
function ConfirmOpenerLink(linkObj, message) {
  var confirmed = confirm(message);
  if (confirmed){
	opener.location = linkObj.href+'&confirmed=1';
	window.close();
  }
  return false;
}

// Send confirmed (confirmed=1) request,
// if user confirm message
function ConfirmLink(linkObj, message) {
  var confirmed = confirm(message);
  if (confirmed){
	document.location = linkObj.href+'&confirmed=1';
  }
  return false;
}

// Open popup window
function PopupLink(link, resizable) {
  var _width = screen.availWidth, _height = screen.availHeight;
  var my_left = 0, my_top = 0;
  var my_width = 800;
  var my_height = 400;

  if (_width > my_width) my_left = (_width-my_width)/2;
  if (_height > my_height) my_top = (_height-my_height)/2;

  return !open(link, "", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+(resizable?"yes":"no")+",resizable="+(resizable?"yes":"no")+",copyhistory=no,top="+my_top+",left="+my_left+",width="+my_width+",height="+my_height);
}


// Set value to openner object
function setToOpener(objId, val, closeWindow, linkType) {
	if (typeof(closeWindow) == "undefined")
		closeWindow = true;
	
	// To FCK wysiwyg editor
	if(objId == "___editor___") {
		window.opener.SetUrl('/['+linkType+':'+val+']');
	} else {
		opener.document.getElementById(objId).value = val;
		if (opener.document.getElementById(objId).onchange)
			opener.setTimeout("document.getElementById('"+objId+"').onchange()", 1);
	}
	
	if (closeWindow)
		window.close();
	return false;
}


// Page slowly fade out
function fadeOut(timeout, step) {
	var old = document.body.style.MozOpacity;
	if (old == "") old = 1;
	
	if (old > 0.3) {
		document.body.style.MozOpacity = old-step;
		document.body.style.filter = "alpha(opacity=" + ((old-step)*100) + ")";
		setTimeout("fadeOut(2, " + step + ")", timeout*1000);
	}
}
function initFadeOut(after, length) {
	setTimeout("fadeOut(1.5, " + (2/length) + ")", (after-length)*1000);
}




/********************************************************/
/*					Support functions					*/
/********************************************************/
var checkingRules = new Array();

function checkForm(id){
  var msg = "Nesprávně vyplněný formulář!";
  var result = true;

  for(i in checkingRules[id]) {
  	if (typeof(checkingRules[id][i]) == "object") {
	var rule = checkingRules[id][i];
	if (rule.rule) {
	  eval("var r = (" + rule.rule + ");");
	  if (!r) {
		msg += "\n  - " + rule.description;
		result = false;
	  }
	} else {
	  rule.regex = rule.regex.replace(/\\/g, '\\\\');

	  if (document.getElementById(rule.element) == null) { 	  // radiobox
		  if (document.getElementById(rule.element+"_1") != null) {
			var i = 0;
			var el = null;
			var checked = false;
			while((el = document.getElementById(rule.element+"_" + ++i)) != null) {
			  if (el.checked) {
				checked = true;
				if (!el.value.match(new RegExp(rule.regex))) {
				  msg += "\n  - ";
				  if (rule.description != "")
					msg += rule.description;
				  else
					msg += "Chybná hodnota pro: " + document.getElementById(rule.element + "_label").innerHTML;
				  result = false;
				}
				break;
			  }
			}
			if (!checked && !"".match(new RegExp(rule.regex))) {
			  msg += "\n  - ";
			  if (rule.description != "")
				msg += rule.description;
			  else
				msg += "Chybná hodnota pro: " + document.getElementById(rule.element + "_label").innerHTML;
			  result = false;
			}
		  }
	  } else if (document.getElementById(rule.element).type == "checkbox") { // checkbox
	  	var el = document.getElementById(rule.element);
	  	if ((!el.checked || !el.value.match(new RegExp(rule.regex))) && !"".match(new RegExp(rule.regex))) {
		  msg += "\n  - ";
		  if (rule.description != "")
			msg += rule.description;
		  else
			msg += "Chybná hodnota pro: " + document.getElementById(rule.element + "_label").innerHTML;
		  result = false;
		}
	  } else if (document.getElementById(rule.element).type == "textarea") { // textarea
	  	var el = document.getElementById(rule.element);
		if (!document.getElementById(rule.element).value.replace(/\n/g, "").match(new RegExp(rule.regex))) {
		  msg += "\n  - ";
		  if (rule.description != "")
			msg += rule.description;
		  else
			msg += "Chybná hodnota pro: " + document.getElementById(rule.element + "_label").innerHTML;
		  result = false;
		}
	  } else { // other inputs
		if (!document.getElementById(rule.element).value.match(new RegExp(rule.regex))) {
		  msg += "\n  - ";
		  if (rule.description != "")
			msg += rule.description;
		  else
			msg += "Chybná hodnota pro: " + document.getElementById(rule.element + "_label").innerHTML;
		  result = false;
		}
	  }
	}
	}
  }
  if (!result)
	alert(msg);

  return result;
}

function makeHttpRequest(processReqChange, url) {
	req = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}

	if(req) {
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send("");
	}
	return req;
}




/********************************************************/
/*				CSS Class based functions				*/
/********************************************************/
// Adding some functions to "CSS marked" objects

function addHideline() {
  if (!document.getElementsByTagName) return false;
  var rows = document.getElementsByTagName("tr");
  for (var i=0; i < rows.length; i++) {
    if (rows[i].className.match("oddRow|evenRow")) {
      rows[i].onmouseover = function() { Hideline(this, true); }
      rows[i].onmouseout = function() { Hideline(this, false); }
    }
  }
}

function addIsHrefClick() {
  if (!document.getElementsByTagName) return false;
  var rows = document.getElementsByTagName("tr");
  for (var i=0; i < rows.length; i++) {
	if (rows[i].className.match("oddRow|evenRow")) {
	  var hrefs = rows[i].getElementsByTagName("a");
	  for (var ii=0; ii < hrefs.length; ii++) {
		if (!hrefs[ii].onclick) {
		  hrefs[ii].onclick = function() {isHrefClick=true;};
		} else {
		  hrefs[ii].onclickOriginal = hrefs[ii].onclick;
		  hrefs[ii].onclick = function(event) { isHrefClick=true; return this.onclickOriginal(event); };
		}
	  }

	  var forms = rows[i].getElementsByTagName("form");
	  for (var ii=0; ii < forms.length; ii++) {
		if (!forms[ii].onclick) {
		  forms[ii].onclick = function() {isHrefClick=true;};
		} else {
		  forms[ii].onclickOriginal = forms[ii].onclick;
		  forms[ii].onclick = function(event) { isHrefClick=true; return this.onclickOriginal(event); };
		}
	  }
	}
  }
}

function addConfirmLink() {
  if (!document.getElementsByTagName) return false;
  var hrefs = document.getElementsByTagName("a");
  for (var i=0; i < hrefs.length; i++) {
	if (hrefs[i].className.match("confirmLink")) {
	  var msg = ((hrefs[i].title!="")?hrefs[i].title:hrefs[i].text);
	  msg = msg.replace(/"/g, '\\"');
	  if (hrefs[i].className.match("openerLink")) {
		eval('hrefs[i].onclick = function() { return ConfirmOpenerLink(this, "' + msg + '?");};');
	   } else {
		eval('hrefs[i].onclick = function() { return ConfirmLink(this, "' + msg + '?");};');
	   }
	}
  }
}

function addPopupLink() {
  if (!document.getElementsByTagName) return false;
  var hrefs = document.getElementsByTagName("a");
  for (var i=0; i < hrefs.length; i++) {
	if (hrefs[i].className.match("popupWindow")) {
	  eval('hrefs[i].onclick = function() { return PopupLink("'+hrefs[i]+'"); }');
	} else if (hrefs[i].className.match("resizablePopupWindow")) {
	  eval('hrefs[i].onclick = function() { return PopupLink("'+hrefs[i]+'", true); }');
	}
  }
}

function addButtons() {
  if (!document.getElementsByTagName) return false;
  var hrefButtons = document.getElementsByTagName("a");
  for (var i=0; i < hrefButtons.length; i++) {
    if (hrefButtons[i].className.match("button")) {
      if (navigator.userAgent.indexOf('Opera') < 0) {
		  var button = document.createElement('button');
		  button.innerHTML = hrefButtons[i].innerHTML;
		  eval('button.onclick = function() {document.location = "' + hrefButtons[i].href + '";};');

		  hrefButtons[i].parentNode.replaceChild(button, hrefButtons[i]);
	  } else {
		  var form = document.createElement('form');
		  form.method = "post";
		  eval('form.action = "' + hrefButtons[i].href + '";');

		  var submit = document.createElement('input');
		  submit.type = "submit";
		  submit.value = hrefButtons[i].innerHTML;
		  form.appendChild(submit);

		  hrefButtons[i].parentNode.replaceChild(form, hrefButtons[i]);
	  }
	  i--;
    }
  }
}

function addLeftMenuColapsing() {
  if (!document.getElementById('left_menu')) return false;
  if (!document.getElementsByTagName) return false;
  var menuHeads = document.getElementById('left_menu').getElementsByTagName("h4");
  for (var i=0; i < menuHeads.length; i++) {
	var ul = menuHeads[i].nextSibling;
	while (!ul.tagName || !ul.tagName.match("UL")) {
	  ul = ul.nextSibling;
	}
	if (ul.className.match("collapsed|expanded")) {
	  menuHeads[i].onclick = function() {
		var obj = this.nextSibling;
		while (!obj.tagName || !obj.tagName.match("UL")) {
		  obj = obj.nextSibling;
		}
		obj.style.display=(obj.style.display=='none')?'':'none';
	  };

	  if (ul.className.match("collapsed")) {
		ul.style.display = 'none';
	  }
	}
  }
}

function addSortCollAnimation() {
  var TABLE_SORT_ASC = 'Řadit vzestupně';
  var TABLE_SORT_DESC = 'Řadit sestupně';
  
  if (!document.getElementsByTagName) return false;
  var headColls = document.getElementsByTagName("th");
  for (var i=0; i < headColls.length; i++) {
	if (headColls[i].className.match("sortableColl")) {
	  var imgObj = headColls[i].firstChild.lastChild;
	  if (imgObj.tagName && imgObj.tagName == "IMG") {
		if (headColls[i].firstChild.lastChild.src.match('desc')) {
		  headColls[i].firstChild.onmouseover = function() {
			this.lastChild.src = this.lastChild.src.replace('desc', 'asc');
			this.lastChild.alt = TABLE_SORT_ASC;
		  };
		} else if (headColls[i].firstChild.lastChild.src.match('asc')) {
		  headColls[i].firstChild.onmouseover = function() {
			this.lastChild.src = this.lastChild.src.replace('asc', 'desc');
			this.lastChild.alt = TABLE_SORT_DESC;
		  };
		}
		if (headColls[i].firstChild.lastChild.src.match('asc')) {
		  headColls[i].firstChild.onmouseout = function() {
			this.lastChild.src = this.lastChild.src.replace('desc', 'asc');
			this.lastChild.alt = TABLE_SORT_ASC;
		  };
		} else if (headColls[i].firstChild.lastChild.src.match('desc')) {
		  headColls[i].firstChild.onmouseout = function() {
			this.lastChild.src = this.lastChild.src.replace('asc', 'desc');
			this.lastChild.alt = TABLE_SORT_DESC;
		  };
		}
		headColls[i].firstChild.onclick = function() {
		  this.onmouseout = null;
		  this.onmouseover = null;
		};
	  }
	}
  }
}

function addJsSelectBox() {
	if (!document.getElementsByTagName) return false;
	var divs = document.getElementsByTagName("div");
	for (var i=0; i < divs.length; i++) {
		if (divs[i].className.match("jsSelectBox")) {
			var select = document.createElement("select");
			select.onchange = function() {
				document.location = this.value;
			};
			var bs = divs[i].getElementsByTagName("b");
			var option = document.createElement("option");
			option.innerHTML = bs[0].innerHTML;
			option.style.fontWeight = "bold";
			select.appendChild(option);

			var hrefs = divs[i].getElementsByTagName("a");
			for (var ii=0; ii < hrefs.length; ii++) {
				var option = document.createElement("option");
				option.innerHTML = hrefs[ii].innerHTML;
				option.value = hrefs[ii].href;
				select.appendChild(option);
			}
			
			divs[i].innerHTML = "";
			divs[i].appendChild(select);
		}
	}
}

function addHTMLEditor() {
	if (!document.getElementsByTagName) return false;
	var textareas = document.getElementsByTagName("textarea");
	for (var i=0; i < textareas.length; i++) {
		if (textareas[i].className.match("HTMLEditor")) {
			var textArea = textareas[i];

			var sBasePath = ADMIN_URL + 'js/fck/';
			var oFCKeditor = new FCKeditor(textArea.id, textArea.style.width, textArea.style.height);
			oFCKeditor.BasePath     = sBasePath;
			oFCKeditor.Config['CustomConfigurationsPath'] = sBasePath + 'config_general.js';
			if (navigator.userAgent.indexOf('Opera') < 0) {
				oFCKeditor.ToolbarSet = 'Default';
			}
			// Drop down menus are not suitable with Opera
			else {
				oFCKeditor.ToolbarSet = 'Opera';
			}
			oFCKeditor.ReplaceTextarea() ;
		}
	}
}

function addPriceInputCheck() {
	if (!document.getElementsByTagName) return false;
	var rows = document.getElementsByTagName("input");
	for (var i=0; i < rows.length; i++) {
		if (rows[i].className.match("price")) {
			rows[i].value = rows[i].value.replace('.', ',');
			if (!rows[i].onkeyup) {
				rows[i].onkeyup = function(e) {
					if (e.keyCode == 190) // desetina tecka se prevede na carku
						this.value = this.value.substr(0, this.value.length-1) + ',';
					if (!this.value.match("^([0-9]+(,[0-9]{0,2}){0,1}){0,1}$"))
						this.value = this.value.substr(0, this.value.length-1);
				};
			} else {
				rows[i].onkeyupOriginal = rows[i].onkeyup;
				rows[i].onkeyup = function(e) {
					if (e.keyCode == 190) // desetina tecka se prevede na carku
						this.value = this.value.substr(0, this.value.length-1) + ',';
					if (!this.value.match("^([0-9]+(,[0-9]{0,2}){0,1}){0,1}$"))
						this.value = this.value.substr(0, this.value.length-1);

					this.onkeyupOriginal(e);
				};
			}
		}
	}
}



/********************************************************/
/*	Call CSS Class based functions after window on load	*/
/********************************************************/
window.onload = function() {
	if (DEBUG) {
		initPHPdebugWindow();
	}
	addHideline();
	addConfirmLink();
	addPopupLink();
	addIsHrefClick();
	addButtons();
	addLeftMenuColapsing();
	addSortCollAnimation();
	addJsSelectBox();
	addPriceInputCheck();

	// Should be last - take log time
	addHTMLEditor();
}

function cursorPosition(e) {
	var pos = new Array();
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		pos['x'] = e.pageX;
		pos['y'] = e.pageY;
	} else if (e.clientX || e.clientY) {
		pos['x'] = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
		pos['y'] = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
	}
	return pos;
}

function windowHeight() {
	return (window.innerHeight)?window.innerHeight:document.documentElement.clientHeight;
}



/***********************************************************
funkce createCookie a readCookie vytvoril Peter-Paul Koch
http://www.quirksmode.org/
***********************************************************/
function createCookie(name, value, days) {
  var expires = "";
  if (days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	expires = "; expires="+date.toGMTString();
  }
  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;
}
/**
 * Unescape HTML entities
 */ 
String.prototype.unescapeHtml = function () {
    var temp = document.createElement("div");
    temp.innerHTML = this;
    var result = temp.childNodes[0].nodeValue;
    temp.removeChild(temp.firstChild)
    return result;
} 
