﻿var buttons_resize_timer = false;
var editor = false;
var ignore_callback = false;
var editor_no_p = false;
var editor_html_txt = false;
var editor_height = '200px';
var editor_min_height = '50px';
var editor_max_height = '350px';
var editor_entities_additional = '';//'#260,#262,#280,#321,#323,#211,#346,#377,#379,#261,#263,#281,#322,#324,#243,#347,#378,#380,#187';
var CodeMirrorEditor = false;
var jcrop_api = false;
var fade_on = false;
var on_branding = false;
var is_admin = false;
var api = false;
var do_reload = false;
var displayed_links_behaviour = false;
var preview_timeout = false;
var disable_dialog_users_code = false;
var current_page = '';
var previous_page = '';
var page_title = '';
var hue = '';
var hex = '';
var logo = '';
var repeat_removed = '';
var backup_logo = '';
var site_classname = 'edit';
var repeat_tmp = 0;
var aspect = 1;
var EDITOR_RTE = 1;
var EDITOR_TEXTAREA = 2;
var EDITOR_TEXTAREA_HTML = 3;
var EDITOR_IMAGE = 4;
var EDITOR_RTE_REPEAT = 5;
var EDITOR_REPEAT_IMAGE = 6;
var editor_html_txt_toolbar = [["Bold","Underline","Italic","Cut","Copy","Paste","PasteText","PasteFromWord","Link","Unlink"]];
var ce = {};
var bf = {};
var i = 0;
var i_tmp = 0;
var b = '2px solid #008a00';
var b_tmp = '2px solid #999';
var frame_top = 0;

window.onresize = function()
{
	nav_define_edit_zones();
	$('#partial-overlay').css('top',$('#header').outerHeight());
}

