var sUsername = '';
var jLinkAnswer = null;
var jPostAnswer = null;
var iPostFiles = 0;
var oWaiting = null;
var cursorX=0;
var cursorY=0;
var sel=0;

//$(document).ready(function(){
//	setTimeout(function(){if(quizData.voted == 0){$('#quiz_ref').click()}},1000);
//});

// autorun
$(function(){
 	oValidator.validateAll();
//	$(".ankor").each(function(i){
//		this.name = 'p' + this.name;
//	});
//	// $(".forum_block.posts").ScrollToAnchors(500);
	var sAnkor = window.location.href.split('#')[1];
	if(sAnkor && sAnkor.substr(0,1) == 'p'){
		sAnkor = sAnkor.substr(1);
		$('#'+sAnkor).parents('.post').addClass('full');
		$('#'+sAnkor).addClass('full');
	}
	
	if(sUsername!=''){
		$('div.username span').html(sUsername);
		$('.logout').show();
	}else{
		$('.logging_container').show();
	}
	
	oStarvoter = new Starvoter({count:5, width:28, height:25, src:'/_img/starb.gif', class_name:'stars_b', ajax:'/vote.html'});
	oStarvoterBD = new Starvoter({count:5, width:28, height:25, src:'/_img/starb.gif', class_name:'stars_bd', ajax:'/vote.html', hide_empty: 1});
	oStarvoterM = new Starvoter({count:5, width:18, height:18, src:'/_img/starm.gif', class_name:'stars_m', ajax:'/vote.html', hide_empty: 1});
		
 });

var Common = {
	Cookie:{
		set : function(sName, sValue, sPath, sExpire) {
			document.cookie = sName + '=' + (window.encodeURI? encodeURI(sValue) : escape(sValue)) +
				((sExpire == null)? '' : ('; expires=' + sExpire.toGMTString())) +
				((sPath == null)? '' : ('; path=' + sPath));
		},
		get : function(sName) {
			var sSearch = sName + '=';
			if(document.cookie.length > 0) {
				var iOffset = document.cookie.indexOf(sSearch);
				if(iOffset != -1) {
					iOffset += sSearch.length;
					var iEnd = document.cookie.indexOf(';', iOffset);
					if(iEnd == -1) {
						iEnd = document.cookie.length;
					}
					return window.decodeURI?
						decodeURI(document.cookie.substring(iOffset, iEnd)):
						unescape(document.cookie.substring(iOffset, iEnd));
				}
			}
			return '';
		}
	}
};

function onHsDisplay(){
	if($.browser.mozilla){
		oStarvoterB = new Starvoter({count:5, width:28, height:25, src:'/_img/starb.gif', class_name:'stars_b', ajax:'/vote.html'});
	}
}

function collapseAnswer(){
	if(jPostAnswer){
		jPostAnswer.hide();
		jPostAnswer = null;
	}
	if(jLinkAnswer) jLinkAnswer.removeClass('selected');
}

function doAnswer(obj){
//	if(sUsername==''){
//		oWaiting = obj;
//		showLoginForm();
//	} else {
		if(obj.className != 'jslink' && obj.className != 'button'){	
			collapseAnswer();
		} else {
			collapseAnswer();
			jPostAnswer = $('.post_answer', obj.parentNode);
			jLinkAnswer = $(obj);
			var sAnswer = $('#template_answer').html();
	//		jPostAnswer.html(sAnswer).SlideInUp(500);
			jPostAnswer.html(sAnswer).show();
			var id = obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
			jPostAnswer.find('#parent_id').val(id);
			jLinkAnswer.addClass('selected');
			iPostFiles = 0;
		}
//	}
	return false;
}

function doEdit(obj){
	if(obj.className != 'jslink' && obj.className != 'button'){
		collapseAnswer();
	} else {
		collapseAnswer();
		jPostAnswer = $('.post_edit', obj.parentNode);
		jLinkAnswer = $(obj);
		var sAnswer = $('#template_edit').html();
//		jPostAnswer.html(sAnswer).SlideInUp(500);
		jPostAnswer.html(sAnswer).show();
		var id = obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
		var sName = $(obj.parentNode).find('.for_edit_name').html();
		var sText = $(obj.parentNode).find('.for_edit_text').val();
		jPostAnswer.find('#id').val(id);
		jPostAnswer.find('#post_name').val(sName);
		jPostAnswer.find('#post_text').val(sText);
		jLinkAnswer.addClass('selected');
	}
	return false;
}


