function $(id) 
{
	return document.getElementById(id);
}

function classFilter(r,m,not)
{
	m = " " + m + " ";
	var tmp = [];
	for ( var i = 0; r[i]; i++ )
	{
		var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
		if ( not ^ pass )
			tmp.push( r[i] );
	}
	return tmp;
}

function trim(s)
{
	return s.replace(/^\s*(.*?)\s*$/, "$1");
}

function loadImage(src)
{
	img = new Image();
	img.src = src;
	img.loop_index = 0;
	return img;
}

function loadXMLDoc(url, succes, fail)
{
    var req = null;
    // Create the request object; Microsoft failed to properly
    // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
    try
	{
        req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    } 
	catch(e)
	{}
    if (req)
	{
        req.onreadystatechange = function()
		{
            if (req.readyState ==4)
			{
                switch (req.status)
				{
                case 200:
                    if (typeof succes == 'function')
                        succes(req.responseText);
                    break;
                default:
                    if (typeof fail == 'function')
                        fail(req.status);
                }
            }
        };
        req.open("GET", url, true);
        req.send(null);
    }
    return (req ? true : false);
}

// ****
function imagesShowOnScroll(pos)
{
	var from = Math.floor((pos+20)/168);
	var to = Math.ceil((pos+328)/168);
	var elements = $('image-scrolled-page').getElementsByTagName('IMG');
}

function imagesShowOnScrollHorz(pos)
{
	var from = Math.floor((pos+20)/176);
	var to = Math.ceil((pos+860)/176);
	var elements = $('image-scrolled-page-horz').getElementsByTagName('IMG');
}

function searchTags(el)
{
	var text = trim(el.value).toLowerCase();
	
	var els = classFilter($('tag-serach').getElementsByTagName('DIV'), 'tag-list', false);
	if (!els)
		return true;
	var i=0;
	for (;i<els.length && !els[i].offsetWidth; i++);
	if (i == els.length)
		return true;
	els = els[i].getElementsByTagName('SPAN');
	for (var i=0; i<els.length; i++) {
		var s = els[i].firstChild.firstChild.nodeValue;
		if (s.toLowerCase().indexOf(text)>=0)
		{
			els[i].style.display = 'inline';
		} else
		{
			els[i].style.display = 'none';
		}
	}
	return true;
}

function swapTagsPanels(full)
{
	var els = $('tag-tabs').getElementsByTagName('a');
	els[0].className = full ? '' : 'current';
	els[1].className = full ? 'current' : '';
	$('full-tag-list').style.display = full ? 'block' : 'none';
	$('short-tag-list').style.display = full ? 'none' : 'block';
	$('tagQuickSearch').value = '';
	searchTags($('tagQuickSearch'));
	return false;
}

//  ****

function LoadImageComments(link, message, comments)
{
	var dropdown = document.createElement("DIV");
	var photo = dropdown.appendChild(document.createElement("DIV"));
	var comments = dropdown.appendChild(document.createElement("DIV"));
	var commentscomments = comments.appendChild(document.createElement("DIV"));
	var commentslink = comments.appendChild(document.createElement("A"));
	var frame = link.parentNode.parentNode;
	var imageScroller = frame.parentNode;
	while (imageScroller.id != 'image-scroller' && imageScroller.id != 'image-scroller-horz')
	{
		imageScroller = imageScroller.parentNode;
	}
	var imagePage = frame.parentNode;
	while (imagePage.id != 'image-scrolled-page' && imagePage.id != 'image-scrolled-page-horz')
	{
		if (imagePage.parentNode)
		{
			imagePage = imagePage.parentNode;
		}
		else
		{
			// для случая, когда ссылка нажата уже во всплывающем окне
			return true;
		}
	}
	
	var col = frame.offsetLeft + imagePage.offsetLeft - frame.offsetWidth*3;
	if (col < 0)
		col = 0;
	if (col > frame.offsetWidth)
		col = frame.offsetWidth;

	photo.className = 'photo';
	photo.style.width = (frame.offsetWidth - 2) + 'px';
	photo.style.left = col  + 'px';
	photo.innerHTML = frame.innerHTML;
	comments.className = 'comments';
	commentscomments.className = 'commentscomments';
	commentscomments.innerHTML = "<img src='/i/mediatech/ajax-loader-comments.gif' alt='loading…'>";
	commentslink.className = 'commentslink';
	commentslink.href = link.href;
	commentslink.appendChild(document.createTextNode("Перейти к просмотру фотографии"));
	dropdown.className = 'floatframe';
	dropdown.style.width = (frame.offsetWidth * 2) + 'px';
	dropdown.style.top = (frame.offsetTop + imagePage.offsetTop + 10).toString() + 'px';
	dropdown.style.left = (frame.offsetLeft + imagePage.offsetLeft + 10 - col).toString() + 'px';
	
	dropdown.onmouseout = function ()
	{
		var hidenElement = this;
		this.hideTimer = setTimeout(function () 
		{
			hidenElement = hidenElement.parentNode.removeChild(hidenElement);
			clearTimeout(hidenElement.hideTimer);
			hidenElement.hideTimer = false;
			hidenElement = false;
			hidenElement.onmouseout = false;
			hidenElement.onmouseover = false;
		}, 500);
	};
	dropdown.onmouseover = function ()
	{
		if (this.hideTimer)
		{
			clearTimeout(this.hideTimer);
			this.hideTimer = false;
		}
	};
	
	dropdown = imageScroller.appendChild(dropdown);
	
	loadXMLDoc('/ajax/mediatech-comments/?component=84&item='+message+'&uncache='+comments, function (responce)
	{
		commentscomments.style.textAlign = 'left';
		commentscomments.innerHTML = responce;
	}, function (error)
	{
		commentscomments.style.textAlign = 'left';
		commentscomments.innerHTML = "Ошибка загрузки комментариев";		
	});
	
	return false;
}

