// Adjust menu in Safari for font smoothing
var pattern_safari = new RegExp("Safari");
var pattern_chrome = new RegExp("Chrome");
if ( pattern_safari.test( navigator.userAgent) ){
	document.write( '<style type="text/css">div.custom-selectbox div.custom-selectbox-list{padding-right:11px;}</style>' );
}
if ( pattern_safari.test( navigator.userAgent) && !pattern_chrome.test( navigator.userAgent) ){
	document.write( '<style type="text/css">div#header ul.nav li a{padding-left:14px;} div.custom-selectbox div.custom-selectbox-list{padding-right:9px;}</style>' );
}

//Homepage top flash
function updateFlashOnDemand() {
	if (thisMovie("twod") != undefined) thisMovie("twod").updateOnDemand();
}
function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function GetUserID(){
    return $.cookie('UserID');
}

 function GetWebServiceURL(){
     return ServerPath + 'WebServices.asmx'; //'http://twcvod.wreckingballmedia.com/ondemandv3/WebServices.asmx';
 }

$(document).ready(function(){
	initHeaderCustomCheckboxes();
	initSearchInput();
	initCustomizeHome();
	initSetLocation();
	initSliders();
	initShowcase();
	initDescriptionHover();
	initRolloverPopups();
	initSidebarSubmenus();
	initMyodForm();
	initLeftBoxes();
	initFontReplacement();
	initMyOnDemand();
});

// Cufón Replacement
function initFontReplacement(){
	// Body Header Elements
	Cufon.replace('#main h2:not(.plain),#main h3:not(.plain),.slider h4:not(.plain),.cufon');
};

function initMyOnDemand(){
	$('a.delete-asset, a.delete-series, a.delete-video').unbind('click');
	$('a.delete-asset, a.delete-video, a.delete-series').click(function(){
        UpdateMYOD($(this).attr('class').substr(7,1), $(this).attr('id').replace('t','').replace('r',''));
		return false;
	});	
	
	$('a.add-asset, a.add-video, a.add-series').unbind('click');	
	$('a.add-asset, a.add-video, a.add-series').click(function(){
        UpdateMYOD($(this).attr('class').substr(4,1), $(this).attr('id').replace('t','').replace('r',''));
		return false;
	});
	UpdateMyOnDemandTopCounterAndAssets();	
	GetMyOnDemandContent();
}

function UpdateMyOnDemand(id, type, status){
    $('#'+id+',#t'+id+',#r'+id).each(function(){
        if (status == 1 ) {
            if ($(this).is('.delete-asset')) { $(this).attr({ 'class': 'add-asset', 'title': 'Add' }); }
            else if ($(this).is('.delete-series')) { $(this).attr({ 'class': 'add-series', 'title': 'Add' }); }
            else if ($(this).is('.delete-video')) { $(this).attr({ 'class': 'add-video', 'title': 'Add' });	}
        } else {
            if ($(this).is('.add-asset')) { $(this).attr({ 'class': 'delete-asset', 'title': 'Delete' }); }
            else if ($(this).is('.add-series')) { $(this).attr({ 'class': 'delete-series', 'title': 'Delete' }); }
            else if ($(this).is('.add-video')) { $(this).attr({ 'class': 'delete-video', 'title': 'Delete' });	}       
        }
    });
    initMyOnDemand();
};

