/*  Custom function for videofront page
 *  updated: jan - '10
 *
 *--------------------------------------------------------------------------*/
 
// Global Values
var jsReady = false;
var jsReady = false;
var currentListID = new Array();
var currentListHTML = new Array();
var currentListPublish = new Array();
var categoryListID = new Array(); 
var categoryListHTML = new Array();
var categoryListPublish = new Array();
var searchListID = new Array(); 
var searchListHTML = new Array();
var searchListPublish = new Array();
var currentVideo = 0;
var listCounter = 0;
var categoryListCounter = 0; //
var searchListCounter = 0; //
var currentCategory = 1;
var fromCategory = 1;   // This is used to keep tracking each ddifferrnt category viewed, it gets lost in search from mutiple searches 
var beforeSearch = 1;   // This specifcly used to store the category you were jsut viewing before going to search
var globalCarousel;
var offList = false;
var currentTab = 0;
var searchCarousel;
var searchSize = 0;
var searchQuery = "";
var isSearch = false;
var category = new Object();

//currentVideo = currentVideo, but in the array is one ahead   Index starting at 0;

//////////////////////
function boo(){
	alert(currentListHTML[1]);
}

function boo2(id){
		alert(window['category.length'+id]);
}


 // Delay response
 Ajax.Request.prototype.originalInitialize = Ajax.Request.prototype.initialize;
 Ajax.Request.prototype.initialize = function(url, options) {
   options.onSuccess = options.onSuccess.wrap(function(proceed, request, XML) {

       proceed.curry(request, XML).delay(1);

   });
   this.originalInitialize(url, options);

 }
   // Mock JSON repsonse, to custom return
   // Gets repsonse text from the urls parsed

   Ajax.Response.prototype._getResponseJSON = function() {

       if(this.responseText.include("#!VIDEOREQUEST")) {
          return(handleVideoRequest(this.responseText,this.request.parameters.to,this.request.parameters.from));
       } else if (this.responseText.include("#!SEARCHREQUEST")){
          return(handleSearchRequest(this.responseText,this.request.parameters.to,this.request.parameters.from));
       }
  }

  Ajax.Response.prototype._getHeaderJSON = function() {
   // override to return blank
 }

 UI.Ajax.Carousel.prototype.update = function(transport, json) {

   this.requestRunning = false;
   this.fire("request:ended");
   if (!json)
     json = transport.responseJSON;
   this.hasMore = json.more;

   this.endIndex = Math.max(this.endIndex, json.to);
   this.elements = this.container.insert({bottom: json.html}).childElements();
   //checks for initial load for next up play
   isLoaded();
   return this.updateButtons();
 }

  // Returns converted Duration and XML date to correct format
  // Used patterns #N## and @D@@ to delimit values
	function convertDateAndTime(convertValue, _duration, _publish){
		_duration = _duration.split("&");
		_publish = _publish.split("&");

		for (var i= 1; i < _duration.length; i++){
			convertValue = convertValue.sub("#N##", convertTime(_duration[i]));
		}
		for (var x= 1; x < _publish.length; x++){
			convertValue = convertValue.sub("@D@@", convertXmlTime(_publish[x]));
		}


		return convertValue;
	}
	
	// Returns html with akamai urls for thumbnails
  // Since the HTML will only have scr= in <img> tag, i used that as the pattern
  // check what environement??? with tii.trb and tila.trb and check null
	function convertAkamaiUrl(convertValue){
      
		var requestHost = window.location.host;
      
		 if(akamaiUrl != "" && akamaiUrl != null && requestHost.indexOf(".tii.trb") < 0 && requestHost.indexOf(".tila.trb") < 0) {
			    convertValue = convertValue.gsub('src="http://', 'src="http://' + akamaiUrl+ '.');
			}


		return convertValue;
	}
	
// Given total # of items and amount wanted per page
// return : number of total per

function convertPerPage(total, per){
        

   	if(total % per != 0){
		total = (total / per) + 1;
	} else if (total == per)  {
		total = 1;
	} else {
	    total = total / per;
	}

	return parseInt(total);
}

