/* Core scripts
(C) 2010, Virtual Technologies Ltd.
*/
var VTLib = new Object();
VTLib.CurrentLangIndex = 0;	// current language index
VTLib.isFORS = false;		// FORS not supporting defaultly
VTLib.DefaultPath = "/";
VTLib.CalendarFormat = "DD.MM.YYYY";
VTLib.ContainerSelector = "body";
VTLib.BigPhotoID = "VTLib_BPhoto";

// container for popup-divs
VTLib.getDivContainer = function() { return $(VTLib.ContainerSelector); }

// choise message from array
VTLib.Lng = function(a)
{
	var i = VTLib.CurrentLangIndex;
	if (i >= a.length)
		i = a.length - 1;
	return a[i];
}
VTLib.loadedScripts = [];	// array of loaded scripts
// if script is not active to load this script.
VTLib.usingScript = function(s, func)
{
	s = s.toLowerCase();
	if (VTLib.loadedScripts[s])
		return;
	VTLib.loadedScripts[s] = true;
	document.write('<script type="text/javascript" src="' + s + '"></script>');
}

VTLib.fixPNG = function (a) {
	if (!($.support.opacity))
		a.each(function () {
			var image = $(this).css('backgroundImage');
			if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
				image = RegExp.$1;
				$(this).css({
					'backgroundImage': 'none',
					'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + ($(this).css('backgroundRepeat') == 'no-repeat' ? 'crop' : 'scale') + ", src='" + image + "')"
				}).each(function () {
					var position = $(this).css('position');
					if (position != 'absolute' && position != 'relative')
						$(this).css('position', 'relative');
				});
			}
		});
}

/* Затенение основной зоны экрана */
VTLib.overlayShow = function () {
    var h = $(document).height();
    var ovl = $("#OverlayedFon");
    ovl.css({ "display": "block", "opacity": "0.3", "height": h + "px" });
}
/* Отмена затемнения */
VTLib.overlayHide = function () {
    $("#OverlayedFon").hide(200);
}

VTLib.popupDivShowPrepare = function (divObj, ev) {
    ev = ev || window.event;
    var x = ev.clientX - 40, y = ev.clientY - 20;
    var xMax = $(window).width() - divObj.width() - 60;
    if (x > xMax) x = xMax;
    if (x < 10) x = 10;
    var yMax = $(window).height() - divObj.height() - 60;
    if (y > yMax) y = yMax;
    if (y < 10) y = 10;
    divObj.css("left", x + $(document).scrollLeft());
    divObj.css("top", y + $(document).scrollTop());
    divObj.css("z-index", 9999);
    VTLib.fixPNG($(divObj).find(".borderShadow .border"));
}

// Call URL for PopupWindow in inline mode
VTLib.popupWindowCall = function (url, windowName, jsPar) {
	$.get(url + "&CallMode=inline", "", function (t) { VTLib.popupWindow(t, windowName, jsPar); });
	return false;
}

