
/* Helper for writing to firebug console if available */

function logit(msg) {
    // if available, write to fb console
    if (window.console && window.console.firebug) {
        console.log('logit >> ' + msg);
    
    // otherwise write to browserÕs js console
    } else {
        setTimeout(function() {
            throw new Error("logit >> " + msg);
        }, 0);
    }
}

/* end error writing helper */

/* Class instances and global vars */
var _home = (window.location.href.indexOf('designsquad_dev') < 0) ? '/designsquad/' : '/designsquad_dev/',
_root = document.location.hostname + _home,
_logged_in = false,
_heroes = new Array('engineeradam','judylee','meemer115','lbonkygirl','dakim211','nateds','anads','anneliseds','juands','lindseyds','wesuyds','zachds','deweyds','deysids','jason2ds','kimds','leahds','nick2ds','tomasds','trejondads','ronniedsn','jendsn', 'mariamdsn', 'bertdsn', 'eduardadsn', 'juandsn' , 'beatrizdsn', 'fabrettodsn', 'felipedsn','justindsn'),
_numHeroBgImages = 14; 		/* the number of images available for cycling through on the heroes index page - changes for each episode release */
_overlays = null,			/* provides access to most overlay objects created with jQuery Tools */
_detailOverlay = null,		/* provides access to the submission detail overlay object */
_browser = new Browser(),	/* provides methods relevant to the browser window */
_resultsList = new List(),	/* provides methods and data relevant to all generated lists of UGC */
_html = new Html();			/* provides methods for creating all html strings written to the dom */


/* Browser Class: Manages browser behavior and info */
function Browser() {
	this.getUrlVars=function() {
		var vars = {};
		var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
			vars[key] = value.replace('#','');
		});
		return vars;
	}

	this.scrollTo=function(element, pace) {
		if (!pace){ pace = 1500; }
		var top = element.offset().top;
		$('html,body').animate({scrollTop: top}, pace);
	}
}


/* List Class: Manages results list, sort order, filtering, and display range */
function List() {

	// Private variables
	var currRange = 0;					// default range value for db selection

	var profileRanges = new Object();
	profileRanges['my-stuff'] = 0;		// profile range values for db selection (page has multiple tabs with different data sets)
	profileRanges['fave-stuff'] = 0;
	profileRanges['fave-peeps'] = 0; 
	profileRanges['my-fans'] = 0;

	var profileTotals = new Object();	// profile total values for more button data display
	profileTotals['my-stuff'] = 0;
	profileTotals['my-stuff-all'] = 0;	// includes pending items
	profileTotals['fave-stuff'] = 0;
	profileTotals['fave-peeps'] = 0;
	profileTotals['my-fans'] = 0;

	var numProjPerPage = 9;				// how many trunks will be shown on projects page
	var numSubmissionsPerPage = 25;		// how many submissons will be shown on project detail page or profile tab

	var sort = 'recent';
	var filter = 'sketches';


	// Getters
	this.getSort=function() { return sort; }
	this.getFilter=function() { return filter; }
	this.getNumProj=function() { return numProjPerPage; }
	this.getNumSubmissions=function() { return numSubmissionsPerPage; }

	this.getRange=function() { return currRange; }
	this.getCurrProfileRange=function(tab) { return profileRanges[tab]; }
	this.getProfileTotals=function(tab) { return profileTotals[tab]; }


	// Setters
	this.popular=function() { sort = 'popular'; if ($('#results').find('ul.three-col').size()) { filter = 'sketches'; } }
	this.recent=function() { sort = 'recent'; if ($('#results').find('ul.three-col').size()) { filter = 'sketches'; } }
	this.featured=function() { filter = 'featured'; }
	this.sketches=function() { filter = 'sketches'; }
	this.protos=function() { filter = 'prototypes'; }

	// set default range values
	this.resetRange=function() { currRange = 0; }
	this.nextProjRange=function() { currRange += numProjPerPage; } 
	this.nextSubmRange=function() { currRange += numSubmissionsPerPage; }

	// set profile range values
	this.resetProfileRange=function() { 
		profileRanges['my-stuff'] = 0;
		profileRanges['fave-stuff'] = 0; 
		profileRanges['fave-peeps'] = 0; 
		profileRanges['my-fans'] = 0; 
	}
	this.setProfileRange = function(tabId, range) {
		profileRanges[tabId] = range;
	}
	this.nextProfileRange = function(tabId) {
		profileRanges[tabId] = profileRanges[tabId] + numSubmissionsPerPage
		return profileRanges;
	}
	this.setProfileTotal = function(tabId, total) {
		profileTotals[tabId] = total;
	}
}


