/**
 *  Zbior funkcji javascript dla MultiOpac'a
 *
 *  Author: michalsz
 *
 */    

var integerValue = -1;
var stringValue = '';
var stringValue2 = '';
var idSortValue = -1;
var idAdminValue = -1;
var idElement = null;
var tabLinks = new Array();  // tablica linkow
var isModalOpen = false;
var iCountBib = 0;
var iCurrentCountBib = 1;

/******************************************************************************
 *  Funkcja resetujaca zmienne globalne
 */ 
function resetGlobal() {
  integerValue = -1;
  stringValue = '';
  stringValue2 = '';
  idSortValue = -1;
  idAdminValue = -1;
}
/******************************************************************************
 *  Funkcje do ukrywania i wyswietlanai przycisku zamykajacego system
 */ 
function isModalWindow() {  // isModalWindow
  var returnVal = false;
  
  if (opener && !opener.closed){
    returnVal = true;
  }
  else {
    returnVal = false;
  }
  return returnVal;
}

function showHideCloseBtn() { // showHideCloseBtn
  var isModal = isModalWindow();
  
  if (isModal) {  // show button
    document.getElementById('closebtn').style.display = 'block';
  }
  else {  // hide button
    document.getElementById('closebtn').style.display = 'none';
  }
}
/******************************************************************************
 *  Funkcja do ustawienia focusa na elemencie
 */ 
function setSearchFocus() {
  document.getElementById('warunek1').focus();
}

/******************************************************************************
 *  Funkcja do ustawienia focusa na elemencie
 */ 
function setLoginFocus() {
  document.getElementById('input_login').focus();
}

/******************************************************************************
 *  Funkcja do ustawienia focusa na elemencie o nazwie w zmiennej idElement
 */ 
function setElementFocus() {
  if (idElement != null) document.getElementById(idElement).focus();
  idElement = null;
}

/******************************************************************************
 *  Funkcje do obslugi wyboru lokalizacji i kategorii
 */ 
function changeCity(city) { // changeCity
  var m = city.value;
  var k = document.getElementById('searchform').KategoriePamiec.value;

  document.location.href = 'webs.html?mi=' + m + '&lKat=' + k;
}

/******************************************************************************
 *  Wyslanie formatki logowania
 */ 
function runLoginForm() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var login = document.getElementById('input_login');
  var pass = document.getElementById('input_pass');
  
  // reset kolorow
  document.getElementById('input_login').style.backgroundColor = defaultColor;
  document.getElementById('input_pass').style.backgroundColor = defaultColor;
  
  // walidacja
  if (login.value == '') { 
    login.style.backgroundColor = errorColor;
    isValid = false;
  };
  if(pass.value == '') {
    pass.style.backgroundColor = errorColor;
    isValid = false;
  };
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }
  
  return isValid;
}

/******************************************************************************
 *  Obsluga menu administratora
 */ 
function clearCurrents() {
  var i;
  for (i=0; i<5; i++) {
    try { document.getElementById('amenu' + i).className = ''; }
    catch(e) { void(0); }
  }
}  

function setCurrent(id_adm) {
  clearCurrents();  
  document.getElementById('amenu' + id_adm).className = 'admin-current';
  
  document.location.href = 'admin.html?adm=' + id_adm;
}

/******************************************************************************
 *  EDYCJA - Ustawienia
 */ 
function runParamSubmit() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var multiid = document.getElementById('idmultiid');
  var multiname = document.getElementById('idmultiname');
  var timeout = document.getElementById('idtimeout');
  var login = document.getElementById('idlogin');
  var pass = document.getElementById('idpass');
  
  // reset kolorow
  multiid.style.backgroundColor = defaultColor;
  multiname.style.backgroundColor = defaultColor;
  timeout.style.backgroundColor = defaultColor;
  login.style.backgroundColor = defaultColor;
  pass.style.backgroundColor = defaultColor;
  
  // walidacja
  if (multiid.value == '') { 
    multiid.style.backgroundColor = errorColor;
    isValid = false;
  };
  if (multiname.value == '') { 
    multiname.style.backgroundColor = errorColor;
    isValid = false;
  };
  if(timeout.value == '') {
    timeout.style.backgroundColor = errorColor;
    isValid = false;
  };
  if (login.value == '') { 
    login.style.backgroundColor = errorColor;
    isValid = false;
  };
  if(pass.value == '') {
    pass.style.backgroundColor = errorColor;
    isValid = false;
  };
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }
  
  return isValid;
}

/******************************************************************************
 *  Efekt na ikonach edycji i usuniecia elementu
 */ 
