//Namespace
if (typeof EnergyApps == "undefined"){EnergyApps = {DownloadArea: {}};}
if (typeof EnergyApps.DownloadArea == "undefined"){EnergyApps.DownloadArea = {};}

/**
 * @class EnergyApps.DownloadArea.Panel
 * @namespace EnergyApps.DownloadArea
 * @extends Publicis.Observable
 * Renders and manage the download area
 * <br><br>
 * <b>Only should be instantiated once per page or optimized for total unique IDs and css classes</b>.
 * <br><br>
 * Dependency on Prototype.js Version 1.6.x, scal (calendar: see root/framework/pub/script/module/scal.js), SPRY (Spry.Widget.TabbedPanels see http://labs.adobe.com/technologies/spry/articles/data_api/apis/tabbed_panels.html ), Publicis framework 
 * @constructor
 * Creates a new download area panel<br>
 * <b>It can only be used as a SINGELTON pattern.</b> A JS Class has been implemented for inheritance reasons (Publics.Observable, mandant inheritance for extending and overwriting)
 * @param {Object} cfg Configuration options
 * @author Alexis Dorn
 */
EnergyApps.DownloadArea.Panel = function(cfg){
	/**
	 * @private
	 */
	this.cfg = Object.clone(cfg);
	/**
	 * @cfg {String|DOMElement} renderTo <b>Obligatory:</b> Container Element of search area
	 */
	this.el = $(this.cfg.renderTo);
	/**
	* @cfg {String} id Unique ID for the component
	*/ 
	if (typeof this.cfg.id == "undefined"){
		this.cfg.id = Publicis.uniqueId();
	}
	/**
	 * @private
	 */
	this.template = false;
	/**
	 * @private
	 */
	this.lang = false;
	/**
	 * @private
	 */
	this.rendered = false;
	/**
	 * Saves the instances search panels
	 * @private
	 */
	this.searchpanels = {};
	/**
	 * Instance of EnergyApps.DownloadArea.ResultPanel
	 * @private 
	 */
	this.resultpanel = false;
	/**
	 * Is not false, if searchdata has been given by url of current page
	 */
	this.urldata = false;
	
	EnergyApps.DownloadArea.Panel.superclass.constructor.call(this, cfg);
	
	this.registerEvent([
		/**
		 * @event render
		 * Fires when component is rendered
		 * @param {EnergyApps.DownloadArea.Panel} this
		 * @param {Prototype.Element} this.el
		 */
		"render",
		/**
		 * @event tabchange
		 * Fires when a tab of tabbed panel has been changed
		 * @param {EnergyApps.DownloadArea.Panel} this
		 * @param {Spry.Widget.TabbedPanels} Component (see http://labs.adobe.com/technologies/spry/articles/data_api/apis/tabbed_panels.html for api)
		 * @param {DOMElement} DOM Element of the tab
		 */
		"tabchange"
		]
	);
};
Publicis.extend(EnergyApps.DownloadArea.Panel, Publicis.Observable, {
	/**
	 * Will render and instantiate all components
	 */
	start: function (){
		if (window.location.search.indexOf("dlsearch=1") != -1){
			this.urldata = window.location.href.toQueryParams();
			delete this.urldata.dlsearch;
			delete this.urldata.foldername; 
		}
		this.render();
		if (this.hasSearchDataByUrl() === true){
			this.searchByUrlData();
		}
	},
	/**
	 * Starts search with given searchparams by url
	 * @private
	 */
	searchByUrlData: function(){
		/*
		->this data can be the result of url
		keywords=key1%2C%20key2
		fiProductFamily=wert_family
		fiProductName=wert_name
		fiProductVersion=wert_version
		fiDocumentType=wert_type
		fiLanguage=wert_language
		fiReleaseDateFrom=03%2F21%2F10
		fiReleaseDateTo=03%2F22%2F10
		foldername=wert_folder 
		*/
		var sSearchpanel = this.searchpanels.ProductsAndSystems,
			isKeywordSearch = false;
		//getting searchpanel
		if (this.isKeywordUrlSearch()){
			this.tabbedPanel.showPanel(1);
			sSearchpanel = this.searchpanels.Keywords;
			isKeywordSearch = true;
		}
		//fill search fields
		sSearchpanel.fillURLData(this.urldata);
	},
	/**
	 * Gets the URL data for seaching if passed
	 * @return Object|boolean
	 */
	getUrlSearchdata: function(){
		return this.urldata;
	},
	/**
	 * Returns, if searchdata has been passed by url.
	 * @return boolean
	 * @private
	 */
	hasSearchDataByUrl: function (){
		return (this.urldata === false) ? false : true;
	},
	/**
	 * Returns, if its a Keywordsearch
	 * @return boolean
	 * @private
	 */
	isKeywordUrlSearch: function (){
		if (this.urldata !== false){
			return (typeof this.urldata.keywords != "undefined");
		}
	},
	/**
	 * Repaint View for layout bugs in IE
	 */
	repaintView: function (){
		if (Prototype.Browser.IE) {
			//Repaint it
			$(this.el).addClassName("nonsense-for-ie");
			$(this.el).removeClassName("nonsense-for-ie");
		}
	},
	/**
	 * Clears the result panel
	 */
	clearResult: function(){
		//Closing all Date Picker
		this.closeAllCalendars();
		this.resultpanel.clearResult();
	},
	/**
	 * Start searching with data from searchpanel
	 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} searchpanel
	 */
	search: function (searchpanel){
		this.onSearchButtonClick(searchpanel);
	},
	/**
	 * Callback of event searchpanel.searchbuttonclick
	 * Starts the search and presentation in resultpanel
	 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} searchpanel
	 * @private
	 */
	onSearchButtonClick: function (searchpanel){
		//Getting filter data
		var data = searchpanel.getData();
		//Closing all Date Picker
		this.closeAllCalendars();
		//Starting update xhr with filterdata
		this.resultpanel.update (data);
	},
	/**
	 * Callback of event searchpanel.resetbuttonclick
	 * Deletes presentation in resultpanel
	 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} searchpanel
	 * @private
	 * @TODO
	 */
	onResetButtonClick: function (searchpanel){
		this.clearResult();
		this.enableSearchbuttons();
	},
	/**
	 * Disables search buttons of search panels while requesting search results
	 * @param {Object} resultpanel
	 * @param {Object} filterdata
	 * @private
	 */
	onBeforeSearch: function (resultpanel, filterdata){
		this.disableSearchbuttons();
	},
	/**
	 * Enables search buttons of search panels after requesting search results
	 * @param {Object} resultpanel
	 * @param {Object} responsedata
	 * @private
	 */
	onSearchReady: function (resultpanel, responsedata){
		this.enableSearchbuttons();
	},
	/**
	 * Callback of searchpanel event combobox is loading
	 * @private
	 */
	onSelectBoxIsLoading: function (){
		this.disableSearchbuttons();
	},
	/**
	 * Callback of searchpanel event combobox is loaded
	 * @private
	 */
	onSelectBoxIsLoaded: function (){
		this.enableSearchbuttons();
	},
	/**
	 * Disables the searchbutons of all searchpanels
	 */
	disableSearchbuttons: function (){
		for (var i in this.searchpanels) {
			this.searchpanels[i].disableSearchButton();
		}
	},
	/**
	 * Enables the searchbutons of all searchpanels
	 */
	enableSearchbuttons: function (){
		for (var i in this.searchpanels) {
			this.searchpanels[i].enableSearchButton();
		}
	},
	/**
	 * Callback when DOMNode of tabpanel has been clicked
	 * @param {Event} e
	 * @private
	 */
	onSpryTabClick: function (e){
		var el = Event.element(e);
		//Closing all selectbox lists 
		Publicis.Components.SelectBoxManager.closeOthers(false);
		//Closing all Date Picker
		this.closeAllCalendars();
		//Deleting search result
		this.resultpanel.clearResult();
		//Resetting of the filter in searchdata
		for (var i in this.searchpanels) {
			this.searchpanels[i].reset();
		}
		this.fireEvent("tabchange", this, this.tabbedPanel, el); 
	},
	/**
	 * Closing all data picker of calendars
	 * @private
	 */
	closeAllCalendars: function (){
		//Closing all date picker
		for (var j in this.searchpanels) {
			var calendars = this.searchpanels[j].getCalendars();
			for (var i in calendars) {
				calendars[i].closeCalendar();
			}
		}
	},
	/**
	 * Renders the complete download area view 
	 * @private
	 */
	render: function (){
		var template = this.getTemplate();
		var replaceObject = this.getLang();
		for(var i in this.cfg){
			replaceObject[i] = this.cfg[i];
		}
		
		this.el.update(template.evaluate(replaceObject));
		
		this.searchpanels.ProductsAndSystems  = new EnergyApps.DownloadArea.SearchPanelProducts({
			renderTo: this.cfg.id + "-downloadSearchPuAPanel",
			listeners: {
				searchbuttonclick: {
					fn: this.onSearchButtonClick,
					scope: this
				},
				resetbuttonclick: {
					fn: this.onResetButtonClick,
					scope: this
				},
				startload: {
					fn: this.onSelectBoxIsLoading,
					scope: this
				},
				load: {
					fn: this.onSelectBoxIsLoaded,
					scope: this
				}
			}
		}, this);
		
		this.searchpanels.Keywords  = new EnergyApps.DownloadArea.SearchPanelKeywords({
			renderTo: this.cfg.id + "-downloadSearchKey",
			listeners: {
				searchbuttonclick: {
					fn: this.onSearchButtonClick,
					scope: this
				},
				resetbuttonclick: {
					fn: this.onResetButtonClick,
					scope: this
				}
			}
		}, this);
		
		//energy-downloadarea will be a tabbed area
		//see http://labs.adobe.com/technologies/spry/articles/data_api/apis/tabbed_panels.html for api
		this.tabbedPanel = new Spry.Widget.TabbedPanels("energy-downloadarea");   
		
		this.tabPuA = $(this.cfg.id + "-tabPuA");
		this.tabKeywords = $(this.cfg.id + "-tabKeywords");
		
		this.tabPuA.observe("click", this.onSpryTabClick.bindAsEventListener(this));
		this.tabKeywords.observe("click", this.onSpryTabClick.bindAsEventListener(this));
		
		//build render result area
		this.resultpanel = new EnergyApps.DownloadArea.ResultPanel({
			id: this.cfg.id + "-resultarea",
			renderTo: this.cfg.id + "-resultcontainer",
			listeners: {
				beforesearch: {
					fn: this.onBeforeSearch,
					scope: this
				},
				search: {
					fn: this.onSearchReady,
					scope: this
				}
			}
		}, this);
		
		this.rendered = true;
		this.fireEvent("render", this, this.el);
	},
	/**
	 * Gets the language texts for view
	 * @private
	 */
	getLang: function (){
		if (this.lang !== false){
			return this.lang;
		}
		
		else{
			this.lang = {
				en: {
					fiProductFamily: "Product Family",
					fiProductName: "Product",
					fiProductVersion: "Product Version",
					fiDocumentType: "Downloads",
					fiLanguage: "Language",
					registerTitleProductsAndSystems: "Products & Systems",
					registerTitleKeywordSearch: "Search Keywords",
					labelProductFamily: "Product Family", 
					labelProductVersion: "Product / Version", 
					labelDocument: "Downloads",
					labelReleaseDate: "Release Date",
					labelKeywords: "Keywords",
					labelResetButton: "Reset",
					labelSearchButton: "Search",
					labelEmptyKeywords: "Comma Separated Values",
					textNoResultFound: "",
					labelCountPages: "Objects per page",
					templatePageInformation: "Object #{from} to #{to} of #{totalcount} (page #{pagenumber} of #{pagentotalcount})",
					headerReleaseDate: "Release Date",
					headerDescription: "Description",
					headerType: "Type",
					headerDocuments: "Downloads",
					headerLanguage: "Language",
					headerVersion: "Version",
					headerSize: "Size",
					msgNotCorrectToDate: "The selected date of \"Release Date To\" must be bigger then \"Release Date From\"!",
					msgNotCorrectFromDate: "The selected date of \"Release Date From\" must be smaller then \"Release Date To\"!"
				},
				de: {
					fiProductFamily: "Produktfamilie",
					fiProductName: "Produkt",
					fiProductVersion: "Produktversion",
					fiDocumentType: "Downloads",
					fiLanguage: "Sprache",
					registerTitleProductsAndSystems: "Produkte & Anlagen",
					registerTitleKeywordSearch: "Schlagwortsuche",
					labelProductFamily: "Produktfamilie",
					labelProductVersion: "Produkt / Version", 
					labelDocument: "Downloads",
					labelReleaseDate: "Freigabedatum",
					labelKeywords: "Schlagwörter",
					labelResetButton: "Reset",
					labelSearchButton: "Suchen",
					labelEmptyKeywords: "Komma separiert Werte",
					textNoResultFound: "",
					labelCountPages: "Objekte pro Seite",
					templatePageInformation: "Objekt #{from} bis #{to} von #{totalcount} (Seite #{pagenumber} von #{pagentotalcount})",
					headerReleaseDate: "Freigabedatum",
					headerDescription: "Beschreibung",
					headerType: "Typ",
					headerDocuments: "Downloads",
					headerLanguage: "Sprache",
					headerVersion: "Version",
					headerSize: "Größe",
					msgNotCorrectToDate: "Der gewählte Wert für \"Freigabedatum Bis\" darf nicht kleiner sein als der Wert \"Freigabedatum Von\"!",
					msgNotCorrectFromDate: "Der gewählte Wert für \"Freigabedatum Von\" darf nicht größer sein als der Wert \"Freigabedatum Bis\"!"
				}
			}[(GLOBAL_PAGE_LANG == "en" || GLOBAL_PAGE_LANG == "de") ? GLOBAL_PAGE_LANG : "en"];
			
			return this.lang;
		}
	},
	/**
	 * Gets the prototype search template for thesearch area
	 * @return Template See Prototype documentation
	 * @private
	 */
	getTemplate: function (){
		if (this.template instanceof Template){
			return this.template;
		}
		this.template = new Template([
			'<div id="energy-downloadarea" class="TabbedPanels">',
				'<ul class="TabbedPanelsTabGroup">',
					'<li class="TabbedPanelsTab" id="#{id}-tabPuA">#{registerTitleProductsAndSystems}</li>',
					'<li class="TabbedPanelsTab" id="#{id}-tabKeywords">#{registerTitleKeywordSearch}</li>',
				'</ul>',
				'<div class="TabbedPanelsContentGroup">',
					'<div class="TabbedPanelsContent" id="#{id}-downloadSearchPuAPanel"></div>',
					'<div class="TabbedPanelsContent" id="#{id}-downloadSearchKey"></div>',
				'</div>',
			'</div>',
			'<div style="clear:both;"></div>',
			'<div id="#{id}-resultcontainer" class="downloadResult"></div>'
		].join(""));
		return this.template;
	}
});