function UpdateMyOnDemandTopCounterAndAssets(){
   	$.ajax({
	    type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: ServerPath + 'WebServices.asmx/GetMyOnDemandCounterAndAssets',  
	    data: "{'UserID': '" + $.cookie('UserID') + "', 'LineUpID': '" + $.cookie('LineUpID') + "'}",  
	    success: function (data) {
	        var Assets = data.split(",");
	        if (Assets == "") {
                $("#myondemand-top-counter").html("(0)");
			} else {
                var Counter = 0;
                for(i = 0; i < Assets.length; i++) {
                    $('#'+Assets[i].substring(1) +',#t'+Assets[i].substring(1) +',#r'+Assets[i].substring(1)).each(function(){
                            if ($(this).is('.add-asset')) { $(this).attr({ 'class': 'delete-asset', 'title': 'Delete' }); }
                            else if ($(this).is('.add-series')) { $(this).attr({ 'class': 'delete-series', 'title': 'Delete' }); }
                            else if ($(this).is('.add-video')) { $(this).attr({ 'class': 'delete-video', 'title': 'Delete' });	}       
                    });
                    if (Assets[i].substring(0,1) == 'a') Counter++;
                }
                $("#myondemand-top-counter").html("(" + Counter + ")");				
			}    
	    },
        error: function (xmlhttp) { /*alert('An AJAX '+ xmlhttp.status +' error occured.\n' + xmlhttp.responseText);*/ }
    });	
    return '';  
};

function GetMyOnDemandContent(){
  //   updateFlashOnDemand();
     $.ajax({
	    type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: ServerPath + 'WebServices.asmx/GetMyOnDemand',
	    data: "{'UserID': '" + $.cookie('UserID') + "', 'LineUpID': '" + $.cookie('LineUpID') + "', 'AssetsToShow':'" + $.cookie('MyOnDemand_AssetsToShow') + "'}",  
        success: function (data) {
		    $("div.side-demand").html(data);
			Cufon.replace('div.side-demand h4.cufon'); // Restyle the title
		    DeleteMyOnDemand();
        },
        error: function (xmlhttp) { /*alert('An AJAX '+ xmlhttp.status +' error occured.\n' + xmlhttp.responseText);*/ }
    });	
    if ($("#myondemand-top-counter").html() != '') UpdateMyOnDemandTopCounterAndAssets();
    return '';  
};

function DeleteMyOnDemand(){
	$('a.close').unbind('click');	
	$('a.close').click(function(){
    	$.ajax({
	        type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: ServerPath + 'WebServices.asmx/DeleteFromOMD',
		    data: "{'ID': '" + $(this).attr('rel') + "'}",  
		    success: function (data) {
		    	$('#'+data+',#t'+data+',#r'+data).each(function(){
			        if ($(this).attr('class') == 'delete-asset') $(this).attr({ 'class': 'add-asset', 'title': 'Add' });
			        if ($(this).attr('class') == 'delete-series') $(this).attr({ 'class': 'add-series', 'title': 'Add' });
			        if ($(this).attr('class') == 'delete-video') $(this).attr({ 'class': 'add-video', 'title': 'Add' });			    			    
		        });
                initMyOnDemand();
		    },
            error: function (xmlhttp) { /*alert('An AJAX '+ xmlhttp.status +' error occured.\n' + xmlhttp.responseText);*/ }
	    });
	    return false;
	});
	
    $('div.pagination > ul> li > a').unbind('click');
    $('div.pagination > ul> li > a').click(function(){
        $.cookie('MyOnDemand_AssetsToShow', $(this).attr('rel'));
        GetMyOnDemandContent();
        return false;
    });		
}

function UpdateMYOD(type, id){
	$.ajax({
	    type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: ServerPath + 'WebServices.asmx/UpdateMYOD',
	    data: "{'UserID': '" + $.cookie('UserID') + "', 'type': '" + type + "', 'id':'" + id + "'}",  
	    success: function (data) {
            $('#'+id+',#t'+id+',#r'+id).each(function(){
	            if (data == 'add') {
			        if ($(this).attr('class') == 'add-asset') $(this).attr({ 'class': 'delete-asset', 'title': 'Delete' });
			        if ($(this).attr('class') == 'add-series') $(this).attr({ 'class': 'delete-series', 'title': 'Delete' });
			        if ($(this).attr('class') == 'add-video') $(this).attr({ 'class': 'delete-video', 'title': 'Delete' });	
			    }
	            if (data == 'delete') {			    
			        if ($(this).attr('class') == 'delete-asset') $(this).attr({ 'class': 'add-asset', 'title': 'Add' })
			        if ($(this).attr('class') == 'delete-series') $(this).attr({ 'class': 'add-series', 'title': 'Add' })
			        if ($(this).attr('class') == 'delete-video') $(this).attr({ 'class': 'add-video', 'title': 'Add' });
			    }
		    });	    
            initMyOnDemand();
            updateFlashOnDemand();			
	    },
        error: function (xmlhttp) { alert('An AJAX '+ xmlhttp.status +' error occured.\n' + xmlhttp.responseText); }
    });
}

