//swfobject config
swfobject.switchOffAutoHideShow();

function vimeo_player_loaded(swf_id) {
	moogaloop = document.getElementById(swf_id);
	
	moogaloop.api_addEventListener('onPlay', 'vimeo_play');
	moogaloop.api_addEventListener('onPause', 'vimeo_pause');
	moogaloop.api_addEventListener('onFinish', 'vimeo_finish');
	
	$.getJSON('http://vimeo.com/api/v2/video/' + swf_id.substr(6) + '.json?callback=?', function(data) {
		moogaloop.videoTitle = data[0].title;
	});
}

function vimeo_play(swf_id) {
	var moogaloop = document.getElementById(swf_id);
	if (typeof moogaloop.videoTitle != 'undefined') {
		//console.log('playing: ' + moogaloop.videoTitle);
		pageTracker._trackEvent('Vimeo Videos', 'Play', moogaloop.videoTitle);
	}
}

function vimeo_pause(swf_id) {
	var moogaloop = document.getElementById(swf_id);
	var secs = moogaloop.api_getCurrentTime();
	if (typeof moogaloop.videoTitle != 'undefined') {
		//console.log('pausing: ' + moogaloop.videoTitle + ' at ' + secs);
		pageTracker._trackEvent('Vimeo Videos', 'Pause', moogaloop.videoTitle, secs);
	}
}

function vimeo_finish(swf_id) {
	var moogaloop = document.getElementById(swf_id);
	if (typeof moogaloop.videoTitle != 'undefined') {
		//console.log('completed: ' + moogaloop.videoTitle);
		pageTracker._trackEvent('Vimeo Videos', 'Completed', moogaloop.videoTitle);
	}
}


function playVideo(clipID, replaceID, videoWidth){
	var replaceID = (typeof replaceID != 'undefined' ? replaceID : $('#videoswitcher-target object:first').attr('id'));
	var videoWidth = (typeof videoWidth != 'undefined' ? videoWidth : 503);
	
	var flashvars = {
        clip_id: clipID,
        show_portrait: 0,
        show_byline: 0,
        show_title: 0,
        color: '008ed6',
        fullscreen: 1,
		js_api: 1, // required in order to use the Javascript API
		js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
		js_swf_id: 'video-' + clipID // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
    };
	var params = {
		allowscriptaccess: 'always',
		allowfullscreen: 'true',
		wmode: 'transparent'
	};
	var attributes = { id: 'video-' + clipID };
	$('#' + replaceID).parent('div').removeClass('viddler');
	swfobject.embedSWF("http://vimeo.com/moogaloop.swf", replaceID, videoWidth, "292", "9.0.0","{site_url}flash/expressInstall.swf", flashvars, params, attributes);
}

var playingID = null;

var playStarted = function() {
	if (playingID != null) {
		var viddlerVideo = document.getElementById(playingID);
		var playtime = viddlerVideo.getCurrentTime();
		if (playtime == 0) {
			//console.log('Playback started: ' + viddlerVideo.videoTitle);
			pageTracker._trackEvent('Viddler Videos', 'Play', viddlerVideo.videoTitle);
		} else {
			pageTracker._trackEvent('Viddler Videos', 'Play Resumed', viddlerVideo.videoTitle, playtime);
		}
	}
}

var playEnded = function() {
	if (playingID != null) {
		var viddlerVideo = document.getElementById(playingID);
		pageTracker._trackEvent('Viddler Videos', 'Completed', viddlerVideo.videoTitle);
	}
}

function playViddler(videoCode, replaceID, videoWidth) {
	var replaceID = (typeof replaceID != 'undefined' ? replaceID : $('#videoswitcher-target object:first').attr('id'));
	var videoWidth = (typeof videoWidth != 'undefined' ? videoWidth : 503);
	
	var flashvars = {
        useJavaScript: 't',
        enablecallbacks: 't',
        autoplay: 't'
    };
	var params = {
		allowscriptaccess: 'always',
		allowfullscreen: 'true',
		wmode: 'transparent'
	};
	var attributes = { id: 'video-' + videoCode };
	var parent = $('#' + replaceID).parent('div');
	if (!parent.hasClass('viddler')) parent.addClass('viddler');
	
	// Setup variables for event tracking
	playingID = 'video-' + videoCode;
	
	swfobject.embedSWF("http://www.viddler.com/simple/" + videoCode + "/", replaceID, videoWidth, "303", "9.0.0","{site_url}flash/expressInstall.swf", flashvars, params, attributes);
	
	$.getJSON('/utils/viddler/fetch_details.php?id=' + videoCode, function(data) {
		document.getElementById(playingID).videoTitle = data.video.title;
	});
}