// Popup window
VTLib.popupWindow = function (htmlText, popupWindowName, jsPar) {
    VTLib.overlayShow();
    jsPar = jsPar || {};
    var panStart = '<table class="borderShadow" cellspacing="0" cellpadding="0" border="0">'
		+ '<tr>'
		+ '<td><div class="border borderTL"></div></td>'
		+ '<td><div class="border borderT"></div></td>'
		+ '<td><div class="border borderTR"></div></td>'
		+ '</tr>'
		+ '<tr style="height:100%;">'
		+ '<td height="1"><div class="border borderL"></div></td>'
		+ '<td class="borderC">'
		;
    var panStop = '</td>'
		+ '<td height="1"><div class="border borderR"></div></td>'
		+ '</tr>'
		+ '<tr>'
		+ '<td><div class="border borderBL"></div></td>'
		+ '<td><div class="border borderB"></div></td>'
		+ '<td><div class="border borderBR"></div></td>'
		+ '</tr>'
		+ '</table>'
		;
    var s = '<div class="EditPopupDiv"';
    popupWindowName = popupWindowName || "";
    if (popupWindowName != "") {
        $("#" + popupWindowName).remove();
        s += ' id="' + popupWindowName + '"';
    }
    s += '>'
		+ panStart
		+ '<div rel="VTLib_moving" class="EditPopupDivTitle">'
		+ '<div class="EditPopupDivClose Clear" name="btnClose"><img src="../common/img/butDel.gif" alt="" /></div>'
		+ '<span class="Text">'
		;
    if (jsPar.Title)
        s += jsPar.Title;
    s += '</span>'
		+ '</div>'
		+ '<div class="EditPopupDivContent"></div>'
		+ panStop
		+ '</div>'
		;
    var divObj = $(s).appendTo(VTLib.getDivContainer());
    var divContent = $(divObj).find("div.EditPopupDivContent");
    divContent.append(htmlText);
    VTLib.fixPNG($(divObj).find(".border"));
    var maxWidth = $(window).width() - 30;
    var maxHeight = $(window).height() - 50;
    var w = divObj.width();
    if (jsPar.maxWidth && jsPar.maxWidth < w)
        maxWidth = Math.min(maxWidth, jsPar.maxWidth);
    if (w > maxWidth) {
        w = maxWidth;
        divContent.width(w);
        divObj.width(w);
    }
    var h = divObj.height();
    if (jsPar.maxHeight && jsPar.maxHeight < h)
        maxHeight = Math.min(maxHeight, jsPar.maxHeight);
    if (h > maxHeight) {
        h = maxHeight;
        divContent.height(h);
        divObj.height(h);
    }
    //	alert("DivW=" + divObj.width() + " W=" + divObj.width() + " MaxW=" + maxWidth + " H=" + divObj.height() + " MaxH=" + maxHeight);
    var x = $(window).width() / 2 - w / 2;
    var y = $(window).height() / 2 - h / 2;
    var xMax = $(window).width() - w - 60;
    if (x > xMax)
        x = xMax;
    if (x < 1)
        x = 1;
    var yMax = $(window).height() - h - 60;
    if (y > yMax)
        y = yMax;
    if (y < 1)
        y = 1;
    divObj.css("left", x + $(document).scrollLeft());
    divObj.css("top", y + $(document).scrollTop());
    divObj.unbind();
    divObj.find("[name=btnClose]").bind("click", function (event) {
        event.stopPropagation();
        VTLib.overlayHide();
        divObj.hide(200, function () { divObj.remove(); });
        return false;
    });
    divObj.bind("keypress", function (event) {
        if (event.keyCode != '27')
            return true;
        event.stopPropagation();
        if (window.confirm("Close?")) {
            VTLib.overlayHide();
            divObj.hide(200, function () { divObj.remove() });
        }
        return false;
    });
    var divMoving = divObj.find("[rel=VTLib_moving]");
    divMoving.bind("mousedown", function (event) {
        divObj.mouse_X = event.clientX;
        divObj.mouse_Y = event.clientY;
        $(document.body).bind("mousemove", function (event) {
            event.stopPropagation();
            var dx = event.clientX - divObj.mouse_X;
            var dy = event.clientY - divObj.mouse_Y;
            divObj.mouse_X = event.clientX;
            divObj.mouse_Y = event.clientY;
            divObj.css("left", divObj.position().left + dx);
            divObj.css("top", divObj.position().top + dy);
            return false;
        });
    });
    $(document.body).bind("mouseup", function (event) { $(document.body).unbind("mousemove"); });
    divObj.show(400, function () {
        if (jsPar.fn_post)
            jsPar.fn_post();
        divObj.find("input:text:first").focus();
    });
}

VTLib.sideSlideBarInit = function (divObj) {
    var minDX = 25;
    $(window).bind("scroll resize", function () {
        $(divObj).animate({
            left: $(window).width() + $(document).scrollLeft() - divObj.width() - 2,
            top: $(window).height() / 4 + $(document).scrollTop()
        }, { duration: 200, queue: false });
    });
    $(divObj).find(".scToolbarVTMenu").bind("click", function () {
        var w = divObj.attr("rel");
        var off = $(window).width() + $(document).scrollLeft();
        if (divObj.width() < 60) {
            $(divObj).animate({ left: off - w, width: w, opacity: 1 }, { duration: 400, queue: false });
        } else {
            $(divObj).animate({ left: off - minDX, width: minDX, opacity: 0.5 }, { duration: 400, queue: false });
        }
    });
    $(divObj).find("a, button").bind("click", function () {
        var w = divObj.attr("rel");
        if (divObj.width() > 60) {
            var off = $(window).width() + $(document).scrollLeft();
            $(divObj).fadeTo(100, 0.5);
            $(divObj).animate({ left: off - minDX, width: minDX, opacity: 0.5 }, { duration: 500, queue: false });
        }
    });
    divObj.css("top", $(window).height() / 4 + $(document).scrollTop());
    divObj.css("left", $(window).width() - minDX + $(document).scrollLeft());
    divObj.css("z-index", 9999);
    divObj.width(minDX);
    VTLib.fixPNG($(divObj).find(".borderShadow .border"));
    divObj.show();
    divObj.fadeTo(100, 0.5);
}

// Predefine functions
function CalendarSubmitDate() {}
function CalendarToolsShow() {}
function CalendarSubmitDate() {}

