Storage={engines:["WhatWG","userData","Flash8"],swfUrl:"/storage.swf",init:function(A){for(var B=0;B<this.engines.length;B++){try{this[this.engines[B]](function(){Storage.active=true;A&&A()});break}catch(C){}}}};Storage.WhatWG=function(A){var B=globalStorage[location.hostname];Storage={put:function(C,D){B[C]=D},get:function(C){return String(B[C])},remove:function(C){delete B[C]},getKeys:function(){var C=[];for(i in B){C.push(i)}return C},clear:function(){for(i in B){delete B[i]}}};A()};Storage.userData=function(A){var B="data";if(!document.body.addBehavior){throw new Error("No addBehavior available")}var C=document.getElementById("storageElement");if(!C){C=document.createElement("span");document.body.appendChild(C);C.addBehavior("#default#userData");C.load(B)}Storage={put:function(D,E){C.setAttribute(D,E);C.save(B)},get:function(D){return C.getAttribute(D)},remove:function(D){C.removeAttribute(D);C.save(B)},getKeys:function(){var F=[];var D=C.XMLDocument.documentElement.attributes;for(var E=0;E<D.length;E++){F.push(D[E].name)}return F},clear:function(){var D=C.XMLDocument.documentElement.attributes;for(var E=0;E<D.length;E++){C.removeAttribute(D[E].name)}C.save(B)}};A()};Storage.Flash8=function(B){var A;var C="StorageMovie";while(document.getElementById(C)){C="_"+C}var F=Storage.swfUrl;Storage={put:function(I,J){A.put(I,J)},get:function(I){return A.get(I)},remove:function(I){A.remove(I)},getKeys:function(){return A.getkeys()},clear:function(){A.clear()},ready:function(){A=document[C];B()}};var G=window.location.protocol=="https"?"https":"http";var D="width:0; height:0; position: absolute; z-index: 10000; top: -1000px; left: -1000px;";var E='<embed src="'+F+'"  bgcolor="#ffffff" width="0" height="0" id="'+C+'" name="'+C+'" swLiveConnect="true" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="'+G+'://www.macromedia.com/go/getflashplayer" ></embed>';var H=document.createElement("div");H.setAttribute("id",C+"Container");H.setAttribute("style",D);H.innerHTML=E;document.body.appendChild(H)};

