$jq = jQuery.noConflict();
/* Cookies */
$myCook = {
	get: function ( name ) {
		var start = document.cookie.indexOf( name + '=' );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	},
	set: function ( name, value, expires, path, domain, secure ) {
		var today = new Date(); today.setTime( today.getTime() );
		if ( expires ) {expires = expires * 1000 * 60 * 60 * 24;}
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
			( ( path ) ? ';path=' + path : '; path=/' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );
	},
	del: function ( name, path, domain ) {
		if ( Cookie.get( name ) ){
			 document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : ';path=/') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
		}
	}
}

Number.prototype.constrain = function(min, max) {
	return (this < min) ? min : ((this > max) ? max : this.valueOf());
}
Number.prototype.toPercents = function(n) {
	return (this.valueOf() * 100).toFixed(n) + "%";
}

/* Menu */
$jq(document).ready(function() {
	$jq('#menu > li').mouseenter(function() {
		$jq(this).addClass('hover');
	}).mouseleave(function() {
		$jq(this).removeClass('hover');
	});
});

/* Search */
search = {
init: function(selector) {
	var self = this;
	this.form = $jq(selector);
	$jq('.values:not(".disabl")', this.form).mousedown(function(event) {
		event.stopPropagation();
	}).each(function() {
		var values = $jq(this);
		var control = values.prev('.control');
		control.attr('data-empty', control.text());
		self.update(values);
	}).delegate('input', 'click', function() {
		self.update($jq(this).closest('.values'));
	}).prev('.control').click(function() {
		self.show($jq(this));
	}).mousedown(function(event) {
		if ($jq(this).next('.values').is(':visible')) event.stopPropagation();
	});
	this.self_hide = function() {
		self.hide();
	};
},
update: function(values) {
	var result = [], title;
	$jq('input', values).each(function() {
		if (this.checked) result.push($jq(this).next('label').html());
	});
	var rl = result.length;
	var control = values.prev('.control');
	if (rl > 1) {
		title = '<strong>Выбрано ' + rl + ':</strong> ' + result.join(', ').toLowerCase();
	} else if (rl) {
		title = result[0];
	} else {
		title = control.attr('data-empty');
	}
	control.children('.title').html(title);
	if (values.hasClass('radio')) {
		this.hide();
	}
},
show: function(control) {
	var list = control.next('.values');
	if (list.is(':hidden')) {
		list.width('auto').css('visibility', 'hidden').show();
		if (list.outerWidth() < control.outerWidth()) {
			list.width(control.width() - (list.hasClass('radio') ? 8 : 25));
		}
		var time = 80 + Math.round(list.height() / 4);
		list.hide().css('visibility', 'inherit').slideDown(time);
		$jq(document).bind('mousedown', this.self_hide);
		this.current = list;
	} else {
		this.hide()
	}
},
hide: function() {
	$jq(document).unbind('mousedown', this.self_hide);
	if (this.current) this.current.hide();
	delete(this.current);
}
};

/* Site popup */
sitePopup = {
init: function() {
	var self = this;
	var move = function(event) {
		self.el.css('left', event.pageX + ((event.pageX > self.xmax) ? (- 15 - self.pwidth) : 20));
		self.el.css('top', Math.min(event.pageY, self.ymax + $jq(window).scrollTop()) - 5);
	};
	var stimer;
	this.el = $jq('<div id="sitepopup"></div>').appendTo('body');
	$jq('.gallery').delegate('.preview', 'mouseenter', function(event) {
		var content = $jq('.spopup', $jq(this).parent());
		if (content.length > 0) {
			self.update(content);
			$jq(document).mousemove(move);
			stimer = setTimeout(function() {
				self.el.fadeIn(120);
			}, 500)
		}
	}).delegate('.preview', 'mouseleave', function(event) {
		clearTimeout(stimer);
		self.el.hide();
		$jq(document).unbind('mousemove', move);
	});
},
update: function(content) {
	this.el.html('').css('visibility', 'hidden').css('top', 0).css('left', 0);
	this.el.append(content.clone()).show();
	this.pwidth = this.el.width();
	this.xmax = $jq(window).width() - this.pwidth - 30;	   
	this.ymax = $jq(window).height() - this.el.height() - 10;
	this.el.hide().css('visibility', 'inherit')
}
};

