var IE = (document.all?true:false);

function gE(el){
    return document.getElementById(el);
}

function sleep(millisecondi){
	var now = new Date();
	var exitTime = now.getTime() + millisecondi;
	while(true){
		now = new Date();
		if(now.getTime() > exitTime) return;
	}
}

// calculate the current window width //
function pageWidth() {
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// calculate the current window height //
function pageHeight() {
  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// calculate the current window vertical offset //
function topPosition() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// calculate the position starting at the left of the window //
function leftPosition() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

				function popup(win,w,h,scroll,tool){
				  var iLeft = ( screen.availWidth  - w ) / 2 ;
				  var iTop = ( screen.availHeight  - h ) / 2 ;
				  if ( tool == "" ) tool = "no";
				  if ( scroll == "" ) scroll = "no";
				  
          window.open(win, 'win', 'width='+w+',height='+h+',toolbar='+tool+',scrollbars='+scroll+',dependent=yes,menubar=no,resizable=yes,left='+iLeft+',top='+iTop+'')
        }

  
function ShowLocalImage(imgname,obj) {
	imgname = imgname.replace(/\\/g,"/");
	imgname = imgname.replace(/\'/g,"\\'");
	content = "<img src=\"" + String(imgname) + "\" border=\"0\" height=\"130\" width=\"130\">";
	eval('gE(obj).innerHTML=content');
	gE(obj).style.display = 'block'; // na WWW nefunguje proto tento radek zakomentovan
}
  
  function hit(i,url,tbl){
      cspath=url+"c.php";
      if (i){
        obj_obr=new Image;
        obj_obr.src=""+cspath+"?i="+i+"&t="+tbl+"&r="+Math.random();
      }
      for (x=0;x<100000;x++){}
      return true;
  }
  
  /*
  test
  function CheckOnNumber(hodnota)					//kontrola zda je hodnota ciselna
	{
		if (hodnota==""){
		return false;
		}
		
		hodnota = hodnota.replace(" ", ""); 
		alert(hodnota);
		if(isNaN(hodnota)){
			return false;
		}else{
			return true;
		} 
	} 
  */

  function CheckOnNumber(hodnota)					//kontrola zda je hodnota ciselna
	{
		if (hodnota==""){
		return false;
		}
		//hodnota = hodnota.replace(" ", ""); ///zakomentovano FF a IE8 neznaji replace
		for (i=0;i<hodnota.length;i++){
		  if ( hodnota.charAt(i) != '.' && hodnota.charAt(i) != ',' && hodnota.charAt(i) != '-'  ){
				if (hodnota.charAt(i)<'0'){
  			return false;
  			}
  			if (hodnota.charAt(i)>'9'){
  			return false;
  			}
			}
		}
		return true;
	} 
	

	
	function CheckInput(typ,val){
    if ( typ == 'number' ){			
			if ( !CheckOnNumber(val) && val != '' ){
        alert('Vkládaná hodnota musí být číslo.');
        return false;
      }
    
    }
  }
	
	function CheckOnEmail(email)
	{
		invalidChars='/:,;ěščřžýáíéúů';			//vytvoreni promene se znaky ktere se nesmeji v adrese objevit
		for (i=0;i<invalidChars.length;i++){	//smicka proveruje zda se jeden ze znaku nevyskytuje v adrese
			badChar=invalidChars.charAt(i)
				if (email.indexOf(badChar,0)>-1){
				return false;
				}
		}
		atPos = email.indexOf('@',1)
		if (atPos==-1){
		return false;
		}
		if (email.indexOf('@',atPos+1)>-1){		//od mista nalezu prvniho @ se pokousime hledat @ (dva nelze)
		return false;
		}
		periodPos=email.indexOf('.',atPos)
		if (periodPos==-1){
		return false;
		}
		if (periodPos+3>email.length){
		return false;
		}
		return true;
	}
	
      function CheckLength(id,field,max,txt){
      			retezec = document.getElementById(id).value;
      			strlength=retezec.length;
      				if (strlength > max ) 
      				{
      	                alert(txt);           
      	                document.getElementById(id).value=retezec.substring(0,max);
      				}
      				else{
      			   document.getElementById(field).innerText = max - retezec.length;
      				}
      }
	
  function RoundNumber(num, dec) {
  	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  	return result;
  }


        /*obsluha stisknuti klavesy napr textarea*/
        function HandleKeyDown(obj,action) {
           if ( action == 'tab' ){ // pokud v textarea pouziji TAB odskoci kurzor jako v editoru  nikoliv na dalsi pole ve FORMu
             var tabKeyCode = 9;
             if (event.keyCode == tabKeyCode && event.srcElement == obj) {
                obj.selection = document.selection.createRange();
                obj.selection.text = String.fromCharCode(tabKeyCode);
                event.returnValue = false;
             }
           }
        }

	
function AlertStay(){
  clearInterval(BD);
}
	
function AlertCheck(){
	if ( gE('alert') ){
		BD=window.setTimeout("AlertOff('100')",4000);
	}
}

function AlertOff(opc){
  clearInterval(BD);
		var ie5=(document.getElementById && document.all);
		var ns6=(document.getElementById && !document.all);
		nPlus = 20   //the % of fading for each step
		speed = 50  //the speed
		    if(document.getElementById){
		       imgs = gE('alert');
				opacity = opc-nPlus;
				opc = opacity;
				
		    	if(opacity>-30){
					if(ie5){
				        imgs.style.filter="alpha(opacity=0)";
						imgs.filters.alpha.opacity = opacity;
					}
					
					if(ns6){
		        		imgs.style.MozOpacity = 0;
						imgs.style.MozOpacity = opacity/100;
		    		}
					tmr=setTimeout('AlertOff('+opc+')',speed);
		    	}else{
					clearInterval(tmr);
					gE('alert').style.display='none';
				}
		  }
}

function CookieCreate(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 CookieRead(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 CookieErase(name) {
	CookieCreate(name,"",-1);
}

function ColorPickerShow(id,ac,margin_top,margin_left){
  gE(id).style.display=ac;
  if (margin_top) gE(id).style.marginTop=margin_top;
  if (margin_left) gE(id).style.marginLeft=margin_left;
}

function ColorPickerSelect(color,tri){
  gE('color_picker_value'+tri).value=color;
  gE('color_picker_test_area'+tri).style.backgroundColor=color;
  gE('color_picker'+tri).style.display='none';
  
}

function ColorPickerManual(color){
  if (color.length>2) gE('color_picker_test_area').style.backgroundColor=color;
}

function ColorPickerOver(color,tri){
  var val = color.title;
  gE('color_picker_test_area'+tri).style.backgroundColor=val;
  //alert();
}


var globalCursorPos;
var globalCursorObj;

function CursorPos(obj) {
 globalCursorPos = getCursorPos(obj);
 globalCursorObj = obj;
 //alert(globalCursorPos);
}
function getCursorPos(textElement) {
 //save off the current value to restore it later,
 var sOldText = textElement.value;

//create a range object and save off it's text
 var objRange = document.selection.createRange();
 var sOldRange = objRange.text;

//set this string to a small string that will not normally be encountered
 var sWeirdString = '#%~';

//insert the weirdstring where the cursor is at
 objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length));

//save off the new string with the weirdstring in it
 var sNewText = textElement.value;

//set the actual text value back to how it was
 objRange.text = sOldRange;

//look through the new string we saved off and find the location of
//the weirdstring that was inserted and return that value
 for (i=0; i <= sNewText.length; i++) {
   var sTemp = sNewText.substring(i, i + sWeirdString.length);
   if (sTemp == sWeirdString) {
     var cursorPos = (i - sOldRange.length);
     return cursorPos;
   }
 }
}

//this function inserts the input string into the textarea
//where the cursor was at
function CursorPosInsert(stringToInsert) {
  if ( globalCursorPos && globalCursorObj ){
 // alert(globalCursorPos+' -aa- '+globalCursorObj);
 var firstPart = globalCursorObj.value.substring(0, globalCursorPos);
 var secondPart = globalCursorObj.value.substring(globalCursorPos, globalCursorObj.value.length);
 globalCursorObj.value = firstPart + stringToInsert +  secondPart;
 }
 else{
  alert('Nastavte kurzor do textového pole do kterého chcete vložit. ');
 }
}


function CursorPosInsert2(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
		} else {
		myField.value += myValue;
	}
}



//if (!IE) document.captureEvents(Event.MOUSEMOVE);
// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;
// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0
function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
   // tempX = event.clientX + document.body.scrollLeft
   // tempY = event.clientY + document.body.scrollTop
   tempX = event.x;
   tempY = event.y;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}
  return true
}