function initHeaderCustomCheckboxes(){
	$('div.checkbox').click(function(){
		var Cur = $(this).children('input:checkbox').attr('id') == 'quality-hd' ? 'HD' : 'SD';
		var isHD = $('#quality-hd').parent().hasClass('checkbox-checked');
		var isSD = $('#quality-sd').parent().hasClass('checkbox-checked');
		
		if ((!isHD && Cur == 'SD') || (!isSD && Cur == 'HD')) return false;	
		
		$(this).toggleClass('checkbox-checked');
		$(this).children('input:checkbox').checked = $(this).hasClass('checkbox-checked');
		
		var cont;
		if (Cur == 'HD') cont = $('#left-side div.side-box.is_hd,' +
			'#right-side div.side-box.is_hd,' +
			'#content div.slider.is_hd');
		
		if (Cur == 'SD') cont = $('#left-side div.side-box:not(#left-side div.side-box.is_hd),' +
			'#right-side div.side-box:not(#right-side div.side-box.is_hd):not(div.side-demand),' +
			'#content div.slider:not(#content div.slider.is_hd)');
		
		cont.toggleClass('hidden');
		if (cont.hasClass('hidden')){
			cont.hide();
		} else {
			cont.show();
		}	
		if ($('#quality-hd').parent().hasClass('checkbox-checked')) $('#right-side div.side-box.is_hd').show();
			
	});
}

function initSearchInput(){
	$("#quick-search").focus(function(){
		if ($(this).val() == 'Search')
			$(this).val('');
	});
	$("#quick-search").blur(function(){
		if ($(this).val() == '')
			$(this).val('Search');
	});
}

function initCustomizeHome(){
	if ($.cookie('customizehome') == null && $.cookie('customizehomedefault') != null) $.cookie('customizehome', $.cookie('customizehomedefault'));
	if ($.cookie('customizehome') == null) $.cookie('customizehome', 't20,t15,t16,p76,p386,p394,p364');	
	var CheckBoxes = $.cookie('customizehome').replace( "%2C", "," ).split(",");	
    for(i = 0; i < CheckBoxes.length; i++) {
        $('#chb'+CheckBoxes[i]).attr("checked", "checked");
        $('#r'+CheckBoxes[i]).parent().show();  
        $('#p'+CheckBoxes[i]).show();                
    }  

	// Show or hide customization homepage popup
	$('div#customize a.drop:not(.link)').click(function(){
		hideSetLocation();
		if ($(this).parent().parent().hasClass('expanded')){
			hideCustomizeHome();
		} else {
			showCustomizeHome();
		}
		return false;
	});
	// Reset customization form
	$('a#customization-reset').click(function(){
	    $.cookie( 'customizehome', $.cookie('customizehomedefault'));
		$('form#customize-home-form').submit();		
		return false;
	});
	// Submit customization form
	$('a#customization-save').click(function(){
	    var CustCookie = '';
		$('form#customize-home-form input:checkbox:checked').each(function(){
			CustCookie += this.value + ',';
		});
		CustCookie = CustCookie.substring(0, CustCookie.length - 1);
		$.cookie('customizehome', CustCookie, { expires: 365, path: ServerPath});
		$('form#customize-home-form').submit();
		return false;
	});
	// Cancel customization homepage
	$('a#customization-cancel').click(function(){
		$('div#customize').removeClass('expanded');
		hideCustomizeHome();
		return false;
	});

	// Set custom check boxes correctly
	$('div.check > input:checkbox:checked').parent().addClass('check-checked');

	var int_check_click = false;
	// Custom checkboxes on customization homepage
	$('div.check > input:checkbox').click(function(){
		$(this).parent('div.check').click();
		int_check_click = true;
	})
	$('div.check').click(function(){
		if ( int_check_click ){
			int_check_click = false;
			return;
		} else {
			$(this).toggleClass('check-checked');
			if ($(this).hasClass('check-checked')){
				$(this).children('input:checkbox').attr("checked", "checked");
			} else {
				$(this).children('input:checkbox').removeAttr("checked");
			}
		}
	});

	$('#customize-home-form dl dd div.label').click(function(){
		$(this).siblings(".check").click();
	});

	// Set custom radios correctly
	$('div.radio > input:radio:checked').parent().addClass('radio-selected');

	// Custom radios on customization homepage
	var int_radio_click = false;
	$('div.radio > input:radio').click(function(){
		$(this).parent('div.radio').click();
		int_radio_click = true;
	});
	$('div.radio').click(function(){
		if ( int_radio_click ){
			int_radio_click = false;
			return;
		} else {
			var setName = $(this).find(" > input:radio").attr("name");
			$(this).parent().parent().find("input[name="+setName+"]").each(function(){
				$(this).attr("checked", false);
			});
			$(this).parent().parent().find("div.radio.radio-selected").removeClass("radio-selected");
			$(this).addClass("radio-selected").find(" > input:radio").attr("checked", true);
		}
	});
}
var animateCustomizeHome = false;

