/**
 * $URL:$
 * $Date:$
 * $Revision:$
 * $Author:$
 *
 * Copyright (C) 2009 seso media group <www.seso.at>
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the 
 * Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details: <http://www.gnu.org/licenses/>
 * 
 * powered by Prototype JavaScript framework <http://www.prototypejs.org/>
 * powered by scriptaculous <http://script.aculo.us/>
 * 
 * @author: gg@seso.at
 */

/*******************************************************************************
	OBSERVER
*******************************************************************************/

var dataGridObserver = Class.create(Observer, {

	
	viewCtrl : null,
	
	
	startUp : function() {

		for (var i=0; i<this.cache.length; i++) {
			
			this.cache[i] = new dataGrid(this.cache[i]);
		}
	},
	
	
	getDefaultConfig : function() {
		
		var item = {};
			item.cid		= null;
			item.name		= null;
			item.container	= null;
			item.xmlPath	= null;
			item.defaultView = 'table';
		
		return item;
	}

});

util.prototype.dataGrid = new dataGridObserver('dataGrid');



/*******************************************************************************
	DATA-GRID
*******************************************************************************/

var dataGrid = Class.create({

	config : null,
	data : null,
	view : null,
	
	
	initialize : function(config) {

		if (config.container === null) {
			
			log("missing container", 3, this.config.name);
			return false;
		}
		
		var container = $(config.container);
		
		if (!container) {
			
			log("invalid container-id", 3, this.config.name);
			return false;
		}

		this.config = config;
		this.view = new viewCrtl(container, config);
		this.receiveData(config.xmlPath, this);
	},

	
	
	storeData : function(data) {

		this.data = [];

		var elements = $A(data.getElementsByTagName('element'));
		
		if (elements.length == 0) {
			
			this.view.noResult();
			return;
		}
		
		for (var i=0; i<elements.length; i++) {

			var element = elements[i];
			
			var item = {};
				item.id = element.getAttribute('id');
				item.type = element.getAttribute('type');

			var text = element.getElementsByTagName('textfield');

			for (var j=0; j<text.length; j++) {
				
				var id = text[j].getAttribute('id');
				
				if (!id) {
					continue;
				}
				
				if (id == 'title') {
					
					if (text[j].firstChild) {
						item.title = text[j].firstChild.nodeValue;
					}
				}
			
				if (id == 'channel') {
					
					if (text[j].firstChild) {
						item.channel = text[j].firstChild.nodeValue;
					}
				}
				
				if (id == 'text') {

					if (text[j].firstChild) {
						item.text = text[j].firstChild.nodeValue;
					}
				}
				
				if (id == 'date') {
					
					if (text[j].firstChild) {
						item.date = text[j].firstChild.nodeValue;
					}
				}
			}

			var links = element.getElementsByTagName('link');
			
			for (var j=0; j<links.length; j++) {
				item.href = links[j].getAttribute('href');
				item.target = links[j].getAttribute('target');
			}

			var imgs = element.getElementsByTagName('image');

			for (var j=0; j<imgs.length; j++) {
				
				if (imgs[j].getAttribute('type') == 'thumb_square') {
					
					item.imgSquare = new Image();
					item.imgSquare.src = imgs[j].getAttribute('src');
					item.imgSquare.width = imgs[j].getAttribute('width');
					item.imgSquare.height = imgs[j].getAttribute('height');
					item.imgSquare.alt = item.title;
				}
				
				if (imgs[j].getAttribute('type') == 'thumb_wide') {
					
					item.imgWide = new Image();
					item.imgWide.src = imgs[j].getAttribute('src');
					item.imgWide.width = imgs[j].getAttribute('width');
					item.imgWide.height = imgs[j].getAttribute('height');
					item.imgWide.alt = item.title;
				}
			}

			this.data.push(item);
			
		};
		
		this.view.setData(this.data);
		this.view.draw();
	},

	
	receiveData : function(ajaxTarget, self) {

		var ajax = new Ajax.Request(ajaxTarget, {

			method: 'get',
			onSuccess: function(transport) {

				self.storeData(transport.responseXML);
			},
			
		    onFailure: function() {

				log("receiveData - ajax-request failed: "+ajaxTarget, 3, this.name);
			}
		});
	}

});



/*******************************************************************************
	VIEW-CTRL
*******************************************************************************/

