/**
 * author: chris@doityourself.com
 * requires jquery.js <www.jquery.com>
 */

var POST_URL = '/smoothy/resources/baproject/bapost.php';
var BA_HOME = 'did-it-myself';
var TOTAL_ALT_PHOTOS = 6;
var IMG_WIDTH = 220;
var IMG_HEIGHT = 200;
var THUMB_WIDTH = 80;
var THUMB_HEIGHT = 67;
var ANIMATION_SPEED = 'slow';
var images = new Array();
var openEditBox = 0;

$(document).ready(function() {
	if(location.href.indexOf('create-project') != -1) {
		//create project page
		$("textarea.inputbox").focus(function() {
			if(this.value=='Type here...') this.value='';
		});

		//fill category select box
		$.post(
			POST_URL,
			{data:'cat_select'},
			function(data) {
				var parent = $("#parent");
				parent.html(data);
				parent.children()[0].selected = "selected";
			}
		);

		//setup nav links on create-projects page
		$("#btn_step1").click(gotoStep1);
		$("#btn_step2").click(gotoStep2);
		$("#btn_step3").click(gotoStep3);

		$("input#title").focus();
	}
	else {
		setImageViewer();
	}
});

function setImageViewer() {
	$("a img.pic").click(function() {
		popUp("/smoothy/resources/viewPhoto.php?src=" + this.src + "&alt=" + this.alt, "ImageViewer", 500, 500, "no", "yes", "center");
		return false;
	});
}

function edit(id) {
	if(openEditBox) {
		closeEditBox(openEditBox);
	}

	openEditBox = id;
	var databox = $('#' + id + ' .databox');
	var container = $('#' + id);
	var str = '';

	container.hide();
	var rows = 0;

	switch(id) {
		case'tags':
			a = databox.find("a");
			if(typeof(a[0]) != "undefined") {
				str = $.trim(databox.text());
				str = str.replace(/, /gi, "\n");
				a = str.split("\n");
				rows = a.length + 1;
			}
			else {
				rows = 2;
			}
			break;

		case 'summary':
			str = $.trim(databox.html());
			str = str.replace(/<br>/gi, "\n");
			break;

		case 'materials':
			ul = databox.find("ul");
			if(typeof(ul[0]) != "undefined") {
				str = $.trim(ul.html());
				str = str.replace(/<li>/gi, "");
				str = str.replace(/<\/li>/gi, "\n");
				a = str.split("\n");
				rows = a.length + 1;
			}
			break;

		case 'budget':
			str = $.trim(databox.text());
			str = str.replace(/\$/gi, "");
			if(str == 'n/a') str = '';
			rows = 1;
			break;

		default:
			break;
	}

	container.after('<div id="edit_box"><textarea id="textarea_'+id+'" name="textarea_'+id+'">'+str+'</textarea><div id="btn_save"><button onclick="saveTxt(\''+id+'\');">Save</button><button onclick="closeEditBox(\''+id+'\');">Cancel</button></div></div>');
	if(rows!=0) $('#edit_box textarea').attr('rows', rows);
	$('#edit_box textarea').focus();

	return false;
}

function closeEditBox(id) {
	openEditBox = 0;
	$('#edit_box').remove();
	$('#' + id).show();
}

function saveTxt(id) {
	var editbox = $("#edit_box");
	var txtbox = $("#edit_box textarea");
	var content = $.trim(txtbox.val());
	var databox = $('#'+id+' .databox');
	var container = $('#' + id);

	editbox.remove();

	container.after(getLoadingScreen('saving...'));
	$.post(
		POST_URL,
		{alias: ALIAS, type: id, content: content},
		function(data) {
			container.show();
			if(msg = checkError(data)) {
				error(msg);
				edit(id);
			} else {
				databox.after(data);
				databox.remove();
			}
			removeLoadingScreen();
		}
	);
	openEditBox = 0;
}

function writePhotoContainer(photo_id, img_src, thumbnail, noRemove) {
	document.write(getPhotoContainer(photo_id, img_src, thumbnail, noRemove));
}

function getPhotoContainer(photo_id, img_src, thumbnail, noRemove) {
	var is_new = (typeof(img_src) == "undefined" || img_src == '') ? true : false;
	var noRemove = typeof(noRemove) != "undefined" ? noRemove : false;

	if(thumbnail == true) {
		width = THUMB_WIDTH;
		height = THUMB_HEIGHT;
	} else {
		width = IMG_WIDTH;
		height = IMG_HEIGHT;
	}

	img = new Image(width, height);
	images[photo_id] = img;

	html = '<div align="center" id="' + photo_id + '">';
	html+= '<div class="photo">' + (is_new ? '' : '<a href="' + img_src + '"><img class="pic" src="' + img_src + '" width="' + width + '" height="' + height + '" /></a>') + '</div>';
	html+= '<div align="left" id="btn_box_' + photo_id + '">';
	html+= '<a class="btn_edit" id="btn_edit_' + photo_id + '" href="" onclick="return changePhoto(\'' + photo_id + '\');">change photo</a>';
	html+= !noRemove ? '<br/><a class="btn_delete" id="btn_remove_' + photo_id + '" href="" onclick="return removePhoto(\'' + photo_id + '\')">remove photo</a>' : '';
	html+= '</div>';
	html+= '</div>';

	return html;
}

