/* Copyright (C) 2010-2011, David Earl. All rights reserved. */

/* Copyright (C) 2010-2011, David Earl. All rights reserved. */

var trblock = 'table-row';

function myload() {
  if (this.viewload) { this.viewload(); }
  // ...
}

// --------------------
function loadjson(url, response, always) {
  var req;
  if (window.XMLHttpRequest) { req=new XMLHttpRequest(); } // Mozilla etc
  else if (window.ActiveXObject) { req=new ActiveXObject("Microsoft.XMLHTTP"); } // older IE
  if (req != null) {
    waiting(true);
    req.onreadystatechange = function() {
      if(req.readyState == 4) {
	waiting(false); 
	var internalerror = false;
	if(req.status == 200) {
	    var ch0 = req.responseText.substring(0,1);
	  if (ch0 == '{' || ch0 == '[') { 
	      response(window.JSON ? JSON.parse(req.responseText) : eval("("+req.responseText+")"));
	      return;
	  }
	  if (always) { return { unknown: req.responseText }; }
	  alert("Problem retrieving data: internal error or possible javascript error"); 
	  return;
	}
	if(req.status == 500) { 
	  alert("Internal error, sorry: administrator has been notified about the bug"); 
	} else if (req.status != 0) {
	    if (req.responseText.match(/<span class='oops'>/)) {
		alert("Internal error, sorry. Server said: " + req.responseText.replace(/<br[^>]*>/g, "\n").replace(/<[^>]*>/g, " "));
	    } else {
		alert("Problem retrieving data: has you internet connecton gone down? Server crashed?\n\n(The message we got was: HTTP error "+req.status+": "+req.statusText+")");
	    }
	}
      }
    };
    req.open("GET",url,true);
    req.send(null);
  } else {
    alert("You are not using a suitable browser");
  }
}

// --------------------
function waiting(on) {
  var i;
  var body = document.getElementsByTagName("body")[0];
  var cursor = on ? 'wait' : 'default';
  body.style.cursor = cursor;
  var as = document.getElementsByTagName("a");
  cursor = on ? 'wait' : 'pointer';
  for (i = 0; i < as.length; i++) {
    as[i].style.cursor = cursor;
  }
  var handle = $("wishlistsliderinput_handle");
  if(handle) {
    cursor = on ? 'wait' : 'pointer';
    handle.style.cursor = cursor;
  }
}

// --------------------
function insertbr(text) {
  // ignore leading and trailing newlines
  while (text.length > 0 && text.charAt(text.length-1) == "\n") {
    text = text.substr(0, text.length-1);
  }
  while (text.length > 0 && text.charAt(0) == "\n") {
    text = text.substr(1, text.length-1);
  }
  text = htmlspecialchars(text);
  return text.replace(/\n/g, "<span class='newline'><br /></span>");
}

// --------------------
function windowWidth() {
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    return (window.innerWidth);
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return (document.documentElement.clientWidth);
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return (document.body.clientWidth);
  }
}
// --------------------
function windowHeight() {
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    return (window.innerHeight);
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return (document.documentElement.clientHeight);
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return (document.body.clientHeight);
  }
}
// --------------------
function absTop (o) {
    var curtop = curtop = 0;
    if (o.offsetParent) {
	curtop = o.offsetTop;
	o = o.offsetParent;
	while (o) {
	  curtop += o.offsetTop;
	  o = o.offsetParent;
      }
  }
  return curtop;
}
// --------------------
function absLeft(o) {
    var curleft = curleft = 0;
    if (o.offsetParent) {
	curleft = o.offsetLeft;
	var o = o.offsetParent;
	while (o) {
	  curleft += o.offsetLeft;
	  o = o.offsetParent;
      }
  }
  return curleft;
}
// --------------------
function mouseX(e) {
    var posx = 0;
    if (!e) var e = window.event;
    if (e.touches && e.touches[0]) {
	posx = event.touches[0].pageX;
    } else if (e.pageX || e.pageY) {
	posx = e.pageX;
    } else if (e.clientX || e.clientY) 	{
	posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    }
    return posx;
}
// --------------------
function mouseY(e) {
    var posy = 0;
    if (!e) var e = window.event;
    if (e.touches && e.touches[0]) {
	posy = event.touches[0].pageY;
    } else if (e.pageX || e.pageY) 	{
	posy = e.pageY;
    } else if (e.clientX || e.clientY) 	{
	posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    return posy;
}

// --------------------
function scrollY() {
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    return window.pageYOffset;
  } else if( document.body && document.body.scrollTop) {
    //DOM compliant
    return document.body.scrollTop;
  } else if( document.documentElement && document.documentElement.scrollTop) {
    //IE6 standards compliant mode
    return document.documentElement.scrollTop;
  }
  return 0;
}

