/*
	arguments to this function are:
	arguments(0) : comma separated list of names of css classes.
	arguments(1) to arguments(arguments.length - 1) : list of keys (attribute names) to look for.
	returns a comma separated values. Order of values is same as the order of names given in the argument list.
	a value "" is returned if the attribute was not found in the class names supplied.
*/
function getStyle()
{
	return extractStyleAttribute(true, ",", arguments[0], arguments, 1)
}

function getStyleEx(joinValues, seperator, classes)
{
	return extractStyleAttribute(joinValues, seperator, classes, arguments, 3)
}

function extractStyleAttribute(joinValues, seperator, classes, attributes, attributeOffset)
{
	var styleClassNames = classes.split(",");
	var styleClasses = new Array();
	var values = new Array();
	for (var s = 0; s < document.styleSheets.length && isPublicStyle(s); s++)
	  for (var r = 0; r < document.styleSheets[s].rules.length; r++)
		for (var c = 0; c < styleClassNames.length; c++)
		  if (document.styleSheets[s].rules[r].selectorText == '.' +  styleClassNames[c])
			 styleClasses[c] = document.styleSheets[s].rules[r].style;
	var done;

	for (var i = attributeOffset; i < attributes.length; i++)
	{
		values[i-attributeOffset] = "";
		done = false;
		for (var j = 0; (j < styleClasses.length) && (!done); j++)
		{
			var cssText = styleClasses[j].cssText;
			if (cssText.length < 1) continue;
			var cssPairs = cssText.split(";");
			for (var k = 0; (k < cssPairs.length) && (!done); k++)
			{
				var cssPair = trimStyle(cssPairs[k]);
				var namevalue = cssPair.split(":");
				if (trimStyle(namevalue[0]).toLowerCase() == attributes[i].toLowerCase())
				{
					values[i-attributeOffset] = trimStyle(namevalue[1]);
					if(namevalue.length > 2)
						values[i-attributeOffset] = values[i-attributeOffset]+":"+namevalue[2];
					done = true;
				}
			}
		}
	}
	return joinValues ? values.join(seperator) : values;

}

function trimStyle(s) {
	var regexp 	= new RegExp("[\\S]+","gi");
	var arr = s.match(regexp);
	return arr.join(" ");
}

function isPublicStyle(index)
{
    if( (document.styleSheets[index].href.indexOf("egain.global.css") != -1) || (document.styleSheets[index].href.indexOf("egain.public.css")) )
        return true;
    return false;
}

function generateNextId(id)
{
	var argId =	typeof id == "undefined" ? 0 : id;
	document.egainPlUniqueId = typeof document.egainPlUniqueId == "undefined" ? argId : argId > document.egainPlUniqueId ? argId : document.egainPlUniqueId+1;
	return document.egainPlUniqueId;
}

function getWidgetDir(name)
{
	for(var i=0; i<document.scripts.length;i++)
		if(document.scripts[i].src.replace(/\\/,"/").indexOf("/"+name+".") != -1 )
			return document.scripts[i].src.substring(0,document.scripts[i].src.lastIndexOf("/")+1);
    return ""; //current dir;
}

function getScriptSrc(name)
{
	var src = "";
	for(var i=0; i<document.scripts.length;i++)
		if ( (typeof name != "undefined") && (document.scripts[i].src.replace(/\\/,"/").indexOf("/"+name+".") != -1 ) )
			return "<script language='javascript' src='"+document.scripts[i].src+"'></script>  ";
		else
			src += "<script language='javascript' src='"+document.scripts[i].src+"'></script>\n";
	return src;
}

function getDocumentStyleLink(styleName)
{
	var styleSheets = "";
	for(var i=0; i<document.styleSheets.length;i++)
		if ( (typeof styleName != "undefined") && document.styleSheets[i].href.indexOf("/"+styleName+".") != -1)
			return "<link rel='stylesheet' type='text/css' href='"+document.styleSheets[i].href+"'>   ";
		else
			styleSheets += "<link rel='stylesheet' type='text/css' href='"+document.styleSheets[i].href+"'>\n";
	return styleSheets;
}

