function $(pId) {
  return document.getElementById(pId);
}

function DeForm() {
}

// ---------------------------------------------------------------------
// Browser Detection 
// ---------------------------------------------------------------------
isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false; 
isDOM=(document.getElementById)?true:false
isOpera=isOpera5=window.opera && isDOM
isOpera6=isOpera && window.print
isOpera7=isOpera && navigator.userAgent.indexOf("Opera 7") > 0 || navigator.userAgent.indexOf("Opera/7") >= 0
isMSIE=isIE=document.all && document.all.item && !isOpera
isMSIE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false; 
isMSIEmac = ((document.all)&&(isMac)) ? true : false; 
isNC=navigator.appName=="Netscape"
isNC4=isNC && !isDOM
isNC6=isNC && isDOM


// ---------------------------------------------------------------------
// Safe loading into window.onload
//
// Body onload utility (supports multiple onload functions) 
// ---------------------------------------------------------------------

var gDeFormSafeOnload = new Array(); 
var gDeFormSafeOnloadDelay = new Array();

function DeFormSafeAddOnload(pFunction) {
  DeFormSafeAddOnloadDelayed(pFunction, 0);
}

function DeFormSafeAddOnloadDelayed(pFunction, pDelay) {
  
  if (window.onload != DeFormSafeOnload) { 

    if (window.onload) {
      gDeFormSafeOnload.push(window.onload);
      gDeFormSafeOnloadDelay.push(0);
    }
    
    window.onload = DeFormSafeOnload; 
  }
  
  gDeFormSafeOnload.push(pFunction);
  gDeFormSafeOnloadDelay.push(pDelay);
  
} 

function DeFormSafeOnload() 
{ 
  var len = gDeFormSafeOnload.length;
  
  for (i = 0; i < len; i++) {

    if (typeof(gDeFormSafeOnload[i]) != 'function') {
      gDeFormSafeOnload[i] = new Function(gDeFormSafeOnload[i]);
    }
    
    if (gDeFormSafeOnloadDelay[i] > 0) {
      setTimeout(gDeFormSafeOnload[i], gDeFormSafeOnloadDelay[i]); 
    }
    else {
      gDeFormSafeOnload[i]();
    }  
    
  }
} 

DeForm.WindowOnDomReady = function(init) {
        var state = document.readyState;
        if (state && document.childNodes && !document.all && !navigator.taintEnabled){ //khtml
                if (state.test(/loaded|complete/)) return init();
                else return Window.onDomReady.pass(init).delay(100);
        } else if (!window.XMLHttpRequest && state && window.ActiveXObject){ //ie
                var script = $('_ie_ready_');
                if (!script) document.write("<script id='_ie_ready_' defer='true' src='://'></script>");
                $('_ie_ready_').addEvent('readystatechange', function(){
                        if (this.readyState == 'complete') init();
                });
                return;
        } else { //others
                var myInit = function() {
                        if (arguments.callee.done) return;
                        arguments.callee.done = true;
                        init();
                };
                window.addEvent("load", myInit);
                document.addEvent("DOMContentLoaded", myInit);
        }
}

// ---------------------------------------------------------------------
// Set a cookie
// 
// ---------------------------------------------------------------------
DeForm.SetCookie = function(cookieName, cookieValue, nDays) {
  var today = new Date();
  var expire = new Date();
  if (nDays==null || nDays==0) {
    nDays=1;
  }
   expire.setTime(today.getTime() + 3600000*24*nDays);
   document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}


// ---------------------------------------------------------------------
// Change layer content dynamically
// 
// ---------------------------------------------------------------------
DeForm.ChangeLayerContent = function(id, content) {
  lay = $(id);
  
  var previouscontent = lay.innerHTML;
  lay.innerHTML = content;
  
  return previouscontent;
}


// ---------------------------------------------------------------------
// Add event to object
// 
// ---------------------------------------------------------------------
DeForm.AddEvent = function(pObject, pHandler, pFunction){

  if (typeof(pFunction) != 'function') {
    pFunction = new Function(pFunction);
  }
  
  if (typeof(pObject) != 'object') {
    pObject = $(pObject);
  }
  
  if (!document.all && document.getElementById){
    pObject.addEventListener(pHandler.replace(/^on/, '').toLowerCase(), pFunction, false);
  }    
  
  //workaround for IE 5.x and IE 6
  if (document.all && document.getElementById){
    pObject[pHandler.toLowerCase()] = pFunction;
  }
}


