// KOMPATIBILITA

var Br = new BrCheck()

function BrCheck()
{
	this.VER	= navigator.appVersion;
	this.AGENT	= navigator.userAgent.replace(/[\/]/g,' ');
	this.DOM	= document.getElementById ? true:false;

	this.OP5	= this.AGENT.indexOf("Opera 5")>-1							?true:false;
	this.OP6	= this.AGENT.indexOf("Opera 6")>-1							?true:false;
	this.OP7	= this.AGENT.indexOf("Opera 7")>-1							?true:false;
	this.OP8	= this.AGENT.indexOf("Opera 8")>-1							?true:false;
	this.OP		= (this.OP5 || this.OP6 || this.OP7 || this.OP8);

	this.IE4	= (document.all && !this.DOM && !this.OP)					?true:false;
	this.IE5	= (this.VER.indexOf("MSIE 5")>-1 && this.DOM && !this.OP)	?true:false; 
	this.IE6	= (this.VER.indexOf("MSIE 6")>-1 && this.DOM && !this.OP)	?true:false;
	this.IE7	= (this.VER.indexOf("MSIE 7")>-1 && this.DOM && !this.OP)	?true:false;
	this.IE8	= (this.VER.indexOf("MSIE 8")>-1 && this.DOM && !this.OP)	?true:false;
	this.IE		= (this.IE4 || this.IE5 || this.IE6 || this.IE7 || this.IE8);

	this.Gecko  = this.AGENT.lastIndexOf('Gecko')>0;
	this.NS4	= (document.layers && !this.DOM)							?true:false;
	this.NS7	= (this.DOM && parseInt(this.VER) >= 5 && this.AGENT.lastIndexOf('Netscape')<this.AGENT.lastIndexOf('7'))?true:false;
	this.NS6	= (this.DOM && parseInt(this.VER) >= 5 && !this.NS7)		?true:false;
	this.NS		= (this.NS4 || this.NS6 || this.NS7 || this.Gecko);

	return this;
}

function getE(objectID)		{ return document.getElementById(objectID);	}
function getTN(sValue)		{ if(sValue=='' || sValue==' '){return document.createTextNode('\u00a0');}return document.createTextNode(sValue);	}
function getCE(sElement)	{ return document.createElement(sElement);	}
function getF(formName)		{ return document.forms[formName];			}
function RemoveCh(Node) { if ( Node == null ) return false;  while (Node.childNodes.length>0)   {       Node.removeChild( Node.childNodes[0] );   } }
function GetSRC(e)      { return (window.event)? window.event.srcElement : e.target; }
function setE(id,attr,value){ var el = getE(id); if(el!=null){el[attr] = value;} }

function pagerFormSubmit(pages,idx,url){
    var jtp = getE('jumptopage_' + idx);
    if(jtp){ 
        if (jtp.value!=jtp.defaultValue){
            var page = parseInt("0" + jtp.value,10);
            var pages = parseInt("0" + pages,10);
            if (page > 0 && pages > 0) {
                if (url.indexOf("search.asp") > 0) {
                    url += "p=" + page;
                } else {
                    url = url.replace(/¤/, Math.min(page, pages));
                }                
                window.location.href = url;
                return false;
            }
        }
    }
}
function checkjumpToPage(oF,jnpEl,pageCount,currPage,url){
    if(jnpEl){
        var reqPage = parseInt("0" + jnpEl.value,10);
        var pages = parseInt("0" + pageCount,10);
        if(pages>0){
            reqPage = Math.min(reqPage>0?reqPage:1,pages);
            jnpEl.value = reqPage;
            if(reqPage != currPage){
                oF.action = url.replace(/¤/,reqPage);
                return true;
            }
        }
    }
    return false;
}

//filter - jiz nepouzite
function filterProducerChanged(url,el){
    if(el.type=='select-one' || el.type=='checkbox'){
        var qs = '';
        if(el.type=='select-one'){
            qs = 'm=' + el.value;
            
        }else{
            var elms = el.form.elements;
            for(var i=0; elms.length; i++){
                if(elms[i].type=='checkbox' && elms[i].name=='m' && elms[i].checked){
                    qs += (((qs!='')?'&':'') + 'm=' + elms[i].value);
                }
            }
        }
        location.href = url + qs;
    }
}
//filter - jiz nepouzite
function jumpToPage(page,pages,url){
    var page = parseInt('0'+page,10);
    var pages = parseInt('0'+pages,10);
    if(page>0 && pages>0){
        page = Math.min(page,pages);
        if(page==1){
            url = url.replace( /(\/|\?)p(-|=)¤(&|\/)*/, '$1' );
            /*
            url = url.replace(/-?p(-|=)¤/,'');
            url = url.replace(/\/\//,'/');
            url = url.replace(/\?&/,'?');
            */
        }else{
            url = url.replace( /¤/, page );
        }
        window.location.href = url;
    }
}

// ###   FCE PRO zaskrtnutí a odeslání pk zboží pro Compare.asp   ###

function CompareSelected() {
	var sapkTblCommodity, CompareAdd;
	sapkTblCommodity = "";
	//aby to fungovalo vsude mozzila ie atd....
	for (var x=0; x<document.forms.length;x++){
		if (document.forms[x].name.indexOf("BuyFormBody")){
			if (document.forms[x].CompareAdd){
				if(document.forms[x].CompareAdd.checked){
					if (sapkTblCommodity=="") {
						sapkTblCommodity = document.forms[x].CompareAdd.value;
					}else{
						sapkTblCommodity += "|" + document.forms[x].CompareAdd.value;
					}
				}
			}
		}
	}
	if (sapkTblCommodity.indexOf('|') == -1) {

		alert('Pro porovnání je nutno vybrat nejméně 2 výrobky ...');
	} else {
		window.open('/exec/Compare.asp?CMP=' + sapkTblCommodity, "Compare","scrollbars=1,status=0,toolbar=0,location=0,directories=0,height=500,width=720,left=10,top=10,resizable=1,");
	}
}

function CompareRemoveOne(sapkTblCommodity, sComToRem) {
	var apkTblCommodity, aLen;
	if (sapkTblCommodity == '') {
		window.close();
		return;
	}
	apkTblCommodity = sapkTblCommodity.split('|');
	aLen = apkTblCommodity.length;
	if (aLen == 1) {
		window.close();
		return;
	}
	sapkTblCommodity = '';
	for (var i=0; i<aLen; i++) {
		if (apkTblCommodity[i]!=sComToRem) {
			if (sapkTblCommodity=='') {
				sapkTblCommodity = apkTblCommodity[i];
			} else {
				sapkTblCommodity += "|" + apkTblCommodity[i];
			}
		}
	}
	window.location.href = '/exec/Compare.asp?CMP=' + sapkTblCommodity;
}

// ###   FCE PRO BOXIKY SE SUBKATEGORIEMI   ###

var IdTimeToHideCategoryBox;

function ShowCategoryBox(img_id, cat_id)
{
	if ((IdTimeToHideCategoryBox!=null) && (cat_id!=cat_id_last)) HideAllCategoryBox(cat_id_last);

	var objElem = img_id;
    var x = 0;
    var y = 0;
    x += parseFloat(objElem.offsetLeft) + parseFloat(objElem.offsetWidth);
    y += parseFloat(objElem.offsetTop);

	getE('categoryBoxtable_' + cat_id).style.left = x;
	getE('categoryBoxtable_' + cat_id).style.top = y - 10;
	getE('categoryBoxtable_' + cat_id).style.display = 'block';
}

function HideCategoryBox(cat_id)
{
	cat_id_last = cat_id;
	IdTimeToHideCategoryBox = window.setTimeout('HideAllCategoryBox(' + cat_id + ')', 300);
}

function HideAllCategoryBox(cat_id)
{
	window.clearTimeout(IdTimeToHideCategoryBox);
	IdTimeToHideCategoryBox = null;
	getE('categoryBoxtable_' + cat_id).style.display = 'none';
}

// ###   FCE PRO DIALOG ZADANI VOLITELNYCH PARAMETRU   ###
var gsFormSuffix, gsFormIndex;


// ###   FCE PRO ROZKLIKAVANI KATEGORII   ###

function InsertCookiesCat(intId,idTree){
	document.cookie="category"+idTree+"="+intId+";path=/;";
}
function checkParent(src, dest) {
	while (src!=null) {
		if (src.tagName == dest) return src;
		src = src.offsetParent;
	}
	return null;
}

function outlineCat(e) {
	var open = (e.target) ? e.target : e.srcElement;
	var el = checkParent(open, "TD");
	if (null!=el) {
		for (var pos=0; pos<el.childNodes.length; pos++) {
			if ((el.childNodes[pos].tagName=="TABLE")) {
				
				var nodeNum = (Br.IE ? 0 : 1);
				
				if (el.childNodes[nodeNum].src.indexOf("plus")>0) {
					el.childNodes[nodeNum].src = el.childNodes[nodeNum].src.replace("plus","minus");
				}else if (el.childNodes[nodeNum].src.indexOf("minus")>0) {
					el.childNodes[nodeNum].src = el.childNodes[nodeNum].src.replace("minus","plus");
				}

				break;
			}
		}
	    if (pos==el.childNodes.length) return;
	} else return;
	el = el.childNodes[pos];
	if ("TABLE"==el.tagName) {
		if (el.style.display!="none") {
			el.style.display = "none";
		} else {
			el.style.display = "block";
		}
	}
//	event.cancelBubble = true;
}



