$(document).ready(function(){

	// Twitter scroll bar area
	
	$('#twitterPane').jScrollPane({scrollbarWidth:9,scrollbarMargin:3 });
	reinitialiseScrollPane = function()
	{
		$('#twitterPane').jScrollPane({scrollbarWidth:9,scrollbarMargin:3 });
	}
	$('#add-content').bind(
		'click',
		function()
		{
			$('#twitterPane').load('includes/twitter_feed.cfm', '', reinitialiseScrollPane);
		}
	);

	// Initialize comments pane
	//$('#launchComments').jScrollPane({scrollbarWidth:9,scrollbarMargin:3 });
	
	reinitialiseCommentsPane = function()
	{
		$('#launchComments').jScrollPane({scrollbarWidth:9,scrollbarMargin:3 });
	}
	
	// add mouseover function to each thumbnail	
	$('.singleThumbnail').bind(
		'mouseover',
		function()
		{
			thumbnailOn(this);
		}
	);
	
	// add mouseoff function to each thumbnail	
	$('.singleThumbnail').bind(
		'mouseout',
		function()
		{
			thumbnailOff(this);
		}
	);
	
	// add click function to each thumbnail	
	$('.singleThumbnail').bind(
		'click',
		function()
		{
			var strTNail = new String(this.id);
			var tnNum = strTNail.substr(9,1);
			
			if (ActiveProject == 1 || ActiveProject == 2)
				thumbnailSelect(this);
			else
			{
				if (tnNum <= ProjectActiveEpisode)
					thumbnailSelect(this);
			}
		}
	);
		
	// load summary, poll and comments for the current episode on initial page load
	loadEpisodeSummary(currentEpisode);
	loadPoll(currentEpisode);
	loadCommentPane(currentEpisode);
	
	$("#registerButton").colorbox({width:"50%", inline:true, href:"#registerForUpdatesContent", speed:350, opacity:0.65, width:"556px"});
	$("#registerLinkRight").colorbox({width:"50%", inline:true, href:"#registerForUpdatesContent", speed:350, opacity:0.65, width:"556px"});
	$("#showIndustryContributors").colorbox({width:"50%", inline:true, href:"#contributors", speed:350, opacity:0.65, width:"557px", height:"540px", scrolling:false});
	$("#showIndustryContributorsText").colorbox({width:"50%", inline:true, href:"#contributors", speed:350, opacity:0.65, width:"557px", height:"540px", scrolling:false});
	
	// show post comment box
	$('#postCommentLink').bind(
		'click',
		function()
		{
			$('#postCommentWrapper').css({display:"block"});
			$('#project1CommentsWrapper').css({display:"none"});
			$('#submitIdeaForm').css({display:"none"});
		}
	);
	
	// hide comments and show idea form
	$('#submitProjectIdea').bind(
		'click',
		function()
		{
			hideCommentPanes();
			swapCommentTabs('submitProjectIdea');
			$('#postCommentWrapper').css({display:"none"});
			$('#submitIdeaForm').css({display:"block"});
		}
	);
	
	// hide form and show comments
	$('#discussProject').bind(
		'click',
		function()
		{
			swapCommentTabs('comments');
			$('#submitIdeaForm').css({display:"none"});
			loadCommentPane(currentEpisode);
		}
	);
	
	// hide form and show comments
	$('#submitIdea').find('a').bind(
		'click',
		function()
		{
			hideCommentPanes();
			swapCommentTabs('submitProjectIdea');
			$('#postCommentWrapper').css({display:"none"});
			$('#submitIdeaForm').css({display:"block"});
			
		}
	);
	

// Resigter user's email for project updates
	$('#registerBtn').bind(
		'click',
		function()
		{
			var email = $('#registerText').val();
			// Verify a valid email address and, if valid, submit ajax call to add email to db
			var pattern = /^[a-z0-9]+[-._a-z0-9]*@([a-z0-9]+[-a-z0-9]*\.)+[a-z]{2,}$/;
			if (pattern.test(email.toLowerCase())) 
		  		{
					$.ajax({
						type: "POST",
						async: false,
						url: '/pages/programs/letsgodesign/includes/register_email.cfm',
						data: $("#frmRegister").serialize(),
						success: function(dataRecieved) {
									$('#registerText').val(dataRecieved);
								}
					});
				}
			else
				$('#registerText').val('Please enter a valid email.');
		}
	);
	
	// Submit polling answer
	//$('#launchPollSubmit').bind(
	$('#pollButton').bind(
		'click',
		function()
		{
			var pollAnswer = $('"pollAnswer":checked').val();
			if (pollAnswer != undefined) {
				//alert(pollAnswer+currentProject+currentEpisode);
				//alert('/pages/programs/letsgodesign/includes/episode_vote.cfm?ProjectID='+currentProject+'&EpisodeID='+currentEpisode+'&Rank='+episodeRank);
				$.ajax({
					type: "POST",
					async: false,
					url: '/pages/programs/letsgodesign/includes/episode_vote.cfm?ProjectID='+currentProject+'&EpisodeID='+currentEpisode+'&Rank='+currentEpisode+'&voteClose='+voteClose,
					data: $("#frmEpisodePoll").serialize(),
					success: function(dataReceived) {
								eval("$\('#pollProject" + currentProject + "Episode" + currentEpisode + "'\).html\(" + dataReceived + "\); ");
							},
					error: function(e) {
								alert('An error occurred while posting your vote:\n\n' + e.statusText);
							}
				});
			}
		}
	);
	
	// Submit a design thought (comment)
	$('#btnSubmitThought').bind(
		'click',
		function()
		{
			var comment = $('#txtComment').val();
			var name = $('#UserName').val();
			commentPosted = false;
			if (comment != '' && name != '') {
				// post the new comment to the database
				$.ajax({
					type: "POST",
					async: false,
					url: '/pages/programs/letsgodesign/includes/design_thought_post.cfm?ProjectID='+currentProject+'&EpisodeID='+currentEpisode+'&lang='+sitelanguage,
					data: $("#frmPostComment").serialize(),
					success: function(dataRecieved) {
						if(dataRecieved != 'error') 
							// refresh the comments list to include the new post
							reinitialiseCommentsPane();
					},
					error: function(e) {
						alert('An error occurred while posting your comment:\n\n' + e);
					}
				});
			} else {
				alert('Please fill out both form fields to submit a comment.');
				return false;
			}
		}
	);
	
	// Clear the text in the comment submit form
	$('#btnClearThought').bind(
		'click',
		function()
		{
			//$('form')[2].reset();
			$('#UserName').val('');
			$('#txtComment').val('');
		}
	);
	
	// Clear the comment form
	$('#btnCancelThought').bind(
		'click',
		function()
		{
			$('#btnClearThought').click();
			$('#postCommentWrapper').css({display:"none"});
		}
	);
	
	// Submit polling answer
	$('#btnSubmitProjectIdea').bind(
		'click',
		function()
		{
			var termsAgreed = $('#terms:checked').val();//
			var form = $("#frmSubmitIdea");
			var error = false;
			var msg = 'Please be sure to enter valid data into all required fields.';
			if (document.frmSubmitIdea.fname.value.length < 1) {
				error = true;
				msg = msg + '\n    First Name';
			}
			if (document.frmSubmitIdea.lname.value.length < 1) {
				error = true;
				msg = msg + '\n    Last Name';
			}
			if ((document.frmSubmitIdea.mail.value.length < 6)
			|| (document.frmSubmitIdea.mail.value.indexOf("@") == -1)
			|| (document.frmSubmitIdea.mail.value.indexOf(".") == -1)
			|| (document.frmSubmitIdea.mail.value.indexOf(",") != -1)
			|| (document.frmSubmitIdea.mail.value.indexOf(".") == document.frmSubmitIdea.mail.value.indexOf("@") + 1)
			|| (document.frmSubmitIdea.mail.value.indexOf("@") == 0)
			|| (document.frmSubmitIdea.mail.value.indexOf(".") == 0)
			|| (document.frmSubmitIdea.mail.value.indexOf("@") == document.frmSubmitIdea.mail.value.length - 1)
			|| (document.frmSubmitIdea.mail.value.indexOf(".") == document.frmSubmitIdea.mail.value.length - 1)
			|| (document.frmSubmitIdea.mail.value.lastIndexOf("@") > document.frmSubmitIdea.mail.value.lastIndexOf(".")))
			{
				error = true;
				msg = msg + '\n    Email Address';
			}
			if (document.frmSubmitIdea.whatyoudesign.value.length < 1) {
				error = true;
				msg = msg + '\n    What you would like to design';
			}
			if (document.frmSubmitIdea.problemsolve.value.length < 1) {
				error = true;
				msg = msg + '\n    Problem to be solved';
			}
			if (!document.frmSubmitIdea.terms.checked) {
				error = true;
				msg = msg + '\n\nYou must agree to the Terms and Conditions.';
			}
			
			if (error) {
				alert(msg);
				return false;
			}
			
			$.ajax({
				type: "POST",
				async: false,
				url: '/pages/programs/letsgodesign/includes/project_idea.cfm', //?ProjectID='+currentProject+'&Rank='+currentEpisode,  Project and Episode info not needed
				data: $("#frmSubmitIdea").serialize(),
				success: function(dataRecieved) {
							//alert(dataRecieved);
							$('#submitIdeaForm').html(dataRecieved);
						}
			});
			
		}
	);
	
	$('#btnSubmitRegister').bind(
		'click',
		function()
		{
			var termsAgreed = $('#terms:checked').val();//
			var form = $("#frmRegister");
			var error = false;
			var msg = 'Please be sure to enter valid data into all required fields.';
			if (document.frmRegister.fname.value.length < 1) {
				error = true;
				msg = msg + '\n    First Name';
			}
			if (document.frmRegister.lname.value.length < 1) {
				error = true;
				msg = msg + '\n    Last Name';
			}
			if ((document.frmRegister.mail.value.length < 6)
			|| (document.frmRegister.mail.value.indexOf("@") == -1)
			|| (document.frmRegister.mail.value.indexOf(".") == -1)
			|| (document.frmRegister.mail.value.indexOf(",") != -1)
			|| (document.frmRegister.mail.value.indexOf(".") == document.frmRegister.mail.value.indexOf("@") + 1)
			|| (document.frmRegister.mail.value.indexOf("@") == 0)
			|| (document.frmRegister.mail.value.indexOf(".") == 0)
			|| (document.frmRegister.mail.value.indexOf("@") == document.frmRegister.mail.value.length - 1)
			|| (document.frmRegister.mail.value.indexOf(".") == document.frmRegister.mail.value.length - 1)
			|| (document.frmRegister.mail.value.lastIndexOf("@") > document.frmRegister.mail.value.lastIndexOf(".")))
			{
				error = true;
				msg = msg + '\n    Email Address';
			}
			
			if (error) {
				alert(msg);
				return false;
			}
			
			$.ajax({
				type: "POST",
				async: false,
				url: '/pages/programs/letsgodesign/includes/register_email.cfm', //?ProjectID='+currentProject+'&Rank='+currentEpisode,  Project and Episode info not needed
				data: $("#frmRegister").serialize()
			});
			
		}
	);
	
	//$(".dlForm").colorbox({width:"50%", inline:false, href:"javascript:alert(' Hi from inside the colorbox.');", speed:350, opacity:0.65, width:"559px"});
	
	
	function showResponse(responseText, statusText)  { 
		var search_term = 'coldfusion.runtime.RequestTimedOutException';
		var err_check = responseText.indexOf( search_term ); 
		if( err_check == -1 ) { 
		    $('#frmDownloadFiles').hide();
			$('#formStatus').html(responseText);
		} else {
			alert('ERROR: An error occurred during the download process.\n\nRequest Time Out - Please refresh the page and try again.');
		} 
	};
	
	function showError(x, e)  { 
			if(x.status==0){
			alert('You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
			alert('Requested URL not found.');
			}else if(x.status==500){
			alert('Internel Server Error.');
			}else if(e=='parsererror'){
			alert('Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
			alert('Request Timed Out - Please refresh the page and try again.');
			}else {
			alert('Unknown Error.\n'+x.responseText);
			}
	};
		
	$().bind(
		'cbox_open', 
		function(){
			$('#frmDownloadFiles').show();
			$('#formStatus').html('');				
	});
	
	$('#downloadSubmit').bind(
		'click',
		function(){
			// Loop through selections; as soon as a selected file is found return true to submit the download form
			
			for (var i=1; i<=document.frmDownloadFiles.downloadChoices.length; i++) {
				thisItem = eval("$\('#downloadChoice"+i+":checked'\).val\(\)");
				if (thisItem !== undefined) {
					return true;
				}
			}
			// If no file was selected return false with error message
			alert('ERROR. Please be sure to select at least one file to download.');
			return false;
	});
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	var theBrowser;
	theBrowser = "";
	if ($.browser.msie & parseInt(jQuery.browser.version) == 6) {
		theBrowser = "msie6";
	}
	if ($.browser.msie & parseInt(jQuery.browser.version) == 7) {
		theBrowser = "msie7";
	}
	
	// load lightboxes
	$("#showDownloads").colorbox({width:"50%", inline:true, href:"#fileDownloads", speed:350, opacity:0.65, width:"559px"});
	if (theBrowser ==  "msie6" || theBrowser == "msie7")
	{
		$("#checkOutBio").colorbox({width:"50%", inline:true, href:"#jeremyBio", speed:350, opacity:0.65, width:"557px", height:"566px", scrolling:false});
		$("#showTips").colorbox({width:"50%", inline:true, href:"#tips", speed:350, opacity:0.65, width:"557px", height:"566px"});
		$("#showIndustryContributors").colorbox({width:"50%", inline:true, href:"#contributors", speed:350, opacity:0.65, width:"557px", height:"566px", scrolling:false});
	} else {
		$("#checkOutBio").colorbox({width:"50%", inline:true, href:"#jeremyBio", speed:350, opacity:0.65, width:"557px", height:"540px", scrolling:false});
		$("#showTips").colorbox({width:"50%", inline:true, href:"#tips", speed:350, opacity:0.65, width:"557px", height:"540px"});
		$("#showIndustryContributors").colorbox({width:"50%", inline:true, href:"#contributors", speed:350, opacity:0.65, width:"557px", height:"540px", scrolling:false});
	}
	
	
//	$('#leftTab').bind(
//		'click',
//		function() {
//			currentProject = 1;
//			currentEpisode = 1;
//			loadProject();
//		}
//	);
//	
//	$('#centertTab').bind(
//		'click',
//		function() {
//			currentProject = 2;
//			currentEpisode = 1;
//			loadProject();
//		}
//	);
//	
//	$('#rightTab').bind(
//		'click',
//		function() {
//			currentProject = 3;
//			currentEpisode = 1;
//			loadProject();
//		}
//	);
//	
//	loadProject = function() {
//		loadEpisodes();
//		loadVotePanel();
//		loadComments();
//		loadDownloads();
//	}

	
	loadEpisodes = function()	{
		$.ajax({
			type: "GET",
			async: false,
			url: '/pages/programs/letsgodesign/includes/projects/episodes.cfm?ProjectID='+currentProject+'&EpisodeID='+currentEpisode+'&Rank='+currentEpisode, //+'&voteClose='+voteClose,
			//data: $("#frmEpisodePoll").serialize(),
			success: function(dataReceived) {
						//eval("$\('#pollProject1Episode" + currentEpisode + "'\).html\(" + dataReceived + "\); ");
						$('#belowVideo').html(dataReceived);
					},
			error: function(e) {
						alert('An error occurred while opening the episode display:\n\n' + e);
					}
		});
	}
	
	//loadEpisodes();

	// initialize scrollable
	$(".scrollable").scrollable();

});

