var AC_FL_RunContent = 0;
var DetectFlashVer = 0;
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 45;
var stringHtml='<html><head><meta name="description" content="ClearWare print tool"/><meta name="keywords" content="k"/><meta name="author" content="office@clearware.eu"/><link href="'+path+'css/pub_print.css" rel="stylesheet" /></head><body onload="javscript: window.print();"><div id="main">';
var stringHtmlEnd='</div></body></html>';
var PrintCommandObject = null;
var dyns=new Array();
var scrollOffset=7000;
var scrollTime=0;
var curDyn=0;
var trrt=null;
var logoImgPath = '/tennis24/img/thumbs/188xc296/tools/administration/media/users/';
//TODO: da se opravi Validaciqta na formata za kontakti.

function createFormArray1(form_id){
  var myForm = document.getElementById(form_id);
  var inputs = myForm.elements;
  var out = new Array();
  for (var i=0; i<inputs.length; i++){
		if(inputs[i].name && inputs[i].name!=''){
			if(inputs[i].name.indexOf('[]')!=-1 && inputs[i].type!='select-multiple'){
				if(out[inputs[i].name.replace('[]', '')]==undefined || out[inputs[i].name.replace('[]', '')].constructor.toString().indexOf("Array") == -1){
					out[inputs[i].name.replace('[]', '')]=new Array();
				}
				if(inputs[i].type=='checkbox' || inputs[i].type=='radio'){
					if(inputs[i].checked){
						out[inputs[i].name.replace('[]', '')].push(inputs[i].value);
					}
				}else{
					out[inputs[i].name.replace('[]', '')].push(inputs[i].value);
				}
			}else if (inputs[i].type=='checkbox'){
				out[inputs[i].name]=(inputs[i].checked)?inputs[i].value:'';
			}else if(inputs[i].type=='radio'){
				if(inputs[i].checked)
					out[inputs[i].name]=inputs[i].value;
			}else if (inputs[i].type=='select-multiple'){
				out[inputs[i].name.replace('[]', '')]= getMultiSelectVals(inputs[i]);
			}else{
				out[inputs[i].name]=inputs[i].value;
			}
		}
	}
	return out;
}
function get_cookie ( cookie_name ){
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results )
		return ( unescape ( results[2] ) );
	else
		return null;
}
function getProfileBlock(){
	trrt=get_cookie('f24_loged');
	if(trrt){
		$.get('components/asyncUserInfo.php?jj=1', function(r){
			if(r!='')
				$('#hLoginForm').html(r);
		});
	}
	
}
function genDate(d){
	var dA=d.split('-');
	if(!(dA[1]>0 && dA[1]<13 && dA[0]>0 && dA[0]<32)){
		var date=false;
	}else{
		var date=new Date();
		date.setFullYear(dA[2], dA[1]-1, dA[0]);
		date.setHours(0);
		date.setMinutes(0);
		date.setSeconds(0);
	}
	return date;
}


function printIT(id){
	newWin = window.open('','a','width=780,height=500,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');
	var html = stringHtml+document.getElementById(id).innerHTML+stringHtmlEnd;
	newWin.document.write(html);
	newWin.document.close();
	newWin.focus();
}
function resetDyns(){
	scrollTime=setTimeout(function(){scrollDyns();}, scrollOffset);
}

function initDyns(){
	var i=0;
	$('.pub_dynBig').each(function(){
		dyns[i]=this.id.split('_')[1];
		$(this).attr('arrID', i);
		i++;
	});
	$('img[id^=smallDynImg_]').mouseover(function(){
		var par=0;
		var id=this.id.split('_')[1];
		for(var i=0; i<dyns.length; i++){
			if(id==dyns[i]){
				par=i;
				break;
			}
		}
		scrollDyns(par);
	});
	$('#prevDyn').click(function(){
		prevDyn();
	});
	$('#nextDyn').click(function(){
		nextDyn();
	});
	if(dyns.length>0)
		resetDyns();
}
function nextDyn(){
	var curDyn1=curDyn+1;
	if(curDyn1>=dyns.length)
		curDyn1=0;
	scrollDyns(curDyn1);
}
function prevDyn(){
	var curDyn1=curDyn-1;
	if(curDyn1<0)
		curDyn1=dyns.length-1;
	scrollDyns(curDyn1);
}
function scrollDyns(id){
	$('#dynBig_'+dyns[curDyn]).css('display', 'none');
	if(id==undefined){
		curDyn++;
		if(curDyn>=dyns.length)
			curDyn=0;
	}else{
		curDyn=id;
	}
	$('#dynBig_'+dyns[curDyn]).css('display', 'block');
	
	if(id==undefined)
		resetDyns();
	else
		clearTimeout(scrollTime);
}