/* Html Class: Returns any html strings that will be written to the dom */
function Html() {
	// project trunk as displayed on the projects gallery page
	this.getProjectTrunk=function(project) {
		var author = project.author;
		var wish = project.wish;
		var keyword = project.video ? project.video : 'submitproject';

		if (wish.length > 63) {
			wish = wish.substr(0, 61) + '...';
		}
		var latestSketch = '<div class="latest-sub"><div class="img">Add Sketch</div><p class="num-subs"><span>0</span> sketches</p></div>';
		if (project.sketch_src) { latestSketch = '<div class="latest-sub"><img src="http://www-tc.pbskids.org/upload/' + project.sketch_src + '" /> <p class="num-subs"><span>' + project.sketch_tally + '</span> sketches</p></div>'; }

		var latestProto = '<div class="latest-sub"><div class="img">Add Prototype</div> <p class="num-subs"><span>0</span> prototypes</p></div>';
		if (project.proto_src) { latestProto = '<div class="latest-sub"><img src="http://www-tc.pbskids.org/upload/' + project.proto_src + '" /> <p class="num-subs"><span>' + project.proto_tally + '</span> prototypes</p></div>'; }

		var html = '<li><a class="' + project.className + '" href="http://' + _root + 'projects/project.html?project_id=' + project.id + '&keyword='+ keyword +'">' + 
		'<p class="wish fancy-font"><span class="default-font author">' + author + ' says...</span> I wish ' + wish + '</p>' +
		latestSketch +
		latestProto +
		'</a></li>';
		return html;
	}

	// a submitted image (sketch or prototype) as displayed in the results list on a project's detail page, or a profile page
	this.getImageSubmission = function(img) {
		var description = img.description.replace('& ', '&amp; ');
		var title = img.title;
		if (title.length > 14) {
			title = title.substr(0, 13) + '...';
		} else if (title == '') {
			title = '&nbsp;';
		}

		var metaDataHtml = '';
		var pending = '';
		if (img.pending == true) { 
			metaDataHtml = '<p><span class="title">Waiting for<br /> Approval</span></p>';
		} else {
			metaDataHtml = '<p><span class="title">' + title + '</span> <span class="author">by ' + img.author + '</span></p> <div class="tally"><span class="num-stickers">' +img.num_stickers + '</span> stickers</div>';
		}

		var html = '<li class="' + img.className + ' sub">'+
					'<a rel="#overlay" id="' + img.id + '" href="' + _home + 'inc/detail.html?type=sketch&project_id='+img.wish_id+'&submission_id=' + img.id+'" class="' + img.className + '" >' +
					'<img src="http://www-tc.pbskids.org/upload/' + img.submission + '" alt="' + description + '" /> ' +
					'<div class="sub-meta">' + metaDataHtml + '</div>' + 
					'</a>'+
					'</li>';
		return html;
	}

	// a submitted wish as displayed in the results list on a profile page
	this.getWishSubmission = function(wish) {

		var pending = '';
		var keyword = wish.video ? wish.video : 'submitproject';
		if (wish.pending == true) { 
			var html = '<li class="' + wish.className + ' proj">' + 
						'<p class="wish-text">' + wish.submission + '</p> ' +
						'<div class="sub-meta"><p><span class="title">Waiting for<br /> Approval</span></p></div>' + 
						'</li>';
		} else {
			var html = '<li class="' + wish.className + ' proj"><a id="' + wish.id + '" href="http://' + _root + 'projects/project.html?project_id=' + wish.id + '&keyword=' + keyword + '" >' +
						'<p class="wish-text">' + wish.submission + '</p> ' +
						'<div class="sub-meta"><p><span class="title">&nbsp;</span> <span class="author">by ' + wish.author + '</span></p> <div class="tally"><span class="num-stickers">' +wish.num_stickers + '</span> stickers</div></div>' + 
						'</a></li>';
		}

		return html;
	}

	// a profile image and name as displayed in the results list on a profile page
	this.getProfPic = function(user) {

		// determine prof pic
		var baseFileName = user.author.toLowerCase();
		var prof_pic = 'prof-00';
		if ($.inArray(baseFileName, _heroes) == -1 && user.prof_pic) { 
			prof_pic = user.prof_pic;
		} else if ($.inArray(baseFileName, _heroes) != -1) {
			prof_pic = 'hero-' + baseFileName;
		}

		if (user.author != 'New Inventor') {
			var html = '<li><a id="' + user.id + '" class="' + user.className + '" href="profile.html?id='+ user.author +'">' +
						'<img alt="" src="i/buddypics/'+prof_pic+'.jpg" />'+
						'<div class="sub-meta">'+user.author + '</div>'+
						'</a></li>';
		} else {
			var html = '<li class="no-link">' +
						'<img alt="" src="i/buddypics/'+prof_pic+'.jpg" />'+
						'<div class="sub-meta">New Inventor</div>'+
						'</li>';
		}
		return html;
	}

	// the call to action on a user's profile page if they have not submitted yet
	this.callToSubmit = function(string, linkBool) {
		if (!string) {string = "nothing here yet!";}
		var html = '';
		if (linkBool) {
			html = '<li class="no-sticker"><p class="wish-text">'+string+'</p></li>';
		} else {
			html = '<li class="txt-only no-sticker">'+string+'</li>';
		}

		return html;
	}

	this.emptySub = function() {
		return '<li class="transparent">&nbsp;</li>';
	}
}


/* Retrieves blog feed */
function retrieveLiveData() {

	$.getJSON(_home+'php/proxy.php', function(json) {
		var blogModule = $('#blog-feed');
		blogModule.find('h2').html(json['title']);
		blogModule.find('#description').html(json['description']);
		blogModule.find('#pubDate').html(json['pubDate']);
	});

	return;
}


/* Retrieves and displays the latest featured project on the Design Squad homepage */
function displayProjectsFeed() {
	// get data and display results
	$.getJSON(_home+'php/get-projects-gal.php', {sort: 'recent', filter: 'featured', range: 0, num_to_request: 1}, function(json) {
		var wishHtml = "";
		$.each(json, function(key, projId) {
			if (key != "more" && key != "total" && key != "featured") {
				wishHtml = _html.getProjectTrunk(projId);
			}
		});

		$("#results-grid").append(wishHtml);
	});

	return;
}


