Storage={
		engines:["WhatWG","Flash8"],
		swfUrl:"/storage.swf",
		init:function(A){
			if(!$.browser.msie){
				for(var B=0;B<this.engines.length;B++){
					try{
						this[this.engines[B]](function(){
							Storage.active=true;A&&A()
						});
						//console.log(e);
						break
					}catch(C){
						
					}
				}
			}else{
				try{
					this.userData(function(){
						Storage.active=true;A&&A()
					});
				}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.className = 'storage';
		//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.userData = function(A) {
    var B = "data";

    if (!document.body.addBehavior) {
        throw new Error("No addBehavior available");
    }

	var e = document.createElement("iframe");
	e.setAttribute('id', 'storageFrame');
	e.style.border = '0';
	e.style.width  = '0';
	e.style.height = '0';

	var iframe = document.body.appendChild(e);
	iframe.src='/proxy.html';

	
	try{
		$(iframe).load( function(e){
			var C = iframe.contentWindow.document.getElementById('storageElement');
			if(!C){
				C=iframe.contentWindow.document.createElement("span");
				iframe.contentWindow.document.body.appendChild(C);
				C.addBehavior("#default#userData");
			}
			
			C.load(B);
	
		    Storage = {
		        get: function(key) {
		            return C.getAttribute(key);
		        },
	
		        put: function(key, value) {
		            C.setAttribute(key, value);
		            C.save(B);
		        },
	
		        remove: function(key) {
		            C.removeAttribute(key);
		            C.save(B);
		        },
	
		        clear: function() {
		            var attrs = C.XMLDocument.documentElement.attributes;
	
		            for(var i = 0; i < attrs.length; i++) C.removeAttribute(attrs[i].name);
		            C.save(B);
		        },
	
		        getKeys: function() {
		            var res = [];
		            var attrs = C.XMLDocument.documentElement.attributes;
	
		            for(var i = 0; i < attrs.length; i++) res.push(attrs[i].name);
		            return res;
		        }
		    }
		    A();
		});
	}catch(E){ 
		 
	}

};

			
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);
	
	if($.browser.msie && $.browser.version<7){
		var oCanvas = document.getElementsByTagName(
				(document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY"
			)[0];

		var bodyW=oCanvas.clientWidth;
		var bodyH=oCanvas.clientHeight;
		
		var w_width = window.innerWidth ? window.pageXOffset : oCanvas.scrollLeft;
		var w_height = window.innerHeight ? window.pageYOffset : oCanvas.scrollTop;
		
		var posX=Math.ceil(w_width+bodyW/2);
		var posY=Math.ceil(w_height+bodyH/2); 

		$($frame,".popup-frame-alert").css({ left: posX, top: posY });
	}
	
	$(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);
		$basket.click(toggleBasket);
		$items = $('table tbody:last', $basket);
		$total = $('#total', $basket);
		$basket
			.appendTo( $('#headerRight') )
			.fadeIn('slow')
		
		maxWidth = $(document.body).width() - 300;
		maxHeight = $(window).height();
		
		items = [];
		
		$('a.add','span.cart','div.cart').click(function(){
			try {
				var	$this = $(this),
					item = parseJSON($this.attr('rel'));
				
				//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();
		
		//items_dbg = Storage.get('items');
		setTimeout(load, 900);
		// 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(){
		absolute_right_pos = ( $(document.body).width()-1000 )/2 + 3;
		if ($basket.hasClass('opened')) {
			
			$basket.animate({ right: absolute_right_pos, width: '240px', height: '105px' }, function(){
				$(this).removeClass('opened');
				$(this).css({right: '3px'});
				$toggleLink.html('Открыть');
			});
		} else {
			$basket
				.addClass('opened')
				.css("right",absolute_right_pos)
				// .animate({right: '100px', width: '700px', height: '500px'});
				.animate({right: '150px', width: maxWidth, height: '443px', bottom: (maxHeight >> 1) - 250});
			refresh();
			$toggleLink.html('Закрыть');
		}
	}

	function toggleBasket(){
		if(! $basket.hasClass('opened') ){
			absolute_right_pos = ( $(document.body).width()-1000 )/2 + 3;
			$basket.addClass('opened')
				.css("right",absolute_right_pos)
				// .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,
		refresh: refresh
	}
})();



function slideSwitch() {
	var $active = $('#mediaBanner div.active');
	if ( $active.length == 0 ) $active = $('#mediaBanner div:last');
	var $next =  $active.next().length ? $active.next() : $('#mediaBanner div:first');
	$active.addClass('last-active');
	$next.css({opacity: 0.0})
		.addClass('active')
		.animate({opacity: 1.0}, 1000, function() {
			$active.removeClass('active last-active');
		});
}


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>'),
			image = $('<img src="' + link.attr('src') + '">'),
			button = $('<span title="Закрыть"></span>');
		
		if($.browser.msie && $.browser.version<7){
			
			var oCanvas = document.getElementsByTagName(
					(document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY"
				)[0];

			var bodyW=oCanvas.clientWidth;
			var bodyH=oCanvas.clientHeight;
			
			var w_width = window.innerWidth ? window.pageXOffset : oCanvas.scrollLeft;
			var w_height = window.innerHeight ? window.pageYOffset : oCanvas.scrollTop;
			
			var posX=Math.ceil(w_width+bodyW/2);
			var posY=Math.ceil(w_height+bodyH/2); 
			
			
			loader.css({top: posY,left:posX});
		}
		
		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();
					});
				});
			});
		});

		if($.browser.opera){ image.load(); }
		
		return false;		
	};
	
	return {init: init, load: load}
})();