var viewCrtl = Class.create({

		
	container : null,
	contant : null,
	config : null,
	childs : [],
	activeView : null,
	data : null,
	
	itemsPerPage : 0,
	activePage : 1,
	pageLimit : 0,
	
	
	initialize : function(container, config) {
		
		this.container = container;
		this.config = config;
		this.activeView = config.defaultView || 'table';
		this.itemsPerPage = config.itemsPerPage || 5;
		
		var hash = window.location.hash.split("#")[1];

		if (hash) {
			
			if (hash == 'list') {
				this.activeView = 'table';
			}
		}		
		
		this.childs['table'] = new tableView();
		this.childs['thumb'] = new thumbView();
		
		this.createCrtlPanel();
		this.createPaginator();

		this.content = new Element('div');
		this.content.addClassName('contentContainer');
		
		this.container.appendChild(this.content);
	},
	
	
	createCrtlPanel : function() {
				
		var p = util.dataGrid.p.prefix;
		
		var crtlPanel = new Element('div', {'id':p+'_viewCrtlPanel'});
			crtlPanel.addClassName('viewCrtlPanel');
				
		this.container.appendChild(crtlPanel);
		
		var act = (this.activeView == 'table'); 
		
		var ico = this.childs['table'].getIcon(act);
		crtlPanel.appendChild(ico);
		Event.observe(ico, 'click',  this.switchView, false);

		var act = (this.activeView == 'thumb');
		
		var ico = this.childs['thumb'].getIcon(act);
		crtlPanel.appendChild(ico);
		Event.observe(ico, 'click',  this.switchView, false);
	},
	
	
	createPaginator : function() {
		
		var id = util.dataGrid.p.prefix+'_viewCrtlPaginator';

		var paginator = new Element('div', {'id':id});
			paginator.addClassName('viewCrtlPaginator');
				
		this.container.appendChild(paginator);
		
		var info = new Element('div');
			info.addClassName('info');
		
		paginator.appendChild(info);

		var span = new Element('span');
			span.innerHTML = 'page';
			info.appendChild(span);

		var span = new Element('span', {id: util.dataGrid.p.prefix+'_activePage'});
			span.innerHTML = this.activePage;
			info.appendChild(span);
		
		var span = new Element('span');
			span.innerHTML = 'of';
			info.appendChild(span);
			
			info.appendChild(new Element('span', {id: util.dataGrid.p.prefix+'_pageLimit'}));
		
		var back = new Element('a', {
			
			href: '#',
			title: 'prev',
			id: id+'_back'
		});
	
		back.innerHTML = 'prev';
		
		paginator.appendChild(back);
		back.observe('click', this.backPage, false);
		
		var next = new Element('a', {
			
			href: '#',
			title: 'next',
			id: id+'_next'
		});
		
		next.innerHTML = 'next';
		next.observe('click', this.nextPage, false);
		paginator.appendChild(next);
	},
	
	
	nextPage : function(event) {
		
		event.stop();
		
		var self = util.dataGrid.cache[0].view;
		var p = self.activePage + 1;
		
		if (p > self.pageLimit) {
			return;
		}
		
		self.activePage = p;
		$(util.dataGrid.p.prefix+'_activePage').innerHTML = p;
		self.draw();
	},
	
	
	backPage : function(event) {
		
		event.stop();
		
		var self = util.dataGrid.cache[0].view;
		var p = self.activePage - 1;
		
		if (p < 1) {
			return;
		}
		
		self.activePage = p;
		$(util.dataGrid.p.prefix+'_activePage').innerHTML = p;
		self.draw();
	},
	

	
	switchView : function(event) {

		event.stop();
		
		var e = event.element();
			e.blur();
			
		var self = util.dataGrid.cache[0].view;
		
		self.childs[self.activeView].switchIcon(false);

		self.activeView = e.getAttribute('id');
		
		self.childs[self.activeView].switchIcon(true);
			
		new Effect.Fade(self.content, {
			from: 1.0,
			to: 0.0,
			duration: 0.25,
			afterFinish : function() {

				self.draw();
				
			}
		});
	},
	
	
	setData : function(data) {
		
		if (typeof data == 'object') {
			
			this.data = data;
			this.pageLimit = Math.ceil(this.data.length / this.itemsPerPage);
			
			$(util.dataGrid.p.prefix+'_pageLimit').innerHTML = this.pageLimit;
		}
	},
	
	
	draw : function() {

		if (typeof this.childs[this.activeView] != 'object') {
			
			log("invalid view '"+this.activeView+"'", 2, this.name);
			return false;
		}
		
		var s = (this.activePage * this.itemsPerPage) - this.itemsPerPage;
		var e = s + this.itemsPerPage - 1;
		
		if (e >= this.data.length) {
			e = this.data.length - 1;
		}

		var node = this.childs[this.activeView].draw(this.data, s, e);
		var content = this.content;

		var clone = node.cloneNode(true);
			clone.style.position = 'absolute';
			clone.style.top = '-99999';
			clone.style.display = 'block';
		
		content.appendChild(clone);
		content.style.display = 'block';	
		var h = clone.offsetHeight;
		content.style.display = 'none';	
		content.removeChild(clone);

		content.innerHTML = '';
		content.style.display = 'block';
		content.setOpacity(0);
		
		new Effect.Morph(content, {
			
			style : 'height:'+h+'px;',
			duration : 0.25,
			afterFinish : function() {
				
				content.appendChild(node);
				
				new Effect.Fade(content, {
					from: 0.0,
					to: 1.0,
					duration: 0.25
				});
			}
		});
	},
	
	
	
	noResult : function() {
		
		this.content.innerHTML = 'No results found.';
		this.content.className += ' noResult';
	}
});