function setCurrentCategory(id){
	
	//clear temp list
	categoryListHTML = [];
    categoryListID = [];
    categoryListPublish = [];
    categoryListCounter = 0;
     
    isSearch = false;
	
	
		 
	//create new category object
	if(parseInt(currentCategory) == parseInt(fromCategory)) { //create new category object

		if(window['category.list'+currentCategory] == undefined) {
		  
			//alert("new list: category.list"+currentCategory);
			window['category.html'+currentCategory] = currentListHTML;
			window['category.list'+currentCategory] = currentListID;
			window['category.publish'+currentCategory] = currentListPublish;
			window['category.length'+currentCategory] = currentListID.length;
		} else { // update category object with larger list
			if(currentListID.length > window['category.length'+currentCategory]) {
				//alert("updating category.list:"+currentCategory+"::length"+currentListID.length);
				window['category.html'+currentCategory] = currentListHTML;
				window['category.list'+currentCategory] = currentListID;
				window['category.publish'+currentCategory] = currentListPublish;
				window['category.length'+currentCategory] = currentListID.length;
			}
		
		}
	} else {
		
		if(window['category.list'+id] == undefined) {
		
			//alert("new list: category.list"+currentCategory);
			window['category.html'+id] = categoryListHTML;
			window['category.list'+id] = categoryListID;
			window['category.publish'+id] = categoryListPublish;
			window['category.length'+id] = categoryListID.length;
		} else { // update category object with larger list
			if(categoryListID.length > window['category.length'+id]) {
				//alert("updating category.list:"+id+"::length"+currentListID.length);
				window['category.html'+id] = categoryListHTML;
				window['category.list'+id] = categoryListID;
				window['category.publish'+id] = categoryListPublish;
				window['category.length'+id] = categoryListID.length;
			}
		
		}
	} //end fromcat
	fromCategory = id;
	

	$$('#bottom-content #category-list a.current div.gradient').first().removeClassName('current');
	$$('#bottom-content #category-list a.current').first().removeClassName('current');

	$$('#category-' + id + '-anchor').first().addClassName('current');
	$$('#category-' + id + '-gradient').first().addClassName('current');

	//alert("setCurrentCategory:: 444");
}

// ADD video IDs to playlist
function addList(_publishDates,_list,_max,_page,_template){

	var offset = Math.min((12 * _page)+12, _max);
	
	_template = _template.split("#SEPERATE##");
	_list = _list.split(",");
	_publishDates = _publishDates.split("&");
	
	
	if(!isSearch) { 

		if(currentListID.length < offset && currentCategory == fromCategory ){
			//alert("adding to list"); 
			for (var i= 0; i < _list.length-1; i++){
			    currentListHTML[listCounter] = _template[i];
			    currentListID[listCounter] = _list[i].strip();
			    currentListPublish[listCounter] = convertXmlTime(_publishDates[i+1]);
			    listCounter++;
			}
		 } 	 else { 
			//add to current category list thats being viewed
			for (var i= 0; i < _list.length-1; i++) {
			    categoryListHTML[categoryListCounter] = _template[i];
			    categoryListID[categoryListCounter] = _list[i].strip();
			    categoryListPublish[categoryListCounter] = convertXmlTime(_publishDates[i+1]);
			    categoryListCounter++;
			}

		}//end else
	} else { 
		
		for (var i= 0; i < _list.length-1; i++) {
		    searchListHTML[searchListCounter] = _template[i];
		    searchListID[searchListCounter] = _list[i].strip();
		    searchListPublish[searchListCounter] = convertXmlTime(_publishDates[i].replace(/\n/, ""));
		    searchListCounter++;
		}
		
	}

}

function createListItem(){
	//var test = ="<li > <a onClick=\"javascript:reloadVideo(\'erwerewre\',\'dsfdffsd\',3,1); return false;\" href=\"u\"><div class=\"result-item\"><div id=\"video-thumb\" class=\"video-thumb\"><img src=\"/hive/images/tivid/play_icon.gif\" class=\"playBtn\" border=0 /><img title=\"erfwewrfer\" border=0 /></div><div class=\"video-title\"><utility:truncate length=\"45\">daqdswdwdwdasdwsdd</div><div class=\"video-more\"><div class=\"video-more-detail\">32434234234</div></div></div></a></li>";
	

}

