﻿/**
 * objet that hold a news media and its informations, initialize itemId field
 * @param itemId
 * @return
 */
function MediaItem( itemId )
{
	this._itemId = itemId;
	this._source = null;
	this._type = null;
	this._title = null;
	this._description = null;
	this._fileSize = null;
	this._thumbnail = null;
	this._container = null;
	this._class = null;
	this._picture = null;
	this._width = null;
	this._height = null;
	this._centered = null;
	this._onclickresize = true;
	
	this.NO_MEDIA = 0;
	this.MEDIA_OK = 1;
	this.NO_ITEM = 2;
}	

/**
 * initialize item informations
 * @param source
 * @param type
 * @param title
 * @param description
 * @param fileSize
 * @param thumbnailSource
 * @return
 */
MediaItem.prototype.setItemValues = function (source, type, title, description, fileSize, thumbnailSource)
{
	this._source = source;
	this._type = type;
	this._title = title;
	this._description = description;
	this._fileSize = fileSize;
	this._thumbnail = thumbnailSource;
};

MediaItem.prototype.getCentered = function()
{
	return (this._centered);
};

/**
 * return id
 * @return
 */
MediaItem.prototype.getId = function()
{
	return (this._itemId);
};

/**
 * return source url
 * @return
 */
MediaItem.prototype.getSource = function()
{
	return (this._source);
};

/**
 * return media type
 * @return
 */
MediaItem.prototype.getType = function()
{
	return (this._type);
};

/**
 * return media title
 * @return
 */
MediaItem.prototype.getTitle = function()
{
	return (this._title);
};

/**
 * return media description
 * @return
 */
MediaItem.prototype.getDescription = function()
{
	return (this._description);
};

/**
 * return media file size
 * @return
 */
MediaItem.prototype.getFileSize = function()
{
	return (this._fileSize);
};

/**
 * return thumbnail url
 * @return
 */
MediaItem.prototype.getThumbnail = function()
{
	return (this._thumbnail);
};

/**
 *  ajax request asking for a particular item
 * @param callbackFunction
 * @return
 */
MediaItem.prototype.getItemFromServer = function( callbackFunction )
{
	var url = "index.php?controller=News&action=getItem&itemId=" + this.getId() + "&view=no";
	var xhr = this.getXMLHttpRequest();
	//save reference on this object to use in the call back function
	var item = this;
	xhr.open("GET", url, false);
	xhr.send(null);
	if (xhr.readyState == 4 && xhr.responseXML)
	{
		return (xhr.responseXML);
	}
	return (null);
};

/**
 *  * (re)implementation of the DOM function
 * because it does not exist in Internet Explorer 
 * and Opera Netscape and safari need namespace for composed tag
 * i.e. <atom:id>
 * @param namespace
 * @param tagname
 * @param node
 * @return
 */
MediaItem.prototype.getElementsByTagNameNS = function(namespace, tagname, node)
{
	if (node == null)
		return(null);
	if (node && node.getElementsByTagNameNS)
		return(node.getElementsByTagNameNS(namespace, tagname));
	else
		return (this.ndGetElementByTagNameNS(namespace, tagname, node));
};

/**
 * first time call by getElementsByTagNameNS 
 * then call itself recursively on every node of type node or root
 * @param namespace
 * @param tagname
 * @param node
 * @param result
 * @param count
 * @return
 */
MediaItem.prototype.ndGetElementByTagNameNS = function(namespace, tagname, node, result, count)
{
	if (node == null)
		return(null);
	if (result == null)
	{
		result = Array();
		count = 0;
	}
	if (!node && node.nodeType != 1 && node.nodeType != 9)
	{
		return (null);
	}
	for (var i = 0; i < node.childNodes.length; i++)
	{	
		//if tag name is composed i.e. <atom:id>
		if (	node.childNodes.item(i).namespaceURI == namespace &&
				node.childNodes.item(i).tagName &&
				node.childNodes.item(i).tagName.split(':').length > 1 &&
				node.childNodes.item(i).tagName.split(':')[1] == tagname)
		{
			result[count++] = node.childNodes.item(i);
		}
		this.ndGetElementByTagNameNS(namespace, tagname, node.childNodes.item(i), result, count);
	}
	return (result);
};

