$(function(){

        $('a[rel*=blank]').attr('target', '_blank');
        
        // add2cart
        $('.buy').click(function(){
		$.ajax({
	        	type: "GET",
			url: $(this).attr('href'),
			dataType: "html",
			cache: false,
			data: {
				"_format": "js"
			},
			success: function(data) { // строка ответа: {count: N, sum: M}
			
			//	json = {count: 3, sum: 3456}; // fake
				$('.cart-placeholder, .cart-placeholder-fixed').html(data);
/*				if (json.count) {
					$('#cart').find('.link').text(
						json.count + ' ' + plural('товар', 'товара', 'товаров', json.count)
					).end().find('.sum').text(
						json.sum.space1k()
					);
*/					
					$('#cart').show().animate({
						backgroundColor: '#90BE26'
					}, 150).animate({
						backgroundColor: '#75614C'
					}, 150);	
/*				} else {
				        $('#cart').hide();
				}
*/			
			},
			error: function(){
				alert('Произошла ошибка, попробуйте позже');
			}
		});  	
		return false;
	});
	
	// order form
	$('input, textarea', 'form.validate').bind('change keyup', function(){
                check_input($(this));
        });
        $('form.validate').submit(function(){
                $('input, textarea', this).each(function(){
                        check_input($(this));
                });
                if ($('.error', this).length) {
                        $('.error:eq(0)', this).focus();
                        return false;
                }
                
//               if ($(this).is('#orderform')) {
//			// blablabla via ajax?
//			popup_show('#thanx');
//			return false;
//		}
        });
        
        $('a.popup-trigger').click(function(){
		popup_show($(this).attr('href'));
		return false;
	});
	$('a.popup-hide').click(function(){
		popup_hide();
		return false;
	});
	
	// .teeth a:hover & strong backgrounds
        $('.teeth').each(function(){
                var width   = $(this).outerWidth(),
                    height  = $(this).outerHeight(),
                    bgpoint = Math.ceil((width - 8) / 2) + 1;
                                
                $('strong, a.active', this).each(function(){
                        teeth_bg($(this), bgpoint, height);
                });
                
                $('a:not(.active):not(.noteeth)', this).hover(function(){
                        teeth_bg($(this), bgpoint, height);
                }, function(){
                        $(this).css({
                                backgroundPosition: "0 -200px"
                        });
                });
        });
        function teeth_bg($el, bgpoint, height) {
                var offset = Math.abs(bgpoint - $el.position().left) % 8;
                $el.css({
                        backgroundPosition: Math.round(offset) + "px -" + (500 - height) + "px" 
                });
        }
        
        // cart fixed block
        if ( $('#cart').length ) {
		var cart_top = $('#cart').offset().top,
	            $cart_placeholder = $('.cart-placeholder');
	        function cart_fixed_block() {
	                if ($(window).scrollTop() > cart_top) {
	                        $cart_placeholder.removeClass('cart-placeholder').addClass('cart-placeholder-fixed');
	                } else {
	                        $cart_placeholder.removeClass('cart-placeholder-fixed').addClass('cart-placeholder');
	                }
	        }
	        $(window).scroll(cart_fixed_block);
	        cart_fixed_block();
	}
        
        // cat squares
        var $cat = $('ul.cat'); 
        $('li', $cat).hover(function(){
                $cat.addClass('cat-hovered');
        }, function(){
                $cat.removeClass('cat-hovered');
        });
        
        // cat loading...
        var delay = 300;
	$('.cat .loading').each(function(){
		delay += 100;
		$(this).delay(delay).animate({
			opacity: 0
		}, 250, function(){
			$(this).remove();
		});
	});
	
	// item gallery
	$('.item-gallery .quarter').click(function(){
		if ($(this).hasClass('active'))
			return false;
			
		if ($('.item-gallery img:animated').length)
			return false;
		
		$('.item-gallery .active').removeClass('active');
		$(this).addClass('active');
		
		var $active = $('.item-gallery .half img').css({zIndex: 2});
		var $next   = $('img', this).clone().css({zIndex: 1}).appendTo('.item-gallery .half');
		
		$active.animate({
			opacity: 0
		}, 500, function(){
			$active.remove();
		});
		
		return false;
	});
	
	// cart actions 
	$('.cart .delete').click(function(){
		$.ajax({
			type: "GET",
			url: $(this).attr('href'),
//			dataType: "json",
			cache: false,
			context: this,
			data: {
				"_format": "js"
			},
			success: function(data) {
		var $table = $(this).parents('table'); 
		$(this).parents('tr').hide(300, function(){
			$(this).remove();
			$table.find('tr').removeClass('even').end()
				.find('tr:odd').addClass('even');
			cart_recalc();
		
		});
			},
			error: function(){
				alert('Произошла ошибка, попробуйте позже');
			}
		});  			
		return false;
	});
	$('.cart input[type=text]').bind('blur change', function(){
		$(this).val(parseInt($(this).val().replace(/[^\d]/g, '')) || 1);
		cart_recalc();
	}).bind('keyup', function(){
		$(this).val(parseInt($(this).val().replace(/[^\d]/g, '')) || '');
		cart_recalc();
	});
        
        // index gallery
        var promo = {
	        interval: null,
	        duration:  400,
	        timeout:  8000,
	        pos:         0,
	        width:     756,
	        $wrap:    $('.index-gallery'),
	        $slides:  $('.index-gallery .slide'),
	        $car:     $('.index-gallery .slides'),
	        $keys:    $('.index-gallery .keys'),
	        $active:  null,
	        progress: false,
	        scrollto: function(id) {
	            var self = this;
	            if (this.progress)
	                return false;
	            var $next = $('#' + id, self.wrap);
	            var nextpos = $next.position().left;
	            if (this.pos == nextpos)
	                return false;
	            this.progress = true;
	
	            $('.active', self.$keys)
	                    .removeClass('active');
	            $('.' + id, self.$keys)
	                    .parents('li')
	                    .addClass('active');
	
	            this.$car.animate({
	                left: 0 - nextpos
	            }, (Math.abs(nextpos - self.pos) / self.width + 1) * self.duration,
	                    function() {
	                        self.pos = nextpos;
	                        self.progress = false;
	                    });
	            return true;
	        },
	        stop: function() {
	            if (this.interval !== null) {
	                clearInterval(this.interval);
	                this.interval = null;
	            }
	        },
	        start: function() {
	            var self = this;
	            this.$active = $('.slide:eq(0)', self.$car);
	            this.interval = setInterval(function() {
	                if (!self.progress)
	                    self.next();
	            }, this.timeout);
	        },
	        next: function() {
	            var self = this;
	            var $next = self.$active.next('.slide');
	            if (!$next.length)
	                $next = $('.slide:eq(0)', self.$wrap);
	            this.scrollto($next.attr('id'));
	            self.$active = $next;
	        }
	    };
	
	    if ($('.index-gallery').length) {
	        promo.$car.width(promo.width * promo.$slides.length);
		promo.start();
	        $('a', promo.$keys).click(function() {
	            promo.stop();
	            promo.scrollto($(this).attr('href').replace('#', ''));
	            return false;
	        });
	    }
        
});