function addStyleSheetToDocument(path, styleSheetName, where)
{
    if((!path) || (!styleSheetName) || (styleSheetName == ""))
        return false;
    path = path.replace(/\\/,"\/");
    var element = document.createElement('<link rel="stylesheet" type="text/css" href="'+ ((path == "" || path.charAt(path.length-1) == "/") ? path:(path+"/"))+styleSheetName+'">')
	switch(where)
	{
		case "begin":
            document.all[1].insertAdjacentElement("AfterBegin",element);
			break;
		default:
            document.all[1].insertAdjacentElement("BeforeEnd",element);
            break;
    }
    return true;
}

function addScriptFileToDocument(filePath, id)
{
    if(!filePath || typeof filePath=="undefined" || filePath == "")
        return null;

    if(!id || typeof id=="undefined" || id == "")
        id = 'sf'+ generateNextId();

    filePath = filePath.replace(/\\/,"\/");
	var element = document.createElement('<script id="'+id+'" language="javaScript" src="'+filePath+'"></script>')
	document.all[1].insertAdjacentElement("BeforeEnd",element);
	return id;
}

function getCurrentDir()
{
    var currDir = new String(document.URL)
    currDir     = currDir.substring(0,currDir.lastIndexOf("/")+1)
    return currDir;
}

function getIEVersion()
{
	var browser	=	navigator.userAgent.toLowerCase();
	var major	=	parseInt(navigator.appVersion);
	var ie		=	(browser.indexOf("msie") != -1) && (browser.indexOf("opera") == -1);
	var version =	ie  && (major < 4) ? 3 :
					(ie && (major == 4) && browser.indexOf("msie 5"  )==-1) ? 4 :
					(ie && (major == 4) && browser.indexOf("msie 5.0")!=-1) ? 5 :
					(ie && (major == 4) && browser.indexOf("msie 5.5") !=-1) ? 5.5 :
					ie ? 6 : -1;
	return version;
}

