// this code will safely load tinyMCE before jquery library. The library itself is loaded in PageHelper
tinyMCE.init({ mode : "none"});


function initTinyMCE(options)
{
  if (typeof(options) == 'undefined')
  {
    options = {
	    mode : "textareas",
	    theme : "advanced",
	    //editor_selector : "mceEditor",
	    theme_advanced_toolbar_location:   "top",
	    theme_advanced_toolbar_align:      "left",
	    theme_advanced_statusbar_location: "bottom",
	    submit_patch : true
	  }
  }
  tinyMCE.init(options);
}

// this function will turn on the TinyMCE editor for the given textarea id. To use, you must
// first have called initTinyMCE previously. When the TinyMCE editor is part of a remote func call,
// you must call this function on load success. It is the only way I got remote tinyMCE editing to work.
// In other words, if you have a button to download ajax content, put the initTinyMCE in the remote
// content, and toggleTinyMCEEditor in your success func of the button
function toggleTinyMCEEditor(id) {
  if (!tinyMCE.getInstanceById(id))
    tinyMCE.execCommand('mceAddControl', false, id);
  else
    tinyMCE.execCommand('mceRemoveControl', false, id);
}

function triggerTinyMCESave(id)
{
  tinyMCE.triggerSave();
  tinyMCE.execCommand('mceRemoveControl', true, id);
}

function testcallback(id)
{
  jQuery('#'+id).html('saving...');
}

function clearTinyMCEDirtyFlag(id)
{
  ed = tinyMCE.getInstanceById(id);
  ed.isNotDirty = true;
  ed.nodeChanged();
}

/****************************** helper code for Zebra Striping **************************************/

// you must define a table.tableClass tr.alt css class with a background-color
function ZebraStripeTable(rowSelector)
{
  // 1st remove any leftover 'alt' class (if run prior to changes)
  jQuery(rowSelector).removeClass('alt');
  // 2nd add 'alt' class to odd rows (because of th/tr, we must use odd instead of even)
  jQuery(rowSelector+':odd').addClass('alt');
}

/****************************** helper code for DataTable *******************************************/

function DataTableHelper(tableId, rowindex, reverse)
{
  this.tableId = tableId;
  this.rowToAdd = rowindex;
  if (reverse == null)
    this.reverse = false;
  else
    this.reverse = reverse;
}

DataTableHelper.prototype.getNewRowIndex = function()
{
  return this.rowToAdd;
}

DataTableHelper.prototype.insertNewRow = function()
{
  var prevRow = null;
  var rowContent = null;
  var id = this.tableId;
  var tableSelector = 'table#' + id;
  var rows = jQuery(tableSelector + ' tr.outer-row');
  // store the value for the new row for now
  var newRowNum = 0; // change later
  var numRows = rows.size();
  
  if (numRows > 0) // insert after last row
  {
    newRowNum = this.rowToAdd;
    rowContent = '<tr id=\"'+ id +'_row'+newRowNum+'\" class=\"outer-row\"><td id=\"'+ id +'_data_row'+newRowNum+'\" class=\"data\"></td></tr>';

    if (this.reverse) // insert as first row
    {
      prevRow = rows.get(0); // gets the currently first row
      jQuery(prevRow).before(rowContent);
    }
    else
    {
      prevRow = rows.get(numRows-1); // gets the currently last row
      jQuery(prevRow).after(rowContent);
    }
  }
  else // insert the first row
  {
    newRowNum = 0;
    rowContent = '<tr id=\"'+ id +'_row'+newRowNum+'\" class=\"outer-row\"><td id=\"'+ id +'_data_row'+newRowNum+'\" class=\"data\"></td></tr>';
    jQuery(tableSelector + ' > tbody').html(rowContent);
  }
  	
	jQuery(tableSelector + ' #'+ id +'_data_row'+newRowNum).html('Adding...');
}

