///////////////////////////////////////////
// MAIN FUNCTIONS AREA
///////////////////////////////////////////

function $$(id) {
	if (id=='') { alert('No id'); return false; }
	return document.getElementById(id);
	}


// GLOBAL VARIABLE TO IDENTIFY BROWSER
var browser = navigator.userAgent.toLowerCase();
var isIE = false, isIE6 = false, isIE8 = false, isFirefox = false, isOpera = false, isSafari2 = false, isSafari3 = false;
if (browser.indexOf("msie 6")!=-1) isIE6 = true;
if (browser.indexOf("msie 8")!=-1) isIE8 = true;
if (browser.indexOf("msie")!=-1) isIE = true;
else if (browser.indexOf("firefox")!=-1) isFirefox = true;
else if (browser.indexOf("opera")!=-1) isOpera = true;
else if (browser.indexOf("safari")!=-1) {
	// Safari 3 works as Firefox
	if (browser.indexOf("version/3.")!=-1) {
		isSafari3 = true;
		isFirefox = true;
		}
	else
		isSafari2 = true;
	}
//alert("MSIE:"+isIE+"MSIE6:"+isIE6+"MSIE8:"+isIE8+" Firefox:"+isFirefox+" Opera:"+isOpera+" Safari:"+isSafari2);




function flashObject(swf, div_id, width, height, version, background_color) {
if (!document.getElementById(div_id).object_activated)
	{
	var so = new SWFObject(swf, div_id+"_swf", width, height, version, background_color);
	so.write(div_id);
	id2 = div_id.replace(/_div/,"");
	//alert("object_"+id2+"_form");
	var onfocus_id = document.getElementById(div_id).getAttribute("onfocus_id");
	if (onfocus_id!='' && onfocus_id!=null)
		{
		onfocus_id = onfocus_id.split("_");
		//document.getElementById(div_id+"_swf").onfocus = function () { document.getElementById("object_"+onfocus_id+"_form").submit(); };
		document.getElementById(div_id+"_swf").onfocus = function () { object_config_mode(event,onfocus_id[0], onfocus_id[1]); };
		}
	// Flag that this object was activated and doesn't need it again on main section refresh - otherwise blinks
	document.getElementById(div_id).setAttribute("object_activated",1);
	}
}


function detectFlashObjects() {
//var flashObjects = document.all.tags('object');
var flashObjects = document.getElementsByTagName('object');
for (var i=0; i<flashObjects.length; i++) {
	div_id = flashObjects[i].id.replace(/_swf/,'');
	if (document.getElementById(div_id)) {
		swf_src = document.getElementById(div_id).getAttribute('swf_src');
		flashObject(swf_src, div_id, '100%', '100%', 7, '');
	}
}
}






















///////////////////////////////////////////
// ARTICLE FUNCTIONS AREA
///////////////////////////////////////////


// This function checks if there is any checked category for new article
function sumbit_article(object_type,object_id) {
var is_checked=0;
// Do this check only if edited article was called from MAIN section
// Because in logo, footer and advert there is no need
var type = $('#type').val();
if (object_type=="main" && type!='comment') {
	// find any category selected for the article
	var checkbox=$('input[id*=article_cat_m]:checked');
	if(checkbox.val()){
		if(checkbox.attr('id').indexOf('_copy')==-1){
			is_checked=1;
		}
	}
}
else is_checked=1;

if (is_checked){
	// If Article Active mode is 2 (Active in period) check the dates (modified on 2010.05.12 because radiobuttons are changed to the dropdown box)
	if ($('select[name=article_active]').val()==2){
     	if (check_active_period_date("start")){ 
        	if (check_active_period_date("end")){
         		//CHECK IF THIS PRODUCT ID ALREADY EXISTS
        		checkIfProdIdExists();
         	}
         	else alert("Active period finish date can't be empty!");
    	}
    	else alert("Active period start date can't be empty!");
	}
	// Article Mode is Active or Deactivated, article is submited without dates checking
	//CHECK IF THIS PRODUCT ID ALREADY EXISTS
	else checkIfProdIdExists();
}
// No category selected for the article
else alert("Check any of category for new article!");
}