/*******************************************************************************
	TABLE-VIEW
*******************************************************************************/

var tableView = Class.create({

	
	data : null,
	sortCol : null,
	sortType : null,
	icon : null,

	
	initialize : function() {
		
	},
	
	
	getIcon : function(active) {
		
		var img = new Image();
			img.src = (active) ? 'imgs/icon_table_act.jpg' : 'imgs/icon_table.jpg';
			img.width = 23;
			img.height = 23;
			img.alt = 'table';
			img.id = 'table';
		
		this.icon = img;
			
		return img;
	},
	
	
	switchIcon : function(active) {
		
		this.icon.src = (active) ? 'imgs/icon_table_act.jpg' : 'imgs/icon_table.jpg';
	},
	
	
	draw : function(data, startIndex, endIndex) {

		this.data = data;
		
		var container = new Element('div');
			container.addClassName('module');
			
		var null_point0 = new Element('div');
			null_point0.addClassName('nullPoint');
		
		var rightBg = new Element('img', {src:'imgs/mod_right_bg_top.jpg'});
			rightBg.addClassName('right_bg_top');
		
		null_point0.appendChild(rightBg);
		
		var table = new Element('table', {'cellpadding':0, 'cellspacing':0, 'border':0});
			table.addClassName('tableView');
			
		var thead = new Element('thead');
		
		table.appendChild(thead);
		
		var tr = new Element('tr');
		
		var headlines = ['Date' , '' , 'Title' , 'Channel'];
		
		for (var i=0; i<headlines.length; i++) {

			th = new Element('th');
			h2 = new Element('h2');
			h2.innerHTML = headlines[i];			
			th.appendChild(h2);
			tr.appendChild(th);

			if (headlines[i] == this.sortCol) {
				
				th.className = this.sortType;				
				th.className += ' highlight';
			
			} else {
				
				th.className = 'desc';
			}
			
			th.className += ' cell_'+(i+1);
			
			tr.observe('click', this.sort, true);
		}
		
		thead.appendChild(tr);
		
		var tbody = new Element('tbody');
			table.appendChild(tbody);

		for (var i=startIndex; i<endIndex; i++) {
		
			if (i % 2==0){
				bgClassName="dark_bg";				
			}
			else{
				bgClassName="light_bg";				
			}
		
			var tr = new Element('tr');

			var td = new Element('td', {'valign':'top'});
				td.addClassName('cell_1 '+bgClassName);
				
			var div = new Element('div');
				div.addClassName('date');
				div.innerHTML = data[i].date;
				
			td.appendChild(div);			
			tr.appendChild(td);
			
			var td = new Element('td', {'valign':'top'});
				td.addClassName('cell_2 '+bgClassName);
				
			var a= new Element('a', {'href':data[i].href+'#downloads'});
				a.appendChild(data[i].imgWide);
				
			td.appendChild(a);			
			tr.appendChild(td);

			var td = new Element('td', {'valign':'top'});
				td.addClassName('cell_3 '+bgClassName);
				
						
						
			var h2 = new Element('h2');
			
			var a= new Element('a', {'href':data[i].href+'#downloads'});
				a.innerHTML = data[i].title;
			
			h2.appendChild(a);	
			
			var div_txt_cnt = new Element('div');
				div_txt_cnt.addClassName('txt_cnt');		
		
			td.appendChild(h2);
			td.appendChild(div_txt_cnt);
			div_txt_cnt.innerHTML = data[i].text;
			tr.appendChild(td);

			var td = new Element('td', {'valign':'top'});
				td.addClassName('cell_4 '+bgClassName);
				td.innerHTML = data[i].channel;
				
			tr.appendChild(td);
			
			tbody.appendChild(tr);
		}

		var bottomCnt = new Element('div');
			bottomCnt.addClassName('bottom_cnt');
		
		var bottomBgLeft = new Element('img', {'src':'imgs/mod_bottom_bg_left.jpg'});
			bottomBgLeft.addClassName('bottom_bg_left');
			
		var bottomBgRight = new Element('img', {'src':'imgs/mod_bottom_bg_right.jpg'});
			bottomBgRight.addClassName('bottom_bg_right');
		
		bottomCnt.appendChild(bottomBgLeft);
		bottomCnt.appendChild(bottomBgRight);
		
		null_point0.appendChild(table);
		null_point0.appendChild(bottomCnt);

		container.appendChild(null_point0);
		
		return container;
	}, 
	
	
	sort : function(event) {

		event.stop();
		
		var e = event.element();
			e.blur();
			
		var self = util.dataGrid.cache[0].view;
		var col = e.firstChild.nodeValue;
		var type = 'desc';
		
		if (col == self.childs['table'].sortCol) {
			
			if (self.childs['table'].sortType == 'desc') {
				
				type = 'asc';
			}
		}

		self.data.sort(function(a, b) {
			
			if (type == 'asc') {
			
				return a[col] < b[col];
				
			} else {
				
				return a[col] > b[col];
			}
		});
		
		self.childs['table'].sortCol = col;
		self.childs['table'].sortType = type;

		self.draw(self.data);
	}

});





