$(document).ready(function(){
	
	var dashboard_tabs = $('.bsi_links > a[class!=collapse]');
	dashboard_tabs.click(function() {
		dashboard_tabs.removeClass('active');
		$(this).addClass('active');
	});

	var start_page = self.document.location.hash.substring(1);
	var start_tab = dashboard_tabs.filter('a[href=#' + start_page + ']');

	if(start_tab.length) {
		start_tab.click();
	} else {
		dashboard_tabs.first().click();
	}
	
	attachProfilePopups();
	
});

	
/***********************\
* Profile Popup         *
\***********************/

function attachProfilePopups() {
	profile_links = $('.profile_popup');

	if(profile_links.length) {
		
		//remove any lingering mouse events
		profile_links.unbind();

		profile_links.mouseover(
			function() {
				var this_link = $(this);
				var this_height = this_link.height();
				
				//create elements
				var wrapper = $('<div />').css({
					position: 'relative', 
					display: 'inline'
				});
				var popup = $('<div class="bsi_profile_popup" />').css({
					bottom: this_height
				}).hide();
				
				$.post("process/dashboard.php",
				{ 
					action: 'profilePopup',
					options: $(this_link).attr('rel')
				}, 
				function (data){ 
					photo = $('<img class="avatar" />').attr({
						src:  '/userfiles/profile/'+data.profile_image,
						width: '25',
						height: '25'
					}).appendTo(popup);
									
					//create p
					text = $('<p class="txt" />').html(data.content).appendTo(popup);
					
					//add buttons
					msg_btn = $('<a href="/?page=dashboard&mem_id=' + data.id + '#inbox_compose" class="msg_btn" />').appendTo(popup);
					pro_btn = $('<a href="/?page=profile&mem_id=' + data.id + '" class="pro_btn" />').appendTo(popup);
					add_btn = $('<a href="#" class="add_btn" onclick="networkInviteMsg('+data.id+');" />').appendTo(popup);
				},"json");

				//insert and show elements
				this_link.wrap(wrapper).before(popup);
				popup.slideDown('fast');
				
				this_link.parent().mouseleave(
					function() {
						//prevents mouseout from happening more than once before removal
						$(this).unbind();
						
						//clean up
						popup.slideUp('fast', function() {
							popup.remove();
							this_link.unwrap();
						});
					}
				);
			}
		);
	}
}

function loadDashboardSection(section, target, loadtiny, data_id) {
	$.post("/process/dashboard.php",
	{ 
		action: 'loadDashboardSection',
		section: section,
		data_id: data_id
 	}, 
 	function (data){
		//hide target section
 		$('#' + target).slideUp('fast', function() {
			//load content to target section
	 		$(this).html(data.content);
			//give the last <li> in each <ul> a special class
			$('ul > li:last-child').addClass('last');
			//show target section
	 		$(this).slideDown('slow', function() {
				//load tinyMCE if required
	 			if(loadtiny) { loadTiny(); }
	 		});
		});
	 },"json");
}

function collapseDashboardSection(target) {
	$('#' + target).slideUp('fast');
	$('#' + target).prev().children('a').removeClass('active');
}

function showOverlay(content, delay) {
	//remove any existing overlays
	$('#bsi_overlay').remove();
	//build overlay and content
	var overlay = $('<div id="bsi_overlay"><div class="bsi_overlay content">' + content + '</div></div>').hide();
	if(delay == '0') {
		//append to body and don't fade out
		overlay.appendTo($('body')).fadeIn();			
	} else {
		//set default delay if undefined
		if(delay == undefined) { delay = 2000; }
		//append to body and fade out after delay
		overlay.appendTo($('body')).fadeIn().delay(delay).fadeOut();	
	}
}

function changeTo(section) {
	$.post("/process/dashboard.php",
	{ 
		action: 'loadSelect',
		section: section
 	}, 
 	function (data){
		$('#to_select_replace').html(data.output);
	},"json");
}