function setCurrentList(id){
	
	
	//set current list to populated category list
    if(window['category.list'+id] != undefined && window['category.list'+id+'.length'] >= categoryListHTML.length && !isSearch) {
		currentListHTML = [];
		currentListID = [];
		currentListPublish = [];
		listCounter = 0;
		currentListHTML = window['category.html'+id];
		currentListID = window['category.list'+id];
		currentListPublish = window['category.publish'+id];
		listCounter = window['category.length'+id];	
		//alert("setting listCounter:"+listCounter);
	} else {    
		
		if(parseInt(id) == 99){ // From search  
			
			    
				currentListHTML = [];
				currentListID = [];
				currentListPublish = [];
				listCounter = searchSize;
				currentListHTML = searchListHTML;
				currentListID = searchListID;
				currentListPublish = searchListPublish;
			
		}else if(parseInt(currentCategory) == parseInt(fromCategory) && !isSearch) {  
			if (categoryListHTML.length > 0){ 
				currentListHTML = categoryListHTML;
				currentListID = categoryListID;
				currentListPublish = categoryListPublish;
				listCounter = categoryListID.length;
			}
		} else if(parseInt(fromCategory) == 99){  // came from viewing search videos
			
			currentListHTML = [];
			currentListID = [];
			currentListPublish = [];
			listCounter = 0;
			currentListHTML = window['category.html'+id];
			currentListID = window['category.list'+id];
			currentListPublish = window['category.publish'+id];
			listCounter = window['category.length'+id];
		}
	
	} 
	
}



function isLoaded() {
	if($$('#playlist #playlist-inner #load').first().hasClassName('show')) {
		$$('#playlist #playlist-inner #load').first().removeClassName('show');
		$$('#playlist #playlist-inner #load').first().addClassName('hide');
		
		nextUp(currentVideo);
		
	}
}
function pageInit() {
    jsReady = true;
}

function setPlayList(value) {
    thisPlayer("videofront-player").setPlayList(value);
 //setPlayList("http://vidcmsstage.trb.com/alfresco/service/edge/content/b5b0d9ed-b332-4352-a3c5-ce5c303a4067")
}
function playThisVideo(value) {
    thisPlayer("videofront-player").playThisVideo(value);
 //playThisVideo("http://vidcmsstage.trb.com/alfresco/service/edge/content/b5b0d9ed-b332-4352-a3c5-ce5c303a4067")
}

function alertComplete() {

	var size = 0;
	
	if($('category-'+currentCategory)) {
		size = parseInt($$('#category-'+currentCategory).first().attributes["size"].value);
	}else {
		size = searchSize;
	}

    
	currentVideo = parseInt(currentVideo) + 1;
	if(currentListID[currentVideo-1] != undefined) { 
		setPlayList(currentListID[currentVideo-1]);
		if (currentVideo < size){ 
			nextUp(currentVideo);
		} else if (currentVideo >= size){ 
			currentVideo = 0;
			nextUp(currentVideo);
		}
	} else {
		if (currentVideo < size){ 
			setPlayList(currentListID[currentVideo-1]);
			nextUp(currentVideo);
		} else if (currentVideo >= size){ 
			currentVideo = 1;
			setPlayList(currentListID[currentVideo-1]);
			nextUp(currentVideo);
		}
	}
	
	
	
}

function moreListSuccess() {
	$$('#playlist #playlist-inner #playlist-content').first().innerHTML = currentListHTML[currentVideo];
}

