/***********************************************************
* MODULE : Global Admin
************************************************************/
var MainAdmin = {
	init: function(){
    MainAdminMerchants.init();
    MainAdminPublications.init();
    MainAdminShop.init();
    
    MainAdmin.check_configurations();
	}, 

  check_configurations: function(){
    var config_block;
    if($$('div.configurations').first()){
      config_block = $$('div.configurations').first();
      if($('link-toggle-configurations')){
        Event.observe('link-toggle-configurations', 'click', function(event){MainAdmin.show_configurations();});
        Event.observe(config_block.select('a.btn-close').first(), 'click', function(event){MainAdmin.show_configurations();});
      }
    }
  },
  
  show_configurations: function(){
    var config_block = $$('div.configurations').first();
    
    if(config_block.visible()){
      new Ajax.Request(location.pathname + '?app_conf=publications&conf_show=0', { method:'get' });
      new Effect.BlindUp(config_block, {duration: 0.3, queue: {position: 'end', scope: 'configurations', limit: 1}});      
    }else{
      new Ajax.Request(location.pathname + '?app_conf=publications&conf_show=1', { method:'get' });
      new Effect.BlindDown(config_block, {duration: 0.3, queue: {position: 'end', scope: 'configurations', limit: 1}});      
    }
  }
}

/***********************************************************
* MODULE : Merchants functions
************************************************************/
var MainAdminMerchants = {
	init: function(){
    if($('list-users-simple')){
      MainAdminMerchants.init_list_select('users');
    }
    
    if($('list-members-simple')){
      MainAdminMerchants.init_list_select('members');
    }
  },
  
  init_list_select: function(name){
    $$('ul#list-' + name + '-simple li').each(function(entity){
      Event.observe(entity.select('div.title').first(), 'click', function(event){MainAdminMerchants.link_to_entity(entity, name)});
      if(entity.select('a.ico-delete').first()){
        Event.observe(entity.select('a.ico-delete').first() , 'mouseover', function(event){entity.addClassName('delete');});  
        Event.observe(entity.select('a.ico-delete').first() , 'mouseout', function(event){entity.removeClassName('delete');});  
      }        
    });
  },
  
  link_to_entity: function(entity, name){
    location.href = '/admin/' + name + '/' + entity.id.replace(name, '') + '/edit'
  }
}


