function updateSelections(selection) {
	selections_arr = $('selections').value.split(':');
	selection_idx = selections_arr.indexOf(selection.value);

	if ( selection.checked && selection_idx >= 0 ) {
		//do nothing because it's already there
	} else if ( !selection.checked && selection_idx >= 0) {
		//remove it
		selections_arr.splice(selection_idx, 1);
	} else if ( selection.checked && !(selection_idx >=0) ) {
		//add it
		selections_arr.push(selection.value);
	} else if ( !selection.checked && !(selection_idx >=0) ) {
		//do nothing because it's not there to remove
	}
	Element.show('add_buttons');
	Element.show('add_buttons_bottom');
	cnt_text = (selections_arr.length-1) + ' records selected ';
	$('infoText').innerHTML = cnt_text;
	$('infoTextBottom').innerHTML = cnt_text;	
	$('selections').value = selections_arr.join(':');
}

function ie_zindex_kludge(dont_hide) {

	if (navigator.appVersion.indexOf("MSIE")!= -1) {
		var elems = {}
		elems[0] = "login-home-wrapper";
		elems[1] = "multilingual";
		for (var i in elems) {
			if ($(elems[i]) && elems[i] != dont_hide) {
				if ( $(elems[i]).style.display == "none" ) {
					Element.show(elems[i]);
				} else {
					Element.hide(elems[i]);
				}
			}
		}
	}	
}

function fixTooltipHeight(elem, height) {
  if ($(elem).scrollHeight > height) $(elem).style.height = height+'px';
}

function updateJSONSelect(request, json, selectElement){

  var responses = json;
  $(selectElement).length = 0;

  if (!json) {
    var responses = eval('(' + request.responseText + ')');
  }
  var resSize = responses.length;

  for (var i = 0; i < resSize; i++) {	
     $(selectElement).options[i] = new Option(responses[i][0], responses[i][1]);
  }
}

function selectMultiSelectElements() {
	if ( document.getElementById("aofs[]")) {
		aof_selectall(); 
	}
	if ( document.getElementById("groups[]")) {
		group_selectall(); 
	}
	if ( document.fm_aof ) {
		document.fm_aof.submit(); 
	}
	this.disabled=true;
}

function selectTab(tabSelected, tabArray){
  for (i=0; i<tabArray.length; i++) {
   if ( tabSelected == tabArray[i] ) {
      Element.show(tabArray[i] + "_tab");
      $(tabArray[i] + "_tablink").className = tabOnClass;
    } else {
      Element.hide(tabArray[i] + "_tab");
      $(tabArray[i] + "_tablink").className = tabOffClass;
    }
  }
}

function relTypeSelected(formid, val) {
	if ( val == "other" ) {
		$(formid).relationship_type.style.display = "inline";
		$(formid).relationship_type.value = "please specify";
	} else {
		$(formid).relationship_type.style.display = "none";
		$(formid).relationship_type.value = val;
	}
}

function historyToggler() {
// leave this here for entities that have no history panel
}

function divToggler(divID, linkID, showText, hideText) {
	if (document.getElementById(divID)) {
		div = document.getElementById(divID);
		if (div.style.display == 'none') {
			div.style.display = 'inline';
			if ( linkID && document.getElementById(linkID) ) {
				document.getElementById(linkID).innerHTML = showText;
			}
		} else {
			div.style.display = 'none';
			if ( linkID && document.getElementById(linkID) ) {
				document.getElementById(linkID).innerHTML = hideText;
			}
		}
	}	
}

function wasPreviewed(entity) {
  if ( entity == 'aof' ) {
    var fail = false;

    if ( $('special_text').value.indexOf("[keywords:") == -1 ) {
      alert("[keywords: ] tag is required in the wikitext for Areas of Focus.")
      fail = true;
    }

    if ( $('special_text').value.indexOf("[definition:") == -1  )  { 
      alert("[definition: ] tag is required in the wikitext for Areas of Focus.")
      fail = true;
    }

    if ( fail ) return false
  }

  if ( $('wasPreviewed').value == 1 ) return true;
  alert("Please preview changes before attempting to save...")
  return false;
}

function prepareForPreview() {
  $('p_special_text').value = $('special_text').value
  prepareForAjax($('p_special_text'))
  document.getElementById('statusArea').innerHTML = ''
  if ($('editPane') != undefined) { 
    $('editPane').style.top = '1px'
    $('editPane').style.left = '1px'
    Element.hide('editForm')
    Element.hide('openForm')
    Element.show('collapsedForm') 
  } 
}

function prepareForAjax(text) {
  var output = encodeURIComponent(text);
  //MSword quotes hack
  output = output.replace(/%E2%80%99/g, '%27');
  output = output.replace(/%E2%80%9[CD]/gi, '%22');
  return output;
}