function saveDashboardSettings() {
	$.ajaxSetup({
	  global: false,
	  type: "POST",
	  ajaxStart: showOverlay('Saving your settings...'),
	  ajaxComplete: showOverlay('Your setting information has been saved.')
	});
	
	$.post("/process/dashboard.php",
	{ 	
		action: 'saveDashboardSettings',
		email: $('#email').val(),
		old_pass: $('#old_pass').val(),
		new_pass: $('#new_pass').val(),
		notify: $('#notify:checked').val(),
		twitter_sync: $('input[name=twitter_sync]:checked').val(),
		short_url_service: $('#short_url_service').val(),
		bitly_login: $('#bitly_login').val(),
		bitly_api: $('#bitly_api').val()
	},
	function (data){ 
 		$('#old_pass').val('');
 		$('#new_pass').val('');
 		if(data.form_errors.length>0) {
			for (var i=0;i<data.form_errors.length;i++) {
				switch(data.form_errors[i]) {
					case 'restricted':
						$('#email').after('<span class="hint">The email you requested to change is already a registered email.</span>');
						break;
					case 'pass_restricted':
						$('#old_pass').after('<span class="hint">The new password or old password did not match, password has not changed.</span>');
						break;
				}
			}
		}
		else {
			if(data.changed) {
				window.location.href = '/?page=index';
			}
			else {
				injectMessage('Settings have been changed','success',8000);
			}
		}
	},"json");
}

function saveProfile() {
	$('#ed_content').val(tinyMCE.get('elm1').getContent());
	$('#basicForm').submit();
}

function saveBusiness() {
	$.ajaxSetup({
	  global: false,
	  type: "POST",
	  ajaxStart: showOverlay('Saving your buisness information...'),
	  ajaxComplete: showOverlay('Your business information has been saved.')
	});
	
	var chart_active = $("#chart_active").val() || [];
	var expertise = $("#expertise").val() || [];
	
	$.post("/process/dashboard.php",
	{ 
		business_submit: '1',
		type: $('#type').val(),
		type_other: $('#type_other').val(),
		employees: $('#employees').val(),
		units: $('#units').val(),
		franchise: $('input[name=franchise]:checked').val(),
		training: $('#training').val(),
		spent_chk: $('input[name=spent]:checked').val(),
		spent: $('#spent').val(),
		position: $('#position').val(),
		pos_other: $('#pos_other').val(),
		dept_report: $('#dept_report').val(),
		dept_report_other: $('#dept_report_other').val(),
		dept_tenure: $('#dept_tenure').val(),
		chart_tenure: $('#chart_tenure').val(),
		confs: $('#confs').val(),
		chart_active: chart_active.join("|"),
		expertise: expertise.join("|"),
		chart_heard: $('#chart_heard').val(),
		chart_heard_other: $('#chart_heard_other').val()
 	}, 
 	function (data){
 		if(data.completed!=1) {
			for (var i=0;i<data.form_errors.length;i++) {
				switch(data.form_errors[i]) { 
					case 'type':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select your organization type.</span>');
						break;
					case 'type_require_x':
						$('#type').after(' <span class=\'error\'>You selected other, please enter the type in the other field below.</span>');
						break;
					case 'employees':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter in the number of employees (approx).</span>');
						break;
					case 'units':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter in the number of units (approx).</span>');
						break;
					case 'franchise':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please answer if you are a franchise of not.</span>');
						break;
					case 'training':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter amount of people in your training department.</span>');
						break;
					case 'spent':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter the amount spent (approx).</span>');
						break;
					case 'spent_require_x':
						$('#spent').after(' <span class=\'error\'>Please enter amount spent if applicable.</span>');
						break;
					case 'position':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select your position.</span>');
						break;
					case 'position_require_x':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>You selected other,  please enter the position in the other field below.</span>');
						break;
					case 'dept_report':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select what department does the training.</span>');
						break;
					case 'dept_report_require_x':
						$('#dept_report').after(' <span class=\'error\'>You selected other, please enter the department in the other field below.</span>');
						break;
					case 'dept_tenure':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select your tenure in your training department.</span>');
						break;
					case 'chart_tenure':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select your tenure with CHART.</span>');
						break;
					case 'confs':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select the number of CHART conferences you attended.</span>');
						break;
					case 'chart_active':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select in the ways you are active in CHART.</span>');
						break;
					case 'expertise':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select what you expertise you are willing to share with CHART members.</span>');
						break;
					case 'chart_heard':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select how you heard about CHART.</span>');
						break;
					case 'chart_heard_require_x':
						$('#chart_heard').after(' <span class=\'error\'>You selected other, please enter your answer in the other box below.</span>');
						break;
				}
			}
		}
		else {
			injectMessage('Business Information Saved','success',8000);
		}
 	},"json");
}

