var contextPath = '/jira';// Variables used as maps to store the original text and html of some fields whose values get replaced by
// renderer previews.
var origHtml = new Object();
var origText = new Object();
var origPreviewLink = new Object();

/*
 * Used to submit and restore a renderer preview. This relies of the DWR library and the generated
 * RendererPreviewAjaxUtil.js bean, which performs the server-side access.
 */
function toggleRenderPreview(fieldId, fieldName, rendererType, issueKey)
{
    if(origHtml[fieldId] == null)
    {
        // this is a hack for Safari/dwr since safari does not seem to generate an XMLHTTPRequest correctly see JRA-8354
        if(encodeURI(document.getElementById(fieldId).value).length > 2500 && navigator.userAgent.indexOf('Safari') >= 0)
        {
          // first open the new window
          window.open('', 'wiki_renderer_preview', 'width=780, height=575, resizable, scrollbars=yes');

          // then form submit to the window, we have to form submit because the error we are trying to get around
          // is the max size limit for a GET param value
          var previewForm = document.createElement('form');
          previewForm.action = '/jira/secure/WikiRendererPreviewAction.jspa?rendererType='+ rendererType + '&issueKey=' + issueKey + '&fieldName='+ encodeURI(fieldName);
          previewForm.method = 'POST';
          previewForm.target = 'wiki_renderer_preview';
          var unrenderedMarkup = document.createElement('input');
          unrenderedMarkup.name = 'unrenderedMarkup';
          unrenderedMarkup.type = 'hidden';
          unrenderedMarkup.value= document.getElementById(fieldId).value;
          previewForm.appendChild(unrenderedMarkup);

          var bodys = document.getElementsByTagName('BODY');
          bodys[0].appendChild(previewForm);
          previewForm.submit();
        }
        else
        {
          showWaitImage(true, fieldId);
          RendererPreviewAjaxUtil.getPreviewHtml(rendererType, document.getElementById(fieldId).value, issueKey, renderPreviewCallback(fieldId));
        }
    }
    else
    {
        var scrollSaver = document.createElement("div");
        scrollSaver.innerHTML = "&nbsp;";
        scrollSaver.setAttribute("style", "height: " + "300px");
        document.getElementById(fieldId + "-edit").parentNode.insertBefore(scrollSaver, document.getElementById(fieldId + "-edit"));
        
        document.getElementById(fieldId + "-temp").name = fieldId + "-temp";
        // clear the height before we reset
        xHeight(fieldId + "-edit", null);
        document.getElementById(fieldId + "-edit").innerHTML = origHtml[fieldId];
        document.getElementById(fieldId).value = origText[fieldId];
        origHtml[fieldId] = null;
        document.getElementById(fieldId + "-edit").className = "";
        document.getElementById(fieldId + "-preview_link").innerHTML = "<img alt='"+ "preview" +"' title='" + "preview" +"' class='unselectedPreview' border='0' width='18' height='18' src='/jira/images/icons/fullscreen.gif'>";
        
        scrollSaver.parentNode.removeChild(scrollSaver);
    }
    return false;
}

/*
* This is the call-back function for the AJAX call to the RendererPreviewAjaxUtil getPreviewHtml call. This
* function replaces the input with the renderered content.
*/
var renderPreviewCallback = function(fieldId)
{
    return function(data)
    {
        var scrollSaver = document.createElement("div");
        scrollSaver.innerHTML = "&nbsp;";
        scrollSaver.setAttribute("style", "height: " + "300px");
        document.getElementById(fieldId + "-edit").parentNode.insertBefore(scrollSaver, document.getElementById(fieldId + "-edit"));
        
        var origHeight = xHeight(fieldId + "-edit", null);
        origHtml[fieldId] = document.getElementById(fieldId + "-edit").innerHTML;
        origText[fieldId] = document.getElementById(fieldId).value;
        document.getElementById(fieldId + "-temp").value = origText[fieldId];
        document.getElementById(fieldId + "-temp").name = fieldId;
        showWaitImage(false, fieldId );
        document.getElementById(fieldId + "-preview_link").innerHTML = "<img alt='"+ "edit' title='" + "edit" + "' class='selectedPreview' width='18' height='18' src='/jira/images/icons/fullscreen.gif'>";
        document.getElementById(fieldId + "-edit").className = "previewClass";
        document.getElementById(fieldId + "-edit").innerHTML = data;
        var newHeight = xHeight(fieldId + "-edit", null);
        if(newHeight < origHeight)
        {
           xHeight(fieldId + "-edit", origHeight);
        }
        
        scrollSaver.parentNode.removeChild(scrollSaver);
    }
}