function setMost(res){
	$('#mostHolder').html(res);
}
function setMenus(res){
	$('#menusHolder').html(res);
}
function CreateBookmarkLink() {
	title = "tennis24.bg"; 
	url = location.href;
	if (window.sidebar){ // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ){ // IE Favorite
		window.external.AddFavorite( url, title);
	}else if(window.opera && window.print){ // Opera Hotlist
		return true;
	}
}
function setHomepage(){
	if (document.all){
		document.body.style.behavior='url(#default#homepage)';
		document.body.setHomePage('http://tennis24.bg/');
	}else if(window.sidebar){
		if(window.netscape){
			try{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			}catch(e){
				alert("Тази функция е забранена от браузъра ви. Ако искате да я разрешите, моля въведете about:config в полето Аddress и променете стойността на signed.applets.codebase_principal_support на true");
			}
		}
		var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
		prefs.setCharPref('browser.startup.homepage','http://tennis24.bg/');
	}
}

function picUploaded(d){
  for(var i in d.f){
	var fa=d.f[i].split('/');
	var f=fa[fa.length-1];
	$('#'+i+'Img').val(f);
  }
  globalSaveFunc($('#'+d.dID)[0]);
}

function globalSaveFunc(th){
  if(globalValidation($('form', th))){
	if($('.inpNW', th).length>0 && $(th).attr('linkto') && $(th).attr('linkto')!=''){
	  $('#'+$(th).attr('linkto')).dialog('open');
	  $('#'+$('.inpNW', th)[0].id.replace('_new', '')).val($('.inpNW', th).val());
	  $(th).dialog('close');
	  emptyForm($('form', th));
	}else{
	  var mustsubmit=true;
	  var isEmpty=false;
	  $('input[type=file]', th).each(function(){
		isEmpty|=$('#'+this.id).val()!='';
		mustsubmit&=$('#'+this.id+'Img').val()=='';
	  });
	  // 			if(th.hasClass('submit'))
	  // 				mustsubmit=true;
	  if((!$(th).attr('func') || $(th).attr('func')=='') || ($(th).attr('hasupload')=='true' && mustsubmit && isEmpty)){
		$('form', th).submit();
	  }else{
// 		return false;
		window[$(th).attr('obj')][$(th).attr('func')](createFormArray1($('form', th)[0].id), function(r){
		  if($(th).attr('replace')=='replace'){
			$('#'+$(th).attr('holder')).html(r.html);
			$('.coolbutton').button();
		  }else
			$('#'+$(th).attr('holder')).append(r.html);
		  var each=$('#'+$(th).attr('holder')).attr('cols')*1;
		  if(!isNaN(each)){
			var i=0;
			$('li', $('#'+$(th).attr('holder')).parent()).each(function(){
			  if(i%each==0)
				$(this).addClass('clear_both');
			  else
				$(this).removeClass('clear_both');
			  i++;
			});
		  }
			if(r){
				$(th).dialog('close');
// 			$('.inpNW', th).length>0 &&
				if( $(th).attr('postlinkto') && $(th).attr('postlinkto')!=''){
					var ids=$(th).attr('postlinkto').split(',')
					for(var k in ids){
						if(ids[k].indexOf('v:')==0)
							eval(ids[k].replace('v:', '')+'='+r.ID+';');
						else
							$('#'+ids[k]).val(r.ID);
					}
// 			  $('#'+ids[2]).val($('.inpNW', th).val());
// 			  $(th).dialog('close');
				}
			}
// 		if(r){
// 			$(th).dialog('close');
// 			if($('.inpNW', th).length>0 && $(th).attr('postlinkto') && $(th).attr('postlinkto')!=''){
// 				var ids=$(th).attr('postlinkto').split(',')
// 				$('#'+ids[0]).dialog('open');
// 				$('#'+ids[1]).val(r.ID);
// 				$('#'+ids[2]).val($('.inpNW', th).val());
// 				$(th).dialog('close');
// 			}
// 		}
		if($('form', th).attr('preserve')!='true')
			emptyForm($('form', th));
	  });
	}
  }
}
}

function globalValidation(el){
  var ret=true;
  $('input[class*=valid_],textarea[class*=valid_],select[class*=valid_]', el).each(function(){
	
	var cl=$(this).attr('class'), goon=true;
	if(cl.indexOf('childOf_')>-1){
	  var c=cl.substr(cl.indexOf('childOf_')+8);
	  if(c.indexOf(' ')>-1)
		c=c.split(' ')[0];
	  if(!$('#'+c)[0].checked)
		goon=false;
	}
	$(this).trigger('focus');
	if(goon)
	  ret=(validateF(this) && ret);
	$(this).trigger('blur');
  });
  return ret;
}