function changePhoto(photo_id) {
	loadPhotoPicker(photo_id, true);
	return false;
}

function loadPhotoPicker(photo_id, cancel_btn) {
	var photobox = $('#' + photo_id + " div.photo");
	$('#btn_box_' + photo_id).hide();

	var params = '?photo_id=' + photo_id;
	if(window.location.href.indexOf("/create-project") == -1) params+= '&alias=' + ALIAS;

	html = '<div class="photo_picker" id="photo_picker_' + photo_id + '"><em>Select a photo</em><iframe name="iframe_' + photo_id + '" src="/smoothy/resources/baproject/upload.php' + params + '" frameborder="0" scrolling="no"></iframe>';
	html+= typeof(cancel_btn) != 'undefined' ? '<br/><a id="btn_cancel_' + photo_id + '" href="" onclick="return closePhotoPicker(\'' + photo_id + '\')">cancel this</a>' : '';
	html+= '</div>';

	photobox.after(html);
	photobox.hide();
}

function closePhotoPicker(photo_id) {
	$('#photo_picker_' + photo_id).remove();
	$('#' + photo_id + ' div.photo').show();
	$('#btn_box_' + photo_id).show();
	return false;
}

function removePhoto(photo_id) {
	if(!confirm("Are you sure you want to remove this photo?")) return false;

	$('#btn_box_' + photo_id).hide();
	$('#' + photo_id + " div.photo").html(getLoadingScreen("removing photo..."));

	var project_alias = typeof(ALIAS) != "undefined" ? ALIAS : '';
	$.post(
		POST_URL,
		{remove_photo: photo_id, project_alias: project_alias},
		function(data) {
			msg = checkError(data);
			if(msg) {
				error(msg);
				closePhotoPicker(photo_id);
			}
			else loadPhotoPicker(photo_id);
		}
	);
	return false;
}

// called from upload.php iframe
// when a person selects a file and the upload begins
function imageUploadStart(photo_id) {
	$('#btn_cancel_' + photo_id).remove();
}

// called from upload.php iframe
// when a file has finished uploading successfully
function imageUploadSuccess(photo_id, img_src) {
	var photobox = $('#' + photo_id + ' div.photo');
	photobox.show();
	closePhotoPicker(photo_id);

	var now = new Date();
	img_src = img_src + "?" + now.getTime();

	img = images[photo_id];
	img.src = img_src + "?" + now.getTime();

	photobox.empty();
	photobox.append(img);
}

// called from upload.php iframe
// when a file has finished uploading, but failed for some reason
function imageUploadFailed(photo_id, msg) {
	closePhotoPicker(photo_id);
	error(msg);
}

function toggleBox(id) {
	var tgl_btn = $('#toggle_'+id);
	if(tgl_btn.text()=="-close") {
		$('#'+id).slideUp();
		tgl_btn.text('+view');
	}
	else {
		$('#'+id).slideDown();
		tgl_btn.text('-close');
	}
	return false;
}

function deleteProject() {
	if(confirm("Are you sure you want to delete this project?\nThis cannot be undone.")) {
		$("#beforeafter_detail").html(getLoadingScreen("This Project is being deleted..."));
		$.post(
			POST_URL,
			{alias: ALIAS, type: 'delete'},
			function(data) {
				if(msg = checkError(data)) {
					error(msg);
				}
				else {
					alert(data);
					window.location = "/" + BA_HOME;
				}
			}
		);
	}
	return false;
}

function setPublishStatus(status) {
	msg = status == 1 ? "Are you sure you want to publish this?" : "Are you sure you want to un-publish this?";
	if(confirm(msg)) {
		$("#beforeafter_detail").html(getLoadingScreen("This Project is being updated..."));
		$.post(
			POST_URL,
			{alias: ALIAS, type: 'setPublish', status: status},
			function(data) {
				if(msg = checkError(data)) {
					error(msg);
				}
				else {
					alert(data);
					window.location.reload();
				}
			}
		);
	}
	return false;
}

function toggleHelpBox() {
	var box = $("#help-box");
	if(box.css('display') == 'block') {
		box.slideUp();
	}
	else {
		box.slideDown();
	}
	return false;
}