function showWaitImage(flag, fieldId)
{
    var waitImageHtml = "<img id='" + fieldId + "-wait_image' alt='Wait Image' border='0' src='/jira/images/icons/wait.gif'>";
    if(flag)
    {
      origPreviewLink[fieldId] = document.getElementById(fieldId + "-preview_link_div").innerHTML;
      document.getElementById(fieldId + "-preview_link_div").innerHTML = waitImageHtml;
    }
    else
    {
      document.getElementById(fieldId +  "-preview_link_div").innerHTML = origPreviewLink[fieldId];
      origPreviewLink[fieldId] = null;
    }
}

// xHeight, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xHeight(e,h)
{
  if(!(e=xGetElementById(e))) return 0;
  if (xNum(h)) {
    if (h<0) h = 0;
    else h=Math.round(h);
  }
  else h=-1;
  var css=xDef(e.style);
  if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    h = xClientHeight();
  }
  else if(css && xDef(e.offsetHeight) && xStr(e.style.height)) {
    if(h>=0) {
      var pt=0,pb=0,bt=0,bb=0;
      if (document.compatMode=='CSS1Compat') {
        var gcs = xGetComputedStyle;
        pt=gcs(e,'padding-top',1);
        if (pt !== null) {
          pb=gcs(e,'padding-bottom',1);
          bt=gcs(e,'border-top-width',1);
          bb=gcs(e,'border-bottom-width',1);
        }
        // Should we try this as a last resort?
        // At this point getComputedStyle and currentStyle do not exist.
        else if(xDef(e.offsetHeight,e.style.height)){
          e.style.height=h+'px';
          pt=e.offsetHeight-h;
        }
      }
      h-=(pt+pb+bt+bb);
      if(isNaN(h)||h<0)
      {
        return;
      }
      else
      {
        e.style.height=h+'px';
      }
    }
    else
    {
        e.style.height="";
    }
    h=e.offsetHeight;
  }
  else if(css && xDef(e.style.pixelHeight)) {
    if(h>=0) e.style.pixelHeight=h;
    if(h==-1) e.style.pixelHeight="";
    h=e.style.pixelHeight;
  }
  return h;
}/* x-jira.js compiled from X 4.0 with XC 0.27b. Distributed by GNU LGPL. For copyrights, license, documentation and more visit Cross-Browser.com */
// globals, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

var xOp7Up,xOp6Dn,xIE4Up,xIE4,xIE5,xNN4,xUA=navigator.userAgent.toLowerCase();
if(window.opera){
  var i=xUA.indexOf('opera');
  if(i!=-1){
    var v=parseInt(xUA.charAt(i+6));
    xOp7Up=v>=7;
    xOp6Dn=v<7;
  }
}
else if(navigator.vendor!='KDE' && document.all && xUA.indexOf('msie')!=-1){
  xIE4Up=parseFloat(navigator.appVersion)>=4;
  xIE4=xUA.indexOf('msie 4')!=-1;
  xIE5=xUA.indexOf('msie 5')!=-1;
}
else if(document.layers){xNN4=true;}
xMac=xUA.indexOf('mac')!=-1;
// xAddEventListener, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
                                                      