/**
 * @class EnergyApps.DownloadArea.AbstractSearchPanel
 * @namespace EnergyApps.DownloadArea
 * @extends Publicis.Observable
 * Abstract class for implementation in subclasses.Nevershoul be instantiated directly
 * <br><br>
 * Dependency on Prototype.js Version 1.6.x, scal (calendar: see root/framework/pub/script/module/scal.js), SPRY (Spry.Widget.TabbedPanels see http://labs.adobe.com/technologies/spry/articles/data_api/apis/tabbed_panels.html ), Publicis framework and more 
 * @constructor
 * Never should be instantiated directly
 * @param {Object} cfg Configuration options
 * @param {EnergyApps.DownloadArea.Panel}
 * @author Alexis Dorn
 */
EnergyApps.DownloadArea.AbstractSearchPanel = function (cfg, panelManager){
	/**
	 * The global panelmanager 
	 * @type EnergyApps.DownloadArea.Panel
	 * @private 
	 */
	this.panelManager = panelManager;
	/**
	 * @private
	 */
	this.cfg = Object.clone(cfg);
	/**
	 * @cfg {String|DOMElement} renderTo <b>Obligatory:</b> Container Element of search area
	 */
	this.el = $(this.cfg.renderTo);
	/**
	* @cfg {String} id Unique ID for the component
	*/ 
	if (typeof this.cfg.id == "undefined"){
		this.cfg.id = Publicis.uniqueId();
	}
	/**
	 * @private
	 */
	this.template = false;
	/**
	 * @private
	 */
	this.lang = false;
	/**
	 * @private
	 */
	this.rendered = false;
	/**
	 * @private
	 */
	this.calendars = {};
	/**
	 * @private
	 */
	this.buttons = {};
	/**
	 * @private
	 */
	this.selectboxes = {};
	/**
	 * @private
	 */
	this.tabbedPanel = false;
	/**
	 * @private
	 */	
	this.searchButtonDisable = false;
	/**
	 * @private 
	 */
	this.loadingboxes = [];
	
	//Calling parent constructor
	EnergyApps.DownloadArea.AbstractSearchPanel.superclass.constructor.call(this, cfg);
	
	this.registerEvent([
		/**
		 * @event render
		 * Fires when component is rendered
		 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} this
		 * @param {Prototype.Element} this.el
		 */
		"render",
		/**
		 * @event searchbuttonclick
		 * Fires before search data will be sent to server
		 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} this
		 */
		"searchbuttonclick",
		/**
		 * @event resetbuttonclick
		 * Fires before data will be resetted
		 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} this
		 */
		"resetbuttonclick",
		/**
		 * @event startload
		 * Fires when one selectbox is loading
		 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} this
		 * @param {Publicis.Components.SelectBox} box
		 */
		"startload",
		/**
		 * @event load
		 * Fires when the selectbox has been loaded
		 * @param {EnergyApps.DownloadArea.AbstractSearchPanel} this
		 * @param {Publicis.Components.SelectBox} box
		 */
		"load"
		]
	);
	
	this.render();
};
Publicis.extend(EnergyApps.DownloadArea.AbstractSearchPanel, Publicis.Observable, {
	/**
	 * Return the rendered selectboxes of panel or false if not rendered
	 * @return Object
	 */
	getSelectboxes: function (){
		return this.selectboxes;
	},
	/**
	 * Return the rendered calendars of panel or false if not rendered
	 * @return Object
	 */
	getCalendars: function (){
		return this.calendars;
	},
	/**
	 * Parses the formatted date mm/dd/yy to da js date object
	 * @private
	 * @param {Object} dateString
	 * @return Date
	 */
	parseSearchDateString: function (dateString){
		try {
			dateString = dateString.split("/");
			var year = parseInt(dateString[2], 10);
			var month = parseInt(dateString[0], 10) - 1;
			var day = parseInt(dateString[1], 10);
			year = (year < 2000) ? (year + 2000) : year;
			return new Date(year, month, day);
		}catch(e){
			return new Date();
		}
	},
	/**
	 * Return the rendered buttons of panel or false if not rendered
	 * @return Object
	 */
	getButtons: function (){
		return this.buttons;
	},
	/**
	 * If Searchdata has been passed by url, this method will be called by the EnergyApps.DownloadArea.Panel (panelManager)
	 * to fill the search fields with url params.
	 * Can be overwirtten in subclasses 
	 * @param {Object} searchdata
	 */
	fillURLData: function (searchdata){
		var selboxes = this.getSelectboxes(), i = 0;
		//Updating selectboxes of panel
		for (i in selboxes){
			if (typeof searchdata[i] != "undefined" && !searchdata[i].blank()){
				selboxes[i].disableEvents();
				sData = {};
				sData[i] = searchdata[i];
				selboxes[i].enable(); 
				selboxes[i].update([sData]);
				selboxes[i].setSelectionById(searchdata[i]);
				selboxes[i].enableEvents();
			}
			selboxes[i].disable();
		}
		for (i in this.calendars){
			if (typeof searchdata[i] != "undefined" && !searchdata[i].blank()){
				this.calendars[i].disableEvents();
				searchdata[i] = this.parseSearchDateString(searchdata[i]);
				$(this.calendars[i].getUpdateElement()).value = searchdata[i].format(this.calendars[i].getUpdateFormat());
				this.calendars[i].enableEvents();
			}
			this.calendars[i].disable();
		}
		
	},
	/**
	 * Abstract method to be implementated in subclass
	 * Gets the Configuration of the calendar fields
	 * <br><br>
	 * Has to return an array with objects with following keys.
	 * <br><br>
	 * name, containerid, inputid, iconid
	 * @return Array
	 */
	getCalendarConfig: function (){},
	/**
	 * Abstract method to be implementated in subclass
	 * Gets the Configuration of the buttons
	 * <br><br>
	 * Has to return an object.
	 * <br><br>
	 * {seach: {containerid = "..."}, reset: {containerid = "..."}}
	 * @return Array
	 */
	getButtonConfig: function (){},
	/**
	 * Abstract method to be implementated in subclass
	 * Gets the combo fields configuration
	 * It returns an array of objects with following keys:
	 * <br><br>
	 * field, containerid
	 * @return Object 
	 */
	getSelectboxConfig: function (){},
	/**
	 * Abstract method to be implementated in subclass
	 * Gets the form id for serializing data
	 */
	getFormId: function (){},
	/**
	 * Abstact method for implementation in subclass 
	 * Gets the protptype search template for the search panel
	 * @return Template See Prototype documentation
	 */
	getTemplate: function (){},
	/**
	 * Return the instance of EnergyApps.DownloadArea.Panel
	 * @return EnergyApps.DownloadArea.Panel 
	 */
	getPanelManager: function (){
		return this.panelManager;
	},
	/**
	 * Returns the searchdata of panel
	 */
	getData: function (){
		return $(this.getFormId()).serialize(true);
	},
	/**
	 * Returns all non select box form fields as ID array
	 * @return Array
	 */
	getInputFields: function (){
		var frm = $(this.getFormId()), i;
		var elements = frm.getElements();
		
		var combos = this.getSelectboxes();
		var cmbFieldIds = {};
		for (i in combos){
			cmbFieldIds[combos[i].getInputElement().id] = true;
		}
		var tmp = [];
		for (i = 0; i < elements.length; i++){
			if (typeof cmbFieldIds[elements[i].id] == "undefined"){
				tmp.push(elements[i].id);
			}
		}
		return tmp; 
	},
	/**
	 * Disables Search button
	 */
	disableSearchButton: function (){
		this.searchButtonDisable = true;
		this.buttons.search.setOpacity(0.5);
	},
	/**
	 * Enables Searchbutton
	 */
	enableSearchButton: function (){
		this.searchButtonDisable = false;
		this.buttons.search.setOpacity(1);
	},
	/**
	 * Disables all calendar elements
	 */
	disableCalendars: function (){
		for (var i in this.calendars){
			this.calendars[i].disable();
		}
	},
	/**
	 * Enables all calendar elements
	 */
	enableCalendars: function(){
		for (var i in this.calendars){
			this.calendars[i].enable();
		}
	},
	/**
	 * Extracts the fieldnames of the comboboxes and returns them as array
	 * @return Array
	 * @private
	 */
	getSelectboxConfigAsFieldNames: function (){
		var combos = this.getSelectboxConfig();
		var tmp = [];
		for (var i = 0; i < combos.length; i++){
			tmp.push(combos[i].field);  
		}
		return tmp;
	},
	/**
	 * Gets the language texts for view
	 * @private
	 */
	getLang: function (){
		return this.getPanelManager().getLang();
	},
	/**
	 * @private
	 */
	onXHRFailure: function (){
		alert("An error has occured.");
	},
	/**
	 * Callback when reset button has been clicked (Produkt u Anlagen Form)
	 * @private
	 */
	onResetButtonClick: function (){
		var combos = this.getSelectboxes(), i;
		for (i in combos){
			combos[i].clearSelection();
		}
		var others = this.getInputFields();
		for (i = 0; i < others.length; i++){
			$(others[i]).clear();
		}
		
		this.disableCalendars();
		
		this.fireEvent("resetbuttonclick", this);
	},
	/**
	 * Resets /clears the form
	 * 
	 */
	reset: function (){
		this.onResetButtonClick();
	},
	/**
	 * Callback when search button has been clicked (Produkt u Anlagen Form)
	 * @private
	 */
	onSearchButtonClick: function (){
		if (this.searchButtonDisable){
			return;
		}
		this.fireEvent("searchbuttonclick", this);
	},
	/**
	 * Callback, when input or calendar image has been clicked
	 * @param {Object} e
	 * @param {Object} calobject
	 * @private
	 */
	onCalendarClick: function (e, calobject){
		var el = Event.element(e);
		for (var i in this.calendars){
			this.calendars[i].closeCalendar();
		}
		calobject.toggleCalendar();
	},
	/**
	 * Callback, if data of calendar has been changed.
	 * Seem to be called only if month has been changed in the calendar picker.
	 * @param {Event} eHas adate property with selected date (search in method scal._switchCal for oncalchange, see root/framework/pub/script/module/scal.js)
	 * @private
	 */
	onCalendarChange: function(e){
		//alert("asddas")
		//alert (e.date)	
	},
	/**
	 * Register a Selectbox as loading 
	 * @param {Object} box
	 * @private
	 */
	onSelectboxLoading: function (box){
		this.fireEvent("startload", this, box);
		if (this.loadingboxes.indexOf(box) == -1){
			this.loadingboxes.push(box);
		}
	},
	/**
	 * Fires load event, if ALL loading prozesses of selectboxes a cleared
	 * @param {Object} box
	 * @private
	 */
	onSelectboxLoaded: function (box){
		this.loadingboxes = this.loadingboxes.without(box);
		if(this.loadingboxes.length === 0){
			this.fireEvent("load", this, box);
		}
	},
	/**
	 * Callback method for global event DomReady
	 * Initialization of view
	 * @private
	 */
	render: function (){
		//setting primary template
		this.renderSearchLayer ();
		
		//initialisize selectboxes
		this.renderCombos();
		
		//render calender
		this.renderCalendar();
				
		this.rendered = true;
		this.fireEvent("render", this, this.el);
		
		//xhr request for both forms
		//this.requestCols();
	},
	/**
	 * Rendering of this.template and more
	 * @private
	 */
	renderSearchLayer: function (){
		var template = this.getTemplate();
		var replaceObject = this.getLang();
		for(var i in this.cfg){
			replaceObject[i] = this.cfg[i];
		}
		this.el.update(template.evaluate(replaceObject));
		
		var bttnConfig = this.getButtonConfig();
		
		this.buttons = {
			search: $(bttnConfig.search.containerid),
			reset: $(bttnConfig.reset.containerid)
		};
		this.buttons.reset.observe("click", this.onResetButtonClick.bindAsEventListener(this));
		this.buttons.search.observe("click", this.onSearchButtonClick.bindAsEventListener(this));
	},
	/**
	 * Rendering of selectboxes
	 * @private
	 */
	renderCombos: function (){
		var combos = this.getSelectboxConfig();
		var labels = this.getLang();
		
		this.selectboxes = {};
		for (var i = 0 ; i < combos.length; i++){
			
			var containerName = combos[i].containerid;
			var fieldName = combos[i].field;
			if (!document.getElementById(containerName)){
				continue;
			}
			this.selectboxes[fieldName] = new Publicis.Components.SelectBox({
				renderTo: containerName,
				data: [],
				valueProp: fieldName,
				textProp: fieldName,
				emptyText: labels[fieldName],
				name: fieldName,
				dhtmlScroll: false,
				disabled: combos[i].disabled,
				listeners: {
					beforeload: {
						fn: this.onSelectboxLoading,
						scope: this
					},
					load: {
						fn: this.onSelectboxLoaded,
						scope: this
					}
				}
			});
			//add listeners of configuration
			if (combos[i].listeners){
				for (var j in combos[i].listeners){
					this.selectboxes[fieldName].addListener(j, combos[i].listeners[j].fn, combos[i].listeners[j].scope);
				}
			}
		}
	},
	/**
	 * Renders Calendars and bind events
	 * @private
	 */
	renderCalendar:function (){
		var options = Object.extend({
	        oncalchange: this.onCalendarChange.bind(this),
			weekdaystart: 1
	    });
		
		var calConfig = this.getCalendarConfig();
		
		for (var i = 0; i < calConfig.length; i++){
			//name, containerid, inputid, iconid
			var cfg = calConfig[i]; 
			cfg.disabled = (typeof cfg.disabled == "boolean") ? cfg.disabled : false;
			this.calendars[cfg.name] = new Publicis.ThirdParty.Scal({disabled: cfg.disabled}, cfg.containerid, cfg.inputid, options);
			$(cfg.inputid).observe("click", this.onCalendarClick.bindAsEventListener(this, this.calendars[cfg.name]));
			$(cfg.iconid).observe("click", this.onCalendarClick.bindAsEventListener(this, this.calendars[cfg.name]));
			//add listeners of configuration
			if (cfg.listeners){
				for (var j in cfg.listeners){
					this.calendars[cfg.name].addListener(j, cfg.listeners[j].fn, cfg.listeners[j].scope);
				}
			}
			this.calendars[cfg.name].toggleCalendar();
		}
	},
	/**
	 * Start searching 
	 * @return void
	 */
	search: function (){
		var manager = this.getPanelManager();
		manager.search(this);
	}
});