// --------------------
function scrollX() {
  if( typeof( window.pageXOffset ) == 'number' ) {
    //Netscape compliant
    return window.pageXOffset;
  } else if( document.body && document.body.scrollLeft) {
    //DOM compliant
    return document.body.scrollLeft;
  } else if( document.documentElement && document.documentElement.scrollLeft) {
    //IE6 standards compliant mode
    return document.documentElement.scrollLeft;
  }
  return 0;
}

// --------------------
function dopopup(url) {
  var width = screen.width/2; 
  var height = screen.height*8/10;
  var x = screen.width/4; 
  var y = screen.height/10;
  var w = window.open(url, "twpopup", "width="+width+",height="+height+",left="+x+",top="+y+",menubar=no,resizable=yes,status=no,toolbar=no,scrollbars=yes");
  w.opener = self;
  if (window.focus) { w.focus(); }
}

// --------------------
function getFirstElementByClassName(obj, nodeName, className) {
    var objs = obj.getElementsByTagName(nodeName);
    for (var i = 0; i < objs.length; i++) {
	var split = objs[i].className.split(" ");
	for (var j = 0; j < split.length; j++) {
	    if (split[j] == className) { return objs[i]; }
	}
    }
    return null;
}

// --------------------
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

// -----
function $(id) { 
    /* getElementsById */
    return document.getElementById(id); 
}
function el(nodeName, className /* optional */, id /* optional */) { 
    /* createElement */
    var e =  document.createElement(nodeName.toUpperCase()); 
    if (className) { e.className = className; }
    if (id) { e.id = id; }
    return e;
}
function eld(className, id) { return el("div", className, id); }
function eli(className, id, src, alttitle) { 
    var img = el("img", className, id);
    if (src) { img.src = src; }
    if (alttitle) { img.alt = img.title = alttitle; }
    return img;
}
function tx(eid, text) { 
    /* append text to container eid */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    e.appendChild(document.createTextNode(text)); 
    return e; 
}
function ht(eid, html) { 
    /* apply html to eid */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    e.innerHTML = html; 
    return e; 
}
function clr(eid) { return ht(eid, ""); }
function ap(peid, eid) { 
    /* appendChild on peid (parent object or object id) */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    var p = typeof(peid) == "string" ? $(peid) : peid;
    p.appendChild(e); 
    return p;
}
function att(eid, attributename, attributevalue) {
    /* getAttribute on eid, or setAttribute if given */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    if (typeof(attributevalue) == "undefined") { return e.getAttribute(attributename); }
    e.setAttribute(attributename, attributevalue);
    return e;
}
function vis(eid) {
    /* return displayed */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    return e.style.display && e.style.display != "none";
}
function vb(eid, vis) {
    /* change display for block object according to boolean vis */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    e.style.display = vis ? "block" : "none";
    return e;
}
function vi(eid, vis) {
    /* change display for inline object according to boolean vis */
    var e = typeof(eid) == "string" ? $(eid) : eid;
    e.style.display = vis ? "inline" : "none";
    return e;
}
function sty(eid, style) {
    var e = typeof(eid) == "string" ? $(eid) : eid;
    for (var s in style) { e.style[s] = style[s]; }
    return e;
}
// -----
function cl(e, oc) { /* click-able */
    e.onmouseover = function() { sty(this, {cursor:"pointer"}); };
    e.onmouseout =  function() { sty(this, {cursor: "default"}); };
    e.onclick = oc;
    return e;
}


// --------------------
function h(s) { // htmlspecialchars
  return s.replace(/&/g,"&amp;").replace(/'/g, "&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");
}

// --------------------
function eu(s) { //urlencode
  return encodeURIComponent(s).replace(/\\+/,"%20");
}

// --------------------
function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/'/g, "%27").replace(/"/g, "%22");
}

