
MAG.check_browser = function(){
	if($.browser.opera){
		$(document.body).addClass('opera');
	}else if($.browser.webkit){
		$(document.body).addClass('webkit');

		if(navigator.userAgent.toLowerCase().match(/chrome/)){
			$(document.body).addClass('chrome');
		}
	}
}

$(function(){
	// asd a
	MAG.processed_inputs($('input[type=text],input[type=password],textarea,select'));

	// Стандартни слайдери.
	$('.slider_wrapper').each(function(){
		var holder = $(this);
		var slider = holder.find('.slider');
		var select = holder.find('select');

		select.bind('change', function(){
			slider.slider('value', this.selectedIndex);
		});

		slider.slider({
			value	: select.prop('selectedIndex'),
			min		: 0,
			max		: select.prop('options').length - 1,
			step	: 1,
			animate	: true,
			change	: function(){
				select.prop('selectedIndex', slider.slider('value'));

				//$.cookie('slider_' . select.attr('name'), select.val(), {
				//   path    : MAG.root,
				//   domain  : MAG.cookie_domain
				//});

				if(select.prop('form')){
					select.prop('form').submit();
				}
			}
		});
	});

	// Фиксове за IЁ
	if($.browser.msie && $.browser.version < 9){
		$('#header_menu .submenu_wrapper').append('<div class="orange_button_tr"/><div class="ie_shadow"/>');
		$('#header_buttons .dropdown').append('<div class="orange_button_tl top_border"/><div class="ie_shadow"/>');
		$('.marrygoround .previous, .marrygoround .next').append('<div class="ie_shadow"/>');

		$('.marrygoround .next').append('<div class="shadow_border_tl"/><div class="shadow_border_bl"/>');
		$('.marrygoround .previous').append('<div class="shadow_border_tr"/><div class="shadow_border_br"/>');
		$('.right_column .filter_wrapper').append('<div class="shadow_border_tr"/><div class="shadow_border_br"/>');
		$('#breadcrumb .shadow').append('<div class="shadow_border_tl"/><div class="shadow_border_bl"/><div class="ie_shadow"/>');

		if($.browser.version == 7){
			$('.marrygoround .next a').parent().after($('.marrygoround .next a').addClass('next').attr('hideFocus', 'true'));
			$('.marrygoround .previous a').parent().after($('.marrygoround .previous a').addClass('previous').attr('hideFocus', 'true'));
		}

		$('table.list tr:even').addClass('even');
		$('ul.listing li:odd').addClass('odd');

		MAG.add_round_corners($('#header_menu .title'), 'orange_button', true, true, true, true);
		MAG.add_round_corners($('.list_item_n .grey_back'), 'grey_back', true, true, true, true);
		MAG.add_round_corners($('.orange_button').css('position', 'relative'), 'orange_button', true, true, true, true);
		MAG.add_round_corners($('.tabs_list a, .grey_button'), 'grey_button', true, true, true, true);
	}

	if($('.promotions').length > 0) {
		$('.promotions input[name="max_telecom"]').max_telecomed();
	}


	// Стандартни табове
	new function(){
		$('.tabs_list').each(function(){
			var list = $(this);
			var items = list.find('>*');

			items.bind('click', function(){
				$(this).addClass('active');
				items.not(this).removeClass('active');

				return false;
			});
		});
	}

	// Real tabs
	new function(){
		var tabs = $('#index_tabs > *');
		var items = $('#index_tabs_contents > *');

		tabs.bind('click', function(){
			var item = $(items[tabs.index(this)]);

			item.show(500);
			items.not(item).hide(500);
		})
	}

	// Акардион за дясна колона
	new function(){
		var items = $('.right_column .links_list > *');

		items.find('> .title[href="#"]').bind('click', function(){
			var submenu = $(this.parentNode).find('.links_list_bough').first();

			if($(this.parentNode).hasClass('active')){
				submenu.slideUp($.browser.msie && $.browser.version < 9 ? 0 : 500, function(){
					$(this.parentNode).removeClass('active');
				});
			}else{
				submenu.slideDown($.browser.msie && $.browser.version < 9 ? 0 : 500, function(){
					$(this.parentNode).addClass('active');
				});
			}

			return false;
		});
	}

	// Бутончета "Порфил" и "Колучка"
	$('#header_buttons > *').each(function(){
		var the_button = $(this);
		var items = the_button.find('a, input');
		var dropdown = the_button.find('.dropdown');

		the_button.find('.close').bind('click', function(){
			the_button.removeClass('active').addClass('closed');
			$('#cart').overlay().close();

			setTimeout(function(){the_button.removeClass('closed');}, 100)

			return false;
		});

		items.bind('focus mouseup', function(){
			if(!the_button.hasClass('active')){
				the_button.addClass('active');
				// load overlay
				if(the_button.attr('id') == 'cart'){
					MAG.load_cart_overlay();
				}
			}
		}).bind('blur', function(){
			setTimeout(function(){
				if(!items.filter(':focus').length){
					the_button.removeClass('active');
				}
			}, 50);
		});
	});

//	$("#header_buttons > .icon_cart_grey").overlay({mask: '#000', effect: 'apple'});

	// За субменю в основно меню.
	$('#header_menu .submenu_conteiner:has(.media_holder)').each(function(){
		var conteiner = $(this);
		var wrapper = conteiner.parents('.submenu_wrapper');
		var media_items = wrapper.find('.media_holder');
		var submenu_items = conteiner.find('> *');
		var min_height = null;

		wrapper.addClass('with_media');

		wrapper.css({'visibility' : 'hidden', 'display' : 'block'});

		//media_items.css('lineHeight', (wrapper.height() - 10) + 'px').first().css('display', 'block');

		wrapper.css({'visibility' : 'visible', 'display' : ''});

		submenu_items.bind('mouseover', function(){
			var media_item = $(this).find('.media_holder').css('display', 'block');
			var media_height = media_item.height();
			var container_height = conteiner.height();

			media_items.not(media_item).css('display', 'none');

			if(!min_height){
				min_height = container_height;
			}

			if(media_height > container_height){
				conteiner.css('height', media_height);
			}else if(media_height < container_height){
				conteiner.css('height', Math.max(media_height, min_height));
			}
		}).bind('mouseout', function(){
			var media_item = $(this).find('.media_holder').css('display', 'none');
			conteiner.css('height', 'auto');
		});
	});

	// Меригораунд
	new function(){
		var marry = $('.marrygoround');
		var next_button = marry.find('.next')
		var previous_button = marry.find('.previous')
		var list = marry.find('.list_items');
		var items = list.find('.list_item');
		var interval_move;
		var autoplay_speed = 3000;
		var paused_autoplay = false;

		if(items.length < 2){
			return;
		}else if(items.length < 5){
			var sources = $(items.toArray().slice(0, 5));
			var clones = sources.clone();
			clones.data('is_clone', true);
			items = items.add(clones);
			list.append(clones);
		}

		next_button.show();
		previous_button.show();

		var stage_width = marry.width();
		var effect_duration = 500;
		var effect_method = 'easeInOutQuad';
		var the_index = 0;
		var next_index = 1;
		var previous_index = items.length - 1;
		var thumb_width = 166;
		var thumb_height = thumb_width / (items.width() / items.height());
		var scale_percents = thumb_width / (items.width() / 100);
		var mousewheel_delta = 0;
		var numbering = $();

		// Позиция на десния тъмб
		var right_parameters = {
			left		: 942,
			top			: 145,
			height		: thumb_height,
			width		: thumb_width,
			_fontSize	: scale_percents
		};

		// Позиция на левия тъмб
		var left_parameters = {
			left		: 82,
			top			: right_parameters.top,
			height		: thumb_height,
			width		: thumb_width,
			_fontSize	: scale_percents
		};

		// Позиция на изображение в центъра
		var center_parametrs = {
			left		: 227,
			top			: 0,
			height		: 310,
			width		: 670,
			_fontSize	: 100
		};

		//
		var right_hideout_parameters	= $.extend({}, right_parameters, {left : stage_width + thumb_width});
		var left_hideout_parameters		= $.extend({}, left_parameters, {left : -thumb_width});

		// Параметри за анимация
		var move_to_left_hideout		= {left : -thumb_width};
		var move_to_right_hideout		= {left : stage_width + thumb_width};
		var move_right_from_hideout		= {left : right_parameters.left};
		var move_left_from_hideout		= {left : left_parameters.left};

		function set_right(index){
			$(items[index]).css(right_parameters).addClass('thumb');
		}

		function set_left(index){
			$(items[index]).css(left_parameters).addClass('thumb');
		}

		function move_right(){

			clearTimeout(interval_move);

			var action = function(){

				var animation_finided = (function(){
					var left = 4;
					return function(){
						left--;

						if(left < 1){
							var queue = marry.queue('marrygoround');

							if(queue[0] === action){
								queue.shift();
								marry.queue('marrygoround', queue);
							}

							marry.dequeue('marrygoround');
						}
					};
				})();
				var move_to_left	= $(items[the_index]);
				var to_hide			= $(items[previous_index]);
				var to_center		= $(items[next_index]);
				var queue_length	= marry.queue('marrygoround').length;
				var duration		= queue_length > 1 ? effect_duration / 2 : effect_duration;

				previous_index		= the_index;
				the_index			= next_index;
				next_index			= the_index + 1 >= items.length ? 0 : the_index + 1;

				var used_index		= the_index;
				var move_to_right	= $(items[next_index]);

				move_to_right.queue(function(next){
					move_to_right.css(right_hideout_parameters).addClass('thumb');
					next();
				}).animate(move_right_from_hideout, {
					duration	: duration,
					easing		: effect_method,
					complete	: function(){
						move_to_right.css('zIndex', 99);

						animation_finided();
					}
				});

				to_hide.animate(move_to_left_hideout, {
					duration	: duration,
					easing		: effect_method,
					complete	: function(){
						to_hide.removeClass('thumb');

						animation_finided();
					}
				});

				move_to_left.queue(function(next){
					move_to_left.css('zIndex', 99);
					next();
				}).animate(left_parameters, {
					duration	: duration,
					easing		: effect_method,
					step		: function(value, efe){
						if(efe.prop === '_fontSize'){
							move_to_left.css('fontSize', 100 - ((100 - 24) / 100) * efe.pos * 100 + '%');
						}
					},
					complete	: function(){
						move_to_left.addClass('thumb');

						animation_finided();
					}
				});

				to_center.queue(function(next){
					to_center.css({'zIndex' : 100}).removeClass('thumb')
					next();
				}).animate(center_parametrs, {
					duration	: duration,
					easing		: effect_method,
					step		: function(value, efe){
						if(efe.prop === '_fontSize'){
							to_center.css('fontSize', ((100 - 24) / 100) * efe.pos * 100 + 24 + '%');
						}
					},
					complete	: function(){
						to_center.css({'zIndex' : 100});
						var numbering_children = numbering.children();
						var numbering_children_length = numbering_children.length;

						numbering_children.removeClass('active')
						$(numbering_children.get(used_index % numbering_children_length)).addClass('active');

						animation_finided();
					}
				});
			}

			//marry.queue('marrygoround', function(next){next();});
			marry.queue('marrygoround', action);

			if(marry.queue('marrygoround').length == 1){
				if(!paused_autoplay) {
					marry.queue('marrygoround', function(next) {
						interval_move = setTimeout(function() {move_right()}, autoplay_speed);
						next();
					});
				}

				action();
			}
		}

		function move_left(){

			clearTimeout(interval_move);

			var action = function(){
				var animation_finided = (function(){
					var left = 4;
					return function(){
						left--;

						if(left < 1){
							var queue = marry.queue('marrygoround');

							if(queue[0] === action){
								queue.shift();
								marry.queue('marrygoround', queue);
							}

							marry.dequeue('marrygoround');
						}
					};
				})();

				var move_to_right	= $(items[the_index]);
				var queue_length	= marry.queue('marrygoround').length;
				var duration		= queue_length > 1 ? effect_duration / 2 : effect_duration;

				var to_hide = $(items[next_index]);
				var to_center = $(items[previous_index]);

				next_index = the_index;
				the_index = previous_index;
				previous_index = the_index - 1 >= 0 ? the_index - 1 : items.length - 1;

				var used_index = the_index;
				var move_to_left = $(items[previous_index]);

				//move_to_left.stop();
				//to_center.stop();
				//move_to_right.stop();
				//to_hide.stop();

				move_to_left.queue(function(next){
					move_to_left.css(left_hideout_parameters);
					move_to_left.addClass('thumb');
					next();
				}).animate(move_left_from_hideout, {
					duration	: duration,
					easing		: effect_method,
					complete	: function(){
						move_to_left.css('zIndex', 99);

						animation_finided();
					}
				});

				to_hide.animate(move_to_right_hideout, {
					duration	: duration,
					easing		: effect_method,
					complete	: function(){
						to_hide.removeClass('thumb');

						animation_finided();
					}
				});

				/* if($.browser.msie){
					move_to_right.queue(function(next){
						if($.browser.version < 9){
							//move_to_right.css('_fontSize', '89.5%');
						}else if($.browser.version == 9){
							//move_to_right.css('fontSize', '96%');
						}

						next();
					})
				} */

				move_to_right.animate(right_parameters, {
					duration	: duration,
					easing		: effect_method,
					step		: function(value, efe){
						if(efe.prop === '_fontSize'){
							move_to_right.css('fontSize', 100 - ((100 - 24) / 100) * efe.pos * 100 + '%');
						}
					},
					complete	: function(){
						move_to_right.addClass('thumb');

						animation_finided();
					}
				});

				to_center.queue(function(next){
					to_center.removeClass('thumb')
					next();
				}).animate(center_parametrs, {
					step		: function(value, efe){
						if(efe.prop === '_fontSize'){
							to_center.css('fontSize', ((100 - 24) / 100) * efe.pos * 100 + 24 + '%');
						}
					},
					duration	: duration,
					easing		: effect_method,
					complete	: function(){
						to_center.css({'zIndex' : 100});
						var numbering_children = numbering.children();
						var numbering_children_length = numbering_children.length;

						numbering_children.removeClass('active')
						$(numbering_children.get(used_index % numbering_children_length)).addClass('active');

						animation_finided();
					}
				});

			}

			//marry.queue('marrygoround', function(next){next();});
			marry.queue('marrygoround', action);

			if(marry.queue('marrygoround').length == 1){
				action();
			}

			if(!paused_autoplay) {
				interval_move = setTimeout(function() {move_right()}, autoplay_speed);
			}
		}

		$.fn.bind_autoplay_pause = function(options){

			$(this).mouseenter(function(){
				paused_autoplay = true;
				clearTimeout(interval_move);
			}).mouseleave(function() {
				paused_autoplay = false;
				interval_move = setTimeout(function() {move_right()}, autoplay_speed);
			})

			return this;
		}

		if(items.length > 1){
			clearTimeout(interval_move);

			numbering = $(document.createElement('ul')).addClass('list_numbering');

			for(var z = 0; z < items.length; z++){
				if(!$(items[z]).data('is_clone')){
					numbering.append(document.createElement('li'));
				}
			}

			$(numbering.children().bind('click', function(){
				var target_index = numbering.children().index(this);
				var steps = target_index - the_index;

				if(steps == 0){
					return;
				}

				if(steps < 0){
					for(var z = 0; z > steps; z--){
						move_left();
					}
				}else{
					for(var z = 0; z < steps; z++){
						move_right();
					}
				}

			})[the_index]).addClass('active');

			marry.append(numbering);
		}

		/* marry.bind('mousewheel', function(event, delta){
			if(event.ctrlKey || event.altKey || event.shiftKey){
				return;
			}

			mousewheel_delta += delta;

			if(mousewheel_delta >= 1){
				mousewheel_delta = 0;
				move_left();
			}else if(mousewheel_delta <= -1){
				move_right();
				mousewheel_delta = 0;
			}

			return false;
		}); */

		set_right(next_index);
		set_left(previous_index);

		next_button.bind('click', function(){
			move_right();
			return false;
		}).bind_autoplay_pause();

		previous_button.bind('click', function(){
			move_left();
			return false;
		}).bind_autoplay_pause();

		list.bind_autoplay_pause();

		interval_move = setTimeout(function() {move_right()}, autoplay_speed);

	}

	// Социално ощетени мрежи
	new function(){
		window.addthis_config = {ui_language : 'bg'};

		$(document.head).append('<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e689c5d12945cc7"></script>');
	}

	// Регистрация на потребител
	// Обновяваме капча.
	new function(){
		var captcha = $('#registration_captha');

		captcha.add('#registration_captha_reload').bind('click', function(){
			var src = captcha.attr('src');

			if(src.indexOf('?') === -1){
				src += '?';
			}

			src += new Date().getTime();

			captcha.attr('src', src);

			return false;
		})
	};

	// Добавяне на продукт в кошница
	$('.price_wrapper a[class!="external"], .price_promo_wrapper .price a, .price_promo_wrapper > .price_promo_inner > a').buyable();
	$('.list_item_m .options .icon_plus').buyable({no_scroll : true}).bind('click', function(){
		$('#cart').addClass('active');
	});

	// Добавяне на продукт в любими
	$('.list_item_n .icon_star, .list_item_m .icon_star, .actions_wrapper .favorites').likeable();

	// Добавяне на продукт за сравнение
	$('.list_item_n .icon_balls, .list_item_m .icon_balls, .actions_wrapper .compare').comparable();

	// Продукти със скрита цена
	new function(){
		var overlay = new MAG.Overlay();
		var loaded = false;

		$('.ask_for_price .orange_button, a.ask_for_price').bind('click', function(){
			overlay.open();

			if(!loaded){
				loaded = true;
				$.ajax(MAG.xml_http_request, {
					data		: {method : 'ask_for_price'},
					complete	: function(ajax){
						var result = $.parseJSON(ajax.responseText);
						overlay.update(result.content);
					}
				});
			}

			return false;
		})
	}

	// Показваме съобщение когато се натисне копче "Поръчай", но няма продкти в кошница.
	$('#cart .orange_button.buy').bind('click', function(){
		if(!MAG.Cart.total_quantity){
			var button = $(this);
			var button_offset = button.offset();
			var message = $('<h3 class="default_block_title">Моля, изберете продукт</h3>').css({
				position	: 'absolute',
				width		: 200,
				marginLeft	: -220,
				zIndex		: 9999,
				display		: 'none',
				top			: button_offset.top,
				left		: button_offset.left
			});

			$('#wrapper').append(message);

			message.fadeIn(500, function(){
				message.delay(2000).fadeOut(500, function(){
					message.remove();
				});
			});

			return false;
		}
	});

	// CallBack form
	$('#call_back_form').bind('submit', function(){
		var name = $(this).find('input[name="call_name"]');
		var phone = $(this).find('input[name="call_phone"]');

		if(!name.val().length) {
			alert('Име е задължително поле');
			name.focus();
			return false;
		}

		if(!phone.val().toString().match(/^[0-9 ]+$/)) {
			alert('Моля, използвайте само цифри и интервал');
			phone.focus();
			return false;
		}

		var data = {
			method			: 'call_now',
			is_call_back	: '1',
			url				: window.location.toString(),
			call_name		: name.val(),
			call_phone		: phone.val()
		};

		$.ajax ({
			url		: MAG.xml_http_request,
			data	: data,
			success	: function(){
				alert("Благодарим за интереса \n Ще Ви се обадим при първа възможност!");
				name.val(name.attr('title'));
				phone.val(phone.attr('title'));
			}
		});

		return false;
	});


	$('#header_search .input_field_container input, #footer_search .input_field_container input').autocomplete({
		source		: MAG.search_autocomplete
	}).bind('autocompleteselect', function(event, ui){
		var item = $(this);
		setTimeout(function(){
			item.parents('form').submit();
		}, 200);
	}).bind('autocompleteopen', function(event){
		var autocomplete = $(this).data('autocomplete');
		var dropdown = autocomplete.menu.element;
		var wrapper = $(this).parents('.input_field_wrapper');
		var wrapper_offset = wrapper.offset();
		wrapper_offset.top += wrapper.height() - 4;
		dropdown.width(wrapper.width() - 4);
		dropdown.offset(wrapper_offset);
	});
});