/**
 * @class EnergyApps.DownloadArea.SearchPanelProducts
 * @namespace EnergyApps.DownloadArea
 * @extends EnergyApps.DownloadArea.AbstractSearchPanel
 * Implementation of abstract class EnergyApps.DownloadArea.AbstractSearchPanel for searchpanel Produkte und Systeme
 * @constructor
 * Creates a new search panel<br>
 * @param {Object} cfg Configuration options
 * @param {EnergyApps.DownloadArea.Panel}
 * @author Alexis Dorn
 */
EnergyApps.DownloadArea.SearchPanelProducts = function (cfg, panelManager){
	/**
	 * @private
	 */
	this.cfg = Object.clone(cfg);
	/**
	 * @cfg {String|DOMElement} renderTo <b>Obligatory:</b> Container Element of search area
	 */
	this.el = $(this.cfg.renderTo);
	/**
	* @cfg {String} id Unique ID for the component
	*/ 
	if (typeof this.cfg.id == "undefined"){
		this.cfg.id = Publicis.uniqueId();
	}
	
	this.comboIsFilledByUrlLogic = {};
	
	EnergyApps.DownloadArea.SearchPanelProducts.superclass.constructor.call(this, this.cfg, panelManager);
	
	this.FillLogicByURL = (!this.getPanelManager().hasSearchDataByUrl() || (this.getPanelManager().hasSearchDataByUrl() && this.getPanelManager().isKeywordUrlSearch())) ? false : true;
	
	//Loading Data of primary boxes 
	this.familyRequest();
	
	
};

