
var forwardingFromAction = get_cookie('forwardingFromAction');
var postLoginAction = get_cookie('postLoginAction');
var referringPage = get_cookie('referringPage');
var enteringContest = get_cookie('enteringContest');
var winScroller;

window.addEvents({
			  
	'domready': function(){
		winScroller = new Fx.Scroll(window, { 'duration': 750 });
				
		if(forwardingFromAction){
			var action = get_cookie('postLoginAction');

			if(action)
			{		
				if(action.indexOf('|') != -1)
					var actionParts = action.split('|');
				else
					actionParts[0] = action;
				
				// REMOVE THE ONES THAT WON'T BE NECESSARY 
				// IF DJ ACTIONS ARE ONLY ON DJ PAGES
				
				switch (actionParts[0]){
					
					case "listenHeart":
						window.location.href = "/listen?track_id="+actionParts[1];
						break;
					
					case "listenFacebook":
						window.location.href = "/listen?track_id="+actionParts[1];
						break;
					
					/**************************************
					case "voteFacebook":
						window.location.href = "/dj/"+actionParts[1]+"/"+actionParts[2];
						break;
					
					case "djTrackFacebook":
						window.location.href = "/dj/"+actionParts[1]+"/"+actionParts[2];
						break;
					
					case "djFacebook":
						window.location.href = "/dj/"+actionParts[1]+"/"+actionParts[2];
						break;
					
					case "voteTwitter":
						window.location.href = "/dj/"+actionParts[1]+"/"+actionParts[2];
						break;						
					******************************************/
					case "loginRequired":
						window.location.href = actionParts[1];
						break;
				}
			}
		 	
			delete_cookie('forwardingFromAction');
			
		}
		
		setOverText();
		
	},
	'load': function(){
		
		if(get_cookie('postLoginAction')){
				
			var action = get_cookie('postLoginAction');

			if(action)
			{		
				var actionParts = action.split('|');
				
				switch (actionParts[0]){
						
					case "listenHeart":
						listen_heart(actionParts[1]);
						break;
					
					case "listenFacebook":
						listen_facebook_share(actionParts[1]);
						break;
					
					case "voteFacebook":
						contest_facebook_share(actionParts[1], actionParts[2]);
						break;
						
					case "djTrackFacebook":
						dj_track_share(actionParts[1], actionParts[2]);
						break;
					
					case "voteTwitter":
						contest_twitter_share(actionParts[1], actionParts[2]);
						break;						
				}


				delete_cookie('postLoginAction');
				postLoginAction = null;		
			}
		}
	}
	
})

// DONE
function listen_heart(track_id)
{
	if(logged_in)
	{
		var request = new Request({
			url: "/listen/heart_track",
			method: 'get',
			useSpinner: true,
			evalResponse: 'true'
		}).send('user_id='+logged_in+'&track_id='+track_id);
	}
	else
	{
		set_cookie('postLoginAction', "listenHeart|"+track_id);
		set_cookie('forwardingFromAction', 'listen_heart');
		
		//alert('listen_heart');
		//FB.Connect.requireSession();
		signupOrLogin();		
	}		
}

// FACEBOOK SHARE FROM MUSIC DISCOVERY SYSTEM
function listen_facebook_share(track_id)
{
	if(logged_in)
	{	
		var url = "/listen/share_track";
		var request = new Request({
			url: url,
			method: 'get',
			evalResponse: 'true'
		}).send('user_id='+logged_in+'&track_id='+track_id);
	}
	else
	{
		set_cookie('postLoginAction', "listenFacebook|"+track_id);
		set_cookie('forwardingFromAction', 'listen_facebook_share');
		//alert('listen_facebook_share');
		//FB.Connect.requireSession();

		signupOrLogin();		
	}		
}

// SHARE TRACK (contest = true for contest tracks)
function mixTrack(track_id)
{
	if(logged_in)
	{
		/*******************
		new Popup({
			'heading': 'Coming Soon',
			'message': 'More features are coming your way, stay tuned.',
			'autoClose': true
		}).show();
		*******************/
		
		var url = "/listen/share_track";
		var request = new Request({
			url: url,
			method: 'get',
			evalResponse: 'true'
		}).send('user_id='+logged_in+'&track_id='+track_id);
		
		location.href = "/audiodjx";
	}
	else
	{
		//FB.Connect.requireSession();
		signupOrLogin();		
	}		
}


