///////////////////////////////////////////////////////////////////////////
//
// popup.js
//
// Copyright (c) 2003 by HERMES SoftLab
//
///////////////////////////////////////////////////////////////////////////
//
// CLIENT-SIDE POPUP WINDOW
//
// Displays custom popup in current web page
// Popup is opened by calling
// new Popup(name, srcUrl, params, onCloseFunction)
// name: popup frame name and id
// srcUrl: Url of page to load in frame (or null)
// params:
//   - posElement: name of element that we want the popup to be aligned with
//   - offsetX, offsetY: offset in pixels to be offset
//   - width, height: popup width and height
//   - sticky: whether popup can only be closed by pressing the CLOSE link (true), or is automaticaly closed when user clicks anywhere on page (false - default)
// onCloseFunction: function to be called when popup is closed (or null)
//
// e.g. new Popup("CalculateTaxPopup", "bla.html", "posElement=CalculateTaxPopup_Position, offsetX=0, offsetY=-200, width=350, height=200, sticky=true, waitOnly=true", MyCloseHandler);
// 
// When constructed, popup is available publicly at window.popupName (any page can access it).
// Popup window should have it's own javascript to handle two things:
// 1. Store return value: window.popupName.Value = value_to_return
// 2. Call method to close popup: window.popupName.Close()
// After this, onClose function will be called (that is provided in Popup.Display method).
// Close function can handle return value stored in window.popupName.Value.
//
///////////////////////////////////////////////////////////////////////////

///Popup name
var POPUP_NAME = 'searchPopup';

