// Copyright (C) 2009-2011 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();
}

// returns key-value array of DOM element attributes
function mbXMLAttributes(el) {
	var ret = {};
	if (el!=null && el.attributes) for (var i=0; i<el.attributes.length; i++) ret[el.attributes.item(i).nodeName] = el.attributes.item(i).nodeValue;
	return ret;
}

function mbAttributes(el) {
	var ret = {};
	if (el!=null && el.attributes) for (var i=0; i<el.attributes.length; i++) if (el.attributes[i].specified) ret[el.attributes[i].nodeName] = el.attributes[i].nodeValue;
	return ret;
}

// coalesce(a,b,c,d,e...)
function coalesce() {
	for(var i=0; i<arguments.length; i++) if (arguments[i]!==null) return arguments[i];
	return null;
}

// coalesce([a,b,c,d,e...],'')
function coalesceDef(vars,def) {
	for(var i=0; i<vars.length; i++) if (vars[i]!==null) return vars[i];
	return def;
}

// normalize width or height
function mbSizeNormalize(s) { return (s!=null) ? s+'px' : 'auto'; }


// Options accept the following keys: galleryId, thumbsId, optionsId, fadeDuration, slideDelay
function mbXMLTestimonials(xmlurl,slideDelay,slideDuration,containerId) { //,fadeDuration,slideDelay) {
	this.containerEl = document.getElementById(containerId || 'mbTestimonials');
	if (!this.containerEl) return false;

	this.slideDuration = slideDuration;
	this.slideDelay = slideDelay;
	this.paused = 0;
	this.config = {};

	// 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) {
				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;

		// Inlay panel to provide horizontal scrolling
		var inlayDiv = document.createElement('DIV');

		// Global config in the <images> attributes
		//this.config = mbXMLAttributes(xmldoc.getElementsByTagName('testimonials')[0]);
		//var w = $(this.containerEl).width();

		// Testimonials
		var els = xmldoc.getElementsByTagName('testimonial');
		var items = [];
		for (var i=0; i<els.length; i++) items[i] = els[i];
		// Randomize
		items.sort(function(){return 0.5-Math.random()});
		items[items.length] = items[0];
		for(var i=0; i<items.length; i++) {
			var tmp, content, author;

			tmp = items[i].getElementsByTagName('content');
			if (tmp.length > 0) content = tmp[0].childNodes[0].nodeValue;
			tmp = items[i].getElementsByTagName('author');
			if (tmp.length > 0) author = tmp[0].childNodes[0].nodeValue;

			// Create containers
			var itemDiv = document.createElement('DIV');
			var contentDiv = document.createElement('DIV');
			var authorDiv = document.createElement('DIV');

			contentDiv.className = 'mbTestimonial-content';
			contentDiv.innerHTML = content;
			
			authorDiv.className = 'mbTestimonial-author';
			authorDiv.innerHTML = author;

			itemDiv.className = 'mbTestimonial';
			itemDiv.appendChild(contentDiv);
			itemDiv.appendChild(authorDiv);

			inlayDiv.appendChild(itemDiv);
		}

		inlayDiv.style.width = mbSizeNormalize(items.length * $(this.containerEl).width());

		this.containerEl.innerHTML = '';
		this.containerEl.appendChild(inlayDiv);
	};

	this.slide = function(next) {
		var $inlay = $(this.containerEl).children().eq(0);
		var $current = $inlay.find('DIV.current');
		var $next;
		if ($current.length==0) $current = $inlay.find('DIV:last');
		if (next == undefined) {
			$next = $current.next('DIV');
			if ($next.length==0) {
				$current = $inlay.find('DIV:first');
        $(this.containerEl).scrollTo($current,0);
				$next = $current.next('DIV');
			}
		} else if (next === parseInt(next,10)) {
			$next = $inlay.find('DIV').eq(next);
			if ($next == null) return;
		} else {
			$next = $(next);
		}
		
		if ($next != $current) {
      $(this.containerEl).scrollTo($next,this.slideDuration);
			$current.removeClass('current');
			$next.addClass('current');
		}
	}

	this.init = function() {
		$(this.containerEl).find('DIV.mbTestimonial').bind('mouseover',function(){self.pause(1);}).bind('mouseout',function(){self.resume(1);});
		this.timer = new mbTimer([this,'slide'],this.slideDelay,false,true);
	}

	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();
}