function setSearchpanel(val, element, arrSPpanels) {
  var x

  for (x=0; x<arrSPpanels.length; x++) {
    $('sp_' + arrSPpanels[x]).className='searchpanel'
  }

  element.className = 'searchpanelSelected'

  var re = new RegExp('/([A-Za-z0-9]+)/search');
  var m = re.exec($('search_form').action);
  $('search_form').action = $('search_form').action.replace(m[1], val);
}

function updateFrom(cal) {
  var newDate = new Date(cal.date.getTime() - Date.HOUR*3);
  document.getElementById("From").value = newDate.print("%m/%e/%Y %H:%M");
}

function updateTo(cal) {
  var newDate = new Date(cal.date.getTime() + Date.HOUR*3);
  document.getElementById("To").value = newDate.print("%m/%e/%Y %H:%M");
}

function getWindowPosition(d, top_offset, left_offset) {
  iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body

  dsocleft = document.all ? iebody.scrollLeft : pageXOffset
  dsoctop  = document.all ? iebody.scrollTop  : pageYOffset

  if ( top_offset == 'calculate' ) {
    top_offset = ( dsoctop > 120 ) ? 10 : (120 - dsoctop);
  }

  if ( left_offset > -1 ) {
    d.style.left = (dsocleft + left_offset) + 'px'
  }

  d.style.top  = (dsoctop  + top_offset) + 'px'
  d.style.display = 'block'

}

function showIndicator() {
  var d = $('indicator')

  getWindowPosition(d, 0, -1)
}
  
function showIndicatorAt(top, left) {
  $jq('#indicator').css('top', top+'px')
    .css('left', left+'px')
    .css('width', '16px')
    .css('height', '16px')
    .show();
}


function showImg(i, htmlMetaData) {
  var d  = $('viewer')
  var di = $('viewer_img')

  getWindowPosition(d, 10, 10)

  di.innerHTML = '<img src="' + i + '"><br>'+htmlMetaData
}

msgTimer = false
function showMsgPane() {
  var d  = $('msgPane')
  if ( msgTimer ) clearTimeout(msgTimer);

  getWindowPosition(d, 'calculate', 200)
}

var old_id = false
var xxx = false
function setInfoPanel(aid, isRead)  {
  raid = $("r" + aid)
  infospan = $("viewPane")

  if ( old_id && $("r" + old_id) ) {
    if ( old_id == aid ) {
      return false
    }

    for ( i=0; i<$("r" + old_id).cells.length; i++)  {
      $("r" + old_id).cells[i].className='';
    }

  }

  infospan.innerHTML = 'Please wait...';

  old_id = aid

  for ( i=0; i<raid.cells.length; i++)  {
    raid.cells[i].className='selected'
  }

  if ( isRead < 1 ) $("status" + aid).innerHTML='read'

  return true
}

function checkPreviewSuccess() {
	if (((document.getElementById('p_special_text').value.length == 0 ) && (document.getElementById('statusArea').innerHTML.length == 0)) ||
		((document.getElementById('p_special_text').value.length != 0 ) && (document.getElementById('statusArea').innerHTML.length != 0))) {
//	if ((document.getElementById('statusArea').innerHTML.length != 0) && (document.getElementById('p_special_text').value.length != 0 )) {
		document.getElementById('preview_div').innerHTML = document.getElementById('statusArea').innerHTML;
	} else {
		alert("There was a problem communicating with the server. Please copy and paste your changes into a \
separate document for safe keeping and try to preview again later");
	}
}

function checkSaveSuccess() {
	if (((document.getElementById('p_special_text').value.length == 0 ) && (document.getElementById('statusArea').innerHTML.length == 0)) ||
		((document.getElementById('p_special_text').value.length != 0 ) && (document.getElementById('statusArea').innerHTML.length != 0))) {
		document.getElementById('view_special_text').innerHTML = document.getElementById('statusArea').innerHTML;
		switchFromEdit();
	} else {
		alert("There was a problem saving your data. Please copy and paste your changes into a \
separate document for safe keeping and try to save again later");
	}
}

function switchToEdit() {
  switchToWikiEdit('special_text');
}

function switchToWikiEdit(field_name) {
  if ($('indicator') != undefined) Element.hide('indicator');
  if ($('stuff_edit_link') != undefined) Element.hide('stuff_edit_link');
  if ($('relation_edit_link') != undefined) Element.hide('relation_edit_link');
  if ($(field_name+'_edit_link') != undefined) Element.hide(field_name+'_edit_link');
}

function switchFromEdit() {
  if ($('editPane') != undefined) Element.hide('editPane');
  if ($('stuff_edit_link') != undefined) Element.show('stuff_edit_link');
  if ($('relation_edit_link') != undefined) Element.show('relation_edit_link');
  if ($('special_text_edit_link') != undefined) Element.show('special_text_edit_link');
}

