fullscreen = false;
isnewmap = false;
showhints = false;
classic = 0;
boldfont = 0;
showfda = 0;
nofda = 0;
shared = 0;
domaintag = 1;
currentRightWidth = 156;
collaborationBarOpen = false;
window.onresize = dimensions;
document.onkeyup = keyCheck;

var tmrSave;
var rWidths = new Array(156, 296, 438);
var rWidth  = 0;

function tellFlash(msg, opt) {
	flash = document.getElementById('WisdomapFlash');
	switch(msg) {
		case 'cut': 		flash.doCut();			break;
		case 'paste':		flash.doPaste();		break;
		case 'reload':		flash.reloadMap(selectedNode);	break;
//		case 'spread':		flash.doSpread(newSpread); 	break;
//		case 'rotate':		flash.doRotate(newRotation);	break;
		case 'viewpoint':	flash.newViewpoint();		break;
		case 'map':		flash.movesNodes();		break;
		case 'png':		flash.doExport('png');		break;
		case 'jpg':		flash.doExport('jpg');		break;
		case 'pdf':		flash.doExport('pdf');		break;
		case 'revision':	flash.toggleRevision();		break;
		case 'locked':		flash.setLocked(opt);		break;
		case 'chatsound':	flash.playChatSound();		break;
		case 'presentation':	flash.togglePresentation(opt); document.getElementById('WisdomapFlash').focus();		break;
	}
}

function dimensions(first) {
	if (document.getElementById('node-notesWidgIframe')) obj = document.getElementById('node-notesWidgIframe');
	else obj = document.getElementById('node-notes');

	if (self.innerHeight) {
		width = self.innerWidth;
		height = self.innerHeight;
	} else if (document.body) {
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}
	if (fullscreen) {
		stageWidth = width;
	} else {
		stageWidth = width-currentRightWidth-3;
		rightBarHeight = height-30-1;
		if (collaborationBarOpen) rightBarHeight -= 25;
		document.getElementById('right').style.height = rightBarHeight + 'px';
		mediaBarHeight = document.getElementById('media').offsetHeight;
		if (document.getElementById('assignment')) mediaBarHeight += 83;
		obj.style.height = (rightBarHeight-26-13-mediaBarHeight-26-13+5) + 'px';
	}
	stageHeight = height-30-1;
	document.getElementById('map').style.height = stageHeight + 'px';
	document.getElementById('map').style.width = stageWidth + 'px';
	if (first == 'first') {
		createFlash();
	}
}

function createFlash() {
	var params = {
		allowScriptAccess: 'always',
		allowFullScreen: 'false',
		menu: 'false',
		quality: 'best',
		bgcolor: '#ffffff',
		wmode: 'transparent',
		flashvars: 'mainID=' + mapID + '&secure=' + secure + '&rotation=' + mapRotation + '&classic=' + classic + '&spread=' + mapSpread + '&mapx=' + mapx + '&mapy=' + mapy + '&stagewidth=' + stageWidth + '&stageheight=' + stageHeight + '&boldfont=' + boldfont + '&showfda=' + showfda + '&nofda=' + nofda + '&shared=' + shared + '&domaintag=' + domaintag

	};
	var attributes = {
		id: "WisdomapFlash",
		name: "WisdomapFlash"
	};
	swfobject.embedSWF('Wisdomap.swf', 'flash', '100%', '100%', '9.0.0', null, false, params, attributes);
	if (showfda) flashLoaded();
	setTimeout("flashError()",1000);
}

function flashLoaded() {

}

function flashError() {
	if (document.getElementById('flash')) {
		document.getElementById('flash').style.visibility = 'visible';
	}
}

function addChildNode() {
	if (document.getElementById('article-number').value == '') return;
	titleChange();
	document.getElementById('selected-node').value = '';
	document.getElementById('selected-node').focus();
	document.getElementById('article-number').value = 'add|' + document.getElementById('article-number').value;
}

function deleteNode() {
	if (selectedNode == '' || selectedNode == 0) return;
	if (selectedNode == mapID)	result = confirm('Are you sure you want to delete this entire map?\nThis cannot be undone!');
	else				result = confirm('Are you sure you want to delete this node?');
	if (result == true) {
		function aj(val) {
			if (val == 'go home') {
				goto('home');
			} else {
				selectedNode = val;
				tellFlash('reload');
			}			
		}
		ajax('calls/nodes.php', 'info=delete|' + selectedNode, aj);
	}
}

