/* onload */
/* type browser */
/* ajax */
/* form registration */
/* sessions and cookies */
/* menu/top */
/* show hide comments */
/* report moderator */
/* subscribe new comment */
/* fixpng */



/* onload */
// Onload functions init in this place
function addLoadEvent(func) { // Functions loader
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function(){
			oldonload();
			func();
		};
	}
}

if (window.selectFirst) {
	addLoadEvent(selectFirst);
}
/* /onload */



/* type browser */
var client = {};

client.whoBrouser = function() {
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf ( "MSIE " );
	var ieVer = parseInt (ua.substring (msie+5, ua.indexOf (".", msie )), 10);
	
	if (document.documentMode) {
		if (document.documentMode == 8) {
			ieVer = 8;
		} else if (document.documentMode == 7) {
			ieVer = 7;
		}
	}
	
	if (document.all && navigator.userAgent.indexOf("Opera")<0 && ieVer != 8) {
		return "ie";
	} else {
		return "normal";
	}
};

client.brouser = client.whoBrouser();
/* /type browser */



/* ajax */
var net = {};

net.Loader = function (url,onload,onerror,method,params,contentType) {
	this.req=null;
	this.onload=(onload)?onload:this.defaultOnload;
	this.onerror=(onerror)?onerror:this.defaultError;
	this.loadXMLDoc(url,method,params,contentType);
};

