var cname  = 'timeline';
var data   = null;
var title  = "";
var fields = new Array();
var emode  = "new";
var eitem  = null;
var months = [-1,31,29,31,30,31,30,31,31,30,31,30,31];
var loaded = false;
var catxml = null;

function createCookie(name,value,days)
{
  var expires = "";
  
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  value = encode64(value);

  document.cookie = name+"="+value+"; 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 decode64(c.substring(nameEQ.length,c.length));
    }
  }
  return null;
}

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

function addMainTitle()
{
  el = document.getElementById('form_title');
  if (el != null)
  {
    title = el.value;
    data = readCookie(cname);
    if (data != null)
    {
      analyzeCookie();
      createCookie(cname, 'title="' + title + '", fields=' + fields, 7);
      data = readCookie(cname);
    }
    else
    {
      createCookie(cname, 'title="' + title + '", fields=', 7);
    }
  }

  updateTimeLine();
}

function addTimeLineItem()
{
  el = document.getElementById('form_date');
  if (el != null)
  {
    var date = el.value;
    if (!validateDateFormat(date))
    {
      date = '';
      alert("Sjekk at datoen er skrevet i gyldig format (dd.mm.åååå f.eks: 01.06.2004)");
      return;
    }
  }

  el = document.getElementById('form_text');
  if (el != null)
  {
    var text = el.value;
  }

  // check if empty item
  if (date == 'DD.MM.ÅÅÅÅ' || text.length == 0)
  {
    alert("Du må fylle inn dato og tekst i skjemaet!");
    return;
  }

  // reset the fields
  el = document.getElementById('form_date');
  el.value = 'DD.MM.ÅÅÅÅ';
  el = document.getElementById('form_text');
  el.value = "";

  data = readCookie(cname);
  if (emode == 'new')
  {
    if (data != null)
    {
      analyzeCookie();

      // add the new timeline to the cookie
      var field = '("' + date + '", "' + text + '", "' + formatDate(date) + '")';
      fields[fields.length] = field;
    }
    else
    {
      // add the new timeline to the cookie
      var field = '("' + date + '", "' + text + '", "' + formatDate(date) + '")';
      fields[fields.length] = field;
    }

    createCookie(cname, 'title="' + title + '", fields=' + fields, 7);
    data = readCookie(cname);
  }
  else
  {
    // update the timeline item
    var field = '("' + date + '", "' + text + '", "' + formatDate(date) + '")';
    fields[eitem] = field;
    createCookie(cname, 'title="' + title + '", fields=' + fields, 7);
    data = null;
    eitem = null;
  }

  updateTimeLine();
}

function analyzeCookie()
{
  fields = new Array();
  if (data == null)
    return;
  var t_start = data.indexOf('", fields=');
  if (title == '')
    title = data.substring(7, t_start);

  var _fields = data.substring(t_start + 10, data.length);
  if (_fields.length != 0)
  {
    var elements = _fields.split('),(');

    for (i = 0; i < elements.length; i++)
    {
      var field = elements[i]
      if (i < (elements.length - 1) && elements.length > 1)
        field += ')';
      if (i > 0)
        field = '(' + field;

      fields[fields.length] = field;
    }
  }

  fields.sort(ByDate);
}

function editTimeLineItem(id)
{
  emode = "edit";
  eitem = id;

  if (id < fields.length)
  {
    var field = fields[id].replace('("', '').replace('")', '').split('", "');
    var date  = field[0];
    var text  = field[1];

    el = document.getElementById('form_date');
    el.value = date;
    el = document.getElementById('form_text');
    el.value = text;
  }
}

function deleteTimeLineItem(id)
{
  if (!confirm('Er du sikker på du vil fjerne denne?'))
    return false;

  var buffer = new Array();

  for (i=0; i < fields.length; i++)
  {
    if (i != id)
      buffer[buffer.length] = fields[i];
  }
  fields = buffer;
  createCookie(cname, 'title="' + title + '", fields=' + fields, 7);
  data = readCookie(cname);
  updateTimeLine();
}

