// 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#main div.custom-selectbox div.custom-selectbox-list{padding-right:15px;}</style>' );
	document.write( '<style type="text/css">div#main div.custom-selectbox div.custom-selectbox-list span.custom-selectbox-item{width:180px;}</style>' );
	document.write( '<style type="text/css">div.custom-selectbox div.custom-selectbox-list{padding-right:9px;}</style>' );
}

/********************************* Start Homepage Flash Player  ************************************/
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';
 }
 
/********************************* End Homepage Flash Player  ************************************/

$(document).ready(function(){
	initSendPopup();
	initCustomizeHome();
	initSetLocation();
	initSearch();
	initVideo();
	initHeaderCustomCheckboxes();
	initSearchInput();
	initSliders();
	initShowcase();
	initDescriptionHover();
	initRolloverPopups();
	initSidebarSubmenus();
	initMyodForm();
	initLeftBoxes();
	initFontReplacement();
	initMyOnDemand();
});
/**
* @hint function modified by Aaron Greenlee 5/14/2010 to support our floating input. Results are now positioned on resize
* @revision 05/14/2010
*/
function initSearch(){
	var $ac_element = $("#quick-search");
	
    var data = /*"http://twcvod.wreckingballmedia.com/ondemandv5/WebServices.asmx*/  GetWebServiceURL() + "/GetCompletionList";
	$("#quick-search").autocomplete(data, { dataType: "xml", datakey: "string", max: 100, cap: true});

	/* Force resize, scroll */
	$(window).resize(function() {
		/* Select our div that contains the autocomplete results */
		var $ac_results_element = $('.ac_results');
		
		/* Perform action only if the autocomplete is active */
		if ( $ac_results_element.is(':visible') ) {
			/* Reposition to bind to our floated element */
			var offset = $ac_element.offset();
			$ac_results_element.css({
				top: offset.top + $ac_element.offsetHeight,
				left: offset.left
			})
		}
	});
};
function initVideo(){
	$('#main div.movie div.sidebar-links a.trailer, #main div.movie div.movie-info div.poster-bg a').click(function(){
	    $('#main div.movie').hide();	
		$(twc.episode.player.containerID).show();
		if (twc.episode.player.hasCustomElement)
			$('#player').show();
		return false;
	});
	$('#main div.video-trailer a.close-video,#main div.video-trailer a.more-info').click(function(){
		$(twc.episode.player.containerID).hide();
	    $('#main div.movie').show();			
		if (twc.episode.player.hasCustomElement)
			$('#player').hide();
		return false;
	})
};

// Cufón Replacement
function initFontReplacement(){
	// Body Header Elements
	Cufon.replace('#main h2:not(.plain),#main h3:not(.plain),.slider h4:not(.plain),.block h4,.cufon,div#main div.list-box div.pager h4,div#main div#content h3',{fontFamily:'Arial'});
	Cufon.replace('a.view-all,.cufon-black,div#footer ul.nav dt,div#main ul.tabs li a,#content div.column div.block-title span.cufon',{hover: true,fontFamily:'Stag Sans Round Medium'});
	 Cufon.replace('#header ul.nav li a,div#main ul.tabs li.tabs-selected a', {textShadow: '0 -1px rgba(51, 51, 51, 0.4)', fontFamily:'Stag Sans Round Medium'});
	 
	 
	 
	 
	//Cufon.replace('#main h2',{'font-weight':300});
};

/********************************* Start My On Demand ************************************/
function initMyOnDemand(){
	$('a.delete-asset, a.delete-series, a.delete-video, a.delete-movie, a.delete-episodes').unbind('click');
	$('a.delete-asset, a.delete-video, a.delete-series, a.delete-movie, a.delete-episodes').click(function(){
        UpdateMYOD($(this).attr('class').substr(7,1), $(this).attr('id').replace('t','').replace('r','').replace('v',''));
		return false;
	});	
	
	$('a.add-asset, a.add-video, a.add-series, a.add-movie, a.add-episodes').unbind('click');	
	$('a.add-asset, a.add-video, a.add-series, a.add-movie, a.add-episodes').click(function(){
        UpdateMYOD($(this).attr('class').substr(4,1), $(this).attr('id').replace('t','').replace('r','').replace('v',''));
		return false;
	});
	UpdateMyOnDemandTopCounterAndAssets();	
	GetMyOnDemandContent();
}