function doLink(obj){
	if(obj.className != 'jslink'){	
		collapseAnswer();
	} else {
		collapseAnswer();
		jPostAnswer = $('.post_link', obj.parentNode);
		jLinkAnswer = $(obj);
		var sAnswer = $('#template_link').html();
		jPostAnswer.html(sAnswer).show();
		var x = jPostAnswer.find('#link').get()[0];
		x.focus();
		x.select();		
		var id = obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
		var jPALink = jPostAnswer.find('#link');
		jPALink.val(window.location.href.split('#')[0] + '#p' + id);
		jLinkAnswer.addClass('selected');
	}
	return false;
}

function checkPost(obj){
	if($(obj).find('#post_name').val() || $(obj).find('#post_text').val() ){
		$('form input').each(function(){
			if(this.className.substr(0,2)=='ah'){
				var i=this.className.substr(3);
				if(!aGN[i]){this.value=''}
			}
		});
		return true;
	}{
		return false;
	}
}

function addFile(obj){
	if(iPostFiles<10){
		var html = $('#template_file').html();	
		re1 = /(file_caption)/g;
		re2 = /(file_file)/g;
		var i = Math.round(Math.random()*10000);
		html = html.replace(re1, "$1_"+i);
		html = html.replace(re2, "$1_"+i);
		$('.files_container', obj.parentNode).append(html);
		iPostFiles = iPostFiles + 1;
	}
	return false;
}

function removeFile(obj){
	obj.parentNode.parentNode.removeChild(obj.parentNode);
	iPostFiles = iPostFiles - 1;
}

function switchPost(obj){
	$(obj.parentNode.parentNode).toggleClass('full');
	return false;
}

function expandAll(){
	$('.post').addClass('full');
	$('#exp_all').hide();
	$('#col_all').show();
	return false;
}

function collapseAll(){
	$('.post').removeClass('full');
	$('#exp_all').show();
	$('#col_all').hide();
	return false;
}

function showLoginForm(){
	$('#login_form').show();
}

function hideLoginForm(){
	gotoLogin();
	$('dl.error dd').hide();
	$('dl.error_reg dd').hide();
	$('#login_form').hide();
	return false;
}

function gotoRegistration(){
	$('form#login').hide();
	$('form#register').show();
}
function gotoLogin(){
	$('form#login').show();
	$('form#register').hide();
}

function loginOk(data){
	if(data.length < 4){
		if(data=='md'){
					hideLoginForm();
					parent.window.location = '/';
				} else {
					sUsername = $("#auth-name").val();
					hideLoginForm();
					parent.window.location = '/';
//					if(oWaiting){doAnswer(oWaiting)};
//					$('div.username span').html(sUsername);
//					$('.logging_container').hide();
//					$('.logout').show();
				}			
	} else {
		$('dl.error dd').show();
	}
}

var aGN = {1:1,3:1,19:1,21:1,27:1,37:1,39:1,44:1,45:1,47:1,49:1,50:1,52:1,64:1,65:1,69:1,72:1,75:1,83:1,86:1,92:1,93:1,95:1,99:1,101:1,102:1,106:1,109:1,112:1,116:1,118:1,125:1,140:1,149:1,150:1,157:1,160:1,162:1,166:1,167:1,177:1,178:1,179:1,180:1,182:1,184:1,186:1,191:1,193:1,197:1}

function registerError(log){
	$('#rSubmitBlock input').each(function(){this.disabled = false});
	$('#formerror').html('ник '+log+' уже существует')
}

function loginError(){
	$('#submitBlock input').each(function(){this.disabled = false});
	$('#loginerror').html('неверная пара логин и пароль')
}

function registerOk(){
	reloadPage();
}

function initCoverBaby(){
	$('div.Radios input').click(function(){
		var collect=$(this).attr('collection');
		$('#cover_submit_'+collect)[0].disabled = false
	}).each(function(){
		this.checked = false;
	});
}

function voteBaby(){
	var id = 0;
	$('.CoverInput').each(function(){
		if(this.checked){id = this.value}
	});
	$.get('/vote.html',{table:'cover_baby', id: id}, function(data){
		$('#choose_cover').html(data);
	});
}

function voteBabyMom(){
	var id = 0;
	$('.CoverInput').each(function(){
		if(this.checked){id = this.value}
	});
	$.get('/vote.html',{table:'cover_baby_mom', id: id}, function(data){
		$('#choose_cover').html(data);
	});
}

function voteTop(){
	var id = 0;
	$('div.RegMessage table input').each(function(){
		if(this.checked){
			if(this.value != 'on'){id = id+','+this.value}
//				id = this.value
		}
	});	
	$.get('/vote.html',{table:'poll_question', id: id}, function(data){
		quizData.voted = 1;
		oQuiz.p.data.voted = 1;
		oQuiz.p.data.poll_count = data.poll_count.split(',');
		oQuiz.p.data.poll_percent = data.poll_percent.split(',');
		$('div.quiz_text').html(oQuiz.buildHtml());
		var content = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div><div class="quiz_text">'+oQuiz.buildHtml()+'</div></div>';
		oQuiz.str = Onlyweb.Messages.generateHtml(content);
		
	},"json");
}

