var elements = new Array();

var card_el=null;

$(document).ready(function(){

	$(".catalog-prew a:first-child img").css("visibility", "hidden");

	$(".catalog-prew a:first-child img").each(function(e) {
		if (this.complete) {
			$(this).css("top", (134-$(this).attr("height"))/2);
			$(this).css("visibility", "visible");
		} else {
			$(this).bind("load", function(e) {
				var el=$(e.target);
				$(el).css("top", (134-$(el).attr("height"))/2);
				$(el).css("visibility", "visible");
				$(el).unbind("load");
			});
		}
	});

	$(".catalog-prew a").bind("click", function(){
		open_1($(this));
		return false;
	});

	$(".wind").bind("click", function(){
		open_1($(this).parent().children().eq(0).children());
		return false;
	});

	$("a.spec").bind("mouseover", function(){
		$(this).parent().append($("<span class='title'>Товары со скидкой</span>"));
	});

	$("a.spec").bind("mouseout", function(){
		$("span.title").remove();
	});

	var i = 0;
	$(".catalog-prew").each(function() {
		elements[i] = $(this).children();	
		i++;
	});

	$(".ent a").bind("click", function(){
		op_pop($(this));
		return false;
	});

});

function nextprev ($el) {
		var i = 0;
		
		for (i = 0; i < elements.length; i++ ) {
			if 	($el.attr("href") == elements[i].attr("href")){
				if (i == 0) return {prev:'none', next: elements[i+1]};
				if (i == elements.length-1) return {prev: elements[i-1], next:'none'};
				return {prev: elements[i-1], next: elements[i+1]};
			}
		}
}

function op_pop($el){
	var code, width, width_img, height, height_img, rejim, simv = 0, simvol = 0;

	if ($("div.backgroundDiv").length == 0) _build();
	else _show(100, 100, 0);

	var url = $el.attr("href");

	var res = $.ajax({
		url: url,
		success: function (res) {
			code = res.substring(res.indexOf('<body>') + 6, res.indexOf('</body>'));
			$("#info").html(code);
			if (url.indexOf("registration") == '-1') {
				width = 320;
				height = 160;
			}
			else {
				width = 420;
				height = 420;
			}
			window.setTimeout( function(){
				_show(width, height, 1);
				naves(0, 0, 'none', 'none');
			}, 1000);
		}
	});
}

