//creates a tab object,  fires the event 'tab:select' when clicked.
Tab = Class.create({
    initialize:function(element) {
        this.element = $(element).observe('click', this.markSelected.bindAsEventListener(this));
    },
    markSelected:function(evt){
    	if (evt) evt.stop();

    	this.element.fire('tab:select', {tab: this});
      this.element.addClassName('selected');
     // alert(WWE.Video.NewsTout);
      if (typeof WWE.Video.NewsTout != 'undefined')
      {
        WWE.Video.NewsTout.ToggleTVShowsVisibility(this.element.parentNode.id);
        WWE.Video.NewsTout.ToggleTalentFilterVisibility(this.element.parentNode.id);
      }
	},
    deSelect:function() {
        this.element.removeClassName('selected');
    }
});

//manages loading and clearing of tab collections
TabManager = Class.create({
    initialize: function(tabs){

        var query = new String(window.location.search).parseQuery();

        this.tabs = tabs.collect(function(n) { return new Tab(n); });
        $(document).observe('tab:select', this.clearTabs.bindAsEventListener(this));
        this.clearTabs();
        this.selectTab(query.activeTab);
    },
    //selects the specified tab.  accepts either internal tab items or ids.
    selectTab: function(tab){
        if (typeof tab == 'object') tab.markSelected();
        else if (typeof tab == 'string' || typeof tab == 'number') this.tabs[tab].markSelected();
        else this.tabs[0].markSelected();
    },
    clearTabs: function(){
    	this.tabs.invoke('deSelect');
    }
});

VideoGalleryView = Class.create({
	initialize:function(json){
		this.json = json;
    	json.elapsedTime = this.getElapsedTime(true);
    	json.liveDate = this.getElapsedTime(false);
    	json.moreEpisodesLink = this.getMoreEpisodesLink(json.videoGalleryUrl);
    	var truncatePoint = 34;
    	try {
	    	if ((json.fullName.length > 34) && (json.fullName.lastIndexOf(" ",34) != -1)) {
    		truncatePoint = json.fullName.lastIndexOf(" ",34) + 3;
	    	}
    	} catch (e) {}
    	json.truncFullName = json.fullName.truncate(truncatePoint);
		json.duration = this.getDuration();
	},
	indexTemplate: new Template('\
		<a href="#{path}" style="z-index:1000;"><img height="66" width="88" class="galleryThumbnail" src="#{thumbPath}" alt="#{fullName}"/></a>\
		<dl>\
			<dt><a class="galleryListingTitle" href="#{path}">#{truncFullName}</a></dt>\
			#{liveDate}\
		</dl>\
	'),
      //For 9-22\
      //<dd class="galleryListingViews">#{views} views</dd>\
      //<dd>rater</dd>\

	detailTemplate: new Template('\
		<dl>\
			<dt id="mediaDetails-description">#{fullName}</dt>\
			#{elapsedTime}\
    </dl>\
	'),
      //For 9-22\
      //<dd id="mediaDetails-length">#{duration}</dd>\
      //<dd id="mediaDetails-views">#{views} views</dd>\

	exclusiveTemplate: new Template('\
		<h4>#{show}</h4>\
		<a href="javascript:void(0);" style="z-index:1000;" class="galleryListingTitle"><img src="#{thumbPath}" width="88" height="66" alt="#{fullName}" class="galleryThumbnail" /></a>\
		<dl>\
			<dt><a href="javascript:void(0);" class="galleryListingTitle">#{truncFullName}</a></dt>\
			#{liveDate}\
	  </dl>\
	  <div class="clear">&nbsp;</div>\
	  <p class="videoDescription">#{description}</p>\
		#{moreEpisodesLink}\
	'),



      //For 9-22\
      //<dd class="galleryListingViews">#{views} views</dd>\
      //<dd>rater</dd>\

	getMoreEpisodesLink : function(videoGalleryUrl)
	{
		var moreEpisodesLink = '&nbsp;';
		if (typeof(videoGalleryUrl) != 'undefined' && videoGalleryUrl != null && videoGalleryUrl != '')
		{
			moreEpisodesLink = '<p style=\"position:relative;\"><a href=\"' + videoGalleryUrl + '\" class=\"moreEpisodes\">More Episodes</a></p>';
		}
		return moreEpisodesLink;
	},

  getElapsedTime : function(includeDuration)
  {
    try
    {
      var todayDate = new Date();
      var elapsedTime = '';

      var duration = this.getDuration();
      var serverDate = this.json.publishedDate;

      if (serverDate != '')
      {
        var year = serverDate.substr(0, 4);
        var month = parseInt(serverDate.substr(5, 2), 10) - 1;
        var day = parseInt(serverDate.substr(8, 2), 10);

        var hours = serverDate.substr(11, 2);
        var minutes = serverDate.substr(14, 2);
        var seconds = serverDate.substr(17, 2);

        var liveDate = new Date(year, month, day, hours, minutes, seconds);

        elapsedTime = WWE.DateHelper.getElapsedTime(liveDate, todayDate)

        if (includeDuration)
        {
          if (elapsedTime != '' && duration != '')
          {
            duration = ' | ' + duration;
            elapsedTime = elapsedTime + duration;
          }
        }
      }
      else
      {
        if (includeDuration)
        {
          elapsedTime = duration;
        }
      }
      if (elapsedTime == '')
      {
      	elapsedTime = '&nbsp;';
      }
      return '<dd class=\"mediaDetailsPublishedDate\">' + elapsedTime + '</dd>';

    }
    catch(exception)
    {
      return '';
    }

  },

	getDuration:function()
  {
    var timeMessage = '';


    if ((typeof(this.json.hours) != 'undefined') &&
        (typeof(this.json.minutes) != 'undefined') &&
        (typeof(this.json.seconds) != 'undefined'))
    {
      if (this.json.hours != '' && this.json.minutes != '' && this.json.seconds != '')
      {
        var hours =   (this.json.hours.length == 1)   ? ('0' + this.json.hours)   : this.json.hours;
    		var minutes = (this.json.minutes.length == 1) ? ('0' + this.json.minutes) : this.json.minutes;
    		var seconds = (this.json.seconds.length == 1) ? ('0' + this.json.seconds) : this.json.seconds;

        if (hours != '00')
        {
          timeMessage += hours + ':' + minutes + ':' + seconds;
        }
        else if (minutes != '00')
        {
          timeMessage  = minutes + ':' + seconds;
        }
        else
        {
          timeMessage = '00:' + seconds;
        }
      }
    }

		return timeMessage;
	},

	videoLinkClicked: function(evt){
		evt.stop();
		evt.element().fire('videolink:click', this.json);
	},
	getIndex:function(){
		var shim = new Element('div');
		shim.update(this.indexTemplate.evaluate(this.json));

		var anchor = shim.select('a').each(function(n){
			n.observe('click', this.videoLinkClicked.bindAsEventListener(this));
		}, this)
		return shim;
	},
	getExclusive:function(){
		var shim = new Element('div', {'class': 'galleryExclusive'});

		shim.update(this.exclusiveTemplate.evaluate(this.json));
		var anchor = shim.select('a.galleryListingTitle').each(function(n){
			n.observe('click', this.videoLinkClicked.bindAsEventListener(this));
		}, this)
		return shim;
	},
	getDetail:function(){
		return this.detailTemplate.evaluate(this.json);
	}
});

