
//***************************************************************************
//  Copyright(C) 1999-2001 Active Web Services, LLC.
//  All Rights Reserved.
//
//  Project: Active Web Parts
// ***************************************************************************

//constants definitions
var DELAY_MINIMAL = 100;
var DELAY_SYNC_TREE = 500;
var DELAY_SHOW_PROPS = 500;
var DELAY_CHECK_PUB_STATUS = 1000 * 15;
var IMAGE_EXTENSIONS = "All Files (*.*)\0*.*\0Image Files (*.jpg;*.gif;*.bmp;*.png;*.tif)\0*.jpg;*.gif;*.bmp;*.png;*.tif\0\0";

var bName = navigator.appName;
var bVer = parseInt(navigator.appVersion);
var NS = (bName == "Netscape");
var IE = (bName == "Microsoft Internet Explorer");
var NS4 = (NS && bVer >= 4);
var IE4 = (IE && bVer >= 4);
var NS3 = (NS && bVer < 4);
var IE3 = (IE && bVer < 4);
var IE55 = (navigator.appVersion.indexOf('MSIE 5.5') >= 0);

if (NS4 || IE4)
{
  if (NS)
  {
    layerStyleRef="layer.";
    layerRef="document.layers";
    styleSwitch="";
    bgrcElement="bgColor";
    documentsRef="document.";
  }
  else
  {
    layerStyleRef="div.style.";
    layerRef="document.all";
    styleSwitch=".style";
    bgrcElement="backgroundColor";
    documentsRef="document.all.";
  }
}

function callJS(Str)
{
  return eval(Str)
}

function visWin ( lay )
{
  if (NS4 || IE4)
    eval(layerRef+'["'+lay+'"]'+styleSwitch+'.visibility="visible"' );
}

function hidWin ( lay )
{
  if (NS4 || IE4)
    eval(layerRef+'["'+lay+'"]'+styleSwitch+'.visibility="hidden"' );
}

function openWindow(url, title, options )
{
  if (url)
  {
    var new_win = window.open(url, title, options);
    new_win.focus();
  }
}

function moveOverText(text)
{
  window.status = text;
  setTimeout("clearStatus()",10000);
}

function clearStatus()
{
  window.status="";
}

// add form to request string
function addFormToRequest( form, request, repl )
{  
  var controls = form.all;
  for( var i = 0; i < controls.length; i++ )
  {  
    var item = controls[i];
    if(item.offsetWidth == 0) continue;
    if(item.tagName == "INPUT" || item.tagName == "SELECT" || item.tagName == "TEXTAREA")
    {      
      if((item.type == "checkbox" || item.type == "radio") && !item.checked)
        continue;
      request = addRequestParamEx( request, escape(item.name), escape(item.value), typeof(repl) == "undefined" ? true : repl )
    }
  }
  return request;
}


function getFormData( form, repl )
{  
  var request = "";
  var controls = form.elements;
  for( var i = 0; i < controls.length; i++ )
  {  
    var item = controls[i];
    if(item.type != "hidden" && item.offsetWidth == 0) continue;
    if(item.tagName == "INPUT" || item.tagName == "SELECT" || item.tagName == "TEXTAREA")
    {      
      if((item.type == "checkbox" || item.type == "radio") && !item.checked)
        continue;
      if(item.value.length > 0)
        request = addRequestParamEx( request, escape(item.name), escape(item.value), typeof(repl) == "undefined" ? true : repl )
    }
  }
  return request.substring(1);
}

// add request param
function addRequestParam( request, name, value )
{
  return addRequestParamEx( request, name, value, true );
}

function addRequestParamEx( request, name, value, repl )
{
  if ( value && value.length == 0 )
    return request;

  if ( request && typeof( request ) != 'string' )
    return request;
   
  if(!repl)
  {
    if( request.indexOf("?") == -1 ) request += "?";
    else if( request.indexOf("=") >= 0 ) request += "&";
    request += name + "=" + value;
    return request;
  }

  var re = new RegExp( name + "=\\w+", "" );

  if(request.match(re))
    request = request.replace(re, name + "=" + value);
  else
    request = addRequestParamEx( request, name, value, false );

  return request;
}

function getParamValue( request, name )
{
  var re = new RegExp( name + "=[\\w:/]+", "g" );
  var m = request.match(re);
  if(!m) return;
  if(!m.length) return;
  var res = m[0].split("=");
  if(!res.length) return;
  res = res[1];
  return res;
}