function open_1($el, click_price) {
	card_el=$el;
	var type = get_type($el);
	
	var np = nextprev($el);
	$prev = np['prev'];
	$next = np['next'];
	
	var code, width, width_img, height, height_img, rejim, simv = 0, simvol = 0;

	if ($("div.backgroundDiv").length == 0) _build();
	else _show(100, 100, 0);			
	
	if (type == 'page'){
		var url = $el.attr("href");
		var res = $.ajax({
			url: url,
			success: function (res) {
				code = res.substring(res.indexOf('<body>') + 6, res.indexOf('</body>'));
				$("#info").html(code);
				width_img = parseInt($("#iwidth").html());
				height_img = parseInt($("#iheight").html());

				$("td.cart_cost").each(function (){
					if (simvol < $(this).text().length) simvol = $(this).text().length;
				});
				if ($("td.cart_cost br").length) simvol=simvol/2+3;
				// UPDATED by is on 26/01/10
				$("td.cart_cost").css("width", (simvol+2)*5);
				//$("td.cart_cost").css("width", (simvol+2)*6);

				if (height_img > width_img) {
					$("td.cart_name").each(function (){
						if (simv < $(this).text().length) simv = $(this).text().length;		
					});
					$('td.cart_name').css("width", 7.6*simv + 20);
					var table_width =  240 + 7.6*simv + 20 + (simvol+2)*6 - 60;
					width = width_img +  table_width +30;
					height = height_img + 40;
					$("div#info table").css("width", table_width);
					$("div#info table").css("margin-left", "10px");
					$("div.dopinfo").css("width", width - 20);
					$("div.dopinfo").css("margin-top", "-12px");
					$("div.dopinfo").css("float", "left");
					if(table_width < 512)$("div.pr_req").css("white-space","normal");
					$("div#left").css({'width' : width_img/2 + 10});
					$("div#right").css({'width' : width_img/2 + 10, 'left': width_img/2 + 10});

					//$("div.favorites_link").css("margin-left","10px");
				}
				else {
					width = width_img + 20;
					var niz = 0;
					if ($("div.price").length + $("div.favorites").length) niz = 1;
					height = height_img + $("tr").length*20 + 44 + 33*niz;
				}

				if (click_price) $(".pr_req a").trigger("click");
				// update 08.08.11
				var kd=$("#kd");
				if (kd.length) {
					var kdi=new Number(kd.text());
					if (!isNaN(kdi) && kdi>0) {
						//$("#th_cost").text($("#th_cost").text() + " (Диз.)");
						/*$("td.cart_cost").each(function(el) {
							var arr=$(this).text().split(" ");
							if (arr.length==2) {
								var v=new Number(arr[0]);
								if (!isNaN(v)) $(this).html($(this).html() + " <span style='white-space:nowrap'>(" + Math.ceil(v*kdi) + " &euro;)</span>");
							} else if (arr.length==4) {
								if (arr[1]=='x') {
									var v=new Number(arr[2]);
									var k=new Number(arr[0]);
									if (!isNaN(v)) $(this).html($(this).html() + " <span style='white-space:nowrap'>(" + k + " x " + Math.ceil(v*kdi) + " &euro;)</span>");
								}
							}
						});*/
						$("#th_cost").after("<th>Опт</th>");
						$("td.cart_cost").each(function(el) {
							var arr=$(this).text().split(" ");
							if (arr.length==2) {
								var v=new Number(arr[0]);
								if (!isNaN(v)) $(this).after("<td class='card_opt'>" + Math.ceil(v*kdi) + " &euro;</td>");
							} else if (arr.length==4) {
								if (arr[1]=='x') {
									var v=new Number(arr[2]);
									var k=new Number(arr[0]);
									if (!isNaN(v)) $(this).after("<td class='card_opt'>" + k + " x " + Math.ceil(v*kdi) + " &euro;</td>");
								}
							} else if (arr.length==3) {
								var v1=new Number(arr[0]);
								var re=new RegExp("[^0-9]", "igm");
								var v2=new Number(arr[1].replace(re, ""));
								if (!isNaN(v1) && !isNaN(v2)) $(this).after("<td class='card_opt'>" + Math.ceil(v1*kdi) + " &euro;&mdash;" + Math.ceil(v2*kdi) + " &euro;</td>");
							}
						});
					}
				}

				window.setTimeout( function(){
					_show(width, height, 1);
					naves(width_img, height_img, $next, $prev);
				}, 1000);
			}
		});
	}
		
	if (type == 'image'){
		
		imgPreloader = new Image();
		imgPreloader.src = $el.attr("href");
		imgPreloader.onload = function(){
			code = '<div class="margin"><div id="left"><a class="prev" href="#"><img src="img/prettyPhoto/left.gif"/></a></div><div id="right"><a class="next" href="#"><img id="right" src="img/prettyPhoto/right.gif"/></a></div><div class="clear"><div class="head">&nbsp;</div><a href="#" class="close"><img style="border: medium none ; float: right; margin-top: 3px;" src="img/prettyPhoto/btnClose.gif"/></a></div><img src="' + $el.attr("href") + '" id="main_img"/></div>';
			width = imgPreloader.width + 20;
			height_img = imgPreloader.height;
			height = imgPreloader.height + 40;
			$("#info").html(code);	
			window.setTimeout( function(){
				_show(width, height, 1);
				naves(width - 20, height_img, $next, $prev);
			}, 1000);
		}
	}
	
	return false;
};

function watermark(width, height) {
	var wat, lft;
	
	if (height > width){
		wat = 'watermark2';
		lft = width/2 - 129 + 10;
	}
	else{
		wat = 'watermark';
		lft = width/2 - 215 + 10;
	}

	if (lft < 10) lft = 10;
	
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
			$("img#main_img").after("<img id='watermark' style='position: absolute;' src='img/prettyPhoto/"+ wat + ".gif'/>");
	else 	$("img#main_img").after("<img id='watermark' style='position: absolute;' src='img/prettyPhoto/"+ wat + ".png'/>");

	$("img#watermark").css("left", lft).css("top", height/2 - 22);
}