PhotoGalleryView = new Class.create({
	initialize:function(json){
		this.json = json;
	},
	photoIndexTemplate: new Template('\
		<img src="#{thumbPath}" alt="#{fullName}" class="galleryThumbnail" />\
		<dl>\
			<dt><a href="#{path}" class="galleryListingTitle">#{title}</a></dt>\
			<dd>#{publishedDate}</dd>\
			<dd class="galleryListingViews">#{photoTotal} photos</dd>\
			<dd>test</dd>\
		</dl>\
	'),
	photoDetailTemplate: new Template('\
		<div id="mediaDetails">\
			<dl>\
				<dt>#{title}</dt>\
				<dd>#{publishedDate}</dd>\
				<dd>#{photoTotal} photos</dd>\
			</dl>\
			<div id="rater">\
				rater</div>\
		</div>\
	'),
	getPhotoIndex: function(){
		var shim = new Element('div');
		shim.update(this.photoIndexTemplate.evaluate(this.json));

		var anchor = shim.select('.galleryListingTitle')[0];
		anchor.observe('click', function(evt) {
			evt.stop();
			evt.element().fire('photolink:click', {json:this.json});
		}.bindAsEventListener(this));
		return shim;
	},
	getPhotoDetail: function(){
		return this.photoDetailTemplate.evaluate(this.json);
	}
})

Rater = Class.create({
	initialize:function(id, votes, rating, size, state){
		this.element = new Element('div', { id: size + "Voter"});
		this.element.appendChild(new Element('div', {'class': 'voterText'}).update('Rate:'));
		var list = new Element('ol', {'class':'rater'});
		list.appendChild( new Element('li', { 'class': 'rating', width: rating + 'px'}));

		var links = new ObjectRange(1,5).collect(function(n) {
			var li = new Element('li').update(new Element('a',
				{'class':this.alts[n], alt:this.alts[n]} ));
			this.list.appendChild(li);
		}, {list:list, id:id, alts:["one", "two", "three", "four", "five"]})

		var state = new Element('div', { 'class': state }).update(list);
		var votes = new Element('div', {'class': 'voterText'}).update("("+votes+")")
		this.element.appendChild(state);
		this.element.appendChild(votes);
	}
})

