/**
 * comgate_tereza.js
 *
 * Javascriptova podpurna knihovna pro pouziti dialogoveho systemu ComGate
 * Tereza.
 * @author Ondrej Balaz <ondrej.balaz@comgate.cz>
 * @copyright Copyright © 2008-2009 ComGate Interactive s.r.o.
 */


/**
 * Trida reprezentujici dialogovy system Tereza.
 * @param string id         identifikator aplikace
 * @param Tereza.LAYOUT layout  pouzity layout (embed|popup) na kterem zavisi
 *      politika pri presmerovani (v pripade embed se text nacita az po reloadu)
 * @param url_middleware    URL k middleware (vzdy neco jako
 *      http://tereza.comgate.cz/app/APLIKACE)
 * @param url_media         URL k multimedialnimu obsahu
 * @param entry_node        vstupni uzel (nazev)
 * @param lang              jazyk
 */
function Tereza
(
	id,                 /* id aplikace */
	layout,             /* popup|embed */
	urlMiddleware,      /* URL middleware (tereza.comgate.cz/try/kampan) */
	urlMedia,           /* URL media adresare */
	urlAssets,          /* URL assets (javascript) adresare */
	entryNode,          /* vstupni uzel */
	lang                /* jazyk */
)
{
	this._id = null;
	this._uniqId = Tereza._uniqId++;
	this._build = "20091209";           // verze klientu (ComGate)

	this._logging = true;               // lazeni do FireBugu
	this._parentElem = null;            // DOM element zapouzdrujici flash
	this._swfElem = null;               // DOM element predstavujici flash

	this._popupWin = null;
	this._parentWin = window.opener;
	this._frame = null;

	this._layout = Tereza.LAYOUT.embed;
	this._urlMiddleware = "";
	this._urlMedia = "";
	this._urlAssets = "";
	this._lang = "cs";
	this._entryNode = "start";


	/* --------------------------------------------------------------------- *
	 *                              VEREJNE METODY                           *
	 * --------------------------------------------------------------------- */
	/**
	 * Vlozi flashovy objekt Terezy do stranky. Tato funkce musi mit k dispozici
	 * DOM strom (musime ji poustet po onload atd.).
	 * @param string elemId     id elementu do ktereho ma byt tereza vlozena
	 *      (nahradi jeho stavajici obsah)
	 * @param int width         sirka okna terezy
	 * @param int height        vyska okna terezy
	 */
	this.insert = function(elemId, width, height)
	{
		this._log("insert");

		if(!swfobject)
		{
			this._err("swfobject is not available!");
			return -2;
		}

		// parametry a atributy flashoveho objektu
		var swfParams = {
			wmode: "transparent",
			allowscriptaccess: "always",
			menu: "false",
			quality: "high",
			bgcolor: "#ffffff"
		}
		var swfAttrs = {
			id: "swfObj" + this._id,
			name: "swfObj" + this._id
		};
		// predavane promenne
		var swfVars = {
			tag: "produkce",
			appid: this._id,
			mode: (this._layout == Tereza.LAYOUT.embed) ? "embed" : "popup",
			lang: this._lang,
			url_webservice: this._urlMiddleware,
			url_media: this._urlMedia,
			grafv: this._entryNode
		};

		swfobject.embedSWF(
			// TODO: doplnit varianty flashe
			this._urlAssets + "/" + "tereza_" + this._build + ".swf", // cesta k swf
			elemId,
			width,
			height, 
			"9.0.0", 
			this._urlAssets + "/install.swf", // flash installation link
			swfVars, 
			swfParams,
			swfAttrs
		);
		// odstranit aktivacni ramecek
		swfobject.createCSS("object", "border:none; outline:none;")

		this._parentElemId = elemId;
		this._swfElemId = "swfObj" + this._id;

		return 1;
	}

	/**
	 * Zrusi flashovy objekt.
	 */
	this.remove = function()
	{
		this._log("remove");

		var elem = this._getSwfObj();
		if(!elem)
		{
			this._err("swfobject element not found!");
			return -3;
		}

		elem.parentNode.removeChild(elem);
		return 1;
	}

	/**
	 * Odesle text flashovemu objektu.
	 */
	this.query = function(text)
	{
		this._log("query");

		var elem = this._getSwfObj();
		if(!elem)
		{
			this._err("swfobject element not found!");
			return -3;
		}

		elem.swfquery(text);
		return 1;
	}

	/**
	 * Informuje flashovy objekt o skryti (prestane prehravat zvuk a animace).
	 */
	this.postpone = function()
	{
		this._log("postpone");

		var elem = this._getSwfObj();
		if(!elem)
		{
			this._err("swfobject element not found!");
			return -3;
		}

		elem.swfpostpone();
		return 1;
	}

	/**
	 * Informuje flashovy objekt o znovu-objeveni (posle pozadavek o navazani
	 * predchozi session specialnim zpusobem).
	 */
	this.restore = function()
	{
		this._log("restore");

		var elem = this._getSwfObj();
		if(!elem)
		{
			this._err("swfobject element not found!");
			return -3;
		}

		elem.swfrestore();
		return 1;
	}

	/**
	 * Ulozi atribut.
	 * @param key       klic atributu
	 * @param value     hodnota atributu
	 */
	this.setAttr = function(key, value)
	{
		this._log("setAttrib");
		this._log("storing pair: [" + key + ":" + value + "]");
		this._setCookie(key, value);
	}

	/**
	 * Vrati atribut (pokud neni ulozen/neexistuje vrati defaultni hodnotu).
	 * @param key       klic atributu
	 * @param defaultValue     hodnota atributu v pripade ze neni nalezen
	 */
	this.getAttr = function(key, defaultValue)
	{
		this._log("getAttrib");
		var r = this._getCookie(key);

		if(r == null)
		{
			this._log("pair not found! reverting to default value `" + defaultValue + "'");
			return defaultValue;
		}

		this._log("loaded pair: [" + key + ":" + r + "]");

		return r;
	}

	/* --------------------------------------------------------------------- *
	 *                              PRIVATNI METODY                          *
	 * --------------------------------------------------------------------- */
	/**
	 * Vrati DOM objekt SWF elementu pokud existuje, jinak NULL.
	 */
	this._getSwfObj = function()
	{
		return document.getElementById(this._swfElemId);
	}

	/**
	 * Nacte prislusny parametr z URL ([?&]param=value).
	 * @param string name       nazev parametru
	 * @return string 
	 */
	this._getUrlParam = function(name)
	{
		var pName = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var re = new RegExp("[\\?&]"+pName+"=([^&#]*)");

		var r = re.exec(window.location.href);
		if(r == null)
		{
			this._log("parameter `" + name + "' not found in URL!");
			return null;
		}
		else
		{
			r = unescape(r[1]);
			this._log("parameter `" + name + "'=`" + r + "'");
			return r;
		}
	}

	/**
	 * Nacte cookie. Vraci NULL pro nenastavene cookie.
	 * @param string name       nazev cookie
	 * @return string
	 */
	this._getCookie = function(name)
	{
		var cName = "TEREZA" + escape(this._id) + escape(this._build)
			+ "_" + escape(name);

		var cArray = document.cookie.split(";");
		for(var i=0; i < cArray.length; i++)
		{
			var cookie = cArray[i];
			while(cookie.charAt(0) == " ")
				cookie = cookie.substring(1, cookie.length);

			if(cookie.indexOf(cName + "=") == 0)
			{
				var r = cookie.substring(cName.length + 1, cookie.length);
				r = unescape(r);
				this._log("cookie `" + cName + "'=`" + r + "'");
				return r;
			}
		}

		this._log("cookie `" + cName + "' not found!");
		return null;
	}

	/**
	 * Ulozi cookie. V pripade ze value je NULL, cookie bude odnastaveno.
	 * @param string name       nazev cookie
	 * @param string value      hodnota, NULL odnastavi cookie
	 */
	this._setCookie = function(name, value)
	{
		var exp = new Date();
		var cName = "TEREZA" + escape(this._id) + escape(this._build)
			+ "_" + escape(name);

		if(value != null)
		{
			exp.setDate(exp.getDate() + 1);
			this._log("cookie `" + cName + "'=`" + value + "'");
		}
		else
		{
			exp.setDate(exp.getDate() - 1);
			this._log("cookie `" + cName + "' forced to expire");
		}

		document.cookie = cName + "=" + escape(value)
			+ ';path=/;expires=' + exp.toGMTString();
	}

	/**
	 * Zaloguje ladici hlasku do Firebug konzole.
	 * @param string msg        logovana zprava
	 */
	this._log = function(msg)
	{
		if(undefined===window.console || !console || !this._logging)
			return;
		
		console.warn("[Tereza]: " + msg);
		console.trace();
	}

	/**
	 * Zaloguje chybovou hlasku do Firebug konzole.
	 * @param string msg        chybova zprava
	 */
	this._err = function(msg)
	{
		if(undefined===window.console || !console || !this._logging)
			return;

		console.error("[Tereza]: " + msg);
		console.trace();
	}

	/* --------------------------------------------------------------------- *
	 *                               KONSTRUKTOR                             *
	 * --------------------------------------------------------------------- */
	{
		this._log("init");

		this._id = id;
		this._layout = layout;
		this._urlMiddleware = urlMiddleware;
		this._urlMedia = urlMedia;
		this._urlAssets = urlAssets;
		this._entryNode = entryNode;
		this._lang = lang;

		this._log("initialized: {"
			+ this._id + ","
			+ this._layout.toString() + ","
			+ this._urlMiddleware + ","
			+ this._urlMedia + ","
			+ this._urlAssets + ","
			+ this._entryNode + ","
			+ this._lang + "}");
	}
}


/**
 * Konstanty
 */
Tereza.LAYOUT = {"embed":0, "popup":1};
Tereza._uniqId = 0;
