
function addOption( idSuffix, text, value, selected, toolTip )
{
  var option = new Option(text,value);
  option.title = toolTip;
  var to = document.getElementById("to-select-"+idSuffix);
  var from = document.getElementById("from-select-"+idSuffix);

  var sortList = window["sort-list"+idSuffix];
  if ( sortList == null )
  {
    sortList = new Array();
    window["sort-list"+idSuffix] = sortList;
  }
  sortList[sortList.length] = option;

  if ( selected )
  {
    var index = getOptionIndex(to.options, option.value);
    if (index != null)
      to.options[index].text = option.text;
  }
  else
  {
    var newOption = new Option(option.text, option.value);
    newOption.title = toolTip;
    from.options[from.options.length] = newOption;
  }
}

function getOptionIndex( options, value )
{
  for ( var i=0; i < options.length; i++ )
  {
    if ( options[i].value == value )
      return i;
  }

  return null;
}

function addContent( idSuffix, form )
{
  var to = document.getElementById("to-select-"+idSuffix);
  var from = document.getElementById("from-select-"+idSuffix);
  for ( var i=0; i < from.options.length; i++ )
  {
    if ( from.options[i].selected )
    {
      var newOption = new Option(from.options[i].text, from.options[i].value);
      newOption.title = from.options[i].title;
      to.options[to.options.length] = newOption;
      from.options[i--] = null;
    }
  }
}

function removeContent( idSuffix, form )
{
  var to = document.getElementById("to-select-"+idSuffix);
  var from = document.getElementById("from-select-"+idSuffix);
  for ( var i=0; i < to.options.length; i++ )
  {
    if ( to.options[i].selected )
    {
      var newOption = new Option(to.options[i].text, to.options[i].value);
      newOption.title = to.options[i].title;
      from.options[from.options.length] = newOption;
      to.options[i--] = null;
    }
  }
  sortSelect( from, idSuffix );
}

function addSingleContent( idSuffix, form )
{
  var to = document.getElementById("to-select-"+idSuffix);
  var from = document.getElementById("from-select-"+idSuffix);
  for ( var i=0; i < from.options.length; i++ )
  {
    if ( from.options[i].selected )
    {
      var newOption = new Option(from.options[i].text, from.options[i].value);
      newOption.selected = 'selected';
      newOption.title = from.options[i].title;
      to.options[1] = newOption;
      break;
    }
  }
}

function removeSingleContent( idSuffix, form )
{
  var to = document.getElementById("to-select-"+idSuffix);
  to.options[1] = null;
  to.options[0].selected = 'selected';
}

function moveUp( idSuffix, form )
{
  var list = document.getElementById("to-select-"+idSuffix);
  if (( list.options.length == 0 ) || ( list.options[0].selected )) return;

  for ( var i=1; i < list.options.length; i++ )
  {
    if ( list.options[i].selected )
      swapOptions( list.options[i-1], list.options[i] );
  }
}

function moveDown( idSuffix, form )
{
  var list = document.getElementById("to-select-"+idSuffix);
  if (( list.options.length == 0 ) || ( list.options[list.options.length - 1].selected )) return;

  for ( var i=list.options.length - 2; i >= 0 ; i-- )
  {
    if ( list.options[i].selected )
      swapOptions( list.options[i+1], list.options[i] );
  }
}

function swapOptions( o1, o2 )
{
  var tmpText = o1.text;
  var tmpValue = o1.value;
  var tmpSelected = o1.selected;
  var tmpTitle = o1.title;
  o1.text = o2.text;
  o1.value = o2.value;
  o1.selected = o2.selected;
  o1.title = o2.title;
  o2.text = tmpText;
  o2.value = tmpValue;
  o2.selected = tmpSelected;
  o2.title = tmpTitle;
}

function sortSelect(selectToSort, idSuffix)
{
  var sortList = window["sort-list"+idSuffix];
  if ( sortList )
  {
    // copy option values into map
    var options = new Object();
    for (var i=0; i<selectToSort.options.length; i++)
    {
      options[selectToSort.options[i].value] = new Object();
    }

    // copy sort list options into select list if their value was available in original select list values
    selectToSort.options.length = 0;
    for (var i=0; i<sortList.length; i++)
    {
      if ( options[sortList[i].value] )
      {
        var newOption = new Option(sortList[i].text,sortList[i].value);
        newOption.title = sortList[i].title;
        selectToSort.options[selectToSort.options.length] = newOption;
      }
    }
  }
  else
  {
    // copy options into an array
    var options = new Array();
    for (var i=0; i<selectToSort.options.length; i++)
    {
      options[i] = { optText:selectToSort.options[i].text, optValue:selectToSort.options[i].value, optTitle:selectToSort.options[i].title };
    }

    options.sort(sortOptionsFunction);

    // copy sorted options from array back to select box
    selectToSort.options.length = 0;
    for (var i=0; i<options.length; i++)
    {
      var newOption = new Option(options[i].optText, options[i].optValue);
      newOption.title = options[i].optTitle;
      selectToSort.options[selectToSort.options.length] = newOption;
    }
  }
}

