/**
 * Глобальные настройки ассинхронных запросов
 */
jQuery.ajaxSetup({
    cache: false,
	global: true
});


/**
 * Таймер
 * @method schedule	Планирует вызов функции
 * 					Если нет запланированных вызовов, то функция исполняется немедленно и
 * 					засекается интервал времени, в течение которого другие функции исполняться не будут.
 *					Если есть запланированный вызов, то он отменяется и планируется новый вызов функции.
 * @method cancel	Отменяет запланированный вызов
 */
(function () {
	ZINA.Timer = function () {};
	ZINA.Timer.prototype = {
		schedule: function (when, func, data, scope) {
			var me = this;
			scope = scope || window;
			if (!me.id) {
				// мгновенный вызов
				me.id = setTimeout(function () {
					delete me.id;
				}, when);
				func.apply(scope, data || []);
			} else {
				// отложенный вызов
				me.cancel();
				me.id = setTimeout(function () {
					func.apply(scope, data || []);
					delete me.id;
				}, when);
			}
		},
		cancel: function () {
			if (this.id) {
				clearTimeout(this.id);
				delete this.id;
			}
		}
	};
}());


/** отслеживаем изменение размеров **/
$(function () {
	$(window).resize(function () {
		var width = $(window).width(), cls = "size-normal";

		if (width < 1200) {
			cls = "size-narrow";
		} else if (width > 1400) {
			cls = "size-wide";
		}

		if (!$("body").hasClass(cls)) {
			$("body").removeClass("size-narrow size-normal size-wide").addClass(cls);
		}
	}).triggerHandler("resize");
});


/**
 * Global "please wait" indicator for AJAX-actions
 */
$(function () {

    function setPosition(evt) {
        var ele = document.getElementById("pleasewait");
        var x, y;

        if (ele && evt) {
            if (evt.pageX && evt.pageY) {
                x = evt.pageX;
                y = evt.pageY;
            } else {
                x = evt.clientX + (document.documentElement.scrollLeft ?
                                   document.documentElement.scrollLeft :
                                   document.body.scrollLeft);
                y = evt.clientY + (document.documentElement.scrollTop ?
                                   document.documentElement.scrollTop :
                                   document.body.scrollTop);
            }
			if (!isNaN(x) && !isNaN(y)) {
            	$(ele).css({'left': x + 15, 'top': y + 15});
			}
        }
    }

    $(document).bind('click.pleasewait', setPosition)
		.bind("ajaxStart", function () {
			// show "please wait" label
			var ele = document.getElementById("pleasewait");
			if (!ele) {
				ele = $('<div id="pleasewait" style="display: none; position: absolute; z-index: 1010;">' +
							'<img src="/static/images/busy.gif" style="width: 15px; height: 15px;" alt="" />' +
						'</div>').prependTo("body");
			}

			$(document).bind('mousemove.pleasewait', setPosition);
			$(ele).fadeIn('fast');
		})
		.bind("ajaxStop", function () {
			var ele = document.getElementById("pleasewait");
			if (ele) {
				$(ele).fadeOut('slow', function () {
					$(document).unbind('mousemove.pleasewait');
				});
			}
		});
});


$(function () {
	var timer;
	if (ZINA.REFRESH) {
		timer = setTimeout(function() {
			location.replace(ZINA.REFRESH.url);
		}, ZINA.REFRESH.timeout);
		$(".direct-download-link a").bind("click", function () {
			clearTimeout(timer);
		});
	}
});


/**
 * Social bookmarks
 */
$(function () {

	function loadStyle(src, media) {
		var link = document.createElement('link');
		link.setAttribute("rel", "stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("media", media || "all");
		link.setAttribute("href", src);
		document.getElementsByTagName('head')[0].appendChild(link);
	}

	var externals = [{
		url: "http://vkontakte.ru/js/api/share.js",
		after: function (loc) {
			if (VK) {
				$(".bookmarks-item-vk", this).each(function () {
					var text = $.trim($(this).html()),
						type = $(this).hasClass("bookmarks-item-vk-custom") ? 'custom' : 'button';

					$(this).html(VK.Share.button(loc, {type: type, text: text}));

					if ($(this).hasClass("bookmarks-item-vk-custom")) {
						$(this).bind("click", function () {
							window.open("http://vkontakte.ru/club34044522");
						});
					}
				});
			}
		}
	}, {
		url: "http://stg.odnoklassniki.ru/share/odkl_share.js",
		after: function (loc) {
			if (ODKL) {
				$(".odkl-klass-stat", this).add(".odkl-klass-s", this)
						.attr("href", loc)
						.bind("click", function () {
							ODKL.Share(this);
							return false;
						});
				ODKL.init();
			}
		}
	}, {
		url: "http://cdn.connect.mail.ru/js/loader.js",
		before: function (loc) {
			$(".mrc__plugin_like_button", this).each(function () {
				var href = $(this).attr("href");
				$(this).attr("href", href + "?url=" + encodeURIComponent(loc));
			});
		},
		after: function (loc) {
			$(".bookmarks-item-mm a", this).each(function () {
				$(this).attr("href", "http://connect.mail.ru/share?share_url=" + encodeURIComponent(loc))
						.attr("target", "_blank");
			});
		}
	}];


	var bms = $("div.bookmarks").each(function () {
		var me = $(this),
			loc = location.href.replace(/[?#].*$/, "");

		me.one("loaded.bookmarks", function () {
			controllBookmarks(me);
		});

		loadStyle("http://stg.odnoklassniki.ru/share/odkl_share.css");

		var actualButtons = 0;
		$.each(externals, function (i, need) {
			if (need.before) {
				need.before.call(me, loc);
			}
			$.ajax({
				url: need.url,
				dataType: "script",
				success: function () {
					if (need.after) {
						need.after.call(me, loc);
					}
				},
				complete: function () {
					actualButtons += 1;
					if (externals.length == actualButtons) {
						me.trigger("loaded.bookmarks");
					}
				}
			});
		});
	});

	function controllBookmarks(me) {
		var itemsWidth = 0;

		me.height(me.closest("div.box").find("> h6").outerHeight() - 2)
				.addClass("bookmarks-ready");

		$(window).bind("resize", function () {

			var container = me.parent(),
				w = container.width() - me.find("> div.bookmarks-more").outerWidth();

			itemsWidth = 0;
			w = (w < 0) ? 0 : w;

			var items = me.find("> div.bookmarks-item").each(function () {
				var nextItemWidth = $(this).removeClass("hidden").outerWidth();
				if (itemsWidth + nextItemWidth > w) {
					$(this).addClass("hidden");
				}
				itemsWidth = itemsWidth + nextItemWidth;
			});

			me[items.filter(".hidden").length ? 'removeClass' : 'addClass']("bookmarks-all");

		}).triggerHandler("resize");

		me.find("div.bookmarks-more span").bind("click", function () {
			me.addClass("bookmarks-all")
				.find("> div.bookmarks-item").removeClass("hidden");
		});
	}
});

