// Copyright (C) 2009-2010 Michael A. Bunkin
// http://bunkin.ru

function mbTimer(func,delay,oneTime,runOnStart) {
	if (func.length!=undefined) {
		this.funcObject = func[0];
		this.funcMethod = func[1];
	} else {
		this.funcObject = null;
		this.func = func;
	}
	this.delay = delay;
	this.oneTime = (oneTime==undefined?false:oneTime);
	this.runOnStart = (runOnStart==undefined?false:runOnStart);
	this.handle = null; // setTimeout handle
	this.dateObject = new Date();
	this.setOn = 0; // when called to setTimeout
	this.setUntil = 0; // setOn + delay
	this.pausedOn = 0; // for pausing

	this.set = function(delay) {
		if (delay == undefined) delay = this.delay;
		if (delay >= 0) {
			this.setOn = this.dateObject.getTime();
			this.setUntil = this.setOn + delay;
			var scope = this;
			this.handle = setTimeout(function(){scope.perform()},delay);
		}
	}

	this.perform = function() {
		this.handle = null;
		this.setOn = null;
		if (this.funcObject) {
			this.funcObject[this.funcMethod]();
		} else this.func();
		if (!this.oneTime) this.set();
	}

	this.pause = function() {
		if (this.handle) {
			clearTimeout(this.handle);
			this.handle = null;
			this.pausedOn = this.dateObject.getTime();
			return (this.setUntil-this.pausedOn);
		}
		return -1;
	}

	this.resume = function() {
		if (this.pausedOn) {
			this.set(this.setUntil - this.pausedOn);
			this.pausedOn = 0;
		}
	}

	this.stop = function() {
		clearTimeout(this.handle);
		this.handle = null;
		this.setOn = 0;
		this.pausedOn = 0;
		this.setUntil = 0;
	}

	if (runOnStart) this.perform();
	else this.set();
}

function mbXMLSlideShow(el,xmlurl,fadeDuration,slideDelay) {
	this.containerEl = document.getElementById(el);
	if (!this.containerEl) return false;

	this.fadeDuration = fadeDuration==undefined?1000:fadeDuration;
	this.slideDelay = slideDelay==undefined?3000:slideDelay;
	this.paused = 0;

	// Init Ajax
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		this.http = new XMLHttpRequest();
		if (this.http.overrideMimeType) {
			//this.http.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			this.http = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				this.http = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {}
		}
	}

	if (!this.http) return false;
	var self = this;

	this.http.onreadystatechange = function() {
		if (this.readyState == 4) {
			if (this.status == 200) {
				if (!this.responseXML.documentElement && this.responseStream) {
  				this.responseXML.load(this.responseStream);
				}
				self.initXML(this.responseXML);
			} else alert('Request error '+this.status);
		}
	};

	this.http.open('GET',xmlurl,true);
	this.http.send();

	this.initXML = function(xmlObject)  {
		var xmldoc = xmlObject.documentElement;

		var images = xmldoc.getElementsByTagName('image');
		var imageArray = [];
		// For buttons
		var buttons = document.createElement('UL');

		var $prev = $('<li>&#9668;</li>').bind('click',function(){ var prev = $(this).parent().find('LI.current').prev(); if ($(this)!=prev) prev.trigger('click'); }); //25b6 and 25c4
		var $next = $('<li>&#9658;</li>').bind('click',function(){ var next = $(this).parent().find('LI.current').next(); if ($(this)!=next) next.trigger('click'); }); //25b6 and 25c4

		$(buttons).append($prev);

		for(var i=0; i<images.length; i++) {
			var image = {
				'src':images[i].getElementsByTagName('img')[0].childNodes[0].nodeValue,
				'link':images[i].getElementsByTagName('imgLink')[0].childNodes[0].nodeValue
			};
			imageArray[imageArray.length] = image;
			var div = document.createElement('DIV');
			var a = document.createElement('A');
			var img = document.createElement('IMG');
			img.setAttribute('src',image.src);
			a.setAttribute('href',image.link);
			a.appendChild(img);
			div.appendChild(a);
			$(div).css({opacity:0});
			this.containerEl.appendChild(div);
			var li = document.createElement('LI');
			li.innerHTML = i+1; //'&#9675;';
			buttons.appendChild(li);
			$(div).data('button',li);
			$(li).data('slide',div);
			$(li).bind('click',function() { if (!$($(this).data('slide')).hasClass('current')) { self.stop(); self.slide($(this).data('slide')); } });
			if (i == 0) {
				$(div).css({opacity:1}).addClass('current');
				$(li).addClass('current');
				//li.innerHTML = '&#9679;';
			}
		}

		$(buttons).append($next);
		$(buttons).children('LI').unselectable();
		$(this.containerEl).unselectable();
		//25b6 and 25c4

		this.containerEl.appendChild(buttons);
	};

	this.slide = function(next) {
		var current = $(this.containerEl).find('DIV.current');
		if (current.length==0) current = $(this.containerEl).find('DIV:last');
		if (next == undefined) {
			var next = current.next('DIV');
			if (next.length==0) next = $(this.containerEl).find('DIV:first');
		} else {
			var next = $(next);
		}

		if (next != current) {
			current.parent().children('DIV').stop(true,true);
			current.removeClass('current').addClass('last-current');
			$(current.data('button')).parent().children('LI').removeClass('current');
			$(next.data('button')).addClass('current');
			next.css({opacity:0}).addClass('current').animate({opacity:1}, this.fadeDuration, function() {
				current.removeClass('current last-current');
				//current.data('button').innerHTML = '&#9675;';
				//next.data('button').innerHTML = '&#9679;';
			});
		}
	}

	this.init = function() {
		$(this.containerEl).find('A').bind('mouseover',function(){self.pause(1);}).bind('mouseout',function(){self.resume(1);});
		$(this.containerEl).find('INPUT').bind('focus',function(){selft.pause(2);}).bind('blur',function(){self.resume(2);});
		$(document).find('A[href="#mbSlideshow('+this.containerEl.id+').pause"]').bind('click',function(){self.stop();});
		//$(document).find('A[href="#mbSlideshow('+this.sliderName+').resume"]').bind('click',function(){scope.resume(4);});
		this.timer = new mbTimer([this,'slide'],this.slideDelay);
	}

	this.pause = function(sw) {
		var paused = (this.paused & sw);
		if (paused==0) { this.timer.pause(); this.paused |= sw; }
	}
	this.resume = function(sw) {
		if (this.paused > 0) {
			this.paused &= (~sw);
			if (this.paused==0) { this.timer.resume(); }
		}
	}
	this.stop = function() { this.timer.stop(); }

	self.init();
}

/**
 * @author Samele Artuso <samuele.a@gmail.com>
 */
(function($) {
	$.fn.unselectable = function() {
		return this.each(function() {

			$(this)
				.css('-moz-user-select', 'none')		// FF
				.css('-khtml-user-select', 'none')		// Safari, Google Chrome
				.css('user-select', 'none');			// CSS 3

			if ($.browser.msie) {						// IE
				$(this).each(function() {
					this.ondrag = function() {
						return false;
					};
				});
				$(this).each(function() {
					this.onselectstart = function() {
						return (false);
					};
				});
			} else if($.browser.opera) {
				$(this).attr('unselectable', 'on');
			}
		});
	};
})(jQuery);
