
// /////////////////////
// buyingGuidesModule class
// /////////////////////
//fields
pdBuyingGuidesModule.prototype._transport;
pdBuyingGuidesModule.prototype._user;
pdBuyingGuidesModule.prototype._channelId = 'site.blogs';
pdBuyingGuidesModule.prototype._listObjects;
pdBuyingGuidesModule.prototype._listCurrent;
pdBuyingGuidesModule.prototype._listCacheExpires;
pdBuyingGuidesModule.prototype._listCacheRefresh;
pdBuyingGuidesModule.prototype._BACK_PAGE_NUMBER = -2;
pdBuyingGuidesModule.prototype._NEXT_PAGE_NUMBER = -1;
pdBuyingGuidesModule.prototype._PAGE_NUMBER_LIMIT = 5;

function pdBuyingGuidesModule(){}

pdBuyingGuidesModule.prototype.initialize = function(transport, user){
  	//this function is called back during module registration
	this._transport = transport;
	this._user = user;

	var me = this;	
	
	//if we have a blogs tab menu then we're on a details page
	if($('blog-tabs-menu')){	
		//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 = {
			byCategory: {
				sortField : 'PublishDate',
				sortReverse : true,
				currentPage : 1,
				pageLength : 15,
				searchTerms : '',
				sectionIds : '6FB0FB82C26C4BA1A00203E8DB0AB311',
				subSectionIds : '95488028B3FD419C9B324C0E9CC4D0B1',			
				tags : '',
				headerName : '',
				resultList : $('divBlogsByCategoryResults'),
				pagingList : $('divBlogsByCategoryPaging'),
				path : '/cell-phone-research/blog/',
				cacheKey : 'pd2-page-fragment-blogs-list-by-category'
			},	
			tipsAndTricks: {
				sortField : 'PublishDate',
				sortReverse : true,
				currentPage : 1,
				pageLength : 18,
				searchTerms : '',
				sectionIds : 'CA672235095544BAAA2B1CE923482DE1',
				subSectionIds : '95488028B3FD419C9B324C0E9CC4D0B1',			
				tags : '',
				headerName : '',
				resultList : $('divBlogsTipsAndTricksResults'),
				pagingList : $('divBlogsTipsAndTricksPaging'),
				path : '/cell-phone-tips-and-tricks/',			
				cacheKey : 'pd2-page-fragment-blogs-list-tips-and-tricks'
			},	
			inDepthReviews: {
				sortField : 'PublishDate',
				sortReverse : true,
				currentPage : 1,
				pageLength : 18,
				searchTerms : '',
				sectionIds : '6FB0FB82C26C4BA1A00203E8DB0AB311',
				subSectionIds : '5E634879E8284DD4A698FD590A3335CE',			
				tags : '',
				headerName : '',
				resultList : $('divBlogsInDepthReviewsResults'),
				pagingList : $('divBlogsInDepthReviewsPaging'),
				path : '/cell-phone-reviews/',			
				cacheKey : 'pd2-page-fragment-blogs-list-in-depth-reviews'
			},	
			newVideos: {
				sortField : 'PublishDate',
				sortReverse : true,
				currentPage : 1,
				pageLength : 18,
				searchTerms : '',
				sectionIds : '6FB0FB82C26C4BA1A00203E8DB0AB311',
				subSectionIds : 'C8F2DB9A95C84683BEAE761E1794DA3C',
				tags : '',
				headerName : '',
				resultList : $('divBlogsNewVideosResults'),
				pagingList : $('divBlogsNewVideosPaging'),
				path : '/cell-phone-videos/',			
				cacheKey : 'pd2-page-fragment-blogs-list-new-videos'
			},			
			search: {
				sortField : 'PublishDate',
				sortReverse : true,
				currentPage : 1,
				pageLength : 18,
				searchTerms : '',
				sectionIds : '6FB0FB82C26C4BA1A00203E8DB0AB311',
				subSectionIds : '95488028B3FD419C9B324C0E9CC4D0B1',			
				tags : '',
				headerName : 'Search results',
				resultList : $('divBlogsSearchResults'),
				pagingList : $('divBlogsSearchPaging'),
				path : '/cell-phone-research/blog/',			
				cacheKey : 'pd2-page-fragment-blogs-list-search'
			}	
		}

		//setup tab events
		$('blog-tabs-menu').select('a').each(function(tab){tab.observe('click', me.activateTab.bindAsEventListener(me, tab.identify()));});
		
		//setup search events
		$('blogQuery').observe('focus', this.onBlogSearchFocus.bind(this));
		$('blogQuery').observe('blur', this.onBlogSearchBlur.bind(this));
		$('blogQuery').observe('keyup', this.onBlogSearchEnterTyped.bind(this));	
		$('refBlogSearch').observe('click', this.onBlogSearch.bind(this));
		
		//setup blog category events
		var firstCat = true;	
		$('blog-tabs-blogs-categories').select('div.blogs-list-category').each(function(div){
			if(firstCat){div.addClassName('blogs-list-category-selected');}
			div.observe('click', me.onBlogCategoryClick.bind(me));
			firstCat = false;
		});
		
		$('blog-tabs-blogs-categories').select('div.blogs-list-category-sub').each(function(div){div.observe('click', me.onBlogSubCategoryClick.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);
		
		//check if we a tabid in the querystring and if so
		//then activate that tab
		if(queryInfo.tabid != null){
			this.activateTab(null, queryInfo.tabid);
		}
	}
		
}

pdBuyingGuidesModule.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 = 'blog-tab-active';
	tabOuter.className = 'blog-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('Blogs', 'Tab - click', tab.innerHTML);	
}

