
active = false;

function MyPaging()
{
	this.destroy = false;
	this.showScore = false;

	this.DEBUG = 0;
	this.controller = '/ajax/';
	this.action = '';
	this.id = '';
	this.selectId = 0; //mouse hover show red
	this.paging = true;
	this.format = 'table'; // (table || list)
	this.forcePictureHeight = 70;
	this.currentRecord = 0;
	this.pagingSize = 10;
	this.containerWidth = 710;
	this.maxWidth = 70;
	this.minWidth = 30;
	this.stepSize = 10;
	this.padding = 1;
	this.useMaxWidth = false;
	this.rows = 1;
	this.recordCount = 0;
	this.hideCount = 0;
	this.previousPage;
	this.currentPage;
	this.nextPage;
	this.keyword = '';
	this.colorFilter = false;
	this.sortByDate = false;
	this.startLoadingCallback = false;
	this.endLoadingCallback = false;
	this.ajaxMethod = 'get';

	//search
	this.search = null;
	this.category = null;
	this.brand = null;
	this.color = null;
	this.price = null;
	
	// make sure we init only once
	this.initDone = false;
	// clear page contianer flag
	this.clearContainer = true;

	var self = this;

	this.run = function() {
		if(self.paging) {
			self.currentRecord = 0;
		}
		else {
			if($(self.action+'_left')) $(self.action+'_left').style.display='none';
			if($(self.action+'_right')) $(self.action+'_right').style.display='none';
		}

		this.makeSearch();
	};

	/**
	 * Assigns color filter object to paging
	 * @param v
	 * @return
	 */
	this.setColorFilter = function(v)
	{
		this.colorFilter = v;
	};

	this.makeSearch = function() {
		this.clearContainer = true;

        if ( !this.initDone ) {
        	if ( this.format == 'editor_scroll_table' ) {
        		$(self.action + '_current').observe('scroll', this.onScrollEvent.bindAsEventListener(this));
        	}
        	if ( this.format == 'item_scroll' || this.format == 'set_scroll' ) {
        		Event.observe(document,'scroll', this.onScrollWindowEvent.bindAsEventListener(this));
        	}
            this.initDone = true;
        }

		if ( this.startLoadingCallback ) {
			this.startLoadingCallback(this.action);
		}

        this.currentRecord = 0;
        if(this.paging) this.getRecordCount();
		this.getTableData();

		if(this.paging) setTimeout(function() {this.getPreviousData();}.bind(this), 500);
		if(this.paging) setTimeout(function() {this.getNextData();}.bind(this), 500);
	};

	//new paging className
	this.setPagingClass = function(el) {
		if ( $(self.action+'_left') ) {
			if (this.currentRecord == 0) $(self.action+'_left').className = 'scroll_left_dis';
			else $(self.action+'_left').className = 'scroll_left';
		}
		if ( $(self.action+'_right') ) {
			if ((this.currentRecord + this.getPagingSize()) >= this.recordCount) $(self.action+'_right').className = 'scroll_right_dis';
			else $(self.action+'_right').className = 'scroll_right';
		}
	};
	this.setLeftClass = function(el) {
		if (this.currentRecord == 0)
			el.className = 'scroll_left_dis';
		else 
			el.className = 'scroll_left_act';
	};
	this.setRightClass = function(el) {
		if ((this.currentRecord + this.getPagingSize()) >= this.recordCount)
			el.className = 'scroll_right_dis';
		else 
			el.className = 'scroll_right_act';
	};
	
	this.showNavigation = function() {
		// new paging
		self.setPagingClass();
		
		// old explore paging
		if ($('page_left')) {
			if (this.currentRecord == 0) $('page_left').className = 'btn2 dis-btn2';
			else $('page_left').className = 'btn2';
		}
		if ( $('page_right') ) {
			if ( (this.currentRecord + this.getPagingSize()) >= this.recordCount ) $('page_right').className = 'btn2 dis-btn2';
			else $('page_right').className = 'btn2';
		}
	};

	this.getRecordCount = function() {
		if(this.hideCount==1) {
			if($(this.action + '_count')) $(this.action + '_count').innerHTML = '';
		} else {
			var myAjax = new Ajax.Request(
				this.getSearchCountUrl(),
				{
					method: this.ajaxMethod,
					parameters: this.getSearchCountParameters(),
					onSuccess: this.getRecordCountCallback.bind(this)
				}
			);
		}
	};
	
	this.getTableData = function() {
		//if(self.DEBUG) alert('CURRENT QUERY:: ' + this.controller + this.action +'/'+ this.id +'/' + '?current=' + this.currentRecord + '&size=' + this.getPagingSize());
		if ( self.getPagingSize() <= 0 )
			return;

		new Ajax.Request(
			self.getSearchDataUrl(0), {
				method: self.ajaxMethod,
				parameters: self.getSearchDataParameters(),
				onComplete: function(response) {
					if ( self.endLoadingCallback ) {
						self.endLoadingCallback(self.action);
					}
					if(self.DEBUG) alert('CURRENT DATA :: ' + response.responseText);
					self.currentPage = response.responseText.evalJSON();

					self.draw(self.currentPage, $(self.action + '_current'));
				}
			});
	};

	// used as pre-filter in editor
	this.setKeywordFilter = function(keyword)
	{
		if ( keyword.toLowerCase() != 'search' )
			self.keyword = keyword;
		else
			self.keyword = '';
	};

	this.getSearchCountUrl = function() {
		var url = this.controller + this.action+'_count' +'/'+ this.id +'/?';
		if ( self.search != null ) url = url + '&keyword=' + escape(encodeURI(self.search));
		if ( self.category != null ) url = url + '&category=' + escape(encodeURI(self.category));
		if ( self.brand != null ) url = url + '&brand=' + escape(encodeURI(self.brand));
		if ( self.price != null ) url = url + '&price=' + escape(encodeURI(self.price));
		if ( self.color != null ) url = url + '&colors=' + escape(encodeURI(self.color));
		return url;
	};
	this.getSearchDataUrl = function(pagingOffset) {
		var url = this.controller + this.action +'/'+ this.id +'/?'+ '&current='+(this.currentRecord + pagingOffset)+'&size='+this.getPagingSize();
		if ( self.search != null )url = url + '&keyword=' + escape(encodeURI(self.search));
		if ( self.category != null ) url = url + '&category=' + escape(encodeURI(self.category));
		if ( self.brand != null ) url = url + '&brand=' + escape(encodeURI(self.brand));
		if ( self.price != null ) url = url + '&price=' + escape(encodeURI(self.price));
		if ( self.color != null ) url = url + '&colors=' + escape(encodeURI(self.color));
		return url;
	};
	
    this.getSearchCountParameters = function() {
    	var params = new Object();
        var colors = '';
        if ( this.colorFilter != false ) {
            colors = this.colorFilter.getSelectedColorsStr();
            if (colors) params.colors = colors;
        }
        // set editor prefilter
        if ( self.keyword ) params.keyword = self.keyword;
        
        return params;
    };
    this.getSearchDataParameters = function()
    {
        var colors = '', params = new Object();
        if ( this.colorFilter != false ) colors = this.colorFilter.getSelectedColorsStr();
        if ( colors != '' ) params.colors = colors;
        // set editor prefilter
        if ( self.keyword ) params.keyword = self.keyword;
        
        return params;
    };

	this.getNextData = function() {
		if($(this.action + '_next')) {

			$(this.action + '_next').innerHTML = '';
			active = true;

			if(self.DEBUG) alert('NEXT QUERY :: ' + this.controller + this.action +'/'+ this.id +'/'+ '?current='+(this.currentRecord + this.getPagingSize())+'&size='+this.getPagingSize());
			var myAjax = new Ajax.Request(
				self.getSearchDataUrl(this.getPagingSize()),
				{
					method: self.ajaxMethod,
					parameters: self.getSearchDataParameters(),
					onComplete: function(response) {

						if(self.DEBUG) alert('NEXT DATA :: ' + response.responseText);

						active = false;
						self.nextPage = eval('(' + response.responseText + ')');
						self.draw(self.nextPage, $(self.action + '_next'));
					}
				});
		}
	};
	this.getPreviousData = function() {
		if($(this.action + '_previous')) {
			if((this.currentRecord - this.getPagingSize()) >= 0) {

				$(this.action + '_previous').innerHTML = '';
				active = true;

				var myAjax = new Ajax.Request(
					self.getSearchDataUrl(-this.getPagingSize()),
					{
						method: self.ajaxMethod,
						parameters: self.getSearchDataParameters(),
						onComplete: function(response) {
							active = false;
							self.previousPage = eval('(' + response.responseText + ')');
							self.draw(self.previousPage, $(self.action + '_previous'));
						}
					});

			} else {
				$(this.action + '_previous').innerHTML = '';
			}
		}
	};

	/*---------------------------------------------------------------*/
	this.drawTable = function(page, container) {

        var pagingElem = document.getElementById(this.action + '_paging');
		if(pagingElem) {
			to = (this.currentRecord + this.getPagingSize());
			pagingElem.innerHTML = (this.currentRecord+1) + '-' + (to > this.recordCount ? this.recordCount : to);
		}

		var maxPerRow = (this.getPagingSize() / this.rows);
		var s = [];
		for(var row = 0; row < this.rows; row++) {

			var start = (row * maxPerRow);
			if(start > page['objects'].length-1) continue;

			var end = start + maxPerRow;
			if(end > page['objects'].length-1) end = page['objects'].length;

			objPerRow = end - start;

			var a = new Array();
			var o = new Object();
			var oldScore = null;
			var isEqual = true;
			var maxI = minI = null;
			var longest = shortest = 0;
			for(var i = start; i < end; i++) {

				if ( isEqual && oldScore!=null && oldScore!=page['objects'][i].score ) {
					isEqual = false;
				}
				oldScore = page['objects'][i].score;

				if  ( !shortest || page['objects'][i].alt.length < shortest ) {
					shortest = page['objects'][i].alt.length;
					minI = a.length;
				}

				if  ( !longest || page['objects'][i].alt.length > longest ) {
					longest = page['objects'][i].alt.length;
					maxI = a.length;
				}

				a.push(new Array(
						parseInt(page['objects'][i].id, 10),
						parseInt(page['objects'][i].score, 10),
						parseInt(page['objects'][i].timestamp, 10),
						parseInt(i, 10) //page object index
				));
			}

			//if equal list, then prefer longest
			if ( isEqual ) {
				if (maxI!=null) a[maxI][1] += 3;
				if (minI!=null) a[minI][1] += 2;
			}
			//sort by score descending
			a.sort(function (a,b) {return b[1] - a[1];});

			//begin proportion calculation
			var maxWidthId = a[0][0];
			var calculatedWidth = 0;
			for(var i=0, varWidth = this.maxWidth; i<a.length; i++) {
				var idx = a[i][3];
				var thisScore = a[i][1];
				page['objects'][idx].width = parseInt(varWidth, 10);
				if(i < (a.length-1)) var nextScore = a[1+i][1];
				if(nextScore != thisScore && varWidth > this.minWidth) {
					varWidth -= this.stepSize;
				}
				if(page['objects'][idx].id != maxWidthId) {
					calculatedWidth += page['objects'][idx].width;
				}
			}

			var containerPadding = 20;
			var imageBorder = 2;
			var imagePadding = 4;
			//container + small item paddings + max item padding
			var usedSpace = containerPadding + (imageBorder + this.maxWidth) + ((objPerRow - 1) * (imageBorder + imagePadding));
			var freeSpace = this.containerWidth - usedSpace;
			if(objPerRow < maxPerRow) freeSpace -= (this.minWidth * (maxPerRow - objPerRow));


			//reduce items proportionally
			if(calculatedWidth > freeSpace) {
				var minus = ((calculatedWidth - freeSpace) / (objPerRow - 1));
				var leftover = Math.floor( (Math.ceil(minus) - minus) * (objPerRow - 1) );
				if(minus < 1) leftover = 0;
				//alert(calculatedWidth + ' / ' + freeSpace + ' minus='+minus + ' left='+leftover + ' ceil(minus)='+Math.ceil(minus));
				for(var i = start; i < end; i++) {
					if(page['objects'][i].id != maxWidthId) {
						//alert(i + ' = ' + page['objects'][i].width);
						page['objects'][i].width -= Math.ceil(minus);
						//alert(i + ' = ' + page['objects'][i].width);
						if(leftover > 0) {
							page['objects'][i].width += 1;
							leftover--;
						}
					}
				}
			}
			//maximum objects in row
			else if(objPerRow == maxPerRow && freeSpace > calculatedWidth) {
				var plus = ((freeSpace - calculatedWidth) / (objPerRow - 1));
				var leftover = Math.floor( (plus - Math.floor(plus)) * (objPerRow - 1) );
				for(var i = start; i < end; i++) {
					if(page['objects'][i].id != maxWidthId) {
						page['objects'][i].width += Math.floor(plus);
						if(leftover > 0) {
							page['objects'][i].width += 1;
							leftover--;
						}
					}
				}
			}

			//validate size
			for(var i = start; i < end; i++) {
				if(page['objects'][i].id != maxWidthId) {
					if(page['objects'][i].width > this.maxWidth) page['objects'][i].width = this.maxWidth;
					//NOTICE :: where to put the leftover validation pixels?
					//if(page['objects'][i].width < this.minWidth) page['objects'][i].width = this.minWidth;
				}
			}

			if(this.sortByDate) {
				//sort by date created desc
				a.sort(function (a,b) {return b[2] - a[2];});
			} else {
				//sort by default
				a.sort(function (a,b) {return a[3] - b[3];});
			}

			var draftDiv, q = '';
			s.push('<ul>');
			for(var j=0; j<a.length; j++) {
				var i = a[j][3];

				if(this.useMaxWidth == true) {
					var width = height = this.maxWidth;
				} else {
					var width = height = Math.floor(page['objects'][i].width);
				}

                if(this.destroy) width = height = 70;

				if ( page['objects'][i].draft )
					draftDiv = '<div>Draft</div>';
				else
					draftDiv = '';
					
				var isLast = (j+1 == a.length);

                s.push(this._getListItemHtml(page['objects'][i], width, height, isLast));
			}
			s.push('</ul>');
			if(this.rows > 1) if(!this.destroy) s.push('<div class="clear5"></div>');
		}

        if ( container ) {
		    container.innerHTML = s.join('');
        }
        else {
        }
	};
	
	
	this.clear = function() {
		$(self.action+'_current').innerHTML = '';
	};
	
	this.drawSetListSmallTable = function(page, container) {
		var s = new Array();
		var maxPerRow = parseInt(this.getPagingSize() / this.rows, 10);
		var j = 1;
		if (page['objects'].length == 0) {
			// if ($(self.action+'_container')) $(self.action+'_container').style.display = 'none';
		}
		else {
			if ($(self.action+'_container')) $(self.action+'_container').style.display = '';
			for (var i = 0; i < page['objects'].length; i++) {
				if (j == maxPerRow) {isLast = true; ; j = 1;} else {isLast = false; j++;}
				s.push(this._getSetSmallHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
			}
			container.innerHTML = s.join('');
		}
	};
	
	this.drawSetListTable = function(page, container) {
		var s = new Array();
		var maxPerRow = parseInt(this.getPagingSize() / this.rows, 10);
		var j = 1;
		if (page['objects'].length == 0) {
			// if ($(self.action+'_container')) $(self.action+'_container').style.display = 'none';
		}
		else {
			if ($(self.action+'_container')) $(self.action+'_container').style.display = '';
			for (var i = 0; i < page['objects'].length; i++) {
				if (j == maxPerRow) {isLast = true; ; j = 1;} else {isLast = false; j++;}
				s.push(this._getSetHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
			}
			container.innerHTML = s.join('');
		}
	};

	this.drawListTable = function(page, container) {
		var s = new Array();
		var maxPerRow = parseInt(this.getPagingSize() / this.rows, 10);
		var j = 1;

		if (page['objects'].length == 0) {
			// if ($(self.action+'_container')) $(self.action+'_container').style.display = 'none';
		}
		else {
			if ($(self.action+'_container')) $(self.action+'_container').style.display = '';
			for (var i = 0; i < page['objects'].length; i++) {
				if (j == maxPerRow) {isLast = true; ; j = 1;} else {isLast = false; j++;}

				if (this.format == 'item_list') s.push(this._getItemHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
				if (this.format == 'set_list_small') s.push(this._getSetSmallHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
				if (this.format == 'user_set_list') s.push(this._getUserSetHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
				if (this.format == 'set_list') s.push(this._getSetHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast ));
			}
			container.innerHTML = s.join('');
		}
	};

	this.drawScrollTable = function(page, container) {
		var s = new Array();
		var maxPerRow = parseInt(this.getPagingSize() / this.rows, 10);
		var j = 1;
		if (page['objects'].length == 0) {
			s.push('<center>The end</center>');
		}
		else {
			for (var i = 0; i < page['objects'].length; i++) {
				if (j == maxPerRow) {isLast = true; ; j = 1;} else {isLast = false; j++;}

				if (this.format == 'admin_scroll') s.push(this._getAdminHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast));
				if (this.format == 'item_scroll') s.push(this._getItemHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast)); 
				if (this.format == 'set_scroll') s.push(this._getSetHTML(page['objects'][i], this.maxWidth, this.maxWidth, isLast)); 
			}
		}
		container.innerHTML += s.join('');
	};
	
	this._getAdminHTML = function(obj, width, height, isLast) {
		s = ['<div class="item',(isLast==true ? ' last' : ''),'">', 
		     '<a href="javascript:organizeItem(',obj.id,')"><img width="',width,'" src="',obj.src,'"/></a>',
		     '<div class="product-detail">',obj.alt,
		     '</div>',
		     '</div>'].join('');
		return s;
	};
	
	this._getItemHTML = function(obj, width, height, isLast) {
		s = ['<div id="i',obj.id,'" class="item',(isLast==true ? ' last' : ''),'">', 
		     	'<a href="javascript:_getItemPopup(',obj.id,')"><img width="',width,'" src="',obj.src,'"/></a>',
		     	'<div class="product-detail">',obj.alt,
		     	'<div><span class="price">',S.showPrice(obj.price,obj.currency),'</span></div>',
	     		'</div>',
		     '</div>'].join('');
		return s;
	};

	this._getUserSetHTML = function(obj, width, height, isLast) {
		s = ['<li', (isLast ? ' class="last"' : ''), '>',
		     '<a href="', obj.href, '">',
		     '<img', ' alt="', obj.alt, '" title="', obj.alt, '" width="',width,'" src="',obj.src,'">',
		     '</a>',
		     '<p>', (obj.draft ? '<span class="red">(private)</span> ' : ''), obj.alt, '</p>', 
		     '</li>'].join('');
		return s;
	};
	
	this._getSetHTML = function(obj, width, height, isLast) {
		s = ['<li', (isLast ? ' class="last"' : ''), '>',
		     	'<a href="', obj.href, '">',
		     		'<img', ' alt="', obj.alt, '" title="', obj.alt, '" width="',width,'" src="',obj.src,'">',
		     	'</a>',
		     	'<p>by ','<a href="/', obj.user, '/">', obj.user, '</a>','</p>', 
		     '</li>'].join('');
		return s;
	};
	
	this._getSetSmallHTML = function(obj, width, height, isLast) {
		s = ['<div class="item',(isLast==true ? ' last' : ''),'">', 
		     	'<a href="',obj.href,'"><img alt="', obj.alt, '" title="', obj.alt, '" width="',width,'" src="',obj.src,'"/></a>',
		     '</div>'].join('');
		return s;
	};
	
	this._getListItemHtml = function(obj, width, height, isLast) {
        if ( obj.draft )
            draftDiv = '<div>Draft</div>';
        else
            draftDiv = '';

        s = ['<li', (isLast ? ' class="last"' : ''), '>',
                (this.destroy ? '<input style="width:20px;" type="checkbox" onclick="'+this.action+'.destroyItem(this, '+obj.id+');" value="X" />' : ''),
                '<a href="', obj.href, '" ', (this.selectId == obj.id ? 'style="border:1px solid red"' : ''), '>',
                    draftDiv,
                    ((this.showScore || this.destroy) ? '<div style="position:absolute;float;left">'+obj.score +'</div>' : ''),
                    '<img', ' alt="', obj.alt, '" title="', obj.alt, '"',
                    ' src="', obj.src, '"',
                    ' style="display:block;width:', width, 'px;height:', height, 'px;">',
                '</a>',
             '</li>'].join('');
       
        return s;
	};

	this.drawEditorTable = function(page, container) {
		if($(this.action + '_paging')) {
			to = (this.currentRecord + this.getPagingSize());
			$(this.action + '_paging').innerHTML = (this.currentRecord+1) + '-' + (to > this.recordCount ? this.recordCount : to);
		}

		var s = '';
		var start = 0;
		var end = this.recordCount;
		if(end > page['objects'].length) end = page['objects'].length;

		//leiame kogusumma, millest arvutatakse vastavalt protsentuaalselt piltide suurused
		var sum = 0;

		//leiame summa
		for(var i = start; i < end; i++) {
			if ( !this.forcePictureSize )
				sum += parseInt(page['objects'][i].score, 10);
			else {
				sum += this.forcePictureSize;
				page['objects'][i].score = this.forcePictureSize;
			}
		}
		if ( !this.forcePictureSize ) {
			//leiame suurused ja suurima
			var maxSize = 0;
			for(var i = start; i < end; i++) {
				page['objects'][i].score = ((parseInt(page['objects'][i].score, 10) * 100 / sum) * this.containerWidth / 100);
				if(page['objects'][i].score > this.maxWidth && page['objects'][i].score > maxSize) maxSize = page['objects'][i].score;
			}
			//kui suurim on liiga suur, siis arvutame uuesti ja jagame vaba osa teistele
			if(maxSize) {
				var coef = (this.maxWidth / maxSize);
				for(var i = start; i < end; i++) {
					page['objects'][i].score = (coef * page['objects'][i].score);
				}
			}
		}

		var alt, transUrl;
		s += '<ul>';
		for(var i = start; i < end; i++) {
			alt = page['objects'][i].alt.replace(/'/g, "\\'");
			alt = alt.replace(/\"/g, '&quot;');
			alt = alt.replace(/\n/g, ' ');
			alt = alt.replace(/\r/g, ' ');

			if ( page['objects'][i].transparent_url )
			    transUrl = page['objects'][i].transparent_url;
			else
			    transUrl = '';

			s += '<li style="height: ' + self.forcePictureHeight + 'px;">' +
					//'<a href="javascript:void(0)" onmouseover="S.showThumbtip(event, \''+page['objects'][i].src+'\', '+ page['objects'][i].id + ', \'' + page['objects'][i].original_src + '\', \'' + transUrl + '\')" ' +
					'<a href="javascript:void(0)" ' +
					'onmousedown="SetEditor.registerDragOntoSet(event, '+ page['objects'][i].id + ', \'' + page['objects'][i].original_src + '\', \'' + transUrl + '\', \'' + alt + '\')" onmouseup="SetEditor.unregisterDragOntoSet(event)">' +
					'<div class="hover">Add</div>' +
					'<img alt="" src="' + page['objects'][i].src + '" width="' + parseInt(page['objects'][i].score, 10) + '" onmousedown="return false;">' +
					'</a>' +
				 '</li>';
		}
		/*
		if(end == 0) {
			s += '<li>No items found</li>';
		}
		*/
		s += '</ul>';

        if ( (self.format != 'editor_scroll_table') || self.clearContainer ) {
		    container.innerHTML = '';
		    self.clearContainer = false;
        }
		container.insert(s);
	};
	
	this.onScrollWindowEvent = function(event)
	{
		var windowHeight;
		var scrollTop = document.documentElement.scrollTop;

		if (self.innerHeight) { // all except Explorer
			windowHeight = self.innerHeight;
			windowMaxHeight = self.innerHeight + window.scrollMaxY;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowHeight = document.documentElement.clientHeight;
			windowMaxHeight = document.body.offsetHeight;
		} else if (document.body) { // other Explorers
			windowHeight = document.body.clientHeight;
			windowMaxHeight = document.body.scrollHeight;
		}

		if ( (windowMaxHeight - (windowHeight + scrollTop)) <= 500  ) {
			// TODO :: tingimused, mitte enam p2ringuid teha kui maxCount on
			this.getNextPage();
			// panna l6ppu whitespace ja siis scroll tagasi
		}

	};
	
	this.onScrollEvent = function(event)
	{
		var elem = event.element();
        var height = elem.getHeight();

        if ( ( elem.scrollHeight - ( height + elem.scrollTop ) ) <= 200 ) {
        	var ulElem = elem.select('ul');
        	if ( ulElem.length > 0 && ulElem[0].childElements.length < self.recordCount ) {
                this.getNextPage();
        	}
            // panna l6ppu whitespace ja siis scroll tagasi
        }
	};
	
	this.destroyItem = function(o, itemId) {
		if(confirm('Are you sure?')) {
			o.onclick='';
			o.disabled=true;
			var headID = document.getElementsByTagName("head")[0];
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = this.controller+'destroy_explore_new_item/'+itemId;
			headID.appendChild(newScript);
		}
	};

	this.draw = function(page, container) {

		if (typeof(page) == 'undefined' || typeof(page['objects']) == 'undefined') 
			return false;

		if (typeof(container) == 'undefined' || container == null) 
			return false;
		
		switch (this.format) {
		case 'table': 
			this.drawTable(page, container);  break;
		case 'editor_scroll_table':
			this.drawEditorTable(page, container);  break;
		case 'set_list':
		case 'user_set_list':
		case 'set_list_small':
		case 'item_list':
			this.drawListTable(page, container); break; 
		case 'item_scroll':
		case 'set_scroll':
		case 'admin_scroll':
			this.drawScrollTable(page, container); break;
		}
	};

	this.getNextPage = function() {
		if(this.currentRecord < 0) this.currentRecord = 0;
		if((this.currentRecord + this.getPagingSize()) >= this.recordCount) return false;
		if(!active) {
			
			this.currentRecord += this.getPagingSize();
			
			if ( self.paging == true ) {
				this.showNavigation();
				this.previousPage = this.currentPage;
				this.currentPage = this.nextPage;
			}
			
			this.draw(this.currentPage, $(this.action + '_current'));

			if ( self.paging == true ) {
				this.draw(this.previousPage, $(this.action + '_previous'));
			}

			this.getNextData();
		}
	};
	this.getPreviousPage = function() {
		if(this.currentRecord < 0) this.currentRecord = 0;
		if(this.currentRecord == 0) return false;
		if(!active) {
			this.currentRecord -= this.getPagingSize();

			this.showNavigation();
			this.nextPage = this.currentPage;
			this.currentPage = this.previousPage;
			this.draw(this.currentPage, $(this.action + '_current'));
			this.draw(this.nextPage, $(this.action + '_next'));
			this.getPreviousData();
		}
	};

	/**
	 * Returns the paging size of current element
	 */
	this.getPagingSize = function() {
		if ( typeof(this.pagingSize) == 'object' ) {
			if ( !this._pagingSize ) {
				this._pagingSize = this._calculatePagingSize();
			}
			if ( this.format == 'editor_scroll_table' ) {
			    return this._pagingSize * 2;
			}
			else { 
                return this._pagingSize;
			}
		}
		else {
			return this.pagingSize;	
		}
	};

	this._calculatePagingSize = function() {
		// in this case, the pagingSize is an object of the paging widget container
		var containerDims = this.pagingSize.getDimensions();
		var areaHeight = containerDims.height;
        // remove paddings from both side
        var areaWidth;
        if ( this.pagingSize.style.display == 'none' ) {
        	areaWidth = containerDims.width - 40;
        }
        else {
		    areaWidth = containerDims.width - 20;
        }

		margin = 5;

        // currently we only support forced picture sizes
        var cols = Math.floor(areaWidth / (this.forcePictureSize + margin) );
        // the height is bigger than width
        var rows = Math.floor(areaHeight / ((this.forcePictureSize+20) + 2 ) );

		var pagingSize = cols * rows;
		if ( pagingSize < 0 )
			return 0;
		return pagingSize;
	};

	this.refreshPagingSize = function() {
		if ( typeof(this.pagingSize) == 'object' ) {
			var pSize = this._calculatePagingSize();

			if ( pSize > 0 && this._pagingSize != pSize ) {
                this._pagingSize = pSize;
				this.makeSearch();
			}
			else {
                // paging size is either 0 or unaffected
			    if ( pSize > 0 )
	                this._pagingSize = pSize;
	            else
	                this._pagingSize = 0;
			}
		}
	};
}

MyPaging.prototype.getRecordCountCallback = function(response)
{
    if(this.DEBUG) alert(response.responseText);
    this.recordCount = parseInt(response.responseText, 10);

    if($(this.action+'_showPaging')) {
        if(this.recordCount > this.getPagingSize()) {
            $(this.action+'_showPaging').style.display = '';
        } else {
            $(this.action+'_showPaging').style.display = 'none';
        }
    }

    if($(this.action + '_count')) {
        if(this.recordCount > 0) {
            $(this.action + '_count').innerHTML = this.recordCount;
        } else {
            $(this.action + '_count').innerHTML = 'No';
        }
        //custom case
        if (this.action == 'related_item') {
            if(this.recordCount > 0) {
                $(this.action + '_show').style.display = '';
                $(this.action + '_hide').style.display = 'none';
            }
            else {
                $(this.action + '_show').style.display = 'none';
                $(this.action + '_hide').style.display = '';
            }
        }
    }

    if($(this.action + '_of')) {
        $(this.action + '_of').innerHTML = this.recordCount;
    }

    if(this.paging) this.showNavigation();
};

if(0){var MyPaging=new MyPaging;}


function getWindowXY() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return { x:myWidth, y:myHeight };
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { x:scrOfX, y:scrOfY };
}

//FIXME :: relocate this method
function _getItemPopup(itemId) {
	new Ajax.Request('/ajax/get_item_popup/'+itemId, {method: 'get', 
		onSuccess: function(t) {
			var win_x = getWindowXY().x;
			var scroll_y = getScrollXY().y;
			
			var offset_top = $('i'+itemId).cumulativeScrollOffset().top;
			var offset_left = $('i'+itemId).cumulativeScrollOffset().left;
			
			$('divpopup').innerHTML = '';
			$('divpopup').insert(t.responseText);

			var left=0,top=0;
			left = offset_left;
			
			if (left + $('divpopup').clientWidth > win_x) left = win_x - $('divpopup').clientWidth - 50;
			if (left < 0) left = 0;
			top = offset_top - ($('divpopup').clientHeight) - 10;
			if (top + 20 < scroll_y) top = offset_top + $('i'+itemId).getHeight();

			if(left==0) {
				left = (win_x / 2) - ($('divpopup').clientWidth / 2);
			}
			
            // console.log('win_x: '+win_x+', scroll_y: '+scroll_y+', left: '+left+', top: '+top+', offset_top: '+offset_top+', offset_left: '+offset_left );
			
			$('divpopup').style.left = left + 'px';
			$('divpopup').style.top = top + 'px';
			$('divpopup').style.visibility='';
	}});
};