function _show(width, height, rejim){

	var pos = _getCenterPos(width, height);
	
	if (!rejim) $("div.contentHolder #info").css("display", "none");
	else $("div.contentHolder .loaderIcon").css("display", "none");

	$('div.contentHolder').animate({
				'width': width,
				'height': height,
				'top': pos['top'],
				'left': pos['left']
			}, "normal", function(){
				if (rejim) $("div.contentHolder #info").fadeIn("normal", function(){
					var nm = 1;
					if ($("img#main_img").height() > $("img#main_img").width()) nm = 0;
					var h1 = parseInt($("div.table_div table").height())*nm + 41 +  $("img#main_img").height();
					if (h1 > height) {
						height = h1;
						pos = _getCenterPos(width, height);
						$('div.contentHolder').animate({
							'height': height,
							'top': pos['top']
						}, "normal");
					}
				});
				else $("div.contentHolder .loaderIcon").fadeIn("normal");
			});


	if (rejim) {
		window.setTimeout( function(){
			if ($("div.dopinfo").length) {
	
				height = height + $("div.dopinfo").height()*$("div.dopinfo").length + 15*$("div.dopinfo").length;
	
				pos = _getCenterPos(width, height);
			
				$('div.contentHolder').animate({
					'height': height,
					'top': pos['top']
				}, "normal", function(){
					$("div.dopinfo").css("display", "block");
				});
				
			}
		}, 1000);
	}

}

function get_type($el){
	if (($el.attr("href").indexOf('.jpg') != -1) || ($el.attr("href").indexOf('.gif') != -1)) return 'image';
	else return 'page';
}

function naves(width, height, $next, $prev){
	$('a.close').bind('click', function(){ close(); return false; });
	
	if ($prev == 'none'){
		$('div#left a').css("display", "none");
		$('div#left').css("height", height);
	}
	else $('div#left').css("height", height).mouseover (function(){ $('a.prev img').css("display", "inline");}).mouseout (function(){ $('a.prev img').css("display", "none");});

	if ($next == 'none'){
		$('div#right a').css("display", "none");
		$('div#right').css("height", height);
	}
	else $('div#right').css("height", height).mouseover (function(){ $('a.next img').css("display", "inline");}).mouseout (function(){ $('a.next img').css("display", "none");});
	
	$('a.prev').children().css("margin-top", height/2 - $('a.prev').children().height()/2);
	$('a.next').children().css("margin-top", height/2 - $('a.prev').children().height()/2);
	
	$('a.prev').bind('click', function(){
		open_1($prev);
		return false;
	});
	
	$('a.next').bind('click', function(){
		open_1($next);
		return false;
	});

	watermark(width, height);
}


function _build(){

	if($.browser.msie && $.browser.version == 6){
		$('select').css('visibility','hidden');
	};

	$("div.picture").css('visibility','hidden');

	backgroundDiv = "<div class='backgroundDiv'></div>";
	$('body').append(backgroundDiv);
	$('div.backgroundDiv').css('height',$(document).height());		
	contentHolder = '<div class="contentHolder"><div class="loaderIcon"></div><div id="info"></div></div>';
		
	$('body').append(contentHolder);

	$('.contentHolder').css({'opacity': 0});

	var pos = _getCenterPos($("div.contentHolder").width(), $("div.contentHolder").height());
	
	$('div.backgroundDiv').css('opacity',0).fadeTo('normal', 0.7, function(){
		$('div.contentHolder').css('opacity',0).fadeTo('normal', 1);
		$('div.contentHolder').css({left: pos['left'], top: pos['top']});	
	});


	window.setTimeout( function(){
		$('div.backgroundDiv').bind('click',function(){
			close();
		});
	}, 1000);

};
	
function close(){
	$('div.contentHolder, div.backgroundDiv').fadeOut('normal', function(){
			$('div.backgroundDiv').remove();
			$('div.contentHolder').remove();
			$("select").css("visibility", "visible");
			$("div.picture").css("visibility", "visible");
	});
	
};
		
function _getCenterPos(w, h){
	
		var scrollPos = _getScroll();
			
		if($.browser.opera) {
			windowHeight = window.innerHeight;
			windowWidth = window.innerWidth;
		}else{
			windowHeight = $(window).height();
			windowWidth = $(window).width();
		};
			
		projectedTop = (windowHeight/2) + scrollPos['scrollTop'] - h/2;
		if (projectedTop < 0) projectedTop = 25;
		projectedLeft = (windowWidth/2) + scrollPos['scrollLeft'] - w/2;
		
		return {top: projectedTop, left: projectedLeft};
};

$(window).resize(function(){ if($(".contentHolder").size() > 0) _reshow() });
$(window).scroll(function(){ if ($("div.contentHolder").height() < $(window).height()) _reshow(); });

$(document).keyup(function(e){
	switch(e.keyCode){
		case 27:
			close();
			break;
	};
});

function _reshow() {
	
	var pos = _getCenterPos($("div.contentHolder").width(), $("div.contentHolder").height());
	$("div.contentHolder").css("top", pos['top']).css("left", pos['left']);
	
}

function _getScroll(){
	scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
	return {scrollTop:scrollTop,scrollLeft:scrollLeft};
};
