// CalendarDateSelect version 1.15 - a prototype based date picker
// Questions, comments, bugs? - see the project page: http://code.google.com/p/calendardateselect
if (typeof Prototype == 'undefined') alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (.g. <%= javascript_include_tag :defaults %>) *before* it includes calcQta.js .");
if (Prototype.Version < "1.6") alert("Prototype 1.6.0 is required.  If using earlier version of prototype, please use calendar_date_select version 1.8.3");

Element.addMethods({
  purgeChildren: function(element) { $A(element.childNodes).each(function(e){$(e).remove();}); },
  build: function(element, type, options, style) {
    var newElement = Element.buildAndAppend(type, options, style);
    element.appendChild(newElement);
    return newElement;
  }
});

Element.buildAndAppend = function(type, options, style)
{
  var e = $(document.createElement(type));
  $H(options).each(function(pair) { e[pair.key] = pair.value });
  if (style) e.setStyle(style);
  return e;
};

nil = null;

window.f_height = function() { return( [window.innerHeight ? window.innerHeight : null, document.documentElement ? document.documentElement.clientHeight : null, document.body ? document.body.clientHeight : null].select(function(x){return x>0}).first()||0); }
window.f_scrollTop = function() { return ([window.pageYOffset ? window.pageYOffset : null, document.documentElement ? document.documentElement.scrollTop : null, document.body ? document.body.scrollTop : null].select(function(x){return x>0}).first()||0 ); }

//_translationsCalcQta = {
//  "Seleziona": "Seleziona",
//  "Calcola": "Calcola",
//  "Annulla": "Annulla"
//}

CalcQta = Class.create();
CalcQta.prototype = {
  initialize: function(target_element, options) {
    this.target_element = $(target_element); // make sure it's an element, not a string
    if (!this.target_element) { alert("Target element " + target_element + " not found!"); return false;}
    if (this.target_element.tagName != "INPUT") this.target_element = this.target_element.down("INPUT")
    
    this.target_element.CalcQta = this;
    // initialize the date control
    this.options = $H({
      embedded: false,
      popup: nil,
      Multiplo: 1,
      PezziConf: 1,
      close_on_click: nil,
      popup_by: this.target_element,
      onchange: this.target_element.onchange
    }).merge(options || {});
    this.callback("before_show")
    this.initCalcDiv();
    if(!this.options.get("embedded")) {
      this.positionCalcDiv()
      // set the click handler to check if a user has clicked away from the document
      Event.observe(document, "mousedown", this.closeIfClickedOut_handler = this.closeIfClickedOut.bindAsEventListener(this));
      Event.observe(document, "keypress", this.keyPress_handler = this.keyPress.bindAsEventListener(this));
    }
    this.callback("after_show")
    this.setFocus()
  },
  positionCalcDiv: function() {
    var above = false;
    var c_pos = this.calc_div.cumulativeOffset(), c_left = c_pos[0], c_top = c_pos[1], c_dim = this.calc_div.getDimensions(), c_height = c_dim.height, c_width = c_dim.width; 
    var w_top = window.f_scrollTop(), w_height = window.f_height();
    var e_dim = $(this.options.get("popup_by")).cumulativeOffset(), e_top = e_dim[1], e_left = e_dim[0], e_height = $(this.options.get("popup_by")).getDimensions().height, e_bottom = e_top + e_height;
    
    if ( (( e_bottom + c_height ) > (w_top + w_height)) && ( e_bottom - c_height > w_top )) above = true;
    
    if (e_left+c_width>document.body.clientWidth) {e_left = e_left - ((e_left+c_width) - document.body.clientWidth)}
    
    //alert('e_left:' + e_left);

    var left_px = e_left.toString() + "px", top_px = (above ? (e_top - c_height ) : ( e_top + e_height )).toString() + "px";
    
    this.calc_div.style.left = left_px;  this.calc_div.style.top = top_px;
    
    this.calc_div.setStyle({visibility:""});
    
    // draw an iframe behind the calendar -- ugly hack to make IE 6 happy
    if(navigator.appName=="Microsoft Internet Explorer") this.iframe = $(document.body).build("iframe", {src: "javascript:false", className: "ie6_blocker"}, { left: left_px, top: top_px, height: c_height.toString()+"px", width: c_width.toString()+"px", border: "0px"})
  },
  initCalcDiv: function() {
    if (this.options.get("embedded")) {
      var parent = this.target_element.parentNode;
      var style = {}
    } else {
      var parent = document.body
      var style = { position:"absolute", visibility: "hidden", left:0, top:0 }
    }
    this.calc_div = $(parent).build('div', {className: "calendar_date_select"}, style);
    
    var that = this;
    // create the divs
    $w("top header body buttons footer bottom").each(function(name) {
      eval("var " + name + "_div = that." + name + "_div = that.calc_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ");
    });
    
    this.initHeaderDiv();
    this.initButtonsDiv();
    this.initCalcBody();
  },
  initHeaderDiv: function() {
    var header_div = this.header_div;
    this.close_button = header_div.build("a", { innerHTML: "x", href:"#", onclick:function () { this.close(); return false; }.bindAsEventListener(this), className: "close" });
  },
  initCalcBody: function() {
    var body_div = this.body_div;
    body_div.innerHTML = 'Numero di pezzi:<br><input type="text" id="InputVal" onkeyup="CalcolaPezzi(this.value,' + this.options.get("Multiplo") + ', ' + this.options.get("PezziConf") + ')">';
    if (this.options.get("Multiplo") != '1') {body_div.innerHTML += '<br>Numero di confezioni:<br><input type="text" id="InputValConf" onkeyup="CalcolaConfez(this.value,' + this.options.get("Multiplo") + ')">'}
    body_div.innerHTML = body_div.innerHTML + '<br>Quantit&agrave; da inserire: <br><input type="text" id="OutputVal" disabled="true">' + 
                                              '<div class="Note" id="OutMsg">&nbsp</div>';
    body_div.setStyle({backgroundColor: '#FFF'});
  },
  initButtonsDiv: function()
  {
    var buttons_div = this.buttons_div;

    buttons_div.build("input", { type: "button", value:"Chiudi", onclick:function () { this.close(); return false; }.bindAsEventListener(this)});
    buttons_div.build("input", { type: "button", value:"Seleziona", onclick:function () { this.updateValue(); this.close(); return false; }.bindAsEventListener(this)});
  },
  setFocus:function()
  {
    $('InputVal').focus();
  },
  closeOnClick: function() {
    if (this.options.get("embedded")) return false;
    return (this.options.get("close_on_click"))
  },
  updateValue: function() {
    var last_value = this.target_element.value;
    this.target_element.value = $('OutputVal').value;
    if (last_value!=this.target_element.value) this.callback("onchange");
  },
  close: function() {
    if (this.closed) return false;
    this.callback("before_close");
    this.target_element.calendar_date_select = nil;
    Event.stopObserving(document, "mousedown", this.closeIfClickedOut_handler);
    Event.stopObserving(document, "keypress", this.keyPress_handler);
    this.calc_div.remove(); this.closed = true;
    if (this.iframe) this.iframe.remove();
    if (this.target_element.type != "hidden" && ! this.target_element.disabled) this.target_element.focus();
    this.callback("after_close");
  },
  closeIfClickedOut: function(e) {
    if (! $(Event.element(e)).descendantOf(this.calc_div) ) this.close();
  },
  keyPress: function(e) {
    if (e.keyCode==Event.KEY_ESC)      this.close();
    if (e.keyCode==Event.KEY_RETURN) { this.updateValue(); this.close(); }
  },
  callback: function(name, param) { if (this.options.get(name)) { this.options.get(name).bind(this.target_element)(param); } }
}