net.Loader.prototype = {
	loadXMLDoc:function(url,method,params,contentType){
		if (!method) {
			method="GET";
		}
		if (!contentType && method=="POST") {
			contentType='application/x-www-form-urlencoded'; 
		}
		if (window.XMLHttpRequest) {
			this.req=new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			this.req=new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (this.req) {
			try {
				var loader=this;
				this.req.onreadystatechange = function() {
					loader.onReadyState.call(loader);
				};
				this.req.open(method,url,true);
				if (contentType) {
					this.req.setRequestHeader("Content-Type", contentType);
					this.req.setRequestHeader("Content-length", params.length);  
					this.req.setRequestHeader("Connection", "close"); 
				}
				this.req.send(params);
			} catch (err) {
				this.onerror.call(this);
			}
		}
	},
	
	onReadyState:function(){
		var req=this.req;
		var ready=req.readyState;
		if (ready==4 && this.onload) {
			var httpStatus=req.status;
			if (httpStatus===200 || httpStatus===0) {
				this.onload.call(this);
			} else {
				this.onerror.call(this);
			}
		}
	},

	defaultOnload:function(){
	},
	
	defaultError:function(){
	}
};
/* /ajax */



/* form registration */
function registrationeFocus() {
	if (document.getElementById("reg-mail")) {
		document.getElementById("reg-mail").focus();
	}
}

addLoadEvent(registrationeFocus);

function setCookie(name,value,expires,path,domain,secure) {
	document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function registrationValidateSetGood(id) {
	var errorNode = document.getElementById(id).parentNode;
	if (errorNode.getElementsByTagName("span")[0]) {
		errorNode.removeChild(errorNode.getElementsByTagName("span")[0]);
		errorNode.className = "";
	}
}

function registrationValidateSetError(id,message) {
	var errorNode = document.getElementById(id).parentNode;
	var errorSpan = document.createElement("span");
	var errorMessage = document.createTextNode(message);
	if (errorNode.getElementsByTagName("span")[0]) {
		errorNode.removeChild(errorNode.getElementsByTagName("span")[0]);
	}
	errorSpan.appendChild(errorMessage);
	errorNode.className = "error";
	var myBefore;
	if (errorNode.getElementsByTagName("br")[0]) {
		myBefore = errorNode.getElementsByTagName("br")[0];
	} else {
		myBefore = errorNode.getElementsByTagName("input")[0];
	}
	errorNode.insertBefore(errorSpan,myBefore);
	errorNode.parentNode.parentNode.getElementsByTagName("input")[0].focus();
}

function registrationValidate(_form) {
	var requiredFields = ["reg-mail","reg-password","reg-repeat-password","reg-nick","reg-capcha"];
	var mySubmit = true;
	for (var i=0;i<requiredFields.length;i++) {
		if (document.getElementById(requiredFields[i])) {
			if (!document.getElementById(requiredFields[i]).value) {
				registrationValidateSetError(requiredFields[i],"(не заполнено)");
				mySubmit = false;
			} else {
				registrationValidateSetGood(requiredFields[i]);
			}
		}
	}
	if (document.getElementById("reg-mail").value.indexOf("@")<1) {
		registrationValidateSetError("reg-mail","(неправильно заполнено)");
		mySubmit = false;
	} else {
		registrationValidateSetGood("reg-mail");
	}
	if (document.getElementById("reg-password").value.length < 6) {
		registrationValidateSetError("reg-password","(пароль должен быть длинее 5-и символов)");
		mySubmit = false;
	} else {
		registrationValidateSetGood("reg-password");
	}
	if (document.getElementById("reg-password").value != document.getElementById("reg-repeat-password").value) {
		registrationValidateSetError("reg-repeat-password","(пароли не совпадают)");
		mySubmit = false;
	} else {
		registrationValidateSetGood("reg-repeat-password");
	}
	return mySubmit;
}
/* /form registration */



/* sessions and cookies */
function checkCookies() {
	//empty function for IE
	if (this.req.responseText) {
		var data=this.req.responseText.split(';');
		document.getElementById('auth_form').style.display='none';
		document.getElementById('auth_profile').style.display='block';
		document.getElementById('auth_name').innerHTML=data[1];
	}
}

function checkSession() {
	var nl = new net.Loader('/session?ssid='+authCookie+'&random='+Math.random(),checkCookies,null,"get",null,null);
}

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;
}
/* /sessions and cookies */



/* menu/top */
function spb_cmp_top_menu() {
	var menu = $('#spb_cmp_top_menu_hidden');
	
	if ($(menu).length > 0) {
		$('#spb_cmp_top_menu_add').empty();
		var lis = $('li', menu);
		
		for (var i=0; i<$(lis).length; i++) {
			var li = $($(lis).eq(i)).offset();
			if (li.top >= $(menu).height()) {
				$(lis).eq(i).clone().appendTo('#spb_cmp_top_menu_add');
			}
		}
	}
	
	return false;
}

function spb_cmp_top_menu_add() {
	spb_cmp_top_menu();
	
	var obj = $('#spb_cmp_top_menu_add');
	
	if ($(obj).length > 0) {
		if ($(obj).css('display') == 'block') {
			$(obj).hide();
		} else {
			if ($('li', obj).length > 0) {
				$(obj).css({display: 'block', margin: '0.4em 0 0 -87px'});
			}
		}
	}
	
	return false;
}
/* /menu/top */



/* show hide comments */
function spb_cmp_reel_comms_show(box_id, style_obj, style_show_name, style_hide_name) {
	var now = new Date();
	var expire = new Date(now.getTime() + 3600000);
	
	var obj = document.getElementById(box_id);
	if (obj.style.display == 'block' || obj.style.display == '') {
		document.cookie = 'sportbox_comments_number=1; path=/; domain=.sportbox.ru; expires='+expire.toGMTString();
		
		style_obj.className = style_hide_name;
		obj.style.display = 'none';
	} else {
		document.cookie = 'sportbox_comments_number=0; path=/; domain=.sportbox.ru; expires='+now.toGMTString();
		
		style_obj.className = style_show_name;
		obj.style.display = 'block';
	}
}
/* /show hide comments */



/* report moderator */
function closeComplainBox() {
	$('#complainBox').remove();
}

function finishComplainBox() {
	$('#complainBox').html("<div style=\"padding: 10px\">"+ window.complainLoader.req.responseText+"</div><div style=\"padding: 10px\">Ваше сообщение отправлено и в ближайшее время будет рассмотрено модератором</div>");
	setTimeout(closeComplainBox, 3000);
}

function sendComplain( topicId, postId ) {
	var text = $('#complainTextBox').val();
	var url = "/ipbmakecomments?do=complain&act=report&send=1&t="+topicId+"&p="+postId+"&text="+text;
	window.complainLoader = new net.Loader(url,finishComplainBox,null,"get",null,null);
}

function showComplainBox( callerObj, topicId, postId ) {
	closeComplainBox();
	
	var bounds = $(callerObj).offset();
	var dom_bdiv = $('<div id="complainBox" class="complain-box"></div>').css({left :  bounds.left +"px" , top: bounds.top + 15 + "px"});
	
	$('<span class="spb_user_iface_pointer-box" style="float: right; cursor: pointer"> x </span>').click(function(){closeComplainBox();}).appendTo(dom_bdiv);
	
	dom_bdiv.append(" Введите причину жалобы: ");
	
	$('<textarea id="complainTextBox" class="complain-box-textarea"></textarea>').appendTo(dom_bdiv);
	$('<input type="button" value="Пожаловаться" />').click(function(){sendComplain(topicId, postId);}).appendTo(dom_bdiv);
	
	$('body').append(dom_bdiv);
	
	$('#complainTextBox').focus();
	
	return false;
}

function commentsQuickReplyClick( text ) {
	var bounds = $('#commenttext_field').val(text).focus().offset();
	window.scrollTo(0,bounds.top);
	return false;
}
/* /report moderator */



/* subscribe new comment */
var commentsSubscribeLinkObj;
var commentsSubscribeSubscribeTxt;
var commentsSubscribeUnSubscribeTxt;

function closeCommentsSubscribeBox() {
	if ( document.getElementById('subscribeBox') ) {
		$('#subscribeBox').remove();
	}
}

function finishCommentsSubscribe() {
	closeCommentsSubscribeBox();
	
	var linkVal = commentsSubscribeLinkObj.innerHTML;
	
	if ( linkVal == commentsSubscribeSubscribeTxt ) {
		commentsSubscribeLinkObj.innerHTML = commentsSubscribeUnSubscribeTxt;
	} else if ( linkVal == commentsSubscribeUnSubscribeTxt ) {
		commentsSubscribeLinkObj.innerHTML = commentsSubscribeSubscribeTxt;
	}
	
	
	var bounds = $(commentsSubscribeLinkObj).offset();
	
	$('<div id="subscribeBox" class="complain-box"></div>')
		.css({left: bounds.left + "px", top: bounds.top + $(commentsSubscribeLinkObj).height() + "px"})
		.html('<div style="padding: 10px">'+window.subLoader.req.responseText+'</div>')
		.appendTo('body');
	
	
	setTimeout(closeCommentsSubscribeBox, 3000);
}

function doCommentsSubscribe( callerObj, topicId, subscribeTxt, unsubscribeTxt ) {
	if( !topicId ){
		return "";
	}
	
	commentsSubscribeLinkObj = callerObj;
	commentsSubscribeSubscribeTxt = subscribeTxt;
	commentsSubscribeUnSubscribeTxt = unsubscribeTxt;
	window.subLoader=new net.Loader("/ipbmakecomments?do=subscribe&t="+topicId+"&random="+Math.random(),finishCommentsSubscribe,null,"get",null,null);
}
/* /subscribe new comment */



/* fixpng */
function sb_js_cmn_fixPng(element) {
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
		var src;
		
		if (element.tagName=='IMG') {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = "/d/0/img/s/sb/g/other/pix.gif";
			}
		} else {
			src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage="none";
			}
		}
		
		if (src) {
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='crop')";
		}
	}
}
/* /fixpng */