Publicis.extend(EnergyApps.DownloadArea.SearchPanelProducts, EnergyApps.DownloadArea.AbstractSearchPanel, {
	/**
	 * overrides parentclass 
	 * @param {Object} searchdata
	 * @private
	 */
	fillURLData: function (searchdata){
		/*
		keywords=key1%2C%20key2
		fiProductFamily=wert_family
		fiProductName=wert_name
		fiProductVersion=wert_version
		fiDocumentType=wert_type
		fiLanguage=wert_language
		fiReleaseDateFrom=03%2F21%2F10
		fiReleaseDateTo=03%2F22%2F10
		foldername=wert_folder 
		*/
		
		//No productFamiliy given
		if (typeof searchdata["fiProductFamily"] == "undefined" || searchdata["fiProductFamily"].blank()){
			this.fillRestAndSearch();
		}
	},
	/**
	 * If url params are given, this methods fills the calendar fields ans starts search.
	 * @return void
	 * @private
	 */
	fillRestAndSearch: function (){
		var searchdata = this.getPanelManager().getUrlSearchdata();
		this.enableCalendars();
		//Fill calendars
		for (i in this.calendars){
			if (typeof searchdata[i] != "undefined" && !searchdata[i].blank()){
				this.calendars[i].disableEvents();
				searchdata[i] = this.parseSearchDateString(searchdata[i]);
				$(this.calendars[i].getUpdateElement()).value = searchdata[i].format(this.calendars[i].getUpdateFormat());
				this.calendars[i].enableEvents();
			}
		}
		this.FillLogicByURL = false;
		this.search();
	},
	/**
	 * Returns true if the value of searchdata could be selected in the select box
	 * @param {String} field name of field
	 * @return Boolean  
	 * @private
	 */
	fillComboInUrlLogic: function (field){
		if (typeof this.comboIsFilledByUrlLogic[field] == "undefined" || this.comboIsFilledByUrlLogic[field] == false) {
			var searchdata = this.getPanelManager().getUrlSearchdata();
			this.comboIsFilledByUrlLogic[field] = true;
			return this.selectboxes[field].setSelectionById(searchdata[field]);
		}
		return true;
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getFormId: function (){
		return this.cfg.id + "-downloadSearchPuA";
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getButtonConfig: function(){
		var buttons = {
			reset: {
				containerid: this.cfg.id + "-resetbutton"
			},
			search: {
				containerid: this.cfg.id + "-searchbutton"
			}
		};
		return buttons;
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getCalendarConfig: function (){
		var calendars = [
			{
				name: "fiReleaseDateFrom", 
				containerid: this.cfg.id + "-fiReleaseDateFromContainer", 
				inputid: this.cfg.id + "-fiReleaseDateFromId",
				iconid: this.cfg.id + "-fiReleaseDateFromIdIcon",
				listeners: {
					beforeupdate:{
						fn: function (scal, updateElement, selDate, fromat){
							var toInput = $(this.calendars.fiReleaseDateTo.getUpdateElement());
							if (toInput.value != ""){
								if (this.calendars.fiReleaseDateTo.getSelectedDate() < selDate){
									alert(this.getLang().msgNotCorrectFromDate);
									return false;
								}
							}
							
						},
						scope: this
					} 
				},
				disabled: true
			},
			{
				name: "fiReleaseDateTo", 
				containerid: this.cfg.id + "-fiReleaseDateToContainer", 
				inputid: this.cfg.id + "-fiReleaseDateToId",
				iconid: this.cfg.id + "-fiReleaseDateToIdIcon",
				listeners: {
					beforeupdate:{
						fn: function (scal, updateElement, selDate, fromat){
							var fromInput = $(this.calendars.fiReleaseDateFrom.getUpdateElement());
							if (fromInput.value != ""){
								if (this.calendars.fiReleaseDateFrom.getSelectedDate() > selDate){
									alert(this.getLang().msgNotCorrectToDate);
									return false;
								}
							}
							
						},
						scope: this
					} 
				},
				disabled: true
			}
		];
		
		return calendars;
	},
	/**
	 * Extends parent method
	 * @private
	 * 
	 */
	onResetButtonClick: function (){
		var comboConfig = this.getSelectboxConfig();
		for (var i = 0; i < comboConfig.length; i++){
			if (comboConfig[i].disabled){
				this.selectboxes[comboConfig[i].field].disable(true);
			}
		}
		EnergyApps.DownloadArea.SearchPanelProducts.superclass.onResetButtonClick.call(this);
		
		this.familyRequest();
	},
	/**
	 * Method for xhr request for selectbox data
	 * @private
	 */
	familyRequest: function (){
		this.selectboxes.fiProductFamily.setLoading();
		var url = RESOURCES_PATH + '../../apps/DownloadPool/proxy_column.php?action=filters.getProductFamily';
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: {},
			onSuccess: this.onLoadFamilyRequest.bind(this),
	        onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
	},
	/**
	 * Callback for this.familyRequest
	 * Observer for the success event of xhr
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	onLoadFamilyRequest: function (respObject){
		var response = respObject.responseText.evalJSON(true);
		if (typeof this.selectboxes.fiProductFamily != "undefined"){
			this.selectboxes.fiProductFamily.clearLoading();
		}
		if (response.success === false){
			this.onXHRFailure();
			return;
		}
		for (var i in response.data){
			if (this.selectboxes[i] instanceof Publicis.Components.SelectBox){
				this.selectboxes[i].update(response.data[i]);
			}
		}
		//Fill logic if url params are present
		if (this.FillLogicByURL){
			if (!this.fillComboInUrlLogic("fiProductFamily")){
				this.fillRestAndSearch();
				return
			}
		}

	},
	/**
	 * @param {Publicis.Components.SelectBox} box SelectBox
	 * @param {Object} selection
	 * @param {Object} oldSelection
	 * @private
	 */
	onSelectFiProductFamily: function (box, selection, oldSelection){
		var i = 0;
		//Deletes results
		this.getPanelManager().clearResult();
		
		//load productnames to selectbox 
		this.loadSelectsByProductFamiliy();
		
		//Disable and reset all other fields 
		var others = [
			"fiProductVersion"
		];
		for (i = 0; i < others.length; i++){
			this.selectboxes[others[i]].clearAll();
			this.selectboxes[others[i]].disable();
		}
	},
	/**
	 * Starts XHR Request for available data of dependend selectboxes of selected fiProductFamily
	 * @private
	 */
	loadSelectsByProductFamiliy: function (){
		var value = this.selectboxes.fiProductFamily.getSelection();
		if (value !== false){
			value = value.value;
		}
		var boxes = [
			"fiProductName",
			"fiDocumentType",
			"fiLanguage"
		];
		for (var i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].clearSelection();
			this.selectboxes[boxes[i]].setLoading();
		}
				
		var url = RESOURCES_PATH + '../../apps/DownloadPool/proxy_column.php?action=filters.getByProductFamily';
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: {
				fiProductFamily: value
			},
	        onSuccess: this.onLoadSelectsByProductFamiliy.bind(this),
	        onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
	},
	/**
	 * Callback for xhr request
	 * Observer for the success event of xhr
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	onLoadSelectsByProductFamiliy: function (respObject){
		var boxes = [
			"fiProductName",
			"fiDocumentType",
			"fiLanguage"
		];
		var i = 0, response;
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].clearLoading();
		}
		
		try{
			response = respObject.responseText.evalJSON(true);
		}catch(e){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		
		if (response.success === false){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		
		var startSearchByUrl = [];
		var searchdata = this.getPanelManager().getUrlSearchdata();
		
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].update(response.data[boxes[i]]);
			//Fill logic if url params are present
			if (this.FillLogicByURL){
				if (typeof searchdata[boxes[i]] == "undefined" || searchdata[boxes[i]].blank()){
					startSearchByUrl.push(boxes[i]);
				}
			}
		}
		//only in process fill logic by url params
		if (this.FillLogicByURL) {
			if (startSearchByUrl.length == 3) {
				//there are no url parameters
				this.fillRestAndSearch();
			//try to fill productName	
			}else if (!this.fillComboInUrlLogic("fiProductName")){
				//try to fill documentType 
				if (!this.fillComboInUrlLogic("fiDocumentType")){
					//try to fill language
					if (!this.fillComboInUrlLogic("fiLanguage")){
						this.fillRestAndSearch();
					}
				}
			} 
		}
		
		this.enableCalendars();
		
	},
	/**
	 * @param {Publicis.Components.SelectBox} box SelectBox
	 * @param {Object} selection
	 * @param {Object} oldSelection
	 * @private
	 */
	onSelectFiProductName: function (box, selection, oldSelection){
		//Deletes results
		this.getPanelManager().clearResult();
		this.loadSelectsByProductName();
		
	},
	/**
	 * Starts XHR Request for available data of dependend selectboxes of selected fiProductFamily and fiProductName
	 * @private
	 */
	loadSelectsByProductName: function (){
		var valueFam = this.selectboxes.fiProductFamily.getSelection();
		if (valueFam === false){
			return;
		}
		var valueNam = this.selectboxes.fiProductName.getSelection();
		if (valueNam === false){
			return;
		}
		var boxes = [
			"fiProductVersion",
			"fiDocumentType",
			"fiLanguage"
		];
		for (var i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].clearSelection();
			this.selectboxes[boxes[i]].setLoading();
		}
				
		var url = RESOURCES_PATH + '../../apps/DownloadPool/proxy_column.php?action=filters.getByProductNameAndFamiliy';
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: {
				fiProductFamily: valueFam.value,
				fiProductName: valueNam.value
			},
	        onSuccess: this.onLoadSelectsByProductName.bind(this),
	        onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
		
	},
	/**
	 * Callback for xhr request
	 * Observer for the success event of xhr
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	onLoadSelectsByProductName: function (respObject){
		var boxes = [
			"fiProductVersion",
			"fiDocumentType",
			"fiLanguage"
		];
		
		var i = 0, response;
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].clearLoading();
		}
		
		try{
			response = respObject.responseText.evalJSON(true);
		}catch(e){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		
		if (response.success === false){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		
		var startSearchByUrl = [];
		var searchdata = this.getPanelManager().getUrlSearchdata();
		
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].update(response.data[boxes[i]]);
			//Fill logic if url params are present
			if (this.FillLogicByURL){
				if (typeof searchdata[boxes[i]] == "undefined" || searchdata[boxes[i]].blank()){
					startSearchByUrl.push(boxes[i]);
				}
			}
		}
		//only in process fill logic by url params
		if (this.FillLogicByURL) {
			if (startSearchByUrl.length == 3) {
				//there are no url parameters
				this.fillRestAndSearch();
			//try to fill productName	
			}else if (!this.fillComboInUrlLogic("fiProductVersion")){
				//try to fill documentType 
				if (!this.fillComboInUrlLogic("fiDocumentType")){
					//try to fill language
					if (!this.fillComboInUrlLogic("fiLanguage")){
						this.fillRestAndSearch();
					}
				}
			} 
		}
	},
	/**
	 * @param {Publicis.Components.SelectBox} box SelectBox
	 * @param {Object} selection
	 * @param {Object} oldSelection
	 * @private
	 */
	onSelectVersionTypeLanguage: function(box, selection, oldSelection){
		var who = false, params = {};
		switch (box){
			case this.selectboxes.fiProductVersion:
				who = "fiProductVersion";
			break;
			case this.selectboxes.fiDocumentType:
				who = "fiDocumentType";
			break;
			case this.selectboxes.fiLanguage:
				who = "fiLanguage";
			break;				
		}
		
		//Collecting Parameters
		params = this.getData();
		params.selectedBox = who;
		
		var boxes = [
			"fiProductVersion",
			"fiDocumentType",
			"fiLanguage"
		];
		for (var i = 0; i < boxes.length; i++){
			if (boxes[i] == who){
				continue;
			}
			if (boxes[i] == "fiProductVersion" && this.selectboxes.fiProductVersion.isDisabled()){
				continue;
			}
			this.selectboxes[boxes[i]].setLoading();
		}
		
		var url = RESOURCES_PATH + '../../apps/DownloadPool/proxy_column.php?action=filters.getByProductFamilyVersionTypeLanguage';
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: params,
	        onSuccess: this.onLoadSelectVersionTypeLanguage.bind(this),
	        onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
	},
	/**
	 * Callback for xhr request
	 * Observer for the success event of xhr
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	onLoadSelectVersionTypeLanguage: function (respObject){
		var boxes = [
			"fiProductVersion",
			"fiDocumentType",
			"fiLanguage"
		];
		var i = 0, response;
		try{
			response = respObject.responseText.evalJSON(true);
		}catch(e){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		var who = response.data.selectedBox;
		//extract selected box for this request
		boxes = boxes.without(who);
		
		var updateVersion = true;
		for (i = 0; i < boxes.length; i++){
			if (boxes[i] == "fiProductVersion" && !this.selectboxes.fiProductVersion.isLoading()){
				updateVersion = false;
				continue;
			}
			this.selectboxes[boxes[i]].clearLoading();
		}
		
		if (response.success === false){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.selectboxes[response.data.selectedBox].disable(true);
			this.onXHRFailure();
			return;
		}
		
		for (i = 0; i < boxes.length; i++){
			if (boxes[i] == "fiProductVersion" && !updateVersion){
				continue;
			}
			this.selectboxes[boxes[i]].disableEvents();
			this.selectboxes[boxes[i]].update(response.data[boxes[i]]);
			this.selectboxes[boxes[i]].enableEvents();
		}
		//only in process fill logic by url params
		if (this.FillLogicByURL) {
			switch (who){
				case "fiProductVersion":
					if (!this.fillComboInUrlLogic("fiDocumentType")){
						//try to fill language
						if (!this.fillComboInUrlLogic("fiLanguage")){
							this.fillRestAndSearch();
						}
					}
				break;
				case "fiDocumentType":
					this.fillComboInUrlLogic("fiLanguage");
					this.fillRestAndSearch();
				break;
				default:
					this.fillRestAndSearch();
				break;	
			}
		}
	},
	/**
	 * Implementation of parent abstract method.
	 * Gets the combo fields configuration 
	 * @return Array 
	 * @private
	 */
	getSelectboxConfig: function (){
		var combos = [
			{field: "fiProductFamily", containerid: "fiProductFamily", disabled: false, listeners: {
				select:{
					fn: this.onSelectFiProductFamily,
					scope: this
				}
			}},
			{field: "fiProductName", containerid: "fiProductName", disabled: true, listeners: {
				select:{
					fn: this.onSelectFiProductName,
					scope: this
				}
			}},
			{field: "fiProductVersion", containerid: "fiProductVersion", disabled: true, listeners: {
				select:{
					fn: this.onSelectVersionTypeLanguage,
					scope: this
				}
			}},
			{field: "fiDocumentType", containerid: "fiDocumentType", disabled: true, listeners: {
				select:{
					fn: this.onSelectVersionTypeLanguage,
					scope: this
				}
			}},
			{field: "fiLanguage", containerid: "fiLanguage", disabled: true, listeners: {
				select:{
					fn: this.onSelectVersionTypeLanguage,
					scope: this
				}
			}}
		];
		return combos;
	},
	/**
	 * Gets the protptype search template for thesearch area
	 * @return Template See Prototype documentation
	 * @private
	 */
	getTemplate: function (){
		if (this.template instanceof Template){
			return this.template;
		}
		this.template = new Template([
			'<form method="post" action="" id="#{id}-downloadSearchPuA">',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelProductFamily}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:450px;">',
							'<div class="legend access">Select product family</div>',
							'<div id="fiProductFamily" class="dlaSelect6_6"></div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelProductVersion}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:311px;">',
							'<div class="legend access">Select product</div>',
							'<div id="fiProductName" class="dlaSelect4_6"></div>',
						'</div>',
						'<div class="fieldsetwrapper">',
							'<div class="legend access">Select product version</div>',
							'<div id="fiProductVersion" class="dlaSelect2_6"></div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelDocument}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:232px;">',
							'<div class="legend access">Select document type</div>',
							'<div id="fiDocumentType" class="dlaSelect3_6"></div>',
						'</div>',
						'<div class="fieldsetwrapper">',
							'<div class="legend access">Select language</div>',
							'<div id="fiLanguage" class="dlaSelect3_6"></div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelReleaseDate}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:232px;">',
							'<div class="legend access">Input release date from</div>',
							'<input type="text" value="" class="datum" name="fiReleaseDateFrom" id="#{id}-fiReleaseDateFromId" readonly="true" onKeyPress="" />',
							'<span class="calbutton" id="#{id}-fiReleaseDateFromIdIcon"><img src="' + RESOURCES_PATH + '../pub/style/img/calendar.gif" alt=""/></span>',
							'<div style="clear:both"></div>',
							'<div id="#{id}-fiReleaseDateFromContainer" class="scal dashblack"> </div>',
						'</div>',
						'<span class="dash-seperator">-</span>',
						'<div class="fieldsetwrapper" style="width:225px;">',
							'<div class="legend access">Input release date to</div>',
							'<input type="text" value="" class="datum" name="fiReleaseDateTo" id="#{id}-fiReleaseDateToId" readonly="true" onKeyPress="" />',
							'<span class="calbutton" id="#{id}-fiReleaseDateToIdIcon"><img src="' + RESOURCES_PATH + '../pub/style/img/calendar.gif" alt=""/></span>',
							'<div style="clear:both"></div>',
							'<div id="#{id}-fiReleaseDateToContainer" class="scal dashblack" style=""> </div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<div class="fieldsetwrapper inputright buttonbox" style="width:105px;">',
						' <a class="generic-button" id="#{id}-resetbutton" href="javascript:void(null)">',
							'<span>',
								'<span>#{labelResetButton}</span>',
							'</span>',
						'</a>',
						' <a class="generic-button" id="#{id}-searchbutton" href="javascript:void(null)">',
							'<span>',
								'<span>#{labelSearchButton}</span>',
							'</span>',
						'</a>',
					'</div>',
				'</div>',
			'</form>'
		].join(""));
		return this.template;
	}
});

