var j = jQuery.noConflict();


jQuery(document).ready(function(){

  function simulate_book_price(){

    var pgs = j("input#book_pages_quantity").val();
    var b = j("input#book_price_author").val();
    var c = j("input#book_price");

    if(pgs != '' && b != ''){
      pgs = parseInt(pgs);
      if(pgs <= 700){
      j.getJSON('/backstage/configurarlivro/price_preview', 
        { book_pages: pgs, price_author: b }, 
        function(data){
          c.val(parseFloat(data.total));
        });
      }else{
        alert("O limite de páginas é 700.");
      }
    }

  };

  function calculate_book_price(){


    var book_id = j("input#book_id").val();
    var a = j("input#book_price_author").val();
    var b = j("input#book_price_govtax");
    var c = j("input#book_price");

    if(a != '' && book_id != undefined){
      a = parseFloat(a);
      j.getJSON('/backstage/configurarlivro/final_price_preview', 
            { id: book_id, price_author: a }, 
            function(data){
              b.val(data.govtax);
              c.val(data.total);
            });
    }

  };

  j("div#fake_book_price_calculation input#book_pages_quantity, div#fake_book_price_calculation input#book_price_author").change(function(){
    simulate_book_price();  
  });

  if(j("div#final_book_cost_calculation")){
    j("input#book_price_author").change(function(){
      calculate_book_price();
    });
  }
  j('input#what').click(function(){
    if(j('input#what').val() == 'Título ou Autor'){
      j('input#what').val('');
    }
  });

  // Sort Books

  j('#sort_box form input, #sort_box form select').change(function(){
    location.href = j(this).val();
  });

  j('form#toggle_deliverable p').click(function(){
    j(this).find('input').attr("checked", true);
    j(this).parents('form').submit();
  });

  j('form.editor').submit(function(){
    var row = j(this).parents('tr')
    var id = row.attr('id').replace('order_item_', '');
    j.timer(1000, function(){
      row.children('td:last').load('/backstage/financial/' + id + '/rest');
    });
  });

  j('input.hide').change(function(){
    var row = j(this).parents('tr');
    var col = j(this).parents('th');
    var table = j(this).parents('table');
    var pos = row.find('th').index(col);
    table.find('tr').each(function(){
      var cols = j(this).find('td');
      if(cols.size()){
        j(cols.get(pos)).children('span').toggle();
      }
    })
    
    //alert(row.find('th').index(col));
  });


  j("a.fancybox").fancybox( { titleShow: false } );

  j('span.thumbnail span.input a, span.input a').live('click', function(){
    j(this).parents('span.input').find('input').click();
    j(this).parents('form').submit();
    return false;
  });

});
