
/* See json.org for detail */
if (!Object.prototype.toJSONString) {
  Array.prototype.toJSONString = function () {
    var a = ['['],
        b,
        i,
        l = this.length,
        v;

    function p(s) {
      if (b) {
        a.push(',');
      }
      a.push(s);
      b = true;
    }

    for (i = 0; i < l; i += 1) {
      v = this[i];
      switch (typeof v) {
      case 'object':
        if (v) {
          if (typeof v.toJSONString === 'function') {
	    p(v.toJSONString());
	  }
	} else {
	  p("null");
	}
	break;
      case 'string':
      case 'number':
      case 'boolean':
	p(v.toJSONString());
      }
    }

    a.push(']');
    return a.join('');
  };

  Boolean.prototype.toJSONString = function () {
    return String(this);
  };

  Date.prototype.toJSONString = function () {
    function f(n) {
      return n < 10 ? '0' + n : n;
    }

    return '"' + this.getFullYear() + '-' +
           f(this.getMonth() + 1) + '-' +
           f(this.getDate()) + 'T' +
           f(this.getHours()) + ':' +
           f(this.getMinutes()) + ':' +
           f(this.getSeconds()) + '"';
  };

  Number.prototype.toJSONString = function () {
    return isFinite(this) ? String(this) : "null";
  };

  Object.prototype.toJSONString = function () {
    var a = ['{'],
        b,
        k,
        v;

    function p(s) {
      if (b) {
        a.push(',');
      }
      a.push(k.toJSONString(), ':', s);
      b = true;
    }

    for (k in this) {
      if (this.hasOwnProperty(k)) {
	v = this[k];
	switch (typeof v) {
	case 'object':
	  if (v) {
	    if (typeof v.toJSONString === 'function') {
	      p(v.toJSONString());
	    }
	  } else {
	    p("null");
	  }
	  break;

	case 'string':
	case 'number':
	case 'boolean':
	  p(v.toJSONString());
	}
      }
    }

    a.push('}');
    return a.join('');
  };

  (function (s) {
    var m = {
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\f': '\\f',
      '\r': '\\r',
      '"' : '\\"',
      '\\': '\\\\'
    };

    s.parseJSON = function (filter) {
      var j;

      function walk(k, v) {
	var i;
	if (v && typeof v === 'object') {
	  for (i in v) {
	    if (v.hasOwnProperty(i)) {
	      v[i] = walk(i, v[i]);
	    }
	  }
	}
	return filter(k, v);
      }

      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) {
        try {
          j = eval('(' + this + ')');
        } catch (e) {
          throw new SyntaxError("parseJSON");
        }
      } else {
        throw new SyntaxError("parseJSON");
      }

      if (typeof filter === 'function') {
        j = walk('', j);
      }
      return j;
    };

    s.toJSONString = function () {

      if (/["\\\x00-\x1f]/.test(this)) {
        return '"' + this.replace(/([\x00-\x1f\\"])/g, function (a, b) {
          var c = m[b];
          if (c) {
            return c;
          }
          c = b.charCodeAt();
          return '\\u00' +
            Math.floor(c / 16).toString(16) +
            (c % 16).toString(16);
          }) + '"';
      }
      return '"' + this + '"';
    };
  })(String.prototype);
}
/* See quirksmode.com for more */
function sendDexRequest(url, callback, postData) {
  var req = createXMLHTTPObject();
  if (!req) {
    return;
  }
  var method = (postData) ? "POST" : "GET";
  req.open(method, url, true);
  req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');

  if (postData) {
    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  }

  req.onreadystatechange = function () {
    if (req.readyState != 4) {
      return;
    }

    if (req.status != 200 && req.status != 304) {
      // alert('HTTP error ' + req.status);
      return;
    }

    if (callback != null) {
      callback(req);
    }
  }

  if (req.readyState == 4) {
    return;
  }
  req.send(postData);
}

var XMLHttpFactories = [
  function () {return new XMLHttpRequest()},
  function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
  var xmlhttp = false;
  for (var i = 0; i < XMLHttpFactories.length; i++) {
    try {
      xmlhttp = XMLHttpFactories[i]();
    } catch (e) {
      continue;
    }

    break;
  }
  return xmlhttp;
}

function readElementString(element) {
  if ("innerText" in element) {
    return element.innerText;
  } else if ("textContent" in element) {
    return element.textContent;
  }

  return null;
}

function writeElementString(element, string) {
  if ("innerText" in element) {
    element.innerText = string;
  } else if ("textContent" in element) {
    element.textContent = string;
  }
}

function showSignIn(oldBoxId, signInBoxId) {
  setElementDisplay(oldBoxId, "none");
  setElementDisplay(signInBoxId, "block");
  return false; // cancel the page turn
}

function setElementDisplay(elementId, displayStyle) {
  var theElement = document.getElementById(elementId);
  if (theElement) {
    theElement.style.display = displayStyle;
  }
}

function showElement(elementId) { setElementDisplay(elementId, 'block'); }
function hideElement(elementId) { setElementDisplay(elementId, 'none'); }

function setElementImage(elementId, imageName) {
  var theElement = document.getElementById(elementId);
  if (theElement) {
    theElement.style.background = "transparent images/" + imageName;
  }
}

function showMessageCenterPanel(newPanelID) {
  var elementIDList = ['mc_private', 'mc_friends', 'mc_ignores'];
  for (var i in elementIDList) {
    var elementID = document.getElementById(elementIDList[i]);
    var elementIDContent = document.getElementById(elementIDList[i] + "_content");
    if (elementID && elementIDContent) {
      if (newPanelID == elementIDList[i]) {
        elementID.className = 'active';
        elementIDContent.style.display = 'block';
      } else {
        elementID.className = '';
        elementIDContent.style.display = 'none';
      }
    }
  }
}

function toggleNotepadDisplay() {
  var notepadContent = document.getElementById('notepad-content');
  var notepadHeader = document.getElementById('notepad-header');
  if (notepadContent && notepadContent.style.display != "block") {
    notepadContent.style.display = "block";
    if (notepadHeader) {
      notepadHeader.style.backgroundImage = "url(/static/style/images/arrow-down.png)";
    }
  } else {
    notepadContent.style.display = "none";
    if (notepadHeader) {
      notepadHeader.style.backgroundImage = "url(/static/style/images/arrow-right.png)";
    }
  }
}

function enableNotepadSave() {
  document.getElementById('notepad-action-button').disabled = false;
  writeElementString(document.getElementById('notepad-save-result'), '');
}

function saveNotepad() {
  var notepadButton = document.getElementById('notepad-action-button');
  var notepadData = document.getElementById('notepad-data');
  var notepadPostbackElement = document.getElementById('notepad-postback');
  if (notepadButton && notepadData && notepadPostbackElement) {
    notepadButton.disabled = true;
    notepadData.disabled = true;
    notepadButton.value = 'Saving...';

    // Get the postback URL
    var notepadPostbackURL = readElementString(notepadPostbackElement);
    var newNotepadText = notepadData.value;

    if (notepadPostbackURL != null && newNotepadText != null) {
      sendDexRequest(notepadPostbackURL, notepadDataSaveHandler, newNotepadText);
    }
  }
}

function notepadDataSaveHandler(req) {
  var notepadButton = document.getElementById('notepad-action-button');
  var notepadData = document.getElementById('notepad-data');
  var resultOutput = document.getElementById('notepad-save-result');
  if (notepadButton && notepadData && resultOutput) {
    // Was the save successful?  Tell user so they know if data was saved
    var responseText = req.responseText;
    var responseJSON = responseText.parseJSON();
    var outputText = responseJSON.resultString;
    if (responseJSON.resultCode != 0) {
      outputText = 'Error: ' + outputText;
    }
    writeElementString(resultOutput, outputText);

    notepadData.disabled = false;
    notepadButton.value = 'Save';
  }
}

function toggleMessageCenterDisplay() {
  var allMessages = document.getElementById('all-messages');
  var messageHeader = document.getElementById('message-center');
  if (allMessages && allMessages.style.display != "block") {
    allMessages.style.display = "block";
    if (messageHeader) {
      messageHeader.style.backgroundImage = "url(/static/style/images/arrow-down.png)";
    }

    // Showing for the first time?  If so mark all messages as read
    var postbackURLElement = document.getElementById('message-center-read-message-postback');
    var postbackURL = readElementString(postbackURLElement);

    if (postbackURL != null && postbackURL.indexOf('http') == 0) {
      writeElementString(postbackURLElement, 'sent');
      sendDexRequest(postbackURL, PMMessagesRead, null);
    }
  } else {
    allMessages.style.display = "none";
    if (messageHeader) {
      messageHeader.style.backgroundImage = "url(/static/style/images/arrow-right.png)";
    }
  }
}

function PMMessagesRead(req) {
  // Clear the astrick from after the 'my portfolio' link
  starElement = document.getElementById('newpmstar');
  if (starElement != null) {
    writeElementString(starElement, '');
  }
}

function toggleFilterCenterDisplay() {
  var allFilters = document.getElementById('all-filters');
  var filterHeader = document.getElementById('filter-center');
  if (allFilters && allFilters.style.display != "block") {
    allFilters.style.display = "block";
    if (filterHeader) {
      filterHeader.style.backgroundImage = "url(/static/style/images/arrow-down.png)";
    }
  } else {
    allFilters.style.display = "none";
    if (filterHeader) {
      filterHeader.style.backgroundImage = "url(/static/style/images/arrow-right.png)";
    }
  }
}

function toggleTranslateDisplay() {
  var allTranslations = document.getElementById('translate-content');
  var translateHeader = document.getElementById('translate-header');
  if (allTranslations && allTranslations.style.display != "block") {
    allTranslations.style.display = "block";
    if (translateHeader) {
      translateHeader.style.backgroundImage = "url(/static/style/images/arrow-down.png)";
    }
  } else {
    allTranslations.style.display = "none";
    if (translateHeader) {
      translateHeader.style.backgroundImage = "url(/static/style/images/arrow-right.png)";
    }
  }
}

function updateFilterPref(newTab) {
  var filterCheckbox = document.getElementById('filtercheck');
  if (filterCheckbox != null) {

    // Are we setting a new value or forgetting an old one?
    if (filterCheckbox.checked == false) {
      newTab = 'default';
    }

    var dexURLElement = document.getElementById('update-filter-postback');
    var dexURL = readElementString(dexURLElement);

    if (dexURL != null) {
      sendDexRequest(dexURL + newTab, null, null);
    }
  }
}

function dummyRequestHandler(req) {
  alert("Request returned!");
}
