/**
 * Egotec System klasse
 *
 * @author henning <leutz [at] egotec [dot] com>
 */

/*
   class: egotecSystem
   Die EgoTec System Klasse stellt verschiedene Methoden zur Verfügung

   vars:
    isMSIE - Internet Explorer Browser Check = true/false
    isMSIE5 - Internet Explorer5  Browser Check = true/false
    isMSIE5_0 - Internet Explorer 5.0 Browser Check = true/false
    isGecko - Gecko Browser Check = true/false
    isGecko18 - Gecko Browser 1.8 Check = true/false
    isSafari - Safari Browser Check = true/false
    isKonqueror - Konqueror Browser Check = true/false
    isOpera - Opera Browser Check = true/false
    isMac - Mac Browser Check = true/false
    isNS7 - Netscape 7 Browser Check = true/false
    isNS71 - Netscape 7.1 Browser Check = true/false
    
    dialogs['name'] - Popups
    activePopup		- Aktives Popup, falls mal kein Name angegeben wurde

    (start code)
		egotecSystem.isMSIE
	(end)
*/
function egotecSystem(cms_dir)
{
	// Browser init
	var browser = navigator.userAgent.toLowerCase();

	// Browser check
	this.isMSIE 		= (navigator.appName == "Microsoft Internet Explorer");
	this.isMSIE5 		= this.isMSIE && (navigator.userAgent.indexOf('MSIE 5') != -1);
	this.isMSIE5_0 		= this.isMSIE && (navigator.userAgent.indexOf('MSIE 5.0') != -1);
	this.isGecko 		= browser.indexOf('gecko') != -1;
	this.isGecko18 		= browser.indexOf('Gecko') != -1 && browser.indexOf('rv:1.8') != -1;
	this.isSafari 		= browser.indexOf("safari") != -1;
	this.isKonqueror 	= browser.indexOf("konqueror") != -1;
	this.isOpera 		= browser.indexOf('Opera') != -1;
	this.isMac 			= browser.indexOf('Mac') != -1;
	this.isNS7 			= browser.indexOf('Netscape/7') != -1;
	this.isNS71 		= browser.indexOf('Netscape/7.1') != -1;

	this.dialogs 		= new Array();
	this.activePopup	= '';
	
	this.cmsDir		= cms_dir;
}

/*
   method: alert
    egotec Alert Box

   Parameters:
    innerhtml 	- (string) Alerttext
    msgtype 	- (string) Alert Texttype : 'warning' , 'info' , 'alert'

    (start code)
		egotecSystem.alert('Ein Text', 'warning');
	(end)
*/
egotecSystem.prototype.alert = function(innerhtml, msgtype)
{
	if(window.innerHeight)
	{
		maxHeight = window.innerHeight
		maxWidth = window.innerWidth
	} else
	{
		maxHeight = document.body.clientHeight
		maxWidth = document.body.clientWidth
	}

	topWin = ((maxHeight - 200) / 2);
	leftWin = ((maxWidth - 400) / 2);

	// egotec Alert Objekt
	egotecAlert = new alertBox({
		title 		: "egotec",
		name 		: "myalert",
		height 		: 200,
		width 		: 400,
		top 		: topWin,
		left		: leftWin,
		type		: 'alert',
		msgtype		: msgtype,
		innerhtml	: innerhtml,
		cfunction	: ''
	});

	this.dialogs['myalert'] = egotecAlert;
	this.dialogs['myalert'].show();
}

/*
   method: colorBox
    egotec Color Dialog - colorBox wird per Smarty geöffnet {button type="colorpicker" id="bgImgFont"}
*/
egotecSystem.prototype.colorBox = function(setObj, type, setColor, set)
{
	if(window.innerHeight)
	{
		maxHeight = window.innerHeight
		maxWidth = window.innerWidth
	} else
	{
		maxHeight = document.body.clientHeight
		maxWidth = document.body.clientWidth
	}

	if(!setColor)
	{
		setColor = '';
	}

	topWin = ((maxHeight - 200) / 2);
	leftWin = ((maxWidth - 400) / 2);

	// egotec Alert Objekt
	egotecColor = new colorBox({
		title 		: "egotec",
		name 		: "mycolor",
		height 		: 280,
		width 		: 350,
		top 		: topWin,
		left		: leftWin,
		color		: setColor,
		type		: type,
		set			: set,
		obj			: setObj
	});

	this.dialogs['mycolor'] = egotecColor;
	this.dialogs['mycolor'].show();
}