function InfoBlockMouseOver(o, n)
{
	if (!$.browser.msie)
		return;
	var s = "<div class='InfoBlockCtrlBorder'></div>";
	$(o).before(s);
	var d = $(".InfoBlockCtrlBorder").get(0);
	$(d).css("top", $(o).offset().top);
	$(d).css("left", $(o).offset().left);
	$(d).width($(o).width());
	$(d).height($(o).height());
	$(d).fadeTo(1000, 0.3);
	d.ondblclick = o.ondblclick;
	if (n)
		d.onclick = n.onclick;
}
function InfoBlockMouseOut(o)
{
	$(".InfoBlockCtrlBorder").remove();
}
function infoBlockMenuCmd(mode)
{
	var d = $("#infoblockMenuDiv");
	var gid = $(d).find("[rel=Gid]").text();
	var group = $(d).find("[rel=Group]").text();
	var part = $(d).find("[rel=Part]").text();
	var id = $(d).find("[rel=Id]").text();
	if (mode == "new")
		gid = "";
	d.hide();
	if (mode == "delete")
	{
		if(!confirm(VTLib.Lng(["Удалить контентную зону","Delete content area"]) + gid + "?\r\n" + group + ":" + part+":" + id))
			return;
	}
	if (mode == "fors")
		window.open(VTLib.DefaultPath + "adm/fors.aspx?ObjType=Info&ObjGid=" + gid, "_blank");
	else
		window.open(VTLib.DefaultPath + "asp/infoCard.aspx?&Mode=" + mode + "&gid=" + gid + "&infoGroup=" + group + "&infoPart=" + part + "&infoId=" + id, "_blank");
}

function beginDisplayInfoMenu(gid, group, part, id, obj, ev) {
    VTLib.overlayShow();
    var d = $("#infoblockMenuDiv");
	if (!VTLib.isFORS)
		d.find("[rel=fors]").hide();
	if (gid == "")
	{
		d.find("[rel=new]").show();
		d.find("[rel=edit]").hide();
	}
	else
	{
		$(d).find("[rel=edit]").show();
		$(d).find("[rel=new]").hide();
	}
	d.find("[rel=Gid]").text(gid);
	d.find("[rel=Group]").text(group);
	d.find("[rel=Part]").text(part);
	d.find("[rel=Id]").text(id);

	VTLib.popupDivShowPrepare(d, ev);
	d.show(100, function () {
	    $(document.body).bind("click.infoblock", function () {
	        $(document.body).unbind("click.infoblock"); d.hide(100); VTLib.overlayHide();
	    });
	});
	return false;
}

function divShowHide(divID, divAlter, imgID)
{
	var obj = document.getElementById(divID);
	var objAlter = null;
	if (divAlter)
		objAlter = document.getElementById(divAlter);
	var objIMG = null;
	if (imgID)
		objIMG = document.getElementById(imgID);
	if (obj.style.display == "none")
	{
		obj.style.display = "block";
		if (objAlter)
			objAlter.style.display = "none";
		if (objIMG)
		{
			objIMG.src = objIMG.src.replace("down.gif", "up.gif");
			objIMG.alt = 'Свернуть';
		}
	}
	else
	{
		obj.style.display = "none";
		if (objAlter)
			objAlter.style.display = "block";
		if (objIMG)
		{
			objIMG.src = objIMG.src.replace("up.gif", "down.gif");
			objIMG.alt = 'Развернуть';
		}
	}
}

function RS_set(targetElement, txt)
{
	var obj = document.getElementById(targetElement);
	if (obj)
		obj.innerHTML = txt;
}
function RS_call(url, frm, callBackFunc)
{
	var doc;
	var obj = document.getElementById("RS_iframe");
	if (obj.contentDocument)
	{	// NS6
		doc = obj.contentDocument; 
	}
	else if (obj.contentWindow)
	{	// IE5.5, IE6
		doc = obj.contentWindow.document;
	}
	else if (obj.document)
	{	// IE5
		doc = obj.document;
	}
	else
	{
		alert("Не поддерживаются фреймы!");
		return true;
	}
	if (frm && url && url != "")
		frm.action = url;
	doc.location.replace(url);
	if (event)
		event.cancelBubble = true;
	if (callBackFunc)
		$(doc.document).ready(callBackFunc);
	return false;
}
function setSelectorMessage(obj, txt)
{
	if (!obj)
		return;
	if (obj.selectedIndex)
	{
		obj.selectedIndex = 0;
		while(obj.length > 1)
			obj.remove(1);
		var opt = obj.options[0];
		opt.text = txt;
		opt.value = "";
		opt.style.color = "red";
		opt.style.backgroundColor = "yellow";
	}
	else
	{
		obj.value = "";
	}
}
document.write('<iframe id="RS_iframe" name="RS_iframe" style="border:0px;width:0px;height:0px;"></iframe>');