/* COMPARE  */

var gCCompnTree = 1;
var gCCompIDs = ExtractCookies('CComp'+gCCompnTree).replace('none','');

function CCompChCli(o) {

	if (o)
	if (o.checked==true)
	{
		if (gCCompIDs.indexOf('|'+o.value+'|') < 0)	gCCompIDs += '|'+o.value+'|';
		if (gCCompIDs != '') CCompOn();
		
		if(getE('compareTotalSpan'))
		{
			getE('compareTotalSpan').innerHTML = parseInt(getE('compareTotalSpan').innerHTML)+1;
		}
	}
	else
	{
		gCCompIDs = gCCompIDs.replace('|'+o.value+'|', '');
		if (gCCompIDs == '') CCompOff();
		
		if(getE('compareTotalSpan'))
		{
			getE('compareTotalSpan').innerHTML = parseInt(getE('compareTotalSpan').innerHTML)-1;
		}
	}
	
	InsertCookies('CComp'+gCCompnTree,gCCompIDs);
}

function CCompChOn()
{
	var ch = document.getElementsByName('ccompCh');
	for (var i=0; i<ch.length; i++) {
		if (gCCompIDs.indexOf('|'+ch[i].value+'|') > -1)
			ch[i].checked = true;
	}
}	
function CCompChOff()
{
	var ch = document.getElementsByName('ccompCh');

	for (var i=0; i<ch.length; i++)
		ch[i].checked = false;

	gCCompIDs = '';
	InsertCookies('CComp'+gCCompnTree,'');

}

function CCompGo() { // open compare

	var q = gCCompIDs;
	
	if(q.indexOf('||')<0){alert('Porovnávat lze minimálně dva druhy zboží');return;}
	
	while(q.indexOf('||') > -1) q = q.replace('||', ',');
	while(q.indexOf('|') > -1) q = q.replace('|', '');
	
	if (gCCompIDs=='')	{
		alert('Zvolte si zboží k porovnání')
	} else {
		compareWindow = window.open('/exec/Compare.asp?d='+q,'compareWin','scrollbars=1,status=0,toolbar=0,location=0,directories=0,height=750,width=900,left=10,top=10,resizable=1');
		compareWindow.focus();
	}
}


function CCompOn()
{
	var im = document.getElementById('idCCompGo');
	var de = document.getElementById('idCCompDel');
}


function CCompOff()
{
	var im = document.getElementById('idCCompGo');
	var de = document.getElementById('idCCompDel');
}


function CCompStartup(nTree)
{
	gCCompnTree = nTree.toString();
	gCCompIDs = ExtractCookies('CComp'+gCCompnTree).replace('none','');

	
	if (gCCompIDs != '')
	{
		CCompOn();
		CCompChOn();
	}
}


function CCompDel()
{
	gCCompIDs = '';
	InsertCookies('CComp'+gCCompnTree,gCCompIDs);
	CCompOff();
	CCompChOff();
	
	if(getE('compareTotalSpan'))
	{
		getE('compareTotalSpan').innerHTML = 0;
	}
}


// SELECT on/off
function SelectExcept(o){
	return !( (o.id == "AMenu1")||(o.id == "TabMenu1")||(o.id == "TabMenu5")||(o.id == "TabMenu6")||(o.id == "CellMenu1")||(o.id == "CellMenu2")||(o.id == "ImgMenu1")); 
}

function SelectHide(sStyle){
	SelectHideEx(sStyle,document);
//	for (var i=0;i<window.frames.length;i++){
//		SelectHideEx(sStyle,window.frames[i].document);
//	}
}

function SelectHideEx(sStyle,odocument){	
	var o;
	o = odocument.getElementsByTagName("select");
	if (o !=null ){
		if (o.tagName == 'SELECT') {
			if (SelectExcept(o)) o.style.visibility=sStyle;
		} else {
			for(var i=0;i<o.length;i++){
				if (SelectExcept(o[i])) o[i].style.visibility=sStyle;
			}
		}
	}
}

// ###   FCE PRO PriceList ###

function SHModalDlgPricelist()
{
	var strReturn = showModalDialog("/Includes/EmailPricelist.htm","","status:no; center:yes; help:no; minimize:no;dialogWidth=320px;dialogHeight=124px;");

    if (strReturn == "") return;
	document.location.href = "/EmailPricelist.asp?EmailPricelist=" + strReturn;
}

// ##########

function onAction(imgName){
       getE(imgName).src = eval(imgName + "on.src")
}

function offAction(imgName){
	if (oldImgName.substring(0,4)!=imgName.substring(0,4)){
		getE(imgName).src = eval(imgName + "off.src")
	}
}

function OpenWnd(strURL){
	var objWnd = window.open(strURL,"InfoDetail","scrollbars=no,height=500,width=400,left=10,top=10");
	objWnd.focus();
}
function OpenWndAdvance(strURL, Y, X){
	var swindowname = "info";
	var sParameters = "scrollbars=yes,height=" + Y + ",width=" + X
    var objWnd = window.open(strURL,swindowname,sParameters);
    objWnd.focus();
}

function AddBuy(strName, intPrice, intDph, strCode) {
	var strData,strReturn
	strData = strName+"&"+intPrice+"&"+intDph+"&"+strCode
	strReturn = showModalDialog("/AddUpdBuy.asp",strData,"status:no; center:yes; help:no; minimize:no;dialogWidth=350pt;dialogHeight=200pt");
	if (strReturn == "1")
		ActionCookies('BZbuy');
	else if (strReturn == "2")
		window.location.href = "/exec/order.asp";
}
function AddBuyDetail(strName, intPrice, intDph, strCode) {
	var strData,strReturn
	strData = strName+"&"+intPrice+"&"+intDph+"&"+strCode
	strReturn = showModalDialog("/AddUpdBuy.asp",strData,"status:no; center:yes; help:no; minimize:no;dialogWidth=350pt;dialogHeight=200pt");
	if (strReturn == "1"){
		window.opener.ActionCookies('BZbuy')
	}else if (strReturn == "2"){
		window.opener.location.href="/exec/order.asp";
		window.close();
	}
}
function ActionCookies(strName){
	var strString,strSum1,strSum2,intSuma;
	strSum2 = new Array();
	intSuma = 0;

	strString = ExtractCookies(strName);
	if (strString > ""){
		strSum1 = strString.split("#");
		for (var i=0; i< strSum1.length-1; i++){
			strSum2[i] = strSum1[i].split("&");
			intSuma += BarterComma(strSum2[i][1])*BarterComma(strSum2[i][4]);
		}
		getE('CompletPrice').value =  FormatNumber(intSuma);
	}
}
function DeleteCookies(strName){
	var vyprs=new Date();
	vyprs.setDate(vyprs.getDate() - 365);
	document.cookie=strName+"=; expires="+vyprs.toGMTString()+"; path=/;";
	vyprs.setDate(365 + 365 + vyprs.getDate());
	document.cookie=strName+"=; expires="+vyprs.toGMTString()+"; path=/;";
	getE('CompletPrice').value = "0.00";
}
function InsTreeCook(intId,idTree){
	var vyprs=new Date();
	vyprs.setDate(vyprs.getDate() - 365);
	document.cookie="category"+idTree+"="+intId+"; expires="+vyprs.toGMTString()+"; path=/;";
	vyprs.setDate(365 + 365 + vyprs.getDate());
	document.cookie="category"+idTree+"="+intId+"; expires="+vyprs.toGMTString()+"; path=/;";
}
function InsertCookies(strName,strData){
	var vyprs=new Date();
	vyprs.setDate(vyprs.getDate() - 365);
	document.cookie=strName+"="+strData+"; expires="+vyprs.toGMTString()+"; path=/;";
	vyprs.setDate(365 + 365 + vyprs.getDate());
	document.cookie=strName+"="+strData+"; expires="+vyprs.toGMTString()+"; path=/;";
}

function ExtractCookies(strName){
	var cookieList=document.cookie.split("; ");
	var cookieArray = new Array();
	var name = "#"
	for (var i=0; i < cookieList.length; i++){
		if(cookieList[i].indexOf(strName)>-1){
			if( cookieList[i].indexOf("=")>-1){name = cookieList[i].split("=");}
		}
	}
	if (name != "#"){
		return name[1];
	}else{
		return "none";
	}
}
/***************************************************************************/
/***************************************************************************/
	var cookie_expire=new Date();
	cookie_expire.setDate(cookie_expire.getDate() + 365);