/*
   method: changeClass
    Ändert die CSS Klasse

   Parameters:
    obj - (object) Objekt welches zu ändern ist
    cName - (string) Klassenname

    (start code)
		egotecSystem.changeClass(buttonObj, 'buttonOver');
	(end)

*/
egotecSystem.prototype.changeClass = function(obj, cName)
{
	obj ? obj.className = cName : "" ;
}

/*
   method: confirm
    egotec confirm Box

   Parameters:
    innerhtml 		- (string) Confirmtext
    msgtype 		- (string) Alert Texttype : 'warning' , 'info' , 'alert'
    functionName 	- (string) Confirm Function

    (start code)
		egotecSystem.confirm('Speichern ?', 'warning', 'set_size');
	(end)
*/

egotecSystem.prototype.confirm = function(innerhtml, msgtype, functionName)
{
	if (window.innerHeight)
	{
		maxHeight = window.innerHeight
		maxWidth = window.innerWidth
	} else
	{
		maxHeight = document.body.clientHeight
		maxWidth = document.body.clientWidth
	}

	topWin = ((maxHeight - 200) / 2);
	leftWin = ((maxWidth - 400) / 2);

	// egotec Alert Objekt
	egotecAlert = new alertBox({
		title 		: "egotec",
		name 		: "myconfirm",
		height 		: 200,
		width 		: 400,
		top 		: topWin,
		left		: leftWin,
		type		: 'confirm',
		msgtype		: msgtype,
		innerhtml	: innerhtml,
		commandhandler	: functionName
	});

	this.dialogs['myconfirm'] = egotecAlert;
	this.dialogs['myconfirm'].show();
}

/*
   method: convertCase
    Ändert die Groß / Kleinschreibung eines Strings

   Parameters:
    string 		- (string) String welcher zu ändern ist
    convertion 	- (string) low / up

    (start code)
		egotecSystem.convertCase('BOLD', 'low');
	(end)
*/
egotecSystem.prototype.convertCase = function(string, convertion)
{
	switch(convertion)
	{
		case 'up':
			string = string.toString().toUpperCase();
		break;

		case 'low':
			string = string.toString().toLowerCase();
		break;

		default:
			string = string.toString();
		break;
	}

	return string;
}

/*
   method: convertRGBToHex
    Konvertiert RGB Farben zu Hexadezimal

   Parameters:
    col - (string) Colour

   Returns:
	#F0F0F0

    (start code)
		egotecSystem.convertRGBToHex('rgb(200, 200, 200)');
	(end)
*/
egotecSystem.prototype.convertRGBToHex = function(col)
{
	var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");

	var rgb = col.replace(re, "$1,$2,$3").split(',');
	if (rgb.length == 3)
	{
		r = parseInt(rgb[0]).toString(16);
		g = parseInt(rgb[1]).toString(16);
		b = parseInt(rgb[2]).toString(16);

		r = r.length == 1 ? '0' + r : r;
		g = g.length == 1 ? '0' + g : g;
		b = b.length == 1 ? '0' + b : b;

		return "#" + r + g + b;
	}

	return col;
}

/*
   method: convertHexToRGB
    Konvertiert Hexadezimal Farben zu RGB

   Parameters:
    col - (string) Colour

   Returns:
	rgb(200,200,200);

    (start code)
		egotecSystem.convertHexToRGB('#F0F0F0');
	(end)
*/
egotecSystem.prototype.convertHexToRGB = function(col)
{
	if (col.indexOf('#') != -1)
	{
		col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');

		r = parseInt(col.substring(0, 2), 16);
		g = parseInt(col.substring(2, 4), 16);
		b = parseInt(col.substring(4, 6), 16);

		return "rgb(" + r + "," + g + "," + b + ")";
	}

	return col;
}

