// author: Josef Vanžura
// version: 1.2

/**
 *	PŘÍKLAD POUŽITÍ:
 *	
 *	<div id="cont">
 *		<div>
 *			<div class="trida1"></div>
 *			<img class="trida2"/>
 *		</div>
 *	</div>
 *	
 *	<a href="#" id="prvb">před</a>
 *	<a href="#" id="nexb">další</a>
 *	
 *	<script>
 *		var data = {
 *			pageNumber: 0,
 *			itemsPerPage: 2,
 *			variables: {
 *				'trida1': ['nazev','innerHTML'],
 *				'trida2': ['image','src']
 *			},
 *			items: [
 *				{ nazev: "Název 1", image: "1.jpg" },
 *				{ nazev: "Název 2", image: "2.jpg" },
 *				{ nazev: "Název 3", image: "3.jpg" },
 *				{ nazev: "Název 4", image: "4.jpg" },
 *				{ nazev: "Název 5", image: "5.jpg" }
 *			]
 *		}
 *
 *		var pag = new SZN.ItemsPager("cont", "prvb", "nexb", data, "inactive");
 *	</script>
 */

SZN.ItemsPager = SZN.ClassMaker.makeClass({NAME: 'ItemsPager',VERSION: '1.2',CLASS: 'class'});

/**
 * @param {String} container ID kontejnerového elementu. Jeho první potomek s nodeType==1 se bude brát jako šablona.
 * @param {String} prevButton ID elementu tlačítka 'předchozí'.
 * @param {String} nextButton ID elementu tlačítka 'další'.
 * @param {Object} data Data pro vytvoření prvků.
 * 	data = {
 * 		pageNumber: Number, // číslo aktuální stránky (od 0)
 * 		itemsPerPage: Number, // počet prvků na stránku
 * 		variables: {
 * 			class: ['prop','attribute'], // vyhledá v šablonovém fragmentu elementy s class a těm pak nastavuje attribute podle prop z data.items
 * 			class: ['prop','attribute']
 * 		},
 * 		items: [
 * 			{ prop: 'value', prop: 'value' },
 *			{ prop: 'value', prop: 'value' }
 *		]
 * 	}
 * @param {String} inactiveButtonClass Třída která se přiřadí neaktivnímu tlačítku (pokud není následující/předchozí stránka).
 */
SZN.ItemsPager.prototype.$constructor = function(container,prevButton,nextButton,data,inactiveButtonClass) {
	this.callback = [];
	this.callbackObj = [];
	this.buttonClass = inactiveButtonClass || false;
	this.prevButton = SZN.gEl(prevButton);
	this.nextButton = SZN.gEl(nextButton);
	this.container = container;
	this.pageNumber = data.pageNumber;
	this.itemsPerPage = data.itemsPerPage;
	this.clearAfter = data.clearAfter;
	this.vars = data.variables;
	this.items = data.items;
	this.elmLinks = {};
	this.template = null;
	this.stepNext = false;
	this.stepPrev = false;
	this.from = 0;
	this.to = 0;
	
	SZN.Events.addListener(this.prevButton,"click",this,"prev");
	SZN.Events.addListener(this.nextButton,"click",this,"next");

	this._getTemplate();
	this._stepsCalc();
	this._setButtons();
};

SZN.ItemsPager.prototype.start = function(e){
	this.pageNumber=0;
	this._stepsCalc();
	this._build();
	this._setButtons();
	for(var i = 0;i < this.callback.length; i++){
		this.callbackObj[i][this.callback[i]](this.pageNumber);
	}
	if(e) SZN.Events.cancelDef(e);
	try{pp_gemius_hit(__gemius_id);}catch(e){}
}

SZN.ItemsPager.prototype.next = function(e){
	if(this.stepNext){
		this.pageNumber++;
		this._stepsCalc();
		this._build();
	}
	this._setButtons();
	for(var i = 0;i < this.callback.length; i++){
		this.callbackObj[i][this.callback[i]](this.pageNumber);
	}
	SZN.Events.cancelDef(e);
	try{pp_gemius_hit(__gemius_id);}catch(e){}
}

