var $j = jQuery.noConflict();

$j(document).ready(function()
{
     // Сбрасываем размер шрифта  
     $j("#font_normal").click(function()
	 {  
         $j('.article-content').css('font-size', 15);  
		 $j('.tools ul li').removeClass("active");
		 $j(this).parent().addClass("active");
         return false;  
     });
     // Увеличиваем размер шрифта  
     $j("#font_big").click(function()
	 {  
         $j('.article-content').css('font-size', 18);  
		 $j('.tools ul li').removeClass("active");
		 $j(this).parent().addClass("active");
         return false;  
     });  
     // Уменьшаем размер шрифта  
     $j("#font_small").click(function()
	 {  
         $j('.article-content').css('font-size', 12);  
		 $j('.tools ul li').removeClass("active");
		 $j(this).parent().addClass("active");
         return false;  
     });  
	 // Проверка ввода кода подтверждения смены email
	 $j("#id_confirmstr").keyup(function() 
	 {
		 // check input ($(this).val()) for validity here
		 var code=$j(this).val();
		 //alert(code.length);
		 if (code.length==5)
		 {
			 $j("#id_savebutton").attr("disabled","");
		 }
		 else
		 {
			 $j("#id_savebutton").attr("disabled","disabled");
		 }
	 });
	 // Добавляем товар "Не показывать рекламу" в корзину
	 $j(".class_not_advert").click(function()
	 {
		 jsAjaxUtil.ShowLocalWaitWindow('waitidFormProfile', 'idFormProfile');
		 $j.ajax(
		 {
			 url: '/ajax/index.php', 
			 type: "POST", 
			 timeout: 15000, 
			 cache: false,
			 data: 
			 {
				 cmd: 'buyNotAdvert'
			 },
			 dataType: 'text', 
			 success: function(data)
			 {
				 var arData=AjaxResultsDecode(data);
				 if (arData["ERROR"]=="")
				 {
					 document.location='/personal/cart/';
					 document.getElementById("idFormProfile").innerHTML="Подождите, идет перенаправление...";
				 }
				 else
				 {
					 alert(arData["ERROR"]);				
				 }
				 jsAjaxUtil.CloseLocalWaitWindow('waitidFormProfile', 'idFormProfile');
			 }, error: function(event) {}
		 });
		 return false;
	 });	
	 
	 $j(".buy_subscribe").click(function()
	 {
		 $j(".vip").html("Подождите, идет перенаправление...");
		 $j.ajax(
		 {
			 url: '/ajax/index.php', 
			 type: "POST", 
			 timeout: 15000, 
			 cache: false,
			 data: 
			 {
				 cmd: 'buyNotAdvert'
			 },
			 dataType: 'text', 
			 success: function(data)
			 {
				 var arData=AjaxResultsDecode(data);
				 if (arData["ERROR"]=="")
				 {
					 document.location='/personal/cart/';
				 }
				 else
				 {
					 alert(arData["ERROR"]);				
				 }
			 }, error: function(event) {}
		 });
		 return false;
	 });
	 
	 $j(".article2email").click(function()
	 {
		 var html=$j(".vip").html();
		 $j(".vip").html("Подождите, идет перенаправление...");
		 var newid=$j(this).attr("rel");
		 $j.ajax(
		 {
			 url: '/ajax/index.php', 
			 type: "POST", 
			 timeout: 15000, 
			 cache: false,
			 data: 
			 {
				 cmd: 'article2email',
				 newid: newid
			 },
			 dataType: 'text', 
			 success: function(data)
			 {
				 var arData=AjaxResultsDecode(data);
				 if (arData["ERROR"]=="")
				 {
					 document.location='/personal/cart/';
				 }
				 else
				 {
					 $j(".vip").html(html);
					 alert(arData["ERROR"]);				
				 }
			 }, error: function(event) {}
		 });
		 return false;
	 });
	 
	 // Активизируем tooltip'ы
	 setTooltips();
	 
	 $j("#link").focus(function()
	 {
		 if ($j(this).val()=="Ссылка") $j(this).val("");
     }); 
	 $j("#link-description").focus(function()
	 {
		 if ($j(this).html()=="Описание ссылки") $j(this).html("");
     });
	 $j("#form_read_submit").click(function()
	 {
		 if ($j("#link").val()=="Ссылка") $j("#link").val("");
		 if ($j("#link-description").html()=="Описание ссылки") $j("#link-description").html("");
     });
	 
	 $j('.textarea_comment').maxlength( {maxCharacters: 20000, statusText: "символов осталось", notificationClass: "textarea_comment_notification"} ); 
	 
 });  

