
// /////////////////////
// videoModule class
// /////////////////////
//fields
pdVideosModule.prototype._transport;
pdVideosModule.prototype._user;
pdVideosModule.prototype._channelId = 'site.videos';
pdVideosModule.prototype._listObjects;
pdVideosModule.prototype._listCurrent;
pdVideosModule.prototype._listCacheExpires;
pdVideosModule.prototype._listCacheRefresh;
pdVideosModule.prototype._BACK_PAGE_NUMBER = -2;
pdVideosModule.prototype._NEXT_PAGE_NUMBER = -1;
pdVideosModule.prototype._PAGE_NUMBER_LIMIT = 5;

function pdVideosModule(){}

pdVideosModule.prototype.initialize = function(transport, user){
  	//this function is called back during module registration
	this._transport = transport;
	this._user = user;

	var me = this;	
	
	//setup list objects for the various search lists we have on this page
	//this way each pane and video list loading has its own properties
	this._listObjects = {
		newVideos: {
			sortField : 'PublishDate',
			sortReverse : true,
			currentPage : 1,
			pageLength : 18,
			searchTerms : '',
			companyId : 0,
			tags : '',
			headerName : '',
			resultList : $('divVideosNewVideosResults'),
			pagingList : $('divVideosNewVideosPaging'),
			cacheKey : 'pd2-page-fragment-videos-list-new-videos'
		},
		mostWatched: {
			sortField : 'TotalViews',
			sortReverse : true,
			currentPage : 1,
			pageLength : 18,
			searchTerms : '',
			companyId : 0,
			tags : '',
			headerName : '',
			resultList : $('divVideosMostWatchedResults'),
			pagingList : $('divVideosMostWatchedPaging'),
			cacheKey : 'pd2-page-fragment-videos-most-watched'
		},
		dogFights: {
			sortField : 'PublishDate',
			sortReverse : true,
			currentPage : 1,
			pageLength : 18,
			searchTerms : '',
			companyId : 0,
			tags : 'head to head reviews',
			headerName : '',
			resultList : $('divVideosDogFightsResults'),
			pagingList : $('divVideosDogFightsPaging'),
			cacheKey : 'pd2-page-fragment-videos-list-dog-fights'
		},
		byCategory: {
			sortField : 'PublishDate',
			sortReverse : true,
			currentPage : 1,
			pageLength : 15,
			searchTerms : '',
			companyId : 0,
			tags : '',
			headerName : '',
			resultList : $('divVideosByCategoryResults'),
			pagingList : $('divVideosByCategoryPaging'),
			cacheKey : 'pd2-page-fragment-videos-list-by-category'
		},		
		search: {
			sortField : 'PublishDate',
			sortReverse : true,
			currentPage : 1,
			pageLength : 18,
			searchTerms : '',
			companyId : 0,
			tags : '',
			headerName : 'Search results',
			resultList : $('divVideosSearchResults'),
			pagingList : $('divVideosSearchPaging'),
			cacheKey : 'pd2-page-fragment-videos-list-search'
		}			
	}	
	
	//setup homepage events	
	if($('linkHomeNewVideos')){
		$('linkHomeNewVideos').observe('click', this.activateTab.bindAsEventListener(this, 'video-tab-new-videos'));
		$('linkHomeMostWatchedVideos').observe('click', this.activateTab.bindAsEventListener(this, 'video-tab-most-watched'));
		$('linkHomeDogFights').observe('click', this.activateTab.bindAsEventListener(this, 'video-tab-dog-fights'));
		$('linkHomeVideosByCategory').observe('click', this.activateTab.bindAsEventListener(this, 'video-tab-videos-by-category'));
	}

	//setup tab events
	$('video-tabs-menu').select('a').each(function(tab){
		tab.observe('click', me.activateTab.bindAsEventListener(me, tab.identify()));
	});
	
	//setup search events
	$('videoQuery').observe('focus', this.onVideoSearchFocus.bind(this));
	$('videoQuery').observe('blur', this.onVideoSearchBlur.bind(this));
	$('videoQuery').observe('keyup', this.onSearchEnterTyped.bind(this));	
	$('refVideoSearch').observe('click', this.onVideoSearch.bind(this));	
	
	//setup video category events
	var firstCat = true;	
	$('video-tabs-videos-categories').select('div.videos-list-category').each(function(div){
		if(firstCat){div.addClassName('videos-list-category-selected');}
		div.observe('click', me.onVideoCategoryClick.bind(me));
		firstCat = false;
	});
	
	$('video-tabs-videos-categories').select('div.videos-list-category-sub').each(function(div){
		div.observe('click', me.onVideoSubCategoryClick.bind(me));
	});	
	
	
	//set caching information
	var queryInfo = window.location.search.toQueryParams();
	this._listCacheRefresh = (queryInfo.cacherefresh) ? true : false;
	
	//configure cache expiration date
	var currentHours = new Date(pd_serverDateTime).getHours() + 3;
	var cacheExpires = new Date(pd_serverDateTime).setHours(currentHours);
	this._listCacheExpires = new Date(cacheExpires);
	
	//check if we a tabid in the querystring and if so
	//then activate that tab
	if(queryInfo.tabid != null){
		this.activateTab(null, queryInfo.tabid);
	}
		
}

