/*

TODO: 

This is messy as fuck, split into pages for each main section of Koble

*/
function setup() { 

}

function matchHeight() {
    m=$("main");
    r=$("rightbar");
    h=Math.max(m.scrollHeight, r.scrollHeight);
    m.style.minHeight=h+"px"; 
    r.style.minHeight=h+"px";

}

document.observe("dom:loaded", matchHeight);

// document.observe("dom:loaded", function () { Shadower.shadowWithClass("nicebox"); }); 


function wikicreate() { 
  Effect.toggle('wikiedit');
}

function showPrivacy() { 
  Effect.toggle('privacy');
}

function showCreateThing() { 
  Effect.toggle('createThing');
}

function showCreateSubclass() { 
  Effect.toggle('createSubclass');
}

function showAddLink() { 
  Effect.toggle('addLink');
}


function showAddRelation() { 
  Effect.toggle('addRelation');
}

function showAddAttribute() { 
    Effect.toggle('addAttribute');
}

function createThing() { 
  form=$('createForm'); 
  form.action+=$('name').value; 
  //form.submit()
}

function createSubclass() { 
  form=$('createSubForm'); 
  form.action+=$('subclassname').value; 
  //form.submit()
}




function sidebarClick(uri,event,o,action) { 
  if (event.ctrlKey) { 
    if (action!=null) action(o);
  } else { 
    document.location=uri;
  }
}



function linksLink(o) {  
  l=getLabel(o);
  document.location="/things/"+username+"/"+l+"/links";
}

function getLabel(o) { 
  classes=o.className.split(" ")
    for (i=0; i<classes.length; i++) { 
      if (classes[i].substr(0,6)=="label:") return classes[i].substr(6)
	}
}

function toggleTree(origin, id) { 
  Effect.toggle('treenode_'+id);
  // collapsed.png 
  //  expanded.png
  if (origin.src.substr(-13)=="collapsed.png") { 

    // This code is perfect:
    
    new Ajax.Request("/sys/pimotree", { method: "post", postBody: "<?xml version='1.0'?><states><expanded label='"+id+"' /></states>" });

    origin.src="/static/icons/16x16/expanded.png";
  } else {

    new Ajax.Request("/sys/pimotree", { method: "post", postBody: "<?xml version='1.0'?><states><collapsed label='"+id+"' /></states>" });

    origin.src="/static/icons/16x16/collapsed.png";
  }
}


function createRelation() { 
  f=$("relationform"); 
  f.action+=$("relation").value;
  f.submit();
}

function addAttribute() { 
  f=$("attributeform"); 
  f.action+=$("attribute").value;
  f.submit();
}




function deleteLink(link, label, id, thing) { 

  var a=confirm("Are you sure you want to permanently delete "+label+"?");
  if (a==true) { 
    var uri=link.href;
    if (thing) { 
      uri+="?thing="+URLEncode(thing);
    }
    new Ajax.Request(uri, {method: "delete", 
        onSuccess: function() {
		    Effect.toggle(id); 
		},
		onException: function(e) {
    	    alert("Could not delete link: "+e);
		},
		onFailure: function(e) {
		    alert("Could not delete link: "+e); 
		}
    });
									
  }
}


function deleteThing(link, label) { 
  var a=confirm("Are you sure you want to permanently delete "+label+"?");
  if (a==true) { 
    var uri=link.href;
    new Ajax.Request(uri, {method: "delete", 
        onSuccess: function() {
		    alert(label+" was deleted."); 
		    document.location="/things/"+username;
		},
		onException: function(e) {
    	    alert("Could not delete thing: "+e);
		},
		onFailure: function(e) {
		    alert("Could not delete thing: "+e); 
		}
    });
    
  }


}

function deleteFile(link, label, username,thing) { 
  var a=confirm("Are you sure you want to permanently delete the file  "+label+"?");
  if (a==true) { 
    var uri=link.href;
    if (thing) { 
      uri+="?thing="+URLEncode(thing);
    }

    new Ajax.Request(uri, {method: "delete", 
        onSuccess: function() {
		    alert(label+" was deleted."); 
		    document.location="/files/"+username;
		},
		onException: function(e) {
    	    alert("Could not delete file: "+e);
		},
		onFailure: function(e) {
		    alert("Could not delete file: "+e); 
		}
    });
    
  }


}

function addFileTag(o) { 
  var l=getLabel(o);
  addTag("target",l);
}

function addLinksTag(o) { 
  addTag("tags",getLabel(o));
}

function addTag(id,label) { 
  var e=$(id);
  
  if (e.value!="" && e.value.substring(e.value.length-1)!=",") {
    e.value+=", ";
  }
  e.value+=label;
   
}

function noloading() { 
  $("shadow").style.display="none";
}

