
var VFA = {
	MaxVideos : 200,
	playAll : 'true',
	mode : 'normal',
	editorsPick : '26325',
	siteIntro : '26375',
	introPlayed : 'false',
	currentIndex : 0,
	isDeeplinkedCollection : false,
	editorsPickMap : new Object(),
	omnitureCategory : "most recent",
	omnitureSubCategory : "TBS",
	votingMap : new Object(),
	collectionMap : new Object(),
	votingList : new Array(),
	currentPlaylistMap : new Object(),
	deepVideoPlaylistMap : new Object(),
	allPlaylistMap : new Object(),
	introPlaylistMap : new Object(),
	introVideo : new Object(),
	TodaysTopId : 26376,  
	All : '24731',
	collectionListId : '26322',
	BrowseDropdownUrl : '/veryfunnyads/getBrowseDropdowns.do?id=207,208',
	NavUrl : '/veryfunnyads/getCollections.do?id=',
	ViewsInsertUrl : '/processors/vfaViewsInsert.do?',
	VideosByTypeUrl : '/veryfunnyads/getVideosByType.do?',
	CollectionUrl : '/veryfunnyads/getCollectionById.do?',
	PlaylistUrl : '/veryfunnyads/getPlaylistById.do?',
	FavoritesUrl : '/veryfunnyads/getVideoById.do?',
	vfaVotingUrl : '/processors/vfaUserRatingInsert.do?',
	PlayList : new Array(),
	deepLinkPlayList : new Array(),
	allPlaylist : new Array(),
	introPlaylist : new Array(),
	isVoting : 'false',
	votingCollectionId:  '25029',
	VotersCookie : 'My-VFA-Favs',
	PollCookie : 'VFA-Poll',
	playDeepLinkVideo : false,
	editorsPlayList : new Array(),
	pollMap : new Object(),
	sponsorImgMap : new Object(),
	pollPlayList : new Array(),
	introUrl : "",
	siteStarted : "",

	section : "featured",
	playCount: 0,
	
	/* store collection name and id for later collection name lookup */
	init : function() {
		$.ajax({
			type: "GET",
			url : VFA.NavUrl + VFA.collectionListId,
			cache : true,
			dataType: "xml",
			success : function(data) {
				
				/*******************************************
				 * Set this to true is special voting is 
				 * being used
				 */
				 
				 if(deepLinkedCollection !== "" || deepLinkedVideo !== "") {
				 	VFA.isVoting = 'false';
				 } else {
				 	VFA.isVoting = 'true';
				 }
				var index = 0;
				$(data).find('collection').each(function(){
					var id = $(this).attr('id');
					var name = $(this).find('name').text();
					VFA.collectionMap[id] = name;
				});
				/*
				var navXml = data;
				//build collection map - stores names and ids for name lookup
				VFA.buildCollectionMap(data);
				*/
				// Check to see if this is a deeplinked collection
				if (deepLinkedCollection !== "") {
					//VFA.getIntroVideo(VFA.introUrl);
					var videoId = VFA.siteIntro;
					if (deepLinkedVideo !== ""){
						videoId = deepLinkedVideo;
						VFA.introUrl = VFA.FavoritesUrl + "id=" + deepLinkedVideo;
						VFA.playDeepLinkVideo = true;
					} else { 
					VFA.introUrl = VFA.CollectionUrl + "&limit=1&id=" + videoId + "&offset=&sort=";
					}
					VFA.getIntroVideo(VFA.introUrl,deepLinkedCollection, true);
					//VFA.parseDeepLinkedCollection(deepLinkedCollection); 
						
				} else {
					//VFA.introUrl = VFA.CollectionUrl + "&limit=1&id=" + VFA.siteIntro + "&offset=&sort=";
					//VFA.getIntroVideo(VFA.introUrl);
					// Check the deep link video
					if (deepLinkedVideo !== ""){
						VFA.introUrl = VFA.FavoritesUrl + "id=" + deepLinkedVideo;
						VFA.playDeepLinkVideo = true;
						VFA.getIntroVideo(VFA.introUrl, VFA.TodaysTopId, false);
						//VFA.initializeSite(VFA.TodaysTopId);
					} else {
						VFA.introUrl = VFA.CollectionUrl + "&limit=1&id=" + VFA.siteIntro + "&offset=&sort=";
						VFA.getIntroVideo(VFA.introUrl,VFA.TodaysTopId, false);
						//VFA.initializeSite(VFA.TodaysTopId);
					}
				}
				
				
		
				//Get all of the videos and store video Map
				$.ajax({
					type: "GET",
					url : VFA.CollectionUrl + "&limit=400&id=" + VFA.All + "&offset=&sort=",
					cache : true,
					dataType: "xml",
					success : function(data) {
						VFA.buildAllPlaylist(data);
					}
				});

/*
				//Get the sponsor images for the collections
				$.ajax({
					type: "GET",
					url : "/veryfunnyads/sponsorImg.xml",
					cache : true,
					dataType: "xml",
					success : function(data) {
						 $(data).find('image').each(function(){
							img = Utils.sponsorImages($(this)); 
							VFA.sponsorImgMap[img.collectionId] = img;
						})
					}
				});
	*/	
		/*Initialize the website*/
		
				/*
				if (waitingSection !== "") {
					// if there was a section waiting for the nav to load, load it now
					SectionNav.load(waitingSection);
				}
				*/
			}
		});
	},
	/***************************************
	 * the introUrl is the link to the intro Video
	 * collectionId - this is the default collection 
	 * or the deepLink video or collection id
	 */
	getIntroVideo : function(introUrl,collectionId, isCollection) {
		$.ajax({
			type: "GET",
			url : VFA.introUrl,
			cache : true,
			dataType: "xml",
			success : function(data) {
				var introvid;
				var index = 0;
				$(data).find('episode').each(function(){
					introvid = Utils.storeVideoNode($(this),index);
					$(".player").data("introId", introvid.videoId);
					VFA.introPlaylistMap[introvid.videoId] = introvid;
			 
				}) 
				
				VFA.introVideo = introvid;
				if(!isCollection) {
					//process the default collection
					VFA.initializeSite(collectionId);
				} else {
					//process the deeplink collection
					VFA.parseDeepLinkedCollection(deepLinkedCollection); 
				}
			}
		}); 
	},
	
	 
	

	/**********************************************
	 * Update the database os a video view
	 */
	 updateVideoView : function(contentId) {
	 	$.ajax({
					type: "GET",
					url : VFA.ViewsInsertUrl + "contentId=" + contentId ,
					cache : true,
					dataType: "xml",
					success : function(data) {

					}
			});
	 },

/*
	initializeSiteHold : function() {
		ThumbListArea.init();  //intialize thumbnail area
		VFA.buildAlertBox();
		//create the site
		MainNav.init();
		Menu_UI.init();

		Blog.init();
		VFAPlayer.init();
		UserVoting.init();
		changeAd("featured");
		
		VFA.updateHeader(VFA.TodaysTopId, 'most recent');
		ThumbListArea.loadVideosByCollectionId(VFA.TodaysTopId);
		//ThumbListArea.loadVideo(); //get the videos for the page and build the list
		
		ThumbListArea.loadEditorsPicks(); //load the editors picks

		//ThumbListArea.createVotingDialog();
		
	},
	*/ 
	/*****************************************
	 * Method called by the video player
	 * start the auto play
	 */
	start : function() {
		if (VFA.playAll == 'true') {
			var videoId = VFA.PlayList[VFA.currentIndex].id;
			//update data
			if(videoId == $(".player").data("introId")){
				VFA.introPlayed = 'true';
			}


			var videoInfo = VFA.currentPlaylistMap[videoId];
			/*
			ThumbListArea.updateBackground(videoInfo);

			var backgroundImg = videoInfo.fullImage;
			var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
			$('#background').html(bgdHTML);

			*/
			 ThumbListArea.updatePlayer(videoInfo);


	 		VFA_PLAYER.Play(VFA.PlayList[VFA.currentIndex]);
		} else {

			var videoId = VFA.deepLinkPlayList[0].id;

			var videoInfo = VFA.allPlaylistMap[videoId];
			/*
			ThumbListArea.updateBackground(videoInfo);

			var backgroundImg = videoInfo.fullImage;
			var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
			$('#background').html(bgdHTML);

			*/
			 ThumbListArea.updatePlayer(videoInfo);
	 		VFA_PLAYER.Play(VFA.deepLinkPlayList[0]);

		}
	},

	buildIntro : function(data) {
		var introvid;
		var index = 0;
		$(data).find('episode').each(function(){
			introvid = Utils.storeVideoNode($(this),index);
			$(".player").data("introId", introvid.videoId);
			VFA.introPlaylistMap[introvid.videoId] = introvid;
			//x3 fals
			
		})
		return introvid;
	},

	buildCollectionMap : function(data) {
		
		var index = 0;
		$(data).find('collection').each(function(){
			var id = $(this).attr('id');
			var name = $(this).find('name').text();
			VFA.collectionMap[id] = name;
		});
		 
	},



	buildAllPlaylist : function(data) {

				//ThumbListArea.videoCount = $(data).find('episodes').attr('totalItems');
					var videoArray = new Array();
					var orderArray = new Array();



					var index = 0;  //index for grabbing the video from the playlist
					$(data).find('episode').each(function(){

						var newvid = Utils.storeVideoNode($(this), index);
						videoArray.push(newvid);
						VFA.allPlaylistMap[newvid.videoId] = newvid;

						//VFA.PlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl});

						  index = index + 1;
					});
					VFA.allPlaylist = videoArray;

		},

	parseDeepLinkedVideo : function(data) {
		// parse the xml to play the video
		var deepLinkedVideoMap = new Object();
		var orderArray = new Array();
		var newvidArray = new Array();
		var videoUrl = "";
		VFA.playDeepLinkVideo = true;
		VFA.playAll = 'false';
		VFA.introPlayed = 'true';
		//VFA.PlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl});
		if ($(data).find('episode').length > 0) {
			$(data).find('episode').each(function() {
				newvid = Utils.storeVideoNode($(this));
				orderArray.push(newvid.videoId);
				//deepLinkedVideoMap[newvid.videoId] = newvid;
			    VFA.deepVideoPlaylistMap[newvid.videoId] = newvid;
				//var videoId = VFA.deepLinkPlayList[0].id;
				VFA.deepLinkPlayList.push({id: newvid.videoId, url: newvid.flashUrl, image: newvid.fullImage, title : newvid.fullTitle});

			
			});
		}
	},

	parseDeepLinkedCollection : function(collectionId) { 
		    
			MainNav.buildSortMenu('view');
			var collectionName = VFA.collectionMap[collectionId];
			VFA.mode = "normal";
			VFA.TodaysTopId = '26521';
			//Modify this to handle auto sponsorhip in the future
			
			var shtml = '<div class="vfa_header_title"><h2>' + collectionName + '</h2></div>';
			var includedImage =''; 
			var sImg = "";
			var sponsoredImg = ''; //'<img src="/veryfunnyads/img/autoblog-73x17.gif" width="73" height="19"/>';
			if (collectionId == '26521') {
				///shtml = shtml + sponsoredImg;
				collectionName = 'cars';
				sponsoredImg = '<a href="http://www.autoblog.com" target="_blank" class="vfa_header_sponsor"><img src="/veryfunnyads/img/vfa-autoblog-73x17.JPG" width="73" height="19" style="padding-top:5px;"/></a>';
				shtml = '<div class="vfa_header_title"><h2 style="display:inline;">' + collectionName + '</h2>' ;
			}
			
	  
			VFA.omnitureCategory = "External";
			VFA.omnitureSubCategory = collectionName;    //$(this).html();
			trackCategoryViews("Categories", collectionName);
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "normal");
			$('#item-wrap').data('menuSelection', 'menuCategories');
			VFA.section = collectionName;
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			
			Pager.isCreated = false;
			VFA.initializeSite(collectionId);
			//ThumbListArea.loadVideosByCollectionId(collectionId); 
		 
	},
	
	/*******************************************
	* Update the header info for the collection
	* 
	* */
	updateHeader : function(collectionId, collectionName) {
			var includedImage =''; 
			var sImg = "";
			var sponsoredImg = ''; 
			var shtml = '<h2>' + collectionName + '</h2>';
			if (collectionId == '26521') {
				///shtml = shtml + sponsoredImg;
				collectionName = 'cars';
				//sponsoredImg = '<a href="http://www.autoblog.com" target="_blank" class="vfa_header_sponsor"><img src="/veryfunnyads/img/vfa-autoblog-73x17.JPG" width="73" height="17" style="padding-top:5px;"/></a>';
				shtml = '<div class="vfa_header_title"><h2 style="display:inline;">' + collectionName + '</h2>' + sponsoredImg ;
			}
			return shtml;
		},
		
 	/************************************
 		Get the video list for this page
	**/
	updateUserVote : function (id, rating) {
		// get the teaser xml file
	  var userVote = id + "-" + rating;
	  VFA.votingMap[id] = rating;
	  VFA.votingList.push(userVote);
	  UserVoting.updateCookie()

		$.ajax({
			type: "GET",
			url : VFA.vfaVotingUrl + "rating=" + rating + "&contentId=" + id,
			cache : true,
			dataType: "text",
			success : function() {
				 //alert("Vote Posted");
			}
		});

	},
	
	/*********************************************************
	 * Builds the alert box for site notes (Pink box over player)
	 * 
	 */
	buildAlertBox : function() {
		
		//temp date used to hide box after this date has been attained
		var now = new Date();
		var stopDate = new Date();
		stopDate.setDate(26);
		stopDate.setFullYear(2009);
		stopDate.setMonth(11);
		stopDate.setHours(22);
		
		 
		if(now < stopDate) {
			$('.alert').html();
			var shtml = '<h2>funniest commercials of the year</h2>';
			shtml += '<p>Pick your favorite and see the winner on TBS on Dec 15! <a class="voteLink" href="#">Vote now ></a></p>';
			$('.alert').html(shtml);
			$('.alert').css('visibility', 'visible');
		} else {
			$('.alert').css('visibility', 'hidden');
		}
		
		 
	},
	
	/***************************************
		Builds the sponosrship box above the 
		Thumbnails
	*/
	buildSponsorBox : function(collectionId) {
		var sponsorImg = "";
		
		//Get the sponsor images for the collections
				$.ajax({
					type: "GET",
					url : "/veryfunnyads/sponsorImg.xml",
					cache : true,
					dataType: "xml",
					success : function(data) {
						 $(data).find('image').each(function(){
							img = Utils.sponsorImages($(this)); 
							VFA.sponsorImgMap[img.collectionId] = img;
						})
						
						//update the sponsor box
						sponsorImg = VFA.sponsorImgMap[collectionId];
		 
						if (typeof sponsorImg != 'undefined') {
							$('.sponsor_tiny').html();
							var shtml = '<div class="rel"><span>as seen on:</span>';
							shtml += '<a href="' + sponsorImg.sponsorLink + '" target="_blank"><img src="' + sponsorImg.imageUrl + '" style="border:0;" width="88" height="31" alt="' + sponsorImg.altText + '"/>';
							shtml += '</a></div>';
							$('.sponsor_tiny').html(shtml);
							$('.sponsor_tiny').css('visibility','visible');
						} else {
							$('.sponsor_tiny').css('visibility', 'hidden');
						}
					}
				});
		
		 
	},

	initializeSite : function(collectionId) {
		ThumbListArea.init();  //intialize thumbnail area
		VFA.buildAlertBox();
		//create the site
		MainNav.init();
		Menu_UI.init();

		Blog.init();
		VFAPlayer.init();
		UserVoting.init();
		changeAd("featured");
		
		VFA.updateHeader(VFA.TodaysTopId, 'most recent');
		//if (!VFA.isDeeplinkedCollection) {
			
			
			ThumbListArea.loadVideosByCollectionId(collectionId);
		//ThumbListArea.loadVideo(); //get the videos for the page and build the list
		//}
		ThumbListArea.loadEditorsPicks(); //load the editors picks

		//ThumbListArea.createVotingDialog();
		
	},
	/***************************************
	 * Create the player
	 */
	buildPlayer : function() {
		var flashvars = {};
		flashvars.name1 = "hello";


		var params = {};
		params.menu = "true";
		params.bgcolor = "#ffffff";
		params.allowFullScreen = "true";
		params.allowScriptAccess = "always";
		params.wmode="transparent";
		var attributes = {};
		attributes.id = VFA_PLAYER.ID;
		attributes.name = VFA_PLAYER.ID;

	    swfobject.embedSWF("http://i.cdn.turner.com/v5cache/TBS/veryfunnyads/player.swf", "player_box", "400", "330", "9.0.28.0", "http://i.cdn.turner.com/v5cache/TBS/veryfunnyads/expressInstall.swf", flashvars, params, attributes);


	},

  	playIntro : function() {
  		var introId = $(".player").data("introId");
  		//$(".player").data("introId", introvid.videoId);
  		//dbs
  		var introVid = VFA.introPlaylistMap[introId];
  		
  		ThumbListArea.updateBackground(videoInfo);
  		/*
  		var backgroundImg = videoInfo.fullImage;
		var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
		$('#background').html(bgdHTML);

  		*/
  		//ThumbListArea.updatePlayer(introVid);
  		ThumbListArea.updatePlayer(VFA.introVideo);
		VFA_PLAYER.Play(VFA.introVideo);
  		 //VFA_PLAYER.Play(introVid);
  	},

	/*************************************
	 * Play a single video and cast a vote
	 */
	playSingle : function(video) {
	 //verify that there is a video to play
	  if (VFA.playCount > 0 && VFA.playCount % 2 != 0) {
	  	//alert("Change Ad-" + VFA.section);
	  	/*
	  	if (VFA.section == null || VF.section == "") {
	  		VFA.section = "featured";
	  	}
	  	*/
	  	changeAd(VFA.section);
	  }


    	 VFA_PLAYER.Play(video);
    }

};