/**
 * extract media's informations and initialize mediaItem object with them
 * @param xmlString
 * @return
 */
MediaItem.prototype.mapItem = function(xmlString)
{
	if (xmlString == null)
		return (null);
	var atomNS = "http://www.w3.org/2005/Atom";
	var mediaNS = "http://search.yahoo.com/mrss/";
	//alert('tagNAme' + this.getElementsByTagNameNS(mediaNS, "content", xmlString)[0].tagName);
	if (! (this.getElementsByTagNameNS(atomNS, "id", xmlString).length > 0) )
		return (this.NO_ITEM);
	if (! (this.getElementsByTagNameNS(mediaNS, "content", xmlString).length > 0) )
		return (this.NO_MEDIA);
	var pictureIndex = this._picture == null ? 0 : this._picture;
	var contentTag = this.getElementsByTagNameNS(mediaNS, "content", xmlString)[pictureIndex];
	var source = contentTag.getAttribute("url");
	//force type for windows plateform to open windows media player instead of quicktime
	if (	contentTag.getAttribute("type").indexOf("audio") != -1 &&
			navigator.platform.toLowerCase().indexOf("win") != -1)
		var type = "application/x-mplayer2";
	else
		var type = contentTag.getAttribute("type");
	var fileSize = contentTag.getAttribute("fileSize");
	var	title = this.getElementsByTagNameNS(mediaNS, "title", xmlString)[0].nodeValue;
	var	description = this.getElementsByTagNameNS(mediaNS, "description", xmlString)[0].nodeValue;
	var	thumbnail = this.getElementsByTagNameNS(mediaNS, "thumbnail", xmlString).nodeValue;
	this.setItemValues(source, type, title, description, fileSize, thumbnail);
	return (this.MEDIA_OK);
};

/**
 * interface function to get an item
 * initialize class name to use and container where to put the loaded item
 * @param containerId
 * @param className
 * @param picture
 * @param centered
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.getItem = function(containerId, className, picture, centered, width, height, onclickresize)
{	
	if (this.getId() == -1)
		return (false);
	this._container = document.getElementById(containerId);
	//item already loaded ?
	if (this._container && 
		(this._container.getElementsByTagName("object").length > 0 ||
		 this._container.getElementsByTagName("img").length > 0 ))
	{
		return;
		//ndNews.clearContainer(this._container);
	}
	if(!centered)
		this._centered = false;
	else
		this._centered = true;
	this._class = className;
	if (picture != null)
		this._picture = picture;
	if (width != null && height != null)
	{
		this._width = width;
		this._height = height;
	}
	this._onclickresize = onclickresize ? true : false;
	this.load(this.getItemFromServer());
};

/**
 * check return value of mapItem
 * @param xmlString
 * @return
 */
MediaItem.prototype.load = function(xmlString)
{
	switch (this.mapItem(xmlString))
	{
		case this.NO_ITEM: 
			alert('could not load media\n');
			return (false);
		case this.NO_MEDIA:
			return (false);
		case this.MEDIA_OK:
			this.helperMediaElement(this._width, this._height);
			return (true);
		default:
			break;
	}
	return (false);
};

