_iwa = "http://iwa.miniaturearsenal."+(_lang=="ru"?"ru":"com");
_promo = "http://miniaturearsenal.ru/pubs/miniature_1.html";
$(document).ready(function() {
	Main.init();
});
$(document).keyup(function(e) {
	if ($("#next").length && !Main.blocked) {
		if (e.ctrlKey && e.keyCode == 39 && $("#next").css("display") == "block")
			$("#next").click();
		if (e.ctrlKey && e.keyCode == 37 && $("#prev").css("display") == "block")
			$("#prev").click();
	}
});

var Main = {
	blocked : false,
	order : "",
	init : function() {
		var top = ($(document).height() - $("#site").height()) / 2 - 2;
		$("#site").animate( {
			top : top < 0 ? 0 : top
		});
		Main.scroll();
		Main.initTape();
		fuckAds();
		//document.location.pathname.indexOf("show1") == -1?Show.run():fuckAds();
		Catalog.initCatalogMenu();
		Catalog.LoadScroll();
		Main.aliveLinks();
		$("#picts a:gt(0), #models a").unbind("click").click(function() {
			Main.navigate(this.pathname);
			return false;
		});
		News.init();
		$("#menu").find("td a").click(function() {
			if ($(this).hasClass('here'))
				return false;
			if (Main.blocked)
				return false;
			if (!Main.blocked) {
				Menu.highlight(this.getElementsByTagName('img')[0]);
				Main.navigate(this.pathname);
			}
			$("#menu_cat li").removeClass('sel');
			return false;
		});
		(new Image()).src = "/i/photo_bg_big.jpg";
	},

	navigate : function(url) {
		if (Main.blocked)
			return;
		Main.blocked = true;
		$('#descr').addClass('hide');
		Show.stop();
		$("#page").animate( {
			opacity : 0
		}, "fast");
		if (!/^\//.test(url))
			url = "/" + url;
		$.each($(".lng a"), function() {
			this.href = this.href.replace(/(http:\/\/[^\/]+).+/, "$1") + url;
		});
		var items = url.split("/");
		$("#menu_cat li").removeClass('sel');
		if (items.length == 4) {
			$("#menu_cat li").removeClass('sel');
			$("#menu_cat a[href*=/" + items[2] + "/]").parent('li').addClass('sel');
		}
		try {
			pageTracker._trackPageview(url);
		} catch (e) {

		}
		$.get("/proc/navigation/load_content", {
			url : url
		}, function(d) {
			var $item;
			if (($item = $("#menu a[href=" + url + "]").find('img')).length > 0) {
				if (!$item.hasClass('here')) {
					$item.addClass('here').attr('src', $item.attr('src').replace('.jpg', "here.jpg"));
				}
			}
			$("#search_progress").hide();
			$("#page").stop().html(d).animate( {
				opacity : 1
			}, "fast");
			if ($("#doc_title").length && $("#doc_title").html())
				document.title = $("#doc_title").html();
			Main.scroll();
			Main.initTape();
			Catalog.LoadScroll();
			Main.aliveLinks();
			News.init();
			$("#imodel").val(Main.order);
			Main.blocked = false;
		});
	},

	scroll : function() {
		if ($(".innerPageContentText").length) {
			$(".innerPageContentText").jScrollPane( {
				showArrows : true,
				scrollbarWidth : 11,
				scrollbarMargin : 30
			});
			$(".jScrollPaneTrack").css( {
				width : "2px",
				right : "5px"
			});
			$(".jScrollPaneDrag").css( {
				width : "2px"
			});
		}
		if($('.dd_scroll').length) {
			/*$('.dd_scroll').jScrollPane( {
//				showArrows : true,
				scrollbarWidth : 11,
				scrollbarMargin : 15,
				topCapHeight : 10
			});*/
			$(".jScrollPaneTrack").css( {
				width : "2px",
				right : "5px"
			});
			$(".jScrollPaneDrag").css( {
				width : "2px"
			});
			$('#filter').click(function(){
				$('.dd').toggle();
			});
			$('.dd .m').click(function(){
				$('#filter').html($(this).html());
				$('.dd').toggle();
				var rel = $(this).attr('rel').split('_');
				$('#m').val(rel[0]);
				$('#y').val(rel[1]);
				$('#p').val(1);
				$('#pub_nav').submit();
			});
			$('.dd').css({left:'0px'}).hide();
		}
	},

	initTape : function() {
		init_tape();
		$("#areaDown, #arrDown").mouseover(function() {
			tape_timer = setInterval("move_tape_up()", $.browser.mozilla ? 25 : 10);
		}).mouseout(function() {
			clearInterval(tape_timer);
		});
		$("#bgphotos").mouseover(function() {
			clearTimeout(Hint.tm);
		}).mouseout(function() {
			Hint.hide();
		});
		$("#areaUp, #arrUp").mouseover(function() {
			tape_timer = setInterval("move_tape_down()", $.browser.mozilla ? 25 : 10);
		}).mouseout(function() {
			clearInterval(tape_timer);
		});
		Catalog.initTape();
		$("#tape_cont").bind('mousewheel', function(event, delta) {
			if (delta > 0) {
				move_tape_down(3);
			} else {
				move_tape_up(3);
			}
			return false;
		});
		$("#c_title_img_a").fancybox( {
			'hideOnContentClick' : true,
			'zoomSpeedIn' : 600,
			'overlayOpacity' : 0.6,
			'overlayColor' : '#adadad',
			'zoomSpeedOut' : 500,
			'enableEscapeButton' : true,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack',
			'padding' : 0,
			'frameWidth' : 985,
			'frameHeight' : 529
		});

		$("#cat_layer").click(function() {
			$("#c_title_img_a").click();
		});
		return false;
	},

	aliveLinks : function() {
		$(".innerPageContentText a, #dtext a").click(function() {
			if (this.rel == 'cat') {
				Main.order = this.title;
				// debugger;
				$("#menu td a[href*=" + this.pathname + "] img").click();
				return false;
			}
			if(this.rel != 'no-ajax') {
				Main.navigate(this.pathname);
				return false;
			}
			return true;
		});
		$('a.fancy').unbind('click').fancybox({
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	600, 
			'speedOut'		:	200, 
			'overlayShow'	:	false,
			'scrolling'		:	'no'
		});
	},

	search : function() {
		$("#search_progress").show();
		var q = $("#search_txt").val();
		Main.navigate("/search.html?q=" + q);
		return false;
	}
};

var $ul = null;
var ul_h = null;
var ul_top = 0;
var tape_timer = null;
var ul_count = 0;
var ul_item_height = 0;

function init_tape() {
	$ul = $("#tape_cont ul");
	ul_h = $ul.height() - $("#tape_cont").height() - 23;
	ul_count = $("#tape_cont ul li").length;
	ul_item_height = $("#tape_cont ul li:first").height();
	ul_top = 0;
}
function move_tape_up(n) {
	if (!n)
		n = 1;
	if (ul_count < 3)
		return;
	if (Math.abs(parseInt($ul.css("top"))) < ul_h) {
		ul_top -= 4 * n;
		$ul.css( {
			top : ul_top + "px"
		});
		return;
	}

}
function move_tape_down(n) {
	if (!n)
		n = 1;
	if (parseInt($ul.css("top")) < 0) {
		ul_top += 4 * n;
		$ul.css( {
			top : ul_top + "px"
		});
		return;
	}
	$ul.css( {
		"top" : 0
	});
}

var Menu = {
	highlight : function(el) {
		if (el.className == "here")
			return;
		Menu.downlight();
		el.className = "here";
		el.src = el.src.replace(".jpg", "here.jpg");
		document.getElementById("b_" + el.id.replace("t_", "")).className = "here";
	},

	downlight : function() {
		$.each($("#menu img.here"), function() {
			this.src = this.src.replace("here.jpg", ".jpg");
			this.className = "";
		});
		$.each($(".menu_bottom a.here"), function() {
			this.className = "";
		});
	}
};

var Catalog = {
	initCatalogMenu : function() {
		$("#menu_cat li a img").mouseover(function() {
			$(this).parents('li').addClass('here');
		}).mouseout(function() {
			$(this).parents('li').removeClass('here');
		}).parent('a').click(function() {
			return true;
			$('#menu_cat li').removeClass('sel');
			$(this).parent('li').addClass('sel');
			Main.navigate(this.pathname);
			return false;
		});
	},

	initTape : function() {
		if ($("#cat_layer").length) {
			$("#cat_layer").mouseover(function() {
				Hint.show();
			}).mouseout(function() {
				Hint.hide();
			});
			$("#c_open").click(function() {
				Hint.show_internal();
			});
			$("#c_close").click(function() {
				Hint.show_internal();
			});

			Menu.downlight();
			Hint.add_events();
			$("#btnDescr img").click(function() {
				$("#descr").toggleClass('hide');
			});
			document.title = $("#tape_cont li.here .meta_title:first").text();
			if (!$("#tape_cont li:first").hasClass('here'))
				Catalog.skipNext(-1);
		}

		$(".tape .item a").click(function() {
			$("#c_images").empty();
			$this = $(this);
			if ($this.parent(".item").hasClass('here'))
				return false;
			$(".lng a").attr("pathname", this.pathname);
			$(".tape .item").removeClass('here');
			$this.parent(".item").addClass('here');
			var imgs = this.rel.split("|");
			Catalog.LoadDescription(this.id.replace("item", ""));
			Catalog.LoadMainImage(this.id.replace('item', ''));
			Catalog.HideText();
			$("#bgphotos .photo").removeClass('here').eq(0).addClass('here');
			$("#c_img_title").attr("src", $("#c_img_title").attr("src").replace(/\?.+/, "") + "?t=" + $(this).find("span").text().replace(/\ /g, "%20"));
			document.title = $(this).find("div.meta_title").html();
			// Hint.init($this);
				return false;
			});
		$("#next").click(function() {
			if (Main.blocked)
				return;
			Main.blocked = true;
			var id = parseInt($("#tape_cont li.here:first").attr('id').replace("li", ""));
			id++;
			var $li;
			if (($li = $("#tape_cont #li" + id)).length) {
				Catalog.skipNext();
				$li.find("a").click();
			}
		});
		$("#prev").click(function() {
			var id = parseInt($("#tape_cont li.here:first").attr('id').replace("li", ""));
			id--;
			var $li;
			if (($li = $("#tape_cont #li" + id)).length) {
				Catalog.skipPrev(id);

				$li.find("a").click();
			}
		});
	},

	skipNext : function(n) {
		n = n ? n : 0;
		var top = parseInt($("#tape_cont ul").css("top"));
		var id = parseInt($("#tape_cont ul li.here").attr("id").replace("li", ""));
		ul_top = -((ul_item_height + 24) * (id + n) + 10);
		if (ul_h < Math.abs(ul_top))
			ul_top = -ul_h;
		if (ul_top > 0)
			ul_top = 0;

		$("#tape_cont ul").animate( {
			top : ul_top
		}, "slow", function() {
			Main.blocked = false;
		});
	},

	skipPrev : function(id) {
		var top = parseInt($("#tape_cont ul").css("top"));
		ul_top = -((ul_item_height + 24) * (id - 1) + 10);
		if (ul_h < Math.abs(ul_top))
			ul_top = -ul_h;
		if (ul_top > 0 || id == 0)
			ul_top = 0;
		$("#tape_cont ul").animate( {
			top : ul_top
		}, "slow");
	},

	LoadMainImage : function(id, fromTape) {
		$("#c_img_title").css( {
			display : "none"
		});
		$("#prev").css( {
			display : $("#li0").hasClass('here') ? "none" : "block"
		});
		$("#next").css( {
			display : $("#tape_cont li:last").hasClass('here') ? "none" : "block"
		});
		var img = new Image();
		img.onload = function() {
			var src = this.src;
			$("#logoBW, #loading").stop().animate( {
				opacity : 0
			}, "slow", function() {
				$(this).css( {
					display : "none"
				});
				$("#c_title_img").css( {
					opacity : 0
				}).attr("src", src).load(function() {
					$(this).stop().animate( {
						opacity : 1
					}, "fast");
					Main.blocked = false;
				});
				$("#c_img_title").css( {
					visibility : "visible"
				});
			});
		};
		$("#c_title_img").animate( {
			opacity : 0
		}, "fast", function() {
			$("#logoBW, #loading").css( {
				opacity : 0,
				display : "block"
			}).animate( {
				opacity : 1
			}, "fast");
		});
		if ($("#c_images .here").length)
			var no = $("#c_images .here").find("img").attr('id').replace('cimg', '');
		else
			var no = 1;
		var c_title_img = $id('c_title_img');
		if (!$("#c_title_img").attr('rel')) {
			img.src = "/i/catitem_" + no + "_" + id + ".jpg";
		} else {
			img.src = $("#c_title_img").attr('rel');
			$("#c_title_img").attr('rel', '');
		}
		document.getElementById('c_title_img_a').href = "/i/catitem_big_" + no + "_" + id + ".jpg";
		$("#c_img_title").css( {
			visibility : "hidden"
		});
	},

	LoadDescription : function(id) {
		$.pget("/proc/navigation/get_item_description", {
			id : id
		}, function(d) {
			$("#descr_text").html(d);
			Catalog.LoadScroll();
			Main.aliveLinks();
		});
		$.pget("/proc/navigation/load_item_images", {
			id : id
		}, function(d) {
			$("#c_images").html(d);
			$("#bgphotos").width(95 * $("#bgphotos .photo").length + 40);
			Hint.add_events();
		});
	},

	LoadScroll : function() {
		if ($("#dtext").length) {
			$("#dtext").jScrollPane( {
				showArrows : true,
				scrollbarWidth : 11,
				scrollbarMargin : 15,
				topCapHeight : 10
			});
			$(".jScrollPaneTrack").css( {
				width : "2px",
				right : "5px"
			});
			$(".jScrollPaneDrag").css( {
				width : "2px"
			});
			$("#dtext").css( {
				top : 0
			});

		}
	},

	HideText : function() {
		$("#descr").addClass("hide");
	}
};

var Hint = {
	tm : null,
	blocked : false,
	add_events : function() {
		$("#bgphotos .photo").click(function() {
			if ($(this).hasClass('here'))
				return;
			$("#bgphotos .photo").removeClass('here');
			$(this).addClass('here');
			var no = $(this).find("img").attr('id').replace('cimg', '');
			// debugger;
				Catalog.LoadMainImage($("#tape_cont .here a").attr("id").replace('item', ''));
				Hint.blocked = true;
				Hint.hide_internal();
			});
	},
	init : function(el) {
		if (!el)
			el = $("#tape_cont li:first a");
		var imgs = $(el).attr('rel').split('|');
		var base_url = $("#bgphotos .photo:eq(0) img").attr("src").replace(/[^\/]+\.png/, "");
		for (i = 0; i < imgs.length; i++) {
			$("#bgphotos .photo:eq(" + i + ") img").attr("src", base_url + imgs[i]).load(function() {
				fixPNG(this);
			});
		}
	},
	hide : function() {
		clearTimeout(Hint.tm);
		Hint.tm = setTimeout("Hint.hide_internal()", 300);
	},

	show : function() {
		if (!$("#bgphotos .photo").length)
			return;
		if (Hint.blocked)
			return;
		clearTimeout(Hint.tm);
		Hint.tm = setTimeout("Hint.show_internal()", 300);
	},

	hide_internal : function() {
		$("#bgphotos").css( {
			display : "none"
		});
		setTimeout("Hint.blocked=false;", 400);
	},

	show_internal : function() {
		Catalog.HideText();
		$("#bgphotos").css( {
			display : "block"
		});
	}
};

var Show = {
	timer : null,
	cnt : 7,
	_curr : 0,
	done : 0,
	lang : _lang,
	time : (new Date()).getTime(),

	run : function() {
		Show.slide_in();
	},

	slide_in : function() {
		Show._curr = (Show._curr % Show.cnt) + 1;
		var image = new Image();
		image.onload = function() {
			Show.done++;

			Show.slide_move();
		};
		image.src = "/i/show/" + Show.lang + "/" + Show._curr + ".jpg?" + Show.time;

		var label = new Image();
		label.onload = function() {
			Show.done++;
			Show.slide_move();
		};
		label.src = "/i/show/" + Show.lang + "/" + Show._curr + "_label.gif?" + Show.time;
	},

	slide_move : function() {
		if (Show.done == 2 && $(".show").length) {
			$(".show").empty().createAppend('img', {
				src : "/i/show/" + Show.lang + "/" + Show._curr + ".jpg?" + Show.time
			}).addClass('i').animate( {
				left : 0
			}, "slow", function() {
				Show.timer = setTimeout(Show.slide_out, 4000);
			});

			$(".show").createAppend('img', {
				src : "/i/show/" + Show.lang + "/" + Show._curr + "_label.gif?" + Show.time
			}).addClass('l').animate( {
				right : 36
			}, "slow");
		}
	},

	slide_out : function() {
		$(".show img.i").animate( {
			left : -450
		}, "slow", function() {
			Show.timer = setTimeout(Show.slide_in, 1000);
			Show.done = 0;
		});
		$(".show img.l").animate( {
			right : 1100
		}, "slow");
	},

	stop : function() {
		clearTimeout(Show.timer);
	}
};

var News = {
	tm_move : null,
	leftX : 0,
	maxLeft : 0,
	mask : null,

	init : function() {
		$("#arrLeft, #arrRight").css( {
			display : $("#mask .item").length == 4 ? "none" : "block"
		});
		News.mask = document.getElementById('mask');
		News.maxLeft = -($("#mask .item").length * 184 - 735);
		$("#arrLeft").mouseover(function() {
			News.right();
		}).mouseout(function() {
			clearTimeout(News.tm_move);
		});

		$("#arrRight").mouseover(function() {
			News.left();
		}).mouseout(function() {
			clearTimeout(News.tm_move);
		});
	},

	left : function() {
		News.tm_move = setInterval(News.left_internal, 25);
	},

	left_internal : function() {
		var left = parseInt(News.mask.style.left);
		left -= 4;
		if (left > News.maxLeft) {
			News.mask.style.left = left + "px";
		} else {
			News.mask.style.left = News.maxLeft + "px";
			clearTimeout(News.tm_move);
		}
	},

	right : function() {
		News.tm_move = setInterval(News.right_internal, 25);
	},

	right_internal : function() {
		var left = parseInt(News.mask.style.left);
		left += 4;
		if (left <= 0) {
			News.mask.style.left = left + "px";
		} else {
			News.mask.style.left = "0px";
			clearTimeout(News.tm_move);
		}
	}
};

$(window).resize(function() {
	$("#site").css( {
		top : (($(document).height() - $("#site").height()) / 2) + "px"
	});
});

jQuery.extend( {
	pget : function(url, params, callback) {
		var p = typeof (params) == "object" ? params : null;
		var cb = typeof (params) == "function" ? params : (typeof (callback) == "function" ? callback : null);
		$.get(url, p, function(data) {
			// TODO :data = _global_message_process(data);
				if (typeof (cb) == "function")
					cb(data);
			});
	},
	ppost : function(url, params, callback) {
		var p = typeof (params) == "object" ? params : null;
		var cb = typeof (params) == "function" ? params : (typeof (callback) == "function" ? callback : null);
		$.post(url, p, function(data) {
			// TODO :data = _global_message_process(data);
				if (typeof (cb) == "function")
					cb(data);
			});
	}
});

var Form = {
	contact_submit : function() {
		var name = $(".feedback form input:eq(0)").val();
		var email = $(".feedback form input:eq(1)").val();
		var phone = $(".feedback form input:eq(2)").val();
		var message = $(".feedback form textarea:eq(0)").val();
		set_cookie('sform', 'js-ok', '', '/');
		$.ppost("/proc/submit/contact_submit", {
			name : name,
			email : email,
			phone : phone,
			message : message
		}, function(d) {
			if (d.length > 100)
				$('.feedback').html(d);
			else
				$('.msg').html(d);
		});
	},
	query_submit : function() {
		var name = $(".feedback form input:eq(0)").val();
		var email = $(".feedback form input:eq(1)").val();
		var phone = $(".feedback form input:eq(2)").val();
		var model = $(".feedback form input:eq(3)").val();
		var message = $(".feedback form textarea:eq(0)").val();
		set_cookie('sform', 'js-ok', '', '/');
		$.ppost("/proc/submit/query_submit", {
			name : name,
			email : email,
			phone : phone,
			model : model,
			message : message
		}, function(d) {
			if (d.length > 100)
				$('.feedback').html(d);
			else
				$('.msg').html(d);
		});
	},
	subscribe_submit : function() {
		var email = $("form input:eq(0)").val();
		set_cookie('sform', 'js-ok', '', '/');
		$.ppost("/proc/submit/subscribe_submit", {
			email : email
		}, function(d) {
			if (/OK$/.test(d)) {
				Main.navigate("/proc/navigation/activate_ok");
			} else {
				alert(d);
			}
		});
	}
};

function $id(id) {
	return document.getElementById(id);
}

function fixPNG(element) {
	// IE 5.5-6
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
		var src;

		if (element.tagName == 'IMG') {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = "/i/pix.gif";
			} else {
				src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
				if (src) {
					src = src[1];
					element.runtimeStyle.backgroundImage = "none";
				}
			}
		} else {
			src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = "none";
			}
		}
		if (src)
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	}
};