/*
   method: getEntity
    % oder PX Größe bestimmen

   Parameters:
    size - (string) String

   Returns:
	px oder pc
	- px = Pixel
	- pc = per Cent

	(start code)
		egotecSystem.getEntity('195px');
	(end)
*/
egotecSystem.prototype.getEntity = function(size)
{
	var size = size.toString();
	if(size.match('%'))
	{
		return "pc";
	} else {
		return "px";
	}
}

/*
   method: getPopupArg
    Gibt ein Argument des Popups's zurück

   Parameters:
	request	- (string) Variablename
*/
egotecSystem.prototype.getPopupArg = function(request, name)
{
	if(!name)
	{
		name = this.activePopup;
	}
	
	if(this.dialogs[name])
	{
		return this.dialogs[this.activePopup].getWindowArg(request);
	} else
	{
		alert('Popup "' + name + '" unknown!');
	}
}

/*
   method: getIFrame
    Gibt das Iframe Objekt / Ansprech-String im PopUp zurück

   Parameters:
	type - (string) type; type = 'object' ? return = (object) : return = (string)
	name - (string) Name des Popups
*/
egotecSystem.prototype.getIFrame = function(name, type)
{
	if(!name)
	{
		name = this.activePopup
	}
	return this.dialogs[name].getIFrame(type);
}

/*
   method: getEgotecWindow
    Gibt eine Referenz des gesuchten Fensters

   Parameters:
	windowName	- (string) Fenstername; alive, dlg, page_dlg
	type	- (int) 0 oder 1; 0 = gibt ein Objekt zurück, 1 = gibt den Ansprech String zurück
*/
egotecSystem.prototype.getEgotecWindow = function(windowName, type)
{
	var returnValue;

	if(windowName == 'alive')
	{
		if(type == 1)
		{
			returnValue = "document.getElementById('alive')";
		} else
		{
			returnValue = document.getElementById('alive');
		}
	}

	if(windowName == 'dlg')
	{
		if(type == 1)
		{
			returnValue = "document.getElementById('dlg')";
		} else
		{
			returnValue = document.getElementById('dlg');
		}
	}

	if(windowName == 'page_dlg')
	{
		var pObj 			= document.getElementById('page_dlg');
		var childPageObj 	= document.getElementById('dlg').contentWindow.document.getElementById('page_dlg');

		if(pObj)
		{
			if(type == 1)
			{
				returnValue = "document.getElementById('page_dlg')";
			} else
			{
				returnValue = pObj;
			}

		} else if(childPageObj)
		{
			if(type == 1)
			{
				returnValue = "document.getElementById('dlg').contentWindow.document.getElementById('page_dlg')";
			} else
			{
				returnValue = childPageObj;
			}
		}
	}

	return returnValue;
}

/*
   method: setPopupArg
    Setzt ein Argument des Popups's

   Parameters:
	request	- (string) Variablen Name
	regValue- (string | object) Variablen Wert
	name	- (string) Popup Name, falls nicht wird aktives Fenster verwendet
*/
egotecSystem.prototype.setPopupArg = function(request, regValue, name)
{
	if(!name)
	{
		name = this.activePopup;	
	}
	
	this.dialogs[name].setWindowArg(request, regValue);
}

/*
   method: setIframeSrc
    Setzt den src eines Frames mit popup.php

   Parameters:
	obj			- (object) Frame Object
	srcTpl		- (string) Template, für Smarty
	modulPath	- (string) Pfad der im Template mit {$modul_path} verfügbar ist
	returnType	- (int) 0 / 1, Bei 1 ist der return Wert die URL
	script		- (string) extra php script welches aufgerufen wird; required()
*/
egotecSystem.prototype.setIframeSrc = function(obj, srcTpl, modulPath, returnType, scriptName)
{
	if(obj)
	{
		srcStr = this.cmsDir + 'bin/admin/popup.php?';

		if(srcTpl)
		{
			srcStr += 'template=' + srcTpl;
		}

		if(modulPath)
		{
			srcStr += '&modulPath=' + modulPath;
		}

		if(scriptName && scriptName != '')
		{
			srcStr += '&script=' + scriptName;
		}

		obj.src = srcStr;
	}

	if(returnType == 1)
	{
		return srcStr;
	}
}