// this function checks if product id is valid, if it is valid then it submits edit form
function checkIfProdIdExists() {
/*
if ($('#article_product_id')){
	if ($('#article_product_id').val() && $('#article_product_id').val()!=$('#article_product_id_old').val()){
		if ($('#article_product_id').attr('isValid')==1){
			submitArticleEditForm();
		}
		else{
			alert('Product id is not valid!'); 
		}
	}
	else{
		submitArticleEditForm();
	}
}
else{
	submitArticleEditForm();
}*/
if ($('#article_product_id') && $('#article_product_id').val() && $('#article_product_id').val()!=$('#article_product_id_old').val() && $('#article_product_id').attr('isValid')!=1)
	alert('Product id is not valid!');
else submitArticleEditForm();
}

// this function submits articleEditForm
function submitArticleEditForm() {
if(typeof(updateDraftArticle)!='undefined'){
	clearInterval(updateDraftArticle); 
	tinyMCE.triggerSave(); 
	setTimeout(function (){$('#articleEditForm').submit();},1000);
}
}




function custom_picture_width_toggle() {
if ($("#article_picture_width").val()=="custom")
    $("#article_picture_width_custom").show();
else
    $("#article_picture_width_custom").hide();
}



// This function checks if article active period date is not in the past
function check_active_period_date(id) {
	var dateToValidate = $('input[name=active_period_'+id+']').val();
	if (!dateToValidate){
		return 0;
	}
	else 
		return 1;
}




// Finishs picture preview on picture load complete!
function preview_article_picture_resize(image) {
var width = $("#article_picture_width").val();
if (width=="custom")
    width = $('#article_picture_width_custom').val();
if (parseInt(width,10)) {
    image.width=width;
    $(image).removeAttr('height');
    }
}



function submit_article_generated_form(field_id) {
// event.target emulation
$('input[onclick*='+field_id+']').hide().parent()
.append('<div><img class="rx-validation-image" src="validationCode/validationCode.php" style="float:left;" /><input type="text" name="article_id_validationCode" class="ui-corner-all" autocomplete="off" style="text-align:center;height:25px;width:80px;float:left;font-size:14pt;margin-right:2px;" /><button type="button" class="ui-corner-all ui-state-default ui-state-hover" onclick="rx.articleFormSend(\''+field_id+'\');" style="float:left;padding:5px;margin:0;"><span class="ui-icon ui-icon-check"></span></button></div>');
}


function toggleDisplay(ObjId) {
$('#'+ObjId).toggle();
}

function toggle_object(object_id) {
toggleDisplay(object_id);
}




// Show hidden Xtender screen elements that are used to help IE understand complex colspan and rowspan tables
function toggle_object_titles() {
var cells = document.getElementsByTagName('DIV');
var show_titles = 0;
for (var i = 0; i<cells.length; i++)
	{
	// Show each objects title
	if (cells[i].id.indexOf("object_cell_title_") != -1)
		{
		cells[i].style.display = (cells[i].style.display=='' ? 'none' : '');
		show_titles = (cells[i].style.display=='' ? 1 : 0);
		}
	}

var cells = document.getElementsByTagName('TD');
for (var i = 0; i<cells.length; i++)
	{
	// Show each objects border
	var re = new RegExp("object_cell_[a-z]+_[0-9]+");
	if (cells[i].id.match(re))
		{
		cells[i].style.border = (show_titles ? '3px solid red' : '0px solid red');
		cells[i].style.borderStyle = 'solid';
		}
	}
}






var todayDateColor = 'yellow';
var eventDateColor = 'salmon';
var eventArticleDateColor = 'lightgreen';

var multiselect_calendar;

// Function to start calendar
function calendarStart(container,multiselect) {
	var multiselect_calendar = new Epoch('cal','popup',document.getElementById(container),multiselect);
}


function printVersion(article_id) {
window.open('print.php?aid='+article_id);
}




function formatCommentInput() {
$('#commentText').tinymce({
	script_url : 'tinymce/tiny_mce.js',
	entity_encoding : "raw"
});

$('#addCommentForm').ajaxForm({
	dataType: 'json',
	success : function(response) {
		$.jGrowl(response.responseText);
		$('.rx-validation-image').attr('src','validationCode/validationCode.php?'+Math.round(Math.random()));
		if (typeof(response.validationCodeError)=='undefined') {
			$('div[id$=_comment_body]:first').clone().prependTo($('div[id$=_comment_body]:first').parent()).find('table:first').replaceWith(response.responseHTML);
			$('#addCommentForm').resetForm();
			//tinyMCE.updateContent('commentText');
			$('#commentText').tinymce().setContent('');
		}
	}
});
}