function showPhoto(id)
{
	if (document.getElementById(id))
	{
		document.getElementById(id).style.display = 'block';
	}
}
function hidePhoto(id)
{
	if (document.getElementById(id))
	{
		document.getElementById(id).style.display = 'none';
	}
}

var tooltipTimeOut=null;

function closeTooltip(ob)
{
	clearTimeout(tooltipTimeOut);
	$j(".tooltip[allowHide=1]").fadeOut("400");
}

function setTooltips()
{
	$j(".tooltip").mouseover(function()
	{
		$j(this).attr("allowHide","0");
	}).mouseleave(function()
	{
		$j(this).attr("allowHide","1");
		//$j(this).fadeOut(400);
		setTimeout(closeTooltip, 1000);
		//setTimeout(closeTooltip, 3000);
	});
	
	$j(".a_tooltip").each(function(i)
	{
		var my_tooltip = $j("#"+$j(this).attr('rel'));
		$j(this).mouseover(function()
		{
			if (my_tooltip.html()=="")
			{
				my_tooltip.html("Загрузка...");
				$j.ajax(
				 {
					 url: '/ajax/index.php', 
					 type: "POST", 
					 timeout: 15000, 
					 cache: false,
					 data: 
					 {
						 cmd: 'getTooltip',
						 rel: my_tooltip.attr("rel")
					 },
					 dataType: 'text', 
					 success: function(data)
					 {
						 //var arData=AjaxResultsDecode(data);
						 //alert(data);
						 my_tooltip.html(data);
					 }, error: function(event) {}
				 });
			}
			clearTimeout(tooltipTimeOut);
			$j(".tooltip[allowHide=1]").css("display","none");
			var position = $j(this).position();
			my_tooltip.attr("allowHide","1");
			my_tooltip.css({left:position.left, top:position.top-my_tooltip.outerHeight()-5}).fadeIn(400);
		}).mouseout(function()
		{
			//my_tooltip.fadeOut(400);
			tooltipTimeOut=setTimeout(closeTooltip, 1000);
		});
		/*
		.mousemove(function(kmouse)
		{
			my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
		})
		*/
	});
}

function editComment(comID)
{
	if (el=document.getElementById("comment_"+comID))
	{
		jsAjaxUtil.ShowLocalWaitWindow('wait'+comID, 'div'+comID);
		//jsAjaxUtil.LoadData('/ajax/index.php?cmd=getforummessage&id='+comID+'&rand='+Math.random(),editCommentFinish);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'getforummessage',
				id: comID
			}, 
			dataType: 'text', 
			success: editCommentFinish, error: function(event) {}
		});
	}
}

function editCommentFinish(data)
{
	var arData=AjaxResultsDecode(data);
	var comID=arData["ID"];
	if (el=document.getElementById("comment_"+comID))
	{
		if (arData["ERROR"]=="")
		{
			el.innerHTML=arData["EDITFORM"];
		}
		else
		{
			alert(arData["ERROR"]);
		}
		jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
	}
}

function setBackComment(comID)
{
	if (el=document.getElementById("comment_"+comID))
	{
		jsAjaxUtil.ShowLocalWaitWindow('wait'+comID, 'div'+comID);
		//jsAjaxUtil.LoadData('/ajax/index.php?cmd=getforummessage&id='+comID+'&rand='+Math.random(),setBackCommentFinish);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'getforummessage',
				id: comID
			}, 
			dataType: 'text', 
			success: setBackCommentFinish, error: function(event) {}
		});
	}
}

function setBackCommentFinish(data)
{
	var arData=AjaxResultsDecode(data);
	var comID=arData["ID"];
	if (el=document.getElementById("comment_"+comID))
	{
		el.innerHTML=arData["POST_MESSAGE_TEXT"];
		jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
	}
}

function saveComment(comID)
{
	if (el=document.getElementById("id_message_"+comID))
	{
		var messNew=document.getElementsByName("message_"+comID).item(0).value;
		messNew=messNew.split("\r").join("");
		messNew=messNew.split("<script").join("< script");
		messNew=messNew.split("\n").join("<br>");
		jsAjaxUtil.ShowLocalWaitWindow('wait'+comID, 'div'+comID);
//jsAjaxUtil.LoadData('/ajax/index.php?cmd=saveforummessage&id='+comID+'&message='+messNew+'&rand='+Math.random(),saveCommentFinish);      
        $j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'saveforummessage',
				id: comID,
				message: messNew
			}, 
			dataType: 'text', 
			success: saveCommentFinish, error: function(event) {}
		});
	}
}