MAG.load_cart_overlay = function(){
	var $cart = $('#cart');

	$cart.overlay({
		mask: {
			color: '#789',
			loadSpeed: 200,
			opacity: 0.5
		},
		top: 'auto',
		left: 'auto',
		load: true,
		close: '.close',
		closeOnEsc: true,
		closeOnClick: true,
		onLoad: function(){
			$cart.css('position', 'relative');
		},
		onClose: function(){
			if ($.browser.msie && parseInt($.browser.version, 10) < 8){
				$cart.css('display', 'inline');
			}
			else{
				$cart.css('display', 'inline-block');
			}
			$cart.find('.close').trigger('click');
		}
	});
	// load overlay on second click
	$cart.data("overlay").load();
}

MAG.add_round_corners = function(element, class_name, tl, tr, br, bl){
	var items = $();

	if(tl){
		items = items.add($('<div class="' + class_name + '_tl"/>'));
	}

	if(tr){
		items = items.add($('<div class="' + class_name + '_tr"/>'));
	}

	if(bl){
		items = items.add($('<div class="' + class_name + '_bl"/>'));
	}

	if(br){
		items = items.add($('<div class="' + class_name + '_br"/>'));
	}

	$(element).each(function(){
		$(this).append(items.clone());
	});
}

MAG.processed_inputs = function(items){
	items.each(function(){
		if($(this).hasClass('basic')){
			return;
		}

		MAG.input(this);
	}).not('textarea').bind('focus', function(){
		if(this.value === this.title){
			this.value = '';
		}
	}).bind('blur', function(){
		if(this.value.match(/^\s?$/)){
			this.value = this.title;
		}
	});
};