function preloadImages()
{
  var arrSrc = preloadImages.arguments;
  for( var i = 0; i < arrSrc.length; i++ )
  {
    if(document.images.length > 1 && document.images[document.images.length - 1].src == arrSrc[i])
      continue;

    var img = new Image;
    img.src = arrSrc[i];
    document.images[document.images.length] = img;
  }
}

function createHiddenFrame(id)
{
  var doc = document;
  if(typeof(element) != "undefined") doc = element.document;
  var frm;
  frm = doc.all(id);
  if(frm) frm.removeNode();
  frm = doc.createElement( "iframe" );
  frm.id = id;
  frm = doc.body.appendChild(frm);
  frm.style.display = "none";
  return frm;
}

function show_elements(list, showHide)
{
  if(!list) return;

  if(typeof(list) != "object")
  list = document.all(list);

  if(list.tagName)
  {
    show_item(list, showHide);
  }
  else
  {
    for(var i=0; i<list.length; i++)
    {
      show_item(list[i], showHide);
    }
  }
}

function show_item(item, showHide)
{
  if(typeof(item) != "object")
  item = document.all(item);
  item.style.display = showHide ? "inline" : "none";
}

function get_initialized()
{
  return _initialized;
}

function put_initialized( value )
{
  _initialized = value;
  if( value )
  {
    try
    {
      setTimeout( element.onInitialized, 1 );
    }
    catch(e)
    {
    }
  }
}

function waitForInitialize( object, method )
{
  object.onInitialized = method;
  if( object.initialized )
    object.initialized = true;
}

function waitForComplete(uid)
{
  if(document.all(uid).readyState == "complete")
    return;
  setTimeout("waitForComplete('" + uid + "')", 100);
}

var uniqueID = 0;

/*function showDoc(RID, docName)
{
  var query = "repository.aspx?ID=" + RID;
  if(!docName) if(document.all("doc_" + RID)) docName = document.all("doc_" + RID).innerHTML;
  if(docName) query += "&file=" + escape(docName);
  var frame = createHiddenFrame("frame_" + uniqueID);
  frame.src = "repository.aspx?ID=" + RID + "&File=" + escape(docName) + "&rand=" + uniqueID;
  uniqueID++;
  if(uniqueID >= 10) uniqueID = 0;
}*/

function loadImagePreview(imgFile, imgPreview, img_text_info)
{
  if(imgPreview.src.indexOf(imgFile) == imgPreview.src.length - imgFile.length) return;
  
  imgFile = CreateImageThumbnail(imgFile, imgPreview.max_width, imgPreview.max_height);	
  if(imgFile == null)
  {
	img_text_info.style.display='inline';
    img_text_info.style.visibility = "visible";
    img_text_info.innerHTML = 'Preview is not available.';
    imgFile = "img/1033/_.gif";
  }
  else
  {
    img_text_info.style.display='none';
    img_text_info.style.visibility = "hidden";
  }  
  
  var imgTag = imgPreview.outerHTML;  
  imgTag = imgTag.replace(new RegExp('\\bsrc=\\S*'), 'src="' + imgFile + '"');  
  imgTag = imgTag.replace(new RegExp('\\bwidth=\\S*'), '');  
  imgTag = imgTag.replace(new RegExp('\\bheight=\\S*'), '');    
  imgPreview.outerHTML = imgTag;
}

function onPreviewStateChange(ctrl, img_text_info)
{
  if(ctrl.readyState == "complete" && ctrl.src.indexOf("_.gif") < 0)
  {	  
	var szFit = ScaleToFit(new Size(ctrl.width, ctrl.height), new Size(ctrl.max_width, ctrl.max_height));  
	ctrl.width = szFit.x;
	ctrl.height = szFit.y;  
  }
}

function FillEnumControl(ctrl, xmlEnumOptList, attrValue, nodeName, paramValueName)
{
  ctrl.options.length = 0;
  for(var i=0; i<xmlEnumOptList.length; i++)
  {
    var fld = xmlEnumOptList[i];
    var o = new Option();
    o.value = fld.getAttribute(attrValue ? attrValue : "id");
    if(!nodeName)  o.text = fld.text;
    else if(!paramValueName) o.text = fld.selectSingleNode(nodeName).text;
    else
    {
      var expr = nodeName.replace("{0}", paramValueName + "='" + o.value + "'")
      o.text = fld.selectSingleNode(expr).text;
    }
    ctrl.options[i] = o;
  }
}

