var options = {
  target: "#multi_content",
  beforeSubmit: showRequest, // функция, вызываемая перед передачей
  success: showResponse, // функция, вызываемая при получении ответа
  timeout: 3000 // тайм-аут
};

var tmp_val = 1;
var bascount = '';
var basket_left = 0;
var show_wind = '';

function init_basket() {
  bascount = $("#right_menu");
  show_wind = $("#show_window");
  putItemToBasket(0, 0);
  $('#basket_content').css({left:basket_left , top: bascount.offset().top+20});
  set_top();
}

function set_top() {
  var fly = $('#fly');
  var doc = $(document);
  if (doc.scrollTop() > fly.offset().top) {
    jqSlideTo('right_menu', fly.offset().left-40, doc.scrollTop() + 22, 500);
    if ($('#basket_content').css('display') == 'block') {
      jqSlideTo('basket_content', basket_left , doc.scrollTop()+20, 500);
    }
  } else { 
    jqSlideTo('right_menu',fly.offset().left-40, fly.offset().top + 22, 500); 
    if ($('#basket_content').css('display') == 'block') {
      jqSlideTo('basket_content', basket_left , fly.offset().top+20, 500);
    }
  }
}                

function fnShowBanner() {
  fnShowOverlay();
  var w = $(window);
  var elem =  $("#banner_cont");
  elem.css("left","0");
  elem.css("width","100%");
  elem.css("top","-300");
  elem.animate({ top: (w.height() - elem.height())/2+w.scrollTop() + 20 }, 1200);
}

function fnCloseBanner() {
  $("#banner_cont").hide();
  fnHideOverlay();
}

/* Фон старт */