DataTableHelper.prototype.updateNewRow = function(data)
{
  jQuery('#'+this.tableId+'_data_row'+this.rowToAdd).html(data);
  this.rowToAdd++;
}    

/****************************** spin div stuff ********************************************************/
var SpinDivUpArrowImg;
var SpinDivDownArrowImg;

// spin divs (that is what I call them) are spin controls that show or hide the content following.
// By calling addSpinDivs in your onReady function, all elements matching the selector will receive
// spin controls at their beginning, and this control can be used by the user to show or hide content
// Content should be enclosed within a 'div' or 'p' tag immediately following the selector tag close.
// The content will be hidden by default. Use showSpinDiv to show it.
function addSpinDivs(selector, imgDir)
{
  // hide all immediat child divs under the selectors
  divSelector =  selector + ' + p, ' + selector + ' + div';
  jQuery(divSelector).hide();

  SpinDivUpArrowImg = imgDir + 'SpinDivUp.gif';
  SpinDivDownArrowImg = imgDir + 'SpinDivDown.gif';

  jQuery(selector).prepend('<a href="#" onclick="toggleSpinDiv(this); return false;"><img src="' + SpinDivUpArrowImg + '" alt="Spinner" class="spin-div" /></a>');
    //jQuery(selector).prepend('<img src="' + SpinDivUpArrowImg + '" alt="Spinner" class="spin-div" />');
    //jQuery(selector).wrap('<a href="#" onclick="toggleSpinDiv(this); return false;"></a>');
}

// return the immediate adjacent sibling 'p' or 'div' following the selector
function getSpinDivElem(anchorElem)
{
  var headElem = anchorElem.parent(); // get parent of <a> - usually an <h?>
  var divElem = headElem.next('p, div'); // get the next div that is a <p> or <div>
  return divElem;
  //selector + ' + p, ' + selector + ' + div';
}

// return the 'img' child of the selector
function getSpinImgElem(anchorElem)
{
  var imgElem = anchorElem.children('img');
  return imgElem;
  //selector + ' > a';
}

function toggleSpinDiv(anchorDomElem)
{
   var anchorElem = jQuery(anchorDomElem);
   var imgSrc = getSpinImgElem(anchorElem).attr("src");
   if (imgSrc.match(SpinDivUpArrowImg))
     showSpinDiv(anchorElem);
   else
     hideSpinDiv(anchorElem);
   return false;
}

function showSpinDiv(anchorElem)
{
  var img = getSpinImgElem(anchorElem);
  img.attr({"src": SpinDivDownArrowImg});
  getSpinDivElem(anchorElem).slideDown(400);
  return false;
}

function hideSpinDiv(anchorElem)
{
  var img = getSpinImgElem(anchorElem);
  img.attr({"src": SpinDivUpArrowImg});
  getSpinDivElem(anchorElem).slideUp(400);
  return false;
}

/****************************** show on checkbox ********************************************************/

// this func will show a div when a checkbox is clicked on (uses jquery)
// pass this for chkbox, and the id of the div to show
function toggleDivOnClick(chkboxId, toggleSelector)
{
 // if (jQuery(chkbox).is(':checked'))
  if (jQuery('#'+chkboxId).is(':checked'))
    jQuery(toggleSelector).slideDown('medium')
  else
    jQuery(toggleSelector).slideUp('medium');
}

// similar to toggleDivonClick, this func will disable a dependent element, and
// even clear it and disable its label. It takes an elemId instead of a selector
// so that its label can be found. The actionFlags can be specified to customize
// the funcs operation:
//    1: disable when false. Default = false
//    2: clear on disable. Default = false
//    4: disable label. Default = true
function toggleElementStateOnCheck(chkBoxSelector, elemId, actionFlags)
{
  var disableWhenFalse = actionFlags & 1;
  var clearOnDisable = actionFlags & 2;
  var disableLabel = !(actionFlags & 4); // disable label is default
  var isChecked = jQuery(chkBoxSelector).is(':checked');
  var elem = jQuery('#'+elemId);
  var labelElem = jQuery('label[for='+elemId+']');
  if (isChecked != disableWhenFalse)
  {
    elem.attr('disabled', 'disabled');
    if (clearOnDisable)
      elem.removeAttr('checked');
    if (disableLabel)
      labelElem.attr('disabled', 'disabled');
  }
  else
  {
    elem.removeAttr('disabled');
    if (disableLabel)
      labelElem.removeAttr('disabled');
  }
}