var Pager = {
	isCreated : false,
	init : function(page){

		var scrollerHolder = '<ul id="mycarousel" class="jcarousel-skin-page"></ul>';
    	if(page == "" || page == null) {
    		page = 1;
    	}
    	if (page < 5) {
    		page = 1;
    	}
		$('#pagination2').html(scrollerHolder);

		var pageCount = Math.ceil(ThumbListArea.videoCount / ThumbListArea.limit);
		jQuery('#mycarousel').jcarousel({
		    	start : 1,
		    	scroll: 5,
		    	initCallback: Pager.mycarousel_initCallback,
		    	// This tells jCarousel NOT to autobuild prev/next buttons

		        itemLoadCallback: Pager.mycarousel_itemLoadCallback

		   });
		 jQuery("ul.jcarousel-list").css("width","396px");
	},



	mycarousel_initCallback : function(carousel) {

		$("#page_next").livequery("click", function(e){
				 carousel.next();
				return false;

			});
		$("#page_prev").livequery("click", function(e){

	        carousel.prev();
	        return false;
	    });
	},

	mycarousel_itemLoadCallback : function(carousel, state) {
		 // Since we get all URLs in one file, we simply add all items
		    // at once and set the size accordingly.
		    if (state != 'init')
		        return;

		     //grab the text that was built in ThumbLIstArea.pagination for the data
		      var data = ThumbListArea.carousel_itemsHTML;

		      Pager.mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
	},

	mycarousel_itemAddCallback : function(carousel, first, last, data)
		{

		    // Simply add all items at once and set the size accordingly.

		    var items = data.split('|');

		    for (var i = 0; i < items.length; i++) {

		        carousel.add(i+1, Pager.mycarousel_getItemHTML(items[i]));
		    }

		    carousel.size(items.length);
		},


	mycarousel_getItemHTML : function(url)
		{
			//return '<div>' + url + '</div>';
			return url;

		}

};

/************************************************
 Controller for ThumbList
***********************************************/