/*
   method: parseAttributes
   Zerlegt ein HTML String in seine Attribute

   Parameters:
    attribute_string - HTML String
    - zum Beispiel: <img src="bild.jpg" height="10" width="10" />

   Returns:
	Assoziatives Array mit den Attributen
	- zum Beispiel: attributes['height'] attributes['width']...

	(start code)
		egotecSystem.parseAttributes('<img src="" height="" width="" alt="">');
	(end)

*/
egotecSystem.prototype.parseAttributes = function(attribute_string)
{
	var attributeName = "";
	var attributeValue = "";
	var withInName;
	var withInValue;
	var attributes = new Array();
	var whiteSpaceRegExp = new RegExp('^[ \n\r\t]+', 'g');

	if (attribute_string == null || attribute_string.length < 2)
		return null;

	withInName = withInValue = false;

	for (var i=0; i<attribute_string.length; i++)
	{
		var chr = attribute_string.charAt(i);

		if ((chr == '"' || chr == "'") && !withInValue)
			withInValue = true;
		else if ((chr == '"' || chr == "'") && withInValue)
		{
			withInValue = false;

			var pos = attributeName.lastIndexOf(' ');
			if (pos != -1)
				attributeName = attributeName.substring(pos+1);

			attributes[attributeName.toLowerCase()] = attributeValue.substring(1);

			attributeName = "";
			attributeValue = "";
		} else if (!whiteSpaceRegExp.test(chr) && !withInName && !withInValue)
			withInName = true;

		if (chr == '=' && withInName)
			withInName = false;

		if (withInName)
			attributeName += chr;

		if (withInValue)
			attributeValue += chr;
	}
	return attributes;
}

/*
   method: parseEgotecUrl
   egotec URL in Einzelteile splitten

   Parameters:
    url - Die egotec URL (index.php?site=demo&id=1....)

   Returns:
	Gibt die einzelnen Parameter als Assoziatives Array zurück.
	- arr['id'], arr['site']

	(start code)
		egotecSystem.parseEgotecUrl('index.php?site=multimedia&id=1&suffix=jpg');
	(end)
*/
egotecSystem.prototype.parseEgotecUrl = function (url)
{
	var url = url.toString();
	url = url.replace(new RegExp('&amp;', 'gi'), '&');
	url = url.split('?');

	var attribute = url[1].split('&');

	arr = new Array();

	for(var i = 0; i < attribute.length; i++)
	{
		var tmp = attribute[i].split('=');
		arr[tmp[0]] = tmp[1];
	}

	return arr;
}

/*
   method: parseStyle
   style="" in seine Attribute zerlegen

   Parameters:
    style - (string) style Attribute

   Returns:
	Gibt die einzelnen attribute als Assoziatives Array zurück.
	- styleArr['width'], styleArr['border']

	(start code)
		egotecSystem.parseStyle('width:100; height:100; border-width:1px');
	(end)

*/
egotecSystem.prototype.parseStyle = function(style)
{
	var style = style.toString();
	style = style.replace(new RegExp(' ', 'gi'), '');

	var attribute = style.split(';');
	styleArr = new Array();

	for(var i = 0; i < attribute.length; i++)
	{
		var tmp = attribute[i].split(':');
		styleArr[tmp[0]] = tmp[1];
	}

	return styleArr;
}