function toggleProjectCatList() {
	var box = $("#ba_cat_list");
	if(box.css('display') == 'block') {
		box.slideUp(ANIMATION_SPEED);
	}
	else {
		$("#help_box").hide();
		box.slideDown(ANIMATION_SPEED);
	}
	return false;
}

/*****************
 * Project Journal
 *****************/
var entry_form_open = false;
function getEntryForm(num, header, img_src) {
	entry_form_open = true;

	var html = '<div id="entry_form"><h4>' + header + '</h4>';
	html+= 'Title:<br/><input type="text" id="entry_title" name="entry_title" size="30" maxlength="35" /><div class="small">what do you want to call this entry?<br/>eg. Day 1, Step 1, First Day</div>';
	html+= '<br/><br/>Choose a photo for this entry:<br/>' + getPhotoContainer('journal_photo' + num, img_src, true);
	html+= '<br class="clear-all"/><br/><span class="right">(no HTML, 200 words or less)</span>Journal Entry:<textarea class="edit_box" id="entry_blurb" name="entry_blurb"></textarea><br/>';
	html+= '<button onclick="saveEntry(' + num + ')">Save</button>';
	html+= '<button onclick="cancelEditEntry(' + num + ')">Cancel</button>';
	html+= '</div>';

	return html;
}

//add a new journal entry
function addEntry(num) {
	if(entry_form_open) {
		alert("You are editing another journal entry.\nPlease close that first, then you may continue.");
		return false;
	}
	var entry_container = $("#container_entry" + num);
	entry_container.hide();
	entry_container.after(getEntryForm(num, "New Journal Entry"));
	loadPhotoPicker('journal_photo' + num);

	return false;
}

//edit a journal entry
function editEntry(num) {
	if(entry_form_open) {
		alert("You are editing another journal entry.\nPlease close that first, then you may continue.");
		return false;
	}

	var entry_title = $("#entry_title" + num).text();
	var entry_blurb = $("#entry_blurb" + num).text();
	    entry_blurb = entry_blurb.replace(/<br>/gi, "\n");
	var entry_photo = $("#entry_photo" + num).attr("src");

	var entry_div = $("#entry" + num);
	entry_div.hide();
	entry_div.after(getEntryForm(num, "Journal Entry: " + entry_title, entry_photo));
	$("#entry_title").val(entry_title);
	$("#entry_blurb").html(entry_blurb);

	return false;
}

function cancelEditEntry(num) {
	entry_form_open = false;
	$("#btn_add_entry").show();
	$("#entry_form").remove();
	$("#entry" + num).show();
	$("#container_entry" + num).show();
}

function saveEntry(num) {
	var journal = $("#journal");
	journal.after(getLoadingScreen("saving journal..."));
	journal.hide();

	var entry_title = $("#entry_title").val();
	var entry_blurb = $("#entry_blurb").val();
	$.post(
		POST_URL,
		{alias: ALIAS, type: 'journal', title: entry_title, content: entry_blurb, num: num},
		function(data) {
			msg = checkError(data);
			if(msg) {
				error(msg);
			} else {
				entry_form_open = false;
				$("#journal").html(data); //replace the whole journal section with the updated one
				$("#journal img").each(function() {
					var now = new Date();
					this.src = this.src + "?" + now.getTime();
				});
			}
			journal.show();
			removeLoadingScreen();
		}
	);
}

function deleteEntry(num) {
	if(entry_form_open) {
		alert("You are editing another journal entry.\nPlease close that first, then you may continue.");
		return false;
	}
	if(!confirm("Are you sure you want to delete this journal entry?\nThis cannot be undone.")) return false;

	var journal = $("#journal");
	journal.after(getLoadingScreen("saving journal..."));
	journal.hide();

	$.post(
		POST_URL,
		{alias: ALIAS, type: 'journal', action: 'delete', num: num},
		function(data) {
			if(msg = checkError(data)) {
				error(msg);
			} else {
				journal.html(data); //replace the whole journal section with the updated one
			}
			journal.show();
			removeLoadingScreen();
		}
	);
	return false;
}

function showJournalPage(pageNum) {
	var journal = $("#journal");
	journal.after(getLoadingScreen("loading journal..."));
	journal.hide();

	$.post(
		POST_URL,
		{data: 'journal', alias: ALIAS, journalPage: pageNum},
		function(data) {
			if(msg = checkError(data)) {
				error(msg);
			} else {
				journal.html(data); //replace the whole journal section with the updated one
			}
			journal.show();
			removeLoadingScreen();
		}
	);
	return false;
}

/*********************
 * Project Upload page
 *********************/
