
// setup "namespaces"
if (!I1) var I1 = {}
if (!I1.UI) I1.UI = {}

document.observe('dom:loaded', setUp);
Event.observe(window, 'load', adjustHeight);

var MenuParent;
var MenuParentHeight = 0;

function adjustHeight() {
  var contentHeight = $('content').getHeight();

  //fix content height issue
  if (MenuParentHeight > contentHeight) {
    $('content').setStyle({ 'height': MenuParentHeight });
  }
}

function setUp() {

  setupCalendars();
  setupSiteWidth();

  //Handle back button click
  var backButton = $('back-button');
  if (backButton) {
    backButton.observe('click', function() { history.back(1) });
  }

  //Handle Page Controls
  var pageControlButton = $('edit-page-controls');
  if (pageControlButton) {
    pageControlButton.observe('click', function(ev) {

      //Show and hide buttons
      var PageControl = $$('.page-control');
      PageControl.invoke('toggle');
      PageControl.invoke('highlight');

    });
  }

}

function setupSiteWidth() {
  //Fix width of container when content width extends beyond the viewport
  var navWidth;
  MenuParent = $('menu-parent');

  var contentWidth = $('content').getWidth();

  if (MenuParent) {
    navWidth = MenuParent.getWidth() + 12;
    MenuParentHeight = MenuParent.getHeight();
  }

  var adjustWidth = navWidth + contentWidth;

  //adjust size of page
  if (adjustWidth) {
    $('container').setStyle({ 'width': adjustWidth + 'px' });

    var foot = $('footer');
    if (foot) foot.setStyle({ 'width': adjustWidth + 'px' });
  }
}

//Added popup window functions for excel print and calendar
function PrintPopUp(slocation) {
  window.open(slocation, "PrintableVersion", "top=10,left=10,resizable=yes,toolbar=yes,statusbar=yes,scrollbars=yes");
}
function ExcelPopUp(slocation) {
  window.open(slocation, "Excel", "width=500,height=340,top=10,left=10,resizable=yes,toolbar=yes,statusbar=yes,scrollbars=yes");
}

function PopupAny(popupLink) {
  void window.open(popupLink, 'winPopupAny', 'width=600,height=480,top=10,left=10,scrollbars=yes,resizable=yes');
}

function CalendarPopUp(slocation) {
  window.open(slocation, "remote", "width=200,height=240,top=10,left=10");
}

function AutocompleteHelper(grp, options) {
  var options = Object.extend({
    indicator: grp + '_busy',
    dynamParams: 'username',
    paramName: 'autoCompleteParam'
  }, options || {});

  new Ajax.Autocompleter(
		grp,
		grp + '_results',
		grp + '.asp',
		options
	)
}

function InPlaceEditHelper(grp) {
  pg = grp.split('_')[0]

  new Ajax.InPlaceEditor(
		grp,
		'save_' + pg + '.asp',
		{ cols: 10, highlightcolor: '#4784ff', cancelText: 'no', paramName: grp }
	)
}

function handleCalendarSelect(type, args, obj) {
  var dates = args[0];
  var date = dates[0];
  var year = date[0], month = date[1], day = date[2];

  obj[0].value = month + '/' + day + '/' + year;
  obj[1].hide();
}


function setupCalendars() {

  //get every input date field
  $$('input.date').each(function(field, index) {

    var calendarContainer = new Element('div')
		                .setStyle({ position: 'absolute' })
		                .addClassName('calendar-container')
		                .hide();

    field.insert({ after: calendarContainer });

    var calendar = new YAHOO.widget.Calendar(calendarContainer, {
      title: 'Choose a date:',
      close: true
    });
    calendar.selectEvent.subscribe(handleCalendarSelect, [field, calendar], true);
    calendar.render();

    field
    		            .writeAttribute('autocomplete', 'off')
    		            .addClassName('widgets-calendar-field')
    		            .observe('click', function() {
    		              $$('.calendar-container').invoke('hide');
    		              calendar.show();
    		            });
  });
}

