var SB_T_PADDING = 16;
/**
 * Konstruktor przeciągalnego scrollbara
 * @param {Object} elem
 * @param {Object} options
 */

function scrollbar(elem, options){
	this.nn6 = document.getElementById&&!document.all;
	
	this.local_init = function(){
		this.y = getAbsoluteTop(this.elem);
		this.elem.onselectstart = new Function('return false;');
		var links = this.elem.parentNode.getElementsByTagName('a')
		for(var i=0;i<links.length;i++){
			if(links[i].className=='scrollArrowDn'){
				links[i].href="#";
				links[i].scrollbar = this;
				addListener(links[i], 'click', function(e){(document.getElementById&&!document.all?e.target:event.srcElement).parentNode.scrollbar.nextPage()});
			}else if(links[i].className=='scrollArrowUp'){
				links[i].href="#";
				links[i].scrollbar = this;
				addListener(links[i], 'click', function(e){(document.getElementById&&!document.all?e.target:event.srcElement).parentNode.scrollbar.prevPage();});
			}	
		}
		if(options.mailboxManager)
			options.mailboxManager.scrollbar = this;
	}

	this.updatePoz = function(){
		this.elem.style.top = Math.round(this.getHeight()*options.mailboxManager.curProcPoz())+SB_T_PADDING+'px';
	}
	
	this.prevPage = function(){
		this.options.mailboxManager.prevPage();
		this.updatePoz();
	}
	
	this.nextPage = function(){
		this.options.mailboxManager.nextPage();
		this.updatePoz();
	}
	
	this.startdrag = function(x,y){
	}
	
	this.bTop = function(y){
		var top = y-this.y;
		if(top<0) top=0;
		if(top>this.height) top=this.height;
		return top;
	}
	
	this.getHeight = function(){
		//if(!this.height)
		//	this.height = getRealHeight(this.elem.parentNode) - getRealHeight(this.elem) - 2*SB_T_PADDING;
		this.height = getRealHeight(this.elem.parentNode) - getRealHeight(this.elem) - 2*SB_T_PADDING;
		return this.height;
	}
	
	this.move = function(x, y){
		var top = this.bTop(y);
		this.elem.style.top = top+SB_T_PADDING+'px';
		
		if(this.options.mailboxManager)
			this.options.mailboxManager.goToProcPoz(top/this.getHeight());
	}
	
	this.stopdrag = function(x, y){
		if(this.options.mailboxManager)
			this.options.mailboxManager.goToProcPoz(this.bTop(y)/this.height);
	}
	
	this.init(elem, options);
	this.local_init();
}
scrollbar.prototype = new draggable;


/**
 * Aby element mógł reagować na ruchy wałkiem należy dopisać do niego metodę towheel i wywołać mousewheelmanager.look_on(elem)
 */
function MouseWheelManager(){
	this.onwheel = function(event){
		var delta = 0;
		if (!event) 
                event = window.event;
				
		if (event.target) {
			var fobj = event.target;
			var topelement  = "HTML";
		}
		else {
			var fobj = event.srcElement
			var topelement = "BODY";
		}
		while (fobj.tagName != topelement && (!fobj.mousewheelmanager) ){
			fobj =  fobj.parentNode;
		}
			
		if (fobj.mousewheelmanager) {
			if (event.wheelDelta) {
				delta = event.wheelDelta / 120;
				//if (window.opera) 
				//	delta = -delta;
			}
			else 
				if (event.detail) {
					delta = -event.detail / 3;
				}
			if (delta) 
				fobj.dowheel(delta);
			if (event.preventDefault) 
				event.preventDefault();
		}
		event.returnValue = false;
	}
	
	this.init = function(){
	}
	
	this.look_on = function(elem){
		if(elem)
			elem.mousewheelmanager = this;
		try{
			elem.attachEvent('onmousewheel', this.onwheel);
		}catch(e){
			elem.addEventListener('DOMMouseScroll', this.onwheel, false);
		};
	}
	this.init();
}

window.mousewheelmanager = new MouseWheelManager();

