Pie.Party = (function() {
	var me = {};
	me.partyId = 0;
	me.mixId = 0;
	me.editable = false;
	me.sortable = false;
	me.videos = [];
	me.playSong = 0;

	me.graph = [];
	me.graphTicks = [];

	me.newsFeed = [];

	me.msg_to = null;

	me.to_publish = null;

	me.msg = function(text, error, timeout, html) {
		clearTimeout(me.msg_to);
		var $msgd = $('#mixer_msg_div');
		$msgd.hide();
		
		if(text==undefined)
			return;

		var $msg = $('#mixer_msg');
		html===true ? $msg.html(text) : $msg.text(text);
		$msg.removeClass('info error');
		$msg.addClass( error===true ? 'error' : 'info' );
		$msgd.fadeIn();
		if(timeout !== undefined)
			me.msg_to = setTimeout(function(){ $msgd.fadeOut(); }, timeout<=10 ? timeout*1000 : timeout);
	};

	me.login = function(options) {
		var o = Pie.extend({
			'onSuccess': function() {
				if (Pie.info.uri.action == 'mix') {
					document.location.reload(true);
					return;
				}
				document.location = Pie.urls['party/home'];
			},
			'onCancel': function() {
				if (!('party/welcome' in Pie.urls)
				|| document.location.href.split('#')[0] != Pie.urls['party/welcome']) {
					return;
				}
				alert("You have to allow YouMixer to connect with facebook, otherwise it won't work. Try again.");
			},
			'using': 'facebook',
			'accountStatusUrl': Pie.urls['party/accountStatus'],
			'perms': '' // publish_stream,read_stream,email,read_mailbox,offline_access,sms' // <-- cool to play around with this, http://wiki.developers.facebook.com/index.php/Extended_permissions
		}, options);
		Pie.Users.login(o);
		return false;
	};
	
	me.logout = function(options) {
		var o = Pie.extend({
			'using': 'facebook'
		}, options);
		Pie.Users.logout(o);
		return false;
	};

	me.ajax = function(url,data,callback,err_callback,async) {
		$.ajax({
			url: url,
			dataType: 'json',
			data: data,
			async: (async!==false),
			type: 'POST',
			success: function(data) {
				var res = {};
				try {
					for(var sl in data.slots)
					{
						res[sl] = $.parseJSON(data.slots[sl]);
					}
//					var res = $.parseJSON(data.slots.ajax);
				} catch(e) {
					if(data && data.errors)
					{
						for(ei in data.errors)
							console.log(data.errors[ei]);
					}
					//window.location.reload();
					return;
				}
				if(res && res.ajax && res.ajax.success)
				{
					if(callback !== undefined && callback !== null)
						callback(res);
				}
				else
				{
					if(res && res.ajax && res.ajax.error)
					{
						if(err_callback !== undefined)
						{
							if(err_callback === true)
								Pie.Party.msg(res.ajax.error,true,3);
							else
								err_callback(res.ajax.error);
						}
						else
							console.log('error: '+res.ajax.error);
					}
					else
					{
						console.log('ajax error');
						//console.log(data);
						//window.location.reload();
					}
				}
			}
		});
	};

	me.remove = function(song_id) {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/remove'],'ajax,newsfeed');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId,
			song_id : song_id
		};
		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			me.newsFeed = data.newsfeed.items;
			pl_fill(data.ajax.next!==undefined&&data.ajax.next>0?data.ajax.next:undefined);
			pl_newsfeed();
		},true);
	};

	me.cut = function(song_id,start,end) {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/edit'],'ajax');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId,
			song_id : song_id,
			start : start,
			end : end
		};

		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			pl_fill();
		},true);
	};

	me.add = function(video_id, after_song_id) {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/add'],'ajax,newsfeed');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId,
			video_id : video_id,
			after_song_id: after_song_id
		};

		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			me.newsFeed = data.newsfeed.items;
			pl_fill();
			pl_newsfeed();
			document.getElementById('search_text').focus();
		},true);
	};
	
	me.shuffle = function() {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/shuffle'],'ajax,newsfeed');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId
		};

		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			me.newsFeed = data.newsfeed.items;
			pl_fill();
			pl_newsfeed();
			shuffleFlash();
		},true);
	};

	me.move = function(song_id, after) {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/move'],'ajax,newsfeed');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId,
			song_id : song_id,
			after : after
		};

		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			me.newsFeed = data.newsfeed.items;
			pl_fill(undefined,false);
			pl_newsfeed();