(function($){function toIntegersAtLease(n){return n<10?'0'+n:n}Date.prototype.toJSON=function(a){return this.getUTCFullYear()+'-'+toIntegersAtLease(this.getUTCMonth())+'-'+toIntegersAtLease(this.getUTCDate())};var f=/["\\\x00-\x1f\x7f-\x9f]/g;var g={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(b){if(f.test(b)){return'"'+b.replace(f,function(a){var c=g[a];if(typeof c==='string'){return c}c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+b+'"'};$.toJSON=function(o,a){var b=typeof(o);if(b=="undefined")return"undefined";else if(b=="number"||b=="boolean")return o+"";else if(o===null)return"null";if(b=="string"){return $.quoteString(o)}if(b=="object"&&typeof o.toJSON=="function")return o.toJSON(a);if(b!="function"&&typeof(o.length)=="number"){var c=[];for(var i=0;i<o.length;i++){c.push($.toJSON(o[i],a))}if(a)return"["+c.join(",")+"]";else return"["+c.join(", ")+"]"}if(b=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}var c=[];for(var k in o){var d;b=typeof(k);if(b=="number")d='"'+k+'"';else if(b=="string")d=$.quoteString(k);else continue;var e=$.toJSON(o[k],a);if(typeof(e)!="string"){continue}if(a)c.push(d+":"+e);else c.push(d+": "+e)}return"{"+c.join(", ")+"}"};$.compactJSON=function(o){return $.toJSON(o,true)};$.evalJSON=function(a){return eval("("+a+")")};$.secureEvalJSON=function(a){var b=a;b=b.replace(/\\["\\\/bfnrtu]/g,'@');b=b.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');b=b.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(b))return eval("("+a+")");else throw new SyntaxError("Error parsing JSON, source is not valid.");}})(jQuery);

function alert(_) {
	if (!_ || !_.text) _ = {text: _};
	var $frame = $('<div class="popup-frame-alert"><h1>' + _.text + '</h1></div>'),
		$shadow = $('<div class="popup-shadow-alert"></div>').css('opacity', 0),
		$okBtn = $('<button>Ok</button>').click(function(){			
			$frame.remove();
			$shadow.animate({ opacity: 0 }, 300, function(){
				$shadow.remove();
			})
			_.onOk && _.onOk();
		});
		
	$frame.append($okBtn);
	$(document.body).append($shadow, $frame);
	$shadow.animate({ opacity: .8 }, 300);
};

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var basket = (function(){
	var $basket, $counter, $toggleLink, $items, $total, $sum,
		maxHeight, maxWidth,
		items,
		itemsCount = 0,
		template =
		'<div id="basket">\
			<h1><a href="#" id="basket-toggle" onclick="return false">Открыть</a>Корзина</h1>\
			<div class="bHeader">\
				<p class="hdr">Ваша корзина</p>\
				<p><span id="itemsCounter"></span>Товаров:</p>\
				<p><span id="basketSum"></span>На сумму:</p>\
			</div>\
			<table cellspacing="0"><thead><tr>\
				<th class="name">Наименование</th>\
				<th class="price">Цена</th>\
				<th class="qty">Количество</th>\
				<th class="cost">Стоимость</th>\
				<th class="del delTH">&nbsp;</th>\
			</tr></thead></table><div class="scrolls"><table cellspacing="0"><tbody></tbody></table>\
			</div>\
			<span id="total"></span>\
		</div>';

	function init(){

		$basket = $(template);
		$counter = $('#itemsCounter', $basket);
		$sum = $('#basketSum', $basket);
		$toggleLink = $('#basket-toggle', $basket).click(toggle);
		$items = $('table tbody:last', $basket);
		$total = $('#total', $basket);
		$basket
			.appendTo(document.body)
			.fadeIn('slow')
		
		maxWidth = $(document.body).width() - 300;
		maxHeight = $(window).height();
		
		$('a.addBasket').click(function(){
			try {
				var	$this = $(this),
					item = parseJSON($this.attr('href'));
				
				//item.qty = parseInt( $('input[name=count]', $this.parent()).val() );
				item.qty = 1;
				add(item)
				alert('Товар успешно добавлен в корзину');
			} catch(e) {
				//console && console.log && console.log(e) || 
				alert(e);
			}
			return false;
		});
		
		$('#doPay').live( 'click', exportCart );
		
		Storage.init();
		setTimeout(load, 700);
		// toggle();
	}
	
	function add(_){
		var item = _.id;
			amount = _.qty || 1;
		
		itemsCount += amount;
		if (items[item]) {
			items[item].qty += amount;
		} else {
			items[item] = {
				text:	_.text,
				link:	_.link,
				price:	_.price,
				qty:	amount
			};
		}
		
		save();
		refresh();
		return false;
	}
	
	function refresh(){
		var totalItems = 0,
			totalSum = 0,
			s = '';
		for (var i in items) {
			totalItems += items[i].qty;
			var cost = items[i].price * items[i].qty;
			totalSum += cost;
			s += '<tr rel="'+i+'">\
				<td class="name"><a href="'+items[i].link+'">'+items[i].text+'</a></td>\
				<td class="price TAright">'+items[i].price+'</td>\
				<td class="qty bold TAcenter"><a class="more btn" href="#">+</a><a class="less btn" href="#">-</a>'+items[i].qty+'</td>\
				<td class="cost bold TAright">'+cost+'</td>\
				<td class="del TAright"><a href="#" class="basket-item-remove" rel="'+i+'" title="Удалить">x</a></td>\
			</tr>';
		}
		if (s) {
			$items.html(s);
						
			$total.html('<a href="javascript:void(0)" id="basket-clear">Очистить корзину</a><a href="#" id="doPay">Оформить заказ</a><span>Итого: Всего товаров '+totalItems+' ед. на сумму '+totalSum+' руб</span>');			
			$('#basket-clear').click(clear);
		} else {
			$items.empty();
			$total.empty();
		}
		
		$counter.html(totalItems || '—');
		$sum.html(totalSum);
		$('a.basket-item-remove', $items).click(remove);
		$('a.btn', $items).click(btn);
	}

	function btn(){
		var $btn = $(this),
			id = $btn.parents('tr').attr('rel');
		if ($btn.hasClass('more')) {
			items[id].qty++;
		} else {
			if (items[id].qty > 1) items[id].qty--; else return false;
		}
		save();
		refresh();
		return false;
	}
	
	function remove(){
		delete items[ $(this).attr('rel') ];
		save();
		refresh();
		return false;
	}
	
	function toggle(){
		if ($basket.hasClass('opened')) {
			$basket.animate({right: '1px', width: '150px', height: '70px', bottom: 1}, function(){
				$(this).removeClass('opened');
				$toggleLink.html('Открыть');
			});
		} else {
			$basket
				.addClass('opened')
				// .animate({right: '100px', width: '700px', height: '500px'});
				.animate({right: '150px', width: maxWidth, height: '443px', bottom: (maxHeight >> 1) - 250});
			refresh();
			$toggleLink.html('Закрыть');
		}
	}
	
	function save(){
		Storage.put('items', $.toJSON(items));		
	}
	
	function load(){
		items = Storage.get('items');
		items = (!items || items === 'undefined') ? {} : $.evalJSON(items);
		refresh();
	}
	
	function clear(){
		Storage.clear();
		items = {};
		refresh();			
	}
	
	function parseJSON(_){
		try {
			_ = eval('(' + _ + ')');
		} catch(e) {
			alert(e);
			return false;
		}
		return _;
	}
	
	function exportCart(){
		var s = '<form action="/?cart" method="POST">';
		for (i in items) {
			s += '<input name="id[]" value="'+i+'"/>';
			s += '<input name="text[]" value="'+items[i].text+'"/>';
			s += '<input name="link[]" value="'+items[i].link+'"/>';
			s += '<input name="price[]" value="'+items[i].price+'"/>';
			s += '<input name="qty[]" value="'+items[i].qty+'"/>';
		}
		s += '<input type="hidden" name="order" value="true"></form>';
		$(s).appendTo('body').submit();
		return false;
	}
	
	return {
		init:	init,
		add:	add,
		clear:	clear,
		load:	load
	}
})();

function leather_info_wnd(name, descr, image){
	var d=document.getElementById('leather_'+descr).innerHTML;
      var sf = window.open("","_blank","height=350,width=300,scrollbars=1,resizable=0");
	var tsf = '<html><title>'+name+'</title>\n<body bgcolor=#ffffff>\n';
	tsf = tsf+'<p><b>'+name+'</b></p>';
	tsf = tsf+'<p>'+d+'</p>';
	tsf = tsf+'<img src="http://www.constantag.ru/images/leather_images/'+image+'"><br><br><center><button OnClick="window.close()">Закрыть</button></center></body></html>';
	var dsf = sf.document;
	dsf.open();
	dsf.write(tsf);
	dsf.close();
}

$(function(){
	zoom.init();
});

$(basket.init);

var zoom = (function(){
	var maxHeight, maxWidth, loader, shadow, frame;

	function init(){
		maxHeight = $(window).height() - 50;
		maxWidth = $(document.body).width() >> 1;
		$('img.zoomable')
			.hover(
				function(){$(this).children().stop().animate({opacity: 1}, 200)},
				function(){$(this).children().animate({opacity:.75}, 500)}
			)
			.click(load)
			.children().css({opacity: .75});
	}
	
	function load(){

		function close(){
			loader.remove();
			shadow.animate({opacity: 0}, 300, function(){
				frame.remove();
			});
		}
		var link = $(this),
			frame = $('<div class="popup-frame"></div>'),
			shadow = $('<div class="popup-shadow"></div>').css('opacity',0),
			loader = $('<div class="popup-loader"></div>'),
			bigSrc = 'http://constantag.ru/img/?i=1094978&tp=about&w=0&h=0&s=0',
			image = $('<img src="' + link.attr('src').replace(/w=\d.*?(&|$)/, 'w=' + maxWidth + '&').replace(/h=\d.*?(&|$)/, 'h=' + maxHeight + '&') + '"/>'),
			button = $('<span title="Закрыть"></span>');

		frame.appendTo('body');
		shadow.appendTo(frame).animate({opacity: 0.6}, 300);
		loader.appendTo(frame);
		image.appendTo(loader);		
		
		image.load(function(){

			button.appendTo(loader);

			var h = image.height();
			
			if (h > maxHeight) {
				h = maxHeight;
				image.height(h);
			}
			var w = image.width();			

			loader.addClass('popup-loaded').animate({
				width:		w,
				marginLeft:	-w/2,
				height:		h,
				marginTop:	-h/2
			}, 500, function(){
				loader.addClass('popup-canvas');
				image.animate({opacity: 1}, 300, function(){

					shadow.click(close);
					button.click(close);
					image.click(close);

					$(document).keydown(function(e){
						if (e.which == 27) close();
					});
				});
			});
		});

		return false;		
	};
	
	return {init: init, load: load}
})();


function show_rekv(obj){
	var d=document;
	if(obj.value==1){
		d.getElementById("rek_table").style.display="none";
	}else{
		d.getElementById("rek_table").style.display="inline";
	}
}

function show_short_rekv(obj){
	var d=document;
	if(obj.value==1){
		d.getElementById("agent_table").style.display="none";
		d.getElementById("of_name").innerHTML="Квартира";
	}else{
		d.getElementById("agent_table").style.display="inline";
		d.getElementById("of_name").innerHTML="Офис";
	}
}

function expand_item(id){
	var workDiv=document.getElementById('subtree_'+id);
	var workButton=document.getElementById('expand_'+id);
	workDiv.style.display='block';
	workButton.src="/images/minus.gif";
}
function collapse_item(id){
	var workDiv=document.getElementById('subtree_'+id);
	var workButton=document.getElementById('expand_'+id);
	workDiv.style.display='none';
	workButton.src="/images/plus.gif";
}

function switch_item(id){
	var workDiv=document.getElementById('subtree_'+id);
	switch (workDiv.style.display) {
		case 'none': expand_item(id); break;
		case 'block': collapse_item(id); break;
	}
}
function showToolTip(e,text){
	if(document.all)e = event;

	var obj = document.getElementById('bubble_tooltip');
	var obj2 = document.getElementById('bubble_tooltip_content');
	obj2.innerHTML = text;
	obj.style.display = 'block';
	var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
	if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0;
	var leftPos = e.clientX - 100;
	if(leftPos<0)leftPos = 0;
	obj.style.left = leftPos + 'px';
	obj.style.top = e.clientY - obj.offsetHeight -1 + st + 'px';
	}

	function hideToolTip()
	{
	document.getElementById('bubble_tooltip').style.display = 'none';

	}
