window.utils = {
	// Test if user agent is android
	isAndroid : function() {
		if (utils.regexpTest('Mozilla\\/5\\.0 \\(Linux; U; Android', navigator.userAgent)) {
			return true;
		}
		return false;
	},
	// Test if user agent is iPhone
	isIPhone : function() {
		var validUserAgents = new Array('iPhone', 'iPod');
		for (var i = 0; i < validUserAgents.length; i++) {
			if (utils.regexpTest(validUserAgents[i], navigator.userAgent)) {
				return true;
			}
		}
		return false;
	},
	// Test regular expression
	regexpTest : function(pattern, subject) {
		var regexp = new RegExp(pattern, "i");
		return regexp.test(subject);
	}
};

(function () {  // Module pattern

var global = this;
function utils_extend(obj, dict)
{
    for (var key in dict)
    {
        obj[key] = dict[key];
    }
}

TrayController2 = function ()
{
	// Parameters
	this.animationDuration = 500;
	this.intervalDuration = 5000;
}

TrayController2.prototype.init = function (elem)
{
    this.currentX = 0;
    this.elem = elem;
    this.elem.style.webkitTransitionDuration = this.animationDuration + "ms";
    this.interval = setInterval(this.autoAnim, this.intervalDuration, this);
}

TrayController2.prototype.autoAnim = function (self) {
	// Last element
	var limit = self.delegate.cells.length - 1;
	var currentCell = Math.abs(self.currentX) / 100;
	
	// What is the way
	if (typeof this.sens == 'undefined') {
		this.sens = "right";
	}
	else if (this.sens == "right" && currentCell >= limit) {
		this.sens = "left";
	}
	else if (this.sens == "left" && currentCell <= 0) {
		this.sens = "right";
	}
	
	// New x
	if (this.sens == "right") {
		self.currentX = parseInt(self.currentX) - 100;
	}
	else {
		self.currentX = parseInt(self.currentX) + 100;
	}
	
	// Element displaying
	currentCell = Math.abs(self.currentX) / 100;
	
	self.delegate.updateBarStatus(currentCell);
	self.delegate.update(self.currentX + "%");
}

TrayController2.prototype.touchstart = function (event)
{
	// Delete touchstart event to disable scroll
	event.stopPropagation();
	clearInterval(this.interval);
	
	// Last position was %, we transform into px
	this.currentX = this.elem.offsetWidth * parseInt(this.currentX) / 100;
	this.delegate.update(this.currentX + "px");
	
	// We stock first element position
	this.currentStartX = this.currentX;
	// Stock first touch position
	this.startX = event.touches[0].pageX;
    
	// To know if guy move or clic
	this.touchMoved = false;
    
	// Listener touchmove and touchend event
    this.elem.addEventListener("touchmove", this, true);
    this.elem.addEventListener("touchend", this, true);
    
    // Disable animation
    this.elem.style.webkitTransitionDuration = "0ms";
}

TrayController2.prototype.touchmove = function (event)
{
	// Ok, guy move his finger !
    this.touchMoved = true;
    // Stock element position
    this.lastX = parseInt(this.currentX);
    // Update new element position
    this.currentX = this.currentStartX + event.touches[0].pageX - this.startX;
    this.delegate.update(this.currentX + "px");
}

TrayController2.prototype.touchend = function (e)
{
	// Remove touchmove and touchend listener
	this.elem.removeEventListener("touchmove", this, true);
    this.elem.removeEventListener("touchend", this, true);
    
    if (this.touchMoved) {
        // Enable animation
        this.elem.style.webkitTransitionDuration = this.animationDuration + "ms";
        
    	// Right or left
		var delta = this.currentX - this.lastX;
		var elementWidth = this.elem.offsetWidth;
		
		// Left
		if (delta < 0) {
			this.currentX = parseInt(this.currentX) - elementWidth;
			this.delegate.updateTouchEnd(this, "neg");
		}
		// Right
		else {
			this.currentX = parseInt(this.currentX) + elementWidth;
			this.delegate.updateTouchEnd(this, "pos");
		}
    }
    else {
    	// Get target
    	var target = event.target; 
    	while (target && (target.nodeType != 1 || target.localName.toLowerCase() != 'a')) {
    		target = target.parentNode;
    	}

    	// Send click event
    	if (target) {
	    	var theEvent = document.createEvent("MouseEvents");
			theEvent.initEvent('click', true, true);
			target.dispatchEvent(theEvent);
    	}
    }
}

TrayController2.prototype.handleEvent = function (event)
{
    this[event.type](event);
    event.preventDefault();
}

FlowDelegate2 = function ()
{
	// Parameters
	this.barStatusId = 'scroll1';
	this.barStatusBulletIdPrefix = 'dot';
	this.barStatusBulletClass = this.barStatusBulletIdPrefix + 'G';
	this.barStatusActiveBulletClass = this.barStatusBulletIdPrefix + 'W';
	
    this.cells = new Array();
    this.transforms = new Array();
}

FlowDelegate2.prototype.init = function (elem)
{
    this.elem = elem;
}

FlowDelegate2.prototype.updateTouchEnd = function (controller, sign)
{
	var i = this.getFocusedCell(controller.currentX, sign);
	
	//	dots manager
   
	if (controller.elem.id == "tray"){
		this.updateBarStatus(i);
	} 
    
    controller.currentX = - i * 100;
    this.update(controller.currentX + "%");
}

FlowDelegate2.prototype.barStatus = function (cell)
{
	var scroll1 = document.getElementById(this.barStatusId);
	if(scroll1 != undefined){
		for(j = 0; cell.length > j; j++){
			var spanLine = document.createElement('span');
			spanLine.id = this.barStatusBulletIdPrefix + j;
			spanLine.className = j == 0 ? this.barStatusActiveBulletClass : this.barStatusBulletClass;
			// spanLine.innerHTML = "&#8226;";
			scroll1.appendChild(spanLine);
		}
	}
}

FlowDelegate2.prototype.updateBarStatus = function (current) {
	var scroll1 = document.getElementById(this.barStatusId);
	if (scroll1 != undefined) {
		for (j = 0; scroll1.childNodes.length > j; j++) {
			if (scroll1.childNodes[j] != undefined && scroll1.childNodes[j].className == this.barStatusActiveBulletClass) {
				scroll1.childNodes[j].className = this.barStatusBulletClass;
			}
			var dot = document.getElementById(this.barStatusBulletIdPrefix + current);
			if (dot != undefined) {
				dot.className = this.barStatusActiveBulletClass;	
			}
		}
	}
}

FlowDelegate2.prototype.getFocusedCell = function (currentX, sign)
{
    // Snap to nearest position
	var elementWidth = this.elem.offsetWidth;
	
	if (sign=="neg")
		var i = Math.floor(Math.abs(currentX) / elementWidth);
	else
		var i = - Math.floor(currentX / elementWidth);

    // Clamp to cells array boundary
    return Math.min(Math.max(i, 0), this.cells.length - 1);
}

FlowDelegate2.prototype.transformForCell = function (cell, i, offset)
{
    var x = (i * 100);
	if (utils.isIPhone()) {
    	return "translate3d(" + x + "%, 0, 0)";
    }
    else {
    	return "translate(" + x + "%, 0)";
    }
}

FlowDelegate2.prototype.setTransformForCell = function (cell, i, transform)
{
    if (this.transforms[i] != transform)
    {
        cell.style.webkitTransform = transform;
        this.transforms[i] = transform;
    }
}

FlowDelegate2.prototype.update = function (currentX)
{
	if (utils.isIPhone()) {
		this.elem.style.webkitTransform = "translate3d(" + (currentX) + ", 0, 0)";
	}
	else {
		this.elem.style.webkitTransform = "translate(" + (currentX) + ", 0)";
	}

    for (var i in this.cells)
    {
        var cell = this.cells[i];
        this.setTransformForCell(cell, i, this.transformForCell(cell, i, currentX));
        i += 1;
    }
}

global.zflow2 = function(content, selector)
{
	// Get page header title to apply different css style class
	if (document.title != 'SFR Sport') {
		var pageCat = 'soushome';
	} else {
		var pageCat = 'home';
	}

	var tray = document.querySelector(selector);
	if (tray == null || tray == undefined || tray == "") {
		return;
	}
	
    var controller = new TrayController2();
    var delegate = new FlowDelegate2();
    
    controller.init(tray);
    delegate.init(tray);

	controller.delegate = delegate;

	delegate.barStatus(content);

	var imagesLeft = content.length;
	
    var cellCSS = {
		opacity: 0
    };
    
    content.forEach(function (contenu, i)
    {
		var cell = document.createElement("div");
		var container = document.createElement("a");
        var titreSpan = document.createElement("span");
        var descriptionSpan = document.createElement("span");
        var arrowSpan = document.createElement("span");
        var dateSpan = document.createElement("span");
		var image = document.createElement("img");

		var titleNode = document.createTextNode(content[i].title);
		var descriptionNode = document.createTextNode(content[i].head);
		var dateNode = document.createTextNode(content[i].date);
		var arrowNode = document.createTextNode("");

		if (content[i].videoHref != '') {
			var video = document.createElement("div");
//			video.src = "/sfrxphone/images/buttons/icon_play.png";
			video.style.background = "transparent url(/sfrxphone/images/buttons/icon_play.png) no-repeat center center";
			cell.appendChild(video);
			video.className = "video";
		}

		cell.id = 'cell' + i;
		cell.url = content[i].url;
		container.href = content[i].url;
		container.className = "no_ajax";

		cell.className = "cell";
		if (pageCat == 'soushome') {
			cell.addClassName('cell2');
		} 
		
		cell.appendChild(container)
		container.appendChild(image);
		container.appendChild(titreSpan);
		container.appendChild(descriptionSpan);
		container.appendChild(dateSpan);
		container.appendChild(arrowSpan);

		titreSpan.appendChild(titleNode);
		descriptionSpan.appendChild(descriptionNode);
		dateSpan.appendChild(dateNode);
		arrowSpan.appendChild(arrowNode);

		titreSpan.className = "title";
		descriptionSpan.className = "description";
		arrowSpan.className = "arrow";
		dateSpan.className = "date";

		image.src = content[i].imageHref;

		imagesLeft -= 1;

		/*var iwidth = "240px";
		var iheight = "160px";

		var ratio = Math.min(CSIZE / iheight, CSIZE / iwidth);

		iwidth *= ratio;
		iheight *= ratio;*/

		utils_extend(cell.style, cellCSS);

		/*utils_setxy(cell, (CSIZE - iwidth) / 2, CSIZE - iheight);*/

		delegate.setTransformForCell(cell, delegate.cells.length, delegate.transformForCell(cell, delegate.cells.length, controller.currentX));
		delegate.cells.push(cell);

		cell.style.opacity = 1.0;
		// Start at 0 opacity
		tray.appendChild(cell);

		// Set to 1 to fade element in.
		cell.style.opacity = 1.0;

		if (imagesLeft == 0) {
			window.setTimeout( function() { window.scrollTo(0, 0); }, 100 );
		}
	});

	tray.addEventListener('touchstart', controller, false);
}

})();