SZN.ItemsPager.prototype.prev = function(e){
	if(this.stepPrev){
		this.pageNumber--;
		this._stepsCalc();
		this._build();
	}
	this._setButtons();
	for(var i = 0;i < this.callback.length; i++){
		this.callbackObj[i][this.callback[i]](this.pageNumber);
	}
	SZN.Events.cancelDef(e);
	try{pp_gemius_hit(__gemius_id);}catch(e){}
}

/**
 * Přidá callback, který je volán při next/prev/start akci.
 * @param {Object} callbackObj kontext volané metody (pokud je false tak se bere window)
 * @param {String} callback název volané metody
 */
SZN.ItemsPager.prototype.addCallback = function(callbackObj,callback) {
	this.callback.push( callback );
	this.callbackObj.push( (callbackObj === false)?window:callbackObj );
}

SZN.ItemsPager.prototype._setButtons = function(){
	var m,cls;
	m = this.stepPrev?"removeClass":"addClass"
	cls = this.buttonClass.replace(new RegExp("%","g"),'prev')
	SZN.Dom[m](this.prevButton,cls);

	m = this.stepNext?"removeClass":"addClass"
	cls = this.buttonClass.replace(new RegExp("%","g"),'next')
	SZN.Dom[m](this.nextButton,cls);
}

SZN.ItemsPager.prototype._build = function() {
	this.container.innerHTML = "";
	for(var i = this.from; i < this.to; i++){
		for(var v in this.items[i]){
			for(var el = 0; el < this.elmLinks[v].length; el++){
				var attr = this.elmLinks[v][el][1];
				if('src|href|width|height|rel|id|alt|title'.indexOf(attr) != -1){
					this.elmLinks[v][el][0].setAttribute(attr, unescape(decodeURIComponent(this.items[i][v])));
				} else {
					this.elmLinks[v][el][0][attr] = this.items[i][v];
				}
			}
		}
		this.container.appendChild(this.template.cloneNode(true));
		if(this.clearAfter && (i-this.from+1)%this.clearAfter == 0) {
			this.container.appendChild(SZN.cEl('div', '', 'cleaner'));
		}
	}
}

SZN.ItemsPager.prototype._stepsCalc = function(){
	this.stepNext = true;
	this.stepPrev = true;
	this.offset = this.pageNumber*this.itemsPerPage;
	var len = this.items.length;
	var fr = this.offset;
	var to = this.offset+this.itemsPerPage;
	if(fr <= 0){ fr = 0;this.stepPrev = false; }
	if(to >= len){ to = len;this.stepNext = false; }
	this.from = fr;
	this.to = to;
}

SZN.ItemsPager.prototype._getTemplate = function(){
	this.container = SZN.gEl(this.container);
	var node = this.container.firstChild;
	while(node.nodeType != 1){
		node = node.nextSibling;
	}
	this.template = node.cloneNode(true);
	this._exploreNode(this.template);
}

SZN.ItemsPager.prototype._exploreNode = function(node){
	for(var i = 0; i < node.childNodes.length; i++){
		if(node.childNodes[i].nodeType != 1) continue;
		
		var cl = node.childNodes[i].className;
		if(cl.indexOf(" ")!=-1){
			cl = cl.split(" ");
			for(var c = 0; c < cl.length; c++){
				if(cl[c] in this.vars){
					var x = this.vars[cl[c]];
					if(!this.elmLinks[x[0]]){this.elmLinks[x[0]] = []};
					this.elmLinks[x[0]].push([ node.childNodes[i], x[1] ]);
				}
			}
		} else {
			if(cl in this.vars){
				var x = this.vars[cl];
				if(!this.elmLinks[x[0]]){this.elmLinks[x[0]] = []};
				this.elmLinks[ x[0] ].push([ node.childNodes[i], x[1] ]);
			}
		}
		this._exploreNode(node.childNodes[i]);
	}
}
