
// error s in field f
function um_form_napaka(s,f) {
  alert(s);
  if ( f.focus ) f.focus();
}


// new popup window
var um_form_win = null;
var um_form_win_reloadonclose = false;

function um_form_okno(url) {
  var n = ( arguments[1] || 'Popup' );
  var x = ( arguments[2] || 0 );
  var y = ( arguments[3] || 0 );
  var p = ( arguments[4] || 'width=300,height=400,toolbar=0,location=0,status=0,menubar=0,titlebar=0,scrollbars=1,resizable=1' ); //,alwaysRaised,dependent' );
  var r = ( arguments[5] || 0 );

  um_form_win_reloadonclose = ( r == 1 );

  p = 'left=' + x + ',screenX=' + x + ',top=' + y + ',screenY=' + y + ',' + p;
  
  um_form_win = window.open(url, n, p);
  if ( um_form_win) {
      um_form_win.opener = self;
      um_form_win.focus();
  }
}

function um_form_win_refresh() {
  if ( um_form_win_reloadonclose ) um_form_win.opener.location.reload();
  um_form_win_reloadonclose = false;
}

function um_form_win_close() {
  if ( um_form_win )
  {
    um_form_win.close();
    return true;
  } else
    return false;
}


// file selector/manager
var um_form_fileControl = null;

function um_form_filebrowser(url) {
  um_form_fileControl = ( arguments[1] || null );
  um_form_okno( url, arguments[2], arguments[3], arguments[4], arguments[5] || 'width=780,height=500,toolbar=0,location=0,status=0,menubar=0,titlebar=0,scrollbars=1,resizable=1' );
}

function um_form_fileSelect(f) {

  var elem = null;

  if (opener.um_form_editfield)
    elem = opener.um_form_editfield;
  else if (opener.um_form_fileControl)
    elem = opener.um_form_fileControl;

  if ( elem )
    with ( elem )
    {
      value = f;
      select();
      try {
        onchange();
      } catch (e) {
        // skip err
      }
    }

  top.close();

}


// new HTML editor
function um_form_html(f) {


  //var n = ( arguments[1] || 'Popup' );
  //var x = ( arguments[2] || 0 );
  //var y = ( arguments[3] || 0 );
  var p = ( arguments[4] || 'width=750,height=560,toolbar=0,resize=1,location=0,status=0,menubar=0,titlebar=0,scrollbars=1,resizable' ); //,alwaysRaised,dependent' );

  //p = 'left=' + x + ',screenX=' + x + ',top=' + y + ',screenY=' + y + ',' + p;

  window.inEdit = f;
  // starting value will be set in editor - opener.inEdit

  //var win = window.open("u.asp", n, p);
  //win.opener = self;
  //win.focus();

  um_form_okno("u.asp", "Editor", arguments[2], arguments[3], p);

}

// multiple_values join
function um_form_submit(f) {
  // travel each and every field,
  // if name ends with "_x_" join all values into one "|"-separated string
  // and assign it to field with same name but without "_x_"

  var s = "", n = "";

	if ( f && f.elements && f.elements.length )
	  for ( var i = 0; i < f.elements.length; i++ ) {
	    if ( f.elements[i].name.substr(0,3) == "_x_" && f.elements[i].type.substr(0,6) == "select" ) {
	      n = f.elements[i].name.substr(3);
	      for ( j = 0; j < f.elements[i].options.length; j++ )
	        s += '|' + f.elements[i].options[j].text;
	    }
	  }

	// can add additional validation, based on form name???
	if ( typeof( um_form_submit_custom ) != 'undefined' ) 
		if ( !um_form_submit_custom(f) ) return false;

  // now everything is always fine
	// hide submit button
	if ( f.um_form_submiter ) f.um_form_submiter.style.visibility = 'hidden';
  return true;

}


// add value of f to list l
function um_form_dodajX(f,l) {
  if ( f.value != '' ) {
    var n = new Option( f.value, f.value, false, true );
    with ( l ) {
      options[length] = n;
    }
  } else {
    um_form_napaka( 'Vnesi vrednost!', f );
  }
}


// remove selected value(s) from list l
function um_form_odstraniX ( l ) {
  var del = false;

  with ( l ) {
    for ( var i = 0; i<length; i++ ) {
      if ( options[i].selected ) {
        options[i] = null;
        del = true;
      }
    }
  }

  if ( !del ) um_form_napaka( 'Najprej izberi vrednost', l );
}


