/* rxObject - RASAMAX Object Library
SIA RASAMAX - 2009

Requirements:
rxLib
jQuery - http://jquery.com
jQuery UI - http://jqueryui.com
jQuery.form - http://malsup.com/jquery/form/

*/

if (!rx) var rx = {};

rx.objectPathToModule = rx.getScriptPath('rxObject.js');

rx = $.extend(rx, {

objectInit : function () {
$('.rx-object:not(.inited)').addClass('inited').dblclick(function (event) {
var rxObject = $(event.target).parents('.rx-object:first'), id = this.id, type = id.substring(id.indexOf('_cell')+6,id.lastIndexOf('_')), id = id.substring(id.lastIndexOf('_')+1);
rx.objectConfigToggle(type, id);
event.stopPropagation();
event.preventDefault();
});
},

objectConfigOn : function (type, id) {
$('#object_cell_'+type+'_'+id)
.addClass('config')
.prepend($('<div class="rx-object-config-bar"><table width="100%" cellpadding="0" cellspacing="0"><tr><td>&nbsp;</td><td width="20px"><span class="ui-icon ui-corner-all ui-icon-gear ui-state-default" style="float:right; position:relative; z-index:100;'+(($.browser.msie&&$.browser.version==7.0)? ' left:95%;':'')+'" title="'+rx.translate('object_settings')+'"></span></td></tr></table></div>')
	.find('.ui-icon-gear')
	.click(function(){
		rx.objectConfigSettings(type, id);
	}).end()
)
// Turn on config for included elements
.find('.rx-menu').each(function () {
	rx.menuConfigOn($(this).attr('menuId'));
}).end()
.find('.rx-main').each(function () {
	rx.articleTools('main',id);
}).end()
.find('.rx-advert').each(function () {
	rx.articleTools('advert',id);
}).end()
.find('.rx-logo').each(function () {
	rx.articleOneConfigOn('logo',id);
}).end()
.find('.rx-footer').each(function () {
	rx.articleOneConfigOn('footer',id);
}).end()
.find('.rx-search,.rx-zoom,.rx-navigation,.rx-calendar,.rx-directory,.rx-language').each(function (event) {
	rx.objectOldConfigOn(type,id);
}).end();
},

objectConfigOff : function (type, id) {
$('#object_cell_'+type+'_'+id).removeClass('config').find('.rx-object-config-bar').remove().end()
// Toggle config for included elements
.find('.rx-menu').each(function () {
	rx.menuConfigOff($(this).attr('menuId'));
}).end()
.find('.rx-main').each(function () {
	rx.articleToolsRemove('main',id);
}).end()
.find('.rx-advert').each(function () {
	rx.articleToolsRemove('advert',id);
}).end()
.find('.rx-search,.rx-zoom,.rx-navigation,.rx-calendar,.rx-directory,.rx-language').each(function (event) {
	rx.objectOldConfigOn(type,id);
}).end();
},

objectConfigToggle : function (type, id) {
// Toggle object config mode
if ($('#object_cell_'+type+'_'+id).is('.config'))
	rx.objectConfigOff(type, id);
else rx.objectConfigOn(type, id);
},

objectOldConfigOn : function(objectType, objectId) {
	$('#object_cell_'+objectType+'_'+objectId+' .rx-object-config-bar').hide();
	if ($('#object_cell_'+objectType+'_'+objectId).is('.configOldMode')) {
		$('#config_mode_for_back_form').submit();
	} else {
		$("#config_mode_for").val(objectType+'_'+objectId);
		document.forms["object_config_mode_form"].submit();
	}
},

// Screen object config mode
objectConfigSettings : function (objectType, objectId) {
var buttons = {};
buttons[rx.translate('cancel')] = function () {$('#rx-window').dialog('close');};
buttons[rx.translate('save')] = function () {$('#objectSettingsForm').submit(); rx.objectFormat(objectType, objectId);};
$('<div id="rx-window">').appendTo('body').html(rx.translate('loading')+'...')
	.dialog({
		position: ['center',50],
		bgiframe: true,
		modal : true,
		width : 400,
		show : 'scale',
		hide : 'scale',
		title : rx.translate('object_settings'),
		buttons : buttons,
		beforeclose : function() {
			// Remove Uploadify, otherwise dialog cannot be closed :\
			$('#rx-window object').remove();
		},
		close : function () {
			$('#rx-window').remove();
		}
	})
	.load(rx.objectPathToModule+'rxObjectSettings.php?type='+objectType+'&id='+objectId, null, function() {$('#rx-window input[type=text]').addClass('text ui-widget-content ui-corner-all');});
},

// Apply object setting to current screen
objectFormat : function (objectType, objectId) {
var borderWidth = $('#extra1_size').attr('value') ? parseInt($('#extra1_size').attr('value'),10) : 0;
var calcWidth = $('input[name=width]').val()-$('input[name=left_indent]').val()-$('input[name=right_indent]').val()-borderWidth*2;
var calcHeight = $('input[name=height]').val()-$('input[name=top_indent]').val()-$('input[name=bottom_indent]').val()-borderWidth*2;
$('#object_cell_'+objectType+'_'+objectId).css({
	'width' : calcWidth+'px',
	'height' : calcHeight+'px',
	'border' : $('#extra1_size').attr('value')!='0px' && $('#extra1_size').attr('value')!='' ? $('#extra1_size').attr('value')+' '+$('#extra1_style').attr('value')+' '+$('input[name=extra1_color]').val() : '',
	'background-color' : $('input[name=backgroundcolor]').val(),
	'background-image' : 'url(\''+picture_directory+'/'+$('select[name=backgroundimage]').val()+'\')',
	'background-repeat' : $('input[name=background_repeat]').is(':checked') ? 'repeat' : 'no-repeat',
	'background-position' : $('select[name=background_align]').val()+' left',
	'padding-top' : $('input[name=top_indent]').val()+'px',
	'padding-bottom' : $('input[name=bottom_indent]').val()+'px',
	'padding-right' : $('input[name=right_indent]').val()+'px',
	'padding-left' : $('input[name=left_indent]').val()+'px'
}).parents('table:first').removeAttr('width').css('width','auto').end()
// Set child <div> widths (rx-object-config-bar+div>div)
.find('div:lt(3)').css({width:calcWidth+'px'});
$('#object_cell_title_'+objectType+'_'+objectId).text(objectType+'-'+objectId+' '+$('input[name=width]').val()+'('+calcWidth+')X'+$('input[name=height]').val()+'('+calcHeight+')'+' T:'+$('input[name=top_indent]').val()+';B:'+$('input[name=bottom_indent]').val()+';L:'+$('input[name=left_indent]').val()+';R:'+$('input[name=right_indent]').val());
},

// Article manipulation
articleTools : function (objectType, objectId) {
var articlesCount = $('.rx-'+objectType+'[objectId='+objectId+'] .rx-article').size();
$('.rx-'+objectType+'[objectId='+objectId+'] .rx-article')
	.prepend($('<div class="rx-menu-sort-handler rx-article-sort-handler"></div>').css({background:'none',cursor:'default !important'})
		.prepend('<span class="ui-icon ui-corner-all ui-icon-pencil ui-state-default" style="float:right;cursor:default;margin-left:2px;" title="'+rx.translate('tooltip_edit')+'"></span>')
		.prepend('<span class="ui-icon ui-corner-all ui-icon-closethick ui-state-default" style="float:right;cursor:default;margin-left:2px;" title="'+rx.translate('tooltip_delete')+'"></span>')
		.prepend(objectType=='main' && articlesCount>1 ? '<span class="ui-icon ui-corner-all ui-icon-pin-w ui-state-default" style="float:right;cursor:default;margin-left:2px;" title="'+rx.translate('tooltip_pin_pos')+'"></span>' : '')
		.prepend(articlesCount>1 ? '<span class="ui-icon ui-corner-all ui-icon-grip-dotted-vertical ui-state-default" style="float:right;cursor:move;margin-left:2px;" title="'+rx.translate('tooltip_move')+'"></span>' : '')
	).each(function() {
		var id = Math.round(Math.random()*1000);
		$('.rx-article-sort-handler',this)
			.prepend('<input name="articleSortId'+id+'" value="'+$(this).attr('articleId')+'" type="hidden">');
	});
// Add "New" and "Save positions" buttons
$('td:first',$('.rx-'+objectType+'[objectId='+objectId+']').prev())
// Save positions button
	.append($('<span id="saveArticlePositions_'+objectType+'_'+objectId+'" title="'+rx.translate('save')+'" style="position:absolute; top:0; padding:3px;"></span>').click(function() {
		var positions = $('.rx-'+objectType+'[objectId='+objectId+'] input[name^=articleSortId]').fieldSerialize();
		$.getJSON('actions.php?action=saveArticlesPositions&objectType='+objectType+'&objectId='+objectId+'&'+positions,null,function(response, status) {
			if (response.error) rx.alert(response.error);
			else {
				$.jGrowl(response.responseText);
				rx.setPinned();
			}
		});
}))
// New article button
	.append($('<span style="position:absolute;left:30px;top:0;"><select id="articleTypeList_'+objectType+'_'+objectId+'"><option class="rx-role-article" value="article">'+rx.translate('article')+'<option class="rx-role-iframe" value="iframe" hidden>'+rx.translate('iframe')+'<option class="rx-role-gallery" value="gallery">'+rx.translate('object_gallery')+'<option class="rx-role-latest" value="latest">'+rx.translate('latest_news')+'<option class="rx-role-sitemap" value="sitemap" hidden>'+rx.translate('sitemap')+(user.blog_priv==1 ? '<option class="rx-role-blog" value="blog">'+rx.translate('tab_blog') : '')+(rx.shopActive==1 ? '<option class="rx-role-basket" value="basket" hidden>'+rx.translate('basket') : '')+(rx.shopActive==1 ? '<option class="rx-role-mini-basket" value="mini_basket" hidden>'+rx.translate('mini_basket') : '')+(1==1 ? '<option class="rx-role-data" value="data" hidden>'+rx.translate('data') : '')+'</select></span><span id="newArticleButton_'+objectType+'_'+objectId+'" style="position:absolute;left:30px;top:0;width:100px;">'+rx.translate('new_create')+'</span>')
);
$('#newArticleButton_'+objectType+'_'+objectId).button({
	icons: {
        primary: 'ui-icon-document'
    }
}).addClass('ui-corner-left').removeClass('ui-corner-all').click( function() {
	var newButton = this;
		$.getJSON('actions.php?action=createDraftArticle&objectType='+objectType+'&objectId='+objectId+'&articleType='+$('#articleTypeList_'+objectType+'_'+objectId).val(), function(response) {
			var articleId = response.articleId;
			var parent = $(newButton).parents('.rx-object');
			var objectId = parent.find('.rx-main,.rx-advert').attr('objectId');
			if(parent.find('.rx-main').size()) var objectType = 'main';
			if(parent.find('.rx-advert').size()) var objectType = 'advert';
			// Now we are using div's, before here was nested table not div
			parent.find('> div.rx-'+objectType+' > div:first').prepend($('<div class="rx-article" articleId="'+articleId+'"><div></div></div>'));
			$('.rx-article[articleId='+articleId+']').after(
				$('<div class="articleEditDiv"></div>')
					.load('actions.php?action=editArticle&articleId='+articleId+'&objectType='+objectType+'&objectId='+objectId)
			);
	});
});
// Select menu to create gallery, blog or something else
$('#articleTypeList_'+objectType+'_'+objectId).selectmenu({
	style : 'dropdown',
	width : 200,
	icons : [
		{ find : '.rx-role-article', icon : 'ui-icon-document'},
		{ find : '.rx-role-iframe', icon : 'ui-icon-link'},
		{ find : '.rx-role-gallery', icon : 'ui-icon-image'},
		{ find : '.rx-role-latest', icon : 'ui-icon-signal-diag'},
		{ find : '.rx-role-blog', icon : 'ui-icon-comment'},
		{ find : '.rx-role-sitemap', icon : 'ui-icon-transfer-e-w'},
		{ find : '.rx-role-basket', icon : 'ui-icon-cart'},
		{ find : '.rx-role-mini-basket', icon : 'ui-icon-cart'},
		{ find : '.rx-role-data', icon : 'ui-icon-bookmark'}
	]
});
$('#articleTypeList_'+objectType+'_'+objectId).next().width('125px').css({'left':'0'});
$('#saveArticlePositions_'+objectType+'_'+objectId).button({
	icons: {
        primary: 'ui-icon-disk'
    }
}).removeClass('ui-button-text-icon');
$('#articleTypeList_'+objectType+'_'+objectId).change(function(){
	// Just trigger new article creation
	 $('#newArticleButton_'+objectType+'_'+objectId).click();
});
$('#newArticleButton_'+objectType+'_'+objectId+' .ui-button-text').css({'padding':($.browser.webkit||($.browser.msie&&$.browser.version==7.0)?'0.3em 1em 0.4em 10px':'0.3em 1em 0.3em 10px')});

// Init article buttons - delegate
// Edit button
$('.rx-'+objectType+'[objectId='+objectId+']').delegate('.ui-icon-pencil','click',function() {
//$('.rx-'+objectType+'[objectId='+objectId+'] .ui-icon-pencil').click(function() {
	var articleId = $(this).parents('.rx-article').attr('articleId');
	
	var parent = $(this).parents('.rx-main, .rx-advert, .rx-footer, rx-logo');
	var objectId = parent.attr('objectId');
	
	if(parent.is('.rx-main')) var objectType = 'main';
	if(parent.is('.rx-advert')) var objectType = 'advert';
	if(parent.is('.rx-footer')) var objectType = 'footer';
	if(parent.is('.rx-logo')) var objectType = 'logo';
	
	//$('<div class="articleEditDiv"></div>').prependTo($(this).parents('.rx-main, .rx-advert, .rx-footer, .rx-logo').find('div:first')).load('actions.php?action=editArticle&articleId=' + articleId + '&objectId=' + objectId + '&objectType=' + objectType);
	$('.rx-article[articleId='+articleId+']').hide().after(
	$('<div class="articleEditDiv"></div>').prependTo($(this).parents('.rx-object')).load('actions.php?action=editArticle&articleId=' + articleId + '&objectId=' + objectId + '&objectType=' + objectType)
	);
});
// Delete button
$('.rx-'+objectType+'[objectId='+objectId+']').delegate('.ui-icon-closethick','click',function() {
//$('.rx-'+objectType+'[objectId='+objectId+'] .ui-icon-closethick').click(function() {
	var articleId = $(this).parents('.rx-article:first').attr('articleId');
	rx.confirm(rx.translate('tooltip_delete')+'?',function() {
		$.getJSON('actions.php',{action:'deleteArticle',articleId:articleId},function(response) {
			// If article is in several categories ask for confirmation to delete it everywhere
			if (response.confirmDeleteInAllCategories) {
				rx.confirm(rx.translate('delete_in_all_categories'),function() {
					$.getJSON('actions.php',{action:'deleteArticleConfirmed',articleId:articleId},function(response) {
						if (response.error)
							rx.alert(response.error);
						else {
							$('.rx-article[articleId='+articleId+']').slideUp(500,function() {$('.rx-article[articleId='+articleId+']').remove();rx.setPinned();});
							$.jGrowl(response.responseText);
						}
					});
				});
			}
			// If article is in one categories then delete it at once
			else {
				if (response.error)
					rx.alert(response.error);
				else {
					$('.rx-article[articleId='+articleId+']').slideUp(500,function() {$('.rx-article[articleId='+articleId+']').remove();rx.setPinned();});
					$.jGrowl(response.responseText);
				}
			}
		});
	});
});
// Pin button - Make button pressed if article is pinned
$('.rx-'+objectType+'[objectId='+objectId+'] .ui-icon-pin-w').each(function() {
	if ($(this).parents('.rx-article:first').is('.rx-pinned')) {
		$(this).addClass('ui-state-active');
		$(this).addClass('ui-icon-pin-s');
	}
});
// Toggle article pinnedPos on click
$('.rx-'+objectType+'[objectId='+objectId+']').delegate('.ui-icon-pin-w','click',function() {
	var thisArticle = $(this).parents('.rx-article:first');
	var menuId = $('.rx-menu:has(table.selected)').attr('menuId');
	var catId = $('.rx-menu table.selected').parents('li:first').attr('id');
	var groupId = catId.substring(catId.lastIndexOf('g')+1,catId.lastIndexOf('_'));;
	var articleId = thisArticle.attr('articleId');
	// Unpin an article
	if (thisArticle.is('.rx-pinned')) {
		thisArticle.removeClass('rx-pinned');
		thisArticle.removeAttr('pos');
		$(this).removeClass('ui-state-active');
		$(this).addClass('ui-state-default');
		$(this).removeClass('ui-icon-pin-s');
		$.getJSON('actions.php?action=unpinArticle',{menuId:menuId,groupId:groupId,articleId:articleId},function(response) {
			if (response.error) rx.alert(response.error);
			else $.jGrowl(response.responseText);
		});
	}
	// Pin an article
	else {
		thisArticle.addClass('rx-pinned');
		thisArticle.attr('pos',$('.rx-main .rx-article').index(thisArticle));
		$(this).addClass('ui-state-active');
		$(this).removeClass('ui-state-default');
		$(this).addClass('ui-icon-pin-s');
		$.getJSON('actions.php?action=pinArticle',{menuId:menuId,groupId:groupId,articleId:articleId},function(response) {
			if (response.error) rx.alert(response.error);
			else $.jGrowl(response.responseText);
		});
	}
});
// Make articles sortable
$('.rx-'+objectType+'[objectId='+objectId+']').sortable({
	forceHelperSize: true,
	items: '.rx-article',
	//axis: 'y',
	helper: 'clone',
	opacity: 0.6,
	//delay: 100,
	placeholder: 'rx-article-sort-placeholder',
	tolerance: 'pointer',
	cursor: 'move',
	revert: true,
	handle: '.rx-article-sort-handler .ui-icon-grip-dotted-vertical',
	containment: $('.rx-'+objectType+'[objectId='+objectId+'] td[columns]').size() ? '' : 'parent',
	cancel : '.rx-pinned'
});
// Make article-form review controls
$('.rx-'+objectType+'[objectId='+objectId+'] .rx-article:has(.article_text input[type=button])').append($('<div class="rx-form-controls" currentId="0"></div>').css({height:'20px'}) // Css fix for IE (was 1px by default)
	.append($('<span class="ui-icon ui-corner-all ui-icon-seek-prev ui-state-default"></span>').css({'float':'left',marginRight:'2px'}).click(function() {
		$.getJSON('actions.php?action=getArticleFormData',{articleId:$(this).parents('.rx-article:first').attr('articleId'),id:$(this).parents('.rx-form-controls:first').attr('currentId'),dir:'prev'},function(response) {rx.articleFormFill(response);});
		}))
	.append($('<span class="ui-icon ui-corner-all ui-icon-seek-next ui-state-default"></span>').css({'float':'left',marginRight:'2px'}).click(function() {
		$.getJSON('actions.php?action=getArticleFormData',{articleId:$(this).parents('.rx-article:first').attr('articleId'),id:$(this).parents('.rx-form-controls:first').attr('currentId'),dir:'next'},function(response) {rx.articleFormFill(response);});
		}))
	.append($('<span class="ui-icon ui-corner-all ui-icon-calculator ui-state-default"></span>').css({'float':'left',marginRight:'2px'}).click(function() {
		var articleId = $(this).parents('.rx-article:first').attr('articleId');
		// Create message box
		var rxWindow = $('<div class="rx-window"></div>');
		$(rxWindow).css({display:'none'}).appendTo('body').dialog({
		title : rx.translate('message'),
		show : 'scale',
		hide : 'scale',
		modal : $.browser.msie ? false : true,
		width : 600,
		height : 600,
		position: ['center',50],
		close : function () {
			// Remove if exists for redefining
			$(rxWindow).remove();
			}
		}).html(rx.translate('loading')+'...');
		// Load table content
		$(rxWindow).load('actions.php?action=getArticleFormDataTable&articleId='+articleId);
		}))
	.append('<span>'+rx.translate('form_filled_on')+':<span></span></span>')
	// Stop fast clicking from exiting from config mode
	.dblclick(function(event) {
		event.stopPropagation();
		event.preventDefault();
	})
);
},

articleToolsRemove : function (objectType, objectId) {
	$('.rx-'+objectType+'[objectId='+objectId+']').sortable('destroy');
	$('.rx-'+objectType+'[objectId='+objectId+'] .rx-article-sort-handler').remove();
	//$('.rx-'+objectType+'[objectId='+objectId+'] .ui-icon').remove();
	$('.rx-'+objectType+'[objectId='+objectId+'] .rx-form-controls').remove();
	// Remove button events
	$('.rx-'+objectType+'[objectId='+objectId+']').undelegate('.ui-icon-pencil','click');
	$('.rx-'+objectType+'[objectId='+objectId+']').undelegate('.ui-icon-closethick','click');
	$('.rx-'+objectType+'[objectId='+objectId+']').undelegate('.ui-icon-pin-w','click');
	// Strip out the <form>
	//$('.rx-'+objectType+'[objectId='+objectId+']').appendTo($('.rx-'+objectType+'[objectId='+objectId+']').parent().parent());
	//$('form:first',$('.rx-'+objectType+'[objectId='+objectId+']').parent()).remove();
},

// Add "Edit" button for lonely article in this object (no ConfigOff because icon is in .rx-object-config-bar and is removed by objectConfigOff)
articleOneConfigOn : function(objectType, objectId) {
	var articleId = $('.rx-'+objectType+'[objectId='+objectId+'] .rx-article').attr('articleId');
	// Add "Edit" button
	$('td:first',$('.rx-'+objectType+'[objectId='+objectId+']').prev())
	//$('.rx-'+objectType+'[objectId='+objectId+'] .rx-article')
		.prepend($('<span class="ui-icon ui-corner-all ui-icon-pencil ui-state-default" title="'+rx.translate('tooltip_edit')+'" style="float:left;"></span>')
		.click(function() {
			//edit_article(objectType,objectId,articleId);
			var parent = $(this).parents('.rx-object');
			var articleId = parent.find('.rx-article').attr('articleId');

			var objectId = parent.find('.rx-footer,.rx-logo').attr('objectId');
			if(parent.find('.rx-footer').size()) var objectType = 'footer';
			if(parent.find('.rx-logo').size()) var objectType = 'logo';
			$('.rx-article[articleId='+articleId+']').hide().after(
			$('<div class="articleEditDiv"></div>').prependTo($(this).parents('.rx-object')).load('actions.php?action=editArticle&articleId=' + articleId + '&objectType=' + objectType + '&objectId=' + objectId)
			);
		})
	);
},

articleFormSend : function(fieldId) {
	var articleId = fieldId.match(/(\d*)/)[0];
	// Make checkboxes/radios transfer it's caption as value
	$('.rx-article[articleId='+articleId+'] input[type=checkbox], .rx-article[articleId='+articleId+'] input[type=radio]').each(function() {$(this).val($(this).parents('table:first').find('td:eq(1)').text());});
	// Get form data to be stored in database
	var formValues = $('.rx-article[articleId='+articleId+'] input, .rx-article[articleId='+articleId+'] textarea').fieldSerialize();
	// Store form html to be shown in case of error
	var originalHTML = $('.rx-article[articleId='+articleId+']').html();
	// Strip validation code tool
	$('div:has(>.rx-validation-image)').remove();
	// Change form layout according form data
	$('.rx-article[articleId='+articleId+'] input, .rx-article[articleId='+articleId+'] textarea').each(function() {
		if (this.type=='checkbox' || this.type=='radio') {
			if (this.checked) $('input',$(this).parents('table:first')).remove();
			else $(this).parents('table:first').remove();
		}
		else if (this.type=='button')
			$(this).remove();
		else $(this).replaceWith($(this).val());
	});
	// Get form results to be sent by e-mail
	var formHTML = $('.rx-article[articleId='+articleId+']').html();
	//var articleId = $('.rx-article[articleId='+articleId+']').parents('.rx-article:first').attr('articleId');
	// Send data
	$.post('actions.php?action=submitArticleForm&'+formValues,{formHTML:formHTML,articleId:articleId},function(response) {
		if (response.error) {
			rx.alert(response.error);
			// Return form to original state
			$('.rx-article[articleId='+articleId+']').html(originalHTML);
		}
		else $('.rx-article[articleId='+articleId+']').append(response.responseText);
		if (response.refreshValidationCode) rx.refreshValidationCode();
	},'json');	
},

// Fill the form with data from db
articleFormFill : function(dataObj) {
	// If last form data was shown and no next
	if (dataObj.id == $('.rx-article[articleId='+dataObj.articleId+'] .rx-form-controls').attr('currentId'))
		return;
	$('#'+dataObj.articleId+'_ingress_div *').clearFields();
	var fields = dataObj.formData;
	// jQuery "space" replace-back and make field=value array
	fields = fields.replace(/\+/g, "%20").split("&");
	// Make a field->value array
	$.each(fields,function(i,value){fields[i]=value.split("=");});
	// Set values to form
	$.each(fields,function(i,value){
	$('#'+dataObj.articleId+'_ingress_div *[name='+value[0]+']').each(function(){
		if (this.type=='checkbox')
			this.checked = true;
		else if (this.type=='radio' && $(this).parents('table:first').find('td:eq(1)').text()==decodeURIComponent(value[1]))
			this.checked = true;
		else $(this).val(decodeURIComponent(value[1]));
		});
	});
	// Set new current id
	$('.rx-article[articleId='+dataObj.articleId+'] .rx-form-controls').attr('currentId',dataObj.id);
	// Set date of form filling
	$('.rx-article[articleId='+dataObj.articleId+'] .rx-form-controls span:eq(4)').text(dataObj.fillInDate);
},

// Save draft-article periodicaly for saving data in case of unplanned "shutdown"
updateDraftArticle : function() {
	tinyMCE.triggerSave();
	//$('#articleEditForm').attr('action','actions.php?action=saveArticle');
	setTimeout(function() {
		var articleId = $('#articleEditForm').attr('articleId');
		$('#articleEditForm').ajaxSubmit({
		url: 'actions.php?action=saveArticle&articleId='+articleId,
		dataType: 'json',
		success: function(response){
			$.jGrowl(response.responseText);
		}
		});
		},1000);
},
	
setPinned : function () {
	$('.rx-pinned').each(function() {
		var curPos = $('.rx-main .rx-article').index(this);
		var pinnedPos = $(this).attr('pos');
		var diff = curPos - pinnedPos;
		if (diff < 0) {
			for (;diff<0;diff++)
				$(this).nextAll('.rx-article:first').after($(this));
		}
		else if (diff > 0)
			for (;diff>0;diff--)
				$(this).prevAll('.rx-article:first').before($(this));
	});
},

reloadLatestInAdvert : function() {
	/*
		TODO Or maybe change it to reload only ".rx-latest-articles,.rx-latest-news,.rx-latest-rss_reader" articles (then main is affected, too, but cache harder to reset and requires multiple requests for each article :( )
	*/
	$('.rx-advert:has(.rx-latest-articles,.rx-latest-news,.rx-latest-rss_reader)').each(function() {
		$('div:first',this).load('actions.php?action=getObjectContent&objectId='+$(this).attr('objectId')+'&objectType=advert');
	});
}
		

});



$(function () {
rx.objectInit();
});