function getMoreList() { 
	
	var query = globalCarousel.options.url.toQueryParams([separator = '&']);
	var page;
	
	if(currentListHTML.length < query.listSize ){
        
	    page = (currentListHTML.length / 12);	
		new Ajax.Request(globalCarousel.options.url, {method: "GET", parameters: {from: page, to: page}, onSuccess:  moreListSuccess});

	} 

}
// Order = currentVideo, but the array starts at 0, currentVideo used as next video number too.
function nextUp(order) {
	
	var size = 0; 
	var tempList = ""; 
	var tempLimit = 0;

	if($('category-'+currentCategory)){
		size = parseInt($('category-'+currentCategory).attributes["size"].value);
	} else {
		size = parseInt(searchSize);
		
	}
	

    if(currentListID[order] != undefined) {  
	    
		    if(currentListID.length >= 4) {  
			    tempLimit = order+3;
				for (var i= order; i < tempLimit; i++) {
				
					if(i == currentListID.length){
						tempLimit = tempLimit - i;
						i = 0;
					}
				
			        if(currentListHTML[i] != undefined) 
		               tempList = tempList + currentListHTML[i];
	                 
				} //end for
			} else {  
			     
				if(currentListID.length !=1) {  
					tempLimit = order + (currentListID.length-1);
					for (var i= order; i < tempLimit; i++) {

						if(i == currentListID.length){
							tempLimit = tempLimit - i;
							i = 0;
						}

						if(currentListHTML[i] != undefined) 
							tempList = tempList + currentListHTML[i];

					} //end for
				}  else {  
					tempList = tempList + currentListHTML[order];
					
				}
				
			
		    }//end else
		
		$$('#playlist #playlist-inner #playlist-content').first().innerHTML = tempList;
	
	} else if (currentListHTML[order] == undefined) { 
		
		currentVideo = 0;
		if(currentListHTML.length <= size) { 
			//getMoreList();
			
			 if(currentListID.length != 1) {   
				tempLimit = order + Math.min((currentListID.length-1),3); 
				for (var i= order; i < tempLimit; i++) {

					if(i == currentListID.length){
						tempLimit = tempLimit - i;
						i = 0;
					}

			        if(currentListHTML[i] != undefined) 
		               tempList = tempList + currentListHTML[i];

				} //end for
			} else { 
			
				for (var i= currentVideo; i < currentVideo+3; i++) {
			        if(currentListHTML[i] != undefined) 
		                tempList = tempList + currentListHTML[i];
				}
			}

			$$('#playlist #playlist-inner #playlist-content').first().innerHTML = tempList;
		} else {       
			for (var i= currentVideo; i < currentVideo+3; i++) {
		        if(currentListHTML[i] != undefined) 
	                tempList = tempList + currentListHTML[i];
			}
			
			
			if(tempList == null || tempList == undefined || tempList == "undefined" || tempList == "") 
				$$('#playlist #playlist-inner #playlist-content').first().innerHTML = "An Error has Occured. Please Refresh and Try Again.";
			else 
				$$('#playlist #playlist-inner #playlist-content').first().innerHTML = tempList;

			
		}
	} 
}


function checkNextCat(){
	var nextCat = parseInt(currentCategory) + 1;
	var category = $$('#category-'+nextCat).first().attributes["category"].value;
	var size = $$('#category-'+nextCat).first().attributes["size"].value;
	
	if(!$$('#category-'+ nextCat +'-anchor').empty()){
		
		if(window['category.list'+currentCategory] != undefined) {
			//alert("here:"+nextCat);
			$$('#playlist #playlist-inner #playlist-content').first().innerHTML = window['category.html'+nextCat][0];
		} else {
			currentVideo = 2;
			loadCategory(category, size, nextCat);
			
		}
		
		offList = true;
		
	} else if(offList == true){
		currentVideo = 2;
		loadCategory(category, size, nextCat);

	} else {// no more videos
				//alert("here3"+nextCat);
		$$('#playlist #playlist-inner #playlist-content').first().innerHTML = "";
	}
	
}


function createNewCategory(){
	var query = globalCarousel.options.url.toQueryParams([separator = '&']);
	var page;
	
	if(currentListHTML.length < query.listSize ){
        
	    page = (currentListHTML.length / 12);	
		new Ajax.Request(globalCarousel.options.url, {method: "GET", parameters: {from: page, to: page}, onSuccess:  moreListSuccess});

	}
	
}


function thisPlayer(movieName)
{
	if (window.document[movieName]) { 
		return window.document[movieName]; 
	}

	if (navigator.appName.indexOf("Microsoft Internet")==-1) { 
		if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	}

	else { 
		return document.getElementById(movieName); 
	}

}

function firstUpdate() {
	this.endIndex = Math.max(this.endIndex, json.to);
    this.elements = this.container.insert({bottom: json.html}).childElements();
    return this.updateButtons();
	
}