function updateTimeLine()
{
  //clearCookie(cname);
  if (data == null)
  {
    data = readCookie(cname);
  }
  analyzeCookie();

  el = document.getElementById('timeline_title');
  el.innerHTML = title;
  el = document.getElementById('form_title');
  el.value = title;

  var output = "";
  for (i = 0; i < fields.length; i++)
  {
      var field = fields[i].replace('("', '').replace('")', '').split('", "');
      var date = field[0];
      var text = field[1];

      output += '<div class="row">\n';
      output += '<div class="item date">' + date + '</div>\n';
      output += '<div class="item text">' + text + '</div>\n';
      output += '<div class="item edit"><img src="/grf/jusplanlegger/button_gray_edit.gif" alt="Rediger" onclick="editTimeLineItem(' + i +')" /><img src="/grf/close_small.gif" alt="Fjern" onclick="deleteTimeLineItem(' + i + ')" /></div>\n';
      output += '</div>';
  }

  el = document.getElementById('timeline');
  el.innerHTML = output;
  emode = "new";
  eitem = null;

  if (!loaded)
    updateCategories();
}

function formatDate(date)
{
  if (date.length == 10)
  {
    day = date.substring(0, 2);
    month = date.substring(3, 5);
    year = date.substring(6, 10);
    return year + '' + month + '' + day;
  }
}

function ByDate(x, y)
{
  try
  {
    inxA = x.split('", "');
    inxB = y.split('", "');
    a = parseInt(inxA[2].substring(0,8));
    b = parseInt(inxB[2].substring(0,8));

    if (a < b)
      return 1;
    if (a > b)
      return -1;
  }
  catch (e)
  {}

  return 0;
}

function validateDateFormat(date)
{
  if (date.length == 10)
  {
    try
    {
      now = new Date();
      day = parseInt(parseInt(date.substring(0, 2)));
      month = parseInt(parseFloat(date.substring(3, 5)));
      year = parseInt(parseFloat(date.substring(6, 10)));

      if (month > 12)
        return false;

      if (!day > 0 || !month > 0 || !year > 0)
        return false;

      daysinmonth = months[month];
      if (daysinmonth == -1 || daysinmonth < day)
        return false;

      /*
      if (year > now.getFullYear() || (year == now.getFullYear() && (month-1) > now.getMonth()) || (year == now.getFullYear() && (month-1) == now.getMonth() && day > now.getDate()))
      {
        alert("Datoen du har lagt inn er i fremtiden.");
        return false;
      }
      */
    }
    catch (e)
    {
      alert(e);
      return false;
    }

    return true;
  }

  return false;
}

function updateCategories()
{
  // update content using ajax
  http_request = false;
  url          = "/Din_sak/categories.xml";
  loaded       = true;

  if (window.XMLHttpRequest)
  {
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType)
    {
      http_request.overrideMimeType('text/xml');
    }
  }
  else if (window.ActiveXObject)
  {
    try
    {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
         http_request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {}
    }
  }

  if (!http_request)
  {
    alert('Giving up - Cannot create an XMLHTTP instance');
    return false;
  }

  xml = '<?xml version="1.0" encoding="iso-8859-1"?><request />';

  http_request.open("POST", url, true);
  http_request.onreadystatechange = renderCategories;
  http_request.setRequestHeader("Content-Type", "application/xml");
  http_request.setRequestHeader("Connection", "Close");
  http_request.send(xml);
}

function renderCategories()
{
  if (http_request.readyState == 4)
  {
    if (http_request.status == 200)
    {
      var output = '<option value="">Velg kategori</option>';
      var xmldoc = http_request.responseXML;
      root = xmldoc.getElementsByTagName('items')[0];
      items = root.getElementsByTagName('item');
      catxml = items;
      for (i = 0; i < items.length; i++)
      {
        output += '<option value="' + i + '">' + catxml[i].firstChild.nodeValue + '</option>\n';
      }
      output = '<select name="cat" id="cat" onchange="updateCategoryList();">' + output + '</select>';

      el = document.getElementById('categorySelector');
      if (el != null)
      {
        el.innerHTML = output;
      }
    }
  }
}