function isDateOK(v,s){
  var d=v.split(s);
  if(d.length!=3)
	return false;
  
  d[0]*=1;d[1]*=1;d[2]*=1;
  if(d[0]<1 || d[0]>31)
	return false;
  if(d[1]<1 || d[1]>12)
	return false;
  if(d[2]<1 || d[2]>2999)
	return false;
  if	(d[1]==2 &&((d[2]%4==0 && d[0]>29)||(d[2]%4!=0 && d[0]>28)))
	return false;
  if( ((d[1]<8 && d[1]%2==0) || (d[1]>7 && d[1]%2==1)) && d[0]>30 )
	return false;
  return true;
  
}

function setValidation(th, mess, notok){
  $(th).removeClass('inpKO inpOK inpWt inpFD inpNW');
  if(notok){
	if(th.tagName=='INPUT')
	  $(th).addClass('inpKO');
	$('#check_'+th.id).text(mess);
	$(th).addClass('focused_input preserve_focus').effect("shake", { times:2, distance:3 }, 1, function(){
	  setTimeout(function(){
		$(th).removeClass('focused_input preserve_focus');
	  }, 500);
	});
  }else{
	if(th.tagName=='INPUT')
	  $(th).addClass('inpOK');
	$('#check_'+th.id).text('');
  }
  return !notok;
}

function emptyForm(fID){
  $('input[type=text],input[type=file],input[type=hidden],textarea,select', fID).not('.preserve').val('');
  $('input[type=checkbox]', fID).not('.preserve').each(function(){this.checked=false});
}

function validateF(th){
  var isOK=true;
  var cl=$(th).attr('class').split(/\s+/);
  var cll=cl.length;
  for(var i=0; i<cll; i++){
	if(cl[i].indexOf('valid_')==0){
	  if(cl[i].indexOf('valid_link')==0){
		isOK=valid_link(th);
	  }else if(cl[i].indexOf('valid_min')==0){
		isOK=valid_min(th);
	  }else
		if(window[cl[i]])
		  isOK=window[cl[i]](th);
	}
	if(!isOK)
	  break;
  }
  return isOK;
}

function valid_date(th){
  var reDate = /^[0-3]]?\d\.[0-1]?\d\.[1-2]\d{3}$/;
  return setValidation(th, "'"+$(th).val()+"' не е валидна дата във формат дд.мм.гггг",( !(reDate.exec($(th).val()) && isDateOK($(th).val(), '.') )) );
}
function valid_datef(th){
  var reDate = /^[0-3]]?\d\.[0-1]?\d\.[1-2]\d{3}$/;
  return setValidation(th, "'"+$(th).val()+"' не е валидна дата във формат дд.мм.гггг",( !(reDate.exec($(th).val()) && isDateOK($(th).val(), '.') )) );
}
function valid_http(th){
  var rehttp = /^https?:\/\/.*\.[A-Za-z]{2,4}/;
  return setValidation(th, "'"+$(th).val()+"' не е верен адрес на сайт във формат http://www.domain.com/", !rehttp.exec($(th).val()));
  }
function valid_EM(th){
  $(th).addClass('isWt');
  return setValidation(th, "'"+$(th).val()+"' вече е регистриран",checkVal('EMail', $(th).val(), -2));
}
function valid_SEM(th){
  var reMail = /^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,4}$/;
  return setValidation(th, "'"+$(th).val()+"' не е валиден e-mail адрес.", (!reMail.exec($(th).val())));
}
function valid_UN(th){
  $(th).addClass('isWt');
  return setValidation(th, "'"+$(th).val()+"' вече е регистриран", checkVal('User', $(th).val(), -2));
}
function valid_ne(th){
  return setValidation(th, 'Това поле не може да е празно', ($(th).val()==''));
}
function valid_new(th){
  if($(th).val()==''){
	return setValidation(th, 'Това поле не може да е празно', ($(th).val()==''));
  }else if(!$(th).hasClass('inpFD')){
	$(th).addClass('inpNW');
	$('#check_'+th.id).text('');
	return true;
  }else{
	$('#check_'+th.id).text('');
	return true;
  }
}
function valid_min(th){
  var cl=$(th).attr('class');
  var ct=cl.substr(cl.indexOf('valid_min')+9);
  if(ct.indexOf(' ')>-1)
	ct=ct.substr(0, ct.indexOf(' '));
  ct=ct*1;
  return setValidation(th, 'Стойността трябва да дълга е минимум '+ct+' знака', ($(th).val().length < ct));
}
function valid_link(th){
  var cl=$(th).attr('class');
  var ct=cl.substr(cl.indexOf('valid_link_')+11);
  ct=ct.substr(0, ct.indexOf(' '));
  return setValidation(th, 'Паролите не съвпадат', ($(th).val()!= $('#'+ct).val()));
}
function checkVal(prop, val, uID){
  return xoadObj['check'+prop+"_ajax"](val, uID);
}
function setWallEv(){
	$('.wall li').has('button[id^=remove_]').mouseover(function(){
		$('button[id^=remove_]', this).show();
	}).mouseout(function(){
		$('button[id^=remove_]', this).hide();
	});
	$('button').each(function(){
	  var th=this;
	  $(this).button({
		icons: {primary: th.className}
	  });
	});
}