// In use in list_comments (2010.07.29)
function deleteComment(id) {
rx.confirm('Delete comment?',function() {
	$.get('actions.php?action=deleteArticleConfirmed&articleId='+id,null,function() {
		$('#'+id+'_comment_body').slideUp(500,function() {$('#'+id+'_comment_body').remove();});
	});
});
}


function toggleMusic() {
var musicEl = document.getElementById('bgmusic_div');
musicEl.innerHTML = '';
}

function setArticleRole(articleRole) {
	$('#type').val(articleRole);

	// Disable read more switcher for blog
	if (articleRole=='blog') {
		$('label[for=article_expandable2]').click();
		$('.rx-ui-buttonset:has(#article_expandable1) span').addClass('ui-state-disabled').click(function(event) {return false;});
	}
	else $('.rx-ui-buttonset:has(#article_expandable1) span').removeClass('ui-state-disabled').unbind('click');

	var sections = new Array("index","period","template","picture","document","position","email","iframe","gallery","product","latest","blog","event","archive");
	var sectionsByRoles = new Array();
	sectionsByRoles["article"] = new Array("index","period","template","picture","document","email","product","event","archive");
	sectionsByRoles["logo"] = new Array("picture");
	sectionsByRoles["banner"] = new Array("period","document","email","iframe","event");
	sectionsByRoles["footer"] = new Array("index","template","picture","event");
	sectionsByRoles["iframe"] = new Array("iframe");
	sectionsByRoles["gallery"] = new Array("index","gallery");
	sectionsByRoles["latest"] = new Array("index","latest");
	sectionsByRoles["blog"] = new Array("index","period","template","picture","document","email","blog","event");
	sectionsByRoles["sitemap"] = new Array("index");
	sectionsByRoles["basket"] = new Array("index");
	sectionsByRoles["mini_basket"] = new Array("index");
	sectionsByRoles["data"] = new Array("index","data","email");

	$('#articleEditTabs > ul > li').hide();
	$.each(sectionsByRoles[$('#articleRoleSelect').val()], function(i, val) {
		if (!i) $('#articleEditTabs').tabs('select', '#article_'+this);
		$('#articleEditTabs li:has(a[href=#article_'+this+'])').show();
	});
	
}

function storeArticleBgImage(url, data) {
var articleBgImg = document.getElementById('article_background_image_img');
var articleBg = document.getElementById('article_background_image');
if (url.indexOf('/')==-1) {
	articleBg.value = picture_directory+'/'+articleBg.value;
	url = articleBg.value;
}
articleBgImg.src = url;
articleBg.value = url.indexOf('none.gif')>-1 ? '' : url ;
}


function sendArticleByEmail(articleId) {
if ($('#sendByEmail_'+articleId+'_email').val().match(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i))
	$.get('actions.php?action=sendArticleByEmail&aId='+articleId+'&name='+encodeURI($('#sendByEmail_'+articleId+'_name').val())+'&email='+$('#sendByEmail_'+articleId+'_email').val(),function (response) {
		$('#sendByEmail_'+articleId+'_response').html(response);
		$('#sendByEmail_'+articleId+'_name').val('');
		$('#sendByEmail_'+articleId+'_email').val('');
	});
else rx.alert('Check e-mail address');
}

function toggleSelectCustomValue(selectId) {
$$(selectId).style.display=$$(selectId+'_select').value=='custom'?'':'none';
if ($$(selectId+'_select').value!='custom') $$(selectId).value=$$(selectId+'_select').value;
}

function setSelectValue(selectId,selectValue) {
var selectNode = $$(selectId+'_select'), foundValue='';
for (var i=0;i<selectNode.options.length;i++) {
	if (selectNode.options[i].value==selectValue)
		foundValue=selectValue;
}
if (foundValue)
	selectNode.value=foundValue;
else {
	selectNode.value='custom';
	$$(selectId).style.display='';
}
}

