// JavaScript Document

/*
var oEditor = FCKeditorAPI.GetInstance('InstanceName') ;
oEditor.GetXHTML( formatted )
oEditor.SetHTML( html )
oEditor.GetHTML()

function ajaxLoad() {
	var inst = tinyMCE.getInstanceById('content');

	// Do you ajax call here
	inst.setHTML('HTML content that got passed from server.');
}

function ajaxSave() {
	var inst = tinyMCE.getInstanceById('content');

	// Do you ajax call here
	alert(inst.getHTML());
}
*/

function CreateBulba(content)
{
	bulba	= '';
	bulba	+= '<table class="bulba" cellpadding="0" cellspacing="0">';
	bulba	+= '<tr>';
	bulba	+= '<td class="tableleft"><div class="topleft"></div></td>';
	bulba	+= '<td class="content">'+content+'</td>';
	bulba	+= '<td class="tableright"><div class="topright"></div></td>';
	bulba	+= '</tr>';
	bulba	+= '<tr class="tablebottom">';
	bulba	+= '<td class="botleft"></td>';
	bulba	+= '<td class="botcenter">&nbsp;</td>';
	bulba	+= '<td class="botright">&nbsp;</td>';
	bulba	+= '</tr>';
	bulba	+= '</table>';
	return	bulba;
}

function decodeHtmlEntities(str)
{
	$('<div id="entitiesDecoder"></div>').appendTo("body")
	$('#entitiesDecoder').empty();
	html	= $('#entitiesDecoder').append(str).text();
	$('#entitiesDecoder').remove();
	return	html;
}

function GetXML(xmlURL)
{
	return	$.ajax({ url:xmlURL, type:'GET', dataType:'xml', async:false,
				error:function(){ alert('Error loading XML document'); }
			}).responseXML;
}

function GetHTML(htmlURL)
{
	return	$.ajax({ url:htmlURL, type:'GET', async:false,
				error:function(){ alert('Error loading HTML document'); }
			}).responseText;
}

jQuery.fn.myLabelOver = function(options){
	options = jQuery.extend({
		text: ''
	}, options);
	var item_id		= $(this).attr('for');
	var $item		= $('#'+item_id);
	var $parent		= $('#'+item_id).parent();
	var	item_name	= $item.attr('name');
	var	item_val	= $item.val();
//	alert(inputType+' = '+$('#'+item_id).val());
	$item.val(options.text);
	
	var	inputType	= $('#'+item_id).attr('type');
	if (inputType == 'password')
	{
		if ($.browser.msie)
		{
			$item.after('<input type="text" name="'+item_name+'_temp" id="'+item_id+'_temp" validation="type:pass, required:1, length:40" />');
			$item.remove();
			$('#'+item_id+'_temp').attr('name',item_name);
			$('#'+item_id+'_temp').val(item_val);
			$('#'+item_id+'_temp').attr('id',item_id);
		}
		else
		{
			$('#'+item_id).attr('type','text');
		}
//		alert(inputType+' = '+$('#'+item_id).val());

		inputType	= $('#'+item_id).attr('type');
//		alert(inputType);
	}
	$('#'+item_id).focus(function(){
		if ($.browser.msie)
		{
			item_id		= $(this).attr('id');
			$(this).after('<input type="'+inputType+'" name="'+item_name+'" id="'+item_id+'_temp" validation="type:pass, required:1, length:40" />');
			$(this).remove();
			$('#'+item_id+'_temp').attr('name',item_name);
			$('#'+item_id+'_temp').val(item_val);
			$('#'+item_id+'_temp').attr('id',item_id);
		}
		else
		{
			$(this).attr('type',inputType);
		}
		$(this).val('');
		$(this).unbind('focus');	//	one time
	});
};