/****************************** Image Preview Popup on Hover  ****************************************/
/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
/**
 * To use this script func, you must do two easy things:
 * 1) In your page somewhere, call onReady to call the func:
    
	     // starting the script on page load
	    jQuery(document).ready(function(){
	      imagePreview();
	    });
 * 2) In your image tags, use href=filename as usual, and add the class of 'preview', e.g.:
 
      <a href="mypict.jpg" class="preview"><img src="myThumb.jpg" alt="gallery thumbnail" /></a>
      
 * That's it. When you hover over the thumbnail, the image will popup.
*/

this.imagePreview = function(){ 
  /* CONFIG */
    
    xOffset = 10;
    yOffset = 150;
    
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    
  /* END CONFIG */
  jQuery("a.preview").hover(function(e){
    this.t = this.title;
    this.title = "";  
    var c = (this.t != "") ? "<br/>" + this.t : "";
    jQuery("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");                
    jQuery("#preview")
      .css("top",(e.pageY - yOffset) + "px")
      .css("left",(e.pageX + xOffset) + "px")
      .css("position", "absolute")
      .fadeIn("fast");            
    },
  function(){
    this.title = this.t;  
    jQuery("#preview").remove();
    }); 
  jQuery("a.preview").mousemove(function(e){
    jQuery("#preview")
      .css("top",(e.pageY - yOffset) + "px")
      .css("left",(e.pageX + xOffset) + "px");
  });     
};



/****************************** modal pop-up window ********************************************************/

// this code implements a pop-up window. It is based on http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-using-jquery/

var ModalWindowIds = new Array();

function currentModalWindowId()
{
  var lastIndex = ModalWindowIds.length-1;
  if (lastIndex >= 0)
    return ModalWindowIds[lastIndex];
  else
    return 0;
}

function showModalWindow(winDivId)
{
  //if (currModalWindowId == 0)
  if (currentModalWindowId() != winDivId) // so we don't open it twice'
  {
	  //currModalWindowId = winDivId;
    ModalWindowIds.push(winDivId);
	  centerDiv(winDivId);
	  ////jQuery("#modalBackground").css({"opacity": "0.3"});
	  jQuery("#modalBackground_"+winDivId).fadeIn("slow");
	  jQuery("#"+winDivId).fadeIn("slow");
	  
	  //jQuery('#'+winDivId).dialog({"modal":true, "resizable":false, "title": "test"});
	  //jQuery("#"+winDivId).fadeIn("fast");
	}
}

function centerModalWindow()
{
  //if (currModalWindowId != 0)
  var currId = currentModalWindowId();
  if (currId != 0)
    centerDiv(currId);
}

function hideModalWindow(speed)
{
  if (typeof(speed) == 'undefined')
    speed = "fast";
  var currId = currentModalWindowId();
  if (currId != 0)
  {
    jQuery("#modalBackground_"+currId).fadeOut(speed);
    jQuery("#"+currId).fadeOut(speed);
    //currModalWindowId = 0;
     ModalWindowIds.pop();
  }
}

function setupModalWindowEvents(winSelector, draggable)
{
  if (draggable == null)
     draggable = true;

  // make draggable
  jQuery(winSelector).draggable({ handle: 'div.modalTitleBar' });

  //install Escape key event!
  jQuery(document).keypress(
    function(e){
    if ((e.keyCode==27)){
      hideModalWindow();
    }
  });
}

