///////////////////////
// General Functions //
///////////////////////

function getHTTPRequest () {
  var httpRequest= false;

  if (window.XMLHttpRequest) {
    httpRequest= new XMLHttpRequest ();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) {
    try {
      httpRequest= new ActiveXObject ("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        httpRequest= new ActiveXObject ("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!httpRequest) {
    alert ("AJAX error: cannot create XMLHTTP instance");
    return false;
  }

  return httpRequest;
}

function writePreview (httpRequest, contentBlock) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      contentBlock.innerHTML= httpRequest.responseText;
    } else {
      alert ("There was a problem with the request, could not write preview");
    }
  }
}

// Determines whether the enter key was pressed
function enterPressed (event) {
  return ((event.keyCode && event.keyCode == 13) || (event.which && event.which == 13));
}

// Gets a processed content preview
function getPreview (content, tagId, long, special) {
  long= typeof (long) != 'undefined' ? long : true;
  special= typeof (special) != 'undefined' ? special : "";

  var contentBlock= document.getElementById (tagId);
  var parameters= "content=" + encodeURIComponent (content) + "&type=" + (long ? "l" : "s") + "&special=" + special;

  var httpRequest= getHTTPRequest ();

  if (httpRequest) {
    httpRequest.onreadystatechange= function () { writePreview (httpRequest, contentBlock); };
    httpRequest.open ("POST", document.homePage + "ajax/?m=get_preview", true);
    httpRequest.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader ("Content-length", parameters.length);
    httpRequest.setRequestHeader ("Connection", "close");
    httpRequest.send (parameters);
  }
}

// Gives the user a prompt for text and puts it in a tag
function createTag (fieldId, tagName) {
  var field= document.getElementById (fieldId);

  var promptText= "Enter the tag text";

  var fillOption= true; // Set true for options that get set when highlighted (as opposed to content)

  switch (tagName) {
  case "font_color":
    var before= '[font color="';
    var after= '"][/font]';
    fillOption= false;
    break;
  case "font_type":
    var before= '[font type="';
    var after= '"][/font]';
    fillOption= false;
    break;
  case "font_size":
    var before= '[font size="';
    var after= '"][/font]';
    fillOption= false;
    break;
  case "url":
    var before= '[link url="';
    var after= '"][/link]';
    break;
  default:
    var before= "["+tagName+"]";
    var after= "[/"+tagName+"]";
  }

  InsertTagAroundCursor (field, before, after, fillOption);

  return void (0);
}

// Inserts a block of text at the current cursor position within an input block
function insertAtCursor(block, insertText) {
  if (document.selection) {
    // IE support
    block.focus();
    sel= document.selection.createRange();
    sel.text= insertText;
  } else if (block.selectionStart || block.selectionStart == "0") {
    // Firefox support
    var startPos= block.selectionStart;
    var endPos= block.selectionEnd;
    block.value= block.value.substring (0, startPos) + insertText + block.value.substring (endPos, block.value.length);
  } else {
    // If all else fails, just put it at the end
    block.value+= insertText;
  }
}