jQuery.fn.addFckInstance = function(){
	instanceId	= $(this).attr("id");
	oFCKeditor = new FCKeditor(instanceId);
	oFCKeditor.BasePath = "/" ;
	oFCKeditor.ToolbarSet = 'MyBasic' ;
	oFCKeditor.ReplaceTextarea() ;
/*
	var div = document.getElementById(instanceId);
	var fck = new FCKeditor(instanceId);
	div.innerHTML = fck.CreateHtml();
*/

/*
	//	oFCKeditor.Create();
	//	delete oFCKeditor;
	//	fckconfig.js	in scripts/
*/
};

jQuery.fn.removeFckInstance = function(){
	instanceId	= $(this).attr("id");
//	var oFCKeditor = new FCKeditor(instanceId);
};

jQuery.fn.getFckValue = function(){
	instanceId	= $(this).attr("id");
	if ($('#'+instanceId).html() != "" && $('#'+instanceId).html() != null)
	{
		var oEditor = FCKeditorAPI.GetInstance(instanceId) ;
//		oEditor.GetXHTML( formatted )
//		oEditor.SetHTML( html )
		return	oEditor.GetHTML();
	}
	else	return	'';
};

jQuery.fn.addMceInstance = function(){
	instanceId	= $(this).attr("id");
	if (tinyMCE.getInstanceById(instanceId) == null)	tinyMCE.execCommand('mceAddControl', false, instanceId);
};

jQuery.fn.removeMceInstance = function(){
	instanceId	= $(this).attr("id");
	if (tinyMCE.getInstanceById(instanceId) != null)	tinyMCE.execCommand('mceRemoveControl', false, instanceId);
};

jQuery.fn.getMceValue = function(){
	instanceId	= $(this).attr("id");
	if ($('#'+instanceId).html() != "" && $('#'+instanceId).html() != null)
	{
		var		elm = document.getElementById(instanceId);
		return	tinyMCE.getInstanceById(instanceId).getHTML();
	}
	else	return	'';
};

function InvokeEditable(itemId,url,inputPrefix,inputType,initValue)
{
	if (inputPrefix!='')
	{
		inputItemId	= 'input_'+inputPrefix+itemId;
		formId		= 'form_'+inputPrefix+itemId;
		submitId	= 'submit_'+inputPrefix+itemId;
	}
	else
	{
		inputItemId	= 'input_'+itemId;
		formId		= 'form_'+itemId;
		submitId	= 'submit_'+itemId;
	}
	$this		= $('#'+itemId);
	var thisValue	= $this.text();
	if (initValue != '')	thisValue	= initValue;

	if ($this.attr("editing")!="true" && $this.attr("editing")!="false")	$this.attr("editing","false");
	if ($this.attr("editing") == "true")	return	false;

	if (inputType == 'textarea')
	{
		html_form	= '<form id="'+formId+'"><textarea rows="4" style="width:100%" name="value" id="'+inputItemId+'">'+thisValue+'</textarea><br /><input id="'+submitId+'" type="button" value="OK"></form>';
	}
	if (inputType == 'text')
	{
		html_form	= '<form id="'+formId+'"><input type="text" name="value" id="'+inputItemId+'"><input id="'+submitId+'" type="button" value="OK"></form>';
	}

	$this.empty();
	$this.after(html_form);

	$thisInput	= $('#'+inputItemId);
	$thisForm	= $('#'+formId);
	$thisSubmit	= $('#'+submitId);

	if (inputType != 'textarea')
	{
		$thisInput.css('display','inline');
		$thisForm.css('display','inline');
		$thisSubmit.css('display','inline');
	}
	$thisInput.val(thisValue);
	$this.attr("editing","true");
	$thisSubmit.click(function(){
		$this.attr("editing","false");
		strSerializedForm	= $thisForm.formSerialize();
		thisValue			= $thisInput.val();
		thisValue			= $.ajax({ url:url, data: strSerializedForm, type:"POST", async:false }).responseText;
		$this.html(thisValue);
		$thisForm.remove();
	});
	return	thisValue;
}