/* Retrieves and displays projects on the projects homepage */
function displayProjectsList(sort, range, clear, filter) {	  
	// reset global range if we're back to selecting first group
	if (range == 0) _resultsList.resetRange();

	// adjust active results-nav element based on current filter or sort selection
	var id = sort;
	if (filter == 'featured') {id = filter;}

	var resultsNav = $('.results-nav');
	resultsNav.find('.active').removeClass('active');
	resultsNav.find('#'+id).addClass('active');

	// get data and display results
	var resultsGrid = $("#results-grid");
	$.getJSON(_home+'php/get-projects-gal.php', {sort: sort, range: range, filter: filter, num_to_request: _resultsList.getNumProj()}, function(json) {

		// clear list if needed
		if (clear) {resultsGrid.html("");}
		var featured = json['featured'];
		$("#featured-proj").html('<a class="fancy-font bold" href="project.html?project_id=' + featured['id'] + '&keyword=' +featured['video'] + '">' + featured['wish'] + '</a>');
		
		var file = '/designsquad/i/projects/ft-proj-' + featured['video'] + '.png';
		$('#featured-img').attr('src', file).fadeIn('slow');

		// display the list of projects
		var projectHtml = "";
		$.each(json, function(key, projId) {
			if (key != "more" && key != "total" && key != "featured") {
				projectHtml += _html.getProjectTrunk(projId);
			}
		});
		resultsGrid.append(projectHtml);

		updateDisplayedTally(json['total']);

		// show more button if more results exist
		(json['more']) ? $('#more').show() : $('#more').hide(); 

		var toolTipped = resultsGrid.find('li');
		addTooltip(toolTipped, 'contribute', 87, -58, 15);

	});

	if (range) { _browser.scrollTo($("#more")); }
}


/* Retrieves and displays sketch and prototype submissions on a project's detail page */
function displaySubmissionsList(filter, sort, range, clear) {
	var project_id = _browser.getUrlVars()['project_id'];
	if (!project_id) {
		window.location = 'http://' + _root + 'projects/index.html';
		return;
	}

	// reset global range if we're back to selecting first group
	if (range == 0) _resultsList.resetRange();

	// adjust active results-nav element
	var resultsNav = $('.results-nav');
	resultsNav.find('.active').removeClass('active').find('.filter').css('visibility','hidden');
	resultsNav.find('#'+filter).parent().parent().addClass('active').find('.filter').css('visibility','visible');
	$('.results-nav .active').find('.'+sort).addClass('active');

	var author, wish, tally, link_text, link_href, vid_name = "";
	var totalSubs;

	// get data and display sketch or porotype submissions for wish
	var resultsGrid = $('#results-grid');
	$.getJSON(_home+'php/get-project.php', { filter: filter, sort: sort, project_id: project_id, range: range, num_to_request: _resultsList.getNumSubmissions()}, function(json) {
		totalSubs = json[0]['project_info']['total'];

		// clear list if a fresh view is requested
		if (clear) {resultsGrid.html("");}

		// hide more button if no more results exist
		if (!json['more']) $('#more').hide(); 

		// update dom with project info
		var projectInfo = json[0]['project_info'];
		author = projectInfo['wish_author'];
		wish = projectInfo['wish'];
		tally = projectInfo['wish_stickers'];

		var editorialProject = projectInfo['editorial_project'];
		if (editorialProject) {
			link_text = editorialProject['long'];
			link_href = editorialProject['link'];
			vid_name = editorialProject['video'];
			if (link_text && link_href) { $('#project-link').text(link_text).attr('href', link_href).removeClass('hidden'); }
		} 
		$('#project-author').text(author);

		// link to user's profile if their name is approved, otherwise just display name
		if (author != 'New Inventor') { 
			$('#project-author').attr('href', 'http://' + _root + 'profile.html?id=' + author); 
		} else {
			$('#project-author').contents().unwrap();
		}


		// determine prof pic
		var baseFileName = author.toLowerCase(),
		prof_pic = 'prof-00',
		res_prof_pic = projectInfo['prof_pic'];
		
		if ($.inArray(baseFileName, _heroes) == -1 && res_prof_pic) { 
			prof_pic = res_prof_pic;
		} else if ($.inArray(baseFileName, _heroes) != -1) {
			prof_pic = 'hero-' + baseFileName;
		}
		$('#project').find('.prof-pic').attr('src', _home+'i/buddypics/'+prof_pic+'.jpg');

		$('#project-wish').text(wish).attr('href', _home + 'inc/detail.html?type=wish&project_id='+project_id+'&submission_id=' + project_id);
		$('#project-meta').find('.num-stickers').text(tally);

		var submissionHtml = "";

		// print submitted images for wish
		if (json.length > 1) { 
			$.each(json, function(key, submission) {
				// display the project information: wish, num solutions, etc
				if (!submission['project_info'] && !submission['more']) {
					submissionHtml += _html.getImageSubmission(submission);
				} 

				if (submission['more']) { $('#more').show(); }
			});

			resultsGrid.append(submissionHtml);

			updateDisplayedTally(totalSubs);
			$('#results-meta').show();
		} else {
			resultsGrid.html(_html.callToSubmit('Hey you,<br /> add your ideas!', false));
			$('#results-meta').hide();
		}

		// append blank list items if less than 5 in the grid
		completeGridRow(5, resultsGrid);

		// add tooltips to project wish and submissions
		if (author != current_user) {
			var wishObj = $('#project').find('#project-wish');
			var offset = $('#project-link').is(":visible") ? 610 : 584;
			if (_logged_in) { offset += 26; }
			addTooltip(wishObj, 'sticker', offset, -400, 30);
		}
		var toolTipped = resultsGrid.find('li:not(.no-sticker, .transparent)');
		addTooltip(toolTipped, 'sticker', 143, 18, 30);

		// init detail overlay box functionality
		initDetailOverlay(resultsGrid.find('a, #project-wish, #project-meta .tally'), 'image');

	});

	if (range) { _browser.scrollTo($("#more")); }

}