/*
   method: popup
    egotec Popup Box, erstellt ein Popup mit allen Reitern

   Parameters:
	name	- (string) Name des Popups
	title	- (string) Titel des Popups
	width	- (int) Breite
	height	- (int) Höhe
	execCommand	- (int) Ausführende Funktion bei Klick auf OK Button
	arg	- (int) PopUp Args : {arg1 : arg1, arg2 : arg2} mit getPopupArg können diese abgefragt werden

	(start code)
		popTabs = new Array();

		// Ein Reiter
		popTabs[0] = Array();
		popTabs[0]['name'] 	= 'table';
		popTabs[0]['title']	= 'Tabelle';
		popTabs[0]['tpl'] 	= obj.getLibModulPath() + 'table/table_display.html';
		popTabs[0]['var'] 	= obj.getBinModulPath() + 'table/';

		// Zweiter Reiter
		popTabs[1] = Array();
		popTabs[1]['name'] 	= 'properties';
		popTabs[1]['title'] = 'Eigenschaften';
		popTabs[1]['tpl'] 	= obj.getLibModulPath() + 'table/table_prop.html';
		popTabs[1]['var'] 	= obj.getBinModulPath() + 'table/';

		execCommand = egotecSystem.getEgotecWindow('page_dlg', 1) + ".contentWindow.insertTable()";

		egotecSystem.popup('Tabelle', 420, 500, execCommand, popTabs, {rows : '', cols : '', type : 'update', tableElm : tableElm});
	(end)

	- name 	: gibt den Namen des Reiters an
	- title	: Wie der Reiter beschriftet ist
	- tpl 	: Gibt das Template an welches bei aktivieren des Tabs erscheinen soll
	- var 	: Variable die im Script verfügbar ist {$var}
*/
egotecSystem.prototype.popup = function(name, title, width, height, execCommand, tabs, arg)
{
	if (window.innerHeight)
	{
		maxHeight = window.innerHeight
		maxWidth = window.innerWidth
	} else
	{
		maxHeight = document.body.clientHeight
		maxWidth = document.body.clientWidth
	}

	topWin = ((maxHeight - height) / 2);
	leftWin = ((maxWidth - width) / 2);

	// egotec Alert Objekt
	egotecPopup = new popup({
		title 		: title,
		name 		: name,
		height 		: height,
		width 		: width,
		top 		: topWin,
		left		: leftWin,
		tabs		: tabs,
		arg			: arg,
		execCommand	: execCommand
	});

	this.dialogs[name] = egotecPopup;
	this.dialogs[name].show();
}

/*
   method: popupClose
    Schließt EGOTEC Dialoge
    
   Parameters:
      name - Name des Popups welches geschlosen werden soll, falls kein name angegeben wird wird das aktive Popup geschlossen
*/
egotecSystem.prototype.popupClose = function(name)
{
	if(!name)
	{
		name = this.activePopup;
	}

	if(egotecSystem.dialogs[name])
	{
		egotecSystem.dialogs[name].hide();
		egotecSystem.dialogs[name].destroy();
	}
}

/*
   method: utf8_encode
    Wandelt ISO in UTF8 um
   
   Parameters:
      rohtext - Text der umgewandelt
*/
egotecSystem.prototype.utf8_encode = function(rohtext)
{
	// dient der Normalisierung des Zeilenumbruchs
	rohtext = rohtext.replace(/\r\n/g,"\n");
	var utftext = "";
	for(var n=0; n<rohtext.length; n++)
	{
		// ermitteln des Unicodes des  aktuellen Zeichens
		var c=rohtext.charCodeAt(n);

		if (c<128) // alle Zeichen von 0-127 => 1byte
		{
			utftext += String.fromCharCode(c);
		} else if((c>127) && (c<2048)) // alle Zeichen von 127 bis 2047 => 2byte
		{
			utftext += String.fromCharCode((c>>6)|192);
			utftext += String.fromCharCode((c&63)|128);
		} else // alle Zeichen von 2048 bis 66536 => 3byte
		{
			utftext += String.fromCharCode((c>>12)|224);
			utftext += String.fromCharCode(((c>>6)&63)|128);
			utftext += String.fromCharCode((c&63)|128);
		}
	}
	return utftext;
}

/*
   method: utf8_decode
    Wandelt UTF8 in ISO um
    
   Parameters: 
    utftext - Text der umgewandelt wird
*/
egotecSystem.prototype.utf8_decode = function(utftext)
{
	var plaintext = ""; var i=0; var c=c1=c2=0;
	// while-Schleife, weil einige Zeichen uebersprungen werden
	while(i<utftext.length)
	{
		c = utftext.charCodeAt(i);
		if (c<128)
		{
			plaintext += String.fromCharCode(c);
			i++;
		} else if((c>191) && (c<224))
		{
			c2 = utftext.charCodeAt(i+1);
			plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
			i+=2;
		} else
		{
			c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
			plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
			i+=3;
		}
	}
	return plaintext;
}

