

/** MUSI BYC NA POCZATKU
 * poprawka document.getElementsByName która na IE nie działa jeśli na elemencie nie ma id takiego jak name
 * dlatego dla tego programu do pobierania przeglądarki funkcje przedefinujemy
 *
 *
 */    

var isIE = /*@cc_on!@*/false;                                //this isIE variable is false in any browser other than IE
var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;   // isIE6 variable is true only in Internet Explorer and only in IE6 - just what we need.
var isIE7 = false /*@cc_on || @_jscript_version >= 5.7 @*/;  //isIE7 will be true only in IE7 now.
if( isIE && typeof(window.external) != 'undefined' && document.attachEvent) {
     document.getElementsByName = function(name, tag) {
           if(!tag) tag = '*';
           var elems=document.getElementsByTagName(tag),x=elems.length,i,res=[];
           for(i=0;i<x;i++){
                 att = elems[i].getAttribute('name');
                 if(att == name) res.push(elems[i]);
           }
           return res;
     }
}


function browser_recognize()
{
    var browser = ''; 
    var sInfo = navigator.userAgent;
    
    //alert(sInfo);
    //alert(sInfo.indexOf("Symbian"));
    if ( sInfo.indexOf("Symbian") != -1 )
    {
       browser = "Symbian";
    }
    else if ( sInfo.indexOf("Safari") != -1 )
    {
       browser = "Safari";
    }
    else if ( sInfo.indexOf("Opera") != -1 )
    {
       browser = "Opera";   
    }
    else if ( sInfo.indexOf("MSIE") != -1 )
    {
       browser = "MSIE"; 
    }
    else if ( sInfo.indexOf("Mozilla") != -1 )
    {
       browser = "Mozilla";    
    }
    else 
    {
       browser = "Unknown" ;   
    }
    //alert(browser);
       
    return browser;  
} 

//end test

function set_wineasy_mode()
{
  var browser_information = browser_recognize();
 
  if (browser_information == "Safari" || browser_information == "Symbian"   )
  {
    //alert('WinEasy!!');
    return true;
  }
  else
  {
    //alert('WinLike!!');
    return false;
  }
}

// Returns the filename component of the path 
// example 1: basename('/www/site/home.htm', '.htm'); -> returns 1: 'home'
function basename (path, suffix) 
{
    var b = path.replace(/^.*[\/\\]/g, '');
     
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) 
    {
        b = b.substr(0, b.length-suffix.length);
    }
     
    return b;
}

//var WinEasy =  true;
var WinEasy =  set_wineasy_mode();
//var WinEasy =  false;



 function strtotime(str, now) {  
     // Convert string representation of date and time to a timestamp    
     //   
     // version: 902.2516  
     // discuss at: http://phpjs.org/functions/strtotime  
     // +   original by: Caio Ariede (http://caioariede.com)  
     // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
     // +      input by: David  
     // +   improved by: Caio Ariede (http://caioariede.com)  
     // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)  
     // *     example 1: strtotime('+1 day', 1129633200);  
     // *     returns 1: 1129719600  
     // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);  
     // *     returns 2: 1130425202  
     // *     example 3: strtotime('last month', 1129633200);  
     // *     returns 3: 1127041200  
     // *     example 4: strtotime('2009-05-04 08:30:00');  
     // *     returns 4: 1241418600  
     var i, match, s, strTmp = '', parse = '';  
   
     strTmp = str;  
     strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces  
     strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars  
   
     if (strTmp == 'now') {  
         return (new Date()).getTime();  
     } else if (!isNaN(parse = Date.parse(strTmp))) {  
         return parse/1000;  
     } else if (now) {  
         now = new Date(now);  
     } else {  
         now = new Date();  
     }  
   
     strTmp = strTmp.toLowerCase();  
   
     var process = function (m) {  
         var ago = (m[2] && m[2] == 'ago');  
         var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);  
   
         switch (m[0]) {  
             case 'last':  
             case 'next':  
                 switch (m[1].substring(0, 3)) {  
                     case 'yea':  
                         now.setFullYear(now.getFullYear() + num);  
                         break;  
                     case 'mon':  
                         now.setMonth(now.getMonth() + num);  
                         break;  
                     case 'wee':  
                         now.setDate(now.getDate() + (num * 7));  
                         break;  
                     case 'day':  
                         now.setDate(now.getDate() + num);  
                         break;  
                     case 'hou':  
                         now.setHours(now.getHours() + num);  
                         break;  
                     case 'min':  
                         now.setMinutes(now.getMinutes() + num);  
                         break;  
                     case 'sec':  
                         now.setSeconds(now.getSeconds() + num);  
                         break;  
                     default:  
                         var day;  
                         if (typeof (day = __is_day[m[1].substring(0, 3)]) != 'undefined') {  
                             var diff = day - now.getDay();  
                             if (diff == 0) {  
                                 diff = 7 * num;  
                             } else if (diff > 0) {  
                                 if (m[0] == 'last') diff -= 7;  
                             } else {  
                                 if (m[0] == 'next') diff += 7;  
                             }  
   
                             now.setDate(now.getDate() + diff);  
                         }  
                 }  
   
                 break;  
   
             default:  
                 if (/\d+/.test(m[0])) {  
                     num *= parseInt(m[0]);  
   
                     switch (m[1].substring(0, 3)) {  
                         case 'yea':  
                             now.setFullYear(now.getFullYear() + num);  
                             break;  
                         case 'mon':  
                             now.setMonth(now.getMonth() + num);  
                             break;  
                         case 'wee':  
                             now.setDate(now.getDate() + (num * 7));  
                             break;  
                         case 'day':  
                             now.setDate(now.getDate() + num);  
                             break;  
                         case 'hou':  
                             now.setHours(now.getHours() + num);  
                             break;  
                         case 'min':  
                             now.setMinutes(now.getMinutes() + num);  
                             break;  
                         case 'sec':  
                             now.setSeconds(now.getSeconds() + num);  
                             break;  
                     }  
                 } else {  
                     return false;  
                 }  
   
                 break;  
         }  
   
         return true;  
     }  
   
     var __is =  
     {  
         day:  
         {  
             'sun': 0,  
             'mon': 1,  
             'tue': 2,  
             'wed': 3,  
             'thu': 4,  
             'fri': 5,  
             'sat': 6  
         },  
         mon:  
         {  
             'jan': 0,  
             'feb': 1,  
             'mar': 2,  
             'apr': 3,  
             'may': 4,  
             'jun': 5,  
             'jul': 6,  
             'aug': 7,  
             'sep': 8,  
             'oct': 9,  
             'nov': 10,  
             'dec': 11  
         }  
     }  
   
     match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);  
   
     if (match != null) {  
         if (!match[2]) {  
             match[2] = '00:00:00';  
         } else if (!match[3]) {  
             match[2] += ':00';  
         }  
   
         s = match[1].split(/-/g);  
   
         for (i in __is.mon) {  
             if (__is.mon[i] == s[1] - 1) {  
                 s[1] = i;  
             }  
         }  
   
         return strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]);  
     }  
   
     var regex = '([+-]?\\d+\\s'  
     + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
     + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
     + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'  
     + '|(last|next)\\s'  
     + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
     + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
     + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'  
     + '(\\sago)?';  
   
     match = strTmp.match(new RegExp(regex, 'g'));  
   
     if (match == null) {  
         return false;  
     }  
   
     for (i in match) {  
         if (!process(match[i].split(' '))) {  
             return false;  
         }  
     }  
   
     return (now);  
 }//----------------------------------------------------------------------------
 
 function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, unicodeStr='', hexEscStr='';
    var ret = (str+'').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
 
    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr];
        ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
} 


function rawurlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin van Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
 
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
 
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A'; 
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
 
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
 
    // Restore spaces, converted by encodeURIComponent which is not rawurlencode compatible
    ret = replacer('%20', ' ', ret); // Custom replace. No regexing
 
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
 
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
 
    return ret;
}

/* *********************************/

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}



// *************************************************************************************
// *************************************************************************************
// *************************************************************************************

function FilterTable(sender, selector ){
  var search = sender.value.toLowerCase();
  
  if ( search == '' ){
    $( selector + " tr:not(.no_filter)" ).show();    
  }
  else {
    $( selector + " tr:not(.no_filter)" ).each( function( i,obj ){
      obj = $(obj);
      if ( obj.text().toLowerCase().indexOf( search ) > 0 ) obj.show();
      else obj.hide();
    
    });
    
  } 


}//-----------------------------------------------------------------------------


/* DO PAGINACJI POWYZEJ 20 */

function PaginationOver20GoTo(sender){
  
  var str = document.location.toString();
  var poczatek = str.indexOf('pg=');
  var koniec = str.indexOf('&', poczatek );
  var delimiter = '&';
  if ( str.indexOf('?') == -1 ) delimiter = '?'
  var loc = str.substr(0, poczatek-1) + delimiter +'pg=' + sender.value;
  if ( koniec > 0 ){
    loc = loc + str.substr(koniec);
  }
  document.location = loc;
  
}//-----------------------------------------------------------------------------

/**
 *  Zwraca ita potege dwojki
 *
 *
 */   
function power2( ile ){
 if ( ile == 0 ) return 1;
 var ret = 1;
 for (var i = 0; i < ile; i++){
  ret = ret *2;
 }
 return ret;
}//-----------------------------------------------------------------------------


/**
 * Funkcje do wykorzystania w systemie
 *
 */

function trim(str) {
        return str.replace(/^\s+|\s+$/g,'');
}//-----------------------------------------------------------------------------


/**
 * Konwertuje date z formy javascriot na forme tekstu na modle SQL
 *
 */  

function GetSQLDate(Data){

var Y = Data.getFullYear();
var M = Data.getMonth() + 1; //ale miesiąc w Data jest Zero Based
var D = Data.getDate();

 
if (M < 10)  M = "0" + M;
if (D < 10)  D = "0" + D;

return Y + "-" + M + "-" +D;
}

/**
 * Kopiuje tekst z obstawionego skryptem spana do pola input
 * @param object this (span lub znacznik nie zawierający nic poza tekstem)
 * @param string target_from nazwa pola input 
 */  
function CopyValToField(source,target_name){
  var span_textnode = source.firstChild;
  var data = trim(span_textnode.data);
  var Elements = document.getElementsByName(target_name);
  var ile = Elements.length;
  //alert(ile);
	for (var i = 0; i < ile; i++)
	{
    Elements[i].value = data;
	}
}


/**
 * Kopiuje datę do jednego z 2 podanych pól (name) a później wybiera bliższe
 * @param object this
 * @param string target_from nazwa pola input z datą początkową 
 * @param string target_to nazwa pola input z datą końcową
 *
 */  
function CopyDateToFields(source,target_from, target_to){
  var span_textnode = source.firstChild;
  var data = trim(span_textnode.data);
  var From = document.getElementsByName(target_from);
    if ( From[0].value == "" )From[0].value = data;
    else{
        var To = document.getElementsByName(target_to);        
        if ( To[0].value == "" )To[0].value = data;
        else{
                    var nn = data.split("-");
                    var D = new Date(nn[0], nn[1]-1, nn[2]); // -1 bo miesiace sa zero-based
                    
                    var fro = From[0].value.split("-");
                    var D1 = new Date(fro[0], fro[1]-1, fro[2]);// -1 bo miesiace sa zero-based
             
                    var doo = To[0].value.split("-");
                    var D2 = new Date(doo[0], doo[1]-1, doo[2]);    // -1 bo miesiace sa zero-based
                      
                      if ( D > D2 ) { //jak ponad zakresem to poszesz zakres w górę
                        To[0].value = GetSQLDate(D);
                        }
                      else if( D < D1 ) {   //jak klik ponizej zakresu to poszesz zakres w dol
                        From[0].value = GetSQLDate(D);
                      }
                      else {  //jak w srodku zakresu przyciagnij blizszy
                          if (  D-D1 > D2-D  ){
                              To[0].value = GetSQLDate(D);
                          }
                          else{
                              From[0].value = GetSQLDate(D); 
                          }
                      }
            }
        }

}

/**
 * Zaznacza element jako ostatnio kliknięty, odznaczając resztę z grupy. Elementy muszą mieć wspólne name='groupname'
 *
 *
 */

  function markClick_old( sender, groupname ){
        
      var Elements = document.getElementsByName(groupname);
      var ile = Elements.length;
    	for (var i = 0; i < ile; i++)
    	{
        Elements[i].style.background = '';
    	}
        sender.style.background="#ddddff";
      
      //tylko dla zainstalowanego jQuery
      if (jQuery) { 
        $(sender).parents("tr:first").removeClass("font_mod").removeClass("font_new")
      }  
        
  }

/**
 * Ustawia w DDL o wskazanej nazwie opcję o danej wartości
 *
 *
 */   
function SetValInDDL(ddv_val,target_name){
  var Elements = document.getElementsByName(target_name);
  var ile = Elements.length;
	for (var i = 0; i < ile; i++)
	{
    var o=Elements[i].options;
    var ile2= o.length;
    for (var j = 0; j < ile2; j++){
      if ( o[j].value == ddv_val ) o[j].selected = true;
    }
	}
}

function SelectOptionInSelect( ObjSelect, value ){

  var o=ObjSelect.options;
    var ile2= o.length;
    for (var j = 0; j < ile2; j++){
      if ( o[j].value == value ) o[j].selected = true;
    }
    
}