function InvokeMceEditable(mceEditableElementId,url,name,tooltip)
{
	$this	= $('#'+mceEditableElementId);
	if (url=='')		return	false;
	if (tooltip!='')	$this.attr('title',tooltip);

	var itemId	= mceEditableElementId;
	if ($this.attr("editing")!="true" && $this.attr("editing")!="false")	//	If not set
	{
		$this.attr("editing","false");
	}

	if ($this.attr("editing") == "true")	return	false;
	newValue	= $('#forumMceEditValue').getMceValue();	//	Reading MCE value
	if (!newValue)	newValue	= $this.html();			//	Reading DIV html

	htmlEditForm	= '<form id="forumMceEditForm"><textarea name="'+name+'" id="forumMceEditValue" cols="60" rows="15" style="width:100%">'+newValue+'</textarea><center><input id="forumMceEditSubmit" type="button" value="Сохранить"></center></form>';
	$this.empty();
	$this.append(htmlEditForm);
	$('#forumMceEditValue').css("width","100%");

	//	Adding new tinyMCE instance
	$('#forumMceEditValue').addMceInstance();
	$this.attr("editing","true");
	$('#forumMceEditSubmit').click(function(){
		newValue	= $('#forumMceEditValue').getMceValue();	//	Reading MCE value
		$('#forumMceEditValue').val(newValue);

		strSerializedForm	= $('#forumMceEditForm').formSerialize();
		strSerializedForm	= 'id='+itemId+'&'+strSerializedForm;
		//	Removing old tinyMCE instance
		$('#forumMceEditValue').removeMceInstance();
		$('#forumMceEditForm').remove();
		$('#'+itemId).attr("editing","false");
		newValue	= $.ajax({ url:url,	data: strSerializedForm, type:"POST", async:false }).responseText;
		$('#'+itemId).html(newValue);
	});
	return	false;
}

jQuery.fn.mceEditable = function(options) {
	options = jQuery.extend({
		url: '',
		name: 'id',
		tooltip: ''
	}, options);

	if (options.url=='')	return	false;
	if (options.tooltip!='')	$(this).attr('title',options.tooltip);

	$(this).click(function(){
		var itemId	= this.id;
		if ($(this).attr("editing")!="true" && $(this).attr("editing")!="false")	//	If not set
		{
			$(this).attr("editing","false");
		}

		if ($(this).attr("editing") == "true")	return	false;
		newValue	= $('#forumMceEditValue').getMceValue();	//	Reading MCE value
		if (!newValue)	newValue	= $(this).html();			//	Reading DIV html

		htmlEditForm	= '<form id="forumMceEditForm"><textarea name="'+options.name+'" id="forumMceEditValue" cols="60" rows="15" style="width:100%">'+newValue+'</textarea><center><input id="forumMceEditSubmit" type="button" value="Сохранить"></center></form>';
		$(this).empty();
		$(this).append(htmlEditForm);
		$('#forumMceEditValue').css("width","100%");

		//	Adding new tinyMCE instance
		$('#forumMceEditValue').addMceInstance();
		$(this).attr("editing","true");
/*
		$('#forumMceEditValue').blur(function(){
			alert('test3 blur');
			$('#forumMceEditForm').submit();
		});
		
		$('#forumMceEditValue').mouseout(function(){
			alert('test3 out');
			$('#forumMceEditForm').submit();
		});
*/
		$('#forumMceEditSubmit').click(function(){
			newValue	= $('#forumMceEditValue').getMceValue();	//	Reading MCE value
			$('#forumMceEditValue').val(newValue);

			strSerializedForm	= $('#forumMceEditForm').formSerialize();
			strSerializedForm	= 'id='+itemId+'&'+strSerializedForm;
			//	Removing old tinyMCE instance
			$('#forumMceEditValue').removeMceInstance();
			$('#forumMceEditForm').remove();
			$('#'+itemId).attr("editing","false");
			newValue	= $.ajax({ url:options.url,	data: strSerializedForm, type:"POST", async:false }).responseText;
			$('#'+itemId).html(newValue);
		});

		return	false;
	});
	return	true;

};