// ---------------------------------------------------------------------
//  Loads dynamically script
// ---------------------------------------------------------------------
var gDeFormScriptStack   = [];
var gDeFormScriptStackTimeoutID;

DeForm.LoadScript = function(pScriptSrc, pCallBack) {
  
  // Add to stack
  gDeFormScriptStack.push({src: pScriptSrc, callback: pCallBack});

  // Start loader
  clearTimeout(gDeFormScriptStackTimeoutID);
  gDeFormScriptStackTimeoutID = setTimeout("DeForm.LoadScriptGetFromStack()", 350);
  
  return true;
}
  
DeForm.LoadScriptHelper = function(pScriptSrc, pCallBack) {
  
  scriptElement = document.createElement('script');
  scriptElement.type = 'text/javascript';
  scriptElement.src = pScriptSrc;
  
  if (isMSIE) {
    scriptElement.attachEvent(
      'onreadystatechange',
      function (evt) {
        if (scriptElement.readyState == 'loaded' || scriptElement.readyState == 'complete') {
          DeForm.LoadScriptCallBack(pCallBack);
          DeForm.LoadScriptGetFromStack();
        }
      }
    );
  }
  else if (!isOpera) {
    scriptElement.addEventListener(
      'load',
      function (evt) {
        DeForm.LoadScriptCallBack(pCallBack);
        DeForm.LoadScriptGetFromStack();
      },
      false
    );
  }

  if(isOpera) {
    document.getElementsByTagName("head")[0].appendChild(scriptElement);
    DeForm.LoadScriptCallBack(pCallBack);
    DeForm.LoadScriptGetFromStack();
  }
  else {
    document.getElementsByTagName("head")[0].appendChild(scriptElement);
  }
  
  return true;
}

DeForm.LoadScriptGetFromStack = function() {
  
  // End of processing
  if (gDeFormScriptStack.length == 0) {
    return true;
  }
  
  obj = gDeFormScriptStack.shift();
  
  DeForm.LoadScriptHelper(obj.src, obj.callback);
  
  return true;
}

DeForm.LoadScriptCallBack = function(pCallBack) {
  
  if(typeof(pCallBack) == 'function') {
    pCallBack();
  }
  return true;
}

// ---------------------------------------------------------------------
//  Loads dynamically css file
// ---------------------------------------------------------------------
var gDeFormLoadedCSS = new Array();

DeForm.LoadCSS = function(pCSSSrc, pAlwaysLoad) {
  
  // Check if script was'nt loaded already
  if (true == DeForm.in_array(pCSSSrc, gDeFormLoadedCSS) && true != pAlwaysLoad) {
    return;  
  }
  
  gDeFormLoadedCSS.push(pCSSSrc);
  
  css = document.createElement('link');
  css.rel = 'stylesheet';
  css.href = pCSSSrc;
  
  document.getElementsByTagName("head")[0].appendChild(css);
  
  return css;
}

DeForm.in_array = function(pNeedle, pHaystack) {
  for(var i in pHaystack) {
    if (pNeedle == pHaystack[i]) {
      return true;
    }  
  }  
  return false;
}