function updateCategoryList()
{
  el = document.getElementById('cat');
  if (el != null)
  {
    box = document.getElementById('categories');
    category = el.value;
    if (category != '')
    {
      output = '';
      links = catxml[category].getElementsByTagName('link');
      for (i = 0; i < links.length; i++)
      {
        output += '<li>' + links[i].firstChild.nodeValue.replace('/', ' / ') + '</li>\n';
      }

      if (box != null)
        box.innerHTML = '<ul>' + output + '</ul>';
    }
    else
    {
      if (box != null)
        box.innerHTML = '';
    }
  }
}

/* date selection with three modes:
 *
 * mode 3: Date and time
 * mode 2: Date only
 * mode 1: Time only
 *
 */

//set todays date
Now = new Date();
NowDay = Now.getDate();
NowMonth = Now.getMonth();
NowYear = Now.getYear();
NowHour = Now.getHours();
NowMinute = Now.getMinutes();
if (NowYear < 2000) NowYear += 1900; //for Netscape

var d_locale = { 'en': {'MN_1':'January', 'MN_2':'February', 'MN_3':'March', 'MN_4':'April', 'MN_5':'May', 'MN_6':'June', 'MN_7':'July', 'MN_8':'August', 'MN_9':'September', 'MN_10':'October', 'MN_11':'November', 'MN_12':'December'},
                 'no': {'MN_1':'Januar', 'MN_2':'Februar', 'MN_3':'Mars', 'MN_4':'April', 'MN_5':'Mai', 'MN_6':'Juni', 'MN_7':'Juli', 'MN_8':'August', 'MN_9':'September', 'MN_10':'Oktober', 'MN_11':'November', 'MN_12':'Desember'},
                 'sv': {'MN_1':'Januari', 'MN_2':'Februari', 'MN_3':'Mars', 'MN_4':'April', 'MN_5':'Maj', 'MN_6':'Juni', 'MN_7':'Juli', 'MN_8':'Augusti', 'MN_9':'September', 'MN_10':'Oktober', 'MN_11':'November', 'MN_12':'December'},
                 'nl': {'MN_1':'Januari', 'MN_2':'Februari', 'MN_3':'Maart', 'MN_4':'April', 'MN_5':'Mei', 'MN_6':'Juni', 'MN_7':'Juli', 'MN_8':'Augustus', 'MN_9':'September', 'MN_10':'Oktober', 'MN_11':'November', 'MN_12':'December'}
               };
