function inithttp() {
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    var xmlhttp = new XMLHttpRequest();
    return xmlhttp;
  // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    return xmlhttp;
  }
}

function changecomp(compid,compelem,newtype,includeopt) {
  var xmlhttp = inithttp();
  xmlhttp.onreadystatechange=function () {
    changecompcontent(xmlhttp,compid,compelem);
  }
  if (!includeopt) includeopt = '';
  xmlhttp.open("GET", '/obikicomp/config/'+compid+'/'+newtype+'/'+includeopt,true);
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
}

function changecompcontent(xmlhttp,compid,compelem) {
  var compdiv = document.getElementById(compelem);
  if (xmlhttp.readyState == 4) {
    compdiv.innerHTML = xmlhttp.responseText;
  }
}

function addcomp(docid,type) {
  var xmlhttp = inithttp();
  xmlhttp.onreadystatechange=function () {
    addcompdiv(xmlhttp);
  }
  if (!type) type = '';
  xmlhttp.open("GET", '/obikicomp/add/'+docid+'/'+type,true);
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
}

function addcompdiv(xmlhttp) {
  if (xmlhttp.readyState == 4) {
    var components = document.getElementById("components");
    var newcomp = document.createElement("div");
    var newcompid = xmlhttp.responseText;
    newcomp.id = "comp_" + newcompid;
    components.appendChild(newcomp);
    changecomp(newcompid, "comp_"+newcompid, 'static', 'withopt');
  } 
}

function deletecomp(compid) {
  var xmlhttp = inithttp();
  xmlhttp.open("GET", '/obikicomp/delete/'+compid,true);
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
  var compdiv = document.getElementById('comp_' + compid);
  compdiv.parentNode.removeChild(compdiv);
}

function getchildren(docid,node,alink,id,fieldname,selected) {
  var childul = document.getElementById('obiki_doc_'+docid+'_children_'+id);
  var loadingul = document.getElementById('obiki_doc_'+docid+'_loading_'+id);
  if (childul || loadingul) {
    node.removeChild(childul);
    alink.innerHTML = '[+]';
  } else {
    var xmlhttp = inithttp();
    xmlhttp.onreadystatechange=function () {
      addchildul(xmlhttp,docid,node,id);
    }
    var uri = "/obikixml/children/"+docid+"/"+id;
    if (fieldname != null) {
      uri = uri+"/"+fieldname;
      if (selected != null) {
        uri = uri+"/"+selected;
      }
    }
    xmlhttp.open("GET", uri,true);
    xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
    xmlhttp.send(null);
    alink.innerHTML = '[-]';
    node.innerHTML = node.innerHTML + '<ul id="obiki_doc_'+docid+'_loading_'+id+'"><i>Loading...</i></ul>';
  }
}

function addchildul(xmlhttp,docid,node,id) {
  if (xmlhttp.readyState == 4) {
    var loadingul = document.getElementById('obiki_doc_'+docid+'_loading_'+id);
    if (loadingul) {
      node.removeChild(loadingul);
    }
    node.innerHTML = node.innerHTML + '<ul id="obiki_doc_' + docid + '_children_'+id+'">' + xmlhttp.responseText + '</ul>';
  }
}

function addchild(parentid,doctitle,id) {
  var xmlhttp = inithttp();
  var node = document.getElementById('obiki_doc_'+parentid+'_children_'+id);
  xmlhttp.onreadystatechange=function () {
    newchildli(xmlhttp,parentid,node);
  }
  xmlhttp.open("GET", "/obikixml/addchild/"+parentid+"/"+doctitle.value,true);
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
}

function newchildli(xmlhttp,parentid,childul) {
  if (xmlhttp.readyState == 4) {
    childul.innerHTML = childul.innerHTML + xmlhttp.responseText;
  }
} 

function checkuser(email) {
  var xmlhttp = inithttp();
  var node = document.getElementById('new_person_form');
  xmlhttp.onreadystatechange=function () {
    checkuserresult(xmlhttp,email,node);
  }
  xmlhttp.open("GET", "/obikixml/checkuser/"+email,true);
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
}

function checkuserresult(xmlhttp, email, node) {
  if (xmlhttp.readyState == 4) {
    if (xmlhttp.responseText == 0) {
      window.location = "/admin/people/new/?email="+email;
    } else {
      node.innerHTML = xmlhttp.responseText;
    }
  }
}

function getVocabOptions(node, vocab, controlall) {
  var xmlhttp = inithttp();
  xmlhttp.onreadystatechange=function () {
    getVocabOptionsResult(xmlhttp, node);
  }
  if(controlall) {
    xmlhttp.open("GET", "/obikixml/vocabselect/"+node+"/"+vocab+"?control_all=1", true);
  } else {
    xmlhttp.open("GET", "/obikixml/vocabselect/"+node+"/"+vocab, true);
  }
  xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
  xmlhttp.send(null);
}

function getVocabOptionsResult(xmlhttp, node) {
  if (xmlhttp.readyState == 4) {
    document.getElementById(node + "_options").innerHTML = xmlhttp.responseText;
  }
}

