/**
* general functions, loadable in every page
* prototype 1.6 js lib requirement
*  
* author Iulian Radu <iulian_radu2003@yahoo.com>
*/



/**
* check input values width filters
*
* @param    id - form_id
*/

var sendForm = function (id){
  var form = $(id);
  var no_error = true;
  var tmp = true;
  var tmp_checkbox = false;

  $$('#'+id+' [rel*=required]').each(function (el){
    if (el.getValue().empty() && no_error){
        alert('Campul selectat nu poate fi gol.');
        el.focus();
        el.addClassName('focus');
        no_error = false;
    }else{
        el.removeClassName('focus');
    }
  });

  if (no_error){
  $$('#'+id+' [rel*=number]').each(function (el){

      if (el.getValue()!=''){
      if (isNaN(parseFloat(el.getValue())) && no_error){
          alert('Campul selectat trebuie sa contina un numar.');
          el.focus();
          el.addClassName('focus');
          no_error = false;
      }else{
                el.removeClassName('focus');
      }
    }else{
        el.removeClassName('focus');
    }
  });
  }

  if (no_error){
  $$('#'+id+' [rel*=lte]').each(function (el){

    if (parseFloat(el.getValue()) > parseFloat(el.getAttribute("rel_lte")) && no_error){
        alert('Campul selectat a depasit limita sa maxim admisibila ('+el.getAttribute("rel_lte")+').');
        el.focus();
        el.addClassName('focus');
        no_error = false;
    }else{
        el.removeClassName('focus');
    }
  });
  }

  if (no_error){
  $$('#'+id+' [rel*=array_required]').each(function (el){

    if (el.getValue()){
        for (var i=1;i<=el.getValue().length;i++)
        {
            if (el[i]!=''){
              tmp = false;
            }
        }
    }

    if (tmp && no_error){
        alert('Campul selectat nu poate fi gol.');
        el.focus();
        el.addClassName('focus');
        no_error = false;
    }else{
        el.removeClassName('focus');
    }
  });
  }

  if (no_error){
  $$('#'+id+' [rel*=group]').each(function (el){
      tmp_checkbox = true;
    if (el.getValue())
    {
        tmp_checkbox  = false;
        throw $break;

    }

  });
  }

  if (tmp_checkbox && no_error){
      alert('Trebuie sa selectati cel putin un element.');
      no_error = false;
  }

  if (no_error){
      return true;
  }

  return false;
}



document.observe('dom:loaded', function() {
  //alternez bg-urile randurilor tabeleleor
  $$('table.tbl_list tbody > tr:nth-child(odd)').each(function(s) {
    s.addClassName('odd');
  });
  $$('table.tbl_list tbody > tr:nth-child(even)').each(function(s) {
    s.addClassName('even');
  });

});


/**
* add multiple pictures for current product (on edit or add action)
*/