pdVideosModule.prototype.activateTab = function(event, tabId){
	if(event){Event.stop(event);}
	
	var tab = $(tabId);
	var tabOuter = tab.up('div');
	var tabOuterWrapper = tabOuter.up('div');
	var tabpane = tab.readAttribute('rel');	
	tab.scrollTo();
	this.resetTabs();
	
	tabOuterWrapper.className = 'video-tab-active';
	tabOuter.className = 'video-tab-active-right';
	$(tabpane).show();	
	
	//wait a half second here to let IE catch up
	window.setTimeout(this.loadTabList.bindAsEventListener(this, tab, tabpane), 500);
	
	pd_globalSiteFramework.trackEvent('Videos', 'Tab - click', tab.innerHTML);	
}

pdVideosModule.prototype.loadTabList = function(event, tab, tabpane){	
	var isLoaded = tab.readAttribute('loaded');
	
	if(tabpane == 'video-tabs-new-videos'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.newVideos;
		
		if(isLoaded != 'true'){
			this.loadVideos();
		}
	}else if(tabpane == 'video-tabs-dog-fights'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.dogFights;
		
		if(isLoaded != 'true'){
			this.loadVideos();
		}
	}else if(tabpane == 'video-tabs-most-watched'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.mostWatched;
		
		if(isLoaded != 'true'){
			this.loadVideos();
		}
	}else if(tabpane == 'video-tabs-videos-by-category'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.byCategory;
		
		if(isLoaded != 'true'){
			this.loadVideos();
		}
	}
}

pdVideosModule.prototype.resetTabs = function(){
	$('video-tabs-menu').childElements().each(function(tab){
		tab.className = 'video-tab';
		tab.down('div').className = 'video-tab-right';
	});	
	$$('.video-tabs-pane').each(function(pane){pane.hide();});
}

// ----------------------------------------------------- //
// VIDEOS BY CATEGORY FUNCTIONS
// ----------------------------------------------------- //
pdVideosModule.prototype.onVideoCategoryClick = function(event){
	Event.stop(event);
	var category = Event.element(event);
	var related = category.readAttribute('rel');
	
	if(category.className != 'videos-list-category videos-list-category-selected'){	
		$('video-tabs-videos-categories').select('div.videos-list-category').each(function(div){div.removeClassName('videos-list-category-selected');});
		$('video-tabs-videos-categories').select('div.videos-list-category-sub').each(function(div){div.hide();});		
		$('video-tabs-videos-categories').select('div.videos-list-category-sub[rel="' + related + '"]').each(function(div){div.show();});		
		category.addClassName('videos-list-category-selected');
		
		pd_globalSiteFramework.trackEvent('Videos', 'Category - click', category.innerHTML);
	}
}

pdVideosModule.prototype.onVideoSubCategoryClick = function(event){
	Event.stop(event);
	var subCategory = Event.element(event);	
	
	this._listObjects.byCategory.currentPage = 1;
	this._listObjects.byCategory.companyId = (subCategory.readAttribute('companyId') != '') ? subCategory.readAttribute('companyId') : -1;
	this._listObjects.byCategory.headerName = subCategory.innerHTML + ' Videos';
	this._listObjects.byCategory.tags = (this._listObjects.byCategory.companyId > 0) ? '' : subCategory.innerHTML;
	this._listObjects.byCategory.cacheKey = (this._listObjects.byCategory.companyId > 0) ? 'pd2-page-fragment-videos-list-by-category-' + this._listObjects.byCategory.companyId : 'pd2-page-fragment-videos-list-by-category-' + escape(this._listObjects.byCategory.tags);
	this._listCurrent = this._listObjects.byCategory;
	
	pd_globalSiteFramework.trackEvent('Videos', 'Sub Category - click', subCategory.innerHTML);
	
	this.loadVideos();
}

