﻿window.onerror = function() { 
	if(typeof(iPhone) !== 'undefined' && typeof(HtmlOut) !== 'undefined')
	{	
		sendAlert('JS Error', 'JS Error', 'JS Error',0,3);
	}
};

function SkryDoplnky(lokacia,id)
{
	var divy = new Array();
	divy[0] = getE(lokacia+'Com');
	divy[1] = getE(lokacia+'Pril');
	divy[2] = getE(lokacia+'Spoj');
	divy[3] = getE(lokacia+'Chat');
	divy[4] = getE(lokacia+'Task');
	divy[5] = getE(lokacia+'Udal');
	divy[6] = getE(lokacia+'Aktiv');
	divy[7] = getE(lokacia+'Prieb');
	
	for(i = 0; i <= 7; i++)
	{ 
		if(divy[i] != null)
		{
			if(divy[i].id == id && divy[i].parentNode.style.display != 'none')
				continue;  // ak chcem zatvorit uz otvorene tak ho necham otvorený lebo v Detaile ho skryje /* ak by som ho skryl tu tak ho v Detaile odryje */
			divy[i].parentNode.style.display = 'none';
		}
	}
	
}

function actDateTime(objId, mode)
{
	/* mode: 0 - full, 1 - time, 2 - date */
	
	var ut=new Date();
	var h,m,s;
	var time="";
	
	den = ut.getDate();
	mes = ut.getMonth()+1;
	rok = ut.getFullYear();
	h = ut.getHours();
	m = ut.getMinutes();
	s = ut.getSeconds();
	if(s<=9) s="0"+s;
	if(m<=9) m="0"+m;
	if(h<=9) h="0"+h;

	if(!mode || mode == 2)
		time = "<span class=\"actDate\">" + den + "." + mes + "." + rok + "</span>"; 
	
	if(!mode || mode == 1)
		time +="<span class=\"actTime\">" + h + ":" + m + ":" + s + "</span>";
	
	document.getElementById(objId).innerHTML=time;
	setTimeout("actDateTime('"+objId+"', '"+mode+"')",1000);    
}

nalozObr.nakladacka = new Array;
function nalozObr(k)
{

  if( typeof jQuery === 'undefined' )
      return;
	  
	if(!nalozObr.nakladacka[k])
	{
	//alert(k);
		jQuery('#'+k+' span a').slimbox();
		nalozObr.nakladacka[k] = true;
	}
}


isPageLoad = false
addStartEvent(function(){isPageLoad = true})

function UniWsBackFunc(error,context,method)
{
	if(typeof(iPhone) !== 'undefined' && typeof(HtmlOut) !== 'undefined')
	{	
		sendAlert('Error', 'ADMIN:' + error.get_message() + "@" + method , 'ADMIN:' + error.get_message() + "@" + method,0,3);
	}
	else
	{
		alert('ADMIN:' + error.get_message() + "@" + method );
	}
}

function CallGPS(ridv)
{
    Baris.WebServices.CrmService.GetSpojenie({ RidV: ridv, Typ: '00015' }, GPSResp, UniWsBackFunc)
}

function GPSResp(res)
{
    if (res.length > 0)
    {
        iDetail(305, 'GPS;' + res[0].Hodnota, '', null);
    }
    else
    {
        alert('Ľutujeme GPS kodináty nie sú zadané.');
    }
}

function getHTMLEncode(t) {
    return t.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
}

function stPrint(printArea)
{
	pa = getE('stPa'+printArea);
	ph = getE('mobj'+printArea+'_dragno');
	
	mw = MyWindowOpen('',printArea,400,600,1,1);
	
	var text = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><html><head><title>Tlač</title>';
	text += '</head><body>';
	text += ph.innerHTML;
	text += pa.innerHTML;
	text += '</body></html>';
	
	mw.document.write(text);
	mw.focus();
	mw.print();	
	mw.location.reload(true);
	hideStBody('mobj'+printArea);
}


function enterSubmit(parentId,action)
{
	//	parentId = id elementu ktoreho nodov prechadzam (ak '' prechadzam celu stranku)	
	//	action = id buttonu, priamo funkcia	
	
	if (typeof action != 'object' && typeof action != 'function')
		action = document.getElementById(action)
	
	var p = document.getElementById(parentId);
	var inp = p.getElementsByTagName('input');
	
		for(var i=0; i < inp.length; i++)
		{
			if(inp[i].getAttribute("type") == "text")
			{
				if (typeof action != 'function')
				{
					if(navigator.appName == "Microsoft Internet Explorer")
						inp[i].onkeyup = function() {  /* tSearch(); */ if(event.keyCode == 13) { action.onclick(); return false; }  }; 
					else
						inp[i].setAttribute("onkeyup","if(event.keyCode == 13) { getE('"+action.id+"').onclick(); return false;} ");
				}
				else
				{
					//inp[i].onkeyup = function() { if(event.keyCode == 13) { action } }; 
					inp[i].onkeypress =  action ; 
				}
			}
		}
}


function GetLocationInfo(jsonCfg, backItems )
{
	
    if(jsonCfg.WiFiMAC != null && jsonCfg.WiFiMAC != 'm' )
	{		
	 // alert('test typ: '+typeof(jsonCfg.WiFiMAC));
      Baris.WebServices.CrmService.GetWiFiInfo({WID:jsonCfg.WiFiMAC,RegistrujPolohu:false}, GetWifiInfoOk, UniWsBackFunc, backItems);
	}
    else
	{
	   Baris.WebServices.CrmService.GetLocationInfo(jsonCfg, GetLocationInfoOk, UniWsBackFunc, backItems);
	}
}

function GetWifiInfoOk(response, backItems)
{
    if (response.State == false)
    {
        myAlert("ERR", response.Pozn);
        return;
    }
    
    if(response.LocName == '' )
      myAlert("ERR", response.Pozn);
    else
    {	  
		if(backItems.LocObj != null )
			backItems.LocObj.value = response.Loc.LocName;
		if(backItems.LatObj != null )
			backItems.LatObj.value = response.Loc.Lat;
		if(backItems.LongObj != null )
			backItems.LongObj.value = response.Loc.Long;
	}
			
}

function GetLocationInfoOk(response, backItems)
{
    if (response.State == false)
    {
        myAlert("ERR", response.Pozn);
        return;
    }

    if (response.Locations != null && response.Locations.length > 0)
    {

        if(backItems.LocObj != null )
        {
            backItems.LocObj.value = response.Locations[0].LocName;
        }
        else
        {
            getE(backItems).value = response.Locations[0].LocName;
        }
        
    }
    else
    {
        myAlert("INFO", "Pozicia nebola najdena");
    }
}

