if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    };

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapeable.lastIndex = 0;
        return escapeable.test(string) ?
            '"' + string.replace(escapeable, function (a) {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    };


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// If the object has a dontEnum length property, we'll treat it as an array.

            if (typeof value.length === 'number' &&
                    !value.propertyIsEnumerable('length')) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
})();



/*
 * $Id: xbMarquee.js,v 1.21 2003/09/14 21:22:26 bc Exp $
 *
 */

/* ***** BEGIN LICENSE BLOCK *****
 * The contents of this file are subject to the Mozilla Public License Version 
 * 1.1 (the "License"); you may not use this file except in compliance with 
 * the License. You may obtain a copy of the License at 
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Netscape code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2002
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Doron Rosenberg <doron@netscape.com>
 *                 Bob Clary <bclary@netscape.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 ***** END LICENSE BLOCK ***** */
 
 
 
function xbMarquee(id, height, width, scrollAmount, scrollDelay, direction, behavior, html,scollerConWidth)
{ //* One parameter added 'scollerConWidth' for fixed srcoller width if our function get Failed to calculate it width
  this.id            = id;
  this.scrollAmount  = scrollAmount ? scrollAmount : 6;
  this.scrollDelay   = scrollDelay ? scrollDelay : 85;
  this.direction     = direction ? direction.toLowerCase() : 'left';  
  this.behavior      = behavior ? behavior.toLowerCase() : 'scroll';  
  this.name          = 'xbMarquee_' + (++xbMarquee._name);
  this.runId         = null;
  this.html          = html;
  this.html2          = html;
  this.isHorizontal = ('up,down'.indexOf(this.direction) == -1);
  this.scollerConWidth=scollerConWidth;
  this.firstTime=true; 
  if (typeof(height) == 'number')
  {
    this.height = height;
    this.heightUnit = 'px';
  }
  else if (typeof(height) == 'string')
  {
    this.height = parseInt('0' + height, 10);
    this.heightUnit = height.toLowerCase().replace(/^[0-9]+/, '');
  }
  else
  {
    this.height = 100;
    this.heightUnit = 'px';
  }

  if (typeof(width) == 'number')
  {
    this.width = width;
    this.widthUnit = 'px';
  }
  else if (typeof(width) == 'string')
  {
    this.width = parseInt('0' + width, 10);
    this.widthUnit = width.toLowerCase().replace(/^[0-9]+/, '');
  }
  else
  {
    this.width = 100;
    this.widthUnit = 'px';
  }

  // xbMarquee UI events
  this.onmouseover   = null;
  this.onmouseout    = null;
  this.onclick       = null;
  // xbMarquee state events
  this.onstart       = null;
  this.onbounce      = null;

  var markup = '';

  if (document.layers)
  {
    markup = '<ilayer id="' + this.id + 'container" name="' + this.id + 'container" ' +
             'height="' + height + '" ' +
             'width="' + width + '"  ' +
             'clip="' + width + ', ' + height + '" ' +
             '>' + 
             '<\/ilayer>';
			
  }
  else if (document.body && typeof(document.body.innerHTML) != 'string')
  {
    markup = '<div id="' + this.id + 'container" name="' + this.id + 'container" ' +
             'style="position: relative; overflow: scroll; ' + 
             'height: ' + this.height + this.heightUnit + '; ' +
             'width: ' + this.width + this.widthUnit + '; ' +
             'clip: rect(0px, ' + this.width + this.widthUnit + ', ' + this.height + this.heightUnit + ', 0px); ' +
             '">' + 
             '<div id="' + this.id + '" style="position:relative;' + 
             (this.isHorizontal ? 'width:0px;' : '') + // if we scroll horizontally, make the text container as small as possible
             '">' +
             (this.isHorizontal ? '<nobr>' : '') +
             this.html +
             (this.isHorizontal ? '<\/nobr>' : '') +
             '<\/div>' +
             '<\/div>';
			 
  }
  else 
  {
    markup = '<div id="' + this.id + 'container" name="' + 
             this.id + 'container" ' +
             'style="position: relative; overflow: hidden; ' + 
             'height: ' + this.height + this.heightUnit + '; ' +
             'width: ' + this.width + this.widthUnit + '; ' +
             'clip: rect(0px, ' + this.width + this.widthUnit + ', ' + this.height + this.heightUnit + ', 0px); ' +
             '">' + 
             '<\/div>';
			   
  }
 document.write(markup);

  window[this.name] = this;
 
}
 // Class Properties/Methods

xbMarquee._name = -1;

xbMarquee._getInnerSize = function(elm, propName)
{
  var val = 0;

  if (document.layers)
  {
    // navigator 4
    val = elm.document[propName];
	
  }
  else if (elm.style && typeof(elm.style[propName]) == 'number')
  {
    // opera
    // bug in Opera 6 width/offsetWidth. Use clientWidth
    if (propName == 'width' && typeof(elm.clientWidth) == 'number')
    {  val = elm.clientWidth;  
	}
       else
      {val =  elm.style[propName];}
	 // widthfac2=Math.floor(val/widthfac);
	 
  }
  else
  {
    //mozilla and IE
    switch (propName)
    {
    case 'height':
       if (typeof(elm.offsetHeight) == 'number')
            val =  elm.offsetHeight;
       break;
    case 'width':
       if (typeof(elm.offsetWidth) == 'number')
	    { val = elm.offsetWidth;
	      
		 // THIS [elm.offsetWidth] IS NOT WORKING IN FIRE FOX WHICH IS USED TO CALCULATE ACTUAL WITH OF SCROLLER
		  // WHILE IN IE IT IS WORKING 
       break;
    }
  }
  containerWidth=val;
  window.status=containerWidth;//Tracing  of Container With which i can see on IE
   
  }
  return val;

};

xbMarquee.getElm = function(id)
{
  var elm = null;
  if (document.getElementById)
  {
    elm = document.getElementById(id);
  }
  else
  {
    elm = document.all[id];
  }
  return elm;
}

xbMarquee.dispatchUIEvent = function (event, marqueeName, eventName)
{
  var marquee = window[marqueeName];
  var eventAttr = 'on' + eventName;
  if (!marquee)
  {
    return false;
  }

  if (!event && window.event)
  {
    event = window.event;
  }

  switch (eventName)
  {
  case 'mouseover':
  case 'mouseout':
  case 'click':
    if (marquee[eventAttr])
      return marquee['on' + eventName](event);
  }

  return false;
};

xbMarquee.createDispatchEventAttr = function (marqueeName, eventName)
{
  return 'on' + eventName + '="xbMarquee.dispatchUIEvent(event, \'' + marqueeName + '\', \'' + eventName + '\')" ';
};

// Instance properties/methods

xbMarquee.prototype.start = function ()
{
  var markup = '';
 
  this.stop();

  if (!this.dirsign)
  {
    if (!document.layers)
    {
      this.containerDiv = xbMarquee.getElm(this.id + 'container');

      if (typeof(this.containerDiv.innerHTML) != 'string')
      {
        return;
      }

      // adjust the container size before inner div is filled in
      // so IE will not hork the size of percentage units 
      var parentNode    = null;
      if (this.containerDiv.parentNode)
        parentNode = this.containerDiv.parentNode;
      else if (this.containerDiv.parentElement)
        parentNode = this.containerDiv.parentElement;
		
		

      if (parentNode && typeof(parentNode.offsetHeight) == 'number' && 
          typeof(parentNode.offsetWidth) == 'number')
       {
        if (this.heightUnit == '%')
        {
          this.containerDiv.style.height =  parentNode.offsetHeight * (this.height/100) + 'px';
        }

        if (this.widthUnit == '%')
        {
          this.containerDiv.style.width = 
          parentNode.offsetWidth * (this.width/100) + 'px';
		  
        }
      }

      markup += '<div id="' + this.id + '" name="' + this.id + '" ' +
        'style="position:relative; visibility: hidden;' +
        (this.isHorizontal ? 'width:0px;' : '') + // if we scroll horizontally, make the text container as small as possible
        '" ' +
        xbMarquee.createDispatchEventAttr(this.name, 'mouseover') +
        xbMarquee.createDispatchEventAttr(this.name, 'mouseout') +
        xbMarquee.createDispatchEventAttr(this.name, 'click') +
        '>' +
        (this.isHorizontal ? '<nobr>' : '') +
        this.html +
        (this.isHorizontal ? '<\/nobr>' : '') +
        '<\/div>';

 
		
      this.containerDiv.innerHTML = markup;
	  this.div                    = xbMarquee.getElm(this.id);
      this.styleObj     = this.div.style;
	  
    }
    else /* if (document.layers) */
    {
      this.containerDiv = document.layers[this.id + 'container'];
      markup = 
        '<layer id="' + this.id + '" name="' + this.id + '" top="0" left="0" ' +
        xbMarquee.createDispatchEventAttr(this.name, 'mouseover') +
        xbMarquee.createDispatchEventAttr(this.name, 'mouseout') +
        xbMarquee.createDispatchEventAttr(this.name, 'click') +
        '>' +
        (this.isHorizontal ? '<nobr>' : '') + 
        this.html +
        (this.isHorizontal ? '<\/nobr>' : '') +
        '<\/layer>';
		

      this.containerDiv.document.write(markup);
      this.containerDiv.document.close();
      this.div          = this.containerDiv.document.layers[this.id];
      this.styleObj     = this.div;
	  
    }

    // Start must not run until the page load event has fired
    // due to Internet Explorer not setting the height and width of 
    // the dynamically written content until then
    switch (this.direction)
    {
    case 'down':
      this.dirsign = 1;
      this.startAt = -xbMarquee._getInnerSize(this.div, 'height');
      this._setTop(this.startAt);

      if (this.heightUnit == '%')
        this.stopAt = this.height * xbMarquee._getInnerSize(this.containerDiv, 'height') / 100;
      else
        this.stopAt  = this.height;

      break;

    case 'up':
      this.dirsign = -1;

      if (this.heightUnit == '%')
        this.startAt = this.height * xbMarquee._getInnerSize(this.containerDiv, 'height') / 100;
      else     
        this.startAt = 0;

      this._setTop(this.startAt);
      this.stopAt  = -xbMarquee._getInnerSize(this.div, 'height');

      break;

    case 'right':
      this.dirsign = 1;
      this.startAt = -xbMarquee._getInnerSize(this.div, 'width');
      this._setLeft(this.startAt);

      if (this.widthUnit == '%')
        this.stopAt = this.width * xbMarquee._getInnerSize(this.containerDiv, 'width') / 100;
      else    
        this.stopAt  = this.width;

      break;

    case 'left':
    default:
      this.dirsign = -1;

      if (this.widthUnit == '%')
        this.startAt = this.width * xbMarquee._getInnerSize(this.containerDiv, 'width') / 100;
      else   
	 this.startAt =0; 

      this._setLeft(this.startAt);
      this.stopAt  = -xbMarquee._getInnerSize(this.div,'width');

      break;
    }
    this.newPosition          = this.startAt;
    this.styleObj.visibility = 'visible'; 
  }

  this.newPosition += this.dirsign * this.scrollAmount;

  if ( (this.dirsign == 1  && this.newPosition > this.stopAt) ||
       (this.dirsign == -1 && this.newPosition < this.stopAt) )
  {
    if (this.behavior == 'alternate')
    {
      if (this.onbounce)
      {
        // fire bounce when alternate changes directions
        this.onbounce();
      }
      this.dirsign = -this.dirsign;
      var temp     = this.stopAt;
      this.stopAt  = this.startAt;
      this.startAt = temp;
    }
    else
    {
      // fire start when position is a start
      if (this.onstart)
      {
        this.onstart();
		
      }
	  
       
    }
  }
  
  switch(this.direction)
  {
    case 'up': 
    case 'down':
	 restartPos= Math.abs(this.newPosition) ;
	 containerWidth=xbMarquee._getInnerSize(this.div, 'height');		
         if(restartPos>containerWidth-this.height) // if(restartPos>=containerWidth-this.height)
		 {
		   newRePos=this.newPosition=0;
		   this._setTop(newRePos);
		 }
		 else
		  {
			  newRePos=this.newPosition;
			 this._setTop(newRePos);
		  }
 	          
      break;

    case 'left': 
    case 'right':
	restartPos=Math.abs(this.newPosition);
	  
	 
	 // if(restartPos>=containerWidth-this.width+this.scrollAmount) THIS SHOULD BE CONDITION FOR SCROLLER 
	 // BUT containerWidth IS NOT CALCULATION PROPERLY IN FIREFOX DUE TO  val = elm.offsetWidth; STATEMENT NOT
	 // SUPPORT BY FIREFOX SO I HAVE FIX CONATINER WITH HERE 
	 // AND IN IE IT IS WORKING FINE
	 containerWidth=containerWidth<=0?(this.scollerConWidth!=''?this.scollerConWidth:0):containerWidth;
	
	//* This is use for checked if  val = elm.offsetWidth;  is FAIL to calculate scroller Width
	 //* Then function parameter  'srcr' have defined containter value will be containerWidth
	 
	 
	 
		if(restartPos>=containerWidth-this.width+this.scrollAmount) // if(restartPos>=containerWidth-this.width+this.scrollAmount)
		 {
		  newRePos=this.newPosition=0;
		  this.firstTime=false;
		 }
		else
		  {
			  newRePos=this.newPosition;
			  this._setLeft(newRePos);
		  }
		  break;
    default:
	 this._setLeft(this.newPosition);
	
	 
	 
	   
      break;
  }

  this.runId = setTimeout(this.name + '.start()', this.scrollDelay);
};

xbMarquee.prototype.stop = function ()
{
  if (this.runId)
    clearTimeout(this.runId); 
  this.runId = null;
};

xbMarquee.prototype.setInnerHTML = function (html)
{//alert(html.length);
  if (typeof(this.div.innerHTML) != 'string')
  {
    return;
  }

  var running = false;
  if (this.runId)
  {
    running = true;
    this.stop();
	 
  }
  this.html = html;
  this.dirsign = null;
  if (running)
  {
    this.start();
	
  }
};

// fixes standards mode in gecko
// since units are required

if (document.layers)
{
  xbMarquee.prototype._setLeft = function (left)
  {
    this.styleObj.left = left;
	//alert(this.styleObj.left);
  };

  xbMarquee.prototype._setTop = function (top)
  {
    this.styleObj.top = top;
  };
}
else
{
  xbMarquee.prototype._setLeft = function (left)
  {  
	   
     this.styleObj.left = left+  'px';
	 
  };

  xbMarquee.prototype._setTop = function (top)
  {
    this.styleObj.top = top + 'px';
  };
}


// XMLHttpRequest.js Copyright (C) 2010 Sergey Ilinsky (http://www.ilinsky.com)
//
// This work is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.

// This work is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of
// merchantability or fitness for a particular purpose. See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