function titleChange() {
	var locked = mapLocked.split("|");
	for (var i = 0; i < locked.length; i++) {
		if (document.getElementById('article-number').value == locked[i] && locked[i] != editingNode) {
			document.getElementById('selected-node').readOnly = true;
			return false;
		}
	}
	document.getElementById('selected-node').readOnly = false;
	editingNode = document.getElementById('article-number').value;
	t2u = '';
	if (domaintag == 2) t2u = '-t2u';
	if (document.getElementById('article-number').value == '') return;
	document.getElementById('addNode').src = 'images/btn-finish' + t2u + '.gif';
	document.getElementById('addNode').onclick = function () { doTitleEdit(); };
	document.getElementById('deleteNode').src = 'images/btn-end' + t2u + '.gif';
	document.getElementById('deleteNode').onclick = function () { setArticle(document.getElementById('article-number').value); };
	document.getElementById('titleForm').onsubmit = function () { doTitleEdit(); return false; };
}

function cancelTitleEdit() {
	editingNode = 0;
	t2u = '';
	if (domaintag == 2) t2u = '-t2u';
	document.getElementById('addNode').src = 'images/btn-add' + t2u + '.gif';
	document.getElementById('addNode').onclick = function () { addChildNode(); };
	document.getElementById('deleteNode').src = 'images/btn-delete.gif';
	document.getElementById('deleteNode').onclick = function () { deleteNode(); };
	document.getElementById('titleForm').onsubmit = function () { addChildNode(); return false; };
}

function doTitleEdit() {
	var nodeID = document.getElementById('article-number').value;
	document.getElementById('selected-node').value = document.getElementById('selected-node').value.replace(/\|/g, '{#1}');
	if (nodeID.search(/add/) == 0) {
		function ajAdd(val) {
			selectedNode = val;
			tellFlash('reload');
			document.getElementById('WisdomapFlash').focus();
		}
		ajax('calls/nodes.php', 'info=' + nodeID + '|' + escape(document.getElementById('selected-node').value), ajAdd);
	} else {
		function aj(val) {
			if (val == 'success') {
				selectedNode = nodeID;
				tellFlash('reload');
				document.getElementById('WisdomapFlash').focus();
			} else {
				alert('Unexpected error. Please contact support with error code [map.js#157].');
				alert(val);
			}
		}
		
		ajax('calls/nodes.php', 'info=rename|' + nodeID + '|' + escape(document.getElementById('selected-node').value), aj);
	}
	setArticle(document.getElementById('article-number').value);
	if (showhints && isnewmap) {
		document.getElementById('advice').style.display = '';
		document.getElementById('advice2').style.display = 'block';
		setTimeout("document.getElementById('advice2').style.display = '';", 6000);
		isnewmap = false;
	}
}

function editCurNode() {
	document.getElementById('selected-node').select();	
}

function editNotes() {
	document.getElementById('node-notesWidgIframe').contentWindow.focus();
}