function str2Float(str, def)
{
  var res = def;
  try
  {
    res = parseFloat(str);
  }
  catch(e)
  {
    return def;
  }
  if(isNaN(res)) return def;
  return res;
}

function bankingRound( value )
{
  var result = Math.round( value );
  if ( Math.abs( value - result ) == 0.5 )
  {
    if ( ( result % 2 ) == 1 ) --result;
  }
  return result;
} 

function formatFloat( value, count )
{
  if( count == null )
    count = 2;
  var tmp = Math.pow( 10, count );
  var result = ( Math.round( value * tmp ) / tmp ).toString(10);
  var pos = result.indexOf(".");
  if( pos == -1 )
  {
    result += ".";
    pos = 2;
  }
  else
  {
    pos = pos - result.length + 3;
  }
  for( var i = 0; i < pos; i++ )
    result += "0";
  return result;
}

function str2Int(str, def)
{
  str = strTrim( str );
  var res = def;
  try
  {
    res = parseInt(str);
  }
  catch(e)
  {
    return def;
  }
  if(isNaN(res)) return def;
  return ( res.toString() == str ? res : def );
}

function str2UInt(str, def)
{
  var res = def;
  try
  {
    res = parseInt(str);
    res = Math.abs(res);
  }
  catch(e)
  {
    return def;
  }
  if(isNaN(res)) return def;
  return res;
}

function toBool( val )
{
  var str = val == null ? "" : val.toString().toLowerCase();
  if( str == "true" || str == "1" || str == "yes" )
    return true;
  return false;
}

function str2Date( val, def )
{
  var dt = Date.parse( val );
  if( isNaN( dt ) )
    return def;
  dt = new Date( dt );
  var year = dt.getFullYear();
  if ( year >= 1900 && year < 1970 && val.toString().indexOf( year.toString() ) < 0 )
		dt.setFullYear( year + 100 );
  return dt;
}

function formatDate( date, format )
{
	if (!date || typeof(date) == "undefined")
		return "";
  
  result = format.toLowerCase();
  var day = date.getDate().toString();
//  day = ( day.length == 1 ? "0" + day : day );
  result = result.replace( /dd/, day );
  var month = (date.getMonth() + 1).toString();
//  month = ( month.length == 1 ? "0" + month : month );
  result = result.replace( /mm/, month );
  var year = date.getFullYear().toString();
  result = result.replace( /yyyy/, year );
  result = result.replace( /yy/, year.substr(2, 2) );
  return result;
}

function cancelEvent()
{
  return event.returnValue = false;
}

function setFocusAndSelect(fld)
{
  if(typeof(fld) != "object") fld = document.all(fld);
  if ( typeof( fld.disabled ) != "undefined" )
		if ( fld.disabled ) return; 
  fld.focus();
  var textRange = fld.createTextRange();
  textRange.moveStart( "character", 0 );
  textRange.select();
}

function splitPath(path)
{
	var comps = new Object();
	comps.fullPath = path;
	var pos = path.lastIndexOf("\\");
	if(pos < 0)
		pos = path.lastIndexOf("/");	
	if(pos < 0)
	{
		comps.file = path;
		comps.path = "";
	}
	else
	{
		comps.file = path.substring(pos + 1);
		comps.path = path.substring(0, pos + 1);
	}	
	return comps;
}

function setLastError(err)
{
	top.document.body.lastError = err;
}

function getLastError()
{
	var err = top.document.body.lastError;
	top.document.body.lastError = null;
	return err;
}

function ValidationError(id, value, msg)
{
	this.Type = "ValidationError";
	this.ProID = id;
	this.Value = value;
	this.Description = msg;
}

function ProcessError(e)
{	
	var err = getLastError();		
	if(err)
	{		
		var control = null;
		try { control = document.forms[0].elements.namedItem(err.ProID); } catch(e){}
		if(control) control.focus();
		if(err.Description) alert(err.Description);		
	}
}