(function () {

	// Save reference to earlier defined object implementation (if any)
	var oXMLHttpRequest	= window.XMLHttpRequest;

	// Define on browser type
	var bGecko	= !!window.controllers,
		bIE		= window.document.all && !window.opera,
		bIE7	= bIE && window.navigator.userAgent.match(/MSIE ([\.0-9]+)/) && RegExp.$1 == 7;

	// Constructor
	function cXMLHttpRequest() {
		this._object	= oXMLHttpRequest && !bIE7 ? new oXMLHttpRequest : new window.ActiveXObject("Microsoft.XMLHTTP");
		this._listeners	= [];
	};

	// BUGFIX: Firefox with Firebug installed would break pages if not executed
	if (bGecko && oXMLHttpRequest.wrapped)
		cXMLHttpRequest.wrapped	= oXMLHttpRequest.wrapped;

	// Constants
	cXMLHttpRequest.UNSENT				= 0;
	cXMLHttpRequest.OPENED				= 1;
	cXMLHttpRequest.HEADERS_RECEIVED	= 2;
	cXMLHttpRequest.LOADING				= 3;
	cXMLHttpRequest.DONE				= 4;

	// Public Properties
	cXMLHttpRequest.prototype.readyState	= cXMLHttpRequest.UNSENT;
	cXMLHttpRequest.prototype.responseText	= '';
	cXMLHttpRequest.prototype.responseXML	= null;
	cXMLHttpRequest.prototype.status		= 0;
	cXMLHttpRequest.prototype.statusText	= '';

	// Instance-level Events Handlers
	cXMLHttpRequest.prototype.onreadystatechange	= null;

	// Class-level Events Handlers
	cXMLHttpRequest.onreadystatechange	= null;
	cXMLHttpRequest.onopen				= null;
	cXMLHttpRequest.onsend				= null;
	cXMLHttpRequest.onabort				= null;

	// Public Methods
	cXMLHttpRequest.prototype.open	= function(sMethod, sUrl, bAsync, sUser, sPassword) {
		// Delete headers, required when object is reused
		delete this._headers;

		// When bAsync parameter value is omitted, use true as default
		if (arguments.length < 3)
			bAsync	= true;

		// Save async parameter for fixing Gecko bug with missing readystatechange in synchronous requests
		this._async		= bAsync;

		// Set the onreadystatechange handler
		var oRequest	= this,
			nState		= this.readyState,
			fOnUnload;

		// BUGFIX: IE - memory leak on page unload (inter-page leak)
		if (bIE && bAsync) {
			fOnUnload = function() {
				if (nState != cXMLHttpRequest.DONE) {
					fCleanTransport(oRequest);
					// Safe to abort here since onreadystatechange handler removed
					oRequest.abort();
				}
			};
			window.attachEvent("onunload", fOnUnload);
		}

		// Add method sniffer
		if (cXMLHttpRequest.onopen)
			cXMLHttpRequest.onopen.apply(this, arguments);

		if (arguments.length > 4)
			this._object.open(sMethod, sUrl, bAsync, sUser, sPassword);
		else
		if (arguments.length > 3)
			this._object.open(sMethod, sUrl, bAsync, sUser);
		else
			this._object.open(sMethod, sUrl, bAsync);

		if (!bGecko && !bIE) {
			this.readyState	= cXMLHttpRequest.OPENED;
			fReadyStateChange(this);
		}

		this._object.onreadystatechange	= function() {
			if (bGecko && !bAsync)
				return;

			// Synchronize state
			oRequest.readyState		= oRequest._object.readyState;

			//
			fSynchronizeValues(oRequest);

			// BUGFIX: Firefox fires unnecessary DONE when aborting
			if (oRequest._aborted) {
				// Reset readyState to UNSENT
				oRequest.readyState	= cXMLHttpRequest.UNSENT;

				// Return now
				return;
			}

			if (oRequest.readyState == cXMLHttpRequest.DONE) {
				//
				fCleanTransport(oRequest);
// Uncomment this block if you need a fix for IE cache
/*
				// BUGFIX: IE - cache issue
				if (!oRequest._object.getResponseHeader("Date")) {
					// Save object to cache
					oRequest._cached	= oRequest._object;

					// Instantiate a new transport object
					cXMLHttpRequest.call(oRequest);

					// Re-send request
					if (sUser) {
					 	if (sPassword)
							oRequest._object.open(sMethod, sUrl, bAsync, sUser, sPassword);
						else
							oRequest._object.open(sMethod, sUrl, bAsync, sUser);
					}
					else
						oRequest._object.open(sMethod, sUrl, bAsync);
					oRequest._object.setRequestHeader("If-Modified-Since", oRequest._cached.getResponseHeader("Last-Modified") || new window.Date(0));
					// Copy headers set
					if (oRequest._headers)
						for (var sHeader in oRequest._headers)
							if (typeof oRequest._headers[sHeader] == "string")	// Some frameworks prototype objects with functions
								oRequest._object.setRequestHeader(sHeader, oRequest._headers[sHeader]);

					oRequest._object.onreadystatechange	= function() {
						// Synchronize state
						oRequest.readyState		= oRequest._object.readyState;

						if (oRequest._aborted) {
							//
							oRequest.readyState	= cXMLHttpRequest.UNSENT;

							// Return
							return;
						}

						if (oRequest.readyState == cXMLHttpRequest.DONE) {
							// Clean Object
							fCleanTransport(oRequest);

							// get cached request
							if (oRequest.status == 304)
								oRequest._object	= oRequest._cached;

							//
							delete oRequest._cached;

							//
							fSynchronizeValues(oRequest);

							//
							fReadyStateChange(oRequest);

							// BUGFIX: IE - memory leak in interrupted
							if (bIE && bAsync)
								window.detachEvent("onunload", fOnUnload);
						}
					};
					oRequest._object.send(null);

					// Return now - wait until re-sent request is finished
					return;
				};
*/
				// BUGFIX: IE - memory leak in interrupted
				if (bIE && bAsync)
					window.detachEvent("onunload", fOnUnload);
			}

			// BUGFIX: Some browsers (Internet Explorer, Gecko) fire OPEN readystate twice
			if (nState != oRequest.readyState)
				fReadyStateChange(oRequest);

			nState	= oRequest.readyState;
		}
	};
	cXMLHttpRequest.prototype.send	= function(vData) {
		// Add method sniffer
		if (cXMLHttpRequest.onsend)
			cXMLHttpRequest.onsend.apply(this, arguments);

		// BUGFIX: Safari - fails sending documents created/modified dynamically, so an explicit serialization required
		// BUGFIX: IE - rewrites any custom mime-type to "text/xml" in case an XMLNode is sent
		// BUGFIX: Gecko - fails sending Element (this is up to the implementation either to standard)
		if (vData && vData.nodeType) {
			vData	= window.XMLSerializer ? new window.XMLSerializer().serializeToString(vData) : vData.xml;
			if (!this._headers["Content-Type"])
				this._object.setRequestHeader("Content-Type", "application/xml");
		}

		this._object.send(vData);

		// BUGFIX: Gecko - missing readystatechange calls in synchronous requests
		if (bGecko && !this._async) {
			this.readyState	= cXMLHttpRequest.OPENED;

			// Synchronize state
			fSynchronizeValues(this);

			// Simulate missing states
			while (this.readyState < cXMLHttpRequest.DONE) {
				this.readyState++;
				fReadyStateChange(this);
				// Check if we are aborted
				if (this._aborted)
					return;
			}
		}
	};
	cXMLHttpRequest.prototype.abort	= function() {
		// Add method sniffer
		if (cXMLHttpRequest.onabort)
			cXMLHttpRequest.onabort.apply(this, arguments);

		// BUGFIX: Gecko - unnecessary DONE when aborting
		if (this.readyState > cXMLHttpRequest.UNSENT)
			this._aborted	= true;

		this._object.abort();

		// BUGFIX: IE - memory leak
		fCleanTransport(this);
	};
	cXMLHttpRequest.prototype.getAllResponseHeaders	= function() {
		return this._object.getAllResponseHeaders();
	};
	cXMLHttpRequest.prototype.getResponseHeader	= function(sName) {
		return this._object.getResponseHeader(sName);
	};
	cXMLHttpRequest.prototype.setRequestHeader	= function(sName, sValue) {
		// BUGFIX: IE - cache issue
		if (!this._headers)
			this._headers	= {};
		this._headers[sName]	= sValue;

		return this._object.setRequestHeader(sName, sValue);
	};

	// EventTarget interface implementation
	cXMLHttpRequest.prototype.addEventListener	= function(sName, fHandler, bUseCapture) {
		for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++)
			if (oListener[0] == sName && oListener[1] == fHandler && oListener[2] == bUseCapture)
				return;
		// Add listener
		this._listeners.push([sName, fHandler, bUseCapture]);
	};

	cXMLHttpRequest.prototype.removeEventListener	= function(sName, fHandler, bUseCapture) {
		for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++)
			if (oListener[0] == sName && oListener[1] == fHandler && oListener[2] == bUseCapture)
				break;
		// Remove listener
		if (oListener)
			this._listeners.splice(nIndex, 1);
	};

	cXMLHttpRequest.prototype.dispatchEvent	= function(oEvent) {
		var oEventPseudo	= {
			'type':			oEvent.type,
			'target':		this,
			'currentTarget':this,
			'eventPhase':	2,
			'bubbles':		oEvent.bubbles,
			'cancelable':	oEvent.cancelable,
			'timeStamp':	oEvent.timeStamp,
			'stopPropagation':	function() {},	// There is no flow
			'preventDefault':	function() {},	// There is no default action
			'initEvent':		function() {}	// Original event object should be initialized
		};

		// Execute onreadystatechange
		if (oEventPseudo.type == "readystatechange" && this.onreadystatechange)
			(this.onreadystatechange.handleEvent || this.onreadystatechange).apply(this, [oEventPseudo]);

		// Execute listeners
		for (var nIndex = 0, oListener; oListener = this._listeners[nIndex]; nIndex++)
			if (oListener[0] == oEventPseudo.type && !oListener[2])
				(oListener[1].handleEvent || oListener[1]).apply(this, [oEventPseudo]);
	};

	//
	cXMLHttpRequest.prototype.toString	= function() {
		return '[' + "object" + ' ' + "XMLHttpRequest" + ']';
	};

	cXMLHttpRequest.toString	= function() {
		return '[' + "XMLHttpRequest" + ']';
	};

	// Helper function
	function fReadyStateChange(oRequest) {
		// Sniffing code
		if (cXMLHttpRequest.onreadystatechange)
			cXMLHttpRequest.onreadystatechange.apply(oRequest);

		// Fake event
		oRequest.dispatchEvent({
			'type':			"readystatechange",
			'bubbles':		false,
			'cancelable':	false,
			'timeStamp':	new Date + 0
		});
	};

	function fGetDocument(oRequest) {
		var oDocument	= oRequest.responseXML,
			sResponse	= oRequest.responseText;
		// Try parsing responseText
		if (bIE && sResponse && oDocument && !oDocument.documentElement && oRequest.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/)) {
			oDocument	= new window.ActiveXObject("Microsoft.XMLDOM");
			oDocument.async				= false;
			oDocument.validateOnParse	= false;
			oDocument.loadXML(sResponse);
		}
		// Check if there is no error in document
		if (oDocument)
			if ((bIE && oDocument.parseError != 0) || !oDocument.documentElement || (oDocument.documentElement && oDocument.documentElement.tagName == "parsererror"))
				return null;
		return oDocument;
	};

	function fSynchronizeValues(oRequest) {
		try {	oRequest.responseText	= oRequest._object.responseText;	} catch (e) {}
		try {	oRequest.responseXML	= fGetDocument(oRequest._object);	} catch (e) {}
		try {	oRequest.status			= oRequest._object.status;			} catch (e) {}
		try {	oRequest.statusText		= oRequest._object.statusText;		} catch (e) {}
	};

	function fCleanTransport(oRequest) {
		// BUGFIX: IE - memory leak (on-page leak)
		oRequest._object.onreadystatechange	= new window.Function;
	};

	// Internet Explorer 5.0 (missing apply)
	if (!window.Function.prototype.apply) {
		window.Function.prototype.apply	= function(oRequest, oArguments) {
			if (!oArguments)
				oArguments	= [];
			oRequest.__func	= this;
			oRequest.__func(oArguments[0], oArguments[1], oArguments[2], oArguments[3], oArguments[4]);
			delete oRequest.__func;
		};
	};

	// Register new object with window
	window.XMLHttpRequest	= cXMLHttpRequest;
})();/* CLASS Element */

function Element()  {
    this.display_name =  function(x) { /* a helper function */
        var tokens = x.split('.');
        var fname = tokens.pop();
        fname = fname.replace(/_id/, '');
        return fname;
    };
    
    this.createEventListener = function ( target, eventName, handlerFunc, captureFlag /*bool*/) {
        var context = this;
        var funcWrapper =   function(e) {
                                    var retval = false;
                                    try {
                                        retval = handlerFunc.call(context, e, this);
                                    } catch (ex) {
                                        Ngx.Odb.Form.firstMessage("caught exception in event handler wrapper");
                                    }
                                    return retval;
                                };
        if(Ngx.Odb.CommonUtil.Nav.appName=="Microsoft Internet Explorer"){
            eventName == 'keydown' ? eventName = 'onkeydown' : null;
            target.attachEvent(eventName, funcWrapper);
        }
        else {
            eventName = eventName.replace("on","");
            target.addEventListener(eventName, funcWrapper, captureFlag);
        }
        return funcWrapper; /* callers must return this on deleteEvent calls ! */
    };

    this.deleteEventListener = function ( target, eventName, funcWrapper, captureFlag /*bool*/) {
        if(Ngx.Odb.CommonUtil.Nav.appName=="Microsoft Internet Explorer"){
            target.detachEvent(eventName, funcWrapper);
        }
        else {
            eventName = eventName.replace("on","");
            target.removeEventListener(eventName, funcWrapper, captureFlag);
        }
    };
}


function CommonUtil() {

    // CONSTRUCTOR CommonUtil
    this.Nav= {};
             
    this.initNavigator = function() {
        this.Nav.appCodeName = navigator.appCodeName;
        this.Nav.appMinorVersion = navigator.appMinorVersion;
        this.Nav.appName = navigator.appName;
        this.Nav.appVersion = navigator.appVersion;
        this.Nav.cookieEnabled = navigator.cookieEnabled;
        this.Nav.cpuClass = navigator.cpuClass;
        this.Nav.onLine = navigator.onLine;
        this.Nav.platform = navigator.platform;
        this.Nav.userAgent = navigator.userAgent;
        this.Nav.browserLanguage = navigator.browserLanguage;
        this.Nav.systemLanguage = navigator.systemLanguage;
        this.Nav.userLanguage = navigator.userLanguage;
    };

    this.initialize = function() { 
        this.initNavigator();
    };    

    this.toggleExpandCollapse = function(x,y) {
        var objSpan = document.getElementById(x);
        var objImage = document.getElementById(y);

        if (objSpan.style.display == "none") {
           objSpan.style.display = "";
           objImage.src = "themes/en/default/images/expand_minus.gif";
        }
        else {
           objSpan.style.display = "none";
           objImage.src = "themes/en/default/images/expand_plus.gif";
        }
    }

    this.addMarquee  = function (id, height, width, delta, interval, direction,scrollConWidth) {
         height = height || 200;
         width = width || 100;
         delta = delta || 3; //pixels
         interval = interval || 100; //milliseconds
         direction = direction || 'up';
         scrollConWidth=scrollConWidth || '';

         var node = document.getElementById(id);
         var content = node.innerHTML;

         // removing inner div
         node.parentNode.removeChild(node);

         // creating marquee object
         var marqueeId ='marquee'+id;
         var marquee = new xbMarquee(marqueeId, height, width, delta, interval, direction, 'scroll', content,scrollConWidth);
         marquee.onmouseover = function() { marquee.stop();};
         marquee.onmouseover = function() { marquee.stop();};
         marquee.onmouseout = function() { marquee.start(); };

         // adding marquee in form
         document.addOnLoadFunction(function() {marquee.start();});
    }

    this.openWindow = function (url,name,wd,ht) {
        var params="menubar=no, location=no, status=no, directories=no, toolbar=no, scrollbars=yes, resizable=yes, alwaysraised=yes, ";
        params = params + " left=10, top=10 ";
         if (wd) {
               params = params + ', width=' + wd;
         }
         if (ht) {
               params = params + ', height=' + ht;
         }
         window.open(url, name, params);
    }

    // ajax support,
    // req = json hash with essential parameters (uri, params, method)
    // callback = function to be called on sucessful operations

    this.sendAjaxRequest = function (req , callback) {
        var xhr = new XMLHttpRequest();
        var onStateChange = function() {
            if (xhr.readyState == 4) {  // 4 means operation complete
               // if (xhr.status < 200 || xhr.status >= 300) {   
               //     Ngx.Odb.Util.assert(false, "HTTP status code = " + xhr.status);
               // }
               callback.call(null, xhr);
           }
        };

        var xparams = 't=' + Math.random();
        for(var p in req.params) {
            xparams = xparams + '&' + p + '=' + req.params[p];
        }   

        if (req.method == 'GET') {
           xhr.open('GET', req.uri + '?' + xparams, req.async);
           xhr.onreadystatechange = onStateChange;
           if (document.cookie != null) {
              xhr.setRequestHeader("X-Cookie",document.cookie);
           }
           xhr.send(null);
        } 
        else if (req.method == 'POST') {
           xhr.open('POST', req.uri, req.async);
           xhr.onreadystatechange = onStateChange;
           xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
           if (document.cookie != null) {
              xhr.setRequestHeader("X-Cookie",document.cookie);
           }
           xhr.send(xparams);
        }

    };

     // call back sanity
    this.createCallback = function(func, returnObj) { 
        var context = this;
        var result;
        var funcWrapper =  function() { 
                                var args = [];
                                for (var i=0; i<arguments.length; i++) { 
                                    args.push(arguments[i]);
                                }
                                if (returnObj) { 
                                    args.push(returnObj);
                                }
                                try {
                                    result = func.apply(context, args);   // params is an array [x,y,z] 
                                }
                                catch (ex) {
                                    //Ngx.Odb.Util.logException(ex, "caught exception in callback");
                                }
                                return result;
                            };
        return funcWrapper;
    };


    this.getUri = function() {
        var href = location.href;
        var href_arr = href.split('?');
        var uri = href_arr[0];
        return uri;
    }

    this.getNormalizedUri = function(uri) {
        if (uri == '') {
           return uri;
        }
        if (uri.indexOf("?")==1) {
             uri = this.getUri() + uri; 
        }
        return uri;
    }


    // this function create an Array that contains the JS code of every <script> tag in parameter
    // then apply the eval() to execute the code in every script collected
    this.executeScript = function(wnd, strcode) {
       if (typeof (wnd) == undefined ) {
           alert("window object undefined");
           return;
       }

       if (typeof (strcode) == undefined || strcode == '') {
           return;
       }

       var scripts = new Array();         // Array which will store the script's code
  
       // Strip out tags
       while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
         var s = strcode.indexOf("<script");
         var s_e = strcode.indexOf(">", s);
         var e = strcode.indexOf("</script", s);
         var e_e = strcode.indexOf(">", e);
    
         // Add to scripts array
         scripts.push(strcode.substring(s_e+1, e));
         // Strip from strcode
         strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
       }
  
       // Loop through every script collected and eval it
      for(var i=0; i<scripts.length; i++) {

          var script = wnd.document.createElement("script");
          script.type = "text/javascript";
          script.text = scripts[i];
         try {
            wnd.document.body.appendChild(script);

            // protect from duplicate insertion of script
            wnd.document.body.removeChild(wnd.document.body.lastChild);
         }
         catch(ex) {
            // do what you want here when a script fails
         }
      }
    }


    // function url like 'http://ww.xyz.com/?p1=v1&p2=v2&p3=v3
    // however i am hard coding it to send request to current domain only

    this.loadInlineForm = function (wnd, container_id,url) {
             if (typeof (wnd) == undefined ) {
                 alert("window object undefined");
                 return;
             }

             if (typeof (container_id) == undefined || container_id == '') {
                 return;
             }

             if (typeof (url) == undefined || url == '') {
                 return;
             }

             var url_arr = url.split('?');
             if (url_arr.length>2) {
                 alert("invalid url provided to load inline form");
                 return;
             }
 
	     var req = new Object();
	     req.method="POST";
	     req.uri = Ngx.Odb.CommonUtil.getUri();;
	     req.async = false;

	     req.params = [] ;
	     req.params["container_id"] = container_id;
              
             // adding all params into request 
             if (url_arr[1] != '') {
                 var qparams_arr = url_arr[1].split('&');
                 for(var i = 0; i < qparams_arr.length; i++) {
                     var param_arr = qparams_arr[i].split('=');
                     req.params[param_arr[0]] = param_arr[1];
                 }
             }

             wnd.document.getElementById(container_id).style.display="block";
             wnd.document.getElementById(container_id).innerHTML="Loading, Please wait........";

	     var callback =  function(xhr) {

                 // replace innerHTML
                 wnd.document.getElementById(container_id).innerHTML=xhr.responseText; 

                 // parsing and executing javascript  
                 wnd.Ngx.Odb.CommonUtil.executeScript(wnd, xhr.responseText);
      	     };

	     Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    }

    this.create = function() {
        return this;
    };
}