/// Popup constructor
function Popup(name, srcUrl, params, onCloseFunction, drawOnRight)
{
  // Close existing instance of popup if available
  if (window[name] && window[name].Close) window[name].Close();
  
  popupParams = new PopupParams(params);
  var pos = GetElementAbsolutePosition(popupParams.PositionElement);
  
  var layer = document.createElement("div");
  layer.style.position = "absolute";
   
  if (drawOnRight)
  {
	popupParams.OffsetX = 120;
	popupParams.OffsetY = -100;    
  }

  
  var layerLeft = (pos.x + popupParams.OffsetX + 4) + "px";
  var layerTop  = (pos.y + popupParams.OffsetY + 3) + "px";
    
  layer.style.left = layerLeft;
  layer.style.top = layerTop;
  layer.className = "popup";
  
  // Add table with CLOSE button and wait icon (close button depends on WaitOnly parameter)
  var html = "<table cellpadding='0' cellspacing='0' border='0' width='" + parseInt(popupParams.Width+1) + "'>"
  if (!popupParams.WaitOnly) html += "<tr height='25' class='popupheader'><td><a href='javascript:window." + name + ".Close()'>Zapri okence</a></td></tr>";
  html += "<tr class='popupwait' height='" + parseInt(popupParams.Height) + "'><td align='center'>Prosimo po&#269;akajte</td></tr></table>";
  layer.innerHTML = html;
  
    // Add layer to the page
  document.body.appendChild(layer);
  
  if (!popupParams.WaitOnly) {
    // Creates iframe, position it relative to provided elt and load provided url into it
    var iframe = document.createElement("iframe");
    iframe.id = name;
    iframe.name = name;
    iframe.src = srcUrl;
    iframe.allowTransparency = true;
    iframe.style.position = "absolute";
    iframe.style.left = "0px";
    iframe.style.top = "25px";
    iframe.width = popupParams.Width;
    iframe.height = popupParams.Height;
    iframe.border = 0;
    iframe.frameBorder = 0;
    iframe.marginWidth = 0;
    layer.appendChild(iframe);
    
    // Browser BUG - frame name is not updated in document.frames collection so it should be declared explicitely
    window.frames[window.frames.length-1].name = name;
  }
  
  window[name] = this;
  
  if (!popupParams.Sticky) AddEvent(document, "mousedown", Close);
  
  // Initialize "public" popup properties
  Layer = layer;
  Value = null;
  OnClose = onCloseFunction;
  
  this.Close = Close;
  
  /// Close current popup instance
  function Close() {
    if (OnClose != null) OnClose();
    document.body.removeChild(Layer);
    RemoveEvent(document, "mousedown", Close);
    window[name] = null;
  }
  
  /// Gets absolute position of element on page
  function GetElementAbsolutePosition(eltId){
    if (eltId == null)
      return {x:0,y:0};
    else {
      el = document.getElementById(eltId);
      for (var lx=0,ly=el.offsetHeight;el!=null;
	      lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
      return {x:lx,y:ly}
    }
  }
 
  /// Add event to provided document element
  function AddEvent(el, evname, func) {
    if (el.attachEvent) { // IE
	    el.attachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
	    el.addEventListener(evname, func, true);
    } else { // Opera (or old browsers)
	    el["on" + evname] = func;
    }
  }
  
  /// Detach event from provided document element
  function RemoveEvent(el, evname, func) {
    if (el.detachEvent) { // IE
	    el.detachEvent("on" + evname, func);
    } else if (el.removeEventListener) { // Gecko / W3C
	    el.removeEventListener(evname, func, true);
    } else { // Opera (or old browsers)
	    el["on" + evname] = null;
    }
  }
  
  function PopupParams(params) {
    this.PositionElement = GetParam(params, "posElement", null);
    this.Width = parseInt(GetParam(params, "width", 200));
    this.Height = parseInt(GetParam(params, "height", 200));
    this.OffsetX = parseInt(GetParam(params, "offsetX", 0));
    this.OffsetY = parseInt(GetParam(params, "offsetY", 0));
    this.Sticky = (GetParam(params, "sticky", "false") == "true");
    this.WaitOnly = (GetParam(params, "waitOnly", "false") == "true");
  }

  function GetParam(params, name, defaultValue) {
    var posStart = params.indexOf(name + "=");
    if (posStart != -1) {
      params = params.substr(posStart);
      var posEnd = params.indexOf(",");
      if (posEnd == -1) posEnd = params.length;
      return params.substring(name.length+1, posEnd);
    } else return defaultValue;
  }

}

///////////////////////////////////////////////////////////////////////////
//
// An 'overload' of the function LookupPopupOpen, which contains another parameter, specifying the
// enumeration of the SifrantEnum, which helps determine the type of the Sifrant Search.
//
// The function is virtually the same as LookupPopupOpen, except that it receives another parameter.
//
// Because it is dangerous to overload methods in javascript, it must have a different name.
//
///////////////////////////////////////////////////////////////////////////

function LookupPopupOpenSifrant (ValueTextBoxId, DescriptionTextBoxId, AddedFilter, Params, TypeSifrant, DrawOnRight)
{
    //Init query variable
    var qstring = "";
    
    //Javascript version of atoi()
    var iTypeSifrant = TypeSifrant * 1;
    
    //Hard coded sifrant search page url
    //Set enumval and callername
    qstring = "../Modals/IskanjeSifrant.aspx" + "?enumval=" + iTypeSifrant;
    
    LookupPopupOpen(ValueTextBoxId, DescriptionTextBoxId, AddedFilter, qstring, Params, DrawOnRight);
}

///////////////////////////////////////////////////////////////////////////
//
// Opens popup and fills two textboxes on main form (that contain key and value)
//
// ValueTextBoxId: client id of textbox in the main window, which contains key value for lookup list of values
// DescriptionTextBoxId: client id of textbox in the main window, that will be filled with lookup list description text,
//   after user selects a value in popup window
// SearchUrl: Url of page that should be loaded in popup window (this function automatically appends
//   query string parameter "id=[key]" to the url, where "[key]" is value user entered in text box provided in ValueTextBoxId param
// Params: Additional parameters for popup (width, height, ... - see params help for client-side Popup() function.
//
///////////////////////////////////////////////////////////////////////////
function LookupPopupOpen(ValueTextBoxId, DescriptionTextBoxId, AddedFilter, SearchUrl, Params, DrawOnRight)
{
    val = document.getElementById(ValueTextBoxId).value;
    var qstring = "";
    if (val != "") 
    {
      qstring = (SearchUrl.indexOf("?") != -1) ? "&" : "?"
      qstring += "id=" + val;
    }
    
    SearchUrl += qstring;        
    
    var add = (document.getElementById(AddedFilter)) ? document.getElementById(AddedFilter).value : "";
    qstring = "";    
    if (add != "")
    {
      qstring = (SearchUrl.indexOf("?") != -1) ? "&" : "?"      
      qstring += "add=" + add;
    }
    
    SearchUrl += qstring;            
    
    new Popup(POPUP_NAME, SearchUrl, 'sticky=true, posElement=' + ValueTextBoxId + ", " + Params, Close, DrawOnRight);
    
    function Close()
    {
      val = window[POPUP_NAME].Value;
      if (val) 
      {
        document.getElementById(ValueTextBoxId).value = val;
        document.getElementById(ValueTextBoxId).focus();
        document.getElementById(ValueTextBoxId).onchange();
      }
      if (DescriptionTextBoxId) {
        val = window[POPUP_NAME].Value2;
        if (val) {
          var el = document.getElementById(DescriptionTextBoxId);
          if (el.tagName == "INPUT") el.value = val;
          else el.innerHTML = val;
        }
      }
      
      var which = ValueTextBoxId.substring(3, ValueTextBoxId.length-6);
      
      if (which == 'Ladja')
      {
        if (document.getElementById('txtLadjarOznaka'))
        {
          var newLadjar = vrniLadjarOdLadje(document.getElementById(ValueTextBoxId));
          
          document.getElementById('txtLadjarOznaka').value=newLadjar;
        }
/*        
        if (document.getElementById('txtUgrez'))
        {
          var newUgrez = vrniUgrezOdLadje(document.getElementById(ValueTextBoxId));
          document.getElementById('txtUgrez').value=newUgrez;
        }
*/
      }
    }
}

function LookupPopupClose(id, description)
{
  parent.window[POPUP_NAME].Value = id;
  parent.window[POPUP_NAME].Value2 = ime;
  parent.window[POPUP_NAME].Close();
}

/*
 * Wrapper function around HttpGet.LookupPopupCheckValue() (in ui.js), 
 * so that it is common to all search inputs on all forms
 */
function vrniOznakoOdNaziva (imeSifrant)
{
    var txtOznakaId = 'txt' + imeSifrant + 'Oznaka';
    var txtNazivId  = 'txt' + imeSifrant + 'Naziv';
    
    HttpGet.LookupPopupCheckValue(txtOznakaId, txtNazivId, '../Modals/PreveriSifrant.aspx?sifrant='+imeSifrant);
}

/*
 * Wrapper function around HttpGet.LookupPopupCheckValue() (in ui.js)
 */
function preveriCRC11 ()
{    
    var txtOznakaId = 'txtKontejnerStevilka';
    var txtNazivId  = 'lblOpozorilo';
    HttpGet.LookupPopupCheckValue(txtOznakaId, txtNazivId, '../Modals/PreveriCRC11.aspx?sifrant=aaaa');
}

function vrniNamembnaPostajaOdUprava()
{
    var namembnaUpravaOznaka = document.getElementById('txtNamembnaUpravaOznaka').value;
    
    HttpGet.LookupPopupCheckValue('txtNamembnaPostajaOznaka', 'txtNamembnaPostajaNaziv', '../Modals/PreveriSifrant.aspx?namembnauprava='+namembnaUpravaOznaka);
}

function vrniLadjarOdLadje ()
{
    completed = false;
    var ladjaOznaka = document.getElementById('txtLadjaOznaka').value;
    HttpGet.LookupPopupCheckValue_Double('txtLadjaOznaka', 'txtLadjarOznaka', 'txtUgrez', '../Modals/PreveriSifrant.aspx?ladja=' + ladjaOznaka);
    setTimeout("koncajVrniLadjarOdLadje()", 500);
}

/*
function vrniUgrezOdLadje()
{
    completed = false;
    var ladjaOznaka = document.getElementById('txtLadjaOznaka').value;
    HttpGet.LookupPopupCheckValue('txtLadjaOznaka', 'txtLadjarOznaka', '../Modals/PreveriSifrant.aspx?ladja=' + ladjaOznaka);
    setTimeout("koncajVrniLadjarOdLadje()", 500);
}
*/

function koncajVrniLadjarOdLadje()
{
    if (!completed)
    {
		setTimeout("koncajVrniLadjarOdLadje()", 500);    
    }
    else
    {
		vrniOznakoOdNaziva('Ladjar');      
		completed = false;
    }
}

function vrniNazivDrzavaKraj(postfixPolja)
{
    var listDrzavaId = 'listDrzava' + postfixPolja;
    var txtOznakaKrajaId = 'txtKraj' + postfixPolja + 'Oznaka';
    var txtNazivKrajaId  = 'txtKraj' + postfixPolja + 'Naziv';
    
    var oznakaDrzave = document.getElementById(listDrzavaId).value;
    var oznakaKraja = document.getElementById(txtOznakaKrajaId).value;
    if (oznakaKraja != "") {
        oznakaKraja = oznakaDrzave + oznakaKraja; // 5-znakovna polna oznaka kraja
        HttpGet.LookupPopupCheckValue_ByValue(oznakaKraja, txtNazivKrajaId, '../Modals/PreveriSifrant.aspx?sifrant=DrzavaKraj&drzava=' + oznakaDrzave);    
    }
}