function saveCommentFinish(data)
{
	//document.write(data);
	var arData=AjaxResultsDecode(data);
	var comID=arData["ID"];
	if (el=document.getElementById("comment_"+comID))
	{
		if (arData["ERROR"]!="")
		{
			alert(arData["ERROR"]);
		}
		el.innerHTML=arData["POST_MESSAGE_TEXT"];
		if (arData["HIDE_EDITOR"]=="Y")
		{
			$j("#editcomment_"+comID).hide();
			$j("#delcomment_"+comID).hide();
		}
		jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
	}
}

function AjaxResultsDecode(str,equal,razd)
{
	if (equal==undefined) equal="%=%";
	if (razd==undefined) razd="%|%";
	var arParam=str.split(razd);
	var count=arParam.length;
	var arReturn=new Array();
	for (var i=0;i<count;i++)
	{
		if (strpos(arParam[i], "Parse error")!=false)
		{
			alert(arParam[i]);
			break;
		}
		arI=arParam[i].split(equal);
		if (arI[1]!=undefined)
		{
			arReturn[arI[0]]=arI[1];
		}
	}
	return(arReturn);
}

function delComment(comID)
{
	if (confirm("Удалить?"))
	{
	if (el=document.getElementById("comment_"+comID))
	{
		jsAjaxUtil.ShowLocalWaitWindow('wait'+comID, 'div'+comID);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'delmessage',
				id: comID
			}, 
			dataType: 'text', 
			success: delCommentFinish, error: function(event) {}
		});
	}
	}
}

function delCommentFinish(data)
{
	var arData=AjaxResultsDecode(data);
	var comID=arData["ID"];
	if (el=document.getElementById("comment_"+comID))
	{
		if (arData["ERROR"]=="")
		{
			jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
			document.getElementById("editcomment_"+comID).innerHTML="";
			document.getElementById("delcomment_"+comID).innerHTML="";
			document.getElementById("comment_"+comID).innerHTML=arData["POST_MESSAGE_TEXT"];
			if (arData["SHOW_MESSAGE"]!="")
			{
				alert(arData["SHOW_MESSAGE"]);
			}
		}
		else
		{
			jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
			alert(arData["ERROR"]);
		}
	}
}

function allowSendMessage(form)
{
	if (form.id)
	{
		var request=getRequestBody(form.id);
		jsAjaxUtil.ShowLocalWaitWindow('form_wait', "div_"+form.id);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'getformauth',
				formid: form.id,
				request: request
			}, 
			dataType: 'text', 
			success: function (data)
			{
				var arData=AjaxResultsDecode(data);
				if (arData["ERROR"]=="")
				{
					document.getElementById("div_"+arData["FORMID"]).innerHTML=document.getElementById("auth_comment_form").innerHTML;
				}
				else
				{
					alert(arData["ERROR"]);
				}
				jsAjaxUtil.CloseLocalWaitWindow('form_wait', "div_"+arData["FORMID"]);
			}, error: function(event) {}
		});
	}
	return false;
}


function delCommentFull(comID)
{
	if (confirm("Отменить публикацию?"))
	{
	if (el=document.getElementById("comment_"+comID))
	{
		jsAjaxUtil.ShowLocalWaitWindow('wait'+comID, 'div'+comID);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'delmessagefull',
				id: comID
			}, 
			dataType: 'text', 
			success: delCommentFullFinish, error: function(event) {}
		});
	}
	}
}

function delCommentFullFinish(data)
{
	var arData=AjaxResultsDecode(data);
	var comID=arData["ID"];
	if (el=document.getElementById("comment_"+comID))
	{
		if (arData["ERROR"]=="")
		{
			jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
			//document.getElementById("editcomment_"+comID).innerHTML="";
			//document.getElementById("delcomment_"+comID).innerHTML="";
			//document.getElementById("comment_"+comID).innerHTML=arData["POST_MESSAGE_TEXT"];
			if (document.getElementById("div"+comID))
			{
				document.getElementById("div"+comID).style.display="none";
			}
			alert("Публикация комментария отменена");
			//alert(arData["ERROR"]);
		}
		else
		{
			if (document.getElementById("a_delcommentfull_"+comID))
			{
				document.getElementById("a_delcommentfull_"+comID).style.display="none";
			}
			if (document.getElementById("delcommentfull_"+comID))
			{
				document.getElementById("delcommentfull_"+comID).style.display="none";
			}
			jsAjaxUtil.CloseLocalWaitWindow('wait'+comID, 'div'+comID);
			alert(arData["ERROR"]);
		}
	}
}