/* Retrieves and displays the content within a tab on a profile page */
function displayProfileTab(range, tab) {
	range = _resultsList.getCurrProfileRange(tab);

	var currentPane = $('.panes').find('[id='+tab+']');

	// reset global range if we're back to selecting first group
	if (range == 0) { _resultsList.resetProfileRange(); }

	var prof_id = _browser.getUrlVars()['id'];
	if (!prof_id || prof_id == current_user) { 
		prof_id = current_user;
	} else {
		$('body').removeClass('hl-me');
	}

	// get data and display results
	$.getJSON(_home+'php/get-profile.php', { select_type: tab, prof_id: prof_id, range: range, num_to_request: _resultsList.getNumSubmissions()}, function(json) {

		if (json['invalid'] || prof_id == 'New%20Inventor') { window.location = _home; $('#page-feature').hide(); $('#results').hide(); return; }

		// print current user stats if user just arrived on the page
		var viewing_self = false;
		if(json[0]['user_info']['viewing_self']) { 
			viewing_self = true; 
			$('#stats-container').find('.label').html("Sweet! I've got:");
		} else {
			$('#stats-container').find('.label').html('Points earned:');
		}

		// populate data if its the first time coming
		if($('#username').html() == "") {
			displayProfileStats(prof_id, viewing_self, json);
		}

		// if on a database populated tab, request and display data
		if (tab != 'about-me') {
			var listHtml = "";

			// print submitted works
			if (json.length > 1) { 
				$.each(json, function(key, item) {

					if (!item['user_info'] && !item['more'] && !item['valid']) {

						// my stuff or my favorite stuff tab
						if(tab == 'my-stuff' || tab == 'fave-stuff') {
							if(item['type'] == 'image') {
								listHtml += _html.getImageSubmission(item);
							} else {
								listHtml += _html.getWishSubmission(item);
							}

						// my fans or my favorite peeps tab
						} else {
							listHtml += _html.getProfPic(item);
							msg = "go become a fan of someone";
						}
					} 

				});

				// add the html to the current tabs pane
				currentPane.append(listHtml);
			} else {
				// make call to action message when no entries exist
				var msg = "";
				if (viewing_self) {
					if (tab == 'my-stuff') { msg = 'Hmm, it\'s looking empty here. Go make stuff!'; 
					} else if (tab == 'fave-stuff') { msg = 'Go sticker stuff! It will show up here.'; 
					} else if (tab == 'fave-peeps') { msg = 'Find a project you like, and be a fan of its creator!'; 
					} else if (tab == 'my-fans') { msg = 'Want fans? Submit a wish, sketch or prototype!'; }
				} else {
					if (tab == 'my-stuff') { msg = 'I\'m making stuff. It\'s awesome you should try it!'; 
					} else if (tab == 'fave-stuff') { msg = 'I\'m out stickering stuff.'; 
					} else if (tab == 'fave-peeps') { msg = 'Hey, go make stuff and maybe I\'ll be your fan!'; 
					} else if (tab == 'my-fans') { msg = 'Be my fan! Sign in to get started.'; }
				}

				currentPane.html(_html.callToSubmit('<a href="' + _home + 'projects/index.html">' + msg + '</a>', true));

			}
		}

		// append blank list items if less than 5 in the grid
		completeGridRow(5, currentPane);


		// update grid results tally
		var tot = 0;
		var userInfo = json[0]['user_info'];
		if (tab == 'my-stuff') {
			$('#results-grid .author').hide();
			var num_wishes = Number(userInfo['num_wishes']),
			num_sketches = Number(userInfo['num_sketches']),
			num_prototypes = Number(userInfo['num_prototypes']);
			tot = num_wishes + num_sketches + num_prototypes;
		} else if (tab == 'my-fans') {
			tot = Number(userInfo['num_fans']);
		} else if (tab == 'fave-stuff') {
			tot = Number(userInfo['num_given']);
		} else if (tab == 'fave-peeps') {
			tot = Number(userInfo['num_fave_peeps']);
		}

		_resultsList.setProfileTotal(tab, tot);
		var showing = $('#' + tab).find('li:visible:not(.transparent)').size();
		_resultsList.setProfileRange(tab, showing);

		var total = _resultsList.getProfileTotals(tab);

		// when viewing your own stuff you can see pending items so the number display tally may not match the total submissions tally
		if (viewing_self && tab =='my-stuff') {
			total = userInfo['total_with_pending'];
			_resultsList.setProfileTotal('my-stuff-all', total); 
			updateDisplayedTally(total, $('#' + tab));
		} else {
			updateDisplayedTally(tot, $('#' + tab));
		}	
		
		// show/hide more button
		(showing < total) ? $('#more').show() : $('#more').hide();

		initDetailOverlay($('#my-stuff .sub a, #fave-stuff .sub a'), 'image');
	});

	if (range) { _browser.scrollTo($("#more")); }
}


