Array.prototype.show = function() {
  var l = this.length;
  while(l--) $(this[l]).show();
};
 
Array.prototype.hide = function() {
  var l = this.length;
  while(l--) this[l].hide();
};
 
Array.prototype.remove = function() {
  var l = this.length;
  while(l--) this[l].remove();
};

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
 
var Wizard = {
  onLoad: function() {
    if ($('store_coupon_warning')) {
      $('tooltip_content').innerHTML = $('store_coupon_warning').innerHTML;
      CMS.modalWindow.show();
    }
    if ($('israel_id_warning')) {
      $('tooltip_content').innerHTML = $('israel_id_warning').innerHTML;
      CMS.modalWindow.show();
    }
  },
  
  updateQuestions: function(q_id, value, w_id, p_id) {
    new Ajax.Request('/wizard/user_wizard/get_questions', {
      parameters: "q_id=" + q_id + "&value=" + value + "&wizard_pid=" + w_id + "&policy_pid=" + p_id
    });
  },
 
  showPromoRider: function(form_id, rider_dom_id, rider_id, is_admin) {
    Wizard.onSubmit(form_id);
    
    if (!is_admin && rider_dom_id && $(rider_dom_id) && !$(rider_dom_id).checked) {
      new Ajax.Request('/wizard/wizard_manager/show_promo_rider', {
        parameters: "form_id=" + form_id + "&rider_id=" + rider_id
      })
      return false;
    } else {
      if ($(form_id).getAttribute('exceeded') && $(form_id + '_exceed_warning')) {
        $('tooltip_content').innerHTML = $(form_id + '_exceed_warning').innerHTML;
        CMS.modalWindow.show();
        return false;
      } else {
        $(form_id).submit();
        return true;
      }  
    }
  },
   
  setPromoRider: function(form_id, rider_dom_id, selected) {
    CMS.modalWindow.close();
    if ($(rider_dom_id)) {
      $(rider_dom_id).checked = selected;
    }
    if ($(form_id)) {
      $(form_id).submit();
    }
  },
 
  // skip param used to avoid updating total price by js
  addPolicyConfigListeners: function(skip, container) {
    var parent = (container && $(container)) ? $(container) : window.document;
    Event.observe(parent, 'click', function(event) {
      var el = Event.element(event);
      if (el.getAttribute('rider')) {
        if(el.getAttribute('group')) {
          el.up('li').select('[group='+ el.getAttribute('group') + ']').each(function(item) {
            if (item != el) {
              item.checked = false;
            }
          });
          if (el.getAttribute('remote_form_id')) {
            Wizard.remoteUpdatePolicyPrice(el.getAttribute('remote_form_id'));
          }  
        }
        Wizard.updatePolicyPrice(el.up('.policy_container'), skip);
      }
    });
  },
  
  // skip param used to avoid updating total price by js
  updatePolicyPrice: function(policy_container, skip) {
    var sum = 0;
    var pc = $(policy_container);
    pc.select('[rider]').each(function(item) {
      var c = item.nodeName.toLowerCase() == 'input';
	  var container = item.up('.rider_summary');
	  if(c && item.checked || !c) {
        sum += parseFloat(item.getAttribute('rider'));
		$(item.id + '_value').show();
		if (container) { container.setStyle({'fontWeight':'bold'}); }
      } else {
		$(item.id + '_value').hide();
		if (container) { container.setStyle({'fontWeight':'normal'}); }
	  }
    } );
    pc.select('[policy]').each(function(item) {
      sum += parseFloat(item.getAttribute('policy'));
    });
    pc.select('[discount]').each(function(item) {
      sum -= parseFloat(item.getAttribute('discount'));
    });
    if (!skip) {
      $(pc).select('[total]')[0].innerHTML = sum.toFixed(2);
    }
  },
  
  remoteUpdatePolicyPrice: function(form_id) {
    if (!$(form_id)) { return true; };
    
    $(form_id).setAttribute('target', form_id + '_updater');
    $(form_id + '_in_iframe').value = 'true';
    $(form_id).submit();
    $(form_id).removeAttribute('target');
    $(form_id + '_in_iframe').value = '';
  },
 
  onSubmit: function(form_id, hide_buttons) {
    if (hide_buttons) {
      if ($('form_buttons')) { 
        $('form_buttons').hide();
      }
      if ($('processing'))   { 
        $('processing').show();
      }
    }
    var f = $(form_id);
    if (!f) {
      return true;
    }
 
    if (s = $('store_id')) {
      f.action = f.action + '&store_id=' + s.value.trim();
    }
    if (s = $('employee_id') ) {
      f.action = f.action + '&employee_id=' + s.value.trim();
    }
    return true;
  },
 
  showEmployeeForm: function() {
    $('helped_by_form').show();
    $('helped_by_btn').hide();
  },
 
  hideEmployeeForm: function() {
    $('helped_by_form').hide();
    $('helped_by_btn').show();
  },

  print: function() {
    window.print();
  },
  
  showTab : function(showDiv, el){
    $$('.tab_container').each(function(s){
      s.hide(); s.removeClassName('current_div')
    });
    $$('#tabs_menu li').each(function(s){
      s.removeClassName('active')
    })
    $(showDiv).show();
    //console.log($$('.utilies_menu li'));
    $(el).up().addClassName('active');
    $(showDiv).addClassName('current_div');
  },

  scrollTo: function(elem) {
    var el = $(elem);
    if(el) { 
      el.scrollTo();
    }
  },

  showEmailForm: function() {
    $('email_value').hide();
    $('email_form').show();
  },

  setEmail: function() {
    $('payment_email_value').innerHTML = $('payment_email').value;
    $('email_form').hide();
    $('email_value').show();
  },

  showBuyWarning: function() {
    if ($('buy_warning')) {
      $('tooltip_content').innerHTML = $('buy_warning').innerHTML;
      CMS.modalWindow.show();
    }
  },

  showFinishWarning: function() {
    if ($('finish_warning')) {
      $('tooltip_content').innerHTML = $('finish_warning').innerHTML;
      CMS.modalWindow.show();
    }    	
  },	
  
  // on edit, extend, cancel policy actions	
  onSubmitPolicyAction: function(action) {
    var cb = $('confirm_' + action + '_tos');
    if (cb && !cb.checked) { 
      cb.up('form').select('.errors').show(); return false;
    }
    return true;
  }
}