/*
   method: resize
   Ändert die Größe eines HTML Elements

   Parameters:
      resize_obj - Object das verändert werden soll.

	(start code)
		egotecSystem.resize('editor', -100);
	(end)
*/
egotecSystem.prototype.resize = function(resize_obj, minus)
{
	if (window.innerHeight)
	{
		maxHeight = window.innerHeight;
	} else
	{
		maxHeight = document.body.clientHeight;
	}

	resize_obj.style.height = (maxHeight + minus) + "px";
}


/*
   method: trimSize
    nur die Zahlen eines Strings

   Parameters:
    size - (string) String

   Returns:
	Gibt den String ohne Buchstaben zurück
	- 195px => 195

	(start code)
		egotecSystem.trimSize('195px');
	(end)
*/
egotecSystem.prototype.trimSize = function(size)
{
	var size = size.toString();
	return size.replace(new RegExp('[^0-9]', 'gi'), '');
}

/*
   method: jsInArray
   Prüft, ob ein Wert in einem Array existiert

   Parameters:
    the_needle - gesuchter Wert
    the_haystack - Array in welchem gesucht wird

   Returns:
	Diese Funktion sucht in the_haystack nach the_needle und gibt bei Erfolg *TRUE* zurück, andernfalls *FALSE*.

	(start code)
		a = array('text', 'test')
		egotecSystem.js_in_array('text', a);
	(end)

*/
egotecSystem.prototype.jsInArray = function(the_needle, the_haystack)
{
	var the_hay = the_haystack.toString();

	if(the_hay == '')
    {
        return false;
    }

    var the_pattern = new RegExp(the_needle, 'g');
    var matched = the_pattern.test(the_haystack);

    return matched;
}

/*
  method: soap
	Soap Unterstützung

  Parameters:
	php_func -	(string) PHP Funktion die aufgerufen wird
	param - (array) Variablen was Übergeben wird
	recal_func - (string) Asynchrone Übertragung, Funktion die aufgerufen wird wenn Verarbeitung fertig ist (falls nicht gesetzt synchron)
*/
egotecSystem.prototype.soap = function(php_func, param, recal_func)
{
	var rVar = soap(php_func, param, recal_func);
	return rVar;
}

/*
  method: UserGroupRoleSelect
*/
egotecSystem.prototype.UserGroupRoleSelect = function(title)
{
	var popTabs = new Array();

	popTabs[0] = Array();
	popTabs[0]['name'] 		= 'allgemein';
	popTabs[0]['title']		= 'Allgemein';
	popTabs[0]['tpl_name'] 		= 'rights/t/usergrouproleselect.html';
	popTabs[0]['script_name'] 	= 'rights/usergrouproleselect.php';
	popTabs[0]['active']    = 1;
	
	this.popup('usergrouprole', title, 620, 660, "set_user_and_groups();", popTabs);
}


/*
  method: UserGroupRoleSelect
*/
egotecSystem.prototype.multimedia = function(site)
{
	var popTabs = new Array();

	/*media = '';
	media += this.cmsDir;
	media += "admin/frame.php";
	media += "?site=";
	media += site;
	media += "&session[insert_flag]=2";
	media += "&view=multimedia"
	*/
	
	popTabs[0] = Array();
	popTabs[0]['name'] 		= 'multimedia';
	popTabs[0]['title']		= 'Multimedia Bereich';
	popTabs[0]['script_name'] 	= 'eTK/multimedia/multimedia.php';
	popTabs[0]['tpl_name']	 	= 'eTK/multimedia/t/multimedia.html';
	popTabs[0]['active']    = 1;
	
	this.popup('multimedia', 'Multimedia Bereich', 800, 600, "set_user_and_groups();", popTabs);
}

egotecSystem.prototype.getMainWindow = function()
{
	return window;
}