function loading(msg) { 
  window.scrollTo(0,0);
  Effect.toggle("waiting");
  var wm=$("waitingmessage").firstChild.nodeValue=msg;
  // Effect.toggle("shadow");
  $("shadow").style.display="block";

  //alert(window.innerHeight+", "+window.innerWidth);
  //alert((window.innerHeight/2)-42);
  //alert((window.innerWidth/2)-42);
  //w.style.top=(window.innerHeight/2)-42;
  //w.style.left=(window.innerWidth/2)-42;
  //alert(w.style.top);
  //alert(w.style.left);

  //w.style.display="block";

}


function wikiSave(username, label) { 
  loading("Saving wikipage...");

  var text=$('wikitext').value;
  var action="/things/"+username+"/"+label+"/wiki";
  //alert(text+", "+action);
  new Ajax.Request(action, { method: "post", 
        parameters: {wikitext: text },
        onFailure: function (e) { alert("Could not save wikipage: "+e); noloading();},  
        onSuccess: function () { 
		  // do this instead of document.location.reload to avoid post'ing again
		  document.location="/things/"+username+"/"+label;
		} 
	});
}

function addRelation(type) {
  $('reltype').firstChild.nodeValue=type;
  Effect.toggle("addRelation");
}

function toggleStar() {
    var action=document.location+"/star";
    var s=$("star");
    if (s.src.endsWith("star_inactive.png")) { 
	s.src="/static/icons/star_active.png";
    } else {
	s.src="/static/icons/star_inactive.png";
    }
    new Ajax.Request(action, {method: "put"});
}

function savePrivacy() { 
  var img=('privacyimg');
  var txt=$('privacytxt');
  var p=txt.firstChild.nodeValue;
  var action=document.location+"/privacy/";
  if (p=="private") {
    img.src="/static/icons/16x16/public.png";
    txt.firstChild.nodeValue="public";		
    new Ajax.Request(action+"public", {method: "put"});
  } else { 
    img.src="/static/icons/16x16/private.png";
    txt.firstChild.nodeValue="private";
    new Ajax.Request(action+"private", {method: "put"});
  }
  showPrivacy()
    }

function saveRelation() { 
  loading("Saving relation...");

  var name=$('name').value;
  var invname=$('invname').value;
  var type=$('reltype').firstChild.nodeValue;
  var action=$('addRelationForm').action;

  new Ajax.Request(action, { method: "post", 
    parameters: {name: name, invname: invname, type: type}, 
    onFailure: function (e) { alert("Could not save relation: "+e); noloading();}, 
    onSuccess: function () { document.location.reload(); }
  });
}





function saveNewFileRelations() { 
  loading("Saving relation...");

  var target=$('target').value;
  var action=$('relationForm').action;
  action+="?"+queryString({target: target})
  new Ajax.Request(action, { method: "put", 
    onFailure: function (e) { alert("Could not save relations: "+e); noloading(); }, 
    onSuccess: function() { document.location.reload(); }
  });
}

function checkThingNew(name) { 
  // if the thing does exist, disable submit

  $('thingindicator').style.display='inline';
  new Ajax.Request("/sys/thingexists", 
	       { parameters: { name: name }, 
		 method: "post", 
		   onFailure: function (e) { 
		       $('thingindicator').style.display='none';
		       $('submit').disabled=false; 
		       $('thinghint').firstChild.nodeValue="Ok!"; 
					 $('thinghint').style.color='#006cff';
		   }, 

		   onSuccess: function() { 
   		       $('thingindicator').style.display='none';
		       $('submit').disabled=true; 
		       $('thinghint').firstChild.nodeValue="A thing by that name already exists."; 
					 $('thinghint').style.color='#bc1111';
			 }
		 }
  );
}



// Insert myValue in the textarea myField
function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
	myField.focus();
	sel = document.selection.createRange();
	sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == 0) {
	var startPos = myField.selectionStart;
	var endPos = myField.selectionEnd;
	myField.value = myField.value.substring(0, startPos)
	    + myValue
	    + myField.value.substring(endPos, myField.value.length);
    } else {
	myField.value += myValue;
    }
}

Event.observe(window, 'load', function () { 
	if ($("wikitext")!=null) {
	    $("wikitext").observe("keypress", wikiKey);
	    $("wikitext").observe("keyup", wikiChange);
	    $("wikitext").observe("click", wikiResize);
	}
});

function searchFocus() { 
    if ($("searchbox")==null) return; 
    
    if ($("searchbox").value=="search...") { 
	$("searchbox").style.color="#333";
	$("searchbox").value="";
    }
}
function searchLost() { 
    if ($("searchbox")==null) return; 
    
    if ($("searchbox").value=="") { 
	$("searchbox").style.color="#aaa";
	$("searchbox").value="search...";
    }
}

var timer=null;
var wikiwordstart=null;
var wikiwordlen=null;

var suggestionSelected=-1; 

