// create a ThoughtMesh cloud with navigation features

telamon = new Object;
thoughtMesh = new Object;

function ThoughtMeshPlugin (document_id) {

  this.document_id = document_id;   // int
	this.nav_local   = 1;             // int
	this.nav_submesh = 1;             // int
	this.nav_global  = 1;             // int
	this.default_nav       = (getCookie('nav_submesh')==1)?'nav_submesh':'nav_global';  // string
	this.nav_title_local   = 'Local';      // string
	this.nav_title_submesh = 'SubMesh';    // string
	this.nav_title_global  = 'Global';     // string
	this.return_results_to = '';  // string
	this.draw               = draw;              // method
	this.setDefault         = setDefault         // method
	this.displayLocalNav    = displayLocalNav    // method
	this.displaySubMeshNav  = displaySubMeshNav  // method
	this.displayGlobalNav   = displayGlobalNav   // method
	this.setLocalNavTitle   = setLocalNavTitle   // method
	this.setSubMeshNavTitle = setSubMeshNavTitle // method
	this.setGlobalNavTitle  = setGlobalNavTitle  // method
	this.setReturnResultsTo = setReturnResultsTo;
	this.highlightTag       = highlightTag; // method

	// tags
	// tags should be held in an pre-defined 'documentTags' (via AJAX, ie)
	// frequencies should be held in 'tagFrequencies'

	function draw(html_element) {
	  var html_obj = document.getElementById(html_element);
		if (!html_obj) return false;

		var iHtml;

		var output_div = document.createElement('DIV');
		output_div.id = 'ThoughtMeshPlugin_Div';

		var nav_div = document.createElement('DIV');
		nav_div.id = 'ThoughtMeshPlugin_Nav_Div';
		iHtml = '';
		if (this.nav_local) iHtml += ' <a href="javascript:ThoughtMeshPlugin_Goto(\'ThoughtMeshPlugin_Local_Div\');">'+this.nav_title_local+'</a> ';
		if (this.nav_submesh) {
		  if (this.nav_local) iHtml += '| ';
		  iHtml += ' ';
			if (this.default_nav != 'nav_submesh') iHtml += '<a href="javascript:tm_switchto(\'nav_submesh\');">';
			iHtml += this.nav_title_submesh;
			if (this.default_nav != 'nav_submesh') iHtml += '</a>';
			iHtml += ' ';
		}
		if (this.nav_global) {
		  if (this.nav_submesh) iHtml += '<span style="color:#999999;">|</span> ';
		  iHtml += ' ';
			if (this.default_nav != 'nav_global') iHtml += '<a href="javascript:tm_switchto(\'nav_global\');">';
			iHtml += this.nav_title_global;
			if (this.default_nav != 'nav_global') iHtml += '</a>';
		}
		nav_div.innerHTML = '<h1 class="option headingOption">'+iHtml+'</h1>';
		output_div.appendChild(nav_div);

		var local_div = document.createElement('DIV');
		local_div.innerHTML = 'LOCAL';
		local_div.id = 'ThoughtMeshPlugin_Local_Div';
		local_div.style.display = (this.default_nav == 'nav_local') ? 'block' : 'none';
		output_div.appendChild(local_div);

		var submesh_div = document.createElement('DIV');
		iHtml = '';
		for (var a in documentTags) {
		  iHtml += '<a style="font-size:'+((localTagFrequencies[documentTags[a]]>1)?'15':'13')+'px;" href="javascript:document.getElementById(\''+this.return_results_to+'\').innerHTML=\'Loading...\';tm_ajaxSectionTags('+tm_document_id+', \''+escape(documentTags[a])+'\', 1);">'+documentTags[a]+'</a> &nbsp; ';
		}
		submesh_div.innerHTML = '<h1 class="option">'+iHtml+'</h1>';
		submesh_div.id = 'ThoughtMeshPlugin_SubMesh_Div';
		submesh_div.style.display = (this.default_nav == 'nav_submesh') ? 'block' : 'none';
		output_div.appendChild(submesh_div);

		var global_div = document.createElement('DIV');
		iHtml = '';
		for (var a in documentTags) {
		  iHtml += '<a style="font-size:'+((localTagFrequencies[documentTags[a]]>1)?'15':'13')+'px;color:'+((tagFrequencies[documentTags[a]]<=1)?'#e8947e':'')+';" href="javascript:document.getElementById(\''+this.return_results_to+'\').innerHTML=\'Loading...\';tm_ajaxSectionTags('+tm_document_id+', \''+escape(documentTags[a])+'\');">'+documentTags[a]+'</a> &nbsp; ';
		}
		global_div.innerHTML = '<h1 class="option">'+iHtml+'</h1>';
		global_div.id = 'ThoughtMeshPlugin_Global_Div';
		global_div.style.display = (this.default_nav == 'nav_global') ? 'block' : 'none';
		output_div.appendChild(global_div);

		html_obj.innerHTML = '';
		html_obj.appendChild(output_div);

	}

	function setDefault() {
	  // TODO: not implemented correctly
	  var default_nav = 'nav_submesh';
	  if (this.nav_local != 1) default_nav = 'nav_submesh';
		if (this.nav_local != 1 && this.nav_submesh != 1) default_nav = 'nav_global';
		this.default_nav = default_nav;
	}

	function displayLocalNav(bool) {
	  this.nav_local = (bool) ? 1 : 0;
	}

	function displaySubMeshNav(bool) {
	  this.nav_submesh = (bool) ? 1 : 0;
	}

	function displayGlobalNav(bool) {
	  this.nav_global = (bool) ? 1 : 0;
	}

	function setLocalNavTitle(theStr) {
	  this.nav_title_local = (theStr.length > 0) ? theStr : this.nav_title_local;
	}

	function setSubMeshNavTitle(theStr) {
	  this.nav_title_submesh = (theStr.length > 0) ? theStr : this.nav_title_submesh;
	}

	function setGlobalNavTitle(theStr) {
	  this.nav_title_global = (theStr.length > 0) ? theStr : this.nav_title_global;
	}

	function setReturnResultsTo(resultsTo) {
	  this.return_results_to = resultsTo;
	}

	function highlightTag(tag) {
	  var tagDiv;
		if (this.default_nav == 'nav_local') {
		  tagDiv = 'ThoughtMeshPlugin_Local_Div';
		} else if (this.default_nav == 'nav_submesh') {
		  tagDiv = 'ThoughtMeshPlugin_SubMesh_Div';
		} else if (this.default_nav == 'nav_global') {
		  tagDiv = 'ThoughtMeshPlugin_Global_Div';
		}
		var divObj = document.getElementById(tagDiv);
		if (!divObj) return;
		var elements = divObj.getElementsByTagName("A");
		for (var a = 0; a < elements.length; a++) {
		  if (elements[a]) {
			  if (elements[a].innerHTML == tag) {
				  elements[a].className = 'sel';
					try {
					  elements[a].blur();
					} catch(e) {}
				} else {
				  elements[a].className = '';
				}
			}
		}

	}

} // end prototype