/* Retrieve and display the stats of currently viewed profile: requires json object */
function displayProfileStats(prof_id, viewing_self, json) {

	// display point tallies
	var userInfo = json[0]['user_info'],
	num_wishes = Number(userInfo['num_wishes']),
	num_sketches = Number(userInfo['num_sketches']),
	num_prototypes = Number(userInfo['num_prototypes']),
	num_earned = Number(userInfo['num_earned']),
	num_given = Number(userInfo['num_given']),
	num_fans = Number(userInfo['num_fans']),

	total = Number(userInfo['total']),
	prof_pic = userInfo['prof_pic'],
	prof_pic_src = _home+'i/buddypics/prof-00.jpg';
	if ($('.hero').size()) {
		prof_pic_src = _home+'i/buddypics/hero-'+prof_id+'.jpg';
	} else if (prof_pic) { 
		prof_pic_src = _home+'i/buddypics/'+prof_pic+'.jpg';
	}

	$('#username').text(prof_id);
	$('#wish-stat .score').text(num_wishes);
	$('#sketch-stat .score').text(num_sketches);
	$('#proto-stat .score').text(num_prototypes);
	$('#recieved-stat .score').text(num_earned);
	$('#given-stat .score').text(num_given);
	$('#fans-stat .score').text(num_fans);
	$('#stats-container .num-stickers').text(total);

	$('#identity').find('.prof-pic-big').attr('src', prof_pic_src.toLowerCase());

	// display profile pic and options
	if (viewing_self) {

		$('.self').show();
		var pics = $('#prof-pics > li'),
		goal = 0,
		remaining = 0,
		numToUnlock = 0;

			if (total < 20) {
			goal = 20;
			numToUnlock = 5;
			$('.level1').addClass('unlocked');

		} else if (total < 50) {
			goal = 50;
			numToUnlock = 10;
			$('.level1').addClass('unlocked');
			$('.level2').addClass('unlocked');
		} else if (total < 100) {
			goal = 100;
			numToUnlock = 15;
			$('.level1').addClass('unlocked');
			$('.level2').addClass('unlocked');
			$('.level3').addClass('unlocked');

		} else if (total < 200) {
			goal = 200;
			numToUnlock = 20;
			$('.level1').addClass('unlocked');
			$('.level2').addClass('unlocked');
			$('.level3').addClass('unlocked');
			$('.level4').addClass('unlocked');
		} else if (total >= 200) {
			numToUnlock = 25;
			$('.level1').addClass('unlocked');
			$('.level2').addClass('unlocked');
			$('.level3').addClass('unlocked');
			$('.level4').addClass('unlocked');
			$('.level5').addClass('unlocked');
		}

		// highlight current prof pic
		$('[id='+prof_pic+']').addClass('current');
		$('.unlocked a').click(function (e){
			e.preventDefault();
			updateProfPic(prof_id, $(this).attr('id'));
		});

		// print stats for reaching next level of profile pics
		if (total < 200) { 
			remaining = goal - (total % goal);
			$('#needed').html(remaining);
		} else {
		//todo: you've got all 200 messaging
		}
	}

	// display ability to follow or unfollow currently viewed profile
	if(!viewing_self && _logged_in) {
		$('.self, #login-to-fan').hide();
		if (userInfo['following']) {
			$('#unfollow').show();
		} else {
			$('#follow').show();
		}
	} else if (viewing_self && _logged_in) {
		$('#login-to-fan').hide();
	} else {
		$('#login-to-fan').show();
	}	
}


/* Update profile picture */
function updateProfPic(prof_id, prof_pic) {
	$.get(_home+'php/set-prof-pic.php', {prof_id: prof_id, prof_pic: prof_pic}, function(result) {
		$('#prof-pics').find('.current').removeClass('current');
		$('#prof-pics').find('[id='+prof_pic+']').addClass('current');

		$('#prof-pic').attr('src',_home+'i/buddypics/'+prof_pic+'.jpg').attr('alt',prof_pic);
		$('#identity').find('.prof-pic-big').attr('src', _home+'i/buddypics/'+prof_pic.toLowerCase()+'.jpg');
	});
}


/* Update fan status */
function updateFanSelection(prof_id, action) {
	var score = parseInt($('#fans-stat').find('.score').text());
	var total = parseInt($('#stats-container').find('.num-stickers').text());
	$.get(_home+'php/set-fan.php', {prof_id: prof_id, action: action}, function(result) {
		if (action == 'follow') {
			$('#follow').hide();
			$('#unfollow').show();
		} else {
			$('#unfollow').hide();
			$('#follow').show();
		}

		location.reload(true);
	});
}


/* update tally in more button section */
function updateDisplayedTally(total, list) {
	if (total) {
		if (!list) { list = $("#results-grid"); }
		$("#results-set").html(list.find('li:visible:not(.transparent)').size());
		$("#results-total").html(total);
		$('#results-meta').show();
	} else {
		$('#results-meta').hide();
	}
}


/* complete grid with empty list items if total is not divisible by number of columns in grid */
function completeGridRow(cols, list) {
	var numItems = list.find('li').size();
	var mod = cols-numItems%cols;

	while(mod > 0 && mod != cols) {
		mod--;
		list.append(_html.emptySub());
	}
}


/* Triggers scripting for the Design Squad homepage */
function initDsHome() {
	// display projects teaser feed
	displayProjectsFeed();
	retrieveLiveData();
}