// ---------------------------------------------------------------------
// JSON Implementation taken from www.json.org
// ---------------------------------------------------------------------
/*
     json.js (modified 2006-05-02)

        USAGE:
        var jsObj = JSON.parse(jsonStr);
        var jsonStr = JSON.stringify(jsObj);
*/
var json = (function () {
     var m = {
             '\b': '\\b',
             '\t': '\\t',
             '\n': '\\n',
             '\f': '\\f',
             '\r': '\\r',
             '"' : '\\"',
             '\\': '\\\\'
         },
         s = {
             array: function (x) {
                 var a = ['['], b, f, i, l = x.length, v;
                 for (i = 0; i < l; i += 1) {
                     v = x[i];
                     f = s[typeof v];
                     if (f) {
                         v = f(v);
                         if (typeof v == 'string') {
                             if (b) {
                                 a[a.length] = ',';
                             }
                             a[a.length] = v;
                             b = true;
                         }
                     }
                 }
                 a[a.length] = ']';
                 return a.join('');
             },
             'boolean': function (x) {
                 return String(x);
             },
             'null': function (x) {
                 return "null";
             },
             number: function (x) {
                 return isFinite(x) ? String(x) : 'null';
             },
             object: function (x) {
                 if (x) {
                     if (x instanceof Array) {
                         return s.array(x);
                     }
                     var a = ['{'], b, f, i, v;
                     for (i in x) {
                         v = x[i];
                         f = s[typeof v];
                         if (f) {
                             v = f(v);
                             if (typeof v == 'string') {
                                 if (b) {
                                     a[a.length] = ',';
                                 }
                                 a.push(s.string(i), ':', v);
                                 b = true;
                             }
                         }
                     }
                     a[a.length] = '}';
                     return a.join('');
                 }
                 return 'null';
             },
             string: function (x) {
                 if (/["\\\x00-\x1f]/.test(x)) {
                     x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                         var c = m[b];
                         if (c) {
                             return c;
                         }
                         c = b.charCodeAt();
                         return '\\u00' +
                             Math.floor(c / 16).toString(16) +
                             (c % 16).toString(16);
                     });
                 }
                 return '"' + x + '"';
             }
         };

        return {
                parse: function(s) {
                        try {
                                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                                        s.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                                        eval('(' + s + ')');
                        } catch (e) {
                                return false;
                        }
                },
                stringify: s.object
        };

})();


// ---------------------------------------------------------------------
// ImgAlpha
// ---------------------------------------------------------------------
DeForm.ImgAlpha = function(pSrc, pWidth, pHeight) {

  if (isIE) {
    var img_el = document.createElement('span');
    img_el.style.display = 'block';
    img_el.style.width = pWidth + 'px';
    img_el.style.height = pHeight + 'px';
    img_el.style.border = '0';
    img_el.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + pSrc + "',sizingMethod='scale')";
    img_el.style.cursor = 'pointer';
  }
  else {
    var img_el = document.createElement('img');
    img_el.width = pWidth;
    img_el.height = pHeight;
    img_el.style.border = '0';
    img_el.src = pSrc;
    img_el.style.cursor = 'pointer';
  }
  
  return img_el;
}


// ---------------------------------------------------------------------
// Grid element
// ---------------------------------------------------------------------
DeForm.Grid = function(pInsertEl, pIconImage, pIconWidth, pIconHeight) {

  // Variables init
  this.mInsertEl = $(pInsertEl);
  this.mSelfName = pInsertEl + '_obj';
  this.mOutputEl = $(pInsertEl + '_hidden');
  this.mIconImage = pIconImage;
  this.mIconWidth = pIconWidth;
  this.mIconHeight = pIconHeight;
  
  // Setup table elements
  this.mTableEl = document.createElement('table');
  this.mTableBodyEl = document.createElement('tbody');
  this.mTableHeaderEl = document.createElement('tr');
  
  this.mTableEl.appendChild(this.mTableBodyEl);
  this.mInsertEl.appendChild(this.mTableEl);
  this.mTableBodyEl.appendChild(this.mTableHeaderEl);
  
  // Where grid data are stored
  this.mGridData = {};
  this.mGridColumns = [];
  this.mGridRows = [];
  
  // Methods
  this.AddColumn = DeForm.Grid.AddColumn;
  this.AddRow = DeForm.Grid.AddRow;
  this.DeleteRow = DeForm.Grid.DeleteRow;
  this.SerializeData = DeForm.Grid.SerializeData;
  this.UnserializeData = DeForm.Grid.UnserializeData;
  
}

