/**
 * @requires js/libs/jQuery/plugins/jquery.fancybox.js
 * @requires js/modules/default/catalog/addComment.js
 * @requires js/modules/basket.js
 * @requires js/modules/loading.js
 * @requires js/modules/win.js
 * @requires js/modules/validate.js
 * @requires js/modules/preorder.js
 */

if (typeof(m) == "undefined" || !m) {
	var m = {};
}

(function($) {
	var preorderPopup,
		productId = null;

	m.default_catalog_product = {
		setup : function(iProductId, vkWishForm, haveSize) {
			productId = iProductId;

			__setupVK(vkWishForm, haveSize);
			YAHOO.util.Get.script('http://platform.twitter.com/widgets.js');
			YAHOO.util.Get.script('http://connect.facebook.net/en_US/all.js#xfbml=1');
			__setupGallery();

			this.setupComments();

			var checkSize = ($('#product_size').length) ? true : false;
			$('#add-to-basket').click(function(e) {
				e.preventDefault();

				m.basket.add(productId, checkSize);
			});

			preorderPopup = new m.win('preorder-popup');
			preorderPopup.setConfig({isModal : true});

			$('#make-preorder').click(function(e) {
				e.preventDefault();
				m.preorder.show(productId);
			});
		},

		setupComments : function() {
			$('#add-comment-link').click(function(e) {
				e.preventDefault();
				m.default_catalog_addComment.show();
			});
		}
	}

	function __setupVKWishButton(vkWishForm, haveSize)
	{
		YAHOO.util.Get.script("http://vkontakte.ru/js/api/merchant.js?13", {
			charset : 'windows-1251',
			onSuccess: function() {
				if (haveSize) {
					$('#product_size input').click(function(e) {
						if (this.checked) {
							m.loading.show();
							$.getJSON('/catalog/vkwishform/', {id:productId, size:this.value}, function(vkWishForm) {
								m.loading.hide();
								document.getElementById('vk-wish-wrapper').innerHTML = VK.Merchant.wishbutton(function() {
									return vkWishForm;
								});
							});
						}
					});
				} else {
					document.getElementById('vk-wish-wrapper').innerHTML = VK.Merchant.wishbutton(function() {
						return vkWishForm;
					});
				}
			}
		});
	}

	function __setupGallery()
	{
		$('#product-imgs a.gallery').fancybox({
			'titlePosition' : 'inside',
			'transitionIn' : 'none',
			'transitionOut' : 'none'
		});

		$('#product-imgs ul.thumb-list li').mouseover(__onThumbLiOver).mouseout(__onThumbLiOut);
	}

	function __setupVK(vkWishForm, haveSize)
	{
		$(document).bind('vk-inited', function() {
			VK.Widgets.Like("vk-like", {type: "button"});
			VK.Widgets.Comments("vk-comments", {limit: 20, width: "496", attach: "*"});

			__setupVKWishButton(vkWishForm, haveSize);
		});
	}

	function __onThumbLiOver()
	{
		$('#product-imgs ul.thumb-list li').removeClass('over');
		$(this).addClass('over');
	}

	function __onThumbLiOut()
	{
		$(this).removeClass('over');
	}
}) (jQuery);