// US phone input mask, tabbing
I1.UI.USPhones = {
  defaults: {
    parent: 'ContactFields',
    fields: ['HomePhone', 'WorkPhone', 'Cell', 'FaxNumber']
  },

  initialize: function(options) {
    var options = Object.extend(options || {}, this.defaults);
    document.observe('dom:loaded', this.setup.bind(this, options.parent, options.fields));
  },

  setup: function(parent, fields) {
    var field, parent = $(parent);
    fields.each(this.listen.bind(this, parent));
  },

  listen: function(parent, prefix) {
    for (var p = 1; p <= 3; p++) {
      field = parent.select('input[name=' + prefix + p + ']').first();
      field.observe('keyup', this.focus.curry(prefix, p));
    }
  },

  focus: function(name, index, ev) {
    var key = ev.keyCode || e.which;
    if (!Event.KEY_SHIFT) Event.KEY_SHIFT = 16;
    if (key == Event.KEY_TAB || key == Event.KEY_SHIFT) return;

    var max = 4, next;
    if (index < 3) {
      max = 3;
      next = name + (index + 1);
    }

    if (this.value.length == max && next) document.forms.Form1[next].focus();
  }
}

// ajax company name autocompletion, address population
I1.UI.CompanyAutocomplete = {
  defaults: {
    form: 'Form',
    id: 'FirmTableID',
    textbox: 'company',
    results: 'company-results',
    menu: 'company-options',
    address: 'company-use',
    remove: 'company-remove',
    indicator: 'company-indicator',
    client: 0,
    fields: ['Address', 'Address1', 'Address2', 'City', 'StateID', 'StateName', 'ZipCode', 'Zip4', 'CountryID', 'CountryName', 'FZip', 'Province']
  },

  initialize: function(options) {
    var options = Object.extend(this.defaults, options || {});

    document.observe('dom:loaded', this.listen.bind(this, options));

    document.observe('dom:loaded', function() {
      $(options.address).observe('click', this.fetch.bind(this, options));
    } .bind(this));

    document.observe('dom:loaded', function() {
      $(options.remove).observe('click', this.reset.bind(this, options));
    } .bind(this));
  },

  listen: function(options) {
    new Ajax.Autocompleter(options.textbox, options.results, 'ListMan/FirmListManPost.asp?ClientID=' + options.client, {
      paramName: 'FirmTxt',
      method: 'GET',
      indicator: options.indicator,
      afterUpdateElement: function(text, li) {
        this.map('', options);

        $(options.id).value = li.id;
        $(options.menu).show();
      } .bind(this)
    });
  },

  fetch: function(options, ev) {
    if (ev) ev.stop();

    var id = $F(options.id);
    if (id == '0') return;
    
    var textbox = $(options.textbox);
    if (textbox) textbox.disable();
    
    var indicator = $(options.indicator);
    if (indicator) indicator.show();
    
    this.map('', options);

    new Ajax.Request('FirmAjax.asp?id=' + id, {
      method: 'GET',
      onComplete: function(response) {
        var firm = response.responseText.evalJSON().firm[0];
        this.map(firm, options);

        textbox.enable();
        indicator.hide();
      } .bind(this)
    });
  },

  map: function(firm, options) {
    options.fields.each(function(field) {
      //document.forms[options.form][field].value = (firm == '') ? '' : firm[field.toLowerCase()];

      var val = (firm == '') ? '' : firm[field.toLowerCase()];
      if(val == '' && field.toLowerCase() == 'stateid') {
        val = 0;
      }
      
      var label;
      var input = document.forms[options.form][field];
      if(input) {
          input.value = val;

          label = $(field + 'Name');
      } else {
          label = $(field);
      }

      if(label) label.update(val);
      
    });
  },

  reset: function(options, ev) {
    if (ev) ev.stop();

    this.map('', options);

    $(options.textbox).value = '';
    $(options.id).value = 0;
    $(options.menu).hide();
  }
}