/* Scrollable sites */
var siteline = {
init: function() {
	var self = this;
	this.context = $jq('#siteline');
	this.viewport = $jq('#slviewport').scroll(function() {
		if (self.dragging) return;
		var offset = self.viewport.scrollLeft() / self.sleftmax;
		self.slider.css('left', offset.toPercents(3));
	});
	$jq(window).resize(function() {
		self.update();
		self.viewport.trigger('scroll');
	});
	this.slider = $jq('.slider', this.context);
	this.initDrag();
	this.initArrows();
	this.update();
},
initDrag: function() {
	var self = this;
	var drag = function(event) {
		var d = self.dragging;
		var sx = (d.sx + event.pageX - d.ex).constrain(0, self.scopewidth);
		self.slider.css('left', sx);
		self.viewport.scrollLeft(Math.round(self.sleftmax * sx / self.scopewidth));
	};
	this.slider.mousedown(function(event) {
		event.preventDefault();
		self.dragging = {
			sx: self.slider.position().left,
			ex: event.pageX
		};
		$jq(document).mousemove(drag).one('mouseup', function() {
			$jq(document).unbind('mousemove', drag);
			delete(self.dragging);
		});
	});
},
initArrows: function() {
	var self = this, stimer, direction;
	var scroll = function() {
		if (Math.abs(direction) < 21) direction += direction.constrain(-1, 1);
		self.viewport.scrollLeft(self.viewport.scrollLeft() + direction);
	};
	var initArrow = function(selector, dir) {
		$jq(selector, self.context).mousedown(function() {
			direction = dir;
			stimer = setInterval(scroll, 20);
		}).bind('mouseup mouseout', function() {
			clearInterval(stimer);
		});
	};
	this.scleft = initArrow('.scleft', -1);
	this.scright = initArrow('.scright', 1);
},
update: function() {
	this.sleftmax = this.viewport.get(0).scrollWidth - this.viewport.width();
	this.scopewidth = this.slider.parent().width();
}
};

/* Screenshots */
function initScreenshots() {
	var context = $jq('#spages');
	var wrap = $jq('.wrap', context);
	var title = $jq('h6', context);
	var scroller = $jq('.pscroller', context);
	var pages = $jq('.spage', scroller);
	var pwidth = pages.eq(0).width() + 10;
	var page, current = 0;
	var slide = function(n) {
		current = (current + n).constrain(0, pages.length - 1);
		page = pages.eq(current);
		title.text(page.find('img').attr("alt"));
		prev.toggleClass('disabled', current == 0);
		next.toggleClass('disabled', current == pages.length - 1);
		scroller.animate({'left': -pwidth * current}, 200);
		wrap.animate({'height': page.height()}, 200);
	}
	var prev = $jq('.prev div.arrow', context).click(function() {
		slide(-1);
	});
	var next = $jq('.next div.arrow', context).click(function() {
		slide(1);
	});
	$jq('img:not(:last)', scroller).click(function() {
		slide(1);
	});
	var minheight = 5000;
	for (var i = pages.length; i--;) {
		minheight = Math.min(minheight, pages.eq(0).height());
	}
	prev.add(next).css('margin-top', Math.round(minheight / 2) - 8);

	slide(0);
}

/* Site order */
function initSiteOrder() {
	$jq('#overlay td.align').click(function() {
		$jq('#overlay').hide();
	});
	$jq('#overlay .popup').click(function(event) {
		event.stopPropagation();
	});
	$jq('.compare .button').click(function() {
		var type = $jq(this).attr('data-type'), isRent = type == 'rent';
		var form = $jq('#siteorder');
		form.get(0)['type'].value = type;
		form.find('h4 .type').html(isRent ? 'Аренда' : 'Покупка');
		form.find('.period').toggle(isRent);
		form.find('.buy').toggle(!isRent);
		$jq('#overlay').show();
	});
	$jq('#siteorder select[name=period]').change(function() {
        var select = $jq(this);
        var total = (this.value * parseInt(select.attr('data-permonth'))).toString();
        if (total.length > 3) total = total.substring(0, total.length - 3) + '.' + total.substring(total.length - 3);
        select.closest('dl').find('.cost').html(total + ' р.');
    }).change();
}

/* Client form */
function initClientForm() {
    $jq('#client-button img').click(function() {
        var button = $jq(this), boffset = button.offset(), form = $jq('#client');
        form.css('visibility', 'hidden').show().css({
            left: boffset.left + button.width() - form.width() - 25,
            top: boffset.top + button.height() - form.height() - 23,
            visibility: 'inherit'
        });
        setTimeout(function() {
            $jq('body').one('click', function() {
                form.hide();
            });
        }, 100);
    });
    $jq('#client').click(function(event) {
        event.stopPropagation();
    });
}