CommonUtil.prototype = new Element();
CommonUtil.prototype.constructor = CommonUtil;

/* CLASS Form */

function Form()  { 
    this.message = "",
    this.firstMessage = function(x) {
        if (!this.message) {
            this.message = x;
        }
    };

    this.validationObjects = [];

    this.addValidationObject =  function(x, index) {
        this.validationObjects.push({field : x, index : index });
    };

    this.lastError = {
        obj : null,
        style : {}
    };

    this.runValidations = function() {
        var result = true;
        this.message = '';
        if (this.lastError.obj) {
            for (var p in this.lastError.style) {
                this.lastError.obj.style[p] = this.lastError.style[p];
            }
        }
        this.validationObjects.sort(function(a,b) { return a.index - b.index }); //sort ascending by index
        for (var i=0; i<this.validationObjects.length; i++) {
              var vobj = this.validationObjects[i].field;
              result = result && vobj.validationFunction(); /* no validation function should fail! */
              if (!result) {
                  this.lastError.obj = vobj;
                  this.lastError.style.borderWidth = vobj.style.borderWidth;
                  this.lastError.style.borderColor = vobj.style.borderColor;
                  vobj.style.borderWidth = 'medium';
                  vobj.style.borderColor = 'red';
                  vobj.scrollIntoView();
                  window.scrollBy(0,-50);
                  vobj.focus();
                  break;
              }
        }
        return result;
    };

    this.create = function() {
        return new Form(x, y, m, d);
    };

};

Form.prototype = new Element();
Form.prototype.constructor = Form;

/* CLASS Control */

function Control() {

    this.validations = {

        notNull: function(x,s) {
                      if (!x.value) {
                          Ngx.Odb.Form.firstMessage( (s || Ngx.Odb.Form.display_name(x.name)) + " cannot be null");
                          return false;
                      }
                      else {
                          return true;
                      }
                   },
        isNull: function(x,s) {
                      if (!x.value) {
                          return true;
                      }
                      else {
                          Ngx.Odb.Form.firstMessage( (s || Ngx.Odb.Form.display_name(x.name)) + " must be null");
                          return false;
                      }
                  },
         isNumber: function(x,s) {
             if (isNaN(x.value)){
                     Ngx.Odb.Form.firstMessage( (s || Ngx.Odb.Form.display_name(x.name)) + " must be a number");
                     return false;
                 }
                 else { 
                     return true;
                 }
             },
         isNotNumber: function(x,s) {
             if (!x.value || isNaN(x.value)){
                     return true;
                 }
                 else { 
                     Ngx.Odb.Form.firstMessage((s || Ngx.Odb.Form.display_name(x.name)) + " must not be a number");
                     return false;
                 }
             },
    
         inRange: function(x,s, min, max) {
             if (!isNaN(x.value) && !isNaN(min) && !isNaN(max) && x.value >= min && x.value <= max) {
                 return true;
             }
             else {
                 Ngx.Odb.Form.firstMessage((s || Ngx.Odb.Form.display_name(x.name)) + " must be a number between " + min + " and " + max);
                 return false;
             }
         },
         isPositive: function(x,s) {
             if (isNaN(x.value) || x.value == '' ) {
                 return true;
             }
             if (x.value <= 0) {
                 Ngx.Odb.Form.firstMessage((s || Ngx.Odb.Form.display_name(x.name)) + " value not valid");
                 return false;
             }
             else {
                 return true;
             }
         },
         isEmail: function(x, s) {
             var objRegExp = /^([a-zA-Z0-9])+([a-zA-Z0-9_\.\-])*([a-zA-Z0-9])\@(([a-zA-Z0-9])([a-zA-Z0-9\-])+([a-zA-Z0-9])\.)+([a-zA-Z0-9\+.]{2,4})+$/; 
             if(x.value && objRegExp.test(x.value) == false) {
                 Ngx.Odb.Form.firstMessage((s || Ngx.Odb.Form.display_name(x.name)) + " must be a valid email id");
                 return false
             }
             else {
                 return true;
             }
         },
         noSpace: function(x) {
            var result = true;
            if (x.value && x.value.match(/\s+/)) {
                result = false;
                this.lastError = {msgtype : 'error', msg : x.name + " cannot contain blanks or whitespace" };
                return result;
            }
        },
        isWord: function(x) {
            var result;
            if (x.value && x.value.match(/^[\w]+$/)) {
                result = true;
            }
            else {
                result = false;
                this.lastError = {msgtype : 'error', msg : x.name + " can only contain alphanumerics and underscores" };
            }
            return result;
        }

    };

    this.create = function() {
        return new Control();
    };


}

Control.prototype = new Element();
Control.prototype.constructor = Control;


/* CLASS Date control */

function DateDropdown(x, y, m, d, nullable, range_begin, range_end) {
    this.x = x;
    this.y = y;
    this.m = m;
    this.d = d;
    this.nullable=nullable;
    this.range_begin = range_begin;
    this.range_end = range_end;

    var _this = this;
    this.init_date = function() {
        var day = document.main[_this.d];
        var month = document.main[_this.m];
        var year = document.main[_this.y];
        var dateobj = new Date();

        _this.start_year = _this.compareYear(_this.range_begin);
        _this.end_year = _this.compareYear(_this.range_end);

	_this.end_year = _this.end_year ? _this.end_year : dateobj.getFullYear()+30;
	_this.start_year = _this.start_year ? _this.start_year : 1940;

        var init_date = document.getElementById(_this.x).value;
        var init_date_tokens = init_date.split("-");
        var init_year = parseInt(init_date_tokens[0],10);
        var init_month = parseInt(init_date_tokens[1],10);
        var init_day  = parseInt(init_date_tokens[2],10);

        if (this.nullable == 1) {
          day.options[0] =  new Option('', '', false, false);
          month.options[0] =  new Option('', '', false, false);
          year.options[0] =  new Option('', '', false, false);
        }
        for (var i=1; i<= 31 ; i++) {
            var opt;
            if (init_day == i) {
                opt = new Option(i, i, true, true);
            }
            else {
                opt = new Option(i, i, false, false);
            }
            day.options[i] = opt;
        }
        for (var i=1; i<= 12 ; i++) {
            var opt;
            if (init_month == i) {
                opt = new Option(i, i, true, true);
            }
            else {
                opt = new Option(i, i, false, false);
            }
            month.options[i] = opt;
        }
        for (var i=_this.start_year; i<= _this.end_year; i++) {
            var opt;
            if (init_year == i) {
                opt = new Option(i, i, true, true);
            }
            else {
                opt = new Option(i, i, false, false);
            }
            year.options[i-_this.start_year+1] = opt;
        }
    };

    this.compareYear = function(xx) {
        if (xx == null) {
            return null;
        }
        var FY = xx.split("-");
        for(var t in FY){
            if(FY[t]>1000){
                return FY[t];
            }
        }
    };

    this.check_date = function(y,m,d) {
         var date = new Date (y,m,d);
         var yy = date.getFullYear();
         var mm = date.getMonth();
         var dd = date.getDate();
         return ((yy == y) && (mm == m) && (dd == d));
    };

    this.recalc_day = function(){
        var day = document.main[_this.d];
        var month = document.main[_this.m];
        var year = document.main[_this.y];
        var sel_day = day.value;
        var sel_month = month.value;
        var sel_year = year.value;
        day.options.length = 0;

        // 0 = jan, 1 = feb, 2 = mar etc
        if (! isNaN(sel_month)) {
             sel_month = sel_month - 1;
        }

        //alert('recalculating days : ' +  sel_day + '=' + sel_month + '=' + sel_year);

        if (_this.nullable == 1) {
          day.options[0] =  new Option('', '', false, false);
        }

        for (var i=1; i<= 31 ; i++) {
            var date_flag=0;
            if (isNaN(sel_year) || sel_year == '' || isNaN(sel_month) || sel_month == '') {
                date_flag=1;
            } else if (this.check_date(sel_year,sel_month,i)) {
                date_flag=1;
            }
            if (date_flag == 1) {
                var opt;
                if (i == sel_day) {
                    opt = new Option(i, i, true, true);
                }
                else {
                    opt = new Option(i, i, false, false);
                }
                day.options[i] = opt;
            }
        }
    };

    this.update_field = function() {
         var field = document.main[_this.x];
         var day_val = parseInt(document.main[_this.d].value,10);
         var month_val = parseInt(document.main[_this.m].value,10);
         var year_val = parseInt(document.main[_this.y].value,10);
         if (!isNaN(day_val) && !isNaN(month_val) && !isNaN(year_val)) {
            field.value = year_val + '-' + month_val + '-' + day_val;
         }
    };

    this.create = function(x, y, m, d, nullable, range_begin, range_end) {
        return new DateDropdown(x, y, m, d, nullable, range_begin, range_end);
    };

}

DateDropdown.prototype = new Control();
DateDropdown.prototype.constructor = DateDropdown;

/* CLASS Objectpicker
 *
 * This is the replacement for dojo based dependent dropdowns implementation, 
 * We hope it is lighter weight and easier to understand and maintain
 */

