/* Globals */
var agt=navigator.userAgent.toLowerCase(); // convert all characters to lowercase to simplify testing
var is_gecko = (agt.indexOf('gecko') != -1); // Check for Gecko engine


/*
 * name - name of the cookie
 * value - value of the cookie
 * [path] - path for which the cookie is valid
 *   (defaults to path of calling document)
 * [expires] - expiration date of the cookie
 *   (defaults to end of current session)
 * [domain] - domain for which the cookie is valid
 *   (defaults to domain of calling document)
 * [secure] - Boolean value indicating if the cookie transmission requires
 *   a secure transmission
 *  an argument defaults when it is assigned null as a placeholder
 *  a null placeholder is not required for trailing omitted arguments
 */
function setCookie(name, value, path, expires, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((path) ? "; path=" + path : "") +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

/*
 * name - name of the desired cookie
 * return string containing value of specified cookie or null
 *  if cookie does not exist
 */
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else {
    begin += 2;
  }

  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
    end = dc.length;
  }

  return unescape(dc.substring(begin + prefix.length, end));
}

/*
 * name - name of the cookie
 * [path] - path of the cookie (must be same as path used to create cookie)
 * [domain] - domain of the cookie (must be same as domain used to
 *   create cookie)
 * path and domain default if assigned null or omitted if no explicit
 *   argument proceeds
 */
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

/*
 * date - any instance of the Date object
 * hand all instances of the Date object to this function for "repairs"
 */
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}


/**
 * Add a function to an event as a 'listener' callback
 */
function hookEvent(hookName, hookFunct) {
  if (window.addEventListener) {
    addEventListener(hookName, hookFunct, false);
  }
  else if (window.attachEvent) {
    attachEvent("on" + hookName, hookFunct);
  }
}


/*
 * Show the effect of the toggle value
 */
function setToggleDisplay(toggler, target, display) {
  /* The icon was inserted as first child */
  var state_fb = toggler.childNodes[0];

  if (display) {
    state_fb.setAttribute('src', '/static/toggle_minus.png');
    target.style.display = '';
  }
  else {
    state_fb.setAttribute('src', '/static/toggle_plus.png');
    target.style.display = 'none';
  }
}

/*
 * Toggles display of an element name for all pages
 */
function toggleDisplayGlobal(toggler, target) {
  expire = new Date();
  expire.setTime(expire.getTime() + 1000 * 2592000); /* This gives 30 days */

  /* If the current display is enabled */
  if (target.style.display == '') {
    setToggleDisplay(toggler, target, false);
    setCookie(target.id, false, '/', expire);
  }
  else {
    setToggleDisplay(toggler, target, true);
    setCookie(target.id, true, '/', expire);
  }
}

/*
 * Reads the cookie (if it exists) and sets the element's display property
 */
function addGlobalToggler(toggler_id, target_id, default_disp) {
  var toggler = document.getElementById(toggler_id);
  if (!toggler) return false;
  var target = document.getElementById(target_id);
  if (!target) return false;

  /* Prepare the image */
  var state_fb = document.createElement('img');
  state_fb.setAttribute('width', 12);
  state_fb.setAttribute('height', 12);
  state_fb.setAttribute('class', 'toggler_icon');

  /* Insert the image, prepending to the existing elements */
  toggler.insertBefore(state_fb, toggler.childNodes[0]);

  /* Set script action on whole object */
  toggler.style.cursor = 'pointer';
  toggler.onclick = function() {
    toggleDisplayGlobal(toggler, target);
    return false;
  }

  /* Initialize elements */
  var disp = getCookie(target.id);
  if (typeof(disp) == 'string') {
    disp = (disp == 'true');
  }
  else {
    disp = default_disp;
  }
  setToggleDisplay(toggler, target, disp);
  return true;
}


/** Buttons used for editing WikiNodes */
var edit_buttons = [];

/**
 * This function adds edit toolbar buttons to a list of possible buttons
 */
function addEditButton(image_file, speed_tip, tag_open, tag_close, sample_text) {
  edit_buttons[edit_buttons.length] = {
    'image_file': image_file,
    'speed_tip': speed_tip,
    'tag_open': tag_open,
    'tag_close': tag_close,
    'sample_text': sample_text
  };
}

/**
 * This function generates the actual toolbar buttons
 * This avoids creating the toolbar where javascript is not enabled
 */
function insertEditButton(parent, textbox, item) {
  var image = document.createElement('img');
  image.setAttribute('width', 23);
  image.setAttribute('height', 22);
  image.setAttribute('src', item.image_file);
  image.setAttribute('alt', item.speed_tip);
  image.setAttribute('title', item.speed_tip);
  image.style.cursor = 'pointer';
  image.onclick = function() {
    insertTags(textbox, item.tag_open, item.tag_close, item.sample_text);
    return false;
  }

  parent.appendChild(image);
  return true;
}

function setupEditToolbar(toolbar_id, textbox_id) {
  var toolbar = document.getElementById(toolbar_id);
  if (!toolbar) return false;

  var textbox = document.getElementById(textbox_id);
  if (!textbox) return false;

  // Don't generate buttons for browsers which don't fully support it.
  if (!document.selection && textbox.selectionStart == null)
    return false;

  for (var i in edit_buttons) {
    insertEditButton(toolbar, textbox, edit_buttons[i]);
  }

  return true;
}

/**
 * Apply tag_open/tag_close to selection in textarea.
 * Use sample_text instead of selection if there is none.
 */
function insertTags(textbox, tag_open, tag_close, sample_text) {
  // Internet Explorer
  if (document.selection && !is_gecko) {
    var theSelection = document.selection.createRange().text;
    if (!theSelection) {
      theSelection = sample_text;
    }
    textbox.focus();

    // Exclude ending space char, if any
    if (theSelection.charAt(theSelection.length - 1) == ' ') {
      theSelection = theSelection.substring(0, theSelection.length - 1);
      document.selection.createRange().text = tag_open + theSelection + tag_close + ' ';
    } else {
      document.selection.createRange().text = tag_open + theSelection + tag_close;
    }

  // Mozilla
  } else if (textbox.selectionStart || textbox.selectionStart == '0') {
    var startPos = textbox.selectionStart;
    var endPos = textbox.selectionEnd;
    var scrollTop = textbox.scrollTop;
    var myText = (textbox.value).substring(startPos, endPos);
    var replaced = false;
    if (endPos - startPos) {
      replaced = true;
    }

    if (!myText) {
      myText = sample_text;
    }

    // Exclude ending space char, if any
    if (myText.charAt(myText.length - 1) == ' ') {
      subst = tag_open + myText.substring(0, (myText.length - 1)) + tag_close + ' ';
    } else {
      subst = tag_open + myText + tag_close;
    }
    textbox.value = textbox.value.substring(0, startPos) + subst + textbox.value.substring(endPos, textbox.value.length);
    textbox.focus();

    //set new selection
    if (replaced) {
      var cPos = startPos + (tag_open.length + myText.length + tag_close.length);
      textbox.selectionStart = cPos;
      textbox.selectionEnd = cPos;
    } else {
      textbox.selectionStart = startPos + tag_open.length;
      textbox.selectionEnd = startPos + tag_open.length + myText.length;
    }
    textbox.scrollTop = scrollTop;

  // All other browsers get no toolbar.
  }
  // reposition cursor if possible
  if (textbox.createTextRange) {
    textbox.caretPos = document.selection.createRange().duplicate();
  }
}