function sendMessage() {
	$.ajaxSetup({
	  global: false,
	  type: "POST",
	  ajaxStart: showOverlay('Sending your message...'),
	  ajaxComplete: showOverlay('Your message has been sent.')
	});
	
	$.post("/process/dashboard.php",
	{ 
		send_message: '1',
		to: $('#compose_name').val(),
		title: $('#compose_subject').val(),
		message: tinyMCE.get('elm1').getContent()
 	}, 
 	function (data){ 
 		//reset fields
 		$('#compose_subject').val('');
 		$('#compose_body').val('');
 	},"json");
}

/*
function viewMessage(id) {
	$.post("process/dashboard.php",
	{ 
		view_message: '1',
		id: id
 	}, 
 	function (data){ 
 		$('#bsi_inbox_content').html(data.msg_format);
	 },"json");
}
*/

function deleteMsg(id,type,from) {
	$.post("/process/dashboard.php",
	{ 
		delete_message: '1',
		id: id,
		type: type
 	}, 
 	function (data){ 
        if(from) {
            window.location = "/inbox/";
        }
        else {
    		//$('#new_message_count').html(data.msg_count);
    		$('#msg_'+id).remove();
        }
	 },"json");
}

function replyMsg(id,from,title) {
	loadDashboardSection('inbox_compose','bsi_inbox_content',true,from+'|'+'RE: '+title);
}

function updateStatus() {
	if($('#my_status').val()) {
		$.post("/ajax/dashboard/update_status.php",
		{ 
			action: 'updateStatus',
			status: $('#my_status').val()
	 	}, 
	 	function (data){ 
	 		$('#my_status').val('');
			injectMessage('Your status has been updated','success',8000);
			$('#my_current_status').html('<strong>Current Status</strong>: "<em>'+data.status+'</em>"</span>');
		 },"json");
	 }
	 else {
	 	showOverlay('Please enter in text to update your status.');
	 }
}

function saveBlogSettings(id) {
	if($('#custom_category_val').val()) {
		category = $('#custom_category_val').val();
		custom = true;
	}
	else {
		category = $('#category').val();
		custom = false;
	}
	
	$.post("/process/dashboard.php",
	{ 
		action: 'saveBlogSettings',
		title: $('#blog_title').val(),
		desc: $('#blog_description').val(),
		category: category,
		custom: custom
 	}, 
 	function (data){ 
 		if(!data.error) {
			if(id>0) {
	 			showOverlay('Your blog has been updated.');
			}
			else {
				showOverlay('Your blog has been created.');
			}
		}
		else {
			showOverlay(data.error);
		}
	 },"json");
}

function addContributor() {
	$.post("/process/blogs.php",
	{ 
		action: 'addContributor',
		id: $('#chart_users').val()
 	}, 
 	function (data){ 
 		alert('The member has been mailed about the request, if they accept you will see them under "Contributors to my Blog" section in the blog section of the dashboard.');
 	},"json");
}

function removeContributor(user) {
	$.post("/process/blogs.php",
	{ 
		action: 'removeContributor',
		user: user
 	}, 
 	function (data){ 
 		alert('The member has been removed as a contributor to your blog.');
 		window.location = '/?page=dashboard';
 	},"json");
}

function removeContribution(id) {
	$.post("/process/blogs.php",
	{ 
		action: 'removeContribution',
		id: id
 	}, 
 	function (data){ 
 		alert('You have removed your contribution from this blog.');
 		window.location = '/?page=dashboard';
 	},"json");
}

function deleteBlogPost(post_id) {
	var answer = confirm('Are you sure you want to delete this blog post?  This can not be undone.');
	if(answer) {
		$.post("/process/blogs.php",
		{ 
			action: 'deletePost',
			post_id: post_id
	 	}, 
	 	function (data){ 
	 		showOverlay('This blog post has been deleted');
	 		loadDashboardSection('dashboard_blogs', 'bsi_dashboard_content');
	 	},"json");
	 	//if(!data) {
	 		//alert('You do not have permission to delete this blog post');
	 	//}
 	}
}

