

(function($){
	$.fn.dropmenu = function(custom) {
		var defaults = {
		  	openAnimation: "slide",
			closeAnimation: "slide",
			openClick: false,
			openSpeed: 500,
			closeSpeed: 700,
			closeDelay:500,
			onHide: function(){},
			onHidden: function(){},
			onShow: function(){},
			onShown: function(){}
		  };
		var settings = $.extend({}, defaults, custom);
		
		var menu = this;
		var currentPage = 0;
		var delayTimer = "";
		
		// Trigger init
		init();
		
		/**
		 * Do preparation work
		 */
		function init(){

			// Add open button and class to parent of a submenu
			var items = menu.find(":has(li,div) > a").append('<span class="arrow"></span>');
			$.each(items, function(i, val) {
				if(items.eq(i).parent().is("li")){
					items.eq(i).next().addClass("submenu").parent().addClass("haschildren");
				}else{
					items.eq(i).parent().find("ul").show();
				}
			});
			
			if(settings.openClick){
				menu.find(".submenu").css("display", "none");
				menu.find(":has(li,div) > a").parent().bind("mouseleave",handleHover).bind("mouseenter",function(){ window.clearInterval(delayTimer); });
				menu.find("a span.arrow").bind("click", handleHover);
			}else{
				menu.find(":has(li,div) > a").bind("mouseenter",handleHover).parent().bind("mouseleave",handleHover).bind("mouseenter",function(){ window.clearInterval(delayTimer); });
			}
			
			
		}
		
		/**
		 * Handle mouse hover action
		 */
		function handleHover(e){
			if(e.type == "mouseenter" || e.type == "click"){
				window.clearInterval(delayTimer);
				var current_submenu = $(e.target).parent().find(".submenu:not(:animated):not(.open)");
				if(current_submenu.html() == null){
					current_submenu = $(e.target).parent().next(".submenu:not(:animated):not(.open)");
				}
				if(current_submenu.html() != null){
					settings.onShow.call(current_submenu);
					closeAllMenus();
					current_submenu.prev().addClass("selected");
					current_submenu.css("z-index", "90");
					current_submenu.stop().hide();
					openMenu(current_submenu);
				}
			}
			if(e.type == "mouseleave" || e.type == "mouseout"){
				current_submenu = $(e.target).parents(".submenu");
				if(current_submenu.length != 1){
					var current_submenu = $(e.target).parent().parent().find(".submenu");
					if(current_submenu.html() == null){
						var current_submenu = $(e.target).parent().find(".submenu");
						if(current_submenu.html() == null){
							var current_submenu = $(e.target).parent().parent().parent().find(".submenu");
						}
					}
				}
				if(current_submenu.html() != null){
					if(settings.closeDelay == 0){
						current_submenu.parent().find("a").removeClass("selected");
						closeMenu(current_submenu);
					}else{
						window.clearInterval(delayTimer);
						delayTimer = setInterval(function(){
							window.clearInterval(delayTimer);
							closeMenu(current_submenu);
						}, settings.closeDelay);	
					}
				}
			}
		}
		
		function openMenu(object){
			switch(settings.openAnimation){
				case "slide":
					openSlideAnimation(object);
					break;
				case "fade":
					openFadeAnimation(object);
					break;
				default:
					openSizeAnimation(object);
					break;
			}
		}
		
		function openSlideAnimation(object){
			object.addClass("open").slideDown(settings.openSpeed, function(){ settings.onShown.call(this); });
		}
		
		function openFadeAnimation(object){
			object.addClass("open").fadeIn(settings.openSpeed, function(){ settings.onShown.call(this); });
		}
		
		function openSizeAnimation(object){
			object.addClass("open").show(settings.openSpeed, function(){ settings.onShown.call(this); });
		}
		
		function closeMenu(object){
			settings.onHide.call(object);
			switch(settings.closeAnimation){
				case "slide":
					closeSlideAnimation(object);
					break;
				case "fade":
					closeFadeAnimation(object);
					break;
				default:
					closeSizeAnimation(object);
					break;
			}
		}
		
		function closeSlideAnimation(object){
			object.slideUp(settings.closeSpeed, closeCallback);
		}
		
		function closeFadeAnimation(object){
			object.fadeOut(settings.closeSpeed, function(){ $(this).removeClass("open"); $(this).prev().removeClass("selected"); });
		}
		
		function closeSizeAnimation(object){
			object.hide(settings.closeSpeed, function(){ $(this).removeClass("open"); $(this).prev().removeClass("selected"); });
		}
		
		function closeAllMenus(){
			var submenus = menu.find(".submenu.open");
			$.each(submenus, function(i, val) {
				$(submenus[i]).css("z-index", "1");
				closeMenu($(submenus[i]));
			});
		}
		
		function closeCallback(object){
			$(this).removeClass("open"); 
			if($(this).prev().attr("class") == "selected") settings.onHidden.call(this);
			$(this).prev().removeClass("selected");
		}
			
		// returns the jQuery object to allow for chainability.
		return this;
	}
	
})(jQuery);