$(document).ready(function()
{
  page_title = document.title;
  site_classname = $('#site_classname').val();
  $.history.init(pageload,{unescape: ",/"});
  $('a.ajax').live('click',function()
  {
  	if ($(this).hasClass('disabled'))
  		return false;
		$('#sites').slideUp('fast');
		$('#sitemap-content').slideUp('fast');

  	if ($(this).parent().hasClass('view-source'))
			$(this).attr('href', '/preview/code/'+$.base64Encode($('#frm_a').val()));

  	$('.trigger-nav ul.sub').hide();
  	confirm_changes(null, '$.history.load("'+$(this).attr('href').replace(/^.*#/, '')+'");', null);
  	return false;
  });
  $('a.do-ajax').live('click',function()
  {
  	var the_link = $(this);
    loading_on();
    $.ajax({
      url: the_link.attr('href'),
      dataType: 'json',
    	data: {'dataType':'json'},
      success: function(data)
      {
      	if (the_link.hasClass('reload'))
      		reload_session();

      	callback(null, data);
      }
    });
    return false;
  });
	$('a.process-logout').live('click',function(){
  	confirm_changes(null, 'window.location = "'+$(this).attr('href')+'";', null);
  	return false;
  });
  $('a.new-window').live('click',function(){return !window.open($(this).attr('href'));});
  $('#flashMessage').live('click',function(){$(this).slideUp('fast',function(){$(this).remove();});});
	$('a.toggle').live('click',function(){$('#'+$(this).attr('rel')).slideToggle('fast');});
	$('a.toggle-off').live('click',function()
	{
		$('a.hi', $(this).parent()).removeClass('hi');
		$(this).addClass('hi');
		$('#'+$(this).attr('rel')).slideUp('fast');
		$('.tooltip:visible').hide();
	});
	$('a.toggle-on').live('click',function()
	{
		$('a.hi', $(this).parent()).removeClass('hi');
		$(this).addClass('hi');
		$('#'+$(this).attr('rel')).slideDown('fast');
		$('.tooltip:visible').hide();
	});

  set_defaults();
  site_selector();
  sitemap();
  nav();
  process_forms();
  tooltips();
  site_select_root();
  site_select_page();
  setup_wysiwyg();
  editor_buttons();
  process_upgrade();

	if ($('#displayed_links_dialog').val() == '1') displayed_links_behaviour = true; else displayed_links_behaviour = false;

	$('.preview-seo').live('click',function(){
  	confirm_changes(null, 'load_seo();', null);
		return false;
	});

	// turn links on/off
	$('#frm_links_on_off').live('click',function()
	{
		if ($(this).is(':checked'))
			enable_links();
		else
			disable_links();
	});

  $('#ce-frame').bind('load',function()
  {
		if (preview_timeout !== false)
		{
			clearTimeout(preview_timeout);
			preview_timeout = false;
		}

  	reset_repeat_vars();

		// get the current page path
		var p = $('#frm_a').val();
		var is_xml = (p.substring((p.length-4)) == '.xml');

		// check the url is still within the system
   	try{
			set_frame_height();
		}catch(e){
			if (!is_xml)
			{
				load_editor_page($('#frm_current_site_url').val());
				return false;
			}
		}

    $('html, body').scrollTop(0);

		if (is_xml)
		{
			loading_off();
			if (!$('li.view-source').hasClass('tab-hidden'))
				confirm_changes(null, '$.history.load("/preview/code/'+$.base64Encode($('#frm_a').val())+'");', null);
			return;
		}

		// check for redirects
		var the_content = $('#ce-frame').contents().text();
	  if (typeof the_content == 'string' && the_content.substr(0, 12) == '::redirect::')
	  {
	  	if (the_content.substr(12,7) == 'http://' || the_content.substr(12,8) == 'https://')
	  	{
	  		window.location = the_content.substr(12);
	    	return false;
	    }
	    $.history.load(the_content.substr(12));
	    return false;
	  }

		if ((p.substring((p.length-1)) == '/' && $('#ce-frame').contents().find('base').size() > 0) || (p.substring(-4, 1) != '.' && p.substring(-5, 1) != '.' && p.substring(-6, 1) != '.'))
		{
			p = $('#ce-frame').contents().find('base').attr('href');
			$('#frm_a').val(p);
			$('#frm_current_page').val(p);
		}

		// remove edit buttons
		remove_edit_buttons();
		remove_editable_areas();
		$('#ce-frame').contents().die('click');
		$('.click-to-define').die('click');
		$('.area-defined').die('click');

		if (current_page.substr(0, 15) == '/preview/define')
		{
			// unbind edit content features
			$('#ce-frame, .ce-button').unbind('mouseenter');
			$('#ce-frame').unbind('mouseleave');
		  $(window).unbind('resize');
		  $(window).unbind('scroll');
			$('#ce-frame').contents().find('div').unbind('scroll');

			// turn links on/off
			if ($('#frm_links_on_off').is(':checked'))
				enable_links();
			else
				disable_links();

			define_edit_area_setup();

			// handle removing editable areas
			$('.remove-zone').live('click',function(){define_edit_area_remove($(this));});

			// display current editable areas
			$('#ce-frame').contents().find(
					'.'+site_classname+', .'+site_classname+'-repeat, .'+site_classname+'-wysiwyg'
					+', .'+site_classname+'-img, .'+site_classname+'-image, .'+site_classname+'-repeat-img, .'+site_classname+'-repeat-image'
					+', .'+site_classname+'-txt, .'+site_classname+'-text, .'+site_classname+'-html, .'+site_classname+'-xml'
				).each(function()
			{
				if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '')
					return true;

				$(this).attr('cms-index', i).attr('cms-editable', 'true');

			  $('#canvases').append('<div id="t'+i+'"></div><div id="r'+i+'"></div><div id="b'+i+'"></div><div id="l'+i+'"></div><img src="/images/icons/remove_zone.png" alt="Remove" id="remove-icon-'+i+'" index="'+i+'" cms-id="#'+$(this).attr('id')+'" cms-class="'+site_classname+'" class="remove-zone" />');
				$('#canvases').append('<div id="area-defined-'+i+'" class="area-defined" cms-id="#'+$(this).attr('id')+'">'+$('#js-area-defined').html()+'</div>');

				var the_offset = Math.round(frame_top - $(window).scrollTop());
				if (the_offset < 0)
					var t_top = frame_top;
				else
					var t_top = the_offset;

		  	var t = Math.round($(this).offset().top + t_top) - 4;
			  var l = Math.round($(this).offset().left) - 4;
			  var w = Math.round($(this).outerWidth()) + 8;
			  var h = Math.round($(this).outerHeight()) + 8;

				//if ($.browser.msie)
				if ($.browser.msie && parseInt($.browser.version) < 9)
					t += $(window).scrollTop();

				$('#area-defined-'+i).css({'top':t, 'left':l}).hide();

			  $('#t'+i).css({'position':'absolute', 'top':t, 'left':(l+10), 'width':(w-10), 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
			  $('#r'+i).css({'position':'absolute', 'top':t, 'left':l + w, 'width':'0', 'height':h, 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
			  $('#b'+i).css({'position':'absolute', 'top':t + h - 2, 'left':l, 'width':w, 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
			  $('#l'+i).css({'position':'absolute', 'top':(t+9), 'left':(l < 0)? 0 : l, 'width':'0', 'height':(h-9), 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
				$('#remove-icon-'+i).css({'position':'absolute', 'top':(t+9), 'left':(l < 0)? 4 : l});

				if ($(this).is(':hidden'))
					$('#t'+i+', #r'+i+', #b'+i+', #l'+i+', #remove-icon-'+i).hide();
				else
					$('#t'+i+', #r'+i+', #b'+i+', #l'+i+', #remove-icon-'+i).show();

			  i++;
				define_edit_area_mouseover($(this).attr('id'));
			});

			// handle element mouse over
		  $('#ce-frame').contents().bind('mouseover',function(e)
		  {
		  	$('#canvases-tmp').html('');
		  	var the_id = define_edit_area_get_id(e.target);

				if (!the_id)
					return;

				$('#ce-frame').contents().find('#'+the_id).each(function()
				{
					// only show clickable area if the current, parent elements already aren't selected
					if (has_class($(this)))
						return;

					var the_offset = Math.round(frame_top - $(window).scrollTop());

		  		var t = Math.round($(this).offset().top + the_offset) - 4;
				  var l = Math.round($(this).offset().left) - 4;
				  var w = Math.round($(this).outerWidth()) + 8;
				  var h = Math.round($(this).outerHeight()) + 8;

					if ($.browser.msie && parseInt($.browser.version) < 9)
						t += $(window).scrollTop();

					$(this).css('cursor', 'default');
				  $('#canvases-tmp').append('<div id="tmp_t'+i_tmp+'"></div><div id="tmp_r'+i_tmp+'"></div><div id="tmp_b'+i_tmp+'"></div><div id="tmp_l'+i_tmp+'"></div>');
					$('#canvases-tmp').append('<div id="click-to-define-'+i_tmp+'" class="click-to-define" cms-id="#'+$(this).attr('id')+'">'+$('#js-click-to-define').html()+'</div>');

					$('#click-to-define-'+i_tmp).css({'top':t, 'left':l}).show();

				  $('#tmp_t'+i_tmp).css({'position':'absolute', 'top':t, 'left':l, 'width':w, 'height':'0', 'border-top':b_tmp});
				  $('#tmp_r'+i_tmp).css({'position':'absolute', 'top':t, 'left':l + w, 'width':'0', 'height':h, 'border-right':b_tmp});
				  $('#tmp_b'+i_tmp).css({'position':'absolute', 'top':t + h - 2, 'left':l, 'width':w, 'height':'0', 'border-top':b_tmp});
				  $('#tmp_l'+i_tmp).css({'position':'absolute', 'top':t, 'left':(l < 0)? 0 : l, 'width':'0', 'height':h, 'border-right':b_tmp});
				  i_tmp++;
				});
		  });
			// on mouse out, remove the temporary border
		  //$('#ce-frame').contents().bind('mouseout',function(){$('#canvases-tmp').html('');});


			// handle clicking on elements
		  $('#ce-frame').contents().bind('click',function(e){define_edit_area_process_click(e.target);});

			$('.click-to-define').live('mouseover',function(){$(this).show();});
			$('.click-to-define').live('mouseout',function(){$(this).hide();});
			$('.click-to-define').live('click',function(){var elem = $('#ce-frame').contents().find($(this).attr('cms-id')).get(0);define_edit_area_process_click(elem);});

			$('.area-defined').live('mouseover',function(){$(this).show();});
			$('.area-defined').live('mouseout',function(){$(this).hide();});
			$('.area-defined').live('click',function(){var elem = $('#ce-frame').contents().find($(this).attr('cms-id')).get(0);define_edit_area_process_click(elem);});

			$('#ce-frame').contents().find('div').bind('scroll',function(){position_define_zones();});
		  $(window).bind('resize',function(){position_define_zones();});
		}
		else
		{
			// unbind define edit zone features
			$('#ce-frame').contents().unbind('mouseover');
			$('#ce-frame').contents().unbind('mouseout');
			$('#ce-frame').contents().unbind('click');
			$('#ce-frame').contents().find('div').unbind('scroll');
			$(window).unbind('resize');

			add_edit_buttons();
			$('#ce-frame').contents().find('div').bind('scroll',function(){position_edit_buttons();});
			$('.ce-button').hide();
    	catch_links();
		}

		$('#ce-frame').contents().find('a.cms-flash-disabled').bind('click',function()
		{
			if ($('#user_account_id').val() == '0')
				dialog_box($('#js-flash-disabled-user').html());
			else
				dialog_box($('#js-flash-disabled-admin').html());
			return false;
		});

   	fix_flash();
    loading_off();
  });

	if ($('#flashMessage').html() != '' && $('#flashMessage').html() != null){
		dialog_box($('#flashMessage').html());
	}

	$('.user-remove a').live('click',function()
	{
		remove_box($('#js-title-remove-user').html(), $('#js-remove-user').html(), $('#js-btn-remove-user').html(), $('#js-btn-do-not-remove').html(), $(this));
		return false;
	});

	$('.user-close-account a').live('click',function()
	{
		remove_box($('#js-title-close-account').html(), $('#js-close-account').html(), $('#js-btn-close-account').html(), $('#js-btn-keep-my-account').html(), $(this));
		return false;
	});

	$('.site-remove a').live('click',function()
	{
		remove_box($('#js-title-remove-site').html(), $('#js-remove-site').html(), $('#js-btn-remove-site').html(), $('#js-btn-do-not-remove').html(), $(this));
		return false;
	});

	$('a.reset-branding').live('click',function()
	{
		remove_box($('#js-are-you-sure').html(), str_replace('{subdomain}', $('#AccountOldSubdomain').val(), $('#js-reset-branding').html()), $('#js-btn-reset-branding').html(), $('#js-btn-keep-current-branding').html(), $(this));
		return false;
	});

	$(document).keyup(function(e){
		if (e.keyCode == '27'){
			$('#dialog-overlay').hide();
		}
	});

	$(document).click(function(e)
	{
		if ($('#help-code').is(':visible') && e.target.id == 'partial-overlay')
		{
			$('#partial-overlay').hide();
			$('#help-code').hide('fast');
		}
	});
});

function _go(url){window.location = url;}
function close_editor_window(){try{$('#ce-frame, .ce-button').unbind('mouseleave,mouseenter');$('#ce-frame').contents().unbind('click,mouseover,mouseout');$(window).unbind('scroll,resize');remove_edit_buttons();remove_editable_areas();$('#ce-icon').hide();$('#ce-frame').hide();$('#content').html('');}catch(e){}}
function remove_editable_areas(){$('#canvases').html('');$('#canvases-tmp').html('');}
function load_editor_window(the_url){display_edit_content();load_editor_page(the_url);return true;}
function loading_on(){$('#overlay').show();$('#overlay-loading').show();}
function loading_off()
{
	$('#overlay-loading').fadeOut('fast');$('#overlay').fadeOut('fast');
	if (current_page == '/preview/edit' || current_page == '/preview/edit/')
		$('#ce-frame').trigger('mouseenter');
}

function has_class($elem)
{
	return (
		$elem.hasClass(site_classname) || $elem.parents().hasClass(site_classname) ||
		$elem.hasClass(site_classname+'-repeat') || $elem.parents().hasClass(site_classname+'-repeat') ||
		$elem.hasClass(site_classname+'-wysiwyg') || $elem.parents().hasClass(site_classname+'-wysiwyg') ||
		$elem.hasClass(site_classname+'-img') || $elem.parents().hasClass(site_classname+'-img') ||
		$elem.hasClass(site_classname+'-image') || $elem.parents().hasClass(site_classname+'-image') ||
		$elem.hasClass(site_classname+'-repeat-img') || $elem.parents().hasClass(site_classname+'-repeat-img') ||
		$elem.hasClass(site_classname+'-repeat-image') || $elem.parents().hasClass(site_classname+'-repeat-image') ||
		$elem.hasClass(site_classname+'-txt') || $elem.parents().hasClass(site_classname+'-txt') ||
		$elem.hasClass(site_classname+'-text') || $elem.parents().hasClass(site_classname+'-text') ||
		$elem.hasClass(site_classname+'-html') || $elem.parents().hasClass(site_classname+'-html') ||
		$elem.hasClass(site_classname+'-xml') || $elem.parents().hasClass(site_classname+'-xml')
	)? true : false;
}

function get_selector($elem)
{
	// if the element has an ID, lets use it
	var attribute = ($elem.attr('id') != '')? '#'+$elem.attr('id') : '';

	// need to determine the current position of the element to make sure only one element will be selected
	var eq = (attribute == '' && $elem.get(0).tagName != 'HTML' && $elem.get(0).tagName != 'BODY')? ':nth-child('+($elem.index()+1)+')' : '';

	// if the element doesn't have an ID and the element has a classname, then use the classname(s)
	if (attribute == '' && $elem.attr('class') != '')
		attribute = '[class = "' + $elem.attr('class') + '"]';

	var selector = $elem.get(0).tagName + attribute + eq;

	// get the parents
	$elem.parents().each(function()
	{
		// if the element has an ID, lets use it
		attribute = ($(this).attr('id') != '')? '#'+$(this).attr('id') : '';

		// need to determine the current position of the element to make sure only one element will be selected
		var eq = (attribute == '' && $(this).get(0).tagName != 'HTML' && $(this).get(0).tagName != 'BODY')? ':nth-child('+($(this).index()+1)+')' : '';

		// if the element doesn't have an ID and the element has a classname, then use the classname(s)
		if (attribute == '' && $(this).attr('class') != '')
			attribute = '[class = "' + $(this).attr('class') + '"]';

		selector = $(this).get(0).tagName + attribute + eq + ' ' + selector;
	});

	return selector;
}

function reset_repeat_vars()
{
	repeat_removed = '';
	repeat_tmp = 0;
}

function define_edit_area_setup()
{
	i = 0;
	i_tmp = 0;
	b = '2px solid #008a00';
	b_tmp = '2px solid #999';
	frame_top = Math.round($('#ce-frame').offset().top);
}

function define_edit_area_get_id(e)
{
	if (e.tagName == 'HTML' || e.tagName == 'HEAD' || e.tagName == 'BODY' || e.tagName == 'MAP')
		return false;

	if (e.tagName == 'A' && $('#frm_links_on_off').is(':checked'))
		return false;

	var the_id = e.id;

	if (e.tagName == 'OL' || e.tagName == 'UL')
	{
		var arr = ['HTML','HEAD','BODY','MAP'];
		var tagname = $(e).parent().get(0).tagName;
		if ($.inArray(tagname, arr) != -1 || $(e).parent().get(0).id == '')
			return false;
		the_id = $(e).parent().get(0).id;
	}
	else if (e.tagName == 'LI')
	{
		var arr = ['HTML','HEAD','BODY','MAP'];
		var tagname = $(e).parent().parent().get(0).tagName;
		if ($.inArray(tagname, arr) != -1 || $(e).parent().parent().get(0).id == '')
			return false;
		the_id = $(e).parent().parent().get(0).id;
	}

	if (the_id == '' && $(e).parents('[id != ""]:first') != '')
	{
		the_id = $(e).parents('[id != ""]:first').attr('id');
	}

	if (the_id == '')
		return false;

	return the_id;
}

function define_edit_area_remove($elem)
{
	$('#ce-frame').contents().find($elem.attr('cms-id')).unbind('mouseover,mouseout');
	$('#t'+$elem.attr('index')).remove();
	$('#r'+$elem.attr('index')).remove();
	$('#b'+$elem.attr('index')).remove();
	$('#l'+$elem.attr('index')).remove();
	$('#area-defined-'+$elem.attr('index')).remove();
	$('#ce-frame').contents().find($elem.attr('cms-id')).addClass('cms-edit-zone-removed')
		.removeClass(site_classname)
		.removeClass(site_classname+'-repeat')
		.removeClass(site_classname+'-wysiwyg')
		.removeClass(site_classname+'-img')
		.removeClass(site_classname+'-image')
		.removeClass(site_classname+'-repeat-img')
		.removeClass(site_classname+'-repeat-image')
		.removeClass(site_classname+'-txt')
		.removeClass(site_classname+'-text')
		.removeClass(site_classname+'-html')
		.removeClass(site_classname+'-xml')
		.attr('cms-index', '')
		.attr('cms-editable', '');

	$elem.remove();
	turn_on_save_changes();
}

function define_edit_area_process_click(elem)
{
	var the_id = define_edit_area_get_id(elem);

	if (!the_id)
		return;

	var $elem = $('#ce-frame').contents().find('#'+the_id);

	if ($elem.parents('[cms-editable = "true"]').parents('[id != ""]').length > 0)
	{
		the_id = define_edit_area_parent($elem.parents('[cms-editable = "true"]').parents('[id != ""]'));
	}
	else if ($elem.attr('cms-editable') == 'true')
	{
		the_id = define_edit_area_parent($elem.parents('[id != ""]'));
	}

	if (!the_id)
		return;

	// check if the ID exists already
	var $elem = $('#ce-frame').contents().find('#'+the_id);
	if ($elem.length > 1)
	{
		var the_error = str_replace('{url}', '<a href="http://smplc.ms/duplicateids" class="new-window">http://smplc.ms/duplicateids</a>', $('#js-duplicate-id').html())
		dialog_box(str_replace('{id}', the_id, the_error));
		return;
	}

	define_edit_area_add($elem);
	$('#canvases-tmp').html('');
}

function define_edit_area_add($elem)
{
	// only show clickable area if the current, parent elements aren't already selected
	if (has_class($elem))
		return;

	if ($('.'+site_classname, $elem).size() > 0)
		$('.'+site_classname, $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-repeat', $elem).size() > 0)
		$('.'+site_classname+'-repeat', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-wysiwyg', $elem).size() > 0)
		$('.'+site_classname+'-wysiwyg', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-img', $elem).size() > 0)
		$('.'+site_classname+'-img', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-image', $elem).size() > 0)
		$('.'+site_classname+'-image', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-repeat-img', $elem).size() > 0)
		$('.'+site_classname+'-repeat-img', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-repeat-image', $elem).size() > 0)
		$('.'+site_classname+'-repeat-image', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-txt', $elem).size() > 0)
		$('.'+site_classname+'-txt', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-text', $elem).size() > 0)
		$('.'+site_classname+'-text', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-html', $elem).size() > 0)
		$('.'+site_classname+'-html', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});
	if ($('.'+site_classname+'-xml', $elem).size() > 0)
		$('.'+site_classname+'-xml', $elem).each(function(){define_edit_area_remove($('img[cms-id = "#'+$(this).attr('id')+'"]'));});

	if ($elem.hasClass('cms-edit-zone-removed'))
		$elem.removeClass('cms-edit-zone-removed');

	$elem.addClass(site_classname);
	$elem.attr('cms-index', i).attr('cms-editable', 'true');

	$('#canvases').append('<div id="t'+i+'"></div><div id="r'+i+'"></div><div id="b'+i+'"></div><div id="l'+i+'"></div><img src="/images/icons/remove_zone.png" alt="Remove" id="remove-icon-'+i+'" index="'+i+'" cms-id="#'+$elem.attr('id')+'" cms-class="'+site_classname+'" class="remove-zone" />');
	$('#canvases').append('<div id="area-defined-'+i+'" class="area-defined" cms-id="#'+$elem.attr('id')+'">'+$('#js-area-defined').html()+'</div>');

	var t_top = Math.round(frame_top - $(window).scrollTop());

	if ($.browser.msie && parseInt($.browser.version) < 9)
		t_top += $(window).scrollTop();

	var t = Math.round($elem.offset().top + t_top) - 4;
  var l = Math.round($elem.offset().left) - 4;
  var w = Math.round($elem.outerWidth()) + 8;
  var h = Math.round($elem.outerHeight()) + 8;

	$('.click-to-define').hide();
	$('#area-defined-'+i).css({'top':t, 'left':l}).show();

  $('#t'+i).css({'position':'absolute', 'top':t, 'left':(l+10), 'width':(w-10), 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
  $('#r'+i).css({'position':'absolute', 'top':t, 'left':l + w, 'width':'0', 'height':h, 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
  $('#b'+i).css({'position':'absolute', 'top':t + h - 2, 'left':l, 'width':w, 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
  $('#l'+i).css({'position':'absolute', 'top':(t+9), 'left':(l < 0)? 0 : l, 'width':'0', 'height':(h-9), 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
	$('#remove-icon-'+i).css({'position':'absolute', 'top':(t+9), 'left':(l < 0)? 4 : l});

  i++;
  define_edit_area_mouseover($elem.attr('id'));
	turn_on_save_changes();
}

function define_edit_area_parent(parents)
{
	the_id = false;
	if (parents.length > 0)
	{
		//the_id = parents.get(0).id;
		the_id = define_edit_area_get_id(parents.get(0));

		if (!the_id)
			return false;

		// remove all children areas
		$('#ce-frame').contents().find(
				'#'+the_id+' .'+site_classname+', #'+the_id+' .'+site_classname+'-wysiwyg'
				+', #'+the_id+' .'+site_classname+'-img, #'+the_id+' .'+site_classname+'-image'
				+', #'+the_id+' .'+site_classname+'-txt, #'+the_id+' .'+site_classname+'-text, #'+the_id+' .'+site_classname+'-html, #'+the_id+' .'+site_classname+'-xml'
			).each(function()
		{
			define_edit_area_remove($('#remove-icon-'+$(this).attr('cms-index')));
		});
	}
	return the_id;
}

function define_edit_area_mouseover(the_id)
{
	if (!frame_top)
		frame_top = Math.round($('#ce-frame').offset().top);
	$('#ce-frame').contents().find('#'+the_id).bind('mouseover',function()
	{
		$('.area-defined').hide();
		var the_offset = Math.round(frame_top - $(window).scrollTop());

		var t = Math.round($(this).offset().top + the_offset) - 4;
	  var l = Math.round($(this).offset().left) - 4;
	  var w = Math.round($(this).outerWidth()) + 8;
	  var h = Math.round($(this).outerHeight()) + 8;

		//if ($.browser.msie)
		if ($.browser.msie && parseInt($.browser.version) < 9)
			t += $(window).scrollTop();

		var cms_index = $(this).attr('cms-index');

		$('#area-defined-'+cms_index).css({'top':$('#t'+cms_index).css('top'), 'left':l}).show();
		//$('#area-defined-'+cms_index).css({'top':$('#t'+cms_index).css('top'), 'left':$('#t'+cms_index).css('left')}).show();
	});

	$('#ce-frame').contents().find('#'+the_id).bind('mouseout',function()
	{
		$('#area-defined-'+$(this).attr('cms-index')).hide();
	});
}

function callback(form_id, data)
{
  if (data == null) {
  	loading_off();
    return false;
  }

  if (typeof data == 'string' && !check_login(data))
		return false;

	if (data.login_redirect != undefined && !check_login(data.login_redirect))
		return false;

	if (data.reload_wysiwyg_toolbar != undefined)
	{
		editor_toolbar = eval(data.reload_wysiwyg_toolbar.icons);
		//setup_wysiwyg();
	}

	if (data.set_edit_page != undefined)
	{
		$('#frm_a').val(data.set_edit_page);

		ignore_callback = true;
		load_editor_window(data.set_edit_page);
		$.history.load('/preview/edit');
		return true;
	}

  if (typeof data == 'string' && data.substr(0, 12) == '::redirect::')
  {
  	if (data.substr(12,7) == 'http://' || data.substr(12,8) == 'https://')
  	{
  		window.location = data.substr(12);
    	return false;
    }
  	if (data.substr(12) == '/sites/add' && current_page.substr(0, 14) != '/sites/remove/')
  	{
			if (data.dialog != undefined && eval('typeof window.'+dialog) == 'function')
				eval(data.dialog+'("'+data.error+'")');
	  	else
	    	dialog_box($('#js-add-site-redirect').html());
  	}
  	else if (data.substr(12) == '/sites/add' || data.substr(12) == '/sites/add/true')
  	{
			if (data.dialog != undefined && eval('typeof window.'+dialog) == 'function')
				eval(data.dialog+'("'+data.error+'")');
  	}
    $.history.load(data.substr(12));
    return false;
  }

  if (data.redirect != undefined)
  {
  	if (data.redirect.substr(0,7) == 'http://' || data.redirect.substr(0,8) == 'https://')
  	{
  		window.location = data.redirect;
    	return false;
    }
    $.history.load(data.redirect);
    return false;
  }

  loading_off();

  if (data.error != undefined)
  {
		if (data.dialog != undefined && eval('typeof window.'+dialog) == 'function')
			eval(data.dialog+'("'+data.error+'")');
  	else
    	dialog_box(data.error);
    return false;
  }

  return true;
}

function check_login(data)
{
  // check if the session has timed out
  if (typeof data == 'string' && data.substr(0, 18) == '::login-redirect::') {
    window.location = data.substr(18);
    return false;
  }
  return true;
}

function pageload(hash)
{
 	reset_repeat_vars();

	if (preview_timeout !== false)
	{
		clearTimeout(preview_timeout);
		preview_timeout = false;
	}

	if (hash.substr(0, 15) == '/account/logout')
		window.location = hash;

	$('#sitemap-content').hide();

	if ($('#user_is_blocked').val() == '1')
	{
		var the_path = window.location.pathname+'';
		if (the_path.substr(0,16) != '/account/upgrade')
		{
			window.location = '/account/upgrade';
			return;
		}
		else
		{
			return;
		}
	}

	if ($('#user_is_blocked_trial').val() == '1')
	{
		var the_path = window.location.pathname+'';
		if (the_path.substr(0,16) != '/account/upgrade')
		{
			window.location = '/account/upgrade';
			return;
		}
		else
		{
			return;
		}
	}

	if (hash.substr(0, 14) == '/sites/change/')
	{
		if ($.browser.msie)
		{
			if (hash.indexOf('?') == -1)
				hash += '?t='+Math.floor(Math.random()*110);
			else
				hash += '&t='+Math.floor(Math.random()*110);
		}
	  $.ajax({
	    url: hash,
	    dataType: 'json',
	    data: {'dataType':'json'},
	    success: function(data){
	    	setup_site(data);
	    	callback(null, data);
	    }
	  });
	  return;
	}

	// make sure we're always displaying a logo
	if ($('#logo').attr('src') == '')
		work_out_logo();

	if (hash.substr(0, 18) == '/sites/select_root')
		$('#address').addClass('disabled');
	else
		$('#address').removeClass('disabled');

	// if the user isn't an admin, restrict access to certain sections
	if (!is_admin)
	{
		$('#edit-logo').hide();

		if (hash.substr(0, 5) != '/help' && hash.substr(0, 13) != '/users/update' && hash.substr(0, 14) != '/sites/sitemap' && hash.substr(0, 13) != '/preview/edit' && hash.substr(0, 12) != '/preview/seo' && hash.substr(0, 13) != '/preview/page' && hash.substr(0, 13) != '/preview/code')
		{
			$.history.load('/preview/edit');
			return;
		}

		// check they have permission to edit SEO
		if (hash.substr(0, 12) == '/preview/seo' && $('li.seo').hasClass('tab-hidden'))
		{
			$.history.load('/preview/edit');
			return;
		}

		// check they have permission to add pages
		if (hash.substr(0, 13) == '/preview/page' && $('li.add-page').hasClass('tab-hidden'))
		{
			$.history.load('/preview/edit');
			return;
		}
	}
	else
	{
		if ($('#logo').attr('src') == '/images/logo_simplecms.png')
			$('#edit-logo').show();
		else
			$('#edit-logo').hide();
	}

	/*if (ignore_callback){
		ignore_callback = false;
		return;
	}*/

	if (hash)
	{
		previous_page = current_page;
		current_page = hash;
		remove_editable_areas();
		remove_edit_buttons();
		close_edit_window();
    loading_on();

		if (on_branding == true)
		{
			if (hex != '')
				updateColorsHex(hex);
			else
				updateColors(hue, rotColShiftOpts.hsl.s, rotColShiftOpts.hsl.l);
			//$('#logo').attr('src', logo);
			$('#logo').attr('src', logo).attr('style', '');

			// make sure we're always displaying a logo
			if ($('#logo').attr('src') == '')
				work_out_logo();
		}

    //if($.browser.msie)
      //hash = encodeURIComponent(hash);

		var request = (hash.substring(-1) == '/')? hash.substring(0, -1) : hash;
		//if (request.substr(0, 13) == '/preview/code')
			//request = '/preview/define';

		$('#wrapper #header #rgt #nav-lft ul li.hi').removeClass('hi');
		$('#wrapper #header #rgt #nav-lft ul li a[href = "'+request+'"]').parent().addClass('hi');

		if (hash.substr(0, 13) == '/preview/code')
		{
			$('#ce-frame').attr('src', '');
			$('#wrapper #header #rgt #nav-lft ul li a[href = "/preview/code"]').parent().addClass('hi');
		}

		if (hash.substr(0, 15) == '/preview/define')
		{
			//$('.view-source').parent().removeClass('hi');
			//$('.view-design').parent().addClass('hi');
			//$('.links-on-off').fadeTo(0, 1.0);
			$('ul#nav-define-edit-zones').show();
		}
		else
			$('ul#nav-define-edit-zones').hide();

		if (hash.substr(0, 13) == '/preview/code')
			$('ul#nav-edit-code').show();
		else
		{
			$('#partial-overlay').hide();
			$('#help-code').hide('fast');
			$('ul#nav-edit-code').hide();
		}

		if (
			hash == '/preview' || hash == '/preview/' || hash.substr(0, 15) == '/preview/define' || hash.substr(0, 13) == '/preview/edit' || hash.substr(0, 13) == '/preview/code' || hash.substr(0, 12) == '/preview/seo' || hash.substr(0, 14) == '/preview/page' ||
			hash == '/sites' || hash == '/sites/' || hash.substr(0, 13) == '/sites/remove' || hash.substr(0, 13) == '/sites/update' || hash.substr(0, 13) == '/sites/config' ||
			hash == '/users' || hash == '/users/' || hash.substr(0, 13) == '/users/remove' || hash.substr(0, 10) == '/users/add' || hash.substr(0, 14) == '/users/update/' || hash.substr(0, 11) == '/users/info' || hash.substr(0, 12) == '/users/sites' || hash.substr(0, 12) == '/users/login' || hash.substr(0, 12) == '/users/pages' || hash.substr(0, 17) == '/users/additional' || hash.substr(0, 18) == '/users/permissions'
		)
		{
			if ($('#frm_current_site_url').val() == '')
			{
				dialog_box($('#js-add-site-redirect').html());
				$.history.load('/sites/add');
				return;
			}
		}

    if (hash == '/preview' || hash == '/preview/' || hash.substr(0, 15) == '/preview/define' || hash.substr(0, 13) == '/preview/edit' || hash.substr(0, 13) == '/preview/code')
    {
    	document.title = page_title;
    	$('#save-changes').fadeIn();
    }
		else
		{
    	$('#save-changes').fadeOut();

			// unbind define edit zones and edit content features
			$('#ce-frame, .ce-button').unbind('mouseenter');
			$('#ce-frame').unbind('mouseleave');
			$('#ce-frame').contents().unbind('mouseover');
			$('#ce-frame').contents().unbind('mouseout');
			$('#ce-frame').contents().unbind('click');
			$(window).unbind('resize');
		  $(window).unbind('scroll');
    }

    if (hash == '/preview' || hash == '/preview/' || hash.substr(0, 15) == '/preview/define' || hash.substr(0, 13) == '/preview/edit')
    {
    	document.title = $('#wrapper #header #rgt #nav-lft ul li.hi').text()+' :: '+page_title;

			if ($('#ce-frame').attr('src') == '')
				load_editor_window($('#frm_a').val());
			else
			{
				load_editor_window($('#frm_a').val());
				//display_edit_content();
				//$('#ce-frame').load();
			}
			return;
    }
    else
      close_editor_window();

		var the_timeout = 25000;

		if (hash.substr(0, 12) == '/users/pages')
			the_timeout = 120000;
		else if (hash.substr(0, 18) == '/sites/select_root')
			the_timeout = 600000;

		if ($.browser.msie)
		{
			if (hash.indexOf('?') == -1)
				hash += '?t='+Math.floor(Math.random()*110);
			else
				hash += '&t='+Math.floor(Math.random()*110);
		}

    $.ajax({
      url: hash,
      dataType: 'html',
      data: {'isAjax':'true'},
      timeout: the_timeout,
      error: function(XMLHttpRequest, textStatus, errorThrown)
      {
      	loading_off();
      	dialog_box_hang('ajax-change-page');
      },
      success: function(data)
      {
				if (do_reload === true)
				{
					do_reload = false;
					reload_session();
				}

				if (hash.substr(0, 14) == '/sites/remove/')
					$.ajax({url:'/sites/cleanup',dataType:'html',timeout:500});

        if (callback(null, data))
        {
          $('#content').html(data);
          document.title = $('#content h1:first').text()+' :: '+page_title;
          set_defaults();
          if (hash.substr(0, 14) == '/account/brand')
          	onload_branding();
          else
          	on_branding = false;
					if (hash.substr(0, 13) == '/preview/code' && $('#PreviewDefineEditZoneCode').get(0) != undefined)
						onload_preview_code();

          if (hash.substr(0, 18) == '/sites/select_root')
        	{
						// remove edit buttons
						remove_edit_buttons();
						remove_editable_areas();

						// remove url from iframe
						$('#ce-frame').attr('src', '');
					}

          if (hash.substr(0, 5) == '/help')
        		$('#HelpComments').focus();

					if (hash.substr(0, 13) == '/users/pages/')
					{
						$('.site-pages tr.plain-td').each(function()
						{
							if ($('li.page a.restricted-page', $(this)).length == $('li.page a', $(this)).length)
							{
								$('.restrict-all-pages', $(this)).css('display','none');
								$('.unrestrict-all-pages', $(this)).css('display','block');
							}
						});
					}

					if ($('#flashMessage').html() != '' && $('#flashMessage').html() != null)
					{
						if ($('#flashMessage').hasClass('dialog_box_upgrade'))
							dialog_box_upgrade($('#flashMessage').html());
						else
							dialog_box($('#flashMessage').html());
					}
        }
      }
    });
  }
}

function onload_preview_code()
{
	document.title = 'Code view :: '+page_title;
	var w = $(window).width()-190;
	var h = $(window).height() - ($('#header').offset().top + $('#header').outerHeight() + 21);
	$('#PreviewDefineEditZoneCode').css({'width':w, 'height':h});
	$('#PreviewDefineEditZoneCode').die('keyup');
	if ($('#PreviewIsOk').val() == 'true')
	{
		$('.CodeMirror-wrapping').remove();
		CodeMirrorEditor = CodeMirror.fromTextArea('PreviewDefineEditZoneCode',
		{
			parserfile: ['parsexml.js', 'parsecss.js', 'tokenizejavascript.js', 'parsejavascript.js', 'parsehtmlmixed.js'],
			stylesheet: ['/js/codemirror/css/xmlcolors.css', '/js/codemirror/css/jscolors.css', '/js/codemirror/css/csscolors.css'],
			path: '/js/codemirror/',
			onChange: function(){
				turn_on_save_changes();
			}
		});
	}
	else
	{
		$('#PreviewDefineEditZoneCode').css({'width':w+20, 'height':h-30, 'margin-top':'-30px', 'padding':'10px'});
		$('#PreviewDefineEditZoneCode').live('keyup',function()
		{
			turn_on_save_changes();
		});
	}
}

function onload_branding()
{
	on_branding = true;
	$('#edit-logo').hide();

	process_branding();
	$('#browse-logo').uploadify({
		'uploader'      	: '/js/jquery/uploadify/uploadify.swf',
		'script'        	: '/account/uploadify?sid='+$('#sid').val(),
		'cancelImg'     	: '/images/uploadify/cancel.png',
		'folder'        	: $('#brand-folder-upload').text(),
		'queueID'       	: 'fileQueue',
		'fileExt'       	: '*.jpg, *.jpeg, *.png, *.gif, *.bmp, *.tiff, *.tif',
		'wmode'         	: 'transparent',
		'width'         	: '111',
		'height'        	: '33',
		'auto'          	: true,
		'hideButton'    	: true,
		'multi'         	: false,
		'onSelect'				: function(event, queueID, fileObj)
			{
  			$('#preview-logo .submit a').die('click');
  			$('#preview-logo .submit a').live('click',function(){process_brand_crop();});
				remove_generic_logo();
				$('#preview-logo').addClass('set-logo');
				$('.tooltip:visible').hide();
				loading_on();

				//uploadify
				$('.uploadifyQueueItem').show();
				$('.uploadifyQueueItem:gt(1)').hide();
			},
		'onError'    			: function(event, queueID, fileObj, error)
			{
				loading_off();
			},
		'onComplete'    	: function(event, queueID, fileObj, response)
			{
				//uploadify
				$('.uploadifyQueueItem').hide();

				//$.ajax({url:'/preview/exists',data:{'request':response},success:function(data)
				//{
					loading_off();
					if (api !== false)
						api.destroy();

					$('#preview-logo .logo').html('<img src="'+response+'" id="crop-box" />');
					$('#logo').attr('src', response);
					$('#preview-logo').slideDown('fast');

					$('#crop-box').css('max-width', '516px');
					$('#crop-box').bind('load',function()
					{
						var w = $('#crop-box').width();
						var h = $('#crop-box').height();
						api = $.Jcrop('#crop-box',
						{
							onChange: showPreview,
							onSelect: showPreview,
							boxWidth: 516,
							trueSize: [w,h],
							aspectRatio: 1,
							minSize: [75, 75],
							setSelect: [0, 0, 75, 75],
							sideHandles: false,
							bgColor: '#ebf2fe'
						});
					});
				//}});
			},
		'onOpen' : function()
			{
				$('#AccountJcropSave').val('true');
			}
	});

	// make sure the hue is setup correctly so we don't lose the colour when saving
	rotColShiftOpts.hsl.h = hue;

	// set the sliders up and handle their input
	$('#pickers').show();
	$('#huepicker').slider({value: hue, animate: rotColShiftOpts.sliderAnimSpeed}).bind('slide',function(event, ui)
	{
		rotColShiftOpts.hsl.h = Number(ui.value);
		$('#AccountHue').val(rotColShiftOpts.hsl.h);
		updateColors(rotColShiftOpts.hsl.h, rotColShiftOpts.hsl.s, rotColShiftOpts.hsl.l);
	});
/*
	$('#AccountGuide').live('change',function()
	{
		if ($(this).val() != '')
		{
			var user_guide = $(this).val();
			var res = user_guide.match(new RegExp('.(pdf)$', 'i'));
			if (res == null)
				$(this).addClass('validation-failed');
			else
				$(this).removeClass('validation-failed');
		}
	});
*/
}

function enable_links()
{
	$('#ce-frame').contents().find('a, map area').unbind('click keypress');
	catch_links();
}

function disable_links()
{
	$('#ce-frame').contents().find('a, map area').unbind('click keypress');
	$('#ce-frame').contents().find('a, map area').bind('click keypress',function(e)
	{
		if ($(this).attr('original_href') == undefined)
			$(this).attr('original_href', $(this).attr('href'));
		$(this).attr('href', 'javascript:;');
	});
	// display the "activate links" dialog box when they click on a link - only this dialog box once
	$('#ce-frame').contents().find('a, map area').bind('click',function(e)
	{
		if ($('#ce-frame').contents().find('body div.wrapper-error ul.tree').length > 0)
			return;
		if(!displayed_links_behaviour && current_page.substr(0, 15) == '/preview/define')
		{
			dialog_box_links_behaviour();
			displayed_links_behaviour = true;
			return false;
		}
	});
}

function site_selector()
{
	var site_selector_timeout = false;
  $('#trigger-site-selector').live('click', function(){if ($('#sites').is(':visible')) $('#sites').slideUp('fast'); else $('#sites').slideDown('fast');});
  $('#site-selector').live('mouseenter',function(){window.clearTimeout(site_selector_timeout);});
  $('#site-selector').live('mouseleave',function(){site_selector_timeout=window.setTimeout(function(){$('#sites').slideUp('fast');},800);});
  $('#sites a, a.change-site').live('click', function(){confirm_changes(null, 'switch_site("'+$(this).attr('rel')+'");', null);});
}

function switch_site($id)
{
	if ($('#user_is_blocked').val() == '1' || $('#user_is_blocked_trial').val() == '1')
		return;
  loading_on();
	$('#partial-overlay').hide();
	$('#help-code').hide('fast');
  $('#sites').slideUp('fast');
  $('#sitemap-content').slideUp('fast').html('');
  close_editor_window();
  $('#ce-frame').attr('src', '');
  $.history.load('/sites/change/'+$id);
}

function sitemap()
{
	$('#secure-page').live('hover',function() { if ($(this).hasClass('padlock-open')) $(this).attr('title', $('#js-switch-secure').text()); else $(this).attr('title', $('#js-switch-unsecure').text()); },function() { if ($(this).hasClass('padlock-open')) $(this).attr('title', $('#js-switch-secure').text()); else $(this).attr('title', $('#js-switch-unsecure').text()); });
	$('#secure-page').live('click',function() {
		window.location = $(this).attr('href')+'#'+current_page;
		return false;
	});

	var sitemap_timeout = false;
	$('#trigger-a').live('click',function()
	{
		if ($('#address').hasClass('disabled') || $('#frm_current_site_url').val() == '')
			return;

		$('#partial-overlay').hide();
		$('#help-code').hide('fast');

		var the_url = '/preview/edit';
		if (current_page.substr(0, 15) == '/preview/define')
			the_url = '/preview/define';
		else if (current_page.substr(0, 13) == '/preview/code')
			the_url = '/preview/code/'+$.base64Encode($('#frm_a').val());
		confirm_changes(null, 'ignore_callback=true;load_editor_window("'+$('#frm_a').val()+'");$.history.load("'+the_url+'");', null);
	});

	$('#frm_a').live('keypress',function(e){
		if (e.keyCode == '13')
		{
			if ($('#address').hasClass('disabled') || $('#frm_current_site_url').val() == '')
				return;

			var the_url = '/preview/edit';
			if (current_page.substr(0, 15) == '/preview/define')
				the_url = '/preview/define';
			else if (current_page.substr(0, 13) == '/preview/code')
				the_url = '/preview/code/'+$.base64Encode($('#frm_a').val());
			confirm_changes(null, 'ignore_callback=true;load_editor_window("'+$('#frm_a').val()+'");$.history.load("'+the_url+'");', null);
		}
	});

	$('#trigger-sitemap').live('click',function()
	{
		if ($('#address').hasClass('disabled'))
			return;

		$('#partial-overlay').hide();
		$('#help-code').hide('fast');

		if ($('#sitemap-content').is(':visible'))
      $('#sitemap-content').slideUp('fast');
    else
    	if ($('#sitemap-content').html() == '')
				load_sitemap(true, false);
			else
				$('#sitemap-content').slideDown('fast');
	});

	$('#sitemap li.folder a').live('click',function()
	{
		if ($('#address').hasClass('disabled'))
			return;

		var li = $(this).parent();
    if (li.hasClass('folder-open') || li.hasClass('folder-closed'))
    {
      li.toggleClass('folder-open');
      li.toggleClass('folder-closed');
      $('ul:first', li).slideToggle(500);
    }
	});

	$('#sitemap li.page a').live('click',function()
	{
		if ($('#address').hasClass('disabled'))
			return;

		var the_url = '/preview/edit';
		if (current_page.substr(0, 15) == '/preview/define')
			the_url = '/preview/define';
		else if (current_page.substr(0, 13) == '/preview/code')
			the_url = '/preview/code/'+$.base64Encode($(this).attr('rel'));

		//$('#sitemap-content').slideUp('fast');
		$('#sitemap-content').hide();
		confirm_changes(null, 'ignore_callback=true;$("#frm_a").val("'+$(this).attr('rel')+'");load_editor_window("'+$(this).attr('rel')+'");$.history.load("'+the_url+'");', null);
	});

  $('#sitemap-content').live('mouseenter',function(){window.clearTimeout(sitemap_timeout);});
  $('#sitemap-content').live('mouseleave',function(){sitemap_timeout=window.setTimeout(function(){$('#sitemap-content').slideUp('fast');},800);});
  $('.reload-sitemap').live('click',function(){load_sitemap(true, true);});
}

function load_sitemap(show, fresh)
{
	if ($('#frm_current_site_url').val() == '')
		return false;

	if (show)
	{
		var t = $('#frm_a').position().top + $('#frm_a').outerHeight();
		var l = $('#frm_a').position().left;
		var w = $('#frm_a').outerWidth() - 62;
		$('#sitemap-content').html('<div class="loading"><img src="/images/loading.gif" alt="..." /></div>').css({'top':t,'left':l,'min-width':w}).slideDown('fast');
	}

	var url = '/sites/sitemap/'+fresh+'?isAjax=true';

	if ($.browser.msie)
	{
		if (url.indexOf('?') == -1)
			url += '?t='+Math.floor(Math.random()*110);
		else
			url += '&t='+Math.floor(Math.random()*110);
	}

  $.ajax({
    url: url,
    dataType: 'html',
    success: function(data)
    {
			if (!check_login(data))
				return false;

			var t = $('#frm_a').position().top + $('#frm_a').outerHeight();
			var l = $('#frm_a').position().left;
			var w = $('#frm_a').outerWidth() - 62;

    	$('#sitemap-content').css({'top':t,'left':l,'min-width':w}).html(data);

    	if (show)
    		$('#sitemap-content').slideDown('fast');
    }
  });
}

function nav()
{
	$('#link-user-guide').live('click',function()
	{
		return !window.open(this.href,'helpguide','status=0,toolbar=0,directories=0,menubar=1,resizable=1,scrollbars=1,width=850,height=650');
	});
  $('.trigger-nav').hover(function(){
    if ($('#sites').get(0) == undefined || $('#sites').is(':hidden')){
      var _top = $('#top').height() + $('#nav-rgt').height() + 27;
      var _left = $('a', $(this)).position().left;
      $('ul.sub', $(this)).css({'top':_top+'px','left':_left}).show();
      //$('ul.sub-help', $(this)).css({'left':'auto','right':'8px'});
    }
  },
  function(){$('ul.sub', $(this)).hide();});

	$('.define-help').live('click',function()
	{
		if ($('li.view-source').hasClass('tab-hidden'))
			dialog_box_define_help($('#js-define-help').html());
		else
		{
			var the_url = '/preview/code/'+$.base64Encode($('#frm_a').val());
			confirm_changes(null, '$.history.load("'+the_url.replace(/^.*#/, '')+'");', null);
		}
	});

	$('.code-help').live('click',function()
	{
		$('#partial-overlay').show().css('top',$('#header').outerHeight());
		$('#help-code-content').html(str_replace('{site_classname}', site_classname, $('#help-code-content-hidden').html()));
		$('#help-code').show('fast',function(){
			if ($('#help-code').position().left < 5)
				$('#help-code').css('left', '5px');
		});
	});

	$('.help-code-close').live('click',function()
	{
		$('#partial-overlay').hide();
		$('#help-code').hide('fast');
	});

  nav_define_edit_zones();
}

function nav_define_edit_zones()
{
  var _top = $('#header').outerHeight() + 4;
  var _left = $('li.define-edit-zones a').position().left;
  //var _left = ($('li.define-edit-zones a').position().left + $('li.define-edit-zones a').outerWidth() + 1) - $('ul#nav-define-edit-zones').outerWidth();
  $('ul#nav-define-edit-zones').css({'top':_top+'px', 'left':_left});

  var _top = $('#header').outerHeight() + 4;
  var _left = $('li.view-source a').position().left + $('li.view-source a').outerWidth();
  _left = _left - $('ul#nav-edit-code').outerWidth();
  if ($.browser.safari)
  	_left = _left - 16;
  $('ul#nav-edit-code').css({'top':_top+'px', 'left':_left+1});

  var _top = $('#header').outerHeight() + 4;
  var _left = $(window).width() - ($('li.view-source a').position().left + $('li.view-source a').width());
  _left = _left - 16;

  $('#help-code').css({'top':_top+'px', 'right':_left});
}

function set_defaults()
{
  $('input[type="checkbox"][class != "simple"]').ezMark({checkboxCls: 'ez-checkbox',checkedCls: 'ez-checkbox-on'});
}

function before_submit_UsersToolbarForm()
{
	var icons = '';
	$('#current-toolbar li.on span').each(function(){
		icons += str_replace('value-', '', $(this).attr('id'))+',';
	});
	if (icons == '')
		icons = 'Cut,Copy,Paste,';
	$('#UsersToolbar').val(icons);
	return true;
}

function before_submit_PreviewCodeForm()
{
	if (CodeMirrorEditor)
		$('#PreviewDefineEditZoneCode').val(CodeMirrorEditor.getCode());
	return true;
}

function before_submit_PreviewPageForm()
{
	turn_off_save_changes();
	$('#PreviewFilename').val($('li input#frm_the_filename').val());
	return true;
}

function before_submit_AccountBrandForm()
{
	if ($('#preview-logo').hasClass('set-logo'))
		process_brand_crop();

	if ($('#AccountSubdomain').hasClass('bg-error'))
	{
		dialog_box(str_replace('{subdomain}', $('#AccountSubdomain').val(), $('#js-subdomain-taken').html()));
		return false;
	}

	return true;
}

function before_submit_UsersSitesForm()
{
	if ($('input[name="sites[]"]:checked').length <= 0)
	{
		$('#UsersSitesForm .btn-save a').addClass('disabled');
		return false;
	}
	$('#UsersSitesForm .btn-save a').removeClass('disabled');
	return true;
}

function before_submit_UsersPagesForm()
{
	var pages = '';
	$('.restrict-page').each(function()
	{
		if ($('a.restricted-page', $(this)).length > 0)
		{
			pages += $(this).attr('id');
			$('a.restricted-page', $(this)).each(function(){pages += ','+$(this).attr('rel');});
			pages += '|';
		}
	});
	$('#UsersRestrictedPages').val(pages);
}

function process_forms()
{
  $('form').validate();
  $('.form-submit').live('click', function()
  {
		if ($(this).hasClass('disabled'))
			return false;

    $('.tooltip:visible').hide();
    $('#flashMessage').slideUp('fast',function(){$(this).remove();});
    $('html, body').animate({scrollTop:0}, 'fast');

		if ($(this).parent().parent().get(0).tagName == 'FORM')
			$form = $(this).parent().parent();
		else if ($(this).parent().parent().parent().get(0).tagName == 'FORM')
			$form = $(this).parent().parent().parent();
		else if ($(this).parent().parent().parent().parent().get(0).tagName == 'FORM')
			$form = $(this).parent().parent().parent().parent();
		else
			$form = false;

    if ($form)
    {
      if (!$form.valid())
        return false;

			var form_id = $form.attr('id');

			if (eval('typeof window.before_submit_'+form_id) == 'function')
			{
				if (eval('before_submit_'+form_id+'()') === false)
					return false;
			}

      if ($form.attr('id') == 'SomethingForm')
      {
      	//dialog_box('SomethingForm');
        //$form.submit();
      }
      else
      {
        loading_on();
        form_id = '#'+form_id;

				var the_timeout = 25000;

				if ($form.attr('action').substr(0, 12) == '/users/pages')
					the_timeout = 120000;
				else if ($form.attr('action').substr(0, 18) == '/sites/select_root')
					the_timeout = 600000;

				var the_type = (form_id == '#UsersPagesForm' || form_id == '#AccountUpgradeForm')? 'POST' : 'GET';

        $.ajax({
          url: $form.attr('action'),
          dataType: 'json',
          type: the_type,
          data: $(form_id).serialize()+'&dataType=json',
      		timeout: the_timeout,
		      error: function(XMLHttpRequest, textStatus, errorThrown)
		      {
		      	loading_off();
		      	if (current_page.substring(0, 10) == '/sites/add' && $('#SitesType').val() == 'SFTP')
		      		dialog_box($('#js-sftp-connection-error').html());
		      	else
		      		dialog_box_hang('save-form');
		      },
          success: function(data)
            {
							//if (form_id == '#SitesSelectRootForm' && data.error != undefined)
								//$('.select-root-homepage-url').show();

/*
							if (data.user_guide != undefined)
							{
								if (data.user_guide != '')
									$('#link-user-guide').attr('href',data.user_guide);
								else
									$('#link-user-guide').attr('href','/help/guide');
							}
*/

							if (data.favicon != undefined)
							{
								window.location = '/account/r/'+$.base64Encode('/#/preview/edit');
								return;
/*
								if (data.favicon != '')
									$('link[rel = "shortcut icon"]').attr('href',data.favicon);
								else
									$('link[rel = "shortcut icon"]').attr('href','/favicon.png');
*/
							}

							if (form_id == '#AccountBrandForm')
							{
								logo = $('#logo').attr('src');
								hue = rotColShiftOpts.hsl.h;
							}

							if (form_id == '#AccountUpgradeForm' && data.upgrade_complete != undefined)
								window.location = '/';

							if ((form_id == '#SitesAddForm' || form_id == '#SitesUpdateForm' || form_id == '#SitesSelectRootForm' || form_id == '#SitesConfigForm') && data.error == undefined)
								_reload_session(data, data);

							if (form_id == '#SitesAddForm' || form_id == '#SitesUpdateForm' || form_id == '#SitesConfigForm')
							{
								if (data.xml_sitemap != undefined && data.xml_sitemap != '')
								{
									$('#sitemap-content').html('');
								}
							}

							if ((form_id == '#SitesSelectRootForm' || form_id == '#PreviewPageForm') && data.error == undefined)
								load_sitemap(false, false);

							if (form_id == '#UsersPagesForm')
							{
								$('#sitemap-content').slideUp('fast').html('');
								load_editor_page($('#frm_current_page').val());
							}

							if (form_id == '#UsersAdditionalForm')
								load_editor_page($('#frm_current_page').val());

							if (data.edit_code != undefined)
							{
								if (data.edit_code == '1') $('li.view-source').removeClass('tab-hidden');
								else $('li.view-source').addClass('tab-hidden');
							}
							if (data.add_pages != undefined)
							{
								if (data.add_pages == '1') $('li.add-page').removeClass('tab-hidden');
								else $('li.add-page').addClass('tab-hidden');
							}
							if (data.edit_seo != undefined)
							{
								if (data.edit_seo == '1') $('li.seo').removeClass('tab-hidden');
								else $('li.seo').addClass('tab-hidden');
							}
							if (data.edit_links != undefined)
							{
								if (data.edit_links == '1') $('#edit_links').val('1');
								else $('#edit_links').val('0');
							}
							if (data.define_areas != undefined)
							{
								load_editor_page($('#frm_current_page').val());
								if (data.define_areas == '1')
								{
									$('li.define-edit-zones').removeClass('tab-hidden');
									nav_define_edit_zones();
								}
								else
								{
									$.ajax({url:'/sites/cleanup/all',dataType:'html',timeout:500});
									$('li.define-edit-zones').addClass('tab-hidden');
								}
							}


							//if (data.edit_includes != undefined && data.edit_includes == '1') load_editor_page($('#frm_current_page').val());

							if (data.hex != undefined && data.hex == '1')
							{
								hex = data.hex;
								updateColorsHex(hex);
							}

							if (data.reload_sitemap != undefined)
								load_sitemap(false, true);

              callback(form_id, data);
            }
        });
      }
    }
  });

  $('.btn-random a').live('click', function()
  {
    var chars = 'abcdefghjkmnpqrtuvwxyz2346789';
    var the_password = '';
    for (i = 0; i < 8; i++) {
      var j = Math.floor(Math.random() * chars.length);
      the_password += chars.charAt(j);
    }
    $('#UsersPassword').val(the_password);
  });

	$('#SitesAddForm #SitesUrl').live('blur',function()
	{
		if ($('#SitesHost').val() == '')
		{
			var ftp_host = parse_url($('#SitesUrl').val(), 'PHP_URL_HOST');
			$('#SitesHost').val(str_replace('www.', 'ftp.', ftp_host));
		}
	});

	$('#SitesAddForm #SitesUrl, #SitesUpdateForm #SitesUrl').live('blur',function()
	{
		if ($('#SitesSitemap').val() == '' && $('#SitesUrl').val() != '' && $('#SitesUrl').val() != 'http://')
		{
			var url_parts = parse_url($('#SitesUrl').val());
			var xml_sitemap = 'http://';
			if (url_parts.host != undefined && url_parts.host != '')
				xml_sitemap += url_parts.host;
			if (url_parts.path != undefined && url_parts.path != '')
				xml_sitemap += dirname(url_parts.path);
			xml_sitemap += '/sitemap.xml';
			$.ajax({url:'/sites/url_exists',data:{'u':xml_sitemap},success:function(data){if (data == 'true') $('#SitesSitemap').val(xml_sitemap);}});
		}
	});

	$('#UsersSitesForm input[name="sites[]"]').live('change',function()
	{
		if ($('input[name="sites[]"]:checked').length <= 0)
			$('#UsersSitesForm .btn-save a').addClass('disabled');
		else
			$('#UsersSitesForm .btn-save a').removeClass('disabled');
	});

	$('#UsersSEO').live('change',function()
	{
		//if ($('#user_account_id').val() == '1' && $(this).is(':checked'))
			//dialog_box_upgrade($('#js-upgrade-account').html());
	});

	$('#UsersAddPage').live('change',function()
	{
		//if ($('#user_account_id').val() == '1' && $(this).is(':checked'))
			//dialog_box_upgrade($('#js-upgrade-account').html());
	});

	$('#UsersCode').live('change',function()
	{
		if ($(this).is(':checked'))
		{
			if (current_page.substr(0, 17) == '/users/additional')
				dialog_box_code($('#js-edit-code-user').html()+'<br /><br />'+$('#js-edit-code').html());
			else
				dialog_box_code($('#js-edit-code').html());
		}
	});

	$('#UsersDefine').live('change',function()
	{
		if ($(this).is(':checked'))
		{
			dialog_box_define_areas($('#js-edit-define-areas').html());
		}
	});

	if ($.browser.msie)
	{
		// IE won't work with change event, so detect click event instead
		$('#SitesSelectClassname').live('click',function()
		{
			if ($('#SitesSelectClassname').val() == 'custom')
				$('#SitesClassname').show();
			else
			{
				if (current_page.substr(0, 13) != '/sites/config')
					$('#SitesClassname').hide();
				$('#SitesClassname').val($('#SitesSelectClassname').val());
			}
		});
	}
	$('#SitesSelectClassname').live('change',function()
	{
		if ($(this).val() == 'custom')
			$('#SitesClassname').show();
		else
		{
			if (current_page.substr(0, 13) != '/sites/config')
				$('#SitesClassname').hide();
			$('#SitesClassname').val($(this).val());
		}
	});
	$('#SitesClassname').live('keyup',function()
	{
		var _val = $(this).val();
		var tmp_val = str_replace(' ', '', _val.replace(/[^a-zA-Z 0-9 -]+/g,''));
		if (tmp_val != _val)
			$(this).val(tmp_val);
		//$(this).val(str_replace(' ', '', $(this).val().replace(/[^a-zA-Z 0-9 -]+/g,'')));
	});
	$('#wysiwyg-toolbar li.add').live('click',function(){
		if ($('#current-toolbar span.'+$('span', $(this)).get(0).className).parent().hasClass('on'))
		{
			$('#current-toolbar span.'+$('span', $(this)).get(0).className).parent().removeClass('on').fadeOut();
			$(this).fadeTo(0, 1.0);
		}
		else
		{
			$(this).removeClass('on').fadeTo(0, 0.3);
			$('#current-toolbar span.'+$('span', $(this)).get(0).className).parent().addClass('on').fadeIn('fast');
		}
	});
	$('#current-toolbar li.remove').live('click',function(){
		$(this).removeClass('on').fadeOut();
		$('#wysiwyg-toolbar span.'+$('span', $(this)).get(1).className).parent().fadeTo(0, 1.0);
	});

	$('a.my-account-rte').live('click',function()
	{
		$('#UsersRedirect').val($(this).attr('href'));
		$('#UsersUpdateForm .form-submit').trigger('click');
		return false;
	});

	$('.show-upgrade-paypal').live('click',function()
	{
		window.location = '/account/upgrade/?paypal='+$('#frm_upgrade_account_id').val();
	});

	$('.show-upgrade-cc').live('click',function()
	{
		$('#choose-payment').fadeOut('slow',function(){$('#upgrade-form').slideDown('slow');});
		$.ajax({url:'/account/eu/'+$('#frm_upgrade_account_id').val(),dataType:'html',timeout:500});
	});

	$('.show-upgrade-form').live('click',function()
	{
		$('#upgrade-form h1 span').text($(this).attr('price'));
		$('#frm_upgrade_account_id').val($(this).attr('rel'));
		$('#tbl-upgrade-chart').fadeOut('slow',function(){$('#choose-payment').fadeIn('slow');});
		return false;
	});
	$('.upgrade-back').live('click',function()
	{
		$('#upgrade-form').slideUp('slow',function(){$('#tbl-upgrade-chart').fadeIn('slow');});
	});
	$('#UpgradeCountry').live('change',function()
	{
		if ($(this).val() == 'US')
		{
			$('#upgradestates').show();
			$('#UpgradeState').addClass('required');
		}
		else
		{
			$('#upgradestates').hide();
			$('#UpgradeState').val('').removeClass('required');
		}
	});

	if ($.browser.msie && parseInt($.browser.version) < 8)
	{
		$('#UpgradeCountry').live('click',function()
		{
			$('#UpgradeCountry').trigger('change');
		});
	}

	$('#UpgradeCountry').trigger('change');
	$('#UpgradeCoupon').live('keyup',function()
	{
		$('#UpgradeCoupon').removeClass('validation-failed');
    $('#coupon-result').html('');
	});
	$('#apply-coupon').live('click',function()
	{
		if ($('#UpgradeCoupon').val() == '')
			return false;
		$.ajax({
			url: '/account/coupon_exists/'+$('#UpgradeCoupon').val()+'/'+$('#frm_upgrade_account_id').val(),
			dataType: 'json',
			timeout: 5000,
			error: function(XMLHttpRequest, textStatus, errorThrown){
				$('#coupon-result').html('');
			},success: function(data)
			{
				if (data.available == 'false')
				{
					$('#UpgradeCoupon').addClass('validation-failed');
				}
				else
				{
					$('#UpgradeCoupon').removeClass('validation-failed');

					//$('#coupon-result').html(data.text).removeClass('coupon-true').removeClass('coupon-false').addClass('coupon-'+data.available);
					$('#upgrade-form h1').fadeOut('fast',function()
					{
						$('#upgrade-form h1 span').text(data.total);
						$('#upgrade-form h1').fadeIn('fast');
					});
				}
			}
		});
	});

	$('.upgrade-update-back').live('click',function()
	{
		$('#upgrade-form').slideUp('slow',function(){$('#choose-payment').fadeIn('slow');});
	});
	$('.switch-annual a').live('click',function()
	{
		$('.roundel').fadeOut('slow');
		$('.switch-annual').fadeOut('slow',function(){
			$('.roundel').delay(1500).fadeIn('slow');
			$('.switch-monthly').fadeIn('slow');
		});
		$('.package-details .package').text('Professional annual');
		$('.package-price span').text($('.upgrade-annual-details').attr('price').replace('.00',''));
		$('#upgrade-form h1 span').text($('.upgrade-annual-details').attr('price'));
		$('#frm_upgrade_account_id').val($('.upgrade-annual-details').attr('rel'));
	});
	$('.switch-monthly a').live('click',function()
	{
		$('.roundel').fadeOut('slow');
		$('.switch-monthly').fadeOut('slow',function(){
			$('.switch-annual').fadeIn('slow');
		});
		$('.package-details .package').text('Professional monthly');
		$('.package-price span').text($('.upgrade-monthly-details').attr('price').replace('.00',''));
		$('#upgrade-form h1 span').text($('.upgrade-monthly-details').attr('price'));
		$('#frm_upgrade_account_id').val($('.upgrade-monthly-details').attr('rel'));
	});
}

function tooltips()
{
  $('form .input input, form .input select').live('focus',function(){
    $('.tooltip:visible').hide();
    var _top = $(this).position().top - 2;
    var _left = $(this).position().left + $(this).width() + 33;
		if ($(this).attr('id') == 'SitesSelectClassname')
			_left += 268;
    $('.tooltip', $(this).parent()).css({'top':_top+'px', 'left':_left+'px'}).show();
  });
  $('form .input input, form .input select').live('blur',function(){
  	$('.tooltip').hide();
  });
}

function site_select_root()
{
  $('#select-root a').live('click', function()
  {
    var li = $(this).parent();

    if (li.hasClass('up-level'))
    {
    	loading_on();
    	$('#select-root').slideUp(500);

      $.ajax({
        url: '/sites/up_level/'+$(this).attr('id'),
        dataType: 'html',
        data: {dir:$(this).attr('rel')},
        success: function(data)
          {
          	if (!check_login(data) || data == 'false')
          		return false;

						loading_off();
						$('#select-root').html(data).slideDown(500);
          }
      });
    }

    /*if (li.hasClass('folder'))
    {
    	$('#select-root a.selected-folder').removeClass('selected-folder');
    	$(this).addClass('selected-folder');
    }*/

    if (li.hasClass('page'))
    {
    	$('#select-root a.selected-page').removeClass('selected-page');
    	$(this).addClass('selected-page');
    }

    if (li.hasClass('root-open') || li.hasClass('root-closed'))
    {
      //li.toggleClass('root-open');
      //li.toggleClass('root-closed');
      $('ul', li).slideToggle(500);
    }

    if (li.hasClass('folder-open') || li.hasClass('folder-closed'))
    {
      li.toggleClass('folder-open');
      li.toggleClass('folder-closed');
      $('div:first', li).slideToggle(500);
    }

    if (li.hasClass('folder-open'))
    {
      if ($('ul:first', li).get(0) == undefined)
      {
        li.addClass('loading');
        $.ajax({
          url: '/sites/list_contents/'+$(this).attr('id'),
          dataType: 'html',
          data: {dir:$(this).attr('rel'),level:$(this).attr('rev')},
          success: function(data)
            {
            	if (!check_login(data))
            		return false;

							li.removeClass('loading');
							$('div:first', li).html(data).slideDown(500);
							li.addClass('folder-open');
							li.removeClass('folder-closed');
            }
        });
      }
    }

    if (li.hasClass('page'))
    {
    	if ($(this).attr('rel') != '/')
    		var root_dir = $(this).attr('rel')+'/'+$(this).text();
    	else
    		var root_dir = '/'+$(this).text();
    	$('#SitesRootDirDisplay').val(root_dir);
	    $('#SitesRootDir').val($(this).attr('rel'));
	    $('#select-root a.hi').removeClass('hi');
	    $(this).addClass('hi');
		}
    return false;
  });
}

function site_select_page()
{
	$('.copy-page li.folder a, .restrict-page li.folder a').live('click',function()
	{
		var li = $(this).parent();
    if (li.hasClass('folder-open') || li.hasClass('folder-closed'))
    {
      li.toggleClass('folder-open');
      li.toggleClass('folder-closed');
      $('ul:first', li).slideToggle(500);
    }
	});

	$('.restrict-page li.page a').live('click',function()
	{
		$(this).toggleClass('restricted-page');
		var $pages = $(this).parents('td:first');
		if ($('li.page a.restricted-page', $pages).length == $('li.page a', $pages).length)
		{
			$('.restrict-all-pages', $pages).css('display','none');
			$('.unrestrict-all-pages', $pages).css('display','block');
		}
		else
		{
			$('.restrict-all-pages', $pages).css('display','block');
			$('.unrestrict-all-pages', $pages).css('display','none');
		}
	});

	$('.restrict-all-pages').live('click',function()
	{
		var the_id = '#'+$(this).attr('rel');
		$(the_id+' .restrict-all-pages').css('display','none');
		$(the_id+' .unrestrict-all-pages').css('display','block');
		$(the_id+' li.page a').each(function(){$(this).removeClass('restricted-page');$(this).addClass('restricted-page');});
	});
	$('.unrestrict-all-pages').live('click',function()
	{
		var the_id = '#'+$(this).attr('rel');
		$(the_id+' .restrict-all-pages').css('display','block');
		$(the_id+' .unrestrict-all-pages').css('display','none');
		$(the_id+' li.page a').each(function(){$(this).removeClass('restricted-page');});
	});

	$('.show-pages').live('click',function()
	{
		var the_id = '#tbl-'+$(this).attr('id');
		if ($(the_id).is(':hidden'))
		{
			$(this).addClass('open');
			$(this).removeClass('closed');
			$(the_id).show();
		}
		else
		{
			$(this).removeClass('open');
			$(this).addClass('closed');
			$(the_id).hide();
		}
	});
}

function copy_page()
{
	var copy_page_filename = '';
	$('.copy-page .lft li.page a').draggable({
		revert:'invalid',
		cursor: 'move',
		helper: 'clone',
		refreshPositions: true,
		start: function(){$('.lft a.selected-page').removeClass('selected-page');$(this).addClass('selected-page');}
	});

	$('.copy-page .rgt li.folder').droppable({
		activeClass: 'drop-active',
		hoverClass: 'drop-hover',
		accept: '.copy-page .lft li.page a',
		greedy: true,
		over: function(ev, ui)
		{
			if ($(this).hasClass('root-open'))
				return;

			$(this).addClass('folder-open');
			$(this).removeClass('folder-closed');
			$('ul:first', $(this)).slideDown(500);
		},
		drop: function(ev, ui)
		{
			if (ui.draggable.attr('rel') != undefined)
			{
				turn_on_save_changes();
				copy_page_filename = $('#PreviewFilename').val();
				var ext = ui.draggable.text().split('.').pop();
				var filename = str_replace('.html', '.'+ext, $('#PreviewFilename').val());
				$('#PreviewFilename').val(filename);
				$('#PreviewSource').val(ui.draggable.attr('rel'));
				$('#PreviewDestination').val($('a', $(this)).attr('rel'));
				$('.btn-page a.btn').removeClass('disabled');
				$('.copy-page .lft').fadeTo(0, 0.5);
				$('.copy-page .lft li.page a').draggable('option','disabled',true);
				$('ul:first', $(this)).append('<li class="page new-page"><a href="javascript:;" rel="'+ui.draggable.attr('rel')+'"><span style="display:none;"></span><span><input type="text" name="the_filename" id="frm_the_filename" value="'+filename+'" /></span></a></li>');
				$('ul.tree li.new-page input').focus().select();

				// close all open folders bar the dropped folder
/*
				$('.rgt .folder-open').each(function()
				{
					$(this).removeClass('folder-open');
					$('ul:first', $(this)).hide();
				});
*/
				//$(this).parents('li').addClass('folder-open').show();
				//$(this).addClass('folder-open').show();
				//$('ul:first', $(this).parents()).hide();
			}
		}
	});

	$('.new-page #frm_the_filename').live('blur, keypress',function(e)
	{
		if (e.keyCode == '13' || e.type == 'blur')
		{
			$('.new-page').addClass('saved-page').removeClass('new-page');
			var filename = str_replace(' ', '-', str_replace("'", '', str_replace(',', '', $(this).val())));
			filename = filename.split('.');
			if (filename.length > 1)
				filename.pop();
			filename = filename.join('-')+'.'+$('#PreviewSource').val().split('.').pop();
			$(this).val(filename);
			$('span:first', $(this).parent().parent()).html(filename).show();
			$(this).parent().hide();
			return false;
		}
	});

	$('.reset-copy-page').live('click',function()
	{
		$('#PreviewFilename').val(copy_page_filename);
		$('#PreviewSource').val('');
		$('#PreviewDestination').val('');
		$('.btn-page a.btn').addClass('disabled');
		$('.copy-page .lft').fadeTo(0, 1.0);
		$('.copy-page .lft li.page a').draggable('option','disabled',false);
		$('.copy-page .rgt .new-page').remove();
		$('.copy-page .rgt .saved-page').remove();
	});
}

function load_seo()
{
	if ($('#user_is_blocked').val() == '1' || $('#user_is_blocked_trial').val() == '1')
		return;
	if ($('#frm_current_site_url').val() == '')
	{
		dialog_box($('#js-add-site-redirect').html());
		$.history.load('/sites/add');
		return;
	}

	if (current_page != '/preview/edit')
	{
		$('#wrapper #header #rgt #nav-lft ul li.hi').removeClass('hi');
		$('#wrapper #header #rgt #nav-lft ul li a[href = "/preview/edit"]').parent().addClass('hi');

		// just to make sure the branding reverts to what it should be
		if ($.browser.msie && on_branding == true)
		{
			if (hex != '')
				updateColorsHex(hex);
			else
				updateColors(hue, rotColShiftOpts.hsl.s, rotColShiftOpts.hsl.l);
			$('#logo').attr('src', logo);
		}

		if ($('#ce-frame').attr('src') == '')
			$.history.load('/preview/edit');
		else
		{
			display_edit_content();
			ignore_callback = true;
			$.history.load('/preview/edit');
		}
	}

	// get SEO form and display in the centre of the screen
	loading_on();
  $.ajax({
    url: '/preview/seo/'+$.base64Encode($('#frm_current_page').val())+'/?t='+Math.floor(Math.random()*110),
    dataType: 'json',
    data: {'dataType':'json'},
    success: function(data)
      {
      	loading_off();

				if (data.login_redirect != undefined && !check_login(data.login_redirect))
					return false;

				if (data.error != undefined){
      		dialog_box(data.error);
      		return;
      	}

				$('#canvases').html('<div id="t"></div>');
				$('#t').css({'position':'fixed', 'top':0, 'left':0, 'z-index':20000, 'width':'100%', 'height':'100%'}).show();

				//$('#dialog-overlay').show();
				$('#dialog-confirm').dialog('destroy');
				$('#dialog-confirm').attr('title', $('#js-title-edit-meta-information').html()).html(data.html);

				$('#PreviewSeoTitle').val(data.title);
				$('#PreviewSeoKeywords').val(data.keywords);
				$('#PreviewSeoDescription').val(data.description);

				$('#dialog-confirm').dialog(
				{
					resizable: false,
					height: 'auto',
					modal: true,
					draggable: false,
					position: ['center',100],
					zIndex: 20000,
					stack: false,
					closeOnEscape: false,
					buttons: {
						'Cancel changes': function()
						{
							close_edit_window();
							//$('#dialog-overlay').hide();
							$(this).dialog('close');
						},
						'Save': function()
						{
							close_edit_window();
							//$('#dialog-overlay').hide();
							$(this).dialog('close');

							loading_on();
							$.ajax({
						    url: '/preview/seo/'+$.base64Encode($('#frm_current_page').val()),
						    dataType: 'json',
						    type: 'POST',
						    data: {
						    	'save_seo':'true',
							  	'remote_file':$('#PreviewSeoRemoteFile').val(),
							  	'title':$('#PreviewSeoTitle').val(),
							  	'keywords':$('#PreviewSeoKeywords').val(),
							  	'description':$('#PreviewSeoDescription').val(),
							  	'dataType':'json'
						  	},
						    success: function(data)
						    {
						    	loading_off();

									if (data.redirect != undefined)
										$.history.load(data.redirect);

								  if (data.error != undefined)
								  {
										if (data.dialog != undefined && eval('typeof window.'+dialog) == 'function')
											eval(data.dialog+'("'+data.error+'")');
								  	else
								    	dialog_box(data.error);
								    return false;
								  }

									load_editor_page($('#frm_current_page').val());
				      		close_edit_window();
									//$('#dialog-overlay').hide();
									$(this).dialog('close');

									if (data.login_redirect != undefined && !check_login(data.login_redirect))
										return false;
						    }
						  });
						}
					},
					open: function(event, ui)
					{
						$('span.ui-button-text:eq(0)').html($('#js-btn-cancel-changes-2').html());
						$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

						$('span.ui-button-text:eq(1)').html($('#js-btn-save-changes').html());
						$('span.ui-button-text:eq(1)').parent().addClass('btn-save');
					}
				});
      }
  });
}

function process_image_editor(img_src)
{
	if (jcrop_api !== false)
		jcrop_api.destroy();

	loading_on();

	$('#editor-img, #image-buttons').hide();
	$('.img-content').html('<img src="'+img_src+'" />');
	$('.img-content img').css('max-width', '760px');//.hide();

	$('.img-content img').bind('load',function()
	{
		$(this).show();
		$('#editor-img, #image-buttons').show();

		ce.originalWidth = $(this).width();
		ce.originalHeight = $(this).height();

		if (ce.originalWidth == 0)
			ce.originalWidth = $(this).get(0).width;

		if (ce.originalHeight == 0)
			ce.originalHeight = $(this).get(0).height;

		var w = ce.originalWidth + 40;
		if (w > 800)
			w = 800;
		else if (w < 500)
			w = 500;

		$('#editor-img').css('width', w);

		var l = ($(window).width() / 2) - ($('#editor-img').outerWidth() / 2);
		$('#editor-img').css({'top':'150px', 'left':l}).show();
		var t = $('#editor-img').offset().top+$('#editor-img').outerHeight();
		$('#image-buttons').css({'top':t, 'left':l, 'width':$('#editor-img').outerWidth()}).show();

		jcrop_api = $.Jcrop('.img-content img',
		{
			boxWidth: 760,
			trueSize: [ce.originalWidth,ce.originalHeight],
	    aspectRatio: aspect,
	    setSelect: [0,0,$(this).width(),$(this).height()],
	    sideHandles: false,
	    bgColor: '#fff'
	  });

		loading_off();
	});
}

function display_edit_content()
{
	$('#content').html('');
	$('#ce-frame').show();
	$('#ce-frame').css('height', Math.round(($(window).height() - $('#ce-frame').offset().top))+'px');
}

function process_branding(img)
{
	backup_logo = $('#logo').attr('src');

	$('#brand-example-logos img').live('click',function()
	{
		$('.remove-generic-logo').show();
		$('#brand-example-logos .selected').removeClass('selected');
		$(this).parent().addClass('selected');
		$('#logo').attr('src', $(this).attr('src')).attr('style', '');
		$('#AccountGenericLogo').val($(this).attr('src'));
		$('#preview-logo').slideUp('fast');
		$('#preview-logo').removeClass('set-logo');
	});

	$('.remove-generic-logo a').live('click',function(){remove_generic_logo();});

	$('#AccountSubdomain').live('keyup',function()
	{
		var _val = $(this).val();
		var tmp_val = str_replace(' ', '', _val.replace(/[^a-zA-Z 0-9 -]+/g,''));
		if (tmp_val != _val)
			$(this).val(tmp_val);
		//$(this).val(str_replace(' ', '', $(this).val().replace(/[^a-zA-Z 0-9 -]+/g,'')));
		$('.brand-save .form-submit').removeClass('disabled');
		$('#AccountSubdomain').removeClass('bg-success').removeClass('bg-error');
    $('#check-subdomain').removeClass('taken').removeClass('available').html($('#js-check-name').html());
	});
	$('#check-subdomain').live('click',function(){
    $('.brand-save .form-submit').addClass('disabled');
		$('#check-subdomain').addClass('checking');
		check_subdomain_exists();
	});
}

function remove_generic_logo()
{
	$('#brand-example-logos .selected').removeClass('selected');
	$('#logo').attr('src', backup_logo);
	$('.remove-generic-logo').hide();
	$('#AccountGenericLogo').val('');
}

function process_brand_crop()
{
	$('#preview-logo .submit a').die('click');
	$('#preview-logo').slideUp('fast');
	if (api !== false)
	{
		$('#preview-logo').removeClass('set-logo');

		//loading_on();
		coords = api.tellSelect();

    $.ajax({
      url: '/account/crop',
      dataType: 'json',
      data:
      	{
      		'logo':$('#logo').attr('src'),
      		'w':coords.w,
      		'h':coords.h,
      		'x':coords.x,
      		'y':coords.y,
      		'save':$('#AccountJcropSave').val(),
      		'dataType':'json'
      	},
      success: function(data)
        {
					//loading_off();
					if (data.get.logo)
					{
						logo = data.get.logo+'?t='+Math.floor(Math.random()*110);
						$('#logo').attr('src', logo).attr('style', '');
					}

        	if (data.login_redirect != undefined && !check_login(data.login_redirect))
						return false;

        	$('#AccountJcropSave').val('');
        }
    });
	}
}

function check_subdomain_exists()
{
	if ($('#AccountSubdomain').val() == '')
	{
    $('.brand-save .form-submit').removeClass('disabled');
		$('#check-subdomain').removeClass('checking');
		return false;
	}

  $.ajax({
    url: '/account/subdomain_exists/'+$('#AccountSubdomain').val()+'/true',
    dataType: 'json',
    timeout: 5000,
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
      $('#check-subdomain').removeClass('checking');
  		$('.brand-save .form-submit').addClass('disabled');
  		$('#AccountSubdomain').addClass('bg-error').removeClass('bg-success');
  		$('#check-subdomain').addClass('taken').html($('#js-try-again').html());
    },
    success: function(data)
      {
      	$('#check-subdomain').removeClass('checking');
      	if (data.taken != undefined)
      	{
      		$('.brand-save .form-submit').addClass('disabled');
      		$('#AccountSubdomain').addClass('bg-error').removeClass('bg-success');
      		$('#check-subdomain').addClass('taken').html($('#js-try-again').html());
      	}
      	else
      	{
      		$('.brand-save .form-submit').removeClass('disabled');
      		$('#AccountSubdomain').addClass('bg-success').removeClass('bg-error');
      		$('#check-subdomain').addClass('available').html($('#js-available').html());
      	}
      }
  });
}

function fix_flash()
{
  // sort out embed code
  $('#ce-frame').contents().find('embed').each(function(){
    $(this).attr('wmode', 'transparent');
    $(this).css({'position':'relative'});
  });

  // sort out object code
  $('#ce-frame').contents().find('object[type="application/x-shockwave-flash"]').each(function(){
    $(this).append('<param name="wmode" value="transparent" />');
    $(this).css({'position':'relative'});
  });
}

function catch_links()
{
  $('#ce-frame').contents().find('a, map area').bind('click keypress', function(e)
  {
		setTimeout('set_frame_height();', 200);

  	$('#sites').slideUp('fast');
		$('#sitemap-content').slideUp('fast');

		if (current_page.substr(0, 15) == '/preview/define')
			setTimeout('position_define_zones();', 500);
		else
			setTimeout('position_edit_buttons();', 500);
/*
*/
		if ($(this).attr('original_href') != undefined && $(this).attr('href') == 'javascript:;')
			$(this).attr('href', $(this).attr('original_href'));

    var current_site_url = $('#frm_current_site_url').val();

		if (current_site_url.substring(-1) != '/')
			current_site_url = dirname(current_site_url);

    var the_href = str_replace(current_site_url, '', this.href);

    if (the_href.indexOf('#') >= 0) // let the link act as normal - jquery hidden content / sliders
    {
    	// added this to allow for jquery tabs so the system can load the current page with the anchor on it
    	var href_parts = the_href.split('#');
    	if (typeof href_parts[1] != 'undefined')
    	{
	    	var frame_src = $('#ce-frame').attr('src');
		    if (frame_src.indexOf('#') >= 0)
		    {
		    	frame_src = frame_src.split('#');
		    	frame_src = frame_src[0];
		    }
    		frame_src = frame_src+'#'+href_parts[1];

				if (typeof $('#ce-frame').get(0).contentWindow.$ != 'undefined')
				{
					$('#ce-frame').get(0).contentWindow.$(this).trigger('click');
				}
				$('#ce-frame').attr('src',frame_src);
	    	return false;
	    }
    	return;
    }
    if (the_href.indexOf('#') >= 0)
    	return false;
    //if (the_href.indexOf('#') >= 0)
    	//the_href = the_href.substring(0, the_href.indexOf('#'));

    if (the_href.charAt(0) == '#' || the_href.indexOf('mailto:') >= 0 || the_href.substring(0, 11) == 'javascript:')
    	return; // do nothing

    if (the_href.indexOf('.pdf') > 0 || the_href.indexOf('.doc') > 0 || the_href.indexOf('.rtf') > 0 || the_href.indexOf('.xls') > 0 || the_href.indexOf('.csv') > 0 || the_href.indexOf('.css') > 0 || the_href.indexOf('.js') > 0 || the_href.indexOf('.txt') > 0)
    {
    	dialog_box_new_window($('#js-new-window').html(), this.href);
    	return false;
    	//return !window.open(this.href); // open in new window;
    }

    if (the_href.indexOf('http://') != -1 || the_href.indexOf('https://') != -1)
    {
    	dialog_box_new_window($('#js-new-window').html(), this.href);
    	return false;
    	//return !window.open(); // link is external
    }

    if (the_href.indexOf('.gif') > 0 || the_href.indexOf('.png') > 0 || the_href.indexOf('.jpg') > 0 || the_href.indexOf('.jpeg') > 0)
    {
      if ($(this).attr('rel') == 'lightbox')
      	return; // do nothing
    	dialog_box_new_window($('#js-new-window').html(), this.href);
    	return false;
      //return !window.open(this.href); // open in new window
    }

		confirm_changes(null, 'load_editor_page("'+this.href+'");', null);
    return false;
  });
  $('#ce-frame').contents().bind('click',function(e)
  {
		if (current_page.substr(0, 15) == '/preview/define')
			setTimeout('position_define_zones();', 500);
		else
			setTimeout('position_edit_buttons();', 500);
	});
}

function load_editor_page(url)
{
	remove_edit_buttons();
	close_edit_window();
  loading_on();
  $('#frm_a').val(url);
  $('#frm_current_page').val(url);
	if ($.browser.msie)
	{
		if (url.indexOf('?') == -1)
			url += '?t='+Math.floor(Math.random()*110);
		else
			url += '&t='+Math.floor(Math.random()*110);
	}
	if (preview_timeout === false)
	{
		if (current_page.substr(0, 15) == '/preview/define')
			preview_timeout = setTimeout("send_hang_report('preview-define-load-page__"+$.base64Encode(url)+"');", 35000);
		else
			preview_timeout = setTimeout("send_hang_report('preview-edit-load-page__"+$.base64Encode(url)+"');", 35000);
	}
  $('#ce-frame').attr('src', '/preview?hash='+current_page+'&u='+$.base64Encode(url)+'&the-url='+encodeURIComponent(url));
}

function setup_wysiwyg()
{
	if (editor) {
		editor.destroy();
		editor = null;
	}
	$('#content-html').val('');
	editor = CKEDITOR.replace('content-html',
	{
		toolbar:editor_toolbar,
		height:editor_height,
		resize_enabled:false,
		language:editor_language,
		enterMode:editor_entermode,
		entities:editor_entities,
		toolbarCanCollapse:false,
		contentsCss:editor_customsss,
		entities_additional:editor_entities_additional
	});
	editor.setData('');
	CKFinder.SetupCKEditor(editor, '/js/ckfinder/');


	if (editor_no_p) {
		editor_no_p.destroy();
		editor_no_p = null;
	}
	$('#content-html-no-p').val('');
	editor_no_p = CKEDITOR.replace('content-html-no-p',
	{
		toolbar:editor_toolbar,
		height:editor_height,
		resize_enabled:false,
		language:editor_language,
		enterMode:CKEDITOR.ENTER_BR,
		entities:editor_entities,
		toolbarCanCollapse:false,
		contentsCss:editor_customsss,
		entities_additional:editor_entities_additional
	});
	editor_no_p.setData('');
	CKFinder.SetupCKEditor(editor_no_p, '/js/ckfinder/');

	if ($('#ce-frame').contents().find('base').attr('href') != undefined)
		$('.cke_contents iframe').contents().find('head').append('<base href="'+$('#ce-frame').contents().find('base').attr('href')+'" />');
}

function setup_html_txt_wysiwyg()
{
	if (editor_html_txt) {
		editor_html_txt.destroy();
		editor_html_txt = null;
	}
	$('#content-html-txt').val('');
	editor_html_txt = CKEDITOR.replace('content-html-txt',
	{
		toolbar:editor_html_txt_toolbar,
		height:editor_height,
		resize_enabled:false,
		language:editor_language,
		enterMode:CKEDITOR.ENTER_BR,
		entities:editor_entities,
		toolbarCanCollapse:false,
		contentsCss:editor_customsss,
		entities_additional:editor_entities_additional
	});
	editor_html_txt.setData('');
	CKFinder.SetupCKEditor(editor_html_txt, '/js/ckfinder/');

	if ($('#ce-frame').contents().find('base').attr('href') != undefined)
		$('.cke_contents iframe').contents().find('head').append('<base href="'+$('#ce-frame').contents().find('base').attr('href')+'" />');
}

function set_frame_height()
{
	$('#ce-frame').css('height', $(window).height());
	_set_frame_height();
}

function _set_frame_height()
{
	var h = $('#ce-frame').contents().height();
	if (!isNaN(h))
		$('#ce-frame').css('height', $('#ce-frame').contents().height());
}

function position_define_zones()
{
	frame_top = Math.round($('#ce-frame').offset().top);
	// display current editable areas
	//$('#ce-frame').contents().find('.'+site_classname+', .'+site_classname+'-wysiwyg'+', .'+site_classname+'-img, .'+site_classname+'-image'+', .'+site_classname+'-txt, .'+site_classname+'-text, '+'.'+site_classname+'-html, .'+site_classname+'-xml').each(function()
	$('#ce-frame').contents().find('[cms-editable = "true"]').each(function()
	{
		if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '')
			return true;

		var the_offset = Math.round(frame_top - $(window).scrollTop());
		if (the_offset < 0)
			var t_top = the_offset;
		else
			var t_top = the_offset;

		var t = Math.round($(this).offset().top + t_top) - 4;
	  var l = Math.round($(this).offset().left) - 4;
	  var w = Math.round($(this).outerWidth()) + 8;
  	var h = Math.round($(this).outerHeight()) + 8;

		//if ($.browser.msie)
		if ($.browser.msie && parseInt($.browser.version) < 9)
			t += $(window).scrollTop();

		var cms_index = $(this).attr('cms-index');
		$('#area-defined-'+cms_index).css({'top':t, 'left':l});

	  $('#t'+cms_index).css({'position':'absolute', 'left':l+10, 'top':t, 'width':(w-10), 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
	  $('#r'+cms_index).css({'position':'absolute', 'left':l + w, 'top':t, 'width':'0', 'height':h, 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
	  $('#b'+cms_index).css({'position':'absolute', 'left':l, 'top':t + h - 2, 'width':w, 'height':'0', 'border-top':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
	  $('#l'+cms_index).css({'position':'absolute', 'left':l, 'top':(t+9), 'width':'0', 'height':(h-9), 'border-right':b, 'opacity':'1.0', '-moz-opacity':'1.0', 'filter':'alpha(opacity=100)'});
	  $('#remove-icon-'+cms_index).css({'position':'absolute', 'left':(l < 0)? 4 : l, 'top':(t+9)});

		if ($(this).is(':hidden'))
			$('#t'+cms_index+', #r'+cms_index+', #b'+cms_index+', #l'+cms_index+', #remove-icon-'+cms_index).hide();
		else
			$('#t'+cms_index+', #r'+cms_index+', #b'+cms_index+', #l'+cms_index+', #remove-icon-'+cms_index).show();
	});
}

function position_edit_buttons()
{
	i = 0;
	var button_index = 0;
	var has_images = false;
	var button_positions = {};

	$('#ce-frame').contents().find('.'+site_classname+', .'+site_classname+'-wysiwyg, .'+site_classname+'-repeat').each(function()
	{
		if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '') {
			i++;
			return true;
		}

		if ($(this).attr('new') == undefined || $(this).attr('original') == undefined)
		{
			i++;
			return true;
		}

		// check if the ID exists already
		var $elem = $('#ce-frame').contents().find('#'+$(this).attr('id'));
		if ($elem.length > 1 && $('#user_account_id').val() == '0')
		{
			i++;
			return true;
		}

		$(this).attr('cms-editable', 'true');

		frame_top = Math.round($('#ce-frame').offset().top - $(window).scrollTop());
		if ($.browser.msie && parseInt($.browser.version) < 9)
			frame_top += $(window).scrollTop();
    var t = Math.round($(this).offset().top + frame_top) - ($('#ce-icon').outerHeight() + 12);
    var l = Math.round($(this).offset().left) - 29;

		if (l <= 0)
			l = 2;

		if (t < frame_top)
			t = frame_top+2;

		button_positions[button_index] = {};
		button_positions[button_index]._id = '#ce-icon-'+i;
		button_positions[button_index]._elem_id = '#'+$(this).attr('id');
		button_positions[button_index]._top = t;
		button_positions[button_index]._left = l;
		button_index++;

    if ($('#ce-icon-'+i).get(0) == undefined)
    {
    	var cms_editor = 'html';
			if ($(this).get(0).tagName == 'A' || $(this).get(0).tagName == 'SPAN' || $(this).get(0).tagName == 'H1' || $(this).get(0).tagName == 'H2' || $(this).get(0).tagName == 'H3' || $(this).get(0).tagName == 'H4' || $(this).get(0).tagName == 'H5' || $(this).get(0).tagName == 'H6')
				cms_editor = 'html-txt';
			else if ($(this).get(0).tagName == 'P')
				cms_editor = 'html-no-p';
			else if ($(this).get(0).tagName == 'IMG') {
				has_images = true;
				cms_editor = 'img';
			}
			$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').css({'top':t, 'left':l}).show();

			if (cms_editor == 'img')
			{
				$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-image');
				$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_image.png').css({'width':'28px','height':'16px'});
			}
			if (cms_editor == 'html' || cms_editor == 'html-txt' || cms_editor == 'html-no-p')
			{
				$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-html');
				$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_html.png').css({'width':'23px','height':'16px'});
			}

			if ($(this).hasClass(site_classname+'-repeat'))
			{
				l += $('#ce-icon-'+i).outerWidth() - 3;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-up-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').removeClass('ce-text').addClass('ce-repeat-up').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-up-'+i+' img').attr('src', '/images/icons/repeat_add.png').attr('width', '16').attr('title', $('#js-repeat-up').text());
				$('#ce-icon-repeat-up-'+i+' span').remove();

				l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-remove-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').addClass('rtr rbr').removeClass('ce-text').addClass('ce-repeat-remove').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-remove-'+i+' img').attr('src', '/images/icons/repeat_remove.png').attr('title', $('#js-repeat-remove').text());
				$('#ce-icon-repeat-remove-'+i+' span').remove();
			}
		}
		else
		{
			$('#ce-icon-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-'+i).outerWidth() - 3;
			$('#ce-icon-repeat-up-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
			$('#ce-icon-repeat-remove-'+i).css({'top':t, 'left':l});
		}

		if ($(this).is(':hidden'))
		{
			$('#ce-icon-'+i).hide();
			$('#ce-icon-repeat-up-'+i).hide();
			$('#ce-icon-repeat-remove-'+i).hide();
		}
		else
		{
			$('#ce-icon-'+i).show();
			$('#ce-icon-repeat-up-'+i).show();
			$('#ce-icon-repeat-remove-'+i).show();
		}

		i++;
	});

	$('#ce-frame').contents().find('.'+site_classname+'-img, .'+site_classname+'-image, .'+site_classname+'-repeat-img, .'+site_classname+'-repeat-image').each(function()
	{
		if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '') {
			i++;
			return true;
		}

		if ($(this).attr('new') == undefined || $(this).attr('original') == undefined)
		{
			i++;
			return true;
		}

		// check if the ID exists already
		var $elem = $('#ce-frame').contents().find('#'+$(this).attr('id'));
		if ($elem.length > 1 && $('#user_account_id').val() == '0')
		{
			i++;
			return true;
		}

		$(this).attr('cms-editable', 'true');

		frame_top = Math.round($('#ce-frame').offset().top - $(window).scrollTop());
		if ($.browser.msie && parseInt($.browser.version) < 9)
			frame_top += $(window).scrollTop();
    var t = Math.round($(this).offset().top + frame_top) - ($('#ce-icon').outerHeight() + 12);
    var l = Math.round($(this).offset().left) - 29;

		if (l <= 0)
			l = 2;

		button_positions[button_index] = {};
		button_positions[button_index]._id = '#ce-icon-'+i;
		button_positions[button_index]._elem_id = '#'+$(this).attr('id');
		button_positions[button_index]._top = t;
		button_positions[button_index]._left = l;
		button_index++;

    if ($('#ce-icon-'+i).get(0) == undefined)
    {
    	var cms_editor = 'img';
			has_images = true;

			$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').css({'top':t, 'left':l}).show();

			if ($(this).hasClass(site_classname+'-repeat'))
			{
				l += $('#ce-icon-'+i).outerWidth() - 3;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-up-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').removeClass('ce-text').addClass('ce-repeat-up').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-up-'+i+' img').attr('src', '/images/icons/repeat_add.png').attr('width', '16').attr('title', $('#js-repeat-up').text());
				$('#ce-icon-repeat-up-'+i+' span').remove();

				l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-remove-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').addClass('rtr rbr').removeClass('ce-text').addClass('ce-repeat-remove').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-remove-'+i+' img').attr('src', '/images/icons/repeat_remove.png').attr('title', $('#js-repeat-remove').text());
				$('#ce-icon-repeat-remove-'+i+' span').remove();
			}

			$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-image');
			$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_image.png').css({'width':'28px','height':'16px'});
		}
		else
		{
			$('#ce-icon-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-'+i).outerWidth() - 3;
			$('#ce-icon-repeat-up-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
			$('#ce-icon-repeat-remove-'+i).css({'top':t, 'left':l});
		}

		if ($(this).is(':hidden'))
		{
			$('#ce-icon-'+i).hide();
			$('#ce-icon-repeat-up-'+i).hide();
			$('#ce-icon-repeat-remove-'+i).hide();
		}
		else
		{
			$('#ce-icon-'+i).show();
			$('#ce-icon-repeat-up-'+i).show();
			$('#ce-icon-repeat-remove-'+i).show();
		}

		i++;
	});

	$('#ce-frame').contents().find('.'+site_classname+'-txt, .'+site_classname+'-text, '+'.'+site_classname+'-html, .'+site_classname+'-xml').each(function()
	{
		if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '') {
			i++;
			return true;
		}

		if ($(this).attr('new') == undefined || $(this).attr('original') == undefined)
		{
			i++;
			return true;
		}

		// check if the ID exists already
		var $elem = $('#ce-frame').contents().find('#'+$(this).attr('id'));
		if ($elem.length > 1 && $('#user_account_id').val() == '0')
		{
			i++;
			return true;
		}

		$(this).attr('cms-editable', 'true');

		frame_top = Math.round($('#ce-frame').offset().top - $(window).scrollTop());
		if ($.browser.msie && parseInt($.browser.version) < 9)
			frame_top += $(window).scrollTop();
    var t = Math.round($(this).offset().top + frame_top) - ($('#ce-icon').outerHeight() + 12);
    var l = Math.round($(this).offset().left) - 29;

		if (l <= 0)
			l = 2;

		button_positions[button_index] = {};
		button_positions[button_index]._id = '#ce-icon-'+i;
		button_positions[button_index]._elem_id = '#'+$(this).attr('id');
		button_positions[button_index]._top = t;
		button_positions[button_index]._left = l;
		button_index++;

		if ($('#ce-icon-'+i).get(0) == undefined)
		{
			var cms_editor = 'txt';
			if ($(this).get(0).tagName == 'A' || $(this).get(0).tagName == 'SPAN' || $(this).get(0).tagName == 'H1' || $(this).get(0).tagName == 'H2' || $(this).get(0).tagName == 'H3' || $(this).get(0).tagName == 'H4' || $(this).get(0).tagName == 'H5' || $(this).get(0).tagName == 'H6')
				cms_editor = 'html-txt';
			else if ($(this).get(0).tagName == 'P')
				cms_editor = 'html-no-p';
			else if ($(this).get(0).tagName == 'IMG') {
				has_images = true;
				cms_editor = 'img';
			}
			$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').css({'top':t, 'left':l}).show();

			if ($(this).hasClass(site_classname+'-repeat'))
			{
				l += $('#ce-icon-'+i).outerWidth() - 3;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-up-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').removeClass('ce-text').addClass('ce-repeat-up').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-up-'+i+' img').attr('src', '/images/icons/repeat_add.png').attr('width', '16').attr('title', $('#js-repeat-up').text());
				$('#ce-icon-repeat-up-'+i+' span').remove();

				l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
				$('#ce-icon').clone().appendTo('body').attr('id', 'ce-icon-repeat-remove-'+i).attr('cms-id', '#'+$(this).attr('id')).attr('cms-editor', cms_editor).addClass('ce-button').removeClass('rall').addClass('rtr rbr').removeClass('ce-text').addClass('ce-repeat-remove').css({'top':t, 'left':l}).show();
				$('#ce-icon-repeat-remove-'+i+' img').attr('src', '/images/icons/repeat_remove.png').attr('title', $('#js-repeat-remove').text());
				$('#ce-icon-repeat-remove-'+i+' span').remove();
			}

			if (cms_editor == 'img')
			{
				$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-image');
				$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_image.png').css({'width':'28px','height':'16px'});
			}
			if (cms_editor == 'html-txt')
			{
				$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-html');
				$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_text.png').css({'width':'23px','height':'16px'});
			}
			if (cms_editor == 'html' || cms_editor == 'html-no-p')
			{
				$('#ce-icon-'+i).removeClass('ce-text').addClass('ce-html');
				$('#ce-icon-'+i+' img').attr('src', '/images/icons/edit_html.png').css({'width':'23px','height':'16px'});
			}
		}
		else
		{
			$('#ce-icon-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-'+i).outerWidth() - 3;
			$('#ce-icon-repeat-up-'+i).css({'top':t, 'left':l});
			l += $('#ce-icon-repeat-up-'+i).outerWidth() - 2;
			$('#ce-icon-repeat-remove-'+i).css({'top':t, 'left':l});
		}

		if ($(this).is(':hidden'))
		{
			$('#ce-icon-'+i).hide();
			$('#ce-icon-repeat-up-'+i).hide();
			$('#ce-icon-repeat-remove-'+i).hide();
		}
		else
		{
			$('#ce-icon-'+i).show();
			$('#ce-icon-repeat-up-'+i).show();
			$('#ce-icon-repeat-remove-'+i).show();
		}

		i++;
	});

	if (has_images)
	{
		$('#browse-imgUploader').remove();
		$('#fileQueue').html('');
		$('#image-buttons').show();

		$('#browse-img').uploadify({
			'uploader'       : '/js/jquery/uploadify/uploadify.swf',
			'script'         : '/preview/uploadify?sid='+$('#sid').val(),
			'cancelImg'      : '/images/uploadify/cancel.png',
			'queueID'        : 'fileQueue',
			'fileExt'        : '*.jpg, *.jpeg, *.png, *.gif, *.bmp, *.tiff, *.tif',
			'wmode'          : 'transparent',
			'width'          : $('a.upload-img').outerWidth(),
			'height'         : $('a.upload-img').outerHeight(),
			'auto'           : true,
			'hideButton'     : true,
			'multi'          : false,
			'onError'    		 : function(event, queueID, fileObj, error)
				{
					loading_off();
				},
			'onComplete'     : function(event, queueID, fileObj, response)
				{
					//uploadify
					$('.uploadifyQueueItem').hide();

					loading_off();
					if (response != 'false')
					{
						$('#browse-img, #browse-imgUploader').hide();
						$('#image-buttons .upload-img').addClass('disabled');
						process_image_editor(response);
						reposition_img_buttons(-1);
					}
					$('#fileQueue').html('');
				},
			'onSelect'				: function(event, queueID, fileObj)
				{
					//uploadify
					$('.uploadifyQueueItem').show();
					$('.uploadifyQueueItem:gt(1)').hide();

					//loading_on();
					var scriptData = {
						'src':$('#ce-frame').contents().find(ce.id).attr('src'),
						'site_id':$('#trigger-site-selector').attr('rel'),
						'current_page':$('#frm_current_page').val()
					};
					$('#browse-img').uploadifySettings('scriptData', scriptData);
					reposition_img_buttons(true);
				}
		});

		$('#image-buttons').hide();
	}

	$('#ce-frame').contents().find('img[cms-editable = "true"]').each(function()
	{
		if (!this.complete || (!$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)))
			$(this).addClass('cms-img-broken');
	});
	if (button_index > 1)
	{
		for (var w = 1; w < button_index; w++)
		{
			for (var z = 0; z < button_index; z++)
			{
				if (button_positions[w]._elem_id == button_positions[z]._elem_id)
					continue;
				var diff = $(button_positions[w]._id).offset().top - $(button_positions[z]._id).offset().top;
				if (diff >= 0 && diff <= 40)
				{
					var diff_left = $(button_positions[w]._id).offset().left - $(button_positions[z]._id).offset().left;
					if (diff_left >= 0 && diff_left <= 40)
					{
						var margin_top = (40 - diff)+'px';
						var ce_icon_id = button_positions[w]._id;
						var ce_repeat_up = str_replace('ce-icon-', 'ce-icon-repeat-up-', ce_icon_id);
						var ce_repeat_down = str_replace('ce-icon-', 'ce-icon-repeat-down-', ce_icon_id);
						var ce_repeat_remove = str_replace('ce-icon-', 'ce-icon-repeat-remove-', ce_icon_id);
						$(ce_icon_id).css('margin-top',margin_top);
						$(ce_repeat_up).css('margin-top',margin_top);
						$(ce_repeat_down).css('margin-top',margin_top);
						$(ce_repeat_remove).css('margin-top',margin_top);
						break;
					}
				}
			}
		}
	}
}

function catch_white_on_white(the_data)
{
	if (the_data.indexOf('color="#ffffff"') !== -1 || the_data.indexOf('color="#fff"') !== -1 || the_data.indexOf('color: #fff') !== -1 || the_data.indexOf('color:#fff') !== -1)
	{
		$('.cke_contents iframe').bind('load',function(){
			$('.cke_contents iframe').contents().find('body').css('background','#bfbfbf');
			setTimeout("$('.cke_contents iframe').contents().find('body').css('background','#bfbfbf');", 500);
		});
	}
}

function add_edit_buttons()
{
	position_edit_buttons();
	$(window).bind('resize',function()
	{
		if (buttons_resize_timer != false) window.clearTimeout(buttons_resize_timer);
		buttons_resize_timer = window.setTimeout('position_edit_buttons();reposition_edit_content();',200);
	});
  //$(window).bind('resize',function(){position_edit_buttons();reposition_edit_content();});
  $(window).bind('scroll',function(){
  	if (ce != undefined && ce.mouseenter != undefined && ce.elem != undefined)
  		reposition_fade(ce.elem)
  	else if (ce.id)
  		$('#l').css('width','100%');
  });

	$('#content-txt').autogrow();

	$('.ce-button').bind('mouseenter',function()
	{
		if (fade_on)
			return;

		var ce_icon_id = str_replace('-repeat-up', '', '#'+$(this).attr('id'));
		ce_icon_id = str_replace('-repeat-down', '', ce_icon_id);
		ce_icon_id = str_replace('-repeat-remove', '', ce_icon_id);

		var ce_repeat_up = str_replace('ce-icon-', 'ce-icon-repeat-up-', ce_icon_id);
		var ce_repeat_down = str_replace('ce-icon-', 'ce-icon-repeat-down-', ce_icon_id);
		var ce_repeat_remove = str_replace('ce-icon-', 'ce-icon-repeat-remove-', ce_icon_id);

		$(ce_icon_id).css('z-index', '10000');
		$(ce_repeat_up).css('z-index', '10000');
		$(ce_repeat_down).css('z-index', '10000');
		$(ce_repeat_remove).css('z-index', '10000');

		ce.id = $(this).attr('cms-id');
		ce.btn = $(this);
		ce.mouseenter = true;
		ce.elem = $('#ce-frame').contents().find($(this).attr('cms-id'));

		if (ce.id == '#')
		{
			ce = {};
			fade_on = false;
			remove_editable_areas();
			return;
		}

		$('#ce-frame').contents().find($(this).attr('cms-id')).each(function()
		{
			if ($(this).hasClass('cms-not-editable') || $(this).attr('id') == '')
				return true;

    	$('#canvases').html('<div id="t"></div><div id="r"></div><div id="b"></div><div id="l"></div>');
			$('#t, #r, #b, #l').hide();
    	reposition_fade($(this));
			$('#t, #r, #b, #l').show();
		});
	});

	$('.ce-button').bind('mouseleave',function()
	{
		if (fade_on)
			return;

		var ce_icon_id = str_replace('-repeat-up', '', '#'+$(this).attr('id'));
		ce_icon_id = str_replace('-repeat-down', '', ce_icon_id);
		ce_icon_id = str_replace('-repeat-remove', '', ce_icon_id);

		var ce_repeat_up = str_replace('ce-icon-', 'ce-icon-repeat-up-', ce_icon_id);
		var ce_repeat_down = str_replace('ce-icon-', 'ce-icon-repeat-down-', ce_icon_id);
		var ce_repeat_remove = str_replace('ce-icon-', 'ce-icon-repeat-remove-', ce_icon_id);

		$(ce_icon_id).css('z-index', '100');
		$(ce_repeat_up).css('z-index', '100');
		$(ce_repeat_down).css('z-index', '100');
		$(ce_repeat_remove).css('z-index', '100');

		$('#t, #r, #b, #l').hide();
		remove_editable_areas();
		ce = {};
	});

	$('.ce-button').bind('click',function()
	{
		if (fade_on)
		{
			close_edit_window();
			$(this).trigger('mouseenter');
			return true;
		}

    //$('html, body').scrollTop(0);

		ce = {};
		ce.id = $(this).attr('cms-id');
		ce.btn = $(this);

		if (ce.id == '#')
		{
			ce.id = null;
			ce.btn = null;
			fade_on = false;
			remove_editable_areas();
			return;
		}

		var $elem = $('#ce-frame').contents().find(ce.id);

		if ($elem.attr('new') == undefined || $elem.attr('original') == undefined)
			return;

		// check if the ID exists already
		if ($elem.length > 1)
		{
			var the_error = str_replace('{url}', '<a href="http://smplc.ms/duplicateids" class="new-window">http://smplc.ms/duplicateids</a>', $('#js-duplicate-id').html())
			dialog_box(str_replace('{id}', ce.id.substr(1), the_error));
			return;
		}

		// check if the image is broken
		if ($elem.hasClass('cms-img-broken'))
		{
			dialog_box($('#js-broken-image').html());
			return;
		}

		if ($(this).hasClass('ce-repeat-up'))
		{
			turn_on_save_changes();
			repeat_tmp++;

			// clone the element
			if ($elem.parent().get(0).tagName == 'A')
			{
				var $new_elem = $elem.parent().clone();

				// reset the new element's id
				$new_elem.attr('id', 'cms-tmp-a-'+repeat_tmp+'-'+str_replace('#', '', ce.id));
				$('img', $new_elem).attr('id', 'cms-tmp-'+repeat_tmp+'-'+str_replace('#', '', ce.id)).attr('before-id', str_replace('#', '', ce.id)).addClass('cms-new-repeat-region');

				if ($('img', $new_elem).attr('new') == '')
					$('img', $new_elem).attr('new', $('img', $new_elem).attr('original'));

				var rtmp = 1;
				$('[id != ""]',$new_elem).each(function(){
					var r_id = $(this).attr('id');
					if (r_id != '' && $(this).get(0).tagName != 'IMG'){
						$(this).attr('id',r_id+'-cms-tmp-'+rtmp);
						rtmp++;
					}
				});

				// insert the new element after the current element
				$elem.parent().after($new_elem);
			}
			else
			{
				var $new_elem = $elem.clone();

				// reset the new element's id
				$new_elem.attr('id', 'cms-tmp-'+repeat_tmp+'-'+str_replace('#', '', ce.id)).attr('before-id', str_replace('#', '', ce.id)).addClass('cms-new-repeat-region');

				if ($new_elem.attr('new') == '')
					$new_elem.attr('new', $new_elem.attr('original'));

				var rtmp = 1;
				$('[id != ""]',$new_elem).each(function(){
					var r_id = $(this).attr('id');
					if (r_id != ''){
						$(this).attr('id',r_id+'-cms-tmp-'+rtmp);
						rtmp++;
					}
				});

				// insert the new element after the current element
				$elem.after($new_elem);
			}

			// need to re-add edit buttons so the new area has buttons
			remove_edit_buttons();
			add_edit_buttons();

			// turn off the faded background
			fade_on = false;
			remove_editable_areas();

			// resize the frame
			_set_frame_height();
			return;
		}

		if ($(this).hasClass('ce-repeat-remove'))
		{
			turn_on_save_changes();


			if ($elem.parent().get(0).tagName == 'A')
			{
				if (!$elem.parent().hasClass('cms-new-repeat-region'))
					repeat_removed += $elem.parent().attr('id')+',';

				// delete the area
				$elem.parent().remove();
			}
			else
			{
				if (!$elem.hasClass('cms-new-repeat-region'))
					repeat_removed += $elem.attr('id')+',';

				// delete the area
				$elem.remove();
			}

			// need to re-add edit buttons so the new area has buttons
			remove_edit_buttons();
			add_edit_buttons();

			// turn off the faded background
			fade_on = false;
			remove_editable_areas();

			// resize the frame
			_set_frame_height();
			return;
		}

		var _top = Math.round($(this).offset().top + $(this).outerHeight()) + 12;
		var _left = Math.round($(this).offset().left + $(this).outerWidth()) - 7;
		var _width = $elem.outerWidth() - 2;

		if (_width < 430)
			_width = 430;

		var available_width = ($(window).width() - _left) - 15;
		//if (_width > available_width)
			//_width = available_width;

		editor_height = $elem.outerHeight();
		if (editor_height < 150)
			editor_height = 150;
		else if (editor_height > 600)
			editor_height = 600;

		if ($(this).attr('cms-editor') == 'html')
		{
			//$('#ce-close-icon').css({'top':$(this).css('top'), 'left':$(this).css('left')}).show();
			ce.editor = 'html';

			$('#l').css('width','100%');
			$('#r').hide();

			var the_data = '';
			if ($elem.attr('new') != '')
				the_data = $.base64Decode($elem.attr('new'));
			else if ($elem.attr('original') != '')
				the_data = $.base64Decode($elem.attr('original'));

			//editor.setData('');
			//set_editor_height(the_data, _width);

			setup_wysiwyg();
			editor.setData(the_data);

			var toolbar_width = _width - 6;

			$('#editor-html').show();
			$('#cke_top_content-html .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html').outerHeight();

			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width}).show();

			//$('#editor-html, #editor-buttons').hide();
			//setTimeout("$('#editor-html, #editor-buttons').show();", 500);

			catch_white_on_white(the_data);
		}

		if ($(this).attr('cms-editor') == 'html-txt')
		{
			var the_data = '';
			if ($elem.attr('new') != '')
				the_data = $.base64Decode($elem.attr('new'));
			else if ($elem.attr('original') != '')
				the_data = $.base64Decode($elem.attr('original'));

			var new_toolbar = '[[';

			if (the_data.indexOf('<b>') !== -1 || the_data.indexOf('<b >') !== -1 || the_data.indexOf('<strong>') !== -1 || the_data.indexOf('<strong >') !== -1)
				new_toolbar += '"Bold",';
			if (the_data.indexOf('<u>') !== -1 || the_data.indexOf('<u >') !== -1)
				new_toolbar += '"Underline",';
			if (the_data.indexOf('<i>') !== -1 || the_data.indexOf('<i >') !== -1 || the_data.indexOf('<em>') !== -1 || the_data.indexOf('<em >') !== -1)
				new_toolbar += '"Italic",';
			new_toolbar += '"Cut","Copy","Paste","PasteText","PasteFromWord",';
			if (the_data.indexOf('<a ') !== -1)
				new_toolbar += '"Link","Unlink",';

			// if the content has A, B, U, I, IMG, then display those icons in the toolbar
			if (new_toolbar.substring((new_toolbar.length-1)) == ',')
				new_toolbar = new_toolbar.substring(0, (new_toolbar.length-1));

			new_toolbar += ']]';

			editor_html_txt_toolbar = eval(new_toolbar);
			//editor.setData('');
			//set_editor_height(the_data, _width);
			setup_html_txt_wysiwyg();

			//$('#ce-close-icon').css({'top':$(this).css('top'), 'left':$(this).css('left')}).show();
			ce.editor = 'html-txt';

			$('#l').css('width','100%');
			$('#r').hide();

			editor_html_txt.setData(the_data);

			var toolbar_width = _width - 6;

			$('#editor-html-txt').show();
			$('#cke_top_content-html-txt .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html-txt .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html-txt .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html-txt .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html-txt').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html-txt').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width}).show();

			//$('#editor-html-txt, #editor-buttons').hide();
			//setTimeout("$('#editor-html-txt, #editor-buttons').show();", 500);

			catch_white_on_white(the_data);
		}

		if ($(this).attr('cms-editor') == 'html-no-p')
		{
			//$('#ce-close-icon').css({'top':$(this).css('top'), 'left':$(this).css('left')}).show();
			ce.editor = 'html-no-p';

			$('#l').css('width','100%');
			$('#r').hide();

			var the_data = '';
			if ($elem.attr('new') != '')
				the_data = $.base64Decode($elem.attr('new'));
			else if ($elem.attr('original') != '')
				the_data = $.base64Decode($elem.attr('original'));

			//editor.setData('');
			//set_editor_height(the_data, _width);
			setup_wysiwyg();
			editor_no_p.setData(the_data);

			var toolbar_width = _width - 6;

			$('#editor-html-no-p').show();
			$('#cke_top_content-html-no-p .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html-no-p .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html-no-p .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html-no-p .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html-no-p').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html-no-p').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width}).show();

			//$('#editor-html-no-p, #editor-buttons').hide();
			//setTimeout("$('#editor-html-no-p, #editor-buttons').show();", 500);

			catch_white_on_white(the_data);
		}

		if ($(this).attr('cms-editor') == 'txt')
		{
			//$('#ce-close-icon').css({'top':$(this).css('top'), 'left':$(this).css('left')}).show();
			ce.editor = 'txt';

			$('#l').css('width','100%');
			$('#r').hide();

			var the_data = '';
			if ($elem.attr('new') != '')
				the_data = $.base64Decode($elem.attr('new'));
			else if ($elem.attr('original') != '')
				the_data = $.base64Decode($elem.attr('original'));

			$('#content-txt').val(the_data);

			$('#editor-txt').show();
			$('#editor-txt').css({'top':_top, 'left':_left, 'width':_width});
			$('#content-txt').css({'width':_width-18, 'height':$(this).outerHeight()});
			$('#content-txt').change();

			_top += $('#editor-txt').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width}).show();
		}

		if ($(this).attr('cms-editor') == 'img')
		{
			ce.editor = 'img';
			$(window).scrollTop(0);
			$('#browse-img, #browse-imgUploader').show();
			$('#image-buttons .upload-img').removeClass('disabled');
			aspect = ($elem.width() / $elem.height());
			ce.width = $elem.width();
			ce.height = $elem.height();

			$('#frm_img_title').val('');
			$('#editor-img .img-title').hide();

			if ($('#edit_links').val() == '1')
			{
				if ($elem.parent().get(0).tagName == 'A')
				{
					$('#frm_img_link').val($elem.parent().attr('href'));
					$('#frm_img_title').val($elem.parent().attr('title'));
					$('#editor-img .img-link').show();
				}
				else
				{
					$('#frm_img_link').val('');
					$('#editor-img .img-link').hide();
				}
			}
			else
			{
				$('#editor-img .img-link').hide();
			}

			// make sure the image link is hidden if we're editing a gallery image
			if ($('#ce-frame').contents().find(ce.id).parents().hasClass(site_classname+'-gallery'))
			{
				$('#editor-img .img-link').hide();
				$('#frm_img_title').val($elem.parent().attr('title'));
				$('#editor-img .img-title').show();
			}

			process_image_editor($elem.get(0).src);

			$(window).bind('resize',function(){reposition_img_buttons(false);});
		}


		fade_on = true;

		$('#t').css({'position':'fixed', 'top':0, 'left':0, 'width':'100%', 'height':'100%'});
		$('#r, #b, #l').remove();
		$('#header').css('z-index', '10000');

		$('a.cke_button_source').die('click');
		$('a.cke_button_source').live('click',function()
		{
			the_data = '';
			if (ce.editor != undefined)
			{
				if (ce.editor == 'html')
					the_data = editor.getData();
				else if (ce.editor == 'html-txt')
					the_data = editor_html_txt.getData();
				else if (ce.editor == 'html-no-p')
					the_data = editor_no_p.getData();
			}
			catch_white_on_white(the_data);
		});
	});

	$('#ce-frame, .ce-button').bind('mouseenter',function()
	{
		$('.ce-button').each(function()
		{
			var $elem = $('#ce-frame').contents().find($(this).attr('cms-id'));
			if ($elem.is(':hidden'))
				$(this).hide();
			else
				$(this).show();
		});
		//$('.ce-button').show();
	});
	$('#ce-frame').bind('mouseleave',function(){$('.ce-button').hide();});
}

function set_editor_height(the_data, _width)
{
	// work out the height of the editable area
	var shadow = $('<div></div>').css({position:'absolute',top:-10000,left:-10000,width:_width,resize:'none'}).appendTo(document.body);
	//var val = the_data.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;');//.replace(/\n/g, '<br />')
	var val = the_data.replace(/&/g, '&amp;');//.replace(/\n/g, '<br />')
	var h = shadow.html(val).height();
	var h = h + shadow.html('<br /><br />').height();
	if (h < editor_min_height)
		h = editor_min_height;
	else if (h > editor_max_height)
		h = editor_max_height;
	editor_height = h;
	shadow.remove();
}

function reposition_img_buttons(is_loading)
{
	var l = ($(window).width() / 2) - ($('#editor-img').outerWidth() / 2);
	$('#editor-img').css({'top':'150px', 'left':l});
	var t = $('#editor-img').offset().top+$('#editor-img').outerHeight();
	if (is_loading === true)
		t += 40;
	if (is_loading === -1)
		t -= 40;
	$('#image-buttons').css({'top':t, 'left':l});
}

function reposition_edit_content()
{
	if (ce.id)
	{
		var $elem = $('#ce-frame').contents().find(ce.id);

		var _top = Math.round(ce.btn.offset().top + ce.btn.outerHeight()) + 12;
		var _left = Math.round(ce.btn.offset().left + ce.btn.outerWidth()) - 7;
		var _width = $elem.outerWidth() - 2;

		if (_width < 430)
			_width = 430;

		$('#ce-close-icon').css({'top':ce.btn.css('top'), 'left':ce.btn.css('left')});

		if (ce.editor == 'html')
		{
			var toolbar_width = _width - 6;

			$('#cke_top_content-html .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width});
		}

		if (ce.editor == 'html-txt')
		{
			var toolbar_width = _width - 6;

			$('#cke_top_content-html-txt .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html-txt .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html-txt .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html-txt .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html-txt').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html-txt').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width});
		}

		if (ce.editor == 'html-no-p')
		{
			var toolbar_width = _width - 6;

			$('#cke_top_content-html-no-p .cke_toolbox').css('width', toolbar_width+'px');
			$('#cke_top_content-html-no-p .cke_toolgroup').css('width', (toolbar_width-9)+'px');

			var toolbar_height = $('#cke_top_content-html-no-p .cke_toolbox').outerHeight();
			_top += toolbar_height;

			$('#cke_top_content-html-no-p .cke_toolbox').css('top', '-'+(toolbar_height+1)+'px');
			$('#editor-html-no-p').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-html-no-p').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width});
		}

		if (ce.editor == 'txt')
		{
			$('#editor-txt').css({'top':_top, 'left':_left, 'width':_width});

			_top += $('#editor-txt').outerHeight();
			$('#editor-buttons').css({'top':_top, 'left':_left, 'width':_width}).show();
		}

		if (ce.editor == 'img')
		{
			$('#image-buttons').show().css({'top':_top, 'left':_left});
		}
	}
}

function reposition_fade($elem)
{
	var the_offset = Math.round($('#ce-frame').offset().top - $(window).scrollTop());
	if ($.browser.msie && parseInt($.browser.version) < 9)
		the_offset += $(window).scrollTop();
	if (the_offset < 0)
	{
		var t_top = 0;
		var t_height = Math.round($elem.offset().top - (-the_offset + $(window).scrollTop()));
	}
	else
	{
		//var t_top = the_offset;
		//var t_height = Math.round($elem.offset().top - $(window).scrollTop());
		var t_top = 0;
		var t_height = Math.round($elem.offset().top + (the_offset - $(window).scrollTop()));
	}

	var r_top = Math.round(t_top + t_height);
	var r_height = Math.round($elem.outerHeight());
	var r_left = Math.round($elem.offset().left + $elem.outerWidth());
	var r_width = Math.round($(window).width() - r_left);

	var b_top = Math.round(r_top + r_height);
	var b_height = Math.round($(window).height() - b_top);

	var l_top = r_top;
	var l_height = r_height;
	var l_width = Math.round($elem.offset().left);

  $('#t').css({'top':t_top, 'left':'0', 'width':'100%', 'height':t_height});
  $('#r').css({'top':r_top, 'left':r_left, 'width':r_width, 'height':r_height});
  $('#b').css({'top':b_top, 'left':'0', 'width':'100%', 'height':b_height});
  $('#l').css({'top':l_top, 'left':'0', 'width':l_width, 'height':l_height});

  if ($.browser.msie)
  	$('#t, #r, #b, #l').fadeTo(0, 0.6);
}

function remove_edit_buttons()
{
	$('.ce-button').unbind('mouseover').remove();
}

function close_edit_window()
{
	// reset the content array
	ce = {};
	fade_on = false;
	remove_editable_areas();
	$('.ce-button').css('z-index', '100');
	$('#header').css('z-index', '20000');
  $('#ce-close-icon').hide();
  $('#editor-html').hide();
  $('#editor-html-txt').hide();
  $('#editor-html-no-p').hide();
  $('#editor-txt').hide();
  $('#editor-img').hide();
  $('#editor-history').hide();
  $('#image-buttons').hide();
  $('#editor-buttons').hide();
}

function editor_buttons()
{
	$('#editor-buttons .save-draft').live('click', function()
	{
		$(window).scrollLeft(0);

		var data = '';

		if (ce.editor == 'html')
			data = editor.getData();
		if (ce.editor == 'html-txt')
			data = editor_html_txt.getData();
		if (ce.editor == 'html-no-p')
			data = editor_no_p.getData();
		if (ce.editor == 'txt')
			data = $('#content-txt').val();

		if (data == '')
			data = '&nbsp;';

		// check to see if any files have been uploaded and add the HTTP_HOST to the src path
		data = str_replace('="/tmp/sites/', '="http://'+window.location.hostname+'/tmp/sites/', data);
		var $elem = $('#ce-frame').contents().find(ce.id);
		$elem.attr('new', $.base64Encode(data));
		$elem.addClass('scms-content-updated');
		$elem.html(data.replace(/<script([^>]*>)(<!--)?/g, "<!--cms-script$1").replace(/(\/\/ -->)?[\s\n\r]*<\/script>/g, "</cms-script-->"));
		catch_links();
		turn_on_save_changes();

		fix_flash();

		// re-size the window height
		set_frame_height();

		// re-position edit buttons
		position_edit_buttons();

		close_edit_window();
	});

  $('.editor-buttons .cancel-changes, #ce-close-icon').live('click',function(){close_edit_window();});

	$('#trigger-save-changes span').live('click',function()
	{
		if (!$('#trigger-save-changes').hasClass('disabled'))
			process_save();
	});

	$('#trigger-cancel-changes').live('click',function()
	{
		if (!$('#trigger-cancel-changes').hasClass('disabled'))
		{
			var the_url = '/preview/edit';
			if (current_page == '/preview/define')
				the_url = '/preview/define';
			confirm_changes(null, 'ignore_callback=true;load_editor_window("'+$('#frm_a').val()+'");$.history.load("'+the_url+'");', null);
		}
	});

	/*$('#image-buttons .rotate-left').live('click',function()
	{
	});*/

	$('#image-buttons .save-img').live('click',function()
	{
		if (ce.id && jcrop_api !== false)
		{
			loading_on();
			coords = jcrop_api.tellSelect();

			var gallery_data = {};
			var $img_elem = $('#ce-frame').contents().find(ce.id);

			if ($img_elem.parents().hasClass(site_classname+'-gallery'))
			{
				if ($img_elem.parent().get(0).tagName == 'A')
				{
					gallery_data.link_href = $img_elem.parent().attr('href');
				}
			}

	    $.ajax({
	      url: '/preview/crop',
	      dataType: 'json',
    		type: 'POST',
	      data:
	      	{
	      		'id':ce.id,
	      		'site_id':$('#trigger-site-selector').attr('rel'),
	      		'width':ce.width,
	      		'height':ce.height,
	      		'img':$('.img-content img').attr('src'),
	      		'w':coords.w,
	      		'h':coords.h,
	      		'x':coords.x,
	      		'y':coords.y,
	      		'gallery_data':gallery_data,
	      		'save':'true',
	      		'dataType':'json'
	      	},
	      success: function(data)
	        {
	        	loading_off();

						if (data.login_redirect != undefined && !check_login(data.login_redirect))
							return false;

	        	if (data)
	        	{
							var $elem = $('#ce-frame').contents().find(data.id);

							if (data.src != undefined)
							{
								$elem.attr('new', $.base64Encode(data.src));
								$elem.addClass('scms-content-updated');
								$elem.attr('src', data.src);
							}

							if (data.src_large != undefined && $elem.parent().get(0).tagName == 'A')
							{
								$('#frm_img_link').val(data.src_large);
							}

							$('.img-content').html('');

							if ($elem.parent().get(0).tagName == 'A' && $('#frm_img_link').val() != '')
							{
								$elem.parent().attr('href', $('#frm_img_link').val()).addClass('scms-link-updated');
								if ($('#frm_img_title').val() != '')
									$elem.parent().attr('title', $('#frm_img_title').val());
							}

							turn_on_save_changes();
						}
	        }
	    });

			close_edit_window();
		}
	});
}

function process_save()
{
	if (current_page == '/preview/define' || current_page == '/preview/define/')
		save_define_edit_zones();
	else if (current_page == '/preview/edit' || current_page == '/preview/edit/')
		save_edit_content();
	else if (current_page.substr(0, 13) == '/preview/code')
		save_code();
	else
		turn_off_save_changes();
}

function save_define_edit_zones()
{
	loading_on();
	var removed = {};
	var content = {};
	var j = 0;
	i = 0;

	$('#ce-frame').contents().find('.cms-edit-zone-removed').each(function(){removed[j] = $(this).attr('id');j++;});

	$('#ce-frame').contents().find('.'+site_classname).each(function()
	{
		content[i] = {};
		content[i].id = $(this).attr('id');
		content[i].tag = $(this).attr('tag');
		content[i].index = $(this).attr('index');
		i++;
	});

	if ($.browser.msie && parseInt($.browser.version) < 8 && j == 1)
		removed[j] = removed[0];

	$.ajax({
		url: '/preview/save_zones',
		dataType: 'html',
    type: 'POST',
		data: {
			'removed':removed,
			'content':content,
			'current_page':$('#frm_current_page').val()
		},
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
    	loading_off();
    },
		success: function(data)
		{
			loading_off();
			if (!check_login(data))
				return false;

			if (data.substr(0, 10) == '::dialog::')
				dialog_box(data.substr(10));

			turn_off_save_changes();
			load_editor_page($('#frm_current_page').val());
		}
	});
}

function save_edit_content()
{
	loading_on();
	var content = {};
	var links = {};
	var new_areas = {};
	i = 0;
	k = 0;
	j = 0;

	$('#ce-frame').contents().find('.scms-content-updated').each(function()
	{
		content[i] = {};
		content[i].id = $(this).attr('id');
		content[i]._new = $(this).attr('new');
		i++;
	});

	$('#ce-frame').contents().find('.scms-link-updated').each(function()
	{
		links[k] = {};
		links[k].id = $(this).attr('id');
		links[k].href = $(this).attr('href');
		links[k].title = $(this).attr('title');
		k++;
	});

	$('#ce-frame').contents().find('.cms-new-repeat-region').each(function()
	{
		new_areas[j] = {};
		new_areas[j].id = $(this).attr('id');
		new_areas[j].before_id = $(this).attr('before-id');
		new_areas[j]._new = $(this).attr('new');

		$elem = $('#ce-frame').contents().find('#'+$(this).attr('id'));
		j++;
	});

	$.ajax({
    url: '/preview/save',
    dataType: 'html',
    type: 'POST',
    data: {
	  	'content':content,
	  	'links':links,
	  	'new_areas':new_areas,
	  	'repeat_removed':repeat_removed,
	  	'current_page':$('#frm_current_page').val()
  	},
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
    	loading_off();
    },
    success: function(data)
    {
			loading_off();
			if (!check_login(data))
				return false;

			turn_off_save_changes();
			load_editor_page($('#frm_current_page').val());
    }
  });
}

function save_code()
{
	loading_on();
	before_submit_PreviewCodeForm();
	$.ajax({
    url: $('#PreviewCodeForm').attr('action'),
    dataType: 'html',
    type: 'POST',
    data: {
	  	'code':$('#PreviewDefineEditZoneCode').val()
  	},
    success: function(data)
    {
    	loading_off();
			if (!check_login(data))
				return false;

			turn_off_save_changes();
			load_editor_page($('#frm_current_page').val());
    }
  });
}

function turn_off_save_changes()
{
  reset_repeat_vars();

	if (!$('#trigger-save-changes').hasClass('disabled'))
		$('#trigger-save-changes').css('border-color', '#081221').addClass('disabled');

	if (!$('#trigger-cancel-changes').hasClass('disabled'))
		$('#trigger-cancel-changes').addClass('disabled');

	for(var k in bf)clearTimeout(bf[k]);
}

function turn_on_save_changes()
{
	if ($('#trigger-save-changes').hasClass('disabled'))
		$('#trigger-save-changes').css('border-color', '#fff').removeClass('disabled');

	if ($('#trigger-cancel-changes').hasClass('disabled'))
		$('#trigger-cancel-changes').removeClass('disabled');

	for(var k in bf)clearTimeout(bf[k]);
	border_fade_0();
}
function border_fade_0(){$('#trigger-save-changes').css('border-color', '#081221');bf[0] = setTimeout("border_fade_1();", 100);}
function border_fade_1(){$('#trigger-save-changes').css('border-color', '#fff');bf[0] = setTimeout("border_fade_0();", 3000);}

function process_upgrade()
{
	$('table.tbl-upgrade .buttons a.annual').live('click',function()
	{
		// switch the buttons around
		$('#annual-buttons').hide();
		$('#monthly-buttons').show();
		$('#monthly-buttons .dollar img').hide();

		$('#monthly-rates .text').fadeOut('fast', function()
		{
			$('#monthly-rates').hide();
			$('#annual-rates .text').hide();
			$('#annual-rates').show();
			$('#annual-rates .text').fadeIn('fast', function(){setTimeout("$('#monthly-buttons .dollar img').fadeIn('slow');", 1000);});
		});
	});
	$('table.tbl-upgrade .buttons a.monthly').live('click',function()
	{
		// switch the buttons around
		$('#monthly-buttons .dollar img').fadeOut('fast',function()
		{
			$('#monthly-buttons').hide();
			$('#annual-buttons').show();
		});

		$('#annual-rates .text').fadeOut('fast', function()
		{
			$('#annual-rates').hide();
			$('#monthly-rates .text').hide();
			$('#monthly-rates').show();
			$('#monthly-rates .text').fadeIn('fast');
		});
	});
}

function reload_session(data)
{
	var url = '/sites/reload';
	if ($.browser.msie)
	{
		if (url.indexOf('?') == -1)
			url += '?t='+Math.floor(Math.random()*110);
		else
			url += '&t='+Math.floor(Math.random()*110);
	}
	$.ajax({
    url: url,
    dataType: 'json',
    data: {'dataType':'json'},
    success: function(reload_data)
    {
    	_reload_session(data, reload_data);
    }
  });
  return true;
}

function _reload_session(data, reload_data)
{
	if (reload_data.login_redirect != undefined && !check_login(reload_data.login_redirect))
		return false;

	if (data != undefined && data.ignore_reload != undefined && data.ignore_reload == 'true')
		return false;

	// reload the site selector
  $('#site-selector').remove();
	$('#top').append(reload_data.selector);

	// reload the content editor
	setup_site(reload_data);

	if (data != null && data.redirect != undefined)
	{
	  $.history.load(data.redirect);
	  return false;
	}
}

function setup_site(data)
{
	if (data.has_sites != undefined && data.has_sites == 'false')
	{
		site_classname = 'edit';
		$('#site_classname').val(site_classname);

		$('#frm_a').val('');
		$('#current_page').val('');
		$('#frm_current_site_url').val('');
		$('#trigger-site-selector span').html('');

		$('li.view-source').addClass('tab-hidden');
		$('li.add-page').addClass('tab-hidden');
		$('li.seo').addClass('tab-hidden');

		$('#sitemap-content').html('');

		if (data.ignore_redirect == undefined || data.ignore_redirect != 'false')
			$.history.load('/sites/add');
		return false;
	}

	if (data.site_classname != undefined)
	{
		site_classname = data.site_classname;
		$('#site_classname').val(data.site_classname);
	}

	if (data.current_url != undefined)
		$('#frm_current_site_url').val(data.current_url);

	if (data.site_selector_url != undefined)
		$('#trigger-site-selector span').html(data.site_selector_url);

	if (data.edit_code != undefined && data.edit_code == '1') $('li.view-source').removeClass('tab-hidden'); else $('li.view-source').addClass('tab-hidden');
	if (data.add_pages != undefined && data.add_pages == '1') $('li.add-page').removeClass('tab-hidden'); else $('li.add-page').addClass('tab-hidden');
	if (data.edit_seo != undefined && data.edit_seo == '1') $('li.seo').removeClass('tab-hidden'); else $('li.seo').addClass('tab-hidden');
	if (data.define_areas != undefined && data.define_areas == '1') $('li.define-edit-zones').removeClass('tab-hidden'); else $('li.define-edit-zones').addClass('tab-hidden');
	if (data.is_admin != undefined && data.is_admin == '1')
	{
		$('li.add-site').removeClass('tab-hidden');
		is_admin = true;
	}
	else
	{
		$('li.add-site, li.define-edit-zones').addClass('tab-hidden');
		is_admin = false;
	}
	if (data.displayed_links_dialog != undefined && data.displayed_links_dialog == '1') displayed_links_behaviour = true; else displayed_links_behaviour = false;

	if (data.entermode == undefined || data.entermode == '' || data.entermode == 'p')
		editor_entermode = CKEDITOR.ENTER_P;
	else
		editor_entermode = CKEDITOR.ENTER_BR;

	if (data.entities == undefined || data.entities == '' || data.entities == 'true')
		editor_entities = true;
	else
		editor_entities = false;

	if (data.entities == undefined || data.entities == '' || data.entities == 'true')
		editor_entities = true;
	else
		editor_entities = false;

	if (data.wysiwyg_css == undefined || data.wysiwyg_css == '')
		editor_customsss = ['/js/ckeditor/contents.css'];
	else
		editor_customsss = eval(data.wysiwyg_css);

	if (data.address != undefined)
		load_editor_page(data.address);
}

function showPreview(coords)
{
	var rx = 75 / coords.w;
	var ry = 75 / coords.h;

	var w = Math.round(rx * $('#crop-box').width());
	var h = Math.round(ry * $('#crop-box').height());

	rx = Math.round(rx * coords.x);
	ry = Math.round(ry * coords.y);

	$('#logo').css({
		width: w + 'px',
		height: h + 'px',
		marginLeft: '-' + rx + 'px',
		marginTop: '-' + ry + 'px'
	});

	$('#AccountJcropX').val(rx);
	$('#AccountJcropY').val(ry);
	$('#AccountJcropW').val(w);
	$('#AccountJcropH').val(h);
}

function confirm_changes(save_changes, discard_changes, message)
{
	// proceed with the request if we haven't got any unsaved changes
	if ($('#trigger-save-changes').hasClass('disabled'))
		return eval(discard_changes);

	$('#dialog-overlay').show();

	if (message == null)
	{
		message = {};
		message.title = $('#js-save-changes').html();
		message.text = $('#js-save-changes-message').html();
		message.btn_save = $('#js-btn-save-changes').html();
		message.btn_cancel = $('#js-btn-cancel-changes').html();
		message.btn_close = $('#js-btn-close').html();
	}

	if (current_page == '/preview/define' || current_page == '/preview/define/')
	{
		message.btn_close = $('#js-btn-close-define').html();
	}

	if (current_page == '/preview/code' || current_page == '/preview/code/')
	{
		message.text = $('#js-save-changes-message-code').html();
	}

	if (current_page == '/preview/page' || current_page == '/preview/page/')
	{
		message.text = $('#js-save-changes-message-page').html();
		save_changes = "$('.btn-page .form-submit').click();";
	}

	var btn_save = message.btn_save;
	var btn_cancel = message.btn_cancel;
	var btn_close = message.btn_close;

	//http://jqueryui.com/demos/dialog/#modal-confirmation
	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', message.title).html(message.text);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'Continue editing': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			},
			'Don\'t publish': function()
			{
				// reset the page to remove discarded changes
				$('#ce-frame').attr('src', '');

				if (current_page == '/preview/define' || current_page == '/preview/define/')
				{
					load_editor_page($('#frm_current_page').val());
				}

				$('#dialog-overlay').hide();
				turn_off_save_changes();
				$(this).dialog('close');
				eval(discard_changes);
			},
			'Publish changes': function()
			{
				$('#dialog-overlay').hide();

				// if save_changes is null, then we'll work out what to save and save it
				if (save_changes == null)
					process_save();

				$(this).dialog('close');
				eval(save_changes);

				if (current_page == '/preview/define' || current_page == '/preview/define/')
				{
					if (discard_changes == '$.history.load("/preview/edit");')
						$('#ce-frame').attr('src', '');
				}
				if (current_page == '/preview/edit' || current_page == '/preview/edit/')
				{
					if (discard_changes == '$.history.load("/preview/define");')
						$('#ce-frame').attr('src', '');
				}

				// process original request
				if (discard_changes != null)
					eval(discard_changes);
			}
		},
		open: function(event, ui)
		{
			if (current_page == '/preview/define' || current_page == '/preview/define/')
				$('.ui-dialog').addClass('define-dialog');
			else
				$('.ui-dialog').removeClass('define-dialog');

			$('span.ui-button-text:eq(0)').html(btn_close);
			$('span.ui-button-text:eq(0)').parent().addClass('btn-close');

			$('span.ui-button-text:eq(1)').html(btn_cancel);
			$('span.ui-button-text:eq(1)').parent().addClass('btn-discard');

			$('span.ui-button-text:eq(2)').html(btn_save);
			$('span.ui-button-text:eq(2)').parent().addClass('btn-save');

			if ($.browser.msie && parseInt($.browser.version) < 8)
			{
				var w = 0;

				w = $('span.ui-button-text:eq(0)').parent().width();
				if (current_page == '/preview/define' || current_page == '/preview/define/')
					$('span.ui-button-text:eq(0)').parent().css('width',(w-70));
				else
					$('span.ui-button-text:eq(0)').parent().css('width',(w-35));

				w = $('span.ui-button-text:eq(1)').parent().width();
				$('span.ui-button-text:eq(1)').parent().css('width',(w-20));
			}
		}
	});
}

function dialog_box_upgrade(message)
{
	$('#dialog-overlay').show();
	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-please-upgrade-first').html()).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'No, thank you': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				if (current_page.substr(0, 14) == '/users/toolbar' || current_page.substr(0, 10) == '/users/add' || current_page.substr(0, 13) == '/users/update')
				{
					$('#UsersSEO').attr('checked', false);
					$('#UsersSEO').trigger('change');
					$('#UsersAddPage').attr('checked', false);
					$('#UsersAddPage').trigger('change');
				}
				else if (current_page == '' || current_page.substr(0, 22) == '/account/upgrade/brand')
					window.location = '/';
				else
					$.history.load('/preview/edit');
			},
			'Upgrade account': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				if (current_page.substr(0, 14) == '/users/toolbar' || current_page.substr(0, 10) == '/users/add' || current_page.substr(0, 13) == '/users/update')
					$.history.load('/account/upgrade');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-no-thank-you').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard').addClass('btn-discard-upgrading');

			$('span.ui-button-text:eq(1)').html($('#js-btn-upgrade-account').html());
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_code(message)
{
	if (disable_dialog_users_code)
	{
		disable_dialog_users_code = false;
		return;
	}

	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-important').html()).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'I\'ve changed my mind': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				$('#UsersCode').attr('checked', false);
				$('#UsersCode').trigger('change');
			},
			'I understand': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-change-mind').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

			$('span.ui-button-text:eq(1)').html($('#js-btn-i-understand').html());
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_define_areas(message)
{
	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-important').html()).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'Click-to-define': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				$('#UsersDefine').attr('checked', false);
				$('#UsersDefine').trigger('change');
			},
			'Define manually': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				disable_dialog_users_code = true;
				$('#UsersCode').attr('checked', true);
				$('#UsersCode').trigger('change');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-click-to-define').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

			$('span.ui-button-text:eq(1)').html($('#js-btn-define-manually').html());
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_define_help(message)
{
	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-title-more-control').html()).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'Stay with \'click-to-define\'': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			},
			'Enable Code editing': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');

				if ($('li.view-source').hasClass('tab-hidden'))
				{
					$('li.view-source').removeClass('tab-hidden');
					nav_define_edit_zones();
				}

				var the_url = '/preview/code/'+$.base64Encode($('#frm_a').val())+'/true';
				confirm_changes(null, '$.history.load("'+the_url.replace(/^.*#/, '')+'");', null);
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-happy-with-define').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

			$('span.ui-button-text:eq(1)').html($('#js-btn-enable-code').html());
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_new_window(message, the_url)
{
	$('#dialog-overlay').show();

	var display_url = the_url;
	if (display_url.length > 50)
		display_url = display_url.substr(0, 50)+'...';

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-title-new-window').html()).html(str_replace('{url}', display_url, message));
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'Open in a new window': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
				window.open(the_url);
			},
			'Back to editing': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-open-new-window').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

			if (current_page.substr(0, 15) == '/preview/define')
				$('span.ui-button-text:eq(1)').html($('#js-btn-continue-defining').html());
			else
				$('span.ui-button-text:eq(1)').html($('#js-btn-continue-editing').html());
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_links_behaviour()
{
	$.ajax({url:'/sites/displayed_links_dialog'});

	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-title-link-behaviour').html()).html($('#js-link-behaviour').html());
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'OK': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-ok').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box_hang(where)
{
	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', $('#js-title-hang').html()).html($('#js-hang').html());
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		buttons: {
			'Refresh': function()
			{
				var the_url = '/account/hangman/'+where+'/?u='+encodeURIComponent(window.location)+'&p='+encodeURIComponent(previous_page)+'&c='+encodeURIComponent(current_page);
				if (current_page.substr(0, 10) == '/sites/add')
					the_url += '&data=url:'+$('#SitesUrl').val()+'_|_host:'+$('#SitesHost').val()+'_|_username:'+$('#SitesUsername').val()+'_|_password:'+$('#SitesPassword').val()+'_|_pasv:'+$('#SitesPasv').val()+'_|_type:'+$('#SitesType').val()+'_|_class:'+$('#SitesClassname').val();
				window.location = the_url;
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-refresh').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-ok');
		}
	});
}

function dialog_box(message)
{
	$('#dialog-overlay').show();

	var the_title = $('#js-important').html();

	if (message.substr(0,20) == '<!--upgrade-brand-->')
	{
		dialog_box_upgrade(message);
		return;
	}

	if (message.substr(0,23) == '<!--correct-location-->')
		the_title = $('#js-title-correct-location').html();

	if (message.substr(0,18) == '<!--please-note-->')
		the_title = $('#js-title-please-note').html();

	if (message.substr(0,12) == '<!--error-->')
		the_title = $('#js-title-error').html();

	if (message.substr(0,15) == '<!--declined-->')
		the_title = 'Declined';

	if (message.substr(0,20) == '<!--blocked-trial-->')
		the_title = 'Upgrade to continue';

	if (current_page == '/account/brand' || current_page == '/account/brand/')
		the_title = $('#js-name-is-taken').html();

	if ($('#flashMessage').hasClass('upgrade-successful'))
	{
		$('#flashMessage').removeClass('upgrade-successful');
		the_title = $('#js-title-upgrade-successful').html();
	}
	if ($('#flashMessage').hasClass('upgrade-failed'))
	{
		$('#flashMessage').removeClass('upgrade-failed');
		the_title = $('#js-title-upgrade-failed').html();
	}

	if ($('#flashMessage').hasClass('just-so-you-know'))
	{
		$('#flashMessage').removeClass('just-so-you-know');
		the_title = $('#js-title-just-so-you-know').html();
	}

	var box_top = 200;

	if ($('#flashMessage').hasClass('exported-user'))
	{
		box_top = 100;
		the_title = 'It\'s all changed around here';
	}

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', the_title).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',box_top],
		zIndex: 20000,
		buttons: {
			'OK': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html($('#js-btn-ok').html());
			$('span.ui-button-text:eq(0)').parent().addClass('btn-ok');
			if ($('#flashMessage').hasClass('exported-user'))
			{
				$('span.ui-button-text:eq(0)').html('Let me in!');
			}
		}
	});
}

function send_hang_report(where)
{
	$.ajax({
		url:'/account/hang_report/',
		data:
		{
			'where':where,
			'current_page':current_page,
			'previous_page':previous_page
		},
		timeout:500
	});
}

function remove_box(the_title, message, btn_remove, btn_cancel, $this)
{
	$('#dialog-overlay').show();

	$('#dialog-confirm').dialog('destroy');
	$('#dialog-confirm').attr('title', the_title).html(message);
	$('#dialog-confirm').dialog(
	{
		resizable: false,
		height: 'auto',
		modal: true,
		draggable: false,
		position: ['center',200],
		zIndex: 20000,
		stack: false,
		buttons: {
			'Do not remove': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');
			},
			'Remove': function()
			{
				$('#dialog-overlay').hide();
				$(this).dialog('close');

		    loading_on();
      	do_reload = true;

				var the_href = $this.attr('href');

        if (the_href == '/account/brand_reset' || the_href == '/account/brand_reset/')
        {
      		do_reload = false;
        	on_branding = true;
        	hue = 59;
        	logo = '';
        }

        if (the_href.substr(0, 13) == '/users/remove')
      		do_reload = false;
        if (the_href.substr(0, 14) == '/sites/remove/')
      		do_reload = false;

        if (the_href.substr(0, 21) == '/users/close_account/')
					$.ajax({url:'/sites/cleanup/all',dataType:'html',timeout:500});

		    $.history.load(the_href);
			}
		},
		open: function(event, ui)
		{
			$('span.ui-button-text:eq(0)').html(btn_cancel);
			$('span.ui-button-text:eq(0)').parent().addClass('btn-discard');

			$('span.ui-button-text:eq(1)').html(btn_remove);
			$('span.ui-button-text:eq(1)').parent().addClass('btn-ok');
		}
	});
}

function work_out_logo()
{
	if ($('#user_account_id').val() == '1') // free
		$('#logo').attr('src', '/images/logo_simplecms.png');
	else if ($('#user_account_id').val() == '2') // pro
		$('#logo').attr('src', '/images/logo_editsite_pro.png');
	else if ($('#user_account_id').val() == '3') // pro annual
		$('#logo').attr('src', '/images/logo_editsite_pro.png');
	else if ($('#user_account_id').val() == '4') // pro comp
		$('#logo').attr('src', '/images/logo_editsite_pro.png');
	else if ($('#user_account_id').val() == '5') // bus
		$('#logo').attr('src', '/images/logo_editsite_bus.png');
	else if ($('#user_account_id').val() == '6') // bus annual
		$('#logo').attr('src', '/images/logo_editsite_bus.png');
	else
		$('#logo').attr('src', '/images/logo_editsite.png');
}

function str_replace(search, replace, subject)
{
	// http://kevin.vanzonneveld.net
	var f = search, r = replace, s = subject;
	var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
	while (j = 0, i--) { if (s[i]) { while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){} } }
	return sa ? s : s[0];
}
function parse_url(str, component)
{
	// http://kevin.vanzonneveld.net
	// +      original by: Steven Levithan (http://blog.stevenlevithan.com)
	// + reimplemented by: Brett Zamir (http://brett-zamir.me)
	// %          note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
	// %          note: blog post at http://blog.stevenlevithan.com/archives/parseuri
	// %          note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
	// %          note: Does not replace invaild characters with '_' as in PHP, nor does it return false with
	// %          note: a seriously malformed URL.
	// %          note: Besides function name, is the same as parseUri besides the commented out portion
	// %          note: and the additional section following, as well as our allowing an extra slash after
	// %          note: the scheme/protocol (to allow file:/// as in PHP)
	// *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
	// *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
	var  o   = {
		strictMode: false,
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:   {
			name:   "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-protocol to catch file:/// (should restrict this)
		}
	};
	var m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	k = 14;
	while (k--) {uri[o.key[k]] = m[k] || "";}
	// Uncomment the following to use the original more detailed (non-PHP) script
	/*
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
	if ($1) {uri[o.q.name][$1] = $2;}
	});
	return uri;
	*/

	switch (component) {
		case 'PHP_URL_SCHEME': return uri.protocol;
		case 'PHP_URL_HOST': return uri.host;
		case 'PHP_URL_PORT': return uri.port;
		case 'PHP_URL_USER': return uri.user;
		case 'PHP_URL_PASS': return uri.password;
		case 'PHP_URL_PATH': return uri.path;
		case 'PHP_URL_QUERY': return uri.query;
		case 'PHP_URL_FRAGMENT': return uri.anchor;
		default:
		var retArr = {};
		if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
		if (uri.host !== '') {retArr.host=uri.host;}
		if (uri.port !== '') {retArr.port=uri.port;}
		if (uri.user !== '') {retArr.user=uri.user;}
		if (uri.password !== '') {retArr.pass=uri.password;}
		if (uri.path !== '') {retArr.path=uri.path;}
		if (uri.query !== '') {retArr.query=uri.query;}
		if (uri.anchor !== '') {retArr.fragment=uri.anchor;}
		return retArr;
	}
}
function basename(path){return path.replace(/\\/g,'/').replace( /.*\//, '' );}
function dirname(path){return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');}
(function($){
$.fn.autogrow = function(options){
	this.filter('textarea').each(function(){
		var $this = $(this), lineHeight = $this.css('lineHeight'), minHeight = 25;
		var shadow = $('<div></div>').css({position:'absolute',top:-10000,left:-10000,width:$(this).width(),fontSize:$this.css('fontSize'),fontFamily:$this.css('fontFamily'),lineHeight:$this.css('lineHeight'),resize:'none'}).appendTo(document.body);
		var update = function()
		{
			var val = this.value.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;');//.replace(/\n/g, '<br />')
			var h = shadow.html(val).height();
			var h = h - shadow.html('<br />').height();
			$(this).css('height', Math.max(h, minHeight));
			var _top = $(this).offset().top + $(this).outerHeight() + 57;
			$('#editor-buttons').css('top', _top);
		}
		$(this).change(update).keyup(update).keydown(update);
		update.apply(this);
	});
	return this;
}
})(jQuery);

