// (C) ScreenTunes.com - All Rights Reserved
function $(el) { return document.getElementById(el); }
function hover(el, modal) {
	if(!modal) {
		if(el.id.substr(5) != mode) {
			el.src=el.src.replace(/\.png/, '_h.png');
		}
	} else {
		if(el.id.substr(6) != tab) {
			el.src=el.src.replace(/\.png/, '_h.png');
		}
	}
}
function unhover(el, modal) {
	if(!modal) {
		if(el.id.substr(5) != mode) {
			el.src=el.src.replace(/_h\.png/, '.png');
		}
	} else {
		if(el.id.substr(6) != tab) {
			el.src=el.src.replace(/_h\.png/, '.png');
		}
	}
}
var mode = 'title';
function setMode(val) {
	mode = val;
	$('mode_movie').src='http://www.screentunes.com/images/mode_movie.png';
	$('mode_artist').src='http://www.screentunes.com/images/mode_artist.png';
	$('mode_title').src='http://www.screentunes.com/images/mode_title.png';
	$('mode_lyrics').src='http://www.screentunes.com/images/mode_lyrics.png';
	$('mode_'+val).src='http://www.screentunes.com/images/mode_'+val+'_h.png';
}
var tab = 'movie';
function setTab(val, title) {
	tab = val;
	$('modal_movie').src='http://www.screentunes.com/images/modal_movie.png';
	$('modal_tv').src='http://www.screentunes.com/images/modal_tv.png';
	$('modal_song').src='http://www.screentunes.com/images/modal_song.png';
	$('modal_contact').src='http://www.screentunes.com/images/modal_contact.png';
	if(val != 'song' && val != 'welcome' && val != 'contact' && val != 'msg') { $('modal_'+val).src='http://www.screentunes.com/images/modal_'+val+'_h.png'; }
	$('modal_movie_content').className='hide';
	$('modal_tv_content').className='hide';
	$('modal_song_content').className='hide';
	$('modal_welcome_content').className='hide';
	$('modal_contact_content').className='hide';
	$('modal_'+val+'_content').className='';
	var modeText = val == 'movie' ? 'movie' : 'TV show';
	$('modal_mode').innerHTML = 'Click on a '+modeText+' to see it\'s soundtrack.';
	if(val == 'song') { $('modal_mode').innerHTML = 'Click on a song to see what movies &amp; shows it has been in.'; }
	if(val == 'welcome') { $('modal_mode').innerHTML = 'Coming from Facebook?'; }
	if(val == 'contact') { $('modal_mode').innerHTML = 'Shoot us a message - we\'ll get back to you shortly!'; }
	if(val == 'msg') { $('modal_mode').innerHTML = title; }
}
var activated = false;
function cleaner() {
	if($('input').defaultValue == $('input').value) { $('input').value = ""; }
	activated = true;
}
groove_on = false;
function modal(force) {
	if(!force) { $('modal').style.display = $('modal').style.display == 'block' ? 'none' : 'block'; }
	else { $('modal').style.display = force; }
	if($('modal').style.display == 'block' && $('modal').offsetHeight > 150) { 
		$('player').style.top = '-1000px'; 
		if(groove_on) {
			$('groover').style.display = 'block';
		}
	}
	else { $('player').style.top = '15px'; $('groover').style.display = 'none'; }
}
function email(to, type) {
	$('modal_welcome').className = 'left cap hide';
	$('modal_song').className = 'left cap hide';
	$('modal_movie').className = 'left cap hide';
	$('modal_contact').className = 'left cap';
	$('modal_tv').className = 'hide';
	$('mail_to').value = to+'@screentunes.com';
	$('mail_type').value = type;
	setTab('contact');
	modal('block');
}
function sendMail() {
	jx.load('http://www.screentunes.com/engine/contact.php?to='+$('mail_to').value+'&from='+$('mail_from').value+'&name='+$('mail_name').value+'&type='+$('mail_type').value+'&subject='+$('mail_subject').value+'&body='+$('mail_body').value,function(data) {
		if(data == '1') { var msg = 'Your message got to us - we\'ll respond as soon as possible.'; }
							 else { var msg = data; }
		$('modal_msg_content').innerHTML = msg;
		setTab('msg', 'Thanks!');
	}, 'text', 'post');
}
function catchkey(e) {
	var keyid = (window.event) ? event.keyCode : e.keyCode;
	switch(keyid)   { 
		case 13: send();
		break;
	}
}
function fbFan(result) {
	if(arguments.length == 0) {
		jx.load('http://www.screentunes.com/fb/php/index.php',function(data){	
			fbFan(data);
		});
	} else {
		return result;
	}
}
function listen(title) {
	jx.load('http://www.screentunes.com/engine/search.php?mode=groove&q='+title,function(data){		
		$('player').innerHTML = data;
		groove_on = true;
	});
}
function buy(title, store) {
	var ret = null;
	jx.load('http://www.screentunes.com/engine/go.php?bounce=true&method='+store.toLowerCase()+'&q='+title,function(data){
		if(data == 'nlf;' && store != 'Amazon') {
			alert("Sorry, this song is not available in the "+store+" library.");
		} else {
			window.open('/engine/go.php?method='+store.toLowerCase()+'&q='+title, '_blank');
		}
	});
}
function research(q, type) {
	modal();
	q = unescape(q.replace(/\+/g,' '));
	$('input').value = q;
	setMode(type);
	send();
}
jQuery('.pages .tab').live('click', function() {
	setMode(last[0]);
	send(last[1],last[2],jQuery(this).find('span').html(),last[3]);
});
var last = new Array();
var page = new String();
function send(force, ref, page, fquery) {
	if($('modal').style.display == 'block') { modal(); }
	if((!activated && $('input').value == 'Enter a song name, lyric, or movie here') || $('input').value == '') {
		alert('Enter some search terms first!');
		return false;
	}
	if(ref == 'singback') {
		$('input').value = unescape(force);
		var smode = 'title';
	} else {
		$('credit').innerHTML = ref ? ref.innerHTML : '';
		var smode = force ? 'soundtrack' : mode;
	}
	var el = $('search_button');
	var query = force ? force : $('input').value;
	if(smode == 'artist') {
		wmode = 'Artist';
		smode = 'title';
		query = '{Artist: '+query+'}';
	} else {
		wmode = false;
	}
	spage = page ? '&pg='+page : '';
	el.src = 'http://www.screentunes.com/images/searching.gif';
	if(fquery) { query = fquery; }
	last = Array(mode,force,ref,query);
	jx.load('http://www.screentunes.com/engine/search.php?mode='+smode+spage+'&q='+query,function(data){
		if(cresult = data.match(/^<pages>(\d*)<\/pages>/)) {
			page = page > 1 ? page : 1;
			var pages = (cresult[1]%10 != 0)+Math.floor(cresult[1]/10);
			var tabs = '';
			for(i=1;i<=pages&&i<=25;i++) {
				var h = i == page ? ' h' : '';
				tabs = tabs+'<span class="tab'+h+'"><span>'+i+'</span><div><div></div></div></span>';
			}
			data = data.substring(15+cresult[1].toString().length);
			jQuery('.pages').html(tabs).show();
		} else {
			jQuery('.pages').hide();
		}
		if(smode == 'movie') {
			track('Movie Search', new Array("query:"+query));
			data = json_parse(data);
			if(data) {
				tvi = 1;
				mvi = 1;
				for(i=0;i<data.length;i++) {
					if(data[i].tv == "1") {
						epihtml = data[i].episode.length ? "<br /><i>&raquo; "+data[i].episode.substring(1,data[i].episode.length-1)+"</i>" : "";
						if(tvret)	{ tvret += "<br />"+tvi+'. <a onclick="send(\''+escape(data[i].title)+'\', this)">'+data[i].title+' ('+data[i].year+')'+epihtml+'</a><br />'; }
						else { var tvret = tvi+'. <a onclick="send(\''+escape(data[i].title)+'\', this)">'+data[i].title+' ('+data[i].year+')'+epihtml+'</a><br />'; }
						tvi++;
					} else {
						if(ret)	{ ret += "<br />"+mvi+'. <a onclick="send(\''+escape(data[i].title)+'\', this)">'+data[i].title+' ('+data[i].year+')</a><br />'; }
						else { var ret = mvi+'. <a onclick="send(\''+escape(data[i].title)+'\', this)">'+data[i].title+' ('+data[i].year+')</a><br />'; }
						mvi++;
					}
				}
			}
			if(!ret) { var ret = '<center><b>No Movies Found</b></center>'; }
			if(!tvret) { var tvret = '<center><b>No TV Shows Found</b></center>'; }
			$('modal_movie_content').innerHTML = ret;
			$('modal_tv_content').innerHTML = tvret;
			el.src = 'http://www.screentunes.com/images/search.png';
			$('modal_welcome').className = 'left cap hide';
			$('modal_contact').className = 'left cap hide';
			$('modal_song').className = 'left cap hide';
			$('modal_movie').className = 'left cap';
			$('modal_tv').className = '';
			tab = 'song' ? setTab('movie') : setTab(tab);
			modal('block');
		} else if(smode == 'lyrics') {
			track('Lyrics Search', new Array("query:"+query));
			data = json_parse(data);
			if(data) {
				for(i=0;i<data.length;i++) {
						var clearArtist = escape(data[i].artist.replace(/&#039;/g,'\\\''));
						var clearSong = escape(data[i].song.replace(/&#039;/g,'\\\''))+' {artist: '+clearArtist+'}';
						if(ret)	{ ret += "<br />"+(i+1)+'. <a onclick="send(\''+clearSong+'\', \'singback\')"><b>'+data[i].artist+'</b> - '+data[i].song+'</a><br />'; }
							 else { var ret = (i+1)+'. <a onclick="send(\''+clearSong+'\', \'singback\')"><b>'+data[i].artist+'</b> - '+data[i].song+'</a><br />'; }
				}
			}
			if(!ret) { var ret = '<div align="center"><b>No Songs Found</b></div>'; }
					else { ret += '<br /><div align="center">Lyrics Search Powered by <a href="http://www.lyricsfly.com" target="_blank">LyricsFly</a></div>'; }
			$('modal_song_content').innerHTML = ret;
			el.src = 'http://www.screentunes.com/images/search.png';
			$('modal_welcome').className = 'left cap hide';
			$('modal_contact').className = 'left cap hide';
			$('modal_song').className = 'left cap';
			$('modal_movie').className = 'left cap hide';
			$('modal_tv').className = 'hide';
			setTab('song');
			modal('block');
		} else {
			wtype = smode == 'soundtrack' ? 'Soundtrack' : 'Song';
			if(wtype == 'Soundtrack') { 
				query = unescape(query);
			} else if(wmode == 'Artist') {
				wtype = wmode;
				query = query.substring(8,query.length-1);
			}
			track(wtype+' Search', new Array("page:"+page,"query:"+query));
			$('results').innerHTML = data;
			$('results').style.paddingBottom = '127px';
			$('footer').style.paddingTop = '102px';
			$('footer').style.backgroundImage = 'url(../images/footer_bg.png)';
			$('footer').style.backgroundRepeat = 'repeat-x';
			el.src = 'http://www.screentunes.com/images/search.png';
			$('stripe').style.display = 'block';
			$('pages').style.display = 'block';
			$('results').style.display = 'block';
		}
	},'text');
}
function helper() {
	var help = $('box_help');
	var ads = $('box_ads');
	if(help.style.display == 'block') {
		help.style.display = 'none';
		ads.style.display = 'block';
	} else {
		help.style.display = 'block';
		ads.style.display = 'none';
	}
}
function linker(title,content) {
	this.title = title;
	this.content = content;
}
var pop_about	= new linker('About Us', '<div class=\'about\'>ScreenTunes.com is a free site built to help you find out which movie you might have heard a particular song in. Or, if you heard a song in a movie recently but didn\'t know the name, you can find that too. So basically, go tell your friends.</div>');
var pop_contact = new linker('Contact Us', 'Errors, Bugs, Feedback, etc:<br /><div class=\'divline\'><a class=\'email\' onclick=\'email("webmaster", "Feedback")\'>webmaster<span class=\'breaker\'>@</span>screentunes.com</a></div>Advertisement Queries:<br /><div class=\'divline\'><a class=\'email\' onclick=\'email("advertise", "Ad Query")\'>advertise<span class=\'breaker\'>@</span>screentunes.com</a></div><center><i>English only please!</i></center>');
var pop_credits = new linker('Thank you to...', 'The Internet Movie Database (IMDB)<div class=\'divline\'>Soundtrack &amp; movie data</div>LyricsFly<div class=\'divline\'>Lyric data</div><center><i>And of course Leda, for the idea</i> :)</center>');
var pop_develop	= new linker('API', '<div class=\'about\'>We offer a basic data feed for developers wishing to add our service to their application or site. We also provide a ready-to-use widget that you can plug into your site. See the docs for more info:</div><center><a href="http://www.screentunes.com/api.html">Widget &amp; API Documentation</a></center>');
var pop_press = new linker('Press Resources', '<div class=\'about\'>Want to spread the word? We are always happy to work with anyone wishing to blog, write, or just yell about ScreenTunes. Many resources are available for journalists in our online media kit:</div><center><a href="http://www.screentunes.com/press.html">Media Kit</a></center>');
var pop_privacy = new linker('Privacy Policy', '<div class=\'about\'>ScreenTunes does not collect information about you. We do not share data about you with anyone. That\'s all. If you want to see the legal stuff, please read the not-so-fine print: </div><br/><center><a href=\'http://www.screentunes.com/privacy.html\'>Full Privacy Policy</a></center>');
var pop_staff = new linker('Staff', 'Cecchi MacNaughton - <i>Webmaster</i><div class=\'divline\'><a class=\'email\' onclick=\'email("cecchi", "Feedback")\'>cecchi<span class=\'breaker\'>@</span>screentunes.com</a></div>Lucy Arnold - <i>Head of Operations</i><div class=\'divline\'><a class=\'email\' onclick=\'email("lucy", "Feedback")\'>lucy<span class=\'breaker\'>@</span>screentunes.com</a></div><center><i>We keep it small.</i></center>');
var cur_pop = null;
function popup(el) {
	if(cur_pop == el.id) { 
		$('popup').style.display = 'none';
		cur_pop = null;
		el.className = '';
	} else {
		var links = document.getElementsByTagName('a');
		for(i=0;i<links.length;i++) {
			if(links[i].className == 'selected') { links[i].className = ''; }
		}
		el.className = 'selected';
		var isnull = cur_pop == null ? true : false;
		cur_pop = el.id;
		$('p_title').innerHTML = eval(el.id+'.title');
		$('p_content').innerHTML = eval(el.id+'.content');
		$('popup').style.marginLeft = Math.round($(el.id).offsetWidth/2+$(el.id).offsetLeft+15-153)+'px';
		$('popup').style.display = 'block';
	}
}
function preload() {
	if(document.images) {
		phead = new Image(5,275); 
		phead.src="images/pop_head.png"; 
		pbody = new Image(119,275);
		pbody.src="images/pop_body.png";
		pfoot = new Image(16,275);
		pfoot.src="images/pop_foot.png";
	}
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
function fbwelcome() {
	if(fb) {
		if(!readCookie('screentunes_fb')) {
			createCookie('screentunes_fb','true',365);
			FB.init('ca6314182f20a7583c93e905f206da3b');
			$('fanbox').innerHTML = '<fb:fan profile_id="101963718021" stream="" connections="7" height="180" width="410"></fb:fan>';
			$('modal_welcome').className = 'left cap';
			$('modal_song').className = 'left cap hide';
			$('modal_movie').className = 'left cap hide';
			$('modal_contact').className = 'left cap hide';
			$('modal_tv').className = 'hide';
			setTab('welcome');
			modal('block');
		}
	}
}
function direct() {
	var path = window.location.pathname;
	var dstr = path.match(/^\/(s|l|m|a)\/(.*)/);
	if(dstr) {
		switch(dstr[1]) {
			case 's':
				dmode = 'title';
				break;
			case 'l':
				dmode = 'lyrics';
				break;
			case 'm':
				dmode = 'movie';
				break;
			case 'a':
				dmode = 'artist';
				break;
		}
		research(dstr[2],dmode);
	}
}
function track(title, properties) {
	var w_event = new WoopraEvent(title);
	for(i=0;i<properties.length;i++) {
		var colon = properties[i].search(":");
		var pkey = properties[i].substring(0,colon);
		var pval = properties[i].substring(colon+1);
		w_event.addProperty(pkey, pval);
	}
	w_event.fire();
}
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(direct);
addLoadEvent(preload);
addLoadEvent(fbwelcome);

function timeloop(id) {
	var player = $f("stream_"+id);
	if(player.getState() != 4 && player.getState() != -1) {
		jQuery('#sampler_'+id+' .playpause').addClass('pause');
		jQuery('#sampler_'+id+' .track').slideDown();
		seek(player.getTime(), id);
		setTimeout("timeloop("+id+")", 150);
	}
}
function seek(sec, id) {
	var wid = 115;
	var per = sec/30;
	var pix = per*wid;
	jQuery('#sampler_'+id+' .progress.left').css('width', (pix)+'px');
	jQuery('#sampler_'+id+' .progress.right').css('width', (wid-pix-6)+'px');
}
jQuery(document).ready(function() {
	jQuery('.playpause').live('click', function() {
		var id = jQuery(this).parent().parent().attr('id').substr(8);
		if(!$f("stream_"+id)) {
			$f("*").each(function() {
				this.unload();
			});
			$f("stream_"+id, "http://releases.flowplayer.org/swf/flowplayer-3.1.5.swf", { 
					onLoad: function() { 
						this.setVolume(100);
						this.play();
					},
					onBegin: function() { timeloop(id); },
					onResume: function() { timeloop(id); },
					onPause: function() { jQuery('#sampler_'+id+' .playpause').removeClass('pause'); },
					onFinish: function() { this.unload(); },
					onUnload: function() {
						jQuery('#sampler_'+id+' .playpause').removeClass('pause');
						jQuery('#sampler_'+id+' .track').slideUp();
					},
					canvas: { backgroundGradient: 'none' },
					plugins: { 
							rtmp: { 
									url: 'flowplayer.rtmp-3.1.3.swf', 
									netConnectionUrl: 'rtmp://DMUS.flash-ie.musicnet.com:80/Sample',
									durationFunc: 'getStreamLength' 
							}, 
							controls: null
					}, 
					clip: { 
							provider: 'rtmp', 
							autoPlay: false,
							bufferLength: 1
					} 
			});
		} else {
			var player = $f("stream_"+id);
			if(player.getState() == 3) { 
				player.pause();
			} else {
				player.play();
			}
		}
	});
	jQuery('.track').live('click', function(e) {
		var id = jQuery(this).parent().parent().attr('id').substr(8);
		if($f("stream_"+id)) {
			var player = $f("stream_"+id);
			var clickx = e.pageX
			var trackx = jQuery(this).offset().left+4;
			var spread = clickx-trackx;
			var wid = 115;
			var per = spread/wid;
			var sec = per*30;
			seek(sec, id);
			player.seek(sec);
		}
	});
});