function cart_recalc()
{
	var total = 0, total_count = 0;
	$('.cart tr:has(td)').each(function(){
		var cost = parseFloat($('.cost', this).text().replace(/[^\d\.]/g, '')),
		    quantity = parseFloat($('input[type=text]', this).val().replace(/[^\d\.]/g, '')),
		    sum = cost * quantity;
		total += sum;
		total_count += quantity;
		
		$('.sum', this).text(sum.space1k() + ' руб.');
	});
	$('.cart-summary .total').text(total.space1k() + ' руб.');	
	$('.cart-summary .total-count').text(total_count.space1k() + ' шт.');
	
	if (total_count == 0) {
		$('.cart, .cart-summary').hide();
		$('.cart-empty').show();
	}
}

function check_input($input) {
        var valid = true,
            rel   = $input.attr('rel'),
            val   = $input.val(),
            type  = $input.attr('type'),
//            email_re = /^([0-9a-z\.-_]+)@([0-9a-z\.-_]+)\.([0-9a-z-])+$/i,
			email_re=/^(?:[-a-z\d\+\*\/\?!{}`~_%&'=^^^$#]+(?:\.[-a-z\d\+\*\/\?!{}`~_%&'=^^^$#]+)*)@(?:[-a-z\d_]+\.){1,60}[a-z]{2,6}$/i,
	    validator = '';

	if ($input.is('textarea'))
		type = 'textarea';
	else if ($input.is('select'))
		type = 'select';

        switch ($input.attr('type')) {
                case 'checkbox':
                    if (/required/.test(rel) && !$input.attr('checked'))
                            valid = false;
                    break;

                case 'text':
                case 'password':
                case 'textarea':
                default:
                    if (/required/.test(rel) && val.replace(/\s/g, '') == '') {
                            valid = false;
                            validator = '.required';
                    }
        	    if (valid && /email/.test(rel) && val.match(email_re) == null) {
                            valid = false;
                            validator = '.email';
        	    }
                    break;
        }

        var $wrap = $input.parent('label');
        if (!$wrap.length)
                $wrap = $input;

        $input.nextAll('.validator').hide();
        
	if (valid) {
                $wrap.removeClass('error');
                return true;
        } else {
                $wrap.addClass('error');
                $input.nextAll('.validator' + validator).show();
                return false;
        }
};

function popup_hide() {
	$('#fader').remove();
	$('.popup').css({left: -10000});
	$(window).unbind('resize', fader_resize);
}

function popup_show(popup_selector) {
	var $popup = $(popup_selector);
	
	$('body').append('<div id="fader" />');
	$('#fader').css({ opacity: .5 }).click(popup_hide);
	fader_resize();
	$(window).bind('resize', fader_resize);
	
	var width = $popup.outerWidth(), height = $popup.outerHeight();
	
	$popup.css({
		marginLeft: 0 - Math.round(width / 2),
		left: '50%',
		top: $(window).scrollTop() + Math.round($(window).height() / 2),
		marginTop: 0 - Math.round(height / 2)  
	});
}


function fader_resize(){
	$('#fader').width($('#wrap').width());
	$('#fader').height($('#wrap').height());
}


/**
 * DIGIT DELIMITER
 *******************************************************/ 
String.prototype.space1k = function(spacer) {
    var dot = '.',
    	dotdigits = 2
	dotdigits_string = '',
	string = this.toString(),
	reversed = '',
    	nums = 1;

    if (string.indexOf(dot) !== false) {
    	string = parseFloat(string).toFixed(2).toString();
	var parts = string.split(dot);
	string = parts[0];
	dotdigits_string = parts[1];
    }    	
    
    if (typeof spacer != 'string')
    	spacer = ' ';
 
    string = string.replace(/[^0-9]/g, '');

    for (var i = string.length - 1; i >= 0; i--) {
        if (nums == 4) { reversed = spacer + reversed; nums = 1; }
        reversed = string.substr(i, 1) + reversed; nums++;
    }
    
    if (dotdigits_string.length)
    	reversed += dot + dotdigits_string;
	     
    return reversed;
}
Number.prototype.space1k = function(spacer) {
    if (typeof spacer != 'string') spacer = ' ';
    return this.toString().space1k(spacer);
}

/**
 * PLURAL FORMS
 *******************************************************/
function plural(form1, form2, form5, number)
{
    var form = '';
    if (number >= 100) {number = '' + number; number = parseInt(number.substr(number.length - 2, 2));}
    if (number < 11 || number > 19) {number = '' + number; number = parseInt(number.substr(number.length - 1, 1));
	switch (number) {
	    case 0: case 5: case 6: case 7: case 8: case 9:
		form = form5; break;
	    case 1:
		form = form1; break;
	    case 2: case 3: case 4:
		form = form2; break;
	}
    } else form = form5;
    return form;
}


/* jQuery.color */
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(!fx.colorInit){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);fx.colorInit=true;}fx.elem.style[attr]="rgba("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0),Math.max(Math.min(parseFloat((fx.pos*(fx.end[3]-fx.start[3]))+fx.start[3]),1),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([-+]?[0-9]*\.?[0-9]+)\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3]),parseFloat(result[4])];if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3]),1];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55,1];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16),1];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16),1];if(result=/rgba\(0, 0, 0, 0\)/.exec(color))return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()];}function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255,1],azure:[240,255,255,1],beige:[245,245,220,1],black:[0,0,0,1],blue:[0,0,255,1],brown:[165,42,42,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgrey:[169,169,169,1],darkgreen:[0,100,0,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkviolet:[148,0,211,1],fuchsia:[255,0,255,1],gold:[255,215,0,1],green:[0,128,0,1],indigo:[75,0,130,1],khaki:[240,230,140,1],lightblue:[173,216,230,1],lightcyan:[224,255,255,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],magenta:[255,0,255,1],maroon:[128,0,0,1],navy:[0,0,128,1],olive:[128,128,0,1],orange:[255,165,0,1],pink:[255,192,203,1],purple:[128,0,128,1],violet:[128,0,128,1],red:[255,0,0,1],silver:[192,192,192,1],white:[255,255,255,1],yellow:[255,255,0,1],transparent:[255,255,255,0]};})(jQuery);