function setVideoData(target) {
	
	// setup for closed captioning tab
	// un-comment all to turn on
	
    //target = parseInt(target);
	
	//if($('video-data-info').down(target).hasClassName('hide')) { 
		//$('video-data-info').down(target).removeClassName('hide');
		//$('video-data-info').down(target).addClassName('show');
		//$('video-data-tabs').down('li',target).addClassName('current-tab');
		
		//$('video-data-tabs').down('li',currentTab).removeClassName('current-tab');
		//$('video-data-info').down(currentTab).removeClassName('show');
		//$('video-data-info').down(currentTab).addClassName('hide');
		
		//currentTab = target;
    //} 
    	
}


///////////////
function handleVideoRequest(html,_to,_from) {
	// html[1] = base LI return
   // html[2] = total pages givne # of items in category
   // html[3] = Duration values of each vid, so we can run conversion script, delimted by '&;
   // html[4] = Publish values to run conversion script,, delimted by '&;
   // html[5] = base LI return
   // html[6] = returned list of just the video IDs delimited by commma
   // html[7] = total video in category
   // html[8] = current result page
   // use #SEPERATE## as delimiter of LI tags
   // nbelements = # of pages
	html = html.split("#!VIDEOREQUEST");
	
	var template = html[1];
	var nbElements = html[2]; 
	var durationHold = html[3];
	var publishHold = html[4];
	var playlist = html[6];
	var maxSize = html[7];
	var pageNum = html[8];

    template = convertDateAndTime(template, durationHold, publishHold);
    template = convertAkamaiUrl(template);
    addList(publishHold,playlist,maxSize,pageNum,template);
    template = template.gsub("#SEPERATE##","");

    var from = _from;
    var to   = Math.min(nbElements, _to);

     return {html: template, from: from, to: to, more: to != nbElements};
}

function handleSearchRequest(html,_to,_from) {  
	   
	   html = html.split("#!SEARCHREQUEST");
	
	   // html[1] = base LI return
	   // html[2] = total pages givne # of items in category
	   // html[3] = Duration values of each vid, so we can run conversion script, delimted by '&;
	   // html[4] = Publish values to run conversion script,, delimted by '&;
	   // html[5] = base LI return
	   // html[6] = returned list of just the video IDs delimited by commma
	   // html[7] = total video in category
	   // html[8] = current result page
	   // use #SEPERATE## as delimiter of LI tags
	   // nbelements = # of pages
	
	var template = html[1];
	var nbElements = html[2]; 
	var durationHold = html[3];
	var publishHold = html[4];
	var playlist = html[6];
	var maxSize = html[7];
	var pageNum = html[8];
	
	searchSize = maxSize;
	
	if(parseInt(html[7]) == 0) { /// no results returned
 	   searchResultsText(1,0);
	   return false;
	}
	
    template = convertDateAndTime(template, durationHold, publishHold);
    //template = convertAkamaiUrl(template);
    addList(publishHold,playlist,maxSize,pageNum,template);
    template = template.gsub("#SEPERATE##","");

      

    searchResultsText(2,maxSize);
    $('search-page-count').innerHTML = "Page " + (parseInt(_from)+ 1) + " of " + convertPerPage(searchSize, 12);

    var from = _from;
    var to   = Math.min(nbElements, _to);

     return {html: template, from: from, to: to, more: to != nbElements};
}


///search functions
///////////////////////

function startSearch(query) {
	
	//clear temp list
	searchListHTML = [];
    searchListID = [];
    searchListPublish = [];
    searchListCounter = 0;

    isSearch = true;  
    searchQuery = query;

    killSearch();
    createSearch();
	
	if($('category').hasClassName('show')) {  
		
		// This saves the current category that is being viewed
		// This will happen if it came from the category view
		saveCurrentCategory();
		beforeSearch = currentCategory;
		
		$('category').removeClassName('show');
		$('category').addClassName('hide');
		$('more-video').removeClassName('show');
		$('more-video').addClassName('hide');
		
		$('video-search-result').removeClassName('hide');
		$('video-search-result').addClassName('show');
		
		if($('horizontal_carousel1').hasClassName('hide')) {
             $('horizontal_carousel1').removeClassName('hide');
	 	  	 $('horizontal_carousel1').addClassName('show');
		  }
		
	  } 
	
	
	  searchCarousel = new UI.Ajax.Carousel("horizontal_carousel1",
    {url: "/get-video-search.xml?query="+query, elementSize: 844,first: "false"})
    .observe("request:started", function() {
          $$('div#horizontal_carousel1 #spinner').first().show().morph("opacity:0.5", {duration:0.2});
      })
    .observe("request:ended", function() {

          $$('div#horizontal_carousel1 #spinner').first().morph("opacity:0", {duration:0.2, afterFinish: function(obj) { obj.element.hide(); }});
	
      })
    .observe(	"scroll:ended", function(event) {
         
         var from = this.currentIndex() + 1;
         
        $('search-page-count').innerHTML = "Page " + from + " of " + convertPerPage(searchSize, 12);

      });
	
	
	
}