jQuery.fn.fckEditable = function(options) {
	options = jQuery.extend({
		url: '',
		name: 'id'
	}, options);

	if (options.url=='')	return	false;

	$(this).click(function(){
		var itemId	= this.id;
		if ($(this).attr("editing")!="true" && $(this).attr("editing")!="false")	//	If not set
		{
			$(this).attr("editing","false");
		}

		if ($(this).attr("editing") == "true")	return	false;
		newValue	= $('#forumFckEditValue').getMceValue();	//	Reading MCE value
		if (!newValue)	newValue	= $(this).html();			//	Reading DIV html

		htmlEditForm	= '<form id="forumFckEditForm"><textarea name="'+options.name+'" id="forumFckEditValue" cols="60" rows="15" style="width:100%">'+newValue+'</textarea><center><input id="forumFckEditSubmit" type="button" value="Сохранить"></center></form>';
		$(this).empty();
		$(this).append(htmlEditForm);

		//	Adding new tinyMCE instance
		$('#forumFckEditValue').addFckInstance();
		$(this).attr("editing","true");

		$('#forumFckEditValue').blur(function(){
			alert('test3 blur');
			$('#forumFckEditForm').submit();
		});
		
		$('#forumFckEditValue').mouseout(function(){
			alert('test3 out');
			$('#forumFckEditForm').submit();
		});
		
		$('#forumFckEditSubmit').click(function(){
			newValue	= $('#forumFckEditValue').getFckValue();	//	Reading MCE value
			$('#forumFckEditValue').val(newValue);

			strSerializedForm	= $('#forumFckEditForm').formSerialize();
			strSerializedForm	= 'id='+itemId+'&'+strSerializedForm;
			//	Removing old tinyMCE instance
			$('#forumFckEditValue').removeFckInstance();
			$('#forumFckEditForm').remove();
			$('#'+itemId).attr("editing","false");
			newValue	= $.ajax({ url:options.url,	data: strSerializedForm, type:"POST", async:false }).responseText;
			$('#'+itemId).html(newValue);
		});

		return	false;
	});
	return	true;

};

jQuery.fn.CreateLoadingMessage	= function(options)
{
	options = jQuery.extend({
		width: 300,
		height: 100,
		message: 'Loading...'
	}, options);

	var	left	= $(document).width()/2 - options.width/2;
	var	top		= $(window).height()/2 - options.height/2;
	
	
	$(this).ajaxStart(function() {
		//$(this).show();
		$(this).fadeIn("slow");
//		$(this).slideDown("slow");

		$(this).css("position","absolute");
		loading_left	= parseInt( $('body').css('width') ) / 2;
		loading_left	= loading_left - 175;
		loading_top		= 300;	//$('body').css('height') / 2;
		
//		alert( loading_left+' '+$('body').css('height') );
//		$(this).css("left",loading_left+"px");
//		$(this).css("top",loading_top+"px");
		$(this).css("left",left+"px");
		$(this).css("top",top+"px");

//		$(this).offset().top	= $(document).css('height') / 2;
//		$(this).offset().left	= $(document).css('width') / 2;
	}).ajaxStop(function() {
//		$(this).hide();
		$(this).fadeOut("slow");
//		$(this).slideUp("slow");
	});
}