function saveEvent(id) {
	$.post("/process/events.php",
	{ 
		action: 'saveEvent',
		id: id,
		title: $('#event_title').val(),
		start_date: $('#start-date').val(),
		end_date: $('#end-date').val(),
		time: $('#time').val(),
		building: $('#building').val(),
		location: $('#location').val(),
		city: $('#city').val(),
		state: $('#state').val(),
		website: $('#website').val(),
		content: tinyMCE.get('elm1').getContent()
 	}, 
 	function (data){ 
		if(data.success!=1) {
			$('.error').remove();
			for (var i=0;i<data.form_errors.length;i++) {
				switch(data.form_errors[i]) {
					case 'event_title':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter an event title.</span>');
						break;
					case 'start_date':
						$('#start-date').after(' <span class=\'error\'>Please select the start date.</span>');
						break;
					case 'end_date':
						$('#end-date').after(' <span class=\'error\'>Please select the end date.</span>');
						break;
					case 'time':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter some sort of time for the event.</span>');
						break;
					case 'location':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter the address where the event will be located.</span>');
						break;
					case 'city':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter the city where the event will be located.</span>');
						break;
					case 'state':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select the state where the event will be located.</span>');
						break;
					case 'content':
						$('#elm1').after(' <span class=\'error\'>Please enter a description of the event at least 100 chars.</span>');
						break;
				}
			}
		}
		else {
	 		showOverlay('Your event '+$('#event_title').val()+' has been saved');
	 		loadDashboardSection('dashboard_events', 'bsi_dashboard_content', true);
		}
 	},"json");
}

function removeEvent(id) {
	var answer = confirm('Are you sure you want to delete this event?  This can not be undone.');
	if(answer) {
		$.post("/process/events.php",
		{ 
			action: 'deleteEvent',
			id: id
	 	}, 
	 	function (data){ 
	 		showOverlay('This event has been deleted');
	 		loadDashboardSection('dashboard_events', 'bsi_dashboard_content', true);
	 	},"json");
 	}
}

function saveJob(id) {
	$.post("/process/jobs.php",
	{ 
		action: 'saveJob',
		id: id,
		title: $('#title').val(),
		company: $('#company').val(),
		location: $('#location').val(),
		city: $('#city').val(),
		state: $('#state').val(),
		date_needed: $('#start-date').val(),
		compensation: $('#compensation').val(),
		website: $('#website').val(),
		content: tinyMCE.get('elm1').getContent()
 	}, 
 	function (data){ 
		if(data.success!=1) {
			$('.error').remove();
			for (var i=0;i<data.form_errors.length;i++) {
				switch(data.form_errors[i]) {
					case 'title':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter the job title.</span>');
						break;
					case 'company':
						$('#company').after(' <span class=\'error\'>Please enter in the company name.</span>');
						break;
					case 'city':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter the city where the job will be located.</span>');
						break;
					case 'state':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please select the state where the job will be located.</span>');
						break;
					case 'date_needed':
						$('#start-date').after(' <span class=\'error\'>Please select the start date of the job.</span>');
						break;
					case 'compensation':
						$('#'+data.form_errors[i]).after(' <span class=\'error\'>Please enter some sort of compensation for this job.</span>');
						break;
					case 'content':
						$('#elm1').after(' <span class=\'error\'>Please enter the job description of at least 100 chars.</span>');
						break;
				}
			}
		}
		else {
 			injectMessage('Your job posting '+$('#title').val()+' has been saved','success',8000);
		}
 	},"json");
}

function removeJob(id) {
	var answer = confirm('Are you sure you want to delete this job posting?  This can not be undone.');
	if(answer) {
		$.post("/process/jobs.php",
		{ 
			action: 'deleteJob',
			id: id
	 	}, 
	 	function (data){ 
	 		injectMessage('This job posting has been deleted','success',8000);
	 	},"json");
 	}
}

function inviteControl(id,mode) {
	
	$.post("/process/network.php",
	{ 
		action: mode+'Invite',
		id: id
 	}, 
 	function (data){ 
 		showOverlay(data.message);
 		loadDashboardSection('network_invites', 'bsi_network_content');
 	},"json");
}