/**
 * Dedykowana dla wykresów Ganta, wstawia w okno daty wyklikane miejsce
 *
 * @param string chb_name_prefix Przedrostek w nazwie checkboxa do obsluzenia
 * @param mixed stan co robic z boxami, true zapala, false wylacza, 2 robi inwersje  
 *
 */

function SetGantDateRange( rok, miesiac, dzien, pole_data_od, pole_data_do ){

  var D = new Date(rok, miesiac-1, dzien); // miesiace w JS sa zero-based 

  var Txt_Data_od = document.getElementById(pole_data_od);
  var Txt_Data_do = document.getElementById(pole_data_do);

  if ( Txt_Data_od.value == '' ){                 //1. Jesli nie ma daty startowej wpisz tam kliknieta date
    Txt_Data_od.value = GetSQLDate(D);
  }
  else{ //2. Jesli jest data startowa
  
    //powolanie obiektu daty startowej
    var od = Txt_Data_od.value.split("-");
    var D1 = new Date(od[0], od[1], od[2]);
  
    if ( Txt_Data_do.value == '' ) {           //2a. Jesli jest data poczatkowa ale nie ma koncowej, to 
        if ( D > D1 ) {
          Txt_Data_do.value = GetSQLDate(D);
          }
        else {   
          Txt_Data_do.value = Txt_Data_od.value;
          Txt_Data_od.value = GetSQLDate(D);
        } 
    }
    else{ //2b. Jesli sa obie daty
    
      var doo = Txt_Data_do.value.split("-");
      var D2 = new Date(doo[0], doo[1], doo[2]);    
        
        if ( D > D2 ) { //jak ponad zakresem to poszesz zakres w górę
          Txt_Data_do.value = GetSQLDate(D);
          }
        else if( D < D1 ) {   //jak klik ponizej zakresu to poszesz zakres w dol
          Txt_Data_od.value = GetSQLDate(D);
        }
        else {  //jak w srodku zakresu przyciagnij blizszy
            if (  D-D1 > D2-D  ){
                Txt_Data_do.value = GetSQLDate(D);    
            }
            else{
                Txt_Data_od.value = GetSQLDate(D);  
            }
            
        
        }
    }
  } 
} //----------------------------------------------------------------------------




/**
 * Steruje zaznaczeniem checkboxow w listach
 *
 * @param string chb_name_prefix Przedrostek w nazwie checkboxa do obsluzenia
 * @param mixed stan co robic z boxami, true zapala, false wylacza, 2 robi inwersje  
 *
 */
function SwitchChb( chb_name_prefix, stan)
{
  var collCheckbox = document.getElementsByTagName('input');
	var i = 0;
	var ile = collCheckbox.length;
	var plength = chb_name_prefix.length

	for (var i = 0; i < ile; i++)
	{
   var xxx = collCheckbox[i].id;
   if (xxx != undefined && xxx != ''  ){ 
      var e = document.getElementById(collCheckbox[i].id);
      if (e != null)
  		{
        if (e.type == "checkbox" && e.name.substr(0,plength) == chb_name_prefix)
  			{
  					if (stan ==2){
              if (e.checked == true) e.checked=false;
              else e.checked = true;
            }
            else if ( e.checked != stan ){
                        e.checked = stan;
                      } 
  			}
  		}
	 }
	}
}
 

/**
 * Odwraca widoczność elementu o danym id
 *
 * @param string id_name Nazwa HTML id="" elementu do chowania / pokazania
 *
 */
function ChangeVisibilityById( id ){
 var Element = document.getElementById(id);
 if ( Element.style.display != 'none' ) Element.style.display = 'none';
 else Element.style.display = '';
}


/**
 * Odwraca widoczność elementu o danym id
 *
 * @param string id_name Nazwa HTML id="" elementu do chowania / pokazania
 *
 */
function ChangeVisibilityById2(sender, id, classname ){
 
 if (sender.className==classname+'On')  sender.className=classname+'Off';
 else sender.className=classname+'On';
    
 var Element = document.getElementById(id);
 if ( Element.style.display != 'none' ) Element.style.display = 'none';
 else Element.style.display = '';
}

/**
 * Odwraca widoczność elementów o danym name
 * 
 * \!/ getElementsByName -internet explorer w dosc specyficzny sposób rozumie znaczenie tej funkcji:
 * getElementsById zwraca kolekcje obiektów z takim samym name i id.
 * Jeżli element ma tylko name o okreslonej wartosci nie zostanie przez ta funkcje odnaleziony.  
 *
 * @param string classname Nazwa HTML name="" elementów do chowania / pokazania
 *
 */ 
function ChangeClassVisibilityByName( name , sender, classname, button_id){
var Elements = document.getElementsByName(name);

  if (classname == null){
   classname = 'IconSwitch';
  }

  if ( button_id != undefined ) sender = document.getElementById(button_id);

  if(sender.className!='nag2') //jezeli jest wywolywane przez naglowek, to nie zmieniaj jego klasy
  {
    if (sender.className==classname+'On') sender.className=classname+'Off';
    else sender.className=classname+'On';
  }
  
  
	var i = 0;
	var ile = Elements.length;

	for (var i = 0; i < ile; i++)
	{
    if ( Elements[i].style.display != 'none' ) {
          Elements[i].style.display = 'none';
    }
    else {
          Elements[i].style.display = '';
    }
	}
}

/**
 * Wlacza / wylacza widoczność elementów o danym name
 *
 * @param string classname Nazwa HTML name="" elementów do chowania / pokazania
 * @param bool sync - synchronizacja wlaczenia / wylaczenia ze swieceniem przycisku, false oznacza odwrotnosc
 * @param bool ignore - ignoruje zmiane stanu wylacznika (jak sie wywoluje kilka razy) 
 */ 
function SwitchClassVisibilityByName( name , sender, classname, sync, ignore){
var Elements = document.getElementsByName(name);

  if (classname == null) classname = 'IconSwitch';
  if (ignore == null) ignore = false;
  
  
  if (sender.className==classname+'On') {
      if (! ignore ) sender.className=classname+'Off';
      if (sync = false) var disp='';
      else var disp='none';
  }
  else {
      if (! ignore ) sender.className=classname+'On'; 
      if (sync = false) var disp='none';
      else var disp='';
  }
  
	var i = 0;
	var ile = Elements.length;

	for (var i = 0; i < ile; i++)
	{
          Elements[i].style.display = disp;
	}
}


function SwitchSuboptions( name , sender){


  if (sender.options[ sender.selectedIndex ].value== 0 || sender.options[ sender.selected ]== '' ) {
      var disp='none';
  }
  else {
      var disp='';
  }
  
	var Elements = document.getElementsByName(name);
  var i = 0;
	var ile = Elements.length;


	for (var i = 0; i < ile; i++)
	{
          Elements[i].style.display = disp;
	}
} 
 
 
 

/**
 * Klikniecie na zakladace i przejscie do innej strony
 *
 * @param string targetUrl Adres url, do ktorego nalezy przejsc
 * @param string srcObjId Identyfikator obiektu zrodlowego
 *
 */
function goTo(targetUrl, srcObjId)
{

	var srcObj = document.getElementById(srcObjId);
	
	var CaleMenu = document.getElementsByName('zakladka')
  var len = CaleMenu.length;
    for (var i = 0; i < len; i++){
       CaleMenu[i].className = 'menuitem';
    }
	
	srcObj.className = 'menuitem_selected';

	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
	if (xnr != null)
	{
	    // jest - tylko przeładowanie
	    place.WinLIKE.openaddress(targetUrl, null, 'winTop', null, false, false);
	}
	else
	{
	    // nie ma - otwieram
	    place.WinLIKE.openaddress(targetUrl, null, 'winTop', null, true, false);
	}

	xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
	if (xnr != null)
	{
	    // jest - tylko przeładowanie
	    place.WinLIKE.openaddress('pusty.php', null, 'winContent', null, false, false);
	}
	
	viewNormal();
}


/**
 * Klikniecie na zakladace i przejscie do innej strony PRZELADOWUJE DWIE RAMKI
 *
 * @param string targetUrl Adres url, do ktorego nalezy przejsc
 * @param string srcObjId Identyfikator obiektu zrodlowego
 * @param string targetWin docelowe okno 
 *
 */

//'zad_gora.php', 'menu_2', 'winList' , 'zad_folders.php', 'winContent' 
function goTo3(targetUrl, srcObjId, targetWin, secondUrl, secondWin)
{
  if (WinEasy==true) 
    return goTo3_easy(targetUrl, srcObjId, targetWin, secondUrl, secondWin);
  
  if ( secondUrl == undefined ) secondUrl = '';
  if ( secondWin == undefined ) secondWin = '';
  var place = recognizeWinLIKE_(top);
  if (place == undefined) return false;


  if (targetUrl != '' ){
      xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
    	if (xnr != null)
    	{
    	    // jest - tylko przeładowanie
    	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, false, false);
    	}
    	else
    	{
    	    // nie ma - otwieram
    	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, true, false);
    	}
  }
  
  if (secondUrl != '' ){
      xnr = place.WinLIKE.searchwindow(secondWin);  // znajdz okno
      if (xnr != null)
      {
          // jest - tylko przeładowanie
          place.WinLIKE.openaddress(secondUrl, null, secondWin, null, false, false);
      }
      else
      {
          // nie ma - otwieram
          place.WinLIKE.openaddress(secondUrl, null, secondWin, null, true, false);
      }
  }


	
	viewNormal();
}


/**
 * Klikniecie na zakladace i przejscie do innej strony NIEAKTYWNE?
 *
 * @param string targetUrl Adres url, do ktorego nalezy przejsc
 * @param string srcObjId Identyfikator obiektu zrodlowego
 * @param string targetWin docelowe okno 
 *
 */
function goTo2(targetUrl, srcObjId, targetWin)
{
	var tmp = srcObjId.split("_");

	var srcObj = document.getElementById(srcObjId);
	//alert(srcObj.parentNode.tagName);

	var len = srcObj.parentNode.childNodes.length;
	//alert(len);
    for (var i = 0; i < len; i++)
	{
	    if (srcObj.parentNode.childNodes[i].nodeType == 1)
	    {
		    var tmp2 = srcObj.parentNode.childNodes[i].id.split('_');
			if (tmp2[0] == 'menu')
			{
			    if (tmp2[1] == tmp[1])
			    {
			        // element zaznaczony
			        if (tmp2[1] == '1')
			        {
						document.getElementById('menu_'  + tmp2[1] + '_1').style.backgroundImage = "url('./i/tab1_0.gif')";
						document.getElementById('menu_'  + tmp2[1] + '_1').style.width = "20px";
					}
					else
					{
					    document.getElementById('menu_'  + tmp2[1] + '_1').style.backgroundImage = "url('./i/tab1_1.gif')";
					    document.getElementById('menu_'  + tmp2[1] + '_1').style.width = "19px";

					    var tmpObj = document.getElementById('menu_' + (tmp[1]-1) + '_3');
						if (tmpObj != null)
						{
						    tmpObj.style.backgroundImage = "url('./i/tab2_2.gif')";
						    tmpObj.style.width = "1px";
						}

					}
			        document.getElementById('menu_'  + tmp2[1] + '_2').style.backgroundImage = "url('./i/tab1_2.gif')";

			        document.getElementById('menu_'  + tmp2[1] + '_3').style.backgroundImage = "url('./i/tab1_3.gif')";
			        document.getElementById('menu_'  + tmp2[1] + '_3').style.width = "3px";
				}
				else
				{
				    if (tmp2[1] == '1')
				    {
              document.getElementById('menu_'  + tmp2[1] + '_1').style.backgroundImage = "url('./i/tab2_0.gif')";
					    document.getElementById('menu_'  + tmp2[1] + '_1').style.width = "20px";
					}
					else
					{
			        	document.getElementById('menu_'  + tmp2[1] + '_1').style.backgroundImage = "url('./i/tab2_1.gif')";
					    document.getElementById('menu_'  + tmp2[1] + '_1').style.width = "9px";
					}

			        document.getElementById('menu_'  + tmp2[1] + '_2').style.backgroundImage = "url('./i/tab2_2.gif')";

			        document.getElementById('menu_'  + tmp2[1] + '_3').style.backgroundImage = "url('./i/tab2_3.gif')";
				    document.getElementById('menu_'  + tmp2[1] + '_3').style.width = "3px";
				}
			}
		}
    }

	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    // jest - tylko przeładowanie
	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, false, false);
	}
	else
	{
	    // nie ma - otwieram
	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, true, false);
	}

	viewNormal();
}




/**
 * Przechodzi do okreslonej stronie w wybranym oknie
 *
 * @param string targetUrl Adres WWW
 * @param string targetWin Okno docelowe
 *
 */
function goToPage(targetUrl, targetWin)
{
   if (WinEasy==true) 
    return goToPage_easy(targetUrl, targetWin)
  //  top.open(targetUrl,targetWin);
  // return false;
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null && xnr != undefined)
	{

      // jest - tylko przeładowanie
	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, false, false);
	    
	  if ( place.WinLIKE.windows[xnr] != null ){ //u cos sie sypalo przy dodawaniu do folderow
  		if (place.WinLIKE.windows[xnr].Vis == false)
  		    place.WinLIKE.windows[xnr].Vis = true;
  	}	    
	}
	else
	{
	    // nie ma - otwieram
	    place.WinLIKE.openaddress(targetUrl, null, targetWin, null, true, false);
		if (place.WinLIKE.windows[xnr].Vis == false)
		    place.WinLIKE.windows[xnr].Vis = true;
	}
}


/**
 * Odswieza zawartosc okna
 *
 * @return none
 *
 */