// ----------------------------------------------------- //
// VIDEO SEARCH FUNCTIONS
// ----------------------------------------------------- //
pdVideosModule.prototype.onVideoSearchFocus = function(event){$('videoQuery').value = '';}
pdVideosModule.prototype.onVideoSearchBlur = function(event){var input = $('videoQuery');if(input.value == ''){input.value = 'Search videos...';}}
pdVideosModule.prototype.onSearchEnterTyped = function (event){if(event.which || event.keyCode){if((event.which == 13) || (event.keyCode == 13)){this.onVideoSearch(event);}}}
pdVideosModule.prototype.onVideoSearch = function(event){
	Event.stop(event);
	var searchTerms = $('videoQuery').value;

	if(searchTerms != '' && searchTerms != 'Search videos...'){
		this.resetTabs();
		this._listCurrent = this._listObjects.search;
		this._listObjects.search.headerName = 'Search results for "' + searchTerms + '"';
		this._listObjects.search.searchTerms = searchTerms
		this._listObjects.search.cacheKey = 'pd2-page-fragment-videos-list-search-' + escape(searchTerms);	
	
		$('video-tabs-videos-search').show();	
			
		pd_globalSiteFramework.trackEvent('Videos', 'Search - click', searchTerms);
		
		this.loadVideos();
	}
}

// ----------------------------------------------------- //
// GENERIC LIST LOADING & DISPLAY FUNCTIONS
// ----------------------------------------------------- //
pdVideosModule.prototype.loadVideos = function(){
	this.renderLoadingList();

	var request = {
		'sortField': this._listCurrent.sortField,
		'sortDesc': this._listCurrent.sortReverse,
		'pageIndex': this._listCurrent.currentPage, 
		'pageSize': this._listCurrent.pageLength,
		'companyId': this._listCurrent.companyId,
		'tags' : this._listCurrent.tags,
		'searchTerms' : this._listCurrent.searchTerms,
		'cacheKey' : this._listCurrent.cacheKey + '-' + this._listCurrent.currentPage,
		'cacheExpires' : new Date(this._listCacheExpires).toUTCString(),
		'cacheRefresh' : this._listCacheRefresh
	}
	this._transport.transmitRequest('site.videos', 'getvideos', request, this.onVideosRetrieved.bind(this));	
}

pdVideosModule.prototype.onVideosRetrieved = function(objResponse){
	if(objResponse.videos.length > 0){
		var resultList = new Element('span');
		
		if(this._listCurrent.headerName != ''){
			resultList.appendChild(new Element('h2').update(this._listCurrent.headerName));
		}

		for(var i = 0; i < objResponse.videos.length; i++){
			var video = objResponse.videos[i];			
			var itemWrapper = new Element('div', {'class' : 'videos-list-video'});
			var itemBody = new Element('div', {'class' : 'videos-list-video-body'});				
			var imgWrapper = new Element('div', {'class' : 'videos-list-video-img tip-static-hover', 'tiptitle' : video.PageTitle.replace(/"/g,''), 'tipcontent' : video.MetaDescription.replace(/"/g,'')});
			var imgLink = new Element('a', {'href' : video.PageUrl + '.aspx'});

			var img = new Element('img', {'src' : 'http://i.ytimg.com/vi/' + video.SourceUrl + '/default.jpg'});
			imgLink.appendChild(img);
			imgLink.observe('click', this.onVideoClick.bindAsEventListener(this, video.ShortTitle));
			imgWrapper.appendChild(imgLink);
			itemBody.appendChild(imgWrapper);

			var titleWrapper = new Element('div', {'class' : 'videos-list-video-title'});
			var titleLink = new Element('a', {'href' : video.PageUrl + '.aspx'}).update(video.ShortTitle);
			titleLink.observe('click', this.onVideoClick.bindAsEventListener(this, video.ShortTitle));
			titleWrapper.appendChild(titleLink);
			itemBody.appendChild(titleWrapper);			
			
			var date = new Element('div', {'class' : 'videos-list-video-date'}).update(PDFormatShortDate(video.PublishDate));
			itemBody.appendChild(date);
			itemWrapper.appendChild(itemBody);
			
			resultList.appendChild(itemWrapper);
		}		
		
		this._listCurrent.resultList.update();
		this._listCurrent.resultList.appendChild(resultList);		
		this.resetPaging(objResponse.totalVideos);	
		
		//if we have the tips module successfully loaded
		//then call the function to re-attach the tips
		if(pd_tips != 'undefined'){
			pd_tips.attachEvents();
		}
	}else{
		this.renderNothingFound();

		pd_globalSiteFramework.trackEvent('Videos', 'Search - not found', this._listCurrent.searchTerms);
	}
}