var adaugaImagine = function(){

  var id_curent = $('picture_count').value;
  id_curent = parseInt(id_curent)+1;
  $('picture_count').value = id_curent;

  var tr = new Element('tr',{ 'id': 'tr_'+id_curent});

  var td1 = new Element('td').update('Imagine produs');
  var td2 = new Element('td');

  var div1 = new Element('div', {'class': 'aleft'});
  var div2 = new Element('div', {'class': 'proprietati aleft'});
  var input = new Element('input', { 'type': 'file', 'name' : 'picture_'+id_curent });
  var span = new Element('span').update(" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
  var add = new Element('input', { 'type': 'button', 'value': 'Adauga alta imagine', 'id' : 'button_'+id_curent});
  var add1 = new Element('input', { 'type': 'button', 'value': 'Sterge', 'id' : 'button_sterge_'+id_curent});

  div1.appendChild(input);
  div1.appendChild(span);
  div2.appendChild(add);
  div2.appendChild(add1);

  td2.appendChild(div1);
  td2.appendChild(div2);
  tr.appendChild(td1);
  tr.appendChild(td2);

  $('picture_reference').insert({ "after": tr });

  Event.observe('button_'+id_curent,'click', adaugaImagine);
  Event.observe('button_sterge_'+id_curent,'click', function(){$('tr_'+id_curent).remove()});
}

/**
* turn visible  frame on/off over product picture
*/

var showFrame = function (element){

  var el = $(element);
  el.className =  el.hasClassName('picture_list_show') ? 'picture_list' : 'picture_list_show';
}


/**
* toggle client firm info on and off
*/

var toogleClientFirm = function(){

  if ($('switch_firm').getValue() == "1"){
    $('client_firm').show();
  }else{
    $('client_firm').hide();
  }

  if (!$('client_firm').visible()){

      $$('#client_firm [rel=firm_field]').each(function(elem){
          elem.value = '';
      });

  }

}

/**
* open pop-up window
* @param    url - window url
*/
var open_popup = function(url){
  var x = window.open(url, null, 'height=600,width=800,resizable=yes,toolbar=no,location=no,status=no,scrollbars=yes');

  x.focus();

}

var writeProductParams = function(s, sort){

  if (s == 'test'){
    var string_tmp = sort;
  }else{
    var string_tmp = ($('code') && $('code').getValue() ? "code="+$('code').getValue() : '')
                  +($('name') && $('name').getValue() ? "&name="+$('name').getValue() : '')
                  +($('des') && $('des').getValue() ? "&des="+$('des').getValue() : '')
                  +($('producer') && $('producer').getValue() ? "&producer="+$('producer').getValue() : '')
                  +($('contractor') && $('contractor').getValue() ? "&contractor="+$('contractor').getValue() : '')
                  +($('price') && $('price').getValue() ? "&price="+$('price').getValue() : '')
                  +($('status') && $('status').getValue() ? "&status="+$('status').getValue() : '')
                  +sort;
  }

  $('fconf').value = string_tmp;
}

var fillInTemplates = function(){
  $$('ul.lista input').each(function(el){
    el.checked = false; 
  });

  if ($('template').value){
    var current_template = credentials[$('template').value]; 
    
    $H(current_template).each(function(el){
      if ($('choices_'+el.key)){
        $('choices_'+el.key).checked = true;
      }
    }); 
  }
}

var autocompleterParameter = function(text,query){
  $('firm_selected').value = '';
  var id = $('client').getValue(); 
  return query+"&id="+id;
}

var getSelectionId = function(text,li){
  $('firm_selected').value = li.id;
}

var calculateOfferServiceValue = function(id){
  var price = isNaN(parseFloat($('price_'+id).innerHTML)) ? 0 : parseFloat($('price_'+id).innerHTML); 
  var discount = isNaN(parseFloat($('discount_'+id).value)) ? 0 : parseFloat($('discount_'+id).value);
  
  var total_price = price*(1-discount/100);
  total_price = Math.round(total_price*100)/100;
  
  $('total_price_'+id).innerHTML = total_price;    
}

var showInterval = function(){
  if ($('annex_type').value == 2){
    $('tr_interval').show(); 
    $('tr_finit').hide();
  }else{
    $('tr_interval').hide();
    $('tr_finit').show();
  }  
}

var deleteAllStages = function(){
  $$('#tr_finit tr[rel=stage_row]').each(function(el){el.remove()});
}

var removeStage = function(id){
  $('stage_'+id).remove();
  fillContent();
}


/**
* helper library for ajax requests
*
* author Iulian Radu <iulian_radu2003@yahoo.com>
*/


/**
*
* create graphic element width current ajax request status
*/

var showAjaxStatus = {

  end_loading:  false,
  show_duration:  0.5,      //time(s) for fade in efect
  hide_duration:  0.5,      //time(s) for fade out efect

  start: function (){



    if (typeof Effect!='undefined'){

      this.create_div();
      this.end_loading = false;

      new Effect.Appear('status_div',{
        'from':     0,
        'to':       1,
        'duration':   this.show_duration
      });

      new PeriodicalExecuter(function(pe){
          pe.stop();
          showAjaxStatus.end_loading = true;
        },this.show_duration);
    }else{
      this.create_div('show');
      this.end_loading = true;
    }

  },

  end: function (){
    new PeriodicalExecuter(function(pe){
        if (showAjaxStatus.end_loading) {
          pe.stop();
          if ($('status_div')) {
            showAjaxStatus.disapear();
          }
        }
      },0.1);
  },

  disapear: function(){
    if (typeof Effect != 'undefined'){
      new Effect.Appear('status_div',{
        'from':     1,
        'to':       0,
        'duration':   this.hide_duration
      });

      new PeriodicalExecuter(function(pe){
          pe.stop();
          showAjaxStatus.remove_div();
        },this.hide_duration);
    }else{
      this.remove_div();
    }

  },

  remove_div: function(){
    if ($('status_div')) {
      $('status_div').remove();
    }
  },

  create_div: function (show){

    var width = document.viewport.getWidth();
    var scrolloffset = document.viewport.getScrollOffsets();
    var show = !show ? 'display:none;' : '';

    var div  = new Element('div',{
        'id':     'status_div',
        'style':  show+'position:absolute;left:'+width/2+'px;top:'+(scrolloffset.top + 20) +'px;color:white;font-weight:bold;font-family:arial;background-color:red;width:70px;height:15px;padding:2px;text-align:center;vertical-align:middle'
      });

    div.update('Loading ... ');
    document.body.appendChild(div);

  }
}

/**
* show in defined container all contractors for specific producer
*
* @param    id    - producer id
* @param    prod_id - product_id (optional --- refill existing fields)
*/
var showContractors = function(id, prod_id)
{
  prod_id = prod_id ? prod_id : '';

  new Ajax.Updater('fur_container',$('route').value,{
    method:     'post',
    parameters:     'id='+id+'&prod_id='+prod_id,
    onCreate: showAjaxStatus.start(),
    onComplete: showAjaxStatus.end()
  });
}

/**
* deletes product picture
* @param  element: elementto be deleted
* @param  product: product id
* @param    number: current picture
*/

var deletePicture = function (product, number){

  var path = $('del_path').value;

  var param = { 'product': product, 'number': number };

  var conf = confirm('Sunteti sigur ca doriti eliminarea imaginii selectate?');
  if (conf){

      new Ajax.Request(path,{
      method:   "POST",
      parameters: param,

      onCreate: showAjaxStatus.start(),
      
      onComplete: function (r){
          $('div_'+number).remove();
          showAjaxStatus.end();
      }
      });
  }
}

/**
* scroll page to focus element
* @param id - element id
*/
var scrollPage = function (id){

  var elem = $(id);
  
  if (!elem){
      return false;
  }
  
  elem.scrollTo();
}


var showClientDetails = function(){
  showAjaxStatus.start();
  new Ajax.Request($('route_client').value,{
    parameters: 'id=' + $('contract_client_id').value,
    onComplete: function(resp){
      result = eval('('+resp.responseText+')');
      $('contract_client_firm_id').update(result['firm']);
      $('contract_client_address_id').update(result['address']);
      $('contract_client_firm_address_id').update(result['empty']);
      showAjaxStatus.end()
    }
  });
}

var fillContent = function(){
  var editor = FCKeditorAPI.GetInstance('annex[content]') ;        
  var new_string = editor.GetData(); 
  param = $('myform').serialize(true);
  param['content'] = new_string;
  
  showAjaxStatus.start();
  new Ajax.Request($('route_content').value,{
    parameters: param,
    onComplete: function(resp){
      editor.SetData(resp.responseText);
      showAjaxStatus.end();
    }    
  });
}

var calculateStages = function(){
  var id;
  params = $('myform').serialize(true);    
  $$('#tr_finit tr[rel1=extra]').each(function(el){   
    id = el.id;
  }); 
  params['extra'] = id; 
  showAjaxStatus.start();
  new Ajax.Request($('route_stages').value,{
    parameters: params,
    onComplete: function(resp){
      deleteAllStages();
      $$('#tr_finit tr[rel1=extra]').each(function(el){
        el.remove();
      });       
      $('reference').insert({'after': resp.responseText});
      fillContent();
    }      
  });
}

var populateContract = function(){
  var editor = FCKeditorAPI.GetInstance('content') ;

  showAjaxStatus.start();
  new Ajax.Request($('route_content').value,{
    parameters: 'id=' + $('template').value,
    onComplete: function(resp){
      editor.SetData(resp.responseText);
      showAjaxStatus.end();
    }    
  }); 
}

var showContractAnnex = function(){
  //golesc selecturile de la anexe si etape
  $('anexa').update('<option value="">Alegeti</option>');
  $('etapa').update('<option value="">Alegeti</option>');
  
  if ($('contract').value){
    showAjaxStatus.start();
    new Ajax.Updater($('anexa'),$('route_annex').value,{
      parameters: 'contract_id='+$('contract').value,
      onComplete: function(resp){
        showAjaxStatus.end();
      }
    });
  }  
}

var showAnnexStages = function(){
  //golesc selecturile de la anexe si etape
  $('etapa').update('<option value="">Alegeti</option>');
  
  if ($('anexa').value){
    showAjaxStatus.start();
 
    new Ajax.Request($('route_stage').value,{
      parameters: 'annex_id=' + $('anexa').value,
      evalJS: true, 
      onComplete: function(resp){
        showAjaxStatus.end(); 
        $('etapa').update(resp.responseText); 
      }
    });
  }  
}


var switchAvans = function(){
  var etapa = $('etapa').value; 
  if (old_stages[etapa]){
    $('tr_avans').remove();
  }else{
    if (!$('tr_avans')){
      var tr = new Element('tr',{'id': 'tr_avans'});
      var td = new Element('td').update('Avans:');
      tr.insert(td);
      td = new Element('td'); 
      var check = new Element('input',{'type': 'checkbox', 'value': '1', 'name': 'avans', 'id': 'avans'}); 
      td.insert(check);
      tr.insert(td);
      
      $('avans_ref').insert({'after': tr});
    }
  }
}

var addInvoiceElement = function(type){

  showAjaxStatus.start();
   new Ajax.Updater($('container'),$('route_add_element').value,{
    parameters: 'type='+type,
		insertion: 'bottom',
		onComplete: function(resp){
		  showAjaxStatus.end();
		}
   });
}

var removeElement = function (id, type){
  showAjaxStatus.start();
   new Ajax.Request($('route_del_element').value,{
    parameters: 'type='+type+'&id='+id,
    onComplete: function(resp){
      $('tr_'+id).remove();
      calculateInvoice(); 
      showAjaxStatus.end();
    }
   });
}

var calculateInvoice = function(){
  var id = '';
  var quantity, price; 
  var total_price = 0, tva = 0;
  var total_no_tva = 0, total_tva = 0, total_general = 0;  
  
  $$('input[rel=quantity]').each(function(el){
    id = el.id.split("_"); 
    id = id[1];
    
    if (isNaN(el.value))
    {
      el.value = 1;
    }    
 
    quantity = isNaN(parseFloat(el.value)) ? 1 : parseFloat(el.value);
    price = isNaN(parseFloat($('element_'+id+'_price').value)) ? 0 : parseFloat($('element_'+id+'_price').value);
    
    
    total_price = Math.round(price*quantity*100)/100;
    tva = Math.round(100*total_price*19/100)/100;
    
    $('element_'+id+'_price_without_tva').value = total_price;                           
    $('element_'+id+'_price_tva').value = tva;    
    
    total_no_tva += total_price; 
    total_tva += tva; 
    total_general = total_no_tva + total_tva; 
    
    $('total').update(Math.round(total_no_tva*100)/100+' RON');                       
    $('total_tva').update(Math.round(total_tva*100)/100+' RON');                       
    $('total_general').update(Math.round(total_general*100)/100+' RON');                       
  });
}


var showClientFirms = function(){  
  $('firm').update('<option value="">Alegeti</option>');
  if ($('client').value){
	  showAjaxStatus.start();
	   new Ajax.Updater($('firm'),$('route_firm').value,{
	    parameters: 'id='+$('client').value,
	    onComplete: function(resp){
	      showAjaxStatus.end();
	    }
	   });
   }
}