function editpanewide () {
	if (document.getElementById('editPane')) {
	  document.getElementById('editPane').style.width = '770px';
	}
}

function editpanenarrow () {
	if (document.getElementById('editPane')) {
	  document.getElementById('editPane').style.width = '465px';
	}
}

// Replace Default Input Text 
function ClearInput(value, id){ 
var input = document.getElementById(id); 

	if(value == input.value){ 
	input.value = ''; 
	} 
}

function enableCommentButtons(){
	$('comment_submit').disabled = false;
	$('comment_cancel').disabled = false;
	$('comment_buttons').className = '';
}

// Fix PNG transparency in IE 5.5 and 6
// Use: <img src="xyz.png" alt="foo" width="10" height="20" onload="fixPNG(this)">
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

function fixPNG(myImage) 
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }
}

// Avatar Tooltips

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function showTip(myobject) {
	myobject.className = "ToolTextHover";
	var allContainedElements = myobject.getElementsByTagName("*");
	for (var i = 0; i < allContainedElements.length; i++) {
		var elem = allContainedElements[i];
		if (elem.className == "tooltip") {
			myposition = findPos(elem);
			if (myposition[0] <= 0) {
				elem.style.right = "";
				elem.style.left = "60%";				
			}
		}
	}
}

function submitSearch(type, arrSPpanels) {
	//document.getElementById('searchtype').innerHTML = 'Search ' + label + ': '; 
	setSearchpanel(type, $('sp_' + type), arrSPpanels);
	$('search_form').submit();
}

function resizeTinyMce(width, height) {
  tinyMCE.activeEditor.theme.resizeTo(parseInt(width)+14, parseInt(height)+52);
}

function addToFavorites(url, title) { 
  if (window.sidebar) {
    window.sidebar.addPanel(title,url,"");
  } else if (window.external) { 
    window.external.AddFavorite(url, title);
  } else {
    alert("Sorry! Your browser doesn't support this function."); 
  }
}

OffsetCalculator = function()
{
  this.getLeft = function(field)
  {
    return calculateOffset(field, "offsetLeft");
  }

  this.getTop = function(field)
  {
    return calculateOffset(field, "offsetTop");
  }

  var calculateOffset = function(field, attribute)
  {
    var offset = 0;
    while (field)
    {
      offset += field[attribute];
      field = field.offsetParent;
    }
    return offset;
  }
}

var popupObj=null;
function popupDisplay(obj) {
  popupObj = obj;

  $("overlay").show();
  var pos=new OffsetCalculator();

  clickX = pos.getLeft(obj) + (obj.offsetWidth/2);
  clickY =pos.getTop(obj) + (obj.offsetHeight/2)
  $("popup").setStyle({
    height:'0px',
    width:'0px',
    left: clickX + 'px',
    top: clickY + 'px',
    opacity:'0'
  });
}

function stylePopup(is_closed) {
  if (is_closed) {
    var left = (windowSize().width * .5) - ((866)/2);
    var top = ((windowSize().height * .5) + windowSize().y) - ((468)/2);
    new Effect.Transform([{
      '#popup' :
      'height:476px;'+
      'width:866px;'+
      'left:'+left+'px;' +
      'top:'+top+'px;' + 
      'opacity:1' 
    }, { 
      'popupImage' :
      'height:426px;' +
      'width:605px;' 
    }, { 
      'popup_words' :
      'height:412px;' +
      'width:200px;'
    }], { duration: .6, afterFinish:afterShow.bind()  }).play();
    

  }
}

function windowSize() {
  var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
  var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
  var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
  var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);

  return {'width':width, 'height':height, 'x':x, 'y':y}
};

function afterShow() {
  var pSpan = $('popupSpan');
  if (pSpan) {
    pSpan.setStyle({
      display:'block'
    });
  }
}

function closePop() {
  var pos=new OffsetCalculator();

  clickX = pos.getLeft(popupObj) + (popupObj.offsetWidth/2);
  clickY =pos.getTop(popupObj) + (popupObj.offsetHeight/2);
  new Effect.Transform([
    { '#popup' :
    'height:0px;'+
    'width:0px;'+
    'left:'+clickX+'px;' +
    'top:'+clickY+'px;' + 
  'opacity:1' },
  { 'popupImage' :
  'height:0px;' +
'width:0px;' },
{ 'popup_words' :
'height:0px;' +
  'width:0px;' },			
  ], { duration: 2, afterFinish:afterClose.bind() }).play();
}

function afterClose(){
  $('overlay').hide();

  $("popup").hide();
}

function showMenu(id, event) {
  var popupObj = $jq(id);

  var clickX = 0;
  if (event.currentTarget != undefined) {
    clickX = $jq(event.currentTarget).offset().left+1;
  } else {
    clickX = event.clientX;
  }
  popupObj
    .css('left', clickX)
    .slideToggle();

}