pdBuyingGuidesModule.prototype.loadTabList = function(event, tab, tabpane){	
	var isLoaded = tab.readAttribute('loaded');
	
	if(tabpane == 'blog-tabs-new-videos'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.newVideos;
	}else if(tabpane == 'blog-tabs-blogs-by-category'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.byCategory;
	}else if(tabpane == 'blog-tabs-tips-and-tricks'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.tipsAndTricks;
	}else if(tabpane == 'blog-tabs-in-depth-reviews'){
		tab.writeAttribute('loaded', 'true');
		this._listCurrent = this._listObjects.inDepthReviews;
	}
	
	if(isLoaded != 'true'){this.loadBlogs();}
}

pdBuyingGuidesModule.prototype.resetTabs = function(){
	$('blog-tabs-menu').childElements().each(function(tab){
		tab.className = 'blog-tab';
		tab.down('div').className = 'blog-tab-right';
	});	
	$$('.blog-tabs-pane').each(function(pane){pane.hide();});
}

// ----------------------------------------------------- //
// BLOGS BY CATEGORY FUNCTIONS
// ----------------------------------------------------- //
pdBuyingGuidesModule.prototype.onBlogCategoryClick = function(event){
	Event.stop(event);
	var category = Event.element(event);
	var related = category.readAttribute('rel');
	
	if(category.className != 'blogs-list-category blogs-list-category-selected'){	
		$('blog-tabs-blogs-categories').select('div.blogs-list-category').each(function(div){div.removeClassName('blogs-list-category-selected');});
		$('blog-tabs-blogs-categories').select('div.blogs-list-category-sub').each(function(div){div.hide();});		
		$('blog-tabs-blogs-categories').select('div.blogs-list-category-sub[rel="' + related + '"]').each(function(div){div.show();});		
		category.addClassName('blogs-list-category-selected');
		
		pd_globalSiteFramework.trackEvent('Blogs', 'Category - click', category.innerHTML);
	}
}

pdBuyingGuidesModule.prototype.onBlogSubCategoryClick = function(event){
	Event.stop(event);
	var subCategory = Event.element(event);	
	
	this._listObjects.byCategory.currentPage = 1;
	this._listObjects.byCategory.tags = (subCategory.readAttribute('tag') != '') ? subCategory.readAttribute('tag') : '';
	this._listObjects.byCategory.headerName = subCategory.innerHTML + ' Articles';
	this._listObjects.byCategory.cacheKey = (this._listObjects.byCategory.tags != '') ? 'pd2-page-fragment-blogs-list-by-category-' + this._listObjects.byCategory.tags : '';
	this._listCurrent = this._listObjects.byCategory;
	
	pd_globalSiteFramework.trackEvent('Blogs', 'Sub Category - click', subCategory.innerHTML);
	
	this.loadBlogs();
}

