//Event.observe(document, 'dom:loaded', function()
Event.observe(window,'load', function() {
  if (Prototype.Browser.IE) {
	if ($('share-wrap')) {
      $('share-wrap').observe('mouseenter', function(event) {
        this.addClassName('over');
		if(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6 && $('share-dd'))
		{
		  $('share-dd').addClassName('over');
		}
      });
      $('share-wrap').observe('mouseleave', function(event) {
        this.removeClassName('over');
		if(parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6 && $('share-dd'))
		{
		  $('share-dd').removeClassName('over');
		}
      });
    }
  }
  if (Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6) {
    if ($$('#nav li')) {
      $$('#nav li').each(function(e) {
        e.observe('mouseenter', function(event) {
          this.addClassName('over');
        });
        e.observe('mouseleave', function(event) {
          this.removeClassName('over');
        });
      });
    }
    if ($('subscribe')) {
      $('subscribe').observe('mouseenter', function(event) {
        this.addClassName('over');
      });
      $('subscribe').observe('mouseleave', function(event) {
        this.removeClassName('over');
      });
    }
    if ($$('.dynamic-button')) {
      $$('.dynamic-button').each(function(e) {
        e.observe('mouseenter', function(event) {
          this.addClassName('dynamic-button-over');
        });
        e.observe('mouseleave', function(event) {
          this.removeClassName('dynamic-button-over');
        });
      });
    }
    if ($$('.minor')) {
      $$('.minor').each(function(e) {
        e.observe('mouseenter', function(event) {
          this.addClassName('minor-over');
        });
        e.observe('mouseleave', function(event) {
          this.removeClassName('minor-over');
        });
      });
    }
    if ($$('#useful-information li')) {
      $$('#useful-information li').each(function(e) {
        e.observe('mouseenter', function(event) {
          this.addClassName('over');
        });
        e.observe('mouseleave', function(event) {
          this.removeClassName('over');
        });
      });
    }
    
    if ($$('#copyright li:first-child')) {
      $$('#copyright li:first-child').each(function(e) {
        e.addClassName('first-child');
      });
    }
  }

  if ($('q')) {
    $('q').observe('focus', function(event) {
      if (this.value=='Search') {
        this.value='';
      }
    });
    $('q').observe('blur', function(event) {
      if (this.value=='') {
        this.value='Search';
      }
    });
  }

  if ($('q-inline')) {
    $('q-inline').observe('focus', function(event) {
      if (this.value=='Search') {
        this.value='';
      }
    });
    $('q-inline').observe('blur', function(event) {
      if (this.value=='') {
        this.value='Search';
      }
    });
  }

  if ($$('a[href$="pdf"]')) {
    $$('a[href$="pdf"]').each(function(e) {
      e.observe('click', function(event) {
        window.open(e.href);
        Event.stop(event);
      });
    });
  }

  if ($$('a[class="external"]')) {
    $$('a[class="external"]').each(function(e) {
      e.observe('click', function(event) {
        window.open(e.href);
        Event.stop(event);
      });
    });
  }

  if ($('print-page')) {
    $('print-page').observe('click', function(event) {
      window.print();
      Event.stop(event);
    });
  }

  if ($$('.popup')) {
    $$('.popup').each(function(link) {
      link.observe('click', function(event) {

        var width  = 650;
        var height = 490;
        var left   = (screen.width  - width)/2;
        var top    = (screen.height - height)/2;

        newwin = window.open(this.href, "mapwindow","status=no,toolbar=no,resizable=no,scrollbars=no,width="+width+",height="+height+",top="+top+",left="+left);
        if (window.focus) {newwin.focus()}
        Event.stop(event);
      });
    });
  }
  
  if ($$('a.view-example')) {
    $$('a.view-example').each(function(link) {
      link.observe('click', function(event) {
        if( $$('.on a.view-example') ){
          $$('.on a.view-example').each(function(die){
            die.next('span').hide();
            die.up().removeClassName('on');
          });
        }
        var link = this;
        var example = this.next('span');
        var closeExample = function(e) {
          example.hide();
          link.up().removeClassName('on');
          Event.stop(e);
        };
        if( ! link.hasClassName('on') ){
          Event.stopObserving(document.body, 'click', closeExample);
          Event.observe(document.body, 'click', closeExample);
        }
        example.toggle();
        link.up().toggleClassName('on');
        Event.stop(event);
      });
    });
  };

/**
 * Flipbook links
 */
  if ($$('.read-flipbook').length > 0)
  {
   $$('.read-flipbook').invoke('observe', 'click', function(event) {
      var title = null;
      var flipbook_id = null;

      flipbook_id = this.getAttribute('rel');
      title = $$('.downloads .filetype-pdf a').first().innerHTML;
      window.open("/flipbook/index.php?book=" + flipbook_id, "Flipbook", "width=1000, height=700");

      if (pageTracker) pageTracker._trackEvent('Flipbook Launch', 'Status Newsletter', title);
      event.stop();
    });
  }

  /**
   * Reset Form
   * Setup to work with old button styles
   */
  $$('#reset > a').invoke('observe', 'click', function(event) {
    event.stop();
    var form = event.target.up('form');

    form.select('.optional-field').each(function(element)
    {
      element.hide();
    });

    form.reset();
  });
  
});