function hideCustomizeHome(){
	if ( !animateCustomizeHome ){
		animateCustomizeHome = true;
		$('div#customize').removeClass('expanded');
		$('div#location').removeClass('expanded-customize');
		$('div#customize-home').css('z-index', 1).animate({ 'bottom': '0px' }, 'medium', function(){ animateCustomizeHome = false; });
		return;
	} else {
		return;
	}
}

function showCustomizeHome(){
	if ( !animateCustomizeHome ){
		animateCustomizeHome = true;
		$('div#customize').addClass('expanded');
		$('div#location').addClass('expanded-customize');
		var height = $('div#customize-home').height();
		$('div#customize-home').animate({ 'bottom': '-'+ height +'px' }, 'slow', function(){
			$(this).css('z-index', 3);
			animateCustomizeHome = false;
		});
		return;
	} else {
		return;
	}
}

function initSetLocation(){

	// Show or hide set location popup
	$('div#location > a.drop').click(function(){
		hideCustomizeHome();
		if ( $(this).parent().hasClass('expanded') ){
			hideSetLocation();
		} else {
			showSetLocation();
		}
		return false;
	});
	// Cancel customization homepage
	$('a#close-location').click(function(){
		hideSetLocation();
		return false;
	});
	$('select#set-location-state').selectbox({ className: 'custom-selectbox', animationSpeed: 'slow'});

	var $select = $('select#set-location-state').parent('div.custom-selectbox');
	$select.find('div.custom-selectbox-list span.custom-selectbox-item').click(function(){
		var add_class = false;
		if ($('select#set-location-state').attr('value') != 0 ){
			add_class = true;
			loadMarket( $('select#set-location-state').attr('value') );
		} else {
		    $('select#set-location-state').parents('li:first').children('input.button-go').hide();	
            $('select#set-location-market').parents('li:first').children('input.button-go').hide();	
            $('select#set-location-submarket').parents('li:first').children('input.button-go').hide();   
			// Hide market
			var $select1 = $('select#set-location-market');
			$select1.parents('.custom-selectbox').unselectbox();
			$select1.html('').parents('li:first').slideUp('medium');
			// Hide submarket
			var $select2 = $('select#set-location-submarket');
			$select2.parents('.custom-selectbox').unselectbox();
			$select2.html('').parents('li:first').slideUp('medium');
			$('select#set-location-submarket').parents('li:first').children('input.button-go').fadeOut('medium');
		}
		$(this).parent().children().removeClass('item-selected');
		if ( add_class ) $(this).addClass('item-selected');
	});

}