function contest_like_roosevelt(track_id)
{
	if(logged_in)
	{	
		var request = new Request({
			url: "/facebook/vote_like_roosevelt",
			method: 'get',
			evalResponse: true
		}).send('contest_track_id='+track_id);
	}	
}

function contest_facebook_share(artist_name, track_id)
{
	if(logged_in)
	{	
		var request = new Request({
			url: "/facebook/share_contest_track",
			method: 'get',
			evalResponse: true
		}).send('contest_track_id='+track_id);
	}
	else		
	{
		set_cookie('postLoginAction', "voteFacebook|"+artist_name+"|"+track_id);
		set_cookie('forwardingFromAction', 'contest_facebook_share');
		
		//alert('contest_facebook_share');
		//FB.Connect.requireSession();

		signupOrLogin();
	} 	
}


function contest_twitter_share(artist_name, track_id)
{
	if(logged_in)
	{	
		var request = new Request({
			url: "/twitter/share_contest_track",
			method: 'get',
			evalResponse: true
		}).send('contest_track_id='+track_id);
	}
	else		
	{
		set_cookie('postLoginAction', "voteTwitter|"+artist_name+"|"+track_id);
		set_cookie('forwardingFromAction', 'voteTwitter');
		//alert('contest_facebook_share');
		//FB.Connect.requireSession();
		signupOrLogin();		
	}
}


function dj_track_share(dj, track_id)
{
	if(logged_in)
	{	
		var request = new Request({
			url: "/facebook/dj_track_share",
			method: 'get',
			evalResponse: true
		}).send('track_id='+track_id);
	}
	else		
	{
		set_cookie('postLoginAction', "djTrackFacebook|"+dj+"|"+track_id);
		set_cookie('forwardingFromAction', 'dj_track_share');
		
		//alert('dj_track_share');
		signupOrLogin();
	}	
}


function signupOrLogin()
{
	new Popup({
				'heading': 'Log In Required',
				'message': '<h3>Log In with Facebook Connect</h3><p>Great, you\'re ready to get in the competition. Now all you need to do is <a href="/member/signup">sign-up</a> or <a href="'+login_url+'">log in</a> using Facebook Connect and you\'re all set!</p>',
				'confirmBtnText': 'Log In Now!',
				'onConfirm': function(){
					location.href = login_url;
				}
			}).show();
}

function earnpointsContestTrack(track_id, user_id)
{
	if(user_id == "" || user_id == "undefined" || user_id == undefined)
	{
		new Popup({
			'message': '<h3>Log In with Facebook Connect</h3><p>Great, you\'re ready to get in the competition. Now all you need to do is log in using Facebook Connect and you\'re all set!</p>',
			'confirmBtnText': 'Log In Now!',
			'onConfirm': function(){
				location.href = login_url;
			}
		});
	}
	else		
	{	
		location.href = '/super-rewards/earn_points/' + track_id;
		//$.fn.colorbox({'href':'/super-rewards/earn_points/'+track_id+'/', 'open':true, 'iframe':true, 'width': '90%', 'height': '90%'});
	}	
}

function search_form()
{
	var artist_name = $("artist_name").get('value');		
	var new_name = "";
	
	if(artist_name.match(/^[ ]*$/))
	{
		return false;
	}
	
	for (i=0; i < artist_name.length; i++)
	{
		if(artist_name.charAt(i) == " ")
			new_name += "-";				
		else
			new_name += artist_name.charAt(i);	
	}
	location.href= '/listen/artist/'+new_name;	
}

// FOR SWITCHING TABS
function tab_switcher(parent, name)
{
	var tabs = $$('#'+$(parent).id+' .tab');
	var containers = $$('#'+$(parent).id+' .tab_container');
	
	//if the tab is already active do nothing
	if($('tab_'+name).hasClass('active'))
		return false;
		
	//remove the active class and add it to the new tab
	tabs.each(function(tab){
		if(tab.hasClass('active')){
			tab.removeClass('active');
			tab.addClass('inactive');
		}
		if(tab.id == 'tab_'+name){
			tab.removeClass('inactive');
			tab.addClass('active');
		}
	});
		
	//hide the previous container and show the new one
	containers.each(function(container){
		if(container.getStyle('display') != 'none'){
			container.setStyle('display', 'none');
			container.fade('out');	
		}
		if(container.id == 'tab_container_'+name){
			container.setStyles({
				'opacity': 0,
				'display': 'block'
			});
			container.fade('in');
		}
	});
}

