function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

function windowWidth(){

    if (window.innerWidth){
        if (document.body.offsetWidth){
            if (window.innerWidth!=document.body.offsetWidth)
                return document.body.offsetWidth;
            }
        return (window.innerWidth);                     // Mozilla
    }


    if (document.documentElement.clientWidth)
        return document.documentElement.clientWidth;    // IE6


    if (document.body.clientWidth)
        return document.body.clientWidth;               // IE DHTML-compliant any other
}

function onFaviconClick(ev){
	
	var eventNode = null;
		
	if(ev.srcElement)
		eventNode = ev.srcElement;
	else
		eventNode = this;
	
	var filmstrip = eventNode.parentNode.parentNode.filmstrip;

	// Ignore clicks that were due to dragging for sorting
	if(new Date() - filmstrip.lastSortTime < 100)
		return;
		
	var idx = filmstrip.getFrameIdx(eventNode.parentNode);
	filmstrip.selectFrame(idx);
}


function Filmstrip(containerNode, faviconSpacing, selectedFrameWidth, linksData, mutable){
	this.containerNode = containerNode;
	this.faviconSpacing = faviconSpacing;
	this.selectedFrameWidth = selectedFrameWidth;
	this.mutable = mutable;
	this.lastSortTime = new Date();
	
	containerNode.filmstrip = this;
	
	this.selectedFrameNode = null;
	this.createStripFrames(linksData);
	this.makeSortable();
}

Filmstrip.prototype.makeSortable = function(){
	if(this.mutable){
		Sortable.destroy(this.containerNode.id);
		Sortable.create(this.containerNode.id,
		     {tag: "div", onUpdate: function(element){element.filmstrip.onSort()}, dropOnEmpty:false,constraint:false,overlap:"horizontal"});	
	}
}

Filmstrip.prototype.onSort = function(){
	this.lastSortTime = new Date();
	this.resize();
	
	var idSeq = "seq=";
	var frameNodes = this.containerNode.childNodes;
	
	for(var i=0; i<frameNodes.length; ++i){
		idSeq += frameNodes[i].item_id + "+";
	}
	
	setCookie('lasti', this.getFrameIdx(this.selectedFrameNode), new Date(2020, 12, 31));
	
	new Ajax.Request('/shuffle/update_link_seq', {method:'post', postBody: idSeq});
}

Filmstrip.prototype.toString = function(){ return "[object Filmstrip]"; }

Filmstrip.prototype.calcNewLeftPos = function(idx){
	return windowWidth() / 2 - ((16 + this.faviconSpacing) * idx) - (this.selectedFrameWidth + this.faviconSpacing) / 2;
}

Filmstrip.prototype.resize = function(){
	var newLeftPos = this.calcNewLeftPos(this.getFrameIdx(this.selectedFrameNode));
	this.containerNode.style.left = newLeftPos + "px";
}

Filmstrip.prototype.createStripFrames = function(linksData){
	// Remove any currently in frame
	while(this.containerNode.firstChild)
		this.containerNode.removeChild(this.containerNode.firstChild);
		
	for(i=0;i<linksData.length;i++){
		this.appendStripFrame(linksData[i])
	}
}

Filmstrip.prototype.appendStripFrame = function(linkData){
	var idx = this.containerNode.childNodes ? this.containerNode.childNodes.length : 0;
	var frameElem = document.createElement('div');
		
	frameElem.item_id = linkData.item_id;
	frameElem.item_link = linkData.link;
	frameElem.item_title = linkData.title;
	frameElem.filmstrip = this;
	frameElem.className = "stripFrame";
	frameElem.id = this.containerNode.id + "_" + this.containerNode.id + idx;
	
	faviconImg = document.createElement('img');
	with(faviconImg){
		src = linkData.image;
		alt = linkData.title;
		title = linkData.title;
		style.width = 16;
		style.height = 16;
		style.marginRight = this.faviconSpacing;
		style.align = "top";
	}
	addEvent(faviconImg, "click", onFaviconClick, false);
	frameElem.appendChild(faviconImg);

	var titleSpan = document.createElement('span')
	with(titleSpan){
		innerHTML = '<a title="'+ linkData.link +'" title="'+ linkData.link +'" href="'+ linkData.link +'">' + linkData.title + '</a>';
		style.align = "top";
		style.display = "none";	
		// style.marginRight = 10;
	}
	
	frameElem.appendChild(titleSpan);
		
	this.containerNode.appendChild(frameElem);
	
	return idx;
}

Filmstrip.prototype.deleteSelectedFrame = function(){
	var idx = this.getSelectedFrameIdx();
	new Effect.Highlight(gFilmstrip.getFrameNode(idx));
	new Ajax.Request('/profile/remove_from_set/' + this.getSelectedItemId(), {asynchronous:true, evalScripts:true, onComplete:function(request){gFilmstrip._deleteFrame(gFilmstrip.getFrameNode(idx))}, onLoading:function(request){}});
	return false;
}