//Преобразование символов в JSON-безопасные
function JSONEncode(txt)
{
	return txt
		.replace(/&/g, "&amp;")
		.replace(/\\/g, "&_backslash;")
		.replace(/'/g, "&apos;")
		.replace(/"/g, "&quot;")
		.replace(/\r/g, "&_curr;")
		.replace(/\n/g, "&_curn;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/,/g, "&_coma;")
		.replace(/\t/g, "&_tab;")
		.replace(/\b/g, "&_back;")
		;
}
//Обратное преобразование символов из JSON-безопасных
function JSONDecode(txt)
{
	return txt
		.replace(/&_back;/g, "\b")
		.replace(/&_tab;/g, "\t")
		.replace(/&_coma;/g, ",")
		.replace(/&gt;/g, ">")
		.replace(/&lt;/g, "<")
		.replace(/&_curn;/g, "\n")
		.replace(/&_curr;/g, "\r")
		.replace(/&quot;/g, '"')
		.replace(/&apos;/g, "'")
		.replace(/&_backslash;/g, "\\")
		.replace(/&amp;/g, "&")
		;
}

function wsOpenCard(url, w, h)
{
	var winName = "_blank";
	var winPar = "menubar=no,resizable=yes,status=yes,titlebar=yes,toolbar=no,scrollbars=yes,";
	if (w)
	{
		var openWidth = w;
		var openLeft = (screen.width - openWidth) / 2;
		winPar += " width=" + openWidth + ", left=" + openLeft + ",";
	}
	if (h)
	{
		var openHeight = h;
		var openTop = (screen.height - openHeight) / 3;
		winPar += " height=" + openHeight + ", top=" + openTop;
	}
	window.open(url, winName, winPar);
	return false;
}

function wsSetWindowSize(w, h)
{
	window.moveTo(screen.width / 2 - w / 2, screen.height / 2 - h / 2);
	window.resizeTo(w, h);
}

function wsCloseCard(reloadParent)
{
	if (reloadParent)
	{
		if (window.opener != null)
		{
			if (!window.opener.closed)
			{
				window.opener.location.reload();
				window.opener.focus();
			}
		}
	}
	window.close();
}

// Common site scripts
function deleteRecord(url, txt)
{
	window.event.cancelBubble = true;
	if (txt == null)
		txt = "";
	if (confirm("Удалить запись?\r\n" + txt))
		wsOpenCard(url);
}
// Delete record in inline-mode
function deleteRecordInline(url, txt) {
    window.event.cancelBubble = true;
    if (txt == null)
        txt = "Удалить?";
    if (confirm(txt)) {
//        var v = document.getElementById("RS_iframe");
//        alert(v.document.location.href);
//        if (v)
        //            v.document.location.href = url + "&CallMode=inline";
        window.open(url + "&CallMode=inline", "RS_iframe");
    }
    return false;
}
function reverseSortDir(frm)
{
	var s = "Up";
	if (frm.SortDir.value == "Up")
		s = "Down";
	frm.SortDir.value = s;
	document.all.SortImg.src="../img/sort" + s + ".gif";
}
function clearDateFields(frm, fld1, fld2, fld3, fld4, fld5, fld6, fld7, fld8)
{
	if (fld1) { frm[fld1].value = ""; frm[fld1 + "_"].value = ""; }
	if (fld2) {	frm[fld2].value = ""; frm[fld2 + "_"].value = ""; }
	if (fld3) { frm[fld3].value = ""; frm[fld3 + "_"].value = ""; }
	if (fld4) {	frm[fld4].value = ""; frm[fld4 + "_"].value = ""; }
	if (fld5) { frm[fld5].value = ""; frm[fld5 + "_"].value = ""; }
	if (fld6) {	frm[fld6].value = ""; frm[fld6 + "_"].value = ""; }
	if (fld7) { frm[fld7].value = ""; frm[fld7 + "_"].value = ""; }
	if (fld8) {	frm[fld8].value = ""; frm[fld8 + "_"].value = ""; }
}
function submitDateFields(frm, fld1, fld2, fld3, fld4, fld5, fld6, fld7, fld8)
{
	if (fld1) { submitDate(frm, fld1); }
	if (fld2) { submitDate(frm, fld2); }
	if (fld3) { submitDate(frm, fld3); }
	if (fld4) { submitDate(frm, fld4); }
	if (fld5) { submitDate(frm, fld5); }
	if (fld6) { submitDate(frm, fld6); }
	if (fld7) { submitDate(frm, fld7); }
	if (fld8) { submitDate(frm, fld8); }
}

function getDocumentStylesList(defPath)
{
	var stList = "", dlm = "";
	if (!document.styleSheets)
	{
		stList = defPath + "st/base.css," + defPath + "st/st.csss";
	}
	else
	{
		var st = document.styleSheets;
		var i;
		for (i = 0; i < st.length; i++) {
			var sStyle = st[i];
			if (sStyle.href)
			{
				if (sStyle.href != ""
					&& sStyle.href.indexOf("ws4.css") < 0
					&& sStyle.href.indexOf("editor_") < 0
					&& sStyle.href.indexOf("contextmenu.css") < 0
					)
				{
					stList += dlm + sStyle.href;
					dlm = ",";
				}
			}
		}
	}
	return stList;
}

// Find and check requered fields
VTLib.getRequeredFieldsEmpty = function(frmId)
{
	VTLib.errMsg = "";
	$("#" + frmId + " .requred").each(function(){
		if ($(this).val() == "")
			VTLib.errMsg += "- " + $(this).attr("friendly") + "\r\n";
	});
	return VTLib.errMsg;
}

// Find and check requered fields for feedback forms
VTLib.feedbackCheckFields = function(frmId, jsonPar)
{
	var frm = document.getElementById(frmId);
	if (!frm)
		return true;
	var aFld = jsonPar.Fields;
	var err = "";
	var i;
	$(frm).find(".frmRequered").removeClass("frmRequered");
	for(i=0; i < aFld.length; i++)
	{
		var fld = aFld[i];
		if (fld.FieldRequered)
		{
			var val = $(frm).find("[name=" + fld.FieldName + "]").val();
			if (val == "")
			{
				err += "- " + ((fld.FieldLabel)? fld.FieldLabel : fld.FieldName) + "\r\n";
				var fldID = frmId + "_" + fld.FieldName;
				$(frm).find("#" + fldID).addClass("frmRequered");
			}
		}
	}
	if (err == "")
		return true;
	window.alert(VTLib.Lng(["Необходимо заполнить все обязательные поля!", "Type all requered filds!"]) + err);
	return false;
}

// Selector of Languages parts of edit card
VTLib.LangsArray = new Array();
VTLib.selectLang = function(formId, lng)
{
	$("#" + formId + " .wsLangSel").addClass("wsLang");
	$("#" + formId + " .wsLangSel").removeClass("wsLangActive");
	$("#" + lng + "RowSel").removeClass("wsLang");
	$("#" + lng + "RowSel").addClass("wsLangActive");
	$("#" + formId + " .wsLangTab").css("display", "none");
	$("#" + lng + "Row").css("display", "block");
}

// чтение параметров
function VTReadPar(par)
{
	if (par == null)
		par = new Object();
	var a = document.location.search.substr(1).split('&');
	var parItem;
	var i;
	for (i = 0 ; i < a.length ; i++)
	{
		parItem = a[i].split('=') ;
		par[parItem[0]] = unescape(parItem[1]);
	}
	if (par.basePath == null)
	{
		var baseUrl = parent.document.location;
		par.basePath = baseUrl.protocol + "//" + baseUrl.host + "/common/";
	}
	return par;
}

function VTCloseDialog(val)
{
	window.returnValue = (val == null)? "" : val;
	window.close();
}

function VTShowDialog(pagePath, width, height, attr)
{
	var params = "";
	if (width != null)		params += "dialogWidth:" + width + "px;";
	if (height != null)		params += "dialogHeight:" + height + "px;";
	if (attr == null)
		params += "help:no;scroll:no;status:no;";
	else
		params += attr;
	return showModalDialog(pagePath, window, params);
}

function padi(v, n)
{
	var s = "" + v;
	while (s.length < n)
		s = "0" + s;
	return s;
}

function VTPlug_InfoSlider(obj) {
	this.Group = obj.Group;
	this.Part = obj.Part;
	this.Count = obj.Count;
	this.Margin = obj.Margin;
	this.MinHeight = obj.MinHeight;
	this.AJAHURL = obj.AJAHURL;
	this.PREF = "VTPlug_InfoSlider";
	this.ID_TAB = this.PREF + "_" + this.Group + this.Part;
	this.CL_TD = this.PREF + "_Container";
	this.CL_IS = this.PREF;
	this.CL_IS_ITEMS = this.PREF + "_Items";
	this.Var_CurW = parseInt($("#" + this.ID_TAB + " ." + this.CL_TD).width());
	this.Var_CurElem = 0;
	this.init();
	this.eventBindingHandler();
}
VTPlug_InfoSlider.prototype.init = function() {
	var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_IS_ITEMS);
	var items = itemsContainer.children("span");
	items.css("width", this.Var_CurW - 2 * this.Margin).css("margin", this.Margin);
	var firstElement = itemsContainer.children("span:first");
	var lastElement = itemsContainer.children("span:last");
	itemsContainer.append(firstElement.clone().addClass("clone loaded").removeAttr("id"))
	.prepend(lastElement.clone().addClass("clone").removeAttr("id"));
	itemsContainer.css("left", "-" + this.Var_CurW + "px");
	var firstRealElement = itemsContainer.find("span#IS_1");
	firstRealElement.addClass("loaded").find("div.InfoBlock").css("margin-bottom", "0em");
	var curHeight = firstRealElement.height() + 2 * this.Margin;
	if (curHeight < this.MinHeight)
		curHeight = this.MinHeight;
	$("#" + this.ID_TAB + " ." + this.CL_IS).css("height", curHeight);
};
VTPlug_InfoSlider.prototype.eventBindingHandler = function() {
	var obj = this;
	$("#" + this.ID_TAB + " .IS_prevPage").bind("click", function() { obj.eventPrevPageClick(); });
	$("#" + this.ID_TAB + " .IS_nextPage").bind("click", function() { obj.eventNextPageClick(); });
	$(window).bind("resize", function() { obj.eventWindowResize(); });
};
VTPlug_InfoSlider.prototype.eventPrevPageClick = function() {
	var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_IS_ITEMS);
	if (this.Var_CurElem == 0)
		this.Var_CurElem = this.Count;
	var nextElement = itemsContainer.find("#IS_" + this.Var_CurElem);
	if (nextElement != null && !nextElement.hasClass("loaded")) {
		var return_value = this.getAJAHContent();
		nextElement.addClass("loaded").html(return_value);
		if (this.Var_CurElem == this.Count)
		itemsContainer.children("span:first").addClass("loaded").html(return_value);
	}
	this.heightHandler(nextElement);
	var obj = this;
	itemsContainer.animate({ left: "+=" + obj.Var_CurW + "px" }, 200, function() {
		if (obj.Var_CurElem == obj.Count) {
			var offset = obj.Var_CurW * parseInt(obj.Count);
			itemsContainer.css("left", "-" + offset + "px");
		}
		obj.Var_CurElem--;
	});
};
VTPlug_InfoSlider.prototype.eventNextPageClick = function() {
	var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_IS_ITEMS);
	this.Var_CurElem += 2;
	var nextElement = itemsContainer.find("#IS_" + this.Var_CurElem);
	if (nextElement != null && !nextElement.hasClass("loaded") && this.Count >= this.Var_CurElem) {
		var return_value = this.getAJAHContent();
		nextElement.addClass("loaded").html(return_value);
		if (this.Var_CurElem == this.Count)
			itemsContainer.children("span:first").addClass("loaded").html(return_value);
	}
	this.heightHandler(nextElement);
	var obj = this;
	itemsContainer.animate({ left: "-=" + obj.Var_CurW + "px" }, 200, function() {
		if (obj.Var_CurElem > obj.Count) {
			obj.Var_CurElem = 0;
			itemsContainer.css("left", "-" + obj.Var_CurW + "px");
		}
		else
			obj.Var_CurElem--;
	});
};
VTPlug_InfoSlider.prototype.getAJAHContent = function() {
	return $.ajax({ type: "GET", url: this.AJAHURL, async: false, dataType: "html",
		data: ({ Mode: "ISGetInfoBlockContent",
			Group: this.Group,
			Part: this.Part,
			Id: this.Var_CurElem
		})
	}).responseText;
};
VTPlug_InfoSlider.prototype.heightHandler = function(elem) {
	elem.find("div.InfoBlock").css("margin-bottom", "0em");
	var newHeight = elem.height() + 2 * this.Margin;
	if (newHeight > this.MinHeight) {
		this.MinHeight = newHeight;
		$("#" + this.ID_TAB + " ." + this.CL_IS).css("height", newHeight);
	}
};
VTPlug_InfoSlider.prototype.eventWindowResize = function() {
	var container = $("#" + this.ID_TAB + " ." + this.CL_TD);
	var items = $("#" + this.ID_TAB + " ." + this.CL_IS_ITEMS);
	if (this.Var_CurW != parseInt(container.width())) {
		this.Var_CurW = parseInt(container.width());
		items.children("span").css("width", this.Var_CurW - 2 * this.Margin);
		var offset = this.Var_CurW * (this.Var_CurElem + 1);
		items.css("left", "-" + offset + "px");
		this.heightHandler(items.children("span#IS_" + parseInt(this.Var_CurElem + 1)));
	}
};

