/***********************************************
 DHTML Calendar by Jason Moon - http://www.dynamicdrive.com/dynamicindex7/jasoncalendar.htm
 Adapted by CrossMarx
 ************************************************/

/* The following global variables are used by the document onclick handler to determine wether calendars need to be hidden
 * Please note that the onclick handler may conflict with other attached events in its current implementation
 * TODO Global variables to global script object properties to avoid conflicts and extract calendar style 
 */
var calendars = new Array();
var onCalendar = false;

/* Customizable variables */
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 3; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var NextURL = '/engine/calendar/next.gif';
var PrevURL = '/engine/calendar/prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';

/* Other global variables */
var ZCounter = 100;
var Today = new Date();
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

if (CX.language == 'nl') {
	var WeekDays = new Array('Z','M','D','W','D','V','Z');
	var MonthNames = new Array('Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December');
}else { 
	var WeekDays = new Array('S','M','T','W','T','F','S');
	var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
}

/* Write out the stylesheet definition for the calendar */
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}

/* Gets the absolute pixel position of the supplied element */
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   return true;
}

/* Sets the form elements after a day has been picked from the calendar */
function PickDisplayDay(ClickedDay) {
   if (this.ondemand) {
      this.hide();
      this.picked = new storedMonthObject(this.format, this.displayed.yearValue, this.displayed.monthIndex+1, ClickedDay);
      if(this.DayField.value != ClickedDay || this.MonthField.value != this.displayed.monthIndex + 1 || this.YearField.value != this.displayed.yearValue) CX.setAsModified();
      this.DayField.value = ClickedDay;
      this.MonthField.value = this.displayed.monthIndex + 1;
      this.YearField.value = this.displayed.yearValue;
   }
}

/* Builds the HTML for the calendar days */
function BuildCalendarDays() {
   var dateCounter = 0;
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table cellspacing="1" cellpadding="0" style="cursor:default">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
	    if (this.pickableDates != '') {
	       calendarDate = printf('%d%02d%02d',this.displayed.yearValue, this.displayed.monthIndex +1, Day);
	       if (calendarDate == this.pickableDates[dateCounter]) {
	          dateCounter++;
		  TextStyle = 'color:black;border:1px solid darkred;padding:0px;';
		  BackColor = DayBGColor;
		  HTML += '<td align="middle" class="calendarDateInput" style="' + TextStyle + 'background-color:' + BackColor + ';cursor:pointer;height:' + CellHeight + ';width:' + CellWidth + ';' + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
	       } else {
	       	  TextStyle = 'color:black;';
	          BackColor = CalBGColor;
	          HTML += '<td align="middle" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '">' + Day + '</td>';
  	       }   
	    } else {
                  TextStyle = 'color:black;';
                  BackColor = CalBGColor;
               if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) { 
                  TextStyle += 'border:1px solid darkred;padding:0px;';
                  HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
	       } else {
                  HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
	       }
	    }
         } else { 
            HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
         }
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}

/* Determines which century to use (20th or 21st) when dealing with 2-digit years */
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

/* Returns the number of days in a month (handles leap-years) */
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

/* Highlights the buttons */
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}

/* Mouse-over for the previous/next month buttons */
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
   }
   return true;
}

/* Show the calendar */
function ShowCalendar() {
   // Before showing the calendar it is checked if there is enough space in the (horizontal) window area.
   // If not, the calendar position is moved a few pixels to the left.   
   calendarElement = this.getCalendar();
   rightPos = calendarElement.offsetLeft + CellWidth * 7;
   if (rightPos > (document.body.clientWidth + document.body.scrollLeft)) {
      shiftLeft = rightPos - (document.body.clientWidth + document.body.scrollLeft) + 10;
      calendarElement.style.left = calendarElement.offsetLeft - shiftLeft + "px";
   }
   if(!window.XMLHttpRequest) {
      useShim(this.getCalendar());
   }
   this.getCalendar().style.zIndex = ++ZCounter;
   this.getCalendar().style.visibility = 'visible';
   self.status = '';
}

/* Hide the calendar */
function HideCalendar() {
   if(!window.XMLHttpRequest && this.getCalendar().getAttribute('myshim')) {
      this.getCalendar().getAttribute('myshim').style.visibility = 'hidden';
   }
   this.getCalendar().style.zIndex = --ZCounter;
   this.getCalendar().style.visibility = 'hidden';
   self.status = '';
}

/* TODO move this to standard2.js */
function useShim (calendar) {
   if(!calendar.getAttribute('myshim')) {
      var shim = document.createElement('iframe');
      shim.setAttribute('src','about:blank')
      shim.style.position = "absolute";	
      shim.style.left = GetTagPixels(calendar, 'LEFT')+ "px";   
      shim.style.top = GetTagPixels(calendar, 'TOP') + "px";
      shim.style.width = calendar.clientWidth + 2;
      shim.style.height = calendar.clientHeight + 2;
      calendar.parentNode.appendChild(shim);
      calendar.setAttribute('myshim',shim);
   } else {
      shim = calendar.getAttribute('myshim');
      shim.style.visibility = "visible";
   }
}

/* Get absolute position of html tag */
/* TODO move this to standard2.js */
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

