var pies, preview, analyze, track_overlay, track, general_force_overlay, ajax_overlay, saved_overlay, welcome_overlay, list_overlay, credits_overlay, download_overlay, is_animating, is_mobile, sg_data, mobile_close = "";

function wonk_highlights() {
	is_subscriber ? $(".subscriberlink").addClass("is_upgraded") : $(".subscriberlink").addClass("is_not_upgraded");
	$("td.is_not_upgraded, div.is_not_upgraded").attr('title', "Subscribers only.  Click to learn more.");
	$("td.login_for_graph").attr("title", "Login with Twitter to overlay your follower status for each listed user.  Click to login now.");
	$("td.subscribe_for_graph").attr("title", "Since your social graph is very large, we cannot display your relationship status for listed users in our free version.  Please subscribe now to overlay your social graph.  Click to learn more.");
	//we should always have a screen name for these actions...
	$("td.youfollow").attr("title", '@' + screen_name + ' follows them');
	$("td.theyfollow").attr("title", 'They follow @' + screen_name);
	$("td.theydontfollow").attr("title", "They don't follow @" + screen_name);
	$("td.youdontfollow").attr("title", "@" + screen_name + " doesn't follow them");

	$("td.need_unfol").html("<input type='submit' title='Click and @" + screen_name + " will unfollow' value='unfollow'/>").removeClass("need_unfol").addClass("button_unfollow");
	$("td.need_fol").html("<input type='submit' title='Click and @" + screen_name + " will follow' value='follow'/>").removeClass("need_fol");

	$("input:submit, input.button_it").not("#email_button").button();
	if (is_mobile) {} else {
		$("[title]").qtip({
			style: {tip: {corner: true, method: 'polygon'},classes: 'ui-tooltip-rounded ui-tooltip-shadow'},
			position: {viewport: $(window)}
		});
	}
}

function dismiss(what){
	$.ajax({
		url: "/",
		type: "POST",
		data: {dismiss_alert: 1, to_dismiss: what}
	});
	$("#alert_ribbon").slideUp();
	return false;
}

function tweet_it(url){
	window.open("/tweet-wonkly?" + url);
	return false;
}

function close_overlay(overlay){
	is_mobile ? overlay.hide() : overlay.dialog('close');	
}

function ajax_close(){
	close_overlay(ajax_overlay);
}

function refresh_credits() {
	$.ajax({
		beforeSend: function(msg){
			open_overlay(ajax_overlay);
		},
		url: "/" + "refresh-credits",
		success: function(msg){
			$('#credits').html(msg);
			ajax_close();
		}
	});
	return void(0);
}

function get_credits() {
	$.ajax({
		url: "/" + "get-credits",
		success: function(msg){
			$('#credits').html(msg);
			ajax_close();
		}
	});
	return void(0);
}

function save_report(src, type, tgt, tweet) {
	$.ajax({
		beforeSend: function(msg){
			$('#save_button').html('<center><img src="ajax-loader.gif" alt=""/></center>');
		},
		url: "/" + "save-report/?src=" + src + "&type=" + type + "&tgt=" + tgt + "&tweet=" + tweet,
		success: function(msg){$('#save_button').html(msg);},
		complete: function(msg){get_credits();}
	});
	return void(0);
}

function show_list_overlay(ucnt, sess, titl, stuff, tgt) {
	stuff = stuff ? "<div class='l p5_a'>" + stuff + "</div>" : "";
	$('#list_overlay > .overlay_internal').html('<center><img src="ajax-loader.gif" alt=""/></center>');
	open_overlay(list_overlay, titl);

	$.ajax({
		type: "GET",
		url: "/" + "?session=" + sess + "&tgt=" + (tgt||''),
		success: function(msg){
			$('#list_overlay > .overlay_internal').html(mobile_close + stuff + msg + mobile_close);
			wonk_highlights();	
		}
	});
	return void(0);
}

function open_overlay(overlay, title) {
	if (is_mobile) {
		overlay.removeClass("not_mobile").addClass("mobile");
		$("#mobile_dark").addClass("ui-widget-overlay");
		if (overlay.not(":visible")) {
			//close any already open overlays to handle z-index issue
			$("div.overlay").hide();
			$("#mobile_dark").show();
			overlay.show();
			$('html,body').animate({scrollTop: top}, 1000);
		}
	} else {
		if (overlay.dialog('isOpen')) {} else {
			if (title) {
				overlay.dialog("option", "title", title);
			}
			overlay.dialog('open');
		}
	}
}

function show_purchase_overlay() {
	//no longer an overlay
	window.location = "/buy";
}