function xAddEventListener(e,eT,eL,cap)
{
  if(!(e=xGetElementById(e))) return;
  eT=eT.toLowerCase();
  if((!xIE4Up && !xOp7Up) && e==window) {
    if(eT=='resize') { window.xPCW=xClientWidth(); window.xPCH=xClientHeight(); window.xREL=eL; xResizeEvent(); return; }
    if(eT=='scroll') { window.xPSL=xScrollLeft(); window.xPST=xScrollTop(); window.xSEL=eL; xScrollEvent(); return; }
  }
  var eh='e.on'+eT+'=eL';
  if(e.addEventListener) e.addEventListener(eT,eL,cap);
  else if(e.attachEvent) e.attachEvent('on'+eT,eL);
  else eval(eh);
}
// called only from the above
function xResizeEvent()
{
  if (window.xREL) setTimeout('xResizeEvent()', 250);
  var cw = xClientWidth(), ch = xClientHeight();
  if (window.xPCW != cw || window.xPCH != ch) { window.xPCW = cw; window.xPCH = ch; if (window.xREL) window.xREL(); }
}
function xScrollEvent()
{
  if (window.xSEL) setTimeout('xScrollEvent()', 250);
  var sl = xScrollLeft(), st = xScrollTop();
  if (window.xPSL != sl || window.xPST != st) { window.xPSL = sl; window.xPST = st; if (window.xSEL) window.xSEL(); }
}
// xClientHeight, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xClientHeight()
{
  var h=0;
  if(xOp6Dn) h=window.innerHeight;
  else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientHeight)
    h=document.documentElement.clientHeight;
  else if(document.body && document.body.clientHeight)
    h=document.body.clientHeight;
  else if(xDef(window.innerWidth,window.innerHeight,document.width)) {
    h=window.innerHeight;
    if(document.width>window.innerWidth) h-=16;
  }
  return h;
}
// xClientWidth, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xClientWidth()
{
  var w=0;
  if(xOp6Dn) w=window.innerWidth;
  else if(document.compatMode == 'CSS1Compat' && !window.opera && document.documentElement && document.documentElement.clientWidth)
    w=document.documentElement.clientWidth;
  else if(document.body && document.body.clientWidth)
    w=document.body.clientWidth;
  else if(xDef(window.innerWidth,window.innerHeight,document.height)) {
    w=window.innerWidth;
    if(document.height>window.innerHeight) w-=16;
  }
  return w;
}
// xDef, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}
// xEvent, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xEvent(evt) // object prototype
{
  var e = evt || window.event;
  if(!e) return;
  if(e.type) this.type = e.type;
  if(e.target) this.target = e.target;
  else if(e.srcElement) this.target = e.srcElement;

  // Section B
  if (e.relatedTarget) this.relatedTarget = e.relatedTarget;
  else if (e.type == 'mouseover' && e.fromElement) this.relatedTarget = e.fromElement;
  else if (e.type == 'mouseout') this.relatedTarget = e.toElement;
  // End Section B

  if(xOp6Dn) { this.pageX = e.clientX; this.pageY = e.clientY; }
  else if(xDef(e.pageX,e.pageY)) { this.pageX = e.pageX; this.pageY = e.pageY; }
  else if(xDef(e.clientX,e.clientY)) { this.pageX = e.clientX + xScrollLeft(); this.pageY = e.clientY + xScrollTop(); }

  // Section A
  if (xDef(e.offsetX,e.offsetY)) {
    this.offsetX = e.offsetX;
    this.offsetY = e.offsetY;
  }
  else if (xDef(e.layerX,e.layerY)) {
    this.offsetX = e.layerX;
    this.offsetY = e.layerY;
  }
  else {
    this.offsetX = this.pageX - xPageX(this.target);
    this.offsetY = this.pageY - xPageY(this.target);
  }
  // End Section A
  
  if (e.keyCode) { this.keyCode = e.keyCode; } // for moz/fb, if keyCode==0 use which
  else if (xDef(e.which) && e.type.indexOf('key')!=-1) { this.keyCode = e.which; }

  this.shiftKey = e.shiftKey;
  this.ctrlKey = e.ctrlKey;
  this.altKey = e.altKey;
}

