
function openwin(url,width,height)
{
  myWin= open(url, "_blank",
    "width=" + width + ",height=" + height + ",status=no,toolbar=no,menubar=no,scrollbars=yes");
}


	function switch_to_tab(__item_id, __big_tab_id, __tab_id) {
		var max_tab_num = 20; 
		for(i=1; i<max_tab_num; i++) {
			var el_name = 'item' + __item_id + '_tab' + __big_tab_id + '_' + i;
			//alert(el_name);
			var el = document.getElementById(el_name);
			if(el)
				document.getElementById(el_name).style.display = 'none';
		}
		document.getElementById('item' + __item_id + '_tab' + __big_tab_id + '_' + __tab_id).style.display = '';
		return false;
	}


	function switch_to_tab_big(__item_id, __tab_id) {
		var max_tab_num = 20; 
		for(i=1; i<max_tab_num; i++) {
			var el_name = 'item' + __item_id + '_tab_big' + i;
			//alert(el_name);
			var el = document.getElementById(el_name);
			if(el)
				document.getElementById(el_name).style.display = 'none';
		}
		document.getElementById('item' + __item_id + '_tab_big' + __tab_id).style.display = '';
		return false;
	}


	$(document).ready(function(){
		$(".ajaxCartForm").submit(function(){
			// 'this' refers to the current submitted form
			//alert('123');
			var str = $(this).serialize();
			var the_form = $(this);
			$.ajax({
				type: "POST",
				url: "index.php?object=catalog&action=add_to_cart",
				data: str,
				//dataType: "xml",  
				success: function(msg){
					$('#note', the_form).ajaxComplete(function(event, request, settings){
						$(':input', the_form)
						.not(':button, :submit, :reset, :hidden')
						.val('')
						.removeAttr('checked')
						.removeAttr('selected');
						//seTimeout()
						var result = process_reply(msg);
						$('#submit_field', the_form).hide().delay(2500).fadeIn();
						//$(this).show();
						$(this).hide();
						$(this).html(result);
						$(this).show().delay(1500).fadeOut();
						$('#note', the_form).delay(3000).unbind();
							//$('#submit_field', the_form).show().fadeIn('slow');
					});
				}
			});

			//$(this).reset();
			return false;
		});
	});

	function process_reply(msg) {
		var result = '';
		var vars = $.parseJSON(msg);
        if(vars.status == 'ok')
        {
			$('#top_cart_amount').html(vars.amount);
			result = '<div class="notification_ok">Товары были добавлены в корзину</div>';

			$("#cheque_body").hide();
			$("#cheque_loading").fadeIn();  
			$("#cheque_body").empty();

			//alert(vars.items);
			for (var item_key in vars.items) {
				//alert(item_key);
				//var val = some_array [key];
				//alert (key+' = '+val);
				var item = vars.items[item_key];
				//alert(item);
				$("#cheque_body").append('<div class="item"><a href="index-object-catalog-id-' + item.item_id + '_' + item.sequence_num + '.html">' + item.title_cut_utf + '</a><a href="#" onClick="return remove_item(' + item.item_id + ', ' + item.sequence_num + ');" style="float: right;"><img src="design/int_window_cross.png"></a></div><div class="price">' + item.price + ' x ' + item.quantity + ' = ' + item.amount + '</div>');  
			}
			if(vars.discounts && vars.discounts.length && vars.discounts.length > 0)
			{
				$("#cheque_body").append('<div class="item">Скидки:</div>');  
				for (var item_key in vars.discounts) {
					//alert(item_key);
					//var val = some_array [key];
					//alert (key+' = '+val);
					var item = vars.discounts[item_key];
					//alert(item);
					$("#cheque_body").append('<div class="price">' + item.title_cut_utf + '&nbsp;&nbsp;' + item.previous_total + ' x ' + item.value + '% = (' + item.amount + ')</div>');  
				}
			}

			//for(var i=0; i<vars.items)
			//vars.items.each(function() {
			//alert($(this));
			//find each instance of loc in xml file and wrap it in a link
			//   $("#cheque_body").append('<div>' + $(this).title_cut + ', ' + $(this).price + ' x ' + $(this).quantity + ' = ' + $(this).amount + '</div>');  
			//});  <a href="index-object-catalog-action-view_cart.html">Перейти к оформлению</a>
			if(vars.ship_price_float > 0) {
				$("#cheque_body").append('<div class="subtotal">СУММА ЗАКАЗА: ' + vars.amount + ' руб.</div>');  
				$("#cheque_body").append('<div class="item"><a href="index-object-pages-page-5.html">Доставка</a><div class="price_inline">' + vars.ship_price + '</div></div>');  
			}

			$("#cheque_body").append('<div class="subtotal">ИТОГО: ' + vars.amount_ship + ' руб.' + '</div>');  
			if(vars.can_be_sent)
				$("#cheque_body").append('<a href="index-object-catalog-action-view_cart.html">Перейти к оформлению</a>');  
			else
				$("#cheque_body").append('<div class="message">Для оформления заказа необходимо набрать товаров на сумму более ' + vars.min_amount + ' руб.</div>');  

			$("#cheque_loading").fadeOut();  
			$("#cheque_body").fadeIn();
		}
		else
		{
			result = '"' + (vars.status ? vars.status : 'Ошибка') + '"';
		}
		return result;
	}

	function add_item(__item_id, __tab_id, __subitem_id) {
		var el = $('#subitem_'+__item_id+'_'+__tab_id+'_'+__subitem_id+'_quantity');
		el[0].value = (el[0].value ? parseInt(el[0].value) : 0) + 1;
		return false;
	}

	function dec_item(__item_id, __tab_id, __subitem_id) {
		var el = $('#subitem_'+__item_id+'_'+__tab_id+'_'+__subitem_id+'_quantity');
		el[0].value = (el && el[0].value && el[0].value > 0) ? parseInt(el[0].value) - 1 : 0;
		return false;
	}

	function remove_item(__item_id, __sequence_num) {
		$.ajax({
			type: "GET",
			url: "index.php?object=catalog&action=add_to_cart&subitem_" + __item_id + "_0_" + __sequence_num + "_update",
			//dataType: "xml",  
			success: function(msg){
				var result = process_reply(msg);
			}
		});
		return false;
	}



	function switch_to_level_tab(__tab_id) {
		var max_tab_num = 20; 
		for(i=1; i<max_tab_num; i++) {
			var el_name = 'level_tab_' + i;
			//alert(el_name);
			var el = document.getElementById(el_name);
			if(el)
				document.getElementById(el_name).style.display = 'none';
		}
		document.getElementById('level_tab_' + __tab_id).style.display = '';
		return false;
	}


	function tips2_init() {
		$("a[title]")
         .qtip({
            position: {
               my: 'top center', // Use the corner...
               at: 'bottom center' // ...and opposite corner
            },
            show: {
               event: 'mouseover', // Don't specify a show event...
               ready: false // ... but show the tooltip when ready
            },
            hide: {
		 when: 'unfocus',
		 fixed: true
	     },  // 'click', // Don't specify a hide event
	     style: {
               classes: 'ui-tooltip-shadow ui-tooltip-youtube' // + styles[i]
            }
         });				
	}


	function tips_init() {
		//$.each($(".with_tips"), function(){this.title.replace("|", "\\n");return false;});
				$(".with_tips").qtip({ 					
					position: { 
						corner: {
							tooltip: 'topRight', 
							target: 'bottomRight'
						}
					},				
					show: {
                  				when: 'mouseover',
						solo: true
                  			//	ready: true // Show the tooltip when ready
               			},
					hide: {
						when: 'unfocus',
						fixed: true
					},  // 'click', // Don't specify a hide event
					style: {
						name: 'cream',
						tip: true,
						border:
						{
							width: 1,
							radius: 3,
							color: '#666'					
						},
						color: '#000',
						background: '#f0f0f0'
					} 
				});				
	}



  function move_page() {
	var myFile = document.location.toString();
	if (myFile.match('#')) { // the URL contains an anchor
		var test = myFile.split('#');
		if(test[1]) {
			var myAnchor = '#' + test[1];
			var destination = $(myAnchor).offset().top;
			//alert('about to animate '+destination);
			$("html").animate({scrollTop: 0}, 10);
			$("html").animate({scrollTop: destination}, 2000);
		}
		return false;
	}
  }


	function init_top_menu(){
		var $mainmenu=$(".drop-down");
		var $headers=$mainmenu.parent();
		$headers.each(function(i){
			var $curobj=$(this);
			var $subul=$(this).find('.drop-down:eq(0)');
			
			$curobj.hover(
				function(e){
					var $targetul=$(this).children(".drop-down:eq(0)");
					$targetul.slideDown(300);
				},
				function(e){
					var $targetul=$(this).children(".drop-down:eq(0)");
					$targetul.stop(true,true);
					$targetul.slideUp(300);
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find(".drop-down").css({display:'none', visibility:'visible'})
	}


var current_point = null;

// left catalog menu
function initMenu() {
  $('.menu_items img').wrap('<div></div>');
  $('.menu_items ul').hide();
  var selected_item = $('.menu_items .selected ul');
  if(selected_item)
    selected_item.show();
  else
    $('.menu_items ul:first').show();


$('.menu_items li a').live("mouseenter mouseleave",function(e){

  current_point = $(this);
	//alert(e.type);
  if (e.type == 'mouseenter' ) {
	//alert($(this));
   $(this).data('timeout',setTimeout(function() {
      		//var checkElement = $(this).next();
		var checkElement = current_point.next();
		//alert(checkElement);
      		if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        		return false;
      		}
      		if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
	 		var parent_selected = $('.menu_items').children('li:not(.single)').children('a.selected');
	 		if(parent_selected) {
	   			parent_selected.removeClass('selected');
	 		}
        		$('.menu_items ul:visible').slideUp('fast'); //normal
        		checkElement.slideDown('slow'); //normal
        		checkElement.parent().children('a').addClass('selected');
        		return false;
      		}
      }, 500));
  } else {
   clearTimeout($(this).data('timeout'));
  }
 });

/*
  //$('.menu_items li a').click(
  $('.menu_items li a').hover(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        return false;
      }
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
	 var parent_selected = $('.menu_items').children('li:not(.single)').children('a.selected');
	 if(parent_selected) {
	   parent_selected.removeClass('selected');
	 }
        $('.menu_items ul:visible').slideUp(500); //normal
        checkElement.slideDown(500); //normal
        checkElement.parent().children('a').addClass('selected');
        return false;
      }
    }
  );
*/
}


function theRotator() {
	// Устанавливаем прозрачность всех картинок в 0
	$('div.rotator ul li').css({opacity: 0.0});
 
	// Берем первую картинку и показываем ее (по пути включаем полную видимость)
	$('div.rotator ul li:first').css({opacity: 1.0});

	$('div.rotator').append('<div class="left_ar"><a href="#" onClick="show_previous();return false;"><img src="design/galery_prev.png" style="width: 40px; height: 40px;"></a></div>');
	$('div.rotator').append('<div class="right_ar"><a href="#" onClick="show_previous();return false;"><img src="design/galery_next.png"></a></div>');
 
	// Вызываем функцию rotate для запуска слайдшоу, 5000 = смена картинок происходит раз в 5 секунд
	rotator_id = setInterval('rotate()',5000);
}

function animate(current, next) {
	// Подключаем эффект растворения/затухания для показа картинок, css-класс show имеет больший z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);
 
	// Прячем текущую картинку
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
}
 
function rotate() {	
	// Берем первую картинку
	var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));
 
	// Берем следующую картинку, когда дойдем до последней начинаем с начала
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));	
 
	// Расскомментируйте, чтобы показвать картинки в случайном порядке
	// var sibs = current.siblings();
	// var rndNum = Math.floor(Math.random() * sibs.length );
	// var next = $( sibs[ rndNum ] );

	animate(current, next);
};

