// форматит список автокомплита
function ac_formatItem(row,i,max,value){
	    var str = "<table><tr><td style='width:90px'>";
		if (row[2]){
			str=str+"<img src='"+row[2]+"'/></td><td>";
			    } else {
				    str=str+"</td><td>";
					}
	if (row[1]=="0")  {
		var miniinfo= "отдел<hr/><span class='ac_category'>" +row[0]+"</span>";
	} else {
		var miniinfo= "<span class='ac_onefood'>Отдел:"+row[3]+"</span><br/>"+row[0]+"<br/>Цена:<span class='ac_price'>"+row[4]+"</span>";
	}
	str = str+miniinfo+"</td></tr></table>";
	return str;
}


jQuery(document).ready(function(){
//    $("#search_keywords").focus();
    $("#search_keywords").autocomplete("/autocomplete/", {
		max: 15,
        delay: 200,
        minChars: 2,
        matchContains:true,
        formatItem: ac_formatItem,
		selectFirst: false,
		scroll: true,
		scrollHeight: 570,
		cacheLength:1,
		matchSubset:false
    });
//    $('#nl_informer').nl_informer(10, {partner:'e-pru', source:'news', target:'_blank'});
	$(".slider").slider({
			range: 'min',
			value: 1,
			min: 0.2,
			max: 4,
			step: 0.1,
			orientation: 'horizontal',
			slide: function(event, ui) {
				p=$(this).attr('id');
				p=p.substring(2);
// 				$(".weight[id="+p+"]").html(ui.value);
				$(".weight#we"+p).html(ui.value+'кг');
				$('input:hidden[name=quantity][id=quan'+p+']').val(ui.value);
				quaprice=$('input:hidden[name=quaprice][id=quap'+p+']').val();
				// ui.value*quaprice
				$('#cpr'+p).html((ui.value*quaprice).toFixed(2)+'р');
			}
	});

/*     $(window).scroll(function () {
		var cartY = 150;
		h=$('#sidebar-primary').height();
		wh = $(window).height();
		if (h+cartY<wh) { // scroll only of not big enough
		//alert('go!')
		 var offset = cartY+$(document).scrollTop()+"px";
		 if (1) {
		 $('#sidebar-primary').animate({
          marginTop:offset}, {queue: false, duration: 250} );
		 }
		}
     });*/

/*ddsmoothmenu.init({
	mainmenuid: "menu_container", //Menu DIV id
	orientation: 'v', //Horizontal or vertical menu: Set to "h" or "v"
	classname: 'ddsmoothmenu-v', //class added to menu's outer DIV
// 	customtheme: ["#804000", "#482400"],
	contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
});*/
$('.producti').each(function(){
	$(this).qtip({
		show : {delay:400},
	content: {
		prerender: false,
		url: '/product-tooltip/',
		data: { id: $(this).attr('id').substring(7) },
		method: 'get'
	},
	position: {
// 	  type: 'static',
	  adjust: { screen: true }
//       corner: {
//          target: 'rightMiddle',
//          tooltip: 'leftMiddle'
//       }
// 	  adjust: { screen: true,x:0,y:0 }
	 },
	style: {
      width: 350,
      padding: 3,
      border: {
         width: 7,
         radius: 5
      },
      name: 'light',
	  tip: 'leftMiddle'
   },
	show: 'mouseover',
	hide: 'mouseout'
	});
});

$('.baskets').each(function(){
	$(this).qtip({
		show : {delay:400},
	content: {
		prerender: false,
		url: '/basket-tooltip/',
		data: { id: $(this).attr('tooltip').substring(7) },
		method: 'get'
	},
	position: {
// 	  type: 'static',
      corner: {
         target: 'rightMiddle',
         tooltip: 'leftMiddle'
      }
// 	  adjust: { screen: true,x:0,y:0 }
	 },
	style: {
      width: 500,
      padding: 3,
      border: {
         width: 7,
         radius: 5
      },
      name: 'light',
	  tip: 'leftMiddle'
   },
	show: 'mouseover',
	hide: 'mouseout'
	});
});

$('a[title]').qtip({ style: { name: 'green', tip: true} });
$('img[title]').qtip({ style: { name: 'green', tip: true}, position:{adjust: { screen: true }},show : {delay:50} });
$('#cart_total[title]').qtip({ style: { name: 'green', tip: true },	position: {
      corner: {
         target: 'leftMiddle',
         tooltip: 'rightMiddle'
      } } });

var submitOptions = {
    url : '/cart/add/ajax/',
    type : 'POST',
    dataType : 'json',
    success : function(json) {
        SSS.updatestatus(json, '#statusupdate', '#quickcart .cartcount');
    }
}; $('form.rapidbasket').ajaxForm(submitOptions);
});