function Objectpicker(fname, args) {

    //var this = this;

    this.do_onchange = function(/* event */evt) {
        this.cvalue = this.selectedValues();
        this.onchange(this.selectedNames(), this.selectedValues());
    };

    this.onchange = function(name, value) {
        //functions for others to hook 
    };

    /* rows are an array of name, value pairs */
    /* the value can be a string or an object, user should know what they are retrieving */

        
    /* return the name field of selected row */
    this.selectedNames = function() {
        var selectedIndices = this.getSelectedIndices(this.form_field);
        var names = [];
        for(var yay in selectedIndices){
            names.push(selectedIndices[yay].name);
        }
        return names;
            //return this.form_field.options[this.form_field.selectedIndex].text;
    };
    this.selectedValues = function() {
        var selectedIndices = this.getSelectedIndices(this.form_field);
        var values = {};
        for(var tp in selectedIndices){
            values[selectedIndices[tp].value] = "";
        }
        return values;
            //return this.form_field.options[this.form_field.selectedIndex].value;
    };

    /* returns the (unflattened) selected row from cached_cdata */
    this.selectedRows = function(s) {
        var rows = [];
        for (var i=0; i<cdata.length; i++) {
            if (cdata[i][0] == s) {
                rows.push(cdata[i][1]);
            }
        }
        return rows;
    };

    this.check_constraints = function (row) {
        var result = true;
       if (!this.constraint_fields) {
           //return true;
           return result;
       }
       for (var i=0; i<this.constraint_fields.length; i++) {
            var cname = this.constraint_fields[i];
            var cfield = document.getElementById(cname);
            var cfield_selections = this.getSelectedIndices(cfield);
            //var cvalue = cfield.options[cfield.selectedIndex].value;
            var check = false;
            for(var cfield_sel in cfield_selections){
                var cvalue = cfield_selections[cfield_sel].value;
            //if (row[cname] &&  cvalue >0 &&
            if (cvalue >0 &&
                (row[cname] == cvalue || row[cname]=='') )
            {
                //alert("check constraint failed");
                //return false;
                check = true;
            }
            }
            result  = check;
       }
       //return true;
       return result;
    };

    /* function to select selected indices again */
    this.setSelectedIndices = function(selectObj, indices){
        for(var xmp in indices){
            var index = indices[xmp].index;
            selectObj.options[index].selected=true;
        }
    };

    /* function to get selected indices */
    this.getSelectedIndices = function(selectObj) {
        var indices = [];
        while (selectObj.selectedIndex!=-1){
            indices.push({index : selectObj.selectedIndex, value : selectObj.options[selectObj.selectedIndex].value, text : selectObj.options[selectObj.selectedIndex].text});
            selectObj.options[selectObj.selectedIndex].selected=false;
            if(this.display_method!='list_view'){
                break;
            }
        }
        if(indices.length){
            this.setSelectedIndices(selectObj, indices);
        }
        return indices;
    };

    /* a constrained objectpicker is deemed unconstrained if all of its constraining fields are set to null */

    this.is_unconstrained = function() {
       var result = true;


       if (!this.constraint_fields) {
           return false;
       }
       for (var i=0; i<this.constraint_fields.length; i++) {
            var cname = this.constraint_fields[i];
            var cfield = document.getElementById(cname);
            var cvalue = -1;
            if(cfield.selectedIndex!=-1){
                cvalue = parseInt(cfield.options[cfield.selectedIndex].value);
            }
            if (cvalue > 0 ) {
                result = false;
                break;
            }
        }
        return result;
    };
        

    /* recalc re-creates the options list of the select box */
    /* based on data, constraints, and values of constraining fields */
    /* while any constraining field set to null acts to relax the constraint by allowing all relevant values */
    /* the end condition of all constraining fields set to null causes this field to become disabled */
    /* this is not a mathematical consequence, but a usability issue */
    /* in that a fully unconstrained user input list which is otherwise constrained, is usually senseless */

    this.recalc = function() {

        if (this.is_unconstrained()) {
            this.form_field.options.length = 0;
            this.form_field.innerHTML = '';
                if (this.cis_filter>0) {
                    opt = new Option('Select here','', false, false);
                    this.form_field.options[0] = opt;
                }
                else {
                    opt = new Option(this.cnull_option_display_name,'', false, false);
                    this.form_field.options[0] = opt;
                }
                    

    //        this.form_field.setAttribute('disabled', true);
            this.do_onchange();
            return;
        }
        else {
    //        this.form_field.removeAttribute('disabled');
        }
          
        if (!this.cdata) { 
            this.do_onchange();
            return; 
        }

        this.form_field.options.length = 0;
        this.form_field.innerHTML = '';
        var counter = 0;
   
        var optstring = '';
        if(this.display_method!="list_view"){
        if (this.cis_filter>0) {
            opt = new Option('Select here','', false, false);
            this.form_field.options[counter++] = opt;
        }
        else {
            if (this.cforce_selection > 0) {
                opt = new Option('Select here','-1', false, false);
            }
            else {
                opt = new Option('Select here','', false, false);
            }
            this.form_field.options[counter++] = opt;
        }
        }


        //optstring += '<option value=""></option>'

        var selIndex = [];//null;
        var validOptions = 0;
        for (var i=0; i<this.cdata.length; i++) {
            if (this.check_constraints(this.cdata[i][1])) {
                //if (this.cvalue == this.cdata[i][1].id) {
                if (this.cdata[i][1].id in this.cvalue) {
                    opt = new Option(this.cdata[i][0],this.cdata[i][1].id,true, true);
                    selIndex.push(counter);
                }
                else {
                    opt = new Option(this.cdata[i][0],this.cdata[i][1].id,false, false);
                }
                validOptions++;
                this.form_field.options[counter++] = opt;
            }
        }

        if (selIndex.length) {
            this.form_field.selectedIndex = selIndex;
        }

        if (this.cnull_option > 0 && this.cis_filter <= 0) {
            opt = new Option(this.cnull_option_display_name,'', false, false);
            this.form_field.options[counter++] = opt;
        }
       
        if (this.cnull_option > 0 && this.cis_filter>0) {
            opt = new Option(this.cnull_option_display_name,'null', false, false);
            this.form_field.options[counter++] = opt;
        }   
            
        if (validOptions == 0) {
           // this.form_field.setAttribute("disabled", true);
        }

        this.do_onchange();

    };

    this.valuename = function(v) { 
        for (var i=0; i<this.cdata.length; i++) {
            if (this.cdata[i][1].id == v) {
                return cdata[i][0];
            }
        }
        return '';
    };

    /* the qm api, a standardized set of wrappers around organically grown widgets */

    this.q_initialize = function(/* numeric id */ v) {
        for (var i=0; i<this.form_field.options.length; i++) {
            if (this.form_field.options[i].value == v) {
                this.form_field.options[i].selected = true;
            }
            else {
                this.form_field.options[i].selected = false;
            }
        }
    };

    if (fname) {
        this.form_field = document.getElementById(fname);
        this.cforce_selection = parseInt(args.force_selection);
        this.cnull_option = parseInt(args.null_option);
        this.cnull_option_display_name = args.null_option_display_name;
        this.cis_filter = parseInt(args.is_filter);
        this.display_method = args.display_method;
    
        /* set the style of select input field from args if specified */
        /* don't use setAttribute because IE does not like that for style property */
    
        if (args.style_string) {
            this.form_field.style.cssText = args.style_string;
        }
    
        /* allow data to be sent inline via data argument */
        /* TODO support remote data fetching if required */
    
        if (args.data) {
            this.cdata = JSON.parse(args.data);
        }
    
        //if(this.display_method=="list_view"){
            var cvalues = args.value;
            cvalues = cvalues.split(",");
            this.cvalue = {};
            for(var tmp in cvalues){
                //var k = parseInt(cvalues[tmp]);
                var k = cvalues[tmp];
                this.cvalue[k]="";
            }
            //alert("this.cvalue:  " + JSON.stringify(this.cvalue));
        //}
        /*else {
            this.cvalue = parseInt(args.value);
        }*/
    
        /* set up constraints on the dataset */
        /* these are typically mapped from foreign key relationships in datamodel */
    
        if (args.constraints) { /* */
    
            this.constraint_fields = JSON.parse(args.constraints);
            for(var i=0; i<this.constraint_fields.length; i++) {
                var c = this.constraint_fields[i];
                //dojo.event.connect(dojo.widget.manager.getWidgetById(c).form_field, "onchange", this, "recalc");
                var ev_wrapper = this.createEventListener( document.getElementById(c), 'onchange', this.recalc, true /*bool*/);
                //document.getElementById(c).onchange = this.recalc;
            }
    
        }
    
        /* surface the onchange event of form_field for others to hook */
    
        // dojo.event.connect(this.form_field, "onchange", this, "do_onchange");
    
        /* do the first recalc to create visible/available options list from data given constraints */
    
        this.recalc();
    
        /* initialize with value if present */
    
        if (this.value) {
            //this.q_initialize(this.value);
        }
        
        /* disable if required */
    
        /*document.addOnLoadFunction( function() { if (this.is_unconstrained()) {
                                                  //   this.form_field.setAttribute('disabled', true);
                                                 } 
                                               });*/
    }
    

    this.create = function(fname, args) {
        return new Objectpicker(fname, args);
    };
}

Objectpicker.prototype = new Control();
Objectpicker.prototype.constructor = Objectpicker;

/* CLASS Date control */

