$(document).ready(function(){
	makeTableRowsHiglightableInMSIE();
	loadProfile(0);
	loadVoters();

	$.validator.setDefaults({
		highlight: function(input) {
			$(input).addClass("ui-state-highlight");
		},
		unhighlight: function(input) {
			$(input).removeClass("ui-state-highlight");
		}
	});

	$(".comments-item").hover(function() {
			rowid=$(this).attr('id');
			var pos = rowid.indexOf('row-');
			var id = rowid.substring(pos+4);
			$('div#comments-buttons-'+id).show();
		}, function() {
			rowid=$(this).attr('id');
			var pos = rowid.indexOf('row-');
			var id = rowid.substring(pos+4);
			$('div#comments-buttons-'+id).hide();
		}
	);
});

function otherResize(){
		var wrap = $('#wrap');
		var maxHeight = 0;

		$('.middle')
		.css('min-height', 0)
		.find('.content').each(function()
		{
			var height = $(this).height();

			if (maxHeight < height)
				maxHeight = height;
		}).end()
		.css('min-height', maxHeight).css('min-height', wrap.height());
}

$(function() {
	$('.resume-link').click(function() {
		var el = $(this).parent().next();
		if ('none' == el.css('display')) {
			el.show();
			$(this).addClass('resume-link-selected');
			$(this).text('Скрыть комментарии');
		} else {
			el.hide();
			$(this).removeClass('resume-link-selected');
			$(this).text('Показать все комментарии');
		}
	});
	$('.search-link').click(function() {
		var el = $(this).parent().next();
		if ('none' == el.css('display')) {
			el.show();
			$(this).addClass('resume-link-selected');
			$(this).text('Скрыть форму поиска');
		} else {
			el.hide();
			$(this).removeClass('resume-link-selected');
			$(this).text('Показать форму поиска');
		}
	});
	$('.showform-link').click(function() {
		var el = $(this).next();
		if ('none' == el.css('display')) {
			$(this).hide();
			el.show();
		}
	});
	$('.show-link').click(function() {
		var el = $(this).next();
		if ('none' == el.css('display')) {
			el.show;
			$(this).text('Скрыть пояснения');
		} else {
			el.hide;
			$(this).text('Зачем мне регистрироваться?');
		}
	});
});

function makeTableRowsHiglightableInMSIE() {
	if ( document.all && !window.opera ) {
		for (var iTableIdx = 0; (oTable = document.getElementsByTagName('table')[iTableIdx]); iTableIdx++) {
			if (cmnMatch_class(oTable, 'html')) {
				for (var iRowIdx = 0; (oRow = oTable.getElementsByTagName('tr')[iRowIdx]); iRowIdx++) {
					oRow.onmouseover = function() { cmnSet_class(this, 'hover'); }
					oRow.onmouseout = function() { cmnRemove_class(this, 'hover'); }
				}
			}
		}
	}
}

//cmnAdd_event(window, 'load', makeTableRowsHiglightableInMSIE);

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			if(arrReturnElements.push){
				arrReturnElements.push(oElement);
			}
		}
	}
	return (arrReturnElements)
}

function fix_page_footer() {
	if ( window.resizeBy && window.innerWidth && window.innerWidth < screen.width ){
		window.resizeBy( -1, 0 );
		setTimeout( "window.resizeBy( 1, 0 )", 100 );
	}
}

function loadProfile( doAnimate )
{
	if(doAnimate){
		animateFavorites('add');
		window.setTimeout(doLoadProfile, 1300);
	}else{
		doLoadProfile();
	}
}

function doLoadProfile()
{
	var authCookie = readCookie('session_id');

    if(authCookie != null && authCookie.length > 3){
		if($('div#ProfileHead')){
			$.ajax({
				url: '/index.php?act=Login&CODE=02&sid='+authCookie,
				type: 'GET',
				dataType: 'xml',
				cache: false,
				timeout: 60000,
				 success: function(xml) {
					showLoadedProfile($(xml));
				},
				error: function() {

				}
			});
		}
	}else{
		showUnathorized();
	}
}