function faq_toggle(container, btn, hide) {
  $(container).hide();
  $(btn).observe('click', function(event) {
    this.toggle();
    $(container).toggle();
    Event.stop(event);
  });
  $(hide).observe('click', function(event) {
    $(btn).toggle();
    $(container).toggle();
    Event.stop(event);
  });
}

function resetForm($target, $event) {
  if($event) Event.stop($event);
  
  $($target).select('.optional-field').each(function($element, $i) {
    $element.hide();
  });
  
  $($target).reset();
};

function track404error(url)
{
  if(pageTracker._trackEvent)
  {
    pageTracker._trackEvent('Pages Not Found', 'Frontend', url);
  }
}

var last_abn = false;
var abn_timeout = false;

function startVerifyABN(element, url)
{
  clearTimeout(abn_timeout);
  abn_timeout = setTimeout(verifyABN.curry(element, url), 600);
}

function verifyABN(element, url)
{
  var abn = element.value.replace(/[^0-9]+/gi, '');
  if(abn.length == 11 && abn!=last_abn)
  {
    last_abn = abn;
    new Ajax.Request(url, {
      method: 'post',
      parameters: 'abn=' + abn,
      onSuccess: function(t)
      {
        //console.log(t.responseText);
      }
    });
  }
}

function checkFound(element, other_id)
{
  if (element != null)
  {
    if(element.value == 'Other')
    {
      $(other_id).show();
    }
    else
    {
      $(other_id).hide();
    }
  }
}

/**
 * STAF Grants Module
 */
function organisationInformationStaf()
{
  var previous_assistance = new WidgetTable({
    table: 'grant_previous_assistance',
    field_type: 'input',
    total_field: 'grant_previous_assistance_total',
    keypress: true
  });
  $('add_grant_previous_assistance').observe('click', function(event){
    event.stop();
    previous_assistance.addTableRow('grant[previous_assistance]', 'tr_add_grant_previous_assistance', ['name', 'year', 'total'], 2);
  });

  var other_past_assistance = new WidgetTable({
    table: 'grant_other_past_assistance',
    field_type: 'input',
    total_field: 'grant_other_past_assistance_total',
    keypress: true
  });
  $('add_grant_other_past_assistance').observe('click', function(event){
    event.stop();
    other_past_assistance.addTableRow('grant[other_past_assistance]', 'tr_add_grant_other_past_assistance', ['name', 'year', 'total', 'organisation'], 4);
  });

  var other_applications = new WidgetTable({
    table: 'grant_other_applications',
    field_type: 'input',
    total_field: 'grant_other_applications_total',
    keypress: true
  });
  $('add_grant_other_applications').observe('click', function(event){
    event.stop();
    other_applications.addTableRow('grant[other_applications]', 'tr_add_grant_other_applications', ['organisation', 'total', 'date']);
  });

}

function initiativedetailsStaf()
{
  var breakdown = new WidgetTable({
    table: 'grant_breakdown',
    field_type: 'input',
    total_field: 'grant_breakdown_total',
    keypress: true
  });
  $('add_grant_breakdown').observe('click', function(event){
    event.stop();
    breakdown.addTableRow('grant[breakdown]', 'tr_add_grant_breakdown', ['item', 'num', 'unit', 'total']);
  });

}