var SSS = {
    // handle a form submission
    // including updating the cart quantity
    updatestatus : function(json, result_tgt, count_tgt) {
        var result = json.results;
        
        var errors = json.errors;
        
        if (errors&&errors!="") {
            for (var i = 0; i<errors.length; i++) {
                which = errors[i][0];
                err = errors[i][1];
                if (which == 'quantity') {
                    $.notify({text:'Запрашиваемое количество продукта недоступно', title:'Внимание', icon:'/static/images/dialog-warning.png',delay:2200});
                }
                else if (which == 'product') {
                    $.notify({text:'Запрашиваемое количество продукта недоступно', title:'Внимание', icon:'/static/images/dialog-warning.png',delay:2200});
                }
            }
        }
        else {
			$.notify({text:'Количество товаров изменено', title:'Уведомление', icon:'/static/images/dialog-information.png',delay:1400});
			$.get("/minicart/", function(data){
				$('#minicart').html(data);
			});
        }
    },
    validate : function(formArray, jqForm, tgt) {
        var qty = 0;
        for (var i = 0; i<formArray.length; i++) {
            var elt = formArray[i];
            if (elt.name == 'quantity') {
                qty = elt.value;
            }
        }
        if (! parseInt(qty)>0) {
            $('#label-quantity span.error').html("Choose a quantity");
            return false;
        }
        return true;
    }
};

function ajax_qty(item,qty,diff) {
	var data = {"cartitem":item, "quantity":qty+diff};
	$.post("/cart/qty/ajax/", data, ajax_qty_success);
}

function ajax_qty_success(json) {
        SSS.updatestatus(json, '#statusupdate', '#quickcart .cartcount');
    }
function check_for_service(order, reject) {
	var check_for_service_counter=3;
	if (reject) {
		var data = {"good":-1, 'order':order}
		$.get("/cfs-ajax/", data, check_for_service_succ);
	} else {
		var good=$('[name=cfs_good]').val();
		var beauty=$('[name=cfs_beauty]').val();
		var cash=$('[name=cfs_cash]').val();
		if (good>0) {check_for_service_counter--}
		if (beauty>0) {check_for_service_counter--}
		if (cash>0) {check_for_service_counter--}
		$('#check_for_service_counter').html(check_for_service_counter);

		if (check_for_service_counter==0) {
			var data = {"good":good, "beauty":beauty, 'cash':cash,'order':order};
			$.get("/cfs-ajax/", data, check_for_service_succ);
		}
	}
}
function check_for_service_succ(data)
{
	if (data=="1") {
		$('#check_for_service').css("background-color","#92f5b3").css("padding","30px").css("text-align","center");
		$('#check_for_service').html('<b>Спасибо!</b>');
		setTimeout ( check_for_service_hide, 700 );
	} else if (data=="-1") {
		check_for_service_hide();
	} else {
		alert(data);
	}
}
function check_for_service_hide() {
	$('#check_for_service').fadeOut('normal');
}

function add2favorites(id) {
    var data = {"id":id};
    $.get("/ajax_add2favorites/", data, add2favorites_cb);
}
function add2favorites_cb(data) {
 if (data=="1") {$.notify({text:'Продукт добавлен в Избранное', title:'Успешно', icon:'/static/images/dialog-information.png',delay:1600});}
 else {alert(data)}
}