function networkInviteMsg(id) {
	showOverlay('<p>Your Message: <input id="invite_msg" type="text" style="width:96%;" value="Please join my network." /></p><p><a href="#" onclick="networkInvite('+id+')" class="button small">Invite to My Network</a><a href="#" onclick="$(\'#bsi_overlay\').remove();" class="button small">Cancel</a></p>', 0);
}

function networkInvite(id) {
	$.post("/process/network.php",
	{ 
		action: 'requestInvite',
		id: id,
		invite_msg: $('#invite_msg').val()
 	}, 
 	function (data){ 
 		$('#bsi_overlay').remove();
 		if(data.error) {
 			showOverlay('There is already a network established or one pending.');
 		}
 		else {
			window.location = '/?page=dashboard#network_invites';
		}
 	},"json");
}

function cancelRequest(id,type) {
	$.post("/process/groups.php", { 
		action: 'cancelRequest',
		id: id,
        type: type
	}, 
 	function (data){ 
 		if(data.success) {
	 		injectMessage('You have successfully canceled the request to this group.','success',8000);
            $('#group_'+id).remove();
 		} else {
			if(data.reason) {
				injectMessage('The request has been canceled.','error',8000);
            } else {
 			    injectMessage('You do not have permission for this action.','error',8000);
            }
 		}
 	},"json");
}

function acceptGroupInvite(id) {
	$.post("/process/groups.php",
	{ 
		action: 'acceptInvite',
		id: id
 	}, 
 	function (data){ 
 		if(data.success) {
	 		injectMessage('You have been successfully added to the group','success',8000);
 		}
 		else {
 			injectMessage('You are not the requested member to do this action.','error',8000);
 		}
 	},"json");
}

function acceptGroupRequest(id) {
	$.post("/process/groups.php", { 
		action: 'acceptRequest',
		id: id
 	}, 
 	function (data){ 
 		if(data.success) {
	 		injectMessage('The member has been successfully added to the group','success',8000);
	 		//if($('#invites').is(':last-child')) {
	 		//	$('#invite_box').slideUp();
	 		//}
	 		//else {
	 			$('#invite_'+id).remove();
 			//}
 		} else {
 			injectMessage('You are not the owner of this group.','error',8000);
 		}
 	},"json");
}

function leaveGroup(id) {
	$.post("/process/groups.php",
	{ 
		action: 'leaveGroup',
		id: id
 	}, 
 	function (data){ 
 		if(data.success) {
 			if(data.owner) {
	 			injectMessage('You have successfully removed the member from this group.','success',8000);
 			}
 			else {
 				injectMessage('You have successfully removed yourself from this group.','success',8000);
 			}
	 		//if($('#groups').is(':last-child')) {
	 			//$('#group_box').slideUp();
	 		//}
	 		//else {
	 			$('#group_'+id).remove();
 			//}
 		}
 		else {
 			injectMessage('You do not have permission to remove members from groups.','error',8000);
 		}
 	},"json");
}

function inviteToGroup(group_id) {
	$.post("/ajax/groups/invite.php",
	{ 
		group_id: group_id,
        id: $('#new_invite').val()
 	}, 
 	function (data){ 
        $('#new_invite').val('');
 		if(data.success) {
			injectMessage('You have successfully invited this member.','success',8000);
 		}
 		else {
 			injectMessage('This member is already part of the group or has an invite pending.','error',8000);
 		}
 	},"json");
}

function postWhiteboard(id,post_id,field) {
	$('#post_whiteboard').fadeTo("slow",0.25);
	$.post("/process/groups.php",
	{ 
		action: 'whiteboardPost',
		id: id,
        post_id: post_id,
		content: $(field).val()
 	}, 
 	function (data){ 
 		if(data.success) {
			injectMessage('You have successfully left a whiteboard post.','success',8000);
			window.location = '/groups/whiteboard/id/'+id+'/';
 		}
 		else {
 			injectMessage('You do not have permission to make a whiteboard post on this group.','error',8000);
 		}
 	},"json");
}

function setupWhiteboardComment(id,post_id,where) {
	/* Add comment field */
	var field = $('<input type="text" class="comment_field" value="Type a message..." />').insertBefore(where).click(function() {
		if(this.value == 'Type a message...') this.value = '';																									
	});
	var button = $('<button class="button small">Post</button>').insertAfter(where).click(function() {
		postWhiteboard(id,post_id,field);																						   
	});
}