function show_saved_overlay() {
	$.ajax({
		type: "GET",
		url: "/" + "saved-table/",
		beforeSend: function(msg){
			$('#saved_overlay > .overlay_internal').html('<center><img src="ajax-loader.gif" alt=""/></center>');
			open_overlay(saved_overlay);
		},
		success: function(msg){
			$('#saved_overlay > .overlay_internal').html(mobile_close + msg);
		}
	});
	return void(0);
}

function show_credits_overlay() {
	$.ajax({
		type: "GET",
		url: "/" + "credits-box",
		beforeSend: function(msg) {
			$('#credits_overlay > .overlay_internal').html('<center><img src="ajax-loader.gif" alt=""/></center>');
			open_overlay(credits_overlay);
		},
		success: function(msg){
			$('#credits_overlay > .overlay_internal').html(mobile_close + msg);
		}
	});
	return void(0);
}

function show_download_overlay(sess, ct, tgt) {
	open_overlay(download_overlay);
	if (sess) { //aka not bio page
		$('#download_overlay > .overlay_internal').html('<center><img src="ajax-loader.gif" alt=""/></center>');
		$.ajax({
			type: "GET",
			url: "/" + "data-menu/?tgt=" + (tgt||'') + "&session=" + sess + "&ct=" + ct,
			success: function(msg){$('#download_overlay > .overlay_internal').html(mobile_close + msg);}
		});
	} else {
		//aka bio page
		$("#download_overlay > .overlay_internal").html(mobile_close + $("#bio_download_options").html());
	}
	return void(0);
}

function delete_user(pid){
	if (confirm('Are you sure you wish to remove this account from Follower Wonk?')) {
        $.post('/delete-user', {"pid": pid}, function(){
            location.reload();
        });
	}
}

function show_specific(show_what, show_where){
	what = $(show_what);
	where = $(show_where);
	is_mobile ? where.children("div").hide() : where.children("div").slideUp("normal");
	is_mobile ? what.show() : what.slideDown("normal");
}

function show_hide(what) {
	what = $(what);
	if (what.is(':visible')) {
		is_mobile ? what.hide() : what.slideUp("normal");
	} else {
		is_mobile ? what.show() : what.slideDown("normal");
	}
}

function toggle_search() {
	if ($("#moreoptions").is(':visible')) {
		is_mobile ? $("#moreoptions").hide() : $("#moreoptions").slideUp("normal");
		$("#tab_bio .funexamples").show();
		$("#optiontext").html("more options");
	} else {
		is_mobile ? $("#moreoptions").show() : $("#moreoptions").slideDown("normal");
		$("#tab_bio .funexamples").hide();
		$("#optiontext").html("fewer options");
	}
}

function process_coupon() {
	var coupon = $("#coupon_code").val();
	if (coupon=='') {
		return;
	}
	$.ajax({
		type: "GET",
		url: '/paypal-subscriptions?coupon=' + coupon,
		success: function(msg){$('#paypal_subscribe').html(msg);}
	});
}

function small_pie(data) {
	return "<br/><img src='http://chart.apis.google.com/chart?chf=bg,s,f2f5f7&cht=p&chs=400x125&chco=f9b142,a9eb7a,3d9dfd,ffa099&chd=t:"+data+"'>";
}

function data_download(url) {
	$('#download_overlay > .overlay_internal').html('<center><img src="ajax-loader.gif" alt=""/></center>');
	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){$('#download_overlay > .overlay_internal').html(mobile_close + msg);}
	});
}

function commify(x){
	x = Math.round(x * 100)/100;
	var arr = x.toString().split(".");
	return arr[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, ",") + (arr[1] ? "." + arr[1] : "");
}

function percent(x,y){
	x = Math.abs(x);
	y = Math.abs(y);
	return x>0 && y>0 ? Math.round(((y/x) * 100) * 100)/100 : 0;
}