//
// Ajax handlers
// The event handlers are object oriented, and the 'request' variable is localized. This allows for
// multiple Ajax requests to be sent at the same time, returning to the same return function.
//  -- Craig (Aug 2007)
// TODO: make the response objects inherate the their code-duplicated functions and variables
//

function tm_switchto(_nav) {
  tmplugin.default_nav = _nav;
  tmplugin.draw('ThoughtMeshContent');
  // delete cookies first, then reset the current
  deleteCookie('nav_submesh');
  deleteCookie('nav_global');
  setCookie(_nav,1,5);
}

function tm_ajaxSectionTags(document_id, tag, group_id) {

  var url  = '../thoughtmesh/json/outsideLexias.json.php?tag='+tag+'&documentid='+parseInt(document_id);
	  if (typeof(group_id) != 'undefined') {
	    url += '&groupid='+parseInt(group_id);
	    url += '&showdocown=1';
	  }
	//alert(url);
	tm_httpRequest("GET",url,1,new tm_ReturnSectionTags());
	// TODO: switch to object.instance...
	tmplugin.highlightTag(tag);

}

function tm_ReturnSectionTags() {

  // variables
  var reqObj      = null;

	// methods
	this.setReqObj  = setReqObj;
  this.goResponse = goResponse;

	// method: set the Ajax request object
	function setReqObj(myVal) { reqObj = myVal; }

	// method: Ajax response
  function goResponse() {

    var request = reqObj;

    if (request.readyState == 4) {

      if (request.status == 200) {

  		  var mytext = request.responseText;
//alert(mytext);
  		  if (mytext == '0') {
  			  alert("ERROR! There was a problem attempting to save document data:\nThere was a problem submitting the information to the database.  Please try again.");
        } else if (mytext == '2') {
          alert("ERROR! There was a problem attempting to save document data:\nYou have been logged out.  Please save your data, re-login and try again.");
  			} else {

          // Success!
  				var jsonObject = eval(request.responseText);

					outsideLexiasFun();

					var iHtml = '';
					var hasElements = false;
					for (var a in outsideLexiasObj) {
					  hasElements = true;
					  iHtml += '<div class="tmpluginDocument">';
					  iHtml += (outsideLexiasObj[a].author.length>0) ? outsideLexiasObj[a].author : '(Author Unknown)';
						iHtml += ', ';
						iHtml += '"'+outsideLexiasObj[a].title+'"';
						for (var b in outsideLexiasObj[a].lexias) {
						  iHtml += '<div class="tmpluginSection">';
							iHtml += '<a href="'+outsideLexiasObj[a].url+'#'+outsideLexiasObj[a].lexias[b].anchor+'">'+outsideLexiasObj[a].lexias[b].heading+'</a>';
							iHtml += '</div>';
							iHtml += '<div class="tmpluginExcerpt">';
							iHtml += outsideLexiasObj[a].lexias[b].excerpt;
							iHtml += '</div>';
						}
						iHtml += '</div>';
					}

					if (hasElements) {
					  iHtml = '<div class="tmpluginHeader">ThoughtMesh Results.  Please click a green link to navigate to a new page.</div>'+iHtml;
					} else {
					  iHtml = '<div class="tmpluginHeader">ThoughtMesh Results.<br /><br /><i>There are no other pages with the tag you selected.  Please click another tag to try again.</i></div>';
					}

					document.getElementById(tmplugin.return_results_to).innerHTML = iHtml;

  			}

      } else {
        alert("ERROR! There was a problem attempting to save document data:\nCan't find the required ajax file to send the request.  Please try again.");
      }

    }
    return true;

	} // end method

}

var ajaxLog = '';

function tm_httpRequest(type,url,asynch,respHandle) {

  ajaxLog += url+"\n";

  var request;

  // moz
  if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
  }

  // ie
  else if (window.ActiveXObject) {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    if (!request) request = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // send request | error
  if (request) {
    if (type.toLowerCase() != "post") {
      tm_initRequest(request,type,url,asynch,respHandle);
    }
    else {
      var args = arguments[4];
      if (args != null && args.length > 0) tm_initRequest(request,type,url,asynch,respHandle,args);
    }
  }
  else {
    alert("You appear to be using a browser that does not support AJAX.  Please update your browser.");
  }

}

function tm_initRequest(request,type,url,asynch,respHandle) {

  var objOverride = true;

  try {
	  if (!objOverride) {
		  respHandle.reqObj = request;
      request.onreadystatechange = respHandle;
		} else {
		  respHandle.setReqObj(request);
		  request.onreadystatechange = respHandle.goResponse;
		}
    request.open(type,url,asynch);
    if (type.toLowerCase() == "post") {
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      request.send(arguments[5]);
    }
    else {
      request.send(null);
    }
  } catch (errv) {
    alert("AJAX can not contact the server at this moment.  Please try again.  (Error: "+errv.message+")");
  }

}