var ThumbListArea = {
	limit : 12,
	videoCount : 0,
	sort : '',
	daysback : '',
	offset : '',
	page : 1,
	noOfDays : 14, //number of days to notify if a video is new
	searchQuery : '',
	carousel_itemsHTML : '',
	carousel_itemList : new Array(),
	loadType : 'normal',

	init : function() {
	 var page = ThumbListArea.page;

	// initialize the page
		$("#item-wrap").data("loadType", "normal");
		$('#pagination').data('currentPage', 1);
		$('.pagination_numb a').livequery("click", function(event) {
			 
			var selectedPage = $(this).html();

				$('.pagination_numb').removeClass('current');

				var parentTag = $(this).parent().get(0);
				$(parentTag).addClass('current');
			//$(this).parent().get(0).addClass('current');
			//updatePlayList(_initialFeedId, selectedPage);

			trackCategoryViews(VFA.omnitureCategory, VFA.omnitureSubCategory);
			ThumbListArea.page = selectedPage;

			if(VFA.mode == 'normal') {
				ThumbListArea.loadVideo();
			} else {
				ThumbListArea.loadSearchVideo();
			}
			$('#pagination').data('currentPage', selectedPage)

			event.preventDefault();
			return false;

		});



		//Handle the menu top ads
		$(".notFound a").livequery("click", function(e){
		   var sortItem = $(this).attr("class");
		   VFA.mode = "normal";
		   ThumbListArea.sort = "";
		   MainNav.sortHeader = 'top rated';
		   /*
		   if (sortItem == '') {
			  	ThumbListArea.sort = "views";
			  	MainNav.sortHeader = 'most watched';
			  } else if (sortItem == 'sortDate') {
			  	ThumbListArea.sort = "date";
			  	MainNav.sortHeader = 'most recent';
			  } else if (sortItem == 'sortTopRated') {
			  	ThumbListArea.sort = "rated";
			  	MainNav.sortHeader = 'top rated';
		}
		*/

			var shtml = '<h2>' + MainNav.sortHeader + '</h2>';
			VFA.omnitureCategory = "Top Ads";
			VFA.omnitureSubCategory = MainNav.sortHeader;
			trackCategoryViews("Top Ads", MainNav.sortHeader);
			$('.thumbHeader').html(shtml);
			MainNav.buildSortMenu('view');
			//ThumbListArea.loadType = "byType";
			$("#item-wrap").data("loadType", "normal");
			$('#item-wrap').data('menuSelection', 'menuTopAds');
			VFA.TodaysTopId = '24733'; //$(this).attr("id");
			ThumbListArea.page = 1;
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			ThumbListArea.loadVideo();
			e.preventDefault();
			return false;

		});




		/**************************************
			bind and handle the previouse button click
		*/
		 
		/*****************************************
			bind handle the next button click
		*/
 

			$("#item-wrap li a").livequery("click", function(e){
				 var vid = $(this).attr("vid");
				 //Update the header
				
				var videoInfo = VFA.currentPlaylistMap[vid];
			 	ThumbListArea.updateBackground(videoInfo);
			 	/*
			 	var backgroundImg = videoInfo.fullImage;
				var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
				$('#background').html(bgdHTML);

			 	*/
			 	//Video type is used to distinguish vidoes that are polls, editors picks and standard ad videos	
			 	VFAPlayer.videoType = $(this).attr("videoType");
			 	 ThumbListArea.updatePlayer(videoInfo);


				//get video from the playlist
				var video = VFA.PlayList[videoInfo.playListIndex];

				//check to see id video flv url null as a last resort
				// pull back by id. this is a patch for the search and
				//should not be needed in the next update


				//VFA.PlayList.push({id: introVideo.id, url: introVideo.flashUrl, image: introVideo.fullImage, title: introVideo.fullTitle});
				if(video.url == null || video.url == ""){

					Utils.getSearchFlashUrl(videoInfo.segmentId,video);
					//e.preventDefault();
					return false;
				} else {

					//x3 derrick if (video)
					VFA.playAll="false";
					VFA.playCount = VFA.playCount + 1; //increment the playCount
					VFA.playSingle(video);
					e.preventDefault();

					return false;
				}
			});

			/*************************************************
			 * x3 Chelsey
			 * This jquery handles the voting click of the anchor
			 * tag that creates the voting dialog. This link
			 * is in the Pink attention box
			 * *************************************************/
			//alert
			/*
			$(".alert p a").livequery("click", function(e){
				 VFA.playAll = "false";
				 //ThumbListArea.createVotingDialog();
				e.preventDefault();
				return false;

			});
			*/
			
			$(".alert a").livequery("click", function(e){
				
			 
			var header = $(this).html(); 
			VFA.mode = "normal";
		  
			 VFA.isVoting = 'true';
			 //hide the scale buttons
			 VFAPlayer.voteButtonState("show");
			
			//var shtml = VFA.updateHeader(collectionId, header);
			var shtml = '<h2>best of the year</h2>';
			$('.thumbHeader').html(shtml); 
			ThumbListArea.page = 1; 
			Pager.isCreated = false;
			ThumbListArea.loadVideosByCollectionId(VFA.votingCollectionId);
			//ThumbListArea.loadVideo();
			//ThumbListArea.sort="";
				
			 
				
				e.prevenDefault();
				return false;
			});

			/*************************************************************
			 * x3 Chelsey
			 * this selector handles when the the video name is selected
			 * and causes the video to be played.
			 */
			$(".votingDialog li a").livequery("click", function(e){
				var vid = $(this).attr("id");
				var videoInfo = VFA.pollMap[vid];
				ThumbListArea.updateBackground(videoInfo);
				var video = VFA.pollPlayList[videoInfo.playListIndex];
				  ThumbListArea.updatePlayer(videoInfo);
				  VFA.playAll="false";
				  VFA.playSingle(video);

				e.preventDefault();
				return false;

			});


			/***************************************************
			 * x3 Chelsey
			 * Here is where the call to the pollserver is done.
			 * Also this is where the error msg is created and
			 * this is the landing text that displays after a
			 * successful vote
			 *
			 
			$(".votingBtn a").livequery("click", function(e){
				var vid = $(this).attr("id");
				$(".pollError").html('');
				
				//msg for the user not selecting a option
				var msg = "You didn&#39;t vote for an ad";
				var endMsg = "Your vote has been counted! <br><br>"
				endMsg += "You may come back tomorrow to vote again. And don&#39;t forget to watch the winner ";
				endMsg += "during the World&#39;s Funniest Commercials on June 26 at 9/8c, only on TBS!<br><br>";
			    endMsg += "Please select an item from the menus above to continue watching Very Funny Ads.";
				var val = $("input[@name='rad']:checked").val();
				if($("input[@name='rad']:checked").val()) {
					var videoName = $("input[@name='rad']:checked").val();
					$('.finalPnl').css('display', 'none');
					$(".voteDescription").html(endMsg);
				//	document.pollForm.submit();
					//ThumbListArea.vfaPollVote(videoName)
					//update the poll cookie
					//UserVoting.updatePollCookie(videoId);
				} else {
					$(".pollError").html(msg);
				}
				e.preventDefault();
				return false;

			});
			* */
			
			$(".votingBtn a").livequery("click", function(e){
				 
				$(".pollError").html('');
				var vid = VFAPlayer.currentVideoPlaying.id;
				//msg for the user not selecting a option
			 
				var endMsg = "<span class='pollError'>Your vote has been counted! <br><br>"
				endMsg += "You may come back tomorrow to vote again. And don&#39;t forget to watch the winner ";
				endMsg += "during the World&#39;s Funniest Commercials on June 26 at 9/8c, only on TBS!<br><br>";
			    endMsg += "Please select an item from the menus above to continue watching Very Funny Ads.</span>";
				 
				//dont let user vote for intro video :)
				if(vid != 26594) {
				 //pass the current video to the poll server
				 makeGetRequest();
					
				//$(".votingMsg").html(endMsg);
				$(".votingBtn img").attr("src","/veryfunnyads/img/btn_my_pick.gif");
		 		VFAPlayer.voteButtonState("show");
				UserVoting.updatePollCookie(vid);
				VFAPlayer.hasVoted = "true";
				}
				
				e.preventDefault();
				return false;

			});
			
			//capture the thumbnail selection in editors

			$("#editors_picks li a").livequery("click", function(e){
				 var vid = $(this).attr("vid");
				
				//Video type is used to distinguish vidoes that are polls, editors picks and standard ad videos	
			 	VFAPlayer.videoType = $(this).attr("videoType");
				 //Update the header
				var videoInfo = VFA.editorsPickMap[vid];
				ThumbListArea.updateBackground(videoInfo);
				/*
				var backgroundImg = videoInfo.fullImage;
				var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
				$('#background').html(bgdHTML);

				 */

				 // //get video from the playlist

				var video = VFA.editorsPlayList[videoInfo.playListIndex];
				ThumbListArea.updatePlayer(videoInfo);
				VFA.isVoting="false";
				VFAPlayer.voteButtonState("hide");
				VFA.playAll="false";
				VFA.playSingle(video);
				e.preventDefault();
				return false;

			});



			//Handle the play-all button. Restarts the playlist from the top
			$(".play_all").livequery("click", function(e){
				// var vid = $(this).attr("vid");

				VFA.playAll = "true";
				VFA.currentIndex = 0;
				//start the playlist over for this page
				VFA.start();
				e.preventDefault();
				return false;

			});



		 /*
		  * <form action="#" name="signupform">
			<div class="rel">
			<p><label for="emailsignup">get the <a href="http://www.tbs.com/stories/story/0,,126652,00.html">newsletter!</a></label>
			<input type="text" id="email_signup" name="emailsignup" value="Your email address">
			<button type="submit">submit</button></p>
			</div>
		</form>
		  */


		//Here is where we get the page number. For testing set to 1
		//ThumbListArea.loadVideo(page);
	},


 	/************************************
 		Get the video list for this page
	**/
	loadVideo : function () {
		// get the teaser xml file
	 	//ThumbListArea.loadType = 'normal';
	 	VFA.normal = "normal";
		var page = ThumbListArea.page;
		ThumbListArea.offset = (page - 1) * ThumbListArea.limit;

		// http://tbs.com/veryfunnyads/getCollectionById.do?id=24853&offset=0&limit=9&sort=
		var dataUrl = "";
		//alert("loadType=" + $("#item-wrap").data("loadType"));
		if ($("#item-wrap").data("loadType") == "normal") {
			dataUrl = VFA.CollectionUrl;
		} else {
			dataUrl = VFA.VideosByTypeUrl;
			///$("#item-wrap").data("loadType", "normal");
		}
		/*
		alert("new start ajax pull");

		var htmlURL = dataUrl + "limit=" + ThumbListArea.limit + "&id=" + VFA.TodaysTopId + "&offset=" + ThumbListArea.offset  + "&sort=" + ThumbListArea.sort + "&daysback=" + ThumbListArea.daysback;
		$.post(htmlURL, function(data){
			alert("start loadVideo");
				ThumbListArea.populate(data, page);
				alert("got pat populate loadVideo");
		});
		*/

		$.ajax({
			type: "GET",
			url : dataUrl + "limit=" + ThumbListArea.limit + "&id=" + VFA.TodaysTopId + "&offset=" + ThumbListArea.offset  + "&sort=" + ThumbListArea.sort + "&daysback=" + ThumbListArea.daysback,
			cache : true,
			dataType: "xml",
			success : function(data) {
				//alert("start loadVideo");
				ThumbListArea.populate(data, page);
				//alert("got pat populate loadVideo");
			}
		});

	},

	/************************************
 		loads video by collectionId
	**/
	loadVideosByCollectionId : function (collectionId) {
		// get the teaser xml file
	 	//ThumbListArea.loadType = 'normal';
	 	VFA.normal = "normal";
		var page = ThumbListArea.page;
		ThumbListArea.offset = (page - 1) * ThumbListArea.limit;
		
		VFA.buildSponsorBox(collectionId);
		// http://tbs.com/veryfunnyads/getCollectionById.do?id=24853&offset=0&limit=9&sort=
		var dataUrl = "";
		//alert("loadType=" + $("#item-wrap").data("loadType"));
		if ($("#item-wrap").data("loadType") == "normal") {
			dataUrl = VFA.CollectionUrl;
		} else {
			dataUrl = VFA.VideosByTypeUrl;
			///$("#item-wrap").data("loadType", "normal");
		}
		/*
		alert("new start ajax pull");

		var htmlURL = dataUrl + "limit=" + ThumbListArea.limit + "&id=" + VFA.TodaysTopId + "&offset=" + ThumbListArea.offset  + "&sort=" + ThumbListArea.sort + "&daysback=" + ThumbListArea.daysback;
		$.post(htmlURL, function(data){
			alert("start loadVideo");
				ThumbListArea.populate(data, page);
				alert("got pat populate loadVideo");
		});
		*/
		var viewSort = ThumbListArea.sort;
		if(viewSort == "views") {
			viewSort = "";
		}
		
		var getUrl = dataUrl + "limit=" + ThumbListArea.limit + "&id=" + collectionId + "&offset=" + ThumbListArea.offset  + "&sort=" + viewSort + "&daysback=" + ThumbListArea.daysback;
		if (VFA.isVoting == 'true') {
			getUrl = dataUrl + "limit=10&id=" + VFA.votingCollectionId + "&offset=" + ThumbListArea.offset  + "&sort=" + viewSort + "&daysback=" + ThumbListArea.daysback;
		}
		$.ajax({
			type: "GET",
			url : getUrl,
			cache : true,
			dataType: "xml",
			success : function(data) {
				//alert("start loadVideo");
				if (VFA.isVoting == 'true') {
					ThumbListArea.populateVote(data, page);
				} else {
					ThumbListArea.populate(data, page);
				}
				//alert("got pat populate loadVideo");
			}
		});

	},
	


	/*********************************************
	 * Get the editors picks
	 */
	loadEditorsPicks : function () {
		// get the teaser xml file
	 	var limit = 3;
		VFA.mode = "normal";
		$.ajax({
			type: "GET",
			url : VFA.CollectionUrl + "&limit=" + limit + "&id=" + VFA.editorsPick + "&offset=0&sort=0&daysback=0",
			cache : true,
			dataType: "xml",
			success : function(data) {
				ThumbListArea.populateEditorsPicks(data);
			}
		});
	},

	loadSearchVideo : function () {
		// get the teaser xml file
	 	ThumbListArea.loadType = 'normal';
	 	VFA.mode = 'search';
		var page = ThumbListArea.page;

		ThumbListArea.offset = (page - 1) * ThumbListArea.limit;

		var searchQry = ThumbListArea.searchQuery;
		 var sLabel = searchQry;
	  	var header = Utils.stringShorten(sLabel, 16);
	  	var shtml = '<h2>' + header + '</h2>';

		var shtml = '<h2>' + searchQry + '</h2>';
			$('.thumbHeader').html(shtml);
		// http://tbs.com/veryfunnyads/getCollectionById.do?id=24853&offset=0&limit=9&sort=
		var searchUrl = "/processors/veryfunnyads/getSearchXml.jsp?query=" + searchQry + "&offset=" + ThumbListArea.offset + "&sort=" + ThumbListArea.sort + "&length=" + ThumbListArea.limit;
		//var searchUrl = "http://searchapp.veryfunnyads.com/vfa-search/query.jsp?query=" + searchQry + "&offset=" + ThumbListArea.offset + "&sort=" + ThumbListArea.sort + "&length=" + ThumbListArea.limit;
		$.get(searchUrl, function(data){
			//alert("Retriving data" + data);
			ThumbListArea.populate(data, page);
			//alert("Data Loaded" + data);
			//var myTest = data;
		});
/*
		$.ajax({
			type: "GET",
			url : searchUrl,
			cache : true,
			dataType: "xml",
			success : function(data) {
				//var thisData = data;
				ThumbListArea.populate(data, page);
			}
		});
*/
	},

	/*******************************************
	 * x3 CHelsey
	 * Sends the vote to the poll server
	 */
	vfaPollVote : function(title) {
	/*
		<input type="hidden" name="cmd" value="tally" />
<input type="hidden" name="pollid" value="TBSGeneral!WFC2009" />
<input type="hidden" name="vwf_showquestion" id="vwf_showquestion" />
<input type="hidden" name="results" value="TBSGeneral!WFC2009.results.html" />

<input type="hidden" name="pagenumber" value="0" />
<input type="hidden" name="charset" value="UTF-8" />
<input type="hidden" id="vwf_ShowAndHide_HiddenQuestions" name="vwf_ShowAndHide_HiddenQuestions" value="" />
		*/
		var urlParams = '&cmd=tally&pollid=TBSGeneral!WFC2009&vwf_showquestion=vwf_showquestion';
		urlParams += '&results=TBSGeneral!WFC2009.results.html&pagenumber=0&charset=UTF-8';



		///processors/veryfunnyads/vfaVote.jsp
		//var pollUrl = 'http://poll.turner.com/ViewsFlash/servlet/viewsflash?Video=' + title + urlParams;
		var pollUrl = '/processors/veryfunnyads/vfaVote.jsp?title=' + title;
		$.ajax({
			type: "GET",
			url : pollUrl,
			cache : true,
			dataType : "text",
			success : function(data){
				var success = true;
			}
		})
	},

	/********************************************
	 * x3 Chelsey
	 * This function gets the poll collection
	 *
	 ********************************************/
	createVotingDialog : function() {

		var voteUrl = "/veryfunnyads/getCollectionById.do?limit=10&id=25029&offset=0&daysback=";
		$.ajax({
			type: "GET",
			url : voteUrl,
			cache : true,
			dataType: "xml",
			success : function(data) {
				//pass the xml so the list can be built
				ThumbListArea.buildVotingList(data);
			}
		});

	},

	/***********************************************
	 * x3 Chelsey
	 * Builds the voting list
	 * x3 used for the VFA polling project
	 */
	buildVotingList : function(data) {

		var storedVotes = CookieJar.getCookie(VFA.PollCookie);
		var hasVoted = false;
		if (storedVotes) {
			hasVoted = true;
		}
		$('#votingBox').html('');
		$('#item-wrap').html('');
		$('#thumbPanel').css('display','none');
		$('#errorMsg').html('');
		$('.finalPnl').css('display', '');
		var boxDescription = 'Help decide the world&#39;s funniest commercial! Just watch the 10 ';
		boxDescription +=  'videos below, then place your vote. To see the winner, tune in to ';
		boxDescription += 'TBS on June 26 at 9/8c to watch The World&#39;s Funniest Commercials 2009!';
		//class="votingDialog"
		var html = '<div class="votingDialog"><div class="pollHolder">';
		html += '<span class="voteHeader">vote for your favorite!</span><br><br>';
		html += '<span class="voteDescription">'+ boxDescription+ '</span><br><br>';
	 	//this panel allows for the list to be hidden when the vote is submitted
	 	html += '<div class="finalPnl">';
	 	html += '<script src="/veryfunnyads/js/ajaxpoll.js" type="text/javascript"></script>';
	 	html += '<form action="" name="pollForm" id="pollForm" method="post">';
	 	html = html + '<ul type="none" style="list-style-type: none; margin-left:0; padding-left:0; line-height:20px;">';
	 	html += '<li><div><input id="Video--0" type="radio" name="Video" value="Mafia"   /><a id="26478" class="playVotedVideo" href="#">&nbsp;Braun: Mafia</a></div></li>';
			html += '<li><div><input id="Video--1" type="radio" name="Video" value="Pong"   /><a id="26253" class="playVotedVideo" href="#">&nbsp;Carlsberg: Pong</a></div></li>';
			html += '<li><div><input id="Video--2" type="radio" name="Video" value="Boss"   /><a id="26484" class="playVotedVideo" href="#">&nbsp;Dare: Boss</a></li>';
			html += '<li><div><input id="Video--3" type="radio" name="Video" value="Power of Crunch"   /><a id="26485" class="playVotedVideo" href="#">&nbsp;Doritos: Power of Crunch</a></div></li>';
			html += '<li><div><input id="Video--4" type="radio" name="Video" value="Nurse"   /><a id="26488" class="playVotedVideo" href="#">&nbsp;Dr. Pepper: Nurse</a></div></li>';
			html += '<li><div><input id="Video--5" type="radio" name="Video" value="RubberDuckZilla"   /><a id="26490" class="playVotedVideo" href="#">&nbsp;Oasis: RubberDuckZilla</a></div></li>';
			html += '<li><div><input id="Video--6" type="radio" name="Video" value="Curly"   /><a id="26494" class="playVotedVideo" href="#">&nbsp;Paul Miller: Curly</a></div></li>';
			html += '<li><div><input id="Video--7" type="radio" name="Video" value="Crazy Pets"   /><a id="26497" class="playVotedVideo" href="#">&nbsp;Pedigree: Crazy Pets</a></div></li>';
			html += '<li><div><input id="Video--8" type="radio" name="Video" value="Elevator"   /><a id="26500" class="playVotedVideo" href="#">&nbsp;Santa Fe Beer: Elevator</a></div></li>';
			html += '<li><div><input id="Video--9" type="radio" name="Video" value="My Childhood"   /><a id="26503" class="playVotedVideo" href="#">&nbsp;Tele2: My Childhood</a></div></li>';

	 	html += '</ul>';

	 	if (hasVoted) {
			html += '<span class="pollError">You have already voted today. Please vote again tomorrow.</span>';
		} else {
			html +=	'<p class="votingBtn" style="margin:20px 0 0 20px;"><a href="#"><img src="http://teg8fref1.turner.com:9220/veryfunnyads/img/vfa_submitvote_button.gif" alt="submit vote" onClick="" id="submit"></a></p>';
		}
	 	html += '</form><br><br><span >&nbsp;</span>';
		html += '<br><br><span class="pollError"></span>';
		html += '</div></div></div>';

	 	/***************************************************
	 	 * setup the playlist so the videos can be viewed
	 	 */

	 	var index = 0;
			$(data).find('episode').each(function(){

				var newvid = Utils.storeVideoNode($(this), index);
				//videoArray.push(newvid);
				VFA.pollMap[newvid.videoId] = newvid;
				var _brand = $(this).find('brand').text();
				var _id = $(this).attr('id');
				var _flashUrl = $(this).find('flashUrl').text();
				var _fullTitle = $(this).find('title').text();
				var _title = Utils.stringShorten(_fullTitle,18);
				var _fullSizeStillUrl = $(this).find('fullSizeStillUrl').text();
				var _description = $(this).find('description').text();
				_description = Utils.stringShorten(_description,31);
				//Add the video to the playlist

				VFA.pollPlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl, title: _fullTitle});

				//html += '<li><input type="radio" name="rad" value="' +_fullTitle+'" /><a id="' + _id + '" class="playVotedVideo" href="#">&nbsp;Mafia</a></li>'

				index = index + 1;
			});
			//html += '</ul><br><br>';


		$('#votingBox').html(html);


	},


	/*************************************
	 * Clear the previous page
	 */
	clearPlayList : function() {
			//clear the paylist
			VFA.PlayList = new Array();
			var tmp = $('#item-wrap li').html();
			$('#item-wrap li').remove();
	},

		/***********************************
		 * Build the playlist, playlistMap and the thumbnails
		 */
		populate : function(data, page) {
			 ThumbListArea.clearPlayList();
			 VFA.currentPlaylistMap = new Object();

	 			//ThumbListArea.videoCount = $(data).find('episodes').attr('totalItems');
				ThumbListArea.videoCount = $(data).find('episodes').attr('totalItems');
					var videoArray = new Array();
					var orderArray = new Array();
					var index = 0;
					/************************
					 * add site intro
					 */

					if(VFA.introPlayed == 'false') {
						/*
						//introvid = Utils.storeVideoNode($(this),index);
						var introVideoId = $(".player").data("introId");
					 
						//VFA.introPlaylistMap[introvid.videoId] = introvid;
						var introVideo = VFA.introPlaylistMap[introVideoId];
						if(introVideo == null) {
							introVideo = VFA.introPlaylistMap[introVideoId]; 
						}
						* */
						
						/* Check to see if introVideo not created */
					 
					  
						if (typeof VFA.getIntroVideo == 'undefined') {
							VFA.introVideo = VFA.getIntroVideo(VFA.introUrl);
						}
					 
					 
						VFA.introPlaylistMap[VFA.introVideo.videoId] = VFA.introVideo;
						videoArray.push(VFA.introVideo);
						//videoArray.push(introVideo);
						//VFA.currentPlaylistMap[introVideoId] = introVideo;
						VFA.currentPlaylistMap[VFA.introVideo.id] = VFA.introVideo;
						//VFA.PlayList.push({id: introVideo.id, url: introVideo.flashUrl, image: introVideo.fullImage, title: introVideo.fullTitle});
						VFA.PlayList.push({id: VFA.introVideo.id, url: VFA.introVideo.flashUrl, image: VFA.introVideo.fullImage, title: VFA.introVideo.fullTitle});
						
						index = 1;

					}


					//var index = 0;  //index for grabbing the video from the playlist
					if ($(data).find('episodes').attr('totalItems') == 0) {
						//alert("No search found");
						$('#item-wrap').html('');
						$('#thumbPanel').css('display','');
						$('#votingBox').html('');
						var html = '<div class="notFound">';
						html += '<div class="notFoundText">We looked everywhere (even under the couch). Please try another search, or check out our ';
						html += '<a href="#">top rated ads</a>.';
						html += '</div></div>";'
						$('#errorMsg').html(html);
					} else {
						$('#thumbPanel').css('display','');
						$('#errorMsg').html('');
						$('#votingBox').html('');
					$(data).find('episode').each(function(){

						var newvid = Utils.storeVideoNode($(this), index);
						videoArray.push(newvid);
						VFA.currentPlaylistMap[newvid.videoId] = newvid;

						//launchDate='Thu Jun 19 00:00:00 EDT 2008' expireDate=''>
						var now = new Date();
						var newDate = new Date('Thu Jun 19 00:00:00 EDT 2008');
						var _launchDate = $(this).attr('launchDate');

						var isNew = Utils.isNewVideo(_launchDate, ThumbListArea.noOfDays);

						var _id = $(this).attr('id');
						var _collectionId = $(this).attr('collectionId');
						var _thumbnailUrl = $(this).find('thumbnailUrl').text();
						var _fullSizeStillUrl = $(this).find('fullSizeStillUrl').text();
						var _description = $(this).find('description').text();
						_description = Utils.stringShorten(_description,31);

						var _fullTitle = $(this).find('title').text();
						var _title = Utils.stringShorten(_fullTitle,18);

						var _brand = $(this).find('brand').text();
						_brand = Utils.stringShorten(_brand,20);
						var _countryId = $(this).find('country').attr('id');
						//alert("country=" + _countryId);
						var _country = $(this).find('country').text();
						var _agency = $(this).find('agency').text();
						_agency = Utils.stringShorten(_agency,20);
						var _year = $(this).find('year').text();
						var _tags = $(this).find('tags').text();
						var _featured = $(this).find('featured').text();
						var _rateable = $(this).find('rateable').text();

						var _userRating = $(this).find('userRating').text();
						_userRating = Utils.roundNumber(_userRating,1); //Math.round(_userRating * 100)/100;
						var _timesViewed = $(this).find('timesViewed').text();
						var _timesEmailed = $(this).find('timesEmailed').text();
						var _flashUrl = $(this).find('flashUrl').text();

						//Add the video to the playlist

						VFA.PlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl, title: _fullTitle});

						var headline = "";
						if ($("#item-wrap").data("loadType") == "normal") {
							headline = _brand + "<br>" + _title;
						} else {
							if($('#item-wrap').data('menuSelection') == 'menuBrands'){
								headline = _brand + "<br>" + _title;
							} else {
								headline = _country + "<br>" + _brand;
							}
						}

						//<span class="label_new" style="display: block; visibility: visible;">new</span>
						var newTag  = '<span class="label_new" style="display: block; visibility: visible;">new</span>';
						var href = 'href="' + 'index.jsp?oid=' + _id + '"'

						html = '<li><a id="videoThumb" ' + href + ' vid="' + _id + '" videoType="standard">';
						if(isNew){
							html += newTag;
						}
						html +=	'<span class="thumb_img"><img src="' + _thumbnailUrl + '" width="110" height="83"></span>';
						html += '<span class="thumb_title">' + headline + '</span>';
						html += '<span class="thumb_desc">' + _description + '</span>';
						html += '<span class="thumb_rating">rating: ' + _userRating + '</span></a></li>';
						$('#item-wrap').append($(html));

						  index = index + 1;
					});
					VFA.playList = videoArray;
					var hold = "hold";

					}

					//display the scale buttons
					$(".rating").css({'visibility' : 'visible'});
					//hide the vote button 
					$('.vote').css({'visibility' : 'hidden'});
					ThumbListArea.pagination(page);
					VFA.buildPlayer();
		},


		populateVote  : function(data, page) {
			 ThumbListArea.clearPlayList();
			 var html = '';
			 VFA.currentPlaylistMap = new Object();

	 		//Get polling cookie
	 		var storedVotes = CookieJar.getCookie(VFA.PollCookie);
			var hasVoted = false;
			if (storedVotes) {
				hasVoted = true;
			}
				ThumbListArea.videoCount = $(data).find('episodes').attr('totalItems');
					var videoArray = new Array();
					var orderArray = new Array();
					var index = 0;
					/************************
					 * add site intro
					 */

					if(VFA.introPlayed == 'false') {
					  
						if (typeof VFA.getIntroVideo == 'undefined') {
							VFA.introVideo = VFA.getIntroVideo(VFA.introUrl);
						}
					 
					 
						VFA.introPlaylistMap[VFA.introVideo.videoId] = VFA.introVideo;
						videoArray.push(VFA.introVideo);
						//videoArray.push(introVideo);
						//VFA.currentPlaylistMap[introVideoId] = introVideo;
						VFA.currentPlaylistMap[VFA.introVideo.id] = VFA.introVideo;
						//VFA.PlayList.push({id: introVideo.id, url: introVideo.flashUrl, image: introVideo.fullImage, title: introVideo.fullTitle});
						VFA.PlayList.push({id: VFA.introVideo.id, url: VFA.introVideo.flashUrl, image: VFA.introVideo.fullImage, title: VFA.introVideo.fullTitle});
						
						index = 1;

					}

					var shtml = '<h2>best of the year</h2>';
			$('.thumbHeader').html(shtml); 
					//var index = 0;  //index for grabbing the video from the playlist
					if ($(data).find('episodes').attr('totalItems') == 0) {
						//alert("No search found");
						$('#item-wrap').html('');
						$('#thumbPanel').css('display','');
						$('#votingBox').html('');
						html = '<div class="notFound">';
						html += '<div class="notFoundText">We looked everywhere (even under the couch). Please try another search, or check out our ';
						html += '<a href="#">top rated ads</a>.';
						html += '</div></div>";'
						$('#errorMsg').html(html);
					} else {
						$('#thumbPanel').css('display','');
						$('#errorMsg').html('');
						$('#votingBox').html('');
					
						
						html = '<li class="votingBlock"><span class="voteHeader2">Vote Now!<br></span>';
						html += '<span class="voteText">Watch the funniest commercials of 2009 and pick your favorite.<br><br></span>';
						html += '<span class="voteText">You may vote once per day. TBS reveals the winner on December 15!</span>';
						html +=	'</li>';	
						$('#item-wrap').append($(html));
					/*
						html= '<li><a id="videoThumb" vid="26478" href="index.jsp?oid=26478"> <span class="thumb_img">';
						html += '</span><span class="thumb_title"></span><span class="thumb_desc">When a tough mob guy like th...</span>';
						html += '<span class="thumb_rating">rating: 6.5</span></a></li>';
					*/
					$(data).find('episode').each(function(){

						var newvid = Utils.storeVideoNode($(this), index);
						videoArray.push(newvid);
						VFA.currentPlaylistMap[newvid.videoId] = newvid;

						//launchDate='Thu Jun 19 00:00:00 EDT 2008' expireDate=''>
						var now = new Date();
						var newDate = new Date('Thu Jun 19 00:00:00 EDT 2008');
						var _launchDate = $(this).attr('launchDate');

						var isNew = Utils.isNewVideo(_launchDate, ThumbListArea.noOfDays);

						var _id = $(this).attr('id');
						var _collectionId = $(this).attr('collectionId');
						var _thumbnailUrl = $(this).find('thumbnailUrl').text();
						var _fullSizeStillUrl = $(this).find('fullSizeStillUrl').text();
						var _description = $(this).find('description').text();
						_description = Utils.stringShorten(_description,31);

						var _fullTitle = $(this).find('title').text();
						var _title = Utils.stringShorten(_fullTitle,18);

						var _brand = $(this).find('brand').text();
						_brand = Utils.stringShorten(_brand,20);
						var _countryId = $(this).find('country').attr('id');
						//alert("country=" + _countryId);
						var _country = $(this).find('country').text();
						var _agency = $(this).find('agency').text();
						_agency = Utils.stringShorten(_agency,20);
						var _year = $(this).find('year').text();
						var _tags = $(this).find('tags').text();
						var _featured = $(this).find('featured').text();
						var _rateable = $(this).find('rateable').text();

						var _userRating = $(this).find('userRating').text();
						_userRating = Utils.roundNumber(_userRating,1); //Math.round(_userRating * 100)/100;
						var _timesViewed = $(this).find('timesViewed').text();
						var _timesEmailed = $(this).find('timesEmailed').text();
						var _flashUrl = $(this).find('flashUrl').text();

						//Add the video to the playlist

						VFA.PlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl, title: _fullTitle});

						var headline = "";
						if ($("#item-wrap").data("loadType") == "normal") {
							headline = _brand + "<br>" + _title;
						} else {
							if($('#item-wrap').data('menuSelection') == 'menuBrands'){
								headline = _brand + "<br>" + _title;
							} else {
								headline = _country + "<br>" + _brand;
							}
						}

						//<span class="label_new" style="display: block; visibility: visible;">new</span>
						var newTag  = '<span class="label_new" style="display: block; visibility: visible;">new</span>';
						var iVotedTag = '<span id="label_my_pick" style="display: block; visibility: visible;">My Pick</span>';
						var href = 'href="' + 'index.jsp?oid=' + _id + '"'
						
						
						html = '<li><a id="videoThumb" ' + href + ' vid="' + _id + '" videoType="pollVideo">';
						
						//add the i voted label when 
						var storedVoteId = CookieJar.getCookie(VFA.PollCookie);
					 	if(storedVoteId == _id) {
					 		html += iVotedTag;
					 	}
						if(isNew){
							html += newTag;
						}
						
						html +=	'<span class="thumb_img"><img src="' + _thumbnailUrl + '" width="110" height="83"></span>';
						html += '<span class="thumb_title">' + headline + '</span>';
						html += '<span class="thumb_desc">' + _description + '</span>';
						html += '<span class="thumb_rating">rating: ' + _userRating + '</span></a></li>';
						$('#item-wrap').append($(html));

						  index = index + 1;
					});
					VFA.playList = videoArray;
					var hold = "hold";

					}
					$('.voteBtn').css({'visibility' : 'visible'});
					if (hasVoted) {
						var msg = '<span class="pollError">You have already voted today. Please vote again tomorrow.</span>';
						/*
						$(".votingMsg").html(msg);
						$('.voteBtn').css({'display' : 'none'});
						$('#votingMessage').css({'display' : 'none'});
						* */
						VFAPlayer.voteButtonState("hide");
					}  
					 
					//hide the scale buttons
					$(".rating").css({'visibility' : 'hidden'});
					//display the vote button 
					
					$('#pagination2').css({'visibility' : 'hidden'});
					ThumbListArea.pagination(page);
					VFA.buildPlayer();
		},
		/***********************************
		 * Build the playlist, playlistMap and the thumbnails
		 */
		populateEditorsPicks : function(data) {
			  //editorsPlayList
			  //editorsPickMap
				ThumbListArea.videoCount = $(data).find('episodes').attr('totalItems');
					var videoArray = new Array();
					var orderArray = new Array();
					var index = 0;  //index for grabbing the video from the playlist
					$(data).find('episode').each(function(){

						var newvid = Utils.storeVideoNode($(this), index);
						videoArray.push(newvid);
						VFA.editorsPickMap[newvid.videoId] = newvid;

						var _id = $(this).attr('id');
						var _collectionId = $(this).attr('collectionId');
						var _thumbnailUrl = $(this).find('thumbnailUrl').text();
						var _fullSizeStillUrl = $(this).find('fullSizeStillUrl').text();
						var _description = $(this).find('description').text();
						_description = Utils.stringShorten(_description,28);
						var _launchDate = $(this).attr('launchDate');
						var isNew = Utils.isNewVideo(_launchDate, ThumbListArea.noOfDays);
						var _fullTitle = $(this).find('title').text();
						var _title = Utils.stringShorten(_fullTitle,13);
						var _brand = $(this).find('brand').text();
						_brand = Utils.stringShorten(_brand,20);
						var _country = $(this).find('country').text();
						var _agency = $(this).find('agency').text();
						_agency = Utils.stringShorten(_agency,20);
						var _year = $(this).find('year').text();
						var _tags = $(this).find('tags').text();
						var _featured = $(this).find('featured').text();
						var _rateable = $(this).find('rateable').text();

						var _userRating = $(this).find('userRating').text();
						_userRating = Utils.roundNumber(_userRating,1); //Math.round(_userRating * 100)/100;
						var _timesViewed = $(this).find('timesViewed').text();
						var _timesEmailed = $(this).find('timesEmailed').text();
						var _flashUrl = $(this).find('flashUrl').text();

						//Add the video to the playlist

						VFA.editorsPlayList.push({id: _id, url: _flashUrl, image: _fullSizeStillUrl, title: _fullTitle});

						/*this where we will update the ads*/
						//changeAd(section)
						var newTag  = '<span class="label_new" style="display: block; visibility: visible;">new</span>';

						var href = 'href="index.jsp?oid=' + _id + '"'
						var html = '<li><a id="videoThumb" ' + href + ' vid="' + _id + '" videoType="editorsPick">';

						if(isNew){
							html += newTag;
						}
						html +=	'<span class="thumb_img"><img src="' + _thumbnailUrl + '" width="110" height="83"></span>';
						html += '<span class="thumb_title">' + _brand + "<br>" + _title + '</span>';
						html += '<span class="thumb_desc">' + _description + '</span>';
						html += '<span class="thumb_rating">rating: ' + _userRating + '</span></a></li>';
						$('#editors_picks').append($(html));

						  index = index + 1;
					});
					//VFA.playList = videoArray;
					//var hold = "hold";



		},
	 	/**********************************
	 	 * Updates the area below the video player
	 	 */
	 	updatePlayer : function(videoInfo) {
	 		//var videoInfo = VFA.currentPlaylistMap[videoId];
	 		//set the current Video Object for Poll Sever
	 		VFAPlayer.currentVideoPlaying = videoInfo;
	 		
	 		$(".player").data("videoId", videoInfo.videoId);
	 		$("#fp_videoId").attr("value",videoInfo.videoId);
	 		//set the document title
	 		document.title = videoInfo.brand + " - " + videoInfo.title + " - very funny ads";
			//Utils.updateFacebookHeader(videoInfo.title,videoInfo.description, videoInfo.image );
			
			
			var headingHTML = '<span id="videoInfoHeader"><h1>'+ videoInfo.brand + ":" + videoInfo.title + '</h1>';
			headingHTML = headingHTML + '<p>'+ videoInfo.description + '</p></span>';
			$('#videoHeader').html(headingHTML);

			//set background
			ThumbListArea.updateBackground(videoInfo);

			var searchUrl = "http://search.veryfunnyads.com/vfa/pages/vfaSearchXml.jsp?Query=" + videoInfo.year + "&offset=" + ThumbListArea.offset + "&sort=&length=" + ThumbListArea.limit;
			//VFA.PageUrl + "";
			//<a href="/veryfunnyads/getVideoByType.do?offset="0"&id='+ videoInfo.collectionId+'&sort=&limit='+ ThumbListArea.limit +'>' + videoInfo.country + '</a>
			//

			var linksHTML = '<div id="metaLinks"><dt>country:</dt>';
				linksHTML = linksHTML + '<dd style="width: 200px;" class="country">&nbsp;<a href="#">' + videoInfo.country + '</a></dd>';
				linksHTML = linksHTML + '<dt>brand:</dt>';
				linksHTML = linksHTML + '<dd class="brand"><a href="#">' + videoInfo.brand + '</a></dd>';
				linksHTML = linksHTML + '<dt>year:</dt>';
				linksHTML = linksHTML + '<dd class="year"><a href="#">' + videoInfo.year + '</a></dd></div>';
			$('.info_links').html(linksHTML);

			var numbersHTML = '<dt>overall rating:</dt>';
				numbersHTML = numbersHTML + '<dd>' + videoInfo.userRating + '</dd>';
				numbersHTML = numbersHTML + '<dt>views:</dt>';
				numbersHTML = numbersHTML + '<dd>' + videoInfo.timesViewed + '</dd>';
				numbersHTML = numbersHTML + '<dt>emails:</dt>';
				numbersHTML = numbersHTML + '<dd>' + videoInfo.timesEmailed + '</dd>';
			$('.info_numbers').html(numbersHTML);
			$('#metaLinks').data("countryId", videoInfo.countryId);
			$('#metaLinks').data("brandId", videoInfo.brandId);

			$('#metaLinks').data("year", videoInfo.year);
			//set the hidden input for the emailer
			$('#fp_videoId').attr('value',videoInfo.videoId);
			/*
			//set the background
			var backgroundImg = videoInfo.fullImage;
			var bgdHTML = '<img src="' + backgroundImg + '"><img src="' + backgroundImg + '">';
			$('#background').html(bgdHTML);
			*/
	 		//share data update
	 		var shareLinkHtml =  '<input type="text" name="linkurl" value="http://www.veryfunnyads.com/?oid=' + videoInfo.videoId + '"/>';
	 		$('#share_link_input').html(shareLinkHtml);

	 		//clear the voting
	 		$(".rating li a").removeClass('chosen');
	 		var videoId = $(".player").data("videoId");
	 		var voterRating = VFA.votingMap[videoId];
	 		if (voterRating != null || voterRating != "") {
	 			//add voted info here

	 			var rateClass = ".rate" + voterRating + " a";
	 			var button = $(".rating ul").find(rateClass);

	 			$(button).addClass("chosen");
	 			$(button).parent().prevAll().children("a").addClass("chosen");

	 			/*
	 			$(button).parent().nextAll().children("a").hover(function(){
	 				$(this).addClass
	 			})
	 			*/
	 			//$(button).parent().nextAll().children("a").removeClass("a:hover");
	 			//$(".rating li a").css({'hover':''});
	 		}
	 		//update the share website links
	 		var vidUrl = 'http://www.veryfunnyads.com/?oid=' + videoInfo.videoId
	 		VFAPlayer.shareSite(vidUrl,videoInfo.title);

	 		if(videoInfo.embed == 'Y' || videoInfo.embed == 'y') {

	 		/*
	 		<form id="shareForm" action="#" class="share_embed">
				<label for="embedcode">Embed:</label>
				<input type="text" name="embedcode" value="<object><embed></embed></object>">
			</form>
			*/
	 		} else {
	 			$('#embed-div').hide();
	 		}
	 		//check to see if voter previously voted on this video
	 		//if so show alternate button
			
			if (VFAPlayer.videoType == "pollVideo") {
				VFA.isVoting = "true";
			} else {
				VFA.isVoting = "false";
			}
			var storedVoteId = CookieJar.getCookie(VFA.PollCookie);
		 	//VFAPlayer.hasVoted = "false";
		 	if(storedVoteId) {
		 		VFAPlayer.hasVoted = "true";
		 	}
		 	//set the vote button color
		 	if(storedVoteId == videoId) {
		 		$(".votingBtn img").attr("src","/veryfunnyads/img/btn_my_pick.gif");
		 		VFAPlayer.voteButtonState("show");
		 	} else {
		 		if(VFAPlayer.hasVoted != "true") {
		 			$(".votingBtn img").attr("src","/veryfunnyads/img/btn_i_pick_this_ad.gif");
		 			VFAPlayer.voteButtonState("hide");
		 		}  
		 	}
		 	
		 	if(VFA.isVoting == "true"){
		 		if(VFAPlayer.hasVoted == "true" && storedVoteId != videoId) {
		 			VFAPlayer.voteButtonState("hasVoted");
		 		} else {
		 			VFAPlayer.voteButtonState("show");
		 		}
		 		
		 	} else {
		 		VFAPlayer.voteButtonState("hide");
		 	}
		 	//hide voting for intro video
		 	if(videoId == "26570") {
		 		VFAPlayer.voteButtonState("hide");
		 	}
		 	
	 		//ThumbListArea.clearVoting();
	 		//alert($('.share_link input').attr('value)'));

			//<input type="text" name="linkurl" value="http://www.veryfunnyads.com/v=1564"/>
	 	},

		clearVoting : function() {
			$('.rating ul li a').removeClass('chosen');
		 /*
		//rated will be pulled from the user cookie

		if (Menu_UI.rated == 0) {

			$(this).addClass("chosen");
			$(this).parent().prevAll().children("a").addClass("chosen");
			Menu_UI.rated = 1;
		}

		// handle the user voting
		// grab the videoId from the player
		var videoId = $(".player").data("videoId");
		var rating = $(this).html();
		//var rating = rating/2;
		var rating = Math.ceil(rating/2);
		//alert("temp - " + videoId + "-" + rate);
		VFA.updateUserVote(videoId, rating);
		* */

		},

		updateBackground : function(videoInfo) {
			//var videoInfo = VFA.allPlaylistMap[videoId];
			var backgroundImg = videoInfo.fullImage;
			var bgdHTML = '<img src="' + backgroundImg + '" width="400" height="304"><img src="' + backgroundImg + '" width="400" height="304">';
			$('#background').html(bgdHTML);
		},

		buildShare : function() {
			//<script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_link { padding:2px 0 0 20px; height:16px; background:url(http://b.static.ak.fbcdn.net/images/share/facebook_share_icon.gif?8:26981) no-repeat top left; }</style><a href="http://www.facebook.com/share.php?u=<url>" onclick="return fbs_click()" target="_blank" class="fb_share_link">Share on Facebook</a>
		},

		paginationHTML : function(page) {
				ThumbListArea.carousel_itemList = [];
				var isCreated = $('#pagination').data("isCreated");
				var paginationHTML = "";
				if (Pager.isCreated != "true") {
				 	$('#pagination').html(paginationHTML);
					var count = 1;
					//round up
					var _pageCount = Math.ceil(ThumbListArea.videoCount / ThumbListArea.limit);
					$('#pagination').data("lastPage", _pageCount);
				    paginationHTML = '<p class="pagination_prev"><a href="#" class="ir">prev</a></p>';
					var selected = "";
					while (count <= _pageCount ) {
						var pipe = "";
						if (count == page) {
							selected = " current";
						}
						if (count != page) {
							pipe = "|"
						}
						var carouselItem = '<p class="pagination_numb'+ selected + '"><a href="#">' + count + '</a></p>' + pipe;
						paginationHTML += '<p class="pagination_numb'+ selected + '"><a href="#">' + count + '</a></p>';

						ThumbListArea.carousel_itemList.push(carouselItem);
						selected = "";
						count = count + 1;
					}
					paginationHTML += '<p class="pagination_next"><a href="#" class="ir">next</a></p>';


					$('#pagination').append($(paginationHTML));
					Pager.init();
					//$('#pagination').data("isCreated", "true");
					Pager.isCreated = true;
				}


				//creatPager();
		},

		pagination : function(page) {

				var itemArray = new Array();
				var isCreated = $('#pagination').data("isCreated");
				var paginationHTML = "";
				if (Pager.isCreated == false) {
				 	//	$('#pagination').html(paginationHTML);
					var count = 1;
					//round up
					var _pageCount = Math.ceil(ThumbListArea.videoCount / ThumbListArea.limit);
					$('#pagination').data("lastPage", _pageCount);
				     var selected = "";
					while (count <= _pageCount ) {
						var pipe = "";
						if (count == page) {
							selected = " current";
						}
						if (count != _pageCount) {
							pipe = "|"
						}
						var carouselItem = '<p class="pagination_numb'+ selected + '"><a class="pageLink" href="#">' + count + '</a></p>';
						paginationHTML += '<p class="pagination_numb'+ selected + '"><a class="pageLink" href="#">' + count + '</a></p>' + pipe;
						itemArray.push(carouselItem);
						selected = "";
						count = count + 1;
					}

					ThumbListArea.carousel_itemsHTML = paginationHTML;
					ThumbListArea.carousel_itemList = itemArray;
					//$('#pagination').append($(paginationHTML));
					Pager.init(page);
					//$('#pagination').data("isCreated", "true");
					Pager.isCreated = true;
				}

		},
		/**********************
		 Update the pagination
		 */
	 	updatePagination : function(page) {
	 		var pages = $('.pagination_numb');
				$('.pagination_numb').removeClass('current');
				$('.pagination_numb').each(function(index){
					$pageLink = $(this);
					if (page == $pageLink.text()) {
						$pageLink.addClass("current");
					} else {
						$pageLink.removeClass("current");
					}


				});
	 	}

}

