/**
* local.js contain most of the javascript functions which we tend to use.
*
* @author   everyone, really
**/

// browser check
var dom=document.getElementById&&!document.all
var topelement=dom? "HTML" : "BODY"

/**
* 
* used by confirmClose() to initiate a popup on close.
*
* @var  boolean 
**/
var changeFlag = false;

/**
* sets a div style.display to block or none.
* if set to none, returns 0
* if set to block (i.e., visible), returns 1
**/
function toggleDiv(divid)
    {
    var block = document.getElementById(divid);
    if (block.style.display == "block")
        {
        block.style.display = "none";
        return 0;
        }
    else
        {
        block.style.display = "block";
        return 1;
        }
    };

/**
* pops up a new help window
*
* @param    url     string  the url
* @param    name    string  the window's new name
* @param    width   integer the width
* @param    height  integer the height
**/
function helpPopup(url,name,width,height) {
  var today = new Date();
  var todayTime = today.getTime();
  var scrollbars = 'yes';
  name = name.match(/^\w+/)[0] + todayTime;
  settings="toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,scrollbars="+scrollbars+",resizable=yes,width="+width+",height="+height;
  var popupWindow=window.open(url,name,settings);
  return popupWindow;
}

/**
*
* confirmDelete is a simple confirm window.
*
* @param    name    string  the "name" + "type" will be deleted.  you can't recover "+type+"
* @param    type    string  
**/
function confirmDelete(type,name) {
  if(type == 'block')
      return confirm("You are about to delete the "+name+" "+type+". If you choose to continue, this "+type+" will be moved to the trash clipboard. Please note, only your last 5 deleted "+type+"s are retained in the clipboard.");
  else
      return confirm("WARNING: You are about to permanently delete the "+name+" "+type+" of your site. If you choose to continue, you will not be able to recover this "+type+".");
}

/**
* sets the changeFlag var
**/
function setChangeFlag() {
  changeFlag = true;
}

/**
* if changeFlag is set, will give a warning confirm box
**/
function confirmLeave() {
  if(changeFlag)
    return confirm("WARNING: You have unsaved changes on this page.  If you choose to continue, those changes will be lost.");
  return true;
}

/**
* destroys a child the hard way
**/
function destroyChild() {
  if(self.opener) {
    self.opener.focus();
    setTimeout("self.close()", 4000);
  }
}

/**
* destroys the child and reload's the parent window
* added the reload after the replace because for some reason replace would not work when an anchor tag was in the url -reuvenmh
**/
function destroyAndRefresh()
    {
    if (self.opener)
        {
        var url = self.opener.location.href;
        if(url.indexOf('__edit=1') != -1)
          {
          var mark = url.indexOf('#');
          if(mark != -1)
            var right_url = url.substring(0, mark);
          else
            var right_url = url;
          self.opener.location.href = right_url.replace("__edit=1", "__edit=0");
          self.opener.location.replace(right_url.replace("__edit=1", "__edit=0"));
          }
        else
          {
          var mark = url.indexOf('#');
          if(mark != -1)
            var right_url = url.substring(0, mark);
          else
            var right_url = url;

          self.opener.location.href = right_url;
          self.opener.location.replace(right_url);
          }
        self.opener.focus();
        setTimeout("self.close()", 4000);
        }
    }

/**
* destroys the child and reload's the parent window but stays in edit mode
* added the reload after the replace because for some reason replace would not work when an anchor tag was in the url -reuvenmh
**/
function destroyAndRefreshEdit()
    {
    if (self.opener)
        {
        self.opener.location.replace(self.opener.location.href);
        //self.opener.location.reload();
        self.opener.focus();
        setTimeout("self.close()", 4000);
        }
    }

/**
* destroys a child and refreshes the parent window to $refreshUrl
*
* @param    refreshUrl  string  url to be redirected to
**/
function closeChild(refreshUrl) 
    {
    if(self.opener) 
        {
        self.opener.location = refreshUrl;
        self.opener.focus();
        setTimeout("self.close()", 4000);
        }
    }

/**
* converts a file dn to its user-friendly id
**/
function dnToFileID(dn,curOrgDN) {
    id = dnToSiteID(dn, curOrgDN);
    while (tmp = dn.match(/(.*)(^|,)([^=]+)=(.+)$/)) {
        if (tmp[3] == 'mnF' || tmp[3] == 'mnOD' && tmp[4] != 'My Documents')
            id = id + '/' + tmp[4];
        dn = tmp[1];
    }
    return id;
}

/**
* converts a folder dn to its user-friendly folder id
**/
function dnToFolderID(dn, curOrgDN ) {
    id = dnToSiteID(dn, curOrgDN);
    while (tmp = dn.match(/(.*)(^|,)([^=]+)=(.+)$/)) {
        if ( tmp[3] == 'mnOD' && tmp[4] != 'My Documents')
            id = id + '/' + tmp[4];
        dn = tmp[1];
    }
    return id;
}

function dnToPagePath(dn, curOrgDN) {
    id = dnToSiteID(dn, curOrgDN);
    while (tmp = dn.match(/(.*)(^|,)([^=]+)=(.+)$/)) {
        if ( tmp[3] == 'mnTS')
            id = id + '/' + tmp[4];
        dn = tmp[1];
    }
    return id;
}