// -----
function e_act(action, id, args, f_callback, always /* return the result even if not json */) {
    var alwaysreturn = ! always ? false : true;
    if (window.ok_ct) { if (! ok_ct()) { return; } }
    var url = "doaction.json?action=" + urlencode(action) +"&id=" + id;
    if (args) { 
	for (var key in args) { url += "&" + key + "=" + urlencode(args[key]); } 
    }
    loadjson(url, 
	     function(j) {
		 if (window.menu_clear) { menu_clear(); }
		 if (j.error) { 
		     alert(j.error); 
		     return; 
		 }
		 if (f_callback) { 
		     f_callback(j); 
		 }
	     }, alwaysreturn);
}
/* Copyright (C) 2010-2011, David Earl. All rights reserved. */
var e_form_result = null;

// -----
function e_form(formname, id, args, f_ok, f_cancel) {
    if (formname != "comment_warning" && formname != "undermined_version" && ! ok_ct()) { return; }
    var form = $("ens_form");
    var formbody = frames["ens_form"].document.getElementsByTagName("BODY")[0];
    if (formbody) { ht(formbody, "<p>please wait...</p>"); }

    var url = "getform.php?form=" + urlencode(formname);
    if (typeof(id) == "number") { url += "&id=" + id; }
    if (args) { for (var key in args) { url += "&" + key + "=" + urlencode(args[key]); } }

    e_form_result = {};
    if (f_ok || f_cancel) { e_form_result = { "id": id, "args": args }; }
    e_form_result["f_ok"] = f_ok ? f_ok : null;
    e_form_result["f_cancel"] = f_cancel ? f_cancel : null;

    var w = typeof(window["ef_ordinary_width"]) != "undefined" ? window["ef_ordinary_width"] : 600;
    var h = parseInt(windowHeight() * 0.85);
    att(vb(sty(form, 
	       {"position" : "absolute",
		"zOrder" : 100,
		"width" : w + "px",
		"height" : h + "px",
		"top" : (parseInt((windowHeight() - h) * .75) + scrollY()) + "px",
		"left" : (parseInt((windowWidth() - w) / 2) + scrollX()) + "px" 
	       }), true), "src", url);
    vb("ens_help", false);
    var preview = $("ens_preview");
    var height = absTop(preview)+preview.offsetHeight;
    if (windowHeight() > height) { height = windowHeight(); }
    vb(sty("ens_grayed", {"height": height+"px"}), true);
    menu_clear();
}

// -----
function form_hide(fn) {
    vb("ens_form" + (fn ? "_"+fn : ""), false);
    vb("ens_grayed", false);
}

// -----
function form_result(fn, ok, acknowledge, j) {
    if (! ok || ! acknowledge) { form_hide(fn); }
    if (! e_form_result) { return; }
    var cb = ok ? e_form_result.f_ok : e_form_result.f_cancel;
    if (! cb) { return; }
    if (e_form_result.id) { j.id = e_form_result.id; }
    if (e_form_result.args) { 
	for (var key in e_form_result.args) { j[key] = e_form_result.args[key]; }
    }
    if (acknowledge) { j["acknowledge"] = true; }
    cb(j);
}

// -----
function do_help(help, subject) {
    if (! subject) { subject = ""; }
    var form = $("ens_help");
    var formbody = frames["ens_help"].document.getElementsByTagName("BODY")[0];
    if (formbody) { ap(clr(formbody), tx(el("p"), "please wait...")); }

    var url = "help/" + urlencode(help == "" ? subject : (subject == "" ? help : help+"_"+subject));
    /* shift any visible form out of the way */
    sty("ens_form", {"left": "20px"});
    att(vb(sty("ens_help", {"position" : "absolute",
		    "zOrder" : 1001,
		    "left" : (windowWidth() - 390 + scrollX()) + "px",
		    "top" : (10 + scrollY()) + "px",
		    "height" : (windowHeight() - 30) + "px"}),
	    true), "src", url);
    menu_clear();
}

var e_p = null;
var ensformnumber = 1;

function ep_load(id, name) {
    clr(vb("ens_preview", false));
    vb("ens_intro", false);
    vb("ens_pagenumbers", false);
    loadjson("getpublish.json?id="+id+"&name="+name, j_load);
}

// --------------------
function j_load(j) {
  e_p = j;
  if (e_p.direction == "in") {
      r_about();
      req_upload(e_p.project_id,e_p.name);
  } else if (e_p.passcode_required) {
      req_passcode(e_p.project_id,e_p.name);
  } else {
      r_title_info();
      r_f();
  }
}