function mailformSubmit(){
	var sMailFormError = oValidator.checkSubmit($('#mailform'));
	$('#rSubmitBlock input').each(function(){this.disabled = true});
	if(sMailFormError!=''){
		alert(sMailFormError);
		$('#rSubmitBlock input').each(function(){this.disabled = false});
		return false;
	}
	$('#submitbutton')[0].disabled = true;
	$('#sendimg').show();
	$.get("/sendmail.html",
  { to_email:$('#to_email').val(),
  	from_email:$('#from_email').val(),
  	link_url:$('#link_url').val(),
  	mail_message:escape($('#mail_message').val()),
 		spec_key:$('#spec_key').val()},
  function(data){
		if(data=='mailok\n'){registerOk()};
		if(data=='keyerror\n'){KeyError()};
		if(data=='notallfields\n'){FieldsError()};
		$('#sendimg').hide();
	}
);
}

function KeyError(){
	$('#submitBlock input').each(function(){this.disabled = false});
	$('#mail_form_error').html('*контрольные цифры не совпадают')
}

function FieldsError(){
	$('#submitBlock input').each(function(){this.disabled = false});
	$('#mail_form_error').html('*не все обязательные поля заполнены');
}

function formSubmit(){
	$('#submitBlock input').each(function(){this.disabled = true});
	if($('#fl_login').val()==''){
		$('#submitBlock input').each(function(){this.disabled = false});
		return false;
	}
	$.post("/logon/update.html",
  { fl_login:escape($('#fl_login').val()),
  	fl_pas:escape($('#fl_pas').val()),
  	cmd:'logon'},
  function(data){
		if(data=='ok\n'){registerOk()};
		if(data=='error\n'){loginError()};
	}
);
}

function regFormSubmit(){
	var logi = $('#f_login').val();
	var sError = oValidator.checkSubmit();
	$('#rSubmitBlock input').each(function(){this.disabled = true});
	if(sError==''){
	  if($('#f_pas').val()!=$('#f_pas_1').val()){
			alert('Введенные пароли не совпадают!');
			$('#rSubmitBlock input').each(function(){this.disabled = false});
			return false;
		}
	} else {
		alert(sError);
		$('#rSubmitBlock input').each(function(){this.disabled = false});
		return false;
	}
	$.get("/logon/update.html",
  { f_login:escape($('#f_login').val()),
  	f_name:escape($('#f_name').val()),
  	f_pas:escape($('#f_pas').val()),
  	f_email:escape($('#f_email').val()),
  	cmd:'register'},
  function(data){
		if(data=='clone\n'){registerError(logi)};
		if(data=='ok\n'){registerOk()};
	}
	);
}

function defPosition(event) {
      var x = y = rel_y = 0;
      if (document.attachEvent != null) { // Internet Explorer & Opera
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
            rel_y = window.event.clientY;
      }
      if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
            rel_y = event.clientY;
      }
      return {x:x, y:y, rel_y:rel_y};
}

function article_out(obj){
	$('#article_pop', obj.parentNode).hide();
}

function article_over(obj,evt){
	var evt = evt || window.event;
  cursorX = defPosition(evt).x;
  if($.browser.opera){
  	cursorY = 700;
  } else {
  	cursorY = defPosition(evt).y;
  }
  var j=$('#article_pop', obj.parentNode);
	j.show();
	j.css("top",cursorY+15);	
	j.css("left",cursorX+20);
}
var Common = {
	Cookie:{
	
		set : function(sName, sValue, sPath, sExpire) {
		
			document.cookie = sName + '=' + (window.encodeURI? encodeURI(sValue) : escape(sValue)) +
				((sExpire == null)? '' : ('; expires=' + sExpire.toGMTString())) +
				((sPath == null)? '' : ('; path=' + sPath));
		
		},
		
		get : function(sName) {
		
			var sSearch = sName + '=';
			
			if(document.cookie.length > 0) {
			
				var iOffset = document.cookie.indexOf(sSearch);
				
				if(iOffset != -1) {
				
					iOffset += sSearch.length;
			
					var iEnd = document.cookie.indexOf(';', iOffset);
			
					if(iEnd == -1) {
						iEnd = document.cookie.length;
					}

					return window.decodeURI?
						decodeURI(document.cookie.substring(iOffset, iEnd)):
						unescape(document.cookie.substring(iOffset, iEnd));
					
				}
			}
			
			return '';			
		
		}
	
	}
};