// copy selected value of l in text field
function um_form_izberiX( l ) {
  var f = l.name.substr(3);
  if ( l.form.elements[f].value ) l.form.elements[f].value = l.options[l.selectedIndex].text;
}


// moves selected item(s) of list l in up or down direction
function um_form_premakniX( l, d ) {

  with ( l ) {
    if ( d ) {
      // up
      for ( var i = 1; i < length; i++ ) {
        if ( options[i].selected ) {
          t = options[i-1].text;
          options[i-1].text = options[i].text;
          options[i-1].selected = true;
          options[i].text = t;
          options[i].selected = false;
        }
      }
    } else {
      // down
      for ( var i = length-2; i >= 0; i-- ) {
        if ( options[i].selected ) {
          t = options[i+1].text;
          options[i+1].text = options[i].text;
          options[i+1].selected = true;
          options[i].text = t;
          options[i].selected = false;
        }
      }
    }
  }

}


// sort options of list l
function um_form_urediX ( l ) {
  var a = new Array();
  var i = 0;

  with ( l ) {
    for ( i = 0; i < length; i++ ) a[i] = options[i].text;
    a.sort(um_form_primerjajS);
    for ( i = 0; i < length; i++ ) options[i].text = a[i];
  }

}

// helper sort function for case insensitive sort
function um_form_primerjajS(a, b) {
  var anew = a.toLowerCase();
  var bnew = b.toLowerCase();
  if (anew < bnew) return -1;
  if (anew > bnew) return 1;
  return 0;
}




// form calendar helper function
var um_formCalendarDivWidth = 0;

function um_form_koledar(f, time)
{

	// already there?
	if ( window.calendarPopups && window.calendarPopups.length ) 
		for (var i = 0; i < window.calendarPopups.length; i++)
			if ( window.calendarPopups[i].getFormField() == f ) return;
			
  var jezik = arguments[2] || 'si';
	var calign = arguments[3] || 'rt';
  var cal = new UMClientCalendar(jezik, time);
  cal.setFormField( f );

  switch ( jezik ) {
    case 'si':
      var d = f.value.split(".", 3);
      break;

    default:
      var d = f.value.split("/", 3);
  }

  if ( d.length == 3 )
    if ( d[2].length > 4 )
    {
      var h = d[2].substr(5).split(":");
      cal.setDate( d[2].substr(0,4), d[1], d[0], h[0], h[1] );
    }
    else
      cal.setDate( d[2], d[1], d[0] );

  var p = cal.getPos(f);
	var dX = 0;
  var dY = 0;
  if (calign == 'rt' ) {
		dX = f.offsetWidth + 2;
		dY = -2; //16;
	} else if (calign == 'rb') {
		if ( um_formCalendarDivWidth == 0 ) um_formCalendarDivWidth = UMClientCalendar_getCalendarDivWidth();
		dX = f.offsetWidth - um_formCalendarDivWidth;
		dY = 16;
	}

  cal.showCalendar( p.left + dX, p.top + dY );

  return true;
}

/* *******************************************

  UMClientCalendar Object
  ---
  client side javascript popup calendar

 ******************************************* */