function zoomText(modifier) {
if (modifier) fontSizeModifier=Number(fontSizeModifier) + Number(modifier);// else fontSizeModifier=0;
var classes=new Array('article_heading','article_text','latest_news','menu_current','menu_default','menu_sub','menu_hover','menu_hoverSub'), curSize, elem;
for (var i=0;i<classes.length;i++) {
	curSize=0;
	elem = document.createElement('DIV');
	elem.className = classes[i];
	document.body.appendChild(elem);
	curSize=isIE ? parseInt(elem.currentStyle.fontSize,10) : parseInt(window.getComputedStyle(document.getElementsByClassName(classes[i]).item(0),null).getPropertyValue("font-size"),10);
	document.body.removeChild(elem);
	if (modifier) curSize = Number(curSize) + Number(modifier); else curSize -= fontSizeModifier;
	isIE ? document.styleSheets[0].addRule("."+classes[i],"font-size:"+curSize+'px',document.styleSheets[0].rules.length) : document.styleSheets[0].insertRule("."+classes[i]+"{font-size:"+curSize+'px'+"}",document.styleSheets[0].cssRules.length);
}
if (!modifier) fontSizeModifier=0;
eraseCookie("fontSizeModifier");
createCookie("fontSizeModifier",fontSizeModifier,"1");
}

// Setting article footer's template
function set_article_footer() {
$("#article_footer").val('');
if ($('input[name=article_footer_active_switch]').fieldValue()!='') {
	$("#article_footer_create_date_row").show();
	$("#article_footer_edit_date_row").show();
	$("#article_footer").val($('input[name=article_footer_active_switch]').fieldValue()+$('input[name=article_footer_create_date]').fieldValue()+$('input[name=article_footer_edit_date]').fieldValue());
} else {
	$("#article_footer_create_date_row").hide();
	$("#article_footer_edit_date_row").hide();
}
}

// Preview text styles on fly
function previewGlobalTextElement(text_element_id) {
var preview = $('#'+text_element_id+'_preview');
preview.css({
	fontFamily : $('#'+text_element_id+"_fontType").val(),
	fontSize : $('#'+text_element_id+"_fontSize").val()+'px',
	color : $('#'+text_element_id+"_fontColor").val(),
	backgroundColor : $('#'+text_element_id+"_bgColor").val(),
	backgroundImage : "url('"+picture_directory+'/'+$('#'+text_element_id+"_bgImage").val()+"')",
	fontWeight : $('#'+text_element_id+"_bold").is(':checked') ? 'bold' : 'normal',
	fontStyle : $('#'+text_element_id+"_italic").is(':checked') ? 'italic' : 'normal',
	textDecoration : $('#'+text_element_id+"_underline").is(':checked') ? 'underline' : 'none'
}).find('img').attr('src',picture_directory+'/'+$('#'+text_element_id+"_icon").val()).css('display',$('#'+text_element_id+"_icon").val() ? 'inline' : 'none');
/*if ($('#'+text_element_id+"_icon").val())
	$('img',preview).attr('src',picture_directory+'/'+$('#'+text_element_id+"_icon").val());
else $('img',preview).css('display','none');*/
}



// Cookies functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



// Previews the article picture (works only for uploaded pictures)
function preview_article_picture()
{
if (document.getElementById("article_picture_select").value!='none.gif')
    var picture_path = picture_directory+"/"+document.getElementById("article_picture_select").value;
else var picture_path = picture_directory+'/../../system/none.gif';
// Local file usage is disabled by modern browsers for security reasons
//if (document.getElementById("article_new_picture").value) picture_path = document.getElementById("article_new_picture").value;
// Safari - onload doesn't work if path is the same (when changing only width in preview)
//!!! THIS LINE "KILLS" SESSION ON SERVER - because it calls "http://www.folkewebkultu.no" and $_SESSION['user'] takes default ("root" or "folkeweb") name
//!!! document.getElementById("article_picture_preview").src='';
if (document.getElementById("article_picture_preview").getAttribute('src')!=picture_path)
	{
	document.getElementById("article_picture_preview").removeAttribute('src');
	document.getElementById("article_picture_preview").src=picture_path;
	}
document.getElementById("article_picture_text_preview").innerHTML=(isSafari2 ? document.getElementById("picture_text").innerText : document.getElementById("picture_text").value);
// Resize image
preview_article_picture_resize(document.getElementById("article_picture_preview"));
}