DeForm.Grid.AddRow = function(pArguments) {
  
  // No data to add
  if (pArguments.length <= 0) {
    return;
  }
  
  // Create <tr> element
  tr_el = document.createElement('tr');
  
  // Save row data (reference to tr_el to allow removing it
  this.mGridRows.push(tr_el);
  
  // Record index
  index = this.mGridRows.length - 1;

  for(b in this.mGridColumns) {
    
    col_name = this.mGridColumns[b];
    
    // More data than we have columns
    if (typeof(this.mGridData[col_name]) == 'undefined') {
      continue;
    }

    this.mGridData[col_name].data[index] = pArguments[col_name];
    
    td_el = document.createElement('td');

    // Style
    td_el.style.width = this.mGridData[col_name].column_width;
    
    td_el.style.textAlign = this.mGridData[col_name].column_align;

    // Text 
    td_text = document.createTextNode(pArguments[col_name]);
    td_el.appendChild(td_text)
    
    // Append to <tr> element
    tr_el.appendChild(td_el);
  }
  
  // Last column with remove button - create only if icon was given
  if (this.mIconImage != '') {
    td_el = document.createElement('td');
    td_el.style.verticalAlign = 'middle';
    
    a_el = document.createElement('a');
    icon_el = DeForm.ImgAlpha(this.mIconImage, this.mIconWidth, this.mIconHeight);
    a_el.href = "javascript:" + this.mSelfName + ".DeleteRow(" + index + "); void(0);";
    a_el.appendChild(icon_el);
    
    td_el.appendChild(a_el);
    tr_el.appendChild(td_el);
  }
  
  this.mTableBodyEl.appendChild(tr_el);
  this.SerializeData();
}

DeForm.Grid.AddColumn = function(pName, pText, pColumnWidth, pColumnAlign, pColumnPadding) {
  
  if (typeof(this.mGridData[pName]) == 'object') {
    return;
  }

  this.mGridColumns.push(pName);
  this.mGridData[pName] = {};
  
  this.mGridData[pName].column_width = pColumnWidth;
  this.mGridData[pName].column_align = pColumnAlign;
  this.mGridData[pName].data = {};
  
  th_el = document.createElement('th');
  th_el.style.width = pColumnWidth;
  th_el.appendChild(document.createTextNode(pText));
  
  this.mTableHeaderEl.appendChild(th_el);
}

DeForm.Grid.DeleteRow = function(pIndex) {
  
  // Remove <tr> element
  this.mTableBodyEl.removeChild(this.mGridRows[pIndex]);
  this.mGridRows[pIndex] = null;

  // Remove element from grid data
  for(name in this.mGridData) {
    delete this.mGridData[name].data[pIndex];
  }
  
  this.SerializeData();
}

DeForm.Grid.SerializeData = function() {
  this.mOutputEl.value = json.stringify(this.mGridData);
}

DeForm.Grid.UnserializeData = function() {
  value = this.mOutputEl.value;
  
  if (value != '') {
    data = json.parse(value)
    
    // Detect first column
    first_col_name = '';
    
    for(name in data) {
      first_col_name = name;
      break;
    }
    
    if (first_col_name == '') {
      return;
    }
    
    for(i in data[first_col_name].data) {
      
      if (parseInt(i) != i) {
        continue;
      }
      
      add_row_data = {};
    
      for(col_name in data) {
        if (typeof(data[col_name].data[i]) == 'undefined') {
          add_row_data[col_name] = '';
        }
        else {
          add_row_data[col_name] = data[col_name].data[i];
        }
      }
      this.AddRow(add_row_data);
    }
  }

  // Create blank header column (where remove button is kept) - only when icon was given
  if (this.mIconImage != '') {
    th_el = document.createElement('th');
    this.mTableHeaderEl.appendChild(th_el);
  }
}


