/**
 * copyright (c) 2007 Kjell-Inge Gustafsson kigkonsult
 * www.kigkonsult.se/iCalcreator/index.php
 * ical@kigkonsult.se
 * updated 20070705
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
**/
/** url to Ajax backend data load script */
var url          = 'http://www.kigkonsult.se/glossary/getdata.php';
var datafile     = 'glossary.txt'  // filename data file incl.path
/** width for number of TEXTAREA display columns, N.B. see divClass/divStyle width on top */
var textColWidth = 22;
/** if fixed number of data rows is wanted */
var textFixRows  = 7;
/** alt. if maximal number of data rows is wanted */
var textMaxRows  = 0;

var fontFamily   = "font-family:'Lucida Grande','Lucida Sans Unicode','Bitstream Vera Sans',Lucida,Arial,Geneva,Helvetica,sans-serif;";
var fontFamily2  = "font-family:arial,sans-serif;";
/** css class OR style for iCalGlossary DIV tag */
// N.B. see textColWidth!!!
// var divClass     = 'divClass';
var divStyle     = 'margin:0px;padding:0px;text-align:center;width:220px';
/** iCalGlossary css default font families */
/** text content, title (onMouseOver) and tag type for header, leave [headerText] empty if no header */
var headerText   = 'Calendaring Glossary';
var headeroMo    = 'Calendaring and Scheduling Consortium';
var headerTag    = 'div'; // alt 'div';
/** css class OR style for iCalGlossary [headerTag] tag */
// var headerClass  = 'headerClass';
var headerStyle  = 'background-color:silver;font-size:large;font-weight:bold;'; //  + fontFamily + 'font-size:medium;font-weight:bold;text-align:center;';
/** css class OR style for iCalGlossary SELECT tag */
// var selClass     = 'selClass';
var selStyle     = fontFamily + 'font-size:small;height:2em';
/** css class OR style for iCalGlossary (SELECT) OPTION tags */
// var optClass     = 'optClass';
var optStyle     = fontFamily + 'font-size:small;';
/** css class OR style for iCalGlossary TEXTAREA tag */
// var textClass    = 'textClass';
var textStyle    = 'border-bottom:black solid thin;'+fontFamily2+'font-size:small;padding-left: 5px';
/** don't change anything after this line, unless. . .*/
var divClass    = (typeof(divClass)    === 'undefined') ? '' : divClass;
var divStyle    = (typeof(divStyle)    === 'undefined') ? '' : divStyle;
var headerClass = (typeof(headerClass) === 'undefined') ? '' : headerClass;
var headerStyle = (typeof(headerStyle) === 'undefined') ? '' : headerStyle;
var selClass    = (typeof(selClass)    === 'undefined') ? '' : selClass;
var selStyle    = (typeof(selStyle)    === 'undefined') ? '' : selStyle;
var optClass    = (typeof(optClass)    === 'undefined') ? '' : optClass;
var optStyle    = (typeof(optStyle)    === 'undefined') ? '' : optStyle;
var textClass   = (typeof(textClass)   === 'undefined') ? '' : textClass;
var textStyle   = (typeof(textStyle)   === 'undefined') ? '' : textStyle;
 /** grab data from file.
  one line for every key+glossary item
  use %-character as separator in every file-row between key and data
  use '\n' in glossary item to mark newline
*/
var keys         = Array(); // array holding the keys
var texts        = Array(); // array holdning all texts
/** load 1st key+text to show */
keys[0]          = 'Select keyword to explain';
texts[0]         = 'From the Calendaring and Scheduling Consortium, Calendaring and Scheduling Glossary of Terms, http://www.calconnect.org/publications/calendaringglossaryv1.0.pdf';
function getData() {
  var ar = new Ajax.Request(
    url, {
      method:     'get',
      parameters: 'file=' + datafile,
      onFailure:  function(request) { ajaxError(request.statusText); },
      onComplete: function(request) { ajaxSuccess(request.responseXML); }
     }
  );
}
function ajaxError(text) {
  alert("Error when fetching data:\n" + text)
}
function ajaxSuccess(xml) {
  var keys   = xml.getElementsByTagName('key');
  var values = xml.getElementsByTagName('value');
  var key, value;
  for (var i=0; i < keys.length; i++) {
    key = new String( keys[i].firstChild.data );
    if (textColWidth > key.length)
      key = key.substr(0,textColWidth - 1);
    attr = $H({label: i+1, value: i+1, id: 'iCalGlossaryOpt'+(i+1)});
    addElement('iCalGlossaryKey', 'option', attr, key, optClass, optStyle);
    texts[i+1] = new String( values[i].firstChild.data );
  }
}
function addElement(parent, type, attributes, value, classOpt, styleOpt) {
  newElement = document.createElement(type);
  if (null != attributes)
    attributes.each(function(attr) {
      newElement.setAttribute(attr.key, attr.value);
    });
  if (null != value)
    newElement.innerHTML = value;
  $(parent).appendChild(newElement);
  if (newElement.id && (classOpt || styleOpt))
    setClassStyle(newElement.id, classOpt, styleOpt);
}
function formatText(text) {
      // format in rows
  var strarr  = text.split(' ');
  var word    = '';
  var wordlen = 0;
  var row     = '';
  var rowlen  = 0;
  var output  = new Array();
  var rowno   = 0;
  var nlpos   = 0;
  for (var elemix = 0; elemix < strarr.length; elemix++) {
    word      = new String(strarr[elemix]);
    wordlen   = word.length;
    nlpos     = word.search(/\\/);
    if (-1 < nlpos && 'n' == word.substr(nlpos+1,1)) {
      row    += ' ' + word.substr(0,nlpos-1) + '\n';
      output.push(row);
      rowno++;
      word    = word.substr(nlpos+2);
      wordlen = word.length;
      row     = '';
      rowlen  = 0;
    }
    if ((rowlen + 1 + wordlen) > textColWidth) {
      if (wordlen > textColWidth) {
        var firstchar = '';
        if (0 < rowlen)
          firstchar += ' ';
        while (wordlen > textColWidth) {
          row    += firstchar + word.substr(0, textColWidth - rowlen) + '\n';
          output.push(row);
          rowno++;
          word    = word.substr(textColWidth - rowlen);
          wordlen = word.length;
          row     = '';
          rowlen  = 0;
          firstchar = '';
        }
      }
      else {
        row    += '\n';
        output.push(row);
        rowno++;
      }
      row       = word;
    }
    else {
      if (0 < rowlen)
        row += ' ';
      row += word;
    }
    rowlen = row.length;
  }
  if (0 < rowlen) {
    if('\n' == row.substr(rowlen-1,1))
      row = row.substr(0, rowlen-1);
    output.push(row);
  }
  for(x=0;x<output.length;x++) {
    if ('\n' == output[x])
      output[x] = '';
  }
  return output;
}
function setClassStyle(id, classOpt, styleOpt) {
  if ('' < classOpt) {
    $(id).className = classOpt;
    return;
  }
  if ('' >= styleOpt)
    return;
  styleOpt.split(';').each(function(cssRule){
    if ('' >= cssRule)
      return;
    var theRule   = '';;
    var theStyle  = '';
    theRule = cssRule.split(':');
    theRule[0].split('-').each(function(word) {
      if ('' >= theStyle)
        theStyle  = word;
      else
        theStyle += word.substr(0,1).toUpperCase() + word.substr(1);
    });
    var cmd = '$("' + id + '").style.' + theStyle + '="' + theRule[1] + '";';
    eval(cmd);
  });
}
function setTextRows(rowno) {
  if ((typeof(textFixRows) == 'number') && (1 < textFixRows))
    rowno = textFixRows - 1;
  else if ((typeof(textMaxRows) == 'number') && (1 < textMaxRows) && (rowno > textMaxRows))
    rowno = textMaxRows - 1;
  return rowno;
}
function showText(ix) {
  var output = formatText(texts[ix]);
     // display info and set number of rows to display
  var s      = $("iCalGlossaryData");
  s.cols     = textColWidth;
  s.rows     = setTextRows(output.length);
  s.value    = '';
  output.each(function(row){ s.value += row; });
}
document.writeln("<div id='iCalGlossaryDiv'></div>");
setClassStyle('iCalGlossaryDiv', divClass, divStyle);
if ((typeof(headerText) !== 'undefined') && ('' < headerText)) {
  var attr = $H({id:'iCalGlossaryHeader',title:headeroMo});
  addElement('iCalGlossaryDiv', headerTag, attr, headerText, headerClass, headerStyle);
}
addElement('iCalGlossaryDiv', 'select', $H({id:'iCalGlossaryKey'}), '', selClass, selStyle);
if ($('iCalGlossaryKey').addEventListener)
  $('iCalGlossaryKey').addEventListener('change',function(e){showText($('iCalGlossaryKey').selectedIndex);}
,false);
else if ($('iCalGlossaryKey').attachEvent)
  $('iCalGlossaryKey').attachEvent('onChange', function (e){showText($('iCalGlossaryKey').selectedIndex);});