function changeLogoImage(change_logo_imagename, change_background_imagename, callBackFunc) {
var logoChangeImageName = change_logo_imagename!='' ? picture_directory +'/'+ change_logo_imagename : logo_image_name,
logoChangeType = (logoChangeImageName.indexOf('.swf')!=-1?'swf':'img'),
logoChangeTarget = document.getElementById('logo_image_'+logoChangeType);

if (logoChangeTarget) {
	document.getElementById('logo_image_img').style.display='none';
	document.getElementById('logo_image_swf').style.display='none';
	document.getElementById('logo_image_'+logoChangeType).style.display='';
	if (document.getElementById('logo_image_swf').getAttribute("changedImageSrc")!=logoChangeImageName) {
		// Change logo image if name was given by selecting a category
		if (logoChangeType=='img') {
			logoChangeTarget.setAttribute('src',logoChangeImageName);
			// FIX for IE6
			if (isIE6) setTimeout("document.getElementById('logo_image_img').setAttribute('src','"+logoChangeImageName+"');", 500);
		}

		else { // SWF
			logoChangeTarget.setAttribute("object_activated",0);
			flashObject(logoChangeImageName, "logo_image_swf", "100%", "100%", 7, "");
		}

		document.getElementById('logo_image_swf').setAttribute("changedImageSrc",logoChangeImageName);
	}
}

// Change background image if name was given by selecting a category
var background_image;
var background_target;
// Determine if use requested background image or general for page
background_image = (change_background_imagename ? "url("+picture_directory +"/"+ change_background_imagename+")" : background_image = "url("+picture_directory +"/"+ background_image_name+")");
// Determine background of what object to change (body in normal mode OR "page frame" in admin mode)
background_target = document.getElementById('page_frame_in_design') ? document.getElementById('page_frame_in_design') : document.getElementById("main_body");
if (background_image) {
	background_target.style.backgroundImage = background_image;
	// FIX for IE6
	if (isIE6) setTimeout((document.getElementById('page_frame_in_design') ? "document.getElementById('page_frame_in_design')" : 'document.getElementById("main_body")')+'.style.backgroundImage = "'+background_image+'"', 500);
	}
// Store data in session on server
// (it is stored by GET) ajax('actions.php?action=changeLogoImage','change_logo_image='+change_logo_imagename+'&change_background_image='+change_background_imagename,callBackFunc?callBackFunc:null);
}


