/*
	Title: MLB.com Search Engine
	Desc: This code is intended for MLB Search functionality only!

	Company: MLB Advanced Media.
	Author: Sam Tsvilik
	Project: MLB Search
	Last Modified: 07/21/2008
	
	Dependencies: jQuery.js, bam.js, bam.tracking.js
*/
bam.loadSync(bam.homePath + "bam.dom.js", 
			 bam.homePath + "bam.url.js",
			 bam.homePath + "bam.ajaxHelper.js");

var VideoSearch = bam.ajaxHelper.createInstance(
(function() {
	var formatDuration = function(duration){ // converts HH:MM:SS to MM:SS
		var minSec = "";
		if (typeof(duration)==="string" && duration.length > 7){
			minSec = duration.substr(3,5);
		}
		return minSec;
	};
	
	var constructKeywords = function(k) {
		var _out = [];
		$.each(k, function() {
			if(!/game_pk|timecode_in/.test(this.type)) {
				_out.push(this.keyword);
			}
		});
		return _out.join(", ");
	};
	
	var _processNavigation = function() {				
		if(!!_self.results) {			
			var _totalRecords = parseInt(_self.results.total, 10);
			var _from = 0;
			var _to = 0;
			if(!!_totalRecords) {
				SearchNavigator.Paginate({
					Start: parseInt(_self.results.start, 10),
					PageSize: 12,
					SetSize: 10,
					TotalCount: _totalRecords
				});
				
				var _out = new bam.string.StringBuffer();
				_from = SearchNavigator.Start+1;
				_to = (SearchNavigator.Start+SearchNavigator.PageSize) > (SearchNavigator.TotalCount)?(SearchNavigator.TotalCount):(SearchNavigator.Start+SearchNavigator.PageSize);
				//First, previous 10, previous
				var _out = new bam.string.StringBuffer();
				//First
				if(SearchNavigator.First.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ 0)
						.append(",trackVal:'First'")
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">&laquo; First</a>");
				}
				//Prev 10
				if(SearchNavigator.SetCount > 1 && SearchNavigator.PreviousSet.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ SearchNavigator.PreviousSet.start)
						.append(",trackVal:'Prev 10'")						
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">&laquo; Prev "+SearchNavigator.SetSize+"</a>");
				}
				//Prev
				if(SearchNavigator.Previous.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ SearchNavigator.Previous.start)
						.append(",trackVal:'Prev'")						
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">&lsaquo; Prev</a>");
				}
				//Page items
				if(!!SearchNavigator.Pages.length) {
					var _cItem, _style = "";
					$.each(SearchNavigator.Pages, function() {
						_cItem = this;
						_style = _cItem.selected?"pageLink selectedLink":"pageLink";					
						_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
							.append("start:"+ _cItem.start)
							.append(",trackVal:'"+_cItem.page+"'")
							.append(",hitsPerPage:" + SearchNavigator.PageSize)
							.append(",hitsPerSite:" + SearchNavigator.SetSize)
							.append("})\" class=\""+ _style +"\">"+ _cItem.page + "</a>");
					});
				}
				//Next
				if(SearchNavigator.Next.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ SearchNavigator.Next.start)
						.append(",trackVal:'Next'")						
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">Next &rsaquo;</a>");
				}
				//Next 10
				if(SearchNavigator.SetCount > 1 && SearchNavigator.NextSet.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ SearchNavigator.NextSet.start)
						.append(",trackVal:'Next 10'")						
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">Next "+SearchNavigator.SetSize+" &raquo;</a>");
				}
				//Last
				if(SearchNavigator.Last.active) {
					_out.append("<a href=\"javascript: VideoSearch.NavigateTo({")
						.append("start:"+ SearchNavigator.Last.start)
						.append(",trackVal:'Last'")						
						.append(",hitsPerPage:" + SearchNavigator.PageSize)
						.append(",hitsPerSite:" + SearchNavigator.SetSize)
						.append("})\" class=\"navLink\">Last &raquo;</a>");
				}			
				
				$("#topResultsBar").html(_out.toString());
				$("#botResultsBar").html(_out.toString());
			} else {
				$("#divSearchResults").html("No Results");
			}
			//Query	String		
			$("#media_query").val((_self.results.queryString || ""));
			$("#searchResultsQuery").html((_self.results.queryString || ""));
			//Counts 
			var _counts = "Results (" + _from + " to " + _to + " of " + SearchNavigator.TotalCount + ")";
			$("#divSearchResultsCount").html(_counts);
			$("#divBotResultsCount").html(_counts);
		};
	};
	
	var _self = {
		//Settings
		async: false,
		type: "get",
		dataType: "json",
		//Events	
		onTimeout: function(ex) {
			alert("Search timed out!");
		},
		//Custom Code
		results: {},	
		LoadData: function() {
			var that = this;
			that.makeRequest(function(data) {
				_self.results = data;
			});
		},
		RenderResults: function() {
			_processNavigation();		
			if(!!_self.results.mediaContent) {
				var _out = $("#divSearchResults");
				_out.empty(); //Clear it
				var _itemTemplate = $("#video_item_template")[0];
				
				
				var _goToVideoPage = function(content_id, index){
					bam.tracking.track({
						async:{
							isDynamic    : true, 
							compName     : "Video Search Results Playlist", 
							compActivity : "Video Search Results Playlist Thumbnail " + (index+1),
							actionGen    : true
						}
					});
					location.href = "/media/video.jsp?content_id="+content_id;
				};				
				
				var _newItem, _mItem, that = this, _thumbSrc, _mLen = _self.results.mediaContent.length-1;
				$.each(_self.results.mediaContent, function(idx) {
					_mItem = this;
					_newItem = $(_itemTemplate.cloneNode(true));
					if(idx === _mLen) { //Removes a border under last item(s)
						if(((_mLen+1) % 2) > 0) {
							_newItem.css({border: 0}); 
						} else {
							_newItem.css({border: 0});
							_out.find(".video_item:eq(" + (_mLen-1) + ")").css({border: 0});
						}
					}
					_newItem.removeAttr("id");
					_newItem.find(".title a").html(_mItem.title).attr("href", "/media/video.jsp?content_id="+_mItem.contentId).click(function(id, curIndex){ return function(){ _goToVideoPage(id, curIndex); return false; } }(this.contentId, idx));
					_newItem.find(".body .image .play").attr("id",_mItem.contentId).click(function(id, curIndex){ return function(){ _goToVideoPage(id, curIndex); } }(this.contentId, idx));
					_thumbSrc = (!!_mItem.thumbnails && 
								 bam.object.typeOf(_mItem.thumbnails) === "array" &&
								 !!_mItem.thumbnails.length &&
								 _mItem.thumbnails[0].src) ? _mItem.thumbnails[0].src : "/components/search/images/img_noimage.gif";
					_newItem.find(".body .image img")
						.attr("src", _thumbSrc)
						.hover(function(){ $(this).css({cursor:"pointer"}); }, function(){ $(this).css({cursor:"default"}); })
						.click(function(id, curIndex){ return function(){ _goToVideoPage(id, curIndex); } }(this.contentId, idx));
					_newItem.find(".blurb").append(_mItem.bigBlurb);
					_newItem.find(".blurb .date_duration .added").html(_mItem.date_added);
					_newItem.find(".blurb .date_duration .duration").html(formatDuration(_mItem.duration));
					_newItem.find(".tags").append(constructKeywords(_mItem.keywords));
					_out.append(_newItem);
				});
				_out.append("<div class=\"clear\"></div>");
				//Replace all non-existent images with blanks
				$(".body .image img").one("error", function() {				
					$(this).attr("src", "/components/search/images/img_noimage.gif");
				});				
			}
		},		
		NavigateTo: function(opt) {
			var req = bam.url.Location(window.location);
			var _qs = req.getParams();			
		    $.extend(_qs, opt); //Overwrite some existing attributes			
			if(!!_qs.text && !opt.text && !!_self.results.queryString) { _qs.text = _self.results.queryString; }
			if(_qs.start === -1 || SearchNavigator.Start !== _qs.start) {
				/*
				bam.tracking.track({
					async:{
						isDynamic    : true, 
						compName     : "Video Search Results Playlist", 
						compActivity : "Video Search Results Page " + _qs.trackVal,
						actionGen    : true
					}
				});
				*/
				_qs.start = (_qs.start < 0)?0:_qs.start;
				var _url = "/search/media.jsp" + bam.url.buildSearch(_qs);
				location.href = _url;
			}
		}
	};
	
	return _self;
})());