function Hobjectpicker( fieldname, fieldname_selected_text, main_div_name, full_base_url , h_schema, h_table, display_method, onchangeevents ) {
    this.fieldname = fieldname;
    this.fieldname_selected_text = fieldname_selected_text;
    this.main_div_name = main_div_name;
    this.full_base_url = full_base_url;
    this.h_schema = h_schema;
    this.h_table = h_table;
    this.display_method = display_method;
    this.onchangeEvents = onchangeevents;
    var event_wrapper;
    
    this.leaf_nodes = function() {
        var main = document.getElementById(this.main_div_name);
        var main_lis = main.getElementsByTagName("li");
        if(main_lis.length){
            for(var t=0; t<main_lis.length;t++){
                var inner_ul = main_lis[t].getElementsByTagName("ul");
                var count = main_lis[t].id.split("/");
                if(!inner_ul.length && count.length>2){
                    main_lis[t].className="leaf_node";
                }
            }
        }
    };

    this.show_picker = function() {
        var div_arr = document.getElementsByTagName("div");
        var prefix = this.main_div_name.slice(0,this.main_div_name.lastIndexOf("_")+1);
        for(var q=0;q<div_arr.length;q++){
            var div_prefix = div_arr[q].id.search(prefix);
            var div_id = div_arr[q].id;
            if(div_prefix ==0 && div_id != this.main_div_name){
                div_arr[q].style.display="none";
            }
            else if(div_prefix ==0 && div_id == this.main_div_name){
                if(div_arr[q].style.display=="none") {
                    div_arr[q].style.display="block";
                    this.selected_item();
                    event_wrapper = this.createEventListener( document, 'onclick', this.closepicker, true /*bool*/);
                }
                else {
                    this.hide();
                }
            }
        }
    };

    this.select_kid = function(ev, xpath,xid) {
        /* copying path to textbox */
        var key_obj = window.event? event : ev;
        var fld = document.main.elements[this.fieldname];
        var elem = document.getElementById(this.fieldname_selected_text);
        if(key_obj.ctrlKey){
            //for multiple selection
            xpath = xpath.substring(xpath.indexOf('/')+1);
            var old_val = fld.value ? (fld.value + ', ') : '';
            var old_html = elem.innerHTML ? (elem.innerHTML + ', ') : '';
            if(old_html.search(xpath)>=0){
                var pos = old_val.search(xid);
                var x_id = ' ' + xid + ',';
                var x_path = ' ' + xpath + ',';
                if(!pos){
                    x_id = xid + ', ';
                    x_path = xpath + ', ';
                }
                old_val = old_val.replace(x_id, '');
                fld.value = old_val.substr(0, old_val.length - 2);
                old_html = old_html.replace(x_path,'');
                elem.innerHTML = old_html.substr(0, old_html.length - 2);
            }
            else{
                fld.value = old_val + xid;
                elem.innerHTML = old_html + xpath;//.substring(xpath.indexOf('/')+1);
            }
        }
        else{
            //for sigle selection
            fld.value = xid;
            elem.rel = xpath;
            elem.innerHTML = xpath.substring(xpath.indexOf('/')+1);
        } 
        if (this.onchange) { 
            this.onchange.call(fld);
        }
        if(this.display_method!="list_view"){
            this.hide();
        }
    };

    this.show_kids = function(xpath) {
        var xelement = document.getElementById(xpath);
        var liElem = xelement.parentNode;
        var uls = liElem.getElementsByTagName("ul");
        /* hide all kids */
        this.hide_kids(xelement.id);
        /* hide/show currently selected item  */
        if(uls.length){
            if(uls[0].style.display=="block") {
                uls[0].style.display="none";
                //xelement.style.backgroundImage="url('" + this.full_base_url + 'themes/en/default/images/arrow.png' +"')";
                xelement.src = "themes/en/default/images/arrow.png";
            }
            else {
                uls[0].style.display="block";
                var inner_lis = uls[0].getElementsByTagName("li");
                //xelement.style.backgroundImage="url('" + this.full_base_url + 'themes/en/default/images/arrow-open.png' +"')";
                xelement.src = "themes/en/default/images/arrow-open.png";
                liElem.getElementsByTagName("a")[0].focus();
                //xelement.focus();
            }
        }
    };


    this.hide_kids = function(xnode_id) {
        var sup = document.getElementById(this.main_div_name);
        var lis = sup.getElementsByTagName("li");
        for(var j=0; j<lis.length;j++){
            var li_obj = lis[j];
            var a_obj = li_obj.getElementsByTagName("a")[0];
            var img_obj = li_obj.getElementsByTagName("img")[0];
            var place = xnode_id.lastIndexOf("/");
            var last_place = a_obj.id.lastIndexOf("/");
            if((xnode_id != a_obj.id) && (place == last_place)){
                var uls = li_obj.getElementsByTagName("ul");
                if(uls.length){
                    uls[0].style.display="none";
                    //a_obj.style.backgroundImage="url('" + this.full_base_url + 'themes/en/default/images/arrow.png' +"')";
                    img_obj.src = "themes/en/default/images/arrow.png";
                }
            }
        }
    };



    this.create = function(fieldname, fieldname_selected_text, main_div_name, full_base_url, h_schema, h_table, display_method, onchangeevents) {
        return new Hobjectpicker(fieldname,fieldname_selected_text, main_div_name, full_base_url, h_schema, h_table, display_method, onchangeevents);
    };
    
    this.get_element = function(element,member,type){
        /* select only LI */    
        do{
            if (member == "parent"){
                element = element.parentNode;
            }
            else if(member == "child") {
                element = element.firstChild;
            }
            else if(member == "prev_sibling") {
                element = element.previousSibling;
            }
            else if(member == "next_sibling") {
                element = element.nextSibling;
            }
        }while(element && (element.nodeName!=type || element.nodeType!=1) && element.id != "menu");
        return element;
    };
    
    this.get_key = function(ev,xpath,xid){
        var obj = document.getElementById(xpath);
        var doc_obj = obj.parentNode;
        var key_obj = window.event? event : ev;
        var key_target = key_obj.target || key_obj.srcElement;
        var key_targetid = key_target.id;
        var key = key_obj.keyCode ? key_obj.keyCode : key_obj.charCode;
        if (key == 27){
            this.hide();
            var elem = document.getElementById(this.fieldname_selected_text);
            elem.focus();
        }
        /*if(key == 17){
            alert("ctrl pressed");
            if(key_obj.click){
                alert("click with ctrl");
            }
        }*/
        if(key>=65 && key<=90){
            if(xpath.indexOf("/")!="-1"){
                var ch = String.fromCharCode(key);
                var level = xpath.match("/").length;
                var parent_ul = doc_obj.parentNode;
                var lis = parent_ul.getElementsByTagName("li");
                for(var len=0; len<lis.length; len++){
                    var cur_a = lis[len].getElementsByTagName("a")[0];
                    var cur_img = lis[len].getElementsByTagName("img")[0];
                    var str = cur_a.innerHTML;
                    if(str.charAt(0)==ch && level==cur_img.id.match("/").length){
                        cur_a.focus();
                        break;
                    }
                }
            }
        }
        else if(key==13) {
            if(key_targetid.search(/^hpicker/)==0){
                var main_div = document.getElementById(this.main_div_name);
                //if(main_div.style.visibility=="hidden") {
                if(main_div.style.display=="none") {
                    this.show_picker();
                    if(obj.rel=="") {
                        var main_div_arr = main_div.getElementsByTagName("a");
                        main_div_arr[0].focus();
                    }
                }
            }
            else {
                this.select_kid(xpath,xid);
                //enter_wrapper = this.createEventListener( document, 'onkeydown', this.link_focus, true /*bool*/);
            }
        }
        else if(key == 40){ //down arrow
            obj.blur();
            var sib = this.get_element(doc_obj,'next_sibling','LI');
            var obj_ul = doc_obj.getElementsByTagName("ul");
            if(obj_ul.length!=0 && obj_ul[0].style.display=="block"){
                var obj_li = obj_ul[0].getElementsByTagName("li");
                var sub_an = obj_li[0].getElementsByTagName("a");
                sub_an[0].focus();
            }
            else if(sib) {
                    var sub_an = sib.getElementsByTagName("a");
                    sub_an[0].focus();
            }
            else
            {
                 this.next_item(doc_obj);
            }
        }
        else if(key == 38) { //up arrow
            var sib = this.get_element(doc_obj,'prev_sibling','LI');
            if(sib) {
                this.prev_item(sib);
            }
            else
            {
                var sib = this.get_element(doc_obj,'parent','LI');
                if(sib){
                    var sub_an = sib.getElementsByTagName("a");
                    sub_an[0].focus();
                }
            }
        }
        else if(key == 37) { //left arrow
            var sib = this.get_element(doc_obj,'parent','LI');
            if(sib && sib.id!="menu") {
                var sub_an = sib.getElementsByTagName("a");
                this.show_kids(sub_an[0].id);
                sub_an[0].focus();
            }
        }
        else if(key == 39) { //right arrow
            if(!obj.className.match("leaf_node")){
                var result = true;
                var lis = doc_obj.getElementsByTagName("li");
                if(!lis.length){
                    //obj.className = obj.className + ' loading';
                    var old_src = obj.src;
                    obj.src = "themes/en/default/images/loading.gif";
                    result = this.fetchKids(xid, xpath);
                    //obj.className = obj.className.replace(' loading', '');
                    obj.src = old_src;
                    if(!result){
                        obj.className = "leaf_node onhover";
                        doc_obj.className = "leaf_node";
                        obj.src = "themes/en/default/images/bullet1.png";
                    }
                }
                if(result){
                    this.show_kids(xpath);
                    var sub_li = doc_obj.getElementsByTagName("li");
                    if(sub_li.length) {
                        var sub_an = sub_li[0].getElementsByTagName("a");
                        sub_an[0].focus();
                    }
                }
            }
        }
    };
    
    this.prev_item = function(sib){
        var sup_ul = sib.getElementsByTagName("ul");
                if(sup_ul.length==0 || sup_ul[0].style.display=="none"){
                    var sub_an = sib.getElementsByTagName("a");
                    sub_an[0].focus();
                }
                else{
                    var children = sib.getElementsByTagName("li");
                    var child = children[0];
                    var last_child;
                    do{
                        last_child = child;
                        child = this.get_element(child,'next_sibling','LI');
                    }while(child)
                    var ul = last_child.getElementsByTagName("ul");
                    if(ul.length==0 || ul[0].style.display=="none"){
                        var sub_an = last_child.getElementsByTagName("a");
                        sub_an[0].focus();
                    }
                    else{
                        this.prev_item(last_child);
                    }
                }
    };
    
    this.next_item = function(doc_obj){
        var par = this.get_element(doc_obj,'parent','LI');
        if(par){
            var par_sib = this.get_element(par,'next_sibling','LI');
            if(par_sib){
                var sub_an = par_sib.getElementsByTagName("a");
                sub_an[0].focus();
            }
            else{
                this.next_item(par);
            }
        }
    };
    
    this.hide = function(){
        var main_div = document.getElementById(this.main_div_name);
        //main_div.style.visibility="hidden";
        main_div.style.display="none";
        var uls = main_div.getElementsByTagName("ul");
        for(var t = 1; t<=uls.length-1; t++){
            if(uls[t].style.display!="none")
            {
                uls[t].style.display="none";
                tparent = this.get_element(uls[t],'parent','LI');
                var tparent_img = tparent.getElementsByTagName("img")[0];
                tparent_img.src = "themes/en/default/images/arrow.png";
                //var tparent_an = tparent.getElementsByTagName("a")[0];
                //tparent_an.style.backgroundImage="url('" + this.full_base_url + 'themes/en/default/images/arrow.png' +"')";
            }
        }
        this.deleteEventListener( document, 'onclick', event_wrapper, true /*bool*/);
     };
    
    this.click = function(xpath,xid) {//, xname) {
        /* to select a leaf node */
        var result = true;
        var obj = document.getElementById(xpath);
        if(obj.className.match("leaf_node")) {
            return;
            /*if(this.display_method=="list_view"){
                //this.select_checkbox(xname);
            }
            else{
                this.select_kid(xpath,xid);
            }*/
         //   this.hide();
        }
        else {
            var liObj = obj.parentNode;
            var lis = liObj.getElementsByTagName("li");
            if(!lis.length){
                //obj.className = obj.className + ' loading';
                var old_src = obj.src;
                obj.src = "themes/en/default/images/loading.gif";
                result = this.fetchKids(xid, xpath);
                //obj.className = obj.className.replace(' loading', '');
                obj.src = old_src;
                if(!result) {
                    obj.className = "leaf_node";
                    obj.parentNode.className = "leaf_node";
                    obj.src = "themes/en/default/images/bullet1.png";
                    /*if(this.display_method=="list_view"){
                        //this.select_checkbox(xname);
                    }
                    else{
                        this.select_kid(xpath, xid);
                    }*/
                }
            }

            if(result) {
                this.show_kids(xpath);
            }
        }
    };
    
    this.closepicker = function(e) {
        e = e || event;
    	var target = e.target || e.srcElement;
	    var target_id = target.id || "xyz";
    	if(target_id!=this.fieldname_selected_text && target_id.indexOf('/')=='-1' && target_id!=this.main_div_name && !target_id.match(/^hpicker_selected_value/)){
	        this.hide();
    	}
    };
    
    this.selected_item = function() {
        var selected_text = document.getElementById(this.fieldname_selected_text).rel;
        if(selected_text.match("_/")){
            selected_text = selected_text.replace("filter_/",'');
        }
        if(selected_text.indexOf("/")>0){
            var selected_text_arr = selected_text.split("/");
            var img = document.getElementById(selected_text);
            var elem = img.parentNode;
            var an = elem.getElementsByTagName("a")[0];
            for(var y=selected_text_arr.length ; y>2 ;y--){
                elem = this.get_element(elem,'parent','UL');
                elem.style.display="block";
                elem = this.get_element(elem,'parent','LI');
                var elem_img = elem.getElementsByTagName("img")[0];
                elem_img.src = "themes/en/default/images/arrow-open.png";
                //var elem_an = elem.getElementsByTagName("a")[0];
                //elem_an.style.backgroundImage="url('" + this.full_base_url + 'themes/en/default/images/arrow-open.png' +"')";
            }
            an.className = an.className + " onhover";
            an.focus();   
        }
        else{
            var picker = document.getElementById(this.main_div_name);
            var a_obj = picker.getElementsByTagName("A");
            a_obj[0].focus();
        }
    };
    
    this.link_focus = function() {
        document.getElementById(this.fieldname_selected_text).focus();
        //this.deleteEventListener( document, 'onkeydown', enter_wrapper, true /*bool*/);
    };

    this.fetchKids = function(xid, xpath) {
        if(!xpath){
            this.togglePathPickerLoader();
        }
        var result = false;
        var req = new Object();
        req.method='GET';
        req.uri = this.full_base_url;
        req.async = false;
        req.params = [] ;
        req.params['client_type'] = 'json';
        req.params['current_schema'] = this.h_schema;
        req.params['current_id'] = xid;
        req.params['current_table'] = this.h_table;
        req.params['path_picker'] = xpath ? false : true;
        req.params['objpath'] = 'domain/public/tables/pages/forms/publist';
        req.params['page'] = 'get_htable_rows';
        req.params['action'] = 'render';

        var callback =  Ngx.Odb.CommonUtil.createCallback.call(this, function(xhr) {
            var response = JSON.parse(xhr.responseText);
            if(xpath){
                if(response.rows.length){
                    this.create_hpicker_contents(xpath, response.rows);
                    result = true;
                }
            }
            else {
                this.create_path_picker(this.fieldname_selected_text, this.fieldname, xid, response);
            }
        });

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback); 
        return result;
    };

    this.create_path_picker = function(div_id, fieldname, id, response) {
        var container = document.getElementById(div_id);
        var pathinfo = response.pathinfo;
        var kids = response.rows;
        var html = '<input id="'+ fieldname +'" name="'+ fieldname +'" type="hidden" value="'+ id +'"/>';
        var index = pathinfo.length;
        html = html + pathinfo[index - 1 ].name;
        var prev_id = pathinfo[index - 1].id;
        index--;
        while(index){
            var pathinfo_id = pathinfo[index -1].id;
            var pathinfo_name = pathinfo[index -1].name;
            html = html + ' &raquo; <a onclick="'+ div_id +'.fetchKids('+ prev_id +', null); eval(' + div_id  + '.onchangeEvents);" href="javascript:void(0);">'+ pathinfo_name +'</a> ';
            if(index!=1){
                prev_id = pathinfo_id;
            }
            index--;
        }
        if(kids.length){
            html = html + ' &raquo; <select><option value=""></option></select>';
            container.innerHTML = html;
            var select = container.getElementsByTagName("select")[0];
            for(var kid in kids){
                kid = kids[kid];
                var opt = document.createElement("option");
                opt.value = kid.id;
                opt.innerHTML = kid.name;
                select.appendChild(opt);
            }
            this.setOnChangeEvent(div_id);
        }
        else {
            container.innerHTML = html;
        }
        var lastIndex = div_id.lastIndexOf("_");
        var divId = div_id.substring(0,lastIndex) + "_buttons_" + div_id.substring(lastIndex+1);
        var btn_container = document.getElementById(divId);
        btn_container.innerHTML = '<a href="javascript:void(0);" onclick="document.main.submit();"> Go </a> <a href="javascript:void(0);" onclick="' + div_id +'.fetchKids(' + prev_id + ', null)"> Edit </a>';
        this.togglePathPickerLoader();
    };

    this.auto_refresh = function(value) {
        if(value){
            document.getElementById(this.fieldname).value = value;
        }
        document.main.submit();
    };

    this.setOnChangeEvent = function(div_id) {
        var container = document.getElementById(div_id);
        if(this.display_method == "path_picker_auto_refresh"){
            var select_obj = container.getElementsByTagName("select")[0];
            select_obj.onchange = function() { 
                eval(div_id + ".fetchKids(this.value, null)"); 
                var function_string = eval(div_id + ".onchangeEvents"); 
                eval(function_string);
                eval(div_id + ".auto_refresh(this.value)");
                //eval("document.getElementById(" + div_id + ".fieldname).value = this.value");
                //document.main.submit();
            };
        }
        else{
            container.getElementsByTagName("select")[0].onchange = function() { 
                eval(div_id + ".fetchKids(this.value, null)"); 
                var function_string = eval(div_id + ".onchangeEvents"); 
                eval(function_string);
            };
        }
    };

    this.togglePathPickerLoader = function() {
        var rand = this.main_div_name.substring(this.main_div_name.lastIndexOf("_") + 1);
        var loader = document.getElementById('path_picker_loading_' + rand);
        if(loader.style.display=="block"){
            loader.style.display="none";
        }
        else {
            loader.style.display="block";
        }
    };

    this.create_hpicker_contents = function(xpath, response) {
        var obj = document.getElementById(xpath).parentNode;
        var prefix = '';
        if(xpath.match("filter_")){
            prefix = xpath.substr(0, xpath.indexOf("_")) + '_';
        }
        var obj_id = obj.id;
        var rand = obj_id.substr(obj_id.lastIndexOf("_") + 1, obj_id.length - 1);
        var ul = document.createElement("ul");
        ul.style.display = "none";
        //alert("inside hpicker content creation:    " + this.display_method);
        obj.appendChild(ul);
        for(var x in response){
            var res = response[x];
            var li = document.createElement("li");
            var nodeclass = '';
            li.id = prefix + "_" +res.id + "_" + rand;
            li.className = nodeclass;
            //var display_method = eval("hpicker_" + rand + ".display_method");
            var li_html = '';
            if(this.display_method == "list_view"){
                //li_html = '<input type="checkbox" name="list_picker_checkbox_' + rand + '" value="' + res.id + '" onclick="javascript:list_picker_' + rand + '.select_checkbox(this.name);"/>';
                li_html = '<img src="themes/en/default/images/arrow.png" class="" style="position:absolute; margin-top:5px;" id="' + prefix + res.path + '/' + res.name + '" onclick="' + 'javascript:list_picker_'+rand+'.click(\'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';"/>';
                li_html = li_html + '<a  class="' + nodeclass + '" onclick="' + 'javascript:list_picker_'+rand+'.select_kid(event, \'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';"  onkeydown="' + 'javascript:list_picker_'+rand+'.get_key(event, \'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';" onmouseout="javascript:this.className = this.parentNode.className;" onmouseover="javascript:this.className = this.parentNode.className + \' onhover\';" onblur="javascript:this.className = this.parentNode.className;" onfocus="javascript:this.className = this.parentNode.className + \' onhover\';" tabindex="0">'+ res.name +'</a>';
            }
            else {
                li_html = '<img src="themes/en/default/images/arrow.png" class="" style="position:absolute; margin-top:5px;" id="' + prefix + res.path + '/' + res.name + '" onclick="' + 'javascript:hpicker_'+rand+'.click(\'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';"/>';
                li_html = li_html + '<a  class="' + nodeclass + '" ondblclick="' + 'javascript:hpicker_'+rand+'.click(\'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';" onclick="' + 'javascript:hpicker_'+rand+'.select_kid(event, \'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\');" onkeydown="' + 'javascript:hpicker_'+rand+'.get_key(event, \'' + prefix + res.path + '/' + res.name + '\', \'' + res.id + '\')' + ';" onmouseout="javascript:this.className = this.parentNode.className;" onmouseover="javascript:this.className = this.parentNode.className + \' onhover\';" onblur="javascript:this.className = this.parentNode.className;" onfocus="javascript:this.className = this.parentNode.className + \' onhover\';" tabindex="0">'+ res.name +'</a>';
            }

            li.innerHTML = li_html;
            ul.appendChild(li);

        }
    };

    this.select_checkbox = function(xname) {
        var checkboxes = eval("document.main." + xname);
        var val=[];
        for(var temp=0; temp<checkboxes.length; temp++){
            if(checkboxes[temp].checked){
                val.push(checkboxes[temp].value);
            }
        }
        val.join();
        var fld = document.main.elements[this.fieldname];
        fld.value = val;
    };

    if(this.fieldname && this.display_method.match("path_picker")){
        var obj = document.getElementById(this.fieldname_selected_text);
        if(obj.getElementsByTagName("select")[0]){
            this.setOnChangeEvent(this.fieldname_selected_text);
        }
    }
}

Hobjectpicker.prototype = new Control();
Hobjectpicker.prototype.constructor = Hobjectpicker;

function Imagestrip_picker(random, blocks, fname, wl_args)
{
	var _this = this;
	/* For Image Picker Control - Start */
	//var opacitySpeed = 2;   // Speed of opacity - switching between large images - Lower = faster
	//var opacitySteps = 10;  // Also speed of opacity - Higher = faster
	
	this.wl_name = fname;
	this.columnsOfThumbnails = blocks;  // number of thumbnail columns
	var rand = random;
    this.showArrow = true;
	/* Don't change anything below here */
	var is_largeImage = false;
	var is_imageToShow = false;
	var is_currentOpacity = 100;
	var currentUnqiueOpacityId = false;
	this.is_slideWidth = false;
	this.is_thumbTotalWidth = false;
	this.is_viewableWidth = false;
	this.is_thumbDiv = false;
	this.is_thumbSlideInProgress = false;
	this.leftArrowObj = null;
	this.rightArrowObj = null;
	this.thumbsColIndex = 1;
	this.r_length = null;
    this.radio_btn_Name = null;
	this.render_area = document.getElementById('layout'+rand);

	this.initGalleryScript = function(){
        if(_this.r_btn.length == 0) {  return;  };

		_this.striperHtml();
		var is_currentActiveImage = false;
       	_this.leftArrowObj = document.getElementById('is_leftArrow'+rand);
		_this.leftArrowObj.style.cssText = 'visibility:hidden; float:left;';
        _this.rightArrowObj = document.getElementById('is_rightArrow'+rand);
        _this.leftArrowObj.onclick = _this.moveThumbnails;
        _this.rightArrowObj.onclick = _this.moveThumbnails;
        var innerDiv = document.getElementById('is_thumbs_inner'+rand);
        _this.is_slideWidth = innerDiv.getElementsByTagName('div')[0].offsetWidth;
        _this.is_thumbDiv = document.getElementById('is_thumbs_inner'+rand);
       	_this.is_thumbDiv.style.cssText = 'left:0px';
        var subDivs = _this.is_thumbDiv.getElementsByTagName('div');
        _this.is_thumbTotalWidth = 0;
        var tmpLeft = 0;
        for(var no=0;no<subDivs.length;no++){
            if(subDivs[no].className=='image-strip-thumbnail-groups'){
	            _this.is_thumbTotalWidth = _this.is_thumbTotalWidth + _this.is_slideWidth;
        	    subDivs[no].style.left = tmpLeft + 'px';
                subDivs[no].style.cssText = 'top:0px';
                tmpLeft = tmpLeft + subDivs[no].offsetWidth;
	        }
	    }
        _this.is_viewableWidth = document.getElementById('is_thumbs'+rand).offsetWidth;
	    is_currentActiveImage.className='activeImage';
	};

    this.moveThumbnails = function(){
        var slideSteps = 8;     // Also speed of thumbnail slide - Higher = faster
        if(_this.is_thumbSlideInProgress)return;
        _this.is_thumbSlideInProgress = true;
        if(this.id=='is_leftArrow'+rand){
            _this.thumbsColIndex--;
            _this.rightArrowObj.style.cssText = 'visibility:visible; float:right';
            if(_this.is_thumbDiv.style.left.replace('px','')/1>=0){
                _this.leftArrowObj.style.cssText = 'visibility:hidden; float:left';
                _this.is_thumbSlideInProgress = false;
                return;
            }
            _this.slideThumbs(slideSteps,0);
        }else{
            _this.thumbsColIndex++;
            _this.leftArrowObj.style.cssText = 'visibility:visible; float:left;';
            var left = _this.is_thumbDiv.style.left.replace('px','')/1;
            if(_this.is_thumbTotalWidth + left - _this.is_slideWidth <= _this.is_viewableWidth)_this.showArrow = false;
            if(_this.columnsOfThumbnails)_this.showArrow = true;
            if(!_this.showArrow){
                _this.rightArrowObj.style.cssText = 'visibility:hidden; float:right;';
                _this.is_thumbSlideInProgress = false;
                return;
            }
            _this.slideThumbs((slideSteps*-1),0);
        }
    };

    this.slideThumbs = function(speed,currentPos){
        var leftPos;
		var thumbsLeftPos = false;
		var slideSpeed = 5;     // Speed of thumbnail slide - Lower = faster
        if(thumbsLeftPos){
            leftPos= thumbsLeftPos;
        }else{
            var leftPos = _this.is_thumbDiv.style.left.replace('px','')/1;
            thumbsLeftPos = leftPos;
        }
        currentPos = currentPos + Math.abs(speed);
        var tmpLeftPos = leftPos;
        leftPos = leftPos + speed;
        thumbsLeftPos = leftPos;
        _this.is_thumbDiv.style.left = leftPos + 'px';
        if(currentPos < _this.is_slideWidth)setTimeout('striper_'+rand+'.slideThumbs(' + speed + ',' + currentPos + ')',slideSpeed);
        else{
            if(tmpLeftPos>=0 || (_this.columnsOfThumbnails && _this.thumbsColIndex==1)){
                document.getElementById('is_leftArrow'+rand).style.cssText = 'visibility:hidden; float:left;';
            }
            var left = tmpLeftPos;
            if(_this.is_thumbTotalWidth + left - _this.is_slideWidth <= _this.is_viewableWidth)_this.showArrow=false;
            if(_this.columnsOfThumbnails){
                if((_this.thumbsColIndex+1)<_this.columnsOfThumbnails)_this.showArrow=true; else _this.showArrow = false;
            }
            if(!_this.showArrow){
                document.getElementById('is_rightArrow'+rand).style.cssText = 'visibility:hidden; float:right;';
            }
            _this.is_thumbSlideInProgress = false;
        }
    };

    this.striperHtml = function(){
        var b_container = document.getElementById('is_thumbs_inner'+rand);
        if (b_container==null) {
            return;
        }
		var img_tags = b_container.getElementsByTagName('img');
		var t=0;
        while (t < img_tags.length){
            img_tags[t].setAttribute((document.all ? 'className' : 'class'),'image-strip-imgThumb');
			t++;
        }
    };

    this.r_btn = document.getElementsByName('select_btn'+rand);
    
    this.is_unconstrained = function() {
        var result = true;
       	if (!(_this.constraint_fields)) {
            return false;
       	}
       	for (var i=0; i<this.constraint_fields.length; i++) {
            var cname = this.constraint_fields[i];
            var cfield = document.getElementById(cname);
			var cvalue = cfield.value;
            if (cvalue > 0) {
                result = false;
               	break;
            }
        }
       	return result;
    };
    
    this.recalc = function(cfield_name,cbox_name, c) {
        // trying to figureout value of textbox 
        var cval = null;  
		if (cbox_name !=null ){
            var cboxes = document.getElementsByName(cbox_name);
            for(var cx=0;cx<cboxes.length;cx++) {
                if (cboxes[cx].checked==true) {
  		            cval = cboxes[cx].value;
                }   
            }
            if (cval) {
                document.getElementById(cfield_name).value = cval;
            } 
        }else {
            cbox_name = null;
            cval = null;
        }
        
        var counter = 0;
        var optstring = '';
		
		if(!cval){
			_this.CreateContent(cfield_name,cval, c);
		}else{
			_this.hideShow(cfield_name,cval);
		}
    };

	this.hideShow = function(cfield_name,cval){
        var flag = false;
        var divs;
        if ( cfield_name ) {
            divs = document.getElementsByName(cfield_name + "_" + cval);
        } else {
            divs = document.getElementsByName("small_divs_"+rand);
        }

        for(a=0; a<divs.length; a++) {
            divs[a].setAttribute((document.all ? 'className' : 'class'),'image-strip-selDivs');
        }

        for (var i=0; i < _this.cdata.length; i++) {
            var cfield_value = _this.cdata[i][1][cfield_name];
            var unseldivs = document.getElementsByName(cfield_name + "_" + cfield_value);
	        for(a=0; a<unseldivs.length; a++) {
                if ( cfield_value == cval ) {
                    continue;
                }else {
                    unseldivs[a].setAttribute((document.all ? 'className' : 'class'),'image-strip-unseldivs');
                }
            }
        }
    };

    
    this.CreateContent = function (cfield_name,cval,c){
		var test = null;
		var count = 0;
		var row = _this.cdata.length;

		var mainC = document.getElementById('layout'+rand);
		var header = document.createElement("div");

		header.setAttribute((document.all ? 'className' : 'class'),'image-strip-header');

		var arrowC = document.createElement("div");
		arrowC.setAttribute((document.all ? 'className' : 'class'),'is_arrow');

		var left_arrow = document.createElement("a");
		left_arrow.id='is_leftArrow'+rand;
        left_arrow.style.cssText = 'float:left; margin:0px; visibility:hidden;';
		left_arrow.innerHTML = 'Prev';
		
		var right_arrow = document.createElement("a");
		right_arrow.id='is_rightArrow'+rand;
		right_arrow.setAttribute((document.all ? 'className' : 'class'),'image-strip-right-Arrow');
		right_arrow.innerHTML = 'Next';

		var cls1 = document.createElement("div");
		cls1.setAttribute((document.all ? 'className' : 'class'),'cls');

		header.appendChild(arrowC);
		header.appendChild(left_arrow);
		header.appendChild(right_arrow);
		header.appendChild(cls1);

		mainC.appendChild(header);
		
		var thumb_div = document.createElement("div");
		thumb_div.id='is_thumbs'+rand;
		thumb_div.setAttribute((document.all ? 'className' : 'class'),'image-strip-thumbs-container');

		var thumb_div_inner = document.createElement("div");
		thumb_div_inner.id='is_thumbs_inner'+rand;
		thumb_div_inner.setAttribute((document.all ? 'className' : 'class'),'image-strip-thumbs-inner-container');

		thumb_div.appendChild(thumb_div_inner);
		mainC.appendChild(thumb_div);

		while (row > 0) {
			var strip_thumb = document.createElement("div");
			strip_thumb.setAttribute((document.all ? 'className' : 'class'),'image-strip-thumbnail-groups');
			for (var i=count; i < _this.cdata.length; i++) {
				var imgSrc = _this.cdata[i][1].image;
				var radioValue = _this.cdata[i][1].id;
				var radioName = _this.cdata[i][1].name;
				var radioText = _this.cdata[i][1].description;

                _this.radio_btn_Name = _this.cdata[i][1].name;
                
                var cfield_value = _this.cdata[i][1][c];
				var strip_thumb_data = document.createElement("div");
				strip_thumb_data.style.cssText="float:left";
				strip_thumb_data.setAttribute((document.all ? 'className' : 'class'),'image-strip-selDivs');
                    if (c) {
                        strip_thumb_data.setAttribute("name",c + "_" + cfield_value);
                    }
                    else {
                        strip_thumb_data.setAttribute("name","small_divs_"+rand);
                    }
				if(c){
					strip_thumb_data.setAttribute((document.all ? 'className' : 'class'),'image-strip-hide-thumbs');
				}else{
					strip_thumb_data.setAttribute((document.all ? 'className' : 'class'),'image-strip-visible-thumbs');
				}

				var img_src = document.createElement("img");
				img_src.src=imgSrc;
				img_src.style.cssText = 'display:block';

				var radio_btn = document.createElement(document.all?'<input name=select_btn'+rand+'>':'input');
				radio_btn.type='radio';
				radio_btn.name='select_btn'+rand;
				radio_btn.id='select_btn'+rand;
				radio_btn.setAttribute((document.all ? 'className' : 'class'),'image-strip-radio-btn');
				radio_btn.value=radioValue;
                radio_btn.setAttribute('radioName',radioName);
                if(radioValue==1){
                    radio_btn.checked='checked';
                    document.getElementById(_this.wl_name).value='1';
                }
				var name_cont = document.createElement("div");
				name_cont.setAttribute((document.all ? 'className' : 'class'),'image-strip-radio-name');
				name_cont.innerHTML = radioText;

				var cls = document.createElement("div");
				cls.setAttribute((document.all ? 'className' : 'class'),'cls');
	
				strip_thumb_data.appendChild(img_src);
				strip_thumb_data.appendChild(radio_btn);
				strip_thumb_data.appendChild(name_cont);
				strip_thumb_data.appendChild(cls);
			
				strip_thumb.appendChild(strip_thumb_data);

				count = count + 1;
				if(count == _this.columnsOfThumbnails){
					break;
				}	
			}
			thumb_div_inner.appendChild(strip_thumb);
            row=row-_this.columnsOfThumbnails;
/*			if(test>1){
                row=0
            }
			else{row=row-_this.columnsOfThumbnails;}*/
		}	
        if (wl_args.onclick){
            var callback = wl_args.onclick;
            var hField = wl_args.name;
            var hxField = document.getElementById(hField);
            var hxField_rand_string = hxField.getAttribute('random_string');
            var hbox_name = 'select_btn' + hxField_rand_string;
            var hxField_name = hxField.name;
            var hboxes = document.getElementsByName(hbox_name);
            for(var hx = 0; hx<hboxes.length; hx++){
                var fl_name = hboxes[hx].getAttribute('radioname');
                if(this.value && this.value==hboxes[hx].value){
                    hboxes[hx].checked=true;
                }
                var onRadioClick = function() {
                    callback.call(null, hboxes);
                };
                this.createEventListener(hboxes[hx], 'onclick', onRadioClick , true);
            }
        }
    };

   	if (fname) {
       	this.form_field = document.getElementById(fname);
       	this.cforce_selection = parseInt(wl_args.force_selection);
       	this.cnull_option = parseInt(wl_args.null_option);
       	this.cnull_option_display_name = wl_args.null_option_display_name;
       	this.cis_filter = parseInt(wl_args.is_filter);

       	if (wl_args.style_string) {
       		this.form_field.style.cssText = wl_args.style_string;
       	}

       	if (wl_args.data) {
      		this.cdata = JSON.parse(wl_args.data);
       	}

       	this.cvalue = parseInt(wl_args.value);
        
       	if (wl_args.constraints) { 
       		this.constraint_fields = JSON.parse(wl_args.constraints);
       		for(var i=0; i<this.constraint_fields.length; i++) {
                var c = this.constraint_fields[i];
                var cxfield = document.getElementById(c);
                var cxfield_random_string = cxfield.getAttribute('random_string');
                var cbox_name = 'select_btn' + cxfield_random_string;
                var cxfield_name = cxfield.name;
                var cxform_field_name = this.form_field.name;
                var cboxes = document.getElementsByName(cbox_name);
                for(var cx=0;cx<cboxes.length;cx++) {
                    this.createEventListener( cboxes[cx], 'onclick',function() { _this.recalc(cxfield_name,cbox_name, c);}  , true);
                }
           	}
        }
       
        if(wl_args.value){
            for (var i=0; i < _this.cdata.length; i++) {
                if(_this.cdata[i][1].id==wl_args.value){
                    this.radioName = _this.cdata[i][1].name;
                }
            }
            this.value = wl_args.value;
        }

       this.recalc(null, null, c);

       document.addOnLoadFunction( function() { if (_this.is_unconstrained()) {
		_this.form_field.setAttribute('disabled', true);
        }});
    }
//  Image Striper Code end 

	this.create = function(random, blocks, fname, wl_args) {
		return new Imagestrip_picker(random, blocks, fname, wl_args);
    };
}

Imagestrip_picker.prototype = new Control();
Imagestrip_picker.prototype.constructor = Imagestrip_picker;
function  Language()
{
	var _this = this;
        this.pphText=null;
        this.y = 2;

	this.indicChangePos =function()
	{
        	document.getElementById("indicimelayer").style.top=(document.all?document.documentElement.scrollTop:window.pageYOffset)+_this.y+"px";
	}

	this.indicChange = function(id, script)
	{
		this.pphText.setGlobalScript(script);
	}

 	this.initialize = function()
	{
                if (document.getElementById("language") == null )  {
		    this.lang= "english"; 
                } 
                else {
                    this.lang = document.getElementById('language').options[document.getElementById('language').selectedIndex].value ;
                }
                this.pphText  = new fontHandler();
                this.pphText.convertPageToIndicIME(this.lang, this.indicChange);
        }

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('V 1Y(){M t=V(b){J(14 b==\'15\'){b=\'1Z\'}N{b=b.1b()}M c=b;M d={};M e={};M f=0;M g=Q;T.2P=V(){X g};T.20=V(a){X d[a]};T.1h=V(a){X e[a]};M h=V(){K d["69"];K d["79"];K e["69"];K e["79"];K d["1z"];e["2Q"]="\\4l";e["2i"]="\\4m";d["89"]="\\4n";d["21"]="\\4o";d["2j"]=d["22"];d["2k"]=d["22"];K e["1v"];K e["1i"];K e["1j"]};M j=V(){g=W;K e["1M"];K d["1G"];K d["1v"];d["69"]="\\4p";d["1r"]="\\4q";d["79"]="\\4r";d["1s"]="\\4s";d["2R"]=d["23"];d["2S"]=d["23"];d["2T"]=d["23"];K d["2U"];K d["24"];d["2V"]=d["84"];d["68"]=d["84"];d["2W"]=d["84"];d["78"]="\\4t";d["2X"]=d["25"];d["2Y"]=d["25"];d["2Z"]=d["25"];d["4u"]="\\4v";d["30"]="\\4w";d["31"]="\\4x\\4y";d["33"]=d["26"];d["22"]=d["26"];d["34"]=d["26"];d["1T"]="\\4z";d["39"]="\\4A";d["3a"]="\\2l";d["83"]="\\2l";K d["2m"];K d["4B"];K e["1G"];K e["1v"];K e["1i"];K e["1j"];K d["1i"];K d["1j"];e["69"]="\\4C";e["1r"]="\\4D";e["79"]="\\4E";e["1s"]="\\4F";K e["42"];K d["38"];K d["1z"];d["4G"]="\\4H";d["4I"]="\\4J";d["4K"]="\\4L";d["48"]="\\4M";d["2m"]="\\4N\\4O\\2l"};M k=V(){g=W;d["1T"]="\\4P";K e["42"];K d["1z"];K d["38"];e["21"]="\\4Q";e["2Q"]="\\4R";K e["1i"];K e["1j"];d["69"]="\\4S";d["1r"]="\\4T";d["79"]="\\4U";d["1s"]="\\4V";e["69"]="\\4W";e["1r"]="\\4X";e["79"]="\\4Y";e["1s"]="\\4Z"};M l=V(){K e["1M"];K d["38"];K e["58"];K e["72"];K d["1G"];K d["1v"];K d["1i"];K d["1j"];K e["1G"];K e["1v"];K e["1i"];K e["1j"];K d["69"];K d["79"];K d["76"];K d["3b"];K e["1G"];K e["1v"];K e["69"];K e["79"];K d["3c"];d["1z"]="\\59";d["1T"]="\\5a";e["1M"]="\\5b";e["5c"]="\\5d";d["5e"]="\\5f";d["5g"]="\\5h"};M m=V(){g=W;K e["1M"];d["69"]="\\5i";d["1r"]="\\5j";d["79"]="\\5k";d["1s"]="\\5l";d["1T"]="\\5m";d["5n"]="\\5o";K e["42"];K d["38"];K e["1v"];e["69"]="\\5p";e["1r"]="\\5q";e["79"]="\\5r";e["1s"]="\\5s";e["2i"]="\\5t";K e["1i"];K e["1j"];K d["1z"]};M n=V(){g=W;K e["1M"];d["69"]="\\5u";d["1r"]="\\5v";d["79"]="\\5w";d["1s"]="\\5x";d["5y"]="\\5z";K e["42"];K d["38"];e["69"]="\\5A";e["1r"]="\\5B";e["79"]="\\5C";e["1s"]="\\5D";d["70"]="\\3d";d["39"]="\\3d";K e["1i"];K e["1j"];K d["1z"]};M o=V(){K d["69"];K d["79"];d["1T"]="\\5E";d["2j"]="\\3e";d["2k"]="\\3e";d["5F"]="\\5G";K e["69"];K e["79"];e["2i"]="\\5H";K d["1z"];d["21"]="\\5I";d["76"]=d["3f"]};M p=V(){K d["1j"];K d["1i"];K e["1j"];K e["1i"]};M q=V(){d["3g"]="\\5J";d["3h"]="\\5K";e["3g"]="\\5L";e["3h"]="\\5M";e["36"]="\\5N";e["5O"]="\\5P";e["35"]="\\5Q";e["5R"]="\\5S";d["64"]="\\5T"};M r=V(){g=Q;M a=1,1c,1A="";1m(1c 1N d){K d[1c]}1m(1c 1N e){K e[1c]}e["1M"]="\\5U";e["77"]="\\5V";e["58"]="\\3i";e["72"]="\\3i";d["27"]="\\5W";d["65"]="\\3j";d["3k"]="\\3j";d["3l"]="\\5X";d["73"]="\\3m";d["3n"]="\\3m";d["3o"]="\\5Y";d["85"]="\\3p";d["3q"]="\\3p";d["1G"]="\\5Z";d["1i"]="\\60";d["69"]="\\61";d["1r"]="\\62";d["3r"]="\\63";d["79"]="\\66";d["1s"]="\\67";d["3s"]="\\3t";d["3u"]="\\3t";d["23"]="\\3v";d["2R"]="\\6a";d["2S"]="\\6b";d["2T"]="\\6c";d["6d"]="\\6e";d["6f"]="\\6g";d["2U"]="\\6h";d["6i"]="\\3w";d["24"]="\\6j";d["6k"]="\\3x";d["84"]="\\6l";d["2V"]="\\6m";d["68"]="\\6n";d["2W"]="\\6o";d["78"]="\\6p";d["25"]="\\6q";d["2X"]="\\6r";d["2Y"]="\\6s";d["2Z"]="\\6t";d["30"]="\\6u";d["26"]="\\6v";d["31"]="\\3y";d["33"]="\\3y";d["22"]="\\6w";d["34"]="\\6x";d["6y"]="\\6z";d["6A"]="\\6B";d["6C"]="\\3z";d["82"]="\\3z";d["3f"]="\\6D";d["76"]="\\6E";d["2j"]="\\3A";d["2k"]="\\3A";d["3a"]="\\3B";d["83"]="\\3B";d["3b"]="\\3C";d["6F"]="\\6G";d["6H"]="\\6I";d["2m"]="\\3v\\2n\\3C";d["3c"]="\\3w\\2n\\3x";e["42"]="\\6J";d["38"]="\\6K";e["3k"]="\\3D";e["65"]="\\3D";e["3l"]="\\6L";e["73"]="\\3E";e["3n"]="\\3E";e["3o"]="\\6M";e["85"]="\\3F";e["3q"]="\\3F";e["1G"]="\\6N";e["1v"]="\\6O";e["69"]="\\6P";e["1r"]="\\6Q";e["3r"]="\\6R";e["79"]="\\6S";e["1s"]="\\6T";e["3s"]="\\3G";e["3u"]="\\3G";e[a]="\\2n";d["1z"]="\\6U";d["1v"]="\\6V";d["1j"]="\\6W";e["1i"]="\\6X";e["1j"]="\\6Y";d["48"]="\\6Z";d["49"]="\\71";d["50"]="\\74";d["51"]="\\75";d["52"]="\\7a";d["53"]="\\7b";d["54"]="\\7c";d["55"]="\\7d";d["56"]="\\7e";d["57"]="\\7f";M i=0;1m(1c 1N d){1A="";1m(i=0;i<d[1c].1g;i++){1A=1A+1U.1V((d[1c]).2o(i)+f)}d[1c]=1A}1m(1c 1N e){1A="";1m(i=0;i<e[1c].1g;i++){1A=1A+1U.1V((e[1c]).2o(i)+f)}e[1c]=1U.1V((e[1c]).2o(0)+f)}e["27"]="";d["3H"]="\\7g";d["7h"]="\\7i";d["7j"]="\\7k";d["3I"]="\\7l"};T.1O=V(a){c=a.1b();2p(a.1b()){S"2q":f=7m;Y;S"2r":f=7n;Y;S"1Z":f=0;Y;S"2s":f=7o;Y;S"2t":f=7p;Y;S"2u":f=7q;Y;S"2v":f=7r;Y;S"2w":f=7s;Y;S"2x":f=7t;Y}r();2p(a.1b()){S"2r":p();Y;S"1Z":q();Y;S"2s":m();Y;S"2t":l();Y;S"2u":k();Y;S"2v":n();Y;S"2q":o();Y;S"2w":j();Y;S"2x":h();Y}};T.1O(c)};M u=V(){T.Z=32;T.11=Q;T.1B=Q;T.28="";T.1d=Q;T.1e=Q;T.3J=Q;T.1P="1H";T.1n=Q;T.19={};T.1k=0;T.P=""};M v=[];M w=1;M x=7u,2y=x.7v;M y=(/7w/3K).2z(2y)&&(/7x/3K).2z(x.7y);M z=/7z/.2z(2y);M A=7A;M B={};M C=[];M D=Q;M E="7B";T.7C=V(a){A=a};T.7D=V(a){M b=v[a];X(14 b==\'15\')||b.1B?"1H":b.1P};T.1O=V(a,b){M c=v[a];J(14 c==\'15\'){X}J(b){b=b.1b()}J(b&&(b==\'2q\'||b==\'2r\'||b==\'1Z\'||b==\'2s\'||b==\'2t\'||b==\'2u\'||b==\'2v\'||b==\'2w\'||b==\'2x\')){c.1P=b;J(14 B[b]==\'15\'){B[b]=3L t(b)}c.16=B[b];c.1B=Q}N{c.1B=W}};T.7E=V(a){J(!a){a=\'1H\'}J(D){T.1O(E,a)}N{M i;1m(i 1N v){T.1O(i,a)}}};T.2A=V(a,b){J(!b||(14 b!=\'V\')){2B"1Y.2A(): 7F V 3M 3N 3O";}M c=v[a];c.28=b};T.29=V(a){M b=a;b.Z=32;b.11=Q;b.1d=Q;b.1e=Q;b.3J=Q};T.3P=V(a,b){M c=a;M d=0,P=\'\',17=\'\',1w=\'\',1I=\'\',1o=\'\',1x=\'\',1y=Q,1C=\'\';M e=Q,1J=Q,1K=Q,1Q=Q,1f=Q,10=Q,1L=Q,18=Q;c.P=\'\';c.1k=0;17=1U.1V(b);1C=1U.1V(c.Z);1w=c.16.20(c.Z.1a()+b.1a());1I=c.16.1h(c.Z.1a()+b.1a());1o=c.16.20(b.1a());1x=c.16.1h(b.1a());e=(14(1o)!=\'15\');1J=(14(1x)!=\'15\');1K=(14(1w)!=\'15\');1Q=(14(1I)!=\'15\');1f=c.16.2P();10=c.1d;1L=c.1e;18=c.11;2p(17){S"a":S"e":S"i":S"o":S"u":S"A":S"I":S"U":S"O":S"E":S"R":J(10&&!18){J(1f&&17!=\'R\'){d--}P=(!1J)?\'\':1x;J(1C==\'L\'){J(17==\'u\'){b=13}N J(17==\'U\'){b=12}N c.1e=10}N{c.1e=10}c.11=(P==\'\')}N J(1Q&&1L){J(1C!=\'a\'&&(!18||1f)){d--}P=1I;b=32;c.1e=10;c.11=Q}N J(1K){J(1f&&1C==\'R\'&&(17==\'u\'||17==\'U\')){d--}d--;P=1w;b=32;c.1e=10;c.11=Q}N J(e){J(17==\'R\'){J(1f){P=1o+c.16.1h(w)}N{P=(10&&!18?c.16.1h(w):\'\')+1o}}N{P=1o}c.1e=10;c.11=Q}N{c.1e=10;c.11=W}c.1d=Q;Y;S\'^\':J(!10&&1C!="^"){17=\'\'}N J(1K){d--;P=1w}N{P=(1f?\'\':c.16.1h(w))+1o}c.1e=10;c.1d=Q;c.11=(P==\'\');Y;S\' \':1y=W;J(!1f){17=\'\'}c.1e=10;c.1d=Q;c.11=Q;Y;S\'~\':J(c.Z==21||c.Z==35||c.Z==36||c.Z==38||c.Z==42||c.Z==64||c.Z==58||c.Z==3H){J(14 c.16.1h(c.Z.1a())!=\'15\'||14 c.16.20(c.Z.1a())!=\'15\'){d--;P=1C}N{P=17.1a()}b=32}N J(c.Z==3I){J(!18){d--;J(!1f){d--}}P=1C;b=32}N J((1L||c.Z==77||c.Z==78)&&1Q){J(c.Z==78&&1L){d--}N J(c.Z==13||c.Z==12){d-=2}d--;P=1I;b=32}N J(1K){J(c.Z==13||c.Z==12){d--}J(!18){d--}P=1w;b=32}N J(e){P=1o}N J(1J){J(10&&1f){d--}P=1x}N{P=17.1a()}c.1e=10;c.1d=Q;c.11=Q;Y;S\':\':S\'^\':S\'H\':S\'|\':S\'@\':S\'0\':S\'1\':S\'2\':S\'3\':S\'4\':S\'5\':S\'6\':S\'7\':S\'8\':S\'9\':S\'&\':J(1L&&1Q){d--;P=1I;b=32}N J(1K){J(!18){d--}P=1w;b=32}N{P=e?1o:1J?1x:(b>=65&&b<=3Q||b>=27&&b<=24)?\'\':17.1a()}c.1e=10;c.1d=Q;c.11=Q;Y;S\'*\':J(1J&&10&&!18){J(1f){d--;P=1x+c.16.1h(w)}N{P=1x}}N{P=17.1a()}c.11=Q;Y;7G:c.1e=10;J(1K){J(1f){d=18?0:d-2;P=1w+c.16.1h(w)}N{d=(!18)?d-1:0;P=(18&&10&&1L?c.16.1h(w):\'\')+1w}c.1d=W;c.11=Q}N J(e){J(1f){P=1o+c.16.1h(w)}N{P=(10&&!18?c.16.1h(w):\'\')+1o}c.1d=W;c.11=18?Q:18}N J(1Q){d--;P=1I;c.11=Q;c.1d=Q;b=32}N J(1J){J(10){d=18&&!1f?d-1:0}P=1x;c.11=Q;c.1d=Q}N J((b>=27&&b<=24)||(b>=65&&b<=3Q)){c.1d=W;c.11=W}N{P=17.1a();c.1d=Q;c.11=Q}}c.Z=b;c.1k=d;c.P=P;X 1y};T.3R=V(a,b){M c=D?v[E]:v[a],1t=y?b.1t:b.3S,1p;J(14 c==\'15\'){X W}J(D){M d=b.1D?b.1D:b.2a;J((d.1W.1b()=="3T"&&d.3U.1b()=="P")||d.1W.1b()=="3V"){1p=d;c.1n=Q}N J(d.1E.2b&&d.1E.2b.1b()=="3W"){c.1n=W;1p=d.1E}N{X W}J(c.19!=1p){c.19=1p;T.29(c)}J(C[1p.1l]||C[1p.2C]){X W}}J((1t==46)&&z&&c.1n){J(c.19.1u){1p=c.19.1u}N J(c.19.2c){1p=c.19.2c}M s=1p.2D(),r=s.2E(0);J(1p.1q.3X.2d.1g==1&&r.2F.2e&&r.2G==0){b.2H();b.2I();X Q}}N J(1t==A){J(c.1P!=\'1H\'){c.1B=!c.1B}J(c.28){c.28(a,c.1B?"1H":c.1P)}}N J((1t>=37&&1t<=40)||1t==46||1t==8||1t==13){T.29(c)}X W};T.3Y=V(a,b){M c=D?v[E]:v[a],1y=Q;J(14 c==\'15\'||c.1B){X W}M d=c.19;M e=0,s,r,P=\'\',1k=0;J(b.7H||b.7I){X W}e=y?b.1t:b.3S;J((e<32)||(e>=7J)){X W}J(D){M f=b.1D?b.1D:b.2a;J((f.1W.1b()=="3T"&&f.3U.1b()=="P")||f.1W.1b()=="3V"){d=f;c.1n=Q}N J(f.1E.2b&&f.1E.2b.1b()=="3W"){c.1n=W;d=f.1E}N{X W}J(c.19!=d){c.19=d;T.29(c)}J(C[d.1l]||C[d.2C]){X W}}J(c.1n){d=(D&&d.1l?v[d.1l].19:d);J(d.1u){d=d.1u}N J(d.2c){d=d.2c}}J(z&&(e==8||e==45)&&c.1n){s=d.2D();r=s.2E(0);J(r.2F==d.1q.3X.7K&&r.2G==0){b.2H();b.2I();X Q}}1y=T.3P(c,e);P=c.P;1k=c.1k;J(y){M g=d.1q?d.1q:d;r=g.7L.2J();r.7M(\'7N\',1k);r.P=(r.P.7O(r.P.1g-1)==\' \'?P+\' \':P);r.7P(W);r.7Q();b.1y=1y;b.7R=W}N{J(c.1n){M h,1F,2K="",2L="";s=d.2D();J(d.1q){d=d.1q}J(14(s)!=\'15\'){r=s.2E(0)}N{r=d.2J()}h=r.2F;1F=r.2G;J(h.7S==3){2K=h.2e.2f(0,1F+1k);2L=h.2e.2f(1F)}N{M i=d.7T(P);J(h.2d.1g>0&&h.2d[1F].1W=="7U"){h.7V(i,h.2d[1F])}N{h.7W(i)}h=i;1F=0}h.2e=(2K+P.1a()+2L.1a());r=d.2J();M j=1F+1k+P.1g;J(j<0){j=0}r.7X(h,j);r.7Y(h,j);s.7Z();s.80(r)}N{M k=d.3Z,41=d.43,44=d.47;J(14(P)!=\'15\'&&(P.1g!=0||1k!=0)){d.1X=d.1X.2f(0,d.3Z+1k)+P+d.1X.2f(d.81,d.1X.1g);k=k+P.1g+1k;J(k<0){k=0}d.86(k,k);d.43=41;d.47=44}}J(!1y){b.2H();b.2I()}}X 1y};T.2M=V(a,b){M c=v[a];J(y&&c.19.1u){X c.19.1u.2N}N{X(4a.2N)?4a.2N:b}};M F=V(a){X v[a].19};M G=V(b,c,d){J(!c.1R){c.1R=V(e){M a=(e.1D?e.1D:e.2a);a=(a.1l?a.1l:a.1E.1l);e=c.2M(a,e);X c.3Y(a,e)}}J(!c.1S){c.1S=V(e){M a=(e.1D?e.1D:e.2a);a=(a.1l?a.1l:a.1E.1l);e=c.2M(a,e);X c.3R(a,e)}}M f=F(b);J(f.1u){f=f.1u.1q}N J(f.4b){f=f.4b}J(!z){J(d){f.4c("4d",c.1R);f.4c("4e",c.1S)}N{f.4f("4d",c.1R);f.4f("4e",c.1S)}}N{J(d){f.4g("4h",c.1R,W);f.4g("4i",c.1S,W)}N{f.4j("4h",c.1R,W);f.4j("4i",c.1S,W)}}};T.2g=V(a,b,c,d){J(14 d==\'15\'||d==2O){d=W}J(!c){c=\'1H\'}J(!b){J(a){b=1q.87(a);J(y){M e=1q.88[a];J(e){J(e.1g){1m(M i=0;i<e.1g;i++){J(e[i].2C==a){b=e[i];Y}}}N{b=e}}N{b=2O}}J(!b){2B"1Y.2g(): 4k 3M 3N 3O";}}N{2B"1Y.2g(): 8a 1X 8b 1m 8c 4k 8d 8e";}}J(!a){a=\'8f\'+(v.1g)}v[a]=3L u();M f=v[a];f.1P=c.1b();f.19=b;f.1n=b.1u?W:Q;J(f.1n){b.1u.1q.1l=a}N{b.1l=a}T.1O(a,c);J(d){G(a,T,Q)}};T.8g=V(a,b,c,d){J(!a){a=\'1H\'}J(!c){c=""}J(14 d==\'15\'||d==2O){d=W}D=W;M e=c.8h(","),i=0,2h="";1m(;i<e.1g;i++){2h=e[i];J(2h!=""){C[2h]=W}}T.2g(E,1q,a,d);J(b){T.2A(E,b)}};T.8i=V(a){J(!a){X}G(a,T,W);K v[a]};T.8j=V(){J(!D){X}D=Q;G(E,T,W);K v[E];1m(M a 1N C){K C[a]}}};',62,516,'|||||||||||||||||||||||||||||||||||||||||||||if|delete||var|else||text|false||case|this||function|true|return|break|prevkey|pc|hidden|||typeof|undefined|il|keychar|hdn|elementObject|toString|toLowerCase|key|previousConsonant|previouspreviousConsonant|hls|length|getMod|13126|12126|displace|_indicId|for|isIFrame|base|element|document|101|111|keyCode|contentWindow|8285|bComb|mod|returnValue|7977|result|isEng|prevkeychar|target|ownerDocument|offset|82117|english|mComb|tmod|tbcomb|ppc|77126|in|setScript|language|tmcomb|kblistener|kbposition|114114|String|fromCharCode|nodeName|value|fontHandler|devanagari|getBase|126|98|107|122|116|112|97|callbackName|reset|srcElement|designMode|defaultView|childNodes|nodeValue|substring|convertToIndicIME|str|9785|118|119|u0bb7|120|u094d|charCodeAt|switch|bengali|gujarati|malayalam|gurmukhi|telugu|kannada|tamil|oriya|ua|test|onScriptChange|throw|id|getSelection|getRangeAt|startContainer|startOffset|preventDefault|stopPropagation|createRange|s1|s2|getEventObject|event|null|halfLetterScript|9773|107104|103|103104|67104|84104|68104|116104|100|100104|110|102||112104|98104|||||7676|115104|83104|71121|u0cde|u09f1|108|69126|79126|u0903|u0906|9797|105|u0908|101101|117|u090a|111111|97105|97117|u0914|111117|u0915|u091c|u091e|u092b|u0930|u0935|u0936|u0937|u093e|u0940|u0942|u094c|124|94|specialMode|gi|new|is|not|valid|getNext|90|keydownHandler|which|input|type|textarea|on|body|keypressHandler|selectionStart||st||scrollTop|sl|||scrollLeft|||window|contentDocument|detachEvent|onkeypress|onkeydown|attachEvent|removeEventListener|keypress|keydown|addEventListener|ElementName|u0b56|u0b57|u0b5f|u0b70|u0b8f|u0b8e|u0b93|u0b92|u0ba3|7878|u0ba8|u0ba9|u0b83|u0baa|u0bb1|u0bb4|74104|u0bc7|u0bc6|u0bcb|u0bca|4964|u0bf0|4938|u0bf1|49126|u0bf2|u0030|u0b95|u0bcd|u0c31|u0c55|u0c56|u0c0f|u0c0e|u0c13|u0c12|u0c47|u0c46|u0c4b|u0c4a||||||||||u0a74|u0a5c|u0a70|78126|u0a71|7382|u0a72|8582|u0a73|u0d0f|u0d0e|u0d13|u0d12|u0d31|122104|u0d34|u0d47|u0d46|u0d4b|u0d4a|u0d57|u0c8f|u0c8e|u0c93|u0c92|82114|u0cb1|u0cc7|u0cc6|u0ccb|u0cca|u09f0|116126|u09ce|u09d7|u09fa|u090e|u0912|u0946|u094a|u0951|3636|u0952|u0953|3535|u0954|u0970|u0901|u0902|u0905|u0907|u0909|u090b|u090c|u090d|u090f|u0910|||u0911|u0913|||u0916|u0917|u0918|7871|u0919|99104|u091a|u091b|106|u091d|7889|u091f|u0920|u0921|u0922|u0923|u0924|u0925|u0926|u0927|u0928|u092a|u092c|u092d|109|u092e|121|u092f|114|u0932|u0933|115|u0938|104|u0939|u093c|u093d|u093f|u0941|u0943|u0944|u0945|u0947|u0948|u0949|u094b|u0950|u0960|u0961|u0962|u0963|u0966||u0967|||u0968|u0969|||||u096a|u096b|u096c|u096d|u096e|u096f|u0964|124124|u0965|9494|u200c|u200d|128|384|1024|256|768|896|640|512|navigator|userAgent|MSIE|Explorer|appName|Gecko|123|_globalIndicIME|setToggleKey|getScript|setGlobalScript|Callback|default|altKey|ctrlKey|127|firstChild|selection|moveStart|character|charAt|collapse|select|cancelBubble|nodeType|createTextNode|BR|insertBefore|appendChild|setStart|setEnd|removeAllRanges|addRange|selectionEnd|||||setSelectionRange|getElementById|all||No|found|argument|or|ElementObject|indicime_|convertPageToIndicIME|split|convertToDefault|convertPageToDefault'.split('|'),0,{}));

        this.create = function() {
           return this;
        };
}
Language.prototype = new Control();
Language.prototype.constructor = Language;