function refreshWin(targetWin)
{
   if (WinEasy==true) 
    return refreshWin_easy(targetWin);
    
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    // jest - tylko przeładowanie
	    place.WinLIKE.windows[xnr].innerdoc().location.reload();
	}
}


/**
 * Zamyka okno
 *
 * @return none
 *
 */
function closeWin(targetWin)
{
   if (WinEasy==true) 
    return closeWin_easy(targetWin);

	var place = recognizeWinLIKE_(top);
	//alert (place);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	//alert (xnr);
	if (xnr != null && typeof(xnr) != "undefined" )
	{
	    // jest - tylko przeładowanie
	   // alert (place.WinLIKE.windows[xnr].Vis);
	    place.WinLIKE.windows[xnr].Vis = false;
	    
    //   alert (place.WinLIKE.windows[xnr]);
	   place.WinLIKE.windows[xnr].close();

	  //  place.WinLIKE.windows[xnr].draw();
	}
}



/***** FUNKCJE SKALOWNIA OKIEN */

function hideLeftMenu( sender_id, cssname )
{
  ///alert('hideLeftMenu');
 var place = recognizeWinLIKE_(top);
 if (place == undefined) return false;
 var sender = document.getElementById(sender_id);
 //var cssname = 'cssname_unknown_hover';
 //if(sender.className == cssname_unknown_hover + '_hover') var cssname = cssname_unknown_hover + '_hover';
 
 // menu mozna shcowac hideshow() 
 
  var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
  if (place == undefined) return false;
  
 
    if(sender.className == cssname + 'Show' || sender.className == cssname + 'Show_hover' )
    {
        var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno tresci
        place.WinLIKE.windows[xnr].Left = 0;
        place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width;
      	place.WinLIKE.windows[xnr].draw();
      
      	xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno listy
        place.WinLIKE.windows[xnr].Left = 0;
        place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width;
      	place.WinLIKE.resizewindows();
      	sender.className  = cssname + 'Hidden'; 
      	
      	xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
        place.WinLIKE.windows[xnr].Mn = true;
        place.WinLIKE.windows[xnr].hideshow();
  	}
  	else
  	{
      	//uwazac by xnr kierowal na menu!
        if(place.WinLIKE.windows[xnr].Width < DEF_SMALL_MENU_W + 3){ //sprawdzanie czy mamy do czynienia z malym menu, czy duzym
          var mw = DEF_SMALL_MENU_W; //male menu
        }
        else{
          var mw = DEF_BIG_MENU_W; //duze menu
        }
        
        var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno tresci
        place.WinLIKE.windows[xnr].Left = mw;
        place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width - mw;
        place.WinLIKE.windows[xnr].front();
      	place.WinLIKE.windows[xnr].draw();
      
      	xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno listy
        place.WinLIKE.windows[xnr].Left = mw;
        place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width - mw;
      	place.WinLIKE.windows[xnr].front();
        place.WinLIKE.resizewindows();
      	sender.className  = cssname + 'Show'; 
      	
      	xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
        place.WinLIKE.windows[xnr].Mn = false;
      	place.WinLIKE.windows[xnr].hideshow();
  	}

}//------------------------------------------------------------------------------

function showMiniMenu( sender_id )
{
 ///alert('showMiniMenu');
 var place = recognizeWinLIKE_(top);
 if (place == undefined) return false;
 var sender = document.getElementById(sender_id);
 var size = 60;
 //var cssname = 'cssname_unknown_hover';
 //if(sender.className == cssname_unknown_hover + '_hover') var cssname = cssname_unknown_hover + '_hover';
 
 // menu mozna shcowac hideshow() 
  
  var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
  if(place.WinLIKE.windows[xnr].Width != size && document.getElementById('MenuNormal').style.display == 'block')
  //if(sender.className == cssname + 'Show' || sender.className == cssname + 'Show_hover' )
  {
      var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno tresci
      place.WinLIKE.windows[xnr].Left = size;
      place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width - size;
    	place.WinLIKE.windows[xnr].draw();
    
    	xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno listy
      place.WinLIKE.windows[xnr].Left = size;
      place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width - size;
    	place.WinLIKE.resizewindows();
    	//sender.className  = cssname + 'Hidden'; 
    	
    	var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
      place.WinLIKE.windows[xnr].Width = size;
      place.WinLIKE.resizewindows();
      
      if(document.getElementById('MenuNormal').style.display == 'block')
      {
        document.getElementById('MenuNormal').style.display = 'none'; 
        document.getElementById('MenuMini').style.display = 'block'; 
      }else{
        document.getElementById('MenuNormal').style.display = 'block'; 
        document.getElementById('MenuMini').style.display = 'none'; 
      }
      
	}
	else
	{
    	var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno tresci
      place.WinLIKE.windows[xnr].Left = 150;
      place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width -150;
      place.WinLIKE.windows[xnr].front();
    	place.WinLIKE.windows[xnr].draw();
    
    	xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno listy
      place.WinLIKE.windows[xnr].Left = 150;
      place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width -150;
    	place.WinLIKE.windows[xnr].front();
      place.WinLIKE.resizewindows();
    	//sender.className  = cssname + 'Show'; 
    	
    	xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
    	place.WinLIKE.windows[xnr].Width = 150;
      place.WinLIKE.resizewindows();
     
      if(document.getElementById('MenuNormal').style.display == 'block')
      {
        document.getElementById('MenuNormal').style.display = 'none'; 
        document.getElementById('MenuMini').style.display = 'block'; 
      }else{
        document.getElementById('MenuNormal').style.display = 'block'; 
        document.getElementById('MenuMini').style.display = 'none'; 
      }
    	
	}
	
}

//------------------------------------------------------------------------------


/**
 * Powieksza okno z lista i zmniejsza okno na tresc
 *
 * @return none
 *
 */
function viewNormal()
{
   if (WinEasy == true) 
    return viewNormal_easy();
   
  //alert ('viewNormal')   ;
  var place = recognizeWinLIKE_(top);
	if ( place == undefined ) return false;
	
	xnr = place.WinLIKE.searchwindow('winHeader');  // znajdz okno Menu
  var topsize = place.WinLIKE.windows[xnr].Height;
	

	var ListH = Math.floor( place.WinLIKE.browsersize().Height * 0.4 );
	var contH = place.WinLIKE.browsersize().Height - topsize - ListH;

	var xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
	place.WinLIKE.windows[xnr].Mn = false;
	place.WinLIKE.windows[xnr].Mx = false;
	place.WinLIKE.windows[xnr].Height = ListH;
	place.WinLIKE.windows[xnr].draw();


	xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
	place.WinLIKE.windows[xnr].Mn = false;
	place.WinLIKE.windows[xnr].Mx = false;
	place.WinLIKE.windows[xnr].Top = ListH + topsize;
	place.WinLIKE.windows[xnr].Height = contH;
	place.WinLIKE.windows[xnr].draw();

}//-----------------------------------------------------------------------------



/**
 * Powieksza okno z lista i zmniejsza okno na tresc
 *
 * @return none
 *
 */
function resetWorkspace()
{
   ///alert('resetWorkspace');
  //dla minimenu dziala tylko gdy minimenu.width = 150px, gdy recznie powiekszy mimimenu, to nie dziala
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
  
  //sprawdzanie jak wysokie jest menu gorne
  xnr = place.WinLIKE.searchwindow('winHeader');  // znajdz okno Menu gornego
  var topsize = place.WinLIKE.windows[xnr].Height;
  
  
  var ListH = Math.floor( place.WinLIKE.browsersize().Height * 0.4 );
	//var contH = place.WinLIKE.browsersize().Height - DEF_TOP_MENU_H - ListH;
	var contH = place.WinLIKE.browsersize().Height - topsize - ListH;
  
  //sprawdzanie zcy menu jest male czy duze
  var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno Menu
        if(place.WinLIKE.windows[xnr].Width < DEF_SMALL_MENU_W + 3){ //sprawdzanie czy mamy do czynienia z malym menu, czy duzym
          var mw = DEF_SMALL_MENU_W; //male menu
        }
        else{
          var mw = DEF_BIG_MENU_W; //duze menu
        }
  

  	var xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = false;
  	place.WinLIKE.windows[xnr].Left = mw ;
  	place.WinLIKE.windows[xnr].Top = topsize;
  	place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width- mw -2;
  	place.WinLIKE.windows[xnr].Height = ListH;
  	place.WinLIKE.windows[xnr].draw();
  
  	var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = false;
  	place.WinLIKE.windows[xnr].Left = mw ;
  	place.WinLIKE.windows[xnr].Top = ListH + topsize;
  	place.WinLIKE.windows[xnr].Width = place.WinLIKE.browsersize().Width- mw -2;
  	place.WinLIKE.windows[xnr].Height = contH;
  	place.WinLIKE.windows[xnr].draw();

    var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = false;
  	place.WinLIKE.windows[xnr].Left = 0;
  	place.WinLIKE.windows[xnr].Top = topsize;
  	place.WinLIKE.windows[xnr].Width = mw;
  	place.WinLIKE.windows[xnr].Height = place.WinLIKE.browsersize().Height-topsize-2;
  	place.WinLIKE.windows[xnr].Vis=true;
    place.WinLIKE.windows[xnr].draw();
  
  	place.WinLIKE.resizewindows();

}//-----------------------------------------------------------------------------


/**
 * Powieksza okno z lista i zmniejsza okno na tresc
 *
 * @return none
 *
 */
function FitTopMenu( wys )
{
   ///alert('FitTopMenu4');
	  
  var place = recognizeWinLIKE_(top);
  if (place == undefined) return false;
	var xnr = place.WinLIKE.searchwindow('winHeader');  // znajdz okno
  //alert(place.WinLIKE.windows[xnr].document); //znalezc diwa od menu i zczytac go stad
  //return false

  
  var difference = place.WinLIKE.windows[xnr].Height - wys;
  place.WinLIKE.windows[xnr].Height = wys;
  place.WinLIKE.windows[xnr].draw();

		var xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
  	place.WinLIKE.windows[xnr].Top = place.WinLIKE.windows[xnr].Top - difference;
  	place.WinLIKE.windows[xnr].draw();
  	var topH = place.WinLIKE.windows[xnr].Height;
  
  	
    var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
  	place.WinLIKE.windows[xnr].Top = topH + wys;
  	//place.WinLIKE.windows[xnr].Height = contH;
  	place.WinLIKE.windows[xnr].draw();
  	

  	var xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno
  	place.WinLIKE.windows[xnr].Top = wys;
  	place.WinLIKE.windows[xnr].Top = place.WinLIKE.windows[xnr].Top - difference;
  	//place.WinLIKE.windows[xnr].Height = place.WinLIKE.browsersize().Height-wys;
  	place.WinLIKE.windows[xnr].draw();
  	
	//place.WinLIKE.resizewindows();
}//-----------------------------------------------------------------------------



/**
 * Powieksza okno z lista i zmniejsza okno na tresc
 *
 * @return none
 *
 */
function viewMaxList()
{
	 if (WinEasy==true) 
    return viewMaxList_easy();
	
 //dla minimenu dziala tylko gdy minimenu.width = 150px, gdy recznie powiekszy mimimenu, to nie dziala
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;

  //sprawdzanie jak wysokie jest menu gorne
  xnr = place.WinLIKE.searchwindow('winHeader');  // znajdz okno Menu gornego
  var topsize = place.WinLIKE.windows[xnr].Height;
    
  var ListH = Math.floor( place.WinLIKE.browsersize().Height -24 - topsize );
	var contH = place.WinLIKE.browsersize().Height - topsize - ListH;

  	var xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = false;
  	place.WinLIKE.windows[xnr].Top = topsize;
  	place.WinLIKE.windows[xnr].Height = ListH;
  	place.WinLIKE.windows[xnr].draw();
  
  	var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = true;
  	place.WinLIKE.windows[xnr].Top = ListH + topsize;
  	place.WinLIKE.windows[xnr].Height = contH;
  	place.WinLIKE.windows[xnr].draw();
	
	//place.WinLIKE.resizewindows();
}//-----------------------------------------------------------------------------

function viewMaxContent()
{
	 if (WinEasy==true) 
    return viewMaxContent_easy()
	   ///alert('viewMaxContent');	
 //dla minimenu dziala tylko gdy minimenu.width = 150px, gdy recznie powiekszy mimimenu, to nie dziala
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;

  //sprawdzanie jak wysokie jest menu gorne
  xnr = place.WinLIKE.searchwindow('winHeader');  // znajdz okno Menu gornego
  var topsize = place.WinLIKE.windows[xnr].Height;
    
  var contH = Math.floor( place.WinLIKE.browsersize().Height -24 - topsize );
	var ListH = place.WinLIKE.browsersize().Height - topsize - contH;

  	var xnr = place.WinLIKE.searchwindow('winTop');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = true;
  	place.WinLIKE.windows[xnr].Top = topsize;
  	place.WinLIKE.windows[xnr].Height = ListH;
  	place.WinLIKE.windows[xnr].draw();
  
  	var xnr = place.WinLIKE.searchwindow('winContent');  // znajdz okno
  	place.WinLIKE.windows[xnr].Mn = false;
  	place.WinLIKE.windows[xnr].Top = ListH + topsize;
  	place.WinLIKE.windows[xnr].Height = contH;
  	place.WinLIKE.windows[xnr].draw();
	
	//place.WinLIKE.resizewindows();
}//-----------------------------------------------------------------------------