//  I need someone with IE/Mac to compare test snippets 1 and 2 in section A.
  
//  // Snippet 1
//  if(xDef(e.offsetX,e.offsetY)) {
//    this.offsetX = e.offsetX;
//    this.offsetY = e.offsetY;
//    if (xIE4Up && xMac) {
//      this.offsetX += xScrollLeft();
//      this.offsetY += xScrollTop();
//    }
//  }
//  else if (xDef(e.layerX,e.layerY)) {
//    this.offsetX = e.layerX;
//    this.offsetY = e.layerY;
//  }
//  else {
//    this.offsetX = this.pageX - xPageX(this.target);
//    this.offsetY = this.pageY - xPageY(this.target);
//  }

//  // Snippet 2
//  if (xDef(e.offsetX,e.offsetY) && !(xIE4Up && xMac)) {
//    this.offsetX = e.offsetX;
//    this.offsetY = e.offsetY;
//  }
//  else if (xDef(e.layerX,e.layerY)) {
//    this.offsetX = e.layerX;
//    this.offsetY = e.layerY;
//  }
//  else {
//    this.offsetX = this.pageX - xPageX(this.target);
//    this.offsetY = this.pageY - xPageY(this.target);
//  }

//  This was in section B:

//  if (e.relatedTarget) this.relatedTarget = e.relatedTarget;
//  else if (xIE4Up) {
//    if (e.type == 'mouseover') this.relatedTarget = e.fromElement;
//    else if (e.type == 'mouseout') this.relatedTarget = e.toElement;
//  }
//  changed to remove sniffer after discussion with Hallvord

// Possible optimization:

//  if (e.keyCode) { this.keyCode = e.keyCode; } // for moz/fb, if keyCode==0 use which
//  else if (xDef(e.which) && e.type.indexOf('key')!=-1) { this.keyCode = e.which; }
//  // replace the above 2 lines with the following?
//  // this.keyCode = e.keyCode || e.which || 0;
// xGetComputedStyle, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetComputedStyle(oEle, sProp, bInt)
{
  var s, p = 'undefined';
  var dv = document.defaultView;
  if(dv && dv.getComputedStyle){
    s = dv.getComputedStyle(oEle,'');
    if (s) p = s.getPropertyValue(sProp);
  }
  else if(oEle.currentStyle) {
    // convert css property name to object property name for IE
    var a = sProp.split('-');
    sProp = a[0];
    for (var i=1; i<a.length; ++i) {
      c = a[i].charAt(0);
      sProp += a[i].replace(c, c.toUpperCase());
    }   
    p = oEle.currentStyle[sProp];
  }
  else return null;
  return bInt ? (parseInt(p) || 0) : p;
}

// xGetElementById, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetElementById(e)
{
  if(typeof(e)!='string') return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}