/**
 * 
 * @param item
 * @param image
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.helperImageResize = function(item, image, width, height)
{
	//alert('trying to resize: image width: ' + image.clientWidth + " height: " + image.clientHeight + "  asked width: " + width + " height: " + height);
	if (image.width < width && image.height < height)
	{
		//alert("debug : to small!");
		return (false);
	}
	var imageSize = ndNewsUI.computeOptimalListImageSize(image, width, height);
	if (imageSize != null)
	{
		image.height = imageSize.height;
		image.width = imageSize.width;
		if (item.getCentered())
			MediaItem.center(item._container, image, "both");
	}
	else
	{
		image.height = height;
		image.width = width;
	}
	//alert('resized');
	this._container.style.backgroundImage = "none";
	image.style.visibility = "visible";
	return (true);
},

/**
 * insert the media html node into the document
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.helperMediaElement = function(width, height)
{
	var container = this._container;
	//create the media container for easier style
	var playerDiv = document.createElement("div");
	$(playerDiv).attr("id", "ndNewsPlayerContainer" + this.getId());
	$(playerDiv).attr("class", this._class);
	playerDiv.closePlayer = function(){container.removeChild(this);};
	container.appendChild(playerDiv);
	//the media is an image
	if (this.getType().indexOf("image") != -1)
	{
		var imageElement = this.helperImageElement(width, height);
		if (imageElement == null)
			return (false);
		//insertion in the document
		playerDiv.appendChild(imageElement);
		this.helperSizeImageElement(imageElement, width, height);
		//this.helperImageResize(this, imageElement, width, height);
	}
	else
	{
		var objectElement = this.helperObjectElement(width, height);
		if (objectElement == null)
			return (false);
		//insertion in the document
		playerDiv.appendChild(objectElement);
		objectElement.style.visibility = "visible";
	}
	return (true);
};

/**
 * 
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.helperImageElement = function()
{
	var image  = document.createElement("img");
	image.style.visibility = "hidden";
	//image.id = 'image'+this.getId();
	var srcAtt = document.createAttribute("src");
	srcAtt.nodeValue = this.getSource();
	image.setAttributeNode(srcAtt);
	var classAtt = document.createAttribute("class");
	classAtt.nodeValue = this._class;
	image.setAttributeNode(classAtt);
	var altAtt = document.createAttribute("alt");
	if(this.getTitle() && this.getTitle().length > 0)
		altAtt.nodeValue = this.getTitle();
	else
		altAtt.nodeValue = this.getDescription();
	image.setAttributeNode(altAtt);
	return (image);
};

/**
 * 
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.helperSizeImageElement = function(image, width, height)
{
	//inner function call when image is loaded to resize the image
	var item = this;
	$(image).load(function(){window.setTimeout(function(){item.helperImageResize(item, image, width, height);}, 1000);});
	//resize img on click if possible
	if (this._onclickresize && MediaItem.ImageCanBeDisplay(image, width, height))
	{
		image.style.cursor = "pointer";
		$(image).click(function(){MediaItem.switchToFullscreen(this);});
	}
};

/**
 * 
 * @param width
 * @param height
 * @return
 */
MediaItem.prototype.helperObjectElement = function(width, height)
{
	var objectElement = document.createElement("object");
	//child params
	var param = document.createElement("param");
	param.setAttribute("name", "filename");
	param.setAttribute("value", this.getSource());
	objectElement.appendChild(param);
	param = document.createElement("param");
	param.setAttribute("name", "autoplay");
	param.setAttribute("value", "false");
	objectElement.appendChild(param);
	param = document.createElement("param");
	param.setAttribute("name", "type");
	param.setAttribute("value", this.getType());
	objectElement.appendChild(param);
	//tag object attribute
	var classAtt = document.createAttribute("class");
	classAtt.nodeValue = this._class;
	objectElement.setAttributeNode(classAtt);
	var heightAtt = document.createAttribute("height");
	heightAtt.nodeValue = height;
	objectElement.setAttributeNode(heightAtt);
	var widthtAtt = document.createAttribute("width");
	widthtAtt.nodeValue = width;
	objectElement.setAttributeNode(widthtAtt);
	var dataAtt = document.createAttribute("data");
	dataAtt.nodeValue = this.getSource();
	objectElement.setAttributeNode(dataAtt);
	var typeAtt = document.createAttribute("type");
	typeAtt.nodeValue = this.getType();
	objectElement.setAttributeNode(typeAtt);
	return (objectElement);
};