MAG.input = (function(){
	var wrapper 		  = document.createElement('div');
	var container 		  = wrapper.cloneNode(false);

	wrapper.className 	  = 'input_field_wrapper'
	container.className   = 'input_field_container';

	wrapper.appendChild(container);	// Трява да е първи във врапера.

	if($.browser.msie && $.browser.version < 9){
		var shadow			= wrapper.cloneNode(false);
		var top_right		= wrapper.cloneNode(false);
		var top_left		= wrapper.cloneNode(false);
		var bottom_left		= wrapper.cloneNode(false);
		var bottom_right	= wrapper.cloneNode(false);

		shadow.className		= 'input_field_shadow';
		top_right.className		= 'input_field_top_right';
		top_left.className		= 'input_field_top_left';
		bottom_left.className	= 'input_field_bottom_left';
		bottom_right.className	= 'input_field_bottom_right';

		wrapper.appendChild(shadow);
		wrapper.appendChild(top_right);
		wrapper.appendChild(top_left);
		wrapper.appendChild(bottom_left);
		wrapper.appendChild(bottom_right);
	}

	return function(what){
		var new_wrapper = wrapper.cloneNode(true);
		var sibling 	= what.nextSibling;
		var holder 		= what.parentNode;

		new_wrapper.childNodes[0].appendChild(what);

		if($(what).hasClass('marked')){
			var mark = document.createElement('div');
			mark.className = 'icon_circle_small_grey';
			new_wrapper.appendChild(mark);
		}

		if(what.tagName === 'SELECT'){
			var label = document.createElement('div');
			new_wrapper.childNodes[0].appendChild(label);

			try{
				$(label).text(what.options[what.selectedIndex].innerHTML);
			}catch(e){}

			$(what).bind('change', function(){
				try{
					$(label).text(what.options[what.selectedIndex].innerHTML);
				}catch(e){}
			}).bind('keyup', function(){
				try{
					$(label).text(what.options[what.selectedIndex].innerHTML);
				}catch(e){}
			});
		}

		if(!holder){
			return new_wrapper;
		}

		holder.insertBefore(new_wrapper, sibling);

		return what;
	};
})();