pdVideosModule.prototype.onVideoClick = function(event, videoName){
	pd_globalSiteFramework.trackEvent('Videos', 'Video - click', videoName);	
}


// ----------------------------------------------------- //
// GENERIC RENDER FUNCTIONS
// ----------------------------------------------------- //
pdVideosModule.prototype.renderLoadingList = function(){
	var loadingWrapper = new Element('span');
	var loadingImage = new Element('img', {src : 'http://r.phonedog.com/template/images/loading.gif', alt : 'The phonedog is fetching...'});
	var loadingText = new Element('span').update('Please wait while the phonedog is fetching these videos for you...');
	loadingWrapper.appendChild(loadingImage);
	loadingWrapper.appendChild(loadingText);
	
	this._listCurrent.pagingList.update();
	this._listCurrent.resultList.update();	
	this._listCurrent.resultList.appendChild(loadingWrapper);
}

pdVideosModule.prototype.renderNothingFound = function(){
	var wrapper = new Element('span');
	var text = new Element('span').update('After much digging, the PhoneDog was unable to fetch you any videos for the current category or search term(s)');
	wrapper.appendChild(text);
	
	this._listCurrent.resultList.update();	
	this._listCurrent.resultList.appendChild(wrapper);
}

// ----------------------------------------------------- //
// GENERIC PAGING FUNCTIONS
// ----------------------------------------------------- //
pdVideosModule.prototype.resetPaging = function (itemsCount){	
	var paging = this._listCurrent.pagingList;
	var ulList = new Element('ul');	
	
	paging.update('');	
	
	if (itemsCount > 0){
		//round up to get a whole number of pages
		var pageCount = Math.ceil(itemsCount / this._listCurrent.pageLength); 
		
		if (pageCount > 1){		
			//figure out the upper and lower page numbers, based on the current page
			var minPageNumber = Math.max(1, this._listCurrent.currentPage - parseInt(this._PAGE_NUMBER_LIMIT/2) );
			var maxPageNumber = Math.min(pageCount, this._listCurrent.currentPage + parseInt(this._PAGE_NUMBER_LIMIT/2) );
			if (maxPageNumber - minPageNumber < this._PAGE_NUMBER_LIMIT - 1){
				//insufficient pages displayed - attempt to increase the max number
				 maxPageNumber = Math.min(pageCount, minPageNumber + this._PAGE_NUMBER_LIMIT - 1 );
			}
			if (maxPageNumber - minPageNumber < this._PAGE_NUMBER_LIMIT - 1){
				//insufficient pages displayed - attempt to decrease the min number
				 minPageNumber = Math.max(1, maxPageNumber - this._PAGE_NUMBER_LIMIT + 1 );
			}		
		
			//if not the first page, add the 'first'
			if (this._listCurrent.currentPage > 1){
				ulList.appendChild(this.addPagingLink ('pageFirst', '&laquo; First', 1, 'prevnext'));
			}
			
			//add the page numbers
			for (var p = minPageNumber; p <= maxPageNumber; p++){
				if (p==this._listCurrent.currentPage){
					ulList.appendChild(this.addPagingLink ('pageTo' + p, p, p, 'active'));
				}else{
					ulList.appendChild(this.addPagingLink ('pageTo' + p, p , p, ''));
				}														
			}
			
			//if not the last page, add the 'last' links
			if (this._listCurrent.currentPage < pageCount){
				ulList.appendChild(this.addPagingLink ('pageLast', 'Last &raquo;', pageCount, 'prevnext'));
			}
			
			paging.appendChild(ulList);
		}
	}
}

pdVideosModule.prototype.addPagingLink = function (refId, description, pageNumber, className){
	var listItem = new Element('li', {'class' : className});
	var listLink = new Element('A', {href: '#', id: refId}).update(description);	
	listItem.appendChild(listLink);
	Event.observe(listLink, 'click', this.onPageClicked.bindAsEventListener(this, pageNumber));	
	return listItem;
}

pdVideosModule.prototype.onPageClicked = function (event, pageNumber){
	//navigate to chosen page
	Event.stop(event);
	if (pageNumber == this._BACK_PAGE_NUMBER){
		this._listCurrent.currentPage-- ;
	}else if (pageNumber == this._NEXT_PAGE_NUMBER){
		this._listCurrent.currentPage++ ;		
	}else{
		this._listCurrent.currentPage = pageNumber;
	}
	
	this.loadVideos();
}