// Constructor
function UMClientCalendar() {

  // references to popups...
  if ( !window.calendarPopupIndex ) { window.calendarPopupIndex = 0; }
  if ( !window.calendarPopups ) { window.calendarPopups = new Array(); }
  this.index = calendarPopupIndex++;
  calendarPopups[this.index] = this;

  // other language can be passed as param
  this.language = arguments[0] || 'en';
  this.showTime = arguments[1] || false;

	if ( top.umclientcalendar_prevodi_A ) {
		this.monthNames = top.umclientcalendar_prevodi_A.slice(0,12);
		this.dayHeaders = top.umclientcalendar_prevodi_A[12].split('|');
		this.words = top.umclientcalendar_prevodi_A.slice(13);
		if ( top.umclientcalendar_weekStartDay )
			this.weekStartDay = top.umclientcalendar_weekStartDay;
		else
			this.weekStartDay = 1;
	}
	else
	  switch ( this.language ) {
	    case 'si':
	      this.monthNames = new Array('januar','februar','marec','april','maj','junij','julij','avgust','september','oktober','november','december');
	      this.dayHeaders = new Array('N','P','T','S','&#268;','P','S');
	      this.weekStartDay = 1;
	      this.words = new Array('zapri', 'Koledar', 'danes', 'ura', 'minuta');
	      break;

			default:
	      this.monthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	      this.dayHeaders = new Array('S','M','T','W','T','F','S');
	      this.words = new Array('close', 'Calendar', 'Today', 'Hour', 'Minute');
	      this.weekStartDay = 0;
	  }

  this.calendarPopup = null;
  this.theDate = new Date(); this.theDate.setHours(0,0);
  this.formField = null;

  // Method mappings
  this.setDate = UMClientCalendar_setDate;
  this.setFormField = UMClientCalendar_setFormField;
  this.getFormField = UMClientCalendar_getFormField;
  this.dateSelected = UMClientCalendar_dateSelected;
  this.setMonthNames = UMClientCalendar_setMonthNames;
  this.setDayHeaders = UMClientCalendar_setDayHeaders;
  this.setWeekStartDay = UMClientCalendar_setWeekStartDay;
  this.showCalendar = UMClientCalendar_showCalendar;
  this.hideCalendar = UMClientCalendar_hideCalendar;
  this.refreshCalendar = UMClientCalendar_refreshCalendar;
  this.getCalendar = UMClientCalendar_getCalendar;
  this.getClock = UMClientCalendar_getClock;
  this.setTime = UMClientCalendar_setTime;
	
	this.getPos = function(e) {
		var obj = e;
		var curleft = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curleft += obj.offsetLeft;
				obj = obj.offsetParent;
			}
		}
		else 
			if (obj.x)
				curleft += obj.x;

		obj = e;
		var curtop = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			}
		}
		else
			if (obj.y)
				curtop += obj.y;

		return {left: curleft, top:curtop};
	}

}


// callback...
function UMClientCalendar_dateSelected(i, y, m, d) {
  var f = window.calendarPopups[i].formField;
  var calDate = window.calendarPopups[i].theDate;
  var h = calDate.getHours();
  var min = calDate.getMinutes();

  switch ( window.calendarPopups[i].language ) {
    case "si":
    case "de":
      if (h != 0 || min != 0)
        f.value =  d + "." + m + "." + y + " " + h + ( min < 10 ? ":0" : ":" ) + min;
      else
        f.value =  d + "." + m + "." + y;
      break;

    default:
      if (h != 0 || min != 0)
        f.value =  d + "/" + m + "/" + y + " " + h + ( min < 10 ? ":0" : ":" ) + min;
      else
        f.value =  d + "/" + m + "/" + y;
      break;

  }

  UMClientCalendar_hideCalendar( i );
}



// Set the default date to display...
function UMClientCalendar_setDate() {
  var y = 0 + arguments[0];
  var m = 0 + arguments[1];
  var d = 0 + arguments[2];
  var h = 0 + arguments[3];
  var min = 0 + arguments[4];
  if ( y > 0 && m > 0 && m < 13 && d > 0 && d < 32 )
  {
    if ( h > 0 || min > 0 )
      this.theDate = new Date(y, m-1, d, h, min)
    else
      this.theDate = new Date(y, m-1, d)
  }
}


// Set the name of the form field to receive selected date
function UMClientCalendar_setFormField() {
  if ( arguments[0] ) this.formField = arguments[0];
}
function UMClientCalendar_getFormField() {
  return this.formField;
}

// Set the name of the function to call to get the clicked date
function UMClientCalendar_setReturnFunction(name) {
  this.returnFunction = name;
}

// Over-ride the built-in month names
function UMClientCalendar_setMonthNames() {
  for (var i=0; i<arguments.length; i++) {
    this.monthNames[i] = arguments[i];
  }
}

// Over-ride the built-in column headers for each day
function UMClientCalendar_setDayHeaders() {
  for (var i=0; i<arguments.length; i++) {
    this.dayHeaders[i] = arguments[i];
  }
}

// Set the day of the week (0-7) that the calendar display starts on
// This is for countries other than the US whose calendar displays start on Monday(1), for example
function UMClientCalendar_setWeekStartDay(day) {
  this.weekStartDay = day;
}