function leftTrim(sString)
{
	while (sString.substring(0,1) == '0')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function dhtmlLoadScript(url) {
    var e = document.createElement("script");
    e.src = url;
    e.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}

function up(obj)
{
//	if(obj == null) obj = this
//	obj.className="buttonsOver";
	this.className="buttonsOver";
}
function dn(obj)
{
//	if(obj == null) obj = this
//	obj.className="buttonsDown";
	this.className="buttonsDown";
}
function out(obj)
{
//	if(obj == null) obj = this
//	obj.className="buttonsOut";
	this.className="buttonsOut";
}

function itemUp(obj)
{
	obj.style.border="outset 2px";
}
function itemDn(obj)
{
	obj.style.border="inset 2px";
}

function MyWindowOpen(url,win_id,width,height,resizeable,scrollable)
 {   
   //alert('Spustam ' + win_id);
 /*  xpos = (document.body.offsetWidth - width)/2;
   ypos = (document.body.offsetHeight - height)/2; */
   //alert('SCREEN.W=' + screen.width  + 'SCRREN.H=' + screen.height);
   //alert('WIDTH=' + width  + 'HEIGHT=' + height);
   xpos = (screen.availWidth - width)/2;
   ypos = (screen.availHeight - height)/2;
   myWin = self.open(url,win_id,'top=' + ypos + ',left=' + xpos +',width='+width+',height='+height+',scrollbars='+scrollable+',resizable='+resizeable+',status=yes')
   myWin.focus();
   return myWin;
 }

function MyWindowPopup(name,x,y,w,h,html)
{ 
 var popup = self.open('',name,'top=' + y + ',left=' + x + ',width=' + w + ',height=' + h + ',scrollbars=auto,resizeble=no,status=no'); 
 popup.document.body.style.backgroundColor="lightyellow";
 popup.document.body.style.border= "solid black 1px";
 popup.document.title=name;
 popup.document.body.innerHTML = "<div width='100%' style='cursor:pointer' onclick='self.close()'>" + html + "</div>";
 
 //popup.show(5,5,x,y,elm); 
}
function GetColor()
{
	MyWindowOpen(GetRootPath() + '/Admin/Forms/Colorer.html','Colorer',300,400,false,false);
}

function CisRecordEdit(layout,pk1,pk2)
{
	MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisRecordEdit.aspx?layout=' + layout,'Cis' + pk1 + pk2,400,500,false,false);
}

var refMax = 100;
var refCount = 0;
function AutoRefresh()
{			
	refCount++;
	if (refCount < refMax)
	{		
		var	img = new Image(1,1);	
		var x = Math.random();
		img.src = GetRootPath() + '/Admin/refresh.aspx?retry=' + refCount.toString() + '&rnd=' + x;
		window.status = 'Link to Server Refreshed ' + refCount.toString()+ ' time(s)';
	}
}

function SetAutoRefresh(seconds)
{	
    window.status = 'Autorefresh active ' + seconds + ' sec';
	window.setInterval("AutoRefresh()",1000*seconds);
}

function TovarStrom(mode)
{
	var url = GetRootPath() + '/detail.aspx?content=detail&nid=2&mode=' + mode;	
	MyWindowOpen(url,'TVRTREE',250,450,true,true);
}

function AccessLevel(controlId,currentAR,primaryKey,autoModify)
{
	var addOn = '';
	if( primaryKey != null )	
				addOn += '&pk=' + primaryKey;
	if( autoModify != null )
				addOn += '&autoModify=' + autoModify;
	
	
	MyWindowOpen( GetRootPath() + '/Controls/AccessLevel/AccessLevel.aspx?control=' + controlId + '&ar='+ currentAR + addOn ,'AL',300,400,true,true);
}
 
 
var popUp; 

function OpenCalendar(idname, postBack, time, yearFrom, yearTo,sharedDatumField, sharedInterval)
{ 	var addOn = '';
	if(time != null && time != 'no' && time != 'false' && time != false)
		addOn += '&time=True';

	if(yearFrom != null && !isNaN(yearFrom))
		addOn += '&from='+yearFrom
		
	if(yearTo != null && !isNaN(yearTo))
		addOn += '&to='+yearTo
		
	if(sharedDatumField != null && sharedDatumField != '')
	    addOn += '&sdf='+sharedDatumField;
	    
	if(sharedInterval != null )
	    addOn += '&shint='+sharedInterval;
	    

	popUp = window.open(GetRootPath() + '/Controls/Calendar/Calendar.aspx?formname=' + document.forms[0].name + 
		'&id=' + idname + '&selected=' + document.forms[0].elements[idname].value + '&postBack=' + postBack + addOn, 
		'popupcal', 
		'width=176,height=250,left=200,top=250');
}

function SetDate(formName, id, newDate, postBack)
{

	eval('var theform = document.' + formName + ';');
	popUp.close();
	theform.elements[id].value = newDate;
	if (postBack)
		__doPostBack(id,'');
}	


function Koder(id_cis,clientId,submit,quickselect,extrapar,mode)
{
	if(typeof(Ext) == "undefined")
	{
	    if( mode == null )
		    mode = 0;
	    MyWindowOpen(GetRootPath() + "/Moduly/Common/Forms/Koder.aspx?id_cis=" + id_cis + "&id=" + clientId + "&submit=" + submit  + "&quick=" + quickselect + '&ep=' +  extrapar + '&mode=' + mode ,"Koder",800,280,'no','no');
	    return;
	}	
    if( mode == null )
		mode = 0;
    var elm = $get(clientId);	
    var beh = Sys.UI.Behavior.getBehaviors(elm)
    if( beh != null && beh.length > 0 )
    {
        var cisSelectId = beh[0]._cisSelectId;
	    var cisCondId = beh[0]._cisConditionId;
	    var extraParam = beh[0]._extraParam;
        BarisExtCoder.init(null,400,700,id_cis,cisSelectId,cisCondId);
    }
    else
    {
        BarisExtCoder.init(null,400,700,id_cis);
    }
    BarisExtCoder.loadCoder(215,1330);
    BarisExtCoder.execute = function(PK, editorValues, count, item) {
        if (BarisExtCoder.tempExecItems == null) {
            BarisExtCoder.tempExecItems = new Array();
        }
        BarisExtCoder.tempExecItems[BarisExtCoder.tempExecItems.length] = item;
        if (BarisExtCoder.tempExecItems.length == count) {
            var elm = $get(clientId);
            var beh = Sys.UI.Behavior.getBehaviors(elm)
            if ((beh != null) && (beh.length > 0) && (beh[0]._multiChoice == true)) {
                var text = new Array();
                var value = new Array();
                for (var i = 0; i < BarisExtCoder.tempExecItems.length; i++) {
                    text[i] = BarisExtCoder.tempExecItems[i].data["TEXT"]
                    value[i] = BarisExtCoder.tempExecItems[i].id                    
                }
                beh[0].setMultichoice((BarisExtCoder.tempExecItems.length <= BarisExtCoder.inputLimit) ? text : Array("..."), value,BarisExtCoder.multiChoiceMode)
            }
            else {
                var textField = $get(clientId)
                var valField = $get(clientId + "val")
                if ((textField != null) && (valField != null)) {
                    textField.value = BarisExtCoder.tempExecItems[0].data["TEXT"]
                    valField.value = BarisExtCoder.tempExecItems[0].id
                    if (textField.onchange)
                        textField.onchange()
					if (valField.onchange)
                        valField.onchange()
                    if (submit.toUpperCase() == "TRUE") // 3 krat hura pre netypove jazyky
                        __doPostBack(textField.id.replace(/_/g,':'),valField.value)
                }
                else {
                    alert('Datafield musi byt v editacnom rezime');
                }
            }
            BarisExtCoder.clear();
        }
        else {
            var elm = $get(clientId);
            var beh = Sys.UI.Behavior.getBehaviors(elm)
            if ((beh != null) && (beh.length > 0) && (beh[0]._multiChoice == true)) {
                var text = new Array();
                var value = new Array();
                text[0] = ""
                value[0] = ""
                beh[0].setMultichoice((BarisExtCoder.tempExecItems.length <= BarisExtCoder.inputLimit) ? text : Array("..."), value)
            }
            else {
                var textField = $get(clientId)
                var valField = $get(clientId + "val")
                if ((textField != null) && (valField != null)) {
                    textField.value = ""
                    valField.value = ""
                }
                else {
                    alert('Datafield musi byt v editacnom rezime');
                }
            }
           // 20.9.2011 rem BarisExtCoder.clear();
        }

    }    
}

function PopUpKoder(id_cis,clientId,submit,quickselect,extrapar,max,notnull)
{

	
	var url = "PopUpKoder.ashx?id_cis=" + id_cis + "&id=" + clientId + "&submit=" + submit  + "&quick=" + quickselect + '&ep=' +  extrapar + '&max=' + max  +'&notnull=' + notnull;;		
	UniMenu(url,id_cis);
}


function CisTreeKoder(id_cis,controlId,submit)
{
// window.opener.controlId.value = hodnota;
  //  + window.opener.__doPostBack('','');
  //Form1.controlId.value="ok";
  alert('ok');
}

function TovarInsert()
{
	MyWindowOpen( GetRootPath() + '/Moduly/Shop/Schemy/TovarInsert.aspx' ,'TovarInsert',450,400,true,true);
}




function CisProp(primarykey,idcis)
{
	//alert('Vlastnosti zaznamu s primarny klucom:' + primarykey +' a vzhladom ' + layout);
	//MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisRecordInfo.aspx?pk=' + primarykey + '&layout=' + layout ,'Prop' + primarykey ,400,450,true,true); 
	if( idcis == 263 )
	{
		DetailOP(primarykey);	
	}
	else
		MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisProperties.aspx?pk=' + primarykey  + '&idcis=' + idcis ,'cisp' + primarykey ,650,450,true,true); 		
}

function CisEdit(primarykey,idcis)
{
	//alert('Editacia zaznamu s primarny klucom:' + primarykey +' a vzhladom ' + layout);
	//MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisRecordEdit.aspx?pk=' + primarykey + '&layout=' + layout ,'Prop' + primarykey ,400,450,true,true); 		
	MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisProperties.aspx?pk=' + primarykey + '&idcis=' + idcis,'cisp' + primarykey ,650,450,true,true); 		
}

function CisId(cislo,par)
{
   
   var wsParams = null;
   if(typeof(cislo) == 'object')
	{
        wsParams = cislo;
   }
   else
   {
        var idCisStr = String(cislo).split('-');
        if(idCisStr[0] != '')
        {
	    cislo = Number(idCisStr[0]);
	    }
	    else
	        idCisStr.length = 1;
	    if( cislo == null || cislo == 9999 )
		    cislo = Number(par.substr(0,3));
	var podCis = '';
	
	if( idCisStr.length > 1 )
	   podCis = idCisStr[1];
       wsParams = new function(){};
       wsParams.IdCis = cislo;
  if( typeof(par) === 'string' && par.indexOf(';') > 0 )
		      wsParams.NParams =  par;
	     else
		      wsParams.NParams = 'PK;'+par;      
       wsParams.PodCis = podCis;
   }
   
   wsParams.Modul= barISPage.modulId;

   Baris.Portal.CommonServices.CisDef(wsParams,CisIdDone,UniWsBackFunc);    

}

function CisIdDone(result,context)
{
    if(result.State == false)
    {
        alert('Pre daný typ číselníka nie je možné editovať záznam');
    }
    else
    {
		if( result.AjaxReady )
			iDetail(result.Nid,result.NParams,'0');
		else
			Detail(result.Nid,result.NParams);
    }
}

//function CisId(cislo,par)
//{
//	if(typeof(cislo) == 'object')
//	{
//	    iDetail(cislo.Nid,cislo.NParams);
//	}
//	else
//	{
//	    cislo = String(cislo)
//	
//	    switch(cislo)
//	    {
//		    case '355':Detail(282,'pkrid;'+par); return SKLAD_KARTA_LB
//		    case '7': Detail(1220,'pk;'+par); return b_users
//		   * case '90': Detail(61,'idk;'+par); return
//		   * case '51': Detail(283,'PK;'+par); return
//		  !  case 'kon': Detail(1098,'kon;'+par); return
//		    case '266': Detail(1089,'RID;'+par); return MANAGER_OP
//		    case '266-Market': Detail(1089,'RID;'+par); return
//		   * case '263': Detail(1079,'RID;'+par); return MANAGER  2127
//		    case '254': Detail(45,'pk;'+par); return DOKL_PRILOHY
//		    case '306': Detail(1110,'RID;'+par); return DMS_DOKUMENTY
//		 maja !  case '306-IBO': Detail(1605,'rid;'+par); return
//		    case '8': Detail(1481,'rid;'+par); return INT_DOKL
//		    case '-67': Detail(59,'id;'+par); return MANAGER_KAT
//		   * case '284': Detail(267,'PK;' + par); return SERVIS_KARTA 84
//		   * case '53': Detail(265, 'PK;' + par); return SER_ZAK_L 81
//		    case '38': Detail(270, 'PK;' + par); return BARTEX_POBOCKY
//		    case '50': Detail(278, 'PK;' + par); return
//		    case '62': Detail(271, 'PK;' + par); return
//	    }
//	}
//}

function bMenu(zalId,cisId,cisRid,nparams,rightClick,obj)
{				
	
	if( zalId == '' )  zalId = '0';
	
	if(rightClick == true)
	{
		BarISMenu(''+zalId+'','CISID;' + cisId + ';VAL;' + cisRid + ';PK;'  + cisRid  + ';' + nparams,obj)
	}
	else{
		CisPreview(cisId,cisRid,'fastInfo' + cisId,this,true,true)
	}
	
}

function makeBM(rid,obj)
{
	if(obj != null)
	{
		
		cis = Number(rid.substr(0,3));
		
		onC = "bMenu(0,'"+cis+"', '"+rid+"','TEXT; ')";
		obj.setAttribute('onclick', onC);
		
		onCm = "bMenu(0, '"+cis+"', '"+rid+"','TEXT; ',true, this)";
		obj.setAttribute('oncontextmenu', onCm);
		
		obj.setAttribute('href', 'javascript:void(0)');
	}
}

function CisPreview(idCis,par,inlineObjId,target,extjs)
{
	var podCis = '';
	
	var idCisStr = String(idCis);
	var pdcIdx = idCisStr.lastIndexOf('-');
	if( pdcIdx  > 1 )
	{
		idCis = Number(idCisStr.substr(0,pdcIdx));
		podCis = idCisStr.substr(pdcIdx)
	
	}
	else
	{	
		idCis = Number(idCisStr);
	}
	
	if( idCis == null || idCis == 0 || idCis == 9999 )
		idCis = Number(par.substr(0,3));
	
   var runtimeParams ='';
    	
   if( target != null  && inlineObjId != '')   	        
   {
		if( extjs == true )
		{
			runtimeParams = '$extjs;true;objId;' + inlineObjId + '$'; 
			runtimeParams = runtimeParams + 'extjs;True;';
		}
		else
		{
			runtimeParams = '$objId;' + inlineObjId + '$';            
		}
		
	}                 
	 //CisId(idCis,par);return;      
	switch(idCis)
	{		
		case 251: cDetail(1085,runtimeParams + 'RID;'+par,'0',target); return
		case 62: cDetail( 1957 /*1415*/,runtimeParams + 'PK;'+par,'0',target); return
		case 254: cDetail(1681,runtimeParams + 'RID;'+par,'0',target); includeJs('sb1', 'javascript/slimbox/jquery.min.js'); includeJs('sb2', 'javascript/slimbox/slimbox2.js'); includeCss('sb3', 'css/slimbox2.css'); return
		case 90: cDetail(1986 /*1414*/,runtimeParams + 'PK;'+par,'0',target); return
		case 51: cDetail( 1989 /*1408*/,runtimeParams + 'PK;'+par,'0',target); return
		case 7: cDetail( 1993,runtimeParams + 'PK;'+par,'0',target); return
		case 263: 
				switch(podCis)
				{
					case 'Porady': cDetail(1433,runtimeParams + 'PK;'+par,'0',target); return		
					default: cDetail(2022,runtimeParams + 'PK;'+par,'0',target); return
					//default: cDetail(1411,runtimeParams + 'RID;'+par,'0',target); return
				}
		
		case 2630: cDetail(1433,runtimeParams + 'PK;'+par,'0',target); return
		case 306: 
				switch(podCis)
				{
					case 'T00077': cDetail(2051,runtimeParams + 'PK;'+par,'0',target); return		
					default: cDetail(1437,runtimeParams + 'RID;'+par,'0',target); return
				}
		case 266: 
				switch(podCis)
				{
					case 'Market': cDetail(1729,runtimeParams + 'PK;'+par,'0',target); return		
					default: cDetail(318,runtimeParams + 'PK;'+par,'0',target); return
				}
		
		case 8: cDetail(1496,runtimeParams + 'MOPID;'+par,'0',target); return
		case 50: cDetail(219,runtimeParams + 'cisid;50;PK;'+par,'0',target);return;
					/*
						if( barISPage.modulId == BarISPage.DealerModul ) { cDetail(1951,runtimeParams + 'SKID;'+par,'0',target); } 
						else {	Detail(2013,runtimeParams + 'PK;'+par,target);} return
					*/
		case 99: cDetail(1686,runtimeParams + 'PK;'+par,'0',target); return
		case 38: cDetail(2188,runtimeParams + 'PK;'+par,'0',target); return
        
		case 244: cDetail(1495, 'PK;' + par,'0',target); return;		
		
		case 284: cDetail(2158 /*1898*/, runtimeParams + 'PK;' + par,'0',target); return
		
		case 323: cDetail(1878, runtimeParams + 'PK;' + par,'0', target); return
		
		case 357: cDetail(1616, 'PK;' + par,'0',target); return
		
		case 392: cDetail(20090, runtimeParams + 'PK;' + par,'0', target); return
		case 53: cDetail(2171 /*1911*/, runtimeParams + 'PK;' + par,'0',target); return;		
        case 1: case 3: case 4: case 29: case 22: case 21: case 18: case 19: case 20: case 23: QV(par);return;
		case 247: cDetail(2187,runtimeParams + 'PK;'+par,'0',target); return
		default: cDetail(219,runtimeParams +'cisid;' + idCis + ';podcis;' + podCis + ';PK;'+par,'0',target); return
	}
}


function CisDetail(idCis,pk,subPage,nparams,copyPage,mid,returnHref)
{

	if(idCis == null || Number(idCis) == 9999 )
		idCis = Number(pk.substr(0,3));
		
	if(String(pk).length<9 && (idCis=='50' || idCis=='51' || idCis=='8' || idCis=='38') ) 
	{
		var idCis2 = (1000+Number(idCis));
		idCis2 = String(idCis2);
		idCis2 = idCis2.substr(1,3);
		pk = idCis2+'00000'+pk;
	}	

	var idCisStr = String(idCis).split('-');
	idCis = Number(idCisStr[0]);
	var podCis = idCisStr[1];
	
	if(podCis) idCis = idCis + ';podcis;'+podCis;
	
	if(!copyPage) 
		copyPage = 'DETRID';
		
	if(!nparams) 
		nparams='';
	else
		nparams=';' + nparams;
		
	if(!subPage) 
		subPage='';
	else
		subPage = '&addcontent=' + subPage;


  var url = '?copycontent=' + copyPage + '&from=' + barISPage.content + subPage + '&nparams=cisid;' + idCis + ';PK;' + pk + nparams;
  if(mid != null)	  
	    url += '&' + mid;

    try
			{
			    if (typeof window.opener == 'object') 
		    {   
			    if(returnHref == true)
			        return window.opener.location.pathname + url;
			    else
				    window.opener.location.href = window.opener.location.pathname + url;
			}
			else
			{
			    if (returnHref == true)
			        return window.location.pathname + url;
			    else
			        window.location.href = window.location.pathname + url;
			}
	}
	catch(err)
	{
	    if (returnHref == true)
	        return window.location.pathname + url;
	    else
		    window.location.href = window.location.pathname + url;
	}
}

function AddSysField()
{
	MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/AddSysField.aspx' ,'ASF' ,600,450,true,true); 			
}

function CisEngine(id)
{
	//alert('Vlastnosti pre zaznam '  + id);	
	MyWindowOpen(GetRootPath() + '/Moduly/Common/Forms/CisProperties.aspx?id=' + id ,'ASF' ,600,450,true,true); 		
}

function DDetail(masterId,nid,nparams,inline,width,height)
{
	var loc = '/detail.aspx';
	var url = GetRootPath() + loc + '?content=detail&nid=' + nid + '&mid=' + masterId;
	if( nparams != null && nparams != '' )
		url += '&nparams=' + nparams;
	if(width == "max") width = screen.availWidth
	if(height == "max") height = screen.availHeight
	if(!width) width = 200;
	if(!height) { height = 200; url += "&resizeme=yes"; }
		else url = url.concat("&resizeme=no");
	MyWindowOpen(url,'NID' + nid,width,height,'no','auto');	
}

Detail.spustene = Array()
function Detail(nid,nparams,target,width,height,resizable, obj)
{

	var loc = '';
	var scroll = "yes"
	var modul = '';
	var objId = '';
	var extJs = false
	var inlineMode = 'True';
	var elType ='';
	var pid = '';
	var view = '';
	var deviceMode = barISPage.deviceMode;

	if(nid == null || nid == '')
		return;
			
	if( target == true)
	{	
		loc = 'http://' + window.location.host + location.pathname; 
	}
	else
	{	
	    loc = GetRootPath() + '/detail.aspx';
	}
    
	var windowName = 'NID' + nid;    
	if(nparams != null && nparams.length)
	if(nparams.charAt(0) == "$")
	{
		var endSeq = nparams.indexOf("$",1)
		if(endSeq !== false)
		{
			var params = nparams.substring(1, endSeq).split(";")
			for(var n = 0; n < params.length; n+=2)
				params[params[n]] = params[n+1]
			if(endSeq < nparams.length-1)
				nparams = nparams.substr(endSeq+1)
			else nparams = ""

			if(params["winid"] != null)
				windowName = params["winid"];
				
			if(params["modul"] != null)
				modul = '&modul=' + params["modul"];

			if(params["scroll"] != null)
				scroll = params["scroll"]				
				
		    if(params["objId"] != null)
				objId = params["objId"]				

			if(params["pid"] != null)
				pid = params["pid"]			
				
			if(params["view"] != null)
				view = params["view"]			

		    if(params["elType"] != null)
				    elType = params["elType"]	
				
			if(params["extjs"] == 'true')
				extJs = true
				
		    if(params["inlineMode"] != '' )
				inlineMode = params["inlineMode"]
			
			if(params["stateId"] != '' )
				  stateId = params["stateId"]

			if(params["deviceMode"] != '' )
				  displayMode = params["deviceMode"]
				  
			if(params["fnWhenDone"] != '' )
				  fnWDone = params["fnWhenDone"]
					  
		}
	}

	
	var url = loc + '?rnd='+Math.random()+'&nid=' + nid;
	if( pid != '' )
		url += '&pid=' + pid;
	if( nparams != null && nparams != '' )
	{
		nparams = nparams.replace(/\+/g,'^');
		url += '&nparams=' + nparams;
	}

	if(deviceMode != '' )
	  url += '&deviceMode=' + deviceMode;
	
	if(view != '' )
	  url += '&view=' + view;
	url += modul;
	
	if(extJs  &&  typeof(Ext) !== 'undefined')
	{

		ExtJsDetail(nid,url,nparams,width,height)
		return
	}
	
	if(target == true)
	{
		//alert(url);
		location=url;
	}
	else if(objId != '' || inlineMode == 'ajaxModeExt')
	{
	var myConn = new XHConn();
	    if(objId != '')
	{
	    var inlineObj = $get(objId);
		//	if(Detail.spustene[objId]) { InLinePopUp(objId); return }
		if(Detail.spustene[objId] && params["inlinepu"]) { InLinePopUp(objId); return }
  if(objId == 'autoPlace' && inlineObj != null ) 
		  {
		      inlineObj.parentNode.removeChild(inlineObj);		
		      inlineObj = null;  
		  }
        if( inlineObj == null )
		{
			if(params["style"] == 'float') 
			    inlineObj = addFloatElm(objId);
            else
            {
                if(target != undefined)
                    inlineObj = addInlineElm(target,objId,elType);
            }
		}
		if(inlineObj != null)
		inlineObj.innerHTML = "<center><img src=\"images/system/ajax-loader.gif\"></br></br>Nahrávam...</center>";

			
			
	    var fnWhenDone = function (oXML) 
	    {
		    document.getElementsByTagName("BODY")[0].style.cursor = "default"
		    if( oXML.responseText == '' )
		    {
		        alert('Nie je k dispozicii');
		        return;		    		    
		    }
				if(onlineObj = document.getElementById(objId))
		    {
				    //---------------------------------------------------------------------------
					if(onlineObj.parentNode.id.substr(0,4)=='stPa')
					{
                        newDiv = document.createElement('div'); 
                        newDiv.setAttribute('id', onlineObj.parentNode.id);
                
                        onlineObj.parentNode.parentNode.insertBefore(newDiv, onlineObj.parentNode);
                        
                        onlineObj.parentNode.parentNode.removeChild(onlineObj.parentNode); // vymazem stary
                        
                        newDiv.innerHTML = oXML.responseText;
                        
                        onlineObj = newDiv;
                     }
                     else
                     {
						onlineObj.innerHTML = oXML.responseText;
                     }
                    
					//---------------------------------------------------------------------------
				
		        runJS(oXML.responseText); // spusti javascripty na nalievanej nalepke
				
					if(fnWDone) 
					{
						eval(fnWDone);
					}
				
				var divCollect = onlineObj.getElementsByTagName("DIV")
					// vykresli ovladacie prvky 
				var d = new Date();
				for(var n = 0; n < divCollect.length; n++)
				{
					if(divCollect[n].className == "controls")
					{
						nparamsR = "$reload;true;objId;" + objId + "$" + nparams//.replace(/reload;true/g, "")
						divCollect[n].innerHTML = '<IMG src="images/system/x_pin.gif" title="vyňať do okna" onclick="Detail('+nid+',\''+nparams+'\');hideItem('+objId+'.parentNode)" /><IMG src="images/system/x_reload.gif" title="znova načítať [naposledy: '+date2string(d)+']" onclick="Detail('+nid+',\''+nparamsR+'\')" /><IMG src="images/system/off.gif" title="skryť" onclick="hideItem('+objId+'.parentNode)" />'
						break
					}
				}
	
		    }
		    else
		        alert('Unknown destination tag ID: ' + objId);

			if(width != null) onlineObj.style.width = width + "px"

			
				if(params["reload"])
				{
					//inlineObj.innerHTML = ""
					if(params["style"] == 'float') InLinePopUp(objId)
						else if(inlineObj.parentNode.style != undefined) inlineObj.parentNode.style.display = ''
				}
				else if( inlineObj != null && inlineObj.innerHTML != '' )
				{
					if(params["style"] == 'float') InLinePopUp(objId, obj)
					else
					{
						if(inlineObj.tagName == 'TD' )
							hideItem(inlineObj.parentNode)
						else
							hideItem(objId)
					}
					return;
				}

			if(params["style"] == 'float') InLinePopUp(objId, obj) // az sem koli umiestneniu na stranke podla velkosti obsahu
	    }
        }
	    if (!myConn) 
		    alert("XMLHTTP not available. Try a newer/better browser.");
	    else 
	        document.getElementsByTagName("BODY")[0].style.cursor = "wait"	        
		url = url + '&inline=' + inlineMode;
		if(inlineMode == 'ajaxMode') stateId = barISPage.stateId;
		if( stateId != null )
			url = url + '&stateId=' + stateId + '&dummy=blah';
		else
			url = url + '&dummy=blah';
			
		if(inlineMode == 'ajaxModeExt')
		{
		    myConn.connect(url, 'GET','', ExtfnWhenDone);
		}
		else
		{
		myConn.connect(url, 'GET','', fnWhenDone);
		}
		Detail.spustene[objId] = true
	}
	else
	{
		temp = '';
		if(width == "max") width = screen.availWidth
		if(height == "max") height = screen.availHeight

		if(!width || width == null) { sirka = 200; }
		else { sirka = width; temp += '&width=' + width; }
		if(!height || height == null) { vyska = 200; }
		else { vyska = height; temp += '&height=' + height;  }

		if(!width || width == null || !height || height == null) url += "&resizeme=yes"+temp;
		else url = url.concat("&resizeme=no");
		if(resizable == null || resizable == "") resizable = "yes"
		
		MyWindowOpen(url,windowName,sirka,vyska,resizable,scroll);
	}
	
}


function ExtfnWhenDone(res) 
{
    if(/*BarISPage.myOS() == BarISPage.OS_IPHONE || nparams.indexOf("iPhone;true")> -1 */ 1==1) //mobilne zariadenia
    {
        iPhone.iDetailResp(res);
    }
    else
    {
        // verzia pre portal
    }
}


function cDetail(nid,nparams,displayMode,ev, newAutoPlaceId)
{
	if( String(displayMode) == '0' )
		displayMode = '1';
    if(typeof(nparams) != 'undefined' && nparams != '')
        nparams += ';';
    nparams += 'noCache;true';
    iDetail(nid,nparams,displayMode,ev, newAutoPlaceId);
}

var LastDetailWindow = null;
function ExtJsDetail(nid,url,nparams,width,height)
{	
    var defResponseFn = function(response,request)
    {
    
    var output = null;
    try{
		 eval("output = " + response.responseText);
		 }
		 catch(e)
		 {
		  Ext.Msg.alert('Chyba', 'Nepodarilo sa zobraziť detail - nesprávne data zo serveru');
		 }
		 
		 if(typeof(output.Pid) === 'undefined' )
     {
        Ext.Msg.alert('Chyba', 'Nepodarilo sa zobraziť detail.');
     }
	
		if(width == null)
			width = output.width;
		if(height == null)
			height = output.height
        if(width == null)
        {
            width = 0;
        }
        if(height == null)
        {
            height = 0;
        }
		/* test vysky obsahu okna */
			var elm = document.createElement("DIV")
			elm.style.position = "absolute"
			elm.style.top = "0px"
			elm.style.visibility = "hidden"
			elm.innerHTML = output.html
			
			
			document.getElementsByTagName("BODY")[0].appendChild(elm)
			if(elm.offsetHeight + 30 > document.body.clientHeight) height = document.body.clientHeight - 30
			document.body.removeChild(elm)
					
		/* end */
		
		nparams = uParam('nparams',url);
		
        var detailWin = new Ext.Window({
		title: '<span class="item" title="Otvoriť v novom okne (popup)" onclick="Detail('+nid+',\''+nparams+'\');LastDetailWindow.destroy()"><img src="images/system/16x16/pin-purple.gif"> </span>'+output.title,
        closable:true,
        bodyStyle: "background-color:#ffffff;",
        //titleCollapse:true,
        //minimizable:true,
        width:width + 40,
        height:height + 30,
		autoScroll: true,
		maximizable: true,
        plain:true,
        html:output.html,
        listeners:
        {
            "afterrender":
            {
                fn:function(component)
                {
                    if((this.width == 40) && (this.height== 30))
					{
                    var maxWidth = 40;
                    var height = 10;
                    for(var index = 0; index<component.body.dom.children.length; index++)
                    {
                        if(component.body.dom.children[index].offsetWidth>maxWidth)
                        {
                            maxWidth = component.body.dom.children[index].offsetWidth
                        }
                        height += component.body.dom.children[index].offsetHeight
                    }
                    component.setWidth(maxWidth+20);
						component.setHeight(height+30);
                }
            }
        }
        }
        });
  
        if(detailWin!=null)
        {
			      LastDetailWindow = detailWin;
            LastDetailWindow.Nid = nid;
            detailWin.show();
        }		
        
        if(output.ErrorMessage != null )
        {
          Ext.Msg.alert('Chyba', output.ErrorMessage);
        }
        
		  if(nid == 1428) calc_init()
		  if(nid == 1703) {minceInit(getE('Mince0').value); includeCss('ext_butt', 'css/buttons/ext_buttH.css') }
		
		// RUN JS
		runJS(output.html)
		if(output.scripts.length > 0 )
	        runJS(output.scripts)
		
        return;
        
    }
    
	    
    var conn = new Ext.data.Connection();
    conn.request({
        url: url + '&inline=Ext',
        method: 'GET',
        success: defResponseFn,
        failure: function() {
            Ext.Msg.alert('Chyba', 'Server - nepodarilo sa získať detail.');
        }
    });
	
	if( url.toString().indexOf('noCache;true') == -1 && LastDetailWindow != null )
	{
		LastDetailWindow.hide();
		LastDetailWindow.destroy();
	}
   
}

function ShopJump(val,content)
{	
	pars = val.split(';');
	finContent = 'SHOP';	
	if( content != null )
		finContent = content;
	url='?content=' + finContent;
	var skupina
	if(skupina = getParam('skupina')) url += "&skupina=" + skupina
	nparams = '';
	if( pars[0] != null )
	{	 
	 nparams +='typ_t;' + pars[0];
	}
	if( pars[1] != null && pars[1] != '' )
	{
	 if(nparams != '' )
		nparams += ';';
	 nparams +='vyr;' + pars[1];
	}
	if( nparams != '' )
	  url += '&nparams=' + nparams;	
	
	window.location = url;
}

function AutoResize(width, height)
{

	var pridavok = 20
	var tbl1 = getE("t1")
	if (tbl1 == null) return
	var center =  ( getParam('center') != 'no')

	if(!width || width == null) width = tbl1.offsetWidth + tbl1.offsetLeft * 2
	if(!height || height == null) height = tbl1.offsetHeight + tbl1.offsetTop * 2

	if(width == document.body.clientWidth && height == document.body.clientHeight) return

	widthavail = screen.availWidth
	heightavail = screen.availHeight
	if(width > widthavail) width = widthavail
	if(height > heightavail) height = heightavail
	var rezervaX = widthavail - width
	var rezervaY = heightavail - height
	if(pridavok > rezervaY) pridavok = rezervaY

	if(isPageLoad)
	{
		window.resizeBy(0, height - document.body.clientHeight)
		return
	}

    if(center && width != -1)
    {        
		xpos = (screen.width - width)/2
		ypos = (heightavail - height)/2
		window.moveTo(xpos, ypos)
	}

	var rozdielX = 0
	if(width != -1)
	{
		window.resizeTo(width, height + pridavok)
		rozdielX = width - document.body.clientWidth
		if(rozdielX > rezervaX) rozdielX = rezervaX
		if(BarISPage.myBrowser() == BarISPage.BR_T_CHROME) return;
	}

	var rozdielY = height - document.body.clientHeight
	if(rozdielY > rezervaY) rozdielY = rezervaY
	window.resizeBy(rozdielX, rozdielY)	
	if(center)
	{
	    window.moveBy(-rozdielX/2, -rozdielY/2)
	}
}

function PrepareAutoResize(width, height)
{
	AutoResize(width,height);
	
	/*
	addStartEvent
	(
		function()
		{
			alert('resizujem');
		}
	)
	*/
}

function NewSerZak(sk,op,md)
{
	var query='';	
	if(sk != null )
		query += '&sk=' + sk;
	if(op != null )
		query += '&op=' + op;
	if(md != null )
		query += '&md=' + md;

	MyWindowOpen(GetRootPath() + '/Moduly/System/Forms/NewSerZak.aspx?in=1' + query,'NSZ' ,510,550,"yes","yes"); 		
}


function NewSerZakO(rid,id_r)
{
	var addOn = '';
		if( id_r != null )
				addOn = '&step=2&idr=' + id_r;
	MyWindowOpen(GetRootPath() + '/Moduly/System/Forms/NewSerZakO.aspx?rid=' + rid + addOn ,'NSZO' + rid ,460,200,"no","no"); 
	
}


function EditSerZar(id)
{
	MyWindowOpen(GetRootPath() + '/Moduly/System/Forms/NewSerZar.aspx?svk=' + id ,'EDITSZ' + id ,510,550,"no","no");
}


function NewSerZar(skid,sn,rid)
{
	if(skid == null )
	{
		alert('Nezadaná skladová karta');
		return ;
   }	
    var addOn = '';
    if(sn != null )
    {
		addOn = '&sn=' + sn;
    }
    if(rid != null)
    {
		addOn = addOn + '&mrid=' + rid;
	}
	MyWindowOpen(GetRootPath() + '/Moduly/System/Forms/NewSerZar.aspx?skid=' + skid + addOn,'NEWSZ' ,510,550,"no","no"); 		
}

function NewFD(typ,rid_p,rid_m)
{
	MyWindowOpen(GetRootPath() + '/Moduly/System/Forms/NewFD.aspx?typ=' + typ + '&rid_p=' + rid_p + '&rid_m=' + rid_m ,'NFD' ,400,300,"no","no");
}

function MessageBox(caption,message)
{
	var oNewWindow = window.open('','','width=400,height=200,left=200,top=150,scrollbars=yes,resizable=yes');
	var sMsg = '<HTML><HEAD><TITLE>'+caption+'</TITLE></HEAD><BODY bgColor=\"activeborder\" style="font-size:8pt;font-face:verdana">'+message + '</BODY></HTML>';
	oNewWindow.document.write(sMsg);
}
	
function DetailPic(image)
{
	MyWindowOpen(GetRootPath() + "/Controls/DetailPic/detailpic.aspx?img=" + image,"imgwin",300,300,'yes','auto');		
}


function CRView(rid,prn,nparams)
{
	MyWindowOpen(GetRootPath() + "/Moduly/Common/Forms/ReportViewer.aspx?rid=" + rid +'&prn=' + prn + '&nparams=' + nparams,"RV" + rid,800,600,'yes','yes');		
}	


function Tlac(id,pk)
{
	CRW(id,'','PK;' + pk + ';RID;'+pk+';direct;False',null,null,true)
}

function CRW(id,output,nparams,podm,etype,newwin)
{
	
    id = new String(id);
    var winId = output;
    if( newwin == true)
        output = '';
	if( etype == null )
	        etype = 'PDF';	
    var addq = '';    
    if( podm != null )
            addQ = '&podm=' +  podm ;   
    var url ='';

	if( id.substr(0,1) == 'P' )  
	    url= GetRootPath() + '/Moduly/Common/Forms/ReportViewer11.aspx?prn=' + id.substr(1) + '&att=' + output + '&nparams=' + nparams +  addq + '&stateId=' + barISPage.stateId + '&etype=' + etype ;		
	else if(id.substr(0,1) == 'M' )
        url= GetRootPath() + '/MailMerge.ashx?&nparams=id;' + id.substr(1) + ';' + nparams + '&etype=' + etype + '&stateId=' + barISPage.stateId;			
    else	  
        url= GetRootPath() + '/Moduly/Common/Forms/ReportViewer11.aspx?crw=' + id + '&att=' + output + '&nparams=' + nparams + addq + '&stateId=' + barISPage.stateId + '&etype=' + etype;					

        
     if(newwin)
     {      
       var newWin =  MyWindowOpen(url,winId,600,700,'yes','yes');           
     }
     else
     {     
        window.location = url;
     }
     
}

function Favorit(idcis,ridv,iduser)
{
	if( idcis == null || ridv== null )
								return;
	var url = GetRootPath() + "/Moduly/Common/Forms/UserFavorit.aspx?idcis=" + idcis + "&ridv=" + ridv;
	if(iduser!= null)
	{
		url = url + '&uid=' + iduser;
	}
	MyWindowOpen(url,'UF',320,50,'no','no');

}

function ChangeTree(ridorcis,ctrl,selected,snode)
{
	if( ridorcis== null )
				return;
	var url = GetRootPath() + "/Moduly/Common/Forms/ChangeTree.aspx?ridv=" + ridorcis;	
	if(snode != null)	
		url = url + '&snode=' + snode;
	if( ctrl != null)
		url = url + '&ctrl=' +  ctrl;
	if( selected != null)
		url = url + '&sel=' +  selected;
	MyWindowOpen(url,'CT',320,500,'yes','yes');

}


function QV(rid)
{
	//Detail(20,'rid;' + rid ,false,910,500);
	var cisid = new Number(rid.substr(0,3));
	BarISPage.Detail('DETDOKLAD','PK;' + rid + ';cisid;' + cisid,false)
}


// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page

mouseCapturingOn = false
function EnableMouseCapturing()
{
	if(mouseCapturingOn) return
	// Set Netscape up to run the "captureMousePosition" function whenever
	// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
	// the movement a little easier.
	window.status='Capturing enabled';
	if (document.layers) { // Netscape
		document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = captureMousePosition;
	} else if (document.all) { // Internet Explorer
		document.onmousemove = captureMousePosition;
	} else if (document.getElementById) { // Netcsape 6
		document.onmousemove = captureMousePosition;  
}
mouseCapturingOn = true
}

function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position
        // reflects the position from the top/left of the screen the
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no
        // matter if the user has scrolled or not.
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
		
	//document.title=xMousePos + " " + yMousePos
	
}

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}