function CreateImageThumbnail(imgFile, maxw, maxh)
{
	try
	{
		if(imgFile.indexOf(".aspx") > 0) return imgFile;
		var arrAcceptableMime = new Array("gif", "png", "jpeg", "jpg", "jfif", "bmp", "gif");
		objImageThumbnail.Clear();
		var mime = objImageThumbnail.DetectMIMEType(imgFile);	
		for(var i=0; i<arrAcceptableMime.length; i++)
		{
			if(mime.indexOf(arrAcceptableMime[i]) >= 0)
				break;
		}
		if(i == arrAcceptableMime.length)
			imgFile = objImageThumbnail.Thumbinal(imgFile, maxw, maxh);		
	}
	catch(e)
	{
		imgFile = null;
	}
	return imgFile;
}

function hasAttribute(item, attr)
{
	if(item.attributes.getNamedItem)
		return item.attributes.getNamedItem( attr ).specified;	
	for(var i=0; i<item.attributes.length; i++)
	{
		if(item.attributes.item(i).nodeName == attr)
		{
			return item.attributes.item(i).specified;
		}
	}
	return false;
}

function check_date (value) {
   return /^\d{1,2}\/\d{1,2}\/\d{1,4}$/.test (value);
}

function check_time (value) {
   return /^\d{1,2}(:\d\d)?$/.test (value);
}

function enableElementInternal( element, enabled, className )
{
	if ( element == null ) return;
	if ( typeof(element.tagName) != "string" )
	{
		var i, i2 = element.length;
		for (i = 0; i < i2; i++ )
			enableElementInternal( element.item(i),  enabled );
		return;
	}

	if( enabled == true )
	{
		element.disabled = false;
		var regExp = new RegExp( className, "i" );
		regExp.Global = false;
		if( element.className.search(regExp) != -1 )
		{
		//element.style.removeAttribute( "backgroundColor" );
			var classArr = element.className.split( " ", 2 );
			var i, i2 = classArr.length - 1;
			var sRes = "";
			for( i = 0; i < i2; ++i )
				sRes += (i == 0 ? classArr[ i ]:(" " + classArr[ i ]));

			element.className = sRes;
			//alert( "Class = " + element.className );
		}
	}
	else
	{
		element.disabled = true;
		var regExp = new RegExp( className, "i" );
		regExp.Global = false;
		if( element.className.search(regExp) == -1 )
			element.className += (element.className == "" ? className:(" " + className));
		//element.style.backgroundColor = cbgColor;
		
		//alert( "Class = " + element.className );
		
	}

	if( typeof(element.refresh) != "undefined" )
		element.refresh();
}

function enableElement( bodyElement, arr, enabled, className )
{
	var i, i2 = arr.length;
	for ( i = 0; i < i2; i++ )
		enableElementInternal( bodyElement.all(arr[i].toString()), enabled, className );
}

function FillSelect( obj, html )
{
  var tmp = document.createElement( "div" );
  var result = obj.outerHTML;
  result = result.substr( 0, result.indexOf(">") + 1 );
  result += html + "</select>";
  tmp.innerHTML = result;
  tmp = tmp.firstChild;
  obj.replaceNode( tmp );
  return tmp;
}

function GenerateID()
{
  if( !document._idGenerator ) SetGeneratorValue( 0 );
  ++document._idGenerator;
  return "!" + document._idGenerator;
}

function GetGeneratorValue()
{
  if( !document._idGenerator ) SetGeneratorValue( 0 );
  return document._idGenerator;
}

function SetGeneratorValue( val )
{
  document._idGenerator = val;
}

function restoreStyle( obj )
{
  if( obj.__currentStyle )
    applyStyle( obj, obj.__currentStyle, null, true );
}

function applyStyle( obj, name, styleOwner, restore )
{
  if( !styleOwner )
    styleOwner = obj;

  // parse style
  if( !obj.getAttribute( "__" + name ) )
    obj.setAttribute( "__" + name, parseStyle(styleOwner.getAttribute(name)) );
  var styleArr = obj.getAttribute( "__" + name );

  // restore style
  if( !restore && obj.__currentStyle )
    applyStyle( obj, obj.__currentStyle, null, true );

  // apply style
  for( attr in styleArr )
  {
    if( !restore && styleArr[attr] )
      obj.runtimeStyle.setAttribute( attr, styleArr[attr] );
    else
      obj.runtimeStyle.removeAttribute( attr );
  }

  // store current style
  if( restore )
    obj.removeAttribute( "__currentStyle" );
  else
    obj.__currentStyle = name;
}