//Always Load TinyMCE - needed for blog commenting
function tinyMCEinit(textareaId, themeAdvancedToggleButtonMode, bodyClassName) {
var theme_var, plugins_var, theme_advanced_buttons1_var, theme_advanced_buttons2_var, theme_advanced_buttons3_var, theme_advanced_buttons4_var;

var bodyClassNames = bodyClassName.split(',');
var textareaIds = textareaId.replace(/#/gi,'');
var textareaIds = textareaIds.split(',');
bodyClassName = '';
for (var i=0;i<bodyClassNames.length;i++)
	{
	if (i) bodyClassName += ',';
	bodyClassName += textareaIds[i]+"="+bodyClassNames[i];
	// Show textarea only before init so user don't see HTML in it
	document.getElementById(textareaIds[i]).style.display='';
	}

if (document.getElementById(textareaIds[0])==null)
	{
	//setTimeout('tinyMCEinit("'+textareaId+'", "'+themeAdvancedToggleButtonMode+'", "'+bodyClassName+'");',1000);
	}

	// If mode is ADVANCED
	if (themeAdvancedToggleButtonMode == "advanced")
	{
			// General variable options
		theme_var = "advanced";
		plugins_var = "pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,togglemodebutton,spellchecker,imagemanager,filemanager,formgenerator";

		theme_advanced_buttons1_var = "template,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,|,link,unlink,image,media,|,tablecontrols,|,fullscreen,code";
		theme_advanced_buttons2_var = "fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,forecolor,backcolor,|,insertimage,insertfile,|,togglemodebutton";
		theme_advanced_buttons3_var = "styleselect,formatselect,|,styleprops,|,search,replace,|,blockquote,|,anchor,cleanup,help,|,insertdate,inserttime,|,hr,advhr,removeformat,|,sub,sup,|,ltr,rtl";
		theme_advanced_buttons4_var = "insertlayer,moveforward,movebackward,absolute,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,pagebreak,spellchecker,|,charmap,emotions,|,print,preview,|,,formGeneratorAddInput,formGeneratorAddCheckbox,formGeneratorAddRadioButton,formGeneratorAddTextarea,formGeneratorAddSubmitButton";
	}
	// IF mode is BASIC
	else if (themeAdvancedToggleButtonMode == "basic")
	{
		// General variable options
		theme_var = "advanced";
		plugins_var = "pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager,togglemodebutton,spellchecker";

		theme_advanced_buttons1_var = "template,|,cut,copy,paste,pastetext,pasteword,|,undo,redo,|,link,unlink,image,media,|,tablecontrols,|,fullscreen,code";
		theme_advanced_buttons2_var = "fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,forecolor,backcolor,|,insertimage,insertfile,|,togglemodebutton";
		theme_advanced_buttons3_var = "";
		theme_advanced_buttons4_var = "";
	}
	else theme_var = themeAdvancedToggleButtonMode;

	$(textareaId).tinymce({
		// Use gzip with tinyMce
		//script_url : 'tinymce/tiny_mce.js',
		script_url : 'tinymce/tiny_mce_gzip.php',
		// General options
		theme : theme_var,
		plugins : plugins_var,
		entity_encoding : "raw",
		// Having script tags in text editor is unacceptable in the AJAX based website
		invalid_elements : "script",
		// Spellchecker language
		//spellchecker_languages : "+English=en,Norwegian=sv,Russian=ru",

		// Interface language
		language : tinyMceLang,

		// Example content CSS (should be your site CSS)
		content_css : "style.php,staticStyle.css?v=1",
		body_class : bodyClassName,
		body_id : "bodyId",
		// Them ToggleButton mode value
		theme_advanced_toggle_button_mode : themeAdvancedToggleButtonMode,

		// Theme options
		theme_advanced_buttons1 : theme_advanced_buttons1_var,
		theme_advanced_buttons2 : theme_advanced_buttons2_var,
		theme_advanced_buttons3 : theme_advanced_buttons3_var,
		theme_advanced_buttons4 : theme_advanced_buttons4_var,
		theme_advanced_toolbar_location : "external",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		theme_advanced_styles : "Heading=article_heading;Normal text=article_text;Picture caption=default_picture_text",
		font_size_style_values : "8pt,10pt,12pt,14pt,18pt,24pt,36pt",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "tinymce/lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Addons
		//file_browser_callback : "fileBrowserCallBack",
		file_browser_callback : "mcFileManager.filebrowserCallBack",

		imagemanager_insert_template : '<img src="{$url}" width="{$custom.width}" height="{$custom.height}" border="0" />',

		paste_auto_cleanup_on_paste : true,

		setupcontent_callback : "formatTinyMCE",

		// Insert IMG in ADVLINK with no border
		//extended_valid_elements : "img[class|src|border=0|alt|title|hspace|vspace|width|height|align]",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}

function formatTinyMCE(editor_id, body, doc){
setTimeout(function() {
	// Article background color
	var articleColor = $('#'+editor_id).parents('.articleEditDiv').prev().find('div:eq(1)').css('background-color');
	// Check if article bgcolor is transparent (diff browsers - diff values)
	articleColor = /^rgba\(0, 0, 0, 0\)|rgb\(255, 255, 255\)|#fff|transparent$/.test(articleColor) ? 0 : articleColor;
	// Check if body is transparent or inherits article_heading/text... bgcolor
	if (/^rgb\(255, 255, 255\)|#fff|transparent$/.test($(body).css('background-color'))){
		if (articleColor){
			// Set article background color as text editor background color
			$(body).css('background-color',articleColor);
		}
		else{
			// Set object background color as text editor background color
			$(body).css('background-color',$('#'+editor_id).parents('td[id^=object_cell_]:first').css('background-color'));
		}
	}
	},1000);
}


// jQuery
$(function() {

// Make menu and user-made links to work through iframe
$("a[href*=cid=]:not(a[href*=ttp:])").livequery(function() {
	// If target is _blank then it's certainly not a link to a category on this site
	if (this.target != '_blank') {
		if (!$(this).is('.rx-menu a'))
			$(this).click(function(event) {
				var catId = this.href.match(/cid=(\d+)/)[1];
				var menuId = (this.href.match(/mid=(\d+)/) ? this.href.match(/mid=(\d+)/)[1] : 0);
				rx.menuExpandCategoryFromRoot('m'+menuId+'g'+catId);
				if (this.search) rx.history(this.search);
				event.preventDefault();
				return false;
			});
	}
});

// IE fix when images are loaded on start
$(window).load(function() {
	rx.correctIeTableHeight();
});

});