/**
 * @class EnergyApps.DownloadArea.SearchPanelKeywords
 * @namespace EnergyApps.DownloadArea
 * @extends EnergyApps.DownloadArea.AbstractSearchPanel
 * Implementation of abstract class EnergyApps.DownloadArea.AbstractSearchPanel for searchpanel Keywords
 * @constructor
 * Creates a new search panel<br>
 * @param {Object} cfg Configuration options
 * @param {EnergyApps.DownloadArea.Panel}
 * @author Alexis Dorn
 */
EnergyApps.DownloadArea.SearchPanelKeywords = function (cfg, panelManager){
	/**
	 * @private
	 */
	this.cfg = Object.clone(cfg);
	/**
	 * @cfg {String|DOMElement} renderTo <b>Obligatory:</b> Container Element of search area
	 */
	this.el = $(this.cfg.renderTo);
	/**
	* @cfg {String} id Unique ID for the component
	*/ 
	if (typeof this.cfg.id == "undefined"){
		this.cfg.id = Publicis.uniqueId();
	}
	
	this.comboIsFilledByUrlLogic = {};
	
	EnergyApps.DownloadArea.SearchPanelKeywords.superclass.constructor.call(this, this.cfg, panelManager);
	
	this.manageKeyWords ();
	
	this.FillLogicByURL = (!this.getPanelManager().hasSearchDataByUrl() || (this.getPanelManager().hasSearchDataByUrl() && !this.getPanelManager().isKeywordUrlSearch())) ? false : true;
	if (!this.FillLogicByURL) {
		//Loading Data of primary boxes 
		this.onSelectTypeLanguage();
	}
	
};

Publicis.extend(EnergyApps.DownloadArea.SearchPanelKeywords, EnergyApps.DownloadArea.AbstractSearchPanel, {
	/**
	 * @private
	 */
	manageKeyWords: function (){
		var field = $(this.cfg.id + "-keywords");
		field.observe("keypress", this.submitByKeyPress.bindAsEventListener(this));
	},
	/**
	 * Sets the keyword field values 
	 * @param {String} value
	 */
	setKeyword: function (value){
		$(this.cfg.id + "-keywords").value = value;
	},
	/**
	 * Extending parent abstract method for keyword setting
	 * @param {Object} searchdata
	 * @private
	 */
	fillURLData: function (searchdata){
		/*
		keywords=key1%2C%20key2
		fiProductFamily=wert_family
		fiProductName=wert_name
		fiProductVersion=wert_version
		fiDocumentType=wert_type
		fiLanguage=wert_language
		fiReleaseDateFrom=03%2F21%2F10
		fiReleaseDateTo=03%2F22%2F10
		foldername=wert_folder 
		*/
		if (typeof searchdata.keywords != "undefined" && !searchdata.keywords.blank()){
			this.setKeyword(searchdata.keywords);
		}
		//no other urlparams for selctboxes are given
		if (typeof searchdata.fiLanguage == "undefined" && searchdata.fiLanguage.blank() && typeof searchdata.fiDocumentType == "undefined" && searchdata.fiDocumentType.blank()) {
			this.fillRestAndSearch();
			return;
		}
		
		this.onSelectTypeLanguage();
		
		/*if (!this.fillComboInUrlLogic("fiDocumentType")){
			if (!this.fillComboInUrlLogic("fiLanguage")){
				this.fillRestAndSearch();
				return;
			}
		}*/
	},
	/**
	 * If url params are given, this methods fills the calendar fields ans starts search.
	 * @return void
	 * @private
	 */
	fillRestAndSearch: function (){
		var searchdata = this.getPanelManager().getUrlSearchdata();
		this.enableCalendars();
		//Fill calendars
		for (i in this.calendars){
			if (typeof searchdata[i] != "undefined" && !searchdata[i].blank()){
				this.calendars[i].disableEvents();
				searchdata[i] = this.parseSearchDateString(searchdata[i]);
				$(this.calendars[i].getUpdateElement()).value = searchdata[i].format(this.calendars[i].getUpdateFormat());
				this.calendars[i].enableEvents();
			}
		}
		this.FillLogicByURL = false;
		this.search();
	},
	/**
	 * Returns true if the value of searchdata could be selected in the select box
	 * @param {String} field name of field
	 * @return Boolean  
	 * @private
	 */
	fillComboInUrlLogic: function (field){
		if (typeof this.comboIsFilledByUrlLogic[field] == "undefined" || this.comboIsFilledByUrlLogic[field] == false) {
			var searchdata = this.getPanelManager().getUrlSearchdata();
			this.comboIsFilledByUrlLogic[field] = true;
			return this.selectboxes[field].setSelectionById(searchdata[field]);
		}
		return true;
	},
	/**
	 * Callback for e.g. keywords field => starts result request
	 * @private
	 * @param {Object} e
	 */
	submitByKeyPress: function (e){
		if (e.keyCode === Event.KEY_RETURN){
			this.getPanelManager().search(this);	
		}
	},
	/**
	 * Extends parent method
	 * @private
	 * 
	 */
	onResetButtonClick: function (){
		var hasToBeRelaoded = true;
		
		EnergyApps.DownloadArea.SearchPanelKeywords.superclass.onResetButtonClick.call(this);
		
		if (hasToBeRelaoded){
			this.onSelectTypeLanguage();
		}
		
		this.enableCalendars();
		for (var i in this.selectboxes){
			this.selectboxes[i].enable();
		}
	},
	/**
	 * @param {Publicis.Components.SelectBox} box SelectBox
	 * @param {Object} selection
	 * @param {Object} oldSelection
	 * @private
	 */
	onSelectTypeLanguage: function(box, selection, oldSelection){
		
		var who = "", params = {};
		if (box instanceof Publicis.Components.SelectBox) {
			switch (box) {
				case this.selectboxes.fiDocumentType:
					who = "fiDocumentType";
					break;
				case this.selectboxes.fiLanguage:
					who = "fiLanguage";
					break;
			}
		}
		
		//Collecting Parameters
		params = this.getData();
		params.selectedBox = who;
		
		var boxes = [
			"fiDocumentType",
			"fiLanguage"
		];
		
		for (var i = 0; i < boxes.length; i++){
			if (boxes[i] == who){
				continue;
			}
			this.selectboxes[boxes[i]].setLoading();
		}
		
		var url = RESOURCES_PATH + '../../apps/DownloadPool/proxy_column.php?action=filters.getByTypeLanguage';
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: params,
	        onSuccess: this.onLoadSelectTypeLanguage.bind(this),
			onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
		  
	},
	/**
	 * Callback for xhr request
	 * Observer for the success event of xhr
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	onLoadSelectTypeLanguage: function (respObject){
		var boxes = [
			"fiDocumentType",
			"fiLanguage"
		];
		var i = 0, response;
		try{
			response = respObject.responseText.evalJSON(true);
		}catch(e){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.onXHRFailure();
			return;
		}
		var who = response.data.selectedBox;
		//extract selected box for this request
		boxes = boxes.without(who);
		
		var updateVersion = true;
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].clearLoading();
		}
		
		if (response.success === false){
			for (i = 0; i < boxes.length; i++){
				this.selectboxes[boxes[i]].disable(true);
			}
			this.selectboxes[response.data.selectedBox].disable(true);
			this.onXHRFailure();
			return;
		}
		
		for (i = 0; i < boxes.length; i++){
			this.selectboxes[boxes[i]].disableEvents();
			this.selectboxes[boxes[i]].update(response.data[boxes[i]]);
			this.selectboxes[boxes[i]].enableEvents();
		}
		
		//only in process fill logic by url params
		if (this.FillLogicByURL) {
			switch (who){
				case "":
					if (!this.fillComboInUrlLogic("fiDocumentType")) {
						if (!this.fillComboInUrlLogic("fiLanguage")) {
							this.fillRestAndSearch();
							return;
						}
					}
				break;
				case "fiDocumentType":
					this.fillComboInUrlLogic("fiLanguage");
					this.fillRestAndSearch();
				break;
				case "fiLanguage":
					this.fillRestAndSearch();
				break;	
			}
		}
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getFormId: function (){
		return this.cfg.id + "-downloadSearchKey";
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getButtonConfig: function(){
		var buttons = {
			reset: {
				containerid: this.cfg.id + "-resetbutton_2"
			},
			search: {
				containerid: this.cfg.id + "-searchbutton_2"
			}
		};
		return buttons;
	},
	/**
	 * Implementation of parent abstract method
	 * @private
	 */
	getCalendarConfig: function (){
		var calendars = [
			{
				name: "fiReleaseDateFrom", 
				containerid: this.cfg.id + "-fiReleaseDateFromContainer_2", 
				inputid: this.cfg.id + "-fiReleaseDateFromId_2",
				iconid: this.cfg.id + "-fiReleaseDateFromIdIcon_2",
				listeners: {
					beforeupdate:{
						fn: function (scal, updateElement, selDate, fromat){
							var toInput = $(this.calendars.fiReleaseDateTo.getUpdateElement());
							if (toInput.value != ""){
								if (this.calendars.fiReleaseDateTo.getSelectedDate() < selDate){
									alert(this.getLang().msgNotCorrectFromDate);
									return false;
								}
							}
							
						},
						scope: this
					} 
				},
				disabled: false
			},
			{
				name: "fiReleaseDateTo", 
				containerid: this.cfg.id + "-fiReleaseDateToContainer_2", 
				inputid: this.cfg.id + "-fiReleaseDateToId_2",
				iconid: this.cfg.id + "-fiReleaseDateToIdIcon_2",
				listeners: {
					beforeupdate:{
						fn: function (scal, updateElement, selDate, fromat){
							var fromInput = $(this.calendars.fiReleaseDateFrom.getUpdateElement());
							if (fromInput.value != ""){
								if (this.calendars.fiReleaseDateFrom.getSelectedDate() > selDate){
									alert(this.getLang().msgNotCorrectToDate);
									return false;
								}
							}
							
						},
						scope: this
					} 
				},
				disabled: true
			}
		];
		
		return calendars;
	},
	/**
	 * Implementation of parent abstract method.
	 * Gets the combo fields configuration 
	 * @return Array 
	 * @private
	 */
	getSelectboxConfig: function (){
		var combos = [
			{field: "fiDocumentType", containerid: "fiDocumentType_2", disabled: false, listeners: {
				select:{
					fn: this.onSelectTypeLanguage,
					scope: this
				}
			}},
			{field: "fiLanguage", containerid: "fiLanguage_2", disabled: false, listeners: {
				select:{
					fn: this.onSelectTypeLanguage,
					scope: this
				}
			}}
		];
		return combos;
		
	},
	/**
	 * Gets the protptype search template for thesearch area
	 * @return Template See Prototype documentation
	 * @private
	 */
	getTemplate: function (){
		if (this.template instanceof Template){
			return this.template;
		}
		this.template = new Template([
			'<form method="post" action="" id="#{id}-downloadSearchKey">',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelKeywords}</label>',
						'</div>',
						'<div class="fieldsetwrapper inputwide">',
							'<div class="legend access">Input keywords</div>',
							'<input type="text" value="" class="keywords" name="keywords" id="#{id}-keywords" />',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelDocument}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:230px;">',
							'<div class="legend access">Select document type</div>',
							'<div id="fiDocumentType_2" class="dlaSelect3_6"></div>',
						'</div>',
						'<div class="fieldsetwrapper">',
							'<div class="legend access">Select language</div>',
							'<div id="fiLanguage_2" class="dlaSelect3_6"></div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<fieldset>',
						'<div class="fieldsetwrapper">',
							'<label>#{labelReleaseDate}</label>',
						'</div>',
						'<div class="fieldsetwrapper" style="width:230px;">',
							'<div class="legend access">Input release date from</div>',
							'<input type="text" value="" class="datum" name="fiReleaseDateFrom" id="#{id}-fiReleaseDateFromId_2" readonly="true" onKeyPress="" />',
							'<span class="calbutton" id="#{id}-fiReleaseDateFromIdIcon_2"><img src="' + RESOURCES_PATH + '../pub/style/img/calendar.gif" alt=""/></span>',
							'<div style="clear:both"></div>',
							'<div id="#{id}-fiReleaseDateFromContainer_2" class="scal dashblack"> </div>',
						'</div>',
						'<span class="dash-seperator">-</span>',
						'<div class="fieldsetwrapper" style="width:225px;">',
							'<div class="legend access">Input release date to</div>',
							'<input type="text" value="" class="datum" name="fiReleaseDateTo" id="#{id}-fiReleaseDateToId_2" readonly="true" onKeyPress="" />',
							'<span class="calbutton" id="#{id}-fiReleaseDateToIdIcon_2"><img src="' + RESOURCES_PATH + '../pub/style/img/calendar.gif" alt=""/></span>',
							'<div style="clear:both"></div>',
							'<div id="#{id}-fiReleaseDateToContainer_2" class="scal dashblack"> </div>',
						'</div>',
					'</fieldset>',
				'</div>',
				'<div class="fieldset">',
					'<div class="fieldsetwrapper inputright buttonbox" style="width:105px;">',
						' <a class="generic-button" id="#{id}-resetbutton_2" href="javascript:void(null)">',
							'<span>',
								'<span>#{labelResetButton}</span>',
							'</span>',
						'</a>',
						' <a class="generic-button" id="#{id}-searchbutton_2" href="javascript:void(null)">',
							'<span>',
								'<span>#{labelSearchButton}</span>',
							'</span>',
						'</a>',
					'</div>',
				'</div>',
			'</form>'	
		].join(""));
		return this.template;
	}
});


