/*
 * LovePlanet AJAX pagination
 */
var pgn = {
	cache: {},
	isIE: /MSIE/.test(navigator.userAgent),
	xhr: window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(),
	iframeId: "iframe_"+Math.floor(Math.random()*1000000),
	url: "",
	load: {page: 0, state: 0, handler: 0},
	msg_box: [],
	msg: {
		load: "Загрузка&hellip;",
		error: "Сервер не отвечает"
	},
	

	getDocObj: function(){
		if(pgn.isIE)
			return document.getElementById(pgn.iframeId).contentWindow.document;
		else
			return document;
	},

	showStatus: function(msg, cname){
		var mbox = null;
		for(var i=0; i<pgn.msg_box.length; i++){
			mbox = document.getElementById(pgn.msg_box[i]);
			if(mbox!=null){
				mbox.className = cname;
				mbox.style.display = "block";
				mbox.innerHTML = msg;
			}
		}
	},

	hideStatus: function(msg){
		for(var i=0; i<pgn.msg_box.length; i++){
			mbox = document.getElementById(pgn.msg_box[i]);
			if(mbox!=null) mbox.style.display = "none";
		}
	},

	scanLocation: function(reload){
		if ((document.location.hash != pgn.hash)||(pgn.getDocObj().location.hash != pgn.hash) || reload === true){
			var hs = pgn.isIE? pgn.getDocObj().location.hash : document.location.hash;
			pgn.hash = hs;
			if(pgn.isIE) document.location.hash = pgn.getDocObj().location.hash = pgn.hash;
			var initpm = pgn.hash.match(new RegExp("^#"+pgn.phash+"\\/(\\d+)$", "i"));
			var initp = (initpm !== null)? parseInt(initpm[1]) : 1;
			if((hs == "" || hs == "#") && document.location.href.indexOf("#") != -1){
				window.history.go(pgn.isIE? ((pgn.initpage > 1)? -1 : -2) : -2);
			}else{
				pgn.loadPage(initp + pgn.pshft, 0);
			}
		}
	},

	renderHTML: function(html){
		var js, re=/<script\s*\S*>(?:<!--)?(.+?)(?:-->)?<\/script>/ig;
		if(pgn.before!=null) pgn.before();
		document.getElementById(pgn.cid).innerHTML=html;
		if(pgn.after!=null) pgn.after();
		pgn.setOnClick();
		while ((js = re.exec(html)) != null){
			try{eval(js[1])}
			catch(e){/*alert(e)*/}
		}
	},

	setHash: function(page, start){
		pgn.hash = start? "#" : ("#"+pgn.phash+"/"+page);
		document.location.hash = pgn.hash;
		if(pgn.isIE){
			pgn.getDocObj().open();
			pgn.getDocObj().close();
			pgn.getDocObj().location.hash = pgn.hash;
		}
	},

	loadPage: function(page, isSetHash){
		if(this.load.state==1){
			/* Some info about busy connection */
			return false;
		}
		this.showStatus(this.msg.load, "ajaxact");
		if(pgn.cache[page]==null){
			this.xhr.open('GET', this.url.replace("%p%", page), true);
			this.xhr.onreadystatechange = function(){
				if(pgn.xhr.readyState == 4 && pgn.xhr.status == 200){
					window.clearTimeout(pgn.load.handler);
					pgn.load.state = 2;
					if(isSetHash) pgn.setHash(pgn.load.page - pgn.pshft);
					var responseText = pgn.xhr.responseText.replace(/(^[\s\t]+)/gm, "").replace(/(\r\n|\r|\n)/g, "");
					if(pgn.ttl) pgn.cache[pgn.load.page] = {time: Math.floor((new Date()).getTime()/1000), html: responseText};
					pgn.renderHTML(responseText);
					pgn.hideStatus();
				}
			}
			this.load = {state: 1, page: parseInt(page), handler: window.setTimeout(function(){
				if(pgn.load.state == 1){
					pgn.load.state = 0;
					pgn.showStatus(pgn.msg.error, "ajaxerror");
					pgn.xhr.abort();
				}
			}, 15000)};
			this.xhr.send(null);
		}else{
			if(isSetHash) pgn.setHash(page - pgn.pshft);
			pgn.renderHTML(pgn.cache[page].html);
			pgn.hideStatus()
		}
		return false;
	},

	setOnClick: function(){
		/* Attach onclick event for pages links */
		var node = document.getElementsByTagName("body")[0],
		a = [], l = [], i, j,
		re = new RegExp('\\b' + this.npc + '\\b'),
		els = node.getElementsByTagName("*");
		for(i=0,j=els.length; i<j; i++)
			if(re.test(els[i].className))a.push(els[i]);
		for (i=0; i<a.length; i++){
			l = a[i].getElementsByTagName("a");
			for (j=0; j<l.length; j++){
				if (this.url == "") this.url = "/?"+l[j].href.replace(/http:\/\/[^\/]+\//i, "").replace(/\//g, "&").replace(/-/g, "=").replace(new RegExp("("+this.parg+"=)\\d+"), "$1%p%")+this.ajax;
				l[j].onclick = function(){return pgn.loadPage(parseInt(this.href.match(new RegExp(pgn.parg+"-(\\d+)", "i"))[1]), 1)};
			}
		}
	},

	manageCache: function(){
		var now = Math.floor((new Date()).getTime()/1000);
		for (var i in pgn.cache){
			if(now - pgn.cache[i].time > pgn.ttl) delete pgn.cache[i];
		}
	},

	init: function(conf){
	/*
	 * cid - container ID for innering response
	 * parg - name of page argument in query string (page, p etc)
	 * phash - name of page parameter in location hash
	 * mbox - array of message box containers id
	 * ttl - time for valid page in cache
	 * before - function executing before rendering new page
	 * ajax - additional param for AJAX queries
	 * npc - class of navigation page container
	 * pshft - shift "phash" comparatively "parg"
	 */
		if (typeof conf!= "object" || this.xhr==null) return false;
		if (!conf.cid) return false;
		this.cid = conf.cid;
		this.parg = (typeof conf.parg == "string")?conf.parg:"page";
		this.phash = (typeof conf.phash == "string")?conf.phash:"page";
		this.msg_box = (typeof conf.mbox == "array")?conf.mbox:["pgn_msg_top", "pgn_msg_bottom"];
		this.before = (typeof conf.before == "function")?conf.before:null;
		this.after = (typeof conf.after == "function")?conf.after:null;
		this.ttl = (typeof conf.ttl == "number")?conf.ttl:0;
		this.ajax = (typeof conf.ajax == "string")?conf.ajax:"ajax";
		this.npc = (typeof conf.npc == "string")?conf.npc:"navp";
		this.pshft = (typeof conf.pshft == "number")?conf.pshft:-1;
		
		if(this.isIE){
			var iframe = document.createElement("iframe"), doc = null, body = null;
			iframe.id = this.iframeId;
			iframe.style.display = "none";
			body = document.getElementsByTagName("body")[0];
			body.insertBefore(iframe, body.childNodes[0]);
			/*doc = iframe.contentWindow.document;
			doc.open();
			doc.close();
			doc.location.hash="#";*/
		}
		
		this.setOnClick();
		if(this.url=="") this.url = "/?"+(document.location.href.split("#")[0]).replace(/http:\/\/[^\/]+\//i, "").replace(/\//g, "&").replace(/-/g, "=").replace(new RegExp("("+this.parg+"=)\\d+"), "$1%p%")+"&"+this.ajax;
		var initpm = document.location.hash.match(new RegExp("^#"+pgn.phash+"\\/(\\d+)$", "i"));
		this.initpage = (initpm !== null)? parseInt(initpm[1]) : 1;
		
		this.setHash(0, 1);
		this.setHash(this.initpage);
		if(this.initpage > 1){
			this.loadPage(this.initpage + this.pshft, 0);
		}
		
		this.inhdl = window.setInterval(this.scanLocation, 100);
		if (this.ttl) window.setInterval(this.manageCache, 1000);
	}
}