function hideSearchResults() { 
	isSearch = false;
	killSearch();
    createSearch();


    // populate the categoryList, mocking load Category
     
     fromCategory = beforeSearch;
    categoryListHTML = 	window['category.html'+beforeSearch];
	categoryListID = window['category.list'+beforeSearch];
	categoryListPublish = window['category.publish'+beforeSearch];
	categoryListCounter = window['category.length'+beforeSearch];
	
	$('category').removeClassName('hide');
	$('category').addClassName('show');
	$('more-video').removeClassName('hide');
	$('more-video').addClassName('show');
	
	$('video-search-result').removeClassName('show');
	$('video-search-result').addClassName('hide');
	
	
	}
	
	function killSearch() { 
		if(searchCarousel != null) {
		    searchCarousel.destroy();
		    searchCarousel= null;

		}
	}
	
	function createSearch() { 
		if(searchCarousel == null) {
		    // destroying kills the whole div, setting back the div
			$('video-search-result-data').innerHTML = '<div id="horizontal_carousel1" class="horizontal_carousel show"><div id="nextButton" class="next_button" ></div><div id="prevButton" class="previous_button"></div><div class="container"><ul></ul><div id="spinner" style="display: none;"></div><div class="clear"></div></div><div class="clear"></div></div><div id="search-page-count"></div>';
		}
	}
	
	function searchResultsText(result, total) { 	
		
		switch(parseInt(result))
		{
			case 1:
			  $('search-results-text').innerHTML = "No Search Results for \"" +  searchQuery + "\"";
			  if($('horizontal_carousel1').hasClassName('show')) {
	             $('horizontal_carousel1').removeClassName('show');
		 	  	 $('horizontal_carousel1').addClassName('hide');
			  }
			  break;
			case 2:
			  $('search-results-text').innerHTML = total + " Search Results for \"" +  searchQuery + "\"";
			  if($('horizontal_carousel1').hasClassName('hide')) {
	             $('horizontal_carousel1').removeClassName('hide');
		 	  	 $('horizontal_carousel1').addClassName('show');
			  }
			  break;
			default:
			  $('search-results-text').innerHTML = "Results a little goofy... ";
			  if($('horizontal_carousel1').hasClassName('show')) {
	             $('horizontal_carousel1').removeClassName('show');
		 	  	 $('horizontal_carousel1').addClassName('hide');
			  }
		}
		  
		  
		
	}
	
	function saveCurrentCategory() { 	
		  // This function is for saving the current category you came from, when switching to the Search View
		  // Similar to setcurrent Category
		
		if(window['category.list'+currentCategory] == undefined) {

			//alert("new list: category.list"+currentCategory);
			window['category.html'+currentCategory] = currentListHTML;
			window['category.list'+currentCategory] = currentListID;
			window['category.publish'+currentCategory] = currentListPublish;
			window['category.length'+currentCategory] = currentListID.length;
		} else { // update category object with larger list
			if(currentListID.length > window['category.length'+currentCategory]) {
				//alert("updating category.list:"+currentCategory+"::length"+currentListID.length);
				window['category.html'+currentCategory] = currentListHTML;
				window['category.list'+currentCategory] = currentListID;
				window['category.publish'+currentCategory] = currentListPublish;
				window['category.length'+currentCategory] = currentListID.length;
			}

		}
		
		fromCategory = 99;  // 99 is the ID given to search
		
		
	}




	