/* Class Image Zoomer */

function Imagezoom(schema, table, column, row_id, zoomLoader, zoomContainerId) {

    this.enlargeImage = function() {
        var zoomContainer = document.getElementById(this.zoomContainerId);
        //zoomContainer.classname= zoomContainer;
        if(zoomContainer.style.display=="none")
        {  
            var ele = document.getElementsByTagName("div");
            for(var i = 0, length = ele.length; i < length; i++) {
                if(ele[i].getAttribute('name')=="zoomContainer"){
                   ele[i].style.display = 'none';
                }
            } 
            if (window.innerWidth && window.innerHeight) {
                this.win_height = window.innerHeight;
                this.win_width = window.innerWidth;
            }
            else {
                this.win_height = document.documentElement.offsetHeight;
                this.win_width = document.documentElement.offsetWidth;
            }

            /*if(window.pageYOffset) {
                this.top_pos = window.pageYOffset;
            }
            else {
                this.top_pos = document.documentElement.scrollTop;
            }*/
	
            var loadImg = document.getElementById(this.zoomLoader);
            loadImg.style.cssText="display:block;";
   	        this.requestZoomedImg();
        }
        else {
            this.togglezoomContainer();
        }                 
    };

    this.requestZoomedImg = function(){
    
        var href = window.location.href;
        href = href.substring(0,href.lastIndexOf('\/'));

        var req = new Object();
        req.method='GET';
        req.uri = href;
        req.async = false;
        req.params = [];
        req.params['client_type'] = 'json';
        req.params['schema'] = this.schema;
        req.params['table'] = this.table;
        req.params['column'] = this.column;
        req.params['row_id'] = this.row_id;
        req.params['win_height'] = this.win_height;
        req.params['win_width'] = this.win_width;
        req.params['objpath'] = 'domain/public/tables/images/forms/publist';
        req.params['action'] = 'get_resized_image';

        var callback =  Ngx.Odb.CommonUtil.createCallback.call(this, function(xhr) {
             var response = JSON.parse(xhr.responseText);
             this.showZoomedImg(response.image_url,response.height, response.width);
        });

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    };

    this.showZoomedImg = function(image_url,image_height, image_width) {

       if(!(image_url||image_height||image_width)){
           document.getElementById(this.zoomLoader).style.display="none";
           this.togglezoomContainer();
       }
       else{
          var zoomContainer = document.getElementById(this.zoomContainerId);
          var zoomedImg = zoomContainer.getElementsByTagName("img")[0];
 
          var pos_x = Math.abs((this.win_width-image_width)/2);       
          var pos_y = Math.abs((this.win_height-image_height)/2);
          //var pos_y = Math.abs(this.top_pos+((this.win_height-image_height)/2));
          document.getElementById(this.zoomLoader).style.display="none";
          zoomContainer.className  = "zoomContainer";
	  zoomContainer.style.cssText = "position:fixed; top:"+pos_y+"px; left:"+pos_x+"px;display:block";
          zoomedImg.src = image_url;
	  zoomContainer.focus();
       }
    };

    this.togglezoomContainer = function(){
        var zoomContainer = document.getElementById(this.zoomContainerId);
        zoomContainer.style.display="none";
        zoomContainer.style.src="";
    };

    this.closePicker = function(ev) {
 	var event_obj = window.event? event : ev;
        var key = event_obj.keyCode ? event_obj.keyCode : event_obj.charCode;
    	if (key == 27){
            this.togglezoomContainer();
    	}
    };

    if (zoomContainerId) {
       this.schema = schema; 
       this.table = table; 
       this.column = column;
       this.row_id = row_id;
       this.zoomLoader = zoomLoader;
       this.zoomContainerId = zoomContainerId;
       this.win_height = 0;
       this.win_width = 0;
       this.top_pos = 0;
    }

    this.create = function(schema, table, column, row_id, zoomLoader, zoomContainerId) {
        return new Imagezoom(schema, table, column, row_id, zoomLoader, zoomContainerId);
    };
}
Imagezoom.prototype = new Control();
Imagezoom.prototype.constructor = Imagezoom;
/* CLASS ImageSlideShow control */