// ----------------------------------------------------- //
// BLOG SEARCH FUNCTIONS
// ----------------------------------------------------- //
pdBuyingGuidesModule.prototype.onBlogSearchFocus = function(event){$('blogQuery').value = '';}
pdBuyingGuidesModule.prototype.onBlogSearchBlur = function(event){var input = $('blogQuery');if(input.value == ''){input.value = 'Search videos...';}}
pdBuyingGuidesModule.prototype.onBlogSearchEnterTyped = function (event){if(event.which || event.keyCode){if((event.which == 13) || (event.keyCode == 13)){this.onBlogSearch(event);}}}
pdBuyingGuidesModule.prototype.onBlogSearch = function(event){
	Event.stop(event);
	var searchTerms = $('blogQuery').value;

	if(searchTerms != '' && searchTerms != 'Search blogs...'){
		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-blogs-list-search-' + escape(searchTerms);	
	
		$('blog-tabs-blogs-search').show();	
			
		pd_globalSiteFramework.trackEvent('Blogs', 'Search - click', searchTerms);
		
		this.loadBlogs();
	}
}

// ----------------------------------------------------- //
// BLOG LIST LOADING & DISPLAY FUNCTIONS
// ----------------------------------------------------- //
pdBuyingGuidesModule.prototype.loadBlogs = function(){
	this.renderLoadingList();

	var request = {
		'sortField': this._listCurrent.sortField,
		'sortDesc': this._listCurrent.sortReverse,
		'pageIndex': this._listCurrent.currentPage, 
		'pageSize': this._listCurrent.pageLength,
		'sectionIds': this._listCurrent.sectionIds,
		'subSectionIds': this._listCurrent.subSectionIds,
		'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(this._channelId, 'getblogpages', request, this.onBlogsRetrieved.bind(this));	
}

pdBuyingGuidesModule.prototype.onBlogsRetrieved = function(objResponse){
	if(objResponse.pages.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.pages.length; i++){	
			var page = objResponse.pages[i];
			var pageName = (page.ShortTitle != null && page.ShortTitle.length > 0) ? page.ShortTitle.truncate(25) : page.PageTitle.truncate(25);

			var itemWrapper = new Element('div', {'class' : 'blogs-list-blog'});
			var itemBody = new Element('div', {'class' : 'blogs-list-blog-body'});				
			var imgWrapper = new Element('div', {'class' : 'blogs-list-blog-img tip-static-hover', 'tiptitle' : page.PageTitle.replace(/"/g,''), 'tipcontent' : page.MetaDescription.truncate(150).replace(/"/g,'')});
			var imgLink = new Element('a', {'href' : this._listCurrent.path + page.PageUrl + '.aspx'});

			var img = new Element('img', {'src' : page.ImageMedium});
			imgLink.appendChild(img);
			imgLink.observe('click', this.onBlogClick.bindAsEventListener(this, pageName));
			imgWrapper.appendChild(imgLink);
			itemBody.appendChild(imgWrapper);

			var titleWrapper = new Element('div', {'class' : 'blogs-list-blog-title'});
			var titleLink = new Element('a', {'href' : this._listCurrent.path + page.PageUrl + '.aspx'}).update(pageName);
			titleLink.observe('click', this.onBlogClick.bindAsEventListener(this, pageName));
			titleWrapper.appendChild(titleLink);
			itemBody.appendChild(titleWrapper);			

			var date = new Element('div', {'class' : 'blogs-list-blog-date'}).update(PDFormatShortDate(page.PublishDate));
			itemBody.appendChild(date);
			itemWrapper.appendChild(itemBody);

			resultList.appendChild(itemWrapper);
		}		
		
		this._listCurrent.resultList.update();
		this._listCurrent.resultList.appendChild(resultList);		
		this.resetPaging(objResponse.totalPages);	
		
		//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('Blogs', 'Search - not found', this._listCurrent.searchTerms);
	}
}

pdBuyingGuidesModule.prototype.onBlogClick = function(event, blogName){
	pd_globalSiteFramework.trackEvent('Blogs', 'Blog - click', blogName);	
}


// ----------------------------------------------------- //
// GENERIC RENDER FUNCTIONS
// ----------------------------------------------------- //
pdBuyingGuidesModule.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 blogs for you...');
	loadingWrapper.appendChild(loadingImage);
	loadingWrapper.appendChild(loadingText);
	
	this._listCurrent.pagingList.update();
	this._listCurrent.resultList.update();	
	this._listCurrent.resultList.appendChild(loadingWrapper);
}

pdBuyingGuidesModule.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 blogs for the current category or search term(s)');
	wrapper.appendChild(text);
	
	this._listCurrent.resultList.update();	
	this._listCurrent.resultList.appendChild(wrapper);
}

// ----------------------------------------------------- //
// GENERIC PAGING FUNCTIONS
// ----------------------------------------------------- //
pdBuyingGuidesModule.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);
		}
	}
}

pdBuyingGuidesModule.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;
}

pdBuyingGuidesModule.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.loadBlogs();
}