/**
 * Pokazuje/ukrywa okreslony element
 *
 * @param string targetObjId Id obiektu
 * @param boolean True widoczny, false niewidoczny
 * @return none
 *
 */
function showHideDiv(targetObjId, visible)
{
    var targetObj = document.getElementById(targetObjId);
    if (targetObj != null)
	{
        if (visible == false)
			targetObj.style.display = 'none';
		else
		    targetObj.style.display = '';
	}
}


/**
 * Pokazuje/ukrywa okreslony element
 *
 * @param string targetObjId Id obiektu
 * @param boolean True widoczny, false niewidoczny
 * @return none
 *
 */
function showHideDiv2(targetObjId)
{
    var targetObj = document.getElementById(targetObjId);
    if (targetObj != null)
	{
        if (targetObj.style.display == 'none')
			targetObj.style.display = '';
		else
		    targetObj.style.display = 'none';
	}
}


/**
 * Zwraca obiekt 'document' z szukanego okna
 *
 * @param string targetWin Okno docelowe
 *
 */
function findWindow(targetWin)
{
   if (WinEasy==true) 
    return findWindow_easy(targetWin);
    
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    return place.WinLIKE.windows[xnr].innerdoc();
	}
	else
	{
	    return null;
	}
}


/**
 * Zwraca obiekt 'window' z szukanego okna
 *
 * @param string targetWin Okno docelowe
 *
 */
function getWindowObject(targetWin)
{
   if (WinEasy == true) 
    return getWindowObject_easy(targetWin);
    
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    return place.WinLIKE.windows[xnr].innerframe();
	}
	else
	{
	    return null;
	}
}


/**
 * Pokazuje wybrane okno
 *
 * @param string targetWin Okno docelowe
 * @return none
 *
 */
function showWindow(targetWin)
{
   if (WinEasy == true) 
    return showWindow_easy(targetWin);
    
	var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    place.WinLIKE.windows[xnr].Vis = true;

	    place.WinLIKE.windows[xnr].front();
		place.WinLIKE.windows[xnr].draw();
		place.WinLIKE.resizewindows();
	}
}


/**
 * Ukrywa wybrane okno
 *
 * @param string targetWin Okno docelowe
 * @return none
 *
 */
function hideWindow(targetWin)
{
  if (WinEasy == true) 
    return hideWindow_easy(targetWin);
  
  var place = recognizeWinLIKE_(top);
	if (place == undefined) return false;
	xnr = place.WinLIKE.searchwindow(targetWin);  // znajdz okno
	if (xnr != null)
	{
	    place.WinLIKE.windows[xnr].Vis = false;

		place.WinLIKE.windows[xnr].draw();
		place.WinLIKE.resizewindows();
	}
}


/**
 * Tworzy nowy obiekt hidden w formularzu
 *
 * @param object targetDocument Dokument w ktorym nalezy utworzyc nowe pole
 * @param string fieldName Nazwa pola
 * @param string fieldValue Wartość pola
 *
 */
function createHiddenField(targetDocument, fieldName, fieldValue)
{
	if (targetDocument != null)
	{
	    var newObj = targetDocument.createElement('input');
	    newObj.name = fieldName;
	    newObj.value = fieldValue;
	    newObj.type = 'hidden';
	    
	    return newObj;
	}
	else
	{
	    return null;
	}
}


/**
 * Wyczysczenie opcji w polu Select
 *
 * @return none
 *
 */
function clearOptions(selectObject)
{
	if (selectObject != null)
	{
	    // wyczyszczenie elementow
	    var len = selectObject.options.length;
		for (var i = len - 1; i >= 0; i--)
		{
		    selectObject.options[i] = null;
		}
	}
}

/**
 * Wyczysczenie opcji w polu Input
 *
 * @return none
 *
 */
function ClearField(InputObject)
{
  //alert(InputObject);
	if (InputObject != null)
	{
	   InputObject.value = '';
	}
}


/**
 * wpisanie wartosci do pola o danym id id
 *
 * @return none
 *
 */
function SetValue(id, value)
{
  
  if ( typeof(document.getElementById(id)) !== "undefinded" )
  {
    document.getElementById(id).value = value
  }
  else
    return false;
}

function SetValueFromSelect(el_sel , el_input)
{
  el_input.value = el_sel.value;
}

/**
 * Przekopiowanie zaznaczonej opcji z jednego pola select do drugiego
 *
 * @param string srcObjId Id zrodlowego pola
 * @param string dstObjId Id docelowego pola
 * @param bool only_ one  - jak true to pozwala na skopiowanie tylko jednego pola (jak jest zaznaczone wszystkie to pierwszy) 
 * @return none
 *
 */
function copyOption(srcObjId, dstObjId , only_one )
{
	var srcObj = document.getElementById(srcObjId);
	var dstObj = document.getElementById(dstObjId);
	
	if (srcObj != null && dstObj != null)
	{
		var len = srcObj.options.length;
		var len2 = dstObj.options.length;
		
		for (var i = 0; i < len; i++)
		{
		    // sprawdzam czy opcja jest zaznaczona
		    if (srcObj.options[i].selected == true)
		    {
		        var option_exists = false;
		        
		        // sprawdzam czy opcja jest juz na liscie docelowej
		        for (var j = 0; j < len2; j++)
		        {
		            if (dstObj.options[j].value == srcObj.options[i].value)
		            {
		                option_exists = true;
		                break;
					}
				}

				// jesli nie ma opcji to dodaje do listy docelowej
				if (option_exists == false)
				{
				  if ( only_one != false  )
            clearOptions(dstObj);
            
            // nowy obiekt option
					var newOption = document.createElement('option');

					dstObj.options.add(newOption);
					newOption.value = srcObj.options[i].value;
					newOption.innerHTML = srcObj.options[i].innerHTML;
					
					if ( only_one != false  )
            return true;
					//break;
				}
			}
		}
	}
	else
	{
	    //alert('Nie odnaleziono obiektow.');
	}
}



/**
 * Usuniecie zaznaczonej opcji w obiekcie
 *
 * @param string dstObjId Id pola, z ktorego nalezy usunac opcje
 * @return none
 *
 */
function removeOption(dstObjId , value)
{
	var dstObj = document.getElementById(dstObjId);
	
	if (dstObj != null)
	{
      var len = dstObj.options.length;
	    
	    for (var i = len - 1; i >= 0; i--)
	    {
	        if (value != null && typeof(value) != "undefined" )
	        {
	            if (dstObj.options[i].value == value)
    	            dstObj.options[i] = null;
          }
          else
          {
    	        if (dstObj.options[i].selected == true)
    	            dstObj.options[i] = null;
		      }
    }
	}
}

/**
 * Usuniecie zaznaczonej opcji w obiekcie
 *
 * @param string dstObjId Id pola, z ktorego nalezy usunac opcje -rozni sie od poprzediej ze przekazuje wskaznik do obiektu
 * @return none
 *
 */
function removeOption2(obj, dstObjId , value)
{
	var dstObj = obj.getElementById(dstObjId);
	
	if (dstObj != null)
	{
      var len = dstObj.options.length;
	    
	    for (var i = len - 1; i >= 0; i--)
	    {
	        if (value != null && typeof(value) != "undefined" )
	        {
	            if (dstObj.options[i].value == value)
    	            dstObj.options[i] = null;
          }
          else
          {
    	        if (dstObj.options[i].selected == true)
    	            dstObj.options[i] = null;
		      }
    }
	}
}

function SetPopupSize( w, h )
{
   if (WinEasy == true) 
    return SetPopupSize_easy( w, h );  
  
  var place = recognizeWinLIKE_(top);
  if (place == undefined) return false;
  var xnr = place.WinLIKE.searchwindow('winPopupClose');  // znajdz okno Popup
  place.WinLIKE.windows[xnr].Width = w;
  place.WinLIKE.windows[xnr].Height = h;
  place.WinLIKE.windows[xnr].draw();
}


function ResetPopupSize()
{
   if (WinEasy == true) 
    return ResetPopupSize_easy();

  var place = recognizeWinLIKE_(top);
  if (place == undefined) return false;
  var xnr = place.WinLIKE.searchwindow('winPopupClose');  // znajdz okno Popup
  place.WinLIKE.windows[xnr].Width = 700;
  place.WinLIKE.windows[xnr].Height = 500;
  place.WinLIKE.windows[xnr].draw();
}








//----------------------- COACH NOWE -------------------------------------------





/**
 * Przekopiowanie zaznaczonej opcji z jednego pola select do drugiego
 *
 * @param string srcObjId Id zrodlowego pola
 * @param string dstObjId Id docelowego pola
 * @param string cloneSrcObjId Id klonu źródłowego pola (jak są userzy i ownerzy)
 * @param string cloneDstObjId Id klonudocelowego pola (jak są userzy i ownerzy i kasowanie z listy przydzielonych)
 * @return none
 *
 */
function moveOption(srcObjId, dstObjId, cloneSrcObjId, cloneDstObjId)
{
	//alert('move');
  var srcObj = document.getElementById(srcObjId);
	var dstObj = document.getElementById(dstObjId);
	if (cloneSrcObjId != false) var cloneSrcObj = document.getElementById(cloneSrcObjId);
	if (cloneDstObjId != false) var cloneDstObj = document.getElementById(cloneDstObjId);

	if (srcObj != null && dstObj != null)
	{
		var len = srcObj.options.length;
		var len2 = dstObj.options.length;
		
		var aToDelete = new Array(len);
		
		for (var i = 0; i < len; i++)
		{
		    var SrcVal=srcObj.options[i].value;
        
        // sprawdzam czy opcja jest zaznaczona
		    if (srcObj.options[i].selected == true)
		    {
 		     
					var newOption = document.createElement('option');
					dstObj.options.add(newOption);
					newOption.value = SrcVal;
					newOption.innerHTML = srcObj.options[i].innerHTML;

          // nowy obiekt option dla listy-clona DST
          if (cloneDstObjId != false) {
            var newCloneOption = document.createElement('option');
            cloneDstObj.options.add(newCloneOption);
            newCloneOption.value = SrcVal;
  					newCloneOption.innerHTML = srcObj.options[i].innerHTML;
          }

					//srcObj.options[i] = null; //kasowanie z listy
					aToDelete[i]=true;
					
          //kasowanie z clona SRC
          if (cloneSrcObjId != false){
              var clen=cloneSrcObj.options.length;
          		for (var k = 0; k < clen; k++){
          		  if (cloneSrcObj.options[k] != undefined && cloneSrcObj.options[k].value == SrcVal) {
                  cloneSrcObj.options[k] = null;
                  }
		          }
          }      
			}
		}
		//dopiero teraz kasujemy zbedne wpisy PAMIETAJAC ZE SKASOWANIE PRZEINDEKSOWUJE TABLICE
		var deleted=0;
    for (var i = 0; i < len; i++){
		    if (aToDelete[i]==true) {
          srcObj.options[i-deleted] = null;
          deleted++;
        }  
    }
		
	}
	else
	{
	    //alert('Nie odnaleziono obiektow.');
	}
}




// --------- END COACH NOWE ----------------------------------------------------







/**
 * Zaznacza wszystkie opcje w danym polu
 *
 * @param string dstObjId Id pola, w ktorym zaznaczyc wszystkie opcje
 * @return none
 *
 */
function selectAllOptions(dstObjId)
{
	var dstObj = document.getElementById(dstObjId);

	if (dstObj != null)
	{
	    var len = dstObj.options.length;

	    for (var i = 0; i < len; i++)
	    {
	        dstObj.options[i].selected = true;
		}
	}
}


function openPrintWindow(ldtn_id, print_id, printed_id)
{
	var win = window.open('kredyt_druki.php?do_action=print&kredyt_id=' + ldtn_id + '&print_id=' + print_id + '&printed_id=' + printed_id, '_blank',
		'toolbar=no,scrollbars=yes,statusbar=yes,width=860,height=600');
}

function openPrintWindow2(ldtn_id, print_id, printed_id, stat_prod_typ)
{
	var win = window.open('renego_druki.php?do_action=print&kredyt_id=' + ldtn_id + '&print_id=' + print_id + '&printed_id=' + printed_id + '&stat_prod_typ=' + stat_prod_typ, '_blank',
		'toolbar=no,scrollbars=yes,statusbar=yes,width=860,height=600');
}

function openPrintWindow3(ldtn_id, print_id, printed_id, guarantor_id)
{
	var win = window.open('kredyt_druki.php?do_action=print&kredyt_id=' + ldtn_id + '&print_id=' + print_id + '&printed_id=' + printed_id + '&guarantor_id='+guarantor_id, '_blank',
		'toolbar=no,scrollbars=yes,statusbar=yes,width=860,height=600');
}


function openPrintWindow4(ldtn_id, print_id, printed_id)
{
	var win = window.open('kredyt_druki.php?do_action=print&kredyt_id=' + ldtn_id + '&print_id=' + print_id + '&printed_id=' + printed_id + '&check_form=false', '_blank',
		'toolbar=no,scrollbars=yes,statusbar=yes,width=860,height=600');
}

function setNoTransparent(elem_id)
{
	setTransparent(elem_id, 100);
}


function setTransparent(elem_id, opacity)
{
	var obj1 = document.getElementById(elem_id);
	if (obj1 != null)
	{
		obj1.style.setAttribute('filter', 'alpha(opacity='+ opacity +')');
		obj1.style.setAttribute('-moz-opacity', opacity/100);
		obj1.style.setAttribute('opacity', opacity/100);
	}
}