function CalcolaPezzi(Pezzi, Multiplo, PcsXConf){
    var Val, PEzziEff;
    if (Multiplo != 1) {$('InputValConf').value=''};
    Val = (Pezzi/PcsXConf/Multiplo);
    if (Val.toString() != 'NaN'){
        $('OutMsg').innerHTML='';
        $('OutputVal').value=(Math.ceil(Val));
        PezziEff = (Math.ceil(Val) * PcsXConf * Multiplo);
        if (Math.round(PezziEff) !=  Math.round(Pezzi)){$('OutMsg').innerHTML=GetWarningConf(Math.round(PezziEff));}
        //'Quantit&agrave; calcolata per eccesso.<br>Pezzi effettivi: ' +  Math.round(PezziEff) + '.'
    }else{
        $('OutputVal').value='';
        $('OutMsg').innerHTML=GetAlert('Inserire un valore numerico !!!');
    }
}

function CalcolaConfez(Conf, Multiplo){
    var Val, ConfEff;
    $('InputVal').value='';
    Val = (Conf/Multiplo);
    if (Val.toString() != 'NaN'){
        $('OutMsg').innerHTML='';
        $('OutputVal').value=(Math.ceil(Val));
        ConfEff = (Math.ceil(Val) * Multiplo);
        if (Math.round(ConfEff) !=  Math.round(Conf)){$('OutMsg').innerHTML=GetWarningConf(Math.round(ConfEff)); }
        //'Quantit&agrave; calcolata per eccesso.<br>Confezioni effettive: ' +  Math.round(ConfEff) + '.';
    }else{
        $('OutputVal').value='';
        $('OutMsg').innerHTML=GetAlert('Inserire un valore numerico !!!');
    }
}

function GetWarningConf(QtaEff){
    var OutVal = '';
    OutVal = '<div style="border:1px solid orange; margin:5px;text-align:left;height:24px;" class="Note"><img src="' + BasePath + 'img/notify/warn.png" align="left" >Quantit&agrave; calcolata per eccesso.<br>Confezioni effettive: <b>' +  QtaEff + '</b>.</div>';
    return OutVal
}

function GetAlert(StrText){
    var OutVal = '';
    OutVal = '<div style="border:1px solid red; margin:5px;text-align:left;height:24px;" class="Note"><img src="' + BasePath + 'img/notify/error.png" align="left" >' +  StrText + '.</div>';
    return OutVal
}
