$(document).ready(function(){
	$(".ogg").mouseover(function(){
		$('td',this).css({"background-image":"url(/files/images/bg-hd-tbl.png)"});
	});
	$(".even").mouseover(function(){
		$('td',this).css({"background-image":"url(/files/images/bg-hd-tbl.png)"});
	});
	$(".ogg").mouseout(function(){
		$('td',this).css({"background-image":""});
	});
	$(".even").mouseout(function(){
		$('td',this).css({"background-image":""});
	});
	$(".StatHrefBottom").mouseover(function(){
		$(this).css({"background-image":"url(/files/images/bg-hd-m.png)"});
	});
	$(".StatHrefBottom").mouseout(function(){
		$(this).css({"background-image":""});
	});
});

function JQLoadLite(idobj,filestring,type,objvar){
	if (type == "lite"){
		$.ajax({
			type: "GET",
			url: "/",
			data: "act=lite&"+filestring+"&var="+objvar,
			success: function(data){
				$('#'+idobj).html(data);
			}
		});
	}
}
chekTarg=Array(0,0);
function JQAddFieldBuyTargeting(div){
	flag=0;
	var val=$('#country').attr('value')+"/"+$('#regionsel').attr('value')+"/"+$('#citysel').attr('value')+"/"+$('#NoTarget').attr('checked')*1;
	var cns=new Array();//реализовано массивами потому что не знаю как сделать брейк цикла .each jquery
	var rs=new Array();
	var cts=new Array();
	var nts=new Array();
	var err='';
	var i=0;
	if($('#country').attr('value')=='all'&&$('#NoTarget').attr('checked')*1==1){
		err='Нельзя исключить все страны.';
	}else{
		$('#ListTargets .lidiv input').each(function(){
			name = $(this).attr('name');
			var tmp=/geoTarg\[([A-Za-z1-9 ]+)\/([а-яА-ЯA-Za-z- ]+)\/([а-яА-ЯA-Za-z- ]+)\/(\d+)/.exec(name);
			cns[i]=tmp[1];
			rs[i]=tmp[2];
			cts[i]=tmp[3];
			nts[i]=tmp[4];
			i++;
		});
		for(i=0;i<cns.length;i++){
			if(cns[i]=='all'){
				err='Вы уже указали все страны.';break;
			}else if($('#country').attr('value')=='all'){
				err='Нельзя указывать все страны, если Вы указали хотя бы одну.';break;
			}else if(cns[i]==$('#country').attr('value')&&
						rs[i]==$('#regionsel').attr('value')&&
						cts[i]==$('#citysel').attr('value')){
				err='Такая зона уже существует';break;
			}else if(cns[i]==$('#country').attr('value')&&
						(rs[i]==$('#regionsel').attr('value') || rs[i]=='all' || $('#regionsel').attr('value')=='all')&&
						(cts[i]==$('#citysel').attr('value') || cts[i]=='all' || $('#citysel').attr('value')=='all')&&
						nts[i]==$('#NoTarget').attr('checked')*1
					){
				err='Зоны пересекаются';break;
			}else if(nts[i]==1&&$('#NoTarget').attr('checked')*1==0&&($('#regionsel').attr('value')=='all'&&rs[i]=='all')){
				err='Нельзя указывать страны, если Вы уже исключили хотя бы одну';break;
			}else if(nts[i]==0&&$('#NoTarget').attr('checked')*1==1&&($('#regionsel').attr('value')=='all'&&rs[i]=='all')){
				err='Нельзя исключать страны, если Вы уже указали хотя бы одну';break;
			}else if(cns[i]==$('#country').attr('value')){
				if(nts[i]==1&&$('#NoTarget').attr('checked')*1==0&&rs[i]!='all'&&$('#regionsel').attr('value')!='all'&&$('#citysel').attr('value')=='all'&&cts[i]=='all'){
					err='Нельзя указывать регионы, если Вы уже исключили хотя бы один';break;
				}else if(nts[i]==0&&$('#NoTarget').attr('checked')*1==1&&rs[i]!='all'&&$('#regionsel').attr('value')!='all'&&$('#citysel').attr('value')=='all'&&cts[i]=='all'){
					err='Нельзя исключать регионы, если Вы уже указали хотя бы один';break;
				}else if(rs[i]==$('#regionsel').attr('value')&&rs[i]!='all'){
					if(nts[i]==1&&$('#NoTarget').attr('checked')*1==0){
						err='Нельзя указывать города, если Вы уже исключили хотя бы один';break;
					}else if(nts[i]==0&&$('#NoTarget').attr('checked')*1==1){
						err='Нельзя исключать города, если Вы уже указали хотя бы один';break;
					}else if(cts[i]=='all'){
						if(nts[i]==1){
							err='Вы уже исключили данный регион.';break;
						}else{
							err='Вы уже указали данный регион.';break;
						}
					}
				}else if(rs[i]=='all'&&nts[i]==$('#NoTarget').attr('checked')*1){
					if(nts[i]==1){
						err='Вы уже исключили данную страну.';break;
					}else{
						err='Вы уже указали данную страну.';break;
					}
				}
			}
		}
	}
	if(err==''){
		if($('#NoTarget').attr("checked")==false){
			notarg=0;
		}else{
			notarg=1;		
		}
/*		if ($('input[@name="geoTarg[all]"]').size()!=0 && notarg==0){
			$('input[@name="geoTarg[all]"]').parent().remove();
		}*/
		$.ajax({
			type:"GET",
			url:"/",
			data:"act=lite&type=addfieldtarg&idobj="+$('#country').attr('value')+"/"+$('#regionsel').attr('value')+"/"+$('#citysel').attr('value')+"/"+notarg,
			success:function(data){
				$('#'+div).append(data);
				JQSumTargeting('.SumOneTarget');
				CalcTraffic();
			}
		});
	}else{alert(err);}
}
function JQSumTargeting(div){
	var sum=1;
	$(div).each(function(i){
		tempint = parseInt($(this).text());
		if (isNaN(tempint)){tempint = 0;}
		sum = sum + tempint;
	});
	$('#LiSumDiv span').text(sum);
}
function LinkDisable(){
	if ($("#FLink").attr("disabled")){
		$("#FLink").removeAttr("disabled");
	}else{
		$("#FLink").attr("disabled","disabled");
	}
}
function SubTableStat(linkhref,insafter){
	if ($(insafter).parent().next().attr("class") == "subtable"){
		$(insafter).parent().next().remove();
	}else{
		$.ajax({
			type: "GET",
			url: "/",
			data: linkhref,
			success: function(data){
				lenghttr = 0;
				para = $(insafter).parent();
				lenghttr = para.find("td");
				lenghttr = lenghttr.length;
				$(insafter).parent().after("<tr class='subtable'><td colspan="+lenghttr+"><table sub>"+data+"</table></td></tr>");
			}
		});
	}
}
function DeleteTarget(deleted,delstr){
	chekTarg=Array(0,0);
	selcats=document.getElementById('selcats');	
	var str=""+selcats.value;
	str=str.replace(","+delstr, "");
	str=str.replace(""+delstr+",", "");
	str=str.replace(","+delstr+",", "");
	selcats.value=str.replace(""+delstr, "");
	$(deleted).parent().parent().remove();
	CalcTraffic();
	sendInfo();
}
function CalcTraffic(type){
	var target = '';
	var fulltarg = 0;
	$('#ListTargets .lidiv input').each(function(){
		name = $(this).attr('name');
		value = $(this).attr('value');
		if(name == 'FCountry[]' && value == 'all'){fulltarg = 1;}
		target += name+'='+value+"&";
	});
	var cats='';
	$('#FCat option').each(function(){
		if($(this).attr('selected')){
			valf=$(this).val();
			cats=cats+'cat['+valf+']=1&';
		}
	});
	money=$('#price').val(); 
	money='money='+money+'&';
	show =$('#whatBuy').val();
	$.ajax({
	   type: "POST",
	   url: "index.php?act=lite&type=calctraffic&shows="+show,
	   data: target+money+cats,
	   success:function(data){
		  	data = data.split(',');
			if(show==1){
				data[0]*=100;
			}
			data[0] = Number(data[0]).toFixed(1);
			stop=0;
			if(data[5]>0.007 || show==1){pr=data[5];}else{pr=0.007;stop=1;}
			pr = (show==1)?Number(pr).toFixed(3):pr;
			$('#Pos1').html(pr+'$');
			if(data[6]>0&&stop==0){
				if(data[6]>0.007 ||  show==1){pr=data[6];}else{pr=0.007;stop=1;}
				pr = (show==1)?Number(pr).toFixed(3):pr;
				$('#Pos2').html(pr+'$');
			}else{
				if($('#secondPos').css("display")!='none'){$('#secondPos').toggle();}
			}
			if(type!=1)
				$('#price').attr('value',data[7]);
			$('#PosMin').html(data[3]+'$');
		    $('#tt_maxclicks_hlp').html('<p>При текущей цене средств хватит на: '+data[4]+' кликов</p>');
		    ToolTip('costmax_hlp');
		    ToolTip('maxclicks_hlp');
		    value = $('#FClickCost').attr('value');
		    if(value < data[3]){
		    	$('#FClickCost').attr('value',data[3]);
			}
		}
	});
}
function chCostTh(obj){
	cost=$(obj).html();
	l=cost.length;
	cost=cost.substr(0,l-1);
	$('#price').val(cost);
	CalcTraffic(1);
}
function ToolTipOper(id){
	$('#'+id).mouseout(function(){
		$('#tt_'+id).css({display: "none"});
	});
	$('#'+id).mouseover(function(){
		offset=$(this).offset();
		win_width=$().width();win_height=$().height();
		tt_width=$('#tt_'+id).width();tt_height=$('#tt_'+id).width()
		lch=(tt_width+offset.left>win_width)?tt_width:0;
		tch=(tt_height+offset.top>win_height)?tt_height:0;
		tch=(tch>offset.top+20)?offset.top:tch;
		tch=0; //мера временная, пока не будет времени довести до ума - расчет позиции от верхнего края.
		$('#tt_'+id).css({display : "block", top: offset.top+20-tch, left: offset.left+10-lch});
	});	
}
function ToolTip(id){
	if(id){
		ToolTipOper(id);
	} else {
		$(".tooltip").each(function(){
			id = $(this).attr('id');
			id = id.substring(3);
			ToolTipOper(id);
		});
	}
}
function CheckImg(){
	rt=false;
	str = location.href;
	if(str.indexOf('var=form')>0 && str.indexOf('idobj=')<0){
		a = $('#loc_input').attr('value');
		b = $('#url_input').attr('value');
		if (a == '' && b == ''){
			alert("Нужно добавить рисунок");
		} else if(b!=''){
			if (b.substr(0,4)=='http'){
				rt=true;
				$.ajax({type: "POST",url: "/?act=lite&type=testimg",data: {'url':b},success: function(data){
					if(data==1){rt=true;}
					else{alert("Рисунка по ссылке нет. Проверьте пожалуйста ссылку.");}
				}});
			} else {
				alert("Неверная ссылка попробуйте еще");
			}
		} else if(a!=''){rt=true;}
	} else {
		rt=true;
	}
	return rt;
}
function minCost(){
	userprice = $('#PosMin').attr('value');
	cost=$('#price').attr('value');
	show = $('#price').val();
	if(userprice>0){
		if (cost < userprice ){
			alert('Вам необходимо увеличить цену за клик, у вас слишком низкий CTR\nСейчас цена будет изменена на минимальную.');
			cost=$('#price').val(userprice);
			return false;
		}
		return true;
	}else{
		if (mc > cost){
			alert('Вам необходимо увеличить цену за клик, у вас слишком низкий CTR\nСейчас цена будет изменена на минимальную.');
			$("#price").val(mc);
			return false;
		}
		return true;
	}
}
function checkCost(id){
	$.ajax({
		type: "POST",
		url: "/",
		data: "act=lite&type=minCost&idobj="+id,
		success: function(data){
			arr=data.split(",");
			if (arr[0]>arr[1]){
				 if (confirm("У вас слишком низкий CTR, необходимо повысить цену на пост\nХотите ли поднять автоматически цену и стартовать пост?"))document.location.href="/?act=lite&type=changeCost&idobj="+id;
			}else document.location.href="/?act=lite&type=changeCost&idobj="+id;
		}
	});
}
function override(id,tbl){
	$.get("?act=lite&type=getCurUser&tbl="+tbl+"&id="+id,function(str){
			email=$.trim(prompt('Введите E-Mail пользователя'+str));
			if(email!='' && email!=null){
				$.get("?act=lite&type=override&idobj="+id+"&tbl="+tbl+"&email="+email,function(data){
					if(data=='true')alert('Пользователь переопределен');else alert('E-Mail введен неверно');
				});
			}
		});
}
function recalc(id,loc){
	$.get("?act=lite&type=getRecalcTime&idobj="+id,function(time){
		if(confirm('Статистика поста будет сброшена.\nПримерное время перерасчета '+time+'.\nВы уверены, что хотите продолжить?')){
			$.get("?act=lite&type=recalc&idobj="+id,function(data){
				if(data=='true'){alert('Статистика сброшена.');document.location.href=loc}else{alert('Статистика не сброшена');}
			});
		}
	});
}

function readTicket(messId){
	$.ajax({
			type:"GET",
			url:"/",
			data:"act=lite&type=readTicket&idobj="+messId,
			success:function(data){
				$('#ticketBox').slideUp('slow');
			}
		});
}

function getTargShows(dataStr,selCats,cid,price){
	$('#showsInfo').html("<img alt=\"\" src=\"/files/images/loader.gif\" style=\"width:10px;height:10px;\"/>");
	$.ajax({
		type:"GET",
		url:"/",
		data:"act=lite&type=getTargShows&idobj="+dataStr+"&selCats="+selCats+"&cid="+cid+"&price="+price,
		success:function(data){
			$('#showsInfo').html(data);
		}
	});
}
