function showTooltip(title, authors, price) {
	$(".main > a").mouseover(function() {
		createTooltip($(this), title, authors, price);
	});
	
	$(".main > a").mouseout(function() {
		$(".tooltip").remove();
	});

	$("#shelfTwo div:not(.previewBottomParts) > a").mouseover(function() {
		createTooltip($(this), title, authors, price);
	});
	
	$("#shelfTwo div:not(.previewBottomParts) > a").mouseout(function() {
		$(".tooltip").remove();
	});
	
	$("#imagesHolder > a").mouseover(function() {
		createTooltip($(this), title, authors, price);
	});
	
	$("#imagesHolder > a").mouseout(function() {
		$(".tooltip").remove();
	});
	
	$("#recommendation > a").mouseover(function() {
		createTooltip($(this), title, authors, price);
	});
	
	$("#recommendation > a").mouseout(function() {
		$(".tooltip").remove();
	});
}

function createTooltip(object, title, authors, price) {
	$(".tooltip").remove();

	var tipType = "rightTip";
	var fontAuthors = "12px";
	var indent = 45;
	var topIndent = 0;
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		indent = 15;
		var topIndent = 130;
	} else if (navigator.appName == "Opera") {
		var topIndent = 130;
	}

	var topPosition = object.position().top - 140 + topIndent;
	var leftPosition = parseInt(object.position().left +
								object.width() - indent);
	
	if (parseInt(leftPosition + object.width()) > 950) {
		leftPosition = leftPosition - object.width() - (indent * 2);
		
		if (navigator.appName == "Microsoft Internet Explorer") {
			leftPosition = leftPosition - object.width() - (indent * 2);
		}
		
		tipType = "leftTip";
	}
	
	if (parseInt(leftPosition - object.width()) < 900 &&
		parseInt(leftPosition - object.width()) > 700) {
		leftPosition = leftPosition + object.width() + (indent * 2);
		
		if (navigator.appName == "Microsoft Internet Explorer") {
			leftPosition = leftPosition + object.width() + (indent * 2);
		}
		
		tipType = "rightTip";
	}
	
	var font = detectFontSize(title, 32);
	
	if (authors.length > 17) {
		authors = authors.substring(0, 17) + "...";
		fontAuthors = "11px";
	}
	
	object.after('<div class="tooltip ' + tipType + ' png"' +
				  'style="left: ' + leftPosition + 'px; top: ' + topPosition +
				  'px;">' + '<div id="title" style="font-size: ' + font +
				  '">' + title + '</div>' +
				  '<div style="font-size: ' + fontAuthors + '">' +
				  authors + '</div>' +
				  '<div id="price"><span id="sign">Цена:</span> ' +
				  '<span id="numbers">' + price +
				  '</span> руб</div></div>');
}

function detectFontSize(title, maxLength) {
	var stringLength = Math.round(title.length/2);
	var font = "12";
	
	if (parseInt(145/stringLength) > font) {
		font = font + 'px';
	} else if (parseInt(145/stringLength) < 11) {
		font = '11px';
	} else {
		font = parseInt(145/stringLength) + 'px';
	}
	
	return font;
}

function start_search() {
	$('#searchIndicator').show();
	
	setTimeout('change_search_string()', 300);
}

var str = 1;

function change_search_string() {
	var points = "";
  
	for (var i = 0; i < str; i++) points = points + ".";
	for (var i = str; i < 7; i++) points = points + " ";
	
	str++;
	
	if (str == 8) str = 1;
	
	$('#searchIndicator').html("Идет поиск" + points);
	
	setTimeout('change_search_string()', 400);
}

function setHomePage() {
	document.body.style.behavior = 'url(#default#homepage)';
	document.body.setHomePage("http://www.kniga.ru");
}

function buy(id) {
	var link = '<p><a href="/personal/cart/">Перейти в корзину</a></p>';
	
	$.getJSON("/buy.php", "action=BUY&ID=" + id, function(response) {
		$("#in_basket_" + id)
			.attr("src", "/images/common/button_already_in_basket.gif")
			.attr("width", "152")
			.attr("alt", "Товар добавлен в вашу корзину")
			.attr("title", "Товар добавлен в вашу корзину")
			.parent("a")
			.attr("onclick", "return false;")
			.after(link);
		
		$('#basketInfo > span').html(response.basket_total);
	});
}

function showWarning(width, height) {
    var screenWidth = document.body.clientWidth;
    var leftMargin = screenWidth/2 - width/2 - 10;
    var rightMargin = leftMargin;

    $("#overlay")
        .css({"display": "block",
			  "min-width": leftMargin + 20 + width + "px",
			  "filter": "alpha(opacity=50)"})
        .fadeIn();

    $("#warningContainer")
        .css({"left": leftMargin + "px",
              "right": rightMargin + "px",
              "width": width + "px"})
        .slideDown();
}

function closeWarning() {
    $("#overlay").css("display", "none").fadeOut();
    $("#warningContainer").hide();
}

