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 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(); 
	}
}

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 showImg(i) {
  var d  = $('viewer')
  var di = $('viewer_img')

  getWindowPosition(d, 10, 10)

  di.innerHTML = '<img src="' + i + '">'
}

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 highlightRow(sel_row, old_sel_row)  {
  selected_row = $(sel_row)

  if ( old_sel_row && $(old_sel_row) ) {
    if ( old_sel_row == sel_row ) {
      return sel_row;
    }

    for ( i=0; i<$(old_sel_row).cells.length; i++)  {
      $(old_sel_row).cells[i].className='';
    }
  }

  for ( i=0; i<selected_row.cells.length; i++)  {
    selected_row.cells[i].className='selected'
  }

  return sel_row;
}

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() {
  Element.hide('indicator');
  if ($('stuff_edit_link') != undefined) Element.hide('stuff_edit_link');
  if ($('relation_edit_link') != undefined) Element.hide('relation_edit_link');
  if ($('special_text_edit_link') != undefined) Element.hide('special_text_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 activateCommentsField(ed) {
	ed.focus();
	if ( !comment_inited ) {
		enableCommentButtons();
		ed.setContent('');
	}
}

function enableCommentButtons(){
	$('comment_submit').disabled = false;
	$('comment_cancel').disabled = false;
	$('comment_buttons').className = '';
	comment_inited = true;
}

// 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=\"" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='image');\"></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();
}

// Extending Prototype's Element object
var wiserPopupFunctions = {
  /**
   * positionPopup - Positions a <div> with "id" of popup_id to coordinates of
   *                    <element> with "id" of trigger_id.
   *                    
   * @param {Object}  element - (implicitly passed by Prototype's Element object). 
   * @param {String}  popup_id - "id" of <div> to reposition. 
   * @param {String}  trigger_id - (optional) "id" of element to reposition to. If null then popup_id is hidden. 
   * @param {Int}     offset - (optional) if trigger_id is specified, how many pixels to put between trigger_id and popup_id.
   *                      If offset is negative (offset < 0), popup_id is moved to left of trigger_id
   *                      If offset is positive (offset > 0), popup_id is moved to right of trigger_id
   *                      Default value is +10
   *                              
   * TODO: Examples
   * 
   * <a href="#" onclick="$(this).positionPopup('test_popup','sample_link', 20)">Link</a>
   *    Moves element with ID of 'test_popup' 20 pixels to the right of element with ID 'sample_link'
   * 
   * <a href="#" onclick="$(this).positionPopup('test_popup')">Close</a>
   *    Moves element with ID 'test_popup' out of visible range (-9999,-9999)
   *  
   */
	positionPopup: function( element, popup_id, trigger_id, offset ) {
		// set default args
		offset = ( typeof offset == "undefined" ) ? 10 : offset;
		var hideAction = ( typeof trigger_id == "undefined" ) ? true : false;
		
		var popup = $(popup_id);
		var popup_dim = Element.getDimensions( popup );
		
		var x_coord;
		var y_coord;
		
		if ( !hideAction ) {
		  var trigger = $(trigger_id);
			var trigger_dim = Element.getDimensions( trigger );
						
			var trigger_coords = Position.cumulativeOffset( trigger );
			
			if ( offset >= 0 ) { // RIGHT: top-left coord of trigger + width of trigger + offset
        x_coord = trigger_coords[0] + trigger_dim.width + offset;
      } else { // LEFT: top-left coord of trigger - width of popup - offset
        x_coord = trigger_coords[0] - popup_dim.width - ( offset * -1 );
      }
			// popup and trigger are vertically aligned
			y_coord = trigger_coords[1];
		} else { // hideAction is true
			x_coord = '-9999';
			y_coord = '-9999';
		}
		
		// Move the popup to new coords
		Element.setStyle( popup, {
      position: 'absolute',
			top: y_coord+'px',
			left: x_coord+'px'
		});
		
		return element;
		
  }
}

// Add custom methods to Prototype's Element object
Element.addMethods( wiserPopupFunctions );

  var default_msg_tmpl = new Template("Write your own personal message here");
  var invite_title_tmpl = new Template("Invite #{masterid} to your network");
  var active_invite = {
    invitee_id: null
  }
 
  var initPopupFacade = function( config ) {
    var default_msg = default_msg_tmpl.evaluate({ masterid: config.friend_name });
    var invite_title = invite_title_tmpl.evaluate({ masterid: config.friend_name });
    $("invite_message").defaultValue = default_msg;
    $("invite_title").update(invite_title);
    $("invite_message").value = default_msg;
    $("friend").value = config.friend_id;
    $("inviteFriendPopup").positionPopup("inviteFriendPopup",config.trigger_id,20);
  }

var moveEditorTo = function( id ) {
  if ( !$(id) ) {
    alert("Cannot move editor to: " + id);
  }
  
  var editorHolder = $("editorHolder");
  var current_holder_id = editorHolder.parentNode.id;
  var current_holder = $( current_holder_id );
  
  var addCommentTop = $("addcomment");
  var addCommentBottom = $("addcomment_bottom");
  
  if ( current_holder_id != id ) {
    current_holder.hide();
    tinyMCE.execCommand("mceRemoveControl", false, "comment");
    current_holder.removeChild( editorHolder );
    newEditorLocation = $(id);
    newEditorLocation.appendChild( editorHolder );
    tinyMCE.execCommand("mceAddControl", false, "comment");
    newEditorLocation.show();
		comment_editor_init();
  } else {
    current_holder.show();
  }
}

var comment_editor_init = function() {
	var comment_ed = tinyMCE.get("comment");
	comment_ed.onBeforeExecCommand.add(function(ed, e) {
		if ( comment_ed_inited && !comment_inited ) {
		  enableCommentButtons();
		  ed.setContent("");
		}
	});
	
	commentEventsAdded = 1;
	comment_ed.onInit.add(function(ed, e) {
	  comment_ed_inited = true;
	});
	
	comment_ed.onClick.add(function(ed, e) {
		if ( !comment_inited ) {
		  enableCommentButtons();
		  ed.setContent("");
		}
	});
}

	Event.observe(window,"load",function(){
		var forProfits = $$("span.orgForProfit");
    forProfits.each(function(s){
      Event.observe(s,"mouseover",function(){
        ddrivetip('A business organization within the private sector that carries on a commercial or industrial enterprise, e.g. corporation, partnership, cooperative association.');
      });
      
      Event.observe(s,"mouseout",function(){
        hideddrivetip()
      });
    });
    		
		var publicAgencies = $$("span.orgPublicAgency");
    publicAgencies.each(function(s){
      Event.observe(s,"mouseover",function(){
        ddrivetip('A permanent or semi-permanent organization within the public sector responsible for the oversight and administration of specific functions, e.g. public health agency.');
      });
      
      Event.observe(s,"mouseout",function(){
        hideddrivetip()
      });
    });
	});