function printpreview()
{
	var OLECMDID = 7;
	/* OLECMDID values:
	* 6 - print
	* 7 - print preview
	* 1 - open window
	* 4 - Save As
	*/
	var PROMPT = 1; // 2 DONTPROMPTUSER
	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';

	document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	WebBrowser1.ExecWB(OLECMDID, PROMPT);
	WebBrowser1.outerHTML = "";
}

var tmp_nip_obj_id;
var tmp_nip_company_info = new Array(5);

function nip_get_change_handler()
{
    if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        //alert(result);
        ajax_CreateOptions(result, document.getElementById(tmp_nip_obj_id));
    }
}


function nip_get(src_obj_id, dst_obj_id, div_obj_id)
{
	var obj = document.getElementById(src_obj_id);
	if (obj != null)
	{
		if (obj.value.length >= 4)
		{
//			alert(dst_obj_id);
			tmp_nip_obj_id = dst_obj_id;
			document.getElementById(div_obj_id).style.display = '';
	    	ajax_Init('ajax_lista_firm.php?nip=' + obj.value, nip_get_change_handler)
		}
		else
		{
//			alert('Proszę wpisać dłuższy ciąg znaków.');
		}
	}
}


function nip_change_handler()
{
    if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        //alert(result);
        
        var tmp_info = result.split('###');
        
        var tmp_field = tmp_nip_company_info[0];
        if (tmp_field != '')
        	document.getElementById(tmp_field).value = tmp_info[0];
        if (tmp_nip_company_info[1] != '')
	        document.getElementById(tmp_nip_company_info[1]).value = tmp_info[1];
        if (tmp_nip_company_info[2] != '')
	        document.getElementById(tmp_nip_company_info[2]).value = tmp_info[2];
        if (tmp_nip_company_info[3] != '')
        	document.getElementById(tmp_nip_company_info[3]).value = tmp_info[3];
        if (tmp_nip_company_info[4] != '')
	        document.getElementById(tmp_nip_company_info[4]).value = tmp_info[4];
    }
}

function nip_change(nazwa_id, adres_id, nip_id, regon_id, telefon_id, select_id)
{
	if (tmp_nip_company_info[0] != '')
		tmp_nip_company_info[0] = nazwa_id; 
	if (tmp_nip_company_info[1] != '')
		tmp_nip_company_info[1] = adres_id; 
	if (tmp_nip_company_info[2] != '')
		tmp_nip_company_info[2] = nip_id; 
	if (tmp_nip_company_info[3] != '')
		tmp_nip_company_info[3] = regon_id; 
	if (tmp_nip_company_info[4] != '')
		tmp_nip_company_info[4] = telefon_id; 

	ajax_Init('ajax_info_firma.php?key=' + document.getElementById(select_id).value, nip_change_handler)
}



function TableCellOver(td)
{
  var bgBackup = '';
	bgBackup = td.style.backgroundColor;
	var ile = td.parentNode.cells.length;
	
	for (var i = 0; i < ile; i++)
	{
		td.parentNode.cells[i].style.backgroundColor = '#FFFFCC';
	//	td.parentNode.cells[i].style.color="green";
	//	alert(td.parentNode.cells[i].style.color);
	}
}

function TableCellOut(td)
{
  var bgBackup = '';
	var ile = td.parentNode.cells.length;

	for (var i = 0; i < ile; i++)
	{
		td.parentNode.cells[i].style.backgroundColor = bgBackup;
		//td.parentNode.cells[i].style.color="";
	}
}

function IconOver(icon)
{
  var bgBackup = '';
  var brdBackup = '';
	icon.style.backgroundColor = '#FFFFAC';
	icon.style.border = '1px outset #FFFFFF';

}

function IconOut(icon)
{
  icon.style.backgroundColor = '';
  icon.style.border = '1px outset #FFFFFF' ;
}

function Icon2Over(icon)
{
  var bgBackup = '';
  var brdBackup = '';
	icon.style.backgroundColor = '#EEEEEE';
	//icon.style.border = '1px solid #CCCCCC';

}

function Icon2Out(icon)
{
  icon.style.backgroundColor = '';
  //icon.style.border = '1px solid #CCCCCC' ;
}

// sprawia ze sa widoczne pola lub nie
function make_visible (typer, flag, obj)
{
    var table = obj.getElementById('table_right');
    var aTr = table.getElementsByTagName('tr');
    var aTrlength = aTr.length;
    var disp = "";
    
    for (j=1; j<aTrlength ; j++)
    {
       sId = aTr[j].id;
       if ( sId.substring(0,6) == "tr_ad"+typer )
       {
          if (flag==false)
            disp="none";
          aTr[j].style.display = disp;

       }
    }
    
    if (flag==false)
      obj.getElementById('td_wypelnienie').innerHTML = "";
    else
      obj.getElementById('td_wypelnienie').innerHTML = "";
}

  
// aktywuje zakladki w dok
function ActivateZak(obj, id)
{
    // ustawienie odpowiedniego value na zmienną:
   // if ( document.getElementById("hid_zak_action").value == id )
    //  return false;
    obj.getElementById("hid_zak_action").value = id;
  
    //zakladki - grafika:
    obj.getElementById("zak_left_"+id).style.backgroundImage  = "url(./i/zak_left_act.jpg)";
    obj.getElementById("zak_tlo_"+id).style.backgroundImage  = "url(./i/zak_tlo_act.jpg)";
    obj.getElementById("zak_right_"+id).style.backgroundImage = "url(./i/zak_right_act.jpg)";
    for (k=1; k<=3; k++)
    {
        if ( k != id && obj.getElementById("zak_tlo_"+k).style.backgroundImage == "url(./i/zak_tlo_act.jpg)" )
        {
            obj.getElementById("zak_left_"+k).style.backgroundImage  = "url(./i/zak_left.jpg)";
            obj.getElementById("zak_tlo_"+k).style.backgroundImage  = "url(./i/zak_tlo.jpg)";
            obj.getElementById("zak_right_"+k).style.backgroundImage = "url(./i/zak_right.jpg)";
        }
    }
      
    //operacje na zakladkach
    switch (id)
    {
      case 1:
          make_visible(id, true, obj);
          make_visible(2, false, obj);
          
          emptiness = CheckEmptiness('input' , 'txt_ad1_kores_', obj); 
          if ( emptiness == 0 )
            ShowKores(obj, id,  false)
          else  
            ShowKores(obj, id,  true);
          
          //ClearSpecialFields('input','txt_adr');
          //ClearSpecialFields('select','txt_adr');
          
          // removeOption2(obj, 'txt_adr_type_id', 3 );
          // ReadonlyAddressFields ( false, txt_ad1 ,  obj);
          
          ScanForSimilar = true;
        break;
      
      
      case 2:
          //alert ('activate 2');
          make_visible(id, true, obj);
          make_visible(1, false, obj);
          
          emptiness = CheckEmptiness('input' , 'txt_ad2_kores_', obj); 
          if ( emptiness == 0 )
            ShowKores(obj, id,  false)
          else  
            ShowKores(obj, id,  true);
          
         
          //AddOptions2(obj, 3, "SKOKCOM" , document.getElementById('txt_ad2_type_id') );
          // obj.getElementById('txt_adr_type_id').options[3].disabled = true;
       
      
          // if ( isset($row_info['address_id']) && $row_info['address_id'] != '' ) 
          // alert(document.getElementById('hid_address_id').value);
          if ( obj.getElementById('hid_address_id').value == '' || obj.getElementById('hid_address_id').value == 0  )
          {
             // alert(obj.getElementById('hid_address_id').value);
              goToPage('adresy_gora.php?adding=1', 'winPopupClose') ;
          }
          
         // alert(obj.getElementById('txt_ad2_type_id').value);
          if (obj.getElementById('txt_ad2_type_id').value != 3 )
              ReadonlyAddressFields ( false, 'txt_ad2' , obj );
          else
              ReadonlyAddressFields ( true, 'txt_ad2' , obj );
          
          ScanForSimilar = false;
        break;
      
      
      case 3:
            make_visible(1, false, obj);
            make_visible(2, false, obj);
          //  ClearSpecialFields('input','txt_adr');
          // ClearSpecialFields('select','txt_adr');
            //document.getElementById("hid_address_id").value="";
            ScanForSimilar = false;
        break;
        
    }
}


function filtr_java_off ( word )
{
    var from = /___/g;
  	var to = '"';
    word =  word.replace(from ,to);
    
    var from = /----/g;
  	var to = "'";
    word =  word.replace(from ,to);

    return word;
}

/**
 * kopiuje kontakty z ksiazki adresowej do okna wskazanego w window 
 */
function copy_contact(id,type_id, company_name,first_name,surname,street,house_nr,local_nr,email,nip,regon,tel1,tel2,cellular,cellular2,fax,
                      post_code2,post_code3,city,country,pesel,www,kores_company_name,kores_first_name,kores_surname,kores_city,
                      kores_street,kores_house_nr, kores_local_nr,
                      kores_post_code2, kores_post_code3,kores_country,kores_tel1,kores_fax,window)
{   
    var place = recognizeWinLIKE_(top);
    if (place == undefined) return false;
    xnr = place.WinLIKE.searchwindow(window);
    if (xnr != null)
  	{
  	    var destination = place.WinLIKE.windows[xnr].innerdoc();
  	    destination.getElementById("hid_address_id").value = id;
  	    destination.getElementById("txt_ad2_type_id").value = type_id;
  	    destination.getElementById("txt_ad2_company").value = filtr_java_off(company_name);
  	    destination.getElementById("txt_ad2_first_name").value = filtr_java_off(first_name);
  	    destination.getElementById("txt_ad2_surname").value = filtr_java_off(surname);
  	    destination.getElementById("txt_ad2_street").value = street;
  	    destination.getElementById("txt_ad2_house_nr").value = house_nr;
  	    destination.getElementById("txt_ad2_local_nr").value = local_nr;
  	    destination.getElementById("txt_ad2_email").value = email ;
  	    destination.getElementById("txt_ad2_nip").value = nip;
  	    destination.getElementById("txt_ad2_regon").value = regon;
  	    destination.getElementById("txt_ad2_tel1").value = tel1;
  	    destination.getElementById("txt_ad2_tel2").value = tel2;
  	    destination.getElementById("txt_ad2_cel1").value = cellular;
  	    destination.getElementById("txt_ad2_cel2").value = cellular2;
  	    destination.getElementById("txt_ad2_fax").value = fax;
  	    destination.getElementById("txt_ad2_post_code2").value = post_code2;
  	    destination.getElementById("txt_ad2_post_code3").value = post_code3;
  	    destination.getElementById("txt_ad2_city").value = city ;
  	    destination.getElementById("txt_ad2_country").value = country ;
  	    destination.getElementById("txt_ad2_pesel").value = pesel ;
  	    destination.getElementById("txt_ad2_www").value = www ;
  	    
  	    
  	    destination.getElementById("txt_ad2_kores_company_name").value = filtr_java_off(kores_company_name);
  	    destination.getElementById("txt_ad2_kores_first_name").value = filtr_java_off(kores_first_name);
  	    destination.getElementById("txt_ad2_kores_surname").value = filtr_java_off(kores_surname);
  	    destination.getElementById("txt_ad2_kores_city").value = kores_city ;
  	    destination.getElementById("txt_ad2_kores_street").value = kores_street ;
  	    destination.getElementById("txt_ad2_kores_house_nr").value = kores_house_nr ;
  	    destination.getElementById("txt_ad2_kores_local_nr").value = kores_local_nr ;
  	    destination.getElementById("txt_ad2_kores_post_code2").value = kores_post_code2 ;
  	    destination.getElementById("txt_ad2_kores_post_code3").value = kores_post_code3 ;
  	    destination.getElementById("txt_ad2_kores_country").value = kores_country ;
  	    destination.getElementById("txt_ad2_kores_tel1").value = kores_tel1 ;
  	    destination.getElementById("txt_ad2_kores_fax").value = kores_fax ;
      	
        // sprawdza ile pol korespondencji jest wypelnionych, jak zero to chowa je
        var emptiness = CheckEmptiness('input' , 'txt_ad2_kores_', destination);
        if (emptiness == 0 )
        {
            ShowKores(destination, 2 , false);
        }
        else
        {
            ShowKores(destination, 2 , true);
        }
        //alert(emptiness);
        
        
      	// jak skokcom to blokuje edycje: 
  	    if (type_id == 3)
  	    {  
             ReadonlyAddressFields(true, 'txt_ad2' ,destination);
        }
        else
        {
             ReadonlyAddressFields(false, 'txt_ad2', destination);
  	    }
  	    
  	    ActivateZak(destination, 2);
  	    
         var powiadom = destination.getElementById('duplicate_adr');
         powiadom.className = 'duplicate_adr_hid';
         powiadom.innerHTML = '&nbsp;';
        
        // alert (place.WinLIKE.searchwindow("winPopupClose"));
         closeWin("winPopupClose");

  	}
}

// zlicza ile pol jest wypelnionych
function CheckEmptiness ( sTagName, sBeginName, doc )
{
    //alert ('ch_emt');
    var wynik = 0;
//    var nodeList = document.getElementsByTagName(sTagName);
    var nodeList = doc.getElementsByTagName(sTagName);
    var j = nodeList.length;
    
    for (var i = 0; i < j; i++)
    {
       
        tmp_str = nodeList[i].id;
       // alert(tmp_str.substring(0,7));
    	  if (tmp_str.substring(0,sBeginName.length) == sBeginName)
    	  {
    	      if (nodeList[i].value != '')
              wynik++; 
    	  }
    }
    return wynik;
}