function emptySelect(sel){
  for(var i=sel.childNodes.length-1; i>=0; i--)
	sel.removeChild(sel.childNodes[i]);
}
function setLinkedVals1(res, sel){
  emptySelect(sel);
  for(var i=0; i<res.length; i++){
	var oOpt=document.createElement('option');
	oOpt.value=res[i]['id'];
	oOpt.appendChild(document.createTextNode(res[i]['name']));
	sel.appendChild(oOpt);
  }
}
function setFancy(){
	$("a.showFancy").fancybox({
		'transitionIn':'elastic',
		'transitionOut':'elastic',
	});
}
$('body').ready(function(){
// 	$('#acc').accordion({
// 		autoHeight: false,
// 		navigation: true
// 		changestart: function(event, ui){
// 			$.get(ui.newHeader.href, function(r){
// 				$(ui.new).html($('#pesho', r).html());
// 			});
// 		}
// 	});
// 	$( ".tabs" ).tabs({
// 		ajaxOptions: {
// 			error: function( xhr, status, index, anchor ) {
// 				$( anchor.hash ).html(
// 					"Couldn't load this tab. We'll try to fix this as soon as possible. " +
// 					"If this wouldn't be a demo." );
// 			}
// 		}
// 	});
	$('#actUsr_1,#actUsr_2').click(function(e){
		e.preventDefault();
		$('#actUsr_1,#actUsr_2').removeClass('act')
		$('#actUsr_1Hld,#actUsr_2Hld').slideUp();
		$('#'+this.id+'Hld').slideDown();
		$(this).addClass('act');
	});
	$('#pagButton').live('click', function(e){
		e.preventDefault();
		if(!$(this).hasClass('working')){
			$('#pagButton').attr('intText',$('#pagButton').html()).html('Моля изчакайте...').addClass('working');
			$.get(this.href, function(r){
				$('#cmtHld').append($('#cmtHld', r).html());
				if($('#pagButton', r).length>0)
					$('#pagButton')[0].href=$('#pagButton', r)[0].href;
				else
					$('#pagButton').fadeOut();
				$('#pagButton').html($('#pagButton').attr('intText')).attr('iniText', '').removeClass('working');
			});
		}
	});
	$('.canGiveProg').mouseover(function(){
		$('.canGiveProg .progV').css('display','none');
		$('.progV',this).css('display','block');
	});
	if(document.getElementById("container"))
		jwplayer("container").setup({
			height: 250,
			width: 400,
			flashplayer: path+"flash-video-player/player.swf",
			skin: path+"flash-video-player/skins/glow/glow.zip",
//			"playlist.position": "right",
//			"playlist.size": 250,
// 			plugins: {
// 				"flow-1": {
// 					yposition:-10,
// 					controlbaricon:true,
// 					opacitydecrease:0.15,
// 					buffericon:true,
// 					autorotate:true,
// 					coverwidth:300,
// 					coverheight:200,
// 					showreflection:true,
// 					font:'Arial',
// 					fontsize:16,
// 					color:'f1f1f1',
// 					onplaying:'hide'
// 				}
// 			}
		});
	setFancy();
	$('a.plGo').click(function(e){
		e.preventDefault();
		var pos=(this.id.replace('plGo_', '')*1)-1;
		jwplayer().playlistItem(pos);
	});
	$('.artIcon').live('click', function(e){
		var t=this.id.split('_');
		xoadWeb.setPicIcon_ajax({obID:artID, imgID:t[1], what:t[2], template: 'picsTemplate', inc:"articleInsert,utils"}, function(r){
			$('#imgHolder').html(r.html);
			setFancy();
		});
		return false;
	});
	$('.artImgDel').live('click', function(e){
		if(confirm('Наистина ли искате да изтриете това изображение?')){
			var t=this.id.split('_');
			xoadWeb.delPic_ajax({obID:artID, imgID:t[1], template: 'picsTemplate', inc:"articleInsert,utils"}, function(r){
				$('#imgHolder').html(r.html);
				setFancy();
			});
			return false;
		}
	});

	$('.coolbutton').button();
	$('#showAdvOptions').click(function(e){
		e.preventDefault();
		$('#advancedHolder').slideToggle();
	});
	setWallEv();
	$('button[id^=remove_]').live('click', function(e){
		e.preventDefault();
		if(confirm('Наистина ли искате да премахнете тази информация?')){
			var t=this.id.split('_'), th=this;
			xoadObj.pub_deleteComment_ajax({objectID:t[1], objectTypeID:t[2]}, function(r){
				if(r)
					$(th).parent().fadeOut('slow', function(){remove()});
			});
		}
	});
	$('.valid').submit(function(e){
		var r=globalValidation(this);
		if(!r)
			e.preventDefault();
		return r;
	});
	$('.valid_date').datepicker({
		autosize: true,
		changeYear: true,
		dateFormat: 'dd.mm.yy',
		defaultDate: '01.01.1980',
		gotoCurrent: true,
		firstDay: 1,
		onSelect: function(d, i){
			$(this).trigger('blur');
		}
	});
	$('.valid_datef').datepicker({
		autosize: true,
		changeYear: true,
		dateFormat: 'dd.mm.yy',
		gotoCurrent: true,
		firstDay: 1
	});
	$('input[class*=valid_],textarea[class*=valid_],select[class*=valid_]').blur(function(){
		validateF(this);
	});
	$('.allliking').live('click', function(e){
		e.preventDefault();
		var t=this.id.split('_');
		xoadObj.pub_people_template(
			{'objectID': t[1], 'objectTypeID': t[2],'template': 'people', 'inc': 'utils'},
			function(r){
				$('#globalDialog').html(r.html).dialog('open');
			}
		);
	});
	$('.field input,.field select,.field textarea').focus(function(){
		$(this).addClass('focused_input');
	}).blur(function(){
		$(this).removeClass('focused_input');
	});
	$('#user_pass').blur(function(){
		$('#confirmpw').trigger('blur');
	});
	$('.like').live('click', function(e){
		var t=this.id.split('_');
		xoadObj.pub_likeObject_ajax({'objectID': t[1], 'objectTypeID': t[2], 'isLike': t[3], 'template': 'like', 'inc':'utils', 'params': {obID:t[1], obtID: t[2]}}, function(r){
			$('#likeHld').html(r.html);
		});
// 		 0 - статия
// 		 1 - тенисист
// 		 2 - мач
// 		 3 - друг потребител(от това има ли смисъл?)
// 		 4 - публикация на потребител
	});
	$('#globalDialog').dialog({
		autoOpen: false, 
		width: 620,
		height: 400,
		resizable: false,
		buttons: {
			'Затвори': function() {
				$(this).dialog('close');
			}
		}
	});
	$('.otsystvasht').hide();
	$('#signInWindow').dialog({
		autoOpen: false, 
		width: 620,
		height: 450,
		modal: true,
		resizable: false,
		buttons: {
			'Регистрация': function() {
				if(globalValidation($('#signInForm')))
					$('#signInForm')[0].submit(); 
			},
			'Затвори': function() {
				$(this).dialog('close');
			}
		}
	});
	$('#loginWindow').dialog({
		autoOpen: false, 
		width: 620, 
		height: 350,
		modal: true,
		resizable: false,
		buttons: {
			'Вход': function() {
				if(globalValidation($('#loginForm')))
					$('#loginForm')[0].submit(); 
			},
			'Затвори': function() {
				$(this).dialog('close');
			}
		}
	});
	$('.moreComments').live('click', function(e){
		e.preventDefault();
		var t=this.id.split('_');
		xoadObj.pub_getCommentsByID_template({objectID:t[1], objectTypeID:t[2], beforeID:t[3], template:'allComments', inc:'utils,article', params: {obID: t[1], obtID: t[2], tag: '/ROOT/results/item'}}, function(r){
			$('#commentsHolder').prepend(r.html);
			$('.moreComments', $('#commentsHolder')).parent().remove();
			setWallEv();
		});
	});
	$('#addComment').click(function(e){
		if(globalValidation($('#addCommentForm'))){
			var d=createFormArray1('addCommentForm');
			d.params={obID: d['objectID'], obtID: d['objectTypeID'], tag: '/ROOT/results/item'};
			xoadObj.pub_doComment_ajax(d,function(r){
				$('#commentsHolder').append(r.html);
				if(r.html!='' && r.ID>0){
					$('#commMessText').val($('#commMessText').attr('intval')).addClass('notFocussed');
					setWallEv();
				}
			});
		}
	});

// 	$('.right_user').sortable( {
// 		placeholder: 'ui-state-highlight' 
// 	}).disableSelection();;
	$('.dialog').dialog({
		autoOpen: false, 
		width: 620,
		modal: true,
		resizable: false,
		buttons: {
			'Запис': function() {
				globalSaveFunc(this);
			},
			'Отказ': function() {
				$(this).dialog('close');
			}
		}
	});
	$('.dialog1').dialog({
		autoOpen: false, 
		width: 620,
		modal: true,
		resizable: false,
		buttons: {
			'Отказ': function() {
				$(this).dialog('close');
			}
		}
	});
	$('#addCommentToWall').click(function(e){
		e.preventDefault();
		var datad =createFormArray1('addCommentToWallForm');
		datad['inc']='user_Reg,utils';
		datad['template']='cmtHld';
		xoadObj.pub_insertPost_ajax(datad, function(r){
			$('#cmtHld').prepend(r.html);
		});
	});
	var bioEdit = 0;
	$('.edit2').click(function(){
		if(bioEdit==0){
			$('.bio').fadeOut('slow', function(){
				$('.editShortBio').fadeIn('slow');
			});
			bioEdit = 1;
		}else{
			$('.editShortBio').fadeOut('slow', function(){
				$('.bio').fadeIn('slow');
			});
			bioEdit = 0;
		}
	});
	$('#updateBio').click(function(){
		var shortBio = createFormArray1('shortBioUpdate');
		xoadObj.insertshortBio_ajax(shortBio, function(r){
			$('.bio').html(r.html);
			$('.editShortBio').fadeOut('slow', function(){
				$('.bio').fadeIn('slow');
			});
			bioEdit = 0;
		});
	});
	
// 	if(trrt){
// 		$('#addTeamFav').fadeIn();
// 		$('.pub_comments_form').show();
// 	}else
// 		$('#commentLoginForm').show();
// 	$('#changePass').click(function(){
// 		$('#pub_changePass').show();
// 	});
// 	$('#closeChangePass').click(function(){
// 		$('#pub_changePass').hide();
// 	});
// 	$('.pub_form_submit').click(function(e){
// 		e.preventDefault();
// 		var data = createFormArray1('changePassForm');
// 		xoadObj.changePass_ajax(data, function(r){
// 			if(r.returnValue){
// 				alert('Вашата парола беше успешно сменена!');
// 				$('#pub_changePass').hide();
// 			}else{
// 				alert('Грешка при смяна на паролата! Моля опитайте отново.');
// 			}
// 		});
// 	});

	$('#cityID').change( function(){
		xoadObj.getDistrictsByCityID_ajax($(this).val(), function(r){
			var sel = document.getElementById('areaID');
			if(r.length==0){
				$('#areaID').css({'display':'none'});
			}else{
				setLinkedVals1(r,sel);
				$('#areaID').css({'display':'inline'});
			}
			
		});
	});
	$('#addCommentToWall').click(function(){
		var data = createFormArray1('addCommentToWallForm');
		//xoadObj.pub_insertPost_ajax(data, function(r){
		//	console.log(r);
		//});
	});
	$('#delTeam').click(function(e){
		e.preventDefault();
		if(confirm('Наистина ли искате да премахнте този тенисист от любимите си?')){
			if(xoadObj.sharedUsers_delFavPlayer_ajax($(this).attr('uID'), $(this).attr('teamID')))
				$('#curFav').fadeOut();
		}
		return false;
	});
	$('.addPlayerAsFav').click(function(e){
		var plID=this.id.split('_')[1];
		$.get('/components/asyncAddFavPlayer.php?addToFavPlayers='+plID, function(r){
			alert(r);
		});
	});
	if($('*').james){
		$('input#fav_teamID_jam').james("/components/asyncPlayerSearch.php", {
			minlength: 2,
			method: "get",
			varname: "searchFor",
			keydelay: 100,
			onSelect: function (t, j){
				$("input#fav_teamID_jam").val(t);
				$('input#fav_playerID').val(j['name']);
			}
		});
	}
	$('#delAvatar').click(function(e){
		e.preventDefault();
		if(confirm('Наистина ли искате да изтриете това изображение?')){
			if(xoadObj.delAvatar_ajax($(this).attr('uid'))){
				$('#avatarIHld').show();
				$('#avatarHld').hide();
			}
		}
		return false;
	});
	$('.pub_form_submit').click(function(){
		console.log('123');
	});
	$('#userReg').submit(function(e){
		if(!validate(this)){
			e.preventDefault();
			return false;
		}
	});
	$('#changePassForm').submit(function(e){
		if(!validate_pass()){
			e.preventDefault();
			return false;
		}
	});
	$('#countryID').change(function(){
		if(this.value==70){
			$('#city_bgIDHld').slideDown();
			$('#cityHld').hide();
		}else{
			$('#city_bgIDHld').hide();
			$('#cityHld').slideDown();
		}
	})
	$('*[id^=calHolder_]').click(function(){
		var after='01.01.1900';
		var before='01.01.2005';
		var inpname=this.id.replace('calHolder_', '');
		NewCal(inpname, 'ddmmyyyy', this, false, '', after, before);
	});
	$('.focusblur').each(function(){
		$(this).attr('intval', $(this).val()).focus(function(){
			if(this.value==this.getAttribute('intval')){
				this.value='';
				$(this).removeClass('notFocussed');
			}
		}).blur(function(){
			
			if(this.value==''){
				this.value=this.getAttribute('intval');
				$(this).addClass('notFocussed');
			}
		}).addClass('notFocussed');
	});
	$('#luser, #lpass, #cluser, #clpass').focus(function(){ //da se izkyrti!!!
		if(this.value==this.getAttribute('intval'))
			this.value='';
	}).blur(function(){
		if(this.value=='')
			this.value=this.getAttribute('intval');
	});
// 	$('#signInWindow').dialog({
// 		autoOpen: false,
// 		width: 610,
// 		modal: true,
// 		resizable: false,
// 	 });
	$('a[href^=#]').live('click', function(e){
	  var at=(this.tagName=='A')?$(this).attr('href'):$(this).attr('alt');
	  if(at=='#')
		return true;
	  
	  if($(at).dialog()){
		e.preventDefault();
		$($(this).parents()).dialog('close');
		$(at).dialog('open');
	  }
	});
	
	$('.avatar').live('click', function(){
		var split = this.id.split('_');
		var array = new Array();
		array['imgID'] = split[1];
		array['obID'] = obId;
		xoadObj.pub_setImageAvatar_ajax(array,function(r){
			$('#imgHolder').html(r.html);
			var imgSrc = $(r.html).find('.isLogo').attr("src");
			var imgName = imgSrc.split('/');
			var logoSrc = $('.profile_img').find('img').attr("src");
			var logoName = logoSrc.split('/');
			if(logoName[logoName.length-1]!=imgName[imgName.length-1]){
			  $('.profile_img').find('img').attr('src', logoImgPath+imgName[imgName.length-1]);
			}
			setFancy();
		});
	});
	
	$('.delete').live('click', function(){
		var split = this.id.split('_');
		var array = new Array();
		array['imgID'] = split[1];
		array['obID'] = obId;
		var answer = confirm("Желаете ли да изтриете тази картинка?");
		if (answer){
		  xoadObj.pub_deleteImage_ajax(array, function(r){
			  $('#imgHolder').html(r.html);
			  setFancy();
		  });
		}
	});
	
	$('.addFriend').live('click', function(e){
		e.preventDefault();
		if(addFriend(obId)){
			$(this).html('Изчакване на одобрение');
		}
	});
	$('.addFriend2').live('click', function(e){
	  e.preventDefault();
	  var id=this.id.split('_')[1];
	  if(addFriend(id)){
		  $(this).html('Изчакване на одобрение');
	  }
	});
	
	$('.removeFriend').live('click', function(e){
		e.preventDefault();
		if(removeFriend(obId)){
			$(this).html('Прекъснато приятелство');
		}
	});
	$('.removeFriend2').live('click', function(e){
		e.preventDefault();
		var id=this.id.split('_')[1];
		if(removeFriend(id)){
			$(this).html('Прекъснато приятелство');
			var nmbFriends = $('.nmbFriends').html();
			$('.nmbFriends').text(nmbFriends-1);
		}
	});
	
	$('.confirmFriend').live('click', function(e){
		e.preventDefault();
		if(makeFriend(obId)){
			$(this).html('Успешно потвърдено!');
		}
	});
	$('.confirmFriend2').live('click', function(e){
		e.preventDefault();
		var id=this.id.split('_')[1];
		if(makeFriend(id)){
			$(this).html('Успешно потвърдено!');
			var nmbFriends = $('.nmbFriends').html();
			$('.nmbFriends').text(nmbFriends-1);
		}
	});
	function setPredict(par, xxx, xxx1){
		$('.pub_pollBg', par).animate({'width': xxx+'%'}, 700, function(){
			par.find('div:eq(1)').html(xxx+'%');
			$('b',par).html('Гласували: '+xxx1);
		});
	}
	function setPredictRight(par, xxx, xxx1){
		$('span em', par).animate({'width': xxx+'%'}, 1000);
	}
	$('.rightPredict').click(function(e){
		var q = this.id.split('_'), id = this.id, th=this;
		xoadObj.pub_doPrognosis_ajax({prognosisID: q[1], matchID: q[2],result:q[3]}, function(r){
			var thNo=(q[3]*1)+1;
			var opp=(thNo%2);
			var oppID='#'+id.substr(0, id.lastIndexOf('_')+1)+opp;
			opp++;
			th.id=q[0]+'_'+r.prognosisID+'_'+q[2]+'_'+q[3];
			var par=$('#pl_'+thNo+'_'+q[2]);
			setPredictRight(par, r['percent_'+thNo], r['voted_'+thNo]);
			par=$('#pl_'+opp+'_'+q[2]);
			setPredictRight(par, r['percent_'+opp], r['voted_'+opp]);
			var opInp=$(oppID)[0];
			var qopp=opInp.id.split('_');
			opInp.id=qopp[0]+'_'+r.prognosisID+'_'+qopp[2]+'_'+qopp[3];
			$('#youVot'+q[2]).html("Вие сте гласували за "+$(th).parent().text()).fadeIn();
			$('#nbVot'+q[2]).html(r['voted_1']*1 +r['voted_2']*1);
		});
	});
	
	$('.prediction').click(function(e){
		var q = this.id.split('_'), id = this.id, th=this;
		xoadObj.pub_doPrognosis_ajax({prognosisID: q[1], matchID: q[2],result:q[3]}, function(r){
			var thNo=(q[3]*1)+1;
			var opp=(thNo%2);
			var oppID='#'+id.substr(0, id.lastIndexOf('_')+1)+opp;
			opp++;
			th.id=q[0]+'_'+r.prognosisID+'_'+q[2]+'_'+q[3];
			var par=$(th).parent().find('.pub_pollData');
			setPredict(par, r['percent_'+thNo], r['voted_'+thNo]);
			par=$(oppID).parent().find('.pub_pollData');
			setPredict(par, r['percent_'+opp], r['voted_'+opp]);
			var opInp=$(oppID).parent().find('input')[0];
			var qopp=opInp.id.split('_');
			opInp.id=qopp[0]+'_'+r.prognosisID+'_'+qopp[2]+'_'+qopp[3];
			var tr=$(th).parent().parent();
			tr.parent().find('tr:last td').html("Вие сте гласували за "+tr.find('td:first a').html());
		});
	});
	
	
	$('.loginWindow').click(function(){
		$('#loginWindow').dialog('open');
	});
	
	$('#mostHld .pub_blueHead').click(function(e){
		if(!$(this).parent().hasClass('newsShow')){
			$('#mostHld ul:visible').slideUp('fast');
			$('#mostHld .newsShow').removeClass('newsShow');
			$('ul', $(this).parent().addClass('newsShow')).slideDown('fast');
		}
	});
	$('.yellow li').mouseover(function(){
		$(this).parent().find('li').removeClass('selected');
		$(this).addClass('selected');
	});
	
	$("a[id^=mostArticles_]").live('click', function(e){
		var whatID=this.id.split('_')[1];
		var opID=1;
		if(whatID==1)
			opID=2;
// 		$("#mostArticles_"+whatID)[0].className=$("#mostArticles_"+whatID)[0].getAttribute('origClass')+'a';
// 		$("#mostArticles_"+opID)[0].className=$("#mostArticles_"+opID)[0].getAttribute('origClass');
		Obj.getMostWhateverArticle_ajax(lID, whatID, setMost);
	});
	$("a[id^=menuID_]").live('click', function(e){
		var whatID=this.id.split('_')[1];
		$("#menuID_"+whatID)[0].className='pub_tab2a';
		for(var i=0; i<menus.length; i++)
			if(menus[i]!=whatID)
				$("#menuID_"+menus[i])[0].className='pub_tab2';
		Obj.getArticleByMenuId_limit_ajax(whatID, lID, setMenus);
	});
	initDyns();
});

function makeFriend(id){
  if(xoadObj.pub_confirmFriendRequest_ajax(id)){
	return true;
  }else{
	alert('Грешка при потвърждаване на приятелство!!!');
  }
}

function addFriend(id){
	if(xoadObj.pub_sendFriendRequest_ajax(id)){
		return true;
	}else{
		alert('Грешка при прекратяване на приятелство!!!');
	}
}

function removeFriend(id){
  if(xoadObj.pub_deleteFriend_ajax(id)){
	return true;
  }else{
	alert('Грешка при изпрашане на покана за приятелство!!!');
  }
}