function MailboxManager(elem, container_elem, url, elementow, widocznych, options){
	this.data = new Array();
	
	this.init = function(elem, container_elem, url, elementow, widocznych, options){
		if(!elem) return;
		this.nn6 = document.getElementById&&!document.all;
		if(!options)
			options = new Object();
		if(options.cursor)
			this.cursor = options.cursor;
		else
			this.cursor = 'pointer';
		this.options = options;
		window.mailboxmanager = this;
		this.elementow = elementow;
		this.widocznych = widocznych;
		this.url = url;
		this.elem = elem;
		this.container_elem = container_elem;
		if (this.elem) {
			window.mousewheelmanager.look_on(this.elem);
			this.elem.onselectstart = new Function('return false;');
			this.elem.dowheel = this.dowheel;
			this.elem.mm = this;
		} else
			return;
		
		var url_a = url.split('/');
		
		try{
			this.mailbox_name = url_a[url_a.length-3];
			this.row_gen = eval(this.mailbox_name+'_row_gen');
		}
		catch(e){
			this.row_gen = function(){};
		}
		
		
		this.poz = 0;
		this.data = new Array();
		if (!options.rowsget) {
			var rows = elem.getElementsByTagName('tr');
		}
		else 
			var rows = options.rowsget(this);
			
		for (var i = 0; i < rows.length; i++) {
				if(obtainClass(rows[i], 'selected'))
					this.last_selected = i;
				this.data.push(rows[i]);
				
				rows[i].style.cursor = this.cursor;
				
				this.make_clickable(rows[i], i);
				var td_elems = rows[i].getElementsByTagName('td');
				for(var j=0;j<td_elems.length; j++){
					if(obtainClass(td_elems[j], 'subject') || obtainClass(td_elems[j], 'subject2') || obtainClass(td_elems[j], 'subjectT')){
						td_elems[j].getElementsByTagName('a')[0].href="#";
					}
				}
		}		
		
		var root_elem = this.elem.getElementsByTagName('tbody')[0];
		for(var i=rows.length-1;i<this.elementow;i++){
			if(not(options.hiddenrowsgen)){
				var tr = document.createElement('tr');
				tr.style.display='none';
				tr.className=i%2?'notshaded opaque':'shaded opaque';
				root_elem.appendChild(tr);
			} else 
				var tr = options.hiddenrowsgen(this, i);
			this.row_gen(tr, i);	
			//if (tr.nieklikalny == undefined) {
				tr.style.cursor = this.cursor;
				this.make_clickable(tr, i + 1);
			//}
			
			tr.pusty = true;				
			this.data.push(tr);
		}
	}
	
	this.make_clickable = function(tr, i){
		var thiz = window.mailboxmanager
		addListener(tr, 'click', function(){
			thiz.get_mail(i);
		})
		//wyłączenie bubelsów w inputach
		var elems = tr.getElementsByTagName('input');
		for (var j = 0; j < elems.length; j++) {
			addListener(elems[j].parentNode, 'click', function(e){
				try {
					e.stopPropagation();
				} 
				catch (exception) {
					window.event.cancelBubble = true;
				}
			}, false)
		}
	}
	
	this.get_mail = function(i){
		if(this.data[i].wiadomosc)
			this.show_wiadomosc(this.data[i].wiadomosc, i);
		else
			advAJAX.get({
				url: this.url+i+'/',
				onSuccess: function(obj){
					var data = eval('['+obj.responseText+']');
					var wiadomosc = data[0]['wiadomosc'][0].fields;
					var zalaczniki = new Array();
					var zd = data[0]['zalaczniki'];
					for(var j=0;j<zd.length;j++)
						zalaczniki.push(zd[j]['fields']);
					wiadomosc.zalaczniki = zalaczniki;
					wiadomosc.poz = i;
					wiadomosc.pk = data[0]['wiadomosc'][0].pk;
					window.mailboxmanager.show_wiadomosc(wiadomosc, i)
				}
			})
	}
	
	this.select_row = function(i){
		if(this.last_selected!=undefined)
			unsetClass(this.data[this.last_selected], 'selected')
		this.last_selected = i;
		setClass(this.data[i],'selected', true);
	}


	this.show_wiadomosc = function(wiadomosc, i){
		unsetClass(this.data[i], 'read');
		if (!this.data[i].wiadomosc) 
			this.data[i].wiadomosc = wiadomosc;
		this.select_row(i);
		removeChildren(this.container_elem);
		var mpw = quickElement('div', this.container_elem, '', 'class', 'mailPreviewWrapper');
		var pa = quickElement('div', mpw, '', 'class', 'previewArea');
		var pad = quickElement('div', pa, '', 'class', 'padder');
		// wiadomosc.tresc.split('\n').join('<br />')
		var lines = wiadomosc.tresc.split('\n');
		for (var i=0;i<lines.length;i++ ) {
			pad.appendChild(document.createTextNode(lines[i]));
			quickElement('br', pad);
		}
		
		
		if (wiadomosc.zalaczniki.length) {
			var aw = quickElement('div', mpw, '', 'class', 'attachmentsWrapper');
			for (var k = 0; k < wiadomosc.zalaczniki.length; k++) {
				var nazwa = wiadomosc.zalaczniki[k].plik;
				var rc = nazwa.split('/');
				var kn = rc[rc.length - 1]
				quickElement('a', aw, kn, 'href', MEDIA_URL + nazwa, 'title', kn);
			}
			quickElement('div', aw, '', 'class', 'flCl');
		}
		this.post_show_wiadomosc(wiadomosc, i)
	}
	
	/**
	 * Należy nadpisać tę funkcję aby wyświetlać odpowiednio wiadomość
	 * @param {Object} wiadomosc
	 * @param {Object} i
	 */	
	this.post_show_wiadomosc = function(wiadomosc, i){
		
	}
	
	this.curProcPoz = function(){
		return this.poz/(this.elementow-this.widocznych);
	}
	
	this.dowheel = function(delta){
		var thiz = this.mm;
		if(delta<0){
			thiz.nextPage();
		} else {
			thiz.prevPage();
		}
		if(thiz.scrollbar)
			thiz.scrollbar.updatePoz();
	}
	
	this.goToProcPoz = function(proc_poz){
		return this.goTo(Math.round((this.elementow-this.widocznych+1)*proc_poz))
	}
	
	this.prevPage = function(){
		return this.goTo(this.poz-this.widocznych+2)
	}
	
	this.nextPage = function(){
		return this.goTo(this.poz+this.widocznych-2)
	}
	
	this.timeout = false;
	
	this.update = function(){
		window.mailboxmanager.doupdate();
	}
	
	this.doupdate = function(){
		var ids = new Array();
		for(i=this.poz;i<this.poz+this.widocznych;i++){
			if(this.data[i].pusty){
				ids.push(i);
			}
		}
		if(ids.length==0)
			return;
		var min = ids[0]; 
		var thiz = this;
		advAJAX.get({
	   		url: this.url+ids[0]+'/'+ids[ids.length-1]+'/',
	    	onSuccess : function(obj) { 
				data = eval(obj.responseText);
				for(var i=0;i<data.length;i++){
					if (thiz.data[min + i].pusty == true) {
						thiz.data[min + i].fillrow(data[i].fields, min + i);
						thiz.data[min + i].pusty = false;
						unsetClass(thiz.data[min + i], 'opaque');
					}
				} 
				thiz.scrollbar.updatePoz();
			}
		});
	}
	
	this.goTo = function(first){
		if(first<0)
			first=0;
		if(first>this.elementow-this.widocznych)
			first = this.elementow-this.widocznych; 
		for(var i=this.poz;i<first;i++){
			this.data[i].style.display='none';
		}
		for(var i=first;i<first+this.widocznych;i++){
			if(not(this.options.rowshow))
				this.data[i].style.display=this.nn6?'table-row':'block';
			else
				this.options.rowshow(this, this.data[i])
		}
		
		for(;i<this.data.length;i++){
			if(not(this.options.rowhide))
				this.data[i].style.display='none';
			else
				this.options.rowhide(this, this.data[i])
		}
		this.poz = first;	
		
		if(this.timeout)
			clearTimeout(this.timeout);
		this.timeout = setTimeout("window.mailboxmanager.update()", 500);
	}
	this.init(elem, container_elem, url, elementow, widocznych, options);	
}