// xGetElementsByTagName, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xGetElementsByTagName(t,p)
{
  var list = null;
  t = t || '*';
  p = p || document;
  if (xIE4 || xIE5) {
    if (t == '*') list = p.all;
    else list = p.all.tags(t);
  }
  else if (p.getElementsByTagName) list = p.getElementsByTagName(t);
  return list || new Array();
}
// xNum, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xNum()
{
  for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}
  return true;
}
// xPageX, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xPageX(e)
{
  if (!(e=xGetElementById(e))) return 0;
  var x = 0;
  while (e) {
    if (xDef(e.offsetLeft)) x += e.offsetLeft;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }
  return x;
}
// xPageY, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xPageY(e)
{
  if (!(e=xGetElementById(e))) return 0;
  var y = 0;
  while (e) {
    if (xDef(e.offsetTop)) y += e.offsetTop;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }
//  if (xOp7Up) return y - document.body.offsetTop; // v3.14, temporary hack for opera bug 130324 (reported 1nov03)
  return y;
}
// xScrollLeft, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xScrollLeft(e, bWin)
{
  var offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    var w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollLeft) offset=w.document.documentElement.scrollLeft;
    else if(w.document.body && xDef(w.document.body.scrollLeft)) offset=w.document.body.scrollLeft;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollLeft)) offset = e.scrollLeft;
  }
  return offset;
}
// xScrollTop, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xScrollTop(e, bWin)
{
  var offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    var w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;
    else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollTop)) offset = e.scrollTop;
  }
  return offset;
}
// xStr, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xStr(s)
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}
  return true;
}
// xWidth, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

function xWidth(e,w)
{
  if(!(e=xGetElementById(e))) return 0;
  if (xNum(w)) {
    if (w<0) w = 0;
    else w=Math.round(w);
  }
  else w=-1;
  var css=xDef(e.style);
  if (e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    w = xClientWidth();
  }
  else if(css && xDef(e.offsetWidth) && xStr(e.style.width)) {
    if(w>=0) {
      var pl=0,pr=0,bl=0,br=0;
      if (document.compatMode=='CSS1Compat') {
        var gcs = xGetComputedStyle;
        pl=gcs(e,'padding-left',1);
        if (pl !== null) {
          pr=gcs(e,'padding-right',1);
          bl=gcs(e,'border-left-width',1);
          br=gcs(e,'border-right-width',1);
        }
        // Should we try this as a last resort?
        // At this point getComputedStyle and currentStyle do not exist.
        else if(xDef(e.offsetWidth,e.style.width)){
          e.style.width=w+'px';
          pl=e.offsetWidth-w;
        }
      }
      w-=(pl+pr+bl+br);
      if(isNaN(w)||w<0) return;
      else e.style.width=w+'px';
    }
    w=e.offsetWidth;
  }
  else if(css && xDef(e.style.pixelWidth)) {
    if(w>=0) e.style.pixelWidth=w;
    w=e.style.pixelWidth;
  }
  return w;
}
/**
 * A bunch of useful utilitiy javascript methods available to all jira pages
 */


/**
 * Adds Ctrl+Enter submit functions to textarea elements
 *
 */
window.onload = function ()
{
    var textAreas = xGetElementsByTagName('textarea');
    for (var i = 0; i < textAreas.length; i++) 
    {
        xAddEventListener(textAreas[i], 'keypress', submitOnCtrlEnter);
    }
}

/*
 * Submits an element's form if the enter key is pressed
 */
function submitOnEnter(e) 
{
    var xe = new xEvent(e);
    var targetObject = xe.target;
    if (xe.keyCode  == 13 && targetObject.form)
    {
        targetObject.form.submit();
    }
}

/*
Submits an element's form if the enter key and the control key is pressed
*/
function submitOnCtrlEnter(e) 
{
    var xe = new xEvent(e);
    var targetObject = xe.target;
    if (xe.ctrlKey && (xe.keyCode  == 13 || xe.keyCode == 10 ) && targetObject.form)
    {
        targetObject.form.submit();
        return false;
    }
    return true;
}


/*
Returns a space delimited value of a select list. There's strangely no in-built way of doing this for multi-selects
*/
function getMultiSelectValues(selectObject) 
{
    var selectedValues = '';
    for (var i = 0; i < selectObject.length; i++)
    {
        if(selectObject.options[i].selected)
        {
            if (selectObject.options[i].value && selectObject.options[i].value.length > 0)
                selectedValues = selectedValues + ' ' + selectObject.options[i].value;
        }
    }

    return selectedValues;
}

