$(document).ready(function() {



	var triggers = $(".popover_link").overlay({ 
    		// some expose tweaks suitable for modal dialogs 
    		expose: { 
    			color: '#8a90ca', 
    			loadSpeed: 200, 
    			opacity: 0.9
    		}, 
    		closeOnClick: true
    	});

	$('textarea.comment_input').autoResize({
    		// On resize:
    		onResize : function() {
    			$(this).css({opacity:0.8});
    		},
    		// After resize:
    		animateCallback : function() {
    			$(this).css({opacity:1});
    		},
    		// Quite slow animation:
    		animateDuration : 300,
    		// More extra space:
    		extraSpace : 40
	});

	$('.comment_cancel').click(function() {
		$(this).parent().parent().parent().parent().fadeOut();
	});

	$(".date_link").click( function() {
		var form_id = $(this).parent().parent().parent().attr('id').split('_'); 
		var name = form_id[0];
		var id = form_id[1];

		$("#comment_input_block_"+id).fadeIn();
		$("#comment_input_"+id).focus();
	});

	$('.comment_submit').click(function() {
		var form_id = $(this).parent().attr('id').split('_'); 
		var name = form_id[0];
		var id = form_id[2];

		//var comment_action_html = $("#comment_action_"+id).html();
		//$("#comment_action_"+id).html('<img src="/images/loading.gif" border="0" width="15" height="15" id="comment_submit_'+id+'" />');
		//$("#comment_input_"+id).attr('disabled','disabled');

		$.ajax({
			type: 'POST',
			url: '/dm/send_dm', 
			data: $("#comment_form_"+id).serialize(), 
			success: function() {
				$("#comments_"+id).append('<div class="left_img_comments"><img src="/images/favicon.png" height="15" width="15" border="0" /></div><div class="comment">'+$('#comment_input_'+id).val()+'</div>').fadeIn();
				$("#comment_input_"+id).val("");
				//$("#comment_action_"+id).html(comment_action_html);
				//$("#comment_input_"+id).removeAttr("disabled");
				$("#comment_input_block_"+id).fadeOut();
			},
			error: function(event, xhr, settings) {
				alert("error: "+xhr.content);
				$("#comment_error_"+id).text(xhr.content);
			}
		});

		return false;
	});

	var user_profile_offset = $("#user_profile").offset();
	$("#user_profile").mouseenter(function() {
		$("#user_profile_select").css({
			'left': user_profile_offset.left,
			'top': (user_profile_offset.top-$(this).height)
		}).fadeIn();

	});

	$("#user_profile_select").mouseleave(function() {
		$(this).fadeOut();
	});

	$("#user_profile_first").mouseenter(function() {
		$(".profile_selector").css({
			'background': '#fff'
		});
		$(this).css({
			'background': '#eaeaea',
			'cursor': 'pointer'
		});
	});

	$(".profile_selector").mouseenter(function() {
		$("#user_profile_first").css({
			'background': '#fff'
		});
		$(".profile_selector").css({
			'background': '#fff'
		});
		$(this).css({
			'background': '#eaeaea',
			'cursor': 'pointer'
		});
	});

	if ($("#add_account_selector").html()) {
		if (!$("#add_account_selector").html().match('Upgrade')) {
			$("#add_account_selector").popupWindow({
				centerScreen: 1,
				width: 800
			});
		}
	}

	$("a.account_selector").click(function() {
		$.ajax({
			type: 'GET',
			url: $(this).attr('href'), 
			success: function() {
				location.reload();
			},
			error: function(event, xhr, settings) {
				alert("error: "+xhr.content);
				return false;
			}
		});
		return false;
	});

	$("div[title],li[title],a[title],span[title]").each(function() {
		$(this).qtip({ 
			content: $(this).attr("title"),
			position: {
				corner: {
					target: 'center',
					tooltip: 'bottomRight'
				}
			},
			style: {
				border: {
					width: 5,
					radius: 10,
					color: '#8e8e8e'
				},
				padding: 10, 
				textAlign: 'center',
				tip: true,
				background: '#eaeaea'
			}
		});
		$(this).attr("title","");
	});

	$('abbr.timeago').timeago();

	if ($("#error").find(".details").html()) {
		$("#error").overlay({
			effect: 'default',
			api: true,
			top: '10%'
		}).load();
	}

	if ($("#message").find(".details").html()) {
		$("#message").overlay({
			effect: 'default',
			api: true,
			top: '10%'
		}).load();
	}

	var login_box=0;
	$(".login_link").mouseover( function () {
		login_box=1;
		$(this).css("text-decoration", "underline");
		$("#login_box").fadeIn("slow");
	});

	$(".login_link").click( function () {
		if (!login_box) {
			login_box=1;
			$(this).css("text-decoration", "underline");
			$("#login_box").fadeIn("slow");
		}
	});

	$(".twitter_login").popupWindow({ 
		centerScreen:1,
		width:800
	}); 

	$(".popover form").submit(function(e) { 

		$("#stats_email_submit").replaceWith('<div id="stats_email_submit"><img src="/images/loading.gif" height="25" width="25" border="0" alt="Loading..." /> Please wait - verifying screen name with Twitter...</div>');

   		// get user input 
    		var screenname = $("#twitter_screenname_track", this).val(); 
		var paypal_track_link = $("#paypal_track_link", this).val();
		var socialtoo_key = $("#api_key").val();

		// ping Twitter to see if user exists
		$.ajax({
			type: 'GET',
			url: '/rest/twitter/'+screenname,
			dataType: 'json',
			beforeSend: function (xhr) {
				xhr.setRequestHeader(
					'X-SocialTooKey',
					socialtoo_key
				)
			},
			success:function(response) {
		    		// close the overlay 
 	   			triggers.eq(1).overlay().close(); 
 
    				// do something with the answer 
				window.location.href=paypal_track_link+"&custom="+screenname+",4";
			},
			error: function(x,e) {
				$("#screenname_error").html("You must enter a valid Twitter screen name!");
				$("#stats_email_submit").replaceWith('<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" id="stats_email_submit" />');
			}
		});

    		// do not submit the form 
    		return e.preventDefault(); 
    	});

	if ($(document).getUrlParam('service') && $(document).getUrlParam('twitter_user')) {
		$.ajax({
			type: 'GET',
			url: '/rest/twitter/'+$(document).getUrlParam('twitter_user'),
			dataType: 'json',
			beforeSend: function (xhr) {
				xhr.setRequestHeader(
					'X-SocialTooKey',
					$("#api_key").val()
				)
			},
			success:function(response) {
				$('#affiliate_popover h2').css({
					'background':'url('+response.profile_image_url+') 0 50% no-repeat',
					'margin':'0 0 10px 0',
					'padding':'10px 0 20px 85px',
					'border-bottom':'1px solid #8e8e8e',
					'font-size':'20px',
					'height':'37px',
					'color':'#9fc03e'
				});
			}
		});

		$("#affiliate_popover").overlay({
    			// some expose tweaks suitable for modal dialogs 
    			expose: { 
    				color: '#8a90ca', 
    				loadSpeed: 200, 
    				opacity: 0.9
    			}, 
    			closeOnClick: true,
			api: true
		}).load();

		$("#affiliate_popover form").submit(function(e) { 

			$("#affiliate_submit").replaceWith('<div id="affiliate_submit"><img src="/images/loading.gif" height="25" width="25" border="0" alt="Loading..." /> Please wait - verifying screen name with Twitter...</div>');

   			// get user input 
    			var screenname = $("#twitter_screenname_affiliate", this).val(); 
			var paypal_affiliate_link = $("#paypal_affiliate_link", this).val();
			var socialtoo_key = $("#api_key").val();

			// ping Twitter to see if user exists
			$.ajax({
				type: 'GET',
				url: '/rest/twitter/'+screenname,
				dataType: 'json',
				beforeSend: function (xhr) {
					xhr.setRequestHeader(
						'X-SocialTooKey',
						socialtoo_key
					)
				},
				success:function(response) {
		    			// close the overlay 
 	   				triggers.eq(1).overlay().close(); 
 
    					// do something with the answer 
    					var service_id=3;
    					if ($(document).getUrlParam('service')=='stats') {
						service_id=4;
					}
					else if ($(document).getUrlParam('service')=='catchup') {
						service_id=1;
					}
					else if ($(document).getUrlParam('service')=='unfollow_catchup') {
						service_id=2;
					}

					window.location.href=paypal_affiliate_link+"&custom="+screenname+","+service_id+","+$(document).getUrlParam('twitter_user');
				},
				error: function(x,e) {
					$("#screenname_error_affiliate").html("You must enter a valid Twitter screen name!");
					$("#stats_email_submit").replaceWith('<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" id="stats_email_submit" />');
				}
			});

    			// do not submit the form 
    			return e.preventDefault(); 
    		});
	}

	$('input[title!=""]').hint();

	$("#twitter_email_flag").click(function() { 
		if ( $(this).is(':checked') ) { 
			$.post("/stats/update_email",{ enable: 1 });
		} 
		else { 
			$.post("/stats/update_email",{ enable: 0 });
		} 
	});

	$("#myspace_email_flag").click(function() { 
		if ( $(this).is(':checked') ) { 
			$.post("/stats/update_myspace_email",{ enable: 1 });
		} 
		else { 
			$.post("/stats/update_myspace_email",{ enable: 0 });
		} 
	});

	$(".answer").click(function() {
		var id_pieces = $(this).attr("id").split("_");
		if ($("#multi_choice").val() == 'y') {
			if ($(this).find("img").attr("src").match('quote_green_small')) {
				// remove selection
				$(this).find("img").attr("src", "/images/quote_purple_small.png");
				$(this).css({
					'color': '#8a90ca'
				});
				$("#answers_hidden_"+id_pieces[1]).remove();
			}
			else {
				// add selection
				$("#survey_form").append('<input class="answers" type="hidden" id="answers_hidden_'+id_pieces[1]+'" name="answers[]" value="'+id_pieces[1]+'" />');
				$(this).find("img").attr("src", "/images/quote_green_small.png");
				$(this).css({
					'color': '#9fc03e'
				});
			}
		}
		else {
			$("#survey_form").find('input[type="hidden"].answers').remove();
			$(".answer").find("img").attr("src", "/images/quote_purple_small.png");
			$(".answer").css({
				'color': '#8a90ca'
			});
			$("#survey_form").append('<input class="answers" type="hidden" id="answers_hidden_'+id_pieces[1]+'" name="answers[]" value="'+id_pieces[1]+'" />');
			$("#answer_"+id_pieces[1]).find("img").attr("src", "/images/quote_green_small.png");
			$("#answer_"+id_pieces[1]).css({
				'color': '#9fc03e'
			});
		}

		return false;
	});

	$("#survey_question_mini").find("#survey_submit").click(function() {
		$("#survey_question_mini").find("#survey_form").append('<img src="/images/loading.gif" width="15" height="15" border="0" alt="loading..." class="loading" />');
		$.ajax({
			type: 'PUT',
			url: '/rest/answer/vote',
			dataType: 'json',
			data: $("#survey_form").serialize(), 
			beforeSend: function (xhr) {
				xhr.setRequestHeader(
					'X-SocialTooKey',
					$("#api_key").val()
				);
			},
			success:function(response) {
				$("img.loading").remove();
				$("#survey_question_mini").animate({opacity: 0});
				$("#survey_question_mini").load('/survey/show_results/'+response[0].survey_id, function() {
					$("#survey_question_mini").animate({opacity: 1});
					$("#survey_question_mini").find(".dynamic_bar").each(function() {
						var line_width = ($(this).html()/6);
						$(this).html('');
						$(this).css({ visibility: 'visible' });
						$(this).animate({
							width: line_width+'%'
						}, 1000, 'linear');
					});
				});
			},
			error: function(x,e) {
				var error = x.responseText;
				if (error.match('No answers provided')) {
					error = 'Please choose at least one answer.';
				}
				$("img.loading").remove();
				$("#error").find(".details").html(error);

				$("#error").overlay({
					effect: 'default',
					api: true,
					top: 'center'
				}).load();
			}
		});
		return false;
	});

	$("#survey_comment_submit").click(function() {
		$("#survey_comment_form").append('<img src="/images/loading.gif" width="15" height="15" border="0" alt="loading..." class="loading" />');
		$.ajax({
			type: 'POST',
			url: '/rest/survey_comment',
			dataType: 'json',
			data: $("#survey_comment_form").serialize(), 
			beforeSend: function (xhr) {
				xhr.setRequestHeader(
					'X-SocialTooKey',
					$("#api_key").val()
				);
			},
			success:function(response) {
				$("img.loading").remove();
				var comment_html = '\
<div class="survey-comment s_comment_item" id="survey_comment_'+response.comment_id+'">\
	<div class="left_img">';
	if (response.twitter_user_id || response.facebook_id) {
		comment_html += '<a href="';
		if (response.twitter_user_id) {
			comment_html += 'http://twitter.com/'+response.screen_name;
		}
		else {
			comment_html += 'http://facebook.com/index.php?profile_id='+response.facebook_id;
		}
		comment_html += '" target="_blank">';
		if (response.twitter_user_id) {
			comment_html += '<img src="http://img.tweetimag.es/i/'+response.screen_name+'_n" align="top" border="0" width="48" height="48" />';
		}
		else {
			comment_html += '<fb:profile-pic uid="'+response.facebook_id+'" size="square"></fb:profile-pic>';
		}
		comment_html += '</a>';
	}
				comment_html += '</div>\
<div class="right_content">\
	<div class="profile_img"><img src="/images/favicon.png" width="15" height="15" border="0" align="left" />';
	if (response.twitter_user_id) {
		comment_html += '<a href="http://twitter.com/'+response.screen_name+'">'+response.name+'</a>';
	}
	else {
		comment_html += '&nbsp;';
	}
				comment_html += '</div>\
<div class="text">'+response.comment_text+'</div>\
	<div class="date">\
		<abbr class="timeago" title="'+response.post_date+'">'+jQuery.timeago(new Date())+'</abbr>\
	</div>\
</div>\
</div>';
				$("#indi_comments").prepend(comment_html);
				$("#comment_text").val('');
			},
			error: function(x,e) {
				var error = x.responseText;
				$("img.loading").remove();
				$("#error").find(".details").html(error);

				$("#error").overlay({
					effect: 'default',
					api: true,
					top: 'center'
				}).load();
			}
		});

		return false;
	});

	$(".dynamic_bar").each(function() {
		var line_width = $(this).html();
		$(this).html('');
		$(this).css({ visibility: 'visible' });
		$(this).animate({
			width: line_width
		}, 1000, 'linear');
	});

	if ($("#no_email_msg").html()) {
		$("#settings_link").qtip({ 
			content: {
				text: $("#no_email_msg").html(),
				prerender: true,
			},
			position: {
				corner: {
					target: 'bottomMiddle',
					tooltip: 'topRight'
				}
			},
			style: {
				border: {
					width: 2,
					radius: 10,
					color: '#8e8e8e'
				},
				padding: 10, 
				textAlign: 'center',
				tip: true,
				background: '#eaeaea'
			},
			hide: {
				fixed: true
			},
			show: {
				ready: true
			},
			api: {
				onHide: function() {
					$(".qtip").fadeOut();
				}
			}
		});
	}

	$("#facebook_register_button,#login_facebook_button,#facebook_associate_button").click(function() {
		FB.login(function(response) {
			console.debug(response);
  			if (response.session) {
				if (response.perms) {
					console.debug(response.perms);
    					// user successfully logged in
					$.ajax({
						type: "POST",
						url: "/login/facebook",
						dataType: "html",
						data: {
							access_token: response.session.access_token,
							facebook_id: response.session.uid
						},
						success:function(response) {
							if (response=='login') {
								window.location = window.location+'?login=facebook';
								location.reload(true);
							}
							else if (response=='associate') {
								window.location = window.location+'?associate=facebook';
								location.reload(true);
							}
							else {
								window.location = window.location+'?register=facebook';
								location.reload(true);
							}
						},
						error:function(x,e) {
							alert('Your Facebook login was unsuccessful. Can you please try again?');
						}
					});
				} else {
					alert('You must grant all permissions in order to use SocialToo with Facebook.');
				}
    			} else {
				// user cancelled login
				alert('Your Facebook login was unsuccessful. Can you please try again?');
			}
		}, {
			perms: "publish_stream,read_stream,offline_access,read_mailbox,email,user_checkins,friends_checkins"
		});
	});
	FB.Canvas.setSize();


});

// Facebook Connect
var facebook_onlogin = function () {
	FB.Connect.showPermissionDialog('publish_stream,offline_access,read_mailbox,email', function(result) {
		$.ajax({
			type: "POST",
			url: "/login/facebook",
			dataType: "html",
			success:function(response) {
				if (response=='login') {
					window.location = window.location+'?login=facebook';
				}
				else if (response=='associate') {
					window.location = window.location+'?associate=facebook';
				}
				else {
					window.location = window.location+'?register=facebook';
				}
			},
			error:function(x,e) {
				alert('Your Facebook login was unsuccessful. Can you please try again?');
			}
		});
	}());
}