var selectedPopUp=null;
var selectedPopUpItem=null;
var popup_delay_msec=500;
var popupTimerID=null; 

function popupOff()
{		
	clearTimeout(popupTimerID);
	popupTimerID=null;
	if(selectedPopUp != null)
	{
//			selectedPopUp.parentElement.style.visibility="hidden";
        if(InLinePopUp.hideWhenOut)
		selectedPopUp.style.visibility="hidden";
		else
		    selectedPopUp.style.position = "static";

		selectedPopUp=null;
		selectedPopUpItem=null;
	}
}


function PopUpOn(sPopUpId,x,y)
{
	if(selectedPopUp!=sPopUpId && sPopUpId != null)
	{
		
	    if( typeof x === 'undefined' )
	        return;
		if(selectedPopUp!=null) popupOff();
		selectedPopUp=sPopUpId;
		sPopUpId.style.left= x + "px";
		sPopUpId.style.top= y + "px";
		//sPopUpId.parentElement.style.visibility="visible";
		//alert(sPopUpId.id + ':' + sPopUpId.style.left+", "+sPopUpId.style.top + ' ' + sPopUpId.style.position )
		sPopUpId.style.visibility="visible";
//		var firstTD = sPopUpId.getElementsByTagName("TD")[0]
//		if(firstTD && firstTD.className != "tblSlideMenuLabel" && firstTD.className != "StickerBody") PopUpItemOn(firstTD)
		//PopUpOff()
	}
	else
	{
		
		clearTimeout(popupTimerID); 
		popupTimerID=null;
	}
}