//			Pie.Party.msg('Moved',false,1);
		},true);
	};

	me.removeParty = function(party_id) {
		var url = Pie.ajaxExtend(Pie.urls['party/remove_party'],'ajax');
		var data = {
			party_id : party_id
		};

		me.ajax(url,data,function(data){
			$('.div[pid='+data.ajax.party_id+']','#list,#list2').parent().remove();
			eo(); // repaint
			Pie.Party.msg('Party removed',false,1);
		},true);
	};

	me.renameParty = function(new_name,party_id) {
		var url = Pie.ajaxExtend(Pie.urls['party/rename_party'],'ajax');
		var data = {
			party_id : party_id!==undefined?party_id:me.partyId,
			new_name : new_name
		};

		me.ajax(url,data,function(data){
			party_id!==undefined ? $('.div[pid='+data.ajax.party_id+']','#list,#list2').find('.name').text(data.ajax.party_name) : $('.name .text','#controls_slot').text(data.ajax.party_name);
			Pie.Party.msg('Party renamed',false,1);
		},true);
	};

	me.changePartySettings = function(type, new_val, party_id) {
		var url = Pie.ajaxExtend(Pie.urls['party/settings_party'],'ajax');
		var data = {
			type : type,
			party_id : party_id!==undefined?party_id:me.partyId,
			new_val : new_val
		};

		me.ajax(url,data,function(data){
			var $d = party_id!==undefined ? $('.div[pid='+data.ajax.party_id+']','#list,#list2') : $('.perms','#controls_slot'); 
			$d.attr({'svt':data.ajax.svt,'seb':data.ajax.seb});
			$d.find('.t_vt').text(data.ajax.tvt);
			$d.find('.t_eb').text(data.ajax.teb);
			Pie.Party.msg('Settings changed',false,1);
		},true);
	};

	me.changePartyImage = function(image_id,party_id) {
		var url = Pie.ajaxExtend(Pie.urls['party/image_party'],'ajax');
		var data = {
			party_id : party_id!==undefined?party_id:me.partyId,
			image_id : image_id
		};

		me.ajax(url,data,function(data){
			var $d = party_id!==undefined ? $('.div[pid='+data.ajax.party_id+']','#list,#list2') : $('.img','#controls_slot');
			$d.attr('pi',data.ajax.image_id);
			$d.find('img.pi').attr('src',data.ajax.image_src);
			$('#pis,#pis2').hide();
			Pie.Party.msg('Image changed',false,1);
		},true);
	};

	me._checkPartyName = function(name) {
		if(!name)
			return "The name is required";
		if(name.length < 5)
			return 'The name should be at least 5 characters long';
		return false;
	};

	me.importPlaylist = function(type,param) {
		if(!me.editable) return;
		var url = Pie.ajaxExtend(Pie.urls['party/import'],'ajax,newsfeed');
		var data = {
			party_id : me.partyId,
			mix_id : me.mixId,
			type : type,
			param : param
		};
		
		me.ajax(url,data,function(data){
			me.videos = data.ajax.videos;
			me.newsFeed = data.newsfeed.items;
			yti_reset();
			pl_fill();
			pl_newsfeed();
		},true);
	};

	me.make = function(e) {
		//e.stopPropagation();
		//e.stopImmediatePropagation();

		var name = $('#party_name').val();
		var cr = me._checkPartyName(name);
		if(cr!==false)
		{
			$('#party_name').focus();
			me.msg(cr,true,3);
		}
		else if($('#party_mix').val()==-1)
		{
			$('#party_mix').focus();
			me.msg('Choose songs to play at your party',true,3);
		}
		else
		{
			var url = Pie.ajaxExtend(Pie.urls['party/make'],'ajax');
			var pm = $('#party_mix').val();
			var data = {
				name : name,
				visible_to : $('#visible_to').val(),
				editable_by : $('#editable_by').val(),
				copy_from : pm,
				playlist : search_plid,
				image: ($('.party_image.selected').index('.party_image')+1)
			};

//			console.log(data);
//			return false;

			function stream_publish(data){
				var url = Pie.urls['party/mix']+'/'+data.ajax.id;
				var base = Pie.info.proxies[Pie.info.baseUrl];
				var pp = data.ajax.publish_privacy;
				if(pp===false) // self only
				{
					window.location = url;
					return;
				}
				if(data.ajax.preview !== undefined)
				{
					// unconnected user, redirect to preview page
					var purl = Pie.urls['party/preview']+'/'+data.ajax.preview;
					window.location = purl;
					return;
				}

				var name = 'I started a new mix called "'+data.ajax.name+'". ';
				if (data.ajax.song_count > 0) {
					name += 'It has ' + data.ajax.song_count + ' songs so far.';
				}
				var caption = "YouMixer is a video DJ that you can use for parties - it lets everyone contribute songs to a common party mix, so when you get together, you just put on YouMixer.com and everyone will get to hear their favorite songs.";
				var publish = {
					method: 'stream.publish',
					message: 'Hey, could you add some songs to my mix?',
					display: 'popup',
					attachment: {
						caption: caption,
						name: name,
						href: url,
						media: [{
							type: 'image',
							src: data.ajax.image,
							href: url
						}]
					},
					privacy: { value:pp },
//					action_links: [
//						{ text:'My party',href:url},
//						{ text:'YouMixer',href:base}
//					],
					user_message_prompt: 'Share your Party'
				};
				Pie.Party.to_publish = publish;
			};
			
			function onErr(err){
				Pie.Party.to_publish=null; 
				Pie.Party.msg(err,true,3); 
			}

			me.ajax(url,data,stream_publish,onErr, false);
			if(me.to_publish !== null)
//				FB.ui(me.to_publish, function(){
					window.location = me.to_publish.attachment.href;
//				});
		}

		return false;
	};
	
	return me;
})();