function dnToSiteID(dn, curOrgDN) {
	orgPart = dn.match(/dc=.*$/);
	if (orgPart != curOrgDN) {
		id = orgPart[0].replace(/dc=/g, '');
		id = id.replace(/,/g, '.') + ':';
	} else {
		id = '';
	}
	return id;
}
    
function listAdd(oList, value, caption, oVal)
    {
    var oNew = new Option(caption, value);
    oList.options[oList.length] = oNew;
    oList.selectedIndex = oNew.index;

    oVal = document.getElementById(oVal);
    listSaveString(oList, oVal);
    }

function listRemove(oList, oVal)
    {
    i = oList.selectedIndex;
    if (oList.selectedIndex != -1)
        oList.options[oList.selectedIndex] = null;
    oList.selectedIndex = (i == oList.length ? i - 1 : i);

    oVal = document.getElementById(oVal);
    listSaveString(oList, oVal);
    } 

function listReplaceOption (oList, oldVal, newVal, oVal, newValLabel)
	{
    for(i=0;i<oList.length;i++)
		{
		if (oList.options[i].value == oldVal)
			{
			oList.options[i].text = newValLabel;
			oList.options[i].value = newVal;
			break;
			}
		}
    oVal = document.getElementById(oVal);
    listSaveString(oList, oVal);
	}
    
function listMoveOption (oList, dir, oVal)
    {
    dir = (dir == 'up' ? -1 : 1);
    s = oList.selectedIndex;
    if (s + dir >= 0 && s + dir < oList.length)
        {
        var option = new Object();
        option.text = oList.options[s].text;
        option.value = oList.options[s].value;
        oList.options[s].text = oList.options[s+dir].text;
        oList.options[s].value = oList.options[s+dir].value;
        oList.options[s+dir].text = option.text;
        oList.options[s+dir].value = option.value;
        //forces the box to update with the new selected index, otherwise auto scorlling to the top will make current selection invisible when 
        //option selected is lower than the viewable range
        oList.blur();
        oList.selectedIndex = oList.options[s+dir].index;
        
        oVal = document.getElementById(oVal);
        listSaveString(oList, oVal);
        }
    }
    
function listSaveString(oList, oVal)
    {
    oVal.value = '';
    for(i=0;i<oList.length;i++)
        oVal.value += oList.options[i].value + ';';
	oVal.value = oVal.value.substr(0, oVal.value.length - 1);
    }
    
// get the width of an object in pixels
// (IE uses a different attribute than Mozilla)
function getWidth(obj) {
	width = obj.offsetWidth;
	if (width == 0)
		width = obj.style.pixelWidth;
	return width;
}

// get the height of an object in pixels
function getHeight(obj) {
	height = obj.offsetHeight;
	if (height == 0)
		height = obj.style.pixelHeight;
	return height;
}
    
function centerDiv(div) {
	dom = document.getElementById && !document.all
	px = (dom ? window.pageXOffset : document.body.scrollLeft) + Math.floor(((dom ? window.innerWidth : document.documentElement.clientWidth) - getWidth(div)) / 2) - parseInt(document.body.style.marginLeft);
	py = (dom ? window.pageYOffset : document.body.scrollTop) + Math.floor(((dom ? window.innerHeight : document.documentElement.clientHeight) - getHeight(div)) / 2);
	div.style.left = px + 'px';
	div.style.top = py + 'px';
}

function sidebarSelectTab(tabnum, totalnum, url)
  {
  for(i=1;i<=totalnum;i++)
    {
    if(i == tabnum)
      {
      totalpx = getHeight(document.getElementById('cvsidebar')) - (totalnum*20);
      document.getElementById('sidebar'+i).style.display = 'block';
      document.getElementById('sidebar'+i).style.height = totalpx + "px";
      document.getElementById('cvsidebarselectedelement').value = 'sidebar'+i;
      document.getElementById('cvsidebarlasttab').value = i;
      }
    else
      document.getElementById('sidebar'+i).style.display = 'none';
    }
  doHttpRequest(url, null, function() {}, false);
  }

function sidebarFixTab()
  {
  totalnum = document.getElementById('cvsidebartotalelement').value;
  heightside = getHeight(document.getElementById('cvsidebar')) < 500 ? 500 : getHeight(document.getElementById('cvsidebar'));
  window_height = document.documentElement.clientHeight;
  if (navigator.userAgent.indexOf('Opera') != -1)
 	 window_height = document.body.clientHeight;
  
  //fix for small browsers
  if (window_height < 850)
      {
      document.getElementById('nav_div').style.height = (window_height - totalnum * 20 - 15) + 'px';
      document.getElementById('nav_div2').style.height = (window_height - totalnum * 20 - 15) + 'px';
      heightside = window_height;
      }
  
  totalpx =  heightside - (totalnum*20);
  document.getElementById(document.getElementById('cvsidebarselectedelement').value).style.height = totalpx + "px";
  }