// Проверка формы в профиле пользователя
function AjaxCheckProfileForm()
{
	jsAjaxUtil.ShowLocalWaitWindow('waitCheckProfileForm', 'idFormProfile');
	var email=$j("#id_profile_email").val();
	var confirmstr=$j("#id_confirmstr").val();
	if ($j("#id_confirmstr").parent().css("display")=="none")
	{
		confirmstr="";
		$j("#id_confirmstr").val("");
	}
	$j.ajax(
	{
		url: '/ajax/index.php', 
		type: "POST", 
		timeout: 15000, 
		cache: false,
		data: 
		{
			cmd: 'checkProfileForm',
			email: email,
			confirmstr: confirmstr
		},
		dataType: 'text', 
		success: function(data)
		{
			//alert(data);
			var arData=AjaxResultsDecode(data);
			if (arData["ERROR"]=="")
			{
				//$j("#group_"+arData["rowID"]).val(arData["GROUP"]);
				if (arData["CHECK"]=="Y")
				{
					$j("#id_savebutton").attr("disabled","disabled");
					alert("На "+email+" выслан код подтвреждения. Вставьте его в соответствующее поле");
					$j("#p_email_check").show("slow");
				}
				else
				{
					//alert("Все ок");
					jsAjaxUtil.CloseLocalWaitWindow('waitCheckProfileForm', 'idFormProfile');
					document.getElementById("idFormProfile").submit();
				}
			}
			else
			{
				alert(arData["ERROR"]);				
			}
			jsAjaxUtil.CloseLocalWaitWindow('waitCheckProfileForm', 'idFormProfile');
		}, error: function(event) {}
	});
}

// Проверка заполненность полей профиля для добавления юзера в эксперты
function AjaxCheckSetExpert(user_id,com_id,type,element_id)
{
	jsAjaxUtil.ShowLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+com_id);
	$j.ajax(
	{
		url: '/ajax/index.php', 
		type: "POST", 
		timeout: 15000, 
		cache: false,
		data: 
		{
			cmd: 'CheckSetExpert',
			com_id: com_id,
			type: type,
			user_id: user_id,
			element_id: element_id
		},
		dataType: 'text', 
		success: function(data)
		{
			var arData=AjaxResultsDecode(data);
			if (arData["ERROR"]=="")
			{
				document.location='/supercomment.php?type='+type+'&id='+com_id+'&element_id='+element_id+'&user_id='+user_id;
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return true;
			}
			else
			{
				alert(arData["ERROR"]);	
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return false;
			}
		}, error: function(event) {}
	});
}

// Утверждение действия автора-модератора
function CommentChangeCommit(com_id)
{
	if (confirm('Утвердить?'))
	{
	jsAjaxUtil.ShowLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+com_id);
	$j.ajax(
	{
		url: '/ajax/index.php', 
		type: "POST", 
		timeout: 15000, 
		cache: false,
		data: 
		{
			cmd: 'CommentChangeCommit',
			com_id: com_id
		},
		dataType: 'text', 
		success: function(data)
		{
			var arData=AjaxResultsDecode(data);
			if (arData["ERROR"]=="")
			{
				document.getElementById("comment_"+arData["com_id"]).innerHTML=arData["POST_MESSAGE_TEXT"];
				$j("#editcomment_"+arData["com_id"]).show();
				$j("#delcomment_"+arData["com_id"]).show();
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return true;
			}
			else
			{
				alert(arData["ERROR"]);	
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return false;
			}
		}, error: function(event) {}
	});
	}
}


// Отклонения действия автора-модератора
function CommentChangeRollback(com_id)
{
	if (confirm('Отменить?'))
	{
	jsAjaxUtil.ShowLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+com_id);
	$j.ajax(
	{
		url: '/ajax/index.php', 
		type: "POST", 
		timeout: 15000, 
		cache: false,
		data: 
		{
			cmd: 'CommentChangeRollback',
			com_id: com_id
		},
		dataType: 'text', 
		success: function(data)
		{
			var arData=AjaxResultsDecode(data);
			if (arData["ERROR"]=="")
			{
				$j("#comment_"+arData["com_id"]).html(arData["POST_MESSAGE_TEXT"]);
				$j("#editcomment_"+arData["com_id"]).show();
				$j("#delcomment_"+arData["com_id"]).show();
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return true;
			}
			else
			{
				alert(arData["ERROR"]);	
				jsAjaxUtil.CloseLocalWaitWindow('waitAjaxCheckSetExpert', 'div'+arData["com_id"]);
				return false;
			}
		}, error: function(event) {}
	});
	}
}

