// requires this bit of code 
// 
// var tabs = Array();
// tabs["tab_summary"] = Array("sub", "feedback", "watch_list");
// tabs["tab_qa"] = Array("sub");
// tabs["tab_settings"] = Array();
//
$(document).ready(function() {
	
	if(typeof default_tab != 'undefined')
	{
		load_tab(default_tab);

		$("#profile_nav li.clickme").click(function(){
			// If this is the current selected tab, do nothing.
			if(this == $("#profile_nav li.current")[0]) {
				return;
			}
	
			// Load the proper pages for this tab.
			load_tab(this.id);
		});
	}
});

function load_tab(tab_id, page_list) {
	// Slight condition to show/hide the "mark all as read" link
	if(tab_id == 'tab_settings')
		$('#mark_all_read').hide();
	else
		$('#mark_all_read').show();
	
	// Unselect the current tab
	$("#profile_nav li.current").removeClass("current");

	// Make this current tab the new active one.
	$("#"+tab_id).addClass("current");

	// Make the current content go away.
	$("#profile_content").empty();

	var xyz;
	if(page_list) {
		xyz = page_list;
	} else if(tabs[tab_id]) { 
		xyz = tabs[tab_id];
	}

	var num_pages = xyz.length;
	for(var i=0; i<num_pages; i++) {
		// Check if an id was already provided.
		var tmp = xyz[i].split(",");
		var url;
		var div_id;
		if(tmp[1]) {
			url = tmp[0];
			div_id = tmp[1];
		} else {
			url = xyz[i];
			div_id = xyz[i].split("?")[0];
		}
		load_page(url, "container_" + div_id );
	}
}

function load_page(url, div_id, no_top) {
	// make sure that a blank page doesn't get submitted.
	if(!url) {
		return;
	}

	$("#loading_text").html('Loading...');
	
	if(div_id) {
		if( !document.getElementById(div_id) ) { 
			$("#profile_content").append('<div id="' + div_id + '"></div>');
		}
	}

	var foo = div_id;

	// Get the contents for this tab.
	var url = "/profile/"+url;
	$.get(url, function(html){
		$("#"+div_id).html(html).show();;

		$("#loading_text").html('&nbsp');

		// Add all events to the new page loaded here.
		// Do not try to add events outside of here to the page
		// because they may not get loaded since the page contents
		// are loaded dynamically.
		var o_checks = $("#"+div_id).find(".check_off, .check_on");
		o_checks.mouseover(function(){
			$(this).css("cursor", "pointer");
		});
		o_checks.click(function(){
			var o = $(this);
			var x = o.attr("className").split("_")[1];
			if( x == "on" ) // Turn it off 
			{
				o.attr("className", "check_off");
			} else // Turn it on
			{
				o.attr("className", "check_on");
			}
		});

		$("#"+div_id).find(".row_header .title").mouseover(function(){
			$(this).css("cursor", "pointer");
		});

		$("#"+div_id).find(".row_header .title").click(function(){ 
			var self = $(this);

			$("#"+div_id).find(".container").slideToggle(function(){
				var data = 
				{
					action: 'save',
					name: self.attr('id'),
					value: null
				};
				if(this.offsetHeight == 0) // Hide it 
				{ 
					self.addClass('title_closed');
					data.value = 0;
				} else { // Show it
					self.removeClass('title_closed');
					data.value = 1;
				}
				$.get('/json/user_preference', data);
			});
		});

		// Do more or less rows buttons
		var row_buttons = $("#"+div_id).find(".less_rows, .more_rows");

		row_buttons.hover(
			function()
			{
				this.src = this.src.replace('_off', '_on');
			},
			function()
			{
				this.src = this.src.replace('_on', '_off');
			}
		);

		row_buttons.click(function()
		{ 
			var profile_question_list = $("#"+div_id).find(".profile_question");
			var total = profile_question_list.length;
			var hidden = $("#"+div_id).find(".hide").length;
			var shown = total - hidden;
			
			var direction = ($(this).attr('class') == 'more_rows') ? 1 : -1 ;
			if(direction < 0 && 1 < shown)
			{
				$(profile_question_list[shown+direction]).addClass("hide");
				if(1 == shown + direction)
				{
					this.src = this.src.replace('_off', '_disabled').replace('_on', '_disabled');
				}
				if(total > shown + direction)
				{
					var image = $(this).siblings(".more_rows").attr("src");
					image = image.replace('_disabled', '_off');
					$(this).siblings(".more_rows").attr("src", image);
				}
			}
			if(direction > 0 && total > shown)
			{
				$(profile_question_list[shown]).removeClass("hide");
				if(total == shown + direction)
				{
					this.src = this.src.replace('_off', '_disabled').replace('_on', '_disabled');
				}
				if(1 <= shown)
				{
					var image = $(this).siblings(".less_rows").attr("src");
					image = image.replace('_disabled', '_off');
					$(this).siblings(".less_rows").attr("src", image);
				}
			}
			save_num_rows(div_id, shown + direction);
		});

	});
	if(!no_top)
		backToTop();
}

function save_num_rows(div_id, per_page)
{
	if(per_page < 1 || per_page > 20)
		return;
	var x = div_id.replace('container_', '');
	var pref_name = 'profile_' + x + '_per_page';
	var data = 
	{
		action: 'save',
		name: pref_name,
		value: per_page
	};
	$.get('/json/user_preference', data);
}

function switch_sub_nav(url, div_id, o)
{
	$('#sub_nav span').removeClass();
	o.addClass('current');
	load_page(url, div_id);
}

// Form submissions for IE
function submit_form(o, callback)
{
	if(!callback)
		callback = 'form_handler';
	
	callback = eval(callback);
	var options = { success: callback };
	o.ajaxSubmit(options); 
	return false;
}

function form_handler(responseText, statusText)  
{ 
	$.popup.inline(responseText, {height: 'auto'});	 
}

// post-submit settings account
function form_handler_settings_account(responseText, statusText)
{
	if(responseText)
		$.popup.inline(responseText);
	load_page('settings_account', 'container_settings');
}

// post-submit settings password
function form_handler_settings_password(responseText, statusText)
{
	$.popup.inline(responseText);
	if(responseText == "<div class='center'>Your password has been updated.</div>")
	{
		load_page('settings/password', 'container_settings');
 	}
}


// post-submit callback 
function form_handler_watch_list(responseText, statusText)  
{ 
	if(responseText)
		$.popup.inline(responseText);
	load_page('settings_watch_list', 'container_settings'); 
}

// post-submit callback 
function form_handler_settings_profile(responseText, statusText)  
{ 
	if(responseText == "<div class='center'>Your profile has been updated</div>")
		location.href = "/profile/?tab=settings&page=settings_profile";
	else 
		$.popup.inline(responseText, {height: 'auto'});	 
}

function send_phone_confirm()
{
	$.getJSON('/profile/phone', {action:'send'},
			function(response)
			{
				$('#phone_confirm_txt').html(response.html);
			}
			);
	return false;
	
}


function enter_phone_confirm(num)
{
	$.getJSON('/profile/phone', {action:'confirm', code:num },
			function(response)
			{
				console.log(response);
				$('#phone_confirm_txt').html(response.html);
			}
			);
	return false;
}

