function ExtractCookies_simple(strName){
	var cookieList=document.cookie.split("; ");
	var cookieArray = new Array();
	var name = "#"
	for (var i=0; i < cookieList.length; i++){
		if(cookieList[i].indexOf(strName+'=')==0){
			return cookieList[i].substr(cookieList[i].search('=')+1);
		}
	}
	return "";
}
function ExtractUserCookie(strKey){ // vyuziva hlavniho klice USER
	var strKeysValues = ExtractCookies_simple('USER');
	var aKeyValue, aOneKeyValue;
	if ((strKeysValues=="none")||(strKeysValues=="")) return "";
	aKeyValue = new Array();
	aOneKeyValue = new Array();
	aKeyValue = strKeysValues.split("&");
	for (var i = 0; i<aKeyValue.length; i++) {
		aOneKeyValue = aKeyValue[i].split("=");
		if (aOneKeyValue[0].toLowerCase()==strKey.toLowerCase()) { return unescape(aOneKeyValue[1]); }
	}
	return "";
}
function InsertUserCookie(strKey, strValue){
	var strKeysValues = ExtractCookies_simple('USER');
	var sTmp = '';
	var sDelimiter = '';
	var aKeyValue, aOneKeyValue;
	aKeyValue = new Array();
	aOneKeyValue = new Array();
	if ((strKeysValues=="none")||(strKeysValues=="")) {
		document.cookie = 'USER' + "=" + strKey + "=" + strValue + "; path=/;";
	} else if (("&"+strKeysValues.toLowerCase()).indexOf("&"+strKey.toLowerCase()+"=")==-1) {
		document.cookie = 'USER' + "=" + strKeysValues + "&" + strKey + "=" + strValue + "; path=/;";
	} else {
		aKeyValue = strKeysValues.split("&");
		for (var i = 0; i<aKeyValue.length; i++) {
			aOneKeyValue = aKeyValue[i].split("=");
			if (aOneKeyValue[0].toLowerCase()==strKey.toLowerCase()) aOneKeyValue[1] = strValue;
			sTmp += sDelimiter + aOneKeyValue[0] + "=" + aOneKeyValue[1];
			sDelimiter = "&";
		}
		document.cookie = 'USER' + "=" + sTmp + "; expires=" + cookie_expire.toGMTString() + "; path=/; ";		
	}
}
/***************************************************************************/
/***************************************************************************/

function ParseCookies(strName){
	var strCook = ExtractCookies(strName)
	if (strCook != "none"){
		var strList = strCook.split("a");
		for (var i=0; i < strList.length-1; i++){
			if (getE(strList[i]+'a')) if (getE(strList[i]+'a').tagName=='A') if(typeof(getE(strList[i]+'a')) == "object"){getE(strList[i]+'a').click();}
		}
	}
}
function FormatNumber(text){
	var mezi = BarterComma(text);
	mezi = ''+Math.round(parseFloat(mezi) * 100);
	var desetiny = mezi.substring(mezi.length-2, mezi.length);
	var cele = mezi.substring(0,mezi.length-2);
	if (parseFloat(mezi) < 1){
	        var mezi = "0."+desetiny;
	}else{
	        var mezi = cele+"."+desetiny;
	}
	return mezi;
}
function FormatFloat(nNumber,nDecimal){
	var sNumber = BarterComma(nNumber);
	sNumber = ''+Math.round(parseFloat(sNumber) * Math.pow(10,nDecimal));
	var sDedimal = sNumber.substring(sNumber.length-nDecimal, sNumber.length);
	var nInt = sNumber.substring(0,sNumber.length-nDecimal);
	if (parseFloat(sNumber) < 1){
	        var sNumber = "0."+sDedimal;
	}else{
	        var sNumber = nInt+"."+sDedimal;
	}
	return sNumber;
}
function FormatCurrency(nNumber,nDecimal){
	var sCurrency, iInsertSpace;
	sCurrency = FormatFloat(nNumber, nDecimal).replace('.',',');
	iInsertSpace = sCurrency.indexOf(',') - 3;
	while (iInsertSpace>0) {
		sCurrency = sCurrency.substring(0,iInsertSpace) + ' ' + sCurrency.substring(iInsertSpace,sCurrency.length);
		iInsertSpace -= 3;
	}
	if (nDecimal==0) sCurrency = sCurrency.substring(0,sCurrency.indexOf(","));
	return sCurrency;
}

/*  num:     cislo,
    roundUp: zaokrouhlit nahoru,
    unit:    min jednotky - 50,10,1 - padesatnik, desetniky, halere,...
    dec:     pocet desetinnych mist,
    dot:     desetinny oddelovac
    ths:     oddelovac tisicu
    sfx:     pripona */
function FUCJS(num,roundUp,unit,dec,dot,ths,prf,sfx) {
    if(roundUp==null){roundUp = false}
    if(unit==null){unit = page.currencies[page.currencyID].nMinRoundValue}
    if(dec==null){dec = page.currencies[page.currencyID].nExponent}
    if(dot==null){dot = page.currencies[page.currencyID].chDecimalSeparator}
    if(ths==null){ths = page.currencies[page.currencyID].chThousandSeparator}
    if(sfx==null){sfx = page.currencies[page.currencyID].sCurrencySuffix}
    if(prf==null){prf = page.currencies[page.currencyID].sCurrencyPreffix}

    num = roundCurr(num,roundUp,dec,unit);

    var reg = /([-]?\d+)([.]?)(\d*)/;
    var aRes = reg.exec(num.toString());
    var sNum = '';
    if(aRes[2]==''){ //cele cislo bez desetinne tecky
        sNum = insThousandDelimeter(aRes[0],ths) + (dot? dot + ((dot!='')?sfx:''):'');
    }else{
        if(aRes[3]!=''){ //desetinne cislo
            sNum = insThousandDelimeter(aRes[1],ths)+((dot)?dot:aRes[2])+(aRes[3]+'0000000000').substr(0,dec) + (dec>0?'':sfx);
        }else{ //cele cislo s desetinou teckou ale bez desetinnych mist
            sNum = insThousandDelimeter(aRes[1],ths)+((dot)?dot:aRes[2])+('0000000000').substr(0,dec) + (dec>0?'':sfx);
        }
    }
    return sNum;
}
function insThousandDelimeter(num,delim){
    if(delim && delim!=''){
        var reg = /([-]?)(\d+)([.]?\d*)/;
        var aRes = reg.exec(num.toString());
        if(aRes && aRes.length > 2){
            var num2 = aRes[2];
            num = '';
            for(var i=num2.length-3; i>-3; i-=3){
                num = (i<0? num2.substr(0,(i+3)) : num2.substr(i,3)) + (num!=''?delim:'') + num;
            }
            num = aRes[1] + num + aRes[3];
        }
    }
    return num;
}
/*  num:     cislo
    roundUp: zaokrouhlit nahoru
    unit:    min jednotky - 50,10,1 - padesatnik, desetniky, halere,...
    dec:     pocet desetinnych mist */
function roundCurr(num,roundUp,dec,unit) {
    if(isNaN(num)){return 0;}
    if(dec && !isNaN(dec)){dec = Math.abs(dec)}else{dec = 0}

    var nComDiv = 1.0;
    if(dec > 0){
        unit = parseInt(unit);
        if(isNaN(unit)){
            unit = 1
        }else{
            unit = Math.abs(unit);
            if(unit < 1)
                unit = 1;
        }
        if(unit.toString().length > dec)
            unit /= Math.pow(10,unit.toString().length - dec);
        nComDiv = Math.pow(10,dec)/unit;
    }
    if(roundUp){
        num = Math.ceil(num * nComDiv) / nComDiv;
    }else{
        num = Math.round(num * nComDiv) / nComDiv;
    }
    return num;
}

function BarterComma(text){
	var mezi = ''+text;
	if (mezi.indexOf(',') != -1){
		mezi = mezi.split(",");
		mezi = mezi[0]+"."+mezi[1];
	}else{
		mezi = text;
	}
	return parseFloat(mezi);
}

function EmailControl(f){
	if(f.length==0){return false;}
	if (f.replace(/^[_a-zA-Z0-9\.\-]+@[_a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}$/,"")=="") { 
		return true
	} else {
		return false;
	}
}
function EmailControlMulti(f){
	if(f.length==0){return false;}
	if (f.replace(/^[_a-zA-Z0-9\.\-]+@[_a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}( *; *[_a-zA-Z0-9\.\-]+@[_a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5})*$/,"")=="") {
		return true
	} else {
		return false;
	}
}
function ControlNumber(e){
	var keynum;
	
	if(window.event){
		keynum = window.event.keyCode;
	}
	else if(e.which){
		keynum = e.which;
	}
	
	return (((keynum >= 48) && (keynum <= 57)) || (keynum == 8 || keynum == 13) || keynum === undefined);
}

function ControlDecimalNumber(e){
	var keynum;
	
	if(window.event){
		keynum = window.event.keyCode;
	}
	else if(e.which){
		keynum = e.which;
	}
	if((GetSRC(e).value.indexOf(',')>-1 || GetSRC(e).value.indexOf('.')>-1 )&&(keynum == 44 || keynum == 46)){return false;}
	//alert(keynum);
	//                                                                                      carka           tecka
	return (((keynum >= 48) && (keynum <= 57)) || (keynum == 8 || keynum == 13) || (keynum == 44 || keynum == 46) || keynum === undefined);
}

