$j(document).ready(function() {
    
	// collect a couple re-used nodes
    movies_settingsDialog = $j('#settings-dialog');
    movies_settingsForm = $j('#settings-form');
    movies_settingsSaving = $j('#settings-saving');
	movies_trailer = $j('#movies_trailer');
	
	movies_adjust_num_thumb_pages();
	
	// set $j blockUI defaults
	$j.blockUI.defaults.fadeOut = 0;
	$j.blockUI.defaults.fadeIn = 0;
	$j.blockUI.defaults.message = movies_settingsDialog;
	$j.blockUI.defaults.css = {
        padding:0, 
        margin:0, 
        textAlign:'left',
        cursor:'default',
        border:'0px',
        backgroundColor:'transparent'
    };
	
	// bind hover actions for filter buttons
    $j('#settings-buttons .button').bind('mouseout', function(e) {
        $j(this).removeClass('over')
    });
    
    $j('#settings-buttons .button').bind('mouseover', function(e) {
        $j(this).addClass('over')
    });
});

var movies_savePrefsTimeout = null;
var movies_saving = false;
var movies_settingsDialog = null;
var movies_settingsForm = null;
var movies_settingsSaving = null;
var movies_overlayID = 'settings-overlay';
var movies_trailer = null;
var movies_trailerCSS = {};
var movies_toggleStates = {};
var movies_flashParams = {
	allowScriptAccess:'always',
	allowFullScreen:'true'
}
var movies_flashAttribs = {
	id:'movies_trailerSWFObject'
};
var movies_flashVars = {
	Mode:'ondemand',
	AutoPlay:'true',
	BufferTime:'1.5',
	VideoFit:'automatic',
	DefaultRatio:'1.333333',
	LogoPosition:'topleft',
	ColorBase:'#000000',
	ColorControl:'#e4e4e4',
	ColorHighlight:'#f4f4f4',
	ColorFeature:'#e4e4e4'
};

function movies_toggleRadio(radioID)
{
	var radio = $j('#' + radioID);
	radio.attr('checked', true);
}

function movies_toggleCheckbox(checkboxID)
{
	var checkbox = $j('#'+checkboxID);
	checkbox.attr('checked', !checkbox.attr('checked'));
}

function movies_checkAll(checkboxClass)
{
	if (!movies_toggleStates[checkboxClass])
	{
		movies_toggleStates[checkboxClass] = true;
	}
	else
	{
		movies_toggleStates[checkboxClass] = !movies_toggleStates[checkboxClass];
	}
	
	$j('#movies_checkAll_' + checkboxClass).attr('checked', movies_toggleStates[checkboxClass]);
	$j('input.' + checkboxClass).attr('checked', movies_toggleStates[checkboxClass]);
}

function movies_getCenteredPlacementCSS(object)
{
	var jqWind = $j(window);
	var windowWidth = jqWind.width();
    var windowHeight = jqWind.height();
	var objectWidth = object.width();
	var objectHeight = object.height();
	
	var x = (windowWidth/2 - objectWidth/2) + 'px';
    var y = (windowHeight/2 - objectHeight/2) + 'px';
	
	return {left:x, top:y};
}

function movies_showPreferences()
{
	var centeredCSS = movies_getCenteredPlacementCSS(movies_settingsDialog);
    $j.blockUI({css:centeredCSS});
	
	movies_settingsSaving.hide();
    movies_settingsForm.show();
}

function movies_closePreferences()
{
	if (movies_saving)
	{
		return;
	}
	
	$j.unblockUI();
}

function movies_savePreferences()
{
	// ensure at least one checkbox is selected
	if ($j('#settings-dialog input.checkbox:checked').length == 0)
	{
		alert("You need to select at least one theatre to continue.");
		return;
	}
	
	// save the settings
	movies_saving = true;
	
	// start a reload timer to ensure the user isn't stuck incase this 
	// takes too long
	movies_savePrefsTimeout = setTimeout(function() {
		window.location.reload();
	}, 5000);
	
	$j.ajax({
		type: 'POST',
		data: movies_settingsForm.serialize(),
		success: function() {
			
			// load the listings -- reset the paging counter
			movies_CURRENT_DATA['from'] = 0;
			movies_loadListings(movies_CURRENT_DATA);
			
			// reload the sidebar to match new settings
            $j.ajax({
		        type: 'POST',
		        data: 'action=getNavbar',
		        success: function(html) {
					
					// clear the reload timer
					clearInterval(movies_savePrefsTimeout);
					
					movies_saving = false;
					movies_closePreferences();
		            $j('#movies_navbar').html(html);
		        },
		        url: movies_AJAX
		    });
		},
		url: movies_AJAX
	});
	
	movies_settingsForm.hide();
	movies_settingsSaving.show();
}

function movies_toggleAll(className)
{
	$j(className).attr('checked', true);
}