function deleteBlogPost(id){
	if(confirm("Вы действительно хотите удалить этот пост?")){
		window.location.href = '/profile/blog/edit/deletepost.html?id='+id;
	}
}

function deleteStoryPost(id){
	if(confirm("Вы действительно хотите удалить этот пост?")){
		window.location.href = '/profile/story/edit/deletepost.html?id='+id;
	}
}

function deleteKonkursPost(id){
	if(confirm("Вы действительно хотите удалить этот пост?")){
		window.location.href = '/profile/konkurs/edit/deletepost.html?id='+id;
	}
}

function showButton(){
	if($('#lead').val() == '') {
		$('#adding').attr('disabled', 'disabled');
	} else {
		$('#adding').removeAttr('disabled');
	}
}

function reloadPage(){
	var s = window.location.href;
	if(s.indexOf('#')>-1){s = s.split('#')[0]}
	window.location = s;
}

function setKonkursVote(){
	var iID=$('#konkurs_id').val();
	if(iID && iID==parseInt(iID) && iID>0){
		$.post("/konkurs/vote.html", {id:iID},
			function(data){
				if(data){
					$('#div_vote').html('');
					$('#div_vote').css('display','none');
					$('#poll_count').html(data);
					$('#div_poll').css('display','block');
				}
			}
		);
	}
}

function setVote(obj){
	var iID=$(obj).attr('image_id');
	var i = obj.id;
	var poll_count=$(obj).attr('poll_count');
	var auth=$('#auth').val();
	var sTable = obj.parentNode.id;
	var sel=i;
	$(obj.parentNode).attr('sel', i);
	if(iID && iID==parseInt(iID) && iID>0){
		$.post("/vote.html", {id:iID, auth:auth, mark: i, table: sTable},
			function(data){
				if(data){
					$(obj).parents('div.stars_for_vote').find('div#'+sTable).css('display','none').css('height','39px');
					$(obj).parents('div.stars_for_vote').find('span#poll_count').html(data);
					//$(obj).parents('div.stars_for_vote').find('div#div_poll').find('span#poll_count').html(data);
					$(obj).parents('div.stars_for_vote').find('div#div_poll').css('display','block').css('height','30px').css('padding-top','9px');
					$(obj).parents('div.stars_for_vote').find('div#'+sTable).html('');
//					if(!aVote[iID]){
						aVote[iID]=1;
//					}else{
//					aVote[iID]=1;
//					}
				}
			}
		);
	}
}

function VotePhoto(obj){
	var iID=$(obj).attr('image_id');
	var is_vote=aVote[iID];
	var sTable = obj.parentNode.id;
	if(is_vote=='0'){
		$(obj).parents('div.stars_for_vote').find('div#'+sTable).css('display','block');
	}
	if(is_vote=='1'){
		$(obj).parents('div.stars_for_vote').find('div#div_poll').css('display','block').css('height','30px').css('padding-top','9px');
		$(obj).parents('div.stars_for_vote').find('div#'+sTable).remove();
	}
}

function Elem(sObject){
	return(document.getElementById(sObject));
}

function voteAnketa(oElem){
	if(oElem){
		var iID=oElem.getAttribute('id');
		$.post("/babycover/vote.html", {id:iID},
			function(data){
				if(data!=-1){
					aVote[iID]=data;
					hidePollButton(data, iID);
				}
			}
		);
	}
}

function hidePollButton(iCount, iID){
	var oDivPoll=Elem('div_poll_'+iID);
	var oPollCount=Elem('poll_count_'+iID);
	var oDivVote=Elem('div_vote_'+iID);
	if(oDivPoll && oPollCount && oDivVote){
		oPollCount.innerHTML=iCount;
		oDivVote.innerHTML=oDivPoll.innerHTML;
	}
}

function checkVote(iID){
	if(aVote[iID]){
		hidePollButton(aVote[iID], iID);
	}
}

function trimText(sText){
	sText=sText.replace(/\n+/g,'');
	sText=sText.replace(/^( )+/g,'');
	sText=sText.replace(/( )+$/g,'');
	return(sText);
}

function tweet(sTitle){
	var content_url = document.location;
	var content_title = sTitle;
//	var content_tw = ($.browser.msie && ($.browser.version).substr(0,1) == "8") ?
//			encodeURIComponent(content_title + ' - ' + content_url) :
//			content_title + ' - ' + content_url;
	if (content_url){
		window.open("http://twitter.com/share?url=" + content_url + "&text=" + content_title);
	}
}