/**
 * @class EnergyApps.DownloadArea.ResultPanel
 * @namespace EnergyApps.DownloadArea
 * @extends Publicis.Observable
 * Renders and manage the download result area. Should not be instantiated directly 
 * <br><br>
 * Dependency on Prototype.js Version 1.6.x, Publicis framework, EnergyApps.DownloadArea.AbstractSearchPanel
 * @constructor
 * Creates a new download result area<br>
 * @param {Object} cfg Configuration options
 * @param {EnergyApps.DownloadArea.Panel}  
 * @author Alexis Dorn
 */
EnergyApps.DownloadArea.ResultPanel = function(cfg, panelManager){
	/**
	 * The global panelmanager 
	 * @type EnergyApps.DownloadArea.Panel
	 * @private 
	 */
	this.panelManager = panelManager;
	/**
	 * @private
	 */
	this.cfg = Object.clone(cfg);
	/**
	 * @cfg {String|DOMElement} renderTo <b>Obligatory:</b> Container Element of result area
	 */
	this.el = $(this.cfg.renderTo);
	/**
	 * @cfg {String} id Unique ID for the component
	 */
	if (typeof this.cfg.id == "undefined") {
		this.cfg.id = Publicis.uniqueId();
	}
	/**
	 * @cfg {Integer} defaultLimit Default limit selection if no user selection of limit select boxe has done. Default to 10
	 */
	if (!Object.isNumber(this.cfg.defaultLimit)) {
		this.cfg.defaultLimit = 10;
	}
	/**
	 * Layout template
	 * @private
	 */
	this.masterTemplate = false;
	/**
	 * Template for navigation buttons
	 * @private
	 */
	this.pagerTemplate = false;
	/**
	 * Template for result count information
	 * @private
	 */
	this.resultInfoTemplate = false;
	/**
	 * Template for no result row
	 * @private
	 */
	this.rowNoResultTemplate = false;
	/**
	 * Template for fiProductNameOne row
	 * @private
	 */
	this.rowLevel1Template = false;
	/**
	 * Template for fiGroupMain row
	 * @private
	 */
	this.rowLevel2Template = false;
	/**
	 * Template for fiGroupSub row
	 * @private
	 */
	this.rowLevel3Template = false;
	/**
	 * Template for result row
	 * @private
	 */
	this.rowResultTemplate = false;
	/**
	 * @private
	 */
	this.lang = false;
	/**
	 * @private
	 */
	this.enableForwardNavigation = false;
	/**
	 * @private
	 */
	this.enableBackwardNavigation = false;
	/**
	 * @private
	 */
	this.buttonsNavigation = false;
	/**
	 * @private
	 */
	this.rendered = false;
	/**
	 * Start position for paging
	 * @private
	 */
	this.start = 0;
	/**
	 * temporary memory for filterdata
	 * @private
	 */
	this.tmpFilterdata = false;
	/**
	 * @private
	 */
	this.pInfoObject = false;
	
	EnergyApps.DownloadArea.ResultPanel.superclass.constructor.call(this, this.cfg);
	
	this.registerEvent([
		/**
		 * @event render
		 * Fires when component is rendered
		 * @param {EnergyApps.DownloadArea.ResultPanel} this
		 * @param {Prototype.Element} this.el
		 */
		"render",
		/**
		 * @event beforesearch
		 * Fires before searchdata are requested
		 * @param {EnergyApps.DownloadArea.ResultPanel} this
		 * @param {Object} filterdata Filterdata that will be send as params
		 */
		"beforesearch",
		/**
		 * @event search
		 * Fires when requested seacrhdata will be processed
		 * @param {EnergyApps.DownloadArea.ResultPanel} this
		 * @param {Object} responseData Response from server
		 */
		"search"
		]
	);
	
	this.render();
	
};
Publicis.extend(EnergyApps.DownloadArea.ResultPanel, Publicis.Observable, {
	/**
	 * Returns the selected or default (5) value of limit box
	 * @return Integer
	 */
	getLimitValue: function (){
		if (this.selectBox.hasSelection()){
			return parseInt(this.selectBox.getSelection().value, 10);
		}else{
			return parseInt(this.cfg.defaultLimit, 10);
		}
	},
	/**
	 * Starts update XHR with given filterdata
	 * @param {Object} filterdata
	 */
	update: function (rawFilterdata, noClear /*private parameter*/){
		noClear = (typeof noClear == "boolean") ? noClear : false;
		if (!noClear) {
			//Clear result
			this.clearResult(true);
		}else{
			this.deleteRows(true);
			this.disableFwdNavigation();
			this.disableBwdNavigation();
		}
		
		this.tmpFilterdata = Object.clone(rawFilterdata);
		
		if (this.fireEvent("beforesearch", this, this.tmpFilterdata) === false){
			return;
		}
		
		this.tmpFilterdata.limit = this.getLimitValue();
		this.tmpFilterdata.offset = this.start + 1;
		this.tmpFilterdata.viewmode = "group";
		this.tmpFilterdata.lang = "en";
		this.tmpFilterdata.keywords = (typeof this.tmpFilterdata.keywords == "undefined") ? "" : this.tmpFilterdata.keywords;
		//starting xhr
		this.request(this.tmpFilterdata, this.processResult.bind(this));
		
	},
	/**
	 * Method for xhr requests
	 * @param {Object} params
	 * @param {Function} success
	 * @param {Function} failure
	 * @private
	 */
	request: function (params, success, failure){
		var tmpparams = {}, url = this.getUrl();
		for (var i in params){
			tmpparams[i] = params[i];
			//tmpparams[i] = Object.toJSON(params[i]);
		} 
		return new Ajax.Request(url, {
	        method: 'post',
	        parameters: tmpparams,
			onSuccess: success,
	        onFailure: this.onXHRFailure.bind(this),
			onException: this.onXHRFailure.bind(this)
		});
	},
	onXHRFailure: function (){
		this.clearResult(false);
	},
	/**
	 * Gets the tartget url for xhr requests
	 * @private
	 */
	getUrl: function (){
		return RESOURCES_PATH + '../../apps/DownloadPool/proxy_list.php';
	},
	/**
	 * Callback of xhr request
	 * @param {Prototype.Ajax.Response} respObject
	 * @private
	 */
	processResult: function (respObject){
		
		var responseData = respObject.responseText.evalJSON(true), 
			i, 
			data, 
			limit = this.getLimitValue(), 
			total,
			lastLevel1 = false,
			lastLevel2 = false,
			lastLevel3 = false,
			item, 
			noResultEls;
		
		
		this.fireEvent("search", this, responseData);
		
		data = responseData.data;
		count = (limit > data.length) ? data.length : limit;
		//No Data
		if (count < 1){
			this.clearResult(false);
			return;
		}
		
		total = parseInt(responseData.totalCount, 10);
		start = this.start;
		
		if (start + count > total){
			total = start + count;
		}
		//Collecting data for navigation and page info
		this.pInfoObject = {
			from : start + 1, 
			to : start + count, 
			totalcount: total 
		};
		
		this.pInfoObject.pagentotalcount = Math.ceil(total/limit);
		this.pInfoObject.pagenumber = Math.ceil(this.pInfoObject.to/limit);
		
		this.updateResultInfo(this.pInfoObject);
		
		if (this.pInfoObject.pagenumber < this.pInfoObject.pagentotalcount){
			this.enableFwdNavigation();
		}
		if (this.pInfoObject.pagenumber > 1){
			this.enableBwdNavigation();
		}
		
		//Update row view
		
		for (i = 0; i < count; i++){
			item = data[i];
			item.fiProductName = (item.fiProductName === null) ? "" : item.fiProductName;
			item.fiGroupMain = (item.fiGroupMain === null) ? "" : item.fiGroupMain;
			item.fiGroupSub = (item.fiGroupSub === null) ? "" : item.fiGroupSub;
			
			if (lastLevel1 != item.fiProductName || !lastLevel1){
				lastLevel1 = item.fiProductName;
				if (!item.fiProductName.blank()){
					this.updateLevel1Rows(item);
					lastLevel2 = false;
					lastLevel3 = false;
				}
			}
			if (lastLevel2 != item.fiGroupMain || !lastLevel2){
				lastLevel2 = item.fiGroupMain;
				if (!item.fiGroupMain.blank()){
					this.updateLevel2Rows(item);
					lastLevel3 = false;
				}
			}
			if (lastLevel3 != item.fiGroupSub || !lastLevel3){
				lastLevel3 = item.fiGroupSub;
				if (!item.fiGroupSub.blank()){
					this.updateLevel3Rows(item);
				}
			}
			this.updateResultRows(data[i]);
		}
		
		//delete no result dummies
		noResultEls = $$("tr.doNotRemoveThisClass");
		for (i = 0; i < noResultEls.length; i++){
			Publicis.discardElement(noResultEls[i]);
		}
		//Thanx IE
		this.getPanelManager().repaintView();
	},
	/**
	 * Returns false or object with properties<br><br>
	 * from, to, totalcount, pagentotalcount, pagenumber
	 * @return {Object}  
	 */
	getPagingInfo: function (){
		return this.pInfoObject;
	},
	/**
	 * Updates / Renders the Level 1 result rows
	 * @private
	 */
	updateLevel1Rows: function (rowdata){
		var template = this.getRowLevel1Template();
		var el = this.getRowContainer();
		el.insert({
			bottom: template.evaluate(rowdata)
		}); 
	},
	/**
	 * Updates / Renders the Level 1 result rows
	 * @private
	 */
	updateLevel2Rows: function (rowdata){
		var template = this.getRowLevel2Template();
		var el = this.getRowContainer();
		el.insert({
			bottom: template.evaluate(rowdata)
		}); 
	},
	/**
	 * Updates / Renders the Level 1 result rows
	 * @private
	 */
	updateLevel3Rows: function (rowdata){
		var template = this.getRowLevel3Template();
		var el = this.getRowContainer();
		el.insert({
			bottom: template.evaluate(rowdata)
		}); 
	},
	/**
	 * Updates / Renders the result rows
	 * @private
	 */
	updateResultRows: function (rawdata){
		var template = this.getRowResultTemplate();
		var rowdata = Object.clone(rawdata);
		//Adding rowdata properties
		rowdata.linkText = (!rowdata.fiDescription.blank()) ? rowdata.fiDescription: (!rowdata.fiTitle.blank()) ? rowdata.fiTitle : "&nbsp;";
		rowdata.fileType = this.getIconClass(rawdata.extType);
		rowdata.fiFilesize = Publicis.Format.convertBytes(rowdata.fiFilesize);
		rowdata.fiReleaseDate = 
			(rowdata.fiReleaseDate > 0) ? 
				Publicis.Format.formatDate(Publicis.Format.timeStamp2Date(rowdata.fiReleaseDate), "dd.mm.yyyy") 
					: 
				"";
		
		var el = this.getRowContainer();
		el.insert({
			bottom: template.evaluate(rowdata)
		}); 
	},
	getPanelManager: function (){
		return this.panelManager; 
	},
	/**
	 * Gets the language texts for view
	 * @private
	 */
	getLang: function (){
		return this.getPanelManager().getLang();
	},
	/**
	 * Deletes rows and change it with NO RESULT TEMPLATE
	 * @private
	 */
	deleteRows: function (loader){
		var el = this.getRowContainer(), last;
		loader = (typeof loader == "boolean") ? loader : false;
		content = (!loader) ? this.getLang().textNoResultFound : '<img src="' + RESOURCES_PATH + '../pub/img/ajax-loading.gif" />';
		if (!document.getElementById(this.cfg.id + "-noresultcontent")) {
			el.insert({
				top: this.getRowNoResultTemplate().evaluate({content: content, id: this.cfg.id})
			});
		}else{
			document.getElementById(this.cfg.id + "-noresultcontent").innerHTML = content;
		}
		//for ie reasons (tbody may not be empty)
		while (el.lastChild) {
			last = $(el.lastChild);
			if (last.hasClassName("doNotRemoveThisClass")) {
				break;
			}
			Publicis.discardElement(last);
		}
	},
	/**
	 * Clears the result presentation
	 * @param {boolean} loader True to set loading gif as content. Default to false;
	 */
	clearResult: function (loader){
		this.start = 0;
		this.tmpFilterdata = false;
		loader = (typeof loader == "boolean") ? loader : false;
		
		//Resets result info
		this.updateResultInfo();
		this.disableFwdNavigation();
		this.disableBwdNavigation();
		//Delete Rows
		this.deleteRows(loader);
	},
	/**
	 * Enables forward navigation
	 */
	enableFwdNavigation: function(){
		this.enableForwardNavigation = true;
		for (var i = 0; i < this.buttonsNavigation.length; i++) {
			var bttn = this.buttonsNavigation[i];
			if (["fwd", "fwdfwd"].indexOf(bttn.type) != -1){
				$(bttn.id).removeClassName(bttn.type + "-inactive");
			}
		}
	},
	/**
	 * Disables forward navigation
	 */
	disableFwdNavigation: function(){
		this.enableForwardNavigation = false;
		for (var i = 0; i < this.buttonsNavigation.length; i++) {
			var bttn = this.buttonsNavigation[i];
			if (["fwd", "fwdfwd"].indexOf(bttn.type) != -1){
				$(bttn.id).addClassName(bttn.type + "-inactive");
			}
		}
	},
	/**
	 * Enables backwards navigation
	 */
	enableBwdNavigation: function(){
		this.enableBackwardNavigation = true;
		for (var i = 0; i < this.buttonsNavigation.length; i++) {
			var bttn = this.buttonsNavigation[i];
			if (["bwd", "bwdbwd"].indexOf(bttn.type) != -1){
				$(bttn.id).removeClassName(bttn.type + "-inactive");
			}
		}
	},
	/**
	 * Disables backwards navigation
	 */
	disableBwdNavigation: function(){
		this.enableBackwardNavigation = false;
		for (var i = 0; i < this.buttonsNavigation.length; i++) {
			var bttn = this.buttonsNavigation[i];
			if (["bwd", "bwdbwd"].indexOf(bttn.type) != -1){
				$(bttn.id).addClassName(bttn.type + "-inactive");
			}
		}
	},
	onFwdClick: function (){
		if (!this.enableForwardNavigation){
			return;
		}
		this.start = this.start + this.getLimitValue();
		this.update(this.tmpFilterdata, true);
	},
	onBwdClick: function (){
		if (!this.enableBackwardNavigation){
			return;
		}
		this.start = this.start - this.getLimitValue();
		if (this.start < 1){
			this.start = 0;
		}
		this.update(this.tmpFilterdata, true);
	},
	onBwdBwdClick: function (){
		if (!this.enableBackwardNavigation){
			return;
		}
		this.start = 0;
		
		this.update(this.tmpFilterdata, true);
	},
	onFwdFwdClick: function (){
		if (!this.enableForwardNavigation){
			return;
		}
		var info = this.getPagingInfo();
		if (info !== false && info.pagentotalcount > 1){
			//from, to, totalcount, pagentotalcount, pagenumber
			var limit = this.getLimitValue();
			this.start = (info.pagentotalcount - 1) * limit;
			this.update(this.tmpFilterdata, true);
		}else{
			this.onFwdClick();
		}
	},
	/**
	 * Gets the tbody element as Prototype.Element
	 * @return Prototype.Element
	 * @private
	 */
	getRowContainer: function (){
		return $(this.cfg.id + "-rowcontainer");
	},
	/**
	 * 
	 * @private
	 */
	render: function (){
		var masterTemplate = this.getMasterTemplate();
		var langs = Object.clone(this.getLang());
		langs.id = this.cfg.id;
		this.el.innerHTML = masterTemplate.evaluate(langs);
		//Instantation of select box (limit)
		this.renderSelectBox();
		//Instantiation and update of pager navigation 
		this.updatePagers();
		//Instantiation and update of count info 
		this.updateResultInfo();
		
		this.rendered = true;
		
		this.fireEvent("render", this, this.el);
	},
	/**
	 * @private
	 * Renders select box (limit)
	 */
	renderSelectBox: function (){
		this.selectBox = new Publicis.Components.SelectBox({
			renderTo: this.cfg.id + "-limitcontroller",
			data: [{value: 10}, {value: 20}, {value: 50}],
			valueProp: "value",
			textProp: "value",
			emptyText: this.getLang().labelCountPages,
			name: "resultsize",
			dhtmlScroll: false,
			listeners: {
				close: {
					fn: function (){
						this.getPanelManager().repaintView();
					},
					scope:this
				},
				select: {
					fn: function (){
						if (this.tmpFilterdata !== false) {
							this.start = 0;
							this.update(this.tmpFilterdata, true);
						}						
					},
					scope: this
				}
			}
		});
	},
	/**
	 * Return an object of the icon css classes
	 * @private
	 */
	getIconClass: function (type){
		var data = {
			pdf: "pdf",
	        jpg: "jpg",
	        doc: "doc",
	        zip: "zip",
	        ppt: "ppt",
	        xls: "xls",
	        gif: "gif",
	        png: "image"
	    };
		if (typeof type == "string"){
			if (typeof data[type] != "undefined"){
				return data[type];
			}
			else{
				return "pdf";
			}
		}else{
			return data;
		}
	},
	/**
	 * Updates / Renders the pagers of result area
	 * @private
	 */
	updatePagers: function (){
		var template = this.getPagerTemplate() ,targets, i;
		targets = {
			header: $(this.cfg.id + "-pager-header"),
			footer: $(this.cfg.id + "-pager-footer")
		};
		var j = 0;
		
		this.buttonsNavigation = []; 
		
		for (i in targets){
			targets[i].innerHTML = template.evaluate({id: this.cfg.id, count: j});
			//Register buttons
			this.buttonsNavigation.push({
				id: this.cfg.id + "-fwdfwd-" + j,
				type: "fwdfwd"
			});
			this.buttonsNavigation.push({
				id: this.cfg.id + "-fwd-" + j,
				type: "fwd"
			});
			this.buttonsNavigation.push({
				id: this.cfg.id + "-bwdbwd-" + j,
				type: "bwdbwd"
			});
			this.buttonsNavigation.push({
				id: this.cfg.id + "-bwd-" + j,
				type: "bwd"
			});
			
			//Callbacks
			$(this.cfg.id + "-fwd-" + j).observe("click", this.onFwdClick.bindAsEventListener(this));
			$(this.cfg.id + "-fwdfwd-" + j).observe("click", this.onFwdFwdClick.bindAsEventListener(this));
			$(this.cfg.id + "-bwd-" + j).observe("click", this.onBwdClick.bindAsEventListener(this));
			$(this.cfg.id + "-bwdbwd-" + j).observe("click", this.onBwdBwdClick.bindAsEventListener(this));
			
			j++;
		}
	},
	/**
	 * Updates / Renders the result info
	 * @param {Object} data Object with keys (from, to, totalcount, pagenumber, pagentotalcount). Default is 0 for every key, if data is undefined
	 * @private
	 */
	updateResultInfo: function (data){
		var template = this.getResultInfoTemplate();
		if (typeof data == "undefined"){
			data = {
				from: 0,
				to: 0,
				totalcount: 0,
				pagenumber: 0,
				pagentotalcount: 0
			};
		}
		$(this.cfg.id + "-resultinfo").innerHTML = template.evaluate(data);
	},
	/**
	 * Template for result info
	 * @private
	 */
	getResultInfoTemplate: function (){
		if (this.resultInfoTemplate instanceof Template){
			return this.resultInfoTemplate;
		}
		
		this.resultInfoTemplate = new Template([
			this.getLang().templatePageInformation
		].join(""));
		return this.resultInfoTemplate;
	},
	/**
	 * Template for pager navigation
	 * @private
	 */
	getPagerTemplate: function (){
		if (this.pagerTemplate instanceof Template){
			return this.pagerTemplate;
		}
		this.pagerTemplate = new Template([
			'<a href="javascript: void(null)" id="#{id}-bwdbwd-#{count}" class="bwdbwd bwdbwd-inactive"></a>',
			'<a href="javascript: void(null)" id="#{id}-bwd-#{count}" class="bwd bwd-inactive"></a>',
			'<a href="javascript: void(null)" id="#{id}-fwd-#{count}" class="fwd fwd-inactive"></a>',
			'<a href="javascript: void(null)" id="#{id}-fwdfwd-#{count}" class="fwdfwd fwdfwd-inactive"></a>'
		].join(""));
		return this.pagerTemplate;
	},
	/**
	 * Template for no results
	 * @private
	 */
	getRowNoResultTemplate: function (){
		if (this.rowNoResultTemplate instanceof Template){
			return this.rowNoResultTemplate;
		}
		this.rowNoResultTemplate = new Template([
			'<tr class="doNotRemoveThisClass"><td colspan="7"><div id="#{id}-noresultcontent">#{content}</div></td></tr>'
		].join(""));
		return this.rowNoResultTemplate;
	},
	/**
	 * Template for displaying productname
	 * @private
	 */
	getRowLevel1Template: function (){
		if (this.rowLevel1Template instanceof Template){
			return this.rowLevel1Template;
		}
		this.rowLevel1Template = new Template([
			'<tr><td colspan="2"><div class="level1">#{fiProductName}</div></td><td colspan="5"></td></tr>'
		].join(""));
		return this.rowLevel1Template;
	},
	/**
	 * Template for displaying main group
	 * @private
	 */
	getRowLevel2Template: function (){
		if (this.rowLevel2Template instanceof Template){
			return this.rowLevel2Template;
		}
		this.rowLevel2Template = new Template([
			'<tr><td colspan="2"><div class="level2">#{fiGroupMain}</div></td><td colspan="5"></td></tr>'
		].join(""));
		return this.rowLevel2Template;
	},
	/**
	 * Template for displaying sub group
	 * @private
	 */
	getRowLevel3Template: function (){
		if (this.rowLevel3Template instanceof Template){
			return this.rowLevel3Template;
		}
		this.rowLevel3Template = new Template([
			'<tr><td colspan="2"><div class="level3">#{fiGroupSub}</div></td><td colspan="5"></td></tr>'
		].join(""));
		return this.rowLevel3Template;
	},
	/**
	 * Template for result row
	 * @private
	 */
	getRowResultTemplate: function (){
		if (this.rowResultTemplate instanceof Template){
			return this.rowResultTemplate;
		}
		this.rowResultTemplate = new Template([
			'<tr>',
				'<td class="rowitem" colspan="2" valign="top">',
					'<div class="resultLink"><a target="_blank" class="#{fileType}" href="#{linkURL}">#{linkText}</a></div>',
				'</td>',
				'<td class="rowitem" valign="top" style="text-align:center;padding-left:2px;">#{fiDocumentType}</td>',
				'<td class="rowitem" valign="top" style="text-align:center;padding-left:2px;">#{fiLanguage}</td>',
				'<td class="rowitem" style="text-align:center;padding-left:2px;" valign="top">#{fiProductVersion}</td>',
				'<td class="rowitem" style="text-align:center;padding-left:2px;" valign="top">#{fiReleaseDate}</td>',
				'<td class="rowitem" style="text-align:right;padding-left:2px;" valign="top">#{fiFilesize}</td>',
			'</tr>'
		].join(""));
		return this.rowResultTemplate;
	},
	/**
	 * Gets the prototype result template for the search area
	 * @return Template See Prototype documentation
	 * @private
	 */
	getMasterTemplate: function (){
		if (this.masterTemplate instanceof Template){
			return this.masterTemplate;
		}
		this.masterTemplate = new Template([
			'<table width="100%" cellpadding="0" cellspacing="0">',
				'<thead>',
					'<tr>',
						'<th  style="width:50px;" class="left">#{headerType}</th>',
						'<th>#{headerDescription}</th>',
						'<th>#{headerDocuments}</th>',
						'<th style="width:100px;">#{headerLanguage}</th>',
						'<th style="width:100px;">#{headerVersion}</th>',
						'<th style="width:100px;">#{headerReleaseDate}</th>',
						'<th style="width:50px;" class="right">#{headerSize}</th>',
					'</tr>',
					'<tr>',
						'<td colspan="7">',
							'<div id="#{id}-header"  class="header" style="text-align:left;">',
								'<div id="#{id}-resultinfo" class="downLoadAreaResultPageInfo"></div>',
								'<div id="#{id}-pager-header" style="height: 26px; float: left;" class="downloadPager"></div>',
								'<div style="float: right; padding: 2px;" class="toolbar-pagenav">',
									'<div id="#{id}-limitcontroller"></div>',
								'</div>',
							'</div>',
						'</td>',
					'</tr>',
				'</thead>',
				'<tfoot>',
					'<tr>',
						'<td colspan="7">',	
							'<div id="#{id}-footer"  class="footer" style="text-align:left;">',
								'<div id="#{id}-pager-footer" style="height: 26px; float: left;" class="downloadPager"></div>',
							'</div>',
						'</td>',
				'</tfoot>',
				'<tbody id="#{id}-rowcontainer"  class="rowcontainer" style="overflow:auto;">',
					this.getRowNoResultTemplate().evaluate({id: this.cfg.id}),	
				'</tbody>',
			'</table>'
		].join(""));
		return this.masterTemplate;
	}
});