var WizardCalendars = {
  showStart: function(is_admin) {
    var el = document.getElementById('start_date');
    var format = "%d/%m/%Y";
    var today = new Date();
    var crt_year = today.getFullYear();

    if (_dynarch_popupCalendar != null) {
      // we already have some calendar created
      _dynarch_popupCalendar.hide();                 // so we hide it first.
    } else {
      var cal = new Calendar(0, null, WizardCalendars._onDateSelect, WizardCalendars._closeHandler);
      cal.weekNumbers = false;
      if (!is_admin) {
        cal.setDateStatusHandler(WizardCalendars._notStartDate);
      }
      _dynarch_popupCalendar = cal;                  // remember it in the global var
      cal.setRange(crt_year, crt_year + 1);        // min/max year allowed.
      cal.create();
    }
    _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
    _dynarch_popupCalendar.parseDate(el.value);     // try to parse the text in field
    _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

    // the reference element that we pass to showAtElement is the button that
    // triggers the calendar.  In this example we align the calendar bottom-right
    // to the button.

    _dynarch_popupCalendar.showAtElement(el);        // show the calendar

    return false;
  },

  showEnd: function() {
    var el = document.getElementById('end_date');
    var format = "%d/%m/%Y";
    el.value = $('start_date').value;
    var today = new Date();
    var crt_year = today.getFullYear();
    if (_dynarch_popupCalendar != null) {
      // we already have some calendar created
      _dynarch_popupCalendar.hide();                 // so we hide it first.
    } else {
      var cal = new Calendar(0, null, WizardCalendars._onDateSelect, WizardCalendars._closeHandler);
      cal.weekNumbers = false;
      cal.setDateStatusHandler(WizardCalendars._notEndDate);
      _dynarch_popupCalendar = cal;                  // remember it in the global var
      cal.setRange(crt_year, crt_year + 5);        // min/max year allowed.
      cal.create();
    }
    _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
    _dynarch_popupCalendar.parseDate(el.value);     // try to parse the text in field
    _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

    // the reference element that we pass to showAtElement is the button that
    // triggers the calendar.  In this example we align the calendar bottom-right
    // to the button.

    _dynarch_popupCalendar.showAtElement(el);        // show the calendar

    return false;
  },


  _onDateSelect: function(cal, date) {
    cal.sel.value = date;
    if ($('days') && $('start_date') && $('start_date').value.trim() != '' && $('end_date') && $('end_date').value.trim() != '') {
      var one_day = 1000 * 60 * 60 * 24;
      var start   = Date.parseDate($('start_date').value, '%d/%m/%Y');
      var end     = Date.parseDate($('end_date').value, '%d/%m/%Y');
      $('days').innerHTML = Math.round((end-start)/one_day) + 1;
    }
    if (cal.dateClicked) { 
      cal.callCloseHandler();
    }
  },

  _closeHandler: function(cal) {
    cal.hide();
    _dynarch_popupCalendar = null;
  },

  _notStartDate: function(date, y, m, d) {
    var now = new Date();
    var start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
    var end   = new Date(start.getFullYear() + 1, start.getMonth(), start.getDate(), 23, 59, 0);

    return date < start || date > end; //if true, disable day
  },

  _notEndDate: function(date, y, m, d) {
    var start = Date.parseDate($('start_date').value, '%d/%m/%Y');
    return date < start;
  }
}

Event.observe(window, 'load', Wizard.onLoad);