/**
 * return the XMLHttpRequest use to query the server
 * @return
 */
MediaItem.prototype.getXMLHttpRequest = function()
{
	var xhr = null;
	
	if (window.XMLHttpRequest || window.ActiveXObject) {
		if (window.ActiveXObject) {
			try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		} else {
			xhr = new XMLHttpRequest(); 
		}
	} else {
		alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
		return null;
	}
	return xhr;
};

/**
 * 
 * @param objectElement
 * @param maxwidth
 * @param maxheight
 * @return
 */
MediaItem.computeOptimalListObjectSize = function(objectElement, maxwidth, maxheight)
{
	if (objectElement == null)
		return null;
	var imageSize = 
	{
			height: null,
			width: null
	};
	imageSize.height = (maxheight * 80) / 100;
	imageSize.width = (maxwidth * 90) / 100;
	return (imageSize);
};

/**
 * 
 * @param objectElement
 * @param containerId
 * @return
 */
MediaItem.resizeObject = function(objectElement, containerId)
{
	if (objectElement == null)
		return null;
	var container = document.getElementById(containerId);
	objectElement.height = container.clientHeight;
	objectElement.width = container.clientWidth;
	return;
};

/**
 * compute image final size to fit fullscreen container
 * the height is fixed by parameter size (to be sure that media will not be heigher than available screen)
 * and the width is compute according to the image ratio
 * @param imageElement
 * @return
 */
MediaItem.computeFullScreenImageOptimalSize = function (imageElement)
{
	var container = document.getElementById("container");
	return (ndNewsUI.computeOptimalListImageSize(imageElement, container.clientWidth, container.clientHeight - imageElement.clientHeight));
};

/**
 * compute image final size to fit fullscreen container
 * the height is fixed by parameter size (to be sure that media will not be heigher than available screen)
 * and the width is compute according to the image ratio
 * @param objectElement
 * @param containerId
 * @return
 */
MediaItem.computeFullScreenObjectOptimalSize = function (objectElement, containerId)
{
	var container = document.getElementById("container");
	return (MediaItem.computeOptimalListObjectSize(objectElement, ndNewsUtils.windowSize().width, ndNewsUtils.windowSize().height));
};

/**
 * 
 * @param image
 * @return
 */
MediaItem.ImageCanBeDisplay = function(image, minwidth, minheight)
{
	var height = $(image).height() ? $(image).height() : image.height;
	var width = $(image).width() ? $(image).width() : image.width;
	if (minwidth == 0 && height > minheight)
		return (true);
	if (minheight == 0 && width > minwidth)
		return (true);
	if (height > minheight &&
			width > minwidth)
		return (true);
	return (false);
},

/**
 * get the medie element element from its container and put it in the fullscreen container,
 * save its state and change its attributes and size
 * @param objectElement
 * @return
 */