// --------------------
function r_about() {
    var html = "\
<h1>Ensembling: upload, store, mark-up, comment, review and publish</h1>\
<p>Ensembling is about collaborative working to assemble and review the material that makes up a publication, whether as simple as a letter or as complex as a book or magazine. With it you can:</p>\
<ul>\
  <li>store, manage, review and retrieve the multiple versions of files that will eventually be combined in a finished publication</li>\
<li>collaboratively mark-up and collate comments on the content</li>\
<li>watch and be notified about other people&rsquo;s changes and comments</li>\
<li>make finished files available to third-parties</li>\
</ul>\
\
<p><strong>For a trial project:</strong> log in <a href='https://www.ensembling.com' target='_blank'>here</a></p>\
\
<p><strong>Contact</strong> <a href='mailto:admin@ensembling.com'>admin@ensembling.com</a></p>\
<h1><a class='linked' href='https://www.ensembling.com/help/introduction' target='_blank'>Tell me more&hellip;</a></h1>";
    ap("ensembling", ht(sty(eld(null, "ensl_intro"), 
			    {position: "absolute", top: "70px", right: "35px", 
				    width: "25%", border: "1px solid black", padding: "5px 0 0 0"}), 
			html));
}

// --------------------
function r_title_info() {
    var id = e_p.project_id;
    r_about();
    var div = sty(eld('ec_lefttitle'), {width: "70%"});
    if (e_p.logo != "") {
	ap(div, sty(eli(null, null, e_p.logo, ''), {float: "right", maxheight: "100px", padding: "5px"}));
    }
    ap(div, eli("ec_icon", null, "folder.png", "folder"));
    ap(div, tx(el("span", "ec_name"), e_p.name));
    ap(div, tx(el("span", "ec_category"), " public"));
    ap(div, tx(el("span", "ec_type"), " folder"));
    ap("ens_document_folder_headline", div);
  
    if (e_p.info != "") {
	ht("ens_intro_text", h(e_p.info).replace(/\n/g, "<br />"));
	vb("ens_menu", false);
	vb(sty("ens_intro", { width: "70%", margin: "10px 0 0 0"}), true);
    }
}