// ustawia readonly
function ReadonlySpecialFields( sTagName, sBeginName , bool, doc)
{
    var nodeList = doc.getElementsByTagName(sTagName);
    var j = nodeList.length;
    
    for (var i = 0; i < j; i++)
    {
        tmp_str = nodeList[i].id;
       // alert(tmp_str.substring(0,7));
    	  if (tmp_str.substring(0,sBeginName.length) == sBeginName)
    	  {
            if (sTagName == "input")
              ReadonlyField(tmp_str, bool, doc);
    	      if (sTagName == "select")
    	        ReadonlyFieldSelect(tmp_str, bool, doc);
        }
    }
}

function ReadonlyField(field, bool, doc)
{
    var srcObj = doc.getElementById(field);
    
    //alert(srcObj);
    
    if (bool == true)
      srcObj.readOnly = true;
    else
      srcObj.readOnly = false;
}

function ReadonlyFieldSelect(field, bool, doc)
{
    var srcObj = doc.getElementById(field);
    
    //alert(srcObj);
  //  return true;
    if (bool == true)
    {
          var o=srcObj.options;
          var ile= o.length;
          for (var j = 0; j < ile; j++)
          {
            if (srcObj.options[j].value != 3 )
              srcObj.options[j].disabled = true;
            else
              srcObj.options[j].disabled = false;
          }
    }
    else
    {
          var o=srcObj.options;
          var ile= o.length;
          for (var j = 0; j < ile; j++)
          {
              if (srcObj.options[j].value != 3 )
                srcObj.options[j].disabled = false;
              else
                srcObj.options[j].disabled = true;
          }
    }
}

function ReadonlyAddressFields ( bool, sBeginName , doc )
{
   //txt_ad2
   ReadonlySpecialFields('input' , sBeginName , bool , doc);
   ReadonlySpecialFields('select', sBeginName, bool, doc);
   //ReadonlySpecialFields('input','chb_ad2', bool, doc);
}


// ustawia disable na true lub false dla pol
function DisableSpecialFields( sTagName, sBeginName , bool, doc)
{
    var nodeList = doc.getElementsByTagName(sTagName);
    var j = nodeList.length;
    
    for (var i = 0; i < j; i++)
    {
       
        tmp_str = nodeList[i].id;
       // alert(tmp_str.substring(0,7));
    	  if (tmp_str.substring(0,sBeginName.length) == sBeginName)
    	  {
            DisableField(tmp_str, bool, doc);
    	  }
    }
}

function DisableField(field, bool, doc)
{
    var srcObj = doc.getElementById(field);
    
    //alert(srcObj);
    
    if (bool == true)
      srcObj.disabled = true;
    else
      srcObj.disabled = false;
}

function DisableAddressFields ( bool, doc)
{
   DisableSpecialFields('input','txt_ad2', bool , doc);
   DisableSpecialFields('select','txt_ad2', bool, doc);
   DisableSpecialFields('input','chb_ad2', bool, doc);
}

// pokazuje korespondencje w zaleznosci od flag :
// jak 'none' to zelezy czy checked jest zaznaczony, jak true to pokazuje jak false to nie
function ShowKores (obj, typer,  flag)
{
    
    var disp="";
    if (obj.getElementById('chb_ad' + typer + '_kores_show') == null )
      alert ('brak checkboxa');
     
    if ( flag == 'none' )
    {
        if (obj.getElementById('chb_ad' + typer + '_kores_show').checked != true)
            disp="none";
    }
    else
    {
        if (flag == true)
        {
            obj.getElementById('chb_ad' + typer + '_kores_show').checked = true;
        }
        else
        {
            obj.getElementById('chb_ad' + typer + '_kores_show').checked = false;
            disp="none";
        }
    }
    
    var table = obj.getElementById('table_right');
    if (table == null)
      alert ('brak tabeli');
      
    var aTr = table.getElementsByTagName('tr');
    var aTrlength = aTr.length;
 
    for (j=1; j<aTrlength ; j++)
    {
       sId = aTr[j].id;
       if ( sId.substring(0,13) == "tr_ad" + typer + "_kores_" )
       {
          aTr[j].style.display = disp;
       }
    }
}

// fukcja alertujaca do tetow
function echo()
{
    alert('funkcja echujaca alert na ekran');
}
  
  function PrzechwycEnter(el, nazwa_funkcji)
  {
      var nazwa_funkcji = nazwa_funkcji;
      
      if (el.addEventListener)
      {
        el.addEventListener("keydown", RozpoznajKlawisz , false);
      } 
      else if (el.attachEvent)
      {
        el.attachEvent('onkeydown', RozpoznajKlawisz );
      }
    
      function RozpoznajKlawisz(e)
      {
        //e - zdarzenie - event
        var characterCode // tutaj przechowuje kod klawisza
        
        if (e && e.which) // dla NN4
        { 
          e = e
          characterCode = e.which  // NN4
        }
        else
        {
          e = event
          characterCode = e.keyCode //IE's keyCode
        }
        
        switch(characterCode)
        {
            //** ascii = 13 
            //** ENTER 
            case 13:
                eval(nazwa_funkcji); //submit the form 
               // echo();
                break;
        }
     }
  }

/**
 * Obsluga okna modalnego
 *
 * WYWOLANIE: window_force_focus.init(); w skrypcie ktore ma byc oknem modalnym
 *
 */
var window_force_focus = {
	init : function() {
		var opener = window.opener;
		var child_window = self;
		if (opener.addEventListener) {
			opener.addEventListener("focus", function() {
				setTimeout(function(){
					if (!opener || !child_window) return;
					if (!opener.blur || !child_window.focus) return;
					opener.blur();
					child_window.focus();
				}, 0);
			}, false)
		} else if (opener.attachEvent) {
			opener.attachEvent("onfocus", function() {
				opener.blur();
				child_window.focus();
			})
		}
	}
}





function AddOptions(value, inner , selectObject)
{
      //szukanie opcji o danym value
      
      var len = selectObject.options.length;
      for (var i = 0; i < len; i++)
	     {
          if (selectObject.options[i].value == value){
          selectObject.options[i].innerHTML=inner;
          
          return true; //konczymy funkcje
          }
	     }
			  
        //var newOption = document.createElement('option');
				//newOption.value = value;
			  //newOption.innerHTML = inner;
        //alert(selectObject.options.length);
        //alert(selectObject.options);
        selectObject.options[selectObject.options.length] = new Option(inner, value);
        //alert('yy');

}


function AddOptions2(obj, value, inner , selectObject)
{
      //szukanie opcji o danym value
      
      var len = obj.selectObject.options.length;
      for (var i = 0; i < len; i++)
	     {
          if (obj.selectObject.options[i].value == value){
          obj.selectObject.options[i].innerHTML=inner;
          
          return true; //konczymy funkcje
          }
	     }
			  
        //var newOption = document.createElement('option');
				//newOption.value = value;
			  //newOption.innerHTML = inner;
        //alert(selectObject.options.length);
        //alert(selectObject.options);
        obj.selectObject.options[selectObject.options.length] = new Option(inner, value);
        //alert('yy');

}
/**
 *  Funkcja dla przycisku Wyślij, zabezpiecza przed dwukrotnym wysłaniem formularza poprzez JS
 */ 
function SubmitById( id, sender ){

if ( sender.tag == '7' ) {
                         //alert('blok');
                         return false;
                         } 

sender.tag = '7';
var form = document.getElementById( id ).submit();

}

/**
 * Funkcja znajduje lewe menu i zgłasza mu konieczność odświeżenia liczby danego typu związanego z przeczytaniem.
 *
 */  
function RecountLeft( object_type ){

	var place = recognizeWinLIKE_(top);
  if (place == undefined) return false;
  xnr = place.WinLIKE.searchwindow('winMenu');  // znajdz okno
  if (xnr != null){
    var menu = place.WinLIKE.windows[xnr].innerframe();//innerdoc()
    menu.refreshToDo( object_type );
	}
  

}

function GetPrivPass(){
  var re = prompt("Zabezpieczenie hasłem:");
  return '&ppass=' + re;
}


/**
 *  Zamienia obiektowi jedną klasę na inną nie uszkadzając reszty
 *  Używa prefiksu, czyli potrafi zmienic klase mark_878 na mark_777 ja mu się poda mark_ 
 *
 */  

function ClassSwitch(object, old_class_prefix, new_class ){
    var tmpa = object.className.split(' ');
    var ile = tmpa.length;
    var newclass = '';
    var dlugosc = old_class_prefix.length;
    var switched = false;
    for (var i = 0; i < ile; i++)
    {
        var nazwa = tmpa[i].substring(0, dlugosc);
        if ( nazwa != old_class_prefix ) newclass = newclass + ' ' + tmpa[i];
        else {
            newclass = newclass + ' ' + new_class; //podmiana
            switched = true; //oznaczenie ze byla podmiana
        }
    } 
    if (switched == false) newclass = newclass + " " +new_class; //jak nie było podmiany dodajemy na koncu
    object.className=newclass;
}

/*****************************************************************************
 * Funkcje Markerów oraz zrobienia
 *
 */
 
 
 /*  Marker podglądu  */
 
     function mark_handler()
  	{
  	  if (ajax_IsCompleteRequest() == true)
  		{
  	        var result = ajax_GetResult();
  	        var image = document.getElementById('mark_btn');
            image.src="./i/icons/marker25.gif";
            if ( result == '1' ) {
                                  image.className='HighlightButtonOn';
                                  OffMarkersButtons();                                            
                                  LastButton.style.border = '3px solid black';
                                 } 
  	        else if ( result == '0' ) {
                                  image.className='HighlightButtonOff';
                                  OffMarkersButtons()
                                  }
  	        else alert ( 'RESULT: ' + result );
  	        
  	  }
  	}
  	
  	function OffMarkersButtons(){
                                    var Elements = document.getElementsByName('marker_btn');
                                    var ile = Elements.length;
                                  	for (var i = 0; i < ile; i++)
                                  	{
                                      Elements[i].style.border = '1px solid black';
                                  	}
    }
  	
    
    function Mark(targetObj, mark_nr, obj_type, obj_id)
    {
      	document.getElementById('mark_btn').src="./i/busy.gif";
        ajax_Init('ajax_mark.php?id='+obj_id+'&type='+ obj_type +'&mark='+mark_nr, mark_handler);
        LastButton = targetObj;
    }


/* Oznaczenie zrobienia */

    LastZrob = false;

function done_handler()
{
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        
        if ( result == '1' ) {
                              LastZrob.className='zrob_'+result;
                              ClassSwitch(LastZrob.parentNode.parentNode.parentNode, 'niezrobione', '' )
                             } 
        else if ( result == '0' ) {
                              LastZrob.className='zrob_'+result;
                              ClassSwitch(LastZrob.parentNode.parentNode.parentNode, 'niezrobione_off', 'niezrobione' )
                              }
        else alert (  result );
        
        
  }
}//------------------------------------------------------------------------------


function SwitchDone(sender, obj_type, obj_id){
  var tmp = sender.className.split('_');
  var mark = tmp[1];
  sender.className = 'zrob_work';
  if ( mark == 1 ) mark = 0;
  else if ( mark == 0 ) mark = 1;
  LastZrob = sender;
  ajax_Init('ajax_done.php?id='+obj_id+'&type='+ obj_type +'&mark='+mark, done_handler);
  
}//------------------------------------------------------------------------------


var LastNoreadButton = false;

function switch_readed_handler()
{
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        var _btn = document.getElementById('noread_btn');        
        
        if ( result == '0' ) {
                              //wraca 0 - oznaczono jako nieczytane
                              LastNoreadButton.className = 'readed_no';
                              var klasa = LastNoreadButton.parentNode.parentNode.className;
                              klasa = klasa.replace('font_normal', '');
                              klasa = klasa + ' font_noread';
                              LastNoreadButton.parentNode.parentNode.className = klasa;
                             } 
        else if ( result == '1') {
                              LastNoreadButton.className = 'readed_yes';
                              var klasa = LastNoreadButton.parentNode.parentNode.className;
                              klasa = klasa.replace('font_noread', 'font_normal');
                              klasa = klasa.replace('font_mod', 'font_normal');
                              klasa = klasa.replace('font_new', 'font_normal');
                              LastNoreadButton.parentNode.parentNode.className = klasa;
                              }
        else alert (  result );
        
        
  }
}//------------------------------------------------------------------------------

function SwitchReaded(sender, obj_type, obj_id, ver){
  var tmp = sender.className.split('_');
  var decyzja = tmp[1];
  LastNoreadButton = sender;
  ajax_Init('ajax_readed.php?id='+obj_id+'&type='+ obj_type +'&prev='+decyzja +'&ver='+ver, switch_readed_handler);
  
}//------------------------------------------------------------------------------


    
var MarkRow = false; // to globalna na  rzad ktory byl klikniety markerem
var MarkType = false; //typ obiektu oznaczanego
var MarkId = false; //id obiektu oznaczanego
var MarkNr = false; //id obiektu oznaczanego

function DisplayMarkers(e, sender, obj_type, obj_id){
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	
	MarkRow = sender.parentNode.parentNode.parentNode;
	MarkType = obj_type;
	MarkId = obj_id;
	    var Probnik = document.getElementById('probnik_tel');
      Probnik.style.display="";
      Probnik.style.top = posy - 40;
      Probnik.style.left = posx - 40;
}//---------------------------------------------------------------

