/* 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";

// container for popup-divs
VTLib.getDivContainer = function() { return $("#VTLibContainer"); }

// choise message from array
VTLib.Lng = function(a)
{
	var i = VTLib.CurrentLangIndex;
	if (i >= a.length)
		i = a.length;
	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.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);
}

// Call URL for PopupWindow in inline mode
VTLib.popupWindowCall = function(url, windowName)
{
	$.get(url + "&CallMode=inline", "", function(t) { VTLib.popupWindow(t, windowName); });
	return false;
}

// Popup window
VTLib.popupWindow = function(htmlText, popupWindowName)
{
	var s = '<div class="EditPopupDiv"';
	popupWindowName = popupWindowName || "";
	if (popupWindowName != "")
	{
		$("#" + popupWindowName).remove();
		s += ' id="' + popupWindowName + '"';
	}
	s += '>'
		+ '<div rel="VTLib_moving" style="text-align:right;">'
		+ '<span style="border-bottom:dotted;cursor:move; margin-right:20px;">Move</span>'
		+ '<span style="border-bottom:dotted;cursor:pointer;" name="btnClose">Close</span>'
		+ '</div>'
		+ '</div>'
		;
	var divObj = $(s).appendTo(VTLib.getDivContainer());
	divObj.append(htmlText);
	var w = divObj.width();
	var h = divObj.height();
	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 < 10)
		x = 10;
	var yMax = $(window).height() - h - 60;
	if (y > yMax)
		y = yMax;
	if (y < 10)
		y = 10;
	divObj.css("left", x + $(document).scrollLeft());
	divObj.css("top", y + $(document).scrollTop());
	divObj.unbind();
	divObj.find("[name=btnClose]").bind("click", function(event) {
		event.stopPropagation(); 
		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?"))
			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() {divObj.find("input:text:first").focus();});
}

VTLib.sideSlideBarInit = function(divObj)
{
	$(window).bind("scroll", function() {
		$(divObj).animate({top:$(window).height() / 3 + $(document).scrollTop()}, { duration: 500, queue: false });
	});
	$(window).bind("resize", function() {
		divObj.width(20);
		divObj.css("left", $(window).width() - 20 + $(document).scrollLeft());
		$(divObj).animate({top:$(window).height() / 3 + $(document).scrollTop()}, { duration: 500, queue: false });
	});
	$(divObj).find(".scToolbarVTMenu").bind("click", function() {
		var t = divObj;
		var w = t.attr("rel");
		var off = $(window).width() + $(document).scrollLeft();
		if (t.width() < 60)
		{
			$(t).animate({left:off - w, width:w, opacity: 1}, { duration: 400, queue: false });
		} else {
			$(t).animate({left:off - 20, width:20, opacity: 0.5}, { duration: 400, queue: false });
		}
	});
	$(divObj).find("a, button").bind("click", function() {
		var t = divObj;
		var w = t.attr("rel");
		if (t.width() > 60)
		{
			var off = $(window).width() + $(document).scrollLeft();
			$(t).fadeTo(100, 0.5);
			$(t).animate({left:off - 20, width:20, opacity: 0.5}, { duration: 500, queue: false });
		}
	});
	divObj.css("top", $(window).height() / 3 + $(document).scrollTop());
	divObj.css("left", $(window).width() - 20 + $(document).scrollLeft());
	divObj.css("z-index", 9999);
	divObj.width(20);
	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)
{
	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);
		});
	});
	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);
}
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;
}

// 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;
}