//implements paging, tabbing, layout views, ajax loads/caching, etc.
NewsTout = Class.create({
	initialize:function(element, view){
		this.settings = new WWE.Cookie(document, ".video", null, '/', host);
		if (!this.settings.load()) this.settings.store();

		//paging info
		this.resultsPerPage = 9;
		this.pages = [];
		this.page = 0;
		this.allResults = false;

		//gallery root
		this.element = $(element);
		this.view = view;

		//list root.  pictures are renders within it
		this.itemRoot = this.element.select('.itemRoot')[0];
		this.cachedResults = {};
		this.pageContents = {};
		this.pageJSON = {};

		//TODO: remove exclusives hack
		this.renderAsExclusive = $A();
		//used for talent tabs
		this.currentTabHREF = '';

		$(document).observe('tab:select', this.getPage.bindAsEventListener(this));
		this.tabManager = new TabManager(this.element.select('.galleryTabs li a'));
		this.toggleViewBtn = $('galleryListTools').select('.galleryView')[0].observe('click', this.toggleView.bindAsEventListener(this));

    // initialize properties for arrays of divas/superstars, these are later set in superstarslistjs.jsp and divaslistjs.jsp
    this.divaList = [];
    this.superStarList = [];

    // setup array of talent selection tabs by 'name' so that they are not hardcoded in multiple places.
    // consider making these dynamic somehow by retrieving and associating this javascript from the server side instead of having these hard-coded values
    this.talentFilters = [];
    this.talentFilters[0] = {'filterTypeSpanText' : 'Diva Search: ', 'filterTypeName' : 'tabdivas', 'filterList' : this.divaList};
    this.talentFilters[1] = {'filterTypeSpanText' : 'Superstar Search: ', 'filterTypeName' : 'tabsuperstars', 'filterList' : this.superStarList};

    // acquire reference to the talent filter container
    this.talentFilterContainerElement = $('talentFilterContainer');

    // set up the current tab, on first load this is not set
    // TODO: making this dynamic
    this.activeTabName  = 'tabfeatured';

    // set up container for talent list filter results
    this.talentFilterResultsContainer = $('talentListResultsContainer');

    // set up filter text box reference and add in hook for keyup
    this.talentFilterTextbox = $('talentFilterTextbox');
    this.talentTypeSpan = $('talentTypeSpan');

    this.talentFilterTextbox.observe('keyup', function(event) {
      WWE.Video.NewsTout.talentFilterKeyUp(WWE.Video.NewsTout.talentFilterTextbox);
    });

	}, // end method initialize


	//toggles an id on listRoot
	toggleView:function(evt){
		var target = evt.findElement('li');
		if (target.hasClassName('on')){
			target.removeClassName('on');
			this.itemRoot.id = 'galleryThumb';
		} else{
			target.addClassName('on');
			this.itemRoot.id = 'galleryList';
      //this.getData(this.currentTabURL);
		}
	},
	fireLoadEvt:function(){
		this.element.fire('newstout:pageload', this.pageContents.items.item);
	},
	//loads a page from the cache if available, otherwise pulls from tabs href attribute.
	getPage: function(evt){
		this.currentTabURL = evt.element().rev;

		var tab = evt.findElement('li');
		if (Object.isElement($('pagination'))) $('pagination').update();
		if (tab.id == 'tabExclusives'){
			this.renderAsExclusive.push(this.currentTabURL);
		}
    this.activeTabName = tab.id.toLowerCase();
		this.getData(this.currentTabURL);
	},
	getData:function(url)
  {
	  // ensure that we reset the page number and remove show all
    this.allResults = false;
    this.page = 0;

  	if (this.isCached(url)) {
			this.buildPage(this.cachedResults[url]);
		}
		else{
      var ajaxLoaderImageSrc;

      if (this.itemRoot.id != 'galleryList')
        ajaxLoaderImageSrc = 'ajax-loader.gif';
      else
        ajaxLoaderImageSrc = 'ajax-loader-white.gif';

      this.itemRoot.update('<img src=\"/images/common/spinners/' + ajaxLoaderImageSrc + '\" width=\"32\" height=\"32\" alt=\"Loading...\" />');
			new Ajax.Request(url, { method:"get",
				onSuccess:this.buildPage.bindAsEventListener(this),
				onException:function(request, e){ throw(e); }
			});
		}
	},
	getPages: function(json) {

    var pages = [];

    if (!json.items.item.length)
    {
      // json returned from MT for single result is an item and not an array
      // so we'll need to mimic the same return structure using this trick
      pages.push([json.items.item]);
    }
    else
    {
     	this.numberOfPages = Math.ceil(json.items.item.length / this.resultsPerPage);
  		pages = [];
  		arr = [];
  		for(var p=0; p < this.numberOfPages; p++) {
  			arr=[];
  			for(var i=0; i < this.resultsPerPage; i++) {
  				if(typeof(json.items.item[p * this.resultsPerPage+i]) != 'undefined')
  					arr[i] = json.items.item[p * this.resultsPerPage+i];//console.log(i + ' =' + $H(json.items.item[p * this.resultsPerPage+i]).inspect());
  			}
  			pages[p] = arr;
  		}
    }

		return pages;
	},
	loadPage: function(index) {
		this.allResults = false;
		this.page = index;
		this.renderItemsJSON();
	},
	showAll: function() {
		this.page = -1;
		this.allResults = true;
		this.renderItemsJSON();
	},
	nextPage: function() {
		this.allResults = false;
		this.page++;
		if(this.page > this.numberOfPages-1) this.page = 0;
	},
	//renders the contents of a tab
	buildPage: function(response){
    this.page = 0;

    this.url = response.request.url;
   //alert(this.activeTabName + this.url +"response"+ response);
    //if (this.activeTabName == 'tabtv shows') {
      if (!this.isCached(this.url))
		this.cachedResults[this.url] = response;
	//}

	if (response.responseJSON != null){
		  //if (!this.isCached(this.url))
			//this.cachedResults[this.url] = response;

	      if ((typeof(response.responseJSON.metrics) != 'undefined') &&
	          (typeof(response.responseJSON.metrics.lists) != 'undefined') &&
	          (typeof(response.responseJSON.metrics.lists.list) != 'undefined'))  {
	        this.lists = response.responseJSON.metrics.lists.list;
	      } else  {
	        this.lists = [];
	      }

        this.pageJSON = response.responseJSON;
		this.buildSorts();

		this.renderItemsJSON();
		this.fireLoadEvt();
	} else {
		this.pageJSON = null;
		$('gallerySortOptions').update();
		this.itemRoot.update(response.responseText);
	}
	},
	buildPagination: function()
	{
		var friendlyPageNumber = 0;

		if (this.numberOfPages > 1)
    {
      var pagination = '';
      for(var i=0; i < this.numberOfPages; i++)
      {
      	friendlyPageNumber++;

      	pagination += '<li>'
      	if (i != this.page)
      	{
      		pagination += '<a href="javascript:WWE.Video.NewsTout.loadPage(' + i + ');">' + friendlyPageNumber + '</a>';
      	}
      	else
      	{
      		pagination += friendlyPageNumber;
      	}

        if (friendlyPageNumber < this.numberOfPages)
        {
        	pagination += ',&nbsp;';
       	}

        pagination += '</li>';
      }

      pagination += '<li>&nbsp;|&nbsp;'
      var showAllText = 'Show All';

      if (!this.allResults)
      {
      	pagination += '<a href=\"javascript:WWE.Video.NewsTout.showAll();\">' + showAllText + '</a></li>';
      }
      else
      {
      	pagination += showAllText;
      }

      pagination += '</li>';

      if(Object.isElement($('pagination')))
      {
        $('pagination').update(pagination);
      }
      else
      {
        $('galleryListing').insert('<ol id="pagination">'+pagination+'</ol>')
      }
    }
    else
    {
    	if (Object.isElement($('pagination')))
    	{
    		$('pagination').update('');
    	}
    }

	},
	//uses this.pageJSON to build the sort list.
	//stores the results of the first sort or the specified sort into pageContents
	buildSorts: function(listId){
		this.page = 0;
		this.allResults = false;
		var JSON = this.pageJSON.metrics.lists.list;
    var displaySortingOptions = true;

    // Sometimes json will come back in a different format when there is only one default sorting type..
    // In this case, for the code below to work properly, we need to convert the json into an array as it
    // expects it in this format.. and the java serializer does not do this for us.
    if (!JSON.length)
    {
      JSON = [JSON];
      displaySortingOptions = false;
    }

		//obj to be passed into the Enumerator incrementer
		var contextObj = {
			that: this,
      header: new Element('h3').update('Sort By:'),
			root: new Element('ul'),
			count:JSON.length,
			listId: listId,
			activeIndex:0
		};


    $('gallerySortOptions').update('');

    //create a list item and anchor or span for each list (bound to contextObj);

    if (displaySortingOptions)
    {
      JSON.each(function(n, i){
        var child;
        if (n.listId == this.listId || (Object.isUndefined(this.listId) && i == 0) ) {
          this.activeIndex = i;
          child = new Element('span').update(n.listName)

        } else {
          child = new Element('a', {href:'javascript:;'})
            //sort on click
            .observe('click', this.that.sort.bindAsEventListener({that:this.that, listId:n.listId}))
            .update(n.listName);
        }
        this.root.appendChild(new Element('li', {'class': (i == this.count - 1) ? 'last' : ''}).update(child));
      }, contextObj);

      $('gallerySortOptions').appendChild(contextObj.header);

      $('gallerySortOptions').setStyle({display:'block'});
    }
    else
    {
      if (this.activeTabName == 'tabdivas' || this.activeTabName == 'tabsuperstars')
      {
        $('gallerySortOptions').setStyle({display:'none'});
      }
      else
      {
        contextObj.root.appendChild(new Element('li', {'class':'last'})).update('&nbsp;');
        $('gallerySortOptions').setStyle({display:'block'});
      }
    }

    $('gallerySortOptions').appendChild(contextObj.root);
		this.pageContents = JSON[contextObj.activeIndex];
	},
	//this is bound to {that:PhotoTout, listId:sortId}
	sort: function(evt){
    this.that.lists.each(function(list, index) {
      if (list.listId == this.listId)
      {
        WWE.Video.playlist = this.that.lists[index].items.item;
      }
      }, this);

    this.that.page = 0;

		this.that.renderItemsJSON(this.that.buildSorts(this.listId));
	},
	//takes a json object, iterates through it and renders html for each.
	renderItemsJSON: function(url){

  	if (typeof(url) == 'undefined' || url == null)
  	{
  		url = this.url;
  	}

		var shim = new Element('ul');
		if(this.allResults)
			this.pages[this.page] = this.pageContents.items.item;
		else
			this.pages = this.getPages(this.pageContents); //need method to turn this off for "show all"

		this.pages[this.page].each( function(item, i) {
			var li = new Element('li');
      var index = new this.that.view(item);
      li.insert(index[this.renderMethod]());
			this.shim.appendChild(li);
		}, {that:this, shim:shim, renderMethod : (this.renderAsExclusive.indexOf(url) > -1) ? "getExclusive" : "getIndex" });

		var breakDiv = new Element('div').addClassName('clear').update("&nbsp;");

		this.itemRoot.update(shim);
		this.itemRoot.appendChild(breakDiv);



		this.setBorders();
		this.buildPagination();
	},
	//returns host?query
	createURL:function(host, query) {
		return [host, '?', Object.toQueryString(query)].join('');
	},
	//return protocol + host + path - the query params
	stripQuery:function(url) {
		var i = url.indexOf('?');
		if (i > -1) return url.substr(0, url.indexOf('?'));
		return url;
	},
	isCached: function(url) {
		return !Object.isUndefined(this.cachedResults[url]);
	},
	setBorders: function() {
		RUZEE.ShadedBorder.create({ corner:4 }).render(this.itemRoot.select('li'));
	},

  /// <summary>
  ///   Fires when the user releases a key while the focus is set to the talent filter text box. will search through the list of talents according to the current active tab
  ///   and display any matches in a div below the textbox
  /// </summary>
  ///
  talentFilterKeyUp: function(filterElement) {
		var filterText = filterElement.value.toLowerCase().strip();
		var talentListHtml = '';

		/*
		var testString = "John Cena";
		var testSubString = "John C";
		var regExp1 = new RegExp("^"+testSubString+".*$", "i");
		alert(regExp1.test(testString));
		*/

		// if user entered in some text.. lets filter it
		if (filterText != '') {
			// get our current list for the appropriate current tab
			var talentList = this.getCurrentTalentList();

			var filteredTalent = [];

			// loop through each talent in the list, and see if it contains the user-entered data
			talentList.each(function(talent) {

		        // strip excessive whitespace
		        var name = talent.talentFilterText;
		        var tmp = name.split(" ");
		        var tmpLength = tmp.length;
		        var count = 0;
		        var input = filterText.replace(/\s{2,}/, " ");

		        var regExp = new RegExp("^("+input+".*)$", "i");
		        if (regExp.test(name)) {
			     	filteredTalent.push(talent.talentName);
			     	return;
			    } else if(tmpLength >= 0) {
		        	for(var i=0; i < tmpLength; i=(i+1)) {
		        		if (tmp[i].startsWith(input)) {
		        			filteredTalent.push(talent.talentName);
		        			i = tmpLength;
		        			break;
		        		}
		        	}
		        	return;
			    }
			});

			// loop through our filtered array of talents and create our html
			filteredTalent.sort();
			filteredTalent.each(function(talentName) {
				talentListHtml += '<li><a href=\"javascript:WWE.Video.NewsTout.loadTalent(\'' + talentName + '\')\"><strong>' + talentName + '</strong></a></li>';
			});

			// display our html in the results container if we have any filtered talents
			if (talentListHtml != '' && talentListHtml != null && typeof(talentListHtml) != 'undefined') {
				talentListHtml = '<ul id=\"talentList\">' + talentListHtml + '</ul>';
				this.talentFilterResultsContainer.innerHTML = talentListHtml;
				this.talentFilterResultsContainer.removeClassName('hidden');
			} else {
				this.talentFilterResultsContainer.innerHTML = "";
				this.talentFilterResultsContainer.addClassName('hidden');
			}
		} else {
			this.resetTalentFilter();
		}

	},	// end method talentFilterKeyUp

  /// <summary>
  ///   resets the talent filters and then loads a talent's profile information
  /// </summary>
  ///
  loadTalent : function(talentName)
  {

    this.resetTalentFilter();
    var uri = this.currentTabURL + "/leaftalenttag/" + talentName + ".json";
    this.getData(encodeURI(uri));

  }, // end method loadTalent


  /// <summary>
  ///   gets the current filter list based on the currently selected tab
  /// </summary>
  ///
  /// <remarks>
  ///   Retrieves an array of 'talent' based off of the mapping located at this.talentFilters where filterTypeName is the same as the name of the active tab
  /// </remarks>
  ///
  getCurrentTalentList : function()
  {

    var talentList = [];

    var filterTypesLength = this.talentFilters.length;

    // loop through our custom filter types and see if we find a matching key by activeTabName
    for (var a = 0; a < filterTypesLength; a++)
    {
      if (this.talentFilters[a].filterTypeName == this.activeTabName)
      {
        // found a match, set the talent list to this filter list
        talentList = this.talentFilters[a].filterList;
        break;
      }
   }

   return talentList;

  }, // end method getCurrentTalentList

  /// <summary>
  ///   Toggles the visibility of the talent selection container element after a video tab element is clicked
  /// </summary>
  ///
  /// <remarks>
  ///   Checks the passed in category name value against an array of category name values (NewsTout.talentFilters). If a match is found,
  ///   the talent selection container elements has the 'hidden' classname removed. If a match is not found, the 'hidden' classname is added.
  /// </remarks>
  ///
  ToggleTalentFilterVisibility : function()  {

    var showFilterContainer = false;
    var filterTypesLength = this.talentFilters.length;
    var talentTypeSpanText = '';

    // loop through our custom filter types and see if we find a matching key by activeTabName
    for (var a = 0; a < filterTypesLength; a++){
      if (this.talentFilters[a].filterTypeName == this.activeTabName) {
	        talentTypeSpanText = this.talentFilters[a].filterTypeSpanText;
	        showFilterContainer = true;
	        break;
      }
   }

   if (showFilterContainer)  {
	    this.resetTalentFilter();
	    this.talentFilterContainerElement.removeClassName('hidden');
	    this.talentTypeSpan.innerHTML = talentTypeSpanText;
   } else {
      this.talentFilterContainerElement.addClassName('hidden');
   }
  }, // end method ToggleTalentSelectionVisibility

  ToggleTVShowsVisibility : function()  {
     this.tvShowContainerTopElement = $('galleryNewSubNav');
     this.tvShowContainerElement = $('gallerySubNav');
     this.tvShowContainerElement.addClassName('hidden');

     this.tvshowArr = ["tabtv shows"];
     var subTabUrl = createSubTabArray();
     for(i=0;i<subTabUrl.length;i++)
     	this.tvshowArr[this.tvshowArr.length] = subTabUrl[i].toLowerCase();

     // if activeTabName is Tv Shows
     for (var a = 0; a < this.tvshowArr.length; a++){
	     if (this.tvshowArr[a] == this.activeTabName) {
	         this.tvShowContainerElement.removeClassName('hidden');
	          this.tvShowContainerTopElement.removeClassName('hidden');
	         break;
	  	 } else  {
	     	this.tvShowContainerElement.addClassName('hidden');
	     	 this.tvShowContainerTopElement.addClassName('hidden');
	     }
	 } //end of for

	 // select default show for TVShows [first one is displayed by default]
     if ("tabtv shows" == this.activeTabName) {
     	 this.tabManager.selectTab(5);
     }
  }, // end method ToggleTVShowsVisibility

  /// <summary>
  ///   Resets the various talent filtering controls
  /// </summary>
  ///
  resetTalentFilter : function()
  {
    // clear the text for our filter textbox
    this.talentFilterTextbox.value = '';

    // hide our filter results
    this.talentFilterResultsContainer.addClassName('hidden');

    // remove the innerHtml from the results
    this.talentFilterResultsContainer.innerHTML = '';

  } // end method resetTalentFilter

});