function wikiKey(e) { 
	if (e.keyCode==Event.KEY_TAB && e.shiftKey) { 
	
		e.stop();

		results=$("wikisuggestions"); 
		if (results) {
			results=results.getElementsBySelector("li");
			suggestionSelected++;
			if (suggestionSelected>=results.length) 
				suggestionSelected=-1;
			
			for (i=0; i<results.length; i++) { 
				if (i==suggestionSelected)
					results[i].style.fontWeight="bold";
				else
					results[i].style.fontWeight="normal";
			}
		}

	}

	if (suggestionSelected!=-1 && e.keyCode==Event.KEY_RETURN) {
		results=$("wikisuggestions").getElementsBySelector("li");
		insertText(null, results[suggestionSelected]);
		suggestionSelected=-1;		
		e.stop();
	}
}

function wikiChange(e) { 
	wikiResize();

	if (e.keyCode==Event.KEY_TAB && e.shiftKey) return ; 
	if (suggestionSelected!=-1 && e.keyCode==Event.KEY_RETURN) return ; 

	if (timer!=null) { 
		clearTimeout(timer);
	}
	$("wikiindicator").display="none";
		
	timer=setTimeout( function () { 
   	   timer=null;
	   t=$("wikitext");
	   cursor=t.selectionStart;
	   current=t.value.substr(0,cursor);
	   if (current.match(/\w$/)) { 
		   wikiwordstart=current.search(/\w*$/); 
		   wikiwordend=cursor;
		   word=current.substr(wikiwordstart);
		   
		   $("wikiindicator").style.display="inline";	
		   new Ajax.Updater("wikisuggestions", "/sys/thingsautocomplete", 
							{ parameters: { query: word, limit: 5 }, 
							  onComplete: showWikiSuggestions
							});

	   } }, 1200 ); 
}



function showWikiSuggestions() {
	$("wikiindicator").style.display="none";
	$("wikisuggestions").style.display="inline"; 

	suggestionSelected=-1;

	results=$("wikisuggestions").getElementsBySelector("li");
	for (i=0; i<results.length; i++) { 
		e=results[i];
		e.style.cursor="pointer";
		e.observe("click", insertText);
	}
}

function insertText(e, word) { 
	if (!word) word=this;
	w=$("wikitext");

	o=w.value;

	text=word.collectTextNodes()

	w.value=o.substr(0,wikiwordstart)+text+o.substr(wikiwordend);
	$("wikisuggestions").style.display="none";
	w.focus();
	w.setSelectionRange(wikiwordstart+text.length,wikiwordstart+text.length);
}




var defaultWikiRows=5; 
var maxWikiRows=50;

function wikiResize(event){
    var t = $('wikitext');
    var lines = t.value.split('\n');
    var newRows = lines.length + 1;
    var oldRows = t.rows;
    for (var i = 0; i < lines.length; i++)
    {
        var line = lines[i];
        if (line.length >= t.cols) newRows += Math.floor(line.length / t.cols);
    }
    if (newRows > t.rows) t.rows = Math.min(newRows, maxWikiRows);
    if (newRows < t.rows) t.rows = Math.max(defaultWikiRows, Math.min(newRows, maxWikiRows));
}





// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode( plaintext )
{
  // The Javascript escape and unescape functions do not correspond
  // with what browsers actually do...
  var SAFECHARS = "0123456789" +					// Numeric
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
    "abcdefghijklmnopqrstuvwxyz" +
    "-_.!~*'()";					// RFC2396 Mark characters
  var HEX = "0123456789ABCDEF";

  var encoded = "";
  for (var i = 0; i < plaintext.length; i++ ) {
    var ch = plaintext.charAt(i);
    if (ch == " ") {
      encoded += "+";				// x-www-urlencoded, rather than %20
    } else if (SAFECHARS.indexOf(ch) != -1) {
      encoded += ch;
    } else {
      var charCode = ch.charCodeAt(0);
      if (charCode > 255) {
	alert( "Unicode Character '" 
	       + ch 
	       + "' cannot be encoded using standard URL encoding.\n" +
	       "(URL encoding only supports 8-bit characters.)\n" +
	       "A space (+) will be substituted." );
	encoded += "+";
      } else {
	encoded += "%";
	encoded += HEX.charAt((charCode >> 4) & 0xF);
	encoded += HEX.charAt(charCode & 0xF);
      }
    }
  } // for

  return encoded;
};

function URLDecode( encoded )
{
  // Replace + with ' '
  // Replace %xx with equivalent character
  // Put [ERROR] in output if %xx is invalid.
  var HEXCHARS = "0123456789ABCDEFabcdef"; 

  var plaintext = "";
  var i = 0;
  while (i < encoded.length) {
    var ch = encoded.charAt(i);
    if (ch == "+") {
      plaintext += " ";
      i++;
    } else if (ch == "%") {
      if (i < (encoded.length-2) 
	  && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
	  && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
	plaintext += unescape( encoded.substr(i,3) );
	i += 3;
      } else {
	alert( 'Bad escape combination near ...' + encoded.substr(i) );
	plaintext += "%[ERROR]";
	i++;
      }
    } else {
      plaintext += ch;
      i++;
    }
  } // while
  return plaintext;
};