function changeImg(obj, action_val, turn_val) {
  var imageName = '';
  
  if (action_val == 'edit') {
    imageName = 'edit_icon';
  }
  else if (action_val == 'remove') {
    imageName = 'remove_icon';
  }
  if (action_val == 'update') {
    imageName = 'update_icon';
  }
  if (turn_val == 'off') {
    imageName += '_off';
  }  
  obj.src = '/MultiOpac/prolib/img/' + imageName + '.png';
}

function changeImgById(idVal, action_val, turn_val) {
  var imageName = '';
  var obj = document.getElementById(idVal);
  
  if (action_val == 'edit') {
    imageName = 'edit_icon';
  }
  else if (action_val == 'remove') {
    imageName = 'remove_icon';
  }
  if (action_val == 'update') {
    imageName = 'update_icon';
  }
  if (action_val == 'idxlist_icon') {
    imageName = 'idxlist_icon';
  }
  if (turn_val == 'off') {
    imageName += '_off';
  }  
  obj.src = '/MultiOpac/prolib/img/' + imageName + '.png';
}

/******************************************************************************
 *  Zmiana kolejnosci sortowania
 */ 
function setSortId(adm_val, s_val) {
  document.location.href = 'admin.html?adm=' + adm_val + '&s=' + s_val;
}

/******************************************************************************
 *  EDYCJA/DODANIE BIBLIOTEKI
 */ 