function popUp(url, name, width, height, features) {
  if (!features) features = "toolbar=0,menubar=0,status=0,location=0,directories=0,scrollbars=0";
  if (!width) width= "450";
  if (!height) height= "200";
  features = "width="+width+",height="+height+","+features;
  var theWin = window.open (url, name, features);
  if (theWin) theWin.focus();
}

function emptyField(field,orig) {
  if (field.emptied != true) {
    field.value = ""
    field.emptied = true  
  }
  return field
}

// The following function is taken from: 
// http://kalsey.com/2004/07/dirify_in_php/#comment-2143

function dirify(str) { 
  str = str.toLowerCase();
  var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
              /[\xC8-\xCA]/g, /[\xE8-\xEB]/g, 
              /[\xCC-\xCE]/g, /[\xEC-\xEE]/g, 
              /[\xD2-\xD4]/g, /[\xF2-\xF4]/g, 
              /[\xD9-\xDB]/g, /[\xF9-\xFB]/g 
            ];
  var repChar=['A','a','E','e','I','i','O','o','U','u'];

  for(var i=0; i < rExps.length; i++) {
    str = str.replace(rExps[i],repChar[i]);
  }
  str = str.replace( /\W+/g, '_' );
  str = str.replace( /[_-]+/g, '_' );
  str = str.replace( /^-/, '');
  str = str.replace( /-$/, '');
  return str;
}

// Set desired tab- defaults to four space softtab
var tab = "    ";

function checkTab(evt) {
  var t = evt.target;
  var ss = t.selectionStart;
  var se = t.selectionEnd;

  // Tab key - insert tab expansion
  if (evt.keyCode == 9) {
      evt.preventDefault();
      
      // Special case of multi line selection
      if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) {
          // In case selection was not of entire lines (e.g. selection begins in the middle of a line)
          // we ought to tab at the beginning as well as at the start of every following line.
          var pre = t.value.slice(0,ss);
          var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+tab);
          var post = t.value.slice(se,t.value.length);
          t.value = pre.concat(tab).concat(sel).concat(post);
          
          t.selectionStart = ss + tab.length;
          t.selectionEnd = se + tab.length;
      }
      
      // "Normal" case (no selection or selection on one line only)
      else {
          t.value = 
t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length));
          if (ss == se) {
              t.selectionStart = t.selectionEnd = ss + tab.length;
          }
          else {
              t.selectionStart = ss + tab.length;
              t.selectionEnd = se + tab.length;
          }
      }
  }
  
  // Backspace key - delete preceding tab expansion, if exists
  else if (evt.keyCode==8 && t.value.slice(ss - 4,ss) == tab) {
      evt.preventDefault();
      
      t.value = t.value.slice(0,ss - 
4).concat(t.value.slice(ss,t.value.length));
      t.selectionStart = t.selectionEnd = ss - tab.length;
  }
  
  // Delete key - delete following tab expansion, if exists
  else if (evt.keyCode==46 && t.value.slice(se,se + 4) == tab) {
      evt.preventDefault();
      
      t.value = t.value.slice(0,ss).concat(t.value.slice(ss + 
4,t.value.length));
      t.selectionStart = t.selectionEnd = ss;
  }
  
  // Left/right arrow keys - move across the tab in one go
  else if (evt.keyCode == 37 && t.value.slice(ss - 4,ss) == tab) {
      evt.preventDefault();
      t.selectionStart = t.selectionEnd = ss - 4;
  }
  else if (evt.keyCode == 39 && t.value.slice(ss,ss + 4) == tab) {
      evt.preventDefault();
      t.selectionStart = t.selectionEnd = ss + 4;
  }
  
}

function delAttachment(elm) {
  matches = elm.id.match(/attachment_(\d+)/);
  new Ajax.Request('/obikixml/upload/delete.html?at=' + matches[1], {method: 'post'});
  elm.parentNode.removeChild(elm);
}

function toggleFeatureMenu(elm) {
  var menu = $('add_feature_menu');
  if (Element.visible(menu)) {
    new Effect.SlideUp(menu);
  } else {
    Position.clone(elm, menu, {
      setHeight: false,
      setWidth: false,
      offsetTop: elm.offsetHeight
    });
    new Effect.SlideDown(menu);
  }
}

function showProgress(msg) {
  try {
    Dialog.info(msg, {
      windowParameters: {
        className: "alphacube", 
        width: 200, 
        height: 75 
      }, 
      showProgress: true
    });
  } catch (e) {};
  return true;
}

function hideProgress() {
  Dialog.closeInfo();
}


function showConfig(dc, type) {
  return Dialog.confirm($('config_' + dc).innerHTML, {
          windowParameters: {className:"alphacube", width:600, maxHeight:400},
          okLabel: "Save", cancelLabel: "Cancel",
          ok: function(win) {
            showProgress('Updating display...'); 
            new Ajax.Request('/obikixml/edit/compsubmit/' + dc, { 
              parameters: Form.serialize($('comp_edit_' + dc)),
              asynchronous: 1, 
              onComplete: function(request){
                updateComponent(dc, type)} } );
            return true;
          }
  });
}