/* Triggers scripting for the projects homepage */
function initProjectsHome() {

	// enable form if logged in
	if (_logged_in) {
		$('#id_submission, #submission, #altinfo, #submit').removeAttr('disabled');
	}

	var thanks = _browser.getUrlVars()['upload'];
	if (thanks=="true") { initThankYouMsg(genericSubmissionMssg, 'overlay'); } /*todo: successful submission of uploaded prototype shouldn't redirect the user at all*/

	// display default data set on page load
	displayProjectsList('recent', 0, true, false);

	// describe button behaviors
	var resultsNav = $('#results');
	resultsNav.find('#recent').click(function (){ _resultsList.recent(); displayProjectsList('recent', 0, true, false); });
	resultsNav.find('#popular').click(function (){ _resultsList.popular(); displayProjectsList('popular', 0, true, false); });
	resultsNav.find('#featured').click(function (){ _resultsList.featured(); displayProjectsList('recent', 0, true, 'featured'); });
	resultsNav.find('#recent a, #popular a, #featured a').click(function (e){ e.preventDefault(); });

	$('#more').click(function (){ 
		_resultsList.nextProjRange();							// update current range value
		displayProjectsList(_resultsList.getSort(),				// request data, display results
							_resultsList.getRange(), 
							false, _resultsList.getFilter());
	});


	// handle form validation
	prepareOverlayMsg($('#overlay'));

	var alerts = {
		defaultTxt: 'I wish... ',
		tooLong: 'Oops! Make your entry a little shorter please.',
		empty: 'Wait, wait, tell us your wish first!',
		spam: 'Please only fill in your wish text and leave the other fields blank. URLs are not perrmitted.',
		success: 'Saved on your Me page! <br />We\'ll post your wish soon, ok?',
		serverError: 'Whoa, we messed up...can you try that again?',
		notLoggedIn: 'Oh, hey, can you log in first? thanks!'
		};

	// update the text in the input box to say "i wish" on click
	var textWish = $('#id_submission');
	textWish.val(alerts.defaultTxt);

	textWish.click(function () {
		if (textWish.val() != alerts.defaultTxt && textWish.val() == '') {
			textWish.val(alerts.defaultTxt);
		}
	});

	// alert if user if they've reached a character max
	$('#id_submission').keydown(function(event){
		if (_logged_in == false) {
			textWish.val(alerts.defaultTxt);
			$('.contentWrap').text(alerts.notLoggedIn);
			$('#overlay').data('overlay').load();
		}
		var key = event.which;

		if(key >= 33 || key == 13) {	// keycode 13 = return key
			var length = this.value.length;
			if(length >= 119) {
				event.preventDefault();
				$('.contentWrap').html(alerts.tooLong);
				$('#overlay').data('overlay').load();
			}
		}
	});

	// give feedback based on input
	$('#submit').click(function(event) {
		var txtVal = textWish.val();
		// make sure they're logged in
		if (_logged_in == false) {
			textWish.val(alerts.defaultTxt);
			event.preventDefault();
				$('.contentWrap').text(alerts.notLoggedIn);
				$('#overlay').data('overlay').load();
		// test for spam
		} else if ($('#altinput').val() != "" || 
				txtVal.indexOf('://') != -1 || 
				txtVal.indexOf('[url=') != -1) {
			textWish.val(alerts.defaultTxt);
			event.preventDefault();
				$('.contentWrap').html(alerts.spam);
				$('#overlay').data('overlay').load();

		// test for empty submission
		} else if (!txtVal || txtVal == "" || txtVal == alerts.defaultTxt) {
			textWish.val(alerts.defaultTxt);
			event.preventDefault();
				$('.contentWrap').text(alerts.empty);
				$('#overlay').data('overlay').load();

		// if it passes all else, then submit with success alert
		} else {
			$('.contentWrap').html(alerts.success);
			$('#overlay').data('overlay').load();
		}
	});
}


/* Triggers scripting for a project's detail page */
function initProjectDetail() {
	var thanks = _browser.getUrlVars()['submit'];
	if (thanks=="true") { initThankYouMsg(genericSubmissionMssg, 'overlay-msg'); } /*genericSubmissionMssg defined in project.html*/

	// display default data set on page load
	displaySubmissionsList('sketches', 'recent', 0, true);

	// describe button behaviors
	$('#sketches').click(function (e){ e.preventDefault(); _resultsList.sketches(), _resultsList.recent(); displaySubmissionsList(_resultsList.getFilter(), 'recent', 0, true); });
	$('#prototypes').click(function (e){ e.preventDefault(); _resultsList.protos(), _resultsList.recent(); displaySubmissionsList(_resultsList.getFilter(), 'recent', 0, true); });
	$('.results-nav .recent').click(function (e){ e.preventDefault(); _resultsList.recent(); displaySubmissionsList(_resultsList.getFilter(), 'recent', 0, true); });
	$('.results-nav .popular').click(function (e){ e.preventDefault(); _resultsList.popular(); displaySubmissionsList(_resultsList.getFilter(), 'popular', 0, true); });

	$('.results-nav').find('.filter').css('visibility','hidden');
	$('.results-nav .active').find('.filter').css('visibility','visible');

	$('#more').click(function (){ 
		_resultsList.nextSubmRange();							// update current range value
		displaySubmissionsList(_resultsList.getFilter(),		// request data, display results
								_resultsList.getSort(), 
								_resultsList.getRange(), 
								false);
	});
}


/* Triggers scripting for a user's profile page */
function initProfile() {
	var prof_id = _browser.getUrlVars()['id'];

	// prompt user to login if not logged in and no user id is found
	if (!_logged_in && !prof_id) {
		window.location = 'http://' + _root + 'index.html';
		$('#identity').html('<a href="/go/apps/auth/prompt/?destination=/designsquad/profile.html">Log in or sign up to see your profile</a>');
	}

	var pane = "";
	var paneId = "";
	$(".tabs").tabs(".panes > ul", {
		onBeforeClick: function(event, i) {
			// get the pane to be opened
			pane = this.getPanes().eq(i);
			paneId = pane.attr('id');
			// only load data once.
			if (pane.is(':empty')) {
				displayProfileTab(0, paneId);
			}

			// only heros have the about me tab and content in the 'aside' block
			(paneId == 'about-me') ? $('#aside').show() : $('#aside').hide();

			$('#results-set').html(_resultsList.getCurrProfileRange(paneId));

			// adjust active results-nav element
			$('.results-nav').find('.active').removeClass('active');
			$('.results-nav').find('#'+paneId +'-nav').addClass('active');
	
		}, 
		onClick: function(i) {
			// reset currently viewed range
			var showing = pane.find('li:visible:not(.transparent)').size();
			_resultsList.setProfileRange(paneId, showing);

			var total = _resultsList.getProfileTotals(paneId);

			// when viewing your own stuff you can see pending items so the number display tally may not match the total submissions tally
			if(paneId == 'my-stuff' && (prof_id == current_user || !prof_id || prof_id == 'undefined')) { 
				updateDisplayedTally(_resultsList.getProfileTotals('my-stuff-all'), $('#my-stuff')); 
				total = _resultsList.getProfileTotals('my-stuff-all');
			} else {
				updateDisplayedTally(total);				
			}

			// show/hide more button
			(showing < total) ? $('#more').show() : $('#more').hide();
		}
	});

	// check if viewing a hero
	if (prof_id) {
		var hero = false;
		var baseFileName = prof_id.toLowerCase();
		if ($.inArray(baseFileName, _heroes) != -1) { 
			hero = true;
		}

	}

	// show appropriate tabs and content for hero vs. non-hero
	if (hero) {
		$('#fave-peeps-nav').hide();
		$('#about-me-nav').removeClass('hidden').addClass('active');
		$('#about-me').removeClass('hidden').load('heroes/' + baseFileName + '.html', function() {
			// display aside - content hidden in last results list item
			if ($('#bio').html()) {
				$('#aside').html($('#bio').html());
			} else {
				$('#aside').hide();
			}

			$('#about-me').find('.lb').overlay({
				mask: {
					color: '#000',
					opacity: 0.7
				},
				fixed: false,
				top: '5%',
				onBeforeLoad: function() {
					var asset = this.getOverlay().find("#asset");

					// load the page specified in the trigger
					asset.attr('src', this.getTrigger().attr("href"));

					var caption = this.getOverlay().find("p");
					caption.html(this.getTrigger().find('img').attr('alt'));

				}
			});

			completeGridRow(5, $('#about-me'));
			});
		$('#page-feature').addClass('hero');
		$('.prof-pic-big').attr('src', 'i/buddypics/hero-'+baseFileName+'.jpg');
	} else {
		var api = $('.tabs').data("tabs");
		api.click(1);
	}

	// describe button behaviors
	$('#more').click(function (){ 
		var range = _resultsList.getCurrProfileRange(paneId);
		displayProfileTab(range, paneId);							// request data, display results
	});

	// describe button behaviors
	$('.fan').children().click(function (){
		if (!prof_id) { prof_id = current_user; } //current_user vaule set in html
		updateFanSelection(prof_id, $(this).parent().attr('id'));
	});

}