/*******************************************************************************
	THUMB-VIEW
*******************************************************************************/

var thumbView = Class.create({

	
	icon : null,
	

	initialize : function() {
	
	},
	
	
	getIcon : function(active) {

		var img = new Image();
			img.src = (active) ? 'imgs/icon_thumb_act.jpg' : 'imgs/icon_thumb.jpg';
			img.width = 23;
			img.height = 23;
			img.alt = 'thumb';
			img.id = 'thumb';
		
		this.icon = img;
			
		return img;
	},
	
	
	switchIcon : function(active) {
		
		this.icon.src = (active) ? 'imgs/icon_thumb_act.jpg' : 'imgs/icon_thumb.jpg';
	},
	
	
	draw : function(data, startIndex, endIndex) {
						
		var mainContainer = new Element('div');
			mainContainer.addClassName('module');
			
		var null_point0 = new Element('div');
			null_point0.addClassName('nullPoint');
			
		var rightBg = new Element('img', {src:'imgs/mod_right_bg_top.jpg'});
			rightBg.addClassName('right_bg_top');
			
		null_point0.appendChild(rightBg);
		mainContainer.appendChild(null_point0);
		
		
		var innerCnt = new Element('div');
			innerCnt.addClassName('innerCnt');
		
		var container = new Element('div');
			container.addClassName('thumbView');
		
		innerCnt.appendChild(container);
		
		for (var i=startIndex; i<=endIndex; i++) {
		
			var thumb_cnt = new Element('div', {'class':'thumb_cnt'});
				thumb_cnt.addClassName('thumb_cnt');
			
			var null_point = new Element('div');
				null_point.addClassName('nullPoint');
			
			var a= new Element('a', {'href':data[i].href+'#downloads'});
			
			var overlay =  new Element('div');
				overlay.addClassName('overlay');
			
			//var mediatype = new Element('div');
			
			var div_date = new Element('div');
				div_date.addClassName('date');
				div_date.innerHTML=data[i].date;

			var h2 = new Element ('h2');
				h2.innerHTML=data[i].title;				
			
								
			a.appendChild(data[i].imgSquare);		
			null_point.appendChild(a);
			
			//mediatype.appendChild(h2)
			overlay.appendChild(div_date);
			overlay.appendChild(h2);
			null_point.appendChild(overlay);
			
			thumb_cnt.appendChild(null_point);
			
			container.appendChild(thumb_cnt);	
		}

		innerCnt.appendChild(new Element('div', {'class':'clear'}));
		
		var bottomCnt = new Element('div');
			bottomCnt.addClassName('bottom_cnt');
			
		var bottomBgLeft = new Element('img', {'src':'imgs/mod_bottom_bg_left.jpg'});
			bottomBgLeft.addClassName('bottom_bg_left');
		
		var bottomBgRight = new Element('img', {'src':'imgs/mod_bottom_bg_right.jpg'});
			bottomBgRight.addClassName('bottom_bg_right');
		
		bottomCnt.appendChild(bottomBgLeft);
		bottomCnt.appendChild(bottomBgRight);
		
		null_point0.appendChild(innerCnt);
		null_point0.appendChild(bottomCnt);

		mainContainer.appendChild(null_point0);

		return mainContainer;
		
	}


});