attr = $H({id:'iCalGlossaryOpt0',label:'0',value:'0',selected:'selected'});
addElement('iCalGlossaryKey', 'option', attr,keys[0],optClass,optStyle);
addElement('iCalGlossaryDiv', 'br');
var output = formatText(texts[0]);
attr = $H({id:'iCalGlossaryData',rows:setTextRows(output.length),cols:textColWidth});
addElement('iCalGlossaryDiv', 'textarea', attr, output, textClass, textStyle);
showText(0);
var style0  = 'height:8px;padding-left:10px;padding-right:10px;';
var style1l = 'cssFloat:left';
var style1r = 'cssFloat:right';
var style2  = fontFamily2 + 'font-size:x-small;letter-spacing:0.1em;color:black;text-decoration:none';
addElement('iCalGlossaryDiv','div', $H({id:'iCalinfoHolder'}), '', '', style0);
addElement('iCalinfoHolder','div', $H({id:'iCalDataHolder'}), '', '', style1l);
attr=$H({id:'iCalData',href:'http://www.calconnect.org/',title:'Calendaring and Scheduling Consortium'});
addElement('iCalDataHolder','a', attr, 'calconnect.org', '', style2);
addElement('iCalinfoHolder','div', $H({id:'iCalsponsorHolder'}), '', '', style1r);
attr=$H({id:'iCalsponsor',href:'http://www.kigkonsult.se/iCalcreator/index.php',title:'www.kigkonsult.se/iCalcreator'});
addElement('iCalsponsorHolder','a', attr, 'kigkonsult.se', '', style2);
getData();