function hideSetLocation(){
	$('div#location').removeClass('expanded');
	var $set_location = $('div#set-location');
	if ( $set_location.css('top') == '100%' ){
		$set_location.css({ 'top': 'auto', 'bottom': '-'+ $set_location.height() +'px' });
		$set_location.animate({ 'bottom': '0px' }, 'medium', function(){
			//$('div#set-location div.select select').parents('.jquery-selectbox').unselectbox();
		});
	}
	return;
}

function showSetLocation(){
	$('div#location').addClass('expanded');
	var height = $('div#set-location').height();
	$('div#set-location').animate({ 'bottom': '-'+ height +'px' }, 'slow', function(){
		$(this).css({ 'top': '100%', 'bottom': 'auto' });
	});
	return;
}

function loadMarket(StateID){
	$.ajax({
		type: "POST",
		url: ServerPath+'WebServices.asmx/FillMarketsDDL',
		data: "{'StateID': '" + StateID + "'}",  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",   
		success: function (data) {
			initLoadedMarket(data);
		},
		error: function (xmlhttp) {
			alert('An HTTP '+ xmlhttp.status +' error occured. Your vote was not submitted!\n' + xmlhttp.responseText);
		}
	});
}

function loadSubMarket(MarketID){
	$.ajax({
		type: "POST",
		url: ServerPath+'WebServices.asmx/FillSubMarketsDDL',
		data: "{'MarketID': '" + MarketID + "'}",  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",   
		success: function (data) {
			initLoadedSubMarket(data);
		},
		error: function (xmlhttp) {
			alert('An HTTP '+ xmlhttp.status +' error occured. Your vote was not submitted!\n' + xmlhttp.responseText);
		}	
	});
}

function initLoadedMarket(data){
	$('select#set-location-market').parent('div.custom-selectbox').unselectbox();
    $('select#set-location-state').parents('li:first').children('input.button-go').hide();	
    $('select#set-location-market').parents('li:first').children('input.button-go').hide();	
    $('select#set-location-submarket').parents('li:first').children('input.button-go').hide();    
	var $select1 = $('select#set-location-submarket');
	$select1.parents('.custom-selectbox').unselectbox();
	$select1.html('').parents('li:first').slideUp('medium');
	$('select#set-location-market').html(data);
	if ($('select#set-location-market').html().split("<option").length > 2) {
        $('select#set-location-market').parents('li:first').slideDown('medium');
	    $('select#set-location-market').css('opacity', 0).selectbox({ className: 'custom-selectbox', animationSpeed: 'slow'});
	} else {
		$('select#set-location-market').parents('.custom-selectbox').unselectbox();
		$('select#set-location-market').parents('li:first').slideUp('medium');
	}
	var $select = $('select#set-location-market').parent('div.custom-selectbox');

	if ( $('select#set-location-market').attr('value') != 0 ){
    	loadSubMarket( $('select#set-location-market').attr('value') );
		$('select#set-location-submarket').parents('li:first').children('input.button-go').fadeOut('medium');
		$(this).parent().children().removeClass('item-selected');
		$(this).addClass('item-selected');
	};

	$select.find('div.custom-selectbox-list > span.custom-selectbox-item').click(function(){
		var add_class = false;
		if ( $('select#set-location-market').attr('value') != 0 ){
			add_class = true;
			loadSubMarket( $('select#set-location-market').attr('value') );
			$('select#set-location-submarket').parents('li:first').children('input.button-go').fadeOut('medium');
		} else {
			// Hide submarket
			var $select2 = $('select#set-location-submarket');
			$select2.parents('.custom-selectbox').unselectbox();
			$select2.html('').parents('li:first').slideUp('medium');
			$('select#set-location-submarket').parents('li:first').children('input.button-go').fadeOut('medium');
		}
		$(this).parent().children().removeClass('item-selected');
		if ( add_class ) $(this).addClass('item-selected');
	});
}