function ControlNumberRange(num,rozsah) {
	var minNum = parseInt(rozsah.split('-')[0]);
	var maxNum = parseInt(rozsah.split('-')[1]);
	num = parseInt(''+num,10);
	return (num>=minNum && num<=maxNum);
}
function controlMaxNumber(value,nMax){
		if(value > nMax && value >= 1){    
        alert("Číslo stránky musí být v rozmezí od 1 - " + nMax);
        return false;
    }else{    
        return true;
    }
}
function ControlFloat(){
	if (!Br.IE) return;
	if (((event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode !=46) && (event.keyCode !=44)) event.returnValue = false;
}

function ControlPhone() {
	if (!Br.IE) return;
    if (((event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 32)  && (event.keyCode!=40) && (event.keyCode!=41) && (event.keyCode!=43))
		event.returnValue = false;
}
function ControlPhonePress(e) {
	var keynum;

	if(window.event){
		keynum = window.event.keyCode;
	}else if(e.which){
		keynum = e.which;
	}
	return (((keynum >= 48) && (keynum <= 57)) || keynum == 8 || keynum == 13 || keynum == 32 || keynum == 40 || keynum == 41 || keynum == 43 || keynum === undefined);
}
function ControlZIPpress(e) {
	var keynum;

	if(window.event){
		keynum = window.event.keyCode;
	}else if(e.which){
		keynum = e.which;
	}
	return (((keynum >= 48) && (keynum <= 57)) || keynum == 8 || keynum == 13 || keynum == 32 || keynum === undefined);
}
function ControlPSC() {
	if (!Br.IE) return;
    if (((event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 32))
		event.returnValue = false;
}
function ControlStringLength(testedInput,maxLong) {
	if (testedInput.value.length>maxLong) {
		testedInput.value = testedInput.value.substring(0,maxLong-1);
		return false;
	}
	return true;
}
function getRadioValue( elRadio ){
	var ret = null;
	if(elRadio){
    	if(elRadio.length){
        	for (var i = 0; i < elRadio.length; i++) {
        		if (elRadio[i].checked){
        			ret = elRadio[i].value;
        			break;
        		}
        	}
    	}else{
    	   if(elRadio.checked) {
                ret = elRadio.value;
            }
        }
    }
	return ret
}

//----------info okno-------------------------------------------------------
function InfoWindow(strAddress) {
       showModalDialog(strAddress,"Info","status:no; center:yes; help:no; minimize:no;dialogWidth=450pt;dialogHeight=320pt");
}
function WriteDate(){
	var strDay=new Date();
	var d=strDay.getDay();
	if (d==1) document.writeln('pondělí');
	else { if (d==2) document.writeln('úterý');
	else { if (d==3) document.writeln('středa');
	else { if (d==4) document.writeln('čtvrtek');
	else { if (d==5) document.writeln('pátek');
	else { if (d==6) document.writeln('sobota');
	else { if (d==0) document.writeln('neděle'); }}}}}};
	document.writeln(strDay.getDate(),'.',strDay.getMonth()+1,'.',strDay.getFullYear());
	}
function ShowSearchMenu(x){
    if (x == 1){
        getE('Searchtable').style.display='';
    }else{
        getE('Searchtable').style.display='none';
    }
}
function LocInfo(){
	getE('StateInfo2').innerHTML="  probíná připojování...";
	var e = event.srcElement;
	var y = 0;
	var x = 0;
	while (typeof e == 'object' && e.tagName != 'BODY'){
		y += e.offsetTop;
		e = e.offsetParent;
	};
	x = (window.screen.width/2)+375
	getE('StateInfo1').style.top=y-140;
	getE('StateInfo1').style.left=x;
}

function PositionInfo(strText){
	getE('StateInfo3').innerHTML=strText;
	getE('StateInfo2').innerHTML="  probíhá připojování...";
	var e = event.srcElement;
	var y = 0;
	var x = event.clientX;
	while (typeof e == 'object' && e.tagName != 'BODY'){
		y += e.offsetTop;
		e = e.offsetParent;
	};
	getE('StateInfo1').style.top=y-140;
	if (document.body.clientWidth < 933){
	  getE('StateInfo1').style.left=x-175;
	}else{
	  getE('StateInfo1').style.left=780;
	}
}
function LocState(strCode,intCount){
	window.parent.frames['WinStat'].location.href="/InfoState.asp?ID="+strCode+"&CN="+intCount
	PositionInfo("On-line stav");
}
function ChangeStorage(bState){
	if(bState){
		for(var i = 0; i < getE('S').length; i++){
			getE('S')[i].value="0"
		}
	}else{
		for(var i = 0; i < getE('S').length; i++){
			getE('S')[i].value="-1"
		}
	}
}
function ChangeCloseout(bState){
	if(bState){
		for(var i = 0; i < getE('C').length; i++){
			getE('C')[i].value="1"
		}
	}else{
		for(var i = 0; i < getE('C').length; i++){
			getE('C')[i].value="3"
		}
	}
}
function ValidateAccount(sAccount) {
	var u1,u2,t1,t2,i;
	var vahy = new Array("1","2","4","8","5","10","9","7","3","6")
	u1 = sAccount.substring(0,sAccount.length - 10);
	u2 = sAccount.substring(sAccount.length - 10,12);
	t1 = 0;t2 = 0;
	for(i=u1.length ;i>0;i--) {
		t1 += u1.charAt(i - 1)*vahy[10 - i];
	}	  
	for(i=u2.length ;i>0;i--) {
		t2 += u2.charAt(i - 1)*vahy[10 - i];
	}
	if (((t2%11) == 0)&&((t1%11 == 0))) {
		return true;
	} else {
		return false;
	}
}

// ##### PriceList BEEND #######################################################
function DelProducer(nProd) {
	if (nDeleted==nProducers-1) return;
	getE("bEnabled" + nProd).value='0';
	getE("Producer" + nProd).style.display="none";
	nDeleted += 1;
}

function PutCategoriesIdNameToSelect(saCatIdName, nIndex, bStart) {
	var arrData, arrSubData, saCatID, el;
	arrData = saCatIdName.split("*");
	saCatID = "";
	for (var i=0; i<arrData.length-1; i++) {
	    arrSubData = arrData[i].split("/")
		el = document.createElement("OPTION")
	    el.value = arrSubData[0];
	    el.text = arrSubData[1];
		saCatID += arrSubData[0] + "$"
		if (bStart==true) {
			if (i==0) {
				el.text='-Všechny kategorie-';
				document.PL['Categ'+nIndex].options.add(el);
			}
		} else
		    document.PL['Categ'+nIndex].options.add(el);
	}
		
	document.PL['CatID' + nIndex].value = saCatID.substr(0,saCatID.length - 1);
	if (saCatIdName == "") {
		document.PL['Categ'+nIndex].style.display = "none";
		getE("ChooseCateg"+nIndex).style.display  = "inline";
	} else {
		document.PL['Categ'+nIndex].style.display = "inline";
		getE("ChooseCateg"+nIndex).style.display  = "none";
	}
}

function GetCategoriesIdNameForSelect(nTree,bAlsoDisabled,nIndex,nUserType) {
	var saCatID,nProID,sProNM;
	var r;
	
	nProID = document.PL['ProdID'+nIndex].value;
	
	sProNM = document.PL['ProdID'+nIndex].options[document.PL['ProdID'+nIndex].selectedIndex].innerHTML
	saCatID = document.PL['CatID' + nIndex].value;
	if(Br.IE){
		var strReturn = showModalDialog("/Includes/PriceListSelectCatsOfProd.asp?TREE="+nTree+"&ProID="+nProID+"&DIS="+bAlsoDisabled+"&CatIDs="+saCatID+"&ADM="+nUserType+"&ProNM="+sProNM,"Info","status:no; center:yes; help:no; minimize:no;dialogWidth=470px;dialogHeight=450px");
		if (typeof(strReturn) == 'undefined') return;
		with(getE("Categ"+nIndex)){
			r = options.length;
	       		for (var i=0; i<r; i++) {
	               		options.remove(options.length-1);
	       		}
		}
		PutCategoriesIdNameToSelect(strReturn, nIndex, false);
	}else{
		window.open("/Includes/PriceListSelectCatsOfProd.asp?TREE="+nTree+"&ProID="+nProID+"&DIS="+bAlsoDisabled+"&CatIDs="+saCatID+"&ADM="+nUserType+"&ProNM="+sProNM+"&nIndex="+nIndex,"okno","toobar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,width=470,height=450,left=0,top=0");
	}
	
}
function ClearCategories(nIndex) {

	while(document.PL['Categ'+nIndex].length>0) {
		document.PL['Categ'+nIndex].options[0] = null;	
		}
	
	document.PL['CatID' + nIndex].value = "";
	document.PL['Categ'+nIndex].style.display = "none";
	getE("ChooseCateg"+nIndex).style.display  = "inline";
}

function ShowImage(sImgPath,sName) {
		window.open('/exec/ShowImage.asp?IMG='+ sImgPath +'&title='+ sName, "Foto","scrollbars=0,status=0,toolbar=0,location=0,directories=0,height=100,width=100,resizable=1");
}

function ShowHide(element) {
	var e = (typeof(element)=="object" ? element : getE( element ));
	if (e.style.display=="none") { e.style.display = "" } else { e.style.display = "none" };
//	if (!Br.IE) this.blur(); //aby nam nezustaval v mozile oznacen klikaci text
}
function ShowHide2(element) {
	var e = (typeof(element)=="object" ? element : getE( element ));
	if (e.className.indexOf('closed')>-1) {
		e.className = e.className.replace('closed','opened');
	} else {
		e.className = e.className.replace('opened','closed');
	}
}
function changeCross(element) {
		if (getE(element).className == 'crossClosed') {
			getE(element).className = 'crossOpened' 
		} else {
			getE(element).className = 'crossClosed';
		}
}

function styleChange(elementId,classNameStr) {	
	var e = getE( elementId );	
	e.className = classNameStr;	
}



function showWaitingBox( str ) {
	var box = getE("hoverbox");
	box.style.left = document.documentElement.clientWidth / 2 - 350 + "px";
	box.style.top = topScroll() + document.documentElement.clientHeight / 2 - 10 + "px";
	box.className = "visible";
	box.innerHTML = "<p onclick=\"getE('hoverbox').className=''\">"+str+"</p>";
}

/* positions */
function leftPosition(obj,ev){
	if (ev) {
		if ( obj.offsetLeft + ((obj==document.body) ? 0 : leftPosition(obj.offsetParent)) < ev.clientX )  {
			return obj.offsetLeft + ((obj==document.body) ? 0 : leftPosition(obj.offsetParent))
		} else { // quli dvouradkovym elementum, tak aby se to nezobrazilo daleko od kurzoru na prvnim radku
			return ( ev.clientX );
		}
	} else { // kdyz volame rekurzivne, tak neni objekt ev k dispozici
		return obj.offsetLeft + ((obj==document.body) ? 0 : leftPosition(obj.offsetParent));
	}
}
function topPosition(ev) {
	 return ( ev.clientY + topScroll() );
}
function topScroll() {
	if (window.innerHeight) {
		  return ( window.pageYOffset )
	} else if (document.documentElement && document.documentElement.scrollTop) {
		return ( document.documentElement.scrollTop )
	} else if (document.body) {
		  return ( document.body.scrollTop )
	}
}
/* /positions */

var fadeInOut;
function fadeInObject ( objID, speed, opacity ) { // fce necha plynule zobrazit libovolny objekt na strance dle jeho ID; speed je 1-100; opacity je nepovinna vychozi hodnota
	window.clearTimeout(fadeInOut);
	var obj = getE(objID);
	if (!(opacity>0)) opacity = 0;
	if (!(speed>0)) speed = 5;
	opacity+=speed;
	if (Br.IE) {
		obj.style.filter = 'alpha(Opacity='+opacity+')';
		if (opacity<100) { fade=setTimeout("fadeInObject('"+objID+"',"+speed+","+opacity+");", 0) } else { obj.style.filter='' }
	} else if (Br.NS) {
		obj.style.MozOpacity = opacity/100;
		if (opacity<100) { fade=setTimeout("fadeInObject('"+objID+"',"+speed+","+opacity+");", 0) } else { obj.style.MozOpacity=1; }
	}
	if (obj.style.display!='block') obj.style.display='block';
}
function fadeOutObject ( objID, speed, opacity ) { // fce necha plynule zmiznout libovolny objekt na strance dle jeho ID; speed je 1-100; opacity je nepovinna vychozi hodnota
	window.clearTimeout(fadeInOut);
	var obj = getE(objID);
	if (Br.OP) { obj.style.display='none'; return; }
	if (!(opacity>0)) opacity = 100;
	if (!(speed>0)) speed = 5;
	opacity-=speed;
	if (Br.IE) {
		obj.style.filter = 'alpha(Opacity='+opacity+')';
		if (opacity>0) { fade=setTimeout("fadeOutObject('"+objID+"',"+speed+","+opacity+");", 0) } else { obj.style.display='none'; obj.style.filter=''; }
	} else if (Br.NS) {
		obj.style.MozOpacity = opacity/100;
		if (opacity>0) { fade=setTimeout("fadeOutObject('"+objID+"',"+speed+","+opacity+");", 0) } else { obj.style.display='none'; obj.style.MozOpacity=1; }
	}
}

// basketHoverBox

function showBasketHoverBox() {
	clearTimeout(this.timeouttohide);
	if (Br.IE) {
		if (getE('variantSelector')) getE('variantSelector').style.visibility='hidden';
		if (getE('unitSelector')) getE('unitSelector').style.visibility = 'hidden';

}
    if (Br.IE) {
        SelectHide('hidden');
    }  

	getE('basketHoverBox').style.top = topScroll() + 300+'px';
	getE('basketHoverBox').style.left = (document.body.clientWidth/2 - 100)+'px';
	fadeInObject ( "basketHoverBox", 0 );
	this.timeouttohide = setTimeout("hideBasketHoverBox();", 20000);
}

function hideBasketHoverBox() {
    if (Br.IE) {
        SelectHide('hidden');
    }  

	fadeOutObject('basketHoverBox');
	if (getE('sortingSelector')) getE('sortingSelector').style.visibility='visible';
	if (getE('producerSelector')) getE('producerSelector').style.visibility = 'visible';
	if (Br.IE) {
	    SelectHide('visible');
	}
}

function GetBuy(frm,sAction,sTarget) {	
	frm.action = sAction;
	frm.target = sTarget;
	frm.elements['do'].value = 'addbasketitem';
	//alert('Po');
	//return false;
}


// wishllistHoverBox

function showWishListHoverBox() {
	clearTimeout(this.timeouttohide);
	if (Br.IE) {
		if (getE('variantSelector')) getE('variantSelector').style.visibility='hidden';
		if (getE('unitSelector')) getE('unitSelector').style.visibility='hidden';
	}
	getE('wishlistHoverBox').style.top = topScroll() + 300+'px';
	getE('wishlistHoverBox').style.left = (document.body.clientWidth/2 - 100)+'px';
	fadeInObject ( "wishlistHoverBox", 0 );
	//this.timeouttohide = setTimeout("hideWishListHoverBox();", 20000);
}

function hideWishListHoverBox() {
	fadeOutObject('wishlistHoverBox');
	if (getE('sortingSelector')) getE('sortingSelector').style.visibility='visible';
	if (getE('producerSelector')) getE('producerSelector').style.visibility='visible';
}



function changeSelectedBookmark( bkmrkNo, bkmrksCount ) { 
	for (var i=1; i<=bkmrksCount; i++) { 
		if (getE('bookmark_'+i)) getE('bookmark_'+i).className='bookmark';
		if (getE('bookmark_content_'+i)) getE('bookmark_content_'+i).className='bookmark_content';
	} 
	getE('bookmark_'+bkmrkNo).className='bookmark active';
	getE('bookmark_content_'+bkmrkNo).className='bookmark_content active';
} 

function changeCatProd( catprod, obj, firstId) {
	var hidEl = catprod==1 ? getE('sb_producers') : getE('sb_categories');
	var shwEl = catprod==1 ? getE('sb_categories') : getE('sb_producers');
	if(obj.checked){
	    InsertUserCookie('CP', catprod==1 ? 'C' : 'P');
		if(hidEl && shwEl){
			hidEl.style.display='none';
			shwEl.style.display='block';
		}
		else{
			document.location.href = '/exec/default.asp?pty='+ (catprod==1 ? 'category' : 'producer');
			//'/Default.asp?' + (firstId ? firstId : '');
		}
	}	
}
function changeCatProd2( catprod, obj, cls ) {
	var hidEl = catprod==1 ? getE('sb_producers') : getE('sb_categories');
	var shwEl = catprod==1 ? getE('sb_categories') : getE('sb_producers');
    if(obj){
        InsertUserCookie('CP', catprod==1 ? 'C' : 'P');
    	if(hidEl && shwEl){
    		hidEl.style.display='none';
    		shwEl.style.display='block';
    		var txt = obj.className.replace(" " + cls,"");
    		txt = (catprod==1)? "" : " "+cls ;  
            obj.className = txt;
    	}else{
    		document.location.href = '/exec/default.asp?pty='+ (catprod==1 ? 'category' : 'producer');
    	}
    }
}

/* hover images in commodity list */
var bHoverName = 0, bHoverImage = 0, nLastImageId = 0; // jestli mame mys nad nazvem a obrazkem
function hideHoverImage( hoverWhat, idImage ) {
	if (hoverWhat==1) bHoverName = 0;
	if (hoverWhat==2) bHoverImage = 0;
	setTimeout("if (bHoverName==0 & bHoverImage==0) getE('hover_"+idImage+"').style.display='none';", 500); //getE('hover_'+idImage).style.display='none';
}
function showHoverImage( hoverWhat, idImage ) {
	clearTimeout;
	if (idImage!=nLastImageId) { bHoverName = 0; bHoverImage = 0; if (getE('hover_'+nLastImageId)) getE('hover_'+nLastImageId).style.display='none'; }
	if (hoverWhat==1) bHoverName = 1;
	if (hoverWhat==2) bHoverImage = 1;
	nLastImageId = idImage;
	getE('hover_'+idImage).style.display='block';
}

function ControlPassword(NameOne,NameTwo){
	if (getE(NameOne).value != getE(NameTwo).value){
		alert("Špatně zadané heslo.");
		getE(NameOne).value = "";
		getE(NameTwo).value = "";
		getE(NameOne).focus();
		return false;
	}else{
		return true;
	}
}

function checkCount( myCount, minCount, sUnit, onlyMultiplied ) {
	myCount = parseInt(myCount.replace(",","."));
	minCount = parseInt(minCount.replace(",","."));
	if ( myCount == 0 ) return true;
	if (myCount<0) {
		alert('Zboží nelze objednat v záporném počtu.'); return false;
	}
	if ( myCount < minCount ) {
		alert('Toto zboží lze objednat v minimálním počtu '+minCount+' '+sUnit+'.'); return false;
	}
	if ( (onlyMultiplied==1) && ( (myCount*10) % (minCount*10) != 0) ) {
		alert('Toto zboží lze zakoupit pouze v násobcích '+minCount+' '+sUnit+'.'); return false;
	}
	return true;
}


function checkCounts( oF ) {
	return true;
}


function confirmEmptyBasket() {
	return confirm('Přejete si zrušit objednávku a vyprázdnit košík?');
}

function GoToPage(nPage, sParam) {
	document.location.href = '?pgID=' + nPage + sParam;
}


function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

 function ShowCalendar(oid,pozice)
 {
  var cal = document.getElementById('divcal');
  var calframe = document.getElementById('diviframcal');
  if(typeof(oid).toLowerCase()=='string')
  {
  	var tbox = document.getElementById(oid);
  }
  else
  {
  	var tbox = oid;
  }
  var ssrc = '/administration/Calendar_inc.asp?el=' + oid + '&selDate=' + tbox.value;
  
  if(pozice==undefined)
  {
  	cal.style.top = (tbox.offsetTop + tbox.offsetHeight)>52?(tbox.offsetTop + tbox.offsetHeight):"52";
  	    // 52px je vysoka hlavicka s menuem
  	cal.style.left = tbox.offsetLeft;
  }
  else
  {
  	var Left = pozice[0]-210;
  	var Top = pozice[1]-160;
  	if (Top<52){Top = 52;}
  	if (Left<0){Left = 0;}
  	cal.style.top = Top + 'px';
   	cal.style.left = Left + 'px';
  }
  
  calframe.src = ssrc;
  cal.style.display = 'block';
 }
 
 function setBookmark(url,title){
	if (window.sidebar){
		window.sidebar.addPanel(title, url,"");
	}else if (Br.IE){
		window.external.AddFavorite(url, title);
	}else{
	 	alert('Váš prohlížeč bohužel nepodporuje automatické vkládání stránek mezi oblíbené, pro přidání stiskněte CTRL+D.');
	}
}

// dialog pro FIREFOX
var FFDialog = new Object() ;
FFDialog.Show = function( dialogInfo, dialogName, pageUrl, dialogWidth, dialogHeight, parentWindow, resizable ) {
	var iTop  = (screen.height - dialogHeight) / 2 ;
	var iLeft = (screen.width  - dialogWidth)  / 2 ;

	var sOption  = "location=no,menubar=no,toolbar=no,dependent=yes,dialog=yes,minimizable=no,modal=yes,alwaysRaised=yes" +
		",resizable="  + ( resizable ? 'yes' : 'no' ) +
		",width="  + dialogWidth +
		",height=" + dialogHeight +
		",top="  + iTop +
		",left=" + iLeft ;

	if ( !parentWindow )
		parentWindow = window ;
	
	var oWindow = parentWindow.open( '', dialogName, sOption, true );
	oWindow.moveTo( iLeft, iTop ) ;
	oWindow.resizeTo( dialogWidth, dialogHeight ) ;
	oWindow.focus() ;
	oWindow.location.href = pageUrl ;
	
	oWindow.dialogArguments = dialogInfo ;
	
	this.Window = oWindow ;
	
	try {
		window.top.captureEvents( Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS ) ;
		window.top.parent.addEventListener( 'mousedown', this.CheckFocus, true ) ;
		window.top.parent.addEventListener( 'mouseup', this.CheckFocus, true ) ;
		window.top.parent.addEventListener( 'click', this.CheckFocus, true ) ;
		window.top.parent.addEventListener( 'focus', this.CheckFocus, true ) ;
	}
	catch (e)
	{}
}

FFDialog.CheckFocus = function() {
	if ( typeof( FFDialog ) != "object" )
		return ;
	
	if ( FFDialog.Window && !FFDialog.Window.closed ) {
		FFDialog.Window.focus();
		return false;
	}
	else {
		try {
			window.top.releaseEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS) ;
			window.top.parent.removeEventListener( 'onmousedown', FFDialog.CheckFocus, true ) ;
			window.top.parent.removeEventListener( 'mouseup', FFDialog.CheckFocus, true ) ;
			window.top.parent.removeEventListener( 'click', FFDialog.CheckFocus, true ) ;
			window.top.parent.removeEventListener( 'onfocus', FFDialog.CheckFocus, true ) ;
		}
		catch (e)
		{}
	}
}


// *************************************************************************************************

// status, args nechany z duvodu kompatibility
function showMyModalDialog(url,title,sizeX,sizeY,status,args,top) //top znaci jak daleko od vrchu okna
                                                                  // default je 50px (ve stylech)
{
   var wo = document;
   var frameID = '';
   if(window!=window.top){
      wo = window.top.document;
      frameID = window.self.name;
   }
   
   if(getE('modalIframe')){return;}
   //if(Br.IE){SelectHide('hidden');}
    
   if(Br.IE6)
   {
   		var clona = wo.createElement('iframe');
	    clona.id='clona';
	    clona.src = '/administration/clonaIE6.htm';
   		wo.body.appendChild(clona);
   }
   else
   {
   		var div=wo.createElement('div');
	    div.id='clona';
   		wo.body.appendChild(div);
   }
   
    
   var clona=wo.createElement('div');
   clona.id='clona1'; // margin nelze pouzit, bug v IE

   url += ((url.indexOf("?")>-1)?"&":"?") +"title="+ title+"&frameID="+ frameID;
   
   clona.innerHTML="<iframe name='modalIframe' id='modalIframe' width='"+sizeX+"' height='"+sizeY+"' frameborder='0' scrolling='auto' src='"+ url +"'></iframe>";
    
   wo.body.appendChild(clona);
   if(top!==undefined){
      wo.getElementById('modalIframe').style.top=top;
   }
}
 


function CloseMyModalDialog(){
	if(window.top.document.getElementById('clona1') && window.top.document.getElementById('clona'))
	{ 
    window.top.document.body.removeChild(getE('clona1'));
    window.top.document.body.removeChild(getE('clona'));
    //if(Br.IE){SelectHide('visible');}
    }
}

// ************************************************************************************************
function showMyModalWaitingImg(fnction)

{
    
    if(getE('clonaWait')){return;}
    if(Br.IE){SelectHide('hidden');}
    var clona=document.createElement('div');
    clona.id='clonaWait';
    document.body.appendChild(clona);
    
    var clona1=document.createElement('div');
    clona1.id='clonaWaitInner';
    clona.appendChild(clona1);
    
    var img = getCE('img');
    img.src='/administration/images/working.gif';
    img.id='modalWaitingImg';
    clona1.appendChild(img);
    
    clona1.appendChild(getCE('br'));
    
    var span = getCE('span');
    span.className = 'font';
    span.id = 'waitingSpan';
    clona1.appendChild(span);
    
    
    
    var p = poziceElementu(img);
	
	if(fnction)
	{
		setTimeout(fnction,50);
	}
 }

function closeMyModalWaitingImg()
{
	if(getE('clonaWait'))
	{
		getE('clonaWait').parentNode.removeChild(getE('clonaWait'));
	    if(Br.IE){SelectHide('visible');}
	}
}


function ClearSelect(eSelect) {
    if (typeof(eSelect)=="string") {eSelect=getE(eSelect);}
    if (eSelect) {
		with(eSelect){
			while(options.length>0){remove(options.length-1);}
		}
	}
}

/*function showMyModalDialog(url,title,sizeX,sizeY,status,args){
    if(title)
        url += ((url.indexOf("?") == -1)?"?title=":"&title=") + title;
	if (!Br.IE)
		var ret = FFDialog.Show('','',url,sizeX,sizeY,this);
	else
		var ret = showModalDialog(url,args,status+";dialogWidth="+sizeX+"px;dialogHeight="+sizeY+"px;");

    return ret
}*/

/*  AJAX  */
/*
function Ajax(name,url,callBackFce,getXml){
    this.name = name;
	this.act = false;
	this.xml = null;
	this.url = url;
	this.CBFce = callBackFce;

    this.sendRequest = Ajax_SendRequest; 
        
	if(window.XMLHttpRequest){
	   this.xml = new XMLHttpRequest();
	   if(this.xml.overrideMimeType){
	       this.xml.overrideMimeType('text/xml');
       }
    }else if(window.ActiveXObject){
        try{
            this.xml = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                this.xml = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){}
        }
    }
	
	this.act = (this.xml)? true : false;

	function Ajax_SendRequest(){
    	if(!this.act){return;}
    	if(this.xml.readyState!= 0){return;}
 	
    	this.xml.open("GET", url, true);
    	if(getXml){ this.xml.setRequestHeader("Content-Type", "text/plain"); }
    	this.xml.onreadystatechange = alert(this.xml.status);//new Function('if ('+this.name+'.xml && '+this.name+'.xml.readyState == 4 && '+this.name+'.xml.status == 200){'+this.CBFce+'('+this.name+(getXml?".xml.responseXML":".xml.responseText")+');}');
    	this.xml.send("");
    }
}
*/
function GLS( sSentenceID, sDefault ){
    if(typeof(goLS)!="object"){
        return sDefault;
    }
    if(typeof(goLS[sSentenceID])=="undefined"){
        return sDefault;
    }
    return goLS[sSentenceID]
}
/*prejit z GLS na GLST a GLS maznout*/
function GLST( nScriptID, sSentenceID, sDefault ){
    if(typeof(goLST)!="object"){
        return sDefault;
    }
    if(typeof(goLST[nScriptID.toString() +"_"+ sSentenceID])=="undefined"){
        return sDefault;
    }
    return goLST[nScriptID.toString() +"_"+ sSentenceID]
}

function startString(str,len) {
	var reg = /<[^>]*>/;
	var newstr = str.replace(reg,'');
    var newLength = newstr.length;
	if(newLength>len) { newstr = newstr.substring(1,newstr.lastIndexOf(' ',len)); }
	if (newLength!=newstr.length) { newstr += '...'; }
	return newstr;
}

function showparamdesc(text)
{
    var msg = window.open('blank.htm','ParamDescription','toobar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,width=470,height=450,left=50,top=50');
    msg.document.body.innerHTML = text; 
    msg.focus();
}

function getFirstDiv(el)
{
    if(el.firstChild)
    {
        el=el.firstChild;
        if(el.tagName && el.tagName.toLowerCase()=='div')
        {
            return el;
        }
        else
        {
            el=getNextDiv(el);
            if(el){return el;}
        }
    }
    return false;
}

function getNextDiv(el)
{
    while(el=el.nextSibling)
    {
        if(el.tagName && el.tagName.toLowerCase()=='div')
        {
            return el;
        }
    }
    return false;
}

function getPreviousDiv(el)
{
    while(el=el.previousSibling)
    {
        if(el.tagName && el.tagName.toLowerCase()=='div')
        {
            return el;
        }
    }
    return false;
}

function decimalPlaces(num,places)
{
	places = parseInt(places);
	num = parseFloat(num);
	
	if(num+''=='NaN')
	{
		num=0;
	}
	if(places+''=='NaN')
	{
		places=0;
	}
	
	var powr = Math.pow(10,places);
	num *= powr;
	num = Math.round(num);
	num /= powr;
	if(num - Math.round(num)==0)
	{
		powr=''+powr;
		if(places>0)
		{
			num += '.'+powr.substr(1,places);
		}
	}
	return ''+num;
}



function emptySelection()
{	
	if(Br.IE)
	{
		document.selection.empty();
	}
	else if(window.getSelection)
	{
		window.getSelection().removeAllRanges();
	}
}

function FillMagazineSelect(suffix)
{
	var i,j, tmpYear, bSave

	var form = getF('magazine_search_'+suffix);

	var arrMag = form.arrYearAndNumber.value.split('|');
	var arrTmp = new Array();
	var arrNumber = new Array();
	var arrYear = new Array();
	
	tmpYear = '';
	
	for(i=0;i<arrMag.length;i++){
          arrTmp = arrMag[i].split('$');
          if(tmpYear!=arrTmp[0] && arrTmp[0]!=0){
               arrYear.push(arrTmp[0]);
		}
		tmpYear = arrTmp[0];
		if(arrTmp[1]!=0 && arrTmp[1]!='' ){
		     bSave = true;
		     for(j=0;j<=arrNumber.length;j++){
				if(arrTmp[1] == arrNumber[j]){
				     bSave = false;
				}
			}
			if(bSave){
				arrNumber.push(arrTmp[1]);
			}
		}
	}
	
	var slct, opt
	
	var fragment = document.createDocumentFragment();
	slct = form.select_year;
	for(i=0;i<arrYear.length;i++)
	{
		opt = getCE('option');
		opt.value = arrYear[i];
		opt.appendChild(getTN(arrYear[i]));
		fragment.appendChild(opt);
	}
	slct.appendChild(fragment);
	slct.value = form.actYear.value;

	slct = form.select_number;
	for(i=0;i<arrNumber.length;i++)
	{
		opt = getCE('option');
		opt.value = arrNumber[i];
		opt.appendChild(getTN(arrNumber[i]));
		fragment.appendChild(opt);
	}
	slct.appendChild(fragment);
	slct.value = form.actMonth.value;

}

function SubmitMagazineForm(suffix)
{


	var form = getF('magazine_search_'+suffix);

	var year = form.select_year.value;
 	var number = form.select_number.value;

	var mag = getE('sComUrl_'+ year +'_'+ number +'_'+ suffix)
	
	if(mag){
		document.location.href = mag.value;
	}else{
	    alert(mag);
	}

}


function ControlKatalogOrderForm()
{

	var form = getF("katalogorderform");

	if(form.sFirm.value.trim()==""){alert(GLS('orderkat_js_firstname','lol')); return false;}
//	if(form.sLastName.value.trim()==""){alert(GLS('orderkat_js_lastname','lol')); return false;}
//	if(form.sStreet.value.trim()==""){alert(GLS('orderkat_js_street','lol')); return false;}
	if(form.sCity.value.trim()==""){alert(GLS('orderkat_js_city','lol')); return false;}
	if(form.sZipCode.value.trim()==""){alert(GLS('orderkat_js_zip','lol')); return false;}
	if(form.sEmail.value.trim()==""){alert(GLS('orderkat_js_email','rofl')); return false;}
	if(!EmailControl(form.sEmail.value)){alert(GLS('order_js_email_invalid','lol')); return false;}
}


function SearchSeminary(formIndex)
{
 	var parameters;
	var form = getF("ajax_form_" + formIndex);
	parameters = "";

	if(form.category.value.trim() != "") {parameters += "&c=" + form.category.value.trim();}
	if(form.lektor.value.trim() != "") {parameters += "&lektor=" + form.lektor.value.trim();}
	if(form.place.value.trim() != "") {parameters += "&place=" + form.place.value.trim();}
	if(form.month.value.trim() != "") {parameters += "&month=" + form.month.value.trim();}
	if(form.pn.value.trim() != "") {parameters += "&pn=" + form.pn.value.trim(); }
	if (form.chr.value.trim() != "") {parameters += "&chr=" + form.chr.value.trim();}
	
	if(getE("jumptopage_" + formIndex)){
		parameters += "&p=" + getE("jumptopage_" + formIndex).value;
	}else{
		parameters += "&p=1";
	}
	
	
     var ajax = new Ajax('/exec/SeminaryBack.asp?action=load'+parameters,'get',ShowSeminary);
     ajax.sendRQ( '' , false );
}

var ShowSeminary = function(JScode)
{
	getE('column2').innerHTML = JScode;
}

function SearchSeminaryByFirstLetter(sFirstLetter, formIndex) {

    var form = getF("ajax_form_" + formIndex);

    form.chr.value = sFirstLetter;
    SearchSeminary(formIndex)
}

function OrderSeminar(nComId)
{
    var ajax = new Ajax('/exec/SeminaryBack.asp?action=order&id=' + nComId, 'get', ShowSeminarBox);
     ajax.sendRQ( '' , false );
 }

 var ShowSeminarBox = function(JScode) {
     //alert(JScode);
     eval(JScode);
 }

function GetBuySeminary(nComId, sCode) {

    var ajax = new ajax('/exec/SeminaryBack.asp?action=buy&id=' + nComId + '&code=' + sCode, 'get', JScode);
    ajax.sendRQ('', false);
    
}

var ShowSeminarDetail = function(JScode) {

}


function AddParticipant(sText, nCount, divId)
{

	var sInput = "<input class='input_text' type='text' name='sParticipant' value='"+sText+"' onfocus=\"if(this.value==this.defaultValue){this.value='';}\"  onblur=\"if(this.value.trim()==''){this.value=this.defaultValue;}\"/>";
	var sTmpText = "";
	var nTmpPrice = "";
	

	if(nCount>nActual){
		sTmpText = getE(divId).innerHTML;
		for(var i=1;i<=(nCount-nActual);i++){
		     sTmpText += sInput;
		}
	}else{
	     getE(divId).innerHTML = ""
	     for(var i=1;i<=nCount;i++){
	          sTmpText += sInput;
		}
	}

	if(getE('priceSum')){
	    nTmpPrice = getE("nPrice").value.replace('.', '') * nCount;
	    getE('priceSum').innerHTML = FUCJS(nTmpPrice, '', '', '', '', '.', '', '') + ' Kč';
	}

	nActual = nCount;

	getE(divId).innerHTML = sTmpText;

}

function GenerateParticipantInputs(nComID,nRow,nCount,bEnabled)
{
     var sInput = "";
     var tmpInput = "";
     var arrText = new Array

     if (bEnabled=="1") {
         sInput = "<input class='input_text' type='text' name='sParticipant' id='sParticipant_$$_&&' value='###' onchange=\"UpdateDescription(" + nComID + "," + nRow + "," + nCount + ");\"/>";
     } else {
         sInput = "<input class='input_text' type='text' name='sParticipant' id='sParticipant_$$_&&' value='###' readonly='readonly'/>";
     }

     var sTmpStr = ""  
     
	var tmpText = getF('FormBuy_'+nComID+'_'+nRow).sDescription.value;
	if (nCount > 1 ){
		if (tmpText.indexOf('|') > 0) {
		    arrText = tmpText.split('|');

		    for (var i = 0; i <= nCount - 1; i++) {
		        if (i < arrText.length) {
		            tmpInput = sInput.replace('###', arrText[i]);
		        } else {
		            tmpInput = sInput.replace('###', '');
		        }
		        tmpInput = tmpInput.replace('$$', nComID);
		        tmpInput = tmpInput.replace('&&', i);

		        sTmpStr += tmpInput;
		    }
		}else{
		    for (var i = 0; i <= nCount - 1; i++) {
	            tmpInput = sInput.replace('###', '');
		       tmpInput = tmpInput.replace('$$', nComID);
		       tmpInput = tmpInput.replace('&&', i);
   			  sTmpStr += tmpInput;
			}
		}
	} else {
	    tmpInput = sInput.replace('###', tmpText.replace("|",""));

        tmpInput = tmpInput.replace('$$', nComID);
        tmpInput = tmpInput.replace('&&', '1');

        sTmpStr += tmpInput;	    
	}     
     


	getE('td_'+nComID).innerHTML = sTmpStr;
}

function UpdateDescription(nComID,nRow,nCount)
{	var form = getF('FormBuy_'+nComID+'_'+nRow);
	
	var tmpText = "";

     for(var i=0;i<=nCount;i++){
          if(getE("sParticipant_"+nComID+"_"+i)){
	     	if(getE("sParticipant_"+nComID+"_"+i).value.trim()!=""){
	     	     tmpText += getE("sParticipant_"+nComID+"_"+i).value + "|";
			}
		}
	}

	form.sDescription.value = tmpText;

}


function showMagazineOverPayment(position,type) {
    var ajax = new Ajax('/exec/MagazineBack.asp?action=show&position=' + position + '&type=' + type, 'get', fillMagazineOverPaymentBox);
    ajax.sendRQ('', false);
}

fillMagazineOverPaymentBox = function(JScode)
{
    clearTimeout(this.timeouttohide);
    if (Br.IE) {
        if (getE('variantSelector')) getE('variantSelector').style.visibility = 'hidden';
        if (getE('unitSelector')) getE('unitSelector').style.visibility = 'hidden';
    }

    if (Br.IE) {
        SelectHide('hidden');
    }    
    
    getE('basketHoverBox').style.top = topScroll() + 300 + 'px';
    getE('basketHoverBox').style.left = (document.body.clientWidth / 2 - 100) + 'px';
    fadeInObject("basketHoverBox", 0);
//    this.timeouttohide = setTimeout("hideBasketHoverBox();", 20000);

    getE('basketHoverBox').innerHTML = JScode;

}

function GetOrderOverPayment() {

    if (getE("overpayment_end").checked == false && getE("overpayment_year").checked == false) {

        alert("Zvolte typ předplatného");
        return;            
    }

    if (getE("overpayment_end").checked == true && getE("overpayment_year").checked == true) {

        alert("Zvolte pouze 1 typ předplatného");
        return;
    }

    var frm = getF("MagazineOverPaymentForm");
    var count = getE("countMag").value;
    var tmpInputs = "";
    var nComID = 0;
    var nComCode = "";
    var nYear = getE("year").value;
    var j,index;

    if (getE("overpayment_end").checked == true) {
        j = getE("sMagazineNumber").value;
        if (j > 7) {
            j = j - 1;
        }
    } else {
        j = 1;
    }


    index = 0;
    for (var i = j; i <= 11; i++) {
        index += 1;
        if (i < 7) {
            nComID = getE("comid_" + nYear + "_" + i).value;
            nComCode = getE("comcode_" + nYear + "_" + i).value;
        } else {
            if (i == 7) {
                nComID = getE("comid_" + nYear + "_7–8").value;
                nComCode = getE("comcode_" + nYear + "_7–8").value;
            } else {
                nComID = getE("comid_" + nYear + "_" + (i+1)).value;
                nComCode = getE("comcode_" + nYear + "_" + (i+1)).value;
            }
        }

        tmpInputs += '<input type="hidden" value="' + index + '" name="row"/>' +
                     '<input id="commodity_' + index + '" type="hidden" value="' + nComID + '" name="commodity"/>' +
                     '<input type="hidden" value="0" name="mcfo"/>' +
                     '<input type="hidden" value="0" name="omc"/>' +
                     '<input id="deleted_" type="hidden" value="0" name="deleted"/>' +
                     '<input id="code_' + index + '" class="input_text" type="hidden" value="' + nComCode + '" name="code"/>' +
                     '<input type="hidden" value="' + count + '" name="count"/>';
    }

    getE("formDiv").innerHTML = tmpInputs;
    frm.submit();

}

function showShopPreviewDialog(nComID) {

    var e = getE("orderframe");
    e.style.display = "";
    e.style.zIndex = 999;
    e.style.position = "absolute";
    e.style.top = topScroll() + 50 + 'px';
    e.style.left = (document.body.clientWidth / 2 - 303) + 'px';
    e.src = '/exec/PreviewPage.asp?DPG=' + nComID;
    e.width = "602px";
    e.height = "782px";
    e.scrolling = "no";

    if (Br.IE) {
        SelectHide('hidden');
    }

//      var ajax = new Ajax('/exec/PreviewPage.asp?DPG=' + nComID, 'get', ShowPreview);
//    ajax.sendRQ('', false);

}

var ShowPreview = function(JScode) {
//alert(JScode)
    if (Br.IE) {
        SelectHide('hidden');
    }
    getE("hoverbox").className = "previewBox"
    eval(JScode);

}

function HidePreviewBox() {

    if (Br.IE) {
        window.parent.SelectHide('visible');
    }
    var e = window.parent.getE("orderframe");
    e.src = "";
    e.width = 0;
    e.height = 0;
    
}

function ChangeImage(e, s1, s2, i) {
    getE("img_actual").value = i;
    getE('imgmain').src = e.src.replace(s1, s2);
    getE('imgmain').alt = e.alt;

    var j = parseInt(getE("img_count").value);

    if (i == j) {
        getE("button_next").style.display = "none";
    } else {
        getE("button_next").style.display = "";
    }

    if (i == 1) {
        getE("button_prew").style.display = "none";
    } else {
        getE("button_prew").style.display = "";
    }
    
}

function ShowPrewImage() {
    var i = parseInt(getE("img_actual").value) - 1;
    var j = parseInt(getE("img_count").value);
    if (i > 0) {
        getE("img_" + i).onclick();
    }
    if (i == j) {
        getE("button_next").style.display = "none";
    } else {
        getE("button_next").style.display = "";
    }
}

function ShowNextImage() {
    var i = parseInt(getE("img_actual").value) + 1;
    var j = parseInt(getE("img_count").value);
    if (i <= j) {
        getE("img_" + i).onclick();        
    }
    if (i == 1) {
        getE("button_prew").style.display = "none";
    } else {
        getE("button_prew").style.display = "";
    }
}


function changeFolder() {

    var form = getF("FormBuyFolder")
    var year = form.folderYear.value;

    form.commodity.value = getE("commodity_folder_" + year).value;
    form.code.value = getE("code_folder_" + year).value;
    getE("folderCode").innerHTML = getE("code_folder_" + year).value;
    getE("folder_price").innerHTML = getE("price_folder_" + year).value;
   // getE("img_folder").src = getE("img_folder_" + year).value;

}

function changeCd() {

    var form = getF("FormBuyCd")
    var year = form.cdYear.value;

    form.commodity.value = getE("commodity_cd_" + year).value;
    form.code.value = getE("code_cd_" + year).value;
    getE("cdCode").innerHTML = getE("code_cd_" + year).value;
    getE("cd_price").innerHTML = getE("price_cd_" + year).value;
    getE("img_cd").src = getE("img_cd_" + year).value;

}

function checkMOPcheckbox(type) {
    if (type == 'toend') {
        if (getE("overpayment_end").checked == true) {
            getE("overpayment_year").checked = false
        } else {
            
        }    
    } else {
        if (getE("overpayment_year").checked == true) {
            getE("overpayment_end").checked = false
        } else {

        }            
    }

}

function CheckAccIcoData(value1,value2,sType) {

    var ajax = new Ajax('/exec/userdataback.asp?ico=' + value1 + '&psc=' + value2 + '&type='+sType, 'get', FillRegisterForm);
    ajax.sendRQ('', false);
}

function CheckAccIcoDataOrder(value1, value2, sType) {

    var ajax = new Ajax('/exec/userdataback.asp?ico=' + value1 + '&psc=' + value2 + '&type=' + sType + '&order=1', 'get', FillRegisterForm);
    ajax.sendRQ('', false);
}

function CheckAccContactData(value1) {

    var ajax = new Ajax('/exec/userdataback.asp?email=' + value1 , 'get', FillRegisterForm);
    ajax.sendRQ('', false);
}

var FillRegisterForm = function(JScode) {

    eval(JScode)
}

function ShowDeliveryAddress() {
    getE('deliveryAddressDiv').style.display = "";
}

function HideDeliveryAddress() {
    getE('deliveryAddressDiv').style.display = "none";

    if (getE("caisFirm_0")) {
        getE("caisFirm_0").value = "";
        getE("caisFirm2_0").value = "";
        getE("caisStreet_0").value = "";
        getE("caisCity_0").value = "";
        getE("caisCity_0").value = "";
        CAchanged("0");
    } else {
        getE("sDeliveryZipCode").value = "";
        getE("sDeliveryFirm").value = "";
        getE("sDeliveryFirm2").value = "";
        getE("sDeliveryStreet").value = "";
        getE("sDeliveryCity").value = "";
    }
}