function VTPlug_PhotoSliderAdv(obj) {
	if (VTPlug_PhotoSliderAdv.inited)
		return false;
	VTPlug_PhotoSliderAdv.inited = true;
	this.ObjType = obj.ObjType;
	this.ObjGid = obj.ObjGid;
	this.Count = parseInt(obj.Count);
	this.ItemW = parseInt(obj.ItemWidth);
	this.ItemH = obj.ItemHeight;
	this.ItemM = obj.ItemMargin;
	this.PREF = "VTPlug_PSA";
	this.ID_TAB = this.PREF + "_" + this.ObjType + this.ObjGid;
	this.CL_TD = this.PREF + "_Container";
	this.CL_PSA = this.PREF;
	this.CL_PSA_ITEMS = this.PREF + "_Items";
	this.Var_CurElem = 0;
	this.Var_AllActualElSum = 0;
	this.Var_AllElems = 0;
	this.Var_CurW = parseInt($("#" + this.ID_TAB + " ." + this.CL_TD).width() - 2);
	this.Var_ElemW = this.Var_CurW / this.Count;
	this.init();
	this.eventBindingHandler();
}
VTPlug_PhotoSliderAdv.prototype.inited;

VTPlug_PhotoSliderAdv.prototype.init = function() {
	var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_PSA_ITEMS);
	var items = itemsContainer.children("span");
	items.css("width", this.Var_ElemW - 2 * this.ItemM);
	itemsContainer.find("span > a > span").css("margin-left", (this.Var_ElemW - 2 * this.ItemM - this.ItemW) / 2);
	this.Var_AllActualElSum = items.length;
	this.Var_AllElems = this.Var_AllActualElSum;
	if (this.Var_AllActualElSum > this.Count) {
		for (var i = 0; i < this.Count; i++) {
			itemsContainer.append(items.eq(i).clone().addClass("clone"));
			itemsContainer.prepend(items.eq(this.Var_AllActualElSum - 1 - i).clone().addClass("clone"));
		}
		var newWidth = (this.Var_AllActualElSum + this.Count * 2) * this.Var_ElemW + 2;
		itemsContainer.css("width", newWidth);
		this.Var_AllElems = this.Var_AllActualElSum + 2 * this.Count;
		this.Var_CurElem = this.Count;
		itemsContainer.css("left", "-" + this.Var_ElemW * this.Count + "px");
	}
};
VTPlug_PhotoSliderAdv.prototype.eventBindingHandler = function() {
	var obj = this;
	$("#" + this.ID_TAB + " .PSA_prevPage").bind("click", function() { obj.eventPrevClick(); });
	$("#" + this.ID_TAB + " .PSA_nextPage").bind("click", function() { obj.eventNextClick(); });
	$(window).bind("resize", function() { obj.eventWindowResize(); });
};
VTPlug_PhotoSliderAdv.prototype.eventPrevClick = function() {
	if (this.Var_AllActualElSum > this.Count) {
		this.Var_CurElem--;
		var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_PSA_ITEMS);
		var items = itemsContainer.children("span");
		var nextElement = items.eq(this.Var_CurElem);
		if (!nextElement.hasClass("loaded")) {
			this.makeElementContent(nextElement);
			if (nextElement.hasClass("clone")) {
				var clonedElement = items.eq(this.Var_CurElem + this.Var_AllActualElSum);
				clonedElement.html(nextElement.html()).addClass("loaded");
			}
		}
		var offset = this.Var_ElemW;
		var obj = this;
		itemsContainer.animate({ left: "+=" + offset + "px" }, 200, function() {
			if (obj.Var_CurElem == 0) {
				itemsContainer.css("left", "-" + offset * obj.Var_AllActualElSum + "px");
				obj.Var_CurElem = obj.Var_AllActualElSum;
			}
		});
	}
};
VTPlug_PhotoSliderAdv.prototype.eventNextClick = function() {
	if (this.Var_AllActualElSum > this.Count) {
		this.Var_CurElem++;
		var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_PSA_ITEMS);
		var items = itemsContainer.children("span");
		var nextElement = items.eq(this.Var_CurElem + this.Count - 1);
		if (!nextElement.hasClass("loaded")) {
			this.makeElementContent(nextElement);
			var isClonedElement = this.Var_CurElem - this.Var_AllActualElSum + parseInt(this.Count) - 1;
			if (isClonedElement >= 0 && isClonedElement < this.Count) {
				var clonedElement = items.eq(isClonedElement);
				if (!clonedElement.hasClass("loaded"))
					clonedElement.html(nextElement.html()).addClass("loaded");
			}
		}
		var offset = this.Var_ElemW;
		var obj = this;
		itemsContainer.animate({ left: "-=" + offset + "px" }, 200, function() {
			if (obj.Var_CurElem == parseInt(obj.Var_AllActualElSum) + obj.Count) {
				itemsContainer.css("left", "-" + offset * obj.Count + "px");
				obj.Var_CurElem = obj.Count;
			}
		});
	}
};
VTPlug_PhotoSliderAdv.prototype.makeElementContent = function(nextElement) {
	var url = nextElement.attr("relDir") + nextElement.attr("relPrevName");
	nextElement.addClass("loaded").html('<a href="#" target="_blank" title="" onclick="VTLib.showBigPhoto(\''
	+ url.replace("_sm", "") + '\'); return false;"><span style="cursor:pointer;background:url(' + url + ') no-repeat center center;width:'
	+ this.ItemW + ';height:' + this.ItemH + ';margin-left:' + (this.Var_ElemW - 2 * this.ItemM - this.ItemW) / 2 + '"></span></a>');
};
VTPlug_PhotoSliderAdv.prototype.eventWindowResize = function() {
	this.Var_CurW = parseInt($("#" + this.ID_TAB + " ." + this.CL_TD).width() - 2);
	this.Var_ElemW = this.Var_CurW / this.Count;
	var newWidth = (this.Var_AllActualElSum + this.Count * 2) * this.Var_ElemW + 2;
	var itemsContainer = $("#" + this.ID_TAB + " ." + this.CL_PSA_ITEMS);
	var offset = this.Var_ElemW * this.Var_CurElem;
	itemsContainer.css("width", newWidth).css("left", "-" + offset + "px");
	var items = itemsContainer.children("span");    
	items.css("width", this.Var_ElemW - 2 * this.ItemM);
	itemsContainer.find("span > a > span").css("margin-left", (this.Var_ElemW - 2 * this.ItemM - this.ItemW) / 2);
};