function initLoadedSubMarket(data){
	$('select#set-location-submarket').parent('div.custom-selectbox').unselectbox();
	$('select#set-location-submarket').html(data);
	
	if ($('select#set-location-submarket').html().split("<option").length > 2) {
	    $('select#set-location-market').parents('li:first').children('input.button-go').hide();	
        $('select#set-location-submarket').parents('li:first').slideDown('medium');
	    $('select#set-location-submarket').css('opacity', 0).selectbox({ className: 'custom-selectbox', animationSpeed: 'slow'});
	} else {
		$('select#set-location-submarket').parents('.custom-selectbox').unselectbox();
		$('select#set-location-submarket').parents('li:first').slideUp('medium');
		$('select#set-location-market').parents('li:first').children('input.button-go').fadeIn('medium');
	}
	
	if ($('select#set-location-market').html().split("<option").length == 2 && $('select#set-location-submarket').html().split("<option").length == 2) 
	    $('select#set-location-state').parents('li:first').children('input.button-go').fadeIn('medium');	
	
	if ( $('select#set-location-submarket').attr('value') != 0 ){
    	$('select#set-location-submarket').parents('li:first').children('input.button-go').fadeIn('medium');
		$(this).parent().children().removeClass('item-selected');
		$(this).addClass('item-selected');
	};
	
	var $select = $('select#set-location-submarket').parent('div.custom-selectbox');
	var default_value_submarket = $('select#set-location-submarket').attr('value');
	$select.find('div.custom-selectbox-list > span.custom-selectbox-item').click(function(){
		var add_class = false;
		var $btn = $('select#set-location-submarket').parents('li:first').children('input.button-go');
		if ( $('select#set-location-submarket').attr('value') != 0 ){
			add_class = true;
			$btn.fadeIn('medium');
		} else {
			$btn.fadeOut('medium');
		}
		$(this).parent().children().removeClass('item-selected');
		if ( add_class ) $(this).addClass('item-selected');
	});
}