/**
 * Community Grants Module
 */
function organisationDetailsStepThree()
{
  $('add_communitygrant_previous_assistance').observe('click', function(event){
    event.stop();
    addTableRow('communitygrant[previous_assistance]', 'communitygrant_previous_assistance', 'tr_add_communitygrant_previous_assistance', ['name', 'year', 'total'], 2);
  });
  watchTotals('#communitygrant_previous_assistance input', 'communitygrant_previous_assistance_total');

  $('wrap_organisation_previous_assistance').getElementsBySelector('input').each(function(element){
    $(element).observe('click', function(e){
      checkPreviousAssistance(this.value);
    });
    if(element.checked) checkPreviousAssistance(element.value);
  });

  checkFoundCommunity();
  $('communitygrant_found').observe('click', checkFoundCommunity);
}

function startDate()
{
  var cals = new Array();
  $$('img.trigger_calendar').each(function(element)
  {
    cals[element.getAttribute('rel')] = new scal(element.getAttribute('rel')+'cal', element.getAttribute('rel'), cal_options[element.getAttribute('rel')]);
    element.observe('click', function (event){
      cals[event.element().getAttribute('rel')].toggleCalendar();
    });
  });
}

function checkPreviousAssistance(value)
{
  if(value == 'Yes')
  {
    $('wrap_previous_assistance').show();
  }
  else
  {
    $('wrap_previous_assistance').hide();
  }
}

function checkFoundCommunity()
{
  if ($('communitygrant_found') != null)
  {
    if($('communitygrant_found').value == 'Other' || $('communitygrant_found').value == 'Other directory' || $('communitygrant_found').value == 'Personal referral')
    {
      $('wrap_found_other').show();
    }
    else
    {
      $('wrap_found_other').hide();
    }
  }
}

function addTableRow(field_name, table_id, last_row_id, columns, count_rows)
{
  var index = $$('#'+table_id+' select, #'+table_id+' input').last();
  index = index.id.replace(index.id.match(/(.*)_/)[0], '');
  index++;
  if ((index < count_rows) || count_rows==null)
  {
    var watch = null;
    var date_watch = null;
    var template = '<tr>';
    columns.each(function (s) {
      if(s=='year')
      {
        reference_years = $$('#'+table_id+' select').last().innerHTML;
        template += '<td><select class="inputText" name="' + field_name + '[' + index + '][' + s + ']" id="' + s + '_' + index + '">' + reference_years + '</select></td>';
      }
      else
      {
        template += '<td><input type="text" class="inputText" name="' + field_name + '[' + index + '][' + s + ']" id="' + table_id + '_' + s + '_' + index + '" /></td>';
      }
      if(s=='date')
      {
        date_watch = table_id + '_' + s + '_' + index;
      }
      else if(s=='total')
      {
        watch = table_id + '_' + s + '_' + index;
      }
    });
    template += '</tr>';
    var row = new Template(template).evaluate();
    $(last_row_id).insert({'before': row});
    if(watch != null)
    {
      $(watch).observe('change', calculateTotal.curry('#' + table_id + ' input', table_id + '_total'));
    }
    if(date_watch != null)
    {
      Calendar.setup({dateField: date_watch, dateFormat: '%d/%m/%Y'})
    }
  }
}

function watchTotals(selector, total_field)
{
  var number_keys = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105]
  $$(selector).each(function(element){
    if (element.name.match(/\[total\]$/))
    {
      element.observe('keyup', function(event){
        var code = event.keyCode;

        if (number_keys.indexOf(code) !== -1)
        {
            calculateTotal.curry(selector, total_field)
        }
      });

    }
  });
}

function calculateTotal(selector, total_field)
{
  var total = 0;
  $$(selector).each(function(element){
    if (element.name.match(/\[total\]$/))
    {
      field_value = parseFloat(element.value.replace(/[^0-9\.]/g, ''));
      total += isNaN(field_value) ? 0 : field_value;
    }
  });
  $(total_field).innerHTML = '$' + addCommas(total.toFixed(2));
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function saveChangesReturn()
{
  $('grant').action = $('grant').action + '?return';
  $('grant').submit();
  return false;
}

function saveChangesLogout()
{
  $('grant').action = $('grant').action + '?return&logout';
  $('grant').submit();
  return false;
}
