/*===============================================================================
	general helper functions
=================================================================================*/
var WINDOWS_FOLDER=0;
var SYSTEM_FOLDER=1;
var TEMPORARY_FOLDER=2;

//===============================================================================
// Array key/val extensions

function aArray(key)
{	this.keys = new Array();  this.vals = new Array();	
	this.length = 0;
//return new ActiveXObject("Scripting.Dictionary");
}
/////////////////////////////////////////////////////////////////////////////////
// Adds a new key/val item
aArray.prototype.add = function (key,value)
{
	if (this.keys[key]==undefined) 
		{	this.length++;
			this.keys[key]=key;
		}
	return this.vals[key]=value;
}
////////////////////////////////////////////////////////////////////////////////
// Removes item by key
aArray.prototype.del = function (key)
{	if (this.exists(key))
		{	this.keys[key]=this.vals[key]=undefined;  this.length--;	}
}
///////////////////////////////////////////////////////////////////////////////
// Checks if an item is exists
aArray.prototype.exists = function (key)
{	return this.keys[key]!=undefined;  }
///////////////////////////////////////////////////////////////////////////////
// Returns an item value by key
aArray.prototype.Item = function (key)
{	return this.vals[key];	}
//////////////////////////////////////////////////////////////////////////////
// Returns an array of values
aArray.prototype.Items = function ()
{	return this.vals;	}
/////////////////////////////////////////////////////////////////////////////
// Returns an array of keys
aArray.prototype.Keys = function (ix)
{	var k=new Array(),i=0;
	var e = new Enumerator(this.keys);
	while (!e.atEnd())
		{	if ((v=e.item())!=undefined)
				k[i++]=v; e.moveNext();	
		}
	return (ix!=undefined)?k[ix]:k;	
}

//============================================================
// Hex/dec converters
function chex(v,nplaces)
{
var nv,xr="";
nplaces=nplaces || 0;
v=v.toString(16); 
v=v.fill(nplaces-v.length,"0");
return v.toUpperCase();
}

function cdec(v)
{
var xr=0;
v="0x"+v;
try { xr=eval(v); } catch(z) {  }
return xr;
}	
//=================================================
// Additional string helper functions
//-------------------------------------------------
// fill : fills a string with n chars from l/r
//	- n : nr. of chars to written
//	- ch: character to fill with
//  - left: bool, t=fill from left, f=fill from r
String.prototype.fill = function (n,ch,left)
{
	left=left || true;
	for(var s="";n>0;n--) s+=ch; 
	return ((left)?s+this:this+s);
}
//------------------------------------------------
// trim : trim spaces
//	- dir : direction where trim from (1 left, 0 right)
String.prototype.ltrim = function ()
{
	/* var s=this;
	while ((fp=s.indexOf(" "))==0)
		s=s.substring(1,s.length);
	return s; */
	var s = this;
	var m = s.match(/^(\s*)(.*)/);
	return m[2];
}	

String.prototype.rtrim = function ()
{
	var s=this;
	/* while (s.length && (fp=s.lastIndexOf(" "))==s.length-1)
		s=s.substring(0,s.length-1); */
	var m = s.match(/$(\s*|.*)(\s*)$/);
	return m[1];
}	

String.prototype.trim = function ()
{   
	var s=this;
	s=s.ltrim();
	return s.rtrim();
}	
//===============================================================================
// File function extensions
//===============================================================================
function CreateTextFile(fname, txt, btmp)
{
    var fs = new ActiveXObject("Scripting.FileSystemObject");
	btmp = (btmp==undefined) ? true : false;
    var rv = ((btmp) ? fs.GetSpecialFolder(TEMPORARY_FOLDER)+"\\":"")+fname;
	var path = fs.GetParentFolderName(rv);
	if (!fs.FolderExists(path)) CreateAbsFolder(fs, path);
    var tfile = fs.CreateTextFile(rv,true);
	if (tfile==null) return false;
    tfile.Write(txt);
    tfile.Close();
    return rv;
}

function CreateFolder(name)
{
	var fs = new ActiveXObject("Scripting.FileSystemObject");
	if (fs.FolderExists(name)==false) fs.CreateFolder(name);
	return name;
}
//===============================================================================
// Log window function extensions
//===============================================================================
function __wlog(oLog,msg,level)			// Log writer helper
{ if (oLog) { var v=oLog.wlog(msg,level); return v;}
  return null;
}

//===============================================================================
// CSS module enabler
//		cssid : id of CSS block that would be enabled
//		doc	  : context of document of stylesheets
//===============================================================================
function enable_css(doc,cssid)
{
	for (var i=0; i<doc.styleSheets.length; i++) 
		if (doc.styleSheets(i).id) doc.styleSheets(i).disabled = doc.styleSheets(i).id != cssid;
}
//===============================================================================
// FRAMESET/FRAME creator
//===============================================================================
//	insert_frame - inserts a frame into a frameset
//		objTo : frameset object where the new frame inserted
//		childbefore : objTo child that will be the new frame inserted before
//		size : frame size
//		id : id of frame object
//		htmlsrc : frame html document src
//	VerData.framecode REQUIRED
function insert_frame(objTo,childbefore,size,id,htmlsrc)
{	
	var prop = (objTo.cols!="") ? "cols":"rows";
	objTo[prop] = size + "," + objTo[prop];
	var elm=document.createElement(eval(frmMain.VerData.framecode));
	objTo.insertBefore(elm,childbefore);
}
//-------------------------------------------------------------------------------
// insert_frameset - create a new frameset and inserts a frame into
//		objTo	:	parent framset object (practical) where the new frameset inserted
//		childnode : parent frameset's child node which will be copied into the new frameset
//		colrow	:	"cols" or "rows" according to the order of new frameset
//		size	:	size of the new frame
//		id		:	id of new frameset
//		frameid	:	name of new frame
//		docsrc  : frame html document src
//	VerData.framesetcode REQUIRED
// 
//  example to create a new vertical docking frame: 
//  insert_frameset(document.all("frstRoot"),document.all("frstRoot").children("frstHorizontal"),'cols',100,"frstVertical","frmLogin2","login.html");
//  insert_frame(document.all("frstVertical"),document.all("frstVertical").children(0),150,"frmLogin3","login.html");
//	