Filmstrip.prototype.deleteFrame = function(idx){
	if(this.containerNode.childNodes.length < 1)
		return;
		
	new Effect.Highlight(this.getFrameNode(idx), { afterFinish: function(effect){ effect.element.parentNode.filmstrip._deleteFrame(effect.element);}});
}

Filmstrip.prototype._deleteFrame = function(frameNode){
	var selectedFrameIdx = this.getFrameIdx(this.selectedFrameNode);
	this.setCaption("");
	this.containerNode.removeChild(frameNode);
	selectedFrameIdx = selectedFrameIdx >= this.containerNode.childNodes.length ? 0 : selectedFrameIdx;
	this.selectedFrameNode = null;
	this.selectFrame(selectedFrameIdx);
}

Filmstrip.prototype.getFrameIdx = function(frameNode){
	var frameNodes = this.containerNode.childNodes;
			
	for(var i = 0; i < frameNodes.length; i++){
		if(frameNodes[i] == frameNode)
			return i;
	}
	
	return -1;
}

Filmstrip.prototype.getFrameNode = function(idx){	
	if(idx < 0 || idx >= this.containerNode.childNodes.length)
		return null;
		
	return this.containerNode.childNodes[idx];
}


Filmstrip.prototype.getFrameTitleNode =  function(idx){
	var frameNode = this.getFrameNode(idx)
	return frameNode ? frameNode.childNodes[1] : null
}


Filmstrip.prototype.selectFrame = function(id, jump)
{	
	var selectedFrameIdx = this.getFrameIdx(this.selectedFrameNode);
	
	if(selectedFrameIdx == id || id < 0 || id >= this.containerNode.childNodes.length)
		return;
		
	var containerWidth = windowWidth();
	var currentLeft = findPosX(this.containerNode);
	var newLeft = this.calcNewLeftPos(id);
	
	if(!jump)
		new Effect.MoveBy(this.containerNode, 0, newLeft - currentLeft)
	
	if(selectedFrameIdx >= 0){
		this.getFrameTitleNode(selectedFrameIdx).style.display = 'none';
		this.getFrameNode(selectedFrameIdx).style.width = '';
	}
	
	this.getFrameTitleNode(id).style.display = '';
	
	var frameNode = this.getFrameNode(id);
	frameNode.style.width = this.selectedFrameWidth;
	this.setCaption(frameNode.item_link);
	this.selectedFrameNode = frameNode;
	setCookie('lasti', id, new Date(2020, 12, 31));

	MicrositeWithTimer();
	
	if(jump)
		this.resize();
	return id;
}

Filmstrip.prototype.setCaption = function(link){
	if(link.length == 0)
		$('stripCaption').innerHTML = "&nbsp;"	
	else if(this.mutable)
		$('stripCaption').innerHTML = '<a id="trash-link" href="#" alt="Remove ' + link + ' from your Shuffle" title="Remove ' + link + ' from your Shuffle" onclick="gFilmstrip.deleteSelectedFrame();" style="vertical-align:bottom;"><img src="/images/trash.gif" width="10" height="11" border="0" /> Remove this link from your Shuffle</a>';	
	else 
		$('stripCaption').innerHTML = '&nbsp;';
	
}

Filmstrip.prototype.forwardFrame = function(){
	this.selectFrame((this.getFrameIdx(this.selectedFrameNode) + 1) % this.containerNode.childNodes.length);
	return this.selectedFrameIdx;
}

Filmstrip.prototype.backwardFrame = function(){
	var nFrames = this.containerNode.childNodes.length;
	this.selectFrame((this.getFrameIdx(this.selectedFrameNode) + nFrames - 1) % nFrames);
	return this.selectedFrameIdx;
}

Filmstrip.prototype.getSelectedLink = function(){
	return this.selectedFrameNode ? this.selectedFrameNode.item_link : null;
}

Filmstrip.prototype.getSelectedItemId = function(){
	return this.selectedFrameNode ? this.selectedFrameNode.item_id : null;
}

Filmstrip.prototype.getSelectedFrameIdx = function(){
	return this.getFrameIdx(this.selectedFrameNode);	
}

Filmstrip.prototype.getFrameDetailNode = function(idx){
	return idx >= 0 && idx < this.containerNode.childNodes.length ? this.containerNode.childNodes[idx].detailNode : null	
}

function findPosX(obj)
{    var curleft = 0;
    if (obj.offsetParent)
    {    while (obj.offsetParent)
        {    curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
    {    curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj)
{    var curtop = 0;
    if (obj.offsetParent)
    {    while (obj.offsetParent)
        {    curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
    {    curtop += obj.y;
    }
    return curtop;
}