function UpdateMyOnDemand(id, type, status){
    $('#'+id+',#t'+id+',#r'+id+',#v'+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('.delete-movie')) { $(this).attr({ 'class': 'add-movie', 'title': 'Add' });	}    
            else if ($(this).is('.delete-episodes')) { $(this).attr({ 'class': 'add-episodes', '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' });	}   
            else if ($(this).is('.add-movie')) { $(this).attr({ 'class': 'delete-movie', 'title': 'Delete' });	}      
            else if ($(this).is('.add-episodes')) { $(this).attr({ 'class': 'delete-episodes', '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) +',#v'+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' });	}     
                            else if ($(this).is('.add-movie')) { $(this).attr({ 'class': 'delete-movie', 'title': 'Delete' });	}       
                            else if ($(this).is('.add-episodes')) { $(this).attr({ 'class': 'delete-episodes', '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+',#v'+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' });	
			        if ($(this).attr('class') == 'delete-movie') $(this).attr({ 'class': 'add-movie', 'title': 'Add' });		
			        if ($(this).attr('class') == 'delete-episodes') $(this).attr({ 'class': 'add-episodes', '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+',#v'+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 ($(this).attr('class') == 'add-movie') $(this).attr({ 'class': 'delete-movie', 'title': 'Delete' });	
			        if ($(this).attr('class') == 'add-episodes') $(this).attr({ 'class': 'delete-episodes', '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' });
			        if ($(this).attr('class') == 'delete-movie') $(this).attr({ 'class': 'add-movie', 'title': 'Add' });	
			        if ($(this).attr('class') == 'delete-episodes') $(this).attr({ 'class': 'add-episodes', 'title': 'Add' });				        		        
			    }
		    });	    
            initMyOnDemand();
            updateFlashOnDemand();			
	    },
        error: function (xmlhttp) { alert('An AJAX '+ xmlhttp.status +' error occured.\n' + xmlhttp.responseText); }
    });
}

/************************************** End My On Demand ****************************************/

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.isPYH');
		
		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.isPYH: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');
	});
}

/********************************* Start Set Location  ************************************/
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');
	});
	$('#left-side #location div.select select').selectbox({ className: 'custom-selectbox', animationSpeed: 'slow'});
}

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#header div.menu').removeClass('SetLocationExpanded');
			//$('div#set-location div.select select').parents('.jquery-selectbox').unselectbox();
		});
	}
	return;
}

function showSetLocation(){
	$('div#location').addClass('expanded');
	var height = $('div#set-location').height();
	$('div#header div.menu').addClass('SetLocationExpanded');
	$('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().toLowerCase().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().toLowerCase().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().toLowerCase().split("<option").length == 2 && $('select#set-location-submarket').html().toLowerCase().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');
	});
}
/********************************* End Set Location  ************************************/

/********************************* Start Customize Homepage  ************************************/

getUniqueId = function ()
{
     var dateObject = new Date();
     var uniqueId =
          dateObject.getFullYear() + '' +
          dateObject.getMonth() + '' +
          dateObject.getDate() + '' +
          dateObject.getTime();

     return uniqueId;
 };

 function createUUID() {
     var chars = '0123456789abcdef'.split('');

     var uuid = [], rnd = Math.random, r;
     uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
     uuid[14] = '4'; // version 4

     for (var i = 0; i < 36; i++) {
         if (!uuid[i]) {
             r = 0 | rnd() * 16;

             uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
         }
     }

     return uuid.join('');
 };