// --------------------
function render_menuentry(caption, hint, action /* escape single quotes */, 
			  privilegeneeded, obj /* for which privilege needed */, hid)
{
    var my_icons = 0;
    if (obj && (roles[privilegeneeded] & parseInt(obj.getAttribute("grants"))) == 0) { return ""; }
    var hcaption = my_icons == 2 ? "" : "&nbsp;" + h(caption).replace(/ /g, "&nbsp;") + "&nbsp;";
    var captionnsp = h(caption).replace(/ /, "").replace(/&.*;/, "");
    if (! hid) { hid = captionnsp; }
    var png = action.replace(/^do_/, "").replace(/\(.*/, "");
    var alt = my_icons == 2 ? "["+caption+"] "+hint : "";
    var icon = my_icons == 0 ? "" : "<img class='ec_menuicon' src='ops/"+png+".png' alt='"+alt+"' title='"+alt+"' "+" />";
    var style= my_icons == 0 ? "style='position: relative; top: 3px;'": "";
    hid = "ensmenuentry_" + hid;
    return "<div class='ec_menuentry' onmouseover='javascript: this.style.borderColor=\"#444444\"; this.style.cursor=\"pointer\";' onmouseout='javascript: this.style.borderColor=\"#ababab\";  this.style.cursor=\"default\";' id='"+hid+"' + title='"+h(hint)+"' onclick='"+action+"'>"+icon+"<span class='ec_menu_caption' "+style+">"+hcaption+"</span></div>\n";
}

// -----
function r_m_e(container, caption, hint, action /* function */, name)
{
    var m = eld("ec_menuentry", "ens_menuentry_"+name);
    ap(m, ht(sty(eld("ec_menu_caption"), {position:"relative", top:"3px", padding: "0 4px 0 6px"}), 
	     h(caption).replace(/ /g, "&nbsp;") + "&nbsp;"));
    m.onmouseover = function() { sty(m, {borderColor:"#444444", cursor:"pointer"}); }
    m.onmouseout = function() { sty(m, {borderColor:"#ababab", cursor:"default"}); }
    m.onclick = action;
    m.alt = m.title = h(hint);
    ap(container, m);
    return container;
}

// --------------------
function r_f() {
    loadjson("getchildren.json?id="+e_p.project_id+"&version=1", 
	     function(j) 
    {

	var div = eld('ens_howto');
	if (j.length > 1) {
	    ht(div, "&bull; <strong>click on an item's name or thumbnail to download it to your computer</strong><br />or to download a zip file containing multiple items:<br />&bull; click 'download all', or<br />&bull; choose items to download by ticking/checking the boxes and click 'download selected':<br /><br />");

	    r_m_e(div, "download all", "download all items", 
		  function() { do_download_all(); }, "download_all");
	    r_m_e(div, "select all", "select all documents for downloading", 
		  function() { do_select_all(); }, "select_all");
	    r_m_e(div, "clear all", "clear all documents for downloading", 
		  function() { do_clear_all(); }, "clear_all");
	    r_m_e(div, "download selected", "download all selected items", 
		  function() { do_download_selected(); }, "download_selected");
	} else {
	    ht(div, "&bull; <strong>click on the item's name or thumbnail to download it to your computer.</strong>");
	}
	ap(div, sty(eld(), {clear: "both"}));
	vb(ap("ens_menu", div), true);

	var table = el("table", "ec_folderlisting", "ens_folder_listing");
	if (j.length == 0) {
	    tx(table.insertRow(0).insertCell(0), "empty");
	} else {
	    for (var i = 0; i < j.length; i++) {
		var it = j[i];
		if (! it.version) { continue; }
		var v = it.version;
		var tr = sty(table.insertRow(i), {marginBottom: "10px"});
		if (j.length > 1) {
		    ap(tr.insertCell(0), att(el("input", "ec_cb_download", "download_"+it.id), 
					     "type", "checkbox"));
		}
		var tn = att(eli(v.thumb ? "ec_thumb" : "ec_icon", "thumb_"+it.id,
				 v.thumb ? it.id + "/thumb" : it.type + ".png",
				 it.type), "item_id", it.id);
		tn.onmouseover = function() { this.style.cursor="pointer"; }
		tn.onmouseout = function() { this.style.cursor="default"; }
		tn.onclick = function() { do_download(parseInt(att(this, "item_id"))); }
		ap(att(tr.insertCell(j.length > 1 ? 1 : 0), "class", "ec_folder_thumb"), tn);

		var td = tr.insertCell(j.length > 1 ? 2 : 1);

		var a = tx(att(el("a"), "item_id", it.id), it.name);
		a.href = "javascript:void(0)";
		a.onclick = function() { do_download(parseInt(att(this, "item_id"))); }
		ap(td, ap(el("span", "ec_name"), a));

		ap(ap(td, el("br")),
		   ap(el("span", "ec_version_meta"), 
		      sty(eli(null, null, "mime/"+v.suffix+".png", v.name), 
			  {position: "relative", top: "4px"})));
		var span = ap(tx(el("span", "ec_author"), " "+v.description+" file"), el("br"));
		tx(ap(tx(span, v.addedon), el("br")), v.size);
		if (v.wc && v.wc > 99) {
		    tx(ap(span, el("br")), v.wc+" words");
		}
		ap(td, span);
	    }
	}

	var pc65 = {width: "65%"};
	sty("ens_menu", pc65);
	vb(sty(ap("ens_listing", table), pc65), true);
	sty("ens_intro", pc65);
	vb(clr("ens_commentary"), false);
	vb("ens_preview", false);
    });
}

// --------------------
function change_checkboxes(checked) {
    var table = $("ens_folder_listing");
    if (! table) { return; }
    var inputs = table.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].className == "ec_cb_download") {
	    inputs[i].checked = checked;
	}
    }
}

// --------------------
function do_select_all() { change_checkboxes(true); }

// --------------------
function do_clear_all() { change_checkboxes(false); }

// --------------------
function do_download(id) { window.location.href = "download.php?id="+id; }

function do_download_all() { e_form("download_all", e_p.project_id, {"state": "start"}); }

// --------------------
function do_download_selected(id) {
    var table = $("ens_folder_listing");
    if (! table) { return; }
    var inputs = table.getElementsByTagName("input");
    var separator = '';
    var download_ids = new Array;
    var is = 0;
    for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].className == "ec_cb_download" && inputs[i].checked) {
	    download_ids[is++] = inputs[i].id.replace(/download_/, "");
	}
    }
    if (download_ids.length == 0) { return; }
    var items = download_ids.join(",");
    e_form("download_all", e_p.project_id, {"state": "start", "items": items});
}

// --------------------
function req_passcode(project_id, name) { 
    e_form("public_passcode", project_id, {name: name}, 
	   function(j) { ep_load(j.id, j.name); }); 
}

// --------------------
function req_upload(project_id, name) { 
    e_form("public_upload", project_id, {name: name}); 
    sty("ens_form", {left: "20px"});
}

// -----
function ok_ct() { return true; }
function menu_clear() { }