/**
 * @class EnergyApps.DownloadArea.Layer
 * @namespace EnergyApps.DownloadArea
 * @extends ContentLayer
 * <b>Extends Layer and ContentLayer</b> of virtual identity AG script (see \root\framework\_resources\js\compiled\script.js)
 * @constructor
 * Creates a new lightbox layer<br><br>
 * see \root\framework\_resources\js\compiled\script.js for documentation
 * @param {Element} node 
 * @param {Element} trigger
 * @author Alexis Dorn  
 */

EnergyApps.DownloadArea.Layer = function (node, trigger){
	EnergyApps.DownloadArea.Layer.superclass.constructor.call(this, node, trigger);
	this.pubObserver = new Publicis.Observable({});
	this.pubObserver.registerEvent([
		/**
		 * @event beforeopen
		 * Fires before component is open. Return false to stop open.
		 * @param {EnergyApps.DownloadArea.Layer} this
		 */
		"beforeopen", 
		/**
		 * @event open
		 * Fires when component is open
		 * @param {EnergyApps.DownloadArea.Layer} this
		 */
		"open",
		/**
		 * @event beforeclose
		 * Fires before component is close. Return false to stop closing.
		 * @param {EnergyApps.DownloadArea.Layer} this
		 */
		"beforeclose", 
		/**
		 * @event close
		 * Fires when component is closed
		 * @param {EnergyApps.DownloadArea.Layer} this
		 */
		"close"
	]);
}; 
Publicis.extend(EnergyApps.DownloadArea.Layer, ContentLayer, {
	/**
	 * @private
	 */
	afterOpen: function(){
		this.pubObserver.fireEvent("open", this);
		return EnergyApps.DownloadArea.Layer.superclass.afterOpen.call(this);
	},
	/**
	 * @private
	 */
	afterClose: function(newLayer) {
		this.pubObserver.fireEvent("close", this);
		return EnergyApps.DownloadArea.Layer.superclass.afterClose.call(this, newLayer);
	},
	/**
	 * @private
	 */
	beforeClose: function() {
		if (this.pubObserver.fireEvent("beforeclose", this) === false){
			return;
		}
		return EnergyApps.DownloadArea.Layer.superclass.beforeClose.call(this);
	},
	/**
	 * @private
	 */
	beforeOpen: function() {
		if (this.pubObserver.fireEvent("beforeopen", this) === false){
			return;
		}
		return EnergyApps.DownloadArea.Layer.superclass.beforeOpen.call(this);
	},
	/**
	 * Adds a callback to a event
	 * @param {String} eventname
	 * @param {Function} callback The function that will be called as callback
	 * @param {Object} scope The this scope in callback function
	 */
	addListener: function (eventname, callback, scope){
		this.pubObserver.addListener(eventname, callback, scope);
	},
	/**
	 * Disables firing of all Events, until you will call enableEvents again 
	 */
	disableEvents: function (){
		this.pubObserver.disableEvents();
	},
	/**
	 * Enables firing of all Events, after you disableEvents has been called 
	 */
	enableEvents: function (){
		this.pubObserver.enableEvents();
	}
});