function initSliders(){
	var sliding = false;
	$('div.slider > div.pager > ul > li > a').unbind('click');

	$('div.slider > div.pager').each(function(){
		var pager = $(this);
		var panes = $(this).parent().find("ul.slider-list > li");
		var pagerHTML = "";

		if(panes.length > 1){
			pagerHTML = "<ul><li><a title=\"Previous slide\" href=\"#\" class=\"prev\">Previous slide</a></li>";
			for(i=0; i < panes.length; i++){
				pagerHTML = pagerHTML+"<li";
				if(i==0){
					pagerHTML = pagerHTML+" class='active'";
				}
				pagerHTML = pagerHTML+"><a href='#' title='Slide' rel='"+i+"'>Slide</a></li>";
			}
			pagerHTML = pagerHTML+"<li><a title=\"Next slide\" href=\"#\" class=\"next\">Next slide</a></li></ul>";

			pager.prepend(pagerHTML);

			var newUl = $(this).find("ul");
			var titleWidth = $(this).find("h4").text().length * 11;
			var pagerCenter = pager.width() / 2;
			var ulCenter = newUl.width() / 2;
			var leftOffset = (pagerCenter - ulCenter)

			// Offset for long titles
			//if((leftOffset - titleWidth) < 10){
			//	leftOffset = titleWidth + 5;
			//}
			newUl.css("left", leftOffset).css("marginRight", leftOffset);
		} else {
			$(this).parent().find('a.sidearrow').remove();
		}
	});
	
	$('div.slider > div.slider-hold > a.sidearrow.previous').click(function(){
		$(this).parent().parent().find(".pager ul li a.prev").click();
		return false;
	});
	$('div.slider > div.slider-hold > a.sidearrow.next').click(function(){
		$(this).parent().parent().find(".pager ul li a.next").click();
		return false;
	});

	$('div.slider > div.pager > ul > li > a').click(function(){
		if ( !sliding ) {
			var anim_to;
			var $ul = $(this).parents("div.slider").children('div.slider-hold').children('ul.slider-list');
			var slidecount = $ul.find("> li").length;
			var ul_left = parseInt( $ul.css('left'), 10 );
			var step = $ul.children('li').width();
			var boundary = false;
			if ( this.rel ) {
				sliding = true;
				$(this).parent('li').parent('ul').children('li').removeClass('active');
				$(this).parent('li').addClass('active');
				anim_to = '-'+ step*( $(this).attr('rel') ) +'px';
			} else {
				sliding = true;
				var next_active;
				var active_li = $(this).parent().parent().children("li.active");
				$(active_li).removeClass('active');
				if ($(this).hasClass('prev')){
					if ( ul_left == 0 ){
						anim_to = '+='+ step +'px';
						next_active = $(active_li).parent().children('li:eq('+slidecount+')');
						// Need for first and last li's sliding
						var first_li = $ul.children('li:first').clone(true);
						$ul.css('left', -step*slidecount).append(first_li);
						boundary = true;
						boundary_left = 0;
						boundary_li = 'last';
					} else {
						next_active = $(active_li).prev('li');
						anim_to = '+='+ step +'px';
					}
				} else {
					if ( Math.abs( ul_left ) >= step*(slidecount-1) ){
						anim_to = '-='+ step +'px';
						next_active = $(active_li).parent().children('li:eq(1)');
						// Need for first and last li's sliding
						var last_li = $ul.children('li:last').clone(true);
						$ul.css('left', 0).prepend(last_li);
						boundary = true;
						boundary_left = +step;
						boundary_li = 'first';
					} else {
						next_active = $(active_li).next('li');
						anim_to = '-='+ step +'px';
					}
				}
				$(next_active).addClass('active');
			}
			$ul.animate( {'left': anim_to}, 'medium', function(){
				sliding = false;
				if ( boundary ){
					ul_left = parseInt( $ul.css('left'), 10 );
					$ul.css('left', ul_left+boundary_left ).children('li:'+ boundary_li).remove();
				}
			});
		}
		// Start Loading Asssets for this pod
		$(this).parents('div.slider:not(.loaded)').addClass("loaded").find("a.loading img").attr("src",function(){
			return $(this).attr("source");
		}).load(function(){
			$(this).parent().removeClass(".loading");
		});

		return false;
	});
}

function initShowcase(){
/*	if ( $('div#showcase').get(0) ){
		var flashvars = {};
        var params = {
			wmode: "transparent",
			allowScriptAccess: "sameDomain"
        };
		swfobject.embedSWF(ServerPath+"swf/twod.swf", "showcase", "980", "383", "9.0.0", ServerPath+"swf/expressInstall.swf", flashvars, params);
	}*/
}

var roll_over_poster = false;
var roll_over_poster_div;
var roll_over_movie = false;
var roll_over_movie_div;
function initRolloverPopups(){
	$("div.description-popup").each(function(){
		if($(this).find("img").length > 0){
			$(this).addClass("wide");
		}
	});
	
	$('div#with-popup-posters > ul > li').hover(
		function(){
			roll_over_poster = true;
			roll_over_poster_div = $(this).children('div.poster-popup');
			setTimeout("showPoster()", 500);
		},
		function(){
			roll_over_poster = false;
			$(this).css('z-index', 1);
			$(this).children('div.poster-popup').hide();
		}
	);
	$('div.slider > div.slider-hold ul.slider-list > li > ul.list-posters > li > div.poster a.pict > img').hover(
		function(){
			roll_over_movie = true;
			roll_over_movie_div = $(this).parent().parent().parent().nextAll('div.description-popup');
			hover_movie = true;
			setTimeout("showDescription()", 100);
		},
		function(){
			roll_over_movie = false;
			hover_movie = false;
			checkDescription();
		}
	).mousemove(function(e){
		if(roll_over_movie){
			$('div#popup-description').css('top',e.pageY+15);
			$('div#popup-description').css('left',e.pageX+5);
		}
	}).removeAttr("alt"); // Prevents tooltips in IE
	
    $(".cols-cont-asset .list-view li strong.tit, .cols-cont .list-view li strong.tit, #results table.listings td.title a").hover(
				function(){
					roll_over_movie = true;
					roll_over_movie_div = $(this).nextAll('div.description-popup');
					hover_movie = true;
					//setTimeout("showDescription()", 300);
					showDescription(true);
				},
				function(){
					roll_over_movie = false;
					hover_movie = false;
					checkDescription(true);
				}
			).mousemove(function(e){
				if(roll_over_movie){
					$('div#popup-description').css('top',e.pageY+15);
					$('div#popup-description').css('left',e.pageX+5);
				}
			});	

	$('li > div.title > p > strong > a').hover(
		function(){
			roll_over_movie = true;
			roll_over_movie_div = $(this).parent().parent().nextAll('div.description-popup');
			hover_movie = true;
			setTimeout("showDescription()", 500);
		},
		function(){
			roll_over_movie = false;
			hover_movie = false;
			setTimeout("checkDescription()", 100);
		}
	)	
}