function PopUpOff()
{
   popupTimerID=setTimeout("popupOff()",popup_delay_msec);
}

function PopUpItemOn(popUpItem)
{	
	clearTimeout(popupTimerID);	
	popupTimerID=null;
	if(popUpItem == null) return
	selectedPopUpItem=popUpItem;
	popUpItem.className='tblSlideMenuOn';
}

function PopUpItemOff(popUpItem)
{
	if(popUpItem != null)
	{
		popUpItem.className='tblSlideMenuOff';
		selectedPopUpItem=null;
	}
	PopUpOff();
}

function popUpCombo(objId, item, val, tooltip)
{
    getE(objId+"pop").getElementsByTagName("LI")[eval("selPUC"+objId)].className = ""
    getE(objId+"pop").getElementsByTagName("LI")[item].className = "sel"
    eval("selPUC"+objId+" = item")
    getE(objId).value = val
    getE(objId+"a").title = tooltip
    popupOff()
}

function manageFTX(cmbItem, ftxId)
{
    var txt = cmbItem.innerHTML
    if(getE(ftxId).value == getE(ftxId + "_STATE").value)
        getE(ftxId).value = txt
    getE(ftxId + "_STATE").value = txt
}

function manageFTXK(ftxObj)
{
    if(ftxObj.value == getE(ftxObj.id + "_STATE").value)
    {
        ftxObj.value = ""
        ftxObj.className = "ftxField"
    }
}

function manageFTXB(ftxObj)
{
    if(ftxObj.value == "")
    {
        ftxObj.value = getE(ftxObj.id + "_STATE").value
        ftxObj.className = "ftxHelp"
    }
}

function BarISMenuCis(zalId,idCis,obj,val)
{
        if( zalId == '' )  zalId = '0';
        if( val == null)
        {
            if( getE(obj.id + 'Val').value == ''  )
                return;
            val = getE(obj.id + 'Val').value;
        }
       var nparams = 'CISID;' + idCis + ';VAL;' + val + ';TEXT;' + obj.value + ';PK;'  + val;      
       BarISMenu(zalId,nparams);

}

function BarISMenu(zalId,nparams, obj)
{				
	if( zalId == '' )  zalId = '0';	
	UniMenu(GetRootPath() + "/menu.ashx",zalId,nparams, obj);
	//return false; >> nesmie robit return !!!
	
}

function UniMenu(source,zalId,nparams, obj)
{
  if(!mouseCapturingOn)
    {
	    xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
    }
	

	var myConn = new XHConn();
	var fnWhenDone = function (oXML) 
	{
		if(BarISPage.myOS == BarISPage.OS_IPHONE  )
		{
			var inData = getE("StMenuBody");
			inData.innerHTML = oXML.responseText;
			inData.onclick = function(){setTimeout(function(){ jQT.goBack('#'); BarISPage.RefreshDataSource() },1500)}; 
			return;
		}
		else
		{
			includeCss('anylinkcssmenu', 'css/'+barISPage.modulId+'/anylinkcssmenu.css')
			InLinePopUp('prop' + zalId, oXML.responseText, obj);
			document.getElementsByTagName("BODY")[0].style.cursor = "default"
		}
	}
		
	if (!myConn) 
		alert("XMLHTTP not available. Try a newer/better browser.");
	else document.getElementsByTagName("BODY")[0].style.cursor = "wait"
	myConn.connect(source, "POST", "id=" + zalId + "&nparams=" + nparams, fnWhenDone);
}

function objPopUp(obj)
{
    objx = $get(obj);
    objx.style.position = "absolute";
    objx.style.width = objx.offsetWidth;
    InLinePopUp(objx.id, null, null, false)
}

function InLinePopUp(popUpId, obsah, obj, hideWhenOut)
{

	if(BarISPage.myOS() == BarISPage.OS_IPHONE || typeof(iPhone) !== 'undefined')
	{
	
		//alert(popUpId +","+ obsah +","+ obj +","+ hideWhenOut);
	/*
		var objIn = getE(popUpId);
		var popUp = getE('popUp');
		
		popUp.innerHTML = objIn.innerHTML + popUp.innerHTML;
		jQT.goTo($('#popUp'), 'slideup');
		//location.href='#info';
		*/
	}
	
	//else
	{
		var x
		var y
		InLinePopUp.hideWhenOut = true
	/*	if(Ext != null)
		{
			alert(Ext.fly(doc).getXY())
		}*/
	/*	if(navigator.appName == "Microsoft Internet Explorer") // rychly patch - Jano neskor prerobi na extJs popupmenu
		{
			x += 264
			y += 230
			//alert(EventObject.getXY())
		}*/
		if(obsah == null)
		{
			var objIn = getE(popUpId);
			if(objIn == null )
				return;
			objIn.onmouseover = function(){PopUpOn(this)}
			if(hideWhenOut != null)
				InLinePopUp.hideWhenOut = hideWhenOut
				
			if(BarISPage.myOS() == BarISPage.OS_IPHONE || typeof(iPhone) !== 'undefined')
			{
				objIn.onclick = function(){PopUpOff()};
				setTimeout(function(){PopUpOff()},3000);
			}
			else
			{
				objIn.onmouseout = function(){PopUpOff()}
			}
		}
		else
		{
				var inData = getE("inlineData");
				inData.innerHTML = obsah;
				var objIn = getE(popUpId);
		}

		if(mouseCapturingOn)
		{
			x = xMousePos
			y = yMousePos
		}
		else
		{
			e = window.event
			if(  e != null && e.clientX != null && e.clientY != null)
			{
				x = e.clientX + document.body.scrollLeft
				y = e.clientY + document.body.scrollTop
			}			
		}
		try{	
			objIn.style.display = "table"
		}
		catch(err){
		}
		
	/*
		if(yMousePos + inData.offsetHeight > document.body.clientHeight)
		{
			inData.style.overflow = 'auto';
			inData.style.width = inData.offsetWidth + 16 + "px";
			inData.style.height = document.body.clientHeight - y + "px";
		}
	*/
		y -= 8;
	//	PopUpOn(objIn,x+document.body.scrollLeft,y+document.body.scrollTop);
		if(obj != null)
		{
			var pos = getAbsolutePosition(obj)
			if( pos.x != null && pos.y != null )
			{
				x = pos.x
				y = pos.y
			}
		}
		
		if((x + objIn.offsetWidth) > document.body.clientWidth) 
			x = x - objIn.offsetWidth + 8;
		else 
			x -= 8;
			
		PopUpOn(objIn, x, y);
	}
}



function buble(nid, nparams, obj, alwOpen)
{
	var x
	var y
	var objIn = null;
	
	if(nid != null)
	{
			objIn = getE('bublina');
			if(objIn == null)
			{
				var newDiv = document.createElement("div");
				newDiv.setAttribute('id', 'bublina');
				newDiv.setAttribute('class', 'bublina');
				
				document.getElementsByTagName("BODY")[0].appendChild(newDiv);				
				//obj.parentNode.appendChild(newDiv);		
				
				objIn = newDiv;
			}
			
			if(isNaN(nid))
			{
				newDiv.innerHTML = nid;
			}
			else
			{
				if(nparams.indexOf('$objId') == -1) nparams = '$objId;bublina;fnWhenDone;PosBuble(\'bublina\')$' + nparams;
				
				if(typeof(iPhone) !== 'undefined')
				{
					Detail(nid,nparams);
				}
				else
				{
					iDetail(nid,nparams);
					return;
				}
			}
	}
	
	try
	{	
		objIn.style.display = "table !important";
		if(!alwOpen)
		{
			setTimeout(function() { CloseBuble(); },5000);
		}
			objIn.onclick = function() { CloseBuble(); };
	}
	catch(err)
	{
		alert('Chyba.');
	}
	
	if(obj != null)
	{
		var pos = getAbsolutePosition(obj)
		if( pos.x != null && pos.y != null )
		{
		  x = pos.x
		  y = pos.y
		}
	}else{
		if(mouseCapturingOn)
		{
			x = xMousePos;
			y = yMousePos;
		}
		else
		{
			e = window.event;
			if(typeof(e) !== 'undefined')
			{
				x = e.clientX + document.body.scrollLeft;
				y = e.clientY + document.body.scrollTop;
			}
		}
	}
			
	objIn.style.left = x + "px";
	objIn.style.top = y + "px";
	
	//setTimeout(function() { PosBuble(objIn); },1000);
}

function PosBuble(objIn)
{

	
	if( typeof objIn != 'object' )
		objIn= getE(objIn);

	var x = objIn.offsetLeft;
	var y = objIn.offsetTop;
	
	if(x + objIn.offsetWidth > document.body.clientWidth) 
	{
		x = document.body.clientWidth - objIn.offsetWidth;
	}
	
	if(y + objIn.offsetHeight > document.body.clientHeight) 
	{
		
			var pageY;
			if(typeof(window.pageYOffset)=='number') {
			   pageY=window.pageYOffset;
			}
			else {
			   pageY=document.documentElement.scrollTop;
			}
	
		y = document.body.clientHeight + pageY - objIn.offsetHeight;
	}
	
	
	
	objIn.style.left = (x-10) + "px";
	objIn.style.top = y + "px";
	objIn.style.height = objIn.offsetHeight+30;
	objIn.style.display = 'table';
}

function CloseBuble()
{
	if(getE('bublina') != null) 
		getE('bublina').parentNode.removeChild(getE('bublina'));
}

function DmsAction(action,rid,retControl,submit)
{  
  if( rid == null || rid == '' )
  {
	alert('Nie je vybrany dokument.');
	return;
   }
     
  if( action == null || action == '' )
  {
	alert('Ziadna akcia k dispozicii.');
	return;
   }
  MyWindowOpen(GetRootPath() +  '/Moduly/BArchive/Forms/DmsAction.aspx?aid=' + action + '&rid=' + rid +  '&control=' + retControl + '&submit=' +  submit ,'MoveAction',450,250);   
   return false;
}

function switchItem(obj, obr, setC, setV, Stav)
{
	if(obj)	hideItem(obj,'',Stav);
	
	//if(BarISPage.myBrowser()==1)
	if(BarISPage.myOS() == BarISPage.OS_IPHONE || typeof(iPhone) !== 'undefined')
	{
    if(obr.tagName == undefined)
        obr = obr.nextSibling 
	}
	
	if(obr != null)
	{
	if( obr.src.indexOf("minus") != -1 || Stav) 
		{
			obr.src = obr.src.replace(/minus/,"plus");
			var miniStav = 0;
		}
		else
		{
			obr.src = obr.src.replace(/plus/,"minus");
			var miniStav = 1;
		}
	}
	if(setC)
	{
		var x = getCookie(setC, "")
		if(x!='') x = x.split(";")
		for(var i=0; i<x.length; i++)
		{
			if(x[i].split(",")[0] == setV) {
				x[i] = setV + "," + miniStav;
			break
			}
			
		}
		setCookie(setC, x.join(";"), 5645647)
	}
	
}

function hideItem(obj,clearInput,Stav)
{
   
    if( typeof obj != 'object' )
            obj = getE(obj);

	if( obj != null)
    {
		
		if(BarISPage.myBrowser()==1)
		{
			if(obj.tagName == undefined)
				obj = obj.nextSibling // Toto nikto nezarucuje ze to bude dut vzdy. Ak to blbne, tak pravdepodobne tymto.
		}
	
		if(obj.style == undefined) obj = obj.nextSibling; //ak najdeny object nema property style najdem dalsi (Safari)
	  
	    if((obj.style.display == '' && Stav != 1) || Stav == 0)
	    {
		    obj.style.display='none'
		    if( clearInput)
		        obj.value = '';		    
	        return false;
	    }
	    else
	    {
		    obj.style.display=''
		    if( clearInput)
		        obj.focus();
		    return true;
	    }
	}
}

function hideClass(fromId,css,Stav,noImg)
{
var obj = new Array();

	var myobj = document.getElementById(fromId);
	if(myobj != null)
	obj = myobj.getElementsByTagName("*");
	
	for (i=0; i<obj.length; i++) 
	{
		if (obj[i].className==css) 
		{

			if( obj[i] != null )
			{

			
				if((obj[i].style.display == '' && Stav != 1) || Stav == 0)
				{
				    if(noImg)
					obj[i].style.display='none'
					else
					switchItem(obj[i], document.getElementById('i' + obj[i].id),null,null,0);
				}
				else
				{
                    if(noImg)
					obj[i].style.display=''
					else
					switchItem(obj[i], document.getElementById('i' + obj[i].id),null,null,1);
				}
				
			}
		
		
		}
	}
}


//var hideStkStep = 10
//var hideStkTime = 10
function hideStk(obj, item, itemState)
{
	var stkBody = getE('stk' + item)
	if(stkBody.style.display == '')
	{
//		hideStkAnim(item, hideStkStep)
		stkBody.style.display='none'
		getE(itemState).value=2;
		obj.src = "images/system/shift_dn.gif"
		obj.title = "show"
	}
	else
	{
		stkBody.style.display=''
		getE(itemState).value=1;
		obj.src = "images/system/shift_up.gif"
		obj.title = "hide"
	}
}
/*
function hideStkAnim(item, n, vyska)
{
	var stkBody = getE('stk' + item).rows[1]
	n--
	if(n == 0)
	{
		stkBody.style.display='none'
		stkBody.style.height = "auto"
		return
	}
	
	if(vyska == null) vyska = stkBody.offsetHeight
	stkBody.style.height = Math.round(vyska / hideStkStep * n) + "px"
	setTimeout("hideStkAnim('"+item+"',"+n+","+vyska+")", hideStkTime)
}
*/
function PLSQL(id,nparams)
{		
	var url = GetRootPath() + "/Moduly/Common/Forms/PLSQL.aspx?id=" + id + "&nparams=" + nparams;
//	alert(url);
	MyWindowOpen(url,'UF',320,50,'no','no');
}

function changeClass(obj, mode)
{
	var baseClass
	var poz = obj.className.indexOf("ROERR")

	if(poz == -1) poz = obj.className.indexOf("ERR")
	if(poz == -1) poz = obj.className.indexOf("RO")
	if(poz == -1) baseClass = obj.className
	else baseClass = obj.className.substr(0,poz)
	
	obj.className = baseClass + mode
	if(mode == "RO" || mode == "ROERR") obj.readOnly = true
	else obj.readOnly = false
}

function popUpMenu(id, popis, width, cssclass)
{

	if(width == null) width = 100
	if(cssclass == null) cssclass = 'popUpMenu'
	var temp = '<TABLE class="'+cssclass+'" id="s'+id+'" style="width:'+width+'px" CELLSPACING="0" onmouseover="PopUpItemOn()" onmouseout="PopUpItemOff()">'
	
	for(var i=0; i<popis.length; i++){
		temp += '<TR><TD><A href="javascript:void(0)" onclick="popupOff();'+ id +'('+ i +')">'+ popis[i] +'</A></TD></TR>'
	}
	temp += '</TABLE>'
	InLinePopUp("s"+id, temp);
}


var progressTimerID;
var perc

function startProgressBar(msec, start,fnc)
{
	perc = start
	progressTimerID=window.setInterval(fnc, msec)
}

function progressBar(stav, bar, sirka, vyska)
{
	var sirkaNum = 46
	var sirkaProg = Math.round((sirka - sirkaNum - 4) / 100 * stav)
	getE(bar).innerHTML = '<TABLE cellspacing="0" style="width:'+sirka+'px;height:'+vyska+'px;padding:0px;border:solid 1px gray"><TR><TD><DIV style="width:'+sirkaProg+'px;height:100%;border:solid 1px green;background-color:#90FF84"></DIV></TD><TD align="right" width="'+sirkaNum+'">'+stav+'%</TD></TR></TABLE>'
}


function uParam(name,url)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
 
 
  if(typeof url != 'undefined') result = url;
  else result = window.location.href;
 
  
  var results = regex.exec( result );
  if( results == null )
    return "";
  else
    return results[1];
}