VTLib.showBigPhotoNavi = function(url, obj, index) {
	var actPopup = $("#" + VTLib.BigPhotoID);
	if (actPopup.length == 1 && actPopup.hasClass("naviEnabled")) {
		var photoCont = actPopup.find(".PhotoContainer");
		photoCont.prepend('<div class="Sizer Center Progress" style="position:absolute;top:' + (photoCont.height() - 16) / 2 
		+ 'px;left:' + (photoCont.width() - 16) / 2 + ';width:20;height:16;background:#aaa">'
		+ '<img src="../common/img/ajax_small.gif" alt="" /></div>');
		var content = '<img style="visibility:visible;display:inline;" src="' + url + '">';
		var hiddenDiv = $('<div id="PSA_HiddenDiv" style="display:hidden">' + content + '</div>');
		var hidImg = hiddenDiv.find("img");
		hidImg.bind("load", function(event) {
			actPopup.find(".Progress").remove();
			actPopup.find("." + obj.Cl_Prev).add("." + obj.Cl_Next).remove();
			loadedContent = content;
			var offsetW = hidImg.width() - actPopup.find("img:last").width();
			var offsetH = hidImg.height() - actPopup.find("img:last").height();
			var animateProp = {};
			if (offsetW != 0) {
				if ($.browser.msie)
					offsetW += 3;
				animateProp.width = (offsetW > 0) ? "+=" + offsetW + "px" : "-=" + -offsetW + "px";
				animateProp.left = (offsetW > 0) ? "-=" + offsetW / 2 + "px" : "+=" + -offsetW / 2 + "px";
			}
			if (offsetH != 0) {
				animateProp.height = (offsetH > 0) ? "+=" + offsetH + "px" : "-=" + -offsetH + "px";
				animateProp.top = (offsetH > 0) ? "-=" + offsetH / 2 + "px" : "+=" + -offsetH / 2 + "px";
			}
			actPopup.animate(animateProp, 200, function() {
				photoCont.html(loadedContent);
				actPopup.append(obj.makeNavi(photoCont));
				obj.makeNaviBind(index);
				hiddenDiv.remove();
			});
		});
		hiddenDiv.appendTo(VTLib.ContainerSelector);
	}
}
VTLib.showBigPhoto = function(url, obj, index) {
	VTLib.popupWindow('<div class="Sizer Center" style="width:100px;height:100px">'
	+ '<img src="../common/img/ajax_small.gif" alt="" style="margin-top:42px" /></div>', VTLib.BigPhotoID);
	var content = '<img style="visibility:visible;display:inline;" src="' + url + '">';
	var hiddenDiv = $('<div id="PSA_HiddenDiv" style="display:none">' + content + '</div>');
	hiddenDiv.find("img").bind("load", function(event) {
		var loadedContent = '<div style="padding:5px;position:relative;" class="PhotoContainer Center">';
		loadedContent += content + '</div>';
		if (obj != undefined && obj != null && index != undefined && index != null)
			loadedContent += obj.makeNavi(hiddenDiv);
		VTLib.popupWindow(loadedContent, VTLib.BigPhotoID);
		if (obj != undefined && obj != null && index != undefined && index != null)
			obj.makeNaviBind(index);
		hiddenDiv.remove();
	});
	hiddenDiv.appendTo(VTLib.ContainerSelector);
};