function set_cookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	 * if the expires variable is set, make the correct expires time, the
	 * current script below will set it for x number of days, to make it for
	 * hours, delete * 24, for minutes, delete * 60 * 24
	 */
	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 : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

String.prototype.isEmail = function() {
	return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this);
};

__show_num = 1;
(function($) {
	$.fn.adsRotate = function(options) {
		var defaults = {
			params : {
				width : 380,
				height : 300
			}
		};
		var opts = $.extend(defaults, options);
		try{
			loadImage(this, opts);
		} catch(e) {}
	};

	function loadImage(obj, opts) {
		var img = new Image();
		img.onload = function() {
			if(obj.length == 0) return;
			$(obj).createAppend('img', {
				src : src,
				width : opts.params.width,
				height : opts.params.height,
				style : "display:none;position:absolute;left:0px;cursor:pointer" 
			}).click(function(){
				try{pageTracker._trackPageview('/outgoing/iwa_'+_lang);}catch(e){}
				document.location= _promo;
				}
			).animate( {
				opacity : 0
			}, 1, function() {
				$(this).css( {
					display : "block"
				});
				$(this).animate( {
					opacity : 1
				}, 1000, function() {
					__show_num++;
					if ($("img", $(obj)).length > 1)
						$("img:first", $(obj)).remove();
					setTimeout("fuckAds()", 3000);
				});
			});
		};
		src = img.src = "/i/show_fade/loader.php?lang=" + _lang + '&i=' + __show_num;
	}
})(jQuery);

function fuckAds() {
	$("#show").adsRotate();
}