////http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function winSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}


///////////////////// AJAX /////////////////////
////////////////////////////////////////////////
   var http_request = false;
   function AjaxPostRequest(url, parameters,ret) {

      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Nelze vytvořit XMLHTTP instanci.');
         return false;
      }
      var boundaryString = 'AaB03x';
     // http_request.onreadystatechange = AjaxReturnContent;
      http_request.open('POST', url, true);
      //http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  //http_request.setRequestHeader("Content-type", "text/html; charset=UTF-8");
	  //  http_request.overrideMimeType('text/xml; charset=iso-8859-2'); 
	    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=iso-8859-2");
	    //http_request.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundaryString);
	     http_request.setRequestHeader("Transfer-Encoding", "chunked");
      http_request.setRequestHeader("Content-length", parameters.length);
	 // http_request.setRequestHeader("Accept-Charset", "ISO-8859-2;q=0.7,*;q=0.7");
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
      
	  
	  http_request.onreadystatechange = function(){

		if ( http_request.readyState == 4 ){
		    if (http_request.status == 200) {
					//alert(http_request.responseText);
		      result = http_request.responseText;
					if (ret=="js") { // vysledek bude proveden jako javascript
						eval(result);
					}
				  else if ( result!="" && ret!="" && (gE(ret).value=="" || gE(ret).value)  ) {
            gE(ret).value = result;
            gE(ret).style.backgroundColor='#d5ecd5'; // zvyrazneni INPUT, pokud byl upraven
          }
					else if (result!="" && ret!="") gE(ret).innerHTML = result;   
					else if (result!="" && ret!="") gE('ajax_return').innerHTML = result;
					
	        if ( ret == 'ret_basket' )  alert('Zboží bylo přidáno do nákupního košíku.');
					return true;          
	      } else {
	        alert('Nastal problém s návratem žádosti. Stav není 200.'+ http_request.status);
	        return false;
	      }
		}
	  }
	  
   }
   
   function ajax_return_hide(){ // sktyri LOADING obrazku pri pouziti AJAX
	 	if (AJ) {clearInterval(AJ);}
	 	gE('ajax_return').style.visibility='hidden';
	 }

   function AjaxReturnContent() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            if (result!="") gE('ajax_return').innerHTML = result;            
         } else {
            alert('Nastal problém s návratem žádosti. Stav není 200.');
         }
      }
   }
   
   ////////////////// AJAX END //////////////////////
   
   
   
   
   ///////////// PRO SHORTCUT //////////
   function addEvent(elm,evType,fn,capture) {if(!capture)var capture=true;if(elm.addEventListener){elm.addEventListener(evType, fn, capture);return true;}else if(elm.attachEvent){var r = elm.attachEvent('on' + evType, fn);return r;}else{elm['on' + evType]=fn;}}
   function $(id){return document.getElementById(id);}
   

  	var ie5=(document.getElementById && document.all);
		var ns6=(document.getElementById && !document.all);
		nPlus = 20   //the % of fading for each step
		speed = 50  //the speed
		var tmr = 0;
		
  	function over_mnu(obj,opc){
			if ( d.getElementById('car') ) d.getElementById('car').style.visibility='hidden';

			document.getElementById(obj).style.display='block';
			if (opc==1) tmr=setTimeout('opacity_mnu(\''+obj+'\','+opc+')',500);;
		}
  
    function mnu_layer(obj,ac,opc){
        clearInterval(tmr);
        
        if ( ac == 'show' ){
          if (opc==1) tmr=setTimeout('opacity_mnu(\'mnlay_'+obj+'\',0)',500); //opacity_mnu('mnu_layer_'+obj,0);
        }
        else if ( ac == 'stay'){
          document.getElementById('mnlay_'+obj).style.display = 'block';
        }
        else if ( ac == 'hide' ) {
          document.getElementById('mnlay_'+obj).style.display = 'none';
        }
    }
    
		function opacity_mnu(obj,opc){
		    if(document.getElementById){
		      document.getElementById(obj).style.display = 'block';
		      imgs = document.getElementById(obj);
				  opacity = opc+nPlus;
				  opc = opacity;
				
		    	if(opacity<120){
  					if(ie5){
  				    imgs.style.filter="alpha(opacity=0)";
  						imgs.filters.alpha.opacity = opacity;
  					}
  					
  					if(ns6){
  		        imgs.style.MozOpacity = 0;
  						imgs.style.MozOpacity = opacity/100;
  		    		}
  					tmr=setTimeout('opacity_mnu(\''+obj+'\','+opc+')',speed);
		    	}
          else{
					 clearInterval(tmr);
				  }
		  	}
		}
    