function MarkSelected(sender, mark_nr)
{
    document.getElementById('probnik_tel').style.display="none"; //schowaj probnik
    MankNr = mark_nr;
    ajax_Init('ajax_mark.php?id='+MarkId+'&type='+ MarkType +'&mark='+mark_nr, mark_selected_handler);
}//---------------------------------------------------------------


function mark_selected_handler()
{
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        if ( result == '1' ||  result == '0' ) {
                              var tmpa = MarkRow.className.split(' ');
                              var ile = tmpa.length;
                              var newclass = '';
                              for (var i = 0; i < ile; i++)
                              {
                                  var nazwa = tmpa[i].substring(0, 11);
                                  if ( nazwa != 'mark_marker' )
                                  newclass = newclass + ' ' + tmpa[i];
                              } 
                              if (  result == '1' ) newclass = newclass + " mark_marker" +MankNr;
                              MarkRow.className = newclass;
                             }
        else alert ( 'RESULT: ' + result );
        
        
  }
}//------------------------------------------------------------

var MarkDelete = false;

function DeletePersonal(sender, obj_type, obj_id, mark_nr)
{
    sender.className="zrob_work"; //klepsydra
    MarkDelete = sender;
    MankNr = mark_nr;
    MarkRow = sender.parentNode.parentNode.parentNode;
    MarkType = obj_type;
	  MarkId = obj_id;
    ajax_Init('ajax_mark.php?id='+obj_id+'&type='+ obj_type +'&mark='+mark_nr, delete_personal_handler);
}//---------------------------------------------------------------