function initCustomizeHome() {
    if ($("div#customize a.drop").length == 0) return false; //exit if not the homepage
	if ($.cookie('LineUpID') == null) { $.cookie('LineUpID', '971', { expires: 365 }) };
	if ($.cookie('UserID') == null) { $.cookie('UserID', createUUID(), { expires: 365 }) };
	if ($.cookie('MyOnDemand_AssetsToShow') == null) { $.cookie('MyOnDemand_AssetsToShow', '5', { expires: 365 }) };

    var arrPods = new Array();
    var arrDefaultPods = CHCookieDefault.split(',');
                
    if ($.cookie('customizehomepage') == null) {
        $.cookie('customizehomepage', CHCookieDefault, { expires: 365 });
        arrPods = CHCookieDefault.split(',');
    } else {
        arrPods = $.cookie('customizehomepage').split(',');
        for (i=0;i<arrDefaultPods.length;i++) {
            var Found = false;
            for (j=0;j<arrPods.length;j++)  if (arrPods[j].split('-')[0] == arrDefaultPods[i].split('-')[0]) Found = true;
            if (!Found) arrPods.push(arrDefaultPods[i]);
            for (j=0;j<arrPods.length;j++) {
                if ((arrDefaultPods[i].split('-')[1] == '0') && (arrPods[j].split('-')[1] == '1') && (arrPods[j].split('-')[0] == arrDefaultPods[i].split('-')[0])) arrPods[j] = arrPods[j].split('-')[0] + '-0';
                if ((arrDefaultPods[i].split('-')[1] == '1') && (arrPods[j].split('-')[1] == '0') && (arrPods[j].split('-')[0] == arrDefaultPods[i].split('-')[0])) arrPods[j] = arrPods[j].split('-')[0] + '-1';  
            }    
        } 
    }   
    for(i = 0; i < arrPods.length; i++) {
        if ((arrPods[i].split('-')[1] == '1') || (arrPods[i].split('-')[1] == '3')) 
        {
            $('#chb'+arrPods[i].split('-')[0]).attr("checked", "checked");
            $('#r'+arrPods[i].split('-')[0]).parent().show();  
            $('#r'+arrPods[i].split('-')[0]).parent().addClass('isPYH');             
            $('#p'+arrPods[i].split('-')[0]).show();       
            $('#p'+arrPods[i].split('-')[0]).addClass('isPYH');                        
        }
    }  

    // 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('customizehomepage', CHCookieDefault, { expires: 365 });
        $('form#customize-home-form').submit();		
        return false;
    });
    // Submit customization form
    $('a#customization-save').click(function(){
        var CustCookie = new Array();
        $('form#customize-home-form input:checkbox').each(function(){
            CustCookie.push(this.value + '-' + ($(this).attr("checked") ? '1' : '0'));
        });
        var arrDefaultPods = CHCookieDefault.split(',');                
        for (j=0;j<CustCookie.length;j++)
            for (i=0;i<arrDefaultPods.length;i++) {
                if ((CustCookie[j].split('-')[1] == '0') && (CustCookie[j].split('-')[0] == arrDefaultPods[i].split('-')[0]) && (arrDefaultPods[i].split('-')[1] == '1')) CustCookie[j] = CustCookie[j].split('-')[0] + '-2'
                if ((CustCookie[j].split('-')[1] == '1') && (CustCookie[j].split('-')[0] == arrDefaultPods[i].split('-')[0]) && (arrDefaultPods[i].split('-')[1] == '0')) CustCookie[j] = CustCookie[j].split('-')[0] + '-3'
            }    

        $.cookie('customizehomepage', CustCookie.join(','), { expires: 365 });
        $('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(){ 
				$('.CustomizeHomeExpanded').removeClass('CustomizeHomeExpanded');
				animateCustomizeHome = false; 
			});
            return;
        } else {
            return;
        }
    }

    function showCustomizeHome(){
        if ( !animateCustomizeHome ){
            animateCustomizeHome = true;
            $('div#customize').addClass('expanded');
            $('div#location').addClass('expanded-customize');
			
			$('div#header div.menu').addClass('CustomizeHomeExpanded');
            var height = 408;
            $('div#customize-home').animate({ 'bottom': '-'+ height +'px' }, 'slow', function(){
	            $(this).css('z-index', 3);
	            animateCustomizeHome = false;
				
            });
            return;
        } else {
            return;
        }
    }