MediaItem.switchToFullscreen = function(objectElement)
{
	if (document.getElementById("ndNewsVideoPlayerFullscreenContainer") != null || objectElement == null)
		return;
	$(window).resize(MediaItem.resize);
	//////////////////////////
	//move media object to foreground
	var container = document.getElementsByTagName("body")[0];
	var playerDiv = document.createElement("div");
	var backgroundDiv = document.createElement("div");
	var closeButton = document.createElement("button");
	////gestion du click sur la balise div en arriere plan
	$(backgroundDiv).click(function(e){MediaItem.removeFullscreenContainer(objectElement);if($("#ndNewsArticleViewer-" + objectElement.id.split("-")[1]).length > 0) location.hash = '#article-'+objectElement.id.split("-")[1];});
	$(closeButton).click(function(e){MediaItem.removeFullscreenContainer(objectElement); if($("#ndNewsArticleViewer-" + objectElement.id.split("-")[1]).length > 0) location.hash = '#article-'+objectElement.id.split("-")[1];});
	//nom et style des div
	$(playerDiv).attr("id", "ndNewsMediaPlayerFullscreenContainer");
	$(playerDiv).attr("class", "fullscreenContainer");
	$(closeButton).attr("class", "closeBtn");
	$(backgroundDiv).attr("id", "ndNewsVideoPlayerBackground");
	$(backgroundDiv).attr("class", "fullscreenContainerBackground");
	
	playerDiv.appendChild(backgroundDiv);
	playerDiv.appendChild(closeButton);
	container.appendChild(playerDiv);
	playerDiv.style.position = "fixed";
	//backgroundDiv.style.width = ndNewsUtils.windowSize().width + "px";
	if (ndNewsUtils.windowSize().height < document.getElementsByTagName('body')[0].clientHeight)
		backgroundDiv.style.height = document.getElementsByTagName('body')[0].clientHeight + "px";
	else 
		backgroundDiv.style.height = ndNewsUtils.windowSize().height + "px";
	$(objectElement).hide();
	//////////////////////////
	// Compute image size for fullscreen
	if (objectElement.tagName.toLowerCase() == "img")
	{
		var image = document.createElement("img");
		$(image).attr("src", $(objectElement).attr("src"));
		$(image).attr("id", "fullscreenImage");
		$(image).css("position", "relative");
		$(image).css("display", "none");
		//$(image).css("height", "");
		//$(image).css("width", "");
		window.setTimeout(
				"MediaItem.center($('#ndNewsMediaPlayerFullscreenContainer').get(0), $('#fullscreenImage').get(0), 'both');" +
				"$('#fullscreenImage').fadeIn('slow');", 1000);
		playerDiv.appendChild(image);
	}
	else
	{
		var clone = objectElement.cloneNode(true);
		var fullscreenSize = MediaItem.computeFullScreenObjectOptimalSize(clone, "container");
		$(clone).attr("id", "fullscreenVideoPlayer");
		$(clone).css("position", "relative");
		//$(clone).css("visibility", "hidden");
		$(clone).attr("width", fullscreenSize.width + "px");
		$(clone).attr("height", fullscreenSize.height + "px");
		window.setTimeout(
				"MediaItem.center($('#ndNewsMediaPlayerFullscreenContainer').get(0), $('#fullscreenVideoPlayer').get(0), 'both');" +
				"$('#fullscreenVideoPlayer').show()",
				1000);
		playerDiv.appendChild(clone);
	}
};

/**
 * delete fullscreen container from the document
 * @return
 */
MediaItem.removeFullscreenContainer = function(objectElement)
{
	if (objectElement != null)
		$(objectElement).show();
	if (document.getElementById("ndNewsMediaPlayerFullscreenContainer") != null)
		document.getElementsByTagName("body")[0].removeChild(document.getElementById("ndNewsMediaPlayerFullscreenContainer"));
	$(window).unbind("resize", MediaItem.resize);
};

MediaItem.resizeMultipleImages = function(containerId, width, height, center, referer)
{
	var container = document.getElementById(containerId);
	if (container == null)
		return;
	var images2resize = container.getElementsByTagName("img");
	if (images2resize.length == 0)
		return;
	var parentWidth = container.parentNode.clientWidth;
	var parentHeight = container.parentNode.clientHeight;
	for (i = 0; i < images2resize.length; i++)
	{
		if (width == 0 && height == 0)
			var size = ndNewsUI.computeOptimalListImageSize(images2resize[i], parentWidth - 1, parentHeight - 1 );
		else
			var size = ndNewsUI.computeOptimalListImageSize(images2resize[i], width, height);
		if (size != null)
		{
			images2resize[i].style.height = size.height + "px";
			images2resize[i].style.width = size.width + "px";
			if (center)
			{
				if (referer == null)
					referer = container.parentNode;
				if (referer == 1)
					referer = images2resize[i].parentNode.parentNode;
				MediaItem.center(referer, images2resize[i], center);
			}
			images2resize[i].style.visibility = "visible";
		}
	}
};