function getRandom( total ){
	return(Math.floor(Math.random() * total) + 1);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function showLoadedProfile(xml)
{
	var isAuthorized = $(xml).find('auth').text();

	if(isAuthorized == 1){
		var userEmail = $(xml).find('login').text();
		var userName = userEmail.substring(0, userEmail.indexOf('@'));
		if(!userName) userName = userEmail;

		var pageDomain = getLinkStart();
		var url = getCleanUrl();
		var addToFavorites = 1;

		var favoritesHead = '<div id="favoritesBlock"><DIV class=content><H2><img class="ico" src="/f/1/global/i-favorite.gif" id="profileImg" />Избранное<a href="" class="pseudo_link" href="" onclick="toggleFavoritesBlock(); return false;"><img class="ico" src="/f/1/global/menu-close.gif" /></a></H2><dl class="fav-row">';
		var favoritesFooter = '</dl></noindex></DIV></div>';
		var favorites = '';
		var favoritesFound = false;
		var i =0;
		$(xml).find('page').each(function() {
			var href = $(this).attr('href').replace(/#/gi, "&");
			favoritesFound = true;
			if(url != href){
				favorites += '<dt id="fav-row-'+ i +'">';
				favorites += '<span class="fav-delete"><a href="" onclick="removeFromFavoriteByHref(\''+ href + '\',' + i +'); return false;" class="delete"><img src="/f/1/global/i-delete-r.gif" width="7" height="7" /></a></span>';
				favorites += '<a href="' + href + '" class="fav-link">' + $(this).attr('title') +  '</a>';
				favorites += '</dt>';
			}else{
				addToFavorites = 0;
				favorites += '<dt id="fav-row-'+ i +'" class="selected">';
				favorites += '<span class="fav-delete"><a href="" onclick="removeFromFavoriteByHref(\''+ href + '\',' + i +'); return false;" class="delete"><img src="/f/1/global/i-delete-r.gif" width="7" height="7" /></a></span>';
				favorites += $(this).attr('title')+ '</dt>';
			}
			i++;
		});

		if(!favoritesFound){
			favorites += '<p id="favoritesNotFound">Здесь будут перечислены разделы, которые вы добавите в&#160;избранное (значок сердечка рядом с&#160;заголовком)</p>';
		}

		var body = '';
		if(getCleanUrl() == '/index.php?act=Profile')
			body = '<li><img class="ico" src="/f/1/global/i-profile.gif"><a href="'+pageDomain+'" id="profileLink">' + userName + '</a>&#160;<a href="'+pageDomain+'" id="logoutLink" onclick="mainDeauthorize(); return false;"><img class="ico" src="/f/1/i/i-logout.gif" /></a></li>';
		else {
			var pageDomain = getDomain();
			body = '<li><img class="ico" src="/f/1/global/i-profile.gif"><a class="pseudo_link" href="'+pageDomain+'index.php?act=Profile">' + userName + '</a>&#160;<a href="'+pageDomain+'" id="logoutLink" onclick="mainDeauthorize(); return false;"><img class="ico2" src="/f/1/i/i-logout.gif"  title="Выход"/></a></li><li>' + favoritesHead + favorites + favoritesFooter + '<img class="ico" src="/f/1/global/i-favorite.gif" id="profileImg" /><a class="pseudo_link" href="" onclick="toggleFavoritesBlock(); return false;" id="favoritesListLink">Избранное</a></li>';
             }
		$('div#ProfileHead').html(body);

		if(addToFavorites)
			showAddToFavorites();
		else
			showRemoveFromFavorites();
	}else{
		showUnathorized();
	}
}

function showUnathorized()
{
	var body = '';
	var pageDomain = getLinkStart();
    var authDescriptionLink = '<H2><img class="ico" src="/f/1/i/i-lock-b.gif">Авторизация</H2>';
	var authTable = '<DIV class=content><LOGIN>' + authDescriptionLink + '<form onsubmit="return mainAuthorize()" action="'+pageDomain+' method="POST"><input type="hidden" name="auth.logon" value="1"><input type="hidden" name="script" value="2"><DL class=row><DT><LABEL for=fld-p-signin-login>Логин</LABEL></DT><DD class=field><INPUT id=fld-p-signin-login type=text name=auth.name></DD></DL><DL class=row><DT><LABEL for=fld-p-signin-password>Пароль</LABEL></DT><DD class=field><INPUT id=fld-p-signin-password type=password name=auth.passwd></DD></DL><DL class="row checkbox"><DD class=field><INPUT id=fld-p-signin-remember value=true type=checkbox name=auth.persistent><LABEL for=fld-p-signin-remember>запомнить меня</LABEL></DD></DL><DL class=row><DD class=field><DIV class="panel button_panel item_panel"><SPAN class=p_container><SPAN class=p_content><INPUT id=authBtnSubmit value=Готово type=submit></SPAN></SPAN></DIV></DD></DL>';
	var authBottomLinks = '<DIV class=close><a href="" onclick="hideAuthorizationBlock(); return false;"><img src="/f/1/global/menu-close.gif" /></a></DIV></LOGIN>';
	var authBlock = '<div id=signin_panel>'+ authTable + authBottomLinks + '</div>';

	if(getCleanUrl() != '/index.php?act=Profile')  {
		body = '<li class="item panel button_panel signin"><img class="ico" src="/f/1/i/i-lock-b.gif" id="profileImg" /><a class="pseudo_link" href="" style="z-index: 22;" onclick="showAuthorizationBlock(); return false;">Авторизация</a></li><li class="item panel button_panel signin"><a class="pseudo_link" href="'+pageDomain+'index.php?act=Reg">Регистрация</a></li>'+ authBlock;
	}
	else
		body = '<table id="profile-unauth"><tr><td><img src="/f/1/i/i-lock-b.gif" id="profileImg" />Личный кабинет</td></tr></table>';
	$('div#ProfileHead').html(body);
}

var fav_state = 0

function showAuthorizationBlock()
{
	$('#signin_panel').show();
	window.setTimeout(authFocus, 0);

}

function authFocus()
{
	//$('#authName').focus();
}

function hideAuthorizationBlock()
{
	$('#signin_panel').hide();

}

function mainAuthorize()
{
	$('#authBtnSubmit').attr('disabled', 'disabled');
	var persistent = $('#fld-p-signin-remember:checked').length;
	$.ajax({
		url: '/index.php?act=Login&CODE=01&logon=1&name='+$('#fld-p-signin-login').val()+'&passwd='+$('#fld-p-signin-password').val()+'&persistent='+persistent,
		type: 'POST',
		dataType: 'xml',
		cache: false,
		timeout: 20000,
		success: function(xml) {
			mainAuthorizeResultCheck($(xml));
		},

		error: function() {
			$('#authBtnSubmit').attr('disabled', '');
		}
	});
	return false;
}

function mainDeauthorize()
{
	var pageHref = '';

	$.ajax({
		url: '/index.php?act=Login&CODE=03',
		type: 'POST',
		dataType: 'xml',
		cache: false,
		timeout: 20000,
		success: function(xml) {
			pageHref = getCleanUrl();
			if(pageHref != '/index.php?act=Profile')
				window.location = getCleanUrl();
			else
				window.location = "/";
		},
		error: function() {

		}
	});
	return false;
}

function mainAuthorizeResultCheck(xml)
{
	var status = $(xml).find('response-status').text();

	if(status == 1){
		shakeWindow();
		$('#authPasswd').val('');
		$('#authBtnSubmit').attr('disabled', '');
	}else{
		$('#ProfileHead').fadeOut('fast');
		window.location = getCleanUrl();
	}
}


function shakeWindow()
{
	var limit = 5;
	var defaultOffset = -17;
	var time = 20;
	$('#signin_panel').animate({marginLeft: "-"+ limit +"px"}, (time/2)).animate({marginLeft: limit + "px"}, time).animate({marginLeft: "-"+ limit +"px"}, time).animate({marginLeft: limit + "px"}, time).animate({marginLeft: "-"+ limit +"px"}, time).animate({marginLeft: "-2 px"}, (time / 2));
}

function toggleFavoritesBlock()
{
	if(fav_state == 0){
		$('#favoritesBlock').show();
		fav_state = 1;
		if($.browser.msie){
			$('#favoriteOpenerLink').hide();
		}
	}
	else{
		$('#favoritesBlock').hide();
		fav_state = 0;
		if($.browser.msie){
			$('#favoriteOpenerLink').show();
		}
	}
}

function getLinkStart( hideSlash )
{
	var linkStart = '';
	var pageDomain = getDomain();

	if(pageDomain != 'https://www.sgs1.ru/' && pageDomain != 'https://sgs1.ru/'){
		linkStart = 'http://www.sgs1.ru/';
	}else{
		linkStart = '/';
	}

	if(hideSlash){
		linkStart = linkStart.substring(0, linkStart.length - 1);
	}
	return (linkStart);
}

function getCleanUrl()
{
	var url = document.URL;
	var pos = url.indexOf('//');
	url = url.substring(pos+2);
	pos = url.indexOf('/');
	url = url.substring(pos);

	var pageDomain = getDomain();

	return (url);
}

function getDomain()
{
	var url = document.URL;
	var pos = url.indexOf('//');
	var urlN = url.substring(pos+2);
	var pos2 = urlN.indexOf('/');
	var domain = url.substring(0, (pos+pos2+3));

	return (domain);
}

function showAddToFavorites()
{
	$('#AddFavorite').html('<a href="" id="addFavoriteLink" onclick="addToFavorite(); return false;"><img src="/f/1/global/i-add-favorite.gif" /></a>');
	$('#AddFavorite').show();
}

function addToFavorite()
{
	var authCookie = readCookie('session_id');

    if(authCookie != null && authCookie.length > 3){
    	var pageTitle = getCleanTitle();
		var pageHref = getCleanUrl();

		$.post('/index.php?act=Login&CODE=07&sid='+authCookie,{
			path: pageHref,
			title: pageTitle
		},
		function(){
			showRemoveFromFavorites();
			loadProfile(1);
		});
    }
}

function removeFromFavorite()
{
    var authCookie = readCookie('session_id');

    if(authCookie != null && authCookie.length > 3){
    	var pageHref = getCleanUrl();

		$.post('/index.php?act=Login&CODE=08&sid='+authCookie,{
			path: pageHref
		},
		function(){
			showAddToFavorites();
			animateFavorites('remove');
		});
	}
}

function removeFromFavoriteByHref( pageHref, id )
{
	var authCookie = readCookie('session_id');
	$.post('/index.php?act=Login&CODE=08&sid='+authCookie,{
		path: pageHref
	},
	function(){
		$('dt#fav-row-' + id).hide();
	});
}

function getCleanTitle()
{
	var pageTitle = $('title').html();

	return(pageTitle);
}

function animateFavorites( state )
{
	if(state == 'add' || fav_state != 1){
		$('#favoritesListLink').css('color', '#FFFFFF');
		$('#favoritesListLink').css('background-color', '#EF3124');
		$('#favoritesListLink').css('font-weight', 'bold');
	}

	if(state == 'add'){
		if(fav_state == 1){
			$('div#favoritesBlock').hide();
			fav_state = 0;
		}
		$('#favoritesListLink').animate({opacity: 0}, 200 ).animate({opacity: 1}, 200 ).animate({opacity: 0}, 200 ).animate({opacity: 1}, 200);
		window.setTimeout(stopAnimateFavorites, 1400);
	}
	else{
		if(fav_state == 1){
			$('div#favoritesBlock dt.selected').css('color', '#EF3124');
			$('div#favoritesBlock dt.selected').css('background-color', '#FFFFFF');
			$('div#favoritesBlock dt.selected').fadeOut('slow');
		}else{
			$('#favoritesListLink').animate({opacity: 0}, 1300 ).animate({opacity: 1}, 100);
			window.setTimeout(stopAnimateFavorites, 1300);
			window.setTimeout(reloadProfile, 1400);
		}
	}
}

function stopAnimateFavorites()
{
	$('#favoritesListLink').css('color', '#08628C');
	$('#favoritesListLink').css('font-weight', 'normal');
	$('#favoritesListLink').css('background-color', '#FFFFFF');
}

function reloadProfile()
{
	loadProfile(0);
}

function showRemoveFromFavorites()
{
	$('#AddFavorite').html('<a href="" id="addFavoriteLink" onclick="removeFromFavorite(); return false;"><img src="/f/1/global/i-remove-favorite.gif" /></a>');
	$('#AddFavorite').show();
}

function getParam(paramName)
{
	var url=document.URL.replace(paramName,'');
	if ((left=url.indexOf('?='))<0) if ((left=url.indexOf('&='))<0) return '';
	return (right=url.indexOf('&',left+1))<0?url.substr(left+2):url.substr(left+2,right-left-2);
}

function loadVoters()
{
	domain = getParam("act");
	if (domain == "") domain = "Main"

	$.post('/index.php?act=Vote&CODE=10',{
		module: domain
	},
	function(data) {
		$('div#VoteHead').html(data);
		$('#voteBtnSubmit').attr('disabled', 'disabled');
	});
}

function chkRadio(form, value)
{
	chvote = value;
	$('#voteBtnSubmit').attr('disabled', '');
}

function getVoteResult()
{
    domain = getParam("act");
	if (domain == "") domain = "Main"

	$.post('/index.php?act=Vote&CODE=11',{
		choice: chvote,
		module: domain
	},
	function(){
		loadVoters();
	});
}

function textarea_step_add(textAr)	{
	if(textAr.rows != 8){
		textAr.rows=8;
	}
	else {
		return true
	}
}
function removeComment(id, module)
{
	$.post('/index.php?act='+module+'&CODE=11',{
		comment: id
	},
	function(data){
		$('DIV#comm-row-' + id).css('color', '#EF3124');
		$('DIV#comm-row-' + id).css('background-color', '#FFFFFF');
		$('DIV#comm-row-' + id).fadeOut('slow');
		$('#comment-count').html(data);
	});
}

function getVoteComment(value, choice, module)
{
    $.post('/index.php?act='+module+'&CODE=12',{
		table_id: value,
		choice: choice
	},
	function(data){
		$('div#comments-buttons-'+value).html(data);
	});
}
function closeForm()
{
	$('#show-form').hide();
	$('.showform-link').show();
}

function createIFrame() {
	var id = 'f' + Math.floor(Math.random() * 99999);
	var div = document.createElement('div');
	div.innerHTML = '<iframe style="display:none" src="about:blank" id="'+id+'" name="'+id+'" onload="sendComplete(\''+id+'\')"></iframe>';
	document.body.appendChild(div);
	return document.getElementById(id);
}
function getIFrameXML(iframe) {
	var doc=iframe.contentDocument;
	if (!doc && iframe.contentWindow) doc=iframe.contentWindow.document;
	if (!doc) doc=window.frames[iframe.id].document;
	if (!doc) return null;
	if (doc.location=="about:blank") return null;
	if (doc.XMLDocument) doc=doc.XMLDocument;
	return doc;
}
function sendComplete(id) {
	var iframe=document.getElementById(id);
	if (iframe.onSendComplete && typeof(iframe.onSendComplete) == 'function')
	iframe.onSendComplete();
}
function createElement(name, attrs, style, text, parent) {	var e = document.createElement(name);
	if (attrs) {		for (key in attrs) {			if (key == 'class') {				e.className = attrs[key];
			} else if (key == 'id') {				e.id = attrs[key];
			} else {				e.setAttribute(key, attrs[key]);
			}
		}
	}
	if (style) {		for (key in style) {			e.style[key] = style[key];
		}
	}
	if (text) {		e.appendChild(document.createTextNode(text));
	}
	parent.appendChild(e);
}
function ShowSmilieBox(fid) {
	if (fid) $('#smiliebox'+fid).show();
	else $('#smiliebox').show();
}

function CloseSmilieBox(fid) {
	if (fid) $('#smiliebox'+fid).hide();
	else $('#smiliebox').hide();
}

function emoticon(code, fid) {	id = 'commentForm' + fid;
	form=document.getElementById(id);
	form.comment.value += ' '+code+' ';
	form.comment.focus();
}