function sortOptionsFunction(record1, record2)
{
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(1);
    if (value1 < value2) return(-1);
    return(0);
}

function updateInputs(form,toSelect,inputName)
{

  for ( var i=0; i < toSelect.options.length; i++ ) {
    var value = toSelect.options[i].getAttribute("value");
    if ( value == null )
      value = toSelect.options[i].getAttribute("text");
    addHiddenField(form, inputName, value );
  }
}

function updateEditorInputs(form,editorName,inputName)
{
    // Get the editor instance that we want to interact with.
    var oEditor = FCKeditorAPI.GetInstance(editorName) ;

    // Get the editor contents in XHTML.
    var value = oEditor.GetXHTML( true ) ;		// "true" means you want it formatted.
    addHiddenField(form,inputName,value);

}

function addHiddenField(objForm, strFieldName,strFieldValue)
{
  var objInput = document.createElement("INPUT");
  objInput.type = "hidden";
  objInput.name = strFieldName;
  objInput.value = strFieldValue;
  //alert(strFieldValue);
  objForm.appendChild(objInput);
}

function toggleView(id)
{
  var div = document.getElementById('toggle-div-' + id );
  var link = document.getElementById('toggle-link-' + id );
  if ( div.style.display == 'block' )
  {
    div.style.display = 'none';
    link.childNodes[0].nodeValue = "--open--";
  }
  else
  {
    div.style.display = 'block';
    link.childNodes[0].nodeValue = "--hide--";
  }
}

var allSubmitHandlers = new Object();
function addSubmitHandler(formName,handler)
{
  var handlers = allSubmitHandlers[formName];
  if ( handlers == null )
  {
    handlers = new Array();
    allSubmitHandlers[formName] = handlers;
  }
  handlers[handlers.length] = handler;
}

function callSubmitHandlers(formName)
{
  var handlers = allSubmitHandlers[formName];
  if ( handlers != null )
  {
    for ( var i=0; i < handlers.length; i++ )
      handlers[i]();
  }
}

var allClickHandlers = new Object();
function addClickHandler(elementId,handler)
{
  var handlers = allClickHandlers[elementId];
  if ( handlers == null )
  {
    handlers = new Array();
    allClickHandlers[elementId] = handlers;
  }
  handlers[handlers.length] = handler;
}

function callClickHandlers(elementId)
{
  var handlers = allClickHandlers[elementId];
  if ( handlers != null )
  {
    for ( var i=0; i < handlers.length; i++ )
      handlers[i]();
  }
}

function submitForm(formName)
{
  if ( document[formName].onsubmit )
    document[formName].onsubmit();
  document[formName].submit();
}

function getSelection (e) {
    if (!e) return;

    if (document.selection)
        return document.selection.createRange().text;
    else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        return e.value.substring(start, end);
    }
}

function setSelection (e, v) {
    if (document.selection)
        document.selection.createRange().text = v;
    else if(canFormat) {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        var top = e.scrollTop;
        e.value = e.value.substring(0, start) + v + e.value.substr(end, length);
        e.scrollTop = top;
    } else {
        e.value = e.value + v;
    }
}

function formatStr (e, v) {
    if (!canFormat) return;
    var str = getSelection(e);
    e.focus();
    setSelection(e, '<' + v + '>' + str + '</' + v + '>');
    /*e.scrollTop = e.scrollHeight;*/
    return false;
}

function insertImage (e) {
    if (!canFormat) return;
    var my_link = prompt('Enter URI:', '/');
    if (my_link != null)
        setSelection(e, '<img src="' + my_link + '" />');
    return false;
}

function insertBreak (e) {
    if (!canFormat) return;
    setSelection(e, '<br />');
    return false;
}

function insertLink (e, isMail) {
    if (!canFormat) return;
    var str = getSelection(e);
    var my_link = isMail ? prompt('Enter email address:', '') : prompt('Enter URL:', '/');
    if (isMail) my_link = 'mailto:' + my_link;
    if (my_link != null)
        setSelection(e, '<a href="' + my_link + '">' + str + '</a>');
    return false;
}

function insertExternalLink (e) {
    if (!canFormat) return;
    var str = getSelection(e);
    var my_link = prompt('Enter URL:', 'http://');
    if (my_link != null)
        setSelection(e, '<a href="' + my_link + '">' + str + '</a>');
    return false;
}

