/**
 * @author EvgeniyV
 */
 
 
 /*
 Constructor  of movies panel, that allows to present data 
 
 *top,left - position of panel
 *width,heigth - size of movie item
 *dataLoadCallback - function that loads data
 
 */
MoviesPanel = function (top, left, width, height, perPage, dataLoadCallback, panelId, indexChangedCallBack, pageLoadedCallback, maxDescLength, series, maxNameLength, opts, showDate)
{
    this.otherOptions = opts || null;
    this.notMovies = this.otherOptions != null;

    /*
    Function that loads data
    */  
    this.dataLoadCallback = dataLoadCallback;
    /*
    Function that run when page loaded
    */
    this.pageLoadedCallback = pageLoadedCallback;
    /*
    Function that called when index is changed
    */
    this.indexChangedCallBack = indexChangedCallBack;
    /*
    Stores html of created panel
    */
    this.panel = "";

    this.movieTableId = panelId;
    this.width = width;
    this.height = height;
    this.top = top;
    this.left = left;
    this.maxDescriptionLength = maxDescLength || 150;
    this.maxNameLength = maxNameLength || 40;
    this.series = series;
	this.showDate = showDate;

    /*
    Stores data about movies
    */
    this.movies = [];

    /*
    Count of data in panel
    */
    this.dataCount = 0;

    this.itemPrefix = "movie";
    /*
    Index of current page
    */
    this.currentPage = 0;

    /*
    Number of movies per page
    */
    this.moviesPerPage = perPage;   

    /*
    Number of stored pages
    */
    this.pagesNum = 0;

    /*
    Index of current movie
    */
    this.index = -1;

    /*
    Font size of items-movies
    */
    this.fontSize = 15;

    /*
    Size of big and small images of movie
    */
    this.imgWidth = "50";
    this.imgHeight = "70";
    this.imgLWidth = "60";
    this.imgLHeight = "80";

    /*
    Stores value about last data get from web service, if no data was received equals false
    */
    this.lastDataGetSuccess = true;

    /*
    Is all data getting or using partial loading of data
    */
    this.isAllDataGetted = true;

    this.cellspacing = 0;
    this.cellpadding = 0;

    this.runDataCallback = function(){
		this.dataLoadCallback();
    }
    /*
    sets data array
    */
    this.clear = function()
    {
		this.movies = [];
		this.dataCount = 0;
		this.pagesNum = 0;
		this.loadPage();
    }

    this.unload = function()
    {
        this.movies.length = 0;
        this.movies = null;
        this.dataCount = null;
        this.pagesNum = null;
        this.moviesPerPage = null;
        this.panel = null;
        $("#"+this.movieTableId).empty();
        this.movieTableId = null;
    }

    /*
    sets data array
    */
    this.setMovies = function(movies)
    {
		this.movies = movies;
		this.dataCount = movies.length;
		this.pagesNum = Math.ceil(this.dataCount / this.moviesPerPage);
    }
    /**/
    this.setIndex = function(index) {
		this.index = index;
		this.indexChangedCallBack();
    }
    /*
    Delete movie from data array
    */
    this.deleteArrayItem = function(index)
    {               
		this.movies.splice(index, 1);
		this.dataCount--;
		if(((index + 1) % this.moviesPerPage) == 1)
		{       
			if(index != 0)
			{
				this.currentPage--;
			}
		}
		this.loadPage();
		this.pagesNum = Math.ceil(this.dataCount / this.moviesPerPage); 
		if(index != this.dataCount)
		{
			this.focusItem(index);
		}
		else
		{
			this.focusItem(index - 1);
			this.index--;
		}
		this.displayCounter();
            //this.displayScrollers();
    }
    
     /*
     * Returns true if last item focused
     */
     this.isLastItem = function(){     
        return this.index == (this.movies.length - 1);
     }
     
    /*
    Adds data from web service's response to data array
    */
    this.addData = function(movData, description) {
		Logger.write("Movies before: " + this.movies.length, "MoviesPanel", true);
		Logger.write("MovData: " + movData.length, "MoviesPanel", true);
		this.movies = this.movies.concat(movData);
		Logger.write("Movies after: " + this.movies.length, "MoviesPanel", true);
		
		this.setMovies(this.movies);
		this.loadPage();
		var numPages = Math.ceil(this.movies.length / this.moviesPerPage);
		if (this.paging) {
			numPages = Math.ceil(this.paging.totalItems / this.moviesPerPage);
		}
		this.focusNext();
		if (numPages > 1)
		{
			Logger.write("pages=" + numPages.toString(), "MoviesPanel");
			$("#"+this.movieTableId + "scrollContainer").empty();
			$("#"+this.movieTableId + "scrollContainer").append("<div id='" + this.movieTableId + "scroll' style='height:" + 60 * (this.moviesPerPage + 1).toString() + "px'></div>");
			$("#"+this.movieTableId + "scroll").sfScroll({page: numPages});
			$("#"+this.movieTableId + "scroll").css({'visibility':'visible'});
		}
		else
		{
			$("#"+this.movieTableId + "scroll").css({'visibility':'hidden'});
		}
          //  Logger.write("html after sf="+$("#"+this.movieTableId+"scroll").parent().html(), "MoviesPanel");
    }
    
    /*
    loads data from web service's response
    */
    this.loadData = function(movData, description, count) {
		this.clear();
		this.genreCount = count || 0;       
		this.movies = movData;
		this.setMovies(this.movies);
		this.currentPage = 0;
		this.index = 0;
		this.loadPage();
		var numPages = Math.ceil(movData.length / this.moviesPerPage);
		if (this.paging) {
			numPages = Math.ceil(this.paging.totalItems / this.moviesPerPage);
		}

		if (numPages>1)
		{
			$("#"+this.movieTableId+"scrollContainer").empty();
			$("#"+this.movieTableId+"scrollContainer").append("<div class='moviesPanelScroll' id='"+this.movieTableId+"scroll' style='height:"+60*(this.moviesPerPage+1).toString()+"px'></div>");
			$("#"+this.movieTableId+"scroll").sfScroll({page: numPages});         
			$("#"+this.movieTableId+"scroll").css({'visibility':'visible'});
		}
		else
		{
			$("#"+this.movieTableId+"scroll").css({'visibility':'hidden'});
		}
    }
    
    /*
    loads panel's data
    */
    this.loadPanelData = function(items) {
		this.clear();
		this.setMovies(items);
		this.currentPage = 0;
		this.index = 0;
		this.loadPage();
		var numPages = Math.ceil(items.length / this.moviesPerPage);
		if (this.paging) {
			numPages = Math.ceil(this.paging.totalItems / this.moviesPerPage);
		}
		if (numPages > 1)
		{              
			$("#"+this.movieTableId+"scrollContainer").empty();
			$("#"+this.movieTableId+"scrollContainer").append("<div id='"+this.movieTableId+"scroll' style='height:"+60*(this.moviesPerPage+1).toString()+"px'></div>");
			$("#"+this.movieTableId+"scroll").sfScroll({page: numPages});         
			$("#"+this.movieTableId+"scroll").css({'visibility':'visible'});
		}                
		else
		{
			$("#"+this.movieTableId+"scroll").css({'visibility':'hidden'});
		}
    }

    /*
    loads current page from data array
    */
    this.loadPage = function () {              
		var tmpHtml = "";
		var forEnd = 0;
		if (this.dataCount > 0)
		{                                         
			if ((this.currentPage + 1) == this.pagesNum) {
				forEnd = this.dataCount;
			} else {
				forEnd = (this.currentPage + 1) * this.moviesPerPage;
			}                
			for (var i = this.currentPage * this.moviesPerPage; i < forEnd; i++) {
				if (this.notMovies) {
					var tmpId = this.movieTableId+i.toString();
					tmpHtml += "<div class='panelRow'  id='" + tmpId + "'>";
					tmpHtml += "<div class='panelCover'><img src='"+ this.movies[i].imgSrc+"'  width='"+this.movies[i].imgWidth+"' height='"+this.movies[i].imgHeight+"' /></div>"                                    
					tmpHtml += "<p>" + this.movies[i].description + "</p>";
					tmpHtml += "</div>";
				} else {
					var tmpId = this.movieTableId+i.toString();
					tmpHtml += "<div class='movieRow'  id='" + tmpId + "'>";
					if (!this.series) {
						var imgSrc = AppContext.ImageUrlTemplate.replace("{0}", this.movies[i].id).replace("{1}", 1).replace("{2}", 1) + "&width=45";
						if ((this.movies[i].contentGenres.indexOf(137) > -1 || this.movies[i].contentGenres.indexOf(138) > -1) 
							&& !AppContext.isAdultPasswordEntered()) {
							imgSrc = "./images/xxx_dummy_img.jpg";
						}
						tmpHtml += "<div class='movieCover'><img src='" + imgSrc + "' width='45px' height='66px' /></div>"
					}
					var name = this.movies[i].name;
					var name = name.length > this.maxNameLength ? name.substring(0, this.maxNameLength - 3) + "..." : name;
					tmpHtml += "<div class='movieTitle'><h1 style ='width:" + (width - 22).toString() + "px'>" + name + "</h1>";
					if (this.showDate) {
						tmpHtml += "<div style='color:#72c6f8;display:inline-block;line-height:20px;font-size:16pt;'>&nbsp;&nbsp;(" + DateHelper.getArchPlusDate(this.movies[i].item_date) + ")</div>";
					}
					var hasSeries = this.movies[i].isContainer && this.movies[i].episodeNum === 1 || this.movies[i].episodeNum > 1;
					if (hasSeries) {
						tmpHtml += "<div class='movieSeriesImg'><img class='seriesImg' /></div>";
					}
					var description = this.movies[i].description;
					description = !!description ? description : "";
					description = description.length > this.maxDescriptionLength 
						? description.substring(0, this.maxDescriptionLength) + "..." 
						: description;
					tmpHtml += "</div><p>" + Helpers.decodeHtml(description) + "</p>";
					tmpHtml += "</div>";
				}
			}
			
			var currentPage = this.currentPage;
			if (this.paging) {
				currentPage = Math.ceil((this.index + 1) / this.moviesPerPage) - 1;
			}
			$("#"+this.movieTableId+"scroll").sfScroll('move',this.currentPage);
			$("#"+this.movieTableId+"scroll").show();
		} else {
			$("#"+this.movieTableId+"scroll").hide();
		}
		$("#"+this.movieTableId).empty();
		$("#"+this.movieTableId).append(tmpHtml);
		
		
		$(".seriesImg").sfImage({src:"images/series_icon.png"});
		if (this.pageLoadedCallback) {
			this.pageLoadedCallback();
		}    
		this.displayCounter();
    }
    
    /*
    Displays counter for movies
    */
    this.displayCounter = function() {
        if (this.notMovies)
            return;
            
        var count = this.movies.length;
		
		if (count > 0) {
			var index = this.index;
			if (this.paging) {
				index = this.index;
				count = this.paging.totalItems;
			}
			widgetAPI.putInnerHTML(document.getElementById("MoviesCounter"+this.movieTableId), (index+1).toString()+"  |  "+ count.toString());
			$("#MoviesCounter" + this.movieTableId).show();
		} else {
			$("#MoviesCounter" + this.movieTableId).hide();
		}
    }
    /*
    Hides counter for movies
    */
    this.hideCounter = function(){    
        if (this.notMovies)
            return;
    
        widgetAPI.putInnerHTML(document.getElementById("MoviesCounter"+this.movieTableId), "");
    }

    /*
    Creates table to display data
    */
    this.createTable = function()
    {    
		tmpHtml = "";
		tmpHtml += "<div id='"+this.movieTableId+"'   width='"+this.width+"'  style='position:absolute; left:"+this.left+"px; top:"+this.top+"px;'  class='movieList'></div>"
		if (!this.notMovies)
		{
			tmpHtml += "<div class='movieCounter' style='position:absolute;left:"+(this.left).toString()+"px;top:"+(this.top+60*(this.moviesPerPage+1)).toString()+"px' id ='MoviesCounter"+this.movieTableId+"' ></div>";    
		}
		tmpHtml += "<div id='"+this.movieTableId+"scrollContainer' style='position:absolute; left:"+(this.left+this.width).toString()+"px; top:"+this.top+"px;height:"+60*(this.moviesPerPage+1).toString()+"px'><div id='"+this.movieTableId+"scroll' style='height:"+60*(this.moviesPerPage+1).toString()+"px'></div></div>";
		this.panel = tmpHtml;
    }       
    
    /*
    Sets focus of current item by it's index
    */
    this.focusItem = function(index)
    {
		try
		{
			if (this.notMovies)
			{
				 $("#"+this.movieTableId+index.toString()).addClass(this.otherOptions.focusedItemClassName);                    
			}
			else
			{
				$("#"+this.movieTableId+index.toString()).css({"backgroundColor":"#11476b"});
				$("#"+this.movieTableId+index.toString() + " p").css({"color":"#fff"});
			}
			this.displayCounter();
		}
		catch (err)
		{
			Logger.write("------"+err, "MoviesPanel");
		}
    }
    /*
    Sets blur to current item by it's index 
    */
    this.blurItem = function(index)
    {       
		try
		{
			if (this.notMovies)
			{
				$("#"+this.movieTableId+index.toString()).removeClass(this.otherOptions.focusedItemClassName);                    
			}
			else
			{
				$("#"+this.movieTableId+index.toString()).css({"backgroundColor":"transparent"});
				$("#"+this.movieTableId+index.toString() + " p").css({"color":"#72c6f8"});
			}
			//this.hideCounter();
		}
		catch(err)
		{
			Logger.write("------"+err, "MoviesPanel");
		}
    }

    this.focus = function(){
            this.focusItem(this.index);
    }

    this.blur = function() {
		this.blurItem(this.index);
    }

	/**
		Focuses element with specified index
		*index - index of element
	*/
	this.focusElement = function (number) {
		Logger.write("Focusing element: " + number, "MoviesPanel", true);
		var index = parseInt(number) - 1;
		if (index >= this.dataCount) {
			return;
		}
		
		this.currentPage = Math.floor(index / this.moviesPerPage);
		this.setIndex(index);
		this.loadPage();
		this.focusItem(this.index);
	}
	
    /*
    Focuses next movie-item
    */
    this.focusNext = function()
    {
		if (this.dataCount > 0)
		{
			// for circular navigation
			if (this.series === true && (this.index + 1) == this.dataCount)
			{
				this.currentPage = 0;
				this.setIndex(0);
				this.loadPage();
				this.focusItem(this.index);
				return;
			}
			
			if ((this.index + 1) < this.dataCount)
			{
				//if last element of page
				if(this.index == ((this.currentPage + 1) * this.moviesPerPage - 1))
				{
					this.currentPage++;
					this.loadPage();
				}
				this.setIndex(this.index + 1);   
				//if not last element of page
				if((this.index != 0) && ((this.index % this.moviesPerPage) != 0))
				{
					this.blurItem(this.index - 1);
				}
				this.focusItem(this.index);
			}
			else
			{
				if (!this.isAllDataGetted)
				{
					this.currentPage++;
					this.runDataCallback();
				}
			}
		}
    }
    /*
    Focuses previous movie-item
    */
    this.focusPrev = function()
    {     
		if(this.dataCount > 0)
		{
		
			this.CheckGetDataResult();
			if(/*(this.index != 0) && */(this.index != -1))
			{
				Logger.write("Series: " + this.series + "; Index: " + this.index, "MoviesPanel", true);
				if (this.series === true && this.index == 0)
				{
					this.currentPage = Math.ceil(this.dataCount/this.moviesPerPage) - 1;
					this.setIndex(this.dataCount - 1);
					this.loadPage();
					this.focusItem(this.index);
					return;
				}
			
				//if first element of page
				if (this.index == (this.currentPage * this.moviesPerPage))
				{
					this.currentPage--;
					this.loadPage();
				}
				//if not first element of page
				if(((this.index + 1) % this.moviesPerPage) != 1)
				{  
					this.blurItem(this.index);
				}
				this.setIndex(this.index - 1);
				this.focusItem(this.index);
				 
				Logger.write(this.index, "MoviesPanel");
			}
		}
    }
    /*
    Checks if data of next page was not received from web service and than
    sets current page index to last stored page
    */
    this.CheckGetDataResult = function() {
		if(!this.lastDataGetSuccess)
		{
			Logger.write("SETTING CURRENT PAGE TO NUMBER OF PAGES ", "MoviesPanel");
			this.currentPage = this.pagesNum - 1;
			this.lastDataGetSuccess = true;
		}
    }
	
	this.getCurrentMovie = function () {
		if (!this.movies || !this.movies.length || (!this.index && this.index !== 0)) {
			return;
		}
		
		return this.movies[this.index];
	}
	
	this.sortMovies = function (fieldName, isAscending) {
		Logger.write("Sorting movies by '" + fieldName + "'", "MoviesPanel", true);
		this.setMovies(Helpers.sortByField(this.movies, fieldName, isAscending));
		this.loadPage();
	}

    this.createTable();

}