function dateSelect(Which, mode, from, to)
{
  if (from == null || from==0) from = 1995;
  if (to == null || to==0)  to = from + 20;
  try {
    var clang = currentLanguage;
  } catch(e) {
    var clang = system.lang;
  }
  if (!d_locale[clang])
  {
    var alangs = { 'nb':'no', 'nb-no':'no', 'nn':'no', 'nn-no':'no', 'se':'sv'};
    clang = alangs[clang];
    if (!d_locale[clang]) clang = 'en';
  }

  if (mode & 2)
  {
    document.write('<select name="' + Which + 'Day" id="' + Which + 'Day" onchange="checkField(\'' + Which + '\'); validateField(\'' + Which + '\')">');
    document.write(WriteRangeOptions(1, 31));
    document.write('</select>');

    document.write('<select name="' + Which + 'Month" id="' + Which + 'Month" onchange="checkField(\'' + Which + '\'); ChangeOptionDays(\'' + Which +'\')">');

    for (i=1; i <= 12; i += 1)
    {
      document.write("<option value=\"" + i + "\">" + d_locale[clang]['MN_'+i] + "</option>\n");
    }
    document.write('</select>');

    document.write('<select name="' + Which + 'Year" id="' + Which + 'Year" onchange="checkField(\'' + Which + '\'); ChangeOptionDays(\'' + Which +'\')">');
    document.write(WriteYearOptions(from, to));
    document.write('</select> ');
  }
  else
  {
    document.write('<input type="hidden" name="' + Which + 'Day" value="1" />');
    document.write('<input type="hidden" name="' + Which + 'Month" value="1" />');
    document.write('<input type="hidden" name="' + Which + 'Year" value="1970" />');
  }

  if (mode & 1)
  {
    document.write('<select name="' + Which + 'Hour" id="' + Which + 'Hour" onchange="checkField(\'' + Which + '\'); validateField(\'' + Which +'\')">');
    document.write(WriteRangeOptions(0, 23));
    document.write('</select>');


    document.write('<select name="' + Which + 'Minute" id="' + Which + 'Minute" onchange="checkField(\'' + Which + '\'); validateField(\'' + Which +'\')">');
    document.write(WriteRangeOptions(0, 59));
    document.write('</select>');
  }
  else
  {
    document.write('<input type="hidden" name="' + Which + 'Hour" value="0" />');
    document.write('<input type="hidden" name="' + Which + 'Minute" value="0" />');
  }

  document.write('<input type="hidden" name="' + Which + '" id="' + Which + '" value="" />');

}

//function for returning how many days there are in a month including leap years
function DaysInMonth(WhichMonth, WhichYear)
{
  var DaysInMonth = 31;
  if (WhichMonth == "4" || WhichMonth == "6" || WhichMonth == "9" || WhichMonth == "11") DaysInMonth = 30;
  if (WhichMonth == "2" && (WhichYear/4) != Math.floor(WhichYear/4))  DaysInMonth = 28;
  if (WhichMonth == "2" && (WhichYear/4) == Math.floor(WhichYear/4))  DaysInMonth = 29;

  return DaysInMonth
}

//function to change the available days in a months
function ChangeOptionDays(Which)
{
  DaysObject = eval("document.form1." + Which + "Day");
  MonthObject = eval("document.form1." + Which + "Month");
  YearObject = eval("document.form1." + Which + "Year");
  DaysObject = $('#' + Which + 'Day')[0];
  MonthObject = $('#' + Which + 'Month')[0];
  YearObject = $('#' + Which + 'Year')[0];

  Month = MonthObject[MonthObject.selectedIndex].value;
  Year = YearObject[YearObject.selectedIndex].Text;

  DaysForThisSelection = DaysInMonth(Month, Year);
  CurrentDaysInSelection = DaysObject.length;
  if (CurrentDaysInSelection > DaysForThisSelection)
  {
    for (i=0; i<(CurrentDaysInSelection-DaysForThisSelection); i++)
    {
      DaysObject.options[DaysObject.options.length - 1] = null
    }
  }
  if (DaysForThisSelection > CurrentDaysInSelection)
  {
    for (i=0; i<(DaysForThisSelection-CurrentDaysInSelection); i++)
    {
      NewOption = new Option(DaysObject.options.length + 1);
      DaysObject[DaysObject.length] = NewOption;
    }
  }
  if (DaysObject.selectedIndex < 0) DaysObject.selectedIndex == 0;

  validateField(Which)
}

//function to set options to today
function SetToToday(Which)
{
  DayObject = eval("document.form1." + Which + "Day");
  MonthObject = eval("document.form1." + Which + "Month");
  YearObject = eval("document.form1." + Which + "Year");

  DayObject = $('#' + Which + 'Day')[0];
  MonthObject = $('#' + Which + 'Month')[0];
  YearObject = $('#' + Which + 'Year')[0];

  if (DayObject.type && DayObject.type == 'hidden' && MonthObject.type && MonthObject.type == 'hidden' && YearObject.type && YearObject.type == 'hidden')
    return;

  for (i = 0; i < YearObject.length; i++)
  {
    if (YearObject[i].value == NowYear)
    {
      YearObject[i].selected = true;
    }
  }

  MonthObject[NowMonth].selected = true;

  HourObject = eval("document.form1." + Which + "Hour");
  if (HourObject && HourObject.type != 'hidden')
    HourObject[NowHour].selected = true;

  MinuteObject = eval("document.form1." + Which + "Minute");
  if(MinuteObject  && MinuteObject.type != 'hidden')
    MinuteObject[NowMinute].selected = true;

  ChangeOptionDays(Which);

  DayObject[NowDay-1].selected = true;
}