function VTPlug_PhotoGallery(obj) {
	this.Selector	= obj.Selector;
	this.Id			= obj.Id;
	this.Content	= null;
	this.Cl_Prev = "PG_Left";
	this.Cl_Next = "PG_Next";
	this.init();
}
VTPlug_PhotoGallery.prototype.init = function() {
	var cBox = $(this.Selector);
	var imgA = this.Content = $(cBox).find("a > img").parent();
	if (imgA.length != 0) {
		var plug = this;
		imgA.each(function(i) {
			var obj = this;
			$(this).bind("click", function() { VTLib.showBigPhoto($(obj).attr("href"), plug, i); return false; });
		});
	}
};
VTPlug_PhotoGallery.prototype.makeNavi = function(obj) {
	var NaviElemW = 50;
	var NaviElemH = 20;
	var top = (obj.height() + 20 - NaviElemH) / 2;
	var left = obj.width() + 28 - NaviElemW;
	return '<div class="' + this.Cl_Prev + ' Center" style="position:absolute;border:1px solid #888;background:#aaa;'
		 + 'width:' + NaviElemW + 'px;height:' + NaviElemH + 'px;top:' + top + ';left:20px; cursor:pointer">' + VTLib.Lng(["Назад", "Prev"]) + '</div>'
		 + '<div class="' + this.Cl_Next + ' Center" style="position:absolute;border:1px solid #888;background:#aaa;'
		 + 'width:' + NaviElemW + 'px;height:' + NaviElemH + 'px;top:' + top + ';left:' + left + ';cursor:pointer">'
		 + VTLib.Lng(["Вперед", "Next"]) + '</div>';
};
VTPlug_PhotoGallery.prototype.makeNaviBind = function(index) {
	var obj = this;
	var divObj = $("#" + VTLib.BigPhotoID);
	var prevBut = divObj.find("." + this.Cl_Prev);
	prevBut.bind("click", function() {
		var ind = (index == 0) ? obj.Content.length - 1 : index - 1;
		VTLib.showBigPhotoNavi(obj.Content.eq(ind).attr("href"), obj, ind);
	});
	var nextBut = divObj.find("." + this.Cl_Next);
	nextBut.bind("click", function() {
		var ind = (index == obj.Content.length - 1) ? 0 : index + 1;
		VTLib.showBigPhotoNavi(obj.Content.eq(ind).attr("href"), obj, ind);
	});
	var all = prevBut.add(nextBut);
	all.animate({ opacity: 0.75 }, 10);
	divObj.bind("mouseenter", function() { all.stop().animate({ opacity: 0.75 }, 100); });
	divObj.bind("mouseleave", function() { all.stop().animate({ opacity: 0 }, 100); });
	divObj.addClass("naviEnabled");
};