function show_previous() {
	clearInterval(rotator_id);
	var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));
	var prev = ((current.prev().length) ? ((current.prev().hasClass('show')) ? $('div.rotator ul li:last') : current.prev()) : $('div.rotator ul li:last'));	
	animate(current, prev);
	rotator_id = setInterval('rotate()',5000);
}

function show_next() {
	clearInterval(rotator_id);
	var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));	
	animate(current, next);
	rotator_id = setInterval('rotate()',5000);
}






var last_search_id = 0;

function initAutoSearch() {
	$('input[name=words]').keyup(function() {
		var the_form = $(this).parents('form');
		var str = the_form.serialize();
		var d = new Date();
		last_search_id = d.getTime();
		var copy_search_id = last_search_id;
		$.ajax({
			type: "POST",
			url: "index.php?object=search&ajax=1",
			data: str,
			//dataType: "xml",  
			success: function(msg){
				//alert(msg);
				if(copy_search_id == last_search_id) {
					var result = process_search_reply(msg);
				}
				//alert(result);
			}
		});
		return false;
	});
	$('input[name=words]').focusout(function() {
		$(".search_results").fadeOut();
	});
}

function process_search_reply(msg) {
	var result = '';
	var vars = $.parseJSON(msg);
	var object_ids = ['news', 'articles', 'catalog'];
	for(var obj_key in object_ids) {
		var obj_id = object_ids[obj_key]
		$("#search_results_" + obj_id).hide();
		$("#search_list_" + obj_id).empty();
	}
	for(var obj_key in object_ids) {
		var obj_id = object_ids[obj_key]
		if(vars.results && vars.results[obj_id]) {
			var obj_results = vars.results[obj_id];
			for (var item_key in obj_results) {
				var item = obj_results[item_key];
				$("#search_list_" + obj_id).append('<li><a href="' + item.link + '">' + (item.picture.big_icon != undefined ? '<div><img src="' + item.picture.big_icon + '"></div> ' : '') + item.title + '</a></li>');  
			}
			$("#search_results_count_" + obj_id).text(vars.results_count[obj_id]);
			$("#search_results_" + obj_id).show();
		}
	}
	return result;
}

$(document).ready(function() {
	//alert('123');
	$(".fancybox").fancybox({'centerOnScroll': true});
	$(".fancybox_inline").fancybox({'centerOnScroll': true});
	$(".thickbox").fancybox({'centerOnScroll': true});
	$(".colorbox").fancybox({'centerOnScroll': true});

	init_top_menu();
	initMenu();
	tips2_init();
	//tips_init();
	//$(".with_tips2[title]").tooltip({effect: 'slide'});
	move_page();
	theRotator();
	initAutoSearch();
});