MAG.Cart = (function(){
	var cart = MAG.Cart;

	$(function(){
		cart.count_holder = $('#products_count');
		cart.total_holder = $('#cart_total_price');
		cart.table = $('#cart_products_table');
		cart.list = $('#cart_products_list');
		cart.empty_title = $('#cart_empty');

		//cart.counter(cart.list.children().length);
		//cart.total_quantity = parseInt(cart.count_holder.text());

		if(cart.total_quantity){
			cart.count_holder.css('visibility', 'visible');
		}

		cart.counter(cart.total_quantity);

		attach_remove_event(cart.list);
		attach_update_event(cart.list);
	});

	function attach_remove_event(to){
		$(to).find('.action a.remove').bind('click', function(){
			MAG.Cart.remove(MAG.Cart.parse_hash(this.hash));

			$(this).parents('tr').fadeOut(500, function(){
				$(this).remove();
			});

			return false;
		});
	}

	function attach_update_event(to){
		to.find('td.quantity').each(function(){
			var cell = $(this);
			var to = cell.parent();
			var wrapper = cell.find('.wrapper');
			var plus = cell.find('.plus');
			var minus = cell.find('.minus');
			var match = to.attr('id').match(/order_product_(\d+)_?(\d+)?/);

			plus.bind('click', function(){
				var quantity = parseInt(wrapper.text()) + 1;

				cart.update({
					product_id	: match[1],
					bundle_id	: match[2],
					quantity	: quantity
				});

				wrapper.text(quantity);

				return false;
			});

			minus.bind('click', function(){
				var quantity = parseInt(wrapper.text()) - 1;

				if(quantity < 1){
					cart.remove({
						product_id	: match[1],
						bundle_id	: match[2]
					});

					to.fadeOut(500, function(){
						to.remove();
					});
				}else{
					cart.update({
						product_id	: match[1],
						bundle_id	: match[2],
						quantity	: quantity
					});

					wrapper.text(quantity);
				}

				return false;
			});
		});
	}

	cart.counter = function(value){
		var old_value = parseInt(cart.count_holder.text());

		if(isNaN(old_value) || old_value < 0){
			old_value = 0;
		}

		if(value === true || value === false){
			value = old_value + (value ? 1 : -1);
		}else{
			value = parseInt(value);

			if(isNaN(value) || value < 0){
				value = 0;
			}
		}

		if(value === 0){
			cart.count_holder.css('visibility', 'hidden');
			cart.table.hide();
			cart.empty_title.show();
		}else if(!old_value){
			cart.count_holder.css('visibility', 'visible');
			cart.empty_title.hide();
			cart.table.show();
		}

		cart.count_holder.text(value);

		return value;
	};
	cart.parse_hash = function(hash){
		var data = {};
		var items = hash.match(/(^|\s|#)(buy_|lease_|remove_)?(product|bundle)_(\d+)/g);

		if(!items){
			return data;
		}

		for(var z = 0; z < items.length; z++){
			var item = items[z].match(/(buy_|lease_|remove_)?(product|bundle)_(\d+)/);


			if(item && item.length === 4){
				data.lease = item[1] === 'lease_';

				if(item[2] === 'product'){
					data.product_id = item[3];
				}else if(item[2] === 'bundle'){
					data.bundle_id = item[3];
				}
			}
		}

		return data;
	};
	cart.plus_one = function(options){
		var plus_one = $('<div/>').css({
			position	: 'absolute',
			zIndex		: '99999',
			left		: options.left,
			top			: options.top,
			fontSize	: '15px',
			color		: '#EF4323'
		}).text('+1');

		$(document.body).append(plus_one);

		plus_one.animate({fontSize : '50px'}, {
			duration	: 500
		});

		plus_one.animate({fontSize : '10px'}, {
			duration	: 1500
		});

		plus_one.animate(cart.count_holder.offset(), {
			queue		: false,
			duration	: 2000,
			complete	: function(){
				plus_one.remove();
				cart.counter(true);
				if(typeof options.callback === 'function'){
					options.callback(cart);
				}
			}
		});
	};
	cart.update = function(options){
		var data = {
			product_id			: options.product_id || undefined,
			bundle_product_id	: options.bundle_id || undefined,
			quantity			: options.quantity || undefined,
			method				: 'update_product_quantity'
		};

		$.ajax({
			url			: MAG.xml_http_request,
			data		: data,
			complete	: function(ajax){
				var result = $.parseJSON(ajax.responseText);

				cart.total_price = result.total_price;
				cart.total_quantity = result.total_quantity;
				cart.total_holder.text(result.total_price + 'лв.');
				cart.counter(cart.total_quantity);
			}
		});
	};
	cart.add = function(options){
		var data = {
			product_id			: options.product_id || undefined,
			bundle_product_id	: options.bundle_id || undefined,
			leasing				: options.lease ? 1 : undefined,
			promotion			: options.promotion || undefined,
			method				: 'add_to_cart'
		};

		$.ajax({
			url			: MAG.xml_http_request,
			data		: data,
			complete	: function(ajax){
				try{
					var result = $.parseJSON(ajax.responseText);
				}catch(e){
					return;
				}

				var row_id = 'order_product_' + options.product_id + (options.bundle_id ? '_' + options.bundle_id : '');
				var new_row = $(result.product_row);

				cart.total_price = result.total_price;
				cart.total_quantity = result.total_quantity;
				cart.total_holder.text(result.total_price + 'лв.');

				attach_remove_event(new_row);
				attach_update_event(new_row);

				if($('#' + row_id).length){
					$('#' + row_id).replaceWith(new_row);
				}else{
					cart.list.append(new_row);
				}

				if(options && typeof options.complete === 'function'){
					options.complete();
				}
			}
		});
	};
	cart.remove = function(options){
		var data = {
			product_id			: options.product_id || undefined,
			bundle_product_id	: options.bundle_id || undefined,
			method				: 'remove_from_cart'
		};

		$.ajax({
			url		: MAG.xml_http_request,
			data	: data,
			complete	: function(ajax){
				var result = $.parseJSON(ajax.responseText);

				cart.related.itersect(result.related_products_ids);

				cart.total_price = result.total_price;
				cart.total_quantity = result.total_quantity;

				cart.counter(result.total_quantity);
				cart.total_holder.text(result.total_price + 'лв.');
			}
		});
	};
	cart.related = (function(){
		var wrapper, list, left, right;
		var effect_duration = 500;
		var step = 480;

		$(function(){
			wrapper = $('#cart .related_products');
			list = wrapper.find('.listing');

			left = wrapper.find('> .left').data('hidden', true);
			right = wrapper.find('> .right').data('hidden', true);

			left.bind('click', function(){
				move(-1);

				return false;
			});

			right.bind('click', function(){
				move(+1);

				return false;
			});

			wrapper.scrollLeft(0);
			setInterval(check_controls, 1000);

			if(list.children().length){
				wrapper.show();
			}
		});

		function check_controls(){
			var scroll_width = list.prop('scrollWidth');

			if(!scroll_width){
				return;
			}

			var list_width = list.width();
			var scroll_left = list.scrollLeft();

			/* console.log({
				'scroll_width' : scroll_width,
				'list_width' : list_width,
				'scroll_left' : scroll_left
			}); */

			if(scroll_width == list_width){
				if(!right.data('hidden')){
					right.css('display', 'none').data('hidden', true);
				}

				if(!left.data('hidden')){
					left.css('display', 'none').data('hidden', true);
				}
			}else{
				if(!left.data('hidden') && scroll_left == 0){
					left.css('display', 'none').data('hidden', true);
				}else if(left.data('hidden') && scroll_left){
					left.css('display', 'block').data('hidden', false);
				}

				if(!right.data('hidden') && scroll_left + list_width >= scroll_width){
					right.css('display', 'none').data('hidden', true);
				}else if(right.data('hidden') && scroll_left + list_width < scroll_width){
					right.css('display', 'block').data('hidden', false);
				}
			}
		}

		function move(direction){
			direction = (direction < 0 ? -1 : 1);
			var scroll_left = list.scrollLeft();
			var scroll_to = scroll_left + step * direction;
			var scroll_width = list.prop('scrollWidth');
			var list_width = list.width();

			if(scroll_to < 0){
				scroll_to = 0;
			}

			if(direction > 0 && scroll_to + list_width + step / 2 >= scroll_width){
				scroll_to = scroll_width - list_width;
			}

			if(direction < 0 && scroll_to - step / 2 < 0){
				scroll_to = 0;
			}

			list.animate({
				scrollLeft	: scroll_to
			}, {
				duration	: effect_duration,
				complete	: function(){
					check_controls();
				}
			});
		}

		function get_relations(product_id){
			return list.children().filter(function(){
				var related_product_id = $(this).data('related_product_id');

				if(related_product_id === undefined){
					return false;
				}

				if(related_product_id == product_id){
					return true;
				}

				return false;
			});
		}

		function do_the_boogie(options){
			var data = {
				product_id			: options.product_id || undefined,
				bundle_product_id	: options.bundle_id || undefined,
				method				: 'cart_related_products',
				exclude				: []
			};

			if(!data.product_id){
				return false;
			}

			if(get_relations(options.product_id).length){
				return true;
			}

			list.children().each(function(){
				data.exclude.push(this.getAttribute('name').match(/\d+/).shift());
			});

			$.ajax({
				url			: MAG.xml_http_request,
				data		: data,
				complete	: function(ajax){
					try{
						var new_items = $(ajax.responseText);
					}catch(e){
						return;
					}

					list.append(new_items);
					new_items.find('.icon_star').likeable();
					new_items.find('.icon_balls').comparable();
					new_items.find('.icon_plus').buyable({no_scroll : true}).bind('click', function(){
						$('#cart').addClass('active');
						MAG.load_cart_overlay();
					});
					check_controls();

					new_items.data({
						'related_product_id'		: options.product_id || undefined,
						'related_bundle_product_id'	: options.bundle_id || undefined
					});

					if(!wrapper.prop('offsetHeight')){
						wrapper.slideDown(1000);
					}
					/* new_items.find('.icon_plus').bind('click', function(){
						var params = cart.parse_hash(this.hash);
						params.complete = function(){cart.counter(cart.total_quantity);}

						cart.add(params);

						return false;
					}); */
				}
			});
		}

		do_the_boogie.itersect = function(related_products_ids){
			for(var item, items = list.children().toArray(); item = items.shift();){
				var id = item.getAttribute('name').match(/\d+/).shift();
				var found = false;

				for(var z = 0; z < related_products_ids.length; z++){
					if(related_products_ids[z] == id){
						found = true;
						break;
					}
				}

				if(!found){
					$(item).fadeOut(500, function(){
						$(this).remove();
					});
				}
			}

			setTimeout(function(){
				if(!list.children().length){
					wrapper.slideUp(1000);
				}
			}, 600);
		}

		return do_the_boogie;
	})();

	return cart;
})();

MAG.Leasing = function(z){
	/**
	 * S - сума
	 * L - лихва
	 * T - месечна такса обслужване
	 * TKM - месечна такса управление на кредита
	 * M - брой месеци
	 * OS = [M * T + S * M * TKM / 100 + S * (1 + L/100)] - олихвена стойност
	*/

	var os = z.period * z.month_tax + z.price * z.period * z.month_tax_credit / 100 + z.price * (1 + z.interest / 100);//136.38
	//	monthly_fee		: (os / z.period).toFixed(2),
	var m_fee = z.price/z.period + (z.interest/100)*z.price;//75

	return {
		period			: z.period,
		interest		: z.interest,
		monthly_fee		: m_fee.toFixed(2),
		interest_value	: (os - z.price).toFixed(2)
	};
}

MAG.Overlay = function(){
	if(!(this instanceof arguments.callee)){
		return new arguments.callee();
	}

	var pop = this;
	this.effect_duration = 400;
	this.pop_wrapper = $(document.createElement('div')).addClass('pop_wrapper');
	this.overlay = $(document.createElement('div')).addClass('overlay');
	this.content_wrapper = $(document.createElement('div')).addClass('content_wrapper');
	this.content = $(document.createElement('div')).addClass('content');
	this.close_button = $(document.createElement('a')).attr({href : '#', title : 'Затвори'}).addClass('close icon_cross');

	this.content_wrapper.append(this.close_button);
	this.content_wrapper.append(this.content);
	this.pop_wrapper.append(this.overlay);
	this.pop_wrapper.append(this.content_wrapper);

	$(document.body).append(this.pop_wrapper);

	this.close_button.bind('click', function(event){
		pop.close();
		return false;
	});

	var pop_key = function(event){
		if(event.keyCode == 27){
			pop.close.call(pop);
		}
	};

	this.update = function(data){
		pop.content.html(data);
	};

	this.open = function(){
		pop.pop_wrapper.queue('fx', function(next){
			pop.pop_wrapper.css('top', (document.documentElement.scrollTop || document.body.scrollTop) + 100 + 'px');
			next();
		}).fadeIn(pop.effect_duration, function(){
			$(document).bind('keydown', pop_key);
		});
	};

	this.close = function(){
		pop.pop_wrapper.queue('fx', function(next){
			//$(document).unbind('keydown', pop_key);
			next();
		}).fadeOut(pop.effect_duration, function(){
			pop.pop_wrapper.removeClass('open');
			pop.pop_wrapper.css('display', '');
		});
	};

	return this;
};

MAG.setCookie = function(c_name, value, exdays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value = escape(value) + (exdays === null ? '' : '; expires=' + exdate.toUTCString());
	document.cookie = c_name + '=' + c_value;
}

MAG.getCookie = function(c_name){
	var i, x, y, ARRcookies = document.cookie.split(';');

	for(i = 0; i < ARRcookies.length; i++){
		x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
		y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
		x = x.replace(/^\s+|\s+$/g, '');

		if(x == c_name){
			return unescape(y);
		}
	}
}

$.fn.likeable = function(){
	$(this).each(function(){
		if($(this).data('likeable')){
			return true;
		}

		try{
			var product_id = this.hash.match(/\d+/).shift();

			if(!product_id){
				return false;
			}
		}catch(e){
			return false;
		}

		var data = {
			method		: 'add_to_favourites',
			product_id	: product_id
		};

		$(this).data('likeable', true).bind('click', function(){
			if(!$(this).data('liked')){
				$(this).data('liked', true);

				$.ajax({
					url		: MAG.xml_http_request,
					data	: data
				});
			}

			return false;
		});
	});
};

$.fn.buyable = function(options){
	$(this).bind('click', function(event){
		var params = MAG.Cart.parse_hash(this.hash);
		var promotion = $(this).siblings('.promotions').find(':checked');

		if($(this).hasClass('green_button') && $('.promotions').length > 0){
			promotion = $('.price_wrapper').find(':checked');
		}

		if(promotion && promotion.attr('name')) {
			var chosen_promo_with_value = promotion.attr('name') + '_' + promotion.attr('title');
			params.promotion = chosen_promo_with_value;
		}

		MAG.Cart.add(params);
		MAG.Cart.related(params);

		if(!(options && options.no_scroll === true)){
			$($.browser.webkit ? document.body : document.documentElement).animate({scrollTop : $('#cart').offset().top}, {duration : 2000, complete : function(){}});
		}
		MAG.Cart.plus_one({top : event.pageY, left : event.pageX, callback : function(){
			$('#cart').addClass('active');
			MAG.load_cart_overlay();
		}});

		return false;
	});

	return this;
};

$.fn.comparable = (function(){
	var quick_list, button_compare;

	$(function(){
		quick_list = $('#quick_compare_list');
		button_compare = quick_list.find('a.button_compare');

		quick_list.find('> div > a.icon_cross').bind('click', remove_click_handler);
	});

	function update_compare_link(){
		var keys = [];

		for(var key in MAG.Compare.items){
			keys.push(key);
		}

		button_compare.prop('href', MAG.base_domain_url + '/compare/?products=' + keys.join(',') + '&');
	}

	function add_new_item(product_id, product_name){
		var new_item = $('\
			<div>\
				' + product_name + '\
				<a href="#remove_' + product_id + '" class="icon_cross">&nbsp;</a>\
			</div>\
		');

		new_item.find('a.icon_cross').bind('click', remove_click_handler);//.hide()
		quick_list.prepend(new_item);
		new_item.slideDown(400, function(){
			quick_list.css('zoom', 1);
			quick_list.children().css('zoom', 1);
		});
		update_compare_link();
	}

	function remove_click_handler(){
		var product_id = this.hash.match(/\d+/);

		if(product_id){
			product_id = product_id.shift();
		}else{
			return false;
		}

		if(!MAG.Compare.items[product_id]){
			return false;
		}

		delete MAG.Compare.items[product_id];

		update_compare_link();

		$(this.parentNode).slideUp(400, function(){
			$(this).remove();

			var hide_compare_list = true;

			for(var pid in MAG.Compare.items){
				hide_compare_list = false;
				break;
			}

			if(hide_compare_list){
				quick_list.slideUp();
			}
		});

		var data = {
			method			: 'add_or_remove_to_compare',
			product_id		: product_id,
			remove			: 1
		};

		$.ajax({
			url			: MAG.xml_http_request,
			data		: data,
			complete	: function(ajax){
				//MAG.Compare.items = $.parseJSON(ajax.responseText);
			}
		});

		return false;
	}

	function plus_one_effect(options){
		var plus_one = $('<div/>').css({
			position	: 'absolute',
			zIndex		: '99999',
			left		: options.left,
			top			: options.top,
			fontSize	: '15px',
			color		: '#66A000'
		}).text('+1');

		$($.browser.webkit ? document.body : document.documentElement).animate({scrollTop : quick_list.offset().top}, {duration : 2000, complete : function(){}});

		var offset = quick_list.offset(),
			screen_step = Math.floor((options.top - quick_list.offset().top) / 1000) + 1;

		// if we are somewhere down on the screen - animate effect only till the visible area
		/* Disabled because we allowed screen move when adding item to compare
		if(screen_step > 1) {
			offset = {top: $(window).scrollTop(), left: options.left - 50};
		}
		*/

		$(document.body).append(plus_one);

		plus_one.animate({fontSize : '50px'}, {
			duration	: 500
		});

		plus_one.animate({fontSize : '10px'}, {
			duration	: 1500
		});

		plus_one.animate(offset, {
			queue		: false,
			duration	: 2000,
			complete	: function(){
				plus_one.remove();

				if(typeof options.callback === 'function'){
					options.callback();
				}
			}
		});
	};

	function do_the_boogie(){
		if($(this).data('comparable')){
			return true;
		}

		try{
			var product_id = this.hash.match(/\d+/).shift();

			if(!product_id){
				return false;
			}
		}catch(e){
			return false;
		}

		var target_button = $(this);
		var product_name = target_button.attr('title');

		var data = {
			method			: 'add_or_remove_to_compare',
			product_id		: product_id,
			product_name	: product_name,
			add				: 1
		};

		target_button.data('comparable', true).bind('click', function(event){
			if(MAG.Compare.items && MAG.Compare.items[product_id]){
				return false;
			}

			$.ajax({
				url			: MAG.xml_http_request,
				data		: data,
				complete	: function(ajax){
					MAG.Compare.items = $.parseJSON(ajax.responseText);

					if(!MAG.Compare.items[product_id]){
						alert(MAG.labels.up_to_3_products);
						return false;
					}

					if(quick_list.width()){
						quick_list.slideDown(400, function(){
							plus_one_effect({top : event.pageY, left : event.pageX, callback : function(){
								add_new_item(product_id, product_name);
							}});
						});
					}else{
						plus_one_effect({top : event.pageY, left : event.pageX, callback : function(){
							add_new_item(product_id, product_name);
						}});
					}
				}
			});

			return false;
		});
	}

	return function(){
		$(this).each(do_the_boogie);
	}
})();

$.fn.max_telecomed = function(options){
	var selected_package = price_container = backed_up_price = '';

	$(this).bind('click', function(event){
		selected_package = parseFloat($(this).val()),
		price_container = $(this).parent().parent().parent().parent('.price_wrapper').find('h3:first a');
		backed_up_price = $(this).parent().parent().parent().parent('.price_wrapper').find('.backup_price:first');
		bundle_exist = $('.price_promo_inner').length > 0 ? true : false;

		if(bundle_exist){
			bundle_price_container = $('.price_promo_inner').find('h3:first a');
			bundle_backed_up_price = $('.price_promo_inner').find('.backup_bundle_price:first');
		}

		$(this).parent().parent('.max_telecom_box_row').prev().find('input:checked').attr('checked', false);
		$(this).parent().parent('.max_telecom_box_row').next().find('input:checked').attr('checked', false);

		$(this).is(':checked') ? check() : uncheck();
	});

	function check(){
		var current_price =  parseFloat((backed_up_price.length > 0) ? backed_up_price.text() : price_container.text().replace(/([^\d]\.)+/, ''));
		if(bundle_exist){
			var current_price_bundle =  parseFloat((bundle_backed_up_price.length > 0) ? bundle_backed_up_price.text() : bundle_price_container.text().replace(/([^\d]\.)+/, ''));
		}

		if(!backed_up_price.length > 0){
			price_container.append('<span class="backup_price">' + current_price + '</span>'); // backup init price
		}

		if(bundle_exist && !bundle_backed_up_price.length > 0){
			bundle_price_container.append('<span class="backup_bundle_price">' + current_price_bundle + '</span>'); // backup init price
		}

		if(selected_package >= current_price){
			alert('Max telecom gift is not avaible for products which price is lower then the gift price.');
		}
		else{
			price_container.html(price_container.html().replace(/^(\d+)\.?(\d+)?/gi, (current_price - selected_package)));
			if(bundle_exist) bundle_price_container.html(bundle_price_container.html().replace(/^(\d+)\.?(\d+)?/gi, (current_price_bundle - selected_package)));
		}
	}


	function uncheck(){
		if(backed_up_price.length > 0){
			price_container.html(price_container.html().replace(/^(\d+)\.?(\d+)?/gi, backed_up_price.text()));
			$('.backup_price').remove();
		}

		if(bundle_exist && bundle_backed_up_price.length > 0){
			bundle_price_container.html(bundle_price_container.html().replace(/^(\d+)\.?(\d+)?/gi, bundle_backed_up_price.text()));
			$('.backup_bundle_price').remove();
		}
	}

	return this;
};