function insertString (e, string) {
    if (!canFormat) return;
    setSelection(e, string);
    return false;
}

function toggleFallbacks(linkId, showLabel, hideLabel)
{
  var link = document.getElementById(linkId);
  if (link.innerHTML == showLabel)
  {
    showFallbacks();
    link.innerHTML = hideLabel;
  }
  else
  {
    hideFallbacks();
    link.innerHTML = showLabel;
  }
}

function hideFallbacks()
{
  var elements = findFallbackContent();
  for (var i = 0; i < elements.length; i++)
  {
    Element.hide(elements[i]);
  }
  createCookie('hideEditFormFallbacks', 'true');
}

function showFallbacks()
{
  var elements = findFallbackContent();
  for (var i = 0; i < elements.length; i++)
  {
    Element.show(elements[i]);
  }
  eraseCookie('hideEditFormFallbacks');
}

function findFallbackContent()
{
  return Element.getElementsByClassName('edit-widgets', 'fallback-content');
}

// Cookie functions from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = 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(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
// End cookie functions

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

/*
 * Add "over" class to all buttons which have the "js-has-hover" class name.  The "over" class
 * can be used to replicate the :hover psuedo-class that applies to <a/> tags.
 */
function addButtonHoverBehavior(event)
{
  var className = 'over';
  var buttons = $$('button.js-has-hover');
  for (var i = 0; i < buttons.length; i++)
  {
    Event.observe(buttons[i], 'mouseover', function(event)
    {
      Element.addClassName(Event.element(event), className);
    });
    Event.observe(buttons[i], 'mouseout', function(event)
    {
      Element.removeClassName(Event.element(event), className);
    });
    Event.observe(buttons[i], 'click', function(event)
    {
      Element.removeClassName(Event.element(event), className);
    })
  }
}

Event.observe(window, 'load', addButtonHoverBehavior);

function setRecurrenceFrequencey(key)
{
  var frequency = $(key + 'frequency');

  $(key + 'interval--fields').style.display = 'none';
  $(key + 'daysofweek--fields').style.display = 'none';
  $(key + 'month--fields').style.display = 'none';
  $(key + 'end--fields').style.display = 'none';

  if (frequency.value != '')
  {
    $(key + 'interval--fields').style.display = 'block';
    $(key + 'end--fields').style.display = 'block';

    var intervalLabel = $(key + 'interval--label');

    if (frequency.value == 'DAILY')
      intervalLabel.innerHTML = 'day(s)';
    if (frequency.value == 'WEEKLY')
    {
      intervalLabel.innerHTML = 'week(s)';
      $(key + 'daysofweek--fields').style.display = 'block';
    }
    if (frequency.value == 'MONTHLY')
    {
      intervalLabel.innerHTML = 'month(s)';
      $(key + 'month--fields').style.display = 'block';
    }
  }

  updateRecurrence(key);
}

function updateRecurrence(key)
{
  var frequency = $(key + 'frequency');

  var field = $(key + 'text');

  var interval = $(key + 'interval');
  var daysOfWeek = $(key + 'daysofweek');
  var daysOfMonth = $(key + 'daysofmonth');

  var end = $(key + 'end');

  field.value = '';
  if (frequency.value == '') return;

  field.value += 'FREQ=' + frequency.value + ';';
  field.value += 'INTERVAL=' + interval.value + ';';
  if (frequency.value == 'WEEKLY')
  {
    var selectedDaysOfWeek = new Array();
    for (var i = 0; i < daysOfWeek.length; i++)
      if (daysOfWeek[i].selected)
        selectedDaysOfWeek.push(daysOfWeek[i].value);
    field.value += 'BYDAY=' + selectedDaysOfWeek.join(',') + ';WKST=SU;'
  }
  if (frequency.value == 'MONTHLY')
  {
    if ($(key + 'daysofmonth--toggle').checked)
    {
      var selectedDaysOfMonth = new Array();
      for (var i = 0; i < daysOfMonth.length; i++)
        if (daysOfMonth[i].selected)
          selectedDaysOfMonth.push(daysOfMonth[i].value);
      field.value += 'BYMONTHDAY=' + selectedDaysOfMonth.join(',') + ';';
    }
    else
      field.value += 'BYDAY=' + $(key + 'week').value + $(key + 'day').value + ';';
  }
  if (end.value == 'UNTIL' && $(key + 'until').value != '')
  {
    var untilData = $(key + 'until').value.split('-');
    var date = new Date(untilData[0], untilData[1] - 1, untilData[2]);
    field.value += 'UNTIL=' + date.getFullYear() + pad(date.getMonth() + 1, 2) + pad(date.getDate(), 2) + ';';
  }
}