/********************************* End Customize Homepage  ************************************/



function initSliders(){
	var sliding = false;
	$('div.slider > div.pager > ul > li > a').unbind('click');

	$('div.slider > div.pager, 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;
var roll_over_movie_div_parent;

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, div#main div.side-box ul li div.expand div.next h6 a").hover(
				function(){
					roll_over_movie = true;
					roll_over_movie_div = $(this).nextAll('div.description-popup');
					if ($(this).parents('#right-side').size()) {roll_over_movie_div.addClass('right-popup');}
					hover_movie = true;
					//setTimeout("showDescription()", 300);
					showDescription(true);
				},
				function(){
					roll_over_movie_div.removeClass('right-popup');
					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);
				}
			});	
	$('div#main div#right-side ul li div.expand div.next h6 a').hover(function(){
					roll_over_movie = true;
					roll_over_movie_div = $(this).nextAll('div.description-popup');
					roll_over_movie_div.addClass('right-popup');
					hover_movie = true;
					//setTimeout("showDescription()", 300);
					showDescription(true);
				},
				function(){
					roll_over_movie_div.removeClass('right-popup');
					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-315);
				}
			});	
	$('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 );
		// Save the parent to allow us to restore the popup.
		//var roll_over_movie_div_parent = $(roll_over_movie_div).parent();
		//$(roll_over_movie_div).data('parent', roll_over_movie_div_parent);
        // Relocate the popup from it's container assocated with the
        // poster and move it to our container used when a popup is active.

        /*
		$('div#popup-description')
			.append($(roll_over_movie_div).clone())
			.css({ 'display': 'none' })
			.show(); */
		roll_over_movie_div_parent = $(roll_over_movie_div).parent();
        $('div#popup-description')
            .empty()
            .html('')
            .append( $(roll_over_movie_div) )
            .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 ){
	    // Relocate the popup back to it's orginal parent.
        // Hide the container used when popups are visible.

	    var x = $('div#popup-description').children();
	    roll_over_movie_div_parent.append(x);

        $('div#popup-description').empty().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">');
			$(this).find("> a.film img").css('right',25)
		}
	});
	
	
	$('div#main div.side-box ul a.film').click(function(){
		if($(this).parent('li').children('div.expand').get(0) ){
			$(this).toggleClass("open").parent('li').children('div.expand').slideToggle('slow');
			if ($(this).hasClass("open")) 
				$(this).parent('li').find('> a.add-video, > a.play-video').hide();
			else $(this).parent('li').find('> a.add-video, > a.play-video').show();

			return false;
			}
	});
	$('div#main div.side-box ul > li').each(function(){
		if($(this).children('div.expand').get(0)){
			$(this).find("> a.film").append('<div class="hassub">');
			$(this).find('> a.add-video, > a.play-video').hide();
		}
	});
}

function initMyodForm(){
	if ( $('div#myod').get(0) ){
		$('div#myod > div.myod-sorting > fieldset > ul > li > div.select > select').selectbox({ className: 'custom-selectbox', animationSpeed: 'medium'});
	}
	$('div.sort 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;
	});
}