function ImageSlideShow( div_id, params ) {

    this.startSlideShow = function(){
        //if browser does not support the image object, exit.
        if (!document.images){
            return;
        }
        var div_obj = document.getElementById(this.div_id);
        div_obj.getElementsByTagName("img")[0].src=this.image_collection["image"+this.step].src;
        if (this.step<this.img_names.length){
            this.step++;
        }
        else {
            this.step=1;
        }
        var func = 'slideShowObj_' + this.rand + '.startSlideShow()';
        setTimeout(func, this.delay);
    };

    this.slideLinks = function() {
        window.location = this.img_links[this.step -1];
    };

    if(div_id){
        this.params = params;
        this.div_id = div_id;
        var height = this.params.height || "200px";
        var width = this.params.width || "400px";
        this.img_names = null;
        this.img_links = null;
        if(this.params.img_names && this.params.img_names!=""){
            this.img_names = this.params.img_names.split(",");
        }
        if(this.params.img_links && this.params.img_links!=""){
            this.img_links = this.params.img_links.split(",");
        }
        this.delay = this.params.delay || 5000;
        this.rand = this.params.random;
        this.step = 1;

        this.image_collection = {};
        for(var r=1; r<=this.img_names.length; r++){
            this.image_collection[ "image" + r ] = new Image();
            this.image_collection[ "image" + r ].setAttribute("src", "cache/public/images/" + this.img_names[r-1]);
        } 
        var div_obj = document.getElementById(div_id);
        div_obj.style.cssText = "height: " + height + "; width: " + width + ";";
        div_obj.getElementsByTagName("img")[0].style.cssText = "height: " + height + "; width: " + width + ";";
    }

    this.create = function(div_id, params) {
        return new ImageSlideShow(div_id, params);
    };
    
}