var VFAPlayer = {
	currentVideoPlaying : new Object(),
	videoType : "pollVideo",
	hasVoted : "false",
	init : function() {


		//handles the emailForm
		$("#deliciousForm").submit({
			success : function() {
				var msg = 'Thank you';
			}
		});

		//handles the emailForm
		$("#faceboForm").submit({
			success : function() {
				var msg = 'Thank you';
				alert("form sent");

			}
		});
		//handles the emailForm
		var options = {
			//target: "#divResult",
			beforeSubmit: VFAPlayer.validate,
			dataType: 'xml',
			//url: '/processors/veryfunnyads/sendtoafriend09.jsp',
			//clearForm: true,
			resetForm: true,
			type: 'POST',
			success : VFAPlayer.processXml
		};
		
		$("#emailForm").validate();
		
		$("#emailForm").submit(function(){
			var emailInsertUrl = "/processors/vfaEmailsInsert.do?contentId=" + $(".player").data("videoId");
			$.ajax({
				type: "GET",
				url : emailInsertUrl,
				cache : true,
				dataType: "text",
				success : function(data) {
					var result = "yes"; 
					
				}
			});
			
		 
			var voteUrl = "/processors/veryfunnyads/sendtoafriend09.jsp";
			$.ajax({
				type: "POST",
				url : voteUrl,
				cache : true,
				dataType: "xml",
				success : function(data) {
					var result = "yes";
					VFAPlayer.clearEmailForm();
					
				}
			});
		 
		return false;
		});
		
		
	 
		
		
		/*
		 * $("#emailForm").submit({
			success : function() {
				var msg = 'Thank you';
				alert("form sent");

			}
		});
		
		$("#emailForm").ajaxForm({
			target: '#divResult',
			beforeSubmit: VFAPlayer.showRequest,
			success: VFAPlayer.showResponse
		});
		*/
		//$("#emailForm").ajaxForm(options);
		/*
		$("#emailForm").submit(function() {
			VFAPlayer.updateEmailView($(".player").data("videoId"));
			$(this).ajaxSubmit(options);
			VFAPlayer.clearEmailForm();
			//prevent default submitting of form
			return false;
		});
		*/
		
		
		
		
		//handles the shareForm
		$("#shareForm").ajaxForm(function() {
		 		alert("shareForm thankyou");


		});

		//handles the linkForm
		$("#linkForm").ajaxForm(function() {
		 		alert("linkForm thankyou");
		});

		//handles the newsletter
		$("#newsletterSubmit").ajaxForm({
			url: '/processors/vfaEmailAlertsInsert.do?action=add&format=html&list=tbs%2Dveryfunnyads&email=' + $('#newsletterSubmit :text').fieldValue()[0],
			beforeSubmit: VFAPlayer.validateNewsletter,
			resetForm: true,
			success : function() {
				//alert("email sent");
			}
		});

		
		

		//Handles the link in the country
		$("#metaLinks .country").livequery("click", function(e){
			 MainNav.buildSortMenu('view');
			 var sLabel = $(this).find("a").html();
			 var collectionId = $("#metaLinks").data("countryId");
			 VFA.omnitureCategory = "Country";
			 VFA.omnitureSubCategory = sLabel;
			 //$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			trackCategoryViews("Country", sLabel);
	  		 var header = Utils.stringShorten(sLabel, 16);
	  		 var shtml = '<h2>' + header + '</h2>';
			 var shtml = VFA.updateHeader(collectionId,header);
			 //disable voting
			 
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "byType");
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			//ThumbListArea.loadVideo();
			e.preventDefault();
			return false;

		});

		//Handles the brand link in the video player
		$("#metaLinks .brand").livequery("click", function(e){
			MainNav.buildSortMenu('view');
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			$("#item-wrap").data("loadType", "byType");
			var sLabel = $(this).find("a").html();
			VFA.omnitureCategory = "Country";
			VFA.omnitureSubCategory = sLabel;
	  		 trackCategoryViews("Brand", sLabel);
	  		 var header = Utils.stringShorten(sLabel, 16);
	  		 var shtml = '<h2>' + header + '</h2>';
			//disable voting
			  
			$('.thumbHeader').html(shtml);
			VFA.TodaysTopId = $("#metaLinks").data("brandId");
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			e.preventDefault();
			return false;

		});

	  //Handles the year click in the video player div
	  	$("#metaLinks .year").livequery("click", function(e){
	  		 MainNav.buildSortMenu('view');
	  		 //$('#pagination').data("isCreated", 'false');
	  		 Pager.isCreated = false;
	  		 var sLabel = $(this).html();
	  		 VFA.omnitureCategory = "Year";
			VFA.omnitureSubCategory = sLabel;
	  		 trackCategoryViews("Year", sLabel);
	  		 var header = Utils.stringShorten(sLabel, 16);
	  		 var shtml = '<h2>' + header + '</h2>';
	  		 //disable voting
			 
			$('.thumbHeader').html(shtml);
	  		 VFA.sort = 'sort';
	  		 ThumbListArea.searchQuery = $('#metaLinks').data("year");
	  		 ThumbListArea.page = 1;
	  		 ThumbListArea.loadSearchVideo();
			 e.preventDefault();
			 return false;

		});


	},
	
	/*Hide the vote buttons and associated items when voting and handling menus */
	voteButtonState : function(state) {
		if(state == "show") {
			$(".rating").css({'visibility' : 'hidden'});
			//display the vote button 
			$('.voteBtn').css({'display' : ''});
			$('.voteBtn').css({'visibility' : 'visible'});
			$('#pagination2').css({'visibility' : 'hidden'});
			$('.votingMsg').css({'display' : 'none'});
		} 
		if (state == "hide") {
			$(".rating").css({'visibility' : 'visible'});
			//display the vote button 
			$('.voteBtn').css({'display' : 'none'});
			$('#pagination2').css({'visibility' : 'visible'});
			$('.votingMsg').css({'display' : 'none'});
		}
		if (state == "hasVoted") {
			$(".rating").css({'visibility' : 'hidden'});
			//display the vote button 
			$('.voteBtn').css({'visibility' : 'hidden'});
			$('#pagination2').css({'visibility' : 'hidden'});
			$('.votingMsg').css({'display' : 'none'});
		}
		
	},
	
	updateEmailView : function(videoId) {
		$.ajax({
					type: "GET",
					url : 'http://www.tbs.com/processors/vfaEmailsInsert.do?contentId=' + videoId,
					cache : true,
					dataType: "xml",
					success : function(data) {
						 
					}
				});
	},
	
	
	processXml : function(responseXML) {
		var message = $('message', responseXML).text(); 
    	alert(message);
	},
	
	
	showRequest : function(formData, jqForm, options) {
		var queryString = $.param(formData);
		alert("about to submit:" + queryString);
		return true
	},
	showResponse : function(responseText, statusText) {
		
		var msg = "status:" + statusText + "  -  responseText: " + statusText;
		//$('#divResult').html('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
       // '\n\nThe output div should have already been updated with the responseText.');
		//e.preventDefault();
		//return false;
	},
	
	clearEmailForm : function() {
		$('#fp_sender').attr('value','');
		$('#fp_sender_email').attr('value','');
		$('#fp_friend').attr('value','');
		$('#fp_friend_email').attr('value','');
		$('#fp_message').attr('value',''); 
	},
	
	submitSearch : function() {
		//handles the searchForm
		$("#searchForm").ajaxForm({

			beforeSubmit: VFAPlayer.validateSearch,
			resetForm: true,
			success : function() {
				var searchValue = $('#search_input').attr('value');

				VFA.omnitureCategory = "Search";
				VFA.omnitureSubCategory = toLowerCase($(this).html());
				ThumbListArea.page = 1;
				//$('#pagination').data("isCreated", 'false');
				Pager.isCreated = false;
				ThumbListArea.loadSearchVideo();
				//alert("Query =  " + ThumbListArea.searchQuery);

			}
			//return false;

		});

	},

	validateSearch : function(formData, jqForm, options) {
		 var form = jqForm[0];

		 if (!form.search_input.value) {
		 	alert("please insert a value");
		 	return false;
		 }
		 ThumbListArea.searchQuery = form.search_input.value;

	},
	validate : function(formData, jqForm, options) {
		for(var i=0; i<formData.length; i++) {
			if (!formData[i].value){
				//don't check fp_message since its optional
				if(formData[i].name != 'fp_message') {
					alert("please enter a valid email address");
					return false;
				}
			}
		}
		//alert("All fields contain data");
	},

	validateNewsletter : function(formData, jqForm, options) {
		for(var i=0; i<formData.length; i++) {
			if (!formData[i].value || formData[i].value == "Your email address"){
				//don't check fp_message since its optional

					alert("please e email " + formData[i].name);
					return false;

			}
		}
		//alert("All fields contain data");
	},

	//Build social sharing code
	shareSite : function(url, title) {
		//if ($("#deliciousForm :hidden").fieldValue()[0]) {

			 var newUrl = 'return addthis_open(this, "", "' + url + '","'+ title + '")';

			var shareHTML = '<!-- AddThis Button BEGIN -->';
			shareHTML += '<a href="http://www.addthis.com/bookmark.php"';
			shareHTML += " onmouseover='" + newUrl + "'";
			shareHTML += " onmouseout='addthis_close()' onclick='return addthis_sendto()'>";
			shareHTML += '<img src="/veryfunnyads/img/vfa_share_icons.png" width="329" height="48" alt="Bookmark and Share" style="border:0"/></a>';
			shareHTML += '<!-- AddThis Button END -->';
			$(".shareHTML").html(shareHTML);

		//}

	},

	createEmbedVideo : function(id) {
		/*
		 * <object width="400" height="330" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ep">
			<param name="allowfullscreen" value="true" />
			<param name="allowscriptaccess" value="always" />
			<param name="movie" value="player.swf?videoId=26341" />
			<param name="bgcolor" value="#ffffff" />
			<embed src="player.swf?videoId=26341" type="application/x-shockwave-flash" bgcolor="#ffffff"
				allowfullscreen="true" allowscriptaccess="always" width="400" height="330">
			</embed>

		</object>


		 */
		 var embedHTML = '<object width="400" height="330" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ep">';
		 embedHTML = embedHTML + '<param name="allowfullscreen" value="true" />';
		 embedHTML = embedHTML + '<param name="allowscriptaccess" value="always" />';
		 embedHTML = embedHTML + '<param name="movie" value="player.swf?videoId=' + id +'" />';
		 embedHTML = embedHTML + '<param name="bgcolor" value="#ffffff" />';
		 embedHTML = embedHTML + '<embed src="player.swf?videoId=' + id + '" type="application/x-shockwave-flash" bgcolor="#ffffff"';
		 embedHTML = embedHTML + ' allowfullscreen="true" allowscriptaccess="always" width="400" height="330">';
		 embedHTML = embedHTML + '</embed></object>'
	}

}

