﻿//<!--
/************
This file is part of Genwi JS Lib.
All Rights Reserved.

Desc: Global Lib provides basic dom function,
      Environment Variable and prototypes

************/

// String prototypes
String.prototype.has = function (pStr){ return (this.indexOf(pStr) != -1); }

String.prototype.hasArg = function (pArg)
{
	var a = pArg, rv = false;
	if (typeof(a) == "string")
		rv = this.has(a);
	else
	{
		//It's an array (of strings)
		var aL = a.length;
		for (var j=0; j<aL && !rv; j++)
			rv = this.has(a[j]);
	}
	return rv;
}

String.prototype.is = function (s)
{ 
	return (this == s); 
}

String.prototype.hasAny = function ()
{
	var a = arguments, l = a.length, rv = false;
	for (var i=0; i<l && !rv; i++)
		rv = this.hasArg(a[i]);
	return rv;
}

String.prototype.hasAll = function ()
{
	var a = arguments, l = a.length;
	for (var i=0; i<l; i++)
	{
		if (!this.hasArg(a[i]))
			return false;
	}
	return true;
}

String.prototype.escapeSingleQuote = function()
{
    return this.replace(/'/g, "&rsquo;");
}

String.prototype.unescapeSingleQuote = function()
{
    //return this.replace("\", "&nbsp;");
    return this.replace("\\'", "");
}

String.prototype.cleanLineBreaks = function()
{
    var str = this.escapeSingleQuote();
   
    //var str = this; 
    str=str.replace(/\r\n/g,"\n");
    str=str.replace(/\r/g,"\n");
    str=str.replace(/\n\n/g,"\n");
    str=str.replace(/\n/g," ");
    return str;
}

String.prototype.replaceToken = function(pStr,pTkn,pReplace)
{
	var rv=pStr;
	while(rv.has(pTkn))
		rv=rv.replace(pTkn,pReplace);
        
	return rv;
}

String.prototype.replaceTokens=function()
{
	var rv=this,re,a=arguments,l=a.length;
	for(var i=0;i<l;i++)       
		rv=this.replaceToken(rv,"<#"+(i+1)+"#>",a[i]);
	
	return rv;
}

String.prototype.isEmpty = function()
{
    return (this == null || this == "" || (this.length && this.length == 0));
}

// Global Library.
function GlobalLib()
{
	this.win = window;
	this.doc = document;
	this.aParams = [];
	this.bQueryLoaded = false;
	this.oClient = new ClientInfo();
	this.sBaseUrl = null;
	this.bDevEnvironment = document.domain.has('localhost');
	this.sAjaxServiceDir = 'AjaxServices/';
	this.oShadow = null;

    this.addOnLoadListener = function(pFn)
    {
        var w = this.win, d = this.doc, un = 'undefined', fn = pFn;
        if (typeof w.addEventListener != un)
           w.addEventListener('load', fn, false);
        else if (typeof d.addEventListener != un)
           d.addEventListener('load', fn, false);
        else if (typeof w.attachEvent != un)
           w.attachEvent('onload', fn);
        else
        {
           var oFN = window.onload;
           if (typeof w.onload != 'function')
             w.onload = fn;
           else
           {
             window.onload = function()
             {
               oFN();
               fn();
             };
           }
        } 
    }
    
    this.getParentNode = function(pObj)
    {
        var o = pObj.parentNode ? pObj.parentNode : pObj.parentElement;
        return o;
    }

	this.getUIElem = function(pId)
	{
		var s = pId, d = this.doc;
		if (d.getElementById)
			return d.getElementById(s);
		else if (d.all)
			return d.all(s);

		return null;
	}
	
	this.getBaseUrl = function()
	{
	    with(this)
	    {
	        if (!sBaseUrl)
	        {
	            var oGenWiUrl = getUIElem('GenwiUrl');
	            sBaseUrl = oGenWiUrl ? oGenWiUrl.href : 'http://www.genwi.com/';
	        }
	        return sBaseUrl;
	    }
	}
	
	this.isAthenticated = function()
    {
        return (typeof username != 'undefined' && username.length > 0);
    }

	this.redirect = function(pUrl,pReplace,pTarget)
	{
		var l = this.doc.location;
		if (pTarget)
		    l.target = pTarget;
		    
		if (pReplace)	
			l.replace(pUrl);
		else			
			l.href = pUrl;
	}

	this.gotoAnchor = function(pName)
	{
		var l = this.doc.location, t = l.href.split("#"), n = pName || t[1];
		if (n)
			l.href = t[0] + '#' + n;
	}

    this.insertAfter = function(pParent, pNodeAfter, pNode)
    {
        var ns = pNodeAfter.nextSibling;
        if (ns)
            pParent.insertBefore(pNode, ns)
        else
            pParent.appendChild(pNode);
    } 
    
	this.getFormElem = function(pName, pType)
	{
		var d = this.doc;
		if (!d)
			return null;
			
		var frms = d.forms, ln = frms.length, e, eLen;
		for (var i=0;i<ln;i++)
		{
			e = frms[i].elements;
			eLen = e.length;
			for (var j=0;j<eLen;j++)
			{
				if (e[j].name == pName)
				{
					if (pType)
					{
						if (e[j].type == pType)
							return e[pName];
					}
					else
						return e[j];
				}
			}
		}
	}

    this.enableFormElems = function(pForm, pEnable)
    {
        var oFrm = this.doc.forms[pForm], elems = oFrm ? oFrm.elements : null;
        if (elems && elems.length > 0)
        {
            for (var i=0,len=elems.length; i<len;i++)
                elems[i].disabled = !pEnable;
        }
    }

	this.getQueryValue = function (pKey)
	{
		with (this)
		{
			if (!bQueryLoaded)
				loadParams();

			return aParams[pKey] ? aParams[pKey] : null;
		}
	}
	
	this.loadParams = function ()
	{
		var str = this.doc.location.search;
		if (str.length == 0)
			return;

		str = decodeURI(str.substr(1));
		var ps = str.split("&"), psLen = ps.length;

		for (var i=0; i<psLen; i++)
		{
			var p = ps[i].split("=");
			
			this.aParams[p[0]] = "";
			if (p[1])
			{
				//Escape any apostrophes & replace +'s with space
				var tmp = "", c, len = p[1].length;
				for (var j=0; j<len; j++)
				{
					c = p[1].charAt(j);
					if (c.is("'"))		tmp += "\\'";
					else if (c.is("+"))	tmp += " ";
					else				tmp += c;
				}
				this.aParams[p[0]] = tmp;
			}
		}
		
		this.bQueryLoaded = true;
	}

	this.getOffsetLT = function(pElem)
	{
		var e = this.getUIElem(pElem);
		if (e)
		{
			var rv = [0,0];
			while (e)
			{
				rv[0] += e.offsetLeft;
				rv[1] += e.offsetTop;
				e = e.offsetParent;
			}
			return rv;
		}
		return null;
	}
	
	this.createElement = function(pTag)
	{
	    var oD = this.doc;
	    if (oD.createElement)
	        return oD.createElement(pTag);
	    
	    return null;
	}

	this.openWindow = function(url, name, width, height, toolbar, loc,
						status, scrollbars, resizable, menubar, left, top, customprops)
	{
		var props = "";
		if (width) props += ",width=" + width;
		if (height) props += ",height=" + height;
		if (toolbar) props += ",toolbar=" + toolbar;
		if (loc) props += ",location=" + loc;
		if (status) props += ",status=" + status;
		if (scrollbars) props += ",scrollbars=" + scrollbars;
		if (resizable) props += ",resizable=" + resizable;
		if (menubar) props += ",menubar=" + menubar;
		if (left) props += ",screenX=" + left + ",left=" + left;
		if (top) props += ",screenY=" + top + ",top=" + top;
		if (customprops) props += "," + customprops;
		if (props != "") props = props.substring(1);

		var w = window.open(url, name, props);
		if (!this.oClient.bOpera && w && !w.closed) w.focus();
		return w;
	}
	
	this.getRandomNumber = function()
	{
	    return Math.floor(Math.random()*10001);
	}

	this.isAthenticated = function()
    {
        return (typeof username != 'undefined' && username.length > 0);
    }

	this.showShadow = function(pDisplay)
	{
		if (!this.oShadow)
			this.oShadow = new HTMLLayer('shadow');
			
		var d = this.doc, 
		oht = d.documentElement ? d.documentElement.offsetHeight : d.body.offsetHeight,
		sht = d.documentElement ? d.documentElement.scrollHeight : d.body.scrollHeight,
		ht = parseInt(sht) > parseInt(oht) ? sht : oht;
		this.oShadow.setStyle('height', ht + 'px');
	    this.oShadow.show(pDisplay);
	}
	
	this.openDialog = function(pHtml, pWidth, pHeight)
    {
        var oDialog = new Overlay('dialog', 200, 200, true);
        oDialog.sWidth = pWidth;
        oDialog.sHeight = pHeight;
        oDialog.setContent(pHtml);  
        oDialog.display(true);
        oDialog.setPosition();
        return oDialog;
    }
	
	this.getPNGImg = function(pSrc, pW, pH, pStyle)
	{
	    var cl = this.oClient, bIe6 = (cl.bIE && cl.iVer <= 6), s = '';
	    if (bIe6)
	    {
	        s = '<span ';
	        s += 'style="display:inline-block;width:' + pW + 'px;height:' + pH + 'px;';
	        if (pStyle)
	            s += pStyle +';';
	        s += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader';
	        s += '(src=\'' + pSrc + '\',sizingMethod=\'scale\')';
	        s += '"></span>';
	    }
	    else
	    {
	        s = '<img src="' + pSrc + '" border="0" ';
	        if (pStyle)
	            s += 'style="' + pStyle + '"';
	        s += ' />';
	    }
	        
	    return s;
	}
}

// Browser detection.
function ClientInfo()
{
	this.bFirefox = this.bWebTV = this.bOpera = this.bNav = this.bIE = this.bSafari =
	this.bWin = this.bMac = this.bWinXp = this.bXpSp2 = this.bAOL = 
	this.bVista = this.bLinux = false;

	this.iVer = -1;

	var nv = navigator, agt = nv.userAgent.toLowerCase(), i = 0, ver;

	with(this)
	{
		if (agt.has("webtv"))
		{
			bWebTV = true;
			i = agt.indexOf("webtv/") + 6;
		}
		else if (agt.has("firefox"))
		{
			bFirefox = true;
			i = agt.lastIndexOf("firefox") + 8;
		}
		else if (agt.has("safari"))
		{
			bSafari = true;
			i = agt.lastIndexOf("safari") + 7;
		}
		else if(typeof(window.opera)!="undefined")
		{
			bOpera = true;
			i = agt.lastIndexOf("opera") + 6;
		}
		else if (nv.appName.is("Netscape"))
		{
			bNav = true;
			i = agt.lastIndexOf("/") + 1;
		}
		else if (agt.has("msie"))
		{
			bIE = true;
			i = agt.indexOf("msie") + 4;
			if (agt.has('aol') || agt.has('america online'))
				bAOL = true;
		}

		ver = bOpera?window.opera.version():agt.substring(i);
		iVer = parseInt(ver);

		//OS Detection.
		bWin = agt.has("win");
		bWinXp = (bWin && agt.has("windows nt 5.1"));
		bVista = (bWin && agt.has("windows nt 6.0"));
		bXpSp2 = (bWinXp && agt.has("sv1"));
		bMac = agt.has("mac");
	}
	
	this.getFlashVersion=function()
    {
        var fv=0;
        if(this.bIE && this.bWin && !this.bOpera)
        {
            try
            {
                var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		        var ver = axo.GetVariable("$version");
		        if (ver)
		        {
		            av = ver.split(" ");
		            fv = av[1].split(',')[0];
		        }
		    }
		    catch (e) {/***Error ***/ }
        }
        else
        {
            if(navigator.plugins && navigator.plugins.length > 0 && navigator.plugins["Shockwave Flash"])
            {
                var pd=navigator.plugins["Shockwave Flash"].description,
                    aDesc=pd.split(" ");
                if(aDesc.length && aDesc[2])
                    fv=aDesc[2].split('.')[0];
            }            
        }
        return fv;
    }
    
    this.hasQuickTime = function()
    {
        if (this.bIE && this.bWin && !this.bOpera)
        {
            try
            {
                if (hasActiveXControl("QuickTimeCheckObject.QuickTimeCheck.1"))
                    return true;
		    }
		    catch (e) {/***Error***/}
        }
        else
        {
            if (navigator.plugins && navigator.plugins.length > 0)
            {
                for (var i=0,len=navigator.plugins.length;i<len;i++)
                {
                    if(navigator.plugins[i].name.toLowerCase().has('quicktime'))
                        return true;
                }
            }
        
        }
        return false;
    }
    
    this.writeActiveXHelper = function()
    {
        if(this.bIE)
        {
            dw=function(s){document.writeln(s);}
            dw('<scr'+'ipt language="vbscript" type="text/vbscript">');
            dw(' Function hasActiveXControl (pActXName)');
            dw('  aX = false');
            dw('  on error resume next');
            dw('  aX = IsObject(CreateObject(pActXName))');
            dw('  hasActiveXControl = aX');
            dw('End Function');
            dw('</scr'+'ipt>');
        }
    }
    //this.writeActiveXHelper();
}

var _GL = new GlobalLib();


//-->