//-------------------------------------------------------------------------
// DeForm.ComboBoxJS
//-------------------------------------------------------------------------
DeForm.ComboBoxJS = function(pInsertName, pValId){

        this.mInsertName = pInsertName; 
  this.mSelfName = pInsertName + '_obj';
  this.mTabEl = $(pInsertName + '_tab');
        this.mValEl = $(pInsertName);
        this.mTextVal = $(pInsertName + '_text');
  this.mTabVal = [];
        this.mNumberOfRows = 0;
        this.mIsDifferentCaseClick = 0;
        this.value = -1;
        this.is_active = 0;

        this.AddElement = DeForm.ComboBoxJS.AddElement;
        this.ShowElements = DeForm.ComboBoxJS.ShowElements;
        this.MouseOver = DeForm.ComboBoxJS.MouseOver;
        this.SelectVal = DeForm.ComboBoxJS.SelectVal;
        this.HiddeList = DeForm.ComboBoxJS.HiddeList;
        this.SetSelected = DeForm.ComboBoxJS.SetSelected;
        this.SetDisabled = DeForm.ComboBoxJS.SetDisabled;
        this.MarkAllElements = DeForm.ComboBoxJS.MarkAllElements; 
        this.ExecuteEventIfExist = DeForm.ComboBoxJS.ExecuteEventIfExist;
        
                // Domyslnie wartosc zwracana jest do elementu this.mValEl
                // gdy chcemy aby wartosc byla zwracana do innego domyslny 
                // usuwamy i podmieniamy referencje     
        if('null' != pValId){
                var div = $(this.mInsertName+'_contener');
                div.removeChild(this.mValEl);
                this.mValEl = $(pValId);        
        }
        
        DeForm.AddEvent(document.body, 'onclick', this.mSelfName + ".HiddeList(event)");
        DeForm.AddEvent($(this.mInsertName+'_submit'), 'onclick', this.mSelfName + '.ShowElements(1)');
        DeForm.AddEvent(this.mTextVal, 'onclick', this.mSelfName + '.ShowElements(1)');
        
}       

DeForm.ComboBoxJS.ExecuteEventIfExist = function(pEvent){
  if(pEvent != undefined){
    pEvent();  
  } 
}

                // Zaznaczenie komorki w tablicy po najechaniu na nia myszka
DeForm.ComboBoxJS.MouseOver = function(pThis){  
        this.MarkAllElements();
        this.mTabEl.rows[this.value].className = 'DF_ComboBoxJS_Row';
        $(pThis).className = 'DF_ComboBoxJS_Row_Active';
}

                // Zamkniecie listy gdy kliknelismy w dowolne pole na stronie
                // nie nalezace do listy
DeForm.ComboBoxJS.HiddeList = function(pEvent){
  if(this.mIsDifferentCaseClick == 1){
    this.mIsDifferentCaseClick = 0;
    return;
  }
        var ElementId = (pEvent.target || pEvent.srcElement).id;   
        var Reg = /([a-zA-Z0-9]+_[a-zA-Z0-9]+)/;
        
        if(false == Reg.test(ElementId) || RegExp.$1 != this.mInsertName){
                this.mTabEl.style.visibility='hidden';
                this.is_active = 0;
        }
}


                // Fukcja wywolywana po kliknieciu w komorke listy
                // zapisuje wartosc elementu kliknietego do odpowiedniej zmiennej
DeForm.ComboBoxJS.SelectVal = function(pThis){

        for (obj in this.mTabVal){
          this.mTabVal[obj].is_selected = 0;
        }
  var ToMatch = pThis;
        var Reg = /_(\d+)$/;
        Reg.test(ToMatch);
        lp = RegExp.$1;
        
        if(this.value != lp){
          change = true;    
        }
        else{
          change = false;    
        }
        
        this.mTextVal.innerHTML = this.mTabVal[lp].val;
        this.mValEl.value = this.mTabVal[lp].val;
        this.mTabVal[lp].is_selected = 1; 
        this.value = lp;
        
        if(true == change){
          this.ExecuteEventIfExist(this.mValEl.onchange);
        }
        
        this.mTabEl.style.visibility = 'hidden';
        this.is_active = 0;     
}

                // Dodawanie nowego elementu                    
DeForm.ComboBoxJS.AddElement = function(key, val, selected, disabled){
        
        var row = this.mTabEl.insertRow(this.mNumberOfRows);
        row_id = this.mInsertName+'_row_'+this.mNumberOfRows;
        row.setAttribute('id', row_id);
        
        var cell = this.mTabEl.rows[this.mNumberOfRows].insertCell(0);
        cell.setAttribute('id', this.mInsertName+'_cell_'+this.mNumberOfRows+"_0");
        this.mTabEl.rows[this.mNumberOfRows].cells[0].appendChild(document.createTextNode(key));
        
        TmpObj = new DeForm.ComboBoxJS.Row;
        TmpObj.id = row_id;
        TmpObj.lp = this.mNumberOfRows;
        TmpObj.val = val;
        TmpObj.key = key;
        TmpObj.is_selected = 0;
        TmpObj.is_disabled = 0;
        
  this.mTabVal.push(TmpObj);
  
  if(selected == 1){
        //this.SelectVal(row_id);
        this.mTextVal.innerHTML = val;
    this.SetSelected(this.mNumberOfRows);
  }
  if(disabled == 1){
    this.SetDisabled(this.mNumberOfRows);
  }    
  
  
        DeForm.AddEvent(row, 'onmouseover',this.mSelfName + ".MouseOver('" + this.mInsertName+'_row_'+this.mNumberOfRows+"')");
        DeForm.AddEvent(row, 'onclick',this.mSelfName + ".SelectVal('" + this.mInsertName+'_row_'+this.mNumberOfRows+"')");

  this.mNumberOfRows++;
}