var Blog = {
	init : function() {
		Blog.getBlog();
	},

	/***********************************
	 * Get the latest blog
	 */
	getBlog : function() {

		//   "/2009/inc/blog.xml"
		//http://teg8fref1.turner.com:9220/processors/veryfunnyads/getBlogXml.jsp
		var blogUrl = "/veryfunnyads/getBlogXml.jsp";
		$.ajax({
			type: "GET",
			url : blogUrl,
			cache : true,
			dataType: "xml",
			success : function(data) {

				Blog.populateBlog(data);
			}
		});

	},

	/***********************
	 * handles populating the blog
	 * Section in the index page
	 */
populateBlog : function(data) {
		 			 /*
					  * <div class="mini_title">
				<h2><a href="#">the vfa blog</a></h2>
			</div><!--thumb_title-->
			<div class="blog_teaser_wrap">
			<div class="blog_teaser">
				<div class="rel">
				<p class="blog_intro_img"><a href="#"><img src="/2009/img/fpo/bondsunderwearfreestyler110x83.jpg"></a></p>
				<h3><a href="#">Dale Carnegie Training: Robber</a></h3>
				<p class="blog_intro_desc">This is the place to see the funniest TV ads in the world...</p>
				<p class="blog_intro_more"><a href="#">See all the new blog entries</a></p>
				</div>
			</div><!--blog_teaser-->
					  */
					var index = 1;  //index for grabbing the video from the playlist
					$(data).find('blog').each(function(){

						if(index == 1) {
							var title = $(this).find('title').text();
							var link = $(this).find('link').text();
							var id = $(this).find('id').text();
							var description = $(this).find('description').text();
							description = Utils.stringShorten(description,185);
						 	var imgLink = $(this).find('image').text();
						 	var guid = $(this).find('guid').text();
						 	var pubDate = $(this).find('pubDate').text();
						 	//var href = ''

						 	var blogImg = '<a href="' + link + '"><img src="' + imgLink + '" width="110" height="83"></a>';
							$('.blog_intro_img').html(blogImg);
							var blogIngLink = '<a href="' + link + '">'+ title + '</a>';
							$('.blog_teaser h3').html(blogIngLink);
							//var blogIntroDesc =
							Utils.stringShorten($('.blog_intro_desc').html(description));

						}

 					  index = index + 1;
					});


	}
}