function fnCreateOverlay() {
   $('<div id="site_wrap"></div>').appendTo("body");
   $("#site_wrap").prepend('<div id="site_overlay"></div>');
   $("#site_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0.4});
   if ($.browser.msie) {
    $("#site_wrap").prepend('<iframe id="site_bigIframe" scrolling="no" frameborder="0"></iframe>');
    $("#site_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
   }
   $("#site_overlay, #site_bigIframe").hide();
}

function fnShowOverlay() {
  $("#site_overlay,#site_bigIframe").fadeIn("fast").show();
}

function fnHideOverlay() {
  $("#site_overlay,#site_bigIframe").fadeOut("fast").hide();
}

function fnCloseOverlay() {
  $("#site_overlay,#site_bigIframe").fadeOut("fast").remove();
}

/* Прокрутка страницы */
function fnHideScroll() {
  $("body").css("overflow", "hidden");
}

function fnShowScroll() {
  $("body").css("overflow", "auto");
}
/* End */

/* Ajax заказ */   

function putItemToBasket(item_id, count_obj) {

  if (count_obj) {
    item_count = $("#"+ count_obj +"").val();
    url = '/ajax/get_item-'+item_id+'-'+item_count+'.htm';
  } else {
    url = '/ajax/get_item-'+item_id+'.htm';
  }      
  $.ajax({
    type: "POST",
    url: url,
    cache:false,
    success: function(page) {
      if (item_id) {
        var img = '<img id="fly_img" src="image/order2.gif" width="15">';
        var img2 = '<img id="fly_img" src="image/order2.gif" width="15">';
        var env = $("#envelop");
        if (env.length > 0) {
          env.empty().html(img);
          $("#fly_img").css({ left: env.offset().left, top: env.offset().top })
          $("#fly_img").animate({ left: bascount.offset().left + 5, top: bascount.offset().top + 5, opacity: 1 }, 600, function() {
            $(this).remove(); 
            env.empty().html(img2); 
            $("#right_menu").empty().html(page); 
          });        
        } 
      } else {
        $("#right_menu").empty().html(page);
      }         
    }
  });  
}

function basket_show() {  
  var wind_basket = $("#show_window");
  var basket_content = $('#basket_content');
  
  if (basket_content.css('width') != '0px') { //убрать    
    wind_basket.css({left: -950});
    basket_content.removeClass('no_bg');    
    var fly_left = $('#fly').offset().left-Math.floor(bascount.width()/2);
    basket_content.animate({
      left         : fly_left,
      width        : "0px",
      height       : "0px",
      opacity      : '0.4'
    }, 1000, function(){ fnHideOverlay("dark"); set_top(); });      
    $(window).scroll(function() { set_top(); })
  } else { //показать 
    $(window).unbind('scroll');
    divdescr = 'multi_content';
    ajax_url = '/ajax/basket.htm';
      $.ajax({
        type: "POST",
        url: ajax_url,
        cache:false,
        success: function(page) {      
          $("#"+divdescr+"").empty().html(page);
          fnAfterLoad();
          fnShowOverlay("dark");
          if (wind_basket.height()) {
          var fly_left = $('#fly').offset().left-670;
          basket_left = $('#fly').offset().left-670;        
          basket_content.css({left:$('#fly').offset().left-Math.floor(bascount.width()/2), top:bascount.offset().top+20, width: '0px', height: '0px', opacity:'0.2' });
          basket_content.animate({ left: fly_left, width: "650px", height: ""+wind_basket.height()+"px", opacity: 0.8 }, 1000, function() {
            basket_content.addClass('no_bg');
            wind_basket.css({left: basket_content.offset().left, top:basket_content.offset().top});
          });           
          }
        }
      }); 
  }                  
  return false;      
}

function fnAfterLoad() {
  if (!$.browser.msie) {
    $("#tabs a").corner("tl tr 8px");
    $("#tab_content").corner("tr bl br 8px");
  }     
  $(".count_cont").mouseover(function(){ $(this).addClass('sell_cont');  }); 
  $(".count_cont").mouseout(function(){ $(this).removeClass('sell_cont'); });
  //$("#multi_control div").mouseover(function(){  $("#multi_control div").removeClass('sell'); $(this).addClass('sell'); }); 
  //$("#multi_control div").mouseout(function(){ $(this).removeClass('sell'); }); 
  
  $(".count_min").click(function(){
    inp_obj = $("#inp_"+$(this).attr("item")+"");          
    if (parseInt(intval(inp_obj.val())) > 2) {
      inp_obj.val(parseInt(intval(inp_obj.val())) - 1);
    } else {
      inp_obj.val(1);
    }          
    fnPlusMin($(this).attr("item"), inp_obj.val());
  });        
  
  $(".count_min").mouseover(function(){ $(this).addClass('chose_min');  }); 
  $(".count_min").mouseout(function(){ $(this).removeClass('chose_min'); });
  
  $(".count_plus").mouseover(function(){ $(this).addClass('chose_plus');  }); 
  $(".count_plus").mouseout(function(){ $(this).removeClass('chose_plus'); });
         
  $(".count_plus").click(function(){
    inp_obj = $("#inp_"+$(this).attr("item")+"");
    if (parseInt(intval(inp_obj.val())) < 0) {
      inp_obj.val(1);
    } else {      
      inp_obj.val(parseInt(intval(inp_obj.val())) + 1);            
    }          
    fnPlusMin($(this).attr("item"), inp_obj.val());
  });
  
  $(".count_input").focus( function() { tmp_val = $(this).val(); });
  
  $(".count_input").change( function() {           
     if (/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test($(this).val())) {
       if ($(this).val() <= 0) {
         $(this).val(tmp_val);
         alert('Допустимы только числовые значение больше 0!'); 
       } else {
         fnPlusMin($(this).attr("item"), $(this).val());
       }
     } else {
       $(this).val(tmp_val);
       alert('Допустимы только числовые значение больше 0!'); 
     }             
  });
  
  $(".count_input").keyup( function() {           
    if (/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test($(this).val())) {
       if ($(this).val() <= 0) {
         $(this).val(tmp_val);         
       }
    } else {
       $(this).val(tmp_val);
    }             
  });
  
  $(".item_del").click(function(){          
    fnDellChartItem("multi_content", $(this).attr("item"));
  }); 
  
  $(".item_del").mouseover(function(){ $(this).addClass('sel_del');  }); 
  $(".item_del").mouseout(function(){ $(this).removeClass('sel_del'); });  
 
}

function fnShowOrder(divdescr) {
  SetLoader(divdescr);    
  $.ajax({
    type: "POST",
    url: 'ajax/order.htm',
    cache:false,
    success: function(page) {      
      $("#"+divdescr+"").empty().html(page);
      $("#order_form").submit(function() {
        $(this).ajaxSubmit(options);
        return false;
      });
      fnAfterLoad();
    }
  });
}

function fnShowBasket(divdescr) {
  SetLoader(divdescr);    
  $.ajax({
    type: "POST",
    url: 'ajax/basket.htm',
    cache:false,
    success: function(page) {      
      $("#"+divdescr+"").empty().html(page);
      fnAfterLoad();
    }
  });
}

function fnScrollNextPrev(ord, type) {
  if (!ord) ord = 1;    
  now_page = parseInt($("#ord_now").val());
  items = $(".table_basket tr[order='true']");
  items_count = items.length;  
  all_pages = Math.ceil( items_count / ord );  
  if (type == 'next') {
    old_page = now_page;
    if (all_pages > old_page) {
      first_item = now_page * ord;    
      now_page = now_page + 1;    
      last_item = now_page * ord;
    }
  } else if (type == 'prev') {
    old_page = now_page; 
    if (old_page > 1) {      
      now_page = now_page - 1;
      last_item = now_page * ord;
      first_item = (now_page * ord) - ord;
    }
  }               
  
  if (now_page > 0) {        
    items.each(function (i) {
      item_id = i + 1;      
      if (type == 'next' && (all_pages > old_page)) {
        if ((item_id > last_item) || (item_id <= first_item)) {          
          $(this).hide();
        } else {
          $(this).show();
        }
      } else if (type == 'prev' && old_page > 1) {
        //alert('i='+item_id+'&l='+last_item+'&f='+first_item+'');
        if ((item_id <= last_item) && (item_id > first_item)) {
          $(this).show();
        } else {
          $(this).hide();
        }
      }      
    }); 
    $("#ord_now").val(now_page);
  }
  //$(".table_basket tr[order='next']").removeClass("order_tr").addClass("hidden_tr");
}

function fnCloseBanner() {
  $("#banner_cont").hide();
  fnHideOverlay();
}

function fnFormClose(win_id) {
  $("#img_cart").hide();
  $("#"+win_id+"").hide();
  fnHideOverlay();
  //fnShowScroll();  
  left_b = $("#smbg").offset().left;
  left_p = $("#smbg").offset().left + $("#smbg").width() - price_b.width();
  basket_b.css("left", left_b);
  price_b.css("left", left_p);
}

function showRequest(formData, jqForm, options) {
  var queryString = $.param(formData);
  //alert('Вот что мы передаем: \n\n' + queryString);
  SetLoader('multi_content');
  return true;
}

function SetLoader(win_id) {
  $("#"+win_id+"").html($("#loader").html());
}
           

function showResponse(responseText, statusText)  {
  fnAfterLoad();
}


function fnPlusMin(item_id, count) {
  $.ajax({
    type: "POST",
    url: '/ajax/get_item-'+item_id+'.htm?count='+count+'',
    cache:false,
    success: function(page) {      
      bascount.empty().html(page);
      $("#td_inp_"+item_id+"").html($("#item_price_inp").val());
      $("#intogo").html($("#it_price").html());
    }
  });  
}           

function fnEmptyChart(divdescr) {
  SetLoader(divdescr);
  $.ajax({
    type: "POST",
    url: '/ajax/empty_basket.htm',
    cache:false,
    success: function(page) {      
      putItemToBasket(0);
      $.ajax({
        type: "POST",
        url: '/ajax/basket.htm',
        cache:false,
        success: function(page) {      
          $("#"+divdescr+"").empty().html(page);
          fnAfterLoad();
        }
      });
    }
  }); 
}

function fnDellChartItem(divdescr, item_id) {
  SetLoader(divdescr);
  $.ajax({
    type: "POST",
    url: '/ajax/basketdel-'+item_id+'.htm',
    cache:false,
    success: function(page) {      
      putItemToBasket(0);
      $.ajax({
        type: "POST",
        url: '/ajax/basket.htm',
        cache:false,
        success: function(page) {      
          $("#"+divdescr+"").empty().html(page);
          fnAfterLoad();
        }
      });
      //$("#multi_control").hide();
    }
  }); 
}


function intval(mixed_var, base) { 
  var tmp; 
  var type = typeof( mixed_var ); 
  if (type == 'boolean'){ 
    if (mixed_var == true) { 
      return 1; 
    } else { 
      return 0; 
    } 
  } else if (type == 'string') { 
    tmp = parseInt(mixed_var * 1, 10); 
    if (isNaN(tmp) || !isFinite(tmp)) {
      return 0; 
    } else { 
      return tmp.toString(base || 10); 
    } 
  } else if (type == 'number' && isFinite(mixed_var) ) { 
    return Math.floor(mixed_var); 
  } else { 
    return 0; 
  } 
}

function fnSendOrder(form_name) {
  if (!form_name.order_company.value.match(/.+/)) {
    alert("Укажите наименование организации!");
    form_name.order_company.focus();
    return false;
  } 
  if (!form_name.order_adres.value.match(/.+/)) {
    alert("Укажите почтовый адрес!");
    form_name.order_adres.focus();
    return false;
  }   
  if (!form_name.order_phone.value.match(/^[0-9+][0-9 -\(\)]*/)) {
    alert("Правильно укажите телефон!\nТелефон должен начинаться с цифры или \"+\" и может содержать пробелы, скобки и знак \"-\".");
    form_name.order_phone.focus();
    return false;
  }
  if (!form_name.order_name.value.match(/.+/)) {
    alert("Укажите контактное лицо!");
    form_name.order_name.focus();
    return false;
  } 
  if (!form_name.order_email.value.match(/.+/)) {
    alert("Укажите E-mail!");
    form_name.order_email.focus();
    return false;
  }  
  $("#order_form").submit();
}


function fnShowWindow(win_id, type, ajax_url, divdescr) {
  //fnHideScroll();
  fnShowOverlay();    
  var w = $(window);
 /* if ($("#img_cart").length == 0) {
    $('<div id="img_cart"></div>').appendTo("body");
  } */
 
  var elem =  $("#"+win_id+"");
  if (type == 2) {
    elem.animate({ top: (w.height() - elem.height())/2+w.scrollTop() + 20 }, 1200);   
  } else {
    elem.css("top",(w.height()-elem.height())/2+w.scrollTop() + "px");
    elem.css("left",(w.width()-elem.width())/2+w.scrollLeft() + "px");
  }
  if (ajax_url && divdescr) {
    SetLoader(divdescr);    
    $.ajax({
      type: "POST",
      url: ajax_url,
      cache:false,
      success: function(page) {      
        $("#"+divdescr+"").empty().html(page);
        fnAfterLoad();
        $("#img_cart").css("top",($("#"+win_id+"").offset().top + $("#"+win_id+"").height() - 110 + "px"));
        $("#img_cart").css("left",($("#"+win_id+"").offset().left - 50 + "px"));
        $("#img_cart").show();               
      }
    });
  }  
  $("#"+win_id+"").show();
}