// this func is not used anywhere
function autoCloseWindow(allowOutsideClickToClose)
{
  if (allowOutsideClickToClose == null)
   allowOutsideClickToClose = false;

  var currId = currentModalWindowId();

  //Click the x (closebox) event!
  jQuery(".modalCloseBox").click(function(){
    hideModalWindow();
  });
  
  if (allowOutsideClickToClose) //Click outside the window
	  jQuery("#modalBackground_"+currId).click(function(){
	    hideModalWindow();
	  });
  
  //Press Escape key event!
  jQuery(document).keypress(function(e){
    if ((e.keyCode==27)){
      hideModalWindow();
    }
  });
}

function centerDiv(divId) //request data for centering
{ 
  var docWidth = document.documentElement.clientWidth;
  var docHeight = document.documentElement.clientHeight;
  var divHeight = jQuery("#"+divId).height();
  var divWidth = jQuery("#"+divId).width();
  var scrollPos = this.scrollY; // vertical scroll pos
  var topPos = docHeight/2-divHeight/2;
  if (topPos < 0)
    topPos = 0;
  // adjust for when scrolled down
  topPos = topPos + scrollPos;
  //centering
  jQuery("#"+divId).css({
    "position": "absolute",
    "top": topPos,
    "left": docWidth/2-divWidth/2
  });
  //only need force for IE6
  
  jQuery("#modalBackground_".currModalWindowId).css({
    "height": docHeight
  });
}




/****************************** image pop-up dialog ********************************************************/
showImageinPopup = function(title, image) 
{ 
 var imgTag = '<img src="' + image + '" />';
 var alert = Ext.MessageBox;
 alert.show({ title: title, msg: imgTag }); 
 var dlg = alert.getDialog();
 var w = dlg.getInnerWidth();
 var h = dlg.getInnerHeight();
 // this hack is to fix an Ext bug where the first time it opens, it sometimes is very narrow.
 // TODO - still need to center it
 if (w <= 100)
  dlg.setWidth('auto');
}

// inserts the given html code, replacing a placeholder div of the given id
// does same as outerHTML
function replaceDivWithHtml(divId, html) 
{
  var placeHolder = parent.document.getElementById(divId);
  //works in IE only - placeHolder.outerHTML = html; // replace the placeholder
  //var fragment= parent.document.createDocumentFragment(); // create a new empty node
  //fragment.nodeValue = html;
  //placeHolder.parentNode.replaceChild(fragment, placeHolder);
  //var temp = fragment;
  el = Ext.get(placeHolder);
  el.insertHtml('afterEnd', html);
  var container = placeHolder.parentNode;
  container.removeChild(placeHolder);
}

// append a div to a series (within containerId) with the existing name
// NOTE: uses parent instead of document
function appendNewDiv(containerId, divName)
{
  var container = parent.document.getElementById(containerId);

  // first get the last div of the name given
  var node1 = getLastDivByName(divName);
  if (node1 != null)
  {
	  // copy it (just the outer div)
	  var node2 = node1.cloneNode(false);
	  // bump its id by +1
	  var id = node2.getAttribute('id');
	  var newId = incrementString(id);
	  node2.setAttribute('id', newId);
  }
  else
  {
    var node2 = document.createElement('div');
    var newId = divName + '_0';
    node2.setAttribute('id', newId);
    node2.setAttribute('name', divName);
  }
  
  // now insert the new div into the node tree
  container.appendChild(node2);
  
  return newId; // return the new id
}

// delete the given div
// NOTE: uses parent instead of document
function deleteDiv(divId)
{
  var div = parent.document.getElementById(divId);
  var container = div.parentNode;
  container.removeChild(div);
}

// look for numerals at end of string and increment them
function incrementString(str)
{
  var len = str.length;
  var lastChar = str.charAt(len-1);
  var lastDigit = (+lastChar) + 1; // if last is 9, then new digit will be 10 which will replace the 9
  var stub = str.substring(0,len-1); 
  var newStr = stub + lastDigit.toString();
  return newStr;
}