/*********************************************************
   Controls all of the meun behavior
   ************/

var Menu_UI = {
	rated : 0,
	init : function() {
		$('#search_input').one("click", function(){
		$(this).val("");


	});

	$('#email_signup').one("click", function(){
		$(this).val("");
	});

	$('.share_trigger').click(function(){
	$('.share').toggle("blind", { direction: "vertical" }, 500);

	});

	$('.share_blog').click(function(){
	$(this).parent().next('.share').toggle("blind", { direction: "vertical" }, 500);

	});


	$(".link_list_nav").tabs({ fx: { opacity: 'toggle' } });

	//user voting
	$('.rating ul li a').click(function(){
		 var videoId = $(".player").data("videoId");
		//rated will be pulled from the user cookie
		//check to see if user voted on this video before

	 	var voterRating = VFA.votingMap[videoId];

	 	if (voterRating == null || voterRating == "") {
			if (Menu_UI.rated == 0) {
				$(this).addClass("chosen");
				$(this).parent().prevAll().children("a").addClass("chosen");
				Menu_UI.rated = 1;
			}
			// handle the user voting

			var rating = $(this).html();

			VFA.updateUserVote(videoId, rating);
			Menu_UI.rated = 0;
		}


	});


	//IE7 required this Javascript to make the hovers worked

	$("#label_my_pick").parent("a").bind("mouseenter",function(){
		$("#label_my_pick").css({'visibility' : 'hidden'});
	}).bind("mouseleave",function(){
		$("#label_my_pick").css({'visibility' : 'visible'});
	});

	$("#label_my_pick").css({'display' : 'block'});


	$(".label_new").parent("a").bind("mouseenter",function(){
		$(".label_new").css({'visibility' : 'hidden'});
	}).bind("mouseleave",function(){
		$(".label_new").css({'visibility' : 'visible'});
	});

	$(".label_new").css({'display' : 'block'});
	}
}