function selectDaysOfWeekFields(key)
{
  $(key + 'daysofweek--toggle').checked = 'checked';
  $(key + 'daysofmonth--toggle').checked = false;
  $(key + 'daysofmonth').disabled = 'disabled';
  $(key + 'week').disabled = false;
  $(key + 'day').disabled = false;

  updateRecurrence(key);
}

function selectDaysOfMonthFields(key)
{
  $(key + 'daysofmonth--toggle').checked = 'checked';
  $(key + 'daysofweek--toggle').checked = false;
  $(key + 'daysofmonth').disabled = false;
  $(key + 'week').disabled = 'disabled';
  $(key + 'day').disabled = 'disabled';

  updateRecurrence(key);
}

function setRecurrenceEnd(key)
{
  var end = $(key + 'end');
  $(key + 'until--fields').style.display = 'none';

  if (end.value == 'UNTIL')
    $(key + 'until--fields').style.display = 'block';

  updateRecurrence(key);
}

function pad(number, length)
{
  var str = '' + number;
  while (str.length < length)
      str = '0' + str;
  return str;
}

function setRecurrenceSelectedState(key)
{
  var recurrence = new Object();
  var recurrenceFields = $(key + 'text').value.split(';');
  for (var i = 0; i < recurrenceFields.length; i++)
  {
    var recurrenceField = recurrenceFields[i];
    recurrence[recurrenceField.split('=')[0]] = recurrenceField.split('=')[1];
  }
  if (recurrence['FREQ'])
    $(key + 'frequency').value = recurrence['FREQ'];
  if (recurrence['INTERVAL'])
    $(key + 'interval').value = recurrence['INTERVAL'];
  if (recurrence['BYDAY'])
  {
    var daysOfWeekString = recurrence['BYDAY'];
    var daysOfWeekSelect = $(key + 'daysofweek');

    for (var i = 0; i < daysOfWeekSelect.length; i++)
      if (daysOfWeekString.indexOf(daysOfWeekSelect[i].value) != -1)
        daysOfWeekSelect[i].selected = 'selected';
  }
  if (recurrence['BYDAY'])
  {
    $(key + 'daysofmonth--toggle').checked = false;
    $(key + 'daysofweek--toggle').checked = 'checked';
    var day = recurrence['BYDAY'].slice(-2);
    var week = recurrence['BYDAY'].replace(day, '');

    $(key + 'week').value = week;
    $(key + 'day').value = day;
  }
  else if (recurrence['BYMONTHDAY'])
  {
    $(key + 'daysofmonth--toggle').checked = 'checked';
    var daysOfMonthString = recurrence['BYMONTHDAY'];
    var daysOfMonthSelect = $(key + 'daysofmonth');

    for (var i = 0; i < daysOfMonthSelect.length; i++)
      if (daysOfMonthString.indexOf(daysOfMonthSelect[i].value) != -1)
        daysOfMonthSelect[i].selected = 'selected';
  }
  if (recurrence['UNTIL'])
  {
    var untilString = recurrence['UNTIL'];
    $(key + 'end').value = 'UNTIL';
    $(key + 'until').value = untilString.substring(0, 4) + '-' + untilString.substring(4, 6) + '-' + untilString.substring(6, 8);
  }
  
  setRecurrenceFrequencey(key);
  setRecurrenceEnd(key);
}

function setDailyRecurrenceSelectedState(key)
{
  var recurrence = new Object();
  var recurrenceFields = $(key + 'text').value.split(';');
  for (var i = 0; i < recurrenceFields.length; i++)
  {
    var recurrenceField = recurrenceFields[i];
    recurrence[recurrenceField.split('=')[0]] = recurrenceField.split('=')[1];
  }
  if (recurrence['UNTIL'])
  {
    var untilString = recurrence['UNTIL'];
    $(key + 'end').value = 'UNTIL';
    $(key + 'until').value = untilString.substring(0, 4) + '-' + untilString.substring(4, 6) + '-' + untilString.substring(6, 8);
  }
}

function setSuggestedSelectedState(key)
{
  var select = $(key + 'select');
  var text = $(key + 'text');
  var input = $(key + 'input');

  var hasOption = false;
  for (var i = 0; i < select.options.length; i++)
    if (select.options[i].value == input.value)
    {
      select.options[i].selected = 'selected';
      hasOption = true;
    }
  if (!hasOption)
    text.value = input.value;
}

function updateSuggestedSelect(key)
{
  var select = $(key + 'select');
  var text = $(key + 'text');
  var input = $(key + 'input');

  input.value = select.value;
  text.value = '';
}

function updateSuggestedText(key)
{
  var select = $(key + 'select');
  var text = $(key + 'text');
  var input = $(key + 'input');

  input.value = text.value;
  select.value = '';
}