function contextMenu(obj,th) {
	event.returnValue=false;

	var tempX = 0
	var tempY = 0


	if ( gE('last_context_menu').value!='' ) {gE(gE('last_context_menu').value).style.display='none';}
//	var rightedge = document.body.clientWidth-event.clientX;
//	var bottomedge = document.body.clientHeight-event.clientY;
	
	
	//alert( 'clientY' +event.clientY +' / scrollTop:'+document.body.scrollTop  );
	
	 if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
 // document.Show.MouseX.value = tempX
  //document.Show.MouseY.value = tempY

	
	gE(obj).style.left = tempX;
	gE(obj).style.top  = tempY;
	
	gE(obj).style.display = "block";
	gE('last_context_menu').value = obj;
	
	/*
	
	if (rightedge < gE(obj).offsetWidth)
		gE(obj).style.left = document.body.scrollLeft + event.clientX - gE(obj).offsetWidth;
	else
		gE(obj).style.left = document.body.scrollLeft + event.clientX;
	if (bottomedge < gE(obj).offsetHeight){
		gE(obj).style.top = document.body.scrollTop + event.clientY - gE(obj).offsetHeight;
		//alert( document.body.scrollTop +' + '+ event.clientY  +' - '+ gE(obj).offsetHeight );
	}
	else{
		gE(obj).style.top = document.body.scrollTop + event.clientY;
		//gE(obj).style.top = document.body.clientHeight - event.clientY;
		//alert(th.offsetTop);
		alert( 'clientHeight' +document.body.clientHeight +' / scrollTop:'+document.body.scrollTop +' + innerheight:'+ window.innerHeight +' - offsetHeight:'+ document.body.offsetTop + ' - pageY:'+document.body.pageY  );
		gE(obj).style.display = "block";
		gE('last_context_menu').value = obj;
	}
	*/
	return false;
}