/************************************************
	 Builds the Main Nav
************************************************/

var MainNav = {

	timeout : 500,
	closetimer : 0,
	ddmenuitem : 0,
	collectionNavId : 26322,
	sortHeader : '',

	init : function() {
		// highlight the selected main nav item now

		//Here is where we will create the menus
		//MainNav.highlightSelected();

		$('#vfa_menu > li').bind('mouseover', MainNav.vfa_menu_open);
		$('#vfa_menu > li').bind('mouseout',  MainNav.vfa_menu_timer);

		$('#vfa_sort > li').bind('mouseover', MainNav.vfa_menu_open);
		$('#vfa_sort > li').bind('mouseout',  MainNav.vfa_menu_timer);

		$('#vfa_menu').livequery("click", function(e) {
			e.preventDefault();
			return false;
		});


		//search box binders
		var searchBox = $("input.data-entry");

		//check for zilla's keypress
		if ($.browser.mozilla) {
			$("input.data-entry").keypress (MainNav.checkForEnter);
		} else {
			$("input.data-entry").keydown (MainNav.checkForEnter);
		}


		//Handle the sort drop down
		$("#vfa_sort li a").livequery("click", function(e){
			  VFA.mode = "normal";
			  var sortItem = $(this).attr("id");
				ThumbListArea.page = 1;
			  //var sortHeader = '';
			  if (sortItem == '') {
			  	ThumbListArea.sort = "views";
			  	MainNav.sortHeader = 'most watched';
			  } else if (sortItem == 'sortDate') {
			  	ThumbListArea.sort = "date";
			  	MainNav.sortHeader = 'most recent';
			  } else if (sortItem == 'sortViews') {
			  	ThumbListArea.sort = "";
			  	MainNav.sortHeader = 'most watched';
			  } else if (sortItem == 'sortTopRated') {
			  	ThumbListArea.sort = "";
			  	MainNav.sortHeader = 'top rated';
			  } else if (sortItem == 'daysback7') {
			  	ThumbListArea.daysback = "7";
			  } else if (sortItem == 'daysback30') {
			  	ThumbListArea.daysback = "30";
			  } else if (sortItem == '') {
			  	ThumbListArea.daysback = "";
			  }


			  var shtml = '<h2>' + MainNav.sortHeader + '</h2>';
			  $('.thumbHeader').html(shtml);
			  //refresh list

			  //set the pagination back to not created
			  //$('#pagination').data("isCreated", 'false');
			  Pager.isCreated = false;
			  if(VFA.mode == 'normal') {
			 
				ThumbListArea.loadVideosByCollectionId(VFA.TodaysTopId);
			  } else {
				ThumbListArea.loadSearchVideo();
			  }
			  e.preventDefault();

				return false;

		});


		//Handle the menu top ads
		$(".menuTopAds li a").livequery("click", function(e){
		   var sortItem = $(this).attr("class");
		   VFA.mode = "normal";
		   if (sortItem == '') {
			  	ThumbListArea.sort = "views";
			  	MainNav.sortHeader = 'most watched';
			  } else if (sortItem == 'sortDate') {
			  	ThumbListArea.sort = "date";
			  	MainNav.sortHeader = 'most recent';
			  } else if (sortItem == 'sortTopRated') {
			  	ThumbListArea.sort = "";
			  	MainNav.sortHeader = 'top rated';
			  } else if (sortItem == 'sortViews') {
			  	ThumbListArea.sort = "views";
			  	MainNav.sortHeader = 'most watched';
			  }

			var shtml = '<h2>' + MainNav.sortHeader + '</h2>';
			VFA.omnitureCategory = "Top Ads";
			VFA.omnitureSubCategory = MainNav.sortHeader;
			trackCategoryViews("Top Ads", MainNav.sortHeader);
			$('.thumbHeader').html(shtml);
			MainNav.buildSortMenu('view');
			//disable voting
			 VFA.isVoting = 'false';
			 //hide the scale buttons
			
			//display the vote button 
			VFAPlayer.voteButtonState("hide");
			
			 ///ThumbListArea.loadType = "byType";
			$("#item-wrap").data("loadType", "normal");
			$('#item-wrap').data('menuSelection', 'menuTopAds');
			VFA.TodaysTopId = $(this).attr("id");
			ThumbListArea.page = 1;
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			//ThumbListArea.loadVideo();
			ThumbListArea.loadVideosByCollectionId($(this).attr("id"));
			e.preventDefault();
			return false;

		});


			/*
			  var sortItem = $(this).attr("id");
			  //var sortHeader = '';


			  if (sortItem == '') {
			  	ThumbListArea.sort = "views";
			  	MainNav.sortHeader = 'most views';
			  } else if (sortItem == 'sortDate') {
			  	ThumbListArea.sort = "date";
			  	MainNav.sortHeader = 'most recent';
			  } else if (sortItem == 'sortTopRated') {
			  	ThumbListArea.sort = "rated";
			  	MainNav.sortHeader = 'top rated';
			  }


			  var shtml = '<h2>' + MainNav.sortHeader + '</h2>';
			  $('.thumbHeader').html(shtml);
			  //refresh list
			  $('#pagination').data("isCreated", 'false');
			  ThumbListArea.loadVideo();
			//return false;

		});
*/
		//top add handler
		/*
		$(".menuTopAds li a").livequery("click", function(e) {

			MainNav.buildSortMenu('');
		});
	 */
	 	//my ads handler
	 	$(".menuMyAds li a").livequery("click", function(e) {
			MainNav.buildSortMenu('');
		});

		//links to too hot for tv
		$("#tooHot a").livequery("click", function(e){
			/*
			//VFA.parseDeepLinkedCollection(deepLinkedCollection); 
			//VFA.parseDeepLinkedCollection('24636');
			ThumbListArea.loadVideosByCollectionId('24636');
			//VFA.introUrl = VFA.CollectionUrl + "&limit=1&id=" + 24636 + "&offset=&sort=";
			 
			//VFA.getIntroVideo(VFA.introUrl,24636, true);
			e.preventDefault();
			return false;
			* */
			
			
			MainNav.buildSortMenu('view');
			VFA.mode = "normal";
			
			var header = 'too hot for tv';
			var collectionId = '24636';
			
			var shtml = VFA.updateHeader(collectionId, header);
			
			//var shtml = '<h2>' + $(this).html() + '</h2>';
			VFA.omnitureCategory = "To Hot For TV";
			VFA.omnitureSubCategory = $(this).html();
			trackCategoryViews("To hot for tv", $(this).html());
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "normal");
			$('#item-wrap').data('menuSelection', 'menuCategories');
			VFA.section = $(this).text();
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			//disable voting
			VFA.isVoting = 'false';
			//hide the scale buttons
			VFAPlayer.voteButtonState("hide");
					
			//create a new pagination
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			//ThumbListArea.loadVideo();
			e.preventDefault();
			return false;
			
			
		});
		
		//links to external blog site
		$("#blog_link a").livequery("click", function(e){
			window.location="http://blog.veryfunnyads.com";
		});
		//categories handler
	 	$(".menuCategories li a").livequery("click", function(e) {
			MainNav.buildSortMenu('view');
			VFA.mode = "normal";
			
			var header = $(this).html();
			var collectionId = $(this).attr("id");
			
			var shtml = VFA.updateHeader(collectionId, header);
			
			//var shtml = '<h2>' + $(this).html() + '</h2>';
			VFA.omnitureCategory = "Categories";
			VFA.omnitureSubCategory = $(this).html();
			trackCategoryViews("Categories", $(this).html());
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "normal");
			$('#item-wrap').data('menuSelection', 'menuCategories');
			VFA.section = $(this).text();
			//disable voting
			 VFA.isVoting = 'false';
			 //hide the scale buttons
			 VFAPlayer.voteButtonState("hide");
			
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			//create a new pagination
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			//ThumbListArea.loadVideo();
			e.preventDefault();
			return false;
		});

		//my ads handler
	 	$(".menuBrands li a").livequery("click", function(e) {
			MainNav.buildSortMenu('view');
			ThumbListArea.sort="brand";
			var header = $(this).html();
			var collectionId = $(this).attr("id");
			VFA.mode = "normal";
			VFA.omnitureCategory = "Brands";
			VFA.omnitureSubCategory = header;
			trackCategoryViews("Brands", header);
			//disable voting
			 VFA.isVoting = 'false';
			 //hide the scale buttons
			 VFAPlayer.voteButtonState("hide");
			
			var shtml = VFA.updateHeader(collectionId, header);
			
			//var shtml = '<h2>' + $(this).html() + '</h2>';
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "byType");
			$('#item-wrap').data('menuSelection', 'menuBrands');
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			//ThumbListArea.loadVideo();
			//ThumbListArea.sort="";
			e.preventDefault();
			return false;

		});

		//my ads handler
	 	$(".menuCountries li a").livequery("click", function(e) {
			MainNav.buildSortMenu('view');
			ThumbListArea.sort="country";
			var header = $(this).html();
			var collectionId = $(this).attr("id");
			VFA.omnitureCategory = "Countries";
			VFA.omnitureSubCategory = header;
			trackCategoryViews("Countries", header);
			VFA.mode = "normal";
			//var utils
			//disable voting
			 VFA.isVoting = 'false';
			 //hide the scale buttons
			 VFAPlayer.voteButtonState("hide");
			
			var shtml = VFA.updateHeader(collectionId, header);
			//var shtml = '<h2>' + $(this).html() + '</h2>';
			$('.thumbHeader').html(shtml);
			$("#item-wrap").data("loadType", "byType");
			$('#item-wrap').data('menuSelection', 'menuCountries');
			VFA.TodaysTopId = collectionId;
			ThumbListArea.page = 1;
			//$('#pagination').data("isCreated", 'false');
			Pager.isCreated = false;
			ThumbListArea.loadVideosByCollectionId(collectionId);
			//ThumbListArea.loadVideo();
			//ThumbListArea.sort="";
			e.preventDefault();
			return false;
		});

		//Get collection
		MainNav.buildNav(MainNav.collectionNavId);
	},

	/************************************************
	 * Evaluates the keypress or keydown to ensure
	 * that its the enter key thats press
	 */
	checkForEnter : function(e) {
		if (e.which == 13) {
   				ThumbListArea.page = 1;

				ThumbListArea.searchQuery = $("input.data-entry").attr("value");
				//$('#pagination').data("isCreated", 'false');
   				Pager.isCreated = false;
   				ThumbListArea.loadSearchVideo();

   			}
	},
	/************************************
 		Get the collections for the menu
	**/
	buildNav : function (id) {
		// get the teaser xml file

		$.ajax({
			type: "GET",
			url : VFA.NavUrl + id,
			cache : true,
			dataType: "xml",
			success : function(data) {
			MainNav.buildCollectionNav(data);
			}
		});

	},

	/*********************************************
	 * Build collections menu
	 */
	buildCollectionNav : function(data) {

			var html = '<ul>';
		 $(data).find('collection').each(function(){
			var _id = $(this).attr('id');
			var _name = $(this).find('name').text();
			//add <ul>
			html += '<li><a id="'+ _id + '" href="#">' + _name + '</a></li>';
		});
			html = html + '</ul>';
			$('.menuCategories').html(html);
	},

	/*********************************************
	 * Build the sort menus based off type
	 */
	buildSortMenu : function(style) {
		var html = "";
		if (style == 'view') {
			html = '<ul><li><a href="#" id="sortDate">most recent</a></li>';
			html = html + '<li><a href="#" id="">most watched</a></li>';
			html = html + '<li><a href="#" id="sortTopRated">top rated</a></li></ul>';
		} else {
			html = '<ul><li><a href="#" id="daysback7">this week</a></li>';
			html = html + '<li><a href="#" id="daysback30">this month</a></li>';
			html = html + '<li><a href="#" id="">all-time</a></li></ul>';
		}

		$(".sortMenu").html(html);


	},

	vfa_menu_open : function() {
		MainNav.vfa_menu_canceltimer();
		MainNav.vfa_menu_close();
		MainNav.ddmenuitem = $(this).find('.sub_menu_outter_wrap').eq(0).css('visibility', 'visible');
	},

	 vfa_menu_close : function() {
	 	if(MainNav.ddmenuitem) MainNav.ddmenuitem.css('visibility', 'hidden');
	 },

	 vfa_menu_timer : function() {
	 	MainNav.closetimer = window.setTimeout(MainNav.vfa_menu_close, MainNav.timeout);
	 },

	 vfa_menu_canceltimer : function() {
	 	if(MainNav.closetimer)
		{	window.clearTimeout(MainNav.closetimer);
		MainNav.closetimer = null;}
	 }

}