function parseStyle( style )
{
  var styleArr = new Object;

  if( style )
  {
    var params = style.split( ";" );
    for( var i = 0; i < params.length; i++ )
    {
      var nameValue = params[i].split( ":" );
      if( !nameValue.length )
        continue;
      var name = strTrim( nameValue[0] );
      var value = nameValue.length > 1 ? strTrim(nameValue[1]) : "";
      if( name )
        styleArr[name] = value;
    }
  }
  return styleArr;
}

function absoluteUrl( url )
{
  return document.URL.substring( 0, document.URL.lastIndexOf("/") + 1 ) + url;
}

function getImageCache( doc )
{
  if( !doc )
    doc = document;
  if( !doc._imageCache )
  {
    doc._imageCache = new ImageCache();
  }
  return doc._imageCache;
}

function ImageCache()
{
  this.count = 0;
  this.holder = new Array();
  this.callback = null;
  
  this.load = function( imgs, wait )
  {
    var groups = imgs.split( ";" );
    for( var j = 0; j < groups.length; j++ )
    {
      var images = groups[j].split( "," );
      var path = (groups.length > 1 ? images[0] : "");
      for( var i = (groups.length > 1 ? 1 : 0); i < images.length; i++ )
      {
        var src = (path + images[i]).toLowerCase();
        if( !this.holder[src] )
        {
          this.holder[src] = new Image();
          if( wait )
          {
            ++this.count;
            this.holder[src].onload = this.onCacheImageLoad;
            this.holder[src].onerror = this.onCacheImageLoad;
          }
          this.holder[src].src = src;
        }
      }
    }
    return imgs;
  }
  
  this.waitForLoad = function( callback )
  {
    this.callback = callback;
    this.callCallback();
  }
  
  this.callCallback = function()
  {
    if( !this.count && this.callback )
    {
      if( typeof(this.callback) == "string" )
      {
        eval( this.callback );
      }
      else
      {
        this.callback();
      }
    }
  }
  
  this.onCacheImageLoad = function()
  {
    var cache = getImageCache();
    --cache.count;
    cache.callCallback();
  }
}

function WindowCache()
{
  this.put = function( obj )
  {
    if( !window._cachedObjects || !window._cachedObjectsCount )
    {
      window._cachedObjectsCount = 0;
      window._cachedObjects = new Array();
    }
    window._cachedObjects[window._cachedObjects.length] = obj;
    ++window._cachedObjectsCount;
    return window._cachedObjects.length - 1;
  }

  this.get = function( id )
  {
    return window._cachedObjects[id];
  }

  this.remove = function( id )
  {
    --window._cachedObjectsCount;
    delete window._cachedObjects[id];
  }
}

function xmlDate2Date( val, def ){
  var dt = Date.parse( val );
  if( isNaN( dt ) ){
	val = val.replace(/-/g, "/");
	val = val.replace(/T(.)*/,"");
	dt = Date.parse( val );
	if( isNaN( dt ) )
		return def;
  }
  dt = new Date( dt );
  var year = dt.getFullYear();
  if ( year >= 1900 && year < 1970 && val.toString().indexOf( year.toString() ) < 0 )
		dt.setFullYear( year + 100 );
  return dt;
}

function FixTabSetPadding ( id )
{
  iframe = document.all ( id );
  if (iframe)
  {
	iframe.width = "100%";
	iframe.height = "100%";
  }
}

// For required controls 
function SetLabelDefaultStyle(labelID)
{
	var label = document.getElementById(labelID);
	var charsToTrim = label.className.indexOf('Required');
	if(charsToTrim > 0) label.className = label.className.substring(0, charsToTrim);
}
function SetLabelRequiredStyle(labelID)
{
	var label = document.getElementById(labelID);
	if( label.className.indexOf('Required') == -1 ) label.className += 'Required';
}
function CheckRadioButton(fieldID, labelID)
{
	var radioButtonList = document.getElementById(fieldID);
	var selected = false;
	for (i = 0; i < radioButtonList.all.length; i++)
	{
		if (radioButtonList.all[i].type == 'radio')
			if(radioButtonList.all[i].checked)
				selected = true;
	}
	if (selected) SetLabelDefaultStyle(labelID);
	else SetLabelRequiredStyle(labelID);
}