function setArticle(node, reload) {
	if (reload != null && editingNode != 0) return false;
	
	if (shared !== 1) widgInit();
	
	var setNote = function (x, c) {
		if (shared !== 1) {
			document.getElementById('node-notes').value = x;
			updateText();
			setColour(c);
		} else {
			document.getElementById('node-notes').innerHTML = x;
		}
	}

	if (typeof(node) == 'string') node = node.replace(/add\|/, '');
	if (document.getElementById('selected-node') != null) cancelTitleEdit();
	function aj(val) {
		var arrData = val.split('|');
		document.getElementById('article-number').value = arrData[0];
		selectedNode = arrData[0];
		if (document.getElementById('selected-node') != null) document.getElementById('selected-node').value = arrData[1].replace(/\{\#1\}/g, '|');
		if (document.getElementById('right') != null) {
			if (arrData[2] == '') {
				if (document.getElementById('selected-node') != null)  {
					setNote('Click here or press N to add notes...', 1);
				} else {
					setNote('');
				}
			} else {
				arrData[2] = arrData[2].replace(/\{\#1\}/g, '|');
				setNote(arrData[2], 0);
			}
		}
		if (isnewmap) {
			document.getElementById('selected-node').select();
			if (showhints) {
				document.getElementById('advice').style.display = 'block';
				setTimeout("document.getElementById('advice').style.display = '';",3000);
			}
		} else {
			document.getElementById('WisdomapFlash').focus();
		}
		
	}
	ajax('calls/map.php', 'node=' + node, aj)
	function aj2(val) { document.getElementById('media').innerHTML = val; dimensions(); }
	ajax('calls/media.php', 'node=' + node, aj2);
}

function startEdit() {
	var locked = mapLocked.split("|");
	for (var i = 0; i < locked.length; i++) {
		if (document.getElementById('article-number').value == locked[i] && locked[i] != editingNode) {
			document.getElementById('node-notesWidgIframe').contentWindow.document.designMode = "off";
			return false;
		}
	}
	document.getElementById('node-notesWidgIframe').contentWindow.document.designMode = "on"

	editingNode = document.getElementById('article-number').value;
	if (document.getElementById('node-notes').value == '' || document.getElementById('node-notes').value == 'Click here or press N to add notes...') {
		document.getElementById('node-notes').value = '';
		updateText();
		setColour(0);
	}
	
	tmrSave = setInterval('saveText("timer")', 4000);
	return true;
}

function saveText(b) {

	returnText();
	
	var nodeID = document.getElementById('article-number').value;
	function aj(val) { if (val != '-') alert('An error was encountered while saving your text'); }
	if (document.getElementById('node-notes').value == 'Click here or press N to add notes...') document.getElementById('node-notes').value = '';
	ajax('calls/nodes.php', 'info=edit|' + nodeID + '|' + escape(document.getElementById('node-notes').value.replace(/\|/g,'{#1}')), aj);
}

function finishEdit() {
	//window.clearInterval(tmrSave); 
	editingNode = 0;
	
	saveText('function');
	if (document.getElementById('node-notes').value == '') {
		document.getElementById('node-notes').value = 'Click here or press N to add notes...';
		updateText();
		setColour(1);
	}
	return true;
}

function checkKey(e) {
	var evt = e || window.event;
	if (e.keyCode == 27 || e.keyCode == e.DOM_VK_ESCAPE) {
		document.getElementById('WisdomapFlash').focus();
	}
}

function openPopup(popup) {
	document.getElementById('blanket').style.display = 'block';
	//closePopups();
	document.getElementById('popup-' + popup).style.display = 'block';
	lastPopup = popup;
}

function setIframe(type) {
	document.getElementById('iframe').src = '/popup/' + type + '/' + selectedNode;
}

function closePopups() {
	var arrElements=['blanket','popup-layout','popup-download','popup-share','popup-viewpoint','popup-addmedia','popup-doaddmedia','popup-order','popup-collab','popup-assignment_save'];

	for (x in arrElements) {
		if (document.getElementById(arrElements[x])) document.getElementById(arrElements[x]).style.display = '';
	}
	
	if (typeof lastPopup != 'undefined' && (lastPopup == 'addmedia' || lastPopup == 'doaddmedia')) {
		document.getElementById('iframe').src = '/popup/blank';
	}
}

function download(auth) {
	if (!auth) { alert('Sorry, this feature is not available for your account type.'); return; }
	if (document.getElementById('download-png').checked) tellFlash('png');
	if (document.getElementById('download-jpg').checked) tellFlash('jpg');
	if (document.getElementById('download-pdf').checked) tellFlash('pdf');
	if (document.getElementById('download-text').checked) window.location.href = '/map2text/' + mapID;
	closePopups();
}

function printButton(auth) {
	if (!auth) { alert('Sorry, this feature is not available for your account type.'); return; }
	alert('Your mind map has been prepared as a PDF file, which will now be sent to your browser. To print your map, open the file and use the application print function.');
	tellFlash('pdf');
}

function share() {
	function aj() { closePopups(); };
	if (document.getElementById('shared-yes').checked) {
		ajax('calls/nodes.php', 'share=1&map=' + mapID, aj);
	} else if (document.getElementById('shared-no').checked) {
		ajax('calls/nodes.php', 'share=0&map=' + mapID, aj);
	} else {
		ajax('calls/nodes.php', 'share=2&map=' + mapID, aj);
	}
}

function doLayout() {
	function aj() { tellFlash('reload'); };
	if (document.getElementById('style-organic').checked) classic = 0;
	if (document.getElementById('style-classic').checked) classic = 1;
	ajax('calls/nodes.php', 'map=' + mapID + '&classic=' + classic, aj);
}

function doSpread() {
	function aj() { tellFlash('reload'); };
	newSpread = document.getElementById('spread').value;
	ajax('calls/nodes.php', 'map=' + mapID + '&spread=' + newSpread, aj);
}

function doRotate() {
	function aj() { tellFlash('reload'); };
	newRotation = document.getElementById('rotation').value;
	ajax('calls/nodes.php', 'map=' + mapID + '&rotation=' + newRotation, aj);
}

function resetDefaults() {
	function aj() { tellFlash('reload'); };
	ajax('calls/nodes.php', 'spread=0&rotation=0&map=' + mapID, aj);
}

function saveViewpoint(savex,savey) {
	mapx = savex;
	mapy = savey;
	function aj() { openPopup('viewpoint'); }
	ajax('calls/nodes.php', 'mapx=' + savex + '&mapy=' + savey + '&map=' + mapID, aj);
	
}

function keyCheck(e) {
	var kC  = (window.event) ?
		 event.keyCode : e.keyCode;
	var Esc = (window.event) ?   
		27 : e.DOM_VK_ESCAPE
	if(kC==Esc) {
		setArticle(selectedNode);
		document.getElementById('WisdomapFlash').focus();
		closePopups();
	}
}

function changeWidth() {
	rWidth++;
	if (rWidth == 3) rWidth = 0;
	document.getElementById('right').style.width = rWidths[rWidth] + 'px';
	document.getElementById('side-resize').style.right = (rWidths[rWidth] - 3) + 'px';
	currentRightWidths = rWidths[rWidth];
	dimensions();
	ajax('calls/nodes.php', 'rwidth=' + rWidth +  '&map=' + mapID, null);

}

function saveAssignment() {
	openPopup('assignment_save');
}

function submitAssignment() {
	if (confirm('Are you sure you want to submit this assignment?') == true) {
		function aj(a) { 
			alert('Your map has been submitted.'); 
			window.location = '../../';
		};
		ajax('calls/nodes.php', 'assignment-submit=1&map=' + mapID, aj);
	}
}

function saveAssignmentPass() {
	
	function aj(a) {
		document.getElementById('assignment_save_d1').style.display = 'none';
		document.getElementById('assignment_save_d2').style.display = 'block';
	}
	ajax('calls/nodes.php', 'assignment-pass=' + document.getElementById('assignment_save_pass').value + '&map=' + mapID, aj);
}

function emailMapLink(link)
{
	function aj(a) 
	{
		//closePopups();
		document.getElementById('assignment_save_d2').innerHTML = '<p>An email has been sent to you with a link to this map.</p>';
	}
	ajax('calls/nodes.php', 'assignment-email=' + document.getElementById('assignment_email').value + '&link=' + link, aj);
}

//Collaboration

var mapChat = "";
var mapImage = "";
var mapLocked = "";
var editingNode = 0;

function startCollaboration() {
	document.getElementById('collaboration-bar').style.display = 'block';
	collaborationBarOpen = true;
	dimensions();
}

function enableCollaboration(name) {
	function aj(a) 
	{
		window.location.reload();
	}
	ajax('calls/collab.php', 'add='+name+'&map=' + mapID, aj);
}

function updateCollaboration(id) {
	
	function aj(a) 
	{
		tarr = a.split("\n");
		
		tmap = tarr[1].substring(0, 31);
		if (mapImage != "" && mapImage != tmap) tellFlash('reload');
		mapImage = tmap;
		
		tchat = tarr[1].substring(32, 63);
		if (mapChat != tchat) getChat();
				
		mapLocked = tarr[2]; //.substring(64);
		tellFlash("locked", mapLocked);
		
		document.getElementById('collaboration-bar-inner').innerHTML = tarr[0].replace(/\| $/, "");

	}
	ajax('calls/collab.php', 'get=*&map=' + mapID + '&id=' + id + '&locked=' + editingNode, aj);
	
	setTimeout("updateCollaboration(" + id + ")", 2000);

}

function addCollabUser() {
	function aj(a) 
	{
		closePopups();
		document.getElementById('collab-name').value = "";
		document.getElementById('collab-email').value = "";
	}
	ajax('calls/collab.php', 'adduser=' + document.getElementById('collab-name').value + '&email=' + document.getElementById('collab-email').value + '&map=' + mapID, aj);
	
}

function addChatMessage() {
	if (document.getElementById('collab-chat-message').value.replace(/^[ \t]+|[ \t]+$/, '') == '') return false;
	function aj(a) 
	{
		document.getElementById('collab-chat-message').value = '';
		getChat();
	}
	ajax('calls/collab.php', 'addchat=' + document.getElementById('collab-chat-message').value + '&map=' + mapID, aj);
}

function getChat() {
	function aj(a) 
	{
		if (mapChat != '') {
			document.getElementById('collab-chat').style.display = "block";
			if (!nosound) tellFlash("chatsound");
		}
		
		mapChat = a.substring(0, 31);
		document.getElementById('collab-chat-text').innerHTML = a.substring(32);
		document.getElementById('collab-chat-text').scrollTop = document.getElementById('collab-chat-text').scrollHeight;
	}
	ajax('calls/collab.php', 'getchat=' + mapID, aj);
	
}

function displayChat() {
	var wind = document.getElementById('collab-chat');
	var wtext = document.getElementById('collab-chat-text');
	if (wind.style.display != "block") {
		wind.style.display = "block";
		wtext.scrollTop = wtext.scrollHeight;
	}
	else wind.style.display = "none";
}