function UMClientCalendar_getCalendarDivWidth() {
	var w = 250;
	if ( document.styleSheets && document.styleSheets.length ) {
		for ( var s = 0; s < document.styleSheets.length; s++ ) {
            try {
                var rls = document.styleSheets[s].cssRules ? document.styleSheets[s].cssRules : document.styleSheets[s].rules;
                for ( var i=0; i < rls.length; i++ ) {
                    if ( rls[i].selectorText && rls[i].selectorText.toLowerCase() == 'div.frmcalpopup' ) {
                        w = parseInt(rls[i].style.width);
                        return w;
                    }
                }
            } catch (e) {}
		}
	}
	return w;
}

// Populate the calendar and display it
function UMClientCalendar_showCalendar(px, py) {

  var mx = ( px || 10 );
  var my = ( py || 10 );

  with ( this.calendarPopup = document.createElement('DIV') ) {
    className = 'frmCalPopup';
    var html;
    html = this.getCalendar( this.theDate.getFullYear(), this.theDate.getMonth() );
    if ( this.showTime ) html+= this.getClock();
    innerHTML = html;
    style.left = mx + 'px';
    style.top = my + 'px';
  }
	document.body.appendChild(this.calendarPopup);
}

// Hide a calendar object
function UMClientCalendar_hideCalendar( i ) {
  document.body.removeChild( window.calendarPopups[i].calendarPopup );
  window.calendarPopups[i].formField = null;
  window.calendarPopups[i].calendarPopup = null;
}

// Refresh the contents of the calendar display
function UMClientCalendar_refreshCalendar( i ) {
  with ( window.calendarPopups[i] ) {
    var html;
    if ( arguments.length>1 ) {
      html = getCalendar( arguments[1], arguments[2], arguments[3] )
    } else {
      html = getCalendar();
    }
    if ( showTime ) html += getClock();

    calendarPopup.innerHTML = html;
  }
}