function ready_function(){

	$("#atsign, span.atsign").replaceWith("&#0064;");

	// check browser timezone and set if different
	var timezone = jstz.determine_timezone().timezone;
	if (timezone.olson_tz !== tz) {
		tz = timezone.olson_tz;
		$.ajax({url: "/preferences?timezone=" + tz});
	}

	//because of ipad (and others?) problems with jqueryui, specifically effects
	is_mobile = navigator.userAgent.match(/(iPad|mobile|iPhone)/i) != null;

	if (is_mobile) {
		mobile_close = "<div class='r_r p5_a fakelink close_mobile_overlay'>close</div>";
		general_force_overlay = $("#general_force_overlay"), 
		welcome_overlay = $("#welcome_overlay"), track_overlay = $("#track_overlay"), list_overlay = $("#list_overlay");	
		ajax_overlay = $("#ajax_overlay"), credits_overlay = $("#credits_overlay"), download_overlay = $("#download_overlay"), 
		saved_overlay = $("#saved_overlay");

		$("#overlays").on("click", "div.close_mobile_overlay", function(){
			$("#mobile_dark").removeClass("ui-widget-overlay").hide();
			$(this).parents("div.overlay").hide();
		});

	} else {
		var options = {modal: true, autoOpen: false, draggable: true, hide: 'slide', show: 'slide', resizable: true, width: 980, height: 450};
		ajax_overlay = $("#ajax_overlay").dialog({
			modal: true, autoOpen: false, width: 100, height: 100, resizable: false, draggable: false,
			closeOnEscape: true, dialogClass: 'overlay_suppress'
		});
		general_force_overlay = $("#general_force_overlay").dialog(
			$.extend({}, options, {
				title: 'Please upgrade your account...',
				width: 600, height: 'auto'})
		);
		welcome_overlay = $("#welcome_overlay").dialog(
			$.extend({}, options, {
				title: 'Thanks for adding your account...',
				width: 600, height: 'auto'})
		);
		list_overlay = $("#list_overlay").dialog(
			$.extend({}, options, {
				title: 'Twitter users by segment'})
		);
		track_overlay = $("#track_overlay").dialog(options);
		credits_overlay = $("#credits_overlay").dialog(
			$.extend({}, options, {
				title: 'Everything you always wanted to know about credits (but were afraid to ask)',
				width: 600, height: 600})
		);
		saved_overlay = $("#saved_overlay").dialog(
			$.extend({}, options, {
				title: 'Your Saved Reports'})
		);
		download_overlay = $("#download_overlay").dialog(
			$.extend({}, options, {
				title: 'Download user data',
				width: 600, height: 450})
		);
	}

	$("#nav_bar_internal").on("click", "div.tabbable", function(){
		preview.destroy();
		if (is_animating === 1) {
			return false;
		}
		is_animating = 1;

		$("div.tabbable_selected", "#nav_bar_internal").toggleClass("tabbable").toggleClass("tabbable_selected");

		var new_tab = $(this);
		var toShow = new_tab.attr("id").substr(7);
		var visible = $("div.tab_content:visible", "#tab_internal");
		var next_visible = $("#tab_" + toShow);
		
		if (visible.length) {
			//if we already have a tab displayed
			if (is_mobile) {
				visible.hide(); toggle_them();
			} else {
				visible.hide("blind", {}, "normal", function() {
					toggle_them();
				});
			}
		} else {
			//if we dont already have a tab displayed
			if ($("#preview_wrap").is(':visible')) {
				if (is_mobile) {
					$("#preview_wrap").hide(); toggle_them();
				} else {
					$("#preview_wrap").hide("blind", {}, "normal", function(){
						toggle_them();
					});
				}
			} else {
				toggle_them();
			}
		}

		function toggle_them(){
			$("#outer_wrap").removeClass("has_not_tab").addClass("has_tab");			
			new_tab.toggleClass("tabbable").toggleClass("tabbable_selected");
			if (is_mobile) {
				next_visible.show(); is_animating = 0;
			} else {
				next_visible.show("blind", {}, "normal", function() {
					is_animating = 0;
				});
			}
		}		
		
		$("#the_page").fadeOut(function(){
			$("#the_page").html("");
		});
		if (new_tab.attr("id") == "button_track"){
			$.ajax({
				type: "GET",
				url: "/?default_track=1",
				success: function(msg){
					//lets make sure the user hasnt moved to another tab...
					if ($("#button_track").hasClass("tabbable_selected")) {
						$("#the_page").html(msg).fadeIn();
						track = new Track(sg_data);
					}
				} 
			});		

		} else if (new_tab.attr("id") == "button_sort"){
			$.ajax({
				type: "GET",
				url: "/?default_sort=1",
				success: function(msg){
					//lets make sure the user hasnt moved to another tab...
					if ($("#button_sort").hasClass("tabbable_selected")) {
						$("#the_page").html(msg).fadeIn();
						wonk_highlights();
					}
				} 
			});		
		} else {
			$("#the_page").fadeIn();
		}
	});

	$("select.subscribable", "#tab_body").on("change", "", function(){
		if ($(this).val() == "subscribe"){
			window.location = "/buy";
			return false;
		}
	});

	//this is for NON-overlays (as determined by presence in #the_page... overlays are not within)
	$("table.listing_table", "#the_page").on("click", "th.sorter", function(){
		window.location = $(this).find("a").attr("href");
		return false;
	});
	//this is for OVERLAY links
	$("div.overlay").on("click", "th.sorter, div.pager a.paging", function(){
		var url = $(this).find("a").attr("href") ? $(this).find("a").attr("href") : $(this).attr("href");
		var overlay_internal = $(this).parents("div.overlay").find(".overlay_internal");
		$.ajax({
			type: "GET",
			url: url,
			beforeSend: function(msg){
				overlay_internal.html('<center><img src="ajax-loader.gif" alt=""/></center>');
			},
			success: function(msg){
				overlay_internal.html(mobile_close + msg + mobile_close);
				wonk_highlights();
			}
		});
		return false;
	});


	$(".is_not_upgraded").live("click", function(){show_purchase_overlay();});
	$(".is_upgraded").live("click", function(){
		var me = $(this);
		if (me.hasClass("download_general")) {
			show_download_overlay();
		} else if (me.hasClass("download_section")) {
			show_download_overlay(me.children("div.session").html(), me.children("div.count").html(), me.children("div.target").html());
		} else if (me.hasClass("follow_change")) {
			//un/follow action for subscribers
			//get pid to un/follow
			var pid = me.parent().attr("id").substring(4);
			//get whether we want to follow or unfollow
			var button = me.children("input");
			var type = button.val();
			var opposite = button.val().match(/unfollow/) ? "follow" : "unfollow";
			me.removeClass("follow_change").addClass("inbetween");
			$.ajax({
				type: "GET",
				url: "/?follow_change=" + pid + "&type=" + type,
				success: function(msg){
					//not always success, have to check msg for ERROR syntax
					if (msg.match(/ERROR/)) {
						var scrn = me.parents("tr.person").find("a.scrn").html();
						alert("Could not " + type + " @" + scrn + ": " + msg);
						me.html('');
					} else {
						me.removeClass("inbetween").addClass("follow_change").toggleClass("button_unfollow");
						button.val(opposite);
						me.parents("tr.person").find("td.social_left").toggleClass("youfollow").toggleClass("youdontfollow");
						wonk_highlights();
					}
				}
			});
		}
	});

	var pay_tab = $("td.pay_tab", "#payment_options");
	pay_tab.click(function(){
		pay_tab.removeClass("is_selected");
		$(this).addClass("is_selected");
		var what = $(this).attr("id").split(/_/)[0];
		$("div.tab_body_like", "#payment_choice").hide();
		$("#" + what + "_menu").show();
	});

	$(".twitter_login").live("click", function(){
		window.location = "/login";
		return false;
	});

	$("#select_user").change(function(){
		var swap_to = $(this).val();
		if (is_subscriber == 0) {
			show_purchase_overlay();
		} else {
			window.location = "/switch-user?pid=" + swap_to;
			return false;
		}
	});

	$("#bio_search_form").live("submit", function(){
		//weed out null form fields
		var form_array = $(this).serializeArray();
		var query_string;
		for (var key in form_array) {
			if (form_array[key].value) {
				query_string = query_string ? query_string + "&" : "?";
				query_string += form_array[key].name + "=" + escape(form_array[key].value);
			}
		}
		if (query_string){
			window.location = "/bio/" + query_string;
		}
		
		return false;
	});

	$("#tweet_text_form").live("keyup", function(){
		if ($(this).val().length > 140) {
			$(this).val($(this).val().substr(0, 140));
		}
	});

	$("#welcome_form").live("submit", function(){
		close_overlay(welcome_overlay);
		$.post("/", $(this).serialize());
		return false;
	});

	$("#email_request_form").live("submit", function(){
		$.post("/", $(this).serialize());
		$("#alert_ribbon").slideUp(function(){
			$(this).html("<b>Thank you!</b> Please add support@followerwonk.com to your whitelist, and check your e-mail for our confirmation mail.</b>").slideDown();
		});
		return false;
	});

	if ($.cookie("force_overlay")) {
		if ($.cookie("force_overlay") === "welcome") {
			open_overlay(welcome_overlay);
		} else if ($.cookie("force_overlay").match(/track_limit/)) {
			open_overlay(general_force_overlay);
		}
		$.cookie("force_overlay", null);

	} else {
		//only do alert_ribbon if we arent doing a force overlay (as the force overlay messages are often redundant to alert msgs)
		if ($("div.an_alert", "#alert_holder").length) {
			$("#alert_ribbon").html($("div.an_alert").html()).slideDown();
		}
	}
	
	preview			= new Preview();
	track			= new Track(sg_data);
	analyze			= new Analyze(pies);	

	wonk_highlights();
}

$(document).ready(ready_function);