/* JQuery Plugins */
(function($) {
	$.fn.lavaLamp = function(o) {
	    o = $.extend({ fx: "linear", speed: 500, click: function(){} }, o || {});

	    return this.each(function() {
	        var me = $(this), noop = function(){},
	            $back = $('<li class="back"><div class="left"></div></li>').appendTo(me),
	            $li = $("li", this), curr = $("li.current", this)[0] || $($li[0]).addClass("current")[0];

	        $li.not(".back").hover(function() {
	            move(this);
	        }, noop);

	        $(this).hover(noop, function() {
	            move(curr);
	        });

	        $li.click(function(e) {
	            setCurr(this);
	            return o.click.apply(this, [e, this]);
	        });

	        setCurr(curr);

	        function setCurr(el) {
	            $back.css({ "left": el.offsetLeft+"px", "width": el.offsetWidth+"px" });
	            curr = el;
	        };

	        function move(el) {
	            $back.each(function() {
	                $(this).dequeue(); }
	            ).animate({
	                width: el.offsetWidth,
	                left: el.offsetLeft
	            }, o.speed, o.fx);
	        };

	    });
	};
})(jQuery);


$(function(){
	zoom.init();
	basket.init();
	///basket.refresh();
	
	$('form#orderForm').submit(function(){
		if( jQuery.trim($('form#orderForm input#contactPerson').attr('value')) && jQuery.trim($('form#orderForm input#contactPhone').attr('value')) && jQuery.trim($('form#orderForm input#deliveryAddress').attr('value')) ){
			return true;
		}else{
			alert("Не все обязательные поля заполнены.");
			return false;
		}
	});
	
	$('form#orderForm input.radio').click(function(){
		value=$(this).attr('value');
		switch (value){
			case '1' : $('form#orderForm input#deliveryAddress').val(""); break;
			case '2' : $('form#orderForm input#deliveryAddress').val("г.Москва, Озерковская набережная 48/50"); break;
		}
	});

	/* Banner auto rotate */
	setInterval( "slideSwitch()", 7000 );
	$(".lavaLamp").lavaLamp({ speed: 500 });
	$("#logo").click(function(){
		$(location).attr('href',"/");
	}).css({cursor:'pointer'})
	
});