function updateComponent(dc, type) {
  var tiny_inst = tinyMCE.selectedInstance;
  var old_elm = tinyMCE.getElementByAttributeValue(
      tiny_inst.contentDocument.body, 
      "div", 
      "id", 
      'comp_display_' + dc);
  tinyMCE.execCommand('mceSelectNode', false, old_elm);
  new Ajax.Request('/obikixml/edit/loaddisplay.html?inner=1&dc=' + dc, { 
    method: 'get', 
    onSuccess: function(t) {
      old_elm.innerHTML = t.responseText;
      hideProgress();
    }
  });
  new Ajax.Updater('comp_edit_' + dc, '/obikixml/edit/loadform.html?inner=1&dc=' + dc, {method: 'get'});
}

function addComponent(doc, type) {
   var dc_id;
   showProgress('Adding Element...');
   new Ajax.Request("/obikixml/edit/compadd/" + doc + '/' + curPlaceholder(), {
          method: 'post',
          postBody: 'type=' + type,
          onSuccess: function(t) {
            results = t.responseText.match(/id="comp_display_(\d+)"/)
            dc_id = results[1];
            tinyMCE.execCommand('mceInsertContent',false, t.responseText);
      
           new Ajax.Request("/obikixml/edit/loadform.html?dc=" + dc_id, {
            method: 'get',
            onSuccess: function(t2) {
              new Insertion.Bottom($('component_forms'), t2.responseText);
              hideProgress();
              showConfig(dc_id, type);
            }
          });
        }
    });
}

function delComponent(dc) {
  if (!confirm("Are you sure you want to remove this?")) {
    return false;;
  }
  var tiny_inst = tinyMCE.selectedInstance;
  var old_elm = tinyMCE.getElementByAttributeValue(
      tiny_inst.contentDocument.body, 
      "div", 
      "id", 
      'comp_display_' + dc);
  if (tinyMCE.isMSIE) {
    old_elm.outerHTML = '';
  } else {
    var rng = old_elm.ownerDocument.createRange();
    rng.setStartBefore(old_elm);
    rng.setEndAfter(old_elm);
    rng.deleteContents();
  }
  tinyMCE.triggerNodeChange();
  new Ajax.Request("/obikixml/edit/compdel/" + dc, {method: 'post'});
}

function curPlaceholder() {
  return $('selected_placeholder').value;
}

function changeTab(node) {
  node = $(node);
  var ul = node.up().up();
  var ontab = (ul.getElementsByClassName('on'))[0];
  if (node.up().id == 'secondary_form_tab') {
    $('wysiwyg_wrapper').hide();
    $('secondary_form').show();
  } else {
    $('wysiwyg_wrapper').show();
    if ($('secondary_form')) {
      $('secondary_form').hide();
    }
    storeContent(curPlaceholder());
    matches = node.up().id.match(/^tab-(.*)$/);
    $('selected_placeholder').value = matches[1];
    tinyMCE.setContent($('placeholder-content-' + matches[1]).value);
  }
  Element.toggle(ontab.getElementsByTagName('span')[0]);
  Element.toggle(ontab.getElementsByTagName('a')[0]);
  Element.removeClassName(ontab, 'on');
  Element.toggle(node);
  Element.toggle(node.up().getElementsByTagName('span')[0]);
  Element.addClassName(node.up(), 'on');
}

function storeContent(placeholder) {
  $('placeholder-content-' + placeholder).value = tinyMCE.getContent();
} 

function toggleRestrictedAccess(elm) {
  if ($F(elm) == 0) {
    $('restricted_options').show();
    var views = $('restricted_options').getElementsByClassName('view-checkbox');
    for (var i = 0; i < views.length; i++) {
      views[i].disabled = false;
    }
    $('public_warning').hide();
  } else {
    var views = $('restricted_options').getElementsByClassName('view-checkbox');
    for (var i = 0; i < views.length; i++) {
      views[i].disabled = 'disabled';
      views[i].checked = 'checked';
    }
    $('public_warning').show();
    new Effect.Highlight('public_warning', {duration: 3});
  }
}

function addEntity(elm) {
  $('add_auth_entity').value = '';
  new Insertion.Bottom('auth_table', 
'<tr>'
+ '<td>' + elm.innerHTML + '</td>'
+ '<td><input type="checkbox" name="auth_' + elm.id + '" value="view" checked="checked" class="view-checkbox" '
+ ($F('page_public') == 1 ? 'disabled="disabled"' : '') + ' /></td>'
+ '<td><input type="checkbox" name="auth_' + elm.id + '" value="edit" /></td>'
+ '<td><input type="checkbox" name="auth_' + elm.id + '" value="add" /></td>'
+ '</tr>'
);
  new Effect.Highlight('auth_table', {duration: 1.5});
}

// vim: ft=javascript ts=2 sw=2 et cin