/*************************************
	Utility functions
***************************************/


var Utils = {
	storeVideoNode : function(node, index) {
		var newvid = new Object();
		newvid.videoId = $(node).attr('id');
		newvid.id = $(node).attr('id');
		newvid.collectionId = $(node).attr('collectionId');
		newvid.thumb = $(node).find('thumbnailUrl').text();
		newvid.image = $(node).find('thumbnailUrl').text();

		newvid.fullImage = $(node).find('fullSizeStillUrl').text();
		newvid.title = Utils.stringShorten($(node).find('title').text());
		newvid.fullTitle = $(node).find('title').text();
		newvid.embed = $(node).find('embed').text();

		newvid.description = Utils.stringShorten($(node).find('description').text());
		newvid.countryId = $(node).find('country').attr('id');

		var country = $(node).find('country').text();
		var agency = $(node).find('agency').text();

		var year = $(node).find('year').text();
		var brand = $(node).find('brand').text();

		if(country == null || country == "null") {
			country = "";
		}
		if(brand == null || brand == "null") {
			brand = "";
		}
		if(year == null || year == "null") {
			year = "";
		}
		if(agency == null || agency == "null") {
			agency = "";
		}

		newvid.brand = brand;
		newvid.brandId = $(node).find('brand').attr('id');
		newvid.country = country;
		newvid.agency = agency;
		newvid.year = year;
		newvid.tags = $(node).find('description').text();
		newvid.featured = $(node).find('featured').text();
		var _userRating = $(node).find('userRating').text();
		if(_userRating == "0.0" || _userRating == null || _userRating == "null") {
			newvid.userRating = "0";
		} else {
			newvid.userRating = Utils.roundNumber(_userRating,1);// Math.round(_userRating * 100)/100;
		}
		var _timesEmailed =  $(node).find('timesEmailed').text();
		if(_timesEmailed == null || _timesEmailed == "null") {
			_timesEmailed = "0";
		}
		newvid.timesEmailed =  Utils.addCommas(_timesEmailed);

		var _timesViewed = $(node).find('timesViewed').text();
		if(_timesViewed == null || _timesViewed == "null") {
			_timesViewed = "0";
		}
		newvid.timesViewed = Utils.addCommas(_timesViewed);
		newvid.segmentId = $(node).find('segment').attr('id');
		newvid.flashUrl = $(node).find('flashUrl').text();
		newvid.playListIndex = index;

		return newvid;
	},
	
	sponsorImages : function(node) {
		var sponsorImg = new Object();
		sponsorImg.name = $(node).attr('name');
		sponsorImg.collectionId = $(node).attr('collectionId');
		sponsorImg.contentId = $(node).attr('contentId');
		sponsorImg.imageUrl = $(node).find('imageUrl').text();
		sponsorImg.altText = $(node).find('altText').text();
		sponsorImg.sponsorLink = $(node).find('sponsorLink').text();
		
		return sponsorImg;
	},
	 
	
	
	
	updateFacebookHeader : function(title, description, imgSrc) 
	{
		$('meta[name=title]').attr("content", title);
		$('meta[name=description]').attr("content", title);
		 
		$('link[rel=image_src]').attr("href", imgSrc);
	},
	addCommas : function(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	},

	roundNumber : function (rnum, rlength) { // Arguments: number to round, number of decimal places
  		//var newnumber = "";
  			var formattedNumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  		//check for 0, if it exists remove it and return only the int. example 7.0 will be 7
  		//newnumber = formattedNumber;
  		var retVal = formattedNumber;
  		var newnumber = new String(formattedNumber)
  		if (newnumber.indexOf(".0") > 0) {
  			var numArray = newnumber.split(".");
  			retVal = numArray[0];
  		} else {
  			retVal = formattedNumber;
  		}


  		return retVal; // Output the result to the form field (change for your purposes)
	},

	isNewVideo : function(videoDate, noOfDays) {

		videoPubDate = new Date(videoDate);
		today=new Date();
		//testDate = Date("ddd mmm dd HH:MM:ss Z yyyy");
		//var testDate = dateFormat(today, "ddd mmm dd HH:MM:ss Z yyyy");
		var one_day=1000*60*60*24;
		var numberOfDays = Math.ceil(today.getTime() - videoPubDate.getTime())/one_day;
		if(numberOfDays <= noOfDays) {
			return true;
		} else {
			return false;
		}



	},

	getSearchFlashUrl : function(vidId, video) {
		var flashUrl = "";

		$.ajax({
			type: "GET",
			url : "/veryfunnyads/getPlaylistById.do?id=" + vidId,
			cache : true,
			dataType: "xml",
			success : function(data) {
				flashUrl = $(data).find('url').text();
				if (flashUrl != null ||flashUrl != "") {
					video.url = flashUrl;

					VFA.playCount = VFA.playCount + 1; //increment the playCount
					VFA.playSingle(video);
				}
			}
		});

	},

	/****************************************
	 * retrieves a flash vidoe url by segmentId
	 */
	getFlashUrl : function(vidId) {
		var flashUrl = "";

		$.ajax({
			type: "GET",
			url : "/veryfunnyads/getPlaylistById.do?id=" + vidId,
			cache : true,
			dataType: "xml",
			success : function(data) {
				flashUrl = $(data).find('url').text();

			}
		});


		return flashUrl;
	},



	stringShorten : function (sourceString,maxLength) {
		if (!sourceString) {
			result = null;
		}
		else if (sourceString.length>maxLength) {
			preferredSize = maxLength-'...'.length;
			if (preferredSize>0) {
			  result = sourceString.substr(0,preferredSize) + '...';
			}
			else {
			  result = sourceString.substr(0,maxLength);
			}
		}
		  else {
			result = sourceString;
		}
		  return result;
		}
}

 // cookie functions
var CookieJar = {
	getCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');

		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	},
	setCookie : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		} else {
			var expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	}
}


// controller for My Favorites
var UserVoting = {
		init : function() {
		//Here is where you would do the work for the myAd menu items and the
		//cookie storage of the videos that have been voted on
		var orderArray = new Array();

		var storedVotes = CookieJar.getCookie(VFA.VotersCookie);
		if (storedVotes != null || storedVotes == "") {
			var voteArray = storedVotes.split("|");
			for (var i=0; i < voteArray.length; i++) {
				VFA.votingList.push(voteArray[i]);
				var vote = voteArray[i].split("-");
				var vidId = vote[0];
				var rating = vote[1];
				VFA.votingMap[vidId] = rating;
			}
			//VFA.votingMap[]
			//VFA.editorsPickMap[newvid.videoId] = newvid;
		}
	},
	updateCookie : function() {
		var votedList = "";

		for (var i = 0; i < VFA.votingList.length; i++) {
			var videoId = VFA.votingList[i];
			if (votedList === "") {
				votedList = votedList.concat(videoId);
			} else {
				votedList = votedList.concat("|" + videoId);
			}
		}
		CookieJar.setCookie(VFA.VotersCookie, votedList, 365);
	},

	updatePollCookie : function(videoId) {
		if (videoId) {
			CookieJar.setCookie(VFA.PollCookie,videoId, 1);
		}
	}

}