/* Used when document is clicked to hide all active calendars when not hovering above one */
function hideCalendars() {
   if(!onCalendar) {
	   for (i=0;i<calendars.length;i++) {
	      calendars[i].hide();
	   }
   }
}

/* Holds characteristics about a date */
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}

/* Keeps track of the date that goes into the hidden field */
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

/* Object for the current displayed month */
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.DateName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}

/* Object for the previous/next buttons */
function neighborMonthObject(ParentObject, IDText, DateMS) {
   (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.DateName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}

/* Sets the currently-displayed month object */
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}

/* Sets the current selected date */
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
   this.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}

/* The calendar object
 */
function calendarObject(DateName, DateFormat, DefaultDate, PickableDateList, OnDemand) {

   /* Properties */
   this.DateName = DateName;
   this.DayField = document.getElementById(DateName + ':d');
   this.MonthField = document.getElementById(DateName + ':M');
   this.YearField = document.getElementById(DateName + ':y');
   this.pickableDates = PickableDateList;
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.objName = 'Calendar_' + DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;
   this.ondemand = OnDemand;

   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.show = ShowCalendar;  
   this.hide = HideCalendar;  
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');

   // Returns a reference to these elements
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
   this.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());

   // Add this calendar to list of objects to be hidden onclick
   if (OnDemand) {
      calendars.push(this);
      // Please note that the onclick handler may conflict with other attached events in its current implementation
      document.onclick = hideCalendars;
   }
}

/* Main function that creates the calendar 
   @params
   DateName = The date field name
   OnDemand: Wether calendar needs to be selected by the user or is always shown or not. (Not working yet...)
   PickableDateList: A lis of dates in YYYYMMDD format that can be selected by the user. Need to be in ascending order!
   DefaultDate: Not used
 */
function DateInput(DateName, OnDemand, PickableDateList, DefaultDate) {
	var DateFormat = DefaultDateFormat;
	// Define the current date if it wasn't set already
	if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());	
	// Creates the calendar object!
	if (PickableDateList != 'undefined') {
		PickableDateList = ',[' + PickableDateList + ']';
	}

	eval('Calendar_' + DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\'' + PickableDateList + ',' + OnDemand + ')');

	var InitialStatus = '';
	var InitialDate = eval('Calendar_' + DateName + '_Object.picked.formatted');
		// TODO Remove the hidden field and use a variable instead. It causes no problem but it should not be present in the engine search form.
      	// Create the hidden form element
      	with (document) {
		//writeln('<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">');
		eval('Calendar_' + DateName + '_Object.formNumber='+0);	
		/*
		// Find this form number
		for (var f=0;f<forms.length;f++) {
		   for (var e=0;e<forms[f].elements.length;e++) {
		      if (typeof forms[f].elements[e].type == 'string') {
			  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
			     eval('Calendar_' + DateName + '_Object.formNumber='+f);
			     break;
			  }
		       }
		    }
		 }
		*/
		if(OnDemand) {
			writeln('<span id="' + DateName + '_ID" style="position:absolute;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;" onMouseOver="onCalendar=true" onMouseOut="onCalendar=false">');
		} else {
			writeln('<span style="border:1px solid dimgray;display:block;width:' + (CellWidth*7) + 'px;">');
		}
		writeln('<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
		writeln('<td id="' + DateName + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="Calendar_' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return Calendar_' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return Calendar_' + DateName + '_Object.previous.hover(this,false)" title="' + eval('Calendar_' +DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '"></td>');
		writeln('<td id="' + DateName + '_Current_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" colspan="5" onClick="Calendar_' + DateName + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + CurrentDate.fullName + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month">' + eval('Calendar_' + DateName + '_Object.displayed.fullName') + '</td>');
		writeln('<td id="' + DateName + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="Calendar_' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return Calendar_' + DateName + '_Object.next.hover(this,true)" onMouseOut="return Calendar_' + DateName + '_Object.next.hover(this,false)" title="' + eval('Calendar_' + DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>');
		for (var w=0;w<7;w++) writeln('<td width="' + CellWidth + '" align="center" class="calendarDateInput" style="height:' + CellHeight + ';width:' + CellWidth + ';font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;">' + WeekDays[w] + '</td>');
		writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval('Calendar_' + DateName + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>' + String.fromCharCode(13)); 
	      	}
	if (!OnDemand) {
		document.writeln('<input type="hidden" name="' + DateName + ':d' + '">');
		document.writeln('<input type="hidden" name="' + DateName + ':M' + '">');
		document.writeln('<input type="hidden" name="' + DateName + ':y' + '">');
	}
}

/* Function printf(format_string,arguments...)
 * Javascript emulation of the C printf function (modifiers and argument types 
 *    "p" and "n" are not supported due to language restrictions)
 *
 * Copyright 2003 K&L Productions. All rights reserved
 * http://www.klproductions.com 
 *
 * Terms of use: This function can be used free of charge IF this header is not
 *               modified and remains with the function code.
 * 
 * Legal: Use this code at your own risk. K&L Productions assumes NO resposibility
 *        for anything.
 ********************************************************************************/
function printf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
/* Function printf() END */