// return the last instance of elements with the given name
// NOTE: uses parent instead of document
function getLastDivByName(divName)
{
  var divs = parent.document.getElementsByName(divName);
  if (divs.length > 0)
    return divs[divs.length-1]; // get last one; for some reason divs.pop() doesn't work
  else
    return null;
}

/* NOT used anymore

// replace any instances of the given string in the innerHTML content of an elem
function replaceInnerHTMLSubStrings(elem, oldStr, newStr)
{
  var content = elem.innerHTML;
  if (content.indexOf(oldStr) >= 0)
  {
    var newContent = content.replace(new RegExp(oldStr, 'g'), newStr);
    elem.innerHTML = newContent;
  }
}

// DO NOT call this func unless the cloneAndAppendDiv have been called
function undoAppendNewDiv(divName)
{
  // first get the last div of the name given
  var divs = parent.document.getElementsByName(divName); // since we call this func from the iframe, we must go to the parent
  if (divs.length >= 2) // just checking
  {
    var prevNode = divs[divs.length-2]; // get last one; for some reason divs.pop() doesn't work
    var node = divs[divs.length-1]; // get last one; for some reason divs.pop() doesn't work
    // now remove the node
    var container = node.parentNode;
    container.removeChild(node);
    prevNode.style.display = 'none';
  }
}
// callback function once the form is processed
function renderImage(imgDivId, imageFile, imageText) 
{
  var imageName = imageText; // for now - should be passed in
  var container = parent.document.getElementById(imgDivId);
  // set the image
  var images = container.getElementsByTagName('img');
  var image = images[0];
  image.src = imageFile;
  image.alt = imageText;
  // set the caption & a hidden input
  var loadingText = 'loading...';
  var divs = container.getElementsByTagName('*');
  for (i=0; i<divs.length; i++)
  {
    if (divs[i].className == 'caption')
      replaceInnerHTMLSubStrings(divs[i], loadingText, imageText);
    else
      replaceInnerHTMLSubStrings(divs[i], 'empty.gif', imageName);
  }
}

// cloneAndAppendDiv will take a div by name (with id ending with an index, and clone it, replacing every
// occurence of the old id string with the new one. To prevent id conflict, just prefix other ids
// so they'll be unique
function cloneAndAppendDiv(divName)
{
  // first get the last div of the name given
  var node1 = getLastDivByName(divName);
  
  // copy it
  var node2 = node1.cloneNode(true);
  // bump its id by +1
  var id = node2.getAttribute('id');
  var newId = incrementString(id);
  node2.setAttribute('id', newId);
  
  // now search for anything using the id within the innerHTML and replace it with the new id
  // an example would be a delete button (or tag) for the div, using javascript
  replaceInnerHTMLSubStrings(node2, id, newId);
  
  // show orig div (it was probably hidden)
  node1.style.display = 'inline'; // we might want to use visibility="visible/hidden"

  // now insert the new div into the node tree
  var container = node1.parentNode;
  container.appendChild(node2);
  
  return id; // return the original div's id
}

// DO NOT call this func unless the cloneAndAppendDiv have been called
function undoCloneAndAppendDiv(divName)
{
  // first get the last div of the name given
  var divs = parent.document.getElementsByName(divName); // since we call this func from the iframe, we must go to the parent
  if (divs.length >= 2) // just checking
  {
    var prevNode = divs[divs.length-2]; // get last one; for some reason divs.pop() doesn't work
    var node = divs[divs.length-1]; // get last one; for some reason divs.pop() doesn't work
    // now remove the node
    var container = node.parentNode;
    container.removeChild(node);
    prevNode.style.display = 'none';
  }
}

*/


// this doesn't work???
/*
function createHiddenFormElement(form, varId, value)
{
  var input = form.ownerDocument.createElement('input');
  input.type = 'hidden';
  input.id = varId;
  input.value = value;
  form.appendChild(input);
}
*/