function setWarningCookie(cookieName, value, expireDays) {
	var exdate = new Date();

	exdate.setDate(exdate.getDate() + expireDays);
	document.cookie = cookieName + "=" + escape(value) +
		((expireDays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getWarningCookie(cookieName) {
	if (document.cookie.length > 0) {
		cookieStart = document.cookie.indexOf(cookieName + "=");
		
		if (cookieStart != -1) {
			cookieStart = cookieStart + cookieName.length + 1;
			cookieEnd = document.cookie.indexOf(";", cookieStart);
			
			if (cookieEnd == -1)
				cookieEnd = document.cookie.length;
			
			return unescape(document.cookie.substring(cookieStart, cookieEnd));
		}
	}
	
	return "";
}

// Competitions functions - start
function sendCompetition() {
	$("#error").empty();
	$("#submitButton").attr("disabled", "disabled").val("Обрабатываю...");
	
	var name = $("#names").val();
	var age = $("#age").val();
	var city = $("#city").val();
	var email = $("#email").val();
	var agreeCheckBox = $("#agreeCheckBox").attr("checked");
	var favoriteColor = $("input[name='favoriteColor']:checked").val();
	var fan = $("input[name='fan']:checked").val();
	var gothicName = $("input[name='gothicName']:checked").val();
	var dressColor = $("input[name='dressColor']:checked").val();
	var favorite = $("input[name='favorite']:checked").val();
	var numberInFamily = $("input[name='numberInFamily']:checked").val();
	var secondName = $("input[name='secondName']:checked").val();
	var language = $("input[name='language']:checked").val();
	var youngerDaughter = $("input[name='youngerDaughter']:checked").val();
	var fathersJob = $("input[name='fathersJob']:checked").val();
	var story = $("#story").val();

	$.post("/competitions/daughters/reply/",
		   {names: name,
			age: age,
			city: city,
			email: email,
			agreeCheckBox: agreeCheckBox,
			favoriteColor: favoriteColor,
			fan: fan,
			gothicName: gothicName,
			dressColor: dressColor,
			favorite: favorite,
			numberInFamily: numberInFamily,
			secondName: secondName,
			language: language,
			youngerDaughter: youngerDaughter,
			fathersJob: fathersJob,
			story: story
		   },
		   function(response) {
			   if (response.substring(0, 2) == "OK") {
				   $("#competitionBody")
				   	.fadeOut()
					.html('<div id="success">' +
						  '<p>Спасибо за участие в конкурсе.</p>' +
						  'Ваши ответы будут переданы в издательство ' +
						  '"Росмэн" и, возможно, именно вы станете счастливым' +
						  ' обладателем мишки Бублика. Но это еще не все! ' +
						  'Ваш номер участника <strong>' + response.substring(3) +
						  '</strong>, а это значит, ' +
						  'что вы можете получить <strong>3%</strong> единоразовую скидку ' +
						  'на покупку в нашем интернем-магазине. ' +
						  'Для этого вам необходимо указать этот номер в ' +
						  'поле "Комментарий" при оформлении заказа.<br /><br />' +
						  '<strong>Внимание! Скидка является единоразовой и ' +
						  'распространяется только на один заказ.</strong></div>')
					.fadeIn("slow");
			   } else {
				   $("#error")
				   .html('<div id="errorDescription">' +
						 '<p>В ходе проверки формы были найдены ' +
						 'следующие ошибки:</p>' + response + '</div>')
				   .focus();
			   }
			   
			   $("#submitButton").removeAttr("disabled").val("Отправить");
	}, "json");
}
// Competitions functions - end

// Boom cards functions - start
function sendBoomCard() {
	$("#error").empty();
	//$("#submitButton").attr("disabled", "disabled").val("Обрабатываю...");

	var type = $("select[name='type']").val();
	var quantity = $("input[name=quantity]").val();
	var pack = $("input[name=pack]:checked").val();
	var agreeCheckBox = $("#agreeCheckBox").attr("checked");
	var name = $("input[name=names]").val();
	var telephone = $("input[name=telephone]").val();
	var email = $("input[name=email]").val();
	var city = $("input[name=city]").val();
	var street = $("input[name=street]").val();
	var house = $("input[name=house]").val();
	var flat = $("input[name=flat]").val();
	var price = $("select[name='price']").val();
	var totalPrice = $("#summaryPrice").html();
	var comment = $("#comment").val();

	$.post("/boom_cards/order/reply/",
		   {
			type: type,
			quantity: quantity,
			pack: pack,
			agree_box: agreeCheckBox,
			names: name,
			telephone: telephone,
			email: email,
			city: city,
			street: street,
			house: house,
			flat: flat,
			price: price,
			total_price: totalPrice,
			comment: comment
		   },
		   function(response) {
			   if (response == "OK") {
				   $("#contentColumn")
				   	.fadeOut()
					.html('<div id="success">' +
						  '<p>Спасибо за ваш заказ.</p>' +
						  '<p>В ближайшее время с вами свяжется наш оператор ' +
						  'для уточнения адреса и времени доставки.</p></div>')
					.fadeIn("slow");
			   } else {
				   $("#error")
				   .html('<div id="errorDescription">' +
						 '<p>В ходе проверки формы были найдены ' +
						 'следующие ошибки:</p>' + response + '</div>')
				   .focus();
			   }
			   
			   //$("#submitButton").removeAttr("disabled").val("Отправить");
	}, "json");
}
// Boom cards functions - end

function calculatePrice() {
	$("#deliveryPrice").empty();
	
	var quantity = new Number($("input[name=quantity]").val()).toFixed();
	
	if (isNaN(quantity.valueOf()) || quantity.valueOf() < 0) {
		var quantity = new Number(1);
	}
	
	var summaryPrice = parseInt($("select[name=price]").val()) * quantity;
	
	if (summaryPrice < 3000) {
		$("#deliveryPrice").html("Cтоимость доставки: 130 руб.");
		
		summaryPrice += 130;
	}
	
	if ($("input[name=pack]:checked").val() == "gift") {
		summaryPrice += 170;
	}	
	
	$("#summaryPrice").html(summaryPrice + " руб.");
}
// Boom cards functions - end

// Dteatr functions - start
function sendDteatr() {
	$("#error").empty();
	//$("#submitButton").attr("disabled", "disabled").val("Обрабатываю...");

	var quantity = $("input[name=quantity]").val();
	var agreeCheckBox = $("#agreeCheckBox").attr("checked");
	var name = $("input[name=names]").val();
	var telephone = $("input[name=telephone]").val();
	var email = $("input[name=email]").val();
	var city = $("input[name=city]").val();
	var street = $("input[name=street]").val();
	var house = $("input[name=house]").val();
	var flat = $("input[name=flat]").val();
	var price = $("select[name='price']").val();
	var totalPrice = $("#summaryPrice").html();
	var comment = $("#comment").val();

	$.post("/dteatr/order/reply/",
		   {
			quantity: quantity,
			agree_box: agreeCheckBox,
			names: name,
			telephone: telephone,
			email: email,
			city: city,
			street: street,
			house: house,
			flat: flat,
			price: price,
			total_price: totalPrice,
			comment: comment
		   },
		   function(response) {
			   if (response == "OK") {
				   $("#contentColumn")
				   	.fadeOut()
					.html('<div id="success">' +
						  '<p>Спасибо за ваш заказ.</p>' +
						  '<p>В ближайшее время с вами свяжется наш оператор ' +
						  'для уточнения адреса и времени доставки.</p></div>')
					.fadeIn("slow");
			   } else {
				   $("#error")
				   .html('<div id="errorDescription">' +
						 '<p>В ходе проверки формы были найдены ' +
						 'следующие ошибки:</p>' + response + '</div>')
				   .focus();
			   }
			   
			   //$("#submitButton").removeAttr("disabled").val("Отправить");
	}, "json");
}
// Dteatr functions - end


function initializeMainMenu() {
	$("#booksTab").hover(function() {
		$(this).css("background", "url(/images/menu/books_hover_menu_bg.png) no-repeat");
	}, function() {
		$(this).css("background", "none");
	}).click(function() { location.href = "/books/"; });

	$("#studybooksTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/studybooks_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/studybooks/"; });
	
	$("#childrenTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/children_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/children/"; });
	
	$("#softTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/soft_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/soft/"; });
	
	$("#gamesTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/games_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/games/"; });
	
	$("#videoTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/dvd_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/dvd/"; });
	
	$("#musicTab").hover(function() {
		$("#menuSelected").css("background", "url(/images/menu/music_hover_menu_bg.png) no-repeat");
	}, function() {
		$("#menuSelected").css("background", "none");
	}).click(function() { location.href = "/music/"; });
}