function delete_personal_handler()
{
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        if ( result == '1' ||  result == '0' ) {
                              var tmpa = MarkRow.className.split(' ');
                              var ile = tmpa.length;
                              var newclass = '';
                              for (var i = 0; i < ile; i++)
                              {
                                  var nazwa = tmpa[i].substring(0, 11);
                                  if ( nazwa != 'mark_marker' )
                                  newclass = newclass + ' ' + tmpa[i];
                              } 
                              if (  result == '1' ) newclass = newclass + " mark_marker" +MankNr;
                              MarkRow.className = newclass;
                              if (result == '1') {
                                MarkDelete.className = "undelete16";
                                document.getElementById('re_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                document.getElementById('dsw_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                document.getElementById('zsw_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                }
                              else if (result == '0') {
                                MarkDelete.className = "delete16";
                                document.getElementById('re_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                document.getElementById('dsw_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                document.getElementById('zsw_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                }
                             }
        else alert ( 'RESULT: ' + result );
        
        
  }
}//------------------------------------------------------------


var MarkDelete = false;

function DeletePersonalPodgladu(sender, obj_type, obj_id, mark_nr)
{
    return false;
    sender.src="./i/icons/klepsydra.png"; //klepsydra
    MarkDelete = sender;
    MankNr = mark_nr;
    MarkType = obj_type;
	  MarkId = obj_id;
    ajax_Init('ajax_mark.php?id='+obj_id+'&type='+ obj_type +'&mark='+mark_nr, delete_personal_handler);
}//---------------------------------------------------------------


function delete_personal_podgladu_handler()
{
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        alert(result);
        if ( result == '1' ||  result == '0' ) {
                              if (  result == '1' ) newclass = newclass + " mark_marker" +MankNr;
                              MarkRow.className = newclass;
                              if (result == '1') {
                                MarkDelete.className = "undelete16";
                                document.getElementById('re_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                document.getElementById('dsw_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                document.getElementById('zsw_'+MarkId).style.display="none"; //tu by sie przydalo jeszcze TYP
                                }
                              else if (result == '0') {
                                MarkDelete.className = "delete16";
                                document.getElementById('re_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                document.getElementById('dsw_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                document.getElementById('zsw_'+MarkId).style.display=""; //tu by sie przydalo jeszcze TYP
                                }
                             }
        else alert ( 'RESULT: ' + result );
        
        
  }
}//------------------------------------------------------------

function Hide(sender){
  sender.style.display="none";
}//---------------------------------------------------------------










function PopBox( posx, posy, w, h ){
   //nieuzywana
	    //var Probnik = document.createElement('div');
	    var Probnik = document.getElementById('probnik_tel');
      Probnik.style.display="";
      Probnik.style.width = w;
      Probnik.style.height = h;
      //Probnik.className = 'xxx';
      //document.body.appendChild(Probnik);
      //document.getElementById('tabslot_0').appendChild(Probnik);
      Probnik.style.top = posy - w/2;
      Probnik.style.left = posx - h/2;

}//--------------------------------------------------------------------

  function RowSwitch(sender, direction){
    
    var thisRow = sender.parentNode.parentNode;
    var tableBody = thisRow.parentNode;
    
    var len = tableBody.childNodes.length;
    var prev_row = 0; //nie jest oczywise ze to bedzie -1 od i
    var new_row = 0; //nie jest oczywise ze to bedzie -1 od i
    
    if ( direction==1 ){
      for (var i = 0; i < len; i++){
        if (tableBody.childNodes[i].nodeType == 1){
            if ( tableBody.childNodes[i] == thisRow ){
            new_row = i;
            break;
            }
            else prev_row = i;
        }
      }
    }
    if ( direction==2 ){
      
      var stop = false;
      for (var i = 0; i < len; i++){
        if (tableBody.childNodes[i].nodeType == 1){
            new_row = i;
            if (stop) break;
            if ( tableBody.childNodes[i] == thisRow ){
            prev_row = i
            stop = true;
            }
            
        }
      }
    }
    
    //teraz zamiana nodów 
    tableBody.insertBefore( tableBody.childNodes[new_row] , tableBody.childNodes[prev_row]);
 
  }//-------------------------------------------------------------------------







 
 function zlicz_minuty(godziny, minuty, wyjscie)
 {
    godzinyInt = parseInt(document.getElementById(godziny).value);
    minutyInt = parseInt(document.getElementById(minuty).value);
    suma = minutyInt + (godzinyInt*60);

    document.getElementById(wyjscie).value = suma;
 }//----------------------------------------------------------------------------
 
 
 //*************
 //  
 //dla tych przegladarek nadpisujemy funkcje:
 //
 //*************
  

function goTo3_easy(targetUrl, srcObjId, targetWin, secondUrl, secondWin)
{  
  if ( secondUrl == undefined ) secondUrl = '';
  if ( secondWin == undefined ) secondWin = '';
  
  if (targetUrl != '' )
  {
      showWindow_easy(targetWin);
      top.frames[targetWin].location = targetUrl;
  }
  
  if (secondUrl != '' )
  {
       showWindow_easy(secondWin);
       top.frames[secondWin].location = secondUrl;
  }
}

function goToPage_easy(targetUrl, targetWin)
{
  if (targetUrl != '' )
  {
     showWindow_easy(targetWin);
     top.frames[targetWin].location = targetUrl;
  }   
}

function refreshWin_easy(targetWin)
{ 
	if (targetWin != null)
	{
	    showWindow_easy(targetWin);
	    top.frames[targetWin].location.reload();
	}
}

function closeWin_easy(targetWin)
{
  top.document.getElementById(targetWin+"Div").style.display="none";
}

function viewMaxList_easy()
{	
	 // alert('viewMaxList - nieobslugiwana funkcja!!!');
}//-----------------------------------------------------------------------------

function viewMaxContent_easy()
{
  // alert('viewMaxContent - nieobslugiwana funkcja!!!');	
}//-----------------------------------------------------------------------------

function findWindow_easy(targetWin)
{
  //alert('findWindow - nieobslugiwana funkcja!!!');	
}

function getWindowObject_easy(targetWin)
{
   return top.frames[targetWin];	
}

function showWindow_easy(targetWin)
{
   top.document.getElementById(targetWin+"Div").style.display="";
}

function hideWindow_easy(targetWin)
{
   //top.frames[targetWin].document.body.style.display="none";
   top.document.getElementById(targetWin+"Div").style.display="none";
}

function SetPopupSize_easy( w, h )
{
     //alert('SetPopupSize - nieobslugiwana funkcja!!!');	
}

function ResetPopupSize_easy()
{
     //alert('ResetPopupSize - nieobslugiwana funkcja!!!');	
}

function viewNormal_easy()
{
   
}

//--------------------------

 function getVFields(sender)
  {
      var cat = sender.value;
      var ob = new Object();
      ob.cat = cat;
      
      //moga byc jakies pola wypelnione, skanujemy je
      $('.vfields_table input').each( function(i, obj ){
          prop_name = obj.id;
          ob[prop_name] = $(obj).val();
      });
      
      $('#vfields').load('ajax_vfields2.php', ob, getVFields_handler);
  }
  
  function getVFields_handler()
  {
    //poprawka dla klasy cform - dopisanie nowych pol do zlecenia walidacji. Jak cform przejdzie na jquery - zmienic to
    var aaa = new Array();
    $('.cform').each(
                            function(i){
                              aaa.push(this.id)
                            }
                          )
    to_validate = aaa;                      
  }


  /**
   * Przeladoanie strony - wywolywane w ramce zeby powrocic do strony ktora ja wywolala
   *
   * @param none
   * @return none
   *
   */
  function ReloadAfterMakeThumbs()
  {
      var znak = "&";
      var link = parent.location.href;
      
      // jak wywolywane samo z siebie to nie ma przeladowania (np skrypty naprawiajace miniatrki)
      if (link.indexOf("make_thumbs.php") != -1 )
        return false;
      if (link.indexOf("make_thumbs_nz.php") != -1 )
        return false;
        
      link = link.replace('hid_do_action=regenerate' , 'after=reg');
      
      /*
      if (link.indexOf("?") != -1 )
        znak = "?";
      link = link + znak + "file_save";  
       */
       
      parent.location.href = link ;
  }

 /* Oznaczanie jako nieprzeczytane*/
 
 function MarkAsUnread(sender, type, id ){
  sender.src="./i/busy.gif";
  //alert('ajax_mark_unread.php?id=' + id + '&type=' + type, mark_as_unread_handler)
  ajax_Init('ajax_mark_unread.php?id=' + id + '&type=' + type, mark_as_unread_handler);
 }


function mark_as_unread_handler()
{
 
  
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        var noread_btn = document.getElementById('noread_btn');
        noread_btn.src="./i/icons/read_no25.gif";
        if ( result == '1' ){
          noread_btn.className='HighlightButtonOn';
        }
        else{
          alert(result);
          noread_btn.className='HighlightButtonOff';
          
        }
    }
}


 function BlockRead(sender, type, id ){
  sender.src="./i/busy.gif";
  //alert('ajax_blockread.php?id=' + id + '&type=' + type);
  ajax_Init('ajax_blockread.php?id=' + id + '&type=' + type, blockread_handler);
 }


function blockread_handler()
{
 
  
  if (ajax_IsCompleteRequest() == true)
	{
        var result = ajax_GetResult();
        var noread_btn = document.getElementById('blockread_btn');
        noread_btn.src="./i/icons/read_no25.gif";
        if ( result == '1' ){
          noread_btn.className='HighlightButtonOn';
        }
        else if( result == '0' ) {
          noread_btn.className='HighlightButtonOff';
        }
        else {
        alert(result);
        }
    }
}


function nip_get(src_obj_id, dst_obj_id, div_obj_id)
{
	var obj = document.getElementById(src_obj_id);
	if (obj != null)
	{
		if (obj.value.length >= 4)
		{
//			alert(dst_obj_id);
			tmp_nip_obj_id = dst_obj_id;
			document.getElementById(div_obj_id).style.display = '';
	    	
		}
		else
		{
//			alert('Proszę wpisać dłuższy ciąg znaków.');
		}
	}
}


// #############3  PODPIS ELEKTRONICZNY

function eSign(sender, obj_type, obj_id, obj_ver){

  //sprawdzamy czy bylo utworzone, jesli nie, to tworze
  var pytanie = document.getElementById('eSignQuestion');
  if ( pytanie == null ){
      var pytanie = $('<div id="eSignQuestion" class="eSignQuestion">Ładowanie...</div>');
      $('body').prepend(pytanie);
  }
  else pytanie = $(pytanie);
  var obj = $(sender);
  var off = obj.offset(); 
  pytanie.css( 'top', off.top );
  pytanie.css( 'left', off.left );
  
  
  
  pytanie.load('ajaxj_esign.php', { action: 'load', obj_type:obj_type, obj_id:obj_id, obj_ver:obj_ver }, function(){
       //po zaladowaniu wykona sie ta funkcja, tu przypisuje akcje przyciskom wewnatrz
       
       pytanie.find('#eSignOK').click( eSignOK );
       pytanie.find('#eSignUsers').click( eSignUsers );
       pytanie.find('#eSignCancel').click( function(){
       //funkcja na anuluj
          $(this).parents('#eSignQuestion:first').hide(300);
       });
       
       //jesli sa userzy, to powieksz
       var userzy = pytanie.find('#userzyWybrani option');
       if( userzy.length > 0 ) {
        pytanie.height(600) ;
        pytanie.find('#eSignUsers').remove();
       } 
       
       pytanie.show(500);
  });

}//-----------------------------------------------------------------------------

function eSignOK(){
  var sender = $(this);
  var ttt = this.lang.split('_');
  var obj_type = ttt[0];
  var obj_id = ttt[1];
  var obj_ver = ttt[2];
  
  var pytanie = sender.parents("#eSignQuestion:first");
  var note = pytanie.find("#eSignNote").val();
  
  //dodatkowi ludzie
  var dodac = document.getElementById('userzyWybrani');
  var dodacid = '';
  var dodaccomma = '';
  if ( dodac ){
    $(dodac).find("option").each( function( i, obj ){
        dodacid = dodacid + dodaccomma + $(obj).val();
        dodaccomma = ','; 
    });
  }
  
  pytanie.html( ' <div class="loading"></div>' );
  pytanie.load('ajaxj_esign.php', { action: 'sign', note: note, obj_type:obj_type, obj_id:obj_id, obj_ver:obj_ver, dodac : dodacid  }, function(){
    RecountLeft('esign'); // zmiana wartosci do podpisu z lewej
  });
  pytanie.show();
  pytanie.fadeOut(3000);
}//-----------------------------------------------------------------------------

function eSignUsers(){
  var sender = $(this);
  var ttt = this.lang.split('_');
  var obj_type = ttt[0];
  var obj_id = ttt[1];
  var obj_ver = ttt[2];
  
  var pytanie = sender.parents("#eSignQuestion:first");
  pytanie.height(600); //powiększenie okienka
  pytanie.find('#eSignUsers').remove(); //wywalenie przycisku
  
  var drzewo = $('<div id="eSignUsersInner" style="display: none">Ładowanie...</div>'); 

  pytanie.append( drzewo );
  drzewo.load('ajaxj_esign_users.php', { action: 'sign', obj_type:obj_type, obj_id:obj_id, obj_ver:obj_ver }, function(){
    drzewo.fadeIn(400);
    MakeSmartSelect( drzewo.find("#oddzialy")  );
    
    
    
  });

}//-----------------------------------------------------------------------------

function oddzialyChangeClick(){ 
          $(this).unbind('dblclick');
          $(this).dblclick( oddzialyChangeClick2 );
          $("#userzyWybrani").append( this );
}//------------------------------------------------------------------------

function oddzialyChangeClick2(){ 
          $(this).unbind('dblclick');
          $(this).dblclick( oddzialyChangeClick  );
          $("#userzyOddzialu").append( this );
}//------------------------------------------------------------------------

function oddzialyChange( sender ){
 
     $.post("ajax_user_list2.php", { department_id: $(sender).val(), subtree_comp: 1 },
      function(result){
        //alert("Data Loaded: " + data);
        ajax_CreateOptionsNoEmpty(result, document.getElementById("userzyOddzialu"));
        //$("#userzyOddzialu option").dblclick( function(){ $(this).remove();  } );
        $("#userzyOddzialu option").dblclick( oddzialyChangeClick );
      });
}//-----------------------------------------------------------------------------

// DODAWANIE USERA WERSJA PROSTA

function MoveToSelect(sender, user_id, select_id ){

  //sprawdzamy czy w selekcie docelowym nie ma już osoby o danym id
  
  //znajdukemy rzad kliknietej opcji i wyciagamy z niej informacje
  if ( sender.tagName == 'TR' ) var row = $(sender);
  else var row = $(sender).parents("tr:first");
  var text = row.find(".name").text();
  
  //znajdujemy selekta i nakopiujemy na niego dane
  var select = $(document.getElementById(select_id));
  var opt = $('<option value="'+user_id+'">'+text+'</option>');
  select.append(opt);
  
  //chowamy na liscie alfabetycznej te osobe
  row.hide();

}//-----------------------------------------------------------------------------

function ReturnToSelect( sender, table_id ){
  //znalezienie co było dwukliknięte
  var select = $(sender);
  var pozycje = select.find(":selected");
  var lista = $( document.getElementById(table_id) );
  
  //dla wszystkich zaznaczonych
  pozycje.each( function(i, obj){ 
      var obj = $(obj);
      var user_id = obj.val();
      //sprawdzamy czy jest rzad pasujacy
      rzad = lista.find('#user_' +user_id+':first' );
      if ( rzad.length ){
          rzad.show();
          obj.remove();
      }  
      
  });

}//-----------------------------------------------------------------------------


function hr2hr( godz ){
  //godz = godz.replace(',' , '.');
  //jak user wpisze 1.8 to ma byc 2.20
  var calk = parseInt( godz );
  var ulamk = parseFloat( godz ) - calk;
  if( ulamk >= 0.6 ){
    ulamk = ulamk - 0.6;
    calk = calk +1;
  }
  var  val = calk + ulamk 
  return  val.toFixed(2);
}//-----------------------------------------------------------------------------

function fl2hr( ){
  
}//-----------------------------------------------------------------------------

function hr2fl( godz ){

}//-----------------------------------------------------------------------------

function CheckOlderToday(sender){

  var data = sender.value.split('-'); 
  var now = new Date();
  var dat = new Date( data[0], data[1]-1, data[2] ); //uwaga, miesiace licza tutaj od zera
  if (now.getTime() < dat.getTime() ) alert ('Uwaga! Ustawiono przyszłą datę dokumentu!');
  
} //--------------------------------------


/* --------------------- GODZINY PRZEPRACOWANE ------------------------ */

 
  function AddHours3(did, objtype){
   var date =  $('#add_data').val();
   var sHours = $('#add_hours').val();
   var sHours = sHours.replace(',' , '.');
   var hours = parseFloat( sHours );
   var comment = $('#add_comment').val();
   if ( objtype == undefined ) objtype = 60;
   
   if ( did && date && hours ) $.post( 'ajaxj_decl_capt.php', { action: 'add_work', id: did, type: objtype ,work_d: date, work_h: hours, comment:comment }, function(ret){ 
        ret = parseInt(ret);
        if( ret > 0 ){
            var row = $('<tr><td>'+date+'</td><td>'+hr2hr(hours)+'</td><td>' + comment + '</td><td><img src="./i/icons/delete_icon.gif" title="Usuń wpis" onclick="DelHours(this, '+ret+' )" /></td></tr>');
            $('#godziny').append(row);
            var gsuma = $('#godziny_suma');
            
            var s = hr2hr( parseFloat( gsuma.text() ) + hours );
            gsuma.text( s ); 
        }
        else alert( ret );
        //location.reload(); 
      
      });
   else alert( 'Wypełnij pola' );
 }//----------------------------------------------------------------------------
 
  function EdytujGodziny( sender, mid){
    sender = $(sender);
    var val = sender.text();
    sender.text('');
    var edit = $( '<input type="text" style="width: 30px" id="work_h_edit" lang="' + mid + '" />' );
    edit.val( val );
    $(sender).prepend(edit);
    edit.change( ChangeHours );
 }//----------------------------------------------------------------------------
 
  function ChangeHours(){
   sender = $(this);
   var hours = parseFloat( sender.val().replace(',' , '.') );
   if ( ! hours ) alert( 'Niepoprawna wartość' )
   else{
    $.post( 'ajaxj_decl_capt.php', { action: 'edit_work', wid: sender.attr('lang'), work_h: hours }, function(ret){ 
      if ( ret == '1' ){
        sender.parents('td:first').text( hours );
        sender.remove(); 
      }
      else alert(ret);
    });
   }
 }//----------------------------------------------------------------------------
  function DelHours(sender, mid ){
    $.post( 'ajaxj_decl_capt.php', { action: 'del_work', wid: mid }, function(ret){ 
      if ( ret == '1' ){
        sender = $(sender);
        row = sender.parents("tr:first");
        godz = parseFloat( row.find(".ilegodz:first").text() );
        var gsuma = $('#godziny_suma');
        var s = parseFloat( gsuma.text() ) - godz;
        gsuma.text( hr2hr(s) ); 
        row.remove();
      }
      else alert(ret); 
      });
 }//----------------------------------------------------------------------------


// ############# PANEL INFORMACYJNY O UZYTKOWNIKU

function ShowUserInfo(sender, user_id, obj_type, obj_id, mode){

  if ( obj_type == undefined ) obj_type = 0;
  if ( obj_id == undefined ) obj_id = 0;
  if ( mode == undefined ) mode = 0;

  //sprawdzamy czy bylo utworzone, jesli nie, to tworze
  var box = document.getElementById('PopBox');
  if ( box == null ){
      var box = $('<div id="PopBox" class="PopBox"><div class="close_btn" onclick="(this.parentNode).remove()">[x]</div><div class="Loading"></div></div>');
      $('body').prepend(box);
  }
  else box = $(box); //utworzenie z tego obiektu jquery
  var obj = $(sender);
  var off = obj.offset(); 
  box.css( 'top', off.top );
  box.css( 'left', off.left );
  box.html('<div  class="close_btn" onclick="$(this.parentNode).remove()">[x]</div><div class="Loading"></div>');
  box.show(500);
  box.load('user_info.php', { id:user_id,  obj_type: obj_type, obj_id:obj_id, mode:mode  });

}//-----------------------------------------------------------------------------


// ############# PANEL FROM MENU #####################

 
function GetBoxPanel( width, height, sender ){
    //szukamy czy jest już jakiś Box, jesli nie to tworzymy. Liczyy tylko schowane
    var BoxHandle = $('#GeneralBox:hidden:first');
    if (BoxHandle.length == 0   ){
      BoxHandle = $('<div id="GeneralBox" class="GeneralBox"><div class="Loading"></div></div>');
      $('body').prepend(BoxHandle);
    }
    
    //ustalanie pozycji
    BoxHandle.css( 'width', width );
    BoxHandle.css( 'height', height );
    if ( sender != undefined ){
      var pos = $(sender).position();
      BoxHandle.css( 'top', pos.top );
      BoxHandle.css( 'left', pos.left );      
    }
    
    BoxHandle.show();
    return BoxHandle; 
}//----------------------------------------------------------------------------

function BoxClose( sender ){
    $(sender).parents('.GeneralBox:first').fadeOut(400);
 }//----------------------------------------------------------------------------  

//dodawanie userow  
function addUserFromMenu( sender, id, type, cid ){
    var box = GetBoxPanel( 550, 230, sender );
    box.html( ' <div class="Loading"></div>' );
    //jesli jest tabelka z userami, to skanuje ja i tworze banliste
    var filter = new Array();
    var userzy = $('#TeamTable2 .userrow');
    if( userzy.length >0 ){
      userzy.each(function(i, obj) {
              filter.push( obj.lang ); 
             });
    }
    box.load("user_add_panel.php" , { id: id , type: type, cid:cid, mode: 2, 'filter[]':filter });
 }//----------------------------------------------------------------------------  

function AddUsersFromBox(sender, type, id ){
   
  $(sender).unbind('click'); //coby nie naklikali się do oporu
  var box = $(sender).parents('#GeneralBox');
  //tworzenie tablicy userow
  var users = new Array();
  
  var UserTable =  $('#TeamTable2 .user_reads tbody'); //tablica z userami na dole
  box.find("#dst_user_list option").each(function(i, obj) {
              users.push( obj.value );
             
              var name = obj.innerHTML; 
              var tmp = $('<tr lang="'+obj.value+'" class="userrow reads_nigdy"><td class="no_ball"><input type="checkbox" id="ballchb_'+obj.value+'" name="pileczki"></td><td><div title="User" class="flag_user"></div></td><td>'+name+'</td><td class="c">+Nowy+</td><td id="balltxt_'+obj.value+'"></td><td id="balldate_'+obj.value+'"></td></tr>');
              UserTable.prepend(tmp); 
               
             });
  box.html('<div class="Loading"></div>');
  $.post( 'user_add_ajaxj.php', { action: 'add', id:id, type:type, mode: 2 , 'users[]':users  }, function(ret){ 
      if ( ret == '1' ){
        box.fadeOut(300);
      }
      else alert(ret);
    });
    
  
    
}//-----------------------------------------------------------------------------

 
 //dodawanie userow  
function addWydatekFromMenu( sender, id, type, cid ){
    var box = GetBoxPanel( 550, 230, sender );
    box.html( ' <div class="Loading"></div>' );
    box.load("wydatek_add_ajaxj.php" , { id: id , act:'panel' ,type: type, cid:cid });
 }//----------------------------------------------------------------------------  

function AddWydatekFromBox(sender, type, id ){
   
    
   
  
  var box = $(sender).parents('#GeneralBox');
  if( FormValidateSend(box) == false) return false;
  
  //tworzenie tablicy userow
  $(sender).unbind('click'); //coby nie naklikali się do oporu
  var users = new Array();
  
  var UserTable =  $('#WydatekTable2 .wydatki tbody'); //tablica z wydatkami na dole
  
  //znalezienie kwoty, komntarza, akceptacki, kategorii
  //var tmp = $('<tr lang="'+obj.value+'" class="userrow reads_nigdy"><td class="no_ball"><input type="checkbox" id="ballchb_'+obj.value+'" name="pileczki"></td><td><div title="User" class="flag_user"></div></td><td>'+name+'</td><td class="c">+Nowy+</td><td id="balltxt_'+obj.value+'"></td><td id="balldate_'+obj.value+'"></td></tr>');
  //UserTable.append(tmp);
  
  
  var ki = box.find('#kind').val();
  var ca = box.find('#ca').val();
  var ti = box.find('#title').val();
  var de = box.find('#description').val();
  var kwota = box.find('#kwota').val();
  var akceptacja = box.find('#akc:first:checked');
  if( akceptacja.length ) var akc = true;
  else var akc = false;
  
  box.html('<div class="Loading"></div>');
  $.post( 'wydatek_add_ajaxj.php', { act: 'add', id:id, type:type, ti:ti, de:de, ca:ca, ki:ki, kwota:kwota, akc:akc }, function(ret){ 
      if ( ret == '1' ){
        box.fadeOut(300);
      }
      else box.html( ret );
    });
    
  
    
}//-----------------------------------------------------------------------------

// END ############# PANEL FROM MENU #####################