function prepareImageData(parent) //data, 
{
	parent.innerHTML = "<%Out(SetContent());%>";
}

function prepareImageDataHorz(data, parent)
{
	var S = "<table><tr>";
	for (lineNO in data)
	{
		line = data[lineNO];
		S += "<td class=\"item"+(line.current?' current':'')+"\"><a href=\""+line.href+"\" class=\"frame\">";
		S += "<img src=\"/i/mediatech/images/empty.gif\" alt=\""+line.alt+"\" title=\""+line.alt+"\" /></a>";
		if (line.text)
		{
			S += "<p><a href=\""+line.href+"\" "+
				(line.comments>0 ? "class='unreal' onclick=\"return LoadImageComments(this, "+line.message+", "+line.comments+");\"" : '' )+
				">"+line.text+"</a></p>";
		}
		S += "</td>";
	}
	parent.innerHTML = S + "</tr></table>";
}

function setImageScrollBar(scroll)
{
	var ScrollBar = new cScrollBar(
		classFilter(scroll.getElementsByTagName('DIV'), 'track', false)[0],
		classFilter(scroll.getElementsByTagName('A'), 'tracker', false)[0],
		{
			Length: $('image-scrolled-page').offsetHeight,
			Frame: 336,
			Line: 21,
			LinesInWhell: 4,
			ScrollElement: scroll,
			OnUpdate: function(pos)
			{
				$('image-scrolled-page').style.top = -Math.round(pos) + 'px';
				imagesShowOnScroll(pos);
			},
			OnInit: function()
			{
				this.BindAsArrowUp
				(
					classFilter(scroll.getElementsByTagName('A'), 'up', false)[0]
				);
				this.BindAsArrowDown
				(
					classFilter(scroll.getElementsByTagName('A'), 'down', false)[0]
				);
				this.BindAsScrolledPage
				(
					$('image-scrolled-box')
				);
				$('image-scrolled-box').style.overflow = 'hidden';
			}
		}
	);
	imagesShowOnScroll(0);
}

function setImageScrollBarHorz(scroll, pos)
{
	var ScrollBar = new cScrollBar(
		classFilter(scroll.getElementsByTagName('DIV'), 'track', false)[0],
		classFilter(scroll.getElementsByTagName('A'), 'tracker', false)[0],
		{
			Length: $('image-scrolled-page-horz').getElementsByTagName('TD').length * 176,
			Frame: 880,
			Line: 44,
			LinesInWhell: 4,
			ScrollElement: scroll,
			Horizontal: true,
			OnUpdate: function(pos)
			{
				$('image-scrolled-page-horz').style.left = -Math.round(pos) + 'px';
				imagesShowOnScrollHorz(pos);
			},
			OnInit: function()
			{
				this.BindAsArrowUp
				(
					classFilter(scroll.getElementsByTagName('A'), 'left', false)[0]
				);
				this.BindAsArrowDown
				(
					classFilter(scroll.getElementsByTagName('A'), 'right', false)[0]
				);
				this.BindAsScrolledPage
				(
					$('image-scrolled-box-horz')
				);
				$('image-scrolled-box-horz').style.overflow = 'hidden';
			}
		}
	);
	if (pos)
	{
		ScrollBar.ScrollTo(pos);
	} 
	else
	{
		imagesShowOnScrollHorz(0);
	}
}


function Dec1(str)
{
	var strResult = "";
	var i = 0;
	
	if (str == null)
		str = "";
	else
		str = String(str);
	
	while (i < str.length)
	{
		var ch = str.charAt(i);
		
		if (ch == "'")
		{
			strResult += "\\\'";
			i++;
		}
		else if (ch == "\"")
		{
			strResult += "\\\"";
			i++;
		}
		else if (ch == "%" && str.charAt(i+1) != "%")
		{
			strResult += unescape(str.substr(i,3));
			i += 3;
		}
		else
		{
			strResult += ch;
			i++;
		}
	}
	
	if (i < str.length)
		strResult += str.substr(i,str.length-i);
	
	//return unescape(strResult);
	return strResult;
}

function Dec2(str)
{
	var strResult = "";
	var i = 0;
	
	if (str == null)
		str = "";
	else
		str = String(str);
	
	while (i < str.length)
	{
		var ch = str.charAt(i);
		
		if (ch == "\\" && str.charAt(i+1) == "\'")
		{
			strResult += "'";
			i+=2;
		}
		else if (ch == "\\" && str.charAt(i+1) == "\"")
		{
			strResult += "\"";
			i+=2;
		}
		else
		{
			strResult += ch;
			i++;
		}
	}
	
	if (i < str.length)
		strResult += str.substr(i,str.length-i);
	
	//return unescape(strResult);
	return strResult;
	/*return unescape(str);*/
}