jQuery.preloadImages = function() {
	for (var i = 0; i < arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
};

$(document).ready(function() {
	$.preloadImages('/images/menu/books_hover_menu_bg.png',
              	    '/images/menu/children_hover_menu_bg.png',
                    '/images/menu/games_hover_menu_bg.png',
                    '/images/menu/music_hover_menu_bg.png',
                    '/images/menu/soft_hover_menu_bg.png',
	                '/images/menu/studybooks_hover_menu_bg.png',
	                '/images/menu/dvd_hover_menu_bg.png',
	                '/images/index/authors_hover_menu_bg.jpg',
	                '/images/index/events_hover_menu_bg.jpg',
	                '/images/index/new_hover_menu_bg.jpg',
	                '/images/index/soon_hover_menu_bg.jpg');
    
	initializeMainMenu();

	$("#searchTip span").click(function() {
		$("#searchString").val($(this).text());
	});
	
	$("#memberArea").click(function() {
		toggle_private();
		
		return false;
	});

	$('#privateContainer').hide();
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		$("#homePage").html('<a href="#" onclick="setHomePage();">' +
							'Сделать стартовой страницей</a>' +
							'<span>&bull;</span>');
	}
	
	$("#showMore").toggle(function() {
		$(this).text("Свернуть");
        $("#moreInfo").slideDown();
    }, function() {
		$(this).text("Далее");
        $("#moreInfo").slideUp();
    });
});