VideoPlayer = Class.create({
	initialize:function(element, playlistURL, isWmvVideo, brandImageMappings){
		this.isReady = false;
		this.geoipJson = null;
		this.element = $(element);
		this.playlist = null;
		this.nowPlaying = 0;
		this.currentObjectId = 0;
		this.isBuilt = false;
		this.isFlashable = false;
		this.buildPlayer();
		this.defaultActiveTab = 'tabfeatured';
		this.lists = [];
		// initialize the default title of this browser
	    this.defaultTitle = 'WWE: Mediaplayer > ';
	    // initialize show images mapping
	    this.showImagesMapping = brandImageMappings;
	    // initialize and default brand images
	    this.defaultBrandBackgroundImage = '';
	    this.defaultBrandShowImage = '';

	    // look throuh the list of mappings for the default value
	    var mappingLength = this.showImagesMapping.length;
		for (var a = 0; a < mappingLength; a++)
		{
		  if (this.showImagesMapping[a]['brand'].toLowerCase() == 'default')
		  {
				this.defaultBrandBackgroundImage = this.showImagesMapping[a]['pageBackgroundUrl'];
				this.defaultBrandShowImage = this.showImagesMapping[a]['logoSourceUrl'];
				break;
		  }
		}

		// we don't want to build the player if we're launch a wmv video... if we build it it'll set up the
		// player and play nothing, so we'll want to display a graphic instead and that is handled by the openWmv call in videogallery.js
		if (!isWmvVideo)
		{
		  new Ajax.Request(playlistURL, { method:'get', onSuccess:function(response){
		    if (!Object.isUndefined(response.responseJSON))
		    {
		      this.playItem(eval(response.responseJSON.item));
		    }
		  }.bind(this)});
		}
		else
		{
		  new Ajax.Request(playlistURL, { method:'get', onSuccess:function(response){

		  }.bind(this)});
		}
		//For 9-22\
		//WWERatings.initilize();

		$(document).observe('newstout:pageload', this.pageLoaded.bindAsEventListener(this));
		$(document).observe('videolink:click', this.playRequested.bindAsEventListener(this));
	},

	/**
	 * This should probably be moved into global.js
	 */
	isInternal: function(location) {
		var part = "http:\/\/(www(([0-9]+)?\.(dev|qa|stage|ms|pr1ms1|d1msdev2|q1stage1)([0-9]+)?)?\.wwe\.com)|localhost";
		var regExp = new RegExp("^"+part, "i");
		return regExp.test(location);
	},

	buildPlayer: function(){
		var params = window.location.href.toQueryParams();
		var debug = params.debug;
		var progId = (typeof(params.progId) != 'undefined' && this.isInternal(window.location.href)) ? params.progId : "";
		var isDebug = '0'; //(debug == 1 && this.isInternal(window.location.href)) ? '1' : '0';

		var so = new SWFObject("/swf/vp_videoplayer.swf", "WWEVideo", "628", "394", "10.0", "#000000");
		so.addParam("allowFullScreen", "true");
		so.addParam("allowScriptAccess", "always");
		so.addParam("WMode", "Opaque");
		//so.addVariable("showDim", false);
     	so.addVariable("config", "/swf/config.xml");
     	so.addVariable('debugMode', isDebug);
     	so.addVariable('progId', progId);
		this.isFlashable = so.write(this.element.id);
		this.isBuilt = true;
	},

	setupLB:function(){
		this.Overlay = '<div id="overlay" style="display:none"></div>\
						<div id="box" style="background-color: #000000;background-image: none;display: none">\
						<div id="boxContents">\
							<iframe id="lbFrame" name="sl" width="800" height="525" frameborder="0" scrolling="no" marginwidth="0" marginheight="0" src=""></iframe></div>\
						</div>';
		var overlay = new Element('div').update(this.Overlay);
		document.body.appendChild(overlay);
		//document.body.innerHTML += this.Overlay;
		this.LBFrame = $('boxContents').select('iframe')[0];

		$('mediaDetails').select('.lbOn').each(function(n) {
			n.observe('click', function(evt) {
				evt.stop();
				Lightbox.initFrame(this);
				Lightbox.showBoxByIFrame(evt.element().href, 0, 0, evt.element());
			}, this.LBFrame )
		});
	},
	playItem:function(item, index)
    {
		if (!this.isReady || this.geoipJson == null) {
			window.setTimeout(this.playItem.bind(this, item, index), 250);
		  return;
		}
		
		window.scrollTo(0, 0);

		if (!this.isFlashable) {
			return;
		}
		
		if (typeof(this.geoipJson) != null && this.geoipJson.group == 3) {
			//document.title = this.geoipJson.title = this.defaultTitle + 'Test name';
			thisMovie("WWEVideo").playVideo(this.geoipJson);
			return;
		} 
		
		this.nowPlaying = index ? index : this.findInPlaylist(item);
		var regExp = new RegExp("\\.flv$|\\.mp4$|\\.f4v$");
		if (item.videoUrl == '' || typeof(item.videoUrl) == 'undefined' || !regExp.test(item.videoUrl.toLowerCase())) {
	      	this.advancePlayList();
	      	var url = 'http://gen.wwe.com/trac/gif.php?PIXID=23&Str1=' + WWE.Video.NewsTout.pageContents.listId + '&Str2=' + item.objectId;
	      	new Ajax.Request(url);
	      	return;
	    }

		var activeTab = this.defaultActiveTab;
		var title = this.defaultTitle + item.fullName;
		var show = '';

		if (typeof(WWE.Video.NewsTout) != 'undefined')
		{
			activeTab = WWE.Video.NewsTout.activeTabName;
		}
		if (item.show != '' || typeof(item.show) != 'undefined')
		{
			show = item.show.replace(/\s+/g, "");
		}

		var adUrl = "http://ad.doubleclick.net/pfadx/wwe.video/" + activeTab.substring(3) + ";show=" + show + ";objid=" + item.objectId + ";dcopt=ist;tile=1;sz=320x302;vplayer=flv;dcove=d";

      	//thisMovie("WWEVideo").changeAd(adUrl);
		
		item.id = item.objectId;
		item.title = item.fullname;
		item.url = item.videoUrl;
		item.descriptionURL = item.videoUrl;
		item.categories = item.show;
		item.keywords = item.show;
		item.google = {};
		item.google.channel = item.show;
		item.google.videoId = item.objectId;
		item.adParams = {};
		item.adParams.sitename = 'wwe.video';
		item.adParams.zone = activeTab.substring(3);
		item.adParams.show=show.toLowerCase();
		item.adParams.objid=item.objectId;

		/*
		var i = {
			id : item.objectId,
			title : item.fullname,
			url : item.videoUrl,
			descriptionURL : item.videoUrl,
			categories : item.show,
			keywords : item.show,
			videoUrl : item.videoUrl,
			show : item.show,
			google : {
				channel : item.show,
				videoId : item.objectId
			},

			adParams : {
				sitename : 'wwe.5199122',
				zone : activeTab.substring(3),
				show : show.toLowerCase(),
				objid: item.objectId
			}
		}
		*/

		//item.adParams.dcopt = 'ist';
		//item.adParams.tile = '1';
		//item.adParams.sz='320x302';
		//item.adParams.vplayer='flv';
		//item.adParams.dcove='d';
        //item.adParams.ord = new Date().getTime();
		
		thisMovie("WWEVideo").playVideo(item);

      	document.title = title;

		$('mediaDetailsInset').update(new VideoGalleryView(item).getDetail());

      	this.displayDynamicBrandingImages(item);

      	// Allow for calling in a new omniture tracking code
      	setOmnitureTracker(item.fullName, item.show)
      	// ** set the object id of the current video selection
		this.currentObjectId = item.objectId;

		//For 9-22\
		//WWERatings.setCurrentObjectId(item.objectId);
		//WWERatings.setCurrenObjectRatings(item.rating);
		//WWERatings.view();

		// clear the text input if available
		if (typeof( $('talentFilterTextbox') ) != 'undefined') {
			if (typeof (WWE.Video.NewsTout) != 'undefined') {
				WWE.Video.NewsTout.resetTalentFilter();
			}
		}
	},

	playByIndex:function(index, newPlaylist){
		if (typeof newPlaylist != 'undefined' && newPlaylist != null)
			this.playlist = newPlaylist;
		this.playItem(this.playlist[index], index);
	},

	advancePlayList:function(){
		this.nowPlaying += 1;
		if (this.nowPlaying >= this.playlist.length){
			this.nowPlaying = 0;
			this.playByIndex(this.nowPlaying);
		}
		else {
			this.playByIndex(this.nowPlaying);
		}
	},

	playRequested:function(evt){
    	this.playItem(evt.memo);
	},

	pageLoaded: function(evt){
	    if (!this.NewsTout.lists.length)
	    {
	      // json returned from MT for single result is an item and not an array
	      // so we'll need to mimic the same return structure using this trick
	      this.NewsTout.lists = [this.NewsTout.lists];
	    }
		this.playlist = this.NewsTout.lists[0].items.item;
		// this is hit when someone first comes to the page... thats the only time.. so set our nowPlaying back one so that when it
		// increments, it is at 1, not 2
		this.nowPlaying = -1;
	},

	findInPlaylist:function(item)
    {
      var context = {objectId:item.objectId, index:0};

	  // first time here, our playlist is null...
      if (this.playlist != 'undefined' && this.playlist != null)
      {
		this.playlist.find(function(n, i){
			var objectId = (typeof(n.objectId) != 'undefined') ? n.objectId : n.object_id;
          	if (objectId == this.objectId){
  				this.index = i;
            	return true;
  			}
         	return false;
 		}, context);
      }
      return context.index;
	},
	//legacy stuff
	getCurrentObjectId: function(){
		return this.currentObjectId;
	},

    displayDynamicBrandingImages : function(item)
    {
      // sometimes JSON sends back an item without a show, we don't want a js error, so put up the default images
      if (typeof(item.show) == 'undefined' || item.show == null)
      {
        $('showImage').src = this.defaultBrandShowImage;
        document.body.style.backgroundImage = 'url(' + this.defaultBrandBackgroundImage + ')';
        return;
      }
      var brandBackgroundImage = '';
      var brandShowImage = '';
      var mappingsLength = this.showImagesMapping.length;
      for (var a = 0; a < mappingsLength; a++)
      {
        if (this.showImagesMapping[a]['brand'].toLowerCase() == item.show.toLowerCase())
        {
          if ((this.showImagesMapping[a]['pageBackgroundUrl'] != 'undefined') &&
              (this.showImagesMapping[a]['pageBackgroundUrl'] != null))
          {
            brandBackgroundImage = this.showImagesMapping[a]['pageBackgroundUrl'];
          }
          if ((this.showImagesMapping[a]['logoSourceUrl'] != 'undefined') &&
              (this.showImagesMapping[a]['logoSourceUrl'] != null))
          {
            brandShowImage = this.showImagesMapping[a]['logoSourceUrl'];
          }
          break;
        }
      }

      if (brandShowImage == '')
      {
        brandShowImage = this.defaultBrandShowImage;
      }
      if ($('showImage').src != brandShowImage)
      {
        $('showImage').src = brandShowImage;
      }

      if (brandBackgroundImage == '')
      {
        brandBackgroundImage = this.defaultBrandBackgroundImage;
      }
      if (document.body.style.backgroundImage != brandBackgroundImage)
      {
        document.body.style.backgroundImage = 'url(' + brandBackgroundImage + ')';
      }

    }
	});

/**
 * This function runs recursively to
 * identify an element in an array set.
 *
 * @author Kirk R. Gordon
 * @copyright 2008 World Wrestling Entertainment. All Rights Reserved.
 * @param mixed Value to locate in array set
 * @param string The direction to start searching from: the beginning
 *		  or the end of the array.
 * @access public
 * @return bool
 */
if(!Array.prototype.inArray) {
	Array.prototype.inArray = function() {
		var length = this.length;
		var needle = arguments[0];
		var start = arguments[1];

		if (length >= 0) {
			if (start == 'end') {
				for (var i = length; i >= 0; i--) {
					if (typeof this[i] === "object") {
						this[i].inArray(needle, start);
					}

					if (needle == this[i]) {
						return true;
					}
				}
			} else {
				for (var i = 0; i < length; i++) {
					if (typeof this[i] === "object") {
						this[i].inArray(needle, start);
					}

					if (needle == this[i]) {
						return true;
					}
				}
			}
		} else {
			return false;
		}
	}
}