//function to set options to today
function SetDate(Which, year, month, day, hour, minute)
{

  DayObject   = eval("document.form1." + Which + "Day");
  MonthObject = eval("document.form1." + Which + "Month");
  YearObject  = eval("document.form1." + Which + "Year");
  DayObject = $('#' + Which + 'Day')[0];
  MonthObject = $('#' + Which + 'Month')[0];
  YearObject = $('#' + Which + 'Year')[0];
  var mode    = 1;

  if (DayObject.type != 'hidden' && MonthObject.type != 'hidden' && YearObject.type != 'hidden')
  {
    mode = 3;
    FirstYear = YearObject.options[0].value;
  }

  try
  {
    if (mode & 2)
    {
      if (year < FirstYear)
        year = NowYear;

      YearObject[ year - FirstYear].selected = true;
      MonthObject[month-1].selected = true;
    }

    HourObject = eval("document.form1." + Which + "Hour");
    if (HourObject && HourObject.type != 'hidden')
      HourObject[hour].selected = true;

    MinuteObject = eval("document.form1." + Which + "Minute");
    if(MinuteObject  && MinuteObject.type != 'hidden')
      MinuteObject[minute].selected = true;

    if (mode & 2)
    {
      ChangeOptionDays(Which);

      DayObject[day-1].selected = true;
    }
  }
  catch (e)
  {}
}

//function to write option years plus x
function WriteYearOptions(from, to)
{
  line       = "";
  YearsAhead = to - from;

  for (i=0; i < YearsAhead; i++)
  {
    line += "<option value=\"" + (from + i) + "\">";
    line += from + i;
  }

  return line;
}

//function to write option years plus x
function WriteHourOptions(YearsAhead)
{
  line = "";
  for (i=1; i<25; i++)
  {
    line += "<option>";
    line += i;
  }
  return line;
}

function WriteRangeOptions(start, end)
{
  line = "";
  for (i=start; i <= end; i++)
  {
    line += "<option>";
    if (i < 10)
      line += '0';
    line += i;
  }
  return line;
}

function validateField(Which)
{
  DayObject = eval("document.form1." + Which + "Day");
  MonthObject = eval("document.form1." + Which + "Month");
  YearObject = eval("document.form1." + Which + "Year");
  DayObject = $('#' + Which + 'Day')[0];
  MonthObject = $('#' + Which + 'Month')[0];
  YearObject = $('#' + Which + 'Year')[0];

  if (DayObject.type == 'hidden' && MonthObject.type == 'hidden' && YearObject.type == 'hidden')
    return;

  Day = DayObject[DayObject.selectedIndex].text;
  Month = MonthObject[MonthObject.selectedIndex].value;
  Year = YearObject[YearObject.selectedIndex].text;

  HourObject = eval("document.form1." + Which + "Hour");
  if (HourObject && HourObject.type != 'hidden')
    Hour = HourObject[HourObject.selectedIndex].text;
  else
    Hour = 0

  MinuteObject = eval("document.form1." + Which + "Minute");
  if (MinuteObject && MinuteObject.type != 'hidden')
    Minute = MinuteObject[MinuteObject.selectedIndex].text;
  else
    Minute = 0

  TextObject = eval("document.form1." + Which)
  TextObject = $('#' + Which)[0];
  TextObject.value = MonthObject.selectedIndex+1
}

function checkField(Which)
{
  var el = Which + 'ModeB';

  d = document.getElementById(el);

  if (d != null)
  {
    d.checked = true;
  }
}