function getParam(prem,nparams)
{
	if(nparams==null)
	{
		var url = unescape(location.search.substr(1).replace(/\+/g, " "))
		var param = url.split("&")
		var nparams = ""				
		for(var n = 0; n < param.length; n++)
		{			    
			var hodnoty = param[n].split("=")
			if(prem == null || "nparams" == hodnoty[0])
				eval(hodnoty[0] + "='" + hodnoty[1].replace(/\'/g,"\\\'") + "'")
			else
				if(prem == hodnoty[0]) return hodnoty[1]
		}
	}
	var nparam = nparams.split(";")
	var pocet = nparam.length
	if(pocet < 2) return false
	for(n = 0; n < pocet; n+=2)
	{
		if(prem == null)
			eval(nparam[n] + "='" + nparam[n+1].replace(/\'/g,"\\\'") + "'")
		else
			if(prem == nparam[n]) return nparam[n+1]
	}
	return false
}

function setNparam(prem, val, url)
{
	if(url == null)
		url = unescape(location.href.replace(/\+/g, " "))
	var pos = url.search(/nparams=/) + 8
	if(pos == 7)
	{
		if(url.search(/\?/) == -1) return url + "?nparams=" + prem + ";" + val
		return url + "&nparams=" + prem + ";" + val
	}
	return url.substr(0, pos) + prem + ";" + val + ";" + url.substr(pos)
}

function unsetNparam(prem)
{
    var url = unescape(location.href.replace(/\+/g, " "))
    var pos = url.search(/nparams=/) + 8
    if(pos == 7 || url.indexOf(prem) == -1) return url
    else
    {
	    var end = url.indexOf("&", pos)
	    var params = end == -1 ? url.substring(pos) : url.substring(pos, end)
	    var data = params.split(";")
	    if (data.length == 0) return url
	    if (data.length % 2 == 1) data.length -= 1
	    var backUrl = url.substring(0, pos)
	    backUrl += data[0] != prem ? data[0] + ';' + data[1] : ''
	    for (i=2; i<data.length; i+=2)
	    {
		    backUrl += data[i] != prem ? ';' + data[i] + ';' + data[i+1] : ''
	    }
	    backUrl += end == -1 ? "" : url.substring(end)
	    return backUrl
    }
}

function DoklExport(rid,typdokl)
{
	window.location =  GetRootPath() + '/DataExport.ashx?td=' + typdokl + '&nparams=rid;' + rid;
}

function myAlert(typ,obsah,reload,timeout)
{
	if(!isPageLoad) { addStartEvent(function(){myAlert(typ,obsah,reload,timeout)}); return }
	
	if( typeof(iPhone) !== 'undefined' ) 
	{
		alert(obsah);
		return;
	}
		

	var extIcon;
	switch(typ)
	{
		case 'alert': head = 'Upozornenie'; obr = 'Alert.gif'; extIcon = "ALERT"; break
		case 'info': head = 'Inform&#225;cia'; obr = 'Info.gif'; extIcon = "INFO"; break
		case 'hint': head = 'Inform&#225;cia'; obr = 'Info.gif'; extIcon = "INFO"; break
		case 'error': head = 'Chyba'; obr = 'Alert.gif'; extIcon = "ERROR"; break
		default: head = typ; obr = 'Info.gif'; extIcon = "INFO";break
	}
	if(typeof Ext != 'undefined')
	{
		Ext.MessageBox.show
		({
			title: head,
			msg: obsah,                                                                        
			icon : eval("Ext.MessageBox."+extIcon),
			buttons: Ext.Msg.OK
		})
		return
	}
	var onClk = "myAlertDiv.style.visibility='hidden'"
	var clrTimer = ""
	if(timeout)
	{
		myAlertTimerID = setTimeout(onClk, timeout)
		clrTimer = ";clearTimeout(myAlertTimerID)"
	}

	if(reload == true) onClk += ";window.location.href=window.location.href"
//	var temp = '<TABLE id="ma" class="myAlert" cellpadding="0" cellspacing="0"><TR><TD><TABLE cellspacing="0"><TR><TH colspan="2">' + head + '</TH></TR><TR><TD width="60"><IMG SRC="Images/System/' + obr + '" ALT=""></TD><TD>' + obsah + '</TD></TR><TR><TD colspan="2"><BUTTON onClick="tempDiv.innerHTML=\'\'" id="myAlertOK">OK</BUTTON></TD></TR></TABLE></TD></TR></TABLE>'
	var obsah = '<TABLE id="ma" class="myAlert" cellspacing="0"><COL width="60" /><TR><TD><TR><TH colspan="2">' + head + '</TH></TR><TR><TD><IMG SRC="/Images/System/' + obr + '" ALT="" /></TD><TD>' + obsah + '</TD></TR><TR><TD colspan="2"><BUTTON onClick="'+onClk+clrTimer+';return false" id="myAlertOK">OK</BUTTON></TD></TR></TABLE>'

	myAlertShow(obsah)
}

function myAlertShow(obsah)
{
	myAlertDiv = getE("myAlert")
	if(myAlertDiv == null)
	{
		var myAlert = document.createElement("div");
		myAlert.id = "myAlert"
		document.getElementsByTagName("BODY")[0].appendChild(myAlert)
		myAlertDiv = getE("myAlert")
	}
	myAlertDiv.innerHTML = obsah

	CenterElement("ma")
	myAlertDiv.style.visibility = "visible"
	getE("myAlertOK").focus()
}

function isExtJs()
{
	if(typeof Ext != 'undefined') return true
	return false
}

function CenterElement(objId)
{
	if(!isPageLoad) { addStartEvent(function(){CenterElement(objId)}); return }
	var obj = getE(objId)
	obj.style.left = (document.body.clientWidth - obj.offsetWidth)/2 + document.body.scrollLeft + "px";
	obj.style.top = (document.body.clientHeight - obj.offsetHeight)/2 + document.body.scrollTop + "px";
}

function createFlashMarkup(width,height,uri,innerId)
{
 var embed = document.createElement('embed');
 embed.setAttribute('width',width);
 embed.setAttribute('height',height);
 embed.setAttribute('src',uri);

 var div = document.getElementById(innerId);
 document.getElementsByTagName('body')[0].replaceChild(embed,div); 
}

function HFieldcollect()
{
	//alert('aaa');

}

function WebMail(from,to,subject,ctrlID,cc,attachment)
{	
	var nparams = 'xxx;xxx';
	if(from != null)
	nparams += ';from;' + from;
	if(to != null)
	nparams += ';to;'+ to;
	if(subject != null)
	nparams += ';subject;' + subject;
	if(ctrlID != null)
	nparams += ';ctrlID;'+ ctrlID; 
	if(cc != null)
	nparams += ';cc;'+ cc;
	if(attachment != null)
	nparams += ';att;' + attachment;
	
	Detail(1076,nparams,false);
}

function PrintSticker(nid)
{
	Detail(nid,nparams + ';previewmode;print',inline,width,height);
}

function PrintMe()
{
	print();
}

function MailSticker(nid,nparams,to,subject)
{
	Detail(nid,nparams + ';previewmode;mail;to;' + to + ';subject;' + subject,false);
}

function stripTags(oldString)
{
	return oldString.replace(/<[^>]*>/g, "");
}


function existInArray(pole, hodnota)
{
    if(pole == null)
        return -1;
    for(var i = 0; i < pole.length; i++)
        if(pole[i] == hodnota) return i        
    return -1
}

function CrmChoose(katid,nparams)
{
	maxparams = 'id;' + katid;
	if( nparams != null )
		maxparams = maxparams + ';' + nparams;
	Detail(1079,maxparams);	
}

function tabs(tabsId, classOff)
{
	var tabObj
	if(tabsId == null || tabsId == "")
        tabObj = getE("tdTabs");
    else
		tabObj = getE(tabsId)
    if(tabObj == null) return;
    if(classOff == null || classOff == "") classOff = "tabOff"

	tags = tabObj.getElementsByTagName("DIV")
	for(i=0;i<tags.length;i++)
	{
		if(tags[i].getElementsByTagName("IMG").length > 1) continue
		if(tags[i].getElementsByTagName("IMG")[0] == null || tags[i].className != classOff) continue
		tags[i].getElementsByTagName("IMG")[0].style.filter = "gray"
		tags[i].onmouseover = tabColor
		tags[i].onmouseout = tabBW
		tags[i].unselectable = "on"
	}
}
function tabColor()
{
	this.getElementsByTagName("IMG")[0].style.filter=""
//	this.className="tabOffOver"
	this.style.color="black"
}

function tabBW()
{
	this.getElementsByTagName("IMG")[0].style.filter="gray"
	this.style.color=""
}

function stool(id, e)
{
	var inlineData = getE("inlineData")
	var tooltip = getE("tooltip")
	if(id == null)
	{
		if(tooltip != null) tooltip.style.visibility = "hidden"
		return
	}

	obsah = "<table class='tooltip'><tr><td class='tooltipHead'>" + evnt[id][2] + "</td></tr><tr><td>" + evnt[id][3] + "</td></tr><tr><td class='tooltipPartner'>" + evnt[id][0] + " - " + evnt[id][1] + " :: " + evnt[id][4] + "</td></tr></table>"

	if(!e) var e = window.event

	if(tooltip == null)
	{
		var tooltip = document.createElement("div");
		tooltip.id = "tooltip"
		tooltip.style.position = "absolute"
		inlineData.appendChild(tooltip)
	}
	tooltip.innerHTML = obsah
	tooltip.style.left = e.clientX + document.body.scrollLeft
	tooltip.style.top = e.clientY + document.body.scrollTop + 16
	tooltip.style.visibility = "visible"
	inlineData.style.visibility = "visible"
}

function sTool(id, e)
{
	if(id == null)
	{
		tooltip.style.visibility = "hidden"
		zobrazSelecty()
		return
	}
	tooltip = getE(id)

	if(!e) var e = window.event

	showPopUp(id, e)
	//tooltip.style.left = e.clientX + document.body.scrollLeft
	//tooltip.style.top = e.clientY + document.body.scrollTop + 16
	//tooltip.style.visibility = "visible"
}

function showPopUp(objId, e)
{
	if(objId == null)
	{
		if(popUp != null) popUp.style.visibility = "hidden"
		zobrazSelecty()
		return
	}

	popUp = getE(objId)

	if(!e) e = window.event

	var presahX = popUp.offsetWidth - document.body.clientWidth + e.clientX
	var posX = e.clientX + document.body.scrollLeft
	if(presahX > 0) posX -= presahX
	if(posX < document.body.scrollLeft) posX = document.body.scrollLeft

	var presahY = popUp.offsetHeight - document.body.clientHeight + e.clientY
	var posY = e.clientY + document.body.scrollTop + 16
	if(presahY > 0) posY -= presahY
	if(posY < document.body.scrollTop) posY = document.body.scrollTop

	popUp.style.left = posX + "px"
	popUp.style.top = posY + "px"
	
	if(VisibleLayerName != null) menuOff()
	popUp.style.visibility = "visible"
	skrySelecty()
}

function itemOver()
{
	this.className = "tblSlideMenuOn"
}

function itemOut()
{
	this.className = "tblSlideMenuOff"
}

function slideMenu(obj)
{
	var tags = getE(obj).getElementsByTagName("TD")
	for(i=0;i<tags.length;i++)
	{
		tags[i].onmouseover = itemOver
		tags[i].onmouseout = itemOut
		tags[i].unselectable = "on"
	}
}

function myTitle(id,stk)
{
	if(id == null)
	{
		if(objTitle) objTitle.className = "off"
		return
	}
	if(stk == null) stk = 1109
	objTitle = getE(id)
	if(window.event) e = window.event

	var pozice = findElement('dvTB_B_MP_'+stk+'_WebGrid1_')
	var pushX = document.body.scrollLeft
	var pushY = document.body.scrollTop
	if(pozice) { pushX = -pozice.x; pushY = -pozice.y }
	objTitle.style.left = e.clientX + pushX
	objTitle.style.top = e.clientY + 16 + pushY
	objTitle.className = "on"
}


function registerError(location,e,customMessage)
{
  var message = location + ':';
  var iPhoneDebug = false;
  if( e != null )
    message =  message + ' ' + e.message;
  message =  message + ' ' + customMessage;
  
  if(typeof(iPhone) != 'undefined' )
  {
  if(iPhone.Debug)
	alert('JS error: '+message);
  }
  
    if( barISPage.adminMode)
      myAlert('alert', message);
  else
    window.status = message;
}

function runJS(str)
{
try{ 
	var patt_start = /<script type=\"text\/javascript\">/i;
    var patt_end = /<\/script>.*/i;

	var res = str.replace(/\r\n/g,"")
	var executingLine = '';
	
	
    if(res != undefined || res != null)
    {
        res = ("dummy" + res).split(patt_start)

	    for(var n = 1; n < res.length; n++)
	    {
	        //executingLine = res[n].replace(patt_end, "");
	        
	        executingLine = res[n].substring(0,res[n].toLowerCase().indexOf("</script>"));
			eval(executingLine);
	    }
	}
}
catch(e)
{    
	registerError('runJs',e,executingLine );
}
}
function addLoadEvent(func)
{
	addStartEvent(func)
}

function addStartEvent(func, first)
{
    if(isPageLoad)
    {
        func = String(func).replace(/function *\x28\x29/g,"")
        eval(func)
		//alert(func)
        return
    }

  var oldonload = window.onload;
  if (typeof window.onload != 'function') { window.onload = func; }
  else
  {
    window.onload = function()
    {
		if(first) func();
		if(oldonload) { oldonload(); }
		if(!first) func();
    }
  }
}

function maxVal(arr)
{
	var max = arr[0]
	for(n = 0; n < arr.length; n++)
		max = Math.max(max, arr[n])

	return max
}

function cenaFormat(suma, noCommas)
{
	suma = Math.round(suma*100)/100 + ""
	var posCom = suma.search(/\./)
	if(posCom == -1) return addCommas(suma + ",00")

	suma = (suma+"00").replace(/\./, ',').substr(0, posCom+3)
	return (noCommas) ? suma : addCommas(suma)
}

function addCommas(nStr, sep)
{
	if(sep == null) sep = " "
	nStr += '';
	x = nStr.split(',');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + sep + '$2');
	}
	return x1 + x2;
}

function jas(farba, percento)
{
	R = from10toradix(parseInt(255 - (255-parseInt(farba.substr(0, 2), 16)) * percento / 100), 16)
	G = from10toradix(parseInt(255 - (255-parseInt(farba.substr(2, 2), 16)) * percento / 100), 16)
	B = from10toradix(parseInt(255 - (255-parseInt(farba.substr(4, 2), 16)) * percento / 100), 16)

	return(R+G+B)
}

function from10toradix(value,radix)
{
    var retval = '';
    var ConvArray = "0123456789ABCDEF";
	var dlzka = 2;
	var i;

    if (isNaN(value)) return('A0');
    for(i = 0; i < dlzka; i++)
	{
        retval = ConvArray.charAt(value % radix) + retval;
        value = Math.floor(value / radix);
	}
    return retval;
}

function changeDF(obj,editable,clear)
{
    obj.readOnly=!editable; 
    if( clear != false )
        obj.value=''
    if(editable) changeClass(obj, "")
    else changeClass(obj, "RO")
}

function showPic(obj, e)
{
	var inData = getE("inlineData")
	if(obj == 'hide')
	{
		inData.style.visibility = "hidden"
		return
	}

	if(!e) e = window.event

	inData.style.left = e.clientX + document.body.scrollLeft
	inData.style.top = e.clientY + document.body.scrollTop + 16
	inData.innerHTML = '<img src="' + obj.src + '">'
	inData.style.visibility = "visible"
}


function FillPopUpCombo(obj,id_cis,ep)
{       

    if(obj.options.length == 0 )
    {    
       var myConn = new XHConn();
        var fnWhenDone = function (oXML) 
		{
			var values = oXML.responseText.split(String.fromCharCode(164));			
			for(n = 0; n < values.length/2; n++)
            {                
	            obj.options[n] = new Option(values[2*n], values[2*n+1]);
            }
            obj.click()
		}							
		if (!myConn) 
			alert("XMLHTTP not available. Try a newer/better browser.");		
		var url = "PopUpKoder.ashx?mode=combo&id_cis=" + id_cis;
		if( ep != null )
		 url = url + '&ep=' + ep;
		myConn.connect(url, "POST","", fnWhenDone);
		obj.options[0] = new Option("WAIT...", "WAIT...");
		obj.options[1] = new Option("...", "...");
		obj.options[2] = new Option("..", "..");
		obj.options[3] = new Option(".", ".");
		return false;
	}			
    return true;
}


function CartAdd(kod_id,pocet,refresh)
{
    CartAction('a',kod_id,pocet,0,refresh); 
        
}

function CartRemove(id_r,refresh)
{    
    CartAction('r',0,0,id_r,refresh);    
}

function CartAction(action,kod_id,pocet,idr,refresh)
{
    if( pocet == null) 
        pocet = 1;    
    
    var myConn = new XHConn();
    var fnWhenDone = function (oXML) 
	{
	    alert(oXML.responseText);
	    window.location.reload();
	}	
	if (!myConn) 
			alert("XMLHTTP not available. Try a newer/better browser.");		
	var url = 'Cart.ashx?nparams=action;' + action + ';kod_id;' + kod_id + ';pocet;' + pocet + ';idr;' + idr + ';dummy;blah' ;	
    myConn.connect(url, "GET","", fnWhenDone);
}

function TextMaxLength(id, max)
{
	var textMsg = getE(id)
	textMsg.onpropertychange=function(){MaxLengthCnt(this, max)}
	textMsg.onclick=function(){MaxLengthCnt(this, max)}
	textMsg.onmousemove=function(){MaxLengthCnt(this, max)}
	textMsg.onblur=function(){MaxLengthCnt(this, max)}
	textMsg.onkeyup=function(){MaxLengthCnt(this, max)}
	textMsg.onfocus=function(){MaxLengthCnt(this, max)}
	textMsg.onchange=function(){MaxLengthCnt(this, max)}
	textMsg.onafterupdate=function(){MaxLengthCnt(this, max)}
}

var MaxLengthCntLock = false;
function MaxLengthCnt(obj, max)
{
	if(!MaxLengthCntLock)
	{
		MaxLengthCntLock = true;
		if(obj.value.length > max)
		{
	//		alert("Pole nesmie byť dlhšie ako " + max + "znakov!")
			obj.value = obj.value.substring(0, max)
		}
		MaxLengthCntLock = false;
	}
}

/* tovar detail */
function formatuj(id, maxx, maxy)
{
	if(maxx == null) maxx = 220
	if(maxy == null) maxy = 220
	var xwidth
	var xheight
	var obr = getE(id);
	if(!(xwidth = obr.offsetWidth)) return;
	if(!(xheight = obr.offsetHeight)) return;
	if(xwidth > maxx || xheight > maxy)
	{
		var ratio = Math.min(maxx / xwidth, maxy / xheight)						
		obr.style.width = Math.round(xwidth * ratio)
		obr.style.height = Math.round(xheight * ratio)
	}
}

function BindToolTips()
{
	var subMenus = getE("subMenu");
	if( subMenus == null )	
	        return;	        
	subMenus = subMenus.getElementsByTagName("A");	
	objTT = null;
	for(n = 0; n < subMenus.length; n++)
	{
	    objTT = subMenus[n].getElementsByTagName('SPAN');
	    if(objTT != null && objTT.length > 0 )	            
		    subMenus[n].title = objTT[0].innerText // --> takto to bude BindToolTip(submenus[n],objTT[0])
		    
	}
}

function setFormEnter(locationId, buttId)
{
    var location =  getE(locationId)
    if( location == null) return;
	var inputs = location.getElementsByTagName("input")	
	for(var n = 0; n < inputs.length - 1; n++)
	{
		eval('if(inputs[n].type == "text") inputs[n].onkeydown = function(e) { if(!e) e = event; if(e.keyCode == 13) { inputs[' + (n+1) + '].select(); return false; } }')
	}
	if(buttId != null)
	{
	    var buttObj = getE(buttId+"_tbl")
	    if(buttObj == null) buttObj = getE(buttId)
	    if(buttObj == null || buttObj.onclick == null )  return false;	    
		var fSubmit = buttObj.onclick;				
		if(inputs[n].type == "text") inputs[n].onkeydown = function(e) { if(!e) e = event; if(e.keyCode == 13) { fSubmit(); return false } }
	}
	return true;
}

function executeOnClick(buttId)
{

	if(buttId != null)
	{
	    var buttObj = getE(buttId+"_tbl")
	    if(buttObj == null) buttObj = getE(buttId)
	    if(buttObj == null || buttObj.onclick == null ) { alert(buttObj); return false;	 }   
		var fSubmit = buttObj.onclick;				
		alert('idem submitovat');
		fSubmit();
	}

}

function setCookie(name, value, exp, path, domain, secure)
{
	if(name=='') return;
	var cookie=name+'='+escape(value);
	if(value=='')
	{
		cookie+='; expires='+new Date((new Date()).getTime()-1).toGMTString();//zmaz cookie
	}
	else
	{
		if(exp) cookie+='; expires='+new Date((new Date()).getTime()+exp*(1000*60*60)).toGMTString();//hod na milisec
		else cookie+='; expires='+new Date((new Date()).getTime()+(1000*60*60*24*365)).toGMTString();//rok na milisec
		if(path) cookie+='; path='+path;
		if(domain) cookie+='; domain='+domain;
		if(secure) cookie+='; secure';
	}
	document.cookie=cookie;
}

function getCookie(name, def)
{
	var cookies=document.cookie;
	if(cookies=='') return def;
	var from=cookies.indexOf(name+'=');
	if(from<0) return def;
	var to=cookies.indexOf(';',from);
	if(to<0) to=cookies.length;
	return unescape(cookies.substring(from+name.length+1,to));
}

function calendarTitles(id)
{
	var n = 0;
	var fwd;
	var datum = '';
	var bunky = getE(id).getElementsByTagName("TD")
	calD.setHours(calD.getUTCHours())
	for(var i = (calSobota+calNedela+6)*2+1; i < bunky.length; i++)
	{
		if(!bunky[i].getElementsByTagName("DIV").length)
		{
		    datum = date2string(calD);
			bunky[i].title = datum
			eval("bunky[i].onclick = function() { Detail(1084,'k;0;date;"+datum+"') }")			
		}
		bunky[i].style.cursor = "pointer"
		fwd = 1;
		if(n == 4 && !calSobota) { n++; fwd++; }
		if(n == 5 && !calNedela) { n++; fwd++; }
		calD.setDate(calD.getDate()+fwd)
		if(n == 6) { calD.setDate(calD.getDate()-7); calD.setMinutes(calD.getMinutes()+calTimeStep); i++; n=0 }
		else n++
	}
}



function toDate(str, mode)
{
	var theDate = new Date(str * 1000); 
	
    d2 = new Date ( theDate );
	d2.setMinutes ( theDate.getMinutes() + (theDate.getTimezoneOffset()) );
	
	theDate = d2;
	
	
	//alert(str * 1000 + ' - ' + HtmlOut.getCurrentTimestamp());
	dateString = theDate.toGMTString();
	
	if(!mode) return theDate;
	
	
	var d = theDate.getDate()		//	Returns the day of the month (from 1-31)
	var Y = theDate.getFullYear(); 	//	Returns the year (four digits)
	var M = theDate.getMonth()+1;		//	Returns the month (from 0-11)
	
	var Hod = theDate.getHours();	//	Returns the hour (from 0-23)
	var Min = theDate.getMinutes();	//	Returns the minutes (from 0-59)
	var Sec = theDate.getSeconds(); //	Returns the seconds (from 0-59)
	
	dateString = d + '.' + M + '.' + Y + ' ' + Hod + ':' + Min + ':' + Sec;
	
	
	return dateString;
}

function ActualDate(mode)
{
	// datum
	var currentDate = new Date()
	var day = currentDate.getDate()
	var month = currentDate.getMonth()
	var year = currentDate.getFullYear()
	//document.write("<b>" + day + "/" + month + "/" + year + "</b>")

	//cas
	var currentTime = new Date()
	var hours = currentTime.getHours()
	var minutes = currentTime.getMinutes()
	var sec = currentTime.getSeconds()
	if (minutes < 10)
	minutes = "0" + minutes

	//document.write("<b>" + hours + ":" + minutes + " " + "</b>")
	
	return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + sec

}

function date2string(calD, alsoTime)
{
	var datum = ((calD.getDate() < 9) ? "0" : "") + calD.getDate() + "." + ((calD.getMonth() < 9) ? "0" : "") + (calD.getMonth()+1) + "." + calD.getFullYear()
	if(alsoTime == null || alsoTime == true)
		datum += " " + ((calD.getHours() < 10) ? "0" : "") + calD.getHours() + ":" + ((calD.getMinutes() < 10) ? "0" : "") + calD.getMinutes()
	return datum
}

function xpButton(popis, onClk, img, title, bCssClass, targetId)
{
	if(img != null && img != "") img = '<img src="' + GetRootPath() + '/' + img + '" /> '
	else img = ''
	if(title != null) title = 'title="'+title+'" '

	includeCss('imgButt', 'css/buttons/imgButt.css')
	var bCssClassOver = ""
	var bCssClassL = ""
	var bCssClassR = ""
	if(bCssClass != null)
	{
		includeCss(bCssClass, 'css/buttons/'+bCssClass+'.css')
		var bCssClassOver = " " + bCssClass + "Over"
		var bCssClass = " " + bCssClass
		var bCssClassL = " " + bCssClass + "L"
		var bCssClassR = " " + bCssClass + "R"
	}
	else bCssClass = ""
	var buttonHtml = '<table class="imgButt'+bCssClass+'" '+title+'cellpadding="0" cellspacing="0" onClick="'+onClk.replace(/"/g,"'")+'" onMouseOver="this.className=\'imgButtOver'+bCssClassOver+'\'" onMouseOut="this.className=\'imgButt'+bCssClass+'\'"><tr><td class="imgButtL'+bCssClassL+'"></td><td>'+img+popis+'</td><td class="imgButtR'+bCssClassR+'"></td></tr></table>'
	if(targetId != null)
	{
		if(targetId == "html") return buttonHtml
		var butt = document.createElement("span")
		butt.innerHTML = buttonHtml
		getE(targetId).appendChild(butt)
		return butt
	}
	else
		document.write(buttonHtml)
}

function xpButtonClass(obj, newClass)
{
	if(obj == null) return
	includeCss(newClass, 'css/buttons/'+newClass+'.css')
	if(obj.tagName == "SPAN")
		obj = obj.getElementsByTagName("table")[0]
	obj.className = "imgButt " + newClass
	var td = obj.getElementsByTagName("td")
	td[0].className = "imgButtL " + newClass + "L"
	td[2].className = "imgButtR " + newClass + "R"
	obj.onmouseover = function() { this.className = 'imgButtOver ' + newClass + 'Over' }
	obj.onmouseout = function() { this.className = 'imgButt ' + newClass }
}

includeCss.includedCss = new Array()
function includeCss(id, path)
{
//	alert(path);
	if(includeCss.includedCss[id]) return
	var headID = document.getElementsByTagName("head")[0];

	var cssLinks = headID.getElementsByTagName("link")
	for(var n = 0; n < cssLinks.length; n++)
	{
		if(cssLinks[n].href.toLowerCase().search(path.toLowerCase()) != -1)
		{
			includeCss.includedCss[id] = true
			return
		}
	}

	var cssNode = document.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = path;
	cssNode.media = 'screen';
	headID.appendChild(cssNode);

	includeCss.includedCss[id] = true
}

includeJs.includedJs = new Array()
function includeJs(id, path)
{

	var headID = document.getElementsByTagName("head")[0];
	var cssNode = document.createElement('script');
	cssNode.type = 'text/javascript';
	cssNode.src = path;
	headID.appendChild(cssNode);
	
	//document.write('<scr' + 'ipt type="text/javascript" src="' + path + '"></scr' + 'ipt>');

	includeJs.includedJs[id] = true
}

function IncrementDate(dateIn, interval, alsoTime)
{
   
	var isDate = true
	
	if(typeof dateIn == 'string')
	{	    
		dateIn = string2date(dateIn)
		isDate = false;
	}

	dateIn.setMinutes(dateIn.getMinutes()+Number(interval));
    if(isDate)
			return dateIn;
		
	else	
		return date2string(dateIn, alsoTime);
}

function string2date(dateIn)
{
	var myDate = new Date();
	if(dateIn.replace(/ /g, "") == "") return myDate
	var pattern = /\D/
	var arr = dateIn.split(pattern)
	myDate.setDate(1)
	myDate.setMonth(arr[1]-1)
	myDate.setDate(arr[0])
	myDate.setFullYear(arr[2])
	if(arr.length > 3)
	{
		myDate.setHours(arr[3])
		myDate.setMinutes(arr[4])
	}

	return myDate
}

function changeDelay(objIdOd, objIdDo, interval)
{
    var dateIn = string2date(getE(objIdOd).value + " " + getE(objIdOd + "_TM").value)
    if (Number(interval) < 1440) // ak sa jedna o hodiny
        dateIn.setMinutes(dateIn.getMinutes() + Number(interval))
    else {      // ide o pridavanie dni
        dateIn.setDate(dateIn.getDate() + (Number(interval) / 1440) - 1);
        dateIn.setHours(23, 59, 0, 0);
    }
	getE(objIdDo).value = date2string(dateIn, 0)
	getE(objIdDo + "_TM").value = ((dateIn.getHours() < 10) ? "0" : "") + dateIn.getHours() + ":" + ((dateIn.getMinutes() < 10) ? "0" : "") + dateIn.getMinutes()
}

function StoreData(data,name,value,delimiter)
{
    if(!delimiter)delimiter='¤'
    var index=data.indexOf(name)
    if(!data||index<0)
    {
        if(data.length!=0) data+=delimiter
        data+=name+delimiter+value
    }
    else
    {
        var before=data.substring(0,index)
        var lastIndex=data.indexOf(delimiter,index+name.length+1)
        var after=''
        if(lastIndex>0) after=data.substring(lastIndex)
        data=before+name+delimiter+value+after
    }
    return data
}

function switchTab(id, obj, zal) // id DIVu, ktorý chceme zobraziť;  záložka, na ktorú sa kliklo;  pole so zoznamom ID DIVov a meno class
{
 	if(zal['lastZal'] != null) zal['lastZal'].className = zal['class']
	if(obj != null) { obj.className = zal['class']+"Sel"; zal['lastZal'] = obj }
	for(var n = 0; n < zal.length; n++)
	{
		if(zal[n] == id) getE(id).style.display = ""
		else getE(zal[n]).style.display = "none"
	}
}

function getE(id)
{
    if (id) return document.getElementById(id);
    return null;
}

function PopulateComboBox(idCombo, list)
{
    if (!idCombo || !(combo = getE(idCombo))) return
    combo.options.length = 0
    if (!list) return
    for(i=0;i<list.length;i+=2)
    {
        combo.options[i/2] = new Option(list[i],list[i+1])
    }
}

function switchEuroMode(textObj,valObj)
{   
    switch(valObj.value)
    {
        case '0':
           textObj.value = 'Sk';
           valObj.value = '1'; 
           break;
       case '1':
           textObj.value = '&euro;';
           valObj.value = '2'; 
           break;
       case '2':
           textObj.value = '&euro;/Sk';
           valObj.value = '0'; 
           break;       
                
    }         
 //   myAlert('info','Aktivovan reim zobrazovania ' +  textObj.value,true);
}

function PortalMap(pmId)
{    
    var links = getE(pmId).getElementsByTagName('A');
    var tt;
    for( n = 0; n != links.length; n++)
    {
        if( links[n].id.substr(0,4) == 'PAGE' )
        {
            tt = links[n].getElementsByTagName('DIV')[0];           
            if( tt != null  && tt.innerText != '')            
                links[n].parentNode.title = tt.innerText;
             else
                links[n].parentNode.title = links[n].innerText;
        }
     }
    
}


function ShowHint(rid)
{     

	var myConn = new XHConn();	
	var fnWhenDone = function (oXML) 
	{
	    var data = oXML.responseText.split('¤');
	    if( data.length == 1)
	        myAlert('alert',data[0],false);
	    else	    
		    myAlert(data[0],data[1],false);
		document.getElementsByTagName("BODY")[0].style.cursor = "default"
	}		
	if (!myConn) 
		alert("XMLHTTP not available. Try a newer/better browser.");
	else 
	    document.getElementsByTagName("BODY")[0].style.cursor = "wait"	    
	myConn.connect('Common.ashx?action=gethint&ridv=' + rid, 'POST', '', fnWhenDone);

}


function CallTo(rid,idCis,action)
{     

	var myConn = new XHConn();	
	var fnWhenDone = function (oXML) 
	{
	    var data = oXML.responseText;
		document.getElementsByTagName("BODY")[0].style.cursor = "default"
		data = data.split('¤');
		if( data[action] == null || data[action] == '' )
		{
		        alert('Kontaktný údaj nie je uvedený');		        
		        return;
		}
		if( action == 0 )				    		 
		        window.location='callto:' + data[action]
		else if (action == 1) 
		        window.location='mailto:' + data[action]
		
	}		
	if (!myConn) 
		alert("XMLHTTP not available. Try a newer/better browser.");
	else 
	    document.getElementsByTagName("BODY")[0].style.cursor = "wait"	    
	    
	myConn.connect('Common.ashx?action=getcol&col=ip_phone&ridv=' + rid + '&idCis=' + idCis, 'POST', '', fnWhenDone);

}

function numValid(obj, evnt)
{
	if(window.event) // IE
		var key = evnt.keyCode
	else if(evnt.which) // Netscape/Firefox/Opera
	{
		var key = evnt.which
		if(key == 8) return true
	}
	else return true

	if(key == 44 || key == 46)
	{
		if(obj.value.search(/\.|\,/) != -1) return false
		return true
	}
	return key < 58 && key > 47 || key == 13
}

function cDate(dt)
{
    //vstup: "01/01/2000 00:00"
    var myNewDate = String(dt).split(' ');
    var datum = myNewDate[0];
	var cas = myNewDate[1];
    
    datum = myNewDate[0].split('/');
    var den = datum[0];
    var mesiac = datum[1];
    var rok = datum[2];
    
    cas = cas.split(':');
    var hodiny = cas[0];
    var minuty = cas[1];
    
    return new Date(rok,mesiac,den,hodiny,minuty);
 //year, month, date, hour, minute

}

function dateValid(obj, evnt)
{
	if(window.event) // IE
		var key = evnt.keyCode
	else if(evnt.which) // Netscape/Firefox/Opera
	{
		var key = evnt.which
	}
	else return true
	if(key == 8) return true

	if(key == 44 || key == 46)
	{
		var pocetBodiek = 0, i = 0
		while(i < obj.value.length)
		{
			if(obj.value.charAt(i) == ".") pocetBodiek++
			if(obj.value.charAt(i++) == ",") pocetBodiek++
		}
        if(pocetBodiek > 1) return false
		else return true
	}

	return key < 58 && key > 47 || key == 13
}

function disableObj(srcObj)
{
    if( srcObj == null ) return;
	var pocet, inputs, labels, n
	var pocetObj = disableObj.arguments.length
	var chClass = (srcObj.checked) ? "" : "RO"

	for(var i = 1; i < pocetObj; i++)
	{
	    var objN = getE(disableObj.arguments[i])
	    if(objN == null) continue
		inputs = objN.getElementsByTagName("input")
		pocet = inputs.length

		for(n = 0; n < pocet; n++)
		{
			if(inputs[n] == srcObj) continue
			inputs[n].disabled = !srcObj.checked
			if(inputs[n].type == "text")
			{
				changeClass(inputs[n], chClass)
				if(!srcObj.checked) inputs[n].value = ""
			}
		}

		labels = objN.getElementsByTagName("label")
		pocet = labels.length
		for(n = 0; n < pocet; n++)
		{
			labels[n].disabled = !srcObj.checked
		}
	}
}

function upperCase(obj, evnt)
{
	if(window.event) // IE
		var key = evnt.keyCode
	else if(evnt.which) // Netscape/Firefox/Opera
	{
		var key = evnt.which
		if(key == 8) return true
	}
	else return true
	obj.value += String.fromCharCode(key).toUpperCase()
	return false
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function()
{
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function()
{
	return this.replace(/\s+$/,"");
}

var showMiddlePic_delay = 500
var smpTimerID = null
function showMiddlePic(id, obj)
{
	if(smpTimerID != null)
	{
		clearTimeout(smpTimerID);
		smpTimerID = null;
	}
	if(obj != null)
	{
		var pos = getAbsolutePosition(obj)
		var fnc = "showMiddlePicT("+id+", "+pos.x+", "+pos.y+")"
	}
	else
		var fnc = "showMiddlePicT("+id+")"
	
	smpTimerID = setTimeout(fnc, showMiddlePic_delay);
}

function showMiddlePicT(id, x, y)
{
	clearTimeout(smpTimerID);
	smpTimerID = null;

	var existTempPic = getE("tempPic" + id)
	var inData = getE("inlineData")
	if(existTempPic == null)
	{
		var tempPic = document.createElement("img")
		tempPic.id = "tempPic" + id
		tempPic.style.position = "absolute"
		tempPic.src = "GetPrilohu.ashx?skid=" + id + "&typ=0001"
		inData.appendChild(tempPic)
	}
	else
	{
		existTempPic.style.display = ""
		tempPic = existTempPic
	}
	if(x == null) x = xMousePos
	if(y == null) y = xMousePos
	tempPic.style.left = x + 10 + "px"
	tempPic.style.top = y + 10 + "px"
	inData.style.visibility = "visible"
}

function hideMiddlePic(id)
{
	if(smpTimerID != null)
	{
		clearTimeout(smpTimerID);
		smpTimerID = null;
		return
	}

	var prev = getE("tempPic" + id)
	prev.style.display = "none"
	var inData = getE("inlineData")
	inData.style.visibility = "visible"
}

function addInlineElm(obj,newId,elType)
{
  if( elType == 'DIV' )
  {
     var elem = document.createElement('DIV');
     elem.id = newId;
     obj.parentNode.insertBefore(elem, obj.nextSibling);
     return elem;
  }
  else
{
    return addRow(obj,newId);
  }
    
}

function addRow(obj,newId)
{
	var newRow = document.createElement("tr")
	hideItem(newRow)
	while(obj.tagName != "TD") 
    { 
          obj = obj.parentNode 
    }  
	trElm = obj.parentNode;
	trElm.parentNode.insertBefore(newRow, trElm.nextSibling)
	var cellCount = 0;
	var tdArr = trElm.getElementsByTagName("td");
	for(i = 0; i < tdArr.length; i++ )
		cellCount  += tdArr[i].colSpan;

        var newCell  = newRow.insertCell(0)
	newCell.setAttribute("colSpan", cellCount)
	newCell.id = newId

//    var newHeader  = document.createElement('DIV')
//    var newEl  = document.createElement('DIV')
//	newEl.id = newId
//	newCell.appendChild(newHeader)
//    newCell.appendChild(newEl)

	var posX = 0
	var element = obj
    while (element.tagName != "TABLE")
	{
		posX += element.offsetLeft - element.scrollLeft;
		element = element.offsetParent;
    }
	newCell.style.paddingLeft = posX + "px"
	
	return newCell;
}

function addFloatElm(objId)
{
	var newDiv = document.createElement("div")
	newDiv.id = objId
	newDiv.style.position = "absolute"
	newDiv.style.width = "10px"
	document.getElementsByTagName("body")[0].appendChild(newDiv)
	//InLinePopUp(objId)

	return newDiv
}

/* js filter na tbl tasky */
function taskSearch(tblId,chckObj)
{
	var tblId = tblId;
	
		taskSelect = new Array()
		taskSelect["vpraci"] = new Array() 
		taskSelect["tr"] = new Array()
	    taskSelect["tr"] = document.getElementById(tblId).getElementsByTagName("tr");
	    for(var n = 0; n < taskSelect["tr"].length; n++)
	    {
			if(taskSelect["tr"][n].className == 'IbRow0VybCss' || taskSelect["tr"][n].className == 'IbRow1VybCss') taskSelect["vpraci"][n] = true //// IbRow0PtCss urgent
	    }
    
	    for(var n = 0; n < taskSelect["vpraci"].length; n++)
	    {
			if(chckObj.checked && taskSelect["vpraci"][n]) taskSelect["tr"][n].style.display = "none"
			else taskSelect["tr"][n].style.display = ""
	    }
}


/* vyhladavanie v tabulke Ludia v praci nalepka 1424 */

function tableSearch_init(inpId,tblId,chckId)
{
	
	if( typeof ts === 'undefined' )
	{
		ts = new tableSel;
		ts.inputId = inpId;
		ts.tblId = tblId;
		ts.chckId = chckId;
		document.getElementById(ts.inputId).focus();
		ts.init()	
	}
}

function tableSel()
{
}

tableSel.prototype =
{
    init : function()
    {
		inputObj = document.getElementById(this.inputId)
		inputObj.onkeyup = this.inputKeyUp
		chckObj = document.getElementById(this.chckId) 
		chckObj.onclick = this.inputKeyUp 
		tableSelect = new Array()
		tableSelect["text"] = new Array()
		tableSelect["vpraci"] = new Array() 
		tableSelect["tr"] = new Array()
	    tableSelect["tr"] = document.getElementById(this.tblId).getElementsByTagName("tr");
	    for(var n = 0; n < tableSelect["tr"].length; n++)
	    {
			tableSelect["text"][n] = " " + bezdiak(stripTags(tableSelect["tr"][n].innerHTML).toLowerCase())
			if(tableSelect["tr"][n].className != 'IbRow0PtCss' && tableSelect["tr"][n].className != 'IbRow1PtCss') tableSelect["vpraci"][n] = true //// IbRow0PtCss    vpraci
	    }
    },

	inputKeyUp : function()
	{
	    for(var n = 0; n < tableSelect["text"].length; n++)
	    {
			if(tableSelect["text"][n].match(' '+bezdiak(inputObj.value.toLowerCase())) == null) 
			{
			    tableSelect["tr"][n].style.display = "none"
			}
			else if(chckObj.checked && !tableSelect["vpraci"][n]) 
			{
			    tableSelect["tr"][n].style.display = "none"
			}
			else tableSelect["tr"][n].style.display = ""
	    }
	}
}

function selFirst(tblId)
{

	tbl = $get('tbl'+tblId);
	tableSelect = new Array()
	tableSelect["tr"] = tbl.getElementsByTagName("tr");
	firstSkl = "";
	for(var n = 0; n < tableSelect["tr"].length; n++)
	{
		if(firstSkl == "" && tableSelect["tr"][n].style.display=="")
			firstSkl = tableSelect["tr"][n].id;
	}
	
	ChangeSklad(firstSkl.substr(1));

}

function bezdiak(txt)
{
	var sdiak = "áäčďéěíĺľňóôöŕšťúůüýřž";
	var bdiak = "aacdeeillnooorstuuuyrz";
	var tx = "";
	for(p = 0; p < txt.length; p++)
	{
		if (sdiak.indexOf(txt.charAt(p)) != -1)
		{
		  tx += bdiak.charAt(sdiak.indexOf(txt.charAt(p)));
		}
		else tx += txt.charAt(p);
	}
	return tx;
}

function toBarCode(txt)
{
	var srch = "+ľščťžýáíé-ěř";
	var repl = "1234567890/25";
	var tx = "";
	for(p = 0; p < txt.length; p++)
	{
		if (srch.indexOf(txt.charAt(p)) != -1)
		{
		  tx += repl.charAt(srch.indexOf(txt.charAt(p)));
		}
		else tx += txt.charAt(p);
	}
	return tx;
}

function charToNumber(string,mode)
{
	var str = string;
	var replace = '';
	var by = '';
	var display       = new Array("Á","á","Ä","ä","É","é","Í","í","Ó","ó","Ô","ô","Ú","ú","Ý","ý","ť","Š","š","Ž","ž");
	var friendlyCode  = new Array("&Aacue;","&aacue;","&Auml;","&auml;","&Eacute;","&eacute;","&Iacute;","&iacute;","&Oacute;","&oacute;","&Ocirc;","&ocirc;","&Uacute;","&uacute;","&Yacute;","&yacute;","t","S","s","Z","z");
	var numericalCode = new Array("&#193","&#225","&#196","&#228","&#201","&#233","&#205","&#237","&#211","&#243","&#212","&#244","&#218","&#250","&#221","&#253","&#357","&#352","&#353","&#381","&#382");
		
	switch(mode)
	{
	case 1:
	  		replace = display;
			by = friendlyCode;
	break;
	
	case 2:
			replace = display;
			by = numericalCode;
	break;
	
	case 3:
			replace = friendlyCode;
	  		by = display;
	break;

	case 4:
			replace = numericalCode;
	  		by = display;
	break;

	case 5:
			replace = numericalCode;
	  		by = friendlyCode;
	break;
	
	case 6:
			replace = friendlyCode;
	  		by = numericalCode;
	break;
	
	
	default:
	  		replace = display;
			by = friendlyCode;
	}
	
	for(p = 0; p < replace.length; p++)
	{
		str = str.replace(replace[p],by[p]); 
	}
	
	return str;
}

function cutString(str, len)
{
	var new_str = removeHTMLTags(str);
	if(new_str.length > len)
		return new_str.substr(0, new_str.substr(0, len).lastIndexOf(" ")) + " ...";
	return str;
}

function removeHTMLTags(strInputCode)
{
	/* 
		This line is optional, it replaces escaped brackets with real ones, 
		i.e. < is replaced with < and > is replaced with >
	*/	
 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
	 	return (p1 == "lt")? "<" : ">";
	});
	return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
}

function mergeArray(array1,array2)
{
    for(b in array2)
    {
        array1[b] = b
    }
}

function printArray(array)
{
    for ( i in array )
    {
        alert(i + '->' + array[i]);    
    }
}

function callSearch(scenarios,searchPharse)
{
    if(searchPharse.length<3)
    {
        myAlert('alert',"Vyhľadávané slovo musí mať minimálne 3 znaky. Prosím zadajte iné slovo.",false)
        return false
    }

	if(searchPharse.substr(0,1)=='/' || searchPharse.substr(0,2)=='s:')
	{
		if(searchPharse.substr(0,1)=='/') searchPharse = searchPharse.substr(1);
		else searchPharse = searchPharse.substr(2);
		window.location.href=window.location.pathname+"?content="+searchPharse
		return false
    }
	

    if(scenarios.length<1)
    {
        myAlert('alert',"Nevybrali ste si žiadny vyhľadávací scenár. Prosím vyberte si z ponuky.",false)
        return false
    }
    window.location='?copycontent=PORTAL-SEARCH&fwd=no&nid='+scenarios+'&nparams=hladam;' + searchPharse.toUpperCase() + ';unhladam;'+searchPharse;
    return false
}


function setExtraPar(elmId,groupName,groupRid)
{


    var elmObj  = $get(elmId);
    var beh = Sys.UI.Behavior.getBehaviors(elmObj)	
    if( beh != null && beh.length > 0 )
	{	    
	    var extraParam = beh[0].get_extraParam();		    					
	    if( groupRid != '' )
	    {
	        extraParam = 'GROUP;' + groupRid;
	        elmObj.title = groupName;
	    }
	    else
	    {
	        extraParam = '';
	        elmObj.title = '';			
	    }
	    beh[0].set_extraParam(extraParam)	       	    	    	    		
	}

}

function dropDownOver()
{
	this.className = "CisKoder_dropDownOver"
}

function dropDownOut()
{
	this.className = "CisKoder_dropDown"
}

function getAbsolutePosition(element)
{
	var r = { x: element.offsetLeft, y: element.offsetTop };
	if (element.offsetParent)
	{
		var tmp = getAbsolutePosition(element.offsetParent);
		r.x += tmp.x - element.scrollLeft;
		r.y += tmp.y - element.scrollTop;
	}
	return r;
}

function getRadioValue(obj)
{
    for (var i = 0; i < obj.length; i++)
        if (obj[i].checked) return obj[i].value
    return ""
}

function setRadioValue(obj,id)
{
    for (var i = 0; i < obj.length; i++)
    {
        if(i == id)
        {
            obj[i].checked = true;
        }
        else
        {
            obj[i].checked = false;
        }
    }
    
}

function cMenu(menuId,mode,nparams, nadpis, obj)
{
    if(typeof(nparams) != 'undefined' && nparams != '')
        nparams += ';';
    nparams += 'noCache;true';
    iMenu(menuId,mode,nparams, nadpis, obj);
}

function iMenu(menuId,mode,nparams, nadpis, obj, idHTMLobj)
{
	
	//alert('Otvaram' + menuId);
    if(typeof(iPhone) != 'undefined' )
	{   
	     //mode = 0 - new [new Div] (default), 1 - replace [replace exist Div], 2 - add [add to exist]   
	    if(mode == undefined || mode == 3 || mode == 4) mode = 0;
	    var mozemVytvoritMenu = true;
	    mozemVytvoritMenu = iPhone.iCreateMenu(menuId,mode); // vytvorim DIV do ktoreho budem vkladat obsah menu
	    
	    if(mozemVytvoritMenu == true)
	    {
        var myConn = new XHConn();
        
        if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
        else document.getElementsByTagName("BODY")[0].style.cursor = "wait";
		
        if (typeof (nadpis) != 'undefined' && nadpis != '')
        {
                nadpis = ";nadpis;" + nadpis;
        }
        else
        {
            nadpis = '';
        }
            
            if (typeof (nparams) == 'undefined')
                nparams = '';
            else
            {
                nparams = ';' + nparams;
	            nparams = nparams.replace(/\+/g,'%2B');
            }
            
            if(typeof(idHTMLobj)== 'undefined')
                idHTMLobj ='';
            
			
            myConn.connect(GetRootPath() + "/menu.ashx", "POST", "id=MOBILE&idHTMLobj="+idHTMLobj+"&deviceMode="+ barISPage.deviceMode+"&nparams=menuId;"+menuId+ nadpis + nparams + '&mode='+mode, iPhone.iMenuResp);
        }    
    }
    else
    {
        // portal mode
        if (mode == 4)
        {
            BarISMenu('0', 'CISID;'+menuId+';HlMenu;true;'+nparams, obj)
        }
		else if(mode == 3)
		{
            BarISMenu(menuId, nparams, obj)
		}
        else
        {
            if (mode == 99)
            {
                mode = 0;
                xMousePos = window.event.x + document.body.scrollLeft;
                yMousePos = window.event.y + document.body.scrollTop;
            }
            iFakeMenu(menuId, nparams, mode, obj);
        }
    }
}


function iDetail(nid,nparams,displayMode,ev, newAutoPlaceId)
{
   nparams = nparams.replace(/¤/g, '!');
   
   if(nparams.substr(0,1) == '*') // ak nparams zacinaju * vsetky * nahradim za ;
		nparams = nparams.substr(1).replace(/\*/g, ';');

   
  if( ev != null && ev.tagName == 'A')
  {  
	if(ev.className == '' )
	{
		ev.className = 'cube';
	}
	else if( ev.className.substr(0,4) != 'cube' )
	{  
		ev.className = "cube " + ev.className;
	}   
    ev.href = "#N" + nid;
  }
  
  if( typeof(displayMode) === 'undefined' || String(displayMode) == '')
			displayMode = '1'; 
  if(BarISPage.myOS() == BarISPage.OS_IPHONE || typeof(iPhone) !== 'undefined')
	{
		if(typeof(HtmlOut) !== 'undefined') /* prilohy otvarat nalepku pre android - warhan fix */
		{
			if(nid == 77)
			{
				nid=2208; 
				displayMode = 0;
			}
		}
		
		
	    iPhone.iCreateDetail(nid, displayMode,nparams,ev,newAutoPlaceId); // vytvorim DIV do ktoreho budem vkladat obsah nalepky
		
		if(displayMode == 'reload')
			iPhone.iDetail(nid,nparams,ev,displayMode, newAutoPlaceId);
	}
	else
	{  
	  
	 var swDMode = String(displayMode);
	 switch(swDMode)
	 {
	  case '0':
	        Detail(nid,nparams,ev);
	        break;
	  case '1':
	        var stripSys = nparams.split('$');			
		      var nparams = stripSys[stripSys.length-1];				
		      ExtJsDetail(nid,'detail.aspx?rnd=' + Math.random() + '&nid=' + nid + '&nparams=' + nparams + '&destroy=true&deviceMode=' + barISPage.deviceMode );
		      break;		
	  case '2':
			  var locationId = 'autoPlace';
			  if( typeof(newAutoPlaceId) === 'string' && newAutoPlaceId != null )
				locationId = newAutoPlaceId;
		      Detail(nid,'$view;nested;stateId;' + barISPage.stateId + ';objId;'  +  locationId + ';inlineMode;ajaxMode;reload;true;elType;DIV$' + nparams,ev.parentNode);		      
		      break;	
	  case '3':
		      Detail(nid,'$view;nested;stateId;' + barISPage.stateId + ';style;float;objId;autoPlace;inlineMode;ajaxMode;reload;true$' + nparams,ev);		      
		      break;	 
	 }		
	}
	
	//return true;
}



function ExtDetail(nid,nparams)
{
 Detail(nid,'$extjs;true;reload;true$' + nparams);
}


function RefreshSticker(clientId,nid,pid,bindVars)
{  
   Detail(nid,'$reload;true;inlineMode;ajaxMode;objId;stk' + clientId + '$');  
  
}

function HrefFromJavaScript(a) {
    if(a.href.indexOf("javascript:window.location='") != -1)
        a.href = (a.href.replace("javascript:window.location='", "").replace("'", ""));

    if (a.href.indexOf("CisDetail") != -1) {
        a.href = a.href.replace("javascript:", "");
        a.href = eval(a.href);
    }    
}

function iFakeMenu(subMenuId,nparams,mode,obj)
{
///action = "iFakeMenu('" + pwrTab.SubMenuId + "','" + pwrTab.NParams + "'," + (int)pwrTab.DetailMode + ",this)";  
	
  switch(mode)
  {
   case 0:  //popup
      //BarISMenu(subMenuId,nparams,obj);
	  iDetail(298,'menuId;' + subMenuId + ';' + nparams,'1',obj);
      break;
   case 1: // ext
      iDetail(298,'menuId;' + subMenuId + ';' + nparams,'2',obj);
      break;      
   case 2: //inline
 		  Detail(298,'$stateId;' + barISPage.stateId + ';objId;' + obj.parentNode.id +';inlineMode;ajaxMode;reload;true;elType;DIV$menuId;' + subMenuId,obj.parentNode);		      
      break;
   
  }
}

function collapseRows(obj)
{

var colspan = obj.parentNode.colSpan;
var obj2 = obj.parentNode.parentNode.nextSibling;
while(true)
{
 if( obj2.tagName == 'TR' && obj2.cells[0].colSpan != colspan )
 {
    hideItem(obj2);
    obj2 = obj2.nextSibling;    
  }
  else
  {
  break;
  }
}

if( obj.src.indexOf('plus') > 0 )
      obj.src = 'images/system/st-minus.gif';
else
    obj.src = 'images/system/st-plus.gif';

}


function jsonEval(location,variable,jsonDef)
{

  if( jsonDef.indexOf('NOT LOGGED IN BARISPORTAL')>-1)
  {
      alert('Obnovte si stranku, boli ste odhlaseni');
      return;
  }  
  try
  {
    eval(variable + '=' + jsonDef);
  }
  catch(e)
  {
    registerError(location, e, jsonDef);
    return false;
  }
  
  return true;

}

function takeGps()
{
	if(typeof(HtmlOut) !== 'undefined')
		HtmlOut.takeGpsPos();
}

function takePhoto()
{
	if(typeof(HtmlOut) !== 'undefined')
		HtmlOut.takePhoto()
}

function takeBar()
{
	if(typeof(HtmlOut) !== 'undefined')
		HtmlOut.takeBar()
}

function getWifi()
{
	var wifi = '';
	
	if(typeof(HtmlOut) !== 'undefined')
	{
			wifi = HtmlOut.getMacAddress();
	}
	
	return wifi;
}

function getGPS(asText,raiseEvent,actual)
{
	context = {'asText':asText,'raiseEvent':raiseEvent,'actual':actual}
	Baris.WebServices.CrmService.GetCurrentLocation( { OldNess: 0 }, getGPSres, UniWsBackFunc, context);
}

var takeGpsNum = 0;
function getGPSres(response, context)
{	
	var asText = context.asText;
	var raiseEvent = context.raiseEvent;
	var actual = context.actual;

	var gpsCoord = new Object();
	gpsCoord.Lat = 0;
	gpsCoord.Long = 0;
	gpsCoord.Wifi = '';
	gpsCoord.State = '';
	
	if( response.Locations != 0 && response.Locations.length > 0 )
	{
		if(response.Locations[0] != null)
		{
			gpsCoord.Lat = response.Locations[0].Lat;
			gpsCoord.Long = response.Locations[0].Long;	
			alert('Mam z DB cez novy servis');
		}
	}
	
	
	if(typeof(HtmlOut) !== 'undefined')
	{
		gpska = HtmlOut.getLastPos();
		row = gpska.split('_'); 
		if(actual == true)
		{
			row[1] = 0;
			row[2] = 0;
		}
		
		if(typeof(row[1]) !== 'undefined' && typeof(row[2]) !== 'undefined')
		{
			gpsCoord.Lat = row[1];
			gpsCoord.Long = row[2];
			gpsCoord.WiFiMAC = row[3];
			
			/*
			gpsCoord.Lat = 2;
			gpsCoord.Long = 2;
			*/
			gpsCoord.State = 'OK';
		}
		if(barISPage.adminMode) alert(gpsCoord.Lat +', ' + gpsCoord.Long +', '+ gpsCoord.WiFiMAC);
		
		
		if( raiseEvent == true )
		{
			if(gpsCoord.Lat <= 1 && gpsCoord.Long <= 1 && (gpsCoord.WiFiMAC == '' || gpsCoord.WiFiMAC == 'null') )
			{
			//alert('x1'+ gpsCoord.Lat +', ' + gpsCoord.Long +', '+ gpsCoord.WiFiMAC);
			if (takeGpsNum == 0) takeGps();

				sendAlert('GPS','GPS', 'Hľadám pozíciu.',1,1);
				
				gpsCoord.Lat = 'hľadám pozíciu';
				gpsCoord.Long = '...';
				gpsCoord.State = 'KO';

			
				
			context.asText = false;
			context.raiseEvent = raiseEvent;
			
			if(takeGpsNum<30)
				setTimeout("getGPSres("+response+", "+context+")", 1000);
			else
				takeGpsNum = 0;
				
			takeGpsNum = takeGpsNum+1;
			}
			else
			{
				barISPage.fireEvent('haveGPS',gpsCoord);
				takeGpsNum = 0;
			}
			
			return;
		}
	
	}
	
	if( asText == true )
		return String(gpsCoord.Lat) + ',' + String(gpsCoord.Long)
	else
		return gpsCoord;		
}

/*
barISPage.chainEvent('haveGPS', 'insHodnota');
barISPage.fireEvent('haveGPS', {"Lat":2,"Long":2});
*/

function GetExtCloseScript(stickerID, message,refreshDatasource,goBack)
{
    if (LastDetailWindow != null && LastDetailWindow.Nid == stickerID)
    {
        LastDetailWindow.hide();
        LastDetailWindow.destroy();
    }
    if(refreshDatasource == true)
        BarISPage.RefreshDataSource();

    if (message != '')
    {
        if (typeof (goBack) != 'undefined' && goBack > 0)
        {
            iPhone.Alert(message);
            iPhone.HistBack(goBack);
        }
        else
        {
            myAlert('info', message);
        }
    }
};

function xmlencode(string) {
	if( typeof(string) === 'string' )
	{
				return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
						.replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
	}
	else
	{	
		return string;
	}
};

function RegPrilohu(jsonData,fnWhenDone)
{
       
  var _RegPrilohuDone = function (oXML) 
	{
	    var jsonOutput = null;
	    try	    
	    {
	      eval('jsonOutput=' +oXML.responseText);
	    }
	    catch(e)
	    {
	      jsonOutput = new Object();
	      jsonOutput.State =false;
	    }
	    
	    if(fnWhenDone != null )
	    {
			eval(fnWhenDone(jsonOutput)); 
	    }
	    if(jsonOutput.Pozn != '' )
	      myAlert('ERR',jsonOutput.Pozn);	    
	}		
	
	var myConn = new XHConn();
  myConn.connect("GetPrilohu.ashx", "POST","MODE=REGISTER&COMMENT=" + jsonData.Comment +"&TYP=" + jsonData.Type + 
      "&FILENAME=" + jsonData.FileName + "&RIDV=" + jsonData.RidV + "&SOURCE=" + jsonData.Source.replace(/\+/g,'*') , _RegPrilohuDone);
  
	sendAlert('Príloha','Príloha', 'Nahrávam na server...',0,1);
}


function GetGPSInfo(jsonCfg, clientId)
{
	var context = new Object;
	context.CId = clientId;
	context.Lat = jsonCfg.Lat;
	context.Long = jsonCfg.Long;
    Baris.WebServices.CrmService.GetLocationInfo(jsonCfg, SaveGPSInfo, UniWsBackFunc, context);
}

function SaveGPSInfo(response, context)
{

   if (typeof (context.CId) == "object")
	{
		var i = 0;
        //if (response.Locations.length > 1) i = 1;
		
		context.CId.innerHTML = response.Locations[i].LocName;
		context.Name = response.Locations[i].LocName;
			
		Baris.WebServices.CrmService.SaveLocation({"Lat":context.Lat,"Long":context.Long, "LocName":response.Locations[i].LocName},SaveGPSInfoOK, UniWsBackFunc, context)
	}
	else
	{
		getE(context.CId).innerHTML = response.Locations[i].LocName;
	}
}

function SaveGPSInfoOK(response, context)
{
	if (response.State == true)
    {
		if( barISPage.adminMode)
		myAlert('alert', 'Uložené do DB: ' + context.LocName);	
	}
	else
	{
      myAlert('alert', 'Chyba: '+response.Pozn);
	}
}

function shortTxt(string,objId,chLng)
{
	var endChar = "";
	var limitChar = "*!!!*"
	
	if(string.search(limitChar)>0)
	{
		chLng = string.search(limitChar);
	}
	else
	{
		if(!chLng)
		{ 
			limitChar = "";
			chLng = 250;
			var str = string.substr(chLng);
			chLng = (str.search(" ")+chLng);
		}
	}		
	
	if(string.length >= chLng) 
	{
		endChar = '<span id="'+objId+'More" style="display:none">'+string.substr(chLng+limitChar.length)+'</span>';
		string = string.substr(0,chLng)+'<a href="javascript:void(0)" onclick="hideItem($get(\''+objId+'More\'));hideItem(this)" class="manMore"> [...]</a>';
	}
	$get(objId).innerHTML = string+endChar;
}


function StringFormat(formatStr,inpars)
{
		
	var vystupF  =  '';		
	var startB = 0;
	var endB = 0;
			
	var format = '';
	while (true)
	{
	  startB = formatStr.indexOf('{',startB);	  
	  format = '';	  
	  if( startB > -1 )
	  {
	      vystupF += formatStr.substr(endB,startB - endB );
	      endB = formatStr.indexOf('}',startB);	  
	      if( endB > startB +2)
	      {
	          format = formatStr.substr(startB+3,endB-startB-3);
	          vystupF +=  inpars[ Number(formatStr.substr(startB+1,1)) ].format(format);
	      }	  
	      else
	      {
			if(typeof inpars[ Number(formatStr.substr(startB+1,1)) ] === 'object')
				vystupF +=  inpars[ Number(formatStr.substr(startB+1,1)) ].format('d.M.yyyy H:mm');
			else  
				vystupF += inpars[ Number(formatStr.substr(startB+1,1)) ];
	      }
	      startB+=1;	      
	      endB+=1;
	  }
	  else
	  {
	    vystupF += formatStr.substr(endB,formatStr.length - endB);
	    break;
	  }	  
	}
	
  return vystupF
}

GANTT = function() {}
GMAP = function() {}

CisDataField = function() {}

DropDown = function() {}


function CisStickerAction(actionSettings)
{
  var parent = actionSettings.Wnd.opener;
  actionSettings.Wnd.close();
  if(actionSettings.Mode == 'D' )
  {
    
    parent.CisPreview(actionSettings.CisId,actionSettings.PK);
    parent.myAlert('INFO',actionSettings.Msg);    
  } 
  else if (actionSettings.Mode == 'R' )
  {
  
	BarISPage.RefreshDataSource();
	parent.myAlert('INFO',actionSettings.Msg);    
  
  } 
  else if(actionSettings.Mode == 'B' )
  {
    BarISPage.Back();
	parent.myAlert('INFO',actionSettings.Msg);    
  }
}


function fixCopyPaste(el) 
{	
	if(el == null ) 
		return;
	el.bind('paste', function(e) {
		var element = $(this).context;

		var text = $(this).val();
		var start = element.selectionStart;
		var pastedText = e.originalEvent.clipboardData.getData('text/plain');
		$(this).val(text.substring(0, element.selectionStart)
			+pastedText
			+text.substring(element.selectionEnd, text.length));
		element.selectionStart = start+pastedText.length;
		element.selectionEnd = element.selectionStart;
	});
}