jQuery.fn.createImageCode = function(options) {
	options = jQuery.extend({
		scriptUrl: 'ajax/create.imagecode.php',
		imageUrl: 'http://localhost/groups/imagecode.php',
		codeId: 'code'
	}, options);
	strImagecodeId	= $(this).attr('id');
	options.scriptUrl	+= '?rnd='+Math.random();
	
	$.ajax({ url:options.scriptUrl, async: false, success: function(response)	{
				if (response != "0")
				{
					options.imageUrl	+=	'?key='+response+'&rnd'+Math.random();
					$('#'+strImagecodeId).attr('src',options.imageUrl);
					strCodeValidation	= $('#'+options.codeId).attr('validation');
					if (strCodeValidation!="")	strCodeValidation	+= ', match:'+response;
					else						strCodeValidation	= 'match:'+response;
					$('#'+options.codeId).attr('validation',strCodeValidation);
				}
			}
	});
};

jQuery.fn.loadOptions = function(options) {
	options = jQuery.extend({
		url: '',
		target: $(this).attr('id'),
		filter: false,
		selectedItem: false,
		empty: false
	}, options);

	if (options.url!="")
	{
		$.post(options.url, {filter: options.filter, empty: options.empty}, function(data){
			$('#'+options.target).html(data);
			if (options.selectedItem!=false)
			{
				$("option[@value='"+options.selectedItem+"']", $('#'+options.target)).attr("selected","selected");
			}
			else
			{
				$("option:first", $('#'+options.target)).attr("selected","selected");
			}
		});
	}
	else	return '';
};

jQuery.fn.formSerializeValidation = function(options) {
	var formId		= $(this).attr('id');
	var arrInputs	= $('#'+formId+' input');
	var arrTextareas= $('#'+formId+' textarea');
	
	strSV	= "";
	$.each( arrInputs, function(i, n){
		if (($(n).attr('validation') != "") && ($(n).attr('validation') != null) )
		{
			if (strSV!='')	strSV	+= '&';
			strSV += 'val_'+$(n).attr('name')+'='+$(n).attr('validation');
		}
	});
	$.each( arrTextareas, function(i, n){
		if (($(n).attr('validation') != "") && ($(n).attr('validation') != null) )
		{
			if (strSV!='')	strSV	+= '&';
			strSV += 'val_'+$(n).attr('name')+'='+$(n).attr('validation');
		}
	});
	return	strSV;//$.param();
};

jQuery.fn.linkAjaxValidation = function(options) {
	var valResultHandler = function(xmlResponse){
		if($("status",xmlResponse).text() == "1") return true;	/*	status: 1 = ok, 2 = errors	*/

//		$(".validation_error").remove();

		$("error",xmlResponse).each(function(id) {
			error = $("error",xmlResponse).get(id);
			message		= $("message",error).text();
			inputname	= $("inputname",error).text();

			alert(message);
//			$("input[@name="+inputname+"]").after("<div class='validation_error'>"+message+"</div>");
		});
		return	false;
	};
	var formResultHandler = function(responseText) {
		$(strFormResultId).html(responseText);
		$(strFormResultId).css("display","block");
//		$(strFormId).remove();
	};

	var ajaxValError	= function() { alert("Error in Val Handling"); };
	var ajaxFormError	= function() { alert("Error in Form Handling"); };
	options = jQuery.extend({
		validationURL: 'validate.php',
		validationHandler: valResultHandler,
		formHandler: formResultHandler,
		formResult: '#formResult'	//	ID for default formHandler
	}, options);
	strFormId				= '#'+$(this).attr('id');
	strFormResultId			= options.formResult;

	$(this).ajaxForm({ beforeSubmit:function() {

		var strSerializedForm		= $(strFormId).formSerialize();
		var strSerializedFormVal	= $(strFormId).formSerializeValidation();
		if (strSerializedFormVal!='')	strSerializedForm	+= '&'+strSerializedFormVal;
		xmlResponse	= $.ajax({ url: options.validationURL, data: strSerializedForm, dataType: "xml", async: false, timeout:2, error: ajaxValError, success: options.validationHandler }).responseXML;	//.responseText

		if($("status",xmlResponse).text() == 1)	return	true;	//	1 means that validation is ok
		else									return	false;	//	2 means that there are errors

	}, success: options.formHandler, error: ajaxFormError, async: false });
};