$(document).bind('ready', function() {
  cart_func_pay();
});
carttm_pay = new Object();
function cart_func_pay()
{
  if ($('div.selectedItem[@rel=p] a.delete').length == 1) {
    $('div.selectedItem[@rel=p] a.delete').addClass('disabled');
  } else {
    $('div.selectedItem[@rel=p] a.delete').removeClass('disabled');
  }
  $('#dv_orderedItems a.info').bind('click', function() {
     $('div.selectedItem[@rel=p]').hide();
     $(document.body).append($('#infop' + $(this).attr('rel')).show().css({left:($(this).offset().left - 5) + 'px', top:($(this).offset().top - 50) + 'px'}));
    return false;
  });
	$('#dv_orderedItems a.delete').bind('click', function() {
      if (!$(this).is('.disabled')) {
        if (carttm_pay[$(this).attr('rel')]) window.clearTimeout(carttm_pay[$(this).attr('rel')]);
        //$('#itemList a.dec[@rel=' + $(this).attr('rel') + ']').next('input').attr('value', 1).parent('div').addClass('hide').prev('a').removeClass('hide');
        //$('#itemList a.preadd[@rel=' + $(this).attr('rel') + ']').removeClass('hide').next('a').addClass('hide');
        $('div#dv_orderedItems').load('/cart_pre.php?fpay=1&delete_product=' + $(this).attr('rel') + '&is_order=1&rand=' + Math.random(), function() {
          $('#dv_orderedItems .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
          cart_func_pay();
          recalccart_pay();
          //$('#dv_cart').load('/cart_pre.php?just_update=1&rand=' + Math.random(), function() {
          //  cart_func();
          //});
        });
        $('div.selectedItem[@rel=p]').remove();
      }
      return false;
		});
  $('#dv_orderedItems a.dec').bind('click', function() {
			if($(this).next('input').attr('value') > 1){
        if (carttm_pay[$(this).attr('rel')]) window.clearTimeout(carttm_pay[$(this).attr('rel')]);
        $('#itemList').add('div.addThis').add('div.selectedItem[@rel=c]').add('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('input.text[@rel=' + $(this).attr('rel') + ']').attr('value', $(this).next('input').attr('value')/1 - 1);
        updatetm_pay($(this).attr('rel'));
			} else {
        /*
        $('div#dv_orderedItems').load('/cart_pre.php?fpay=1&delete_product=' + $(this).attr('rel') + '&rand=' + Math.random(), function() {
          $('#cartTable').each(function() {fleXenv.fleXcrollMain(this)});
          cart_func_pay();
        });
        $('div.selectedItem[@rel=p]').remove();
        */
      }
      return false;
		});		
		
 $('#dv_orderedItems a.inc').bind('click', function() {
	    if($(this).prev('input').attr('value') < 100){
        if (carttm_pay[$(this).attr('rel')]) window.clearTimeout(carttm_pay[$(this).attr('rel')]);
        $('#itemList').add('div.addThis').add('div.selectedItem[@rel=c]').add('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('input.text[@rel=' + $(this).attr('rel') + ']').attr('value', $(this).prev('input').attr('value')/1 + 1);
        updatetm_pay($(this).attr('rel')); 
      }
      return false;
		});

$('#dv_orderedItems input.text[@rel]').bind('keyup', function() {
    if (carttm_pay[$(this).attr('rel')]) window.clearTimeout(carttm_pay[$(this).attr('rel')]);
    if (!/^[1-9][01-9]*$/.test($(this).attr('value'))) {
      if (/[1-9][01-9]*$/.test($(this).attr('value'))) $(this).attr('value', $(this).attr('value').replace(/[^01-9]+$/, ''));
      else $(this).attr('value', 1);
    }
    if ($(this).attr('value') > 100) $(this).attr('value', 100);
    //$(this).prev('input').attr('value', $(this).prev('input').attr('value')/1 + 1);
    $('#itemList').add('div.addThis').add('div.selectedItem[@rel=c]').add('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('input.text[@rel=' + $(this).attr('rel') + ']').attr('value', $(this).attr('value'));
    updatetm_pay($(this).attr('rel'));
    return false;
  }).bind('focus', function() { this.select(); }).bind('keydown', function(event) {
    var key = event.charCode ? event.charCode : event.keyCode;
    if (key == 38) {
      $(this).next('a').trigger('click');
    } else if (key == 40) {
      $(this).prev('a').trigger('click');
    }
  });
  $('#dv_orderedItems a.shipinfo').bind('click', function() {
    var last_href = modal_link($(this).attr('href'));
    $('div.selectedItem[@rel=p]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      fpar = 'fr=3';
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(add_params(last_href, fpar), function() {
        set_win_title();
        page_func();
        $('div.container:last .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
      });
    }); 
    set_href('/shipment/');    
    return false;
  });
  $('#dv_orderedItems a.det').bind('click', function() {
    var last_href = modal_link($(this).attr('href'));
    $('div.selectedItem[@rel=p]').hide();
    $('div.container:last').hide().each(function() {
      var el = document.createElement('div');
      fpar = 'fr=3';
      fpar2 = 'fr2=5';
      $(el).attr('id', 'container').attr('class', 'container').insertAfter($(this)).load(add_params(last_href, fpar+'&' + fpar2), function() {
        set_win_title();
        item_func();
        $('#dv_detailsSide .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
      });
    });    
    set_href($(this).attr('href'));
    return false;
  });
  $('#terminal font').bind('click', function() {
    $(this).parent().find('input').each(function() {
      this.checked = !this.checked;
      Custom.clear();
    });
  });
  $('#payinfo #addInfo_label').bind('click', function() {
    $(this).hide().prev().each(function() {this.focus()});
  }).prev().bind('blur', function() {
    if (this.value == '') $(this).next().show();
  }).bind('focus', function() {
    $(this).next().hide();
  });
  $('div.container:last #dv_orderedItems .flexcroll').each(function() {fleXenv.fleXcrollMain(this)});
}
function updatetm_pay (id)
{
  recalccart();
  recalccart_pay();
  window.waitamoment++;
  window.setTimeout('window.waitamoment--', 2000);
  carttm_pay[id] = window.setTimeout('_updatetm_pay(' + id + ')', 2000);
}
function _updatetm_pay(id)
{
    $('#invis').load('/cart_pre.php?fpay=1&update_product=' + id + '&qty=' + $('#itemList').add('div.addThis').add('div.selectedItem[@rel=c]').add('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('input.text[@rel=' + id + ']').attr('value') + '&rand=' + Math.random(), function() {
      recalccart();
      recalccart_pay();
      $(this).html('');
    });
}
function recalccart_pay()
{
  if ($('#dv_orderedItems .forPayment strong').length == 0) return;
  $('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('a.dec').each(function() {
    if ($(this).next('input').attr('value') == 1) {
      $(this).addClass('disabled');
    } else {
      $(this).removeClass('disabled');
    }
  });
  $('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('a.inc').each(function() {
    if ($(this).prev('input').attr('value') == 100) {
      $(this).addClass('disabled');
    } else {
      $(this).removeClass('disabled');
    }
  });
  if ($('div.selectedItem[@rel=p] a.delete').length == 1) {
    $('div.selectedItem[@rel=p] a.delete').addClass('disabled');
  } else {
    $('div.selectedItem[@rel=p] a.delete').removeClass('disabled');
  }
  var total = 0;
  var this_total = 0;
  var this_qty = 0;
  var total_ship = 0;
  var total_cour = 0;
  $('#dv_orderedItems input[@type=hidden][@rel]').each(function() {
    this_qty = $('#itemList').add('div.addThis').add('div.selectedItem[@rel=c]').add('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('input.text[@rel=' + $(this).attr('rel') + ']').attr('value');
    total_ship += this_qty*$(this).next().attr('value');
    this_total = parseInt($(this).attr('value')*this_qty);
    total += this_total;
    $('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('.price[@rel='+$(this).attr('rel')+']').each(function(){
      $(this).html($(this).html().replace(/[1-9][01-9]*/, this_total))
    });
    if (this_qty > 1) {
      $('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('.quantity2[@rel='+$(this).attr('rel')+']').each(function(){
        $(this).html($(this).html().replace(/[01-9]+/, this_qty)).removeClass('hide');
      });
    } else {
      $('#dv_orderedItems').add('div.selectedItem[@rel=p]').find('.quantity2[@rel='+$(this).attr('rel')+']').each(function(){
        $(this).html($(this).html().replace(/[01-9]+/, this_qty)).addClass('hide');
      });
    }
  });
  var total_grn = total;
  if ($('#dv_orderedItems .forPayment em.tt').length > 0) {
    total_grn = total*$('#dv_orderedItems input[@name=exchange]').attr('value');
  }
  var csh = $('#dv_orderedItems input[@name=city_ship]').attr('value').split('|');
  total_ship = Math.round(1*csh[4] + 0.01*csh[1]*total_grn + 0.01*csh[2]*total_ship);
  total_cour = (1*csh[3] && 1*csh[3] < total_grn) ? 0 : 1*csh[0];
  
  var lab = $('#payinfo .payIn input[@checked]').length ? $('#payinfo .payIn input[@checked]').parent() : $('#payinfo .payIn input[@type=hidden]').parent();
  if (lab.hasClass('payt7')) {
    $('#payinfo ul.paytype li.start a span').html('Менеджеру');
    $('#terminal font').html('Картой Visa / MasterCard через терминал');
    $('#dv_orderedItems .delivery').addClass('termdis2');
  } else {
    $('#payinfo ul.paytype li.start a span').html('Курьеру');
    $('#terminal font').html('Картой Visa / MasterCard курьеру с терминалом');
    $('#dv_orderedItems .delivery').removeClass('termdis2');
  }
  var def_percent = lab.attr('rel').split('|');

  $('#dv_orderedItems input[@name=total_ship]').attr('value', 0.01*Math.round(100*total_ship/$('#dv_orderedItems input[@name=exchange]').attr('value')));
  $('#payinfo .shipIn label').each(function() {
    var this_percent = $(this).attr('rel').split('|');
    var dif = Math.round(1*this_percent[0] + 0.01*this_percent[1]*total_grn +0.01*this_percent[2]*total_ship +0.01*this_percent[3]*total_cour) - Math.round(1*def_percent[0] + 0.01*def_percent[1]*total_grn +0.01*def_percent[2]*total_ship +0.01*def_percent[3]*total_cour);
    if (dif == 0) {
      $(this).find('span.pr').html('');
    } else {
      $(this).find('span.pr').html(' ('+(dif>0 ? '+' : '')+dif+' грн.)');
    }
  });
  if ($('#dv_orderedItems .forPayment em.tt').length > 0) {
    total_ship = (1*def_percent[0] + 0.01*def_percent[1]*total_grn + 0.01*def_percent[3]*total_cour)/$('#dv_orderedItems input[@name=exchange]').attr('value') + 0.01*def_percent[2]*$('#dv_orderedItems input[@name=total_ship]').attr('value');
    $('#dv_orderedItems .delivery span:first').html($('#dv_orderedItems .delivery span:first').html().replace(/[01-9]+/, Math.round(total_ship)));
    if (total_ship > 0) {
      total += Math.round(total_ship);
      $('#dv_orderedItems .delivery span:last').addClass('invis').prev().removeClass('invis');
    } else {
      $('#dv_orderedItems .delivery span:last').removeClass('invis').prev().addClass('invis');
    }
    $('#dv_orderedItems .forPayment em.tt').html($('#dv_orderedItems .forPayment em.tt').html().replace(/[1-9][01-9]*/, total));
    $('#dv_orderedItems .forPayment strong').html($('#dv_orderedItems .forPayment strong').html().replace(/[1-9][01-9]*/, parseInt(total*$('#dv_orderedItems input[@name=exchange]').attr('value'))));
  } else {
    total_ship = 1*def_percent[0] + 0.01*def_percent[1]*total_grn + 0.01*def_percent[2]*$('#dv_orderedItems input[@name=total_ship]').attr('value')*$('#dv_orderedItems input[@name=exchange]').attr('value') + 0.01*def_percent[3]*total_cour;
    $('#dv_orderedItems .delivery span:first').html($('#dv_orderedItems .delivery span:first').html().replace(/[01-9]+/, Math.round(total_ship)));
    if (total_ship > 0) {
      total += Math.round(total_ship);
      $('#dv_orderedItems .delivery span:last').addClass('invis').prev().removeClass('invis');
    } else {
      $('#dv_orderedItems .delivery span:last').removeClass('invis').prev().addClass('invis');
    }
    $('#dv_orderedItems .forPayment strong').html($('#dv_orderedItems .forPayment strong').html().replace(/[1-9][01-9]*/, parseInt(total)));
  }
}