// Funkcja wywolana po kliknieciu w strzalke, rozwija liste
DeForm.ComboBoxJS.ShowElements = function(pIsDifferentCaseClick){
  
  if(pIsDifferentCaseClick == undefined){
    this.mIsDifferentCaseClick = 1;
  }
  else{
    this.mIsDifferentCaseClick = 0;
  }
  
  if(0 == this.is_active){
    this.is_active = 1;
    this.MarkAllElements();  
        this.mTabEl.style.visibility='visible';
  }
  else{
    this.mTabEl.style.visibility='hidden';
    this.is_active = 0; 
  }  
}



DeForm.ComboBoxJS.Row = function(){
  this.id=0;
  this.lp=0;
  this.val=0;
  this.key=0;
  this.is_selected = 0;
  this.is_disabled = 0;
}

DeForm.ComboBoxJS.MarkAllElements = function(){
  for (i in this.mTabVal){
    obj = this.mTabVal[i];
    
    if(1 == obj.is_selected){
      this.mTabEl.rows[obj.lp].className = 'DF_ComboBoxJS_Row_Active';
    }
    else if(1 == obj.is_disabled){
      this.mTabEl.rows[obj.lp].className = 'DF_ComboBoxJS_Row_Disabled';
    }  
    else{
      this.mTabEl.rows[obj.lp].className = 'DF_ComboBoxJS_Row';
    }    
  }
}


DeForm.ComboBoxJS.SetSelected = function(pLp){
  if(-1 != this.value){
    this.mTabVal[this.value].is_selected = 0;
  }
  this.mTabVal[pLp].is_selected = 1;
  this.value = pLp;
}

DeForm.ComboBoxJS.SetDisabled = function(pLp){
  this.mTabVal[pLp].is_disabled = 1;
  this.mTabVal[pLp].is_selected = 0;
  if(this.value == pLp){
    this.value = -1;
  }
}

DeForm.mAddJSToolTipTmp = {};
DeForm.mAddJSToolTipTmp2 = {};
DeForm.mAddJSToolTipTimeout = {};
DeForm.AddJSToolTip = function(pElement, pStyle) {
  
  if (pStyle.test('standard')) {
    fx_duration = 150;
    time_out = 30;
    tipoffsets = {'x': 3, 'y': 15};
  }
  else {
    fx_duration = 150;
    time_out = 150;
    tipoffsets = {'x': 25, 'y': -10};
  }

  $(pElement).addEvent('keydown', function() {
    if (true == DeForm.mAddJSToolTipTmp2[pElement]) {
      return;
    }
    DeForm.mAddJSToolTipTmp2[pElement] = true;
    DeForm.mAddJSToolTipTmp[pElement].toolTip.effects({duration: 300}).start({'opacity': 0});
  });
  
  DeForm.mAddJSToolTipTmp[pElement] = new Tips($$('#' + pElement), {
    showDelay: time_out,
    hideDelay: time_out,
    maxTitleChars: 1,
    className: pStyle,
    onShow: function(pTip) {
      pTip.setStyle('margin-left', 0);
      pTip.setStyle('opacity', 0.92);
      pTip.setStyle('visibility', 'visible');
      DeForm.mAddJSToolTipTmp2[pElement] = false;
    },
    onHide: function(pTip) {
      pTip.setStyle('visibility', 'hidden');
    },
    fixed: false,
    offsets: tipoffsets
  });
}