ImageSlideShow.prototype = new Control();
ImageSlideShow.prototype.constructor = ImageSlideShow;
/* CLASS Accordion control */

function Accordion(accordionCount, params) { 

    this.defaultAccordionContent = function(accordionId) {
        var obj = document.getElementById(accordionId);
        obj.style.display="block";
        obj.style.height="200px";
        this.oldAccordion = obj;
    };

    this.showAccordionContent = function(accordionId) {
        var newAccordion = document.getElementById(accordionId);
        if(accordionId != this.oldAccordion.id){
            newAccordion.style.display="block";
            for(ev=10; ev<=200; ev=ev+10){
                newAccordion.style.height = ev + "px";
                this.oldAccordion.style.height = this.oldAccordion.offsetHeight - ev + "px";
            }
            this.oldAccordion.style.display="none";
            this.oldAccordion = newAccordion;
        }
    };

    this.create = function(accordionCount, params) {
        return new Accordion(accordionCount, params);
    };

    if(accordionCount){
        this.rand = params.random_no;
        var defaultAccordionId = params.defaultAccordionId ? params.defaultAccordionId : 1;
        this.defaultAccordionContent(defaultAccordionId);
    }
    
}

Accordion.prototype = new Control();
Accordion.prototype.constructor = Accordion;

function Users() {

     this.checkUser = function(callback, login_name) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        if (this.isEmail(login_name) == false) {
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id must be valid email id";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.login_name"] = login_name;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "check_user";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 

    this.checkAuth = function(callback, login_name, password, do_login, nexturl) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             var response = new Object();
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.login_name"] = login_name;
	req.params["base.users.password"] = password;
	req.params["nexturl"] =  (typeof (nexturl) != 'undefined' ? nexturl : '' );
	req.params["do_login"] = (typeof (do_login) != 'undefined' ? do_login : 0 );
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "check_auth";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 

    //strictly for imap/pop based authentication checking via server
    this.checkEmailAuth = function(callback, login_name, password) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             var response = new Object();
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }
        if (typeof (password) == 'undefined' || password == '') { 
             var result = new Object();
             result.error = "failed";
             result.description = "Password could not be empty";
             var response = new Object();
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.login_name"] = login_name;
	req.params["base.users.password"] = password;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "check_email_auth";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 


    this.sendAccessCode = function(callback, login_name, disallowed_auth_type) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.login_name"] = login_name;
	req.params["client_type"] = "json";
	req.params["disallowed_auth_type"] = disallowed_auth_type;
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "send_access_code";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 

    this.resetPassword = function(callback, access_code, login_name, password, confirm_password ) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (access_code) == 'undefined' || access_code == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Access Code could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }
        if (typeof (password) == 'undefined' || password == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Password could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }
        if (password != confirm_password) { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Password and Confirm Password should not be different.";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.access_code"] = access_code;
	req.params["base.users.login_name"] = login_name;
	req.params["base.users.password"] = password;
	req.params["base.users.confirm_password"] = confirm_password;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "reset_password";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 


    this.activateUser = function(callback, access_code, login_name ) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (access_code) == 'undefined' || access_code == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Access Code could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.access_code"] = access_code;
	req.params["base.users.login_name"] = login_name;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "activate_user";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 

    this.registerUsingEmail = function(callback, params ) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }

        if (typeof (params['base.users.login_name']) == 'undefined' || params['base.users.login_name'] == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }
        if (typeof (params['base.users.password']) == 'undefined' || params['base.users.password'] == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Password could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }


        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "register_using_email";
        for(x in params) {
           req.params[x] = params[x];
        }


        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 


    this.activateUser = function(callback, access_code, login_name ) {

        if (typeof (callback) == 'undefined') {
           alert("callback is undefined");
        }
        if (typeof (access_code) == 'undefined' || access_code == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Access Code could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        if (typeof (login_name) == 'undefined' || login_name == '') { 
             var result = new Object();
             var response = new Object();
             result.error = "failed";
             result.description = "Login Id could not be empty";
             response.responseText = JSON.stringify(result);	
             callback.call(null,response);
             return;
        }

        var req = new Object();
        req.method="GET";
        req.uri = Ngx.Odb.CommonUtil.getUri();
        req.async = false;
 
	req.params = [] ;
	req.params["base.users.access_code"] = access_code;
	req.params["base.users.login_name"] = login_name;
	req.params["client_type"] = "json";
	req.params["objpath"] = "domain/base/tables/users/forms/login_form";
	req.params["action"] = "activate_user";

        Ngx.Odb.CommonUtil.sendAjaxRequest(req, callback);
    } 

    this.isEmail = function(x) {
       var objRegExp = /^([a-zA-Z0-9])+([a-zA-Z0-9_\.\-])*([a-zA-Z0-9])\@(([a-zA-Z0-9])([a-zA-Z0-9\-])+([a-zA-Z0-9])\.)+([a-zA-Z0-9\+.]{2,4})+$/; 
       var result = true;
       if(x && objRegExp.test(x) == false) {
           result = false;
       }
       return result;
     }

    this.create = function() {
        return this;
    };
}

Users.prototype = new Form();
Users.prototype.constructor = Users;
/* GLOBAL Ngx */

var Ngx = { 

    Odb: {
        Form: new Form(),
        Users: new Users(),
        Control: new Control(),
        DateDropdown: new DateDropdown(),
        Objectpicker: new Objectpicker(),
        Hobjectpicker: new Hobjectpicker(),
        CommonUtil: new CommonUtil(),
    	Language: new  Language(),
        Imagestrip_picker: new Imagestrip_picker(),
        Imagezoom: new Imagezoom(),
        ImageSlideShow: new ImageSlideShow(),
        Accordion: new Accordion()
    }

}
Ngx.Odb.CommonUtil.initialize();
Ngx.Odb.Language.initialize();

function set_action (x) {
    document.main.action.value = x;
}

function qm_marquee(id, height, width, delta, interval, direction,scrollConWidth) {
    Ngx.Odb.CommonUtil.addMarquee(id, height, width, delta, interval, direction,scrollConWidth);
}

function popwindow (url,name,tab,wd,ht) {
    Ngx.Odb.CommonUtil.openWindow(url,name,wd,ht);
}

function toggleExpandCollapse(x,y) {
    Ngx.Odb.CommonUtil.toggleExpandCollapse(x,y);
}