/**
 * 
 * @param container
 * @param element
 * @param center
 * @return
 */
MediaItem.center = function(container, element, center, options)
{
	if (container == null || element == null)
		return;
	if (!$(container).height() || !$(container).width())
		return;
	element.style.position = "relative";
	var height = $(element).height() ? $(element).height() : this.height;
	var width = $(element).width() ? $(element).width() : this.width;
	if (options != null && options.border != null)
	{
		width 	+= 2 * options.border;
		height 	+= 2 * options.border;
	}
	if (center == "both")
		$(element).css("top", ($(container).height() - height) / 2 + "px");
	$(element).css("left", ($(container).width() - width) / 2 + "px");
	if ($(element).css("visibility") == "hidden")
		$(element).css("visibility", "visible");
};


MediaItem.resize = function()
{
	var fullscreenSize = MediaItem.computeFullScreenObjectOptimalSize($("#fullscreenVideoPlayer").get(0), "container");
	if (!fullscreenSize)
		return (false);
	$("fullscreenVideoPlayer").css("visibility", "hidden");
	$("fullscreenVideoPlayer").attr("width", fullscreenSize.width + "px");
	$("fullscreenVideoPlayer").attr("height", fullscreenSize.height + "px");
	window.setTimeout(
			"MediaItem.center($('#ndNewsVideoPlayerFullscreenContainer').get(0), $('#fullscreenVideoPlayer').get(0), 'both');" +
			"$('#fullscreenVideoPlayer').css('visibility', 'visible')",
			1000);
};

MediaItem.loadAudioItemCallback = function (carousel, state)
{
	MediaItem.loadItemCallback(carousel, state, "getNewsAudioItems");
};

MediaItem.loadImageItemCallback = function (carousel, state)
{
	var qs = new Querystring();
    var url = "index.php?controller=News&action=getNewsImageItems"
    	+ "&type=" + qs.get("type");
    if (qs.get("pipeline", null) != null)
    	url += "&pipeline=" + qs.get("pipeline");
    if (qs.get("date", null) != null)
    	url += "&date=" + qs.get("date");
    if (qs.get("search", null) != null)
    	url += "&search=" + qs.get("search");
    if (qs.get("from", null) != null)
    	url += "&from=" + qs.get("from");
    if (qs.get("to", null) != null)
    	url += "&to=" + qs.get("to");
    if (qs.get("src", null) != null)
    	url += "&src=" + qs.get("src");
    var index = 1;
    carousel.options.scroll = 1;
    var step = 5;
    var page = 0;
    var pageoffset = Number(qs.get("page", 0));
    var resPerPage = Number(qs.get("resPerPage", MediaItem.resPerPage));
    switch (state)
    {
    case "init":
	  	url += "&resPerPage=" + resPerPage + "&page=" + pageoffset;
	  	index = pageoffset * resPerPage;
	  	MediaItem.addImageInCarousel(carousel, url, index);
	  	break;
    case "next":
    	var end = carousel.last + step;
    	for (var i = carousel.last; i < end; i++)
		    if (!carousel.has(i)) 
		    {
				url += "&resPerPage=" + 1 + "&page=" + i;
				MediaItem.addImageInCarousel(carousel, url, i);
		  	}
		break;
    case "prev":
    	var start = carousel.first - step;
    	for (var i = carousel.first; i > start; i--)
		    if (i >= 0 && !carousel.has(i)) 
		    {
				url += "&resPerPage=" + 1 + "&page=" + i;
				MediaItem.addImageInCarousel(carousel, url, i);
		  	}
    	break;
    }
    
};