/***********************************************************
* MODULE : Publications functions
************************************************************/
var MainAdminPublications = {
	init: function(){
    MainAdminPublications.init_configurations();
    MainAdminPublications.init_properties();
    MainAdminPublications.init_chapters();
    MainAdminPublications.init_toc();
    MainAdminPublications.init_security();
    MainAdminPublications.init_cost();
    
    if($('list-publications')){
      $$('#list-publications li').each(function(publication){
        Event.observe(publication, 'click', function(event){MainAdminPublications.link_to_publication(publication.select('input.publication-id').first().value);});
      });
    }
  },
  
  link_to_publication: function(id){
    location.href = '/admin/publications/' + id
  },
  
  /***********************************************************
  * PUBLICATIONS : Configurations
  ************************************************************/
  init_configurations: function(){
    if($('show_options_publications')){
      Event.observe('filter', 'change', function(event){MainAdminPublications.set_filter_interface();});
      MainAdminPublications.set_filter_interface();
    }
  },
  
  set_filter_interface: function(){
    var new_filter = 'filter-' + $('filter').value
    MainAdminPublications.hide_filters();
    if($(new_filter)){
      $(new_filter).force_show();
    }
  },
  
  hide_filters: function(){
    $('filter-state').hide();
    $('filter-name').hide();
    $('filter-isbn').hide();
  },
  
  /***********************************************************
  * PUBLICATIONS : Standard properties
  ************************************************************/
  init_properties: function(){
    if($('form-publication')){
      Event.observe($$('a.add-key').first(), 'click', function(event){MainAdminPublications.add_fields_key(event);});
      
      $$('a.ico-delete').each(function(link_delete) {
        Event.observe(link_delete, 'click', function(event){MainAdminPublications.delete_field_key(event, link_delete.up('div.key'));});
      });
    }
  },
  
  add_fields_key: function(e){
    var wrapper = $$('div.publication-keys').first();
    var template = wrapper.select('div.key').first();
    var element = new Element('div', {'class': 'key'});
    var id = Math.round(Math.random() * 10000);
    var field_type;
    var field_value;
    var btn_delete;
    
    element = template.cloneNode(true);
    
    element.show();
    
    field_type = element.select('select').first();
    field_type.setAttribute('id', 'keytype' + id);
    field_type.selectedIndex = 0;
    
    field_value = element.select('input').first();
    field_value.setAttribute('id', 'keyvalue' + id);
    field_value.clear();
    
    if(element.select('div.record-data').first()){
      element.select('div.record-data').first().remove(); 
    }

    btn_delete = element.select('a.ico-delete').first();
    btn_delete.remove();
    btn_delete = new Element('a', {'class': 'ico ico-delete', 'href': '#'});
    btn_delete.innerHTML = 'Supprimer';
    Event.observe(btn_delete, 'click', function(event){MainAdminPublications.delete_field_key(event, btn_delete.up('div.key'));});    
    element.insert({bottom:btn_delete});
    
    wrapper.insert({bottom:element});

    e.stop();
  },
  
  delete_field_key: function(event, field){
    keys = field.up('div.publication-keys').select('div.key');
    nbr_visible_keys = 0;
        
    keys.each(function(key){
      if(key.visible()){nbr_visible_keys++;} 
    });
    
    if(nbr_visible_keys > 1){
      if(field.select('input.destroyed').first()){
        field.select('input.destroyed').first().value = 1;
        field.hide();
      }else{
        field.remove();    
      }  
    }
    
    event.stop();
  },
  
  /***********************************************************
  * PUBLICATIONS : Chapters and pages
  ************************************************************/
  init_chapters: function(){
    
    if($('update-position')){
      Event.observe('update-position', 'change', MainAdminPublications.update_page_preview.bindAsEventListener(MainAdmin));
    }
    
    if($('publication-tree')) {
      $$('#publication-tree div.chapter-details').each(function(group_pages){
        group_pages.select('ul.pages').first().hide();
        Event.observe(group_pages.select('a.show-pages').first(), 'click', function(event){MainAdminPublications.show_pages(event, group_pages);});
      });
    }
  },
  
  show_pages: function(e, group_pages){
    var list = group_pages.select('ul.pages').first();
    var link = group_pages.select('a.show-pages').first();

    if(list.visible()){
      link.innerHTML = link.innerHTML.replace('Hide'.l(), 'Show'.l())
      list.hide();  
    }else{
      link.innerHTML = link.innerHTML.replace('Show'.l(), 'Hide'.l())
      list.force_show();
    }
    e.stop();
  },
  
  update_page_preview: function(){
    var content = '';
    
    content += '<object type="application/x-shockwave-flash" data="/admin/pages/' + $F('update-position') + '?find=position" id="flash-preview-page">';
    content += '<param name="movie" value="/admin/pages/' + $F('update-position') + '?find=position" />';
    content += '</object>';
    
    $('preview-page').innerHTML = content;
  },
  
  
  /***********************************************************
  * PUBLICATIONS : Table of content
  ************************************************************/
  init_toc: function(){
    if($('toc-manager')){
      $$('ul#checks-toc-type li').each(function(item){
          Event.observe(item, 'click', function(event){MainAdminPublications.change_toc_type(item);});
      });
      
      $$('ul#checks-toc-type li').each(function(item){
          Event.observe(item, 'click', function(event){MainAdminPublications.change_toc_type(item);});
      });
    }
    
    if($('checks-toc-format')){
      $$('ul#checks-toc-format li').each(function(item){
          Event.observe(item, 'click', function(event){MainAdminPublications.change_toc_format(item);});
      });
    }  
  },
  
  change_toc_type: function(item){
    $('toc_type').value = item.id.replace('toctype', '');
    $('form-toc').submit();
  },
  
  change_toc_format: function(item){
    $('toc_format').value = item.id.replace('tocformat', '');
    $('form-toc').submit();
  },
  
  
  /***********************************************************
  * PUBLICATIONS : Security
  ************************************************************/
  init_security: function(){
    if($('security-level')){
      $$('ul#security-level li').each(function(item){
          Event.observe(item, 'click', function(event){MainAdminPublications.change_security_level(item);});
      });
    }
    
    if($('security-tree')){
      $$('#security-tree li').each(function(chapter){
        if(chapter.select('ul.pages').first()){
          Event.observe(chapter.select('div.title').first(), 'click', function(event){MainAdminPublications.show_security_pages(chapter.select('ul.pages').first());});
          Event.observe(chapter.select('div.ico').first(), 'click', function(event){MainAdminPublications.change_lock(chapter, false, '');});            
          
          if(chapter.select('ul.pages').length > 1){
            chapter.select('ul.pages').first().hide();  
          }
          chapter.select('ul.pages li').each(function(page){
            Event.observe(page.select('div.ico-small').first(), 'click', function(event){MainAdminPublications.change_lock(page, true, '');});            
          });
        }        
      });
    }  
  },
  
  change_security_level: function(item){
    $('publication_security').value = item.id.replace('securitylevel', '');
    $('form-change-security').submit();
  },
  
  show_security_pages: function(list){
    if(list.visible()){
      list.hide();  
    }else{
      list.force_show();
    }
  },
  
  change_lock: function(entity, page, force_change){
    var current_class = 'off';
    var new_class = 'on';
    var icon;
    
    if(page){
      icon = entity.select('div.ico-small').first();
    }else{
      icon = entity.select('div.ico').first();
    }
    
    if(icon.className.indexOf('on') != -1){
      current_class = 'on';
      new_class = 'off';
    }
    
    if(force_change != ''){
      new_class = force_change;
    }
    
    icon.className = icon.className.replace(current_class, new_class);
    
    if(entity.select('input.lock-input')){
      if(new_class == 'off'){
        entity.select('input.lock-input').first().value = 0;
      }else{
        entity.select('input.lock-input').first().value = 1;
      }
    }
    
    if(!page){
      entity.select('ul.pages li').each(function(page){
        MainAdminPublications.change_lock(page, true, new_class);
      });
    }
  },
  
  
  /***********************************************************
  * PUBLICATIONS : Cost
  ************************************************************/
  init_cost: function(){
    if($('publication-cost')){
      Event.observe('publication_cost_formatted', 'keyup', function(event){MainAdminPublications.update_publication_cost(false);});
      Event.observe('profit', 'keyup', function(event){MainAdminPublications.update_publication_cost(true);});
    
      MainAdminPublications.update_publication_cost(false);
    }
  },
  
  update_publication_cost: function(update_by_profit){
    var sales_margin = 0;
    var new_value = $('publication_cost_formatted').value.replace(',', '.');
    var price = 0;
    var is_num = false
    
    if(update_by_profit){
      new_value = $('profit').value.replace(',', '.');
    }
    
    if(new_value == ''){return;}
    
    if(new_value.endsWith('.')){
      if(new_value.indexOf('.') == new_value.lastIndexOf('.')){
        return;
      }
    }
    
    is_num = new_value.is_numeric();
    
    if(is_num){
      price = Number(new_value)
          
      if(!update_by_profit){
        sales_margin = ((Number($('sales_margin_percent').value) / 100) * price).round_decimal(2);
        $('sales_margin').value = sales_margin;
        $('profit').value = (price - sales_margin).round_decimal(2);
      }else{
        $('publication_cost_formatted').value = (price / (100 - Number($('sales_margin_percent').value)) * 100).round_decimal(2);
        $('sales_margin').value = (Number($('publication_cost_formatted').value) - price).round_decimal(2);
      }
    }else{
      $('publication_cost_formatted').value = 0;
      $('sales_margin').value = 0;
      $('profit').value = 0;
    }
  }
}


/***********************************************************
* MODULE : Shop functions
************************************************************/
var MainAdminShop = {
  init: function(){
    MainAdminShop.check_payment_manager
  },
  
  check_payment_manager: function(){
    if($('payment-form')){
      $$('.purchase-check').each(function(check){
        Event.observe(check, 'click', function(event){MainAdminShop.update_payment_total();});
      });
      MainAdminShop.update_payment_total();
    }
  },
  
  update_payment_total: function(){
    total = 0;
    balance = 0;
    $$('.payment-value').each(function(payment_value){
      purchase_id = payment_value.name.replace('purchase_payment_', '')
      if($('purchase' + purchase_id).checked){
        total += Number(payment_value.value);  
      }else{
        balance += Number(payment_value.value);
      }
    });
    
    $('payment_amount').value = total;
    $('show_amount').value = total/100;
    $('show_balance').value = balance/100;
  },
  
  update_payment_balance: function(){
    
  }
}

Event.observe(window, 'load', MainAdmin.init);