function insert_frameset(objTo,childnode,colrow,size,id,frameid,docsrc)
{
	colrow=colrow+"='*'";
	var elm=document.createElement(eval(frmMain.VerData.framesetcode));
	elm.appendChild(childnode);
	insert_frame(elm,elm.firstChild,size,frameid,docsrc);
	objTo.insertBefore(elm);
}

function getCSSElement(cssobj,ruletxt)
{
	for (var i=0;i<cssobj.rules.length;i++)
		if (cssobj.rules(i).selectorText==ruletxt) return cssobj.rules(i);
	return cssobj.rules(i);
}
//=================================================================================
// finds an returns the current IE Application window. Returns InternetExplorer obj
function findInternetExplorer(win)
{
    var oShell = new ActiveXObject("Shell.Application");
	var win = win || window;
	var tt = win.document.title;
	win.document.title = "findme";

	var shw = oShell.Windows();
	var fp=null;
	for (var i=0;i<shw.Count;i++)
		{	try 
			{	fp = shw.Item(i).document.title;
				if (fp=="findme")	
					{	win.document.title=tt;	
						return shw.Item(i);
					}
			}
			catch(e)
			{	}
		}
	return fp;
}
//=================================================================================
function getExtName(sFilename)
{	var p;
	return ((p=sFilename.lastIndexOf("."))>-1)?sFilename.substr(p+1):"";	
}

function getFileName(sFilename,slash)
{	var p;
	return ((p=sFilename.lastIndexOf(slash))>-1)?sFilename.substr(p+1):"";	
}

function CreateAbsFolder(fso, path)
{
	var sp=path.split("\\");
	for (var pn=sp[0],i=1;i<sp.length;i++)
		{	pn+="\\"+sp[i];
			if (!fso.FolderExists(pn)) fso.CreateFolder(pn);
		}
}
//=================================================================================
// if an attribute has 'javascript:' prefix, evaluates it else read as a string
function jsAttribute(attr,base)
{ base = base || ""; if (base.length) base+=".";
  return (isJsAttribute(attr))?eval(base+attr.substr(11)):attr; }

function isJsAttribute(attr)
{ return attr.substr(0,11).toUpperCase()=="JAVASCRIPT:"; }

function addslashes(str)
{	var re = /\\/gi;
	return str.replace(re,"\\\\");
}

function openExplorer(sPath)
{
	var osh = new ActiveXObject("Shell.Application");
	osh.Explore(sPath);
}
//=================================================================================

function SetCookie(sName, sValue, exp)
{
  //if (!exp) DT = new Date(); 
  //else DT = exp; 
  //date.setYear(date.getYear()+1);
  document.cookie = sName + "=" + escape(sValue) + "; expires=" + exp.toGMTString();
}

function DelCookie(sName)
{
  document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function GetCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }
  return null;
} 

///============================================
//// Format : y-m-d | d-m-y | ...
////============================================
function isoDate(date,format)
{
	var dt = new Array();
	
	dt['y'] = date.getYear() + "";
	dt['M'] = date.getMonth() + 1;
	dt['d'] = date.getDate();
	dt['-'] = "-";
	dt[' '] = " ";
	dt['.'] = ".";
	var rs="";
	
	if (!format || format==undefined) format='y-M-d';

	if (dt['y'].length < 4)
		dt['y'] = dt['y'] - 0 + 1900;

	dt['y'] = "" + dt['y'];

	if (dt['M'] < 10)
		dt['M'] = "0" + dt['M'];

	if (dt['d'] < 10)
		dt['d'] = "0" + dt['d'];
	
	try
	{
		for (var i=0; i<format.length; i++)
			rs += dt [format.substr(i,1)];
	}
	catch(e) {}
	return(rs);
}

function parseDate(date)
{
	var y, m, d;

	if(! date) return false;

	date = '' + date + '';

	y = parseInt(date.substring(0, 4));
	m = parseInt(date.substring(5, 7)) - 1;
	d = parseInt(date.substring(8, 10));

	return new Date(y, m, d);
}

function serialize (variable) 
{ 
    switch (typeof variable) 
    { 
        case 'number': 
            if (Math.round(variable) == variable) 
                return 'i:'+variable+';'; 
            else 
                return 'd:'+variable+';'; 
        case 'boolean': 
            if (variable == true) 
                return 'b:1;'; 
            else 
                return 'b:0;'; 
        case 'string': return 's:'+variable.length+':"'+variable+'";'; 
        case 'object': 
            r = 'a:'+variable.length+':{'; 
            for(i=0; i < variable.length; i++) 
            { 
                r+= serialize(i)+serialize(variable[i]); 
            } 
            r += '}'; 
            return r; 
            break; 
        default: 
            return 'unkown type: '+typeof variable; 
    } 
} 