function getMultiSelectValuesAsArray(selectObject)
{
    var selectedValues = new Array();
    for (var i = 0; i < selectObject.length; i++)
    {
        if(selectObject.options[i].selected)
        {
            if (selectObject.options[i].value && selectObject.options[i].value.length > 0)
                selectedValues[selectedValues.length] = selectObject.options[i].value;
        }
    }
    return selectedValues;
}

/*
  Returns true if the value is the array
*/
function arrayContains(array, value)
{
    for (var i = 0; i < array.length; i++)
    {
        if (array[i] == value)
        {
            return true;
        }
    }

    return false;
}

/*
Adds a class name to the given element
*/
function addClassName(elementId, classNameToAdd) 
{
    var elem = document.getElementById(elementId);
    if (elem)
    {
        elem.className = elem.className + ' ' + classNameToAdd;
    }
}

/*
 Removes all class names to from the given element
 */
function removeClassName(elementId, classNameToRemove) 
{
    var elem = document.getElementById(elementId);
    if (elem)
    {
        elem.className = (' ' + elem.className + ' ').replace(' ' + classNameToRemove + ' ', ' ');
    }
}

/*
    Returns the field as an encoded string (assuming that the id == the field name
*/
function getEscapedFieldValue(id)
{

    var e = document.getElementById(id);

    if (e.value)
    {
        return id + '=' + encodeURIComponent(e.value);
    }
    else
    {
        return '';
    }
}

/*
    Returns a concatenated version of getEscapedFieldValue
*/
function getEscapedFieldValues(ids)
{
    var s = '';
    for (i = 0; i < ids.length; i++)
    {
        s = s + '&' + getEscapedFieldValue(ids[i]);
    }
    return s;
}

/* Manages Gui Preferences and stores them in the user's cookie. */
var GuiPrefs = {
    toggleVisibility: function(elementId) {
        var elem = document.getElementById(elementId);
        if (elem)
        {
            if (readFromConglomerateCookie("jira.conglomerate.cookie", elementId, '1') == '1')
            {
                elem.style.display = "none";
                removeClassName(elementId + 'header', 'headerOpened');
                addClassName(elementId + 'header', 'headerClosed');
                saveToConglomerateCookie("jira.conglomerate.cookie", elementId, '0');
            }
            else
            {
                elem.style.display = "";
                removeClassName(elementId + 'header', 'headerClosed');
                addClassName(elementId + 'header', 'headerOpened');
                eraseFromConglomerateCookie("jira.conglomerate.cookie", elementId);
            }
        }
    }
};

/*
 Toggles hide / unhide an element. Also attemots to change the "elementId + header" element to have the headerOpened / headerClosed class.
 Also saves the state in a cookie
 DEPRECATED: use GuiPrefs.toggleVisibility
*/
function toggle(elementId) 
{
    GuiPrefs.toggleVisibility(elementId);
}

function toggleDivsWithCookie(elementShowId, elementHideId)
{
    var elementShow = document.getElementById(elementShowId);
    var elementHide = document.getElementById(elementHideId);
    if (elementShow.style.display == 'none')
    {
        elementHide.style.display = 'none';
        elementShow.style.display = 'block';
        saveToConglomerateCookie("jira.viewissue.cong.cookie", elementShowId, '1');
        saveToConglomerateCookie("jira.viewissue.cong.cookie", elementHideId, '0');
    }
    else
    {
        elementShow.style.display = 'none';
        elementHide.style.display = 'block';
        saveToConglomerateCookie("jira.viewissue.cong.cookie", elementHideId, '1');
        saveToConglomerateCookie("jira.viewissue.cong.cookie", elementShowId, '0');
    }
}

