$().ready(function(){
	$(".auto-val").each(function(){
		$this = $(this);
		if($this.attr("title") != '') {
			$this.bind("focus",function(){ 
				$this = $(this).css('color', '#000');
				if($this.val() == $this.attr("title")) $this.val('');
			});
			$this.bind("blur",function(){ 
				$this = $(this);
				if($this.val() == '') $this.css('color', '#ccc').val($this.attr("title"));
			});
		}
	});

	$(".brends .box").brands();

	$("div[class^=cm-head]").bind("click", function(){ 
		if(this.className == "cm-head") {
			$this = $(this);
			$this.parent().find("div[class=cm-head-a]").attr('className', 'cm-head').next().stop().slideUp('fast');
			$this.attr('className', 'cm-head-a').next().stop().slideDown('fast');
		}
	})

	$('img.basket_add').click(function() { $(this).prev('form.basket_add:first').submit() })

	$('div.basket').each(function() {
		var basket = this
		$('input[type=checkbox]', basket).click(function() {
			var tr = $(this).parents('tr:first')
			var tds = $('td:not(:last)', tr)
			if (this.checked) tds.css({ opacity: 0.5, textDecoration: 'line-through' })
			else tds.css({ opacity: 1, textDecoration: 'inherit' })
			var input = $('.count input', tr)
			if (this.checked) input.attr('disabled', 'disabled')
			else input.attr('disabled', false)
		})
		$('#basket_clear input[type=submit]').click(function() { return confirm('Вы действительно хотите очистить корзину?') })
	})
})

$(document).bind("load",function(){
	preloadImages('/images/structure/mm_01_a.gif', '/images/structure/mm_02_a.gif', '/images/structure/mm_03_a.gif', '/images/structure/mm_04_a.gif', '/images/structure/mm_05_a.gif', '/images/structure/mm_06_a.gif', '/images/structure/mm_07_a.gif');
});

function preloadImages() { 
	var d=document; 
	if(d.images){ 
		if(!d.MM_p) d.MM_p=new Array();
		var i,j=d.MM_p.length,a=arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0) { 
			d.MM_p[j]=new Image; 
			d.MM_p[j++].src=a[i];
		}
	}
}

jQuery.fn.brands = function() {
	return this.each(function(){
		var $this = jQuery(this);
		$this.removeClass("box").wrap('<div class="box"></div>').wrap('<div class="fixed"></div>');
		$this.parent().before(jQuery('<div class="b-left b-left-dis" title="влево"></div>'))
			.prev()
				.bind("mousedown", function() {
					var $box = jQuery(this).next().get(0);
					$box.direction = -1;
					$box.startScrolling();
				});
		$this.parent().after(jQuery('<div class="b-right" title="вправо"></div>'))
			.next()
				.bind("mousedown", function() {
					var $box = jQuery(this).prev().get(0)
					$box.direction = 1;
					$box.startScrolling();
				});	
		$(document).bind("mouseup",function(){ jQuery(".brends .box .fixed").get(0).stopScrolling(); });
		this.parentNode.startScrolling = function() { jQuery(".brends .box .fixed").get(0).scrolling(); }
		this.parentNode.stopScrolling = function() { jQuery(".brends .box .fixed").get(0).direction = 0; }
		this.parentNode.scrolling = function() {
			if(this.direction && this.direction != 0) {
				if(jQuery(this).scrollLeft() + this.direction * 10 <= 0) {
					jQuery(this).prev().addClass("b-left-dis");
					jQuery(this).scrollLeft(0);
				} else if(jQuery(this).scrollLeft() + this.direction * 10 >= this.controlWidth - jQuery(this).width()) {
					jQuery(this).next().addClass("b-right-dis");
					jQuery(this).scrollLeft(this.controlWidth - jQuery(this).width() + 9);
				} else {
					if(jQuery(this).prev().hasClass("b-left-dis")) jQuery(this).prev().removeClass("b-left-dis");
					if(jQuery(this).next().hasClass("b-right-dis")) jQuery(this).next().removeClass("b-right-dis");
					jQuery(this).scrollLeft(jQuery(this).scrollLeft() + this.direction * 10);
					setTimeout(function(){jQuery(".brends .box .fixed").get(0).scrolling()},25);
				}
			}
		}
		var allWidth = 0;
		jQuery("a",$this).addClass("b-float").each(function(){ allWidth += jQuery(this).find("img").width() + 22; });
		jQuery(".brends .box .fixed").get(0).controlWidth = allWidth;
		allWidth += 15;
		if(jQuery.browser.msie) allWidth += 1000;
		$this.width(allWidth);
	});
}

/**
 * Проверяет изменение поля
 * После смены значения запускает callback с новым значением
 * 
 * @author Ti
 * @version 0.1
 * 
 * @param {function} callback
 */
$.fn.changeValue = function(callback) {
	if (0 === arguments.length) {
		$(this).each(function() {
			if (!this._changeValueCallbacks) return result
			this._changeValueCallbacks.run()
		})
		return this
	}
	if (typeof callback !== 'function') throw new Error('Invalid first argument expected!')
	$(this).each(function() {
		var _this = this
		if (_this._changeValueCallbacks) return _this._changeValueCallbacks.push(callback)
		_this._changeValueCallbacks = [callback]
		_this._changeValueCallbacks.run = function() {
			for(var i = 0; i < _this._changeValueCallbacks.length; i++) _this._changeValueCallbacks[i].call(_this, val)
		}
		var val = _this.value
		var check = function() {
			if (val === _this.value) return
			val = _this.value
			_this._changeValueCallbacks.run()
		}
		var interval
		$(_this).focus(function() {
			val = _this.value
			interval = setInterval(check, 50)
		})
		$(_this).blur(function() {
			clearInterval(interval)
			check()
		})
	})
	return this
}



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



$().ready(function() {
	$('#reg').each(function() {
		var $reg = $(this)
		var get = function(i) { return $('input[name=password'+i+']', $reg) }
		var more = get(1).length
		if (!more) return;

		var l = $('<label id="show_pass"> показать '+(more ? 'пароли' : 'пароль')+'</label>')
		var c = $('<input type="checkbox" name="show_pass" id="show_pass" />').prependTo(l)
		var withOld = get('').length
		if (withOld) get('').parent().append(l)
		else get(1).parent().append(l)

		var replace = function(old) {
			var type = c.attr('checked') ? 'text' : 'password'
			var result = $('<input name="'+old.attr('name')+'" type='+type+' />').val(old.val()).insertBefore(old)
			old.remove()
			return result
		}

		var change = function() {
			if (withOld) replace(get(''))
			if (more) {
				replace(get(1)).changeValue(function(newVal) { get(2).val(newVal) })
				replace(get(2)).attr('readonly', 'readonly').val(get(1).val()).css('opacity', 0.5)
			}
			$.cookie('show_pass', c.attr('checked') ? 'yes' : '', { path: '/' })
		}

		if ($.cookie('show_pass')) {
			c.click()
			change()
		}

		c.click(change)

		$('input,textarea', $('div.error').parents('tr').next()).first().focus()
	})
})