function initSendPopup() {
    $('.send-popup div.form-item input[type=radio]').live('click', function() {
        var radio_id = $(this).attr('id');
        /*alert(radio_id);*/
        if (radio_id) {
            switch (radio_id) {
                case 'send-friend':
                    $('div.send-popup div.recipient-block').slideDown();
                    break;
                case 'send-yourself':
                    $('div.send-popup div.recipient-block').slideUp();
                    break;
            }
        }
    });

    $(window).scroll(function() {
        if ($('#shadow').length == 1) {
            var w = $(window).width();
            var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
            $('#shadow').css({ width: w, top: scrollTop, left: 0 });
        }
    });


    $('.send-popup div.form-buttons input.cancel').live('click', function() {
        $('#send-playlist').hide();
        $('#shadow').hide();
        $(".content").show();
        return false;
    })

    $('.send-popup div.form-buttons input.submit').live('click', function() {
        if ($('#send-playlist input#send-friend').attr('checked') && $('#send-playlist input#RecName').attr('value') == "") {
            ShowEmailMessage("Please enter Recipient's Name.");
            return false;
        }
        if ($('#send-playlist input#send-friend').attr('checked') && $('#send-playlist input#RecEmail').attr('value') == "") {
            ShowEmailMessage("Please enter Recipient's Email.");
            return false;
        }
        if ($('#send-playlist input#send-friend').attr('checked') && $('#send-playlist textarea#Message').attr('value') == "") {
            ShowEmailMessage("Please enter the message text.");
            return false;
        }
        if ($('#send-playlist input#YourName').attr('value') == "") {
            ShowEmailMessage("Please enter Your Name.");
            return false;
        }
        if ($('#send-playlist input#YourEmail').attr('value') == "") {
            ShowEmailMessage("Please enter Your Email.");
            return false;
        }

        $.ajax({
            type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: ServerPath + 'WebServices.asmx/SendToFriendEmail',
            data: "{ 'SendFriend': '" + $('#send-playlist input#send-friend').attr('checked') + "', " +
	                "'SendYourself': '" + $('#send-playlist input#send-yourself').attr('checked') + "', " +
	                "'RecName': '" + $('#send-playlist input#RecName').attr('value').replace("'", "~~") + "', " +
	                "'RecEmail': '" + $('#send-playlist input#RecEmail').attr('value') + "', " +
	                "'Message': '" + $('#send-playlist textarea#Message').attr('value').replace("'", "~~") + "', " +
	                "'YourName': '" + $('#send-playlist input#YourName').attr('value').replace("'", "~~") + "', " +
	                "'YourEmail': '" + $('#send-playlist input#YourEmail').attr('value') + "', " +
	                "'MesType': '" + $('#send-playlist input#MesType').attr('value') + "', " +
	                "'UserID': '" + $.cookie('UserID') + "', " +
	                "'IDs': '" + $('#send-playlist input#IDs').attr('value') + "' }",
            success: function(data) {
            ShowEmailMessage(data);
            $("#send-playlist input.text, #send-playlist textarea.text").val('');
                setTimeout(function() { $('#send-playlist').hide(); $('#shadow').hide(); }, 3500);
                /*      
                var recipe =  window.open('','RecipeWindow','width=1000,height=1000,scrollbars=yes');
                $('#recipe1').clone().appendTo('#myprintrecipe');
                recipe.document.open();
                recipe.document.write(data);
                recipe.document.close();*/

                return false;

            },
            error: function(xmlhttp) { alert('An AJAX ' + xmlhttp.status + ' error occured.\n' + xmlhttp.responseText); }
        });
        return false;
    })
};

function ShowEmailMessage(Text) {
    $('.send-popup div.form-message').html(Text).fadeIn('slow');
    setTimeout(function() { $('.send-popup div.form-message').fadeOut('slow'); $(".content").show(); }, 3000);
};  
  
/*
function initTabs(){
	$('div.sort div.select > select').selectbox({ className: 'custom-selectbox', animationSpeed: 'medium'});
	$('.tabs-wrapper').tabs({
	onHide: function() {
   if ($('ul.tabs-nav li:last').hasClass('tabs-selected')) {
	 	//alert(1);
	 	$('ul.tabs-nav li:last').prev().addClass('prev');
	 }
	 else $('ul.tabs-nav li').removeClass('prev');
   }
	});

};*/