function contextMenuDisplay(obj,ac){
	gE(obj).style.display=ac;
}


      function overlay_win_hide(){
				var over_win = gE('id_overlay_win');
			  var over_mask = gE('id_overlay_mask');
			  over_win.style.display="none";
			  over_mask.style.display="none";
      }
		  function overlay_win(dialogwidth,dialogheight,ac,customText){
				var opacity = 30;
				var width = pageWidth();
			  var height = pageHeight();
			  var left = leftPosition();
			  var top = topPosition();
			  var topposition = top + (height / 2) - (dialogheight / 2);
			  var leftposition = (width / 2) - (dialogwidth / 2 );
				var content = gE('pg');
				var over_win = gE('id_overlay_win');
			  var over_mask = gE('id_overlay_mask');
			  
			  
			  over_win.innerHTML = "";
			  over_win.style.display="block";
			  over_mask.style.display="block";
			  over_win.style.top = topposition + "px";
			  over_win.style.left = leftposition + "px";
			  over_win.style.width = dialogwidth + "px";
			  over_win.style.height = dialogheight + "px";
			  AjaxPostRequest(_MAIN_URL+'ajax.php', 'a_ac='+ac+'&customText='+customText,'id_overlay_win');
				//over_win.innerHTML = content;
				
				//$('#over_win').html('<p>All new content. <em>You bet!</em></p>');

				
				over_mask.style.height = content.offsetHeight + 'px';
        over_mask.style.opacity = (opacity / 100);
				over_mask.style.filter = 'alpha(opacity='+opacity+')';
			}