/*
 Similar to toggle. Run this on page load.
*/
function restoreDivFromCookie(elementId, cookieName, defaultValue)
{
    if (defaultValue == null)
        defaultValue = '1';

    var elem = document.getElementById(elementId);
    if (elem)
    {
        if (readFromConglomerateCookie(cookieName, elementId, defaultValue) != '1')
        {
            elem.style.display = "none";
            removeClassName(elementId + 'header', 'headerOpened');
            addClassName(elementId + 'header', 'headerClosed')
        }
        else
        {
            elem.style.display = "";
            removeClassName(elementId + 'header', 'headerClosed');
            addClassName(elementId + 'header', 'headerOpened')
        }
    }
}

/*
 Similar to toggle. Run this on page load.
*/
function restore(elementId)
{
    restoreDivFromCookie(elementId, "jira.conglomerate.cookie", '1');
}

// Cookie handling functions

function saveToConglomerateCookie(cookieName, name, value)
{
    var cookieValue = getCookieValue(cookieName);
    cookieValue = addOrAppendToValue(name, value, cookieValue);

    saveCookie(cookieName, cookieValue, 365);
}

function readFromConglomerateCookie(cookieName, name, defaultValue)
{
    var cookieValue = getCookieValue(cookieName);
    var value = getValueFromCongolmerate(name, cookieValue);
    if(value != null)
    {
        return value;
    }

    return defaultValue;
}

function eraseFromConglomerateCookie(cookieName, name)
{
    saveToConglomerateCookie(cookieName, name,"");
}

function getValueFromCongolmerate(name, cookieValue)
{
    var newCookieValue = null;
    // a null cookieValue is just the first time through so create it
    if(cookieValue == null)
    {
        cookieValue = "";
    }
    var eq = name + "=";
    var cookieParts = cookieValue.split('|');
    for(var i = 0; i < cookieParts.length; i++) {
        var cp = cookieParts[i];
        while (cp.charAt(0)==' ') {
            cp = cp.substring(1,cp.length);
        }
        // rebuild the value string exluding the named portion passed in
        if (cp.indexOf(name) == 0) {
            return cp.substring(eq.length, cp.length);
        }
    }
    return null;
}

//either append or replace the value in the cookie string
function addOrAppendToValue(name, value, cookieValue)
{
    var newCookieValue = "";
    // a null cookieValue is just the first time through so create it
    if(cookieValue == null)
    {
        cookieValue = "";
    }

    var cookieParts = cookieValue.split('|');
    for(var i = 0; i < cookieParts.length; i++) {
        var cp = cookieParts[i];

        // ignore any empty tokens
        if(cp != "")
        {
            while (cp.charAt(0)==' ') {
                cp = cp.substring(1,cp.length);
            }
            // rebuild the value string exluding the named portion passed in
            if (cp.indexOf(name) != 0) {
                newCookieValue += cp + "|";
            }
        }
    }

    // always append the value passed in if it is not null or empty
    if(value != null && value != '')
    {
        var pair = name + "=" + value;
        if((newCookieValue.length + pair.length) < 4020)
        {
            newCookieValue += pair;
        }
    }
    return newCookieValue;
}

function getCookieValue(name)
{
    var eq = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i<ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(eq) == 0) {
            return c.substring(eq.length,c.length);
        }
    }

    return null;
}

function saveCookie(name,value,days)
{
  var ex;
  if (days) {
    var d = new Date();
    d.setTime(d.getTime()+(days*24*60*60*1000));
    ex = "; expires="+d.toGMTString();
  }
  else {
    ex = "";
  }
  document.cookie = name + "=" + value + ex + ( (contextPath) ? ";path=" + contextPath : ";path=/");
}

/*
Reads a cookie. If none exists, then it returns and 
*/
function readCookie(name, defaultValue)
{
  var cookieVal = getCookieValue(name);
  if(cookieVal != null)
  {
      return cookieVal;
  }

  // No cookie found, then save a new one as on!
  if (defaultValue)
  {
      saveCookie(name, defaultValue, 365);
      return defaultValue;
  }
  else
  {
      return null;
  }
}

function eraseCookie(name)
{
  saveCookie(name,"",-1);
}