function show_activate_popup(is_contest, url)
{
	new Popup({
		'type': 'confirm',
		'confirmBtnText': 'Log In',
		'cancelBtnText': 'Cancel',
		'heading': 'Log In Required',
		'message': 'In order to successfully activate your account for the contest you must log in.',
		'onConfirm': function(){
			location.href = login_url;
		}
	}).show();
}

function show_feature_login_popup(is_contest, url)
{
	new Popup({
		'type': 'confirm',
		'confirmBtnText': 'Log In',
		'cancelBtnText': 'Cancel',
		'heading': 'Log In Features',
		'message': 'Logging in through Facebook allows you to add songs to your favourites, vote for your favourite DJ and many other things. Are you ready to log in now?',
		'onConfirm': function(){
			location.href = login_url;
		}
	}).show();
}

function load_track_page(element, url, page, play)
{
	new Request.HTML({
		update: element,
		url: url,
		useSpinner: true,
		evalScripts: true,
		evalResponse: true,
		'onSuccess': function(){
			handle_page_change(page, play);
		}
	}).post({'play': play});
}

function load_leader_page(element, url, page)
{
	new Request.HTML({
		update: element,
		url: url,
		useSpinner: true,
		evalScripts: true,
		evalResponse: true,
		'onSuccess': function(){
			// SINCE THIS IS AN AJAX CALLED PAGE WE HAVE TO RE-PARSE FOR XFBML ELEMENTS (PROFILE PHOTOS)
			if ( FB.XFBML.Host.parseDomTree )
				setTimeout( FB.XFBML.Host.parseDomTree, 100 );
		}
	}).send();
}

function show_terms()
{
	new Popup({
		'type': 'ajax',
		'heading': 'Contest Terms &amp Conditions',
		'url': '/site/contest-rules/?popup=true',
		'width': 720
	}).show();
}

function show_battle_terms()
{
	new Popup({
		'type': 'ajax',
		'heading': 'Contest Terms &amp Conditions',
		'url': '/site/battle-rules/?popup=true',
		'width': 720
	}).show();
}