function showPoster(){
	if ( roll_over_poster ){
		$(roll_over_poster_div).parent('li').css('z-index', 5).show();
	}
}

function showDescription(){
	if ( roll_over_movie && roll_over_movie_div.length > 0){
		var offset = $(roll_over_movie_div).parent().offset();
		var top = (parseInt( $(roll_over_movie_div).parent().height(), 10)*0.35 );

		$('div#popup-description')
			.html($(roll_over_movie_div).clone())
			.css({'display':'none'})
			.show();
	}
}
var hover_movie= false;
var hover_desc = false;
function initDescriptionHover(){
	$('div#popup-description').hover(
		function(){ hover_desc = true; },
		function(){ hover_desc = false; checkDescription(); }
	)
}

function checkDescription(){
	if ( hover_movie === false && hover_desc === false ){
		$('div#popup-description').html('').hide();
	}
}

function initSidebarSubmenus(){
	$('div#main div.side-box ul a.film').click(function(){
		if($(this).parent('li').children('ul.sub').get(0) ){
			$(this).toggleClass("open").parent('li').children('ul.sub').slideToggle('slow');
			return false;
		}
	});
	$('div#main div.side-box ul > li').each(function(){
		if($(this).children('ul.sub').get(0)){
			$(this).find("> a.film").append('<div class="hassub">');
		}
	});
}

function initMyodForm(){
	if ( $('div#myod').get(0) ){
		$('div#myod > div.myod-sorting > fieldset > ul > li > div.select > select').selectbox({ className: 'custom-selectbox', animationSpeed: 'medium'});
	}
}

function initLeftBoxes(){
	// Take position of each box from cookie
	$('div#left-side > div.side-box').each(function(){
		var cookie = $.cookie( 'twod-'+ $(this).attr('id') );
		if ( cookie == 'collapsed' ){
			$(this).children('ul').slideToggle('slow');
			$(this).children().children('a.collapse').attr({
				'class': 'expand',
				'title': 'Expand box'
			});
		}
	});
	// Set cookie and collapse/expand box on click
	$('div#left-side > div.side-box > div.box-title > a.collapse, div#left-side > div.side-box > div.box-title > a.expand').unbind('click');
	$('div#left-side > div.side-box > div.box-title > a.collapse, div#left-side > div.side-box > div.box-title > a.expand').click(function(){
		// Change class and icon
		var new_class = $(this).attr('class') == 'collapse' ? 'expand' : 'collapse';
		var new_title = $(this).attr('class') == 'collapse' ? 'Expand box' : 'Collapse box';
		$(this).attr({
			'class': new_class,
			'title': new_title
		});
		// Change state of list
		var ul = $(this).parent().next('ul');
		var ul_visible = $(ul).css('display') == 'block' ? true : false;
		$(ul).slideToggle('slow');
		// Set cookie based on state
		var box_id = $(this).parent().parent('div.side-box').attr('id');
		var box_state = ( ul_visible ) ? 'collapsed' : 'expanded';
		$.cookie( 'twod-'+ box_id, box_state, { expires: 7 });
		return false;
	});
}