function checkMenuScroll()
  {
  var scrollY = 0;
  if(document.getElementById('cvsidebar').style.position == 'fixed') {
    scrollY = 0;
  }
  else if( document.documentElement && document.documentElement.scrollTop ) {
    scrollY = document.documentElement.scrollTop;
  }
  else if( document.body && document.body.scrollTop ) {
    scrollY = document.body.scrollTop;
  }
  else if( window.pageYOffset ) {
    scrollY = window.pageYOffset;
  }
  else if( window.scrollY ) {
    scrollY = window.scrollY;
  }

/*
  var height = 600;
  if(document.clientHeight) {
    height = document.clientHeight;
  }
  else if( document.documentElement && document.documentElement.clientHeight ) {
    height = document.documentElement.clientHeight > document.body.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight-5;
  }
  else if( document.body && document.body.clientHeight ) {
    height = document.body.clientHeight;
  }
  else if( window.innerHeight ) {
    height = window.innerHeight - 18; 
  }
 */

  window_height = document.documentElement.clientHeight;
  if (navigator.userAgent.indexOf('Opera') != -1)
 	 window_height = document.body.clientHeight;

  if(window_height > 500) 
    {
    document.getElementById('cvsidebar').style.height = (window_height-2) + "px"; 
    document.getElementById('cvsidebarlastheight').value = (window_height-2);
    }
  document.getElementById('cvsidebar').style.top = scrollY + "px";
  sidebarFixTab();
  }

function showHideSideBar(close)
  {
  if(close)
    {
    // if we at some point decide to make this work with ajax we can use this
    //document.getElementById('cvsidebartoolbarshow').parentNode.style.width = '20px';
    //document.getElementById('cvsidebartoolbarshow').style.display = 'inline';
    //document.getElementById('cvsidebar').style.display = 'none';
    //document.body.style.marginLeft = '0px';

    document.getElementById('cvsidebarstatus').value = 'hidden';
    document.cvsecurity.submit();
    }
  else
    {
    // if we at some point decide to make this work with ajax we can use this
    //document.getElementById('cvsidebartoolbarshow').style.display = 'none';
    //document.getElementById('cvsidebartoolbarshow').parentNode.style.width = '0px';
    //document.getElementById('cvsidebar').style.display = 'block';
    //document.body.style.marginLeft = '160px';

    document.getElementById('cvsidebarstatus').value = 'visible';
    document.cvsecurity.submit();
    }
  }

function getDocHeight(doc) {
  var docHt = 0, sh, oh;
  if (doc.height) docHt = doc.height;
  else if (doc.body) {
    if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
    if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
    if (sh && oh) docHt = Math.max(sh, oh);
  }
  return docHt;
}

function cv_delLayoutEdit(mode, id, response)
    {
    if (response == 2) {
        alert("You cannot delete this block, because it is in the clipboard.  Please remove it from the clipboard and try again.");
        return;
        }
    switch(mode)
        {
        case 'block':
            var element = document.getElementById(id + 'edit');
            element.parentNode.removeChild(element);
            break;
        }
    }        


function cv_delLayout(mode, id, response)
    {
    if (response == 2) {
    	alert("You cannot delete this block, because it is in the clipboard.  Please remove it from the clipboard and try again.");
    	return;
	}
    switch(mode)
        {
        case 'block':
            var element = document.getElementById(id);
            element.parentNode.removeChild(element);

			for(var i=0;i<colList.length;i++) {
			if(colList[i] != null)
			  {
			  if(colList[i].sizer != null)
				colList[i].sizer.style.height = '0px';
			  colList[i].style.height = '0px';            
			  }
			}

			for(var i=0;i<colList.length;i++) {
			if(colList[i] != null)
			  {
			  colList[i].style.height = 'auto';
			  if(colList[i].sizer != null)
				colList[i].sizer.style.height = '100%';
			  }
			}
            break;
        }

	cv_markDirty();
    drag_resetBlanks();
    }


function cv_insertAtCursor(myField, myValue) 
    {
    //IE support
    if (document.selection) 
        {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == '0') 
        {
        var scrollPos = myField.scrollTop;
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue
        + myField.value.substring(endPos, myField.value.length);

        myField.selectionEnd = endPos+myValue.length;
        myField.selectionStart = endPos+myValue.length;
        myField.focus();
        myField.scrollTop = scrollPos;
        }
    else 
        {
        myField.value += myValue;
        }
    }

// goes up the parent tree until class is found. If not found, returns null
function drag_getObjectByClass(target,clazz,exact) {
	if (typeof exact == 'undefined')
		exact = true;
	var r = new RegExp(exact ? '(^| )' + clazz + '($| )' : clazz);
    while (target.tagName!=topelement && target.className.search(r) == -1){
        target=dom? target.parentNode : target.parentElement;
    }

    if (target.className.search(r) != -1){
        return target;
    }else {
        return null;
    }   
}

function cv_firstChildByTag(obj, tagName) {
    mycnt = 0;
    for (var i=0;i<obj.childNodes.length;i++) {
        if (obj.childNodes[i].tagName == tagName) {
            return obj.childNodes[i];
        }
    }
	return null;
}
