 var $vod=jQuery.noConflict();
var isIE = "\v" == "v";
var isIOS = (navigator.userAgent.match(/iPhone/gi) != null) || (navigator.userAgent.match(/iPod/gi) != null) || (navigator.userAgent.match(/iPad/gi) != null);
var isFancy = !isIE;
var isChineseSite = false;

/* ######################### VOD Library #########################
########## Table of content
- menu
-- init
-- browse
-- view
- playlist
- popOut
- animation
- error
- ds
- template
- param
- cache
*/

var vod={
	/**
	 * Init
	 * @param options
	 * @param target
	 */
	init:function(options, target){
		//check login status
		vod.param.loginStatus();

		/* setup video page URL*/
		if(document.domain.indexOf('theworldgame.')>-1){
			vod.param.server.videoPage='/video/';
			vod.param.noImagePlaceholderPath = '/web/images/vod/';
		}else{
			var subSite=window.location.pathname;
			if (subSite.indexOf('chinese') > 0) {
				isChineseSite = true;
			}
			if(subSite.indexOf('/')==0){
				subSite=subSite.substring(1, subSite.length);
			}
			if (subSite.toLowerCase().indexOf('cyclingcentral')>-1 && subSite.indexOf('video')>0){
				subSite=subSite.substring(0, subSite.indexOf('video') - 1);
			}
			else if(subSite.indexOf('/')>0){
				subSite=subSite.substring(0, subSite.indexOf('/'));
			}
			vod.param.server.videoPage='/'+subSite+'/video/';
		}

		// Override settings
		$vod.extend(vod.param.settings, options);

		// Create container if one doesn't exist
		if(!$vod(target).next().hasClass('the_grid')) $vod(target).after(vod.template.container);

		// Featured widget filter function
		$vod('.vod_featured .filter').delegate('a', 'click', function(){
			// return if already selected
			if($vod(this).hasClass('vod-selected')) return false;
			
			if($vod(this).attr('rel') == '' || $vod(this).attr('rel') == undefined) {
				return false;
			}

			// select tab
			$vod('.vod_featured .filter a').removeClass('vod-selected');
			$vod('.vod_featured .filter li').removeClass('selected');
			$vod(this).addClass('vod-selected');
			$vod(this).parents('li').addClass('selected');

			//Animate
			vod.animation.clickDisable($vod('.vod_featured .col'));
			$vod('.vod_featured .vod_widget').animate({opacity:[0.3, 'swing']}, 300,'linear', function(){});

			// ajax time!
			if($vod(this).hasClass('vod-filter')){
				vod.ds.theFilter($vod('.vod_featured .vod_widget'), vod.template.filtergrid, $vod(this).attr('rel'));
			}else {
				vod.ds.widget($vod('.vod_featured .vod_widget'), vod.template.grid, $vod(this).attr('rel'));
			}
		});

		$vod('#vod_lead_marquee .vod_items').delegate('a', 'click', vod.animation.switchLeadMarqueeImage);
		vod.animation.leadMarqueeLoop(0);
	},
	menu:{
		init:function(){
			vod.init();
			vod.menu.closeMenu();
			vod.animation.init();
			// clear menu
			$vod('#vod_menu .vod_menu').html('');
			// write menu
			$vod.each(VideoMenu,function(inx, val){
				$vod('#vod_menu .vod_menu').append('<li class="vod_menu_tab"><a href="javascript:void(0);" rel="'+inx+'" class="vod_menu_item">'+inx+'</a><span></span></li>');
			});
			$vod('#vod_menu .vod_menu_tab a').click(vod.menu.view);
			// wire menu
			$vod('#vod_menu .vod_menu_tab a').click(vod.menu.view);
			$vod('.the_grid_region .aside_nav').delegate('a','click',vod.menu.browse);
			$vod('#vod_search').submit(vod.menu.search);
			$vod('#vod_menu .vod_menu_tab .vod_selected').css({'width':''});
		},
		browse:function(){
			//vod.param.lastLocation = this.rel;
			// check other animations
			if(vod.param.animating>0){
				return false;
			}

			vod.param.lastAction = 'browse';

			// mark active
			$vod('#the_grid .the_grid_region .aside_nav .vod_selected').removeClass('vod_selected');
			$vod('#the_grid .the_grid_region .aside_nav .vod_browse_select').removeClass('vod_browse_select');
			$vod(this).parent().addClass('vod_selected').next('span').show();
			$vod(this).addClass('vod_browse_select');

			// new data tree
			var objMenu=vod.ds.getObj(this.rel,VideoMenu);
			var objParent=objMenu;
			if(this.rel.indexOf('.children')>-1){
				var objParent=vod.ds.getObj(this.rel.substring(0,this.rel.lastIndexOf('.children')),VideoMenu);
			}

			vod.animation.clickDisable($vod('#the_grid .the_grid_region .vod_viewport .vod_loader')); // ajax loader

			// check children
			if(!$vod(this).hasClass('vod_drilldown')&&!$vod(this).hasClass('vod_btn_back')){
				try{
					// AJAX
					var objTarget = $vod('#the_grid .vod_view_grid ul.vod_loader');

					vod.ds.grid(vod.ds.query(this, objMenu, objMenu['url'].toString(), objTarget), objTarget, vod.template.grid);
				}catch(e){}
			}else{
				$vod('#the_grid .the_grid_region .aside_nav ').css('overflow','hidden');

				// reverse direction for back
				var animateControl='-';
				if($vod('.vod_browse_select').hasClass('vod_btn_back')){
					animateControl='+';
					objMenu=objParent;
				}

				// animate out
				vod.animation.counterAdd();
				$vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').animate({marginLeft: [animateControl+'='+$vod('#the_grid .the_grid_region .aside_nav').css('width'), 'swing']}, 150, 'linear', function(){
					vod.animation.counterRemove();
					// write back button
					curMenu=$vod('.vod_browse_select').attr('rel');

					if($vod('.vod_browse_select').hasClass('vod_btn_back')){
						curMenu=curMenu.substring(0,curMenu.lastIndexOf('.children'));
					}
					$vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').attr('href','#'+curMenu);
					$vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').attr('rel',curMenu);
					if($vod('.vod_browse_select').hasClass('vod_btn_back')&&$vod('.vod_btn_back').attr('rel').indexOf('.children')<0){
						$vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').css('visibility','hidden');
					}else{
						$vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').css('visibility','visible');
					}

					// header
					$vod('#the_grid .the_grid_region .aside_nav h2').html(objMenu['name']);

					// write new nav
					$vod('#the_grid .the_grid_region .aside_nav li').remove();
					vod.ds.menu(objMenu,$vod('#the_grid .the_grid_region .aside_nav ul'));

					// reverse direction for back
					var animateControl=$vod('#the_grid .the_grid_region .aside_nav').css('width');
					if($vod('.vod_browse_select').hasClass('vod_btn_back')){
						animateControl='-'+animateControl;
					}

					// animate in
					$vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').css('margin-left',animateControl);

					vod.animation.counterAdd();
					$vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').animate({marginLeft: ['0px', 'swing']}, 300, 'linear', function(){
						$vod('#the_grid .the_grid_region .aside_nav .vod_browse_select').removeClass('vod_browse_select');
						vod.animation.counterRemove();
					});
					try{
						var query = vod.ds.query(this, objMenu, objMenu['url'].toString(), objTarget), objTarget = $vod('#the_grid .vod_view_grid ul.vod_loader');
						if(objMenu.sf && objMenu.furl)
						query = objMenu.furl;
						// AJAX
						vod.ds.grid(query, objTarget, vod.template.grid);
					}catch(e){}
				});
			}
			return false;
		},
		view:function(){
			/*
			if(vod.param.lastLocation != '') {
				vod.menu.navigateTo(this, vod.param.lastLocation);
				return;
			}
			*/
			// prevent double animation
			if(vod.param.animating>0){
				return false;
			}
			vod.param.lastAction = 'view';

			//disable search active states
			$vod('#vod_search').removeClass('vod_selected');
			$vod('#vod_menu .search_box').find('span').hide();

			// slide close
			var currentRegion=$vod('#the_grid');

			// close menu else stay open
			var gridRegion = currentRegion.find('.the_grid_region');
			if(currentRegion.css('display')=='block'&&$vod(this).hasClass('vod_selected')){
				$vod('#video_page_container').css({visibility:'visible'});

				$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
				gridRegion.css('opacity','1');
				vod.animation.counterAdd();
				gridRegion.animate({height:[0,'swing'],opacity:[0,'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					gridRegion.removeAttr('style');
					gridRegion.css('height','');
					currentRegion.removeAttr('style');
					vod.param.leadMarqueePause = 0;
					//for resetting page height if showMore was pressed
					$vod('.content .left_column, .content .right_column').css({height: 'auto'});
				});
				if (vod.menu.selfHidden){
					vod.menu.hideVodMenu();
				}
			}else{
				$vod('#video_page_container').css({visibility:'hidden'});

				vod.param.leadMarqueePause = 1;
				vod.param.contentHeight = $vod('.content').height();

				// write grid content template
				$vod('#the_grid .vod_viewport').html(
					 '<div class="vod_filters">'
					+	'<div class="mask"></div>'
					+	'<span><a class="close" href="javascript:void(0);" title="">Close</a></span>'
					+	'<span class="view_mode"><a class="view_grid" href="javascript:void(0);" title="">Grid</a>'
					+	'<a class="view_list" href="javascript:void(0);" title="">List</a></span>'
					+'</div>'
					+'<div class="vod_header">'
					+	'<div class="vod_add">Add</div>'
					+	'<div class="vod_title selected">Title</div>'
					+	'<div class="vod_added">Date Added</div>'
					+	'<div class="vod_remain">Expires in</div>'
					+	'<div class="vod_duration">Length</div>'
					+	'<div class="vod_progress">progress</div>'
					+'</div>'
					+'<ul class="vod_loader"></ul>'
					+'<div class="clear"></div>'
				);

				// unselect other tab
				$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').hide();

				vod.animation.clickDisable($vod('#the_grid .the_grid_region .vod_viewport .vod_loader')); // ajax loader

				if(currentRegion.css('display')=='none'){
					// hide other overlays
					vod.animation.init($vod(this));
					$vod(this).addClass('vod_selected').next('span').css({'width':$vod(this).outerWidth()-1}).animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
					// unselect other tab

					currentRegion.css('display','block');
					var vod_sort_region_height=gridRegion.css("height");
					gridRegion.css('height','0px');
					gridRegion.css('opacity','0');
					vod.animation.counterAdd();
					currentRegion.find('.the_grid_region .vod_disable .vod_shader div').animate({height:[vod_sort_region_height,'swing']}, 300,'linear', function(){});
					gridRegion.animate({height:[vod_sort_region_height,'swing'],opacity:[1, 'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					currentRegion.find('.the_grid_region').removeAttr('style');
					currentRegion.find('.the_grid_region').css('height','');
					currentRegion.css('display','block');
					});
				}else{
					//If the grid is already open
					$vod(this).addClass('vod_selected').next('span').css({'width':$vod(this).outerWidth()-1}).show();
				}

				var vodMenuObj = $vod('#vod_menu'), dropDownShift = 6, dropDownPosition;
				var offsetPosition = vodMenuObj.offset();
				if (offsetPosition != null){
					dropDownPosition = (vodMenuObj.height() + dropDownShift + offsetPosition.top + "px");
					$vod('.the_grid').css({top: dropDownPosition, left: '-1px'});
				}

				// write left nav
				vod.animation.counterAdd();
				var asideNav = $vod('#the_grid .the_grid_region .aside_nav');
				asideNav.find('.aside_nav_panel').animate({opacity:[0,'swing']}, 300,'linear', function(){
					asideNav.find('li').remove();
					asideNav.find('.vod_btn_back').attr('href','javascript:void(0);');
					asideNav.find('.vod_btn_back').attr('rel',$vod('.vod_menu .vod_selected').attr('rel'));
					asideNav.find('.vod_btn_back').css('visibility','hidden');
					asideNav.find('h2').html($vod('#vod_menu .vod_menu_tab .vod_selected').html());
					vod.ds.menu(VideoMenu[$vod('.vod_menu .vod_selected').attr('rel')],$vod('.the_grid_region .aside_nav ul'));
					asideNav.find('.aside_nav_panel').animate({opacity:[1,'swing']}, 300,'linear', function(){vod.animation.counterRemove(); vod.animation.showLeftNav();});
				});


				// load right content
				try{
					// AJAX
                    var query, objTarget = $vod('#the_grid .vod_view_grid ul.vod_loader');

                    if(VideoMenu[$vod('#vod_menu .vod_menu .vod_selected').attr('rel')].sf && VideoMenu[$vod('#vod_menu .vod_menu .vod_selected').attr('rel')].furl)
                        query = VideoMenu[$vod('#vod_menu .vod_menu .vod_selected').attr('rel')].furl;
                    else query = vod.ds.query(this, VideoMenu[$vod('#vod_menu .vod_menu .vod_selected').attr('rel')], VideoMenu[$vod('#vod_menu .vod_menu .vod_selected').attr('rel')]['url'].toString(), objTarget);
					vod.ds.grid(query, objTarget,vod.template.grid);
				}catch(e){}

			}

			return false;
		},
		navigateTo:function(event, rel){
            if(typeof event.stopPropagation == 'function')
                event.stopPropagation();

			// prevent double animation
			if(vod.param.animating>0){
				return false;
			}
			rel = rel || $vod(this).attr('rel');
			vod.param.lastAction = 'view';

            var tabname = rel.replace('#','').replace(rel.substr(rel.indexOf('.')), '');
			var $tab = $vod('li.vod_menu_tab a[rel="'+tabname+'"]');

			//disable search active states
			$vod('#vod_search').removeClass('vod_selected');
			$vod('#vod_menu .search_box').find('span').hide();

			// slide close
			var currentRegion=$vod('#the_grid');

			// close menu else stay open
			var gridRegion = currentRegion.find('.the_grid_region');
//			$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
			if((currentRegion.css('display')=='block') && $tab.hasClass('vod_selected')){
				$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
				gridRegion.css('opacity','1');
				vod.animation.counterAdd();
				gridRegion.animate({height:[0,'swing'],opacity:[0,'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					gridRegion.removeAttr('style');
					gridRegion.css('height','');
					currentRegion.removeAttr('style');
					vod.param.leadMarqueePause = 0;
					//for resetting page height if showMore was pressed
					$vod('.content .left_column, .content .right_column').css({height: 'auto'});
				});
			}else{
				vod.param.leadMarqueePause = 1;
				vod.param.contentHeight = $vod('.content').height();

               /* // write grid content template
                $vod('#the_grid .vod_viewport').html(
                     '<div class="vod_filters">'
                    +	'<div class="mask"></div>'
                    +	'<span><a class="close" href="javascript:void(0);" title="">Close</a></span>'
                    +	'<span class="view_mode"><a class="view_grid" href="javascript:void(0);" title="">Grid</a>'
                    +	'<a class="view_list" href="javascript:void(0);" title="">List</a></span>'
                    +'</div>'
                    +'<div class="vod_header">'
                    +	'<div class="vod_add">Add</div>'
                    +	'<div class="vod_title selected">Title</div>'
                    +	'<div class="vod_added">Date Added</div>'
                    +	'<div class="vod_remain">Expires in</div>'
                    +	'<div class="vod_duration">Length</div>'
                    +	'<div class="vod_progress">progress</div>'
                    +'</div>'
                    +'<ul class="vod_loader"></ul>'
                    +'<div class="clear"></div>'
                );*/

                vod.animation.clickDisable($vod('#the_grid .the_grid_region .vod_viewport .vod_loader')); // ajax loader
                var section = rel.replace('#','').split('.');



                if(currentRegion.css('display')=='none'){
                    // hide other overlays
					vod.animation.init($tab);

					var position = $vod('#vod_menu a.vod_menu_item').offset();
					if(position != null){
							position = (57+position.top+"px");
							currentRegion.css({top: position, left: '-1px'});
					}

					$tab.addClass('vod_selected').next('span').css({'width':$tab.outerWidth()-1}).animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
					// unselect other tab

                    currentRegion.css('display','block');
                    var vod_sort_region_height=gridRegion.css("height");
                    gridRegion.css('height','0px');
                    gridRegion.css('opacity','0');
                    vod.animation.counterAdd();
                    currentRegion.find('.the_grid_region .vod_disable .vod_shader div').animate({height:[vod_sort_region_height,'swing']}, 300,'linear', function(){});
                    gridRegion.animate({height:[vod_sort_region_height,'swing'],opacity:[1, 'swing']}, 300,'linear', function(){
						vod.animation.counterRemove();
						currentRegion.find('.the_grid_region').css('height','');
						currentRegion.css('display','block');
                    });
				}else{
					//If the grid is already open
					$tab.addClass('vod_selected').next('span').css({'width':$tab.outerWidth()-1}).show();
                }

                vod.param.lastAction = 'browse';

                // mark active
                $vod('#the_grid .the_grid_region .aside_nav .vod_selected').removeClass('vod_selected');
                $vod('#the_grid .the_grid_region .aside_nav .vod_browse_select').removeClass('vod_browse_select');

                // new data tree
				rel = rel.replace('#', '');
                var objMenu=vod.ds.getObj(rel,VideoMenu);
                var objParent=objMenu;
                if(rel.indexOf('.children')>-1){
                    var objParent=vod.ds.getObj(rel.substring(0,rel.lastIndexOf('.children')),VideoMenu);
                }

                vod.animation.clickDisable($vod('#the_grid .the_grid_region .vod_viewport .vod_loader')); // ajax loader

                $vod('#the_grid .the_grid_region .aside_nav ').css('overflow','hidden');

                // reverse direction for back
                var animateControl='-';
                if($vod('.vod_browse_select').hasClass('vod_btn_back')){
                    animateControl='+';
                    objMenu=objParent;
                }

                // animate out
                vod.animation.counterAdd();
                $vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').animate({marginLeft: [animateControl+'='+$vod('#the_grid .the_grid_region .aside_nav').css('width'), 'swing']}, 150, 'linear', function(){
                    vod.animation.counterRemove();
                    // write back button
                    curMenu=rel;

                    if($vod('.vod_browse_select').hasClass('vod_btn_back')){
                        curMenu=curMenu.substring(0,curMenu.lastIndexOf('.children'));
                    }
                    $vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').attr('href','#'+curMenu);
                    $vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').attr('rel',curMenu);
                    if($vod('.vod_btn_back').attr('rel').indexOf('.children')<0){
                        $vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').css('visibility','hidden');
                    }else{
                        $vod('#the_grid .the_grid_region .aside_nav .vod_btn_back').css('visibility','visible');
                    }

                    // header
                    $vod('#the_grid .the_grid_region .aside_nav h2').html(objMenu['name']);

                    // write new nav
                    $vod('#the_grid .the_grid_region .aside_nav li').remove();
                    vod.ds.menu(objMenu,$vod('#the_grid .the_grid_region .aside_nav ul'));

                    // reverse direction for back
                    var animateControl=$vod('#the_grid .the_grid_region .aside_nav').css('width');
                    if($vod('.vod_browse_select').hasClass('vod_btn_back')){
                        animateControl='-'+animateControl;
                    }

                    // animate in
                    $vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').css('margin-left',animateControl);

                    vod.animation.counterAdd();
                    $vod('#the_grid .the_grid_region .aside_nav .aside_nav_panel').animate({marginLeft: ['0px', 'swing']}, 300, 'linear', function(){
                        $vod('#the_grid .the_grid_region .aside_nav .vod_browse_select').removeClass('vod_browse_select');
                        vod.animation.counterRemove();
                    });
                    try{
                        var query = vod.ds.query(this, objMenu, objMenu['url'].toString(), objTarget), objTarget = $vod('#the_grid .vod_view_grid ul.vod_loader');
                        if(objMenu.sf && objMenu.furl)
                        query = objMenu.furl;
                        // AJAX
                        vod.ds.grid(query, objTarget, vod.template.grid);
                    }catch(e){}
                });
            }
			return false;
		},
		search:function(event){
			// prevent form submit
			event.preventDefault();
			// prevent double animation
			var searchString = $vod('#vod_search .input_search').val();
			if(vod.param.animating>0 || (searchString == "search")){
				return false;
			}

			// slide close
			var currentRegion=$vod('#the_grid');

			// write grid content template
			if(!$vod('#the_grid .vod-show-more').hasClass('vod-show-more-active')) $vod('#the_grid .vod_viewport').html(
				 '<div class="vod_filters">'
				+	'<div class="mask"></div>'
				+	'<span><a class="close" href="javascript:void(0);" title="">Close</a></span>'
				+	'<span class="view_mode"><a class="view_grid" href="javascript:void(0);" title="">Grid</a>'
				+	'<a class="view_list" href="javascript:void(0);" title="">List</a></span>'
				+'</div>'
				+'<div class="vod_header">'
				+	'<div class="vod_add">Add</div>'
				+	'<div class="vod_title selected">Title</div>'
				+	'<div class="vod_added">Date Added</div>'
				+	'<div class="vod_remain">Expires in</div>'
				+	'<div class="vod_duration">Length</div>'
				+	'<div class="vod_progress">progress</div>'
				+'</div>'
				+'<ul class="vod_loader"></ul>'
				+'<div class="clear"></div>'
			);
			vod.param.lastAction = 'search';

			// unselect other tab
			$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').hide();
			vod.animation.clickDisable($vod('#the_grid .the_grid_region .vod_viewport .vod_loader')); // ajax loader
			if(currentRegion.css('display')=='none'){
				// hide other overlays
				vod.animation.init($vod(this));
				$vod(this).addClass('vod_selected').next('span').css({'width':$vod(this).outerWidth()}).animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
				// unselect other tab
				currentRegion.css('display','block');
				var vod_sort_region_height=currentRegion.find('.the_grid_region').css("height");
				currentRegion.find('.the_grid_region').css('height','0px');
				currentRegion.find('.the_grid_region').css('opacity','0');
				vod.animation.counterAdd();
				currentRegion.find('.the_grid_region').animate({height:[vod_sort_region_height,'swing'],opacity:[1, 'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					vod.param.leadMarqueePause = 1;
					currentRegion.find('.the_grid_region').removeAttr('style');
					currentRegion.find('.the_grid_region').css('height','');
					currentRegion.css('display','block');
				});
			}else{
				$vod('#vod_menu .search_box form').next('span').css({'width':$vod(this).outerWidth()}).toggle();
			}

			var position = $vod('a.vod_menu_item').offset();
			if(position != null){
				position = (57+position.top+"px");
				$vod('.the_grid').css({top: position, left: '-1px'});
			}

			// write left nav
			$vod(this).addClass('vod_selected').next('span').show();
			$vod('#the_grid .the_grid_region .aside_nav li').remove();
			var vodBtnBack = $vod('#the_grid .the_grid_region .aside_nav .vod_btn_back');
			vodBtnBack.attr('href','javascript:void(0);');
			vodBtnBack.attr('rel',$vod('.vod_menu .vod_selected').attr('rel'));
			vodBtnBack.css('visibility','hidden');

			//Hide left nav
			vod.animation.hideLeftNav();

			// load search results
			try{
                var categoryString = (vod.param.category != '') ? '&byCategories='+vod.param.category : '';
				var objTarget = $vod('#the_grid .vod_view_grid ul.vod_loader'),
					//query = vod.ds.query(this, {}, 'http://feed.theplatform.com/f/'+mpxFeedId+'/search?form=json&q='+searchString+categoryString, objTarget);
					query = vod.ds.query(this, {}, '/api/video_feed/f/'+mpxFeedId+'/search?form=json&q='+searchString+categoryString, objTarget);
				// AJAX
				vod.ds.grid(query,objTarget,vod.template.grid);
			}catch(e){}
			return false;
		},
        viewDay:function(){
			$vod('#the_grid .vod_day_navigation').find('.vod_selected').removeClass('vod_selected');
			$vod(this).addClass('vod_selected');
            vod.param.filterDay = $vod(this).attr('rel');
            vod.menu.browse.call($vod('#the_grid .the_grid_region .aside_nav .vod_selected a').get(0));
        },
        showMore:function(){
            $vod('#the_grid .vod-show-more').addClass('vod-show-more-active');
			if(vod.param.lastAction == 'search') $vod('#vod_search').submit();
			else vod.menu.browse.call($vod('#the_grid .the_grid_region .aside_nav .vod_selected a').get(0));
        },
		ajaxGrid:function(){

		},
		closeMenu:function() {
			var bodyHandler = function(event) {
				//for resetting page height if showMore was pressed
				$vod('.content .left_column, .content .right_column').css({height: 'auto'});
				$vod('#video_page_container').css({visibility:'visible'});

				vod.param.leadMarqueePause = 0;
				vod.animation.init();
				vod.playlist.sync();
				var target = event.target;
				var isVideoMenu = (target && $vod(event.target).attr('title') && $vod(event.target).attr('title').toLowerCase() == 'videos');
				if (vod.menu.selfHidden && !isVideoMenu){
					vod.menu.hideVodMenu();
				}

			};
			$vod('body').click(bodyHandler);
			$vod('#the_grid .the_grid_region, #the_grid, .vod_playlist').unbind('click').click(function(event){
				event.stopPropagation();
			});
		},
		showVodMenuAndSection:function(event, navigateToLink) {
			if ($('#vod_menu').css('display') != 'block') {
				$vod('#vod_menu').show(400, function() {
					vod.menu.navigateTo(event, navigateToLink);
				});
				this.selfHidden = true;
			}
			else {
				vod.menu.hideVodMenu();
			}
		},
		hideVodMenu:function(){
			$vod('#vod_menu').hide(400);
		}
	},
	playlist:{
		init:function(){
			if(vod.param.server.state){
				$vod('body').addClass('vod_user');
			}
			/* wire sorting */
			$vod(".vod_sortable").sortable({
				containment: 'parent',
				stop: function(event, ui) {
					var loca=1;
					var moveID=$vod(ui.item).attr('videoid');
					$vod('.vod_playlist .vod_sortable .vod_playlist_item').each(function(index){
						if($vod(this).attr('videoid')==moveID){
							loca=index;
							return false;
						}
					});
					loca=$vod('.vod_playlist .vod_sortable .vod_playlist_item').size()-loca;
					vod.ds.playlist.update(moveID,loca);
				}
			});

			$vod(".vod_sortable").disableSelection();

			/* wire add clicks*/
			$vod('.vod_widget, .vod_widget_filter_related, #vod_lead_marquee, #the_grid .vod_viewport, .vod_program_header').click(function(e){
				var target = e.target,
					$target = $vod(target);

				if(target.nodeName.toUpperCase() == 'A' && $target.parents('.vod_playlist_item .tt_list li.vod_playlist_add').length > 0)
					vod.playlist.add($target);

				if (e.stopPropagation !== undefined) {
					e.stopPropagation();
				}
			});

			// if the title is too long, decrease the font-size
			var programHeaderTitle = $vod('.vod_program_header h1');
			if (programHeaderTitle.height() > 60) {
				programHeaderTitle.addClass('long_title');
			}
			programHeaderTitle.show();


			var playlist = $vod('.vod_playlist .playlist_summary, .vod_playlist .vod_dropdown');

			//One event to rule them all
			playlist.click(function(e){
				var target = e.target,
					$target = $vod(target);

				if(target.nodeName.toUpperCase() == 'A'){
					if ($target.parents('.playlist_summary').length > 0){
						if(vod.param.animating>0){
							return false;
						}
						// hide other overlays
						if(vod.param.request!=0){return false;}

						var currentRegion=$target.parent('.playlist_summary').next();

						// animate
						vod.animation.counterAdd();
						if(currentRegion.css('display')=='block'){
							currentRegion.animate({height: [0,'swing']}, 150, 'linear', function(){
								currentRegion.parents('.vod_playlist').removeClass('vod_playlist_selected');
								currentRegion.removeAttr('style');
								currentRegion.css('display','none');
								vod.animation.counterRemove();
								vod.playlist.collapse($target);
								vod.playlist.sync($vod('body'));

							});
							if (vod.menu.selfHidden){
								vod.menu.hideVodMenu();
							}
						}else{
							currentRegion.removeAttr('style');
							vod.animation.init($target);
							var vod_sort_region_height=currentRegion.css("height");
							currentRegion.css('height','0px');
							currentRegion.css('display','block');
							currentRegion.parents('.vod_playlist').addClass('vod_playlist_selected');
							currentRegion.animate({height: [vod_sort_region_height,'swing']}, 200, 'linear', function(){
								vod.animation.counterRemove();
								currentRegion.removeAttr('style');
								currentRegion.css('display','block');
								vod.playlist.sync($vod('body'));
							});
						}
						return false;
					} else if($target.hasClass('vod_tip_autoplay_close')){
						var d = new Date();
						d.setFullYear(d.getFullYear()+10);
						document.cookie = 'vod_tip=autoplay; expires='+d+'; path=/';
						$target.parents('.playlist_help_play').remove();
					} else if($target.parents('.playlist_action').length > 0){
						vod.playlist.extend($target);
					} else if ($target.hasClass('close') && $target.parents('.vod_filters').length > 0){
						vod.playlist.collapse($target);
					} else if ($target.parents('.playlist_filter').length > 0){
						vod.playlist.filter($target);
					} else if ($target.hasClass('btn_playlist') && $target.parents('.vod_notification').length > 0){
					/*
					MOVED
					*/
					} else if ($target.parents('.aside_nav').length > 0){
						vod.playlist.view($target);
					}
				} else if(target.nodeName.toUpperCase() == 'SPAN' && $target.parent().hasClass('btn_playlist')){
					vod.playlist.notification.save();
					savedCheck = $target.parent().hasClass('saved')?true:false;
					if(!savedCheck) {
						//$vod(this).parent()
						$target.parent().addClass('saved').append('<div class="tick"></div>');
					}
				}

				if (e.stopPropagation !== undefined) {
					e.stopPropagation();
				}
			});

		},
		add:function(objTarget){
			// if no vod menu on the page -> return;
			if (!$vod('#vod_menu')) {
				return;
			}
			// prevent double click
			if(vod.param.animating>0){return false;}
			// prevent subscription
			if(!vod.param.server.state){
				if(objTarget.html()=='Subscribe to Series'){
					vod.animation.init();
					var vodMenuTop = $vod('#vod_menu').offset().top;
					$vod(window).scrollTop(vodMenuTop);
					var playListDropdown = $vod('.vod_playlist .vod_dropdown');
					playListDropdown.css('display','block');
					vod.playlist.extend(objTarget);
					return false;
				}
			}
			if($vod('#vod_lead_marquee').length != 0){
				$vod('#vod_lead_marquee .vod_items').find('a[videoid='+objTarget.parents('.vod_playlist_item').attr('videoid')+']').addClass('tt_added');
			}

			// make a copy of the item
			objTarget.parents('.vod_playlist_item').clone().appendTo('#vod_menu .vod_playlist .vod_playlist_content > ul.vod_sortable');

			// save to api & fire off the event handler
			vod.ds.playlist.add(objTarget.parents('.vod_playlist_item').attr('videoid'), objTarget);
			vod.handlePlaylistAdd(objTarget.parents('.vod_playlist_item').attr('videoid'));

			//animate out >> fade in with tick and added bubble >> fade out bubble
			vod.animation.clickDisable(objTarget.parents('.vod_padder'));
			vod.animation.counterAdd();
			var toolTip = $vod(objTarget.parents('.tt_list'));
			toolTip.animate({opacity: 0}, 150, 'linear', function(){
				if($vod('#vod_lead_marquee').length == 0){
					toolTip.find('.vod_playlist_popup_title, .vod_playlist_popup_option').css('display','none');
					toolTip.find('.vod_playlist_popup_option_added').css('display','block');
				}
				toolTip.attr('style','');
				objTarget.parents('.tt_active').removeClass('tt_active');

				var finishStuff = function(){
					vod.playlist.sync($vod('body'));
					vod.animation.clickEnable(objTarget.parents('.vod_padder'));
					vod.animation.counterRemove();
				};
				if(isFancy){
					// show video moving to playlist
					if(objTarget.parents('.vod_gutter').find('img.vod_clip').length == 0) {
						vod.animation.clickEnable(objTarget.parents('.vod_padder'));
						vod.animation.counterRemove();
						return;
					}
					var offset = objTarget.parents('.vod_gutter').find('img.vod_clip').offset();
					var toLocation = $vod('#vod_menu .vod_playlist').offset();
					toLocation.left += 50;
					toLocation.top  += 20;
					var delta = offset.top - toLocation.top;
					if((delta < 800)  && (objTarget.parents('.v_g').length > 0 || objTarget.parents('.vod_widget').length > 0)){
						objTarget.parents('.vod_gutter').find('img.vod_clip').clone().css({position: 'absolute', top: offset.top, left: offset.left, zIndex:'9999', display:'none'}).appendTo('body').fadeIn(150, function() {
							$vod(this).animate({top: toLocation.top, left: toLocation.left, width:'50px', height:'28px'}, 400, 'easeInOutQuad', function() {
								$vod(this).fadeOut(150, function() {
									$vod(this).remove();
									finishStuff();
								})
							})
						});
					} else {
						finishStuff();
					}
				} else {
					finishStuff();
				}
			});
		},
		remove:function(objTarget){

			// prevent double click
			if(vod.param.animating>0){return false;}

			// save to api
			if(objTarget.parents('.vod_playlist_item_subscription').size()>0){
				vod.ds.playlist.removeExt(vod.cache.subscription['id_'+objTarget.parents('.vod_playlist_item_subscription').attr('videoid')].seriesID,'subscription');
				delete vod.cache.subscription['id_'+objTarget.parents('.vod_playlist_item_subscription').attr('videoid')];
				objTarget.parents('.vod_playlist_item_subscription').remove();
			}else{
				// remove from cache if success
				delete vod.cache.playlist['id_'+objTarget.parents('.vod_playlist_item').attr('videoid')];
				if(objTarget.parents('.vod_playlist').size()>0){
					objTarget.parents('.vod_playlist_item').slideUp(150,'easeInCubic',function(){$vod(this).remove()});
				}
				$vod('.vod_playlist_item[videoid='+objTarget.parents('.vod_playlist_item').attr('videoid')+'] .vod_padder').removeClass('tt_added');
				$vod('#vod_lead_marquee .vod_items a[videoid='+objTarget.parents('.vod_playlist_item').attr('videoid')+']').removeClass('tt_added');
				vod.ds.playlist.remove(objTarget.parents('.vod_playlist_item').attr('videoid'));
				vod.handlePlaylistRemove(objTarget.parents('.vod_playlist_item').attr('videoid'));
			}

		},
		sync:function(objTarget){
			if(vod.param.server.state){
				$vod('body').addClass('vod_user');
			}
			var playList = $vod('#vod_menu .vod_playlist');
			var rendering = '', renderingSubscription = '';
			var render_expiring="";
			var playlist_Count=0;
			var sorter_expiring={
				data:{},
				init:function(){
					function sortNumber(a,b){return a - b;}
					var sorter=new Array();
					var key=new Array();
					var value=new Array();
					var sorted=new Array();
					$vod.each(sorter_expiring.data,function(inx, val){
						if(vod.cache.video['id_'+val.videoID]){
							sorter[sorter.length]=vod.cache.video['id_'+val.videoID].media$expirationDate;
							key[key.length]=val.videoID;
							value[value.length]=vod.cache.video['id_'+val.videoID].media$expirationDate;
						}
					});

					sorter=sorter.sort(sortNumber);
					for(i=0;i<sorter.length;i++){
						for(i2=0;i2<sorter.length;i2++){
							if(sorter[i]==value[i2]){
								sorted[sorted.length]=key[i2];
								value[i2]=-1;
							}
						}
					}

					var render='';
					for(i=0;i<sorted.length;i++){
						if(259200000 > vod.cache.video['id_'+sorted[i]].media$expirationDate-vod.param.server.time*1000){
							render+=vod.template.grid(vod.cache.video['id_'+sorted[i]],'',false);
						}
					}
					if(render==''){
						$vod('.vod_playlist_content .vod_expiring ul', playList).css('display','none');
					}else{
						$vod('.vod_playlist_content .vod_expiring ul', playList).css('display','block');
					}
					$vod('.vod_playlist_content .vod_expiring ul', playList).html(render);
				}
			};
			// populate playlist
			if(!vod.filter.object.isEmpty(vod.cache.playlist)){
				sorter_expiring.data=vod.cache.playlist;
				$vod.each(vod.cache.playlist,function(inx, val){
					if(vod.cache.video['id_'+val.videoID]){
						playlist_Count++;
						rendering+=vod.template.grid(vod.cache.video['id_'+val.videoID],'',false);
					}
				});
				sorter_expiring.init();
			}
			// render playlist
			$vod('.vod_playlist_content ul.vod_sortable', playList).html(rendering);

			// replace failed image with SBS placeholder
			$vod('img.vod_clip').error(function() {
				if (!jQuery.browser.msie || jQuery.browser.version != '7.0') {
					$vod(this).removeAttr('src'); // cause browser freazing on IE7
				}
				$vod(this).attr('src', vod.param.noImagePlaceholderPath + vod.param.noImagePlaceholder);
			});
			var imagesNoSrc = $vod('img.vod_clip[src=""]');
			if (imagesNoSrc.length > 0) {
				imagesNoSrc.attr('src', vod.param.noImagePlaceholderPath + vod.param.noImagePlaceholder);
			}

			$vod('.vod_playlist .vod_playlist_video .vod_playlist_item').each(function(){
				if(vod.cache.video['id_'+$vod(this).attr('videoid')]){
					if(vod.param.server.time>vod.cache.video['id_'+$vod(this).attr('videoid')].media$expirationDate){
						$vod(this).prepend('<div class="vod_expired_video"><div class="vod_expired_video_shader" style="width:'+$vod(this).css('width')+';height:'+$vod(this).css('height')+'"><div class="tt_added"><div class="vod_tt_overlay"><a title="" href="javascript:void(0);" class="vod_playlist_remove"></a></div></div></div></div>');

						$vod(this).find('.vod_expired_video .vod_playlist_remove').click(function(){
							delete vod.cache['id_'+$vod(this).parents('.vod_playlist_item').attr('videoid')];
							$vod(this).parents('.vod_playlist_item').remove();
						});
					}
				}
			});

			// render expiring soon
			$vod('.playlist_summary span span', playList).html(playlist_Count);
			if(vod.param.request==0){
				$vod('.playlist_summary_counter', playList).css('display','block');
			}

			// alert full playlist
			if(playlist_Count>100){
				$vod('body').addClass('vod_playlist_full');
			}else{
				$vod('body').removeClass('vod_playlist_full');
			}

			// update page videos
			var allFilterOption = $vod('#vod_menu .playlist_filter li:contains("All")');
			var expireSoonFilterOption = $vod('#vod_menu .playlist_filter li:contains("Expire soon")');

			$vod('.playlist_filter_active', playList).removeClass('playlist_filter_active');
			allFilterOption.addClass('playlist_filter_active');

			var playlistContent = $vod('#vod_menu .vod_dropdown .vod_playlist_content');
			if(!vod.filter.object.isEmpty(vod.cache.playlist)){
				if(rendering!=''){
					playlistContent.addClass('vod_has_video');
					/*if(playlistContent.find('.vod_playlist_item').size()>3){
						playlistContent.addClass('vod_has_video_many');
					}else{
						playlistContent.removeClass('vod_has_video_many');
					}*/
					if($vod('#vod_menu .playlist_filter .playlist_filter_active a').html()=='All'){
						$vod('#vod_menu .vod_dropdown .vod_playlist_video').css('display','block');
					}else{
						if(!$vod('#vod_menu .vod_playlist.vod_playlist_extend')){
							$vod('#vod_menu .vod_dropdown .vod_playlist_video').css('display','none');
						}
					}
					expireSoonFilterOption.removeClass("disabled_filter");
				}else{
					playlistContent.removeClass('vod_has_video');
					expireSoonFilterOption.addClass("disabled_filter");
				}
			}else{
				$vod('#vod_menu .vod_dropdown .vod_playlist_video').css('display','none');
				playlistContent.removeClass('vod_has_video');
				expireSoonFilterOption.addClass("disabled_filter");
			}

			$vod('#vod_menu .vod_dropdown .playlist_help').css('display','block');
			if($vod('#vod_menu .vod_playlist_extend .aside_nav .vod_selected').size()>0){
				if($vod('#vod_menu .vod_playlist_extend .aside_nav .vod_selected a').attr('rel')=='playlist'){
					$vod('#vod_menu .vod_dropdown .playlist_help').css('display','block');
				}else{
					$vod('#vod_menu .vod_dropdown .playlist_help').css('display','none');
				}
			}

			// removed closed tips
			if(vod.param.server.state){
				$vod('#vod_menu .vod_dropdown .playlist_help_register').css('display','none');
			}else{
				$vod('#vod_menu .vod_dropdown .playlist_help_register').css('display','');
			}
			if(document.cookie.indexOf('vod_tip=autoplay')>-1){
				$vod('#vod_menu .vod_dropdown .playlist_help_play').remove();
			}
			else{
				// update top popsition of playlist_help_play
				vod.playlist.updatePosition();
			}

			// sync all video element
			$vod.each(vod.cache.playlist,function(inx, val){
				if(vod.cache.video['id_'+val.videoID]){
					$vod('.vod_playlist_item[videoid='+val.videoID+'] .vod_padder').addClass('tt_added').find('.vod_tt_overlay a').addClass('vod_playlist_remove');
					$vod('#vod_lead_marquee .vod_items a[videoid='+val.videoID+']').addClass('tt_added');
				}
			});
			// sync all progress element
			$vod.each(vod.cache.progress,function(inx, val){
				if(vod.cache.video[inx]){
					var vod_progress;
					if(typeof vod.cache.video[inx].media$content != 'undefined')
						vod_progress=parseInt((val)/(vod.cache.video[inx].media$content[0].plfile$duration*10));
					else if(typeof vod.cache.video[inx].duration != 'undefined' && vod.cache.video[inx].duration)
						vod_progress=parseInt((val)/(vod.cache.video[inx].duration*10));

					$vod('.vod_playlist_item[videoid='+inx.replace('id_','')+'] .vod_progress div').css('width',vod_progress+'%');
				}
			});

			// sync main video
			if(vod.cache.playlist['id_'+$vod('.vod_program_header .vod_playlist_item').attr('videoid')]){
				$vod('.vod_program_header .vod_playlist_item .info').html('Added to \'My Videos\'');
			}else{
				$vod('.vod_program_header .vod_playlist_item .vod_tt_overlay .vod_playlist_remove').removeClass('vod_playlist_remove');
				$vod('.vod_program_header .vod_playlist_item .info').html('Add to \'My Videos\'');
			}
			// sync all video tt menu
			$vod('.vod_playlist_item').each(function(inx, val){
				$vod(this).find('.tt_list li').css('display','');
				if(vod.cache.playlist['id_'+val.videoID]){
					$vod(this).find('.vod_playlist_popup_option').css('display','none');
					$vod(this).find('.vod_playlist_popup_option_added').css('display','block');
				}
			});

			// sync preference tab notification
			vod.playlist.notification.get();

			// update playlist tabs
			if($vod('#vod_menu .vod_playlist.vod_playlist_extend')){
				if($vod('#vod_menu .vod_playlist .aside_nav .vod_selected a').attr('rel')!='playlist'){
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_playlist_video').css('display','none');
				}
				// render history
				if(!vod.filter.object.isEmpty(vod.cache.history)){
					rendering='';
					$vod.each(vod.cache.history,function(inx, val){
						d=new Date(parseInt(val.viewed));
						//d = 'Added '+vod.filter.text.formatDate('j F',d);
						d = vod.filter.text.formatDate('j F',d);
						var filterTitle;
						if(vod.cache.video['id_'+val.videoID]){
							var media = vod.ds.processMediaObj(vod.cache.video['id_'+val.videoID], '');
							if (media['title'].length > vod.param.charLimit.gridLongLimit) {
								filterTitle = vod.filter.text.cleanStringExtract(media['title'], vod.param.charLimit.gridLongLimit);
							} else {
								filterTitle = media['title'];
							}
							rendering+='<li videoid="" class="vod_playlist_item"><div class="vod_padder"><div class="vod_gutter"><div></div><div class="info"><p><a href="'+(vod.param.server.videoPage+media['id']+'/'+vod.filter.text.websafe(media['title']))+'" class="vod_show">'+filterTitle+'</a><span class="vod_added">'+d+'</span><span class="vod_remain "><span class="">'+media['expirationDate']+'</span></span><span class="vod_duration">'+vod.filter.text.formatTime(vod.param.timeFormat, media['duration'])+'</span></p></div></div></div></li>';
						}else{
							if (val.title.length > vod.param.charLimit.gridLongLimit) {
								filterTitle = vod.filter.text.cleanStringExtract(val.title, vod.param.charLimit.gridLongLimit);
							} else {
								filterTitle = val.title;
							}
							rendering+='<li videoid="" class="vod_playlist_item vod_playlist_item_expired"><div class="vod_padder"><div class="vod_gutter"><div></div><div class="info"><p><a href="javascript:void(0)" class="vod_show">'+filterTitle+'</a><span class="vod_added">'+d+'</span><span class="vod_remain "><span class="">Expired</span></span><span class="vod_duration">'+vod.filter.text.formatTime(vod.param.timeFormat, val.duration)+'</span></p></div></div></div></li>';
						}
					});
					$vod('.vod_playlist .vod_filters span .btn_history_clear').remove();
					if(rendering==''){
						rendering='<li class="history_no_items"><p>You currently have no items in your history.</p></li>';
						$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_history .vod_header').css('display','none');
					}
					else{
						$vod('<a href="javascript:void(0);" class="btn_history_clear"><span>Clear History</span></a>').insertBefore('.vod_playlist .vod_filters span .close');
						$vod('.vod_playlist .vod_filters span .btn_history_clear').click(function(){
							$vod('.vod_playlist .vod_filters span .btn_history_clear').remove();
							vod.cache.history={};
							vod.ds.playlist.historyClear();
							vod.playlist.sync();
							$vod(this).remove();
						});
						$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_history .vod_header').css('display','block');
					}
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_history ul.playlist_tab').html(rendering);
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_history .vod_header').css('display','block');
				}
				else{
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_history ul.playlist_tab').html('<li class="history_no_items"><p>You currently have no items in your history.</p></li>');
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_history .vod_header').css('display','none');
				}
				// render subscribtions
				if ($vod('.vod_playlist.vod_playlist_extend .aside_nav li.vod_selected a').attr('rel')=='subscription') {
					if(!vod.filter.object.isEmpty(vod.cache.subscription) && vod.param.server.state) {
						renderingSubscription = '';
						$vod.each(vod.cache.subscription,function(inx, val){
							renderingSubscription += vod.template.subscription(vod.cache.subscription['id_'+val.seriesID]).replace('"vod_playlist_item"','"vod_playlist_item_subscription"');
							vod.ds.playlist.dealcode(vod.cache.subscription['id_'+val.seriesID]);
						});
						if(renderingSubscription == ''){
							$vod('.vod_playlist .vod_subscription .vod_header').css('display','none');
							renderingSubscription = '<li class="subscription_no_items"><p>You currently have no items in your subscription.</p></li>';
						}
						else{
							$vod('.vod_playlist .vod_subscription .vod_header').css('display','block');
						}
					}
					else {
						$vod('.vod_playlist .vod_subscription .vod_header').css('display','none');
						renderingSubscription = '<li class="subscription_no_items"><p>You currently have no items in your subscription.</p></li>';
					}
					$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_subscription ul.playlist_tab').html(renderingSubscription);
				}

				if($vod('#vod_menu .vod_playlist .aside_nav .vod_selected a').attr('rel')!='history'){
					$vod('.vod_playlist .vod_filters span .btn_history_clear').css('display','none');
				}
			}else{
				$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_expiring, .vod_playlist.vod_playlist_extend .content_list .vod_subscription, .vod_playlist.vod_playlist_extend .content_list .vod_notification, .vod_playlist.vod_playlist_extend .content_list .vod_history, .vod_playlist.vod_playlist_extend .content_list .vod_history, .vod_playlist.vod_playlist_extend .content_list .vod_expiring, .vod_playlist .vod_filters span .btn_history_clear').css('display','none');
				//$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_playlist_video').css('display','');
			}

		},
		extend:function(objTarget){
			if(vod.param.animating>0){return false;}
			var panelShow='#vod_menu .vod_playlist .vod_dropdown .vod_filters, #vod_menu .vod_playlist_content .vod_playlist_video';
			var panelHide='#vod_menu .vod_playlist .vod_dropdown .vod_playlist_content_header, #vod_menu .vod_playlist_content .vod_playlist_video, #vod_menu .vod_playlist_content .vod_expiring';

			// active states
			$vod('#vod_menu .vod_playlist .aside_nav .aside_nav_panel li.vod_selected').removeClass('vod_selected');
			var contentList = $vod('#vod_menu .vod_playlist .content_list');
			contentList.removeClass('vod_viewport');
			contentList.removeClass('v_l');


			if(objTarget.html()=='History'){
				panelShow='#vod_menu .vod_playlist .vod_dropdown .vod_filters, #vod_menu .vod_playlist .vod_playlist_content .vod_history';
				$vod('#vod_menu .vod_playlist .aside_nav .aside_nav_panel li').eq(3).addClass('vod_selected');
				vod.ds.playlist.tab('history');
			}
			else if(objTarget.html()=='Subscribe to Series'){
				panelShow='#vod_menu .vod_playlist .vod_dropdown .vod_filters, #vod_menu .vod_playlist .vod_playlist_content .vod_subscription';
				$vod('#vod_menu .vod_playlist .aside_nav .aside_nav_panel li').eq(1).addClass('vod_selected');
				vod.ds.playlist.tab('subscription');
			}
			else{
				panelShow='#vod_menu .vod_playlist .vod_dropdown .vod_filters, #vod_menu .vod_playlist .vod_playlist_content .vod_playlist_video';
				$vod('#vod_menu .vod_playlist .aside_nav .aside_nav_panel li').eq(0).addClass('vod_selected');
			}
			// animate
			vod.animation.counterAdd();
			$vod(panelHide).animate({opacity: [0, 'linear']}, 100, 'linear', function(){
				$vod(panelHide).attr('style','');
				$vod(panelHide).css('display','none');
				$vod('#vod_menu .vod_playlist').addClass('vod_playlist_extend');
				$vod(panelShow).css('display','block');
				$vod('#vod_menu .vod_playlist .vod_dropdown .vod_filters').css('opacity',0);
				$vod(panelShow).animate({opacity: [1, 'linear']}, 100, 'linear', function(){
					vod.animation.counterRemove();
				});
			});

			$vod('#vod_menu .vod_dropdown .content_list').css('visibility','hidden');
			vod.animation.counterAdd();
			contentList.toggleClass('vod_viewport v_l').css({'width':'795px'});;
			$vod('#vod_menu .vod_playlist .vod_dropdown').animate({width: ['990px', 'swing']}, 300, 'linear', function(){
				$vod('#vod_menu .vod_dropdown .content_list').css('visibility','visible');
				$vod('#vod_menu .vod_dropdown .content_list').css('opacity','0');
				$vod('#vod_menu .vod_dropdown .content_list').animate({opacity: ['1', 'swing']}, 100, 'linear', function(){
					vod.animation.counterRemove();
					vod.playlist.sync($vod('body'));
				});
			});
		},
		collapse:function(objTarget){
			var playlist = $vod('#vod_menu .vod_playlist');
			$vod('.vod_header', playlist).attr('style','');
			vod.animation.counterAdd();
			$vod('.vod_dropdown .vod_filters, .vod_playlist_content .vod_playlist_video', playlist).animate({opacity: [0, 'linear']}, 100, 'linear', function(){
				$vod('.content_list .vod_expiring, .vod_playlist .content_list .vod_subscription, .content_list .vod_notification, .content_list .vod_history, .content_list .vod_notification, .content_list .vod_playlist_video', playlist).css('display','none');
				$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_playlist_video').css('opacity','');
				playlist.removeClass('vod_playlist_extend');
				$vod('.playlist_filter_active', playlist).removeClass('playlist_filter_active');
				$vod('.playlist_filter li:first-child', playlist).addClass('playlist_filter_active');
				$vod('.vod_dropdown .vod_filters', playlist).css('display','none');
				$vod('.vod_dropdown .vod_playlist_content_header', playlist).css('display','block');
				$vod('.vod_dropdown .vod_playlist_content_header', playlist).css('opacity',0);
				$vod('.vod_dropdown .vod_playlist_content_header', playlist).animate({opacity: [1, 'linear']}, 100, 'linear', function(){
					vod.animation.counterRemove();
				});
			});
			vod.animation.counterAdd();
			$vod('#vod_menu .vod_playlist .content_list').css({'width':'328px'});
			$vod('#vod_menu .vod_playlist .content_list.vod_viewport').removeClass('vod_viewport');
			$vod('#vod_menu .vod_playlist .content_list.v1').removeClass('v1');

			$vod('#vod_menu .vod_playlist .vod_dropdown').animate({width: ['330px', 'swing']}, 300, 'linear', function(){
				$vod('#vod_menu .vod_playlist .vod_playlist_content .vod_playlist_video').attr('style','');
				$vod('#vod_menu .playlist_help').css('display', 'block');
				vod.animation.counterRemove();
				vod.playlist.sync($vod('body'));
			});
		},
		view:function(objTarget){
			if (objTarget.parent().hasClass('vod_selected')) {
				// the same item was clicked again
				return;
			}
			$vod('#vod_menu .vod_playlist .aside_nav .vod_selected').removeClass('vod_selected');
			objTarget.parent().addClass('vod_selected');
			$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_expiring, #vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_subscription, #vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_notification, #vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_history, #vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_history, #vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_expiring, .vod_playlist a.btn_history_clear').css('display','none');
			if(objTarget.attr('rel')=='playlist'){
				$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_playlist_video').css('display','block');
				$vod('#vod_menu .vod_dropdown .playlist_help').css('display','block');

				var playlistContent = $vod('#vod_menu .vod_dropdown .vod_playlist_content');
				if (!playlistContent.hasClass('vod_has_video')){
					$vod('#vod_menu .vod_dropdown .vod_playlist_video').css('display','none');
				}

				// update top popsition of playlist_help_play
				vod.playlist.updatePosition();
			}else{
				if(objTarget.attr('rel')=='notification'){
					/*$vod('#vod_menu .vod_playlist.vod_playlist_extend .content_list .vod_header').css('display','none');*/
				}
				$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_playlist_video').css('display','none');
				$vod('#vod_menu .vod_playlist.vod_playlist_extend .vod_playlist_content .vod_'+objTarget.attr('rel')).css('display','block');
				if(objTarget.attr('rel')=='history'){
					vod.ds.playlist.tab(objTarget.attr('rel'));
				}else if(objTarget.attr('rel')=='subscription'){
					if(vod.param.server.state){
						vod.ds.playlist.tab(objTarget.attr('rel'));
					}
					vod.playlist.sync($vod('body'));
				}
				$vod('#vod_menu .vod_dropdown .playlist_help').css('display','none');
			}
			return false;
		},
		filter:function(objTarget){
			if(!objTarget.parent().hasClass('playlist_filter_active') && !objTarget.parent().hasClass('disabled_filter')){
				$vod('#vod_menu .vod_playlist .playlist_filter li').removeClass('playlist_filter_active');
				objTarget.parent().addClass('playlist_filter_active');
				if(objTarget.html()=='All'){
					$vod('#vod_menu .vod_playlist .vod_playlist_video').css('display','block');
					$vod('#vod_menu .vod_playlist .vod_expiring').css('display','none');
				}else{
					$vod('#vod_menu .vod_playlist .vod_playlist_video').css('display','none');
					$vod('#vod_menu .vod_playlist .vod_expiring').css('display','block');
				}
				$vod('.playlist_help').css('display', 'block');
				vod.playlist.updatePosition();
			}
			return false;
		},
		commingSoon:{
			add:function(objTarget){
				var comingSoon = objTarget.parents('.vod_comming_soon');
				if(comingSoon.hasClass('vod_comming_soon_series')){
					vod.ds.playlist.comingSoon('/api/video_subscription/add/?dealcode='+comingSoon.attr('pilatdealcode'));
				}else{
					vod.ds.playlist.comingSoon('/api/video_programs/add/?pilatid='+comingSoon.attr('pilatid'));
				}

				/*disable*/
				comingSoon.removeClass('tt_active');
				comingSoon.find('.tt_list').css('display','none');
				/*perm remove*/
				comingSoon.find('.tt_list').remove();
			}
		},
		notification:{
			get:function(){
				if(vod.param.server.notification.subscription!=0){
					$vod('#vod_menu .vod_playlist .vod_notification input[name="subscription"]').attr('checked','checked');
				}else{
					$vod('#vod_menu .vod_playlist .vod_notification input[name="subscription"]').removeAttr('checked');
				}
				if(vod.param.server.notification.expiring!=0){
					$vod('#vod_menu .vod_playlist .vod_notification input[name="expiration"]').attr('checked','checked');
				}else{
					$vod('#vod_menu .vod_playlist .vod_notification input[name="expiration"]').removeAttr('checked');
				}
			},
			set:function(){
				if($vod('#vod_menu .vod_playlist .vod_notification input[name="subscription"]').attr('checked')){
					vod.param.server.notification.subscription=1;
				}else{
					vod.param.server.notification.subscription=0;
				}
				if($vod('#vod_menu .vod_playlist .vod_notification input[name="expiration"]').attr('checked')){
					vod.param.server.notification.expiring=1;
				}else{
					vod.param.server.notification.expiring=0;
				}
			},
			save:function(){
				vod.playlist.notification.set();
				vod.ds.playlist.notification.set();
			}
		},
		updatePosition:function(){
			if(document.cookie.indexOf('vod_tip=autoplay')>-1){
				return;
			}
			// calculate and update top coordinate for .playlist_help_play
			var playlistContent = $vod('#vod_menu .vod_dropdown .vod_playlist_content');
			var playlistContentScrollerHeight = 428;
			var playlistItemsContainerHeight = 0;
			var playlistItemsHeaderHeight = 0;
			var playlistHelpRegisterHeight = 0;
			var playlistHelpHowHeight = 0;

			var playlistContentScroller = playlistContent.find('.vod_playlist_content_scroller');
			if (playlistContentScroller) {
				playlistContentScrollerHeight = playlistContentScroller.outerHeight(true);
			}

			var playlistItemsContainer = null;
			if ($vod('.vod_playlist_video').css('display') == 'block') {
				playlistItemsContainer = playlistContent.find('.vod_playlist_video ul');
			}
			else {
				playlistItemsContainer = playlistContent.find('.vod_expiring ul');
			}
			if (playlistItemsContainer) {
				playlistItemsContainerHeight = playlistItemsContainer.outerHeight(true);
			}

			var playlistItemsHeader = playlistContent.find('.vod_playlist_video .vod_header');
			if (playlistItemsHeader && playlistItemsHeader.css('display') != 'none') {
				playlistItemsHeaderHeight = playlistItemsHeader.outerHeight(true);
			}

			var playlistHelpRegister = playlistContent.find('.playlist_help .playlist_help_register');
			if (playlistHelpRegister && playlistHelpRegister.css('display') != 'none') {
				playlistHelpRegisterHeight = playlistHelpRegister.outerHeight(true);
			}

			var playlistHelpHow = playlistContent.find('.playlist_help .playlist_help_how');
			if (playlistHelpHow && playlistHelpHow.css('display') != 'none') {
				playlistHelpHowHeight = playlistHelpHow.outerHeight(true);
			}

			var playlistHelpPlay = playlistContent.find('.playlist_help_play');
			if (playlistHelpPlay) {
				var playlistHelpPlayHeight = playlistHelpPlay.outerHeight(true);
				if (playlistItemsContainerHeight + playlistItemsHeaderHeight + playlistHelpRegisterHeight + playlistHelpHowHeight + playlistHelpPlayHeight < playlistContentScrollerHeight) {
					playlistHelpPlay.css('top', (playlistContentScrollerHeight - playlistHelpPlayHeight - playlistItemsContainerHeight - playlistItemsHeaderHeight - playlistHelpRegisterHeight - playlistHelpHowHeight) + 'px');
				}
				else {
					playlistHelpPlay.css('top', 'auto');
				}
			}
		}
	},
	popOut:{
		init:function(){
			/*
			 * Video Player - Follow screen scrolling
			 */
			var nav = $vod('#scrollbox'),
				content = $vod('body'),
				vodHeight = nav.outerHeight(true),
				vodLeft = nav.offset().left,
				navHeight = nav.outerHeight(true),
				navLeft = nav.offset().left,
				yMin = nav.offset().top - parseInt(nav.css('margin-top'), 10),
				navFix = navHeight + content.offset().top,
				yMax = content.offset().top + content.outerHeight(),
				position = 'default',
				positionCSS = {
					'default': {position: 'relative', bottom: 0},
					'fixed': {position: 'fixed', bottom: 0, visibility: 'visible'},
					'bottom': {position: 'absolute', bottom: yMax - content.offset().bottom - navHeight}
				};
			function setVodPosition() {
				var w = $vod(this),
					x = w.scrollLeft(),
					y = w.scrollTop();
				if (y > yMin) {
					if (y + vodHeight < yMax) {
						position = 'fixed';
						$vod('.left_column.vod_lhc').css({'z-index':'10'});
						$vod('.vod_lhc #vod_lead_marquee').css({'visibility':'hidden'});
					}
					else {
						position = 'bottom';
						$vod('.left_column.vod_lhc').css({'z-index':'1'})
						$vod('.vod_lhc #vod_lead_marquee').css({'visibility':'visible'});
					}
				}
				else {
					position = 'default';
					$vod('.left_column.vod_lhc').css({'z-index':'1'})
				}
				// Clear all styles, then set appropriately.
				nav.removeAttr('style');
				nav.css(positionCSS[position]);
				// Adjust for horizontal scroll.
				if (position === 'fixed' && x > 0) {
					nav.css({left: vodLeft - x});
				}
			}
			// Only slide the vod box on pages that are long enough.
			if (yMax - vodHeight > yMin) {
				$vod(window).scroll(setVodPosition);
			}
		}
	},
	switchView:{
		init:function(){

			/*
			 * Set Default View mode
			 */
			var defaultViewMode = $vod('#the_grid .vod_viewport').is('.v_l, .v_g')?true:false;
			if (!defaultViewMode) {
				$vod('#the_grid .vod_viewport').addClass('v_g');
			}

			/*
			 * Toggle View Modes
			 */
			var pageLoad = $vod('#the_grid .vod_viewport');
			var control = $vod('#the_grid .vod_filters .view_mode a[class]');

			if(pageLoad.hasClass('v_l')) {
				$vod('#the_grid .vod_filters .view_mode a.view_list').addClass('selected');
			} else if(pageLoad.hasClass('v_g')) {
				$vod('#the_grid .vod_filters .view_mode a.view_grid').addClass('selected');
			}

			$vod('#the_grid .vod_filters span .close').bind('click', function() {
				$vod('#video_page_container').css({visibility:'visible'});
				var currentRegion=$vod('#the_grid');
				// close menu else stay open
				if(currentRegion.css('display')=='block'){
					$vod('#vod_menu .vod_menu_tab .vod_selected').removeClass('vod_selected').next('span').animate({opacity:['toggle', 'swing'],height:['toggle', 'swing']}, 300, 'linear');
					currentRegion.find('.the_grid_region').css('opacity','1');
					vod.animation.counterAdd();
					currentRegion.find('.the_grid_region').animate({height:[0,'swing'],opacity:[0,'swing']}, 300,'linear', function(){
						vod.animation.counterRemove();
						currentRegion.find('.the_grid_region').removeAttr('style');
						currentRegion.find('.the_grid_region').css('height','');
						currentRegion.removeAttr('style');
					});
					$vod('.vod_selected, #vod_search').removeClass('vod_selected');
					$vod('#vod_menu .search_box').find('span').hide();
					$vod('.content .left_column, .content .right_column').css({height: 'auto'});
					vod.param.leadMarqueePause = 0;
					if (vod.menu.selfHidden) {
						vod.menu.hideVodMenu();
					}
				}
			});
			$vod('#the_grid .vod_filters .view_list, #the_grid .vod_filters .view_grid').click( function() {
				var t = $vod(this);
				var viewBy = t.attr('class');
				var viewPort = t.parent().parent().parent();
				if(viewBy == 'view_list') {
					control.removeClass('selected');
					t.addClass('selected');
					if(viewPort.hasClass('v_g')) {
						viewPort.removeClass('v_g');
					}
					viewPort.addClass('v_l');
				}
				else if (viewBy == 'view_grid') {
					control.removeClass('selected');
					t.addClass('selected')
					if(viewPort.hasClass('v_l')) {
						viewPort.removeClass('v_l');
					}
					viewPort.addClass('v_g');
				}

				// Resize page to line up videopopup with page footer
				if($vod('.footer_bg').length){
					var footerOffset = $vod('.footer_bg').offset().top,
					    popupOffset = $vod('#the_grid .the_grid_region').offset().top+$vod('#the_grid .the_grid_region').height();

					var diff = popupOffset - footerOffset;
					var height = $vod('.content').height();
					var adjustment = diff+height;
					if(adjustment > vod.param.contentHeight)
						$vod('.content .left_column, .content .right_column').css({height: adjustment});
				}
			});
		}
	},
	toolTip:{
		init:function(){
			vod.toolTip.closeTT();
			var containers = $vod('.vod_widget, .vod_widget_filter_related, #vod_lead_marquee, #the_grid .vod_viewport, .vod_program_header');

			$vod('ul.tt_list').each(function(index){
				var ttOptions = $vod(this).children('.vod_playlist_add');
				if(ttOptions.length == '1'){
					var ttOption = $vod(ttOptions.get(0));
					if(ttOption.find('a').text() == 'Add Video to Playlist' && ttOption.css('display') != 'none') {
						$vod(this).next().addClass('no_options');
					}
				}
			});

			containers.click(function(e){
				var target = e.target,
					$target = $vod(target),
					playlistObj = $vod('.vod_playlist');

				if(target.nodeName.toUpperCase() == 'A' && $target.parents('.vod_tt_overlay').length > 0 && playlistObj.length > 0){
					var t = $target;
					var ttl = $target.parent().parent().find('.tt_list');
					// check if already added or if still loading
					if(vod.cache.playlist['id_'+t.parents('.vod_playlist_item').attr('videoid')]||vod.param.requesting>0||vod.param.animating>0){return false;}

					var ttOpen = $vod('ul li').find('.tt_active');
					var ttTest = ttOpen?true:false;
					var box = t.parent().parent().parent().parent();
					var anim = t.hasClass('animating')?true:false;
					if (box.hasClass('tt_active')) {
						// checking for animation in progress and disabling clicks till complete
						if (anim != true) {
							t.addClass('animating');
							ttl.animate({
								 height: ['toggle', 'swing'],
								opacity: ['toggle', 'swing']
							},1, 'linear', function() {
								t.removeClass('animating');
								// resets all other active tooltips
								if (ttTest) {
									ttOpen.removeClass('tt_active');
									$vod('ul li *').find('.tt_list').hide();
								}
								box.removeClass('tt_active');
							});
						};
					} else {
						if (anim != true) {
							// auto add function instead of tooltip popup
							var ttoptions = ttl.children('.vod_playlist_add');
							if(ttoptions.length == 1){
								var ttoption = $vod(ttoptions.get(0));
								if(ttoption.find('a').text() == 'Add Video to Playlist' && ttoption.css('display') != 'none'){
									vod.playlist.add($vod(ttoptions.get(0)));
									return;
								}
							}

							if (ttTest) {
								ttOpen.removeClass('tt_active');
								$vod('ul li *').find('.tt_list').hide();
							}
							t.addClass('animating');
							ttl.animate({
								 height: ['toggle', 'swing'],
								opacity: ['toggle', 'swing']
							},1, 'linear', function() {
								t.removeClass('animating');
								box.addClass('tt_active');
							});
						}
					}
				}

				if (e.stopPropagation !== undefined) {
					e.stopPropagation();
				}
			});



			/*
			 * CONTENT EXPANDING.
			 */
			var tt_info = $vod('ul li .vod_padder');
			tt_info.each(function(index){
				var t = $vod(this);
				var Info = t.find('div.info');
				var progDiv = t.find('.vod_progress');
				t.unbind('mouseenter').unbind('mouseleave');
				t.bind({
					mouseenter: function() {
						if(!$vod(this).hasClass('hover')) $vod(this).parents('ul').find('.vod_padder.hover').mouseleave().removeClass('hover');
						var infoDiv = Info;
					  		defined = t.find('.info .infoexp').html()?true:false;

						// update expiration
						var videoId = $vod(this).parents('.vod_playlist_item').attr('videoid');
						var expiration = vod.cache.video['id_' + videoId]['media$expirationDate'];
						var now = new Date();
						if(now.getTime() > expiration){
							$vod(this).find('.vod_remain').html('<span class="pre-exp expired">Expired</span><span></span>');
						}
					  	if (!defined) {
					  		infoDiv.append('<div class="infoexp" style="width:100%;top:0px; left:0px">'
					  					 +	 '<p>'+ t.children().children('.info').children('p').html()+ '</p>'
					  					 + '</div>' );
					  	}
						//start:RHC line Mask
						  	var InfoExpParent = t.find('div.info').parent().parent().outerHeight(true);
							var	pTest = t.parent().parent().parent().parent().parent().parent().attr('class');
							if (pTest == 'right_column vod_rhc'){
						  		var pHeightMath = InfoExpParent-2;
						  		Info.append('<div class="masker" style="height:'+pHeightMath+'px;"></div>')
						  	}
						//end:RHC line Mask

					  	t.find('.info').children('p').css({'visibility':'hidden'});
					  	progDiv.css({'z-index':'11'});
					  	t.children().children().find('.infoexp').show();
			  		},
				  	mouseleave: function() {
						t.find('.info').children('p').css({'visibility':'visible'});
						t.children().children().find('.infoexp').hide();
						progDiv.css({'z-index':'9'});
						Info.find('.masker').remove();
				  	}
				});

			});
		},
		closeTT:function() {
			var bodyHandler = function() {
				$vod('.tt_active .tt_list').animate({
		 			height: ['toggle', 'swing'],
					opacity: ['toggle', 'swing']
				}, 1, 'linear');
				$vod('.vod_padder').removeClass('tt_active');
			};
			$vod('body').click(bodyHandler);
		}
	},
	carousel:{
		// timed autoscroll
		//window.setInterval(function(){$vod('.vod_carousel a.next').click();},7000);
		init:function() {
			$vod('div.scroller').each(function(){
				var s = $vod(this);
				s.show();
				var ul = s.find('ul').eq(0);
				var n = ul.find('li').length;
				if (s.hasClass('shop')){
					if (s.hasClass('rhs')) {n = Math.round(n/2);}
					else {n = Math.round(n/4)};
				}
				var w = Math.abs((parseFloat(s.find('.wrapper li').eq(0).outerWidth(true))));
				var m = Math.abs((parseFloat(s.find('.wrapper').eq(0).outerWidth(true))));
				var full_width = w*n;
				var dots = s.find('ol').eq(0);
				ul.css('width',full_width+'px');

				// SET indicator DOTS
				/*var str = '<li class="on"></li>';
				for (var i=1;i<n;i++) {
					str+= '<li></li>'
				}
				dots.html(str).css('marginLeft','-'+dots.width()/2+'px');	*/

				s.find('.btns > a').bind('click', function() {
					var a = $vod(this);
					vod.carousel.moveItems(a,ul,n,w,full_width,dots,m);
					a.parent().addClass('blocked');
					return false;
				});
				vod.carousel.rePosition(m,w,full_width,ul); // auto-position on page load (Detects classname "playing".
			});
		},
		moveItems:function(a,ul,n,w,full_width,dots,m){
			if (!a.parent().hasClass('blocked')) {
				var visItem = Math.floor(m/w); // Set number of visible items customise for adhoc builds
				var maskEnd = -w*visItem; // how wide is each
				var carouselEnd = Math.floor(full_width-(w*visItem));
				var dir = a.text();
				var left_pos = parseFloat(ul.css('left'));
				var new_left_pos = 0;
				if (dir=='Previous') { // Previous btn
					if (left_pos>=0) {
						new_left_pos = -carouselEnd;
					}
					else {
						new_left_pos = left_pos+w;
					}
				}
				else { // Next btn
					if (left_pos<=-full_width+w) {
						new_left_pos = 0;
					}
					else {
						new_left_pos = left_pos-w;
						if(left_pos == -carouselEnd) {
							new_left_pos = 0;
						}
					}
				}
				ul.animate({"left":[new_left_pos+'px', 'swing']},"20",function(){a.parent().removeClass('blocked')});
				/*dots.find('li').removeClass('on');
				dots.find('li').eq(Math.abs(new_left_pos/w)).addClass('on');*/
			}
		},
		rePosition:function(m,w,full_width,ul) {
			var visItem = Math.floor(m/w); // Set number of visible items
			var maskEnd = -w*visItem; // how wide is the mask
			$vod('div.scroller ul li').each(function() {
				t = $vod(this);
				if (t.is('.playing')) {
					var startPos = t.position().left;
					var testVal = full_width-startPos;
					var testCont = w*visItem;
					if (-ul.outerWidth() < maskEnd) { // checking carousel contens against visible mask
						new_left_pos = '-'+ t.position().left;
						if (testVal <= testCont) { //Checking dimensions for reposition
							new_left_pos = -(full_width+maskEnd);
						}
					} else { // if less items than can overflow the carousel mask
						new_left_pos = 0;
						$vod('div.scroller').find('.btns > a').unbind('click').addClass('disabled').click(function(event){
							event.stopPropagation();
						});
					}
					$vod('div.scroller ul').animate({"left":[new_left_pos+'px', 'swing']},"20");
				} else {
					if (-ul.outerWidth() > maskEnd) {
						$vod('div.scroller').find('.btns > a').unbind('click').addClass('disabled').click(function(event){
							event.stopPropagation();
						});
					}
				}
			});
		},
		render:function(objTarget, htmlRepeater, urlFeed, imageSize){

			var markup = '';

			// functions
			var writer = function(data, imageSize){

				var videoInSeries = false;
				var totalCount = data.entries.length;

				$vod.each(data.entries , function(inx, val){

					var playing = '';
					var videoId = vod.ds.filterVideoId(val.id);

					if(videoId == currVideoId){
						playing = ' class="playing"';
						if(totalCount > (inx+1)){
							nextVideoId = vod.ds.filterVideoId(data.entries[inx+1].id);
							nextVideoTitle = data.entries[inx+1].title.replace(/[^a-zA-Z 0-9]+/g,'-');
							nextVideoTitle = nextVideoTitle.replace(/\s/g, '-');
						}
						videoInSeries = true;
					}

					if(totalCount == (inx+1) && videoInSeries == false){
						nextVideoId = vod.ds.filterVideoId(data.entries[0].id);
						nextVideoTitle = data.entries[0].title.replace(/[^a-zA-Z 0-9]+/g,'-');
						nextVideoTitle = nextVideoTitle.replace(/\s/g, '-');
					}

					// save to video cache
					//vod.cache.video['id_' + videoId]=val;
					var value = htmlRepeater(val, imageSize, playing);

					if(value!=''){
						markup += value;
					}
					else {
						return '';
					}

				});

				if(markup!=''){
					objTarget.html(markup);
					objTarget.parent().find('.vod_disable').find('.vod_shader div').remove();
				}
			}

			$vod.ajax({
				url : urlFeed,
				dataType : 'json',
				success: function(data){
					if(data.entries.length > 1){ // Video Carousel should not appear when there is only 1 episode available on a series
						//vod.cache.feed[urlFeed]=data;
						writer(data, imageSize);
						vod.carousel.init();
					}
				},
				error: function(){
					if (window.ActiveXObject) {
						var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
						xmlHttpReq.open('POST', urlFeed, true);
						xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttpReq.onreadystatechange = function() {
							if (xmlHttpReq.readyState == 4) {
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									//vod.cache.feed[urlFeed]=data;
									writer(data, imageSize);
							}
						}
						xmlHttpReq.send();
					}
				},
				timeout: 5000,
				statusCode:{
					400 : function(){
						vod.error.genericRefresher();
					},
					404 : function(){
						vod.error.genericRefresher();
					},
					500 : function(){
						vod.error.genericRefresher();
					}
				}
			});

		}
	},
	autoPlay:{
		check:function() {
			autoSet = $vod('.autoplay');
			//set default states
			if(autoSet.hasClass('on, off') == false) {
				if($vod.cookie('vod_autoplay') == 'series') {
					$vod('.vod_carousel .autoplay').removeClass('off').addClass('on');
					$vod('.vod_playlist_content_footer .autoplay').removeClass('on').addClass('off');
				}
				else if ($vod.cookie('vod_autoplay') == 'playlist') {
					$vod('.vod_playlist_content_footer .autoplay').removeClass('off').addClass('on');
					$vod('.vod_carousel .autoplay').removeClass('on').addClass('off');
				}
				else {
					autoSet.addClass('off');
				}
			}
			//autoplay click events
			$vod('.autoplay a').unbind('click'); // Reset the delegation
			$vod('.autoplay a').bind('click', function() {
				t = $vod(this);
				p = t.parent();
				pL = p.parent().parent().hasClass('vod_playlist_content_footer')?true:false;

				if(t.hasClass('vod_auto_on') && pL) {
				// PLAYLIST - autoplay ON
					p.removeClass('off').addClass('on');
					$vod('.vod_carousel .autoplay').removeClass('on').addClass('off');
					$vod.cookie('vod_autoplay', 'playlist', { path: '/', domain: cookieDomain, expires: 7 });
				}
				else if(t.hasClass('vod_auto_off') && pL) {
				// PLAYLIST - autoplay OFF
					p.removeClass('on').addClass('off');
					$vod.cookie('vod_autoplay', 'off', { path: '/', domain: cookieDomain, expires: 7 });
				}
				else if(t.hasClass('vod_auto_on') && !pL) {
				// PAGE - autoplay ON
					p.removeClass('off').addClass('on');
					$vod('.vod_playlist_content_footer .autoplay').removeClass('on').addClass('off');
					$vod.cookie('vod_autoplay', 'series', { path: '/', domain: cookieDomain, expires: 7 });
				}
				else if(t.hasClass('vod_auto_off') && !pL) {
				// PAGE - autoplay OFF
					p.removeClass('on').addClass('off');
					$vod.cookie('vod_autoplay', 'off', { path: '/', domain: cookieDomain, expires: 7 });
				};
			});
		},
		setCookie:function() {
			if($vod.cookie('vod_autoplay') == 'series') {
				$vod.cookie('vod_autoplay', 'series', { path: '/', domain: cookieDomain, expires: 7 });
			}
			else if ($vod.cookie('vod_autoplay') == 'playlist') {
				$vod.cookie('vod_autoplay', 'playlist', { path: '/', domain: cookieDomain, expires: 7 });
			}
			else {
				autoSet.addClass('off');
				$vod.cookie('vod_autoplay', 'off', { path: '/', domain: cookieDomain, expires: 7 });
			}
		},
		//check if the auto play is on for either the playlist or series carousel and redirect to next video.
		getNextAutoplayUrl:function() {

			var firstVideoUrl = '';
			var nextVideoUrl = '';

			//if autoplay is on for series. (nextVideoId and nextVideoTitle is automatically set when the carousel is rendered.
			if($vod.cookie("vod_autoplay") == "series"){
				nextVideoUrl = (nextVideoId != '') ? baseUrl + '/video/' + nextVideoId + '/' + nextVideoTitle : '';
			 //elseif autoplay is on for playlist
			}else if($vod.cookie("vod_autoplay") == "playlist"){
				var playlistCount = vod.autoPlay.countProperties(vod.cache.playlist);
				var getNextElement = false;
				var counter = 1;
				$vod.each(vod.cache.playlist , function(inx, val){
					//vod.cache.video['id_'+val.videoID]
					//get next video id and title.
					var videoId = inx.replace('id_', '');

					if(counter <= playlistCount && getNextElement){
						nextVideoId = videoId;
						nextVideoTitle = vod.cache.video['id_'+videoId].title.replace(/[^a-zA-Z 0-9]+/g,'-');
						nextVideoTitle = nextVideoTitle.replace(/\s/g, '-');
						nextVideoUrl = (nextVideoId != '') ? vod.param.server.videoPage + nextVideoId + '/' + nextVideoTitle : '';
						getNextElement = false;
					}

					//get videoUrl for the first video in playlist.
					if(counter == 1) {
						var firstVideoTitle = vod.cache.video['id_'+videoId].title.replace(/[^a-zA-Z 0-9]+/g,'-');
						firstVideoTitle = firstVideoTitle.replace(/\s/g, '-');
						firstVideoUrl = (videoId != '') ? vod.param.server.videoPage + videoId + '/' + firstVideoTitle : '';
					}

					if(videoId == currVideoId){
						getNextElement = true;
					}
					counter++;
				});

				if(nextVideoUrl == ''){
					nextVideoUrl = firstVideoUrl;
				}
			}
			//alert(nextVideoUrl);
			return nextVideoUrl;
		},
		countProperties:function(obj) {
			var prop;
			var propCount = 0;

			for (prop in obj) {
				propCount++;
			}
			return propCount;
		}

	},
	logout:function() {
		$vod('.logout').bind('click', function() {
			var thisDomain = window.location.hostname;
			var logoutUrl = 'http://' + thisDomain + '/api/Member/logout/';
			$vod.ajax({
				url : logoutUrl,
				dataType : 'json',
				success: function(data) {
					window.location.reload();
				}
			});
		});
	},
	overlay: {
		init:function() {
			vod.overlay.attach();
			vod.logout();
		},
		close:function() {
			var ovrly = $vod('#ovrly');
			var overlay = $vod('#vod_overlay');
			$vod('#mask').fadeOut('fast');
			overlay.fadeOut('fast',function(){
				if ($vod('#mask').length==1){
					$vod('#mask').remove();
					$vod('#vod_overlay').remove();
					$vod('#close').remove();
					$vod('#overlay_content').remove();
				};
			});
		},
		//attach overlays
		attach:function() {
			// start: takeover oneClicks login panel
			var thisDomain = window.location.hostname.replace('www.', '');
			var thisDomain = thisDomain.replace('theworldgame.', '');

			var onClick = "$vod.cookie('core_anon', null, { path: '/', domain: '.sbs.com.au'}); oneSocialLogin.init(); return false;";
			if (!isChineseSite) {
				$vod('#socialLoginLink').html('<a class="lgn" href="javascript:void(0);" onclick="'+onClick+'">Login</a><span></span><a id="oneSignupLink" href="http://secure.' + thisDomain + '/signon/onesite/profile" title="Sign up now">Sign up now</a><div class="spreader"></div>');
			}
			$vod('.vod_login').show();

			var uLoggedIn = $vod('#tum_avatar_container');
			var uLogOut = $vod('#tum_top_links_td');
			var loggedIn = uLoggedIn.length;
			var checkSite = window.location.hostname;

			if(loggedIn > 0) {
				var user = uLoggedIn.find('a').find('img').attr('alt');
				if(checkSite.search('theworldgame.') >= 0) {
					// add undefined condition
					twgPanel();
					//$vod('.vod_login').html('<a class="user" href="/memberservices/user/'+ user +'" title="'+ user +' Profile">'+ user +'</a><span></span><a class="account_settings" href="http://theworldgame.' + thisDomain + '/memberservices/profile/" title="'+ user +' - Account Settings">Account Settings</a><span></span><a class="logout" target="_self" href="javascript:void(0);" title="Logout">Logout</a>');
				} else {
					$vod('.vod_login').html('<a class="user" href="javascript:void(0);">'+ user +'</a><span></span><a class="logout" target="_self" href="javascript:void(0);" title="Logout">Logout</a>');
				}
			} else {

				//site specific conditions (TWG)
				if(checkSite.search('theworldgame.') >= 0) {
					if($vod('#backofthenet_replace').length >= 1) {
						$vod('#backofthenet_replace a').removeAttr('rel').removeClass('show_twg_overlay botn_sm').unbind('click').attr('onclick',onClick);
					}
					var becomeLink = $vod('#socialLoginLink a.become').length;
					var settingsLink = $vod('a#oneAccountSettings').length;
					if(becomeLink == 0) {
						$vod('<a class="become" href="/news/994456/Become-a-Member" title="Become a Member" target="_parent">Become a Member</a><span></span>').insertBefore($vod('#socialLoginLink a.lgn'))
					}
					if(settingsLink != 0) {
						$vod('a#oneAccountSettings').each( function() {
							$vod(this).attr('href','http://theworldgame.'+thisDomain+'/memberservices/profile/');
						});
					}
					/*$vod('#socialLoginLink a.lgn').click( function() {

						$('#modalLoginBox').clone().appendTo('body');
						//console.log('div#modalLoginBox'.html);
					})*/
				}
			}

			// end: takeover oneClicks login panel
			var tCount = 0;
			$vod('#oneSignupLink, #oneAccountSettings').click(function() {
				var checkOnesite = $vod('a.modalClose')?true:false;
				if(checkOnesite) {
					$('#modalLoginBox').hide(); // modification for some onesite changes
					//$vod('a.modalClose').click(); // close OneSite login form
				};

				var a = $vod(this);
				if (a.hasClass('account_settings')) {
					var url = a.attr('name');
				}
				else {
					var url = 'http://secure.' + thisDomain + '/signon/onesite/register';
				}
				var iframe = a.attr('href')?true:false;
				var type = iframe?'<iframe id=\'iframe\' scrolling=\'no\' frameborder=\'0\'></iframe>':'<div id=\'overlay_container\'></div>';

				// check if overlay exists
				if ($vod('#mask').length==0){
					$vod('body').append('<div id=\'mask\'></div><div id=\'vod_overlay\'><div id=\'close\'><span></span>Close</div><div id=\'overlay_content\'>'+type+'</div></div>');
					$vod('#close').click(function(){vod.overlay.close();});
					$vod('#mask').click(function() {
						vod.overlay.close();
					});
					$vod('#vod_overlay').click(function(event){
						//event.stopPropagation();
					});
				};
				$vod('#overlay_content').html(type);
				if (iframe){$vod('#iframe').attr('src',url);}
				else {
					$vod('#overlay_container').load(url,function() {
					});
				};
				// set inner based on type
				var overlay = $vod('#vod_overlay');

				// show (extra bits needed 'cause ie sucks...)
				var top_pos = $vod(window).scrollTop() - (parseFloat(overlay.css('height'))/2);
				$vod('#mask').css({'height':$vod(document).height(),'display':'block','opacity':'0'}).animate({opacity:['1','swing']},'fast');

				var windowHeight = $vod(window).height()/2;
				var divHeight = $vod('#vod_overlay').height()/2;
				var divPos = windowHeight-divHeight;
				overlay.css('marginTop',divPos+'px').fadeIn('fast');
				return false;
			});
		}
	},
	animation:{
		init:function(objTarget){
		// general clearing
			$vod('.the_grid').attr('style','');
			$vod('.vod_selected, form#vod_search').removeClass('vod_selected');
			$vod('.vod_menu_tab').find('span').hide();
			$vod('.search_box').find('span').hide();
			$vod('.vod_browse_select').removeClass('vod_browse_select');
		// tooltips
			$vod('.vod_padder').removeClass('tt_active z1 z0');
			$vod('.tt_list').hide();
		// playlist
			$vod('.vod_dropdown, .vod_dropdown .vod_header').attr('style','');
			$vod('.vod_dropdown .vod_subscription, .vod_dropdown .vod_notification, .vod_dropdown .vod_history').css('display','none');
			$vod('.vod_playlist').removeClass('vod_playlist_selected');
			$vod('.vod_playlist.vod_playlist_extend .vod_dropdown, .vod_playlist.vod_playlist_extend .content_list, .vod_playlist.vod_playlist_extend .vod_filters, .vod_playlist.vod_playlist_extend .vod_playlist_content_header').attr('style','');

			$vod('.vod_playlist.vod_playlist_extend .vod_viewport').removeClass('vod_viewport');
			$vod('.vod_playlist.vod_playlist_extend .v_l').removeClass('v_l');
			$vod('.vod_playlist.vod_playlist_extend').removeClass('vod_playlist_extend');
			 //for resetting page height if showMore was pressed
			$vod('.content .left_column, .content .right_column').css({height: 'auto'});
		},
		/*
		 * param object animateion target
		 */
		clickDisable:function(objTarget){
			if($vod(objTarget).parent().find('.vod_disable')){
				$vod(objTarget).parent().prepend('<div class="vod_disable"><div class="vod_shader"><div></div></div></div>');
			}
			objTarget.parent().css('width',objTarget.parent().css('width'));
			objTarget.parent().find('.vod_shader, .vod_shader div').css('width',objTarget.parent().css('width'));
			objTarget.parent().find('.vod_shader, .vod_shader div').css('height',objTarget.parent().css('height'));
		},
		clickEnable:function(objTarget){
			vod.animation.counterAdd();
			objTarget.animate({opacity:[1, 'swing']}, 300,'linear', function(){
				vod.animation.counterRemove();
				if(vod.param.animating==0){
					$vod('.vod_disable').remove();
				}
				objTarget.css('opacity','1');
			});
		},
		counterAdd:function(){
			vod.param.animating++;
		},
		counterRemove:function(){
			if(vod.param.animating>0){
				vod.param.animating--;
			}
		},
		showLeftNav:function(){
			//Show left nav if hidden
			$vod('.the_grid .content_list, .the_grid_region').removeClass('vod_search');
			$vod('.the_grid .content_list, .vod_view_grid div.vod_viewport.v_l > ul > li').css({'width':''});
			$vod('.the_grid .vod_viewport').css({'width':'795px'});
			if($vod('.the_grid .aside_nav').width() == 0){
				vod.animation.counterAdd();
				$vod('.the_grid .aside_nav').animate({'width': '173px'}, 300, function(){
					vod.animation.counterRemove();
					vod.animation.clickEnable($vod('#the_grid .vod_view_grid ul.vod_loader'));
				});
			}
		},
		hideLeftNav:function(){
			$vod('.the_grid .content_list, .the_grid_region').addClass('vod_search');
			$vod('.the_grid .aside_nav').css({overflow: "hidden"});
			vod.animation.counterAdd();
			$vod('.the_grid .vod_filters, .the_grid .vod_viewport').animate({'width': '990px'}, 300);
			$vod('.the_grid .vod_loader').animate({'width': '100%'}, 300);
			$vod('.the_grid .content_list').animate({'width': '990px'}, 300);
			$vod('.the_grid .aside_nav').animate({'width': '0px'}, 300, function(){
				vod.animation.clickDisable($vod('#the_grid .vod_view_grid ul.vod_loader'));
				vod.animation.counterRemove();
			});
		},
		switchLeadMarqueeImage:function(isClick){
            if($vod('#vod_lead_marquee .vod_items li').length <= 1) return;
			if(vod.param.animating > 0 || vod.param.leadMarqueePause > 0) return;
			isClick = (typeof(isClick) == 'object');
			if(isClick){
				for(var n = 0; n < vod.param.leadMarqueeTimeoutArray.length; n++){
					clearTimeout(vod.param.leadMarqueeTimeoutArray.shift());
				}
				var item;
				for(var n = 0; n < 3; n++){
					if(this == $vod('#vod_lead_marquee .vod_items a').get(n)){
						item = n;
						break;
					}
				}
				vod.animation.leadMarqueeLoop(item);
			}

 			// do nothing if selected
            if($vod(this).hasClass('vod-selected')) return false;

			// check if added to playlist
			if($vod(this).hasClass('tt_added')) $vod('#vod_lead_marquee .vod_playlist_item .vod_padder').addClass('tt_added');
			else $vod('#vod_lead_marquee .vod_playlist_item .vod_padder').removeClass('tt_added');

			// modify playlist tooltip
			if($vod(this).attr('series') == 'true') $vod('#vod_lead_marquee .vod_playlist_item .tt_list .vod_pl_series').removeClass('preLoad');
			else $vod('#vod_lead_marquee .vod_playlist_item .tt_list .vod_pl_series').addClass('preLoad');

			if($vod(this).attr('trailer') == 'true') $vod('#vod_lead_marquee .vod_playlist_item .tt_list .vod_pl_trailer').removeClass('preLoad');
			else $vod('#vod_lead_marquee .vod_playlist_item .tt_list .vod_pl_trailer').addClass('preLoad');

            var 	element = $vod(this),
					imageURL = element.attr('rel'),
					linkURL = element.attr('link'),
					title = element.attr('title'),
					description = element.attr('description'),
					id = element.attr('videoid'),
					duration = vod.filter.text.formatTime(vod.param.timeFormat, element.attr('duration'));
					// default state for duration
					if(duration==''){
						duration='--:--';
					}

            // Select thumbnail
            $vod('#vod_lead_marquee .vod_items a').removeClass('vod-selected');
            element.addClass('vod-selected');

            // Change video meta
            $vod('#vod_lead_marquee #vod_meta').stop().animate({opacity: [0, 'swing']}, 100, 'linear', function(){
                $vod('#vod_lead_marquee #vod_title').html('<a href="'+linkURL+'" title="'+title+'">'+title+'</a>');
                $vod('#vod_lead_marquee #vod_description').text(description);
                $vod('#vod_lead_marquee div > .vod_show').attr('href', linkURL);
                $vod('#vod_lead_marquee .vod_tt_overlay a').attr('title', duration);
                $vod('#vod_lead_marquee .vod_tt_overlay a').html(duration);
				$vod('#vod_lead_marquee .vod_playlist_item').attr('videoid', id);

                // Animate fade
                $vod('#vod_lead_marquee .vod_clip').stop().animate({opacity:[0, 'swing']}, 300, 'linear', function(){

                    // Setup buffer
                    $vod(this).attr('src', imageURL).delay(50).animate({opacity:[1, 'swing']}, 300, 'linear');
                    $vod('#vod_lead_marquee #vod_meta').animate({opacity: [1, 'swing']}, 300, 'linear');
                });
            });
        },
		leadMarqueeLoop:function(i){
			i++;
			if(i > 2) i = 0; // reset loop
            if($vod('#vod_lead_marquee .vod_items li').length > 1){
                var todo = "vod.animation.switchLeadMarqueeImage.call($vod('#vod_lead_marquee .vod_items a').get("+i+"), true); vod.animation.leadMarqueeLoop("+i+");";
                vod.param.leadMarqueeTimeoutArray.shift();
                vod.param.leadMarqueeTimeoutArray.push(setTimeout(todo, vod.param.leadMarqueeTimeout));
            }
		},
		stopLeadMarquee:function(){
			for(var n = 0; n < vod.param.leadMarqueeTimeoutArray.length; n++)
				clearTimeout(vod.param.leadMarqueeTimeoutArray.shift());
		}
	},
	error:{
		genericRefresher:function(){

		}
	},
	ds:{
		counterAdd:function(){
			vod.param.request++;
		},
		counterRemove:function(){
			if(vod.param.request>0){
				vod.param.request--;
			}
		},
		/**
		 * get
		 *
		 * @param string namspace
		 * @param json vod
		 * @return json
		 */
		getObj:function(name,result){
			name=name.replace(window.location+"/",'').replace(window.location,'').split('.'); // fix IE bug returning domain as well
			for(i=0;i<name.length;i++){
				result=result[name[i].toString()];
			}
			return result;
		},
		filterVideoId:function(idString){
			var videoIdMatch = /\d+/.exec(idString);
			if(videoIdMatch != null){
				return videoIdMatch[0];
			}
			return '';
		},
		detectSize: function(objTarget){
			var that = objTarget, imageSize = 'medium';
			for(var i = 0; i < 5; i++){
					if($vod(that).hasClass('vod-size-medium')){
							imageSize = "medium";
							break;
					} else if($vod(that).hasClass('vod_loader')){
							imageSize = "mediumGrid";
							break;
					} else if($vod(that).hasClass('vod-size-small')){
							imageSize = "small";
							break;
					} else if($vod(that).hasClass('vod-size-large')){
							imageSize = "large";
							break;
					} else if($vod(that).hasClass('vod-size-leadMarquee')){
							imageSize = "leadMarquee";
							break;
					} else if($vod(that).hasClass('vod-size-leadMarquee-smaller')){
							imageSize = "leadMarqueeSmaller";
							break;
					} else that = $vod(that).parent();
			}
			return imageSize;
		},
		detectFilterImageSize: function(objTarget){
			var that = objTarget, imageSize = [];
			for(var i = 0; i < 5; i++){
					if($vod(that).hasClass('vod-size-medium')){
							imageSize['size'] = "medium";
							imageSize['width'] = "400";
							imageSize['height'] = "226";
							break;
					} else if($vod(that).hasClass('vod_loader')){
							imageSize['size'] = "mediumGrid";
							imageSize['width'] = "134";
							imageSize['height'] = "75";
							break;
					} else if($vod(that).hasClass('vod-size-small')){
							imageSize['size'] = "small";
							imageSize['width'] = "134";
							imageSize['height'] = "75";
							break;
					} else if($vod(that).hasClass('vod-size-large')){
							imageSize['size'] = "large";
							imageSize['width'] = "400";
							imageSize['height'] = "226";
							break;
					} else that = $vod(that).parent();
			}
			return imageSize;
		},
		getFilterThumbnailUrl: function(thumbnails, imageSize){

			var imageUrl = '';
			var backupThumb = '';

			for (var i = 0; i < thumbnails.length; i++){
				var imageWidth = Number(thumbnails[i].width);
				if(thumbnails[i].width == imageSize['width']){
					imageUrl = thumbnails[i].url;
				}else if(imageWidth > 100 && imageWidth < 400){
					backupThumb = thumbnails[i].url;
				}
			}
			if(imageUrl == '' && backupThumb != ''){
				imageUrl = backupThumb;
			}
			return imageUrl;
		},
		/**
		 * write content grid
		 * @param string urlFeed
		 * @param obj objTarget
		 * @return string
		 */
		grid:function(urlFeed, objTarget, htmlRepeater){
			var markup = '';
			//Save url in state
			vod.param.url = urlFeed;

			//Autodetect what thumbnail dimensions to use
			var imageSize = vod.ds.detectSize(objTarget);
			if(urlFeed.indexOf('defaultThumbnailAssetType') == -1) urlFeed += "&defaultThumbnailAssetType="+vod.param.settings[imageSize].defaultThumbnailAssetType;

			vod.param.currentlyBrowsing = urlFeed;

			// functions
			var empty  = function(type){
				type = type || "empty";
				if(type == "empty") type = -100;
				else type = parseInt(type.replace(' Error', ''));
				$vod('#the_grid .vod-show-more').hide();
				var markup = '';
				switch(type){
					case 400:
						markup = '<h2 class="vod-error">No videos found</h2>' +
								'<p class="vod-error">We\'re sorry but videos are currently not available for the chosen category. Please choose another category from the left.</p>';
						break;
					case 404:
						markup = '<h2 class="vod-error">404 - Page not found</h2>';
						break;
					case 500:
						markup = '<h2 class="vod-error">No videos found</h2>' +
								'<p class="vod-error">We\'re sorry but videos are currently not available for the chosen category. Please choose another category from the left.</p>';
						break;
					default:
						markup = '<h2 class="vod-error">No videos found</h2>' +
								'<p class="vod-error">We\'re sorry but videos are currently not available for the chosen category. Please choose another category from the left.</p>';
						break;
				}

				objTarget.html(markup);
				objTarget.parent().find('.vod_disable').find('.vod_shader div').remove();
				vod.toolTip.init();
				vod.switchView.init();
				vod.animation.counterAdd();
				objTarget.animate({opacity:[1, 'swing']}, 200,'linear', function(){
					vod.animation.counterRemove();
					vod.animation.clickEnable(objTarget);
				});
			};

			var cleaner = function(){
				objTarget.parent().find('.vod_disable').find('.vod_shader div').remove();
				vod.toolTip.init();
				vod.switchView.init();
				vod.animation.counterAdd();
				objTarget.animate({opacity:[1, 'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					vod.animation.clickEnable(objTarget);
				});
			}

			var writerComingSoon = function(data){
				$vod('#the_grid .vod_viewport .vod_comming_soon_container').html('');
				vod.ds.counterRemove();
				var row="";
				var rowCount=0;

				$vod.each(data.comingsoon.response.series , function(inx, val){
					rowCount++;
					if(rowCount>5){
						rowCount=1;
					}
					row=row+'<li class="vod_comming_soon vod_comming_soon_series vod_comming_soon_count_'+rowCount+'" pilatDealcode="'+val.pilatDealcode+'"><div class="vod_padder"><div class="vod_gutter">'
										+'<ul style="display: none;" class="tt_list"><li class="t_cnr"></li><li class="vod_playlist_popup_title"><p>Add to \'My Videos\'</p></li><li class="vod_playlist_popup_option vod_playlist_full"><div><a href="javascript:void(0);" title="Your playlist is full">Your playlist is full</a></div></li><li class="vod_playlist_popup_option vod_playlist_popup_option_added"><div><a href="javascript:void(0);" title="Added to My Videos">Added to \'My Videos\'</a></div></li><li class="vod_playlist_popup_option vod_playlist_add vod_playlist_subscription"><div><a href="javascript:void(0);" title="Subscribe to series">Subscribe to series</a></div></li><li class="b_cnr"></li></ul>'
										+'<div class="vod_tt_overlay"><a href="javascript:void(0);">'+val.title+'</a>'
									+'</div></div></div></li>';
				});
				$vod('#the_grid .vod_viewport .vod_comming_soon_container').append('<h3>Upcoming Series</h3><ul class="blocklist">'+row+'</ul>');
				$vod('#the_grid .vod_comming_soon a[title="Subscribe to series"]').bind('click',function(){
					vod.playlist.commingSoon.add($vod(this));
				});

				row="";
				rowCount=0;
				var duplicate=new Array();
				var duplicates='';
				var count=0;
				// remove duplicate
				$vod.each(data.comingsoon.response.programs , function(inx, val){
					duplicate[duplicate.length]=val.title;
				});
				for(i=0;i<duplicate.length;i++){
					count=0;
					for(i2=i+1;i2<duplicate.length;i2++){
						if(duplicate[i]==duplicate[i2]){
							duplicates+='@#'+duplicate[i]+'#@';
						}
					}
				}
				$vod.each(data.comingsoon.response.programs , function(inx, val){
					if(duplicates.indexOf('@#'+val.title+'#@')<0){
						rowCount++;
						if(rowCount>5){
							rowCount=1;
						}
						row=row+'<li class="vod_comming_soon vod_comming_soon_count_'+rowCount+'" pilatId="'+val.pilatId+'"><div class="vod_padder"><div class="vod_gutter">'
											+'<ul style="display: none;" class="tt_list"><li class="t_cnr"></li><li class="vod_playlist_popup_title"><p>Add to \'My Videos\'</p></li><li class="vod_playlist_popup_option vod_playlist_full"><div><a href="javascript:void(0);" title="Your playlist is full">Your playlist is full</a></div></li><li class="vod_playlist_popup_option vod_playlist_popup_option_added"><div><a href="javascript:void(0);" title="Added to My Video">Added to \'My Videos\'</a></div></li><li class="vod_playlist_popup_option vod_playlist_add"><div><a href="javascript:void(0);" title="Add when program available">Add when program available</a></div></li><li class="b_cnr"></li></ul>'
											+'<div class="vod_tt_overlay"><a href="javascript:void(0);">'+val.title+'</a>'
										+'</div></div></div></li>';
					}
				});
				$vod('#the_grid .vod_viewport .vod_comming_soon_container').append('<h3>Upcoming Programs</h3><ul class="blocklist">'+row+'</ul>');
				$vod('#the_grid.vod_comming_soon a[title="Add when program available"]').bind('click',function(){
					vod.playlist.commingSoon.add($vod(this));
				});


				if($vod('#the_grid .vod_viewport .vod_comming_soon_container').html()==''){
					$vod('#the_grid .vod_viewport .vod_comming_soon_container').css('display','none');
				}

				cleaner();
			}
			var writer = function(data, imageSize){
				$vod.each(data.entries , function(inx, val){
					// save to video cache
					vod.cache.video['id_'+vod.ds.filterVideoId(val.id)]=val;
					var val = vod.template.grid(val, imageSize);
					if(val!=''){
						markup += val;
					}
					else {
						return '';
					}
				});

				if(markup!=''){
						if(data.totalResults > (data.startIndex + data.entryCount - 1)){ // Display 'show more' link if there are extra results
							if($vod('#the_grid .vod-show-more').length == 0) { //if it doesn't exist, create it!
								$vod('#the_grid .vod_viewport').append('<div class="vod_show_more_anchor"><a href="#'+$vod('.vod_btn_back').attr('rel') +'" class="vod-show-more">Show '+data.itemsPerPage+' more</a></div>');
								$vod('#the_grid .vod-show-more').click(vod.menu.showMore);
							}


							var count = parseInt(data.totalResults) - parseInt(data.entryCount) - parseInt(data.startIndex) + 1;
							count = (count > data.itemsPerPage) ? data.itemsPerPage : count;
							$vod('#the_grid .vod-show-more').html('Show '+count+' more');

							var values = vod.param.range.split("-"),
											begin = parseInt(values[0])+parseInt(data.itemsPerPage),
											end = parseInt(values[1])+parseInt(data.itemsPerPage);

							$vod('#the_grid .vod-show-more').attr('rel', begin+"-"+end);
							$vod('#the_grid .vod-show-more').show();
						} else {
								$vod('#the_grid .vod-show-more').hide();
						}

						if($vod('#the_grid .aside_nav .vod_browse_select').html()=='Coming Soon'){
							$vod('#the_grid .vod_viewport').addClass('vod_viewport_comming_soon');
							if($vod('#the_grid .vod_viewport .vod_comming_soon_container').size()==0){
								$vod('#the_grid .vod_viewport').append('<div class="vod_comming_soon_container"></div>');
							}
						}else{
							$vod('#the_grid .vod_viewport').removeClass('vod_viewport_comming_soon');
							$vod('#the_grid .vod_viewport .vod_comming_soon_container').remove('');
						}
						if($vod('#the_grid .vod-show-more').hasClass('vod-show-more-active')){
							objTarget.append(markup);
							// Resize page to line up videopopup with page footer
                            if($vod('.footer_bg').length){
                                var footerOffset = $vod('.footer_bg').offset().top,
                                    popupOffset = $vod('#the_grid .the_grid_region').offset().top+$vod('#the_grid .the_grid_region').height();

                                if(popupOffset > footerOffset){
                                    var diff = popupOffset - footerOffset;
                                    var height = $vod('.content').height();
                                    var adjustment = diff+height;
                                    $vod('.content .left_column, .content .right_column').css({height: adjustment});
                                }
                            }
							$vod('#the_grid .vod-show-more').removeClass('vod-show-more-active');

						} else {
							$vod('.content .left_column, .content .right_column').css({height: 'auto'});
							objTarget.html(markup);
						}
						urlFeed='/api/video_programs/comingsoon';
						if($vod('#the_grid .aside_nav .vod_browse_select').html()=='Coming Soon'){

							vod.ds.counterAdd();
							$vod.ajax({
								url : urlFeed,
								dataType : 'json',
								success: function(data){
                                    if(typeof data.isException == 'undefined'){
                                        vod.cache.feed[urlFeed]=data;
                                        writerComingSoon(data);
                                    } else empty("400 Error");
								},
								error: function(){
									if (window.ActiveXObject) {
										var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
										xmlHttpReq.open('POST', urlFeed, true);
										xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
										xmlHttpReq.onreadystatechange = function() {
											if (xmlHttpReq.readyState == 4) {
												vod.ds.counterRemove();
												var data = $vod.parseJSON(xmlHttpReq.responseText);
												vod.cache.feed[urlFeed]=data;
												writerComingSoon(data);
											}
										}
										xmlHttpReq.send();
									} else vod.ds.counterRemove();
								},
								statusCode:{
									400 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
										empty("400 Error");
									},
									404 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
										empty("404 Error");
									},
									500 : function(){
										vod.ds.counterRemove();
										// show nice error
										vod.error.genericRefresher();
										empty("500 Error");
									}
								}
							});
						}else{
							cleaner();
						}
				} else  { //if result is empty
					empty();
                }

				if(vod.param.request==0){
					vod.playlist.sync($vod('body'));
				}
			};

			// check cache data
			//vod.animation.clickDisable(objTarget);

			if(vod.cache.feed[urlFeed]){
				if(vod.param.currentlyBrowsing == urlFeed)
					writer(vod.cache.feed[urlFeed], imageSize);
			}else{
				vod.animation.counterAdd();
				objTarget.animate({opacity:[0.3, 'swing']}, 300,'linear', function(){
					vod.animation.counterRemove();
					vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						dataType : 'json',
						success: function(data){
                            if(typeof data.isException == 'undefined'){
                                vod.ds.counterRemove();
                                vod.cache.feed[urlFeed]=data;
                                if(vod.param.currentlyBrowsing == urlFeed)
                                    writer(data, imageSize);
                            } else empty("400 Error");
						},
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										vod.cache.feed[urlFeed]=data;
										writer(data, imageSize);
									}
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							400 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
								empty("400 Error");
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
								empty("404 Error");
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
								empty("500 Error");
							}
						}
					});
				});
			}
		},
		widget:function(objTarget, htmlRepeater, urlOverride, showMore){
			var markup = '';
			var urlFeed=objTarget.find('.vod_attr_feed').attr('title');
			urlFeed = urlFeed || urlOverride;
			var imageSize = vod.ds.detectSize(objTarget);
			// put in debug feed if feed failed
			if(!urlFeed){
				var publicFeedId = (mpxFeedId == 'dYtmxB') ? 'section-programs' : 'sbs-section-programs';
				urlFeed='http://feed.theplatform.com/f/'+mpxFeedId+'/'+publicFeedId+'/?byCategories=Channel/SBS1|Channel/SBS2&byPubDate=1314086400000~1314108000000&form=json&range=1-2';
			}
			if(urlFeed.indexOf('defaultThumbnailAssetType') == -1) urlFeed += "&defaultThumbnailAssetType="+vod.param.settings[imageSize].defaultThumbnailAssetType;
			// functions
			var error = function(){
				var widget = objTarget.parent().parent().parent();
				if(!widget.hasClass('vod_featured'))
					widget.remove();
			};
			var writer = function(data, imageSize){
				if(typeof data.entries == 'undefined' || data.entries.length == 0)
				{
					objTarget.html('&nbsp');
					vod.ds.counterRemove();
					vod.animation.clickEnable(objTarget);
					return;
				}
				// if parent column has a class starting from vod_section_, then add section name when video URL will be built
				var inSection = '';
				var sectionClassPrefix = 'vod_section_';

				var sectionParentObj = objTarget.parents('[class*="'+sectionClassPrefix+'"]');
				if (sectionParentObj && sectionParentObj.length > 0){
					var columnClassName = sectionParentObj[0].className;
					if (columnClassName && columnClassName.indexOf(sectionClassPrefix) != -1) {
						var classNames = columnClassName.split(' ');
						$vod.each(classNames, function(index, className) {
							if (className.indexOf(sectionClassPrefix) != -1){
								inSection = className.substr(sectionClassPrefix.length);
							}
						});
					}
				}

				$vod.each(data.entries , function(inx, val){
					// save to video cache
					vod.cache.video['id_'+vod.ds.filterVideoId(val.id)]=val;
					var value = vod.template.grid(val, imageSize, '', '', '', inSection);
					if(value!=''){
						markup += value;
					}
					else {
						return '';
					}
				});
				if(markup!=''){
                    var showMoreElement = objTarget.parent().find('.vod-widget-show-more');
                    if(data.totalResults > (data.startIndex + data.entryCount - 1) && objTarget.hasClass('vod_show_more')){ // Display 'show more' link if there are extra results
						if(showMoreElement.length == 0) { //if it doesn't exist, create it!
							objTarget.parent().append('<div class="vod_show_more_anchor"><a href="javascript:void(0);" url="'+urlFeed+'" class="vod-widget-show-more">Show '+data.itemsPerPage+' more</a></div>');
                            showMoreElement = objTarget.parent().find('.vod-widget-show-more');
							showMoreElement.click(vod.ds.widgetShowMore);
						}

						var count = parseInt(data.totalResults) - parseInt(data.entryCount) - parseInt(data.startIndex) + 1;
						count = (count > data.itemsPerPage) ? data.itemsPerPage : count;
						showMoreElement.html('Show '+count+' more');

						var range = urlFeed.substr(urlFeed.indexOf('range=')+6);
						range = range.substring(0, range.indexOf('&'));

						var values = range.split("-"),
										begin = parseInt(values[0])+parseInt(data.itemsPerPage),
										end = parseInt(values[1])+parseInt(data.itemsPerPage);

						showMoreElement.attr('rel', begin+"-"+end);
						showMoreElement.show();
					} else {
						showMoreElement.hide();
					}

					if(typeof showMore != 'undefined' && showMore) objTarget.append(markup);
					else objTarget.html(markup);

					if(objTarget.parents('.vod_featured').length >= 0) objTarget.parents('.vod_featured').find('.vod_disable .vod_shader div').remove();
					else objTarget.parent().find('.vod_disable .vod_shader div').remove();

                    if(objTarget.hasClass('vod_count')){
                        var videosLeft = data.totalResults - data.entryCount;
                        var target = objTarget.parent().find('h2').html();
                        var videoCount = '<a href="#" class="vod_videocount" onclick="vod.menu.navigateTo(event, vod.filter.findInMenu(\''+target+'\'));">'+videosLeft+' more videos</a>';
                        objTarget.parent().find('.h2').append(videoCount);
                    }


					vod.toolTip.init();
					vod.switchView.init();
					vod.animation.counterAdd();
					objTarget.animate({opacity:[1, 'swing']}, 200,'linear', function(){
						vod.animation.counterRemove();
						if(vod.param.request==0 && typeof showMore == 'undefined'){
							vod.ds.playlist.get();
							vod.playlist.sync($vod('body'));
						}
						vod.animation.clickEnable(objTarget);

						if(showMore){
							vod.animation.clickEnable(objTarget.parent().parent());
							vod.animation.counterRemove();
						}

					});
				}
			}
			// check if cached
			if(vod.cache.feed[urlFeed]){
				writer(vod.cache.feed[urlFeed], imageSize);
			}else{
				vod.ds.counterAdd();
				$vod.ajax({
					url : urlFeed,
					dataType : 'json',
					success: function(data){
						vod.ds.counterRemove();
						vod.cache.feed[urlFeed]=data;
						writer(data, imageSize);
					},
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									vod.cache.feed[urlFeed]=data;
									writer(data, imageSize);
								}
							}
							xmlHttpReq.send();
						}else{
             				vod.ds.counterRemove();
							error();
						}
					},
					statusCode:{
						400 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});
			}

		},
		widgetShowMore:function(e){
			e.preventDefault();
			var objTarget = $vod(this).parent().parent().children('.vod_widget');
			var urlFeed = $vod(this).attr('url');

			vod.animation.clickDisable(objTarget.parent().parent());
			vod.animation.counterAdd();
			urlFeed = urlFeed.substr(0, urlFeed.indexOf('&range'));
			urlFeed = urlFeed + "&range=" + $vod(this).attr('rel');

			vod.ds.widget(objTarget, vod.template.grid, urlFeed, true);
		},
		theFilter:function(objTarget, htmlRepeater, urlFeed, limit, widgetDiv){

			var markup = '';
			var imageSize = vod.ds.detectSize(objTarget);
			//var imageSize = vod.ds.detectFilterImageSize(objTarget);

			//add number of items to get to urlFeed.
			if(limit){
				urlFeed += '&$take=' + limit;
			}

			// functions
			var cacheVideo=function(data){
					vod.ds.counterRemove();
					if(data.entries){
						$vod.each(data.entries , function(inx, val){
							if(!val.responseCode){
								vod.cache.video['id_'+vod.ds.filterVideoId(val.id)]=val;
							}
						});
					}else{
						if(!data.responseCode){
							vod.cache.video['id_'+vod.ds.filterVideoId(data.id)]=data;
						}
					}
					if(vod.param.request==0){
						vod.playlist.sync($vod('body'));
					}
				}


			var writer = function(data, imageSize){
				if(typeof data.Items == 'undefined' || data.Items.length == 0)
				{
					objTarget.html('&nbsp');
					vod.ds.counterRemove();
					vod.animation.clickEnable(objTarget);
					return;
				}
				var ids='';
				if (data.responseid) {
					var responseId = data.responseid;
				}
				$vod.each(data.Items , function(inx, val){

					var videoId = vod.ds.filterVideoId(val.id);

					// save to video cache
					vod.cache.video['id_'+videoId]=vod.ds.processMediaObj(val,'');
					vod.cache.theFilter['id_'+videoId]=val;

					//checks if the current page already has the videoId existing and remove the video if it does.
					val.responseId = responseId;
					var value = vod.template.grid(val, imageSize, '', '', 'theFilter');
					if((typeof currVideoId != 'undefined') && (videoId == currVideoId)){
						value = '';
					}

					if(ids==''){
						ids=videoId;
					}else{
						ids=ids+','+videoId;
					}
					if(value!=''){
						markup += value;
					}
					else {
						return '';
					}
				});
				if(markup!=''){
					objTarget.html(markup);
					if(vod.param.request==0){
						vod.ds.playlist.get();
						vod.playlist.sync($vod('body'));
					}
					objTarget.parent().find('.vod_disable').find('.vod_shader div').remove();
					vod.toolTip.init();
					vod.switchView.init();
					vod.animation.counterAdd();
					objTarget.animate({opacity:[1, 'swing']}, 200,'linear', function(){
						vod.animation.counterRemove();
						vod.animation.clickEnable(objTarget);
					});
				}
				if(vod.param.request==0){
					vod.playlist.sync($vod('body'));
				}

				if(ids!=''){
					var publicFeedId = (mpxFeedId == 'dYtmxB') ? 'search' : 'sbs-search';
					var urlFeed='http://feed.theplatform.com/f/'+mpxFeedId+'/'+publicFeedId+'/'+ids+'?form=json';
					vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						dataType : 'json',
						success: cacheVideo,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										//vod.cache.feed[urlFeed]=data;
										cacheVideo(data);
									}
									if(vod.param.request==0){
										vod.playlist.sync($vod('body'));
									}
									removeExpire();
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							403 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
			};

			// check if cached
			if(vod.cache.feed[urlFeed]){
				writer(vod.cache.feed[urlFeed], imageSize);
			}else{
				vod.ds.counterAdd();
				$vod.ajax({
					url : urlFeed,
					dataType : 'jsonp',
					jsonp: 'jsonp',
					success: function(data){
						vod.ds.counterRemove();
						//console.log(JSON.stringify(data));
						if(data.Items.length != 0){
							vod.cache.feed[urlFeed]=data;
							writer(data, imageSize);
						}else{
							$vod(widgetDiv).hide();
						}
					},
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									vod.cache.feed[urlFeed]=data;
									writer(data, imageSize);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					timeout: 15000,
					statusCode:{
						400 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});
			}
		},
		processMediaObj:function(mediaObj, type){
			var media = {};

			//For theFilter feed data
			if(type == 'theFilter'){
				media['id'] = mediaObj.id;
				media['title'] = mediaObj.title;
				media['description'] = mediaObj.metadata.item['description'];
				media['content'] = (typeof mediaObj.metadata != 'undefined') ? true : false;
				media['classification'] = vod.template.filterClassification(mediaObj);
				media['programName'] = (typeof mediaObj.metadata.item['pl1:programName'] != 'undefined') ? mediaObj.metadata.item['pl1:programName'][0].value : '';
				media['pilatDealCode'] = (typeof mediaObj.metadata.item['pl1:pilatDealcode'] != 'undefined') ? mediaObj.metadata.item['pl1:pilatDealcode'][0].value : '';
				media['pilatId'] = (typeof mediaObj.metadata.item['pl1:pilatId'] != 'undefined') ? mediaObj.metadata.item['pl1:pilatId'][0].value : '';
				media['episodeNumber'] = (typeof mediaObj.metadata.item['pl1:episodeNumber'] != 'undefined') ? mediaObj.metadata.item['pl1:episodeNumber'][0].value : 0;
				media['duration'] = (typeof mediaObj.metadata.item['media:group'][0]['media:content'][0].duration != 'undefined') ? mediaObj.metadata.item['media:group'][0]['media:content'][0].duration : '';

				var expirationDate = (typeof mediaObj.metadata.item['dcterms:valid'] != 'undefined') ? mediaObj.metadata.item['dcterms:valid'][0].value : '';
				expirationDate = (expirationDate != '') ? expirationDate.substr(31, 20) : '';
				expirationDate = new Date(expirationDate);
				var expirationUnixTime = expirationDate.getTime();

				media['expirationDate'] = vod.filter.text.expiryString(vod.param.server.time*1000, expirationUnixTime);
				media['classification'] = vod.template.filterClassification(mediaObj);
				media['defaultThumbnailUrl'] = mediaObj.metadata.item['plmedia:defaultThumbnailUrl'][0].value;
				media['pubDate'] = (typeof mediaObj.metadata.item.pubDate != 'undefined') ? mediaObj.metadata.item.pubDate : '';
				media['noRemain'] = ((media['expirationDate']) == '&nbsp;') ? 'empty' : '';
				media['useType'] = ((typeof mediaObj.metadata.item['pl1:useType'] != 'undefined') && (typeof mediaObj.metadata.item['pl1:useType'][0]['value'] != 'undefined')) ? mediaObj.metadata.item['pl1:useType'][0]['value'] : 'None';
				media['countryOfOrigin'] = '';
				//inSectionPromos.
				media['inSectionPromos'] = false;
				media['responseId'] = (typeof mediaObj.responseId != 'undefined') ? mediaObj.responseId : '';
				if(typeof mediaObj.metadata.item['media:category']!= 'undefined'){
					for(var i = 0; i < mediaObj.metadata.item['media:category'].length; i++){
						if(mediaObj.metadata.item['media:category'][i].value){
							if(mediaObj.metadata.item['media:category'][i].value == "Section/Promos"){
								media['inSectionPromos'] = true;
							}
						}
					}
					//media['inSectionPromos'] =  false;
				}

				//filterCatgory.
				try{
					media['filterCategory'] = '';
					$vod(mediaObj.metadata.item['media:category']).each( function(inx, val) {
						if(val.scheme == 'Genre'){
							var categoryClass = 'vod_category';
							var pC = val.value;
							if (pC == 'Factual') {
								var pC = 'Documentary';
							}
							if (pC == 'Short Film') {
								categoryClass += ' vod_sub_category';
							}
							if (pC) {
								// Episode name
								if (pC.length > vod.param.charLimit.gridLimit) {
									media['filterCategory'] = '<span class="' + categoryClass + '">' + vod.filter.text.cleanStringExtract(pC, vod.param.charLimit.gridLimit) + '</span>';
								}
								else {
									media['filterCategory'] = '<span class="' + categoryClass + '">' + pC + '</span>';
								}
							}
						}
					});
				}catch(e){}

			//For MPX feed data.
			}else{
				media['id'] = vod.ds.filterVideoId(mediaObj.id);
				media['title'] = mediaObj.title;
				media['description'] = mediaObj.description;
				media['content'] = (typeof mediaObj.media$content != 'undefined') ? true : false;
				media['programName'] = mediaObj['pl1$programName'];
				media['pilatDealCode'] = (typeof mediaObj.pl1$pilatDealcode != 'undefined') ? mediaObj.pl1$pilatDealcode : '';
				media['pilatId'] = (typeof mediaObj.pl1$pilatId != 'undefined') ? mediaObj.pl1$pilatId : '';
				media['useType'] = (typeof mediaObj.pl1$useType != 'undefined') ? mediaObj.pl1$useType : 'None';
				media['episodeNumber'] = mediaObj.pl1$episodeNumber;
				media['duration'] = (!mediaObj.media$content) ? false : mediaObj.media$content[0].plfile$duration;
				media['expirationDate'] = mediaObj.media$expirationDate;
				media['expirationDate'] = vod.filter.text.expiryString(vod.param.server.time*1000, media['expirationDate']);
				media['classification'] = vod.template.classification(mediaObj);
				media['defaultThumbnailUrl'] = mediaObj.plmedia$defaultThumbnailUrl;
				media['pubDate'] = mediaObj.pubDate;
				media['noRemain'] = ((media['expirationDate']) == '&nbsp;') ? 'empty' : '';
				media['countryOfOrigin'] = (typeof mediaObj.pl1$countryOfOrigin != 'undefined' && mediaObj.pl1$countryOfOrigin != '' && mediaObj.pl1$countryOfOrigin != 'Australia') ? '<span class="vod_country">' + mediaObj.pl1$countryOfOrigin + '</span>': '';

				//inSectionPromos.
				media['inSectionPromos'] = false;
				media['responseId'] = '';
				if(mediaObj.media$categories){
					for(var i = 0; i < mediaObj.media$categories.length; i++){
						if(mediaObj.media$categories[i].media$name){
							if(mediaObj.media$categories[i].media$name == "Section/Promos"){
								media['inSectionPromos'] = true;
							}
						}
					}
					//media['inSectionPromos'] =  false;
				}

				//filterCatgory.
				try{
					media['filterCategory'] = '';
					$vod(mediaObj['media$categories']).each( function(inx, val) {
						if(val.media$scheme == 'Genre'){
							var categoryClass = 'vod_category';
							var pC = val.media$name;
							if (pC == 'Factual') {
								var pC = 'Documentary';
							}
							if (pC == 'Short Film') {
								categoryClass += ' vod_sub_category';
							}
							if (pC) {
								// Episode name
								if (pC.length > vod.param.charLimit.gridLimit) {
									media['filterCategory'] = '<span class="' + categoryClass + '">' + vod.filter.text.cleanStringExtract(pC, vod.param.charLimit.gridLimit) + '</span>';
								}
								else {
									media['filterCategory'] = '<span class="' + categoryClass + '">' + pC + '</span>';
								}
							}
						}
					});
				}catch(e){}
			}

            // Clean up titles for front end, and create media object fields for episode title, season, and episode number
            var e = media.title.match(/ Ep ?([0-9]+)/),
                s = media.title.match(/ S ?([0-9]+)/);

            if((s != null) && (s.length == 2)){
                media.title = media.title.replace(s[0], '');
                media.seasonNumber = s[1];
            }

            if((e != null) && (e.length == 2)){
                media.title = media.title.replace(e[0], '');
                media.episodeNumber = e[1];
            }

            var episodeNameTest = media.title.indexOf(' - ');
            if(episodeNameTest != -1){
                media.episodeName = media.title.substr(episodeNameTest+3);
            }

			return media;
		},
		playlist:{
			add:function(objID,callingElement, marquee){
				var responder=function(data, marquee){
					vod.ds.counterRemove();
					// add to cache if success
					vod.cache.playlist['id_'+objID]={};
					vod.cache.playlist['id_'+objID]['id']=objID;
					if(vod.param.request == 0){
						vod.ds.playlist.get();
						vod.playlist.sync($vod('body'));
					}
					if (subscriptionRequested && data.add.response) {
						vod.ds.playlist.subscription.get();
					}
					if(typeof marquee != 'undefined'){
						callingElement.addClass('added');
					}
				}
				// quick check id is not empty
				if(objID){
					// Default type is video
					var type = 'video', dealcode = '', videoid = '&ids={"ids":["'+objID+'"]}', pilatid = '';
					if(callingElement.hasClass('vod_playlist_trailer')) {
						type = 'trailer';
						pilatid = (typeof vod.cache.video['id_'+objID].pl1$pilatId != 'undefined') ? '&pilatid=' + vod.cache.video['id_'+objID].pl1$pilatId : '';
					} else if(callingElement.hasClass('vod_playlist_subscription')) {
						type = 'subscription';
						videoid = '&id='+objID;
						if(vod.cache.video['id_'+objID].pl1$pilatDealcode){
							dealcode = '&dealcode='+vod.cache.video['id_'+objID].pl1$pilatDealcode;
						} else{
							dealcode='&dealcode='+vod.cache.video['id_'+objID].metadata.item['pl1:pilatDealcode']['0'].value;
						}
					}


					vod.ds.counterAdd();
					var expiration_timestamp = new Date();
					expiration_timestamp=expiration_timestamp.setFullYear(expiration_timestamp.getFullYear()+20);
					if(vod.cache.video['id_'+objID].media$expirationDate>0){
						expiration_timestamp=vod.cache.video['id_'+objID].media$expirationDate;
					}
					var urlFeed = '/api/video_playlist/add/';
					var subscriptionRequested = false;
					if (type == 'subscription') {
						urlFeed = '/api/video_subscription/add/';
						subscriptionRequested = true;
					}


					$vod.ajax({
						url : urlFeed,
						dataType : 'json',
						data: 'type='+type+videoid+'&expiration={"timestamp":["'+expiration_timestamp+'"]}'+dealcode+pilatid,
						type: 'POST',
						success: responder,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										vod.cache.feed[urlFeed]=data;
										responder(data);
									}
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							404:function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500:function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
			},
			remove:function(objID){
				// quick check id is not empty
				if(objID){
					vod.ds.counterAdd();
					$vod.ajax({
						url : '/api/video_playlist/remove/',
						dataType : 'json',
						data: 'type=video&ids={"ids":["'+objID+'"]}',
						type: 'POST',
						success: function(data){
							vod.ds.counterRemove();
							//delete vod.cache.video['id_'+objID];
							if(vod.param.request==0){
								vod.playlist.sync($vod('body'));
							}
						},
						statusCode:{
							404:function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500:function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
				return false;
			},
			removeExt:function(objID,type){
					var urlFeed='/api/video_playlist/remove/';
					if(type=='subscription'){
						objID='&seriesID='+objID;
						urlFeed='/api/video_subscription/remove/';
					}else{
						'&ids={"ids":["'+objID+'"]}'
					}

				// quick check id is not empty
				if(objID){
					vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						dataType : 'json',
						data: 'type='+type+objID,
						type: 'POST',
						success: function(data){
							vod.ds.counterRemove();
							if(vod.param.request==0){
								vod.playlist.sync($vod('body'));
							}
						},
						statusCode:{
							404:function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500:function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
				return false;
			},
			update:function(objID,objOrder){
				// quick check id is not empty
				if(objID){
					vod.ds.counterAdd();
					$vod.ajax({
						url : '/api/video_playlist/update/',
						dataType : 'json',
						data: 'type=video&id='+objID+'&order='+objOrder,
						type: 'POST',
						success: function(data){
							vod.ds.counterRemove();
							// update cache.playlist
							vod.cache.temp=vod.cache.playlist;
							vod.cache.playlist={};
							$vod('.vod_playlist .vod_sortable .vod_playlist_item').each(function(index){
								vod.cache.playlist['id_'+$vod(this).attr('videoid')]=vod.cache.temp['id_'+$vod(this).attr('videoid')];
							});
							delete vod.cache.temp;
						},
						statusCode:{
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
				return false;
			},
			get:function(){
				vod.ds.playlist.notification.get();

				var removeExpire=function(){
					$vod.each(vod.cache.playlist , function(inx, val){
						if(vod.cache.video['id_'+val.videoID]){
							if(vod.cache.video['id_'+val.videoID].media$expirationDate){
								if(vod.cache.video['id_'+val.videoID].media$expirationDate<vod.param.server.time-86400*7){
									delete vod.cache.playlist['id_'+val.videoID];
									vod.ds.playlist.remove(val.videoID);
								}
							}
						}
					});
				}
				var getVideoData=function(ids){

						// add current video page
						if($vod('.vod_program_header .vod_playlist_item').size()>0){
							if(!vod.cache.video['id_'+$vod('.vod_program_header .vod_playlist_item').attr('videoid')]){
								if(ids==''){
									ids+=$vod('.vod_program_header .vod_playlist_item').attr('videoid');
								}else{
									ids+=","+$vod('.vod_program_header .vod_playlist_item').attr('videoid');
								}
							}
						}
						if(ids!=''){
							var publicFeedId = (mpxFeedId == 'dYtmxB') ? 'search' : 'sbs-search';
							var urlFeed='http://feed.theplatform.com/f/'+mpxFeedId+'/'+publicFeedId+'/'+ids+'?form=json';
							vod.ds.counterAdd();

							$vod.ajax({
								url : urlFeed,
								dataType : 'json',
								success: cacheVideo,
								error: function(){
									vod.ds.counterRemove();
									//TODO solve cross site permissions using proxy
									/*
									if (window.ActiveXObject) {
										var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
										xmlHttpReq.open('POST', urlFeed, true);
										xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
										xmlHttpReq.onreadystatechange = function() {
											if (xmlHttpReq.readyState == 4) {
												vod.ds.counterRemove();
												var data = $vod.parseJSON(xmlHttpReq.responseText);
												//vod.cache.feed[urlFeed]=data;
												cacheVideo(data);
											}
											if(vod.param.request==0){
												vod.playlist.sync($vod('body'));
											}
											removeExpire();
										}
										xmlHttpReq.send();
									} else vod.ds.counterRemove();
									*/
								},
								statusCode:{
									403 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
									},
									404 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
									},
									500 : function(){
										vod.ds.counterRemove();
										// show nice error
										vod.error.genericRefresher();
									}
								}
							});
						}else{
							if(vod.param.request==0){
								vod.playlist.sync($vod('body'));
							}
						}
				}
				var cacheVideo=function(data){
					removeExpire();
					vod.ds.counterRemove();
					if(data.entries){
						$vod.each(data.entries , function(inx, val){
							if(!val.responseCode){
								vod.cache.video['id_'+vod.ds.filterVideoId(val.id)]=val;
							}
						});
					}else{
						if(!data.responseCode){
							vod.cache.video['id_'+vod.ds.filterVideoId(data.id)]=data;
						}
					}
					if(vod.param.request==0){
						vod.playlist.sync($vod('body'));
					}
				}
				var progress=function(data){
					vod.ds.counterRemove();
					if(data.get.response){
						$vod.each(data.get.response , function(inx, val){
							vod.cache.progress['id_'+inx]=val;
						});
					}
					if(vod.param.request==0){
						vod.playlist.sync($vod('body'));
					}
				}
				var responder=function(data){
					vod.ds.counterRemove();
					var ids="";

					if(!vod.filter.object.isEmpty(data.get.response)){
						vod.cache.playlist={};
						$vod.each(data.get.response.playlist , function(inx, val){


							// already in cache
							if(vod.filter.object.isEmpty(vod.cache.video['id_'+val.videoID])){
								if(ids==''){
									ids+=val.videoID;
								}else{
									ids+=","+val.videoID;
								}
							}

							vod.cache.playlist['id_'+val.videoID]=val;
						});
					}
					getVideoData(ids);
					removeExpire();
				}
				var responderHistory = function(data){
					vod.ds.counterRemove();
					if(data.get.response){
						$vod.each(data.get.response , function(inx, val){
							vod.cache.history['id_'+inx] = val;
						});
					}
					if(vod.param.request == 0){
						vod.playlist.sync($vod('body'));
					}
				}

				// get progress
				vod.ds.counterAdd();
				var urlFeed='/api/video_progress/get/';
				$vod.ajax({
					url : urlFeed,
					data: 'type=progress',
					type: 'GET',
					dataType : 'json',
					success: progress,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									vod.cache.feed[urlFeed]=data;
									progress(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});

				// get playlist
				vod.ds.counterAdd();
				urlFeed='/api/video_playlist/get/';
				$vod.ajax({
					url : urlFeed,
					data: 'type=playlist',
					type: 'GET',
					dataType : 'json',
					success: responder,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									vod.cache.feed[urlFeed]=data;
									responder(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});

				// get history data
				vod.ds.counterAdd();
				urlFeed='/api/video_history/get/';
				$vod.ajax({
					url : urlFeed,
					data: 'type=history',
					type: 'GET',
					dataType : 'json',
					success: responderHistory,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									vod.cache.feed[urlFeed]=data;
									responderHistory(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});

			},
			tab:function(target){
				var cacheVideo=function(data){
					vod.ds.counterRemove();
					if(data.entries){
						$vod.each(data.entries , function(inx, val){
							if(!val.responseCode){
								vod.cache.video['id_'+vod.ds.filterVideoId(val.id)]=val;
							}
						});
					}else{
						if(!data.responseCode){
							vod.cache.video['id_'+vod.ds.filterVideoId(data.id)]=data;
						}
					}
					if(vod.param.request==0){
						vod.playlist.sync($vod('body'));
					}
				}
				var responder=function(data){
					vod.ds.counterRemove();
					var ids="";
					vod.cache[$vod('.vod_playlist .aside_nav .vod_selected a').attr('rel')]={};
					if(!vod.filter.object.isEmpty(data.get.response)){
						if($vod('.vod_playlist .aside_nav .vod_selected a').attr('rel')=='history'){
							if(data.get.response.length>0){
								vod.cache['history']={};
								for(i=0;i<data.get.response.length;i++){
									vod.cache['history']['id_'+i]=data.get.response[i];
								}
							}
						}else{
							$vod.each(data.get.response , function(inx, val){
								// already in cache
								if($vod('.vod_playlist .aside_nav .vod_selected a').attr('rel')=='subscription'){
										vod.cache[$vod('.vod_playlist .aside_nav .vod_selected a').attr('rel')]['id_'+val.seriesID]=val;
								}else{
									if(vod.filter.object.isEmpty(vod.cache.video['id_'+val.videoID])){
										if(ids==''){
											ids+=val.videoID;
										}else{
											ids+=","+val.videoID;
										}
									}
									vod.cache[$vod('.vod_playlist .aside_nav .vod_selected a').attr('rel')]['id_'+val.videoID]=val;
								}
							});
						}
						if(ids!=''){
							var publicFeedId = (mpxFeedId == 'dYtmxB') ? 'search' : 'sbs-search';
							var urlFeed='http://feed.theplatform.com/f/'+mpxFeedId+'/'+publicFeedId+'/'+ids+'?form=json';
							vod.ds.counterAdd();
							$vod.ajax({
								url : urlFeed,
								dataType : 'json',
								success: cacheVideo,
								error: function(){
									if (window.ActiveXObject) {
										var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
										xmlHttpReq.open('POST', urlFeed, true);
										xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
										xmlHttpReq.onreadystatechange = function() {
											if (xmlHttpReq.readyState == 4) {
												vod.ds.counterRemove();
												var data = $vod.parseJSON(xmlHttpReq.responseText);
												vod.cache.feed[urlFeed]=data;
												cacheVideo(data);
											}
											if(vod.param.request==0){
												vod.playlist.sync($vod('body'));
											}
										}
										xmlHttpReq.send();
									} else vod.ds.counterRemove();
								},
								statusCode:{
									403 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
									},
									404 : function(){
										vod.ds.counterRemove();
										// show nice error message
										vod.error.genericRefresher();
									},
									500 : function(){
										vod.ds.counterRemove();
										// show nice error
										vod.error.genericRefresher();
									}
								}
							});
						}else{
							if(vod.param.request==0){
								vod.playlist.sync($vod('body'));
							}
						}
					}else{

					}
				}

				var urlFeed='/api/video_playlist/get/';
				if(target=='subscription'){
					urlFeed='/api/video_subscription/get/';
				}else if(target=='history'){
					urlFeed='/api/video_history/get/';
				}else if(target=='preferences'){
					urlFeed='/api/video_preferences/get/';
				}


				vod.ds.counterAdd();

				$vod.ajax({
					url : urlFeed,
					data: 'type='+target,
					type: 'GET',
					dataType : 'json',
					success: responder,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									//vod.cache.feed[urlFeed]=data;
									responder(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});

			},
			dealcode:function(objTarget){
				var responder=function(data){
					vod.ds.counterRemove();
					if(data.totalResults){
						$vod('.vod_playlist_item_subscription[videoid="'+objTarget.seriesID+'"] .vod_playlist_col_episode').html(data.totalResults);
					}
				}

				var target="";
				for(i=0;i<objTarget.pilatDealcodes.length;i++){
					if(target==""){
						target=objTarget.pilatDealcodes[i];
					}else{
						target=target+'|'+objTarget.pilatDealcodes[i];
					}
				}


				var urlFeed='http://feed.theplatform.com/f/'+mpxFeedId+'/search?byCustomValue={pilatDealcode}{'+target+'}&count=true&entries=false&form=json';


				vod.ds.counterAdd();

				$vod.ajax({
					url : urlFeed,
					data: '',
					type: 'GET',
					dataType : 'json',
					success: responder,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4) {
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									responder(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});

			},
			comingSoon:function(urlFeed){
				var responder=function(data){
					vod.ds.counterRemove();
					return data;
				}

				vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						data: '',
						type: 'GET',
						dataType : 'json',
						success: responder,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										responder(data);
									}
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							304 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});

			},
			notification:{
				set:function(){
					var responder=function(data){
						vod.ds.counterRemove();
						return data;
					}
					var urlFeed='/api/video_preferences/save?subscription_notify='+vod.param.server.notification.subscription+'&expire_notify='+vod.param.server.notification.expiring;
					vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						data: '',
						type: 'GET',
						dataType : 'json',
						success: responder,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										responder(data);
									}
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							304 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				},
				get:function(){
					var responder=function(data){
						vod.ds.counterRemove();
						$vod.each(data.get.response , function(inx, val){
							if(inx=='subscription_notify'){
								vod.param.server.notification.subscription=val;
							}else if(inx=='expire_notify'){
								vod.param.server.notification.expiring=val;
							}
							vod.playlist.notification.get();
						});
					}
					var urlFeed='/api/video_preferences/get/';
					vod.ds.counterAdd();
					$vod.ajax({
						url : urlFeed,
						data: '',
						type: 'GET',
						dataType : 'json',
						success: responder,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4){
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										responder(data);
									}
								}
								xmlHttpReq.send();
							} else {
								vod.ds.counterRemove();
							}
						},
						statusCode:{
							304 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
			},
			subscription:{
				get:function(){
					var responderSubscription = function(data){
						vod.ds.counterRemove();
						if(data.get.response){
							$vod.each(data.get.response, function(inx, val){
								vod.cache.subscription['id_'+inx] = val;
							});
						}
						if(vod.param.request == 0){
							vod.playlist.sync($vod('body'));
						}
					}

					vod.ds.counterAdd();
					urlFeed='/api/video_subscription/get/';
					$vod.ajax({
						url : urlFeed,
						data: 'type=subscription',
						type: 'GET',
						dataType : 'json',
						success: responderSubscription,
						error: function(){
							if (window.ActiveXObject) {
								var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								xmlHttpReq.open('POST', urlFeed, true);
								xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
								xmlHttpReq.onreadystatechange = function() {
									if (xmlHttpReq.readyState == 4) {
										vod.ds.counterRemove();
										var data = $vod.parseJSON(xmlHttpReq.responseText);
										vod.cache.feed[urlFeed]=data;
										responderSubscription(data);
									}
								}
								xmlHttpReq.send();
							} else vod.ds.counterRemove();
						},
						statusCode:{
							304 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							404 : function(){
								vod.ds.counterRemove();
								// show nice error message
								vod.error.genericRefresher();
							},
							500 : function(){
								vod.ds.counterRemove();
								// show nice error
								vod.error.genericRefresher();
							}
						}
					});
				}
			},
			historyClear:function(){
				var responder = function(){
					vod.ds.counterRemove();
				}
				$vod.ajax({
					url : '/api/video_history/remove/',
					data: '',
					type: 'GET',
					dataType : 'json',
					success: responder,
					error: function(){
						if (window.ActiveXObject) {
							var xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							xmlHttpReq.open('POST', urlFeed, true);
							xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
							xmlHttpReq.onreadystatechange = function() {
								if (xmlHttpReq.readyState == 4){
									vod.ds.counterRemove();
									var data = $vod.parseJSON(xmlHttpReq.responseText);
									responder(data);
								}
							}
							xmlHttpReq.send();
						} else vod.ds.counterRemove();
					},
					statusCode:{
						304 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						404 : function(){
							vod.ds.counterRemove();
							// show nice error message
							vod.error.genericRefresher();
						},
						500 : function(){
							vod.ds.counterRemove();
							// show nice error
							vod.error.genericRefresher();
						}
					}
				});
			}
		},
		/**
		 * handles left menu writes
		 */
		menu:function(menu, objTarget){

			var target = $vod(objTarget),
                section = $vod('.the_grid_region .aside_nav .vod_btn_back').attr('rel'),
                selected = ' class="vod_selected vod_separator"',
                selectbool = true;

			//featured
			if(parseInt(menu.sf) && menu.furl){
                selected = (selectbool)?selected:'';
                selectbool = false;
				target.append('<li'+selected+'><a href="#'+section+'" rel="'+section+'" param="" class="vod-featured vod-sort">Featured</a></li>');
			}

            //Latest -- always show!
            selected = (selectbool)?selected:'';
            selectbool = false;
            target.append('<li'+selected+'><a href="#'+section+'" rel="'+section+'" class="vod-latest vod-sort">Latest</a></li>');

            //popular -- metrics.viewCount.last30Days
			if(parseInt(menu.sp)){
                selected = (selectbool)?selected:'';
                selectbool = false;
				target.append('<li'+selected+'><a href="#'+section+'" rel="'+section+'" class="vod-most-popular vod-sort">Most Popular</a></li>');
			}

            // most discussed -- ignore for now
			if(parseInt(menu.sd)){
				//target.append('<li><a href="#" rel="" class="vod-most-discussed vod-sort">Most Discussed</a></li>');
			}
			var first = true;
			if(typeof menu['children'] != 'undefined'){
				$vod.each(menu['children'], function(index, value){
					var hasChild='', separator = (first) ? (selectbool) ? ' class="vod_separator vod_selected"':' class="vod_separator"':'';
					first = false;
					if(value['children']){
						hasChild=' class="vod_drilldown"';
					}
					if(parseInt(value.clickable)) target.append('<li'+separator+'><a'+hasChild+' rel="'+$vod('.the_grid_region .aside_nav .vod_btn_back').attr('rel')+'.children.'+index+'" href="#'+$vod('.the_grid_region .aside_nav .vod_btn_back').attr('rel')+'.children.'+index+'">'+value.name+'</a></li>');
					else target.append('<li class="vod_title"><span>'+value.name+'</span></li>');
				});
			}
		},
		/**
		 * Generate url for query
		 * @param element
		 * @param objMenu
		 * @param url
		 * @return queryUrl
		 */
		query:function(element, objMenu, url, objTarget){
			var query = '&count=true';
			var imageSize = vod.ds.detectSize(objTarget);

			// Range --  show more results
			if($vod('.vod-show-more').hasClass('vod-show-more-active')){
				vod.param.range = $vod('.vod-show-more').attr('rel');
				query += '&range=' + vod.param.range;
			} else if(url.indexOf('search?') > -1) {
				vod.param.range = '1-24';
				query += '&range=1-24';
			} else {
				vod.param.range = '1-20';
				query += '&range=1-20';
			}

			query += "&defaultThumbnailAssetType="+vod.param.settings[imageSize].defaultThumbnailAssetType;

			// Day navigation
			if (parseInt(objMenu.df)){
				if($vod('#the_grid .vod_day_navigation').length <= 0){            // create day navigator if it doesn't exist
					$vod('#the_grid .vod_viewport .vod_filters').append(vod.template.dayNavigation());
					$vod('#the_grid .vod_filters .vod_day_navigation').delegate('a','click',vod.menu.viewDay);
				}
				$vod('#the_grid .vod_day_navigation').show();
				if(vod.param.filterDay.length == 0) vod.param.filterDay = $vod('#the_grid .vod_day_navigation .vod_selected').attr('rel');
				query += "&byPubDate=" + vod.param.filterDay;
			}else{
				$vod('#the_grid .vod_day_navigation').hide();
			}

			// Sorting
			if($vod(element).hasClass('vod-sort')){
				if($vod(element).hasClass('vod-most-popular')) {
					query += '&sort=metrics.viewCount.last7Days|desc';
					var now = new Date(),
						pastFortnight = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()+1, 0,0,0,0),
						format = "Y-m-dTH:i:s",
						time = "Z";

					pastFortnight = pastFortnight.setDate(pastFortnight.getDate()-14);
					var period = vod.filter.text.formatDate(format, pastFortnight) + time + '~';

					query += '&byPubDate='+period;
				}
				else if($vod(element).hasClass('vod-latest')) query += ''; // latest is default
				else if($vod(element).hasClass('vod-featured')) return objMenu.furl; // return the featured url
			}
			return url+query;
		}
	},
	template:{
		subscription:function(mediaObj){
			var result = 	'<li videoid="'+mediaObj.seriesID+'" class="vod_playlist_item_subscription">'
				+							'<div class="vod_padder">'
				+								'<div class="vod_gutter">'
				+									'<div>'
				+										'<div class="vod_tt_overlay">'
				+											'<a title="remove" href="javascript:void(0);" class="vod_playlist_remove">remove</a>'
				+										'</div>'
				+									'</div>'
				+									'<div class="info">'
				+										'<span class="vod_playlist_col_title">'+mediaObj.title+'</span>'
				+										'<span class="vod_playlist_col_episode"></span>'
				+										'<span class="vod_playlist_col_available">'+mediaObj.nextEpisodeAvailable+'</span>'
				+									'</div>'
				+								'</div>'
				+							'</div>'
				+						'</li>';
			return result;
		},

		grid:function(mediaObj, imageSize, imageOverride, urlOverride, type, section){
			//console.log('grid', 'mediaObj', mediaObj, 'imageSize', imageSize, 'imageOverride', imageOverride, 'urlOverride', urlOverride, 'type', type, 'section', section);

			//process media object from different type of feeds.

			var media = vod.ds.processMediaObj(mediaObj, type);
			//console.log('media', media);

			// Character Filter
			if (!media['id'] || !media['title'] || !media['content']) {
				return '';
			}

			imageOverride = imageOverride || media['defaultThumbnailUrl'];
			imageSize = imageSize || "medium";

			var videoPage = vod.param.server.videoPage;
			if (section) {
				// insert section name in videoPage URL
				videoPage = vod.param.server.videoPage.replace('video', section + '/video');
			}

			// URL for <a> tags
			if (!urlOverride) {
				urlOverride = videoPage
				            + media['id']
				            + '/' + vod.filter.text.websafe(media['title'])
				            + (typeof(type) != undefined && type != '' ? '?from=' + type : '');
			}

			// Create an onClick tag for recommendations passed in through theFilter
			aOnClick = '';
			if (type == 'theFilter' && media['responseId']) {
				aOnClick = " onClick=\"return vod.handleRecommendationClick('"+media['responseId']+"', '"+media['id']+"');\"";
			}

			// Program name
			var pN = media['programName'];

			if (!pN) {
				var filterProgram = '';
				// Episode name
				if (media['title'].length > vod.param.charLimit.listLimit) {
					var filterTitle = vod.filter.text.cleanStringExtract(media['title'], vod.param.charLimit.listLimit);
				} else {
					var filterTitle = media['title'];
				}
			} else {
				if (pN.length > vod.param.charLimit.gridLimit) {
					var filterProgram = vod.filter.text.cleanStringExtract(pN, vod.param.charLimit.gridLimit);
				} else {
					var filterProgram = pN + ':';
				}
				// Episode name
				if (media['title'].length > vod.param.charLimit.gridLimit) {
					var filterTitle = vod.filter.text.cleanStringExtract(media['title'], vod.param.charLimit.gridLimit);
				} else {
					var filterTitle = media['title'];
				}
			}

			var vod_playlist_popup_option="";
			vod_playlist_popup_option+='<li class="vod_playlist_popup_option vod_playlist_add"><div><a href="javascript:void(0);" title="Add Video to Playlist">Add Video to Playlist</a></div></li>';


			// trailer or program
			// piltaid -> add program when available
			if(media['inSectionPromos'] && media['pilatId'] && imageSize != "leadMarquee" && imageSize != "leadMarqueeSmaller"){
				vod_playlist_popup_option+='<li class="vod_playlist_popup_option vod_playlist_add"><div><a class="vod_playlist_trailer" href="javascript:void(0);" title="Add Program when available">Add Program when available</a></div></li>';
			}
			// has series
			if(media['pilatDealCode'] && (media['episodeNumber'] && media['episodeNumber'] > 0) && imageSize != "leadMarquee" && imageSize != "leadMarqueeSmaller"){
				vod_playlist_popup_option+='<li class="vod_playlist_popup_option vod_playlist_add vod_playlist_subscription"><div><a class="vod_playlist_add vod_playlist_subscription" href="javascript:void(0);" title="Subscribe to Series">Subscribe to Series</a></div></li>';
			}

			if(imageSize == "leadMarquee" || imageSize == "leadMarqueeSmaller"){
				vod_playlist_popup_option+='<li class="vod_playlist_popup_option vod_playlist_add preLoad vod_pl_trailer"><div><a class="vod_playlist_trailer" href="javascript:void(0);" title="Add Program when available">Add Program when available</a></div></li>';
				vod_playlist_popup_option+='<li class="vod_playlist_popup_option vod_playlist_add vod_playlist_subscription preLoad vod_pl_series"><div><a class="vod_playlist_add vod_playlist_subscription" href="javascript:void(0);" title="Subscribe to Series">Subscribe to Series</a></div></li>';
			}

			var useType = ((media['useType'] == 'Promo') || (media['useType'] == 'Sneak Peek') || (media['useType'] == 'Trailer') || (media['useType'] == 'Interview') || (media['useType'] == 'Exclusive') || (media['useType'] == 'Extras') || (media['useType'] == 'Review')) ? '<span class="vod_usetype">[' + media['useType'] + ']</span>' : '';
			/*
			 * Results
			 */
			var result="",
			width = vod.param.settings[imageSize].width,
			height = vod.param.settings[imageSize].height;
			if(!media['id']||!media['title']){return '';}
			var timeVal = '';
			if(media['content']){
				if(vod.filter.text.formatTime(vod.param.timeFormat, media['duration']) == '&nbsp;'){timeVal = 'class="hidden" ';} else{timeVal = '';}
			}

			var rating = '', infosection = '';


			var vodRemain = '';
			var vodRemainClass = '';
			if(media['inSectionPromos'] == true) {
				vodRemain = '<span class="airdate">AIRS ON:</span><span>' + vod.filter.text.formatDate(vod.param.dateFormat, media['pubDate']) + '</span>';
				vodRemainClass = '';
			} else {
				vodRemain = media['expirationDate'];
				vodRemainClass = media['noRemain'];
			};

			var vodVideoTX = '';
			/*
			if (mediaObj && mediaObj.media$availableDate) {
				vodVideoTX = new Date(mediaObj.media$availableDate);
				vodVideoTX = vod.filter.text.formatDate('j F', vodVideoTX);
			}
			*/
			var iosPlayButton = (isIOS) ? '<img src="/vod/sbs/images/icons/play.png" class="vod_play_icon" width="70" height="70" />' : '';
			var isPlaylistObjOnPage = ($vod('.vod_playlist').length > 0);
			var overlayItem = '<div class="vod_tt_overlay"><a '+timeVal+'href="javascript:void(0);" title="'+vod.filter.text.formatTime(vod.param.timeFormat, media['duration'])+'">'+vod.filter.text.formatTime(vod.param.timeFormat, media['duration'])+'</a></div>';
			if (!isPlaylistObjOnPage) {
				overlayItem = '<div class="vod_tt_overlay"><span>'+vod.filter.text.formatTime(vod.param.timeFormat, media['duration'])+'</span></div>';
			}

			result = '<li class="vod_playlist_item" videoid="'+media['id']+'"><div class="vod_padder"><div class="vod_gutter">'
				+	'<div>'
				+ 		'<ul class="tt_list">'
				+ 			'<li class="t_cnr"></li>'
				+ 			'<li class="vod_playlist_popup_title"><p>Add to \'My Videos\'</p></li>'
				+ 			'<li class="vod_playlist_popup_option vod_playlist_full"><div><a href="javascript:void(0);" title="Your playlist is full">Your playlist is full</a></div></li>'
				+ 			'<li class="vod_playlist_popup_option vod_playlist_popup_option_added"><div><a href="javascript:void(0);" title="Added to \'My Videos\'">Added to \'My Videos\'</a></div></li>'
				+ 			vod_playlist_popup_option
				+ 			'<li class="b_cnr"></li>'
				+ 		'</ul>';

			if (isPlaylistObjOnPage) {
				result += overlayItem;
			}
			result += '<a class="vod_show" href="'+urlOverride+'" '+aOnClick+'>'+iosPlayButton+'<img style="display:block;background:#ccc;"width="'+width+'" height="'+height+'" src="'+imageOverride+'" class="vod_clip" />';
			if (!isPlaylistObjOnPage) {
				result += overlayItem;
			}
			result += '</a></div>';

			var episodeDetails = '';
			var isSeason = (!isNaN(media['seasonNumber']) && (media['seasonNumber'] > 0));
			var isEpisode = (!isNaN(media['episodeNumber']) && (media['episodeNumber'] > 0));
			if(isSeason || isEpisode){
				episodeDetails = '<span class=\"vod_episode\">';
				if(isSeason) episodeDetails += '<span class=\"vod_season\"> Season '+media['seasonNumber']+'</span>';
				if(isEpisode) episodeDetails += '<span class=\"vod_season\"> Episode '+media['episodeNumber']+'&nbsp;</span>';
				episodeDetails += '</span>';
			}

			infosection = '<div class="info">'
				+		'<p>'
				+			'<a class="vod_show" href="'+urlOverride+'"'+aOnClick+'><span class=\"vod_program\">'+ filterProgram +'</span>'+filterTitle+'</a>'
				+			'<span class=\"vod_added\">'+vodVideoTX+'</span>'
				+			'<span class=\"vod_remain '+vodRemainClass+ '\">' +vodRemain+'</span>'
				+			'<span class=\"vod_duration\">'+vod.filter.text.formatTime(vod.param.timeFormat, media['duration'])+'</span>'
				+			'<span class="vod_progress"><span style="width:0%"></span></span>'
				+			'<span class=\"vod_description\"><span class="tt_meta">' + episodeDetails + media['countryOfOrigin'] + media['filterCategory'] + useType + media['classification'] + '</span>'+media['description']+'</span>'
				+		'</p>'
				+	'</div>';

			if(imageSize != 'leadMarquee' && imageSize != 'leadMarqueeSmaller') result += infosection;
			result	+= '</div></div></li>';

			return result;
		},
		dayNavigation:function(){
			var markup = '<div class="vod_day_navigation" style="z-index:1000"><ul>',
			today = new Date(),
			format = "Y-m-dS:i:s",
			time = "Z";
			//start from the beginning of the day
			today = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0,0,0,0);
			//get UTC time
			var utcday = new Date(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), today.getUTCHours(), 0,0,0);

            for(var n = 0; n > -7; n--){
                var selected = '';
				var thisDay = new Date();
				thisDay = thisDay.setDate(today.getDate()+n);
				var startUTCDay = new Date(utcday.getFullYear(), utcday.getMonth(), utcday.getDate(), today.getUTCHours(),0,0,0);
				startUTCDay.setDate(utcday.getDate()+n);
				var endUTCDay = new Date(utcday.getFullYear(), utcday.getMonth(), utcday.getDate(), today.getUTCHours(),0,0,0);
				endUTCDay.setDate(utcday.getDate()+n+1);
                var period = vod.filter.text.formatDate(format, startUTCDay) + time + '~' + vod.filter.text.formatDate(format, endUTCDay) + time;
                if(n == 0){
                    selected = 'class="vod_selected"';
                    vod.param.filterDay = period;
                }
                markup += '<li>';
            	markup += 	'<a '+selected+' href="javascript:void(0);" rel="' + period + '">';
            	markup += 		'<span class="day">' + vod.filter.text.formatDate("D", thisDay) + '</span>';
            	markup += 		'<span class="date">' + vod.filter.text.formatDate("j", thisDay) + '</span>';
            	markup += 		'<span class="suffix">' + vod.filter.text.formatDate("S", thisDay) + '</span>';
            	markup += 	'</a>';
            	markup += '</li>';
            }

            markup += '</ul></div>';

            return markup;
		},
        container:function(){
            var result = '<div class="the_grid" id="the_grid">'
                        +   '<div class="the_grid_region">'
                        +      '<div class="aside_nav">'
                        +            '<div class="aside_nav_panels">'
                        +                '<div class="aside_nav_panel">'
                        +                    '<div class="mask"><a class="vod_btn_back" href="#">Back</a></div>'
                        +                    '<h2>Documentary</h2>'
                        +                   '<ul>'
                        +                        '<li><span class="vod_loading">Loading</span></li>'
                        +                    '</ul>'
                        +               '</div>'
                        +            '<div class="clear"></div>'
                        +            '</div>'
                        +       '</div>'
                        +        '<div class="content_list vod_view_grid">'
                        +            '<div class="vod_viewport">'
                        +           '</div>'
                        +        '</div><!-- /content_list -->'
                        +   '</div>'
                        +'</div><!-- /the_grid -->';

            return result;
        },
        carousel:function(mediaObj, imageSize, playing) {

        	if(!mediaObj.id||!mediaObj.title){return '';}
			var image = mediaObj.plmedia$defaultThumbnailUrl;

			var videoIdOrig = mediaObj.id;
			var videoId = vod.ds.filterVideoId(videoIdOrig);

			/*
			 * Results
			 */
			var result = "",
			width = imageSize['width'],
			height = imageSize['height'];

			var videoPageUrl = baseUrl + '/video/';
			if (baseUrl.toLowerCase().indexOf('cyclingcentral') > -1){
				var subSite = window.location.pathname;
				videoPageUrl = subSite.substring(0, subSite.indexOf('video') + 6);
			}

			// write condition to display subsribeToSeries link.
			result = '<li id="' + videoId + '"' + playing + '>'
				+	 '	<div class="item_text">'
				+	 '<a class="vod_show" href="'+ videoPageUrl + videoId + '/'+vod.filter.text.websafe(mediaObj.title)+'"><img style="display:block;background:#ccc;"width="'+width+'" height="'+height+'" src="'+image+'" alt="video" class="vod_clip" /></a>'
				+	 '	</div>'
				+	 '	<div class="clear"></div>'
				+	 '</li>';
			return result;
		}	,
		classificationImage:function(mediaObj){
			var classification = (typeof mediaObj.media$ratings[0] != 'undefined') ? mediaObj.media$ratings[0].rating : false;
			var ratings = (typeof mediaObj.media$ratings[0] != 'undefined') ? mediaObj.media$ratings[0].subRatings : false;
			if(!ratings || !classification) return '';

			// sort array alphabetically
			ratings.sort();

			var ratingString = '';
			for(var i =0; i < ratings.length; i++)
				ratingString += ratings[i];

			var subClassificationsArray = {g: [],
									m: ['al','lsv','n'],
									ma15:['asv','ls'],
									pg: ['lv', 's']};

			var subClassifications = subClassificationsArray[classification] || '';
			var imageFile = '';
			for(var i = 0; i < subClassifications.length; i++)
				if(ratingString.indexOf(subClassifications[i]) > -1)
					imageFile = classification + "_" + subClassifications[i];

			if(!imageFile) return '';

			var markup = '<span class="vod_classification">' +
					'<img src="/vod/sbs/images/icons/classification/'+imageFile+'.png" alt="'+classification+'" />' +
					'</span>';

			return markup;
		},
		classificationString:function(mediaObj){
			var subClassificationsText = {a:"Adult themes and/or dangerous stunts",
											d:"Drug references and/or drug use",
											h:"Horror and supernatural themes",
											l:"Coarse language",
											n:"Nudity",
											s:"Sexual references and/or sex scenes",
											v:"Violence"};

			var classification = (typeof mediaObj.media$ratings[0] != 'undefined') ? mediaObj.media$ratings[0].rating : false;
			var ratings = (typeof mediaObj.media$ratings[0] != 'undefined') ? mediaObj.media$ratings[0].subRatings : false;
			if(!ratings || !classification) return '';

			// sort array alphabetically
			ratings.sort();

			var markup = 'Rated: <span class="vod_classification">'+classification+'</span>';

			for(var i = 0; i < ratings.length; i++)
				markup+='Rated: <span class="vod_rating" title='+subClassificationsText[ratings[i]]+'>'+subClassificationsText[ratings[i]]+'</span>';

			return markup;
		},
		classification:function(mediaObj){
			var classification='', markup='';
			if(mediaObj.media$ratings){
				if(mediaObj.media$ratings.length>0){
					if(classification=mediaObj.media$ratings[0].rating != ''){
						classification=mediaObj.media$ratings[0].rating;
						markup = 'Rated: <span class="vod_classification">'+classification+'</span>';
					}
				}
			}
			return markup;
		},
		filterClassification:function(mediaObj){
			var classification = (typeof mediaObj.metadata.item['media:rating'] != 'undefined') ? mediaObj.metadata.item['media:rating'][0].value : false;
			if(!classification) return '';
			var markup = 'Rated: <span class="vod_classification">'+classification+'</span>';
			return markup;
		}
	},
	param:{
        category:"",
		server:{
			state:false,
			notification:{
				expiring:0,
				subscription:0
			},
			time:0,
			videoPage:'/ondemand/video/'
		},
		url:"",
		filterDay:"",
		animating:0,
		request:0,
		gridSize:20,
        timeFormat:"H:M:S",
        dateFormat:"j M Y",
        range:"1-20",
		currentlyBrowsing:'',
		lastAction:'',
        lastLocation:'',
		leadMarqueeTimeout: 8000,
		leadMarqueeTimeoutArray: [],
		leadMarqueePause: 0,
		charLimit:{
			gridLimit:44,
			gridLongLimit:80,
			listLimit:104
		},
		contentHeight:0,
		settings:{ // default settings   121 x 68
			imageSize: "medium",
			small: {
					width: "125px",
					height: "70px",
					defaultThumbnailAssetType: "Thumbnail"
			},
			medium: {
					width: "138px",
					height: "78px",
					defaultThumbnailAssetType: "Thumbnail"
			},
			mediumGrid: {
					width: "137px",
					height: "77px",
					defaultThumbnailAssetType: "Thumbnail"
			},
			large: {
					width: "189px",
					height: "106px",
					defaultThumbnailAssetType: "Thumbnail"
			},
			leadMarquee: {
					width: "640px",
					height: "360px",
					defaultThumbnailAssetType: "Thumbnail Large"
			},
			leadMarqueeSmaller: {
					width: "627px",
					height: "352px",
					defaultThumbnailAssetType: "Thumbnail Large"
			}
		},
		loginStatus:function(){
			var thisDomain = window.location.hostname;
        	var logstatUrl = 'http://' + thisDomain + '/api/Member/loginstatus/';
        	$vod.ajax({
				url : logstatUrl,
				dataType : 'json',
				success: function(data) {
					vod.param.server.state = data.loginstatus.response;
					if(!data.loginstatus.response)	$vod.cookie('core_anon', '1', { path: '/', domain: '.sbs.com.au', expires: 7});
					// get subscription data if logged in
					if (vod.param.server.state) {
						vod.ds.playlist.subscription.get();
					}
				}
        	});
		},
		noImagePlaceholderPath:'/vod/sbs/images/',
		noImagePlaceholder:'on-demand-placeholder-sbs.gif'
	},
	cache:{
		/**
		 * dynamically added
		 */
		feed:{},
		playlist:{},
		progress:{},
		theFilter:{},
		history:{},
		subscription:{},
		video:{}
	},
	/**
	 * standard conversions
	 */
	filter:{
        findInMenu:function(name){

            var search = function (name, section, result){
                for(var n in section){
                    if(n == name){
                        return n;
                    } else if(typeof section[n]['children'] != 'undefined'){
                        if(typeof search(name, section[n]['children'], result) != 'undefined'){
                            result.push(n);
                            return result;
                        }
                    } else if(section[n]['name'] == name){
                        result.push(n);
                        return result;
                    }
                }
            };

            var result = search(name, VideoMenu, []);

            if(typeof result != 'undefined'){
                var output = '';
                for(var n = result.length - 1; n >= 0; n--){
                    output += result[n];
                    if(n != 0)
                         output += '.children.';
                }
                return output;
            } else return false;
        },
		text:{
			cleanStringExtract:function(string, length){
				var result = string.substr(0, length);
				result = result.substr(0, result.lastIndexOf(" "));
				return result + "...";
			},
			websafe:function(data){return data.replace(/[-'"]/g,'').replace(/\s/g,'-').replace(/-*-/g, '-');},
			domain:function(url) {
				var m = ((url||'')+'').match(/^http:\/\/[^/]+/);
				return m ? m[0] : null;
			},
			expiryString:function(from, to){
				if(to > from){
					var days = Math.ceil((to - from) / 86400000);
					var result, emphasis = '';
					if (days <= 5) {
						emphasis = 'hlight';
					}
					if (days > 31) {
						result = '&nbsp;';
					}
					else if (days == 1 || days == 0) {
						result = "<span class='pre-exp'>Expires</span><span class='hlight emph'>Today</span>";
					}
					else {
						result = "<span class='pre-exp'>Expires</span><span class='" + emphasis + "'>" +days+ " Days</span>";
					}
				} else {
					result = '&nbsp;';
				}
				return result;
			},
			formatDate: function (format, timestamp) {  //PHP Date formatting: http://phpjs.org/functions/date:380
			    var that = this,
					jsdate, f, formatChr = /\\?([a-z])/gi,
					formatChrCb,
					_pad = function (n, c) {
						if ((n = n + '').length < c) {
							return new Array((++c) - n.length).join('0') + n;
						}
						return n;
					},
					txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

			    formatChrCb = function (t, s) {
			        return f[t] ? f[t]() : s;
			    };
			    f = {
			        // Day
			        d: function () { // Day of month w/leading 0; 01..31
			            return _pad(f.j(), 2);
			        },
			        D: function () { // Shorthand day name; Mon...Sun
			            return f.l().slice(0, 3);
			        },
			        j: function () { // Day of month; 1..31
			            return jsdate.getDate();
			        },
			        l: function () { // Full day name; Monday...Sunday
			            return txt_words[f.w()] + 'day';
			        },
			        N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
			            return f.w() || 7;
			        },
			        S: function () { // Ordinal suffix for day of month; st, nd, rd, th
			            var j = f.j();
			            return j > 4 || j < 21 ? 'th' : {1: 'st', 2: 'nd', 3: 'rd'}[j % 10] || 'th';
			        },
			        w: function () { // Day of week; 0[Sun]..6[Sat]
			            return jsdate.getDay();
			        },
			        z: function () { // Day of year; 0..365
			            var a = new Date(f.Y(), f.n() - 1, f.j()),
			                b = new Date(f.Y(), 0, 1);
			            return Math.round((a - b) / 864e5) + 1;
			        },

			        // Week
			        W: function () { // ISO-8601 week number
			            var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
			                b = new Date(a.getFullYear(), 0, 4);
			            return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
			        },

			        // Month
			        F: function () { // Full month name; January...December
			            return txt_words[6 + f.n()];
			        },
			        m: function () { // Month w/leading 0; 01...12
			            return _pad(f.n(), 2);
			        },
			        M: function () { // Shorthand month name; Jan...Dec
			            return f.F().slice(0, 3);
			        },
			        n: function () { // Month; 1...12
			            return jsdate.getMonth() + 1;
			        },
			        t: function () { // Days in month; 28...31
			            return (new Date(f.Y(), f.n(), 0)).getDate();
			        },

			        // Year
			        L: function () { // Is leap year?; 0 or 1
			            return new Date(f.Y(), 1, 29).getMonth() === 1 | 0;
			        },
			        o: function () { // ISO-8601 year
			            var n = f.n(),
			                W = f.W(),
			                Y = f.Y();
			            return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);
			        },
			        Y: function () { // Full year; e.g. 1980...2010
			            return jsdate.getFullYear();
			        },
			        y: function () { // Last two digits of year; 00...99
			            return (f.Y() + "").slice(-2);
			        },

			        // Time
			        a: function () { // am or pm
			            return jsdate.getHours() > 11 ? "pm" : "am";
			        },
			        A: function () { // AM or PM
			            return f.a().toUpperCase();
			        },
			        B: function () { // Swatch Internet time; 000..999
			            var H = jsdate.getUTCHours() * 36e2,
			                // Hours
			                i = jsdate.getUTCMinutes() * 60,
			                // Minutes
			                s = jsdate.getUTCSeconds(); // Seconds
			            return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
			        },
			        g: function () { // 12-Hours; 1..12
			            return f.G() % 12 || 12;
			        },
			        G: function () { // 24-Hours; 0..23
			            return jsdate.getHours();
			        },
			        h: function () { // 12-Hours w/leading 0; 01..12
			            return _pad(f.g(), 2);
			        },
			        H: function () { // 24-Hours w/leading 0; 00..23
			            return _pad(f.G(), 2);
			        },
			        i: function () { // Minutes w/leading 0; 00..59
			            return _pad(jsdate.getMinutes(), 2);
			        },
			        s: function () { // Seconds w/leading 0; 00..59
			            return _pad(jsdate.getSeconds(), 2);
			        },
			        u: function () { // Microseconds; 000000-999000
			            return _pad(jsdate.getMilliseconds() * 1000, 6);
			        },

			        // Timezone
			        e: function () { // Timezone identifier; e.g. Atlantic/Azores, ...
			            throw 'Not supported (see source code of date() for timezone on how to add support)';
			        },
			        I: function () { // DST observed?; 0 or 1
			            var a = new Date(f.Y(), 0),
			                c = Date.UTC(f.Y(), 0),
			                b = new Date(f.Y(), 6),
			                d = Date.UTC(f.Y(), 6); // Jul 1 UTC
			            return 0 + ((a - c) !== (b - d));
			        },
			        O: function () { // Difference to GMT in hour format; e.g. +0200
			            var a = jsdate.getTimezoneOffset();
			            return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4);
			        },
			        P: function () { // Difference to GMT w/colon; e.g. +02:00
			            var O = f.O();
			            return (O.substr(0, 3) + ":" + O.substr(3, 2));
			        },
			        T: function () {
			            return 'T';
			        },
			        Z: function () { // Timezone offset in seconds (-43200...50400)
			            return -jsdate.getTimezoneOffset() * 60;
			        },
			        c: function () { // ISO-8601 date.
			            return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb);
			        },
			        r: function () { // RFC 2822
			            return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
			        },
			        U: function () { // Seconds since UNIX epoch
			            return jsdate.getTime() / 1000 | 0;
			        }
			    };
			    this.date = function (format, timestamp) {
			        that = this;
			        jsdate = ((typeof timestamp === 'undefined') ? new Date() : // Not provided
			        (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
			        new Date(timestamp) // UNIX timestamp (auto-convert to int)
			        );
			        return format.replace(formatChr, formatChrCb);
			    };
			    return this.date(format, timestamp);
			},
			formatTime: function(format, duration){
				/*
				 * h -- hours
				 * H -- hours not including 0
				 * m -- minutes
				 * M -- minutes past the hour
				 * s -- seconds
				 * S -- seconds past the minute
				 * d -- dirty -- don't strip non-numbers from edges of result string
				 * / -- escape character -- (using forward slash to avoid conflicts)
				 */

				duration = parseInt(duration);  // Some values seem to be floating point

				if(duration == 0 || isNaN(duration)) return '--:--';  // don't display anything for videos with no length data

				var hours = Math.floor(duration / 3600),
					minutes = Math.floor(duration / 60),
					seconds = duration % 60,
					heap = format.split(""),
					result = "",
					dirty = false;

				for(var n = 0; n < heap.length; n++){
					if(heap[n] == "/") 		result += heap[++n];
					else if(heap[n] == "h") result += hours;
					else if(heap[n] == "H") result += (hours == 0) ? "" : hours;
					else if(heap[n] == "m") result += minutes;
					else if(heap[n] == "M") {
						var minutesPastHour = minutes%60;
						result += (hours > 0 && minutesPastHour < 10) ? "0" + minutesPastHour : minutesPastHour;
					}
					else if(heap[n] == "s") result += duration;
					else if(heap[n] == "S") {
						result += (seconds < 10) ? "0":"";
						result += seconds;
					}
					else if(heap[n] == "d") dirty=true;
					else result += heap[n];
				}

				if(!dirty){
					result = result.substring(result.search(/\d/));
				}

				return result;
			}
		},
		object:{
			isEmpty:function(obj){
				for(var i in obj){
					return false;
				}
				return true;
			},
			/**
			 * @param obj // the json you want to convert to mpx
			 * @return result //json object with all mpx attr plus additional attr
			 */
			toMPX:function(obj){
				var result={};
			 /*
			 Thanh WIP
			 automatic json converter that compares the two json object and bridge the two structures, with extension for irregualer mapping
			 */

				/* ##### obtain mpx json structure assuming all page has at least one video cached ##### */
				var objMPX={};
				$vod.each(vod.cache.video, function(inx, val){
					objMPX=val;
					return false;
				});

				/* ##### mpx consistentcy check to know what needs mapping ##### */
				$vod.each(objMPX, function(inx, val){
					if(obj[inx]){
						// collect mapping data
					}else{
						// save attr to result
						result[inx]=obj[inx];
						// purge so that reiterator only try to map whats missing
						delete objMPX[inx];
						delete obj[inx];
					}
				});
				/* ##### map over known routes // dont forget to purge once mapped ##### */

				/* ##### massive reiterator to transverse obj to match remaining mpx attr then map data over ##### */
				return result;
			}
		}
	},


	checkLoginStatus:function(){
		return ($vod('.vod_login .logout').length > 0);
	},

	handlePlaylistAdd: function (contentId) {
		//console.log('handlePlaylistAdd', recommendationId, contentId);

		if (typeof(TheFilter) != 'undefined') {
			TheFilter.CaptureEvidence('PlaylistAdd', contentId, 'Video');
		}
		if (typeof(_gaq) != 'undefined') {
			_gaq.push(['_trackEvent', 'Videos', 'PlaylistAdd', vod.cache.video['id_' + contentId]['title']]);
		}

		return true;
	},

	handlePlaylistRemove:function (contentId) {
		//console.log('PlaylistRemover', recommendationId, contentId);

		if (typeof(TheFilter) != 'undefined') {
			TheFilter.CaptureEvidence('PlaylistRemover', contentId, 'Video');
		}
		if (typeof(_gaq) != 'undefined') {
			_gaq.push(['_trackEvent', 'Videos', 'PlaylistRemover', vod.cache.video['id_' + contentId]['title']]);
		}

		return true;
	},

	handleRecommendationClick: function (recommendationId, contentId) {
		//console.log('handleRecommendationClick', recommendationId, contentId);

		if (typeof(TheFilter) != 'undefined') {
			TheFilter.CaptureEvidence('RecClick', contentId, 'Video', {'recId':recommendationId});
		}
		if (typeof(_gaq) != 'undefined') {
			// Not tracked through Google Analytics because this data really needs The Filter to make sense of it
			_gaq.push(['_trackEvent', 'Videos', 'Recommendation Click To', vod.cache.video['id_' + recommendationId]['title']]);
			_gaq.push(['_trackEvent', 'Videos', 'Recommendation Click From', vod.cache.video['id_' + contentId]['title']]);
		}

		return true;
	},

	handleFacebookClick:function (contentId) {
		//console.log('handleFacebookClick', contentId);

		if (typeof(TheFilter) != 'undefined') {
			TheFilter.CaptureEvidence('FacebookLike', contentId, 'Video');
		}
		if (typeof(_gaq) != 'undefined') {
			_gaq.push(['_trackEvent', 'Videos', 'FacebookLike', vod.cache.video['id_' + contentId]['title']]);
		}

		return true;
	}
}

// More easing options to give us fancy animations -- Harley
$vod.easing['jswing'] = $vod.easing['swing'];

$vod.extend( $vod.easing,
{
	def: 'easeOutQuad',
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	}
});