function movies_processSelection(selectNode, name)
{
	var value = $j(selectNode).val();
	if (!value)
	{
		return;
	}
	
	if (name == 'theatre')
	{
		if (value == 'all')
		{
			movies_loadListings({'theatre':value});
		}
		else if (value == 'reponly')
		{
			document.location = movies_WEB_DOMAIN + '/rep_cinemas_toronto/';
		}
		else
		{
			document.location = movies_WEB_DOMAIN + '/' + value + '/';
		}
	}
	else if (name == 'movie')
	{
		if (value == 'all')
        {
            movies_loadListings({'movie':value});
        }
        else
        {
            document.location = movies_WEB_DOMAIN + '/?movie=' + value;
        }
	}
	else if (name == 'day')
	{
		movies_loadListings({'day':value});
	}
}

function movies_toggleView(node, viewType)
{
	$j('.movies_navbar_filterbutton').removeClass('on');
	$j(node).addClass('on');
	movies_loadListings({view:viewType}); 
}

function movies_loadListings(listingsData)
{
	if (!listingsData.theatre)
	{
		$j("#movies_select_theatre").val('Choose');
	}
	if (!listingsData.movie)
	{
		$j("#movies_select_movie").val('Choose');
	}
	
	$j('#movies_deeper_breadcrumb').prev().removeClass('category');
	$j('#movies_deeper_breadcrumb').remove();
	
	// update the current data
	movies_CURRENT_DATA = {};
	for (var i in listingsData)
    {
		movies_CURRENT_DATA[i] = listingsData[i];
    }
	
	listingsData['action'] = 'getListings';
	
    $j('#listings-loading').show();
	$j('#listings-content').hide();
	
	$j.ajax({
        type: 'POST',
        data: listingsData,
        success: function(html) {
			$j('#listings-loading').hide();
			$j('#movie_listings').html(html);
			
			movies_thumbs_currPage = 1;
			movies_adjust_num_thumb_pages();
		},
        url: movies_AJAX
    });
}

function movies_showTrailer(trailerURL, large)
{
	// removing old stale players if they exist
	if ($j('#' + movies_flashAttribs.id).length > 0)
	{
		swfobject.removeSWF(movies_flashAttribs.id);
	}
	
	// create a div wrapper for swfobject to replace
	$j('#movies_trailerSWF').html('<div id="'+movies_flashAttribs.id+'"></div>');
	
	// set the flashvars 'File' attribute to the trailer's URL
	movies_flashVars.File = trailerURL;
	
	var mediaplayer_url = movies_WEB_DOMAIN + '/swf/bitgravity/bitgravity_player_v6_1_0.swf';
//	var mediaplayer_url = 'http://bitcast-b.bitgravity.com/player/6/bitgravity_player_v6_1_0.swf';
    var expressInstall_url = movies_WEB_DOMAIN + '/swf/bitgravity/expressInstall.swf';
//	var expressInstall_url = 'http://bitcast-b.bitgravity.com/player/expressInstall.swf';
	
	var width = large ? 640 : 480;
	var height = large ? 480 : 360;
	
	height += 20; // compensate for the bitgravity player controls
	
	movies_trailer.css({'width':width,'height':height});
	movies_trailerCSS = movies_getCenteredPlacementCSS(movies_trailer);
	
	// embed the bitgravity player
	swfobject.embedSWF(
	   mediaplayer_url,
	   movies_flashAttribs.id,
	   width,
	   height,
	   "9.0.0",
       expressInstall_url,
	   movies_flashVars,
	   movies_flashParams,
	   movies_flashAttribs);
	
	// display it using the blockUI plugin
    $j.blockUI({css:movies_trailerCSS, message:movies_trailer});
}

function movies_closeTrailer()
{
	swfobject.removeSWF(movies_flashAttribs.id);
	$j.unblockUI();
}

var movies_thumbs_currPage = 1;
var movies_thumbs_lastPage = null;

function movies_thumbs_prev()
{
	movies_thumbs_go(movies_thumbs_currPage - 1);
}

function movies_thumbs_next()
{
	movies_thumbs_go(movies_thumbs_currPage + 1);
}

function movies_thumbs_last()
{
	movies_thumbs_go(movies_thumbs_lastPage);
}

function movies_thumbs_go(page)
{
	if (page == movies_thumbs_currPage || page < 1 || page > movies_thumbs_lastPage)
	{
		return;
	}
	
	$j('#movies_pagingbutton_'+page).addClass('selected');
	$j('#movies_pagingbutton_'+movies_thumbs_currPage).removeClass('selected');
	
    $j('#movies_thumbs_scroller').animate({left:((page - 1) * 900) * -1});
	
	movies_thumbs_currPage = page;
}

function movies_adjust_num_thumb_pages()
{
	movies_thumbs_lastPage = $j('#movies_thumbs_scroller div.movie_thumbs_set').length;
}