function playMP3(file, replaceID) {
	var flashvars = {
        wimpyApp: '',
        wimpyReg: 'N1AlNUNVWWlmNSU3RSU4MHglMjQlM0MlODElM0I5bFRtJTgxNEclM0RiJTVDJTdCJTNEVi1HSCU=1RHB4',
        wimpySkin: '/rave/skins/skin_audio.xml',
        startPlayingOnload: 'yes',
        startOnTrack: 1,
        autoAdvance: 'no',
        theVolume: 75,
        popUpHelp: 'no',
        debugMode: 'no',
        playlist: file
    };
	var params = {
		allowscriptaccess: 'always',
		loop: false,
		menu: false,
		quality: 'high',
		salign: 'lt',
		scale: 'noscale',
		bgcolor: '#e6e6e6'
	};
	var attributes = { id: replaceID };
	
	swfobject.embedSWF("/rave/rave.swf" + "?cachebust=" + new Date().getTime(), replaceID, 333, 37, "9.0.0","{site_url}flash/expressInstall.swf", flashvars, params, attributes);
}

function initDefaultInputValues(parent) {
	var parent = (typeof(parent) != 'undefined' ? parent : 'body');
	$(parent).find('input[type=text], textarea').each(function() {
		// Go through all textboxes and swap their contents intelligently
		var input = $(this);
		var title = input.attr('title');
		if (title != '' && (input.val() == '' || input.val() == title)) {
			input.val(title).addClass('unchanged');
			input.focus(function() {
				if (input.val() == title) {
					input.val('').removeClass('unchanged');
				}
			});
			input.blur(function() {
				if (input.val() == '') {
					input.val(title).addClass('unchanged');
				}
			});
			input.parents("form:first").submit(function() {
				if (input.val() == title) {
					input.val('');
				}
			});
		}
	});
}

// Handle pausing Flash videos and MP3s on Facebox close (since IE sucks at this)
$(document).bind('close.facebox', function() {
	var movie = $('#facebox object:first')[0];
	if (movie.js_wimpy_pause) {
		movie.js_wimpy_pause();
	} else if (movie.viddlerPause) {
		movie.viddlerPause();
	}
});

jQuery(document).ready(function($) {
	$('.ajax a[rel*=facebox]').each(function() {
		$(this).click(function() {
			var target = $(this).attr('href') + 'inline/';
			$.facebox({ ajax: target });
			return false;
		});
		$(this).attr('rel', '');
	});
	$('a[rel*=facebox]').each(function() {
		$(this).facebox();
	});
	$.facebox.settings.opacity = 0.1;
	initDefaultInputValues();
	
	$('#thumbnails li a').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).click(function() {
		$('#thumbnails li').each(function() { $(this).removeClass('active'); });
		$(this).parent('li:first').addClass('active');
		$('#detail').empty();
		$('#detail').load($(this).attr('href') + ' img');
		return false;
	});
	
	$('#trends li').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	$('#trends p, #trends h3').click(function(e) {
		e.stopPropagation();
		$(this).parents('li:first').find('a:first').trigger('click');
		return false;
	});
	
	$('.aggregate').change(function() {
		var result = '';
		$('.aggregate[name=' + $(this).attr('name') + ']').each(function(index, el) {
			if ($(this).val() !== '') {
				if (result === '') {
					result = $(el).val();
				} else {
					result += ('&' + $(this).val());
				}
			}
		});
		$('#aggregator-' + $(this).attr('name')).val(result);
	});
	
	if ($('.video-widget').length) {
		var total_vids = $('.video-widget li').length;
		var cur_vid = 1;
		
		$('#widget-right').click(function() {
			advance_video(1);
			return false;
		});
		$('#widget-left').click(function() {
			advance_video(-1);
			return false;
		});
	}
	
	function advance_video(increment) {
		var next = cur_vid + increment;
		if (next <= 0) {
			next = total_vids;
		} else if (next > total_vids) {
			next = 1;
		}
		$('#video-' + cur_vid).fadeOut();
		$('#video-' + next).fadeIn();
		cur_vid = next;
	}
	
	$('.videoswitcher').click(function() {
		playVideo($(this).attr('rel'));
		return false;
	});
	
	$('.viddlerswitcher').click(function() {
		playViddler($(this).attr('rel'));
		return false;
	});
	
	$('.req-js').show();
});