function CheckTextField(fieldID, labelID)
{
	value = document.getElementById(fieldID).value;

	for (i = 0; i < value.length; i++)
	{
		if (value.charAt(i) != " ")
		{
			SetLabelDefaultStyle(labelID);
			return;
		}
	}
		
	SetLabelRequiredStyle(labelID);
}
function CheckNumericField(oEdit, newText, oEvent)
{
	var labelID = oEdit.ID.substring(0, oEdit.ID.lastIndexOf('_')) + '_label';
	if (newText.length == 0) SetLabelRequiredStyle(labelID);
	else SetLabelDefaultStyle(labelID);
}
function CheckDateChooser(oDropDown, newValue, oEvent)
{
	var labelID = oDropDown.Id.substring(0, oDropDown.Id.lastIndexOf('xdate')) + '_label';
	if (newValue == null) SetLabelRequiredStyle(labelID);
	else SetLabelDefaultStyle(labelID);
}
function CheckAwsDateChooser(labelID, controlID)
{
	event.srcElement.value = event.srcElement.value.replace(/\s*/g,'');
	if (event.srcElement.value == '') return;
	var date_parts = event.srcElement.value.split("/");
	if (date_parts == null || date_parts.length != 3)
	{
		ResolveAwsDateChooserError(labelID, controlID);
		return;
	}
	
	year = date_parts[2];
	month = date_parts[0] - 1; //month begins from 0
	day = date_parts[1];
	
	var date = new Date();
	date.setFullYear(year, month, day);
	if (year != date.getFullYear() || month != date.getMonth() || day != date.getDate())
	{
		ResolveAwsDateChooserError(labelID, controlID);
		return;
	}

	SetLabelDefaultStyle(labelID);
}
function ResolveAwsDateChooserError(labelID, controlID)
{
	SetLabelRequiredStyle(labelID);
	var datecontrol = document.getElementById(controlID);
	if(datecontrol != null)
	{
		window.setTimeout("SetAwsDateChooserFocused('" + controlID + "')", 10);
		alert("Invalid date format");
	}	
	return;
}

function SetAwsDateChooserFocused(controlID)
{
	var datecontrol = document.getElementById(controlID);
	if(datecontrol != null)
	{
		datecontrol.focus();	
	}	
}

function SetAwsNumericFocused(controlID)
{
	var numeric = document.getElementById(controlID + "_t");
	if(numeric != null)
	{
		numeric.focus();
	}
}
function CheckComboBox( fieldID, labelID, fName )
{
	var field = document.getElementById(fieldID);
	if (field.value.length == 0) SetLabelRequiredStyle(labelID);
	else SetLabelDefaultStyle(labelID);
	eval(fName);
}

function ConstructObjectResultFromStringResult( str )
{
	if( str == null || str == "" ) return null;
	var objectResult = new Object();
	
	var valueItems = str.split("??");
	if( valueItems.length > 0 )
	{
		var strsAttrs = valueItems[0].split('&');
		for( var d = 0; d < strsAttrs.length; d++ )
		{
			var nameValue = strsAttrs[d].split('=');
			if( nameValue.length == 2 )
			{
				var name = nameValue[0];
				var value = nameValue[1];
				
				var regexpQuestion = new RegExp('question;');
				name = name.replace(regexpQuestion, '?');
				value = value.replace(regexpQuestion, '?');
				var regexpAmpersand = new RegExp('ampersand;');
				name = name.replace(regexpAmpersand, '&');
				value = value.replace(regexpAmpersand, '&');
				var regexpEqual = new RegExp('equal;');
				name = name.replace(regexpEqual, '=');
				value = value.replace(regexpEqual, '=');
				
				objectResult[name] = value;
			}
		}
	}
	
	if( valueItems.length > 1 )
	{
		var strsObj =  valueItems[1].split('&&');
		for( var c = 0; c < strsObj.length; c++ )
		{
			var curObj = new Object();
			objectResult[c] = curObj;
			
			var strsAttrs = strsObj[c].split('&');
			for( var d = 0; d < strsAttrs.length; d++ )
			{
				var nameValue = strsAttrs[d].split('=');
				if( nameValue.length == 2 )
				{
					var name = nameValue[0];
					var value = nameValue[1];
					
					var regexpAmpersand = new RegExp('ampersand;');
					name = name.replace(regexpAmpersand, '&');
					value = value.replace(regexpAmpersand, '&');
					var regexpEqual = new RegExp('equal;');
					name = name.replace(regexpEqual, '=');
					value = value.replace(regexpEqual, '=');
					
					curObj[name] = value;
				}
			}
		}
	}
	return objectResult;
}