/* Triggers scripting for the featured image on the heroes page */
function initHeroes() {
	var numImages = _numHeroBgImages; // number of available images to cycle through

	var featuredImg = $('#featured-img');	// placeholder element for current image

	// if a source value was provided in the html, don't cycle the image
	if(featuredImg.attr('src')) {
		featuredImg.fadeIn('slow');

	// otherwise randomly swap featured image on page refresh
	} else {
		var ranNum = Math.floor(Math.random()*numImages);
		featuredImg.attr('src', '../i/heroes/hero-'+ranNum+'.png').fadeIn('slow');
	}
}


function initThankYouMsg(msg, overlay) {
	var overlayId = 'overlay';
	if (overlay) { overlayId = overlay; }

	$('#'+overlayId).overlay({
		top: 260,
		mask: {
			color: '#000',
			opacity: 0.7,
			loadSpeed: 200
		},
		load: true,
		onBeforeLoad: function() {
			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".contentWrap");

			// load the page specified in the trigger
			if (msg) { wrap.html(msg); /*variable set in project.html*/ }
		}
	});
}

function initDetailOverlay(elements, type) {
	var fileName = '', // url of html file, with post vars, to load into overlay
	submissionId = '', // id of wish (project)
	browserVars = '';

	_detailOverlay = $('#overlay').overlay({
		api: true,
		top: '5%',
		mask: {
			color: '#000',
			opacity: 0.7,
			loadSpeed: 200
		},
		fixed: false,
		onBeforeLoad: function() {
			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".contentWrap");

			// load the page specified in the trigger
			wrap.load(fileName);
		},
		onLoad: function() {
			$.getJSON(_home+'php/get-submission.php', {project_id: browserVars, submission_id: submissionId}, function(json) {

				var result = json[0];

				// populate the content
				var detail = $('#det'),
				overview = $('#det').find('#project-overview'),
				authorId = result['wish_author'];


				// determine prof pic
				var baseFileName = authorId.toLowerCase();
				var wish_author_pic = 'prof-00';
				if ($.inArray(baseFileName, _heroes) == -1 && result['wish_author_pic']) { 
					wish_author_pic = result['wish_author_pic'];
				} else if ($.inArray(baseFileName, _heroes) != -1) {
					wish_author_pic = 'hero-' + baseFileName;
				}

				if (authorId != 'New Inventor') { 
					overview.find('#wish-author').text(authorId).attr('href', _home+'profile.html?id='+authorId);
				} else {
					// remove link to user's profile if their name is not approved
					overview.find('#wish-author').text(authorId).contents().unwrap();
				}
				overview.find('#wish-text').text(result['wish']);
				overview.find('.prof-pic').attr('src', _home + 'i/buddypics/' + wish_author_pic + '.jpg');

				// fill out image data
				if (submissionId != 0) {
					var submission = $('#det').find('#submission-info');
					var author_pic = result['author_pic'];
					if (!author_pic) author_pic = 'prof-00';
					authorId = result['author'];
					if (authorId != 'New Inventor') { 
						submission.find('#image-author').text(authorId).attr('href', _home+'profile.html?id='+authorId);
					} else {
						// remove link to user's profile if their name is not approved
						submission.find('#image-author').text(authorId).contents().unwrap();
					}
					submission.find('#image-title').text(result['title']);
					submission.find('#image-description').text(result['description']);
					submission.find('.num-stickers').text(result['num_stickers']);
					submission.find('#image').attr('src', 'http://www-tc.pbskids.org/upload/' +result['src']);

					// determine prof pic
					baseFileName = authorId.toLowerCase();
					var author_pic = 'prof-00';
					if ($.inArray(baseFileName, _heroes) == -1 && result['author_pic']) { 
						author_pic = result['author_pic'];
					} else if ($.inArray(baseFileName, _heroes) != -1) {
						author_pic = 'hero-' + baseFileName;
					}


					submission.find('.prof-pic').attr('src', _home + 'i/buddypics/' + author_pic + '.jpg');
					$('#submission-info').show();
				} else {
					$('#submission-info').hide();
				}
			});
		}
	});

	// create live click event so dynamically added elements get overlay effect
	$(elements).live('click', function(e){
		e.preventDefault();

		// set variables to be used by overlay
		fileName = $(this).attr("href");
		submissionId = $(this).attr('id');
		browserVars = _browser.getUrlVars()['project_id'];
		if (!browserVars) browserVars = 0; 

		// when clicking to sticker a wish the elment id would not be wish id
		if (submissionId == 'project-wish') { submissionId = 0; }

		// load the overlay
		_detailOverlay.load();
	});

}


