//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);
      });
    });
  }
  
});

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.value == 'Other')
  {
    $(other_id).show();
  }
  else
  {
    $(other_id).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)
{
  $$(selector).each(function(element){
    if (element.name.match(/\[total\]$/))
    {
      element.observe('change', 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 saveChangesLogout()
{
  $('grant').action = $('grant').action + '?logout';
  $('grant').submit();
  return false;
}