function AwsTextBoxValidate( src, args )
{
	var textBox = document.getElementById(src.getAttribute('TextBoxId'));
	if( textBox.value == null || textBox.value == '' )
	{
		args.IsValid = false;
		textBox.focus();
	}
	return args;
}

function safeFocus( control )
{
//new implementation by I.Rudyak
	if (control == null)
	{
		return false;
	}

	if (control.tagName == 'INPUT' || control.tagName == 'TEXTAREA' || control.tagName == 'SELECT' || control.tagName == 'A' || control.tagName == 'SPAN')
	{
		if (control.focus == null || control.disabled || control.tabIndex == -1)
		{
			return false;
		}
        
		if (control.tagName == 'TEXTAREA' && !control.isContentEditable)
		{
			return false;
		}
        
		if (control.tagName == 'INPUT' &&
			(control.type == 'hidden' ||
			((control.type == 'checkbox' || control.type == 'file' ||
			control.type == 'password' || control.type == 'radio' ||
			control.type == 'text') && !control.isContentEditable)))
		{
			return false;
		}
        
		try
		{
			control.focus()
			return true;
		}
		catch (e)
		{
		    return false;
	    }
	}
    
	if (control.children == null)
	{
		return false;
	}

	//iterate throw each child control
	// we should create local variable for recurrent function otherwise global variable will be used and 
	// and we've got infinit cycle
	var i = 0; 
	for (i = 0; i < control.children.length; i++)
	{
		if (safeFocus(control.children[i]))
        {
            return true;
        }
	}

    return false;

/* Old implementation by B.Bogachev
    try
    {
        control.focus();
    }
    catch(e)
    {
    }
*/    
}

function awsFocusInit()
{
    var _f = document.getElementById( "__awsFocus" ); 
    if ( !_f || !_f.value ) return;
    var _c = document.getElementById( _f.value );
    if ( !_c ) return;
    safeFocus( _c );
}

// popup control methods
function AwsGetElementById(tagId) 
{
	var obj;
	obj = document.getElementById(tagId);
	return obj;

	if(document.all)
		obj=document.all[tagId];
	else
		obj=document(tagId);
	if(obj && obj.length && obj[0].id==tagId)
		obj=obj[0];

	return obj;
}

function UpdateHiddenWindowID()
{
    var hdwdCtl = AwsGetElementById('__HiddenWindowID');
    if (!hdwdCtl) return;

    if (!hdwdCtl.value && window.parent)
    {
        var hdwdCtLocal = window.parent.document.getElementById('__HiddenWindowID');
        if (hdwdCtLocal)
            hdwdCtl.value = hdwdCtLocal.value;
    }
    
    if (!hdwdCtl.value)
        hdwdCtl.value = Math.round(Math.random()*10000);
}

/// Query string parsing code
function PageQuery(q) 
{
    this.parameters = new Array();
    this.values = new Array();
    this.length = 0;
    
    if(q.length > 1) this.q = q.substring(1, q.length);
        else this.q = null;
    
    if(this.q) 
    {
        var queryParts = this.q.split("&");
        var parameterIndex = 0;
        for(var i=0; i < queryParts.length; i++) 
        {
            if (queryParts[i] > "")
            {
                var pair = queryParts[i].split("=");
                this.parameters[this.length] = pair[0];
                this.values[this.length] = unescape(pair[1]);
                this.length++;
            }
        }
    }
    
    
    this.getValue = function(idx) { return this.values[idx]; }
    this.getParameter = function(idx) { return this.parameters[idx]; }
  
    this.getParameterValue = function(s) 
    {
        for(var j=0; j < this.length; j++) 
        {
            if(this.parameters[j].toLowerCase() == s.toLowerCase())
                return this.values[j];
        }
        return false;
    }

    this.getLength = function() { return this.length; } 
}

function queryString(key)
{
    var page = new PageQuery(window.location.search); 
    return page.getParameterValue(key); 
}

/// End of query string parsing code