//Namespace
if (typeof EnergyApps == "undefined"){EnergyApps = {Webfeature: {}};}
if (typeof EnergyApps.Webfeature == "undefined"){EnergyApps.Webfeature = {Box: {}, Manager: {}, HeaderVisual: {}};}

/**
 * GENERAL link manager as this selector is really big - "abused" for other link bindings too
 * TODO: rename towards general link manager or sth like that
 *
 * @class EnergyApps.Webfeature.Manager
 * @namespace EnergyApps.Webfeature
 * @extends Publicis.Observable
 * @constructor
 * @param {Object} cfg Configuration options
 * @author Alexis Dorn
 * @author Sebastian Sauer
 *
 */
EnergyApps.Webfeature.Manager = function(cfg){
	EnergyApps.Webfeature.Manager.superclass.constructor.call(this, cfg);
	this.rootpath = "/apps/features";
	this.fallbackpath = this.rootpath + "/fallback.jpg";
	this.findFeatures ();
}
Publicis.extend(EnergyApps.Webfeature.Manager, Publicis.Observable, {
	/**
	 * @private
	 */
	findFeatures: function(){
		var i = 0;
		$A(document.getElementsByTagName("a")).each(
			function (item){
				item = $(item);
				i++;
				switch(item.rel){
					case "webfeature_b2":
						var layer = new EnergyApps.Webfeature.Box({
							idContainer: "webfeature_container_b2_" + i,
							idSwf: "webfeature_container_b2_swf_container_" + i,
							trigger: item,
							manager: this
						});
					break;
					case "webfeature_a1":
						var layer = new EnergyApps.Webfeature.HeaderVisual({
							idContainer: "headermedia-zone",
							tmpA: item,
							manager: this
						});
					break;
					case "webfeature_b1":
						var linkClass = "featurelink_b1";
						if (GLOBAL_PAGE_LANG && GLOBAL_PAGE_LANG.length > 0) {
							switch (GLOBAL_PAGE_LANG) {
								case 'de':
									linkClass += " featurelink_b1_de"
									break;
							}
						}
						var newATag = this.addCrateANode(item.getAttribute('href'), document.getElementById("fluid-zone"), linkClass);
						var layer = new EnergyApps.Webfeature.Box({
							idContainer: "webfeature_container_b2_" + i,
							idSwf: "webfeature_container_b2_swf_container_" + i,
							trigger: newATag,
							manager: this
						});
					break;
					case "form":
						var layer = new EnergyApps.Form.Layer({
							layerType : "form",
							idContainer: "form_container_" + i,
							trigger: item,
							manager: this
						});
					break;
				}


			}.bind(this)
		);
		//call b2 feature by hash in url e.g. #webfeature=/apps/features/testname/all/de
		if (location.hash.indexOf("#webfeature=") != -1){
			i++;
			var newATag = this.addCrateANode(location.hash, document.getElementsByTagName("body")[0], "");
			var layer = new EnergyApps.Webfeature.Box({
				idContainer: "webfeature_container_b2_" + i,
				idSwf: "webfeature_container_b2_swf_container_" + i,
				trigger: newATag,
				manager: this
			});
			layer.open();
		}

		if (location.hash.indexOf("#form=") != -1){
			i++;
			var href = (function () {
				var parts = location.hash.split( /#/ ),
					i;
				for( i in parts ) {
					if( (/form=/).test( parts[ i ] ) ) { 
						return parts[ i ].replace(/form=/, "" );						
					}
				}
			})(), 
			newATag, layer;
			if( ! href ) { 
				return; 
			}
			newATag = this.addCrateANode( href, document.getElementsByTagName("body")[0], "");
			layer = new EnergyApps.Form.Layer( {
					layerType : "form",
					idContainer: "form_container_" + i,
					trigger: newATag,
					manager: this
			} );
			
			layer.open();
		}

	},
	/**
	 * @private
	 * @param {String} href URL for the new a node
	 * @param {DOMElement} container node to which the new a tag will be apended
	 * @param {String} cssClass class attribute of new a node
	 */
	addCrateANode: function (href, container, cssClass){
		try {
			var cssClass = (typeof cssClass == "string") ? cssClass : "";
			var id = Publicis.uniqueId () ;
			var template =  new Template([
					'<a href="' + href + '" rel="webfeature_b2" onclick="return false" class="' + cssClass + '" id="' + id + '">',
					'<a>'
				].join("")
			);
			var newATag = template.evaluate({});
			if (container !== null) {
				container = $(container);
				container.insert({
					bottom: newATag
				});
			}
			return $(document.getElementById(id));
		}catch(e){

		}
	},
	/**
	 * @private
	 * @param {String} hashpath path or url
	 */
	getBasePath: function (hashpath){
		var splitted = hashpath.split("#webfeature=");
		return splitted.pop();
	},
	/**
	 * @private
	 */
	parseXMLResponse: function (xmldoc, basepath){
		var data = {href: "", flashVars: {}, flashParams: {}, fallback: {}}, item = false, subitems = false, subitem = false, fallbackItems = false;
		var root = xmldoc.documentElement;
		var children = root.childNodes;
		data.href = basepath + root.getAttribute('href');
		for (var i = 0; i < children.length; i++) {
			item = children[i];
			if (item.nodeType != 1){
				continue;
			}
			if (item.nodeName == "flashParams" || item.nodeName == "flashVars" || item.nodeName == "flashInfo"){
				subitems = item.childNodes;
				for (var j = 0; j < subitems.length; j++) {
					subitem = subitems[j];
					if (subitem.nodeType != 1) {
						continue;
					}
					if (item.nodeName != "flashInfo") {
						data[item.nodeName][subitem.getAttribute("name")] = this.getNodeVal(subitem);
					}else if (subitem.nodeName == "fallback"){
						fallbackItems = subitem.childNodes;
						for (var k = 0; k < fallbackItems.length; k++) {
							if (fallbackItems[k].nodeType == 1){
								if (fallbackItems[k].nodeName == "text") {
									data.fallback.text = this.getNodeVal(fallbackItems[k]);
								}
								if (fallbackItems[k].nodeName == "img") {
									data.fallback.img = basepath + fallbackItems[k].getAttribute("src");
								}
							}
						}
					}
				}
			}
		}
		//Obligatory flash params
		data.flashParams.wmode = "transparent";
		data.flashParams.scale = "noscale";
		data.flashParams.salign = "TL";

		data.flashVars.basepath = basepath;
		return data;
	},
	/**
	 * @private
	 */
	getNodeVal : function (node) {
		try {
			if(node.textContent) {
				return node.textContent;
		    }
		    return node.text;
		} catch (e) { return ''; }
	}
});

/**
 * @class EnergyApps.Webfeature.HeaderVisual
 * @namespace EnergyApps.Webfeature
 * @extends Publicis.Observable
 * @constructor
 * @param {Object} cfg Configuration options
 * @author Alexis Dorn
 */
EnergyApps.Webfeature.HeaderVisual = function (config){
	/**
	 * @cfg {DOMNode} tmpA <b>Obligatory:</b> info node, will be deleted
	 */
	this.tmpA = config.tmpA;
	/**
	 * @cfg {EnergyApps.Webfeature.Manager} manager <b>Obligatory:</b> Instance of EnergyApps.Webfeature.Manager
	 */
	this.manager = config.manager;
	/**
	 * @cfg {String} idContainer <b>Obligatory:</b> DOM ID of container for swf movie
	 */
	this.idContainer = config.idContainer;

	EnergyApps.Webfeature.HeaderVisual.superclass.constructor.call(this, config);

	this.basepath = this.getBasePath(this.tmpA.readAttribute('href'));

	this.loadConfig();
}
Publicis.extend(EnergyApps.Webfeature.HeaderVisual, Publicis.Observable, {
	/**
	 * @private
	 */
	getBasePath: function (hashpath){
		return this.manager.getBasePath(hashpath);
	},
	/**
	 * @private
	 */
	loadConfig: function (){
		    url = this.basepath + "/config.xml";
			try {
				var xhr = new Ajax.Request(
					url,
					{
						method: 'get',
						onSuccess: this.requestOK.bind(this),
						onFailure : this.requestNotOK.bind(this),
						onException: this.requestNotOK.bind(this)
					}
				);
			} catch (e) {
				this.requestNotOK();
				return;
            }
	},
	/**
	 * @private
	 */
	requestOK: function (response){
		try {
			if (null === response.responseXML) {
				this.requestNotOK();
				return;
			}
			var xml = response.responseXML;
			this.featureData = this.manager.parseXMLResponse(xml, this.basepath);
			swfobject.embedSWF(
				this.featureData.href,
				this.idContainer,
				"989",
				"393",
				"9.0.0",
				'/apps/features/swfobject/expressInstall.swf',
				this.featureData.flashVars,
				this.featureData.flashParams,
				null,
				this.callbackSWFObject.bind(this)
			);
		}catch(e){
			this.requestNotOK();
		}
	},
	requestNotOK: function (){
		var img = "/apps/features/fallback.jpg";
		if (this.featureData && this.featureData.fallback && this.featureData.fallback.img){
			img = this.featureData.fallback.img;
		}
		var container = document.getElementById(this.idContainer);
		if (container){
			container.style.height = "393px";
			container.style.width = "989px";
			container.style.background = "url(" + img + ")";
		}
	},
	callbackSWFObject: function (e){
		if (e.success === false){
			this.requestNotOK();
		}
	}
});
/**
 * @class EnergyApps.Webfeature.Box
 * @namespace EnergyApps.Webfeature
 * @extends Publicis.Lightbox
 * @constructor
 * @param {Object} cfg Configuration options
 * @author Alexis Dorn
 */
EnergyApps.Webfeature.Box = function (config){

	EnergyApps.Webfeature.Box.superclass.constructor.call(this, config);

	this.swfContainer = $(config.idSwf);
	/**
	 * @cfg {EnergyApps.Webfeature.Manager} manager <b>Obligatory:</b> Instance of EnergyApps.Webfeature.Manager
	 */
	this.manager = config.manager;
	this.featureData = false;
	this.actualSWFDivId = false;
	this.replacerDiv = false;

	this.tmpSwfContainerBackground = this.swfContainer.getStyle("background-image");

	this.addListener("open", function (){
		this.actualSWFDivId = this.swfContainer.id + "_" + Date.parse(new Date());
		this.replacerDiv = new Element ("div", {id: this.actualSWFDivId});
		this.swfContainer.insert({bottom: this.replacerDiv});

		this.loadConfig();

	}, this);

	this.addListener("close", function (){
		try {
			swfobject.removeSWF(this.actualSWFDivId);
			this.featureData = false;
			this.actualSWFDivId = false;
			this.replacerDiv = false;
			if (this.tmpSwfContainerBackground != this.swfContainer.getStyle("background-image")){
				this.swfContainer.style.backgroundImage = this.tmpSwfContainerBackground;
			}
			if ((this.replacerDiv instanceof Element)) {
				Publicis.discardElement(this.replacerDiv);
			}
		}catch(e){

		}
	}, this);
	this.basepath = this.getBasePath(this.trigger.readAttribute('href'));
}
Publicis.extend (EnergyApps.Webfeature.Box, Publicis.Lightbox, {
	/**
	 * @private
	 */
	getBasePath: function (hashpath){
		return this.manager.getBasePath(hashpath);
	},
	/**
	 * @private
	 */
	loadConfig: function (){
		    url = this.basepath + "/config.xml";
			try {
				var xhr = new Ajax.Request(
					url,
					{
						method: 'get',
						onSuccess: this.requestOK.bind(this),
						onFailure : this.requestNotOK.bind(this),
						onException: this.requestNotOK.bind(this)
					}
				);
			} catch (e) {
				this.requestNotOK();
				return;
            }
	},
	/**
	 * @private
	 */
	requestOK: function (response){
		try {
			if (null === response.responseXML) {
				this.requestNotOK();
				return;
			}
			var xml = response.responseXML;
			this.featureData = this.manager.parseXMLResponse(xml, this.basepath);
			swfobject.embedSWF(
				this.featureData.href,
				this.replacerDiv.id,
				"960",
				"393",
				"9.0.0",
				'/apps/features/swfobject/expressInstall.swf',
				this.featureData.flashVars,
				this.featureData.flashParams,
				null,
				this.callbackSWFObject.bind(this)
			);
		}catch(e){
			this.requestNotOK();
		}
	},
	requestNotOK: function (){
		if (this.replacerDiv instanceof Element){
			Publicis.discardElement(this.replacerDiv);
		}
		var img = "/apps/features/fallback.jpg";
		if (this.featureData && this.featureData.fallback && this.featureData.fallback.img){
			img = this.featureData.fallback.img;
		}
		this.swfContainer.style.backgroundImage = "url(" + img + ")";
	},
	removeReplacerDiv: function (){
		Publicis.discardElement()
	},
	callbackSWFObject: function (e){
		if (e.success === false){
			this.requestNotOK();
		}
	}
})