MediaItem.addImageInCarousel = function(carousel, url, index)
{
	if (carousel.loading == null)
	{
		carousel.loading = {};
	}
	if (carousel.loading[index] != null)
	{
		return (false);
	}
	jQuery.ajax(
		    {
				dataType: "html",
				url: url,
				success: function(data)
				{
					var ul = document.createElement("ul");
				    $(ul).html(data);
				    $(ul).find("li").each(function(i)
				    {
				       carousel.add( index + i, $(this).html());
				       $(carousel.get(index + i)).css("backgroundImage", "none");
				       $(carousel.get(index + i)).children(".contentImageThumbnail").resizeImages( {width: 600, height: 400, center: 'both', force: true, border: 10});
				    });
				    carousel.loading[index] = null;
				},
				error: function(xhr)
				{
					if (xhr.status ==  404)
					{
						carousel.size(index);
						//$(".jcarousel-"+state).attr("disabled", true);
						//$(".jcarousel-"+state).addClass("jcarousel-next-disabled jcarousel-next-disabled-horizontal");
						return (false);
					}
					ndNewsUtils.processXHR(xhr);
				}
		  	});
	carousel.loading[index] = true;
};


MediaItem.loadItemCallback = function (carousel, state, action)
{
	var qs = new Querystring();
    var url = "index.php?controller=News&action=" + action
    	+ "&type=" + qs.get("type");
    if (qs.get("pipeline", null) != null)
    	url += "&pipeline=" + qs.get("pipeline");
    if (qs.get("date", null) != null)
    	url += "&date=" + qs.get("date");
    if (qs.get("search", null) != null)
    	url += "&search=" + qs.get("search");
    if (qs.get("from", null) != null)
    	url += "&from=" + qs.get("from");
    if (qs.get("to", null) != null)
    	url += "&to=" + qs.get("to");
    if (qs.get("src", null) != null)
    	url += "&src=" + qs.get("src");
    var index = 0;
    var step = carousel.last - (carousel.first - 1);
    carousel.options.scroll = step;
    var initialstep = step * 2;
    var pageoffset = Number(qs.get("page", 0));
    var resPerPage = Number(qs.get("resPerPage", 0));
    var offset = Number(qs.get("offset", 0));
    var itemOffset = (pageoffset * resPerPage) + offset;
    var page = 0 + Math.floor(itemOffset / initialstep);
    if (state == "init")
    {
  	  url += "&resPerPage=" + initialstep + "&page=" + page;
    }
    else 
    {
    	if (carousel.has(carousel.first + step, carousel.last + step)) 
        {
           return;
      	}
    	var ratio = resPerPage / step;
    	page = Math.floor((carousel.first + step) / step) + (pageoffset * 2);
    	url += "&resPerPage=" + step + "&page=" + page;
    	index = carousel.last;
    }
    jQuery.ajax(
    {
		dataType: "html",
		url: url,
		success: function(data)
		{
			var ul = document.createElement("ul");
		    $(ul).html(data);
		    $(ul).find("li").each(function(i)
		    {
		       carousel.add( index + i, $(this).html());
		       $("#ImageViewer .contentImageThumbnail").resizeImages( {width: 600, height: 400, center: 'both', force: true});
		    });
		},
		error: function(xhr)
		{
			if (xhr.status ==  404)
			{
				carousel.options.size = index;
				$(".jcarousel-"+state).attr("disabled", true);
				$(".jcarousel-"+state).addClass("jcarousel-next-disabled jcarousel-next-disabled-vertical");
				return (false);
			}
			ndNewsUtils.processXHR(xhr);
		}
  	});
};

MediaItem.loadAudioItemInPlayer = function(item)
{
	$("#jplayer_playlist .title").html($(item).find(".title").html());
	$("#jplayer_playlist .description").html($(item).find(".description").html());
	$("#jplayer_playlist .pubdate").html($(item).find(".pubdate").html());
	$("#jplayer_playlist .feedtitle").html($(item).find(".feedtitle").html());
	$("#jplayer_playlist .feedlink").attr("href", $(item).find(".feedlink").html());
	$("#jplayer_playlist .feedlogo").replaceWith($(item).find(".feedlogo").clone());
	$("#jquery_jplayer").jPlayer("setFile",  $(item).find(".link").html()).jPlayer("play");
};