function includeL10NFile(base, language, bundle, locale, application)
{
    var country;
    base        = new String((base != "." || base != "..") ? base.replace(/\\/,"/") : base);
    base        = (base != "" && base.lastIndexOf("/") != "/") ? base+"/" : base;
    language    = (!language || language == "undefined") ? "en"+"/" : language + "/";
    locale      = (!locale || typeof locale == "undefined" || locale == "") ? "us/" : locale +  "/";

	locale	= typeof locale == "undefined" || locale == null || locale == "" ? "en_us" : locale;
    locale 	= locale.split("_");
    country	= locale[1];

    application = (!application || typeof application == "undefined" || application == "") ? "pl/" : application +  "/";
    bundle      = (bundle == "undefined" || !bundle) ? "web/admin.properties" : bundle.replace(/\\/,"/"); //$$$
    var url     = base + language + country+ application +bundle;
    url         = url.replace(/\/\//,"/")
    document.write('<script language="JavaScript" src="' + url +'"></script>')
}

function loadL10NFile(file, id, language, country, application)
{
	var fileURL= file.replace(/\\/,"/");
	if(language && language != "undefined" && language != "" && language != "en")
		fileURL = fileURL.replace('/en/','/'+language+'/');

	if(country && country != "undefined" && country != "" && country.indexOf("_") != -1)
		country = (country.split("_"))[1];

	if(country && country != "undefined" && country != "" && country != "us")
		fileURL = fileURL.replace('/us/','/'+country+'/');
	if(application && application != "undefined" && application != "" && application != "pl")
		fileURL = fileURL.replace('/pl/','/'+application+'/');
	loadScriptFile(fileURL, id)
}

function loadHelpFile(file, id, language, country, application)
{
	var fileURL= file.replace(/\\/,"/");
	if(language && language != "undefined" && language != "" && language != "en")
		fileURL = fileURL.replace('/en/','/'+language+'/');
	if(country && country != "undefined" && country != "" && country != "us")
		fileURL = fileURL.replace('/us/','/'+country+'/');
	if(application && application != "undefined" && application != "")
		fileURL = fileURL.replace('/pl/','/'+application+'/');
	loadScriptFile(fileURL, id)
}

function loadScriptFile(fileURL, id)
{
	document.all[id].src = fileURL;
}

function includeUserCSSFile(fileName,userId)
{
    //if user css not fond then don't generate anything
}

function writeCachedProperty(propertyName)
{
    document.write(getCache(propertyName))
}

function writeL10NProperty(propertyName)
{
    document.write(propertyName)
}

function writeString(name)
{
    document.write(name)
}

function loadUserStylesheet(url, userId, id)
{
	if(isNaN(parseInt(userId)))
		return;
	if(url != "" || url != null)
	{
		url = url.replace(/\\/,"\/");
		url = url.charAt(url.length-1) == "/" ? url : url+"/";
	}
	url = url + userId + ".css";
	id = (typeof id == "undefined" || id == "") ? "userStylesheet" : id;
	document.write('<link rel=stylesheet type="text/css" href="'+url+'" id="'+id+'">')
	return;
}

function ltrim(data)
{
	return data.replace( /^\s*/, "" )
}

function rtrim(data)
{
	return data.replace( /\s*$/, "" );
}

function trim(data)
{
	return rtrim(ltrim(data));
}


function evalReturn(string)
{
	if(string == null || string == "")
		return null;
	var temp = null;
	try
	{
		eval("temp =" + string)
	}
	catch(err) { }
	return temp;
}

/* used to get data pattern from cache eg date pattern */
function getDataFormat(type)
{
	if(type == null || type == "")
		return type;
	dataFormat = getCache(type+"Format");
	dataFormat = dataFormat == null ? type : dataFormat;
	return dataFormat;
}

function showHelp(key, defaultKeys, features, url, arguments)
{
	var handle	= null;
	var width	= 600;
	var height	= 480;
	var left	= Math.ceil( (window.screen.width  - 580) / 2 );
	var top		= Math.ceil( (window.screen.height - 440) / 2 );

	defaultKeys	= defaultKeys != null ? defaultKeys.split(",") : new Array();
	var helpURL = key == null ? url : evalReturn(key);
	for(var i = 0; helpURL == null && i < defaultKeys.length; i++)
		helpURL = evalReturn(defaultKeys[i]);
	arguments = typeof arguments == "undefined" ? window : arguments;
	features = (typeof features == "undefined") || (features == "") ? "height="+height+",width="+width+"left="+left+", top="+top+" ,status=no,toolbar=no,menubar=no,location=no,directories=no,titlebar=no,resizable=yes,scrollbars=yes" : features;
	if(helpURL != null)
	{
		handle = window.open(helpURL, "help", features);
		handle.focus();

		var topWin = window.open("", "eGainMainWindow");
		try
		{
			var egpl_open_windows = topWin.openedWindows;
			if (typeof egpl_open_windows == "undefined")
				egpl_open_windows = new Array();
			egpl_open_windows["help"] = handle;
			topWin.openedWindows = egpl_open_windows;
		}
		catch (e) { }
	}
	return handle;
}

function showHelpURL(url, features, arguments)
{
	return showHelp(null, null, features, url, arguments)
}

/* Date related utilities */

/*
* This converts the dateStr in the fromDateFormat to toDateFormat
*/
function changeDateFormat(dateStr, fromDateFormat, toDateFormat)
{
	if(typeof dateStr == "undefined" || dateStr == null)
		return null;

	var dd = "";
	var MM = "";
	var yyyy = "";

	var fromSeperator = "/";;
	if(fromDateFormat.indexOf("-") != -1)
		fromSeperator = "-";
	else if(fromDateFormat.indexOf(".") != -1)
		fromSeperator = ".";

	var fromFormat = fromDateFormat.split(fromSeperator);
	var date = dateStr.split(fromSeperator);

	for(var i=0; i<fromFormat.length; i++)
	{
		if(fromFormat[i].substring(0,1) == "d")
			dd = date[i];
		else if (fromFormat[i].substring(0,1) == "y")
			yyyy = date[i];
		else if (fromFormat[i].substring(0,1) == "M")
			MM = date[i];
	}

	return getFormattedDateString(dd, MM, yyyy, toDateFormat);
}

/*
* This converts gets you the dateStr in the specified date format
*/
function getFormattedDateString(dd, mm, yy, dateFormat)
{
	var seperator = "/";;
	if(dateFormat.indexOf("-") != -1)
		seperator = "-";
	else if(dateFormat.indexOf(".") != -1)
		seperator = ".";

	var form = dateFormat.split(seperator);
	var dateStr = "";

	for(var i=0; i<3; i++)
	{
		if(form[i].substring(0,1) == "d")
			dateStr += (dateStr == ""?dd:seperator+dd);
		else if(form[i].substring(0,1) == "y")
			dateStr += (dateStr == ""?yy:seperator+yy);
		else if(form[i].substring(0,1) == "M")
			dateStr += (dateStr == ""?mm:seperator+mm);
	}

	return dateStr;
}
/***************************************/