// returns calendar html code
function UMClientCalendar_getCalendar() {
  var now = new Date();
  var mnt = arguments[1]; if ( mnt < 0 || mnt > 11 ) mnt = now.getMonth();
  var dt_datetime = new Date(
    arguments[0] || now.getFullYear(),
    mnt,
    arguments[2] || now.getDate()
  );
  var dt_prev_month = new Date( dt_datetime.getFullYear(), dt_datetime.getMonth(), -5 );
  var dt_next_month = new Date( dt_datetime.getFullYear(), dt_datetime.getMonth(), 35 );
  var dt_firstday = new Date(dt_datetime);
  dt_firstday.setDate(1);
  dt_firstday.setDate(1-(7+dt_firstday.getDay()-this.weekStartDay)%7);
  var dt_lastday = new Date(dt_next_month);
  dt_lastday.setDate(0);

  var dt_current_day = new Date(dt_firstday);
  result = '<center><table width="100%" border="0" cellspacing="0" cellpadding="1">';


  // navigation
	result += '<tr valign="middle"><td class="caldayh" style="cursor:pointer;" colspan="7" onclick="UMClientCalendar_hideCalendar(' + this.index + ');">&times;</a></td>';
	result += '</tr><tr valign="middle" align="center">';
	result += '<td class="cal" rowspan="2" width="20%" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + now.getFullYear() + ',' + now.getMonth() + ');" style="cursor:pointer;">' + this.words[2] + '</td>';
	result += '<td class="cal" colspan="2" width="40%">' + this.monthNames[ dt_datetime.getMonth() ] + '</td>';
	result += '<td class="cal" colspan="4" width="40%">' + dt_datetime.getFullYear() + '</td>';
	result += '</tr><tr valign="middle" align="center">';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + dt_prev_month.getFullYear() + ',' + dt_prev_month.getMonth() + ',1);" style="cursor:pointer;">&lsaquo;</td>';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + dt_next_month.getFullYear() + ',' + dt_next_month.getMonth() + ',1);" style="cursor:pointer;">&rsaquo;</td>';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + (dt_datetime.getFullYear()-10) + ',' + dt_datetime.getMonth() + ',1);" style="cursor:pointer;">&laquo;</td>';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + (dt_datetime.getFullYear()-1) + ',' + dt_datetime.getMonth() + ',1);" style="cursor:pointer;">&lsaquo;</td>';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + (dt_datetime.getFullYear()+1) + ',' + dt_datetime.getMonth() + ',1);" style="cursor:pointer;">&rsaquo;</td>';
	result += '<td class="cal" onclick="UMClientCalendar_refreshCalendar(' + this.index + ',' + (dt_datetime.getFullYear()+10) + ',' + dt_datetime.getMonth() + ',1);" style="cursor:pointer;">&raquo;</td>';
  result += '</tr></table>\n';


  // print weekdays titles
  result += '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr>';
  for (var n=0; n<7; n++)
    result += '<td class="caldayh">' + this.dayHeaders[ (this.weekStartDay + n) % 7 ] + '</td>';
  // print calendar table
  result += '</tr>';
  for ( var n = 0; n < 6; n++ ) {
  //while (dt_current_day.getMonth() == dt_datetime.getMonth() || dt_current_day.getMonth() == dt_firstday.getMonth()) {
    // print row header
    result += '<tr align="right">';
    for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {
        if (dt_current_day.getFullYear() == this.theDate.getFullYear() && dt_current_day.getDate() == this.theDate.getDate() && dt_current_day.getMonth() == this.theDate.getMonth())
          // mark stored date
          result += '<td class="calmark">';
        else if (dt_current_day.getFullYear() == now.getFullYear() && dt_current_day.getDate() == now.getDate() && dt_current_day.getMonth() == now.getMonth())
          // mark current date
          result += '<td class="caltoday">';
        else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6)
          // mark weekend days
          result += '<td class="calweekend">';
        else
          // mark working days of current month
          result += '<td class="calwork">';

        if (dt_current_day.getMonth() == dt_datetime.getMonth())
          // print days of current month
          result += '<a class="calthismonth" '

        else
          // print days of other months
          result += '<a class="calothermonth" '

        result += 'href="javascript:UMClientCalendar_dateSelected(' + this.index + ',' + dt_current_day.getFullYear() + ',' +
            (dt_current_day.getMonth()+1) + ',' + dt_current_day.getDate() + ');">' + dt_current_day.getDate() + '</a></td>\n';

        dt_current_day.setDate(dt_current_day.getDate()+1);
    }
    // print row footer
    result += '</tr>\n';
  }

  result += '</table></center>';

  return result;

}


function UMClientCalendar_setTime(i, h, m) {
	var c = window.calendarPopups[i];
	if ( h > -1 ) c.theDate.setHours(h);
	if ( m > -1 ) c.theDate.setMinutes(m);
	document.getElementById("um_clientcalendar_timeselect_" + i).innerHTML = 
			c.theDate.getHours() + ( c.theDate.getMinutes() < 10 ? ":0" : ":" ) + c.theDate.getMinutes();
}

// returns clock html code
function UMClientCalendar_getClock() {

  // hh:mm navigation
  result = '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr>';
  result += '<td colspan="12" class="cal" align="center"><span id="um_clientcalendar_timeselect_' +this.index + '">' + this.theDate.getHours() + (this.theDate.getMinutes() < 10 ? ':0' : ':') + this.theDate.getMinutes() + '</span></td>';
  result += '</tr><tr><td colspan="12" class="caldayh">' + this.words[3] + '</td></tr><tr align="right">';

  for ( var n = 0; n < 24; n++ )
  {
    result += '<td><a class="calthismonth" href="javascript:UMClientCalendar_setTime(' + this.index + ',' + n + ', -1);\">' + n + '</a></td>';
    if (n == 11) result += '</tr><tr align="right">';
  }

  result += '</tr></table><table width="100%" border="0" cellspacing="1" cellpadding="2"><tr><td colspan="12" class="caldayh">' + this.words[4] + '</td></tr><tr align="right">';

  for ( var n = 0; n < 60; n+=5 )
    if ( n < 10 )
      result += '<td><a class="calthismonth" href="javascript:UMClientCalendar_setTime(' + this.index + ', -1, ' + n + ');\">0' + n + '</a></td>';
    else
      result += '<td><a class="calthismonth" href="javascript:UMClientCalendar_setTime(' + this.index + ', -1, ' + n + ');\">' + n + '</a></td>';

  result += '</tr></table></center>';

  return result;

}