// for displaying any alerts or messages
function prepareOverlayMsg(element) {
	if (element) {
		element.overlay({
			top: '25%',
			mask: {
				color: '#000',
				opacity: 0.7,
				loadSpeed: 200
			},
			fixed: false
		});
	}
}


// CREATE THE TOOLTIP POP-UPS ON THE GALLERY PAGES
function addTooltip(items, stickerName, offsetTop, offsetLeft, numImages) {
	if (!numImages) { numImages = 1; }	// numImages = number of images available to cycle through
	
	items.hover(
		function() {
			var pos = $(this).position(),				
				topY = pos.top - offsetTop, 
				leftX = pos.left - offsetLeft, 
				ranNum = Math.floor(Math.random()*numImages) + 1,
				newSrc = _home + "i/stickertips/" + stickerName + ranNum + ".png"; /* grab random sticker - would code smarter with more time */
			$('#toolTipSticker').attr({src: newSrc}).css({top: topY, left: leftX}).fadeIn('fast');

		}, function() {
			$('#toolTipSticker').hide();
		});

	// careful to not let tooltip show on roll out of grid
	$('#toolTipSticker').mouseover(function() { $('#toolTipSticker').hide(); });
}


// VALIDATE THE PHOTO UPLOAD FORM
function initUploadForm() {

	var alerts = {
		spam: 'Please only fill in only the required fields and leave the other fields blank. URLs are not perrmitted.',
		success: 'Thanks, your photo has been sent to the gallery!',
		empty: 'Please select a file first!',
		tooLong: 'Oops! Make your entry a little shorter please.',
		type: 'Please only upload image files!'
		};

	// alert if user if they've reached a character max
	$('#title').keydown(function(event){

		var $key = event.which;

		if($key >= 33 || $key == 13) {	// keycode 13 = return key
			var $length = this.value.length;
			if($length >= 45) {
				event.preventDefault();
				$('#msg').html('<p>'+alerts.tooLong+'</p>');
			}
		}
	});

	$('#description').keydown(function(event){

		var $key = event.which;

		if($key >= 33 || $key == 13) {	// keycode 13 = return key
			var $length = this.value.length;
			if($length >= 230) {
				event.preventDefault();
				$('#msg').html('<p>'+alerts.tooLong+'</p>');
			}
		}
	});


	// give feedback based on input
	$('#submit').click(function(event) {
		var $submission = $('#submission').val(),
		$titleVal = $('#title').val(),
		$descripVal = $('#description').val();

		// test for spam
		if ($('#altinput').val() != "" || 
				$titleVal.indexOf('://') != -1 || 
				$titleVal.indexOf('[url=') != -1 ||
				$descripVal.indexOf('://') != -1 || 
				$descripVal.indexOf('[url=') != -1
				) {
			event.preventDefault();
			$('#msg').html('<p>'+alerts.spam+'</p>');

		// test for empty submission
		} else if (!$submission) {
			event.preventDefault();
			$('#submission').addClass('error');
			$('#msg').html('<p>'+alerts.empty+'</p>');

		// test for file type
		} else if ( ($submission.indexOf('.jpg') == -1) &&
					($submission.indexOf('.gif') == -1) &&
					($submission.indexOf('.png') == -1) ) {
			event.preventDefault();
			$('#submission').addClass('error');
			$('#msg').html('<p>'+alerts.type+'</p>');

		// if it passes all else, then submit with success alert
		} else {
			_overlays.eq(1).overlay().close();
			/*todo: redirect currently doesn't fire*/
			window.location = 'http://' + _root + 'projects/project.html?project_id=' + $('#hidden-inputs input[name=wish]').val() + '&submit=true';
		}
	});
}


$(document).ready(function(){

	if(current_user && current_user != 'anonymous!@') { _logged_in = true; }

	// shift content down to allow for pbs bar when logged in
	if (_logged_in) {
		var bar_height = $('#pbskidsgologinbar').height();
		if ( bar_height > 0) { bar_height += 7; } // for border and box padding
		$('#pbskidsgologinbar').css('border-bottom', '1px solid #000');
		$('body').addClass('logged_in').css('background-position', '0 '+bar_height+'px'); 
	}

	// set global ajax error handling
	$('body').ajaxError(function(xhr, status, error) {
		$("#results-grid").html(serverErrorMssg); // value defined in html
	});

	// generate requested page results
	if ($('#projects-feed').size()) { initDsHome(); }
	if ($('#projects-gallery').size()) { initProjectsHome(); }
	if ($('#project-page').size()) { initProjectDetail(); }
	if ($('#profile').size()) { initProfile(); }
	if ($('#heroes').size()) { initHeroes(); }

	// activate any light boxes
	if ($('.lb').size()) { 
		_overlays = $('a.lb').overlay({
			mask: {
				color: '#000',
				opacity: 0.7
			},
			fixed: false,
			top: '5%',
			onBeforeLoad: function() {
				if (this.getOverlay().hasClass('external')) {
					// grab wrapper element inside content
					var wrap = this.getOverlay().find(".contentWrap");

					// load the page specified in the trigger
					wrap.load(this.getTrigger().attr("href"));
				}
			},
			onLoad: function() {
				if ($('#upload').size()) { initUploadForm(); }
			}
		});
	}
});