function elBody(){ 
	return document.getElementsByTagName('BODY')[0]; 
}
function showPreloader(){
	var elPreloader = document.getElementById('Preloader');
	//var elPreloader = $('#Preloader');
	if( elPreloader!=null ) elPreloader.parentNode.removeChild(elPreloader);
	
	elPreloader = document.createElement('DIV');
	elPreloader.id = 'Preloader';
	elBody().appendChild(elPreloader);
	elPreloader.style.height = elBody().offsetHeight + 'px';
	
	elBody().className = 'noObjects';
}
function hidePreloader(){
	var elPreloader = document.getElementById('Preloader');
	if( elPreloader ) elPreloader.parentNode.removeChild(elPreloader);
	elBody().className = '';
}
function AddCartItem(id)
{
	showPreloader();
	var id_aromat=$("#aromat_id").attr('value');
	$.post(
		'/catalog/ajax.php',
		{
			type: "test-request",
			id: id,
			id_aromat: id_aromat
		},
		onAjaxSuccess
	);
}
function onAjaxSuccess(data)
{
	hidePreloader();
	if(data!='0')
	{
		$("#SecondCartInfoBlock").attr('innerHTML',data);
		$("#CartInfoWindow").attr('innerHTML',data);
		alert('Товар добавлен в корзину');
	}
	else alert("Ошибка при добавлении товара");
}
function PlusItem(id)
{
	var old_value=$("#QUANTITY_"+id).attr('value');
	var cur_value=parseInt(old_value)+1;
	$("#QUANTITY_"+id).attr('value',cur_value);
	var price=parseFloat($("#price_item_"+id).attr('value'));
	var all_sum=parseFloat($("#all_sum_value").attr('value'));
	$("#item_sum_value_format_"+id).attr('innerHTML',number_format(parseFloat(parseFloat($("#item_sum_value_"+id).attr('value'))+price),2,"."," "));
	$("#item_sum_value_"+id).attr('value',number_format(parseFloat(parseFloat($("#item_sum_value_"+id).attr('value'))+price),2,".",""));
	all_sum=parseFloat(all_sum+price);
	$("#all_sum_value").attr('value',all_sum);
	$("#TotalDiscountedPrice").attr('innerHTML',number_format(all_sum,2,"."," "));
	
}
function MinusItem(id)
{
	var old_value=$("#QUANTITY_"+id).attr('value');
	if(parseInt(old_value)>0)
	{
		var cur_value=parseInt(old_value)-1;
		$("#QUANTITY_"+id).attr('value',cur_value);
		
		var price=parseFloat($("#price_item_"+id).attr('value'));
		var all_sum=parseFloat($("#all_sum_value").attr('value'));
		all_sum=parseFloat(all_sum-price);
		$("#all_sum_value").attr('value',all_sum);
		$("#TotalDiscountedPrice").attr('innerHTML',number_format(all_sum,2,"."," "));
		
	}
	else	$("#QUANTITY_"+id).attr('value',0);
}
function DeleteItemBasket(id)
{
	if(confirm('Вы уверены что хотите удалить из заказа товар \n"'+$("#href_name_"+id).attr('innerHTML').trim()+'" ?'))
	{
		showPreloader();
		var tmp=str_all_product.split(",");
		var count_all="";
		for(var i=0; i<tmp.length; i++)
		{
			if(parseInt(tmp[i])>0)
			{
				count_all+=$("#QUANTITY_"+tmp[i]).attr('value');
				count_all+=",";
			}
			else
			{
				count_all+="0";
				count_all+=",";
			}
		}
		$.post(
			'/cart/ajax.php',
			{
				type: "test-request",
				id: id,
				all_id:str_all_product,
				all_count:count_all
			},
			onAjaxSuccessDelete
		);
	}
}
function onAjaxSuccessDelete(data)
{
	hidePreloader();
	if(parseInt(data)==0)
	{
		alert("Ошибка при удалении товара");
	}
	else
	{
		var tmp=data.split("|||");
		for(var i=1; i<=5; i++)
		{
			$("#td"+i+"_"+parseInt(tmp[0])).css({display:"none"});
		}
		$("#TotalDiscountedPrice").attr('innerHTML',number_format(parseFloat(tmp[1]),2,"."," "));
		alert('Товар удален из корзины');
	}
}

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
String.prototype.replaceAll = function(search, replace){
  return this.split(search).join(replace);
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}