// Отправялем уведомление когда платная новость становится доступной всем пользователям
function vipSendMeWhereNewAllow(newid)
{
	var tmp=$j(".vip_sendme").html();
	$j(".vip_sendme").html("Загрузка...");
	$j.ajax(
	{
		url: '/ajax/index.php', 
		type: "POST", 
		timeout: 15000, 
		cache: false,
		data: 
		{
			cmd: 'vipSendMeWhereNewAllow',
			newid: newid
		},
		dataType: 'text', 
		success: function(data)
		{
			//alert(data);
			var arData=AjaxResultsDecode(data);
			if (arData["ERROR"]=="")
			{
				$j(".vip_sendme").html(arData["OK"]);
			}
			else
			{
				$j(".vip_sendme").html(tmp);
				alert(arData["ERROR"]);
			}
		}, error: function(event) {}
	});
}

// Уведомление модератора
function AjaxReportToModerator(com_id,type,url)
{
	if (confirm('Уверены?'))
	{
		jsAjaxUtil.ShowLocalWaitWindow('waitAjaxReportToModerator', 'div'+com_id);
		$j.ajax(
		{
			url: '/ajax/index.php', 
			type: "POST", 
			timeout: 15000, 
			cache: false,
			data: 
			{
				cmd: 'ReportToModerator',
				type: type,
				url: url,
				com_id: com_id
			},
			dataType: 'text', 
			success: function(data)
			{
				var arData=AjaxResultsDecode(data);
				//alert(data);
				if (arData["ERROR"]=="")
				{
					alert(arData["MSG"]);	
					jsAjaxUtil.CloseLocalWaitWindow('waitAjaxReportToModerator', 'div'+arData["com_id"]);
					$j("#mod_buttons_"+arData["ID"]).hide("slow");
				}
				else
				{
					alert(arData["ERROR"]);	
					jsAjaxUtil.CloseLocalWaitWindow('waitAjaxReportToModerator', 'div'+arData["com_id"]);
				}
			}, error: function(event) {}
		});
	}
}


/*
  Вспомагательные функции
*/

function getRequestBody(oFormTxt)
{
	oForm=document.getElementById(oFormTxt);
	var aParams = new Array();
	for(var i = 0; i < oForm.elements.length; i++)
	{
		//alert(oForm.elements[i].name+'='+oForm.elements[i].value);
	  if (oForm.elements[i].name!="")
	  {
		  var elementType=oForm.elements[i].type.toLowerCase();
		  if (elementType!="radio")
		  {
			  var sParam = encodeURIComponent(oForm.elements[i].name);
			  sParam += "=";
			  sParam += encodeURIComponent(oForm.elements[i].value);
			  aParams.push(sParam);
			  if (elementType=="checkbox")
			  {
				  var sParam = encodeURIComponent(oForm.elements[i].name+"_checked");
				  sParam += "=";
				  if (oForm.elements[i].checked == true)
				  {
					  sParam += encodeURIComponent('Y');
				  }
				  else
				  {
					  sParam += encodeURIComponent('N');
				  }
				  aParams.push(sParam);
			  }
		  }
		  else
		  {
			if (oForm.elements[i].checked == true)
			{
				var sParam = encodeURIComponent(oForm.elements[i].name);
				sParam += "=";
				sParam += encodeURIComponent(oForm.elements[i].value);
				aParams.push(sParam);
			}
		  }
	  }
	}
	return aParams.join("&");
}

function strpos( haystack, needle, offset){	// Find position of first occurrence of a string
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

	var i = haystack.indexOf( needle, offset ); // returns -1
	return i >= 0 ? i : false;
}


function var_dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects
   for(var item in arr) {
    var value = arr[item];
   
    if(typeof(value) == 'object') { //If it is an array,
     dumped_text += level_padding + "'" + item + "' ...\n";
     dumped_text += var_dump(value,level+1);
    } else {
     dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    }
   }
  } else { //Stings/Chars/Numbers etc.
   dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
} 

function showConfirm(msg)
{
	if (msg==undefined) msg="Уверены?";
	if (confirm(msg))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function FBLogin(num)
{
	$j("#id_fblogin").val(1);
	if (num==1)
	{
		FB.login();
	}
	return false;
}