function checkTitle() {
	var btn = $("#btn_save_title");
	btn.hide();
	btn.after(getLoadingScreen("saving, please wait..."));

	if($("#parent").val() == 0) {
		error("You must select a Category for your Project.");
		btn.show();
		removeLoadingScreen();
		return false;
	}
	var title = $("#title").val();

	//expects a parsed title to be sent back
	$.post(
		POST_URL,
		{check_title: title},
		function(data) {
			if(msg = checkError(data)) {
				error(msg);
			}
			else {
				$("#project-title").html('Create a Project: ' + data);
				$("#btn_step1").show();
				$("#btn_step2").show();
				gotoStep2();
			}
			btn.show();
			removeLoadingScreen();
		}
	)
	return false;
}

function checkPhotos() {
	var btn = $("#btn_save_photos");
	btn.hide();
	btn.after(getLoadingScreen("saving, please wait..."));

	$.post(
		POST_URL,
		{check_photos: 1},
		function(data) {
			msg = checkError(data);
			if(msg) {
				error(msg);
			} else {
				$("#waiting_screen").remove();
				$("#btn_step2").show();
				$("#btn_step3").show();
				gotoStep3();
			}
			removeLoadingScreen();
			btn.show();
		}
	);
}

function checkBudget() {
	var val = $("#budget").val();
	if(val!='') {
		if(val.match(/[^0-9\.]/)) {
			error("Budget is not valid. Please enter again.");
			$("#budget").val('');
			$("#budget").focus();
		}
	}
}

function gotoStep1() {
	$("#btn_step1").addClass('bold');
	$("#btn_step2").removeClass('bold');
	$("#btn_step3").removeClass('bold');

	$("#intro").show();
	$("#step2").hide();
	$("#step3").hide();
	$("#step1").show();
	window.scrollTo(0,0)
	return false;
}

function gotoStep2() {
	$("#btn_step1").removeClass('bold');
	$("#btn_step2").addClass('bold');
	$("#btn_step3").removeClass('bold');

	$("#intro").hide();
	$("#step1").hide();
	$("#step3").hide();
	$("#step2").show();
	window.scrollTo(0,0)
	return false;
}

function gotoStep3() {
	$("#btn_step1").removeClass('bold');
	$("#btn_step2").removeClass('bold');
	$("#btn_step3").addClass('bold');

	$("#step1").hide();
	$("#step2").hide();
	$("#step3").show();
	window.scrollTo(0,0)
	return false;
}

function gotoStep4() {
	saveProject();
	return false;
}

function saveProject() {
	$("#project-upload textarea, #project-upload input").attr('disabled', true);
	var btn = $("#btn_save_new");
	btn.hide();
	btn.after(getLoadingScreen("saving, please wait..."));

	var title = $("#title").val();
	var summary = $("#summary").val() != 'Type here...' ? $("#summary").val() : '';
	var tags = $("#tags").val() != 'Type here...' ? $("#tags").val() : '';
	var materials = $("#materials").val() != 'Type here...' ? $("#materials").val() : '';
	var budget = $("#budget").val();
	var parent = $("#parent").val();

	$.post(
		POST_URL,
		{new_project:1, title:title, summary:summary, tags:tags, materials:materials, budget:budget, parent:parent},
		function(data) {
			if(msg = checkError(data)) {
				error(msg);
				removeLoadingScreen();
				btn.show();
				$("#project-upload textarea, #project-upload input").attr('disabled', false);
			}
			else {
				window.location = '/' + BA_HOME + '/' + data;
			}
		}
	);
}

function getAltPhotoLink(num) {
	return '<div align="center" class="container_alt_photo" id="container_alt_photo' + num + '"><a class="btn_add" href="" onclick="return addAltPhoto(' + num + ')">Add a Photo</a></div>';
}

function addAltPhoto(num) {
	if(num > TOTAL_ALT_PHOTOS) {
		alert("Sorry, we only allow up to " + TOTAL_ALT_PHOTOS + " alternate photos");
	} else {
		var photo_id = 'alt_photo' + num;
		var container = $('#container_alt_photo' + num);
		container.html(getPhotoContainer(photo_id, null, true));
		loadPhotoPicker(photo_id);

		//add another add photo link
		container.after(getAltPhotoLink(num + 1));
	}
	return false;
}

function flagDocument() {
	if(!confirm("You are about to send warning of this page to an Editor.\n\nContinue?")) return false;

	var btn = $("#btn_flag_document");
	btn.hide();
	btn.after(getLoadingScreen("sending request..."));

	$.post(
		AJAX_URL,
		{action: "flagDocument", alias: ALIAS, contentid: CONTENTID, url: window.location},
		function(data) {
			if(msg = checkError(data)) {
				error(msg);
			}
			else {
				alert(data);
			}
			removeLoadingScreen();
			btn.show();
		}
	);
	return false;
}