// Inserts blocks of text before and after the current cursor position within an input block
function InsertTagAroundCursor(block, beforeText, afterText, fillOption) {
  // For [tag param="|"][/tag] usage on highlighting
  // Put the cursor inside the tag if the param is filled
  var postAdjust= 0;
  if (beforeText.substring (beforeText.length - 1) != "]") {
    postAdjust= afterText.indexOf ("]") + 1;
  }

  var cursor= getCursorPosition (block);

  if (document.selection) {
    // IE support
    block.focus();
    range= document.selection.createRange ();
    priorTextLength= range.text.length;

    if (!fillOption && range.text.length > 0) {
      beforeText+= afterText.substring (0, postAdjust);
      afterText= afterText.substring (postAdjust, afterText.length);
      postAdjust= -postAdjust - range.text.length;
    }

    // If the selected text starts and ends with these tags, remove them instead of adding them
    if (range.text.substring (0, beforeText.length) == beforeText && range.text.substring (range.text.length - afterText.length) == afterText) {
      range.text= range.text.substring (beforeText.length, range.text.length - afterText.length);
      return true;
    }

    var tempRange= document.selection.createRange ();
    tempRange.moveStart ("character", -beforeText.length);
    tempRange.moveEnd ("character", afterText.length);

    // If the selected text is wrapped with these tags, remove them instead of adding them
    if (tempRange.text.substring (0, beforeText.length) == beforeText && tempRange.text.substring (tempRange.text.length - afterText.length) == afterText) {
      tempRange.text= tempRange.text.substring (beforeText.length, tempRange.text.length - afterText.length);
      return true;
    } else if (range.text.length == 0 && tempRange.text.substring (tempRange.text.length - afterText.length) == afterText && beforeText.substring (beforeText.length - 1, beforeText.length) == "]" && afterText.substring (0, 1) == "[") {
      // If you're at the end of a tag, but there is content before the cursor, "end" the tag by moving past it
      range.move ("character", afterText.length);
      range.select ();
      return true;
    }

    range.text= beforeText + range.text + afterText;

    // If nothing was highlighted, put the cursor between the added blocks
    if (priorTextLength == 0) {
      range.move ('character', -1 * afterText.length);
      range.select ();
    } else if (postAdjust != 0) {
      range.move ('character', -1 * afterText.length + postAdjust);
      range.select ();
    }

    return true;
  } else if (block.selectionStart || block.selectionStart == "0") {
    // Firefox support
    var startPos= block.selectionStart;
    var endPos= block.selectionEnd;
    var selectionSize= endPos - startPos;

    if (!fillOption && selectionSize > 0) {
      beforeText+= afterText.substring (0, postAdjust);
      afterText= afterText.substring (postAdjust, afterText.length);
      postAdjust= -postAdjust - selectionSize;
    }

    if (block.value.substring (startPos, startPos + beforeText.length) == beforeText && block.value.substring (endPos - afterText.length, endPos) == afterText) {
      // If the selected text starts and ends with these tags, remove them instead of adding them
      block.value= block.value.substring (0, startPos) + block.value.substring (startPos + beforeText.length, endPos - afterText.length) + block.value.substring (endPos);
      selectionSize-= (beforeText.length + afterText.length);

      setHighlight (block, cursor, cursor + selectionSize);
      return true;
    } else if (block.value.substring (startPos - beforeText.length, startPos) == beforeText && block.value.substring (endPos, endPos + afterText.length) == afterText) {
      // If the selected text is already wrapped in these tags, remove them as well
      block.value= block.value.substring (0, startPos - beforeText.length) + block.value.substring (startPos, endPos) + block.value.substring (endPos + afterText.length);

      cursor-= beforeText.length;
      setHighlight (block, cursor, cursor + selectionSize);
      return true;
    } else if (selectionSize == 0 && block.value.substring (endPos, endPos + afterText.length) == afterText && beforeText.substring (beforeText.length - 1, beforeText.length) == "]" && afterText.substring (0, 1) == "[") {
      // If you're at the end of a tag, but there is content before the cursor, "end" the tag by moving past it
      setCursorPosition (block, cursor + afterText.length);
      return true;
    } else {
      block.value= block.value.substring (0, startPos) + beforeText + (startPos != endPos ? block.value.substring (startPos, endPos) : "") + afterText + block.value.substring (endPos, block.value.length);
    }

    // If nothing was highlighted, put the cursor between the added blocks
    if (selectionSize == 0) {
      setCursorPosition (block, cursor + beforeText.length);
    } else if (postAdjust != 0) {
      setCursorPosition (block, cursor + beforeText.length + selectionSize + postAdjust);
    } else {
      setHighlight (block, cursor, cursor + selectionSize + beforeText.length + afterText.length);
    }

    return true;
  } else {
    // If all else fails, just put it at the end
    block.value+= beforeText + afterText;

    return false;
  }
}

// Highlights text in an input block from character position start to position end
function setHighlight (block, start, end) {
  if (block.setSelectionRange) {
    block.setSelectionRange (start, end);
    block.focus ();
  } else if (block.createTextRange) {
    var range= block.createTextRange ();
    range.collapse (true);
    range.moveEnd ('character', end);
    range.moveStart ('character', start);
    range.select ();
  }
}

// Sets the cursor position of the specified input block
function setCursorPosition (block, position) {
  setHighlight (block, position, position);
}

// Finds the cursor position of the specified input block (only in Firefox)
function getCursorPosition (block) {
  if (block.selectionStart || block.selectionStart == "0") {
    return block.selectionStart;
  } else {
    block.focus ();
    var range= document.selection.createRange ();
    range.moveStart ('character', -block.value.length);
    return range.text.length;
  }
}

// Allows users to press Ctrl-B or Ctrl-I to insert tags
function checkTagPress (evt, fieldId, long) {
  long= typeof (long) != 'undefined' ? long : true;

  evt= (evt) ? evt : window.event;

  if (!evt.ctrlKey) return true;

  switch (String.fromCharCode (evt.keyCode).toLowerCase ()) {
    case "b":
      createTag (fieldId, "b");
      break;
    case "e":
      createTag (fieldId, "edit");
      break;
    case "i":
      createTag (fieldId, "i");
      break;
    case "l":
      createTag (fieldId, "url");
      break;
    default:
      return true;
    }

    evt.cancelBubble= true;
    evt.returnValue= false;

    if (evt.stopPropagation) {
      evt.stopPropagation ();
      evt.preventDefault ();
    }

    return false;
}

function refreshPreview (fieldId) {
  if (fieldId == "page_content") {
    var content= document.getElementById ("page_content").value;

    getPreview (content, "content_preview");
    getPreview (document.getElementById ("page_title").value, "title_preview", false);

    document.getElementById ("page_preview").style.display= "block";
  }

  return void (0);
}

//////////////////////
// Paging Functions //
//////////////////////

function sort (sortBy, defDir) {
  if (sortBy == document.filters["s"]) {
    defDir= document.filters["d"] == 'a' ? 'd' : 'a';
  }
  var link= document.link + "&s=" + sortBy + "&d=" + defDir;

  for (var i in document.filters) {
    if (i == "s" || i == "d") continue;
    link+= "&" + i + "=" + document.filters[i];
  }

  document.location= link;
}

function showPage (pageNum) {
  var link= document.link + "&p=" + pageNum;

  for (var i in document.filters) {
    if (i == "p") continue;
    link+= "&" + i + "=" + document.filters[i];
  }

  document.location= link;
}

function checkNum (field, min, max) {
  if (isNaN (field.value) || field.value == "") {
    field.value= "";
  } else if (field.value < min) {
    field.value= min;
  } else if (field.value > max) {
    field.value= max;
  } else {
    field.value= Math.round (field.value);
  }
}

function swapStatSort (num) {
  var link= document.link + "&s=" + document.filters["f"+num] + "&f" + num + "=" + document.filters["s"];

  for (var i in document.filters) {
    if (i == "s" || i == ("f"+num)) continue;
    link+= "&" + i + "=" + document.filters[i];
  }

  document.location= link;
}

///////////////////////////
// File Upload Functions //
///////////////////////////

function uploadFile (fieldId, type) {
  document.imageWindow= window.open ("/index.php?m=upload&t=" + type + "&field=" + fieldId, "image_upload", "width=640,height=200");
}

// Puts a file or image tag in the text
function insertFileTag (fieldId, tagType, value) {
  var field= document.getElementById (fieldId);

  InsertTagAroundCursor (field, "[" + tagType + "=\""+value+"\"]", "", false);

  return void (0);
}