function set_cookie(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 get_cookie(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 delete_cookie(name)
{
	set_cookie(name,"",-1);
}

String.implement({
	phone: function() {
		var newphone = this.replace(/[^\d]/g, "");
		var phonematches = newphone.match(/^(\d{0,3})(\d{0,3})(\d{0,4})/);
		if (phonematches[1].length > 0){
			newphone = "(" + phonematches[1];
		}
		if (phonematches[1].length == 3){
		  newphone += ") " + phonematches[2];
		  if (phonematches[2].length == 3){
		    newphone += "-" + phonematches[3];
		  }
		}
		return newphone;
	},
	numeric: function() {
		var numeric = this.replace(/[^\d]/g, "");
		return numeric;
	},
	alpha: function() {
		var alpha = this.replace(/[^0-9.,]/g, "");
		return alpha;
	},
	alphanumeric: function() {
		var alpha = this.replace(/\W/, "");
		return alpha;
	}
});

function remove_notice(id)
{
	new Request({
		url: "/user/mark_notice",
		onComplete: function(response){
			var notices_count = $('my_account_notice').get('text').toInt() -1;
			if(notices_count > 0){
				if(notices_count >1)
					$('my_account_notice').set('text', notices_count+' Notices');
				else
					$('my_account_notice').set('text', '1 Notice');
			}
			
			var outfx = new Fx.Tween($('notice_'+response),{
				duration: 1000,
				onComplete: function(){
					$('notice_'+response).destroy();
					if(notices_count == 0){
						$('my_account_notice').destroy();
						$('notices_box').destroy();
					}
				}
			});
			outfx.start('opacity', 0);
			
		}
	}).post({'id': id});
}

function show_vote_embed_code(id)
{
	new Popup({
		'width': 700,
		'heading': 'PromoteDJ Widget',
		'message': '<div style="float: left; width: 380px"><h3>More ways to promote!</h3><p>Now promoting your favourite track is even easier than ever before. Introducing the <strong>Audio Academy PromoteDJ Widget</strong>. Simply paste the Embed Code below <strong>exactly</strong> where you\'d like to see the widget on your website and you\'re on your way.</p><hr /><p style="font-size: 11px"><strong style="color: #CC0000">Note:</strong><br />The widget minimum width is 160px. The PromoteDJ Widget works best in the side column of your website. However, it can also be displayed in the main content and will stretch up to 640px wide.</p></div><div style="float: right"><img src="/images/aa_widget_screen.gif" /></div><div class="clearfix"></div><div style="width: 658px; background-color: #fffeed; padding: 10px; margin-top: 20px; border: solid 1px #ffdd99; color: #000000"><h4>Your Embed Code</h4><span style="font-size: 11px">&lt;div style="text-align: right;"&gt;&lt;script type="text/javascript" src="http://www.audioacademy.fm/widget.php?track_id='+id+'"&gt;&lt;/script&gt;&lt;a href="www.audioacademy.fm" style="color: #0080FF"&gt;audioacademy.fm&lt;/a&gt;&lt;/div&gt;</span></div></div>'
	}).show();
}

function requiredLogin()
{
	alert('asdf');
}

function setOverText(){
	
	var inputs = $$('.overtext');
	inputs.each(function(el){
		var overText = el.getProperty('alt');
		el.setProperty('value', overText);
		el.addEvents({
			'focus': function(){
				if(el.getProperty('value') == overText)
					el.setProperty('value', '');
			},
			'blur': function(){
				if(el.getProperty('value') == '')
					el.setProperty('value', overText);
			}
		});
	});
	
}

function subscribe(){
	
	var serialize = $('optin_form').toQueryString();
	var email = $('optin_email').getProperty('value');
	var overtext = $('optin_email').getProperty('alt');
	
	// We'll handle empty field values here
	if(email='' || email==overtext){
		new Popup({
			'heading': 'Error!',
			'message': '<li>You must fill in your email address</li>',
			'isError': true
		}).show();
	}
	else{
		new Request({
			url: "/mailchimp/adduser",
			method: 'post',
			onComplete: function(response){
				
				var email = $('optin_email').getProperty('value');
				
				// SUCCESS
				if(response==1){
					new Popup({
						'heading': 'Check Your Email',
						'message': "We've just sent an email to: <strong style='font-style: italic'>\""+email+"\"</strong> with instructions for how to confirm your subscription to our mailing list. Be sure to check your junk mail folder if you don't see it in your inbox. Simply follow the instructions and leave the rest to us.",
						'width': 500
					}).show();
				}
				
				// FAILURES
				else{
					
					if(response==214)
						var message = "<li>The email address: <strong style='font-style: italic'>\""+email+"\"</strong> already exists in this list</li>";
						
					else if(response==502)
						message = "<li>The email address: <strong style='font-style: italic'>\""+email+"\"</strong> is not formatted correctly (e.g. name@domain.com)</li>";
						
					else
						message = "An unknown error has occured. Please try again.";
						
					new Popup({
						'heading': 'Error!',
						'message': message,
						'isError': true,
						'width': 500
					}).show();
				}
				// REPEAT AS NECESSARY
				
			}
		}).send(serialize);
	}
	
}

function connectDjs(){
	$('dj_connections').addEvent('click',function() {
				
		//make the ajax call, replace text
		var req = new Request({
			method: 'get',
			url: '/facebook/dj_connections/',
			useSpinner: true,
			spinnerTarget: $('dj_friend_pics'),
			update: $('dj_connections'),
			onComplete: function(response) { 
				// SINCE THIS IS AN AJAX CALLED PAGE WE HAVE TO RE-PARSE FOR XFBML ELEMENTS (PROFILE PHOTOS)
				if ( FB.XFBML.Host.parseDomTree )
					setTimeout( FB.XFBML.Host.parseDomTree, 100 );
			}
		}).send();
		
	});
}