function runBibSubmit(count) {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var isChecked = false;
  var kategorie = document.getElementById('kategorieform');
  var nazwa = document.getElementById('idnazwa');
  var idbib = document.getElementById('ididbib');
  var host = document.getElementById('idhost');
  var port = document.getElementById('idport');
  var wsagent = document.getElementById('idwsagent');

  // reset kolorow
  kategorie.style.backgroundColor = defaultColor;
  nazwa.style.backgroundColor = defaultColor;
  idbib.style.backgroundColor = defaultColor;
  host.style.backgroundColor = defaultColor;
  port.style.backgroundColor = defaultColor;
  wsagent.style.backgroundColor = defaultColor;
  
  // czy zaznaczono kategorie
  for (var i=0; i<count; i++) {
    if (document.getElementById('Check' + i).checked == true) {
      isChecked = true;
      break;
    }
  }

  if (isChecked == false) {
    kategorie.style.backgroundColor = errorColor;  
    isValid = false;
  }  
  if (nazwa.value == '') {
    nazwa.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (idbib.value == '') {
    idbib.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (host.value == '') {
    host.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (port.value == '') {
    port.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (wsagent.value == '') {
    wsagent.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }

  return isValid;
}

/******************************************************************************
 *  Usuniecie biblioteki z listy
 */ 
function RemBib(bib_nr,bibName,s, adm) {
  integerValue = bib_nr;
  stringValue = bibName;
  idSortValue = s;
  idAdminValue = adm;
  questionBox('Pytanie', 'Czy na pewno chcesz usunąć bibliotekę "<strong>' + stringValue + '</strong>" z listy?', 'Tak', 'Nie', deleteLibrary, resetGlobal);
}

function deleteLibrary() {
  window.location.href = 'edit.html?action=4&idbib=' + integerValue + '&s=' + idSortValue + '&adm=' + idAdminValue;  
  resetGlobal();
}

/******************************************************************************
 *  EDYCJA/DODANIE MIASTA
 */ 
function runCitySubmit() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var nazwa = document.getElementById('idnazwa');
  
  // reset kolorow
  nazwa.style.backgroundColor = defaultColor;
  
  if (nazwa.value == '') {
    nazwa.style.backgroundColor = errorColor;
    isValid = false;
  }
  
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }

  return isValid;
}

/******************************************************************************
 *  Usuniecie miasta z listy
 */ 
function RemMia(mia_nr,miaName,s, adm) {
  integerValue = mia_nr;
  stringValue = miaName;
  idSortValue = s;
  idAdminValue = adm;
  questionBox('Pytanie', 'Czy na pewno chcesz usunąć miasto "<strong>' + stringValue + '</strong>" z listy?', 'Tak', 'Nie', deleteCity, resetGlobal);
}

function deleteCity() {
  window.location.href = 'edit.html?action=6&idmia=' + integerValue + '&s=' + idSortValue + '&adm=' + idAdminValue;  
  resetGlobal();
}

/******************************************************************************
 *  EDYCJA/DODANIE KATEGORII
 */ 
function runCatSubmit() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var nazwa = document.getElementById('idnazwa');
  var kod = document.getElementById('idkod');
  
  // reset kolorow
  nazwa.style.backgroundColor = defaultColor;
  kod.style.backgroundColor = defaultColor;
  
  if (nazwa.value == '') {
    nazwa.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (kod.value == '') {
    kod.style.backgroundColor = errorColor;
    isValid = false;
  }
  
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }

  return isValid;
}

/******************************************************************************
 *  Usuniecie kategorii z listy
 */ 
function RemKat(kat_nr,kodKat,katName,s, adm) {
  integerValue = kat_nr;
  stringValue2 = kodKat;
  stringValue = katName;
  idSortValue = s;
  idAdminValue = adm;
  questionBox('Pytanie', 'Czy na pewno chcesz usunąć kategorię "<strong>' + stringValue + '</strong>" z listy?', 'Tak', 'Nie', deleteCat, resetGlobal);
}

function deleteCat() {
  window.location.href = 'edit.html?action=10&idKat=' + integerValue + '&kodKat=' + stringValue2 + '&s=' + idSortValue + '&adm=' + idAdminValue;  
  resetGlobal();
}

/******************************************************************************
 *  EDYCJA/DODANIE INDEKSU
 */ 
function runIndSubmit() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var nazwa = document.getElementById('idnazwa');
  var kodprolib = document.getElementById('idkodprolib');
  var kodm21 = document.getElementById('idkodm21');
  
  // reset kolorow
  nazwa.style.backgroundColor = defaultColor;
  kodprolib.style.backgroundColor = defaultColor;
  kodm21.style.backgroundColor = defaultColor;
  
  if (nazwa.value == '') {
    nazwa.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (kodprolib.value == '') {
    kodprolib.style.backgroundColor = errorColor;
    isValid = false;
  }
  if (kodm21.value == '') {
    kodm21.style.backgroundColor = errorColor;
    isValid = false;
  }
  
  if (!isValid) { 
    AlertBox('Uwaga!', '<span class="redColor">Wypełnij wszystkie wymagane pola.</span>', 'OK'); 
  }

  return isValid;
}

/******************************************************************************
 *  Usuniecie indeksu z listy
 */ 
function RemInd(ind_nr,indName,s, adm) {
  integerValue = ind_nr;
  stringValue = indName;
  idSortValue = s;
  idAdminValue = adm;
  questionBox('Pytanie', 'Czy na pewno chcesz usunąć kategorię "<strong>' + stringValue + '</strong>" z listy?', 'Tak', 'Nie', deleteInd, resetGlobal);
}

function deleteInd() {
  window.location.href = 'edit.html?action=12&idInd=' + integerValue + '&s=' + idSortValue + '&adm=' + idAdminValue;  
  resetGlobal();
}

/******************************************************************************
 *  Otworzenie okienka z pomoca
 */ 
function showHelp() {
  var winHelp = window.open('/MultiOpac/prolib/mohelp/startowa.html', '', 'width=700,height=500,noresizable');
  winHelp.creator = self;
}

/******************************************************************************
 *  Aktualizacja danych o wersjach opaca www
 */ 
function updateVer() {
  if (isModalOpen == false) {
    questionBox('Aktualizacja danych!', 'Czy chcesz uaktualnić informacje o wersjach Opaca WWW?', 'Tak', 'Nie', updateDoIt);
  }
}

function updateDoIt() {    
    loadingboxBox(); 
    iCountBib = tabLinks.length;    
    iCurrentCountBib = 1;                      
    sendRequestToOpac(1);
}

function sendRequestToOpac(lpbib) {
  var urlAdd = tabLinks[lpbib];
  if (typeof(urlAdd) == 'undefined') {
    iCurrentCountBib += 1;
    if (iCurrentCountBib == iCountBib + 1) {
      hideForm();  
    }
    else {
      sendRequestToOpac(iCurrentCountBib);        
    }        
  }
  else {
    if (urlAdd.substring(urlAdd.length - 1, urlAdd.length) != '/') {
      urlAdd = 'http://' + urlAdd + '/getver.p';
    }
    else {
      urlAdd = 'http://' + urlAdd + 'getver.p';
    }
    advAJAX.get({
      url: 'services.html?mNum=1&urlA=' + urlAdd,
      timeout : 5000,
      onSuccess : function(obj) {
        if (obj.responseText.indexOf('versionxml') == -1 ){
          setValues(lpbib, false);
        } 
        else {
          /* sprawdzenie wersji proliba */
          var xmlDoc = obj.responseXML.documentElement;
          var elements = xmlDoc.getElementsByTagName('versionnum');
          var versionnum = elements[0].childNodes[0].nodeValue;
          var parts = versionnum.split('.');
          var val1 = parseInt(parts[0]);
          var val2 = parseInt(parts[1]);
          if ((val1 == 2008) && (val2 >= 3)) {
            setValues(lpbib, true);
          }
          else 
          if (val1 > 2008) {
            setValues(lpbib, true);
          }
          else {          
            setValues(lpbib, false);
          }
        }
        iCurrentCountBib += 1;        
        if (iCurrentCountBib == iCountBib + 1) {
          hideForm();    
        }
        else {
          sendRequestToOpac(iCurrentCountBib);        
        }
      },
      onError : function(obj) {
        setValues(lpbib, false);
        iCurrentCountBib += 1;
        if (iCurrentCountBib == iCountBib + 1) {
          hideForm();    
        }
        else {
          sendRequestToOpac(iCurrentCountBib);        
        }
      },
      onTimeout : function(obj) {
        setValues(lpbib, false);
        iCurrentCountBib += 1;
        if (iCurrentCountBib == iCountBib + 1) {
          hideForm();
        }
        else {
          sendRequestToOpac(iCurrentCountBib);        
        }        
      }
    });      
  }
}

function setValues(idelement, val) {
  if (val == true) {
    document.getElementById('updateico' + idelement).src = '/MultiOpac/prolib/img/correct_icon.png';
    document.getElementById('updateico' + idelement).title = 'Nowy Opac WWW';
    document.getElementById('updateval' + idelement).value = 'YES';               
  }
  else if (val == false) {
    document.getElementById('updateico' + idelement).src = '/MultiOpac/prolib/img/incorrect_icon.png';
    document.getElementById('updateico' + idelement).title = 'Stary Opac WWW';
    document.getElementById('updateval' + idelement).value = 'NO';  
  }
  else {
    document.getElementById('updateico' + idelement).src = '/MultiOpac/prolib/img/unknow_icon.png';
    document.getElementById('updateico' + idelement).title = 'Nieznana';
    document.getElementById('updateval' + idelement).value = 'NO';    
  }
}

function hideForm() {
  YAHOO.loadingbox.loadingbox.hide();
  isModalOpen = false;    
  questionBox('Zapisać zmiany?', 'Czy zapisać aktualne dane?', 'Tak', 'Nie', saveData, resetData);  
}

function saveData() {
  document.saveversions.submit();
}

function resetData() {
  location.reload();
}

function checkVersion() {
  var isValid = true;
  var defaultColor = '#ffffff';  
  var errorColor = '#FF8888';
  var host = document.getElementById('idhost');
  var agent = document.getElementById('idwsagent');
  var contents = document.getElementById('updatefunc');
  var urlAdd = 'http://';
  
  //reset pol
  host.style.backgroundColor = defaultColor;
  agent.style.backgroundColor = defaultColor;
  
  if ((host.value == '') || (agent.value == '')) {
    host.style.backgroundColor = errorColor;
    agent.style.backgroundColor = errorColor;
    AlertBox('Uwaga!', '<span class="redColor">Do prawidłowego działania wymagane jest wypełnienie pól: <b>Host</b> i <b>WebSpeed Agent</b>.</span>', 'OK');
  }
  else {
    //wyslij zapytanie
    contents.innerHTML = "<img src='/MultiOpac/prolib/img/loader-orange.gif' width='16' height='16' />";
    urlAdd += host.value + '/' + agent.value + '/getver.p';
    advAJAX.get({
      url: 'services.html?mNum=1&urlA=' + urlAdd,
      timeout : 9000,
      onSuccess : function(obj) {
        if (obj.responseText.indexOf('versionxml') == -1 ){
          setResult(false);
        } 
        else {
          /* sprawdzenie wersji proliba */
          var xmlDoc = obj.responseXML.documentElement;
          var elements = xmlDoc.getElementsByTagName('versionnum');
          var versionnum = elements[0].childNodes[0].nodeValue;
          var parts = versionnum.split('.');
          var val1 = parseInt(parts[0]);
          var val2 = parseInt(parts[1]);
          if ((val1 == 2008) && (val2 >= 3)) {
            setResult(true);
          }
          else 
          if (val1 > 2008) {
            setResult(true);
          }
          else {          
            setResult(false);
          }
        }        
      },
      onError : function(obj) {
        setResultError('error');
      },
      onTimeout : function(obj) {
        setResultError('timeout');
      }
    });          
  }
}

function setResult(val) {
  var contents = document.getElementById('updatefunc');
  contents.innerHTML = "<a href='javascript:checkVersion();' title='Sprawdź, czy używany jest nowy Opac WWW'>&#171; Sprawdź</a>";
  if (val == true) {
    document.getElementById('isnew').checked = true;
    AlertBox('Wynik', 'Sprawdzana biblioteka posiada nowy Opac WWW', 'OK');
  }
  else {
    document.getElementById('isnew').checked = false;
    AlertBox('Wynik', 'Sprawdzana biblioteka posiada stary Opac WWW', 'OK');
  }
}

function setResultError(type) {
  var contents = document.getElementById('updatefunc');
  contents.innerHTML = "<a href='javascript:checkVersion();' title='Sprawdź, czy używany jest nowy Opac WWW'>&#171; Sprawdź</a>";
  document.getElementById('isnew').checked = false;
  if (type == 'error') {
    AlertBox('Uwaga!', '<span class="redColor">Nie można nawiązać połączenia z hostem.</span>', 'OK');
  }
  else if (type == 'timeout') {
    AlertBox('Uwaga!', '<span class="redColor">Host nie odpowiada. Sprwadź ustawienia hosta.</span>', 'OK');
  }
}

function closeWaitingBox() {
  YAHOO.loadingbox.loadingbox.hide();
  isModalOpen = false;    
}

/**
 *  Aktualizacja informacji o wersjach obslugujacych aliasy indeksow wyszukiwawczych
 */
function updateAliases() {
  if (isModalOpen == false) {
    loadingboxBox(); 
    iCountBib = tabLinks.length;    
    iCurrentCountBib = 1;   
    sendRequestToOpac2(1);                   
  }
} 

function sendRequestToOpac2(lpbib) {
  var urlAdd = tabLinks[lpbib];
  if (typeof(urlAdd) == 'undefined') {
    iCurrentCountBib += 1;
    if (iCurrentCountBib == iCountBib + 1) {
      saveAliasForm();  
    }
    else {
      sendRequestToOpac2(iCurrentCountBib);        
    }        
  }
  else {
    if (urlAdd.substring(urlAdd.length - 1, urlAdd.length) != '/') {
      urlAdd = 'http://' + urlAdd + '/getver.p';
    }
    else {
      urlAdd = 'http://' + urlAdd + 'getver.p';
    }
    advAJAX.get({
      url: 'services.html?mNum=1&urlA=' + urlAdd,
      timeout : 5000,
      onSuccess : function(obj) {
        if (obj.responseText.indexOf('versionxml') == -1 ){
          setAliasValue(lpbib, false);
        } 
        else {
          /* sprawdzenie wersji proliba */
          var xmlDoc = obj.responseXML.documentElement;
          var elements = xmlDoc.getElementsByTagName('versionnum');
          var versionnum = elements[0].childNodes[0].nodeValue;
          var parts = versionnum.split('.');
          var val1 = parseInt(parts[0]);
          var val2 = parseInt(parts[1]);
          if ((val1 == 2009) && (val2 >= 1)) {
            setAliasValue(lpbib, true);
          }
          else 
          if (val1 > 2009) {
            setAliasValue(lpbib, true);
          }
          else {          
            setAliasValue(lpbib, false);
          }
        }
        iCurrentCountBib += 1;        
        if (iCurrentCountBib == iCountBib + 1) {
          saveAliasForm();    
        }
        else {
          sendRequestToOpac2(iCurrentCountBib);        
        }
      },
      onError : function(obj) {
        setAliasValue(lpbib, false);
        iCurrentCountBib += 1;
        if (iCurrentCountBib == iCountBib + 1) {
          saveAliasForm();    
        }
        else {
          sendRequestToOpac2(iCurrentCountBib);        
        }
      },
      onTimeout : function(obj) {
        setAliasValue(lpbib, false);
        iCurrentCountBib += 1;
        if (iCurrentCountBib == iCountBib + 1) {
          saveAliasForm();
        }
        else {
          sendRequestToOpac2(iCurrentCountBib);        
        }        
      }
    });      
  }
}

function setAliasValue(idelement, val) {
  if (val == true) {
    document.getElementById('updateval' + idelement).value = 'YES';               
  }
  else if (val == false) {
    document.getElementById('updateval' + idelement).value = 'NO';  
  }
  else {
    document.getElementById('updateval' + idelement).value = 'NO';    
  }
}

function saveAliasForm() {
  YAHOO.loadingbox.loadingbox.hide();
  isModalOpen = false;    
  document.savealiases.submit();  
}

/**
 *  Ustawienie odpowiedniej wartosci radio buttonna
 */

