// Define variable used to hold the sectionId of the section that is being edited.
var editableSectionId;

var fckSafariHeight = 150;
var fckEditorLabel = "FCKEditor";
var fckContent ='';
var id_address2=0;
var tpfck=new Object();
var tpfck2 =new Object();
var tpfckHeadline = new Object();
var margins; 
var columnarFormat=false;
var is_adding=false;
var has_headline=0;
var menu = [];
var hoverColor="#ffd88e";
var fckWidth=0;
var fckLeftPos=0;
var fckLeftPadding=0;
var contextMenu;
//We define here the labels for the fields until we decide how to procee with the language

var editables = {}; //stores the editable labels
var notEditables = {};//stores the non-editable labels

var label_examples_button = "Examples";
var label_actionwords_button= "Action Verbs";
var label_click_here_to_add_text_old = "<i>Click here to add text</i>";
var label_click_here_to_add_text = "";

var label_organization_name = "Organization name";
var label_organization_dateRange="Date range";
var hint_organization_name = "";
var hint_organization_dateRange="";

//LABELS
var label_hybrid_name="Hybrid section name";
var label_experience_name="Section name";
//HINTS
var hint_hybrid_name="";
var hint_experience_name="";

//LABELS
var label_employer_name="Employer name";
var label_employer_location="Employer Location";
var label_employer_dateRange ="Date range";
var label_employer_linkURL="Employer URL";
var label_employer_title="Job Title";
var label_employer_description="Company Description";
var label_employer_description_off="Remove the company description (optional)";
//HINTS
var hint_employer_name="";
var hint_employer_location="";
var hint_employer_dateRange ="";
var hint_employer_linkURL="";
var hint_employer_title="";
var hint_employer_description="";
var hint_employer_description_off="";

//LABELS
var label_job_title="Job Title";
var label_job_jobLocation="Job location";
var label_job_jobDateRange="Date range";
//HINTS
var hint_job_title="Job Title";
var hint_job_jobLocation="Job location";
var hint_job_jobDateRange="Date range";

//LABELS
var label_section_name="Section Name";
var label_add_section="Add Section";
//HINTS
var hint_section_name="We recommand that you select a section name among the names presented by intellisense.";
var hint_add_section="";

var blankaddress2='[Address2 Here]';
var blankaddress1='[Address1 Here]';
var blankphone1='[Phone1 Here]';
var blankphone2='[Phone2 Here]';
var blankphone3='[Phone3 Here]';
var blankemail='[Email Here]';
var blankheadline='[Headline Here]';


var label_recip_prefix="Recipient title";
var label_recip_first_name="Recipient first name";
var label_recip_last_name="Recipient last name";
var label_recip_job_title="Recipient position";
var label_recip_organization_name="Recipient organization"
var label_recip_address_line_1="Address line 1";
var label_recip_address_line_2="Address line 2";
var label_recip_city="Recipient city";
var label_recip_state="Recipient state";
var label_recip_postal_code="Recipient postal code";
var label_recip_country="Recipient country";
var label_recip_opening="Greeting";
//HINT
var hint_recip_prefix="";
var hint_recip_first_name="";
var hint_recip_last_name="";
var hint_recip_job_title="";
var hint_recip_organization_name="";
var hint_recip_address_line_1="";
var hint_recip_address_line_2="";
var hint_recip_city="";
var hint_recip_state="";
var hint_recip_postal_code="";
var hint_recip_country="";
var hint_recip_opening="";

var label_closing_close_value="Closing";
var label_closing_close_signature="Signature";
var label_closing_close_enclosure="Enclosure(s)";
var hint_closing_close_value="";
var hint_closing_close_signature="Be sure to type your full name in the text box below.";
var hint_closing_close_enclosure='If you plan on sending this letter in an envelope AND you plan include another document with it, select the adjacent checkbox to include the word "ENCLOSURE" at the bottom of your letter.';

var fckSectionId;
var fckSectionType;
var fckSectionName;
var hoverId;

var experience_is_showing=false;
//variable used to preserve sytle hightlight between resume page refresh
var lastStyleHighlight;
var dataLoadedJSON;

$(document).ready(function(){
	//initForms();
	
});

function showViewOptions(callee)
{
	if ( $("#viewMenu").length == 0 )
	{
		var pos = $(callee).position();
		var cHeight = $(callee).height();
		$("body").append('<div id="viewMenu" style="display:none;" class="viewMenu"><div id="previewMode"><span></span><font>Print Preview</font></div><div id="editMode"><span></span><font>Normal View</font></div></div>');
		var viewMenu = $("#viewMenu");
		viewMenu.css("position","absolute");
		viewMenu.css("top",(pos.top + cHeight));
		viewMenu.css("left",pos.left);
		
		$('#previewMode').click(function(){ previewMode(); $("#viewMenu").toggle(); });
		$('#editMode').click(function(){ editMode(); postEditMode(); $("#viewMenu").toggle(); });
	}
	$("#viewMenu").toggle();
	
}

(function($){

$.fn.extend({

	/**
	 * Stores the original version of offset(), so that we don't lose it
	 */
	_offset : $.fn.offset,

	/**
	 * Set or get the specific left and top position of the matched
	 * elements, relative the the browser window by calling setXY
	 * @param {Object} newOffset
	 */
	offset : function(newOffset){
	    return !newOffset ? this._offset() : this.each(function(){
			var el = this;

			var hide = false;

			if($(el).css('display')=='none'){
				hide = true;
				$(el).show();
			};

			var style_pos = $(el).css('position');

			// default to relative
			if (style_pos == 'static') {
				$(el).css('position','relative');
				style_pos = 'relative';
			};

			var offset = $(el).offset();

			if (offset){
				var delta = {
					left : parseInt($(el).css('left'), 10),
					top: parseInt($(el).css('top'), 10)
				};

				// in case of 'auto'
				if (isNaN(delta.left))
					delta.left = (style_pos == 'relative') ? 0 : el.offsetLeft;
				if (isNaN(delta.top))
					delta.top = (style_pos == 'relative') ? 0 : el.offsetTop;

				if (newOffset.left || newOffset.left===0)
					$(el).css('left',newOffset.left - offset.left + delta.left + 'px');

				if (newOffset.top || newOffset.top===0)
					$(el).css('top',newOffset.top - offset.top + delta.top + 'px');
			};
			if(hide) $(el).hide();
		});
	}

});

})(jQuery);


function insertSectionSet()
{
	var selectedSet = $('.sectionSetSelectedMarker', '.sectionSetContainer').not(":hidden").parent().attr("ssid");
	$.ajax({
			async: false,
			url: '/modules/ordocument/index.php',
			data: {
				action: 'applySectionSet',
				docid: $('#documentId').attr('value'),
				module: $('#documentType').attr('value')+'s',
				ssid: selectedSet
			},
			success: function(data,textMessage){
			   	$('#moduleCanvas').replaceWith(data);
			   	$('#docConfigInit').dialog('close');
			   },
		   complete: function (XMLHttpRequest, textStatus) {
			   initDoc();
		   }
			});
}

function applyHeaderFormat()
{
	var jsonHeaderFormat = {
		headerFormat: $(":input[name='headerFormat'] option:selected").attr("value"),
		templateLayouts: []
	};
	
	var submit = false;
	$.each($("div[layout]"), function(i,val){
		$(":input[name='container"+ $(this).attr("layout") + "Orientation'] option").attr("selected","");
		$(":input[name='container"+ $(this).attr("layout") + "Orientation'] option[value='"+$("img[alignment].selected",$(this)).attr("alignment")+"']").attr("selected","selected")
		var tLayout = {
			layout: $(this).attr("layout"),
			alignment: $("img[alignment].selected",$(this)).attr("alignment"),
			positions: []
		};
		var rCount = 1;
		$.each($("div[row]", $(this)), function(rNum,sortable){
			items = $(sortable).sortable('toArray');
			if ( items.length > 0 ){
				submit = true;
			}
			row = $(this).attr("row");
			
			
			for(i=0;i<items.length;i++)
			{
				var pObj = {};
				pObj.positionY = rCount;
				pObj.elementName = items[i]
				pObj.positionX = ""+(i+1);
				tLayout.positions.push(pObj);
				
			}
			if ( items.length > 0 ) 
			{
				rCount++;
			}
		});
		jsonHeaderFormat.templateLayouts.push(tLayout);
		});
		
		
		if (submit) {
			$.ajax({
				type: 'POST',
				url: '/modules/ordocument/stylist.php',
				beforeSend: function() {
					$("#headerIndicator").show();
				},
				data: {
					action: 'applyHeaderFormat',
					layout: JSON.stringify(jsonHeaderFormat),
					module: $('#documentType').attr('value') + 's',
					docid: $('#documentId').attr('value')
				},
				success:function(data){
					getStylistBufferData();
					$('#moduleCanvas').replaceWith(data);
					$("#headerIndicator").hide();
					if ( SpellChecker.active == true )
					{
						SpellChecker.checkAsync();
					}
					initDocAjax();
					
				}
			});

		}
	
}

function removeMenu(){
	//unbindSectionEvent();
	$("#handle").css("display","none");
	lastMoveMenuSender = null;
}

function applyPreStyle(prestyleId)
{

	if ( prestyleId == undefined )
	{
		prestyleId = $(":input[name='preStyle']:checked").attr("value");
	}
	else
	{
		$.each($(":input[name='preStyle']"), function(idx, val){
			$(val).attr("checked","");
			if ( $(val).attr("value") == prestyleId )
			{
				$(val).attr("checked","checked");
			}
		});
	}
	$.ajax({
		beforeSend: function(xreq){
			$("#prestyleAjaxIndicator").show();
		},
		type: 'GET',
		async:true,
		url:'/modules/ordocument/stylist.php',
		data: {
			action:'applyStyle',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			styleDef: 'preStyle',
			styleValue: prestyleId
		},
		success: function(successData){
			getStylistBufferData();
			getStylistValues();
			$('#moduleCanvas').replaceWith(successData);
//			initDocAjax();
			
			initForms();
			init();
			showMarginMarkers();
			
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
			$("#prestyleAjaxIndicator").hide();
		}
	});
}

function applyStyle(element)
{
	$(".stylistAjaxIndicator", $(element).parent()).show();
	if ($(element).attr('name') != 'preStyle' && $(":input[name='preStyle']:checked").attr("value") != -1)
	{
		$(":input[name='preStyle']:first").attr("checked","checked");
		$.ajax({
			type:'GET',
			async:true,
			url:'/modules/ordocument/stylist.php',
			data: {
			action:'applyStyle',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			styleDef: 'preStyle',
			styleValue: '-1'
		},
		success: function(successData){
		}
		});
		
	}
	// This is needed for the options that are checkboxes
	var styleCol = $(element).attr('name');
	var styleValue = $(element).attr('value');
	if ( (styleCol == 'headerName' || 
			styleCol == 'headerEmail'  || 
			styleCol == 'headerPhone') && $(element).attr("checked") == '' )
	{
		styleValue = 0;
	}
	$.ajax({
		type: 'GET',
		async:true,
		url:'/modules/ordocument/stylist.php',
		data: {
			action:'applyStyle',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			styleDef: styleCol,
			styleValue: styleValue
		},
		beforeSend: function(XMLHttpRequest){
			$(".stylistAjaxIndicator", $(element).parent()).show();
		},
		complete: function (XMLHttpRequest, textStatus) {
			$(".stylistAjaxIndicator", $(element).parent()).hide();
		},
		success: function(successData){
			getStylistBufferData();
			if ( $(element).attr("name") == 'styleBody' && $(element).attr('value') == 'Standard')
			{
				$(":input[name='firstcellpercentasdecimal']").parent().parent().hide();
			}
			else if ( $(element).attr("name") == 'styleBody' && $(element).attr('value') != 'Standard'){
				$(":input[name='firstcellpercentasdecimal']").parent().parent().show();
			}
			$('#moduleCanvas').replaceWith(successData);
//			initDocAjax();

			initForms();
			init();
			showMarginMarkers();
			
			// FB 854
			// Need to re-initialize fck editors on style change so that the editors get properly sized.
			if ( $(element).attr("name") == 'styleBody' || $(element).attr("name") == 'firstcellpercentasdecimal' ||
					$(element).attr("name") == 'sectionIndentationLevel')
			{
				initFck();
				initFckEmployerDescription();
			}
			
			// FB 109
			if ( styleCol == 'styleBody' && styleValue == '2 Columns')
			{
				var src = $("img.experienceOptionImg[src*='or20_Experience7']").attr("src");
				$("img.experienceOptionImg[src*='or20_Experience7']").attr("src",src.replace("or20_Experience7","or20_Experience7_2column"));
			}
			else if ( styleCol == 'styleBody' && styleValue == 'Standard')
			{
				var src = $("img.experienceOptionImg[src*='or20_Experience7']").attr("src");
				$("img.experienceOptionImg[src*='or20_Experience7']").attr("src",src.replace("or20_Experience7_2column","or20_Experience7"));
			}
			if ( $(element).attr('name') == 'styleExperienceSection')
			{
				$.each($("img.experienceOptionImg").not(":hidden"), function(idx,val){
					var src = $(this).attr("src");
					if (src != undefined) {
						$(this).attr("src", src.replace("_selected", ""));
					}
				});
			}
			else
			{
				var parent = $(element).parent();
				$.each($(parent).children(), function(idx,val){
					var src = $(this).attr("src");
					if (src != undefined) {
						$(this).attr("src", src.replace("_selected", ""));
					}
				});
			}
			if ($(element).attr("src") != undefined) {
				$(element).attr("src", $(element).attr("src").replace(".gif", "_selected.gif"));
			}
			$('#ajaxProgressContainer').remove();
			
			if ( lastStyleHighlight != undefined && lastStyleHighlight != '' )
			{
				showHighlight(lastStyleHighlight,false);
			}
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
		}
	});
	if ( $(element).attr('name') == 'headerFormat')
	{
		loadHeaderFormatTemplate(element);
	}

}

function handleFontCaseChange(element)
{
	var name = $(element).attr("name");
	var value = $(element).attr("value");
	var imgSrc = $(element).attr("src");
	
	if ( imgSrc.indexOf("_selected") > -1 )
	{
		// This value needs to be toggled.
		$(element).attr("src",imgSrc.replace("_selected",""));
		value = "Plain Text";
	}
	else
	{
		$(element).siblings("img[name='"+name+"']").attr("src",$(element).siblings("img[name='"+name+"']").attr("src").replace("_selected",""));
		$(element).attr("src",imgSrc.replace(".gif","_selected.gif"));
	}
	
	$.ajax({
		type: 'GET',
		async:true,
		url:'/modules/ordocument/stylist.php',
		data: {
			action:'applyStyle',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			styleDef: name,
			styleValue: value
		},
		beforeSend: function(XMLHttpRequest){
			$(".stylistAjaxIndicator", $(element).parent()).show();
		},
		complete: function (XMLHttpRequest, textStatus) {
			$(".stylistAjaxIndicator", $(element).parent()).hide();
		},
		success: function(successData){
			$('#moduleCanvas').replaceWith(successData);
			getStylistBufferData();
			initDocAjax();
			unbindSectionEvent();
		
			if ( lastStyleHighlight != undefined && lastStyleHighlight != '' )
			{
				showHighlight(lastStyleHighlight,false);
			}
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
			
		}
	});
}

function handleFontStyleChange(element)
{
	var name = $(element).attr("name");
	var value = $(element).attr("value");
	var imgSrc = $(element).attr("src");
	var boldSelected = false;
	var italicsSelected = false;
	var underlineSelected = false;
	
	if ( imgSrc.indexOf("_selected") > -1 )
	{
		$(element).attr("src",imgSrc.replace("_selected",""));
	}
	else 
	{
		$(element).attr("src",imgSrc.replace(".gif","_selected.gif"));
		if ( value == 'Bold' )
		{
			boldSelected = true;
		}
		else if ( value == 'Italics' )
		{
			italicsSelected = true;
		}
		else if ( value == 'Underline')
		{
			underlineSelected = true;
		}
	}
	
	
	
	$.each($(element).siblings("img[name='"+name+"']"),function(idx,val){
		if ( $(this).attr("src").indexOf("_selected") > -1 && $(this).attr("value") == 'Bold')
		{
			boldSelected = true;
		}
		else if ( $(this).attr("src").indexOf("_selected") > -1 && $(this).attr("value") == 'Italics' )
		{
			italicsSelected = true;
		}
		else if ( $(this).attr("src").indexOf("_selected") > -1 && $(this).attr("value") == 'Underline')
		{
			underlineSelected = true;
		}
	});
	
	if ( boldSelected && !italicsSelected && !underlineSelected)
	{
		value = 'Bold';
	}
	else if ( !boldSelected && italicsSelected && !underlineSelected )
	{
		value = 'Italics';
	}
	else if ( !boldSelected && !italicsSelected && underlineSelected )
	{
		value = 'Underline';
	}
	else if ( boldSelected && italicsSelected && !underlineSelected )
	{
		value = 'Bold Italics';
	}
	else if ( boldSelected && !italicsSelected && underlineSelected )
	{
		value = 'Bold Underline';
	}
	else if ( !boldSelected && italicsSelected && underlineSelected )
	{
		value = 'Italics Underline';
	}
	else if ( boldSelected && italicsSelected && underlineSelected )
	{
		value = 'Bold Italics Underline';
	}
	else if ( !boldSelected && !italicsSelected && !underlineSelected)
	{
		value = 'Plain Text';
	}
	
	$.ajax({
		type: 'GET',
		async:true,
		url:'/modules/ordocument/stylist.php',
		data: {
			action:'applyStyle',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			styleDef: name,
			styleValue: value
		},
		beforeSend: function(XMLHttpRequest){
			$(".stylistAjaxIndicator", $(element).parent()).show();
		},
		complete: function (XMLHttpRequest, textStatus) {
			$(".stylistAjaxIndicator", $(element).parent()).hide();
		},
		success: function(successData){
			$('#moduleCanvas').replaceWith(successData);
			initDocAjax();
			getStylistBufferData();
			unbindSectionEvent();
		
			if ( lastStyleHighlight != undefined && lastStyleHighlight != '' )
			{
				showHighlight(lastStyleHighlight,false);
			}
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
		}
	});
}

function getHeaderElementPositions()
{
	$.ajax({
		type:'GET',
		url: '/modules/ordocument/stylist.php',
		data: {
			action: 'getHeaderElementPositions',
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value')
		},
		dataType: 'json',
		success: function(data,textMessage){
			for(i=0;i<data.templateLayouts.length;i++)
			{
				var layout = data.templateLayouts[i].layout;
				var tLayout = data.templateLayouts[i];
				var t = $("div[layout='"+layout+"']");
				for (x=0; x<tLayout.positions.length;x++)
				{
					var elementPos = tLayout.positions[x];
					var row = $("div[layout='"+layout+"'] > div[row='"+elementPos.positionY+"']");
					var li = $("span#"+elementPos.elementName);
					var lis = $("div[layout='"+layout+"'] > div[row='"+elementPos.positionY+"'] > span"); 
					li.appendTo(row);
				}
			}
			
			$.each($("div[layout]"), function(i,val){
				$.each($("div[row]", $(this)), function(rNum,sortable){
					var items = $(sortable).sortable('toArray');
					for ( var i = 0; i < items.length; i++ )
					{
						var eName = items[i];
						if ( (eName == 'address1' || eName == 'address2') &&
								items.length > 1 )
						{
							$(":input[name='addressOrientation'] option[value='vertical']").attr("selected","");
							$(":input[name='addressOrientation'] option[value='horizontal']").attr("selected","selected");
							
							$(":input[name='addressOrientation']").attr("disabled","disabled");
							$(":input[name='addressOrientation']").parent().append('<span id="aOrientationMessage" style="display:inline;font-size:75%;color:red;">Address Layout must be set to Horizontal since an address is on a line with another header element.</span>');
						}
					}
				});
			});
		}
	});
}

function setHeaderAlignment(alignment,container)
{
	$.each($("div[layout='"+container+"'] img[alignment]"), function(idx,val){
				var src = $(this).attr("src");
				$(this).attr("src",src.replace("_selected",""));
				$(this).removeClass("selected");
			});
	$("div[layout='"+container+"'] img[alignment='"+alignment+"']").attr("src",$("div[layout='"+container+"'] img[alignment='"+alignment+"']").attr("src").replace(".png", "_selected.png"));
	$("div[layout='"+container+"'] img[alignment='"+alignment+"']").addClass("selected");
	if ( alignment == "left" )
	{
		$("div[layout='"+container+"'] > div[row]").css("text-align","left");
	}
	else if ( alignment == "right") 
	{
		$("div[layout='"+container+"'] > div[row]").css("text-align","right");
	}
	else{
		$("div[layout='"+container+"'] > div[row]").css("text-align","center");
	}
}

function containerAlignmentControls(container)
{
	var selected = container.attr("alignment");
	
	var s = '<span id="alignmentControl'+ container.attr("layout") +'" style="float:right;text-align:center;margin-bottom:5px;width:100%;">';
	s += '<img src="/images/or20/stylist/or20_AlignLeft_small.png" class="buttonNotSelected" alignment="left" alt="Left" title="Left" ';
	s += 'onclick="setHeaderAlignment(\'left\',\''+container.attr('layout') + '\');"/>';
	s += '<img src="/images/or20/stylist/or20_AlignCenter_small.png" class="buttonNotSelected" alignment="center" alt="Center" title="Center" ';
	s += 'onclick="setHeaderAlignment(\'center\',\''+container.attr('layout') + '\');"/>';
	s += '<img src="/images/or20/stylist/or20_AlignRight_small.png" class="buttonNotSelected" alignment="right" alt="Right" title="Right" ';
	s += 'onclick="setHeaderAlignment(\'right\',\''+container.attr('layout') + '\');"/>';
	s += "</span>";
	var jElem = container.prepend(s);

	if ( selected == undefined || selected == '')
	{
		$("img[alignment='left']",jElem).addClass("selected");
	}
	else
	{
		setHeaderAlignment(selected,container.attr("layout"));
		$("img[alignment='"+selected+"']",jElem).addClass("selected");
	}
}

function resizeAdjacentHeaderLines(event,ui,container)
{
	var layoutContainer = container.parent();
	var lcTop = layoutContainer.position().top;
	var row = container.attr("row");
	$.each($("div[layout]"),function(idx,val) {
		
		
		if ( $(this).position().top == lcTop && $(this).attr("layout") != $(layoutContainer).attr("layout") )
		{
			if (event.type == 'sortableover') {
				$("div[row='" + row + "']", $(this)).css("height", ui.item.css("height"));
			}
			else {
				$("div[row='" + row + "']", $(this)).sortable('refresh');
				container.sortable('refresh');
				if ($("div[row='" + row + "']", $(this)).sortable('toArray').length == 0 &&
					container.sortable('toArray').length == 0) {
						$("div[row='" + row + "']", $(this)).css("height", "");
						container.css("height", "");
				}
				else
				{
					var eHeight = "15px";
					$("div[row='" + row + "']", $(this)).css("height", eHeight);
					container.css("height", eHeight);
				}
			}
		}
	});
}

function checkAddressLayout(event,ui,container)
{
	var layoutContainer = container.parent();
	var row = container.attr("row");
	
	var aOrientationSelect = $(":input[name='addressOrientation'] option:selected");
	var setHorizontalOrientation = false;
	$.each($("div[layout] > div[row]"),function(idx,val){
		var items = $(this).sortable('toArray');
		for(var i = 0; i < items.length; i++ )
		{
			if (( items[i] == 'address1' || items[i] == 'address2' ) && items.length > 1 )
			{
				setHorizontalOrientation = true;
				break;
			}
		}
	});
	if (aOrientationSelect.attr("value") != 'horizontal' && setHorizontalOrientation == true) {
		$(":input[name='addressOrientation'] option[value='horizontal']").attr("selected", "selected");
		$(":input[name='addressOrientation']").trigger('change');
		$(":input[name='addressOrientation']").attr("disabled","disabled");
		$("#aOrientationMessage").show();
		
	}
	else if ( aOrientationSelect.attr("value") == 'horizontal' && setHorizontalOrientation == true )
	{
		$(":input[name='addressOrientation']").attr("disabled","disabled");
		$("#aOrientationMessage").show();
		
	}
	else if ( setHorizontalOrientation == false )
	{
		$(":input[name='addressOrientation']").attr("disabled","");
		$("#aOrientationMessage").hide();
		
	}
}

function initHeaderFormat()
{
	getHeaderElementPositions();
	$("#headerLayoutFieldsCanvas > div#availableFields").sortable('destroy');
	$("div[layout] > div[row]").sortable('destroy');
	$("#headerLayoutFieldsCanvas > div#availableFields").sortable({
		connectWith:$('div[layout] > div[row]'),
		placeholder: 'ui-state-highlight',
		forceHelperSize:true,
		forcePlaceholderSize:true,
		over: function(event,ui){
			$(this).css({
				background: '#f7efd6'
			});
		},
		out: function(event,ui){
			$(this).css({
				background: "#ffffff"
			});
		}
	}).disableSelection();
	$("div[layout] > div[row]").sortable({
		connectWith:$('#headerLayoutFieldsCanvas > div#availableFields,div[layout] > div[row]'),
		placeholder: 'ui-state-highlight',
		forceHelperSize:true,
		forcePlaceholderSize:true,
		over: function(event,ui){
			$(this).css({
				background: '#f7efd6'
			});
			resizeAdjacentHeaderLines(event,ui,$(this));
		},
		out: function(event,ui){
			$(this).css({
				background: "#ffffff"
			});
		},
		change: function(event,ui){
			resizeAdjacentHeaderLines(event,ui,$(this));
		},
		update: function(event,ui){
			checkAddressLayout(event,ui,$(this));
		}
	}).disableSelection();
	
	
	$("div[row],#headerLayoutFieldsCanvas > div#availableFields").css({
		paddingTop: 5,
		paddingBottom:5,
		marginBottom: 5,
		marginLeft:'0px',
		marginRight:'0px',
		background: '#ffffff',
		listStyleType: 'none',
		clear: 'both',
		textAlign:'left'
	});
	
	$("div[layout] > div[row] > span,#headerLayoutFieldsCanvas > div#availableFields > span").css({
			margin:'2px',
			fontSize: '0.8em',
			fontWeight: 'bold',
			border: '1px dotted #000000',
			padding: '1px'
	});
	
	$.each($("div[layout]"),function(i,val){
		containerAlignmentControls($(this));
	});
	
	$("div[layout]").css({
		padding:'1px',
		margin:'1px',
		backgroundColor:'#ecdeb1',
		border: '1px solid #000000',
		opactiy:1
	});
}

function resetHeaderFields()
{
	$("#availableFields").empty();
	$("#availableFields").append('<span id="name" class="or20_Item_Drag">Name</span>\
					<span id="headline" class="or20_Item_Drag">Headline</span>\
					<span id="email" class="or20_Item_Drag">Email</span>\
					<span id="phone1" class="or20_Item_Drag">Phone 1</span>\
					<span id="phone2" class="or20_Item_Drag">Phone 2</span>\
					<span id="phone3" class="or20_Item_Drag">Phone 3</span>\
					<span id="address1" class="or20_Item_Drag">Address 1</span>\
					<span id="address2" class="or20_Item_Drag">Address 2</span>');
}

function loadHeaderFormatTemplate(element)
{
	var template = $(element).attr("value");
	$.ajax({
		type:'GET',
		url: '/modules/ordocument/stylist.php',
		data:
		{
			action: 'loadFormatStyle',
			formatValue: template,
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value')
		},
		success:function(successData){
			$("#headerLayoutContainer").empty().append(successData);
			resetHeaderFields();
			initHeaderFormat();
		}
		});
		
		
}
function showStylist(openHeaderSection,showMargins)
{
	unbindSectionEvent();
	var height = $(document).height();
	var imgX = $(window).width() / 2;
	var imgY = $(window).height() / 2;
	var bHeight = $(document).height();
	var bWidth = $(document).width();
	var varStylistScrollTop = $(window).scrollTop();
	var stylistTop = 0;
	if (varStylistScrollTop<280) //280=resume content offset top
	{
		stylistTop = $("#maincontent").offset().top-varStylistScrollTop;
	}
	var stylistWrapperOverlay = '<div id="bodyOverlay" style="width:'+bWidth+'px;height:'+bHeight+'px;filter:Alpha(opacity=40);opacity:0.4;background-color:#ffffff;z-index:1000;position:absolute;top:0;left:0;">\
									</div>';
										 
	var stylistWrapper = '<div id="stylistWrapper" style="width:312px;  ">\
											<div class="or20_Advanced_Stylist">\
												<div class="or20_Advanced_Stylist_Heading">\
													<h4>Styling Palette</h4>\
													<a class="or20_Close_Stylist" href="javascript:void(0);"><img src="/images/or20/stylist/or20_Close_Stylist.png" border="0" /></a>\
												</div>\
												<div id="divStylistContent" style="min-height:150px;background:url(/images/or20/stylist/or20_Back_Advanced_Stylist.png) repeat-y top left;width:312px;">\
													<div style="padding:20px;">\
													<img src="/images/or20/or20_ajax-loader_small.gif" border="0" /><br /> <b>Loading Styling Palette. Please wait...</b>\
													<br /><br />While the Styling Palette is open, you will not be able to edit your resume or use the side menu. <br />\
													You can move this window anywhere on the screen by dragging it by the blue title bar.\
													</div>\
												</div>\
												<div id="styleTemporaryContent" style="display:none;"></div>\
											</div>\
									 </div>';									 
	$("body").append(stylistWrapperOverlay);
	$("body").append(stylistWrapper);
	


	
	$("#stylistWrapper").draggable({
		handle: '.or20_Advanced_Stylist_Heading',
		containment: [0,0,$(document).width()-300,$(document).height()-300],
		stop: function(event,ui){
			var stylistOffTop = $(this).offset().top;
			var stylistOffLeft = $(this).offset().left;
			var wScrollTop = $(window).scrollTop();
			var wScrollLeft = $(window).scrollLeft();
			var stylistHeight = $("#stylistWrapper").children(":first").height();
			var wHeight = $(window).height();
			
			if ( stylistOffTop < wScrollTop )
			{
				$("#stylistWrapper").css("top","0");
			} else if ( (stylistOffTop + stylistHeight) > (wScrollTop + wHeight))
			{
				$("#stylistWrapper").css("top", (wHeight-35-stylistHeight));
			}
		}
	});
	$("#stylistWrapper").css({
		position: 'fixed',
		"z-index":9999,
		top: stylistTop,
		left: $("#maincontent").offset().left,
		maxHeight: $(window).height() - 50
	});
	
	
	
	$("a.or20_Close_Stylist",$("#stylistWrapper")).click(function(){
		$("#bodyOverlay").remove();
		$("#stylistWrapper").remove();
		removeHighlight();
		bindSectionEvent();
	});
	
	$.ajax({
		type: 'GET',
		async:true,
		url: '/modules/ordocument/stylist.php',
		data: {
			module: $('#documentType').attr('value') + 's',
			docid: $('#documentId').attr('value'),
			showHeaderFormat: openHeaderSection == true ? true : false,
			showMargins: showMargins == true ? true : false,
			action:"showStylist"
		},
		success: function(successData){
			$("#styleTemporaryContent").append(successData);
			$(".or20_Advanced_Stylist_Content").css({
				"max-height":$(window).height() - 120,
				"overflow":"auto",
				width: 310
			});
			getStylistBufferData();
			initHeaderFormat();
			initStylistHelp();
			$("#divStylistContent").hide();
			$("#styleTemporaryContent").show();
		}
	});
}

function sleep(numberMillis){
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true){
	now = new Date();
	if (now.getTime() > exitTime) return;
	}
};

function delTagRef(tagId)
{
	$.ajax({
		beforeSend: function(XMLHttpRequest){
			$("#existingTagsContainer").prepend('<div><img src="/images/or20/or20_ajax-loader_small.gif"/></div>');
		},
		type: 'GET',
		async: true,
		url: '/modules/ordocument/index.php',
		data: {
			module: $("#documentType").attr('value') + 's',
			docid: $("#documentId").attr('value'),
			tagid: tagId,
			action: 'removeDocumentTag'
		},
		success: function(successData){
			$("#existingTagsContainer").replaceWith(successData);
		},
		error: function(errorData){}
	});
}

function addDocTag()
{
	$.ajax({
			beforeSend: function(XMLHttpRequest){
				$("#existingTagsContainer").prepend('<div><img src="/images/or20/or20_ajax-loader_small.gif"/></div>');
			},
			type:'GET',
		   async: false,
		   dataType: 'text',
	   	   url: '/modules/ordocument/index.php',
	   	   data: {
		   		docid: $("#documentId").attr("value"),
				module: $("#documentType").attr("value"),
				existingTagId: $("#existingTagId").attr("value"),
				action: $(":input[name='action']").attr("value"),
				tagname: $(":input[name='tagname']").attr("value")
		   },
	 	   success: function(successData){
	       		$('#existingTagsContainer').replaceWith(successData);
	       		$('#tagname').attr("value","");
				$("#existingTagId").val("-1");
	        },
	        error: function(XMLHttpRequest, textStatus, errorThrown){
			   alert("The data did not save: "+textStatus+": "+errorThrown);
	    
	        }
	        
	    }); 
}

function getDocTags()
{
	$.ajax({type:'GET',
			beforeSend: function(XMLHttpRequest){
			$("#existingTagsContainer").prepend('<div><img src="/images/or20/or20_ajax-loader_small.gif"/></div>');
			},
			async:true,
			url:'/modules/ordocument/index.php',
			data: {
				module: $("#documentType").attr('value') + 's',
				docid: $("#documentId").attr('value'),
				action: 'getDocumentTags'
			},
			success: function(successData){
				$("#existingTagsContainer").replaceWith(successData);
			},
			error: function(errorData){
			}
		});
}

function addToolbarTag()
{
	var iconContainer = $("#shortcut_garden");
	var element = '<div id="tagMenu" class="taskbar_button" onclick="tabHandleClick(this,\'taskbar_add_tags\');getDocTags();" onmouseout="return tabHandleMouseOut(this);" onmouseover="return tabHandleMouseOver(this);">';
	element += '<div class="titletip"><strong>Tags</strong></div>';
	element += '</div>';
	$("#tagFormDocId").attr("value",$("#documentId").attr("value"));
	$("#tagFormModule").attr("value",$("#documentType").attr("value") + "s");
	iconContainer.append(element);
	
	$("#tagname").autocomplete(
			"/modules/ordocument/index.php?action=tagAutocomplete&module="+ $("#documentType").attr("value") + "s" + "&docid="+$("#documentId").attr("value"),
			{
				delay:15,
				minChars:2,
				matchSubset:1,
				matchContains:1,
				cacheLength:10,
				autoFill:false
			});
	
	$("#tagname").result(function(event, data, formatted) {
		if (data){
			$("#existingTagId").val(data[1]);
		}
	});

}
function stopRKey(evt) {
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) { return false; }
}
	

function initForms(){
	//check if we have a valid documentId and documentType at this step
	var docIdErrorValue = $("#documentId").attr("value");
	var docTypeErrorValue = $("#documentType").attr("value");
	if (docIdErrorValue=='' || docIdErrorValue=="undefined" || isNaN(docIdErrorValue) || (docTypeErrorValue!="resume" && docTypeErrorValue!="letter"))
	{
		var docContentErrorValue = $("body").html();
		$.ajax({
			type:'POST',
			url: 'sendError.php',
			data:{
				docIdErrorValue: docIdErrorValue,
				docTypeErrorValue:  docTypeErrorValue,
				docContentErrorValue: docContentErrorValue
			},
			success: function(successData){
			//	location.reload();
			}
		});
	}
	
	// Add an ID to each element that has a sectionType attribute
	experience_name_only=false;
	
	if($("#xsl_headline").val()!='') has_headline=1;
	
	$("div[sectiontype]").not(":hidden").each(function(i){
		this.id = "section_" + i;
		if ($(this).attr("sectiontype")=="address2") id_address2=i;
		
	});
	
	//////////////////////////////////////
	/*GETS RESUME CONTENT
	var content ='';
	$("span[id^='xsl_']").not(":hidden").each(function(i){ 
		content +=  $(this).html();
		
	});
	alert(content);*/
	
	///////////////////////////
	if ($("#bodyStyle").attr("value")!="Standard"){
		 columnarFormat=true;	
	}else  columnarFormat=false;	
	
	margins= $('.pageMargins')[0];
	
	$("div[sectiontype]").each(function(e){
		$(this).addClass("editableSection");
	});

	$("div[sectiontype]").not(":hidden").each(function(e) {
		index =$(this).attr("id").split("_");
		var i=index[1];
		var type= $(this).attr("sectiontype");
		switch (type){
			case "name":
			case "phone1":
			case "phone2":
			case "phone3":
			case "email":
			case "address1":
			case "address2":
			case "address3":
			case "personal":
			case "recipient":
			case "headline":
			case "relocation_preference":
				sectionCat ="header";
				
			break;
			case "subsection":
				//sets the parent node for employers in experience and subsections in hybrid
				if (columnarFormat==true) indexparent= $("#section_"+i).parent().parent().attr("id");
				else indexparent= $("#section_"+i).parent().attr("id");
				$("#section_"+i).attr("myparentNode",indexparent);		
				sectionCat  ="subsection";
				break;
			case "employer":
			case "employer_multiple_jobs":
					//sets the parent node for employers in experience and subsections in hybrid
					if (columnarFormat==true) indexparent= $("#section_"+i).parent().parent().parent().attr("id");
					else indexparent= $("#section_"+i).parent().attr("id");
					$("#section_"+i).attr("myparentNode",indexparent);		
					sectionCat  ="subsection";
					
			break;
			case "job":
				//sets the parent node for employers in experience and subsections in hybrid
				 indexparent= $("#section_"+i).parent().attr("id");
				$("#section_"+i).attr("myparentNode",indexparent);		
				sectionCat  ="subsection";
				break;
			default:
				sectionCat ="body";
			break;
		}
		//Sets the section category for each section
		//Section categories can be header, body or subsection.
		//this determines how to handle category editing
		//IMPORTANT NOTE: the parameter cMenu is parsed w Ajax so the first parameter
		//will be called menuId and then other variable=value can be passed
		$("#section_"+i).attr("sectionCat",sectionCat);
		
		});
		
		
		//$(currentSections).children("span").children("table").css("background-color","white");
	 	//$("#section_"+i+" > *").children("span").children("table:first").animate({backgroundColor:hoverColor},"slow","linear");

	//If the section is hidden, it will be used as a template when creating a new section
	 $("div[sectiontype]:hidden").each(function(e) {
		$(this).attr("sectionCat","duplicate");
	}); 
	 
	
		
	
	 bindSectionEvent();
	
	
}

function unbindSectionEvent(i){	
	SpellChecker.disable();
//	hideHoverMenu(i);
//	removeMenu(i);
	lastMoveMenuSender = null;
	$("[sectiontype]").not(":hidden").unbind("click");
	$("[sectiontype]").not(":hidden").unbind("mouseenter");
	$("[sectiontype]").not(":hidden").unbind("mouseleave");
	$("[sectioncat='body'],[sectioncat='subsection'],[sectioncat='header'],[highlightemp='true'], #xsl_Section_Spacing_Between_Employers").not(":hidden").unbind("mousemove");
	$("#maincontent").unbind('mousemove');
	$("#moduleCanvas").unbind('mousemove');
	 
	disableSectionHighlighting();
	try
	{
		$("[sectiontype]").not(":hidden").bind("click",displayCurrentlyEditingDialog);
	} catch ( err ) {}
}

function getSectionChildren(thisSection)
{
	var markup = $('<ul id="' + $(thisSection).attr("id") + '_sortable" class="or20_Work_Experience_List"></ul>');
	$.each($("[myparentnode='"+$(thisSection).attr("id") +"'].draggable"), function(idx,val){
		var name = '';
		switch ( $(this).attr("sectiontype"))
		{
			case 'job':
				name = $("#xsl_job_title",$(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Job';
				}
				var id = $(this).attr("id").split("_")[1];
				markup.append($('<li  opos="'+ (idx+1) + '" sid="'+id+'" id="item_'+id+'" class="or20_Job_Drag_List"><span class="file">Job: '+name+'</span></li>'));
				break;
			case 'subsection':
				name = $("#xsl_organization_name",$(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Organization';
				}
				var id = $(this).attr("id").split("_")[1];
				markup.append($('<li  opos="'+ (idx+1) + '" sid="'+id+'" id="item_'+id+'" class="or20_Employer_Drag_List"><span class="file">'+name+'</span></li>'));
				break;
			case 'employer':
				name = $("#xsl_employer_name",$(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Employer';
				}
				var id = $(this).attr("id").split("_")[1];
				markup.append($('<li  opos="'+ (idx+1) + '" sid="'+id+'" id="item_'+id+'" class="or20_Employer_Drag_List"><span  class="file">'+name+'</span></li>'));
				break;
			case 'employer_multiple_jobs':
				name = $("#xsl_employer_name", $(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Employer';
				}
				var fileType = 'file';
				var jobsListLoad =  getSectionChildren($(this));
				if (jobsListLoad!=''  && jobsListLoad != undefined )
				{
					fileType="folder";
				}
				var id = $(this).attr("id").split("_")[1];
				var li = ($('<li  opos="'+ (idx+1) + '" sid="'+id+'" id="item_'+id+'" class="or20_Employer_Drag_List"><span  class="'+fileType+'">'+name+'</span></li>'));
				li.append(getSectionChildren($(this)));
				markup.append(li);
				break;
		}
		
	});
	
	return markup;
}

function initDraggableSections()
{
		var sortableMarkup = $('<ul id="sortableSection" class="or20_Reorder_Sections_List"></ul>');
		if ( $("#margins_1").children("[sectiontype].draggable").not(":hidden").length == 0 )
		{
			sortableMarkup.append("There are no sections to sort");
		}
		$.each($("#margins_1").children("[sectiontype].draggable").not(":hidden"),function(idx,val){
			var name = '';
			var markup = '';
			var fileType = "file";
			switch ($(this).attr("sectiontype")) {
				case 'hybrid':
					name = $("#xsl_section_name",$(this)).text();
					markup = getSectionChildren($(this));
					break;
				case 'experience':
					name = $("#xsl_section_name",$(this)).text();
					markup = getSectionChildren($(this));
					break;
				default:
					name = $("#xsl_section_name",$(this)).text();
					break;
			}

			if ( name == '' || name == undefined)
			{
				name = 'Untitled Section';
			}
			if (markup!=''  && markup != undefined)
			{
				var fileType = "folder";
			}	
			
			var id = $(this).attr("id").split("_")[1];
			var li = $('<li  opos="'+ (idx+1) + '" sid="'+id+'" id="item_'+id+'" class="or20_Section_Drag_List"><span class="'+fileType+'">'+name+'</span></li>');
			
			if ( markup != '' && markup != undefined )
			{
				li.append(markup);
			}
			sortableMarkup.append(li);
		});
		
		var leftlOrderDiv = $('<div id="sortableWindow"   class="or20_Reorder_List_Left"></div>');
		leftlOrderDiv.append(sortableMarkup);
		var rightOrderDiv = '<div class="or20_Reorder_List_Right">\
				<p style="padding-left: 70px;"><img src="images/or20/or20_Help_Reorder.png" alt="Help" /></p>\
				<p><strong>With this function, you can change the order of certain elements within your resume. </strong></p>\
				<p>You can reorder: </p>\
				<ul>\
					<li>the sections of your resume </li>\
					<li>the order of employers within a work  experience section </li>\
					<li>the order of jobs at a particular employer </li>\
					<li>the order of organizations in a hybrid section</li>\
				</ul>\
				<p><strong>Drag and drop an item to change its location. Click the + and - buttons to expand or contract an object.</strong></p>\
				<p style="margin-top: 20px; padding: 10px; font-weight: bold;"> <span class="or20_CheckButton"><a href="javascript://" class="or20_BigButton" id="linkApplyOrderSections">Apply</a></span> or <a href="javascript://" id="linkCancelOrderSections">Cancel</a>\
				<span id="loadingSortApply" style="display:none;"><img src="/images/or20/or20_ajax-loader_small.gif" border="0" /></span>\
				</p>\
				</div>';
		
		var modalMarkup = $('<div class="or20_Reorder_Sections"></div>');
		modalMarkup.append(leftlOrderDiv);
		modalMarkup.append(rightOrderDiv);
		$("body").append(modalMarkup);
		
		sortableMarkup.treeview();
		
		$.each($("ul",sortableMarkup).add("#sortableSection"),function(idx,val){
			$(this).sortable({
				opacity: 0.5,
				scroll: true, 
				scrollSensitivity: 100,
				forceHelperSize:true,
				forcePlaceholderSize:true
			}).disableSelection();
		});


		//apply reorder sections
		$("#linkApplyOrderSections").click(function(){
			var height = $(document).height();
			var imgX = $(window).width() / 2;
			var imgY = $(window).scrollTop() + ($(window).height() / 2);
			$("#loadingSortApply").show();
			sections = {};
			sections.section = [];
			var sectPos = 1;
			var hashLookup = [];
			var newPositionLookup = [];
			$.each($("#sortableSection").add($("ul",$("#sortableSection"))), function(idx,val){
				sectPos = 1;
				var order = $(this).sortable('toArray');
				for ( var i=0; i < order.length;i++)
				{
					var sectLi = $("#"+order[i]);
					var sectDiv = $("#section_"+sectLi.attr("sid"));
					hashLookup["section_"+sectLi.attr("sid")] = sectLi.attr("opos");
					newPositionLookup["section_"+sectLi.attr("sid")] = (i+1);
					section = {};
					section.id = sectLi.attr("sid");
					section.position = sectPos++;
					section.type = sectDiv.attr("sectiontype");
					section.order = (i+1);
					section.originalPosition = sectLi.attr("opos");
					section.text = $(sectLi.selector + " > span").text();
					if ( sectDiv.attr("myparentnode") != '' )
					{
						section.parentPosition = hashLookup[sectDiv.attr("myparentnode")];
						section.newParentPosition = newPositionLookup[sectDiv.attr("myparentnode")];
						if ( sectDiv.parent().attr("myparentnode") != '')
						{
							section.rootPosition = hashLookup[sectDiv.parent().attr("myparentnode")];
							section.newRootPosition = newPositionLookup[sectDiv.parent().attr("myparentnode")];
						}
					}
					sections.section.push(section);
				}
			});
			$.ajax({
				type:'POST',
				url: '/modules/ordocument/index.php',
				data:{
					module: $('#documentType').attr("value"),
			   		docid :  $('#documentId').attr("value"),
					sections: JSON.stringify(sections),
					action: 'arrangeSections'
				},
				success: function(successData){
					$("#loadingSortApply").hide();
					$('#moduleCanvas').replaceWith(successData);
					initDoc();
					$("#sortableWindow").dialog('destroy');
					$("#sortableWindow").remove();
					modalMarkup.dialog('destroy');
					modalMarkup.remove();
				}
			});
		});

		//cancel reorder section
		$("#linkCancelOrderSections").click(function(){
			modalMarkup.dialog('destroy');
			modalMarkup.remove();
			//$("#addSectionDialog").dialog('destroy');
		});
		
		var topBarContent ='<h3 class="arrowModalWindow">Reorder Sections/Employer/Jobs</h3>';
		modalMarkup.dialog({
			title: topBarContent,
			height:470,
			modal:true,
			width:700,
			close: function(event,ui){
				modalMarkup.dialog('destroy');
				modalMarkup.remove();
			}
		});
		modalMarkup.css("width","100%");
}

function isDocumentEmpty(){

	if ($("#documentType").attr("value")=="letter" ){
		//THE DOCUMENT IS A LETTER
			if ($("[sectiontype='general']").not(":hidden").length==0)
			{
				$("#lastHeaderSection").css("display","block");
				return true;
			}else{
				$("#or20_Header_Inside_Menu").css("display","none");
			}
		}else{
		//THE DOCUMENT IS A RESUME
		//TESTING IF THE RESUME IS EMPTY
			if ($("[sectioncat='body'],[sectioncat='subsection']").not(":hidden").length==0)
			{
//				$("#lastHeaderSection").css("display","block");
//			
//					$("#lastHeaderSection").hover(function(e){
//					
//					$("#edit_menu").html("GET STARTED");
//					$("#delete_menu").css("display","none");
//					$("#handle").css("display","block");
//					posTop = $(this).offset().top;
//					posLeft = $(this).offset().left-150;
//					
//					$("#handle").offset({
//						left: posLeft,
//						top: posTop
//					});
//						
//					var index =$("[sectioncat='header']:last").not(":hidden").attr("id").split("_");
//					var i=index[1];
//					var options = addMenu(i,"first");
//					$("#submenu").html(options);
//					
//				});
				return true
			}else{
				return false;	
			}
				
		}
	return false;
	
}


function getElementForHover(element)
{
			// If this is display : inline element, then hover parent
			if (element.css('display') == "inline")
				element = $(element[0].parentNode);


			//$("#div_debug").html($("#div_debug").html() + " " + $(element).attr('sectiontype'));
			// If sender is sectiontype='experience'
			if (element.attr('sectiontype') == "experience")
			{


				// if we have at least two employers , then mark only header name
				var counter = element.find("[sectiontype='employer_multiple_jobs']").length + $(element).find("[sectiontype='employer']").length;

				if (counter >= 2)
					element = element.find("#xsl_section_name");
			}

			if (element.attr('id') == "xsl_Section_Spacing_Under_Employer")
				element = element.parent();

			// if [highlightemp='true'] then go to parent and find all children with this attribute

			if (element.attr('highlightemp') == 'true')
			{
				element = $(element[0].parentNode).find("[highlightemp='true']");

				/*
				 *mo: Removed, because not sure what is this used for, and it was causing bug: spans were resized in IE and stayed resized after unhover
				element.each(function(){
					//alert($(this).find("span").height());
					var spans = $(this).find("span");
					for (var k=0; k < spans.length; k++)
					{
						if ($(spans.get(k)).height() > 0)
							$(this).css('height', $(spans.get(k)).height());
					}
				});
				*/
			}
			return element;
}


function unhoverElements(sender)
{
	var currentElementAlreadyMarked = false;
	$("[hovered='true']").each(function()
			{
				if ($(this) != sender)
				{
					$(this).css('background-color', "");
					$(this).attr('hovered', '');
				}
				else
				{
					currentElementAlreadyMarked = true;
				}
			});
		return currentElementAlreadyMarked;
}

var lastMoveMenuSender = null;
function bindSectionEvent(id)
{
	try
	{
		// Unbind click event from sections that is used to alert the user that they are currently editing a section
		$("[sectiontype]").not(":hidden").unbind("click",displayCurrentlyEditingDialog);
	} catch ( err ) {}
	
	
	SpellChecker.enable();
	
	$("div[sectiontype]").css("cursor","pointer");
			
	$("[sectioncat='header']").not(":hidden").bind("click", function(e){
		e.preventDefault();
//		removeMenu();
		sectionClick(e,{id: $(this).attr("id"), sectionType:$(this).attr("sectionType")});		
	});	
	
	$("[sectioncat='body'],[sectioncat='subsection']").not(":hidden").bind("click", function(e){
		e.preventDefault();
		sectionClick(e,{id: $(this).attr("id"), sectionType:$(this).attr("sectionType")});		
	});	
	
	
	
	if ($("#documentType").attr("value")=="letter" ){
		
		$("div[sectiontype='closing']").not(":hidden").bind("click", function(e){
			e.preventDefault();
			sectionClick(e,{id: $(this).attr("id"), sectionType:$(this).attr("sectionType")});		
		});	
		
	}
//
	$("[sectioncat='body'],[sectioncat='subsection'],[sectioncat='header'],[highlightemp='true']").not(":hidden").mouseout(function(e){


		return;
		appendDebug($(this).attr('id') + "[OUT]-");
		var element = $(this);

			//
			// Find id of section with category 'body'
			var sectionId = "section_0";
			if (element.attr('sectioncat') == 'body')
			{
				sectionId = element.attr('id');
			}
			else
			{
				// find parent
				var parent = element.parents("[sectioncat='body']");
				
				if (parent.attr('id') != undefined)
					sectionId = parent.attr('id');
			}

			$("[orsectionid='" + sectionId + "']").css('background-color', '');


		element = getElementForHover(element);

		element.css('backgroundColor','');
		$(this).find("table").find("tr").css('background-color', '');



			

	});

	/*$(document).mousemove(function(e)
	{
				unhoverElements(null);
	});*/



		$("[sectioncat='body'],[sectioncat='subsection'],[sectioncat='header'],[highlightemp='true'], #xsl_Section_Spacing_Between_Employers, #xsl_Section_Spacing_Under_Employer").not(":hidden").mousemove(function(e){

			appendDebug($(this).attr('id') + "[IN]-");
		
			e.stopPropagation();
			e.preventDefault();
			e.stopImmediatePropagation();


			var element = $(this);


			//
			// Find id of section with category 'body'
			var sectionId = "section_0";
			if (element.attr('sectioncat') == 'body')
			{
				sectionId = element.attr('id');
			}
			else
			{
				// find parent
				var parent = element.parents("[sectioncat='body']");
				if (parent.attr('id') != undefined)
					sectionId = parent.attr('id');
			}

			


			var id = element.attr('id');

			if (id == "xsl_Section_Spacing_Under_Section_Header" || id == "xsl_Section_Spacing_Between_Employers")
			{
				unhoverElements(null);
				return;
			}
				

			// if we hover xsl_Section_Spacing_Under_Employer, and our parent is employer_multiple_jobs - do not highlight
			if (id == "xsl_Section_Spacing_Under_Employer" && element.parent().attr('sectiontype') == "employer_multiple_jobs")
			{
				unhoverElements(null);
				return;
			}
				

			element = getElementForHover(element);

			
		

			
			if (element.attr('stopPropagation') == 'true')
			{
					return;
			}

		
			//if (lastMoveMenuSender == this)
				//				return;

		//	$("[sectioncat='body'],[sectioncat='subsection'],[sectioncat='header']").css('backgroundColor', '');
			//element.style.backgroundColor = hoverColor;
			
			// add special attribute for element
			var currentElementAlreadyMarked = unhoverElements(element);
			
			if (!currentElementAlreadyMarked)
			{
				element.css('background-color', hoverColor);
				element.attr('hovered', 'true');
			}

			// hover element in right menu
			var rightMenu = $("[orsectionid='" + sectionId + "']");
			rightMenu.css('background-color', hoverColor);
			rightMenu.attr('hovered', 'true');

			var tableElements = $(this).find("table").find("tr");
			tableElements.css('background-color', hoverColor);
			tableElements.attr('hovered', 'true');

			lastMoveMenuSender = this;
			
			  
			});
		
		
		
	//}

	
	$("#deleteSection").bind("click", function(e){
		var index =$(this).attr("id").split("_");
		var i=index[1];
		var type= $(this).attr("sectiontype");
		DeleteSection(""+i,""+type+"");
	});
	 
//	initSectionHighlighting();
}

function sectionClick(e, data)
{
//	alert(typeof(FCKeditorAPI));
//	alert(typeof(tpfck.ToolbarSet.CurrentInstance));
//	alert(tpfck.Status);
	if ((typeof(FCKeditorAPI)!=='undefined') && (typeof(tpfck.ToolbarSet.CurrentInstance)!=='undefined')){
		
	
	if ( tpfck.Status != 2 && tpfck2.Status != 2 )
	{
		return;
	}
	
	if ( e.target.nodeName.toLowerCase() == "A".toLowerCase() )
	{
		
		return;
	}
	var index =data.id.split("_");
	var i=index[1];
	var type= data.sectionType;
	//unbindSectionEvent(i);
	
	//removeMenu(i);
	showEditor(i, type);
	/*if ( tpfck.Status != 2 && tpfck2.Status != 2 )
	{
		return;
	}
	alert(e.originalEvent+"target.id "+e.originalEvent.target.id+" "+e.originalEvent.originalTarget);
	if ( e.originalEvent.target.id =="handle" || e.originalEvent.target.id =="subhandle")
	{
		return;
	}
	if ( e.originalEvent.target.nodeName.toLowerCase() == "A".toLowerCase() )
	{
		return;
	}
	unbindSectionEvent();
	removeMenu(e.data.index);
	showEditor( e.data.index, e.data.sectionType);
	return false;*/
	}else{
		alert("Please wait for the page to fully load.");
	}
}

function isMSIE() {
  return '\v' == 'v';
}

//Sets the content of fck
function SetFCKContent(fck1, fckcontent, append,insertAtCursor){
	var wasIE = false;
	var fck= eval(fck1);
	
	if (isMSIE() && fck.EditMode == FCK_EDITMODE_WYSIWYG) {
		
		fck.SwitchEditMode();
		wasIE = true;
	}
	
	var addBreakBeforeTable = "";
	var addBreakAfterTable = "";
	var contentLength = fckcontent.length;
	if (append == 1) {
		
		//this case is used when inserting examples into the fck
		if (fckcontent != undefined) 
			if (fck.Name == "fckResumeData") 
				content = FCKeditorAPI.GetInstance('fckResumeData').GetXHTML();
		if (fck.Name == "fckResumeDescription") 
			content = FCKeditorAPI.GetInstance('fckResumeDescription').GetXHTML();
		if (fck.Name == "fckResumeHeadline") 
			content = FCKeditorAPI.GetInstance('fckResumeHeadline').GetXHTML();
		
		if (content!=undefined){
			var trimStr =content.replace("<br />","").replace("<br/>","");
		}
		if ( insertAtCursor === true && !FCKBrowserInfo.IsIE && !FCKBrowserInfo.IsSafari )
		{
			fck.InsertHtml(fckcontent);
		}
		else
		{
			if (trimStr!='') fck.SetData(content +'<br/> '+ fckcontent);
			else fck.SetData(fckcontent);			
		}
		
	}
	else {
		
		//if (fckcontent != undefined && fckcontent.length > 0) {
			//add br if the only content in the fckeditor is a list or a table
			if (fckcontent.substr(0,7).indexOf("table")!=-1)
			{
				addBreakBeforeTable = "<br />";
			}
			
			if (fckcontent.substr(contentLength-7,contentLength).indexOf("table")!=-1)
			{
				addBreakAfterTable = "<br />";
			}
			
			//list
			if (fckcontent.toLowerCase().substr(0,5).indexOf("ul")!=-1 && fckcontent.toLowerCase().substr(contentLength-5,contentLength).indexOf("ul")!=-1)
			{
				
				addBreakAfterTable = "<br />";
			}
			
			fck.SetData(addBreakBeforeTable+fckcontent+addBreakAfterTable);
			
		/*}
		else 
			fck.SetData(label_click_here_to_add_text);
			*/
	}
	
	fck.Events.AttachEvent('OnAfterSetHTML', setFckEditorDefaultFont);
	
	if ( wasIE ){

		
		fck.SwitchEditMode();
		
		fck.Focus();
	}
	
	//$("[type='text']").not(":hidden").focus();
	//fck.MakeEditable();
	if (FCKBrowserInfo.IsSafari)
	{
		//alert('Test3: Safari');
		resizeFckArea(fckSafariHeight + 30, fckSectionId, fck.Name);
		triggerNext(fckSectionId);
	}
	fck.Events.AttachEvent('OnAfterSetHTML',getDataLoaded);
	
}

var autoGrowPlugin = null;
function assignAutoGrowPlugin(autoGrowPluginInstance)
{
	autoGrowPlugin = autoGrowPluginInstance;
}


//set editor default font
function setFckEditorDefaultFont(fck)
{
	var sectionFontSize = getSectionFontSize();
	var sectionFontFamily = getSectionFontFamily();
	fck.EditingArea.Document.body.style.cssText += 'font-size:'+sectionFontSize+';font-family:' + sectionFontFamily +';';
		$("td",$(fck.EditingArea.Document.body)).css({
		  "font-family" : sectionFontFamily,
		  "font-size" : sectionFontSize
		});
		
		$("ul",$(fck.EditingArea.Document.body)).css({
			  "margin-left" : getListMarginLeft,
			  "padding-left" : getListPaddingLeft
			});

	fireAutoGrow();
}

function getDataLoaded(fck)
{
	dataLoadedJSON = $("#general_form").serializeArray();
    var obj = {};
    if (fck.Name == "fckResumeData") 
    {
 	   obj = {};
 	   obj.name='fck';
 	   obj.value=encodeURIComponent(tpfck.GetXHTML(true));
 	   dataLoadedJSON.push(obj);
    }
    if (fck.Name == "fckResumeDescription") {
			obj = {};
			obj.name = 'description';
			obj.value=encodeURIComponent(tpfck2.GetXHTML(true));
			dataLoadedJSON.push(obj);
    }
    if (fck.Name == "fckResumeHeadline") 
    {
			obj = {};
			obj.name = 'headline';
			obj.value = encodeURIComponent(tpfckHeadline.GetXHTML(true));
			dataLoadedJSON.push(obj);
    }
}

//get section font size
function getSectionFontSize()
{
	var styleSectionValue = $("#xsl_section_data").parent().attr("style").toLowerCase();
	var styleSectionValueArray1 = styleSectionValue.split(";");
	var sectionFontSize = "12";
	for (var p=0;p<styleSectionValueArray1.length;p++)
	{
		if (styleSectionValueArray1[p].indexOf("font-size")!=-1)
		{
			var styleSectionValueArray2 = styleSectionValueArray1[p].split(":");
			if (styleSectionValueArray2[0].indexOf("font-size")!=-1)
			{
				//alert(styleSectionValueArray2[1]);
				sectionFontSize = styleSectionValueArray2[1].replace(/^\s+|\s+$/g,"");
				var emPosition = sectionFontSize.indexOf("em");
				sectionFontSize = sectionFontSize.substr(0,emPosition);
				sectionFontSize = parseInt(sectionFontSize*16);
			//	sectionFontSize = String(sectionFontSize);
				sectionFontSize = sectionFontSize+"px";
			}
		}
	}
   return  sectionFontSize;
}

//get section font famiy
function getSectionFontFamily()
{
	var sectionFontFamily = $("#xsl_section_data").css('font-family');
	return sectionFontFamily;
}


//get list margin left
function getListMarginLeft()
{
	var styleMarginLeft = $("ul", $("#maincontent")).css("margin-left");
	return styleMarginLeft;
}

//get list padding left
function getListPaddingLeft()
{
	var stylePaddingLeft = $("ul", $("#maincontent")).css("padding-left");
	stylePaddingLeft = "14px";
	return stylePaddingLeft;
}

function initFck(){	 
	
	//create FCK with javascript
	
	
//	instanceName, width, height, toolbarSet,
	tpfck = new FCKeditor("fckResumeData");
	
	if ($('#documentType').attr("value")=="resume")
		tpfck.ToolbarSet	= 'ResumeBuilder' ;
	else tpfck.ToolbarSet	= 'LetterBuilder' ;

	if (($("#xsl_section_data" ,"div[sectioncat='body']").html() == null) || ($("#xsl_section_data" ,"div[sectioncat='body']").html() == '')) {
		$("div[sectiontype='general'][sectioncat='duplicate']").css("display", "block");
		$("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").html(" ");
		
		var paddingLeft =0;
		if ($("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").length==0)
		{	paddingLeft=0;
			fckWidth=pageWidth;
		}else{
			paddingLeft = $("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").parent().css("padding-left").split("px");
		
			if (paddingLeft[0] > 0) {
				fckLeftPadding = paddingLeft[0];
				fckWidth = $("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").parent().width() - paddingLeft[0];
			}
			else {
				fckLeftPadding=0;
				fckWidth = $("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").parent().width();
			}
			$("div[sectiontype='general'][sectioncat='duplicate']").css("display", "none");
			$("#xsl_section_data", "div[sectiontype='general'][sectioncat='duplicate']").html("");
		}
	}
	else {
	
	    
	
		//GET THE WIDTH OF THE CONTENT SECTION - NEED TO USE PARENT BECAUSE SPAN COULD BE BLANK
		var paddingLeft = $("#xsl_section_data").parent().css("padding-left").split("px");
		if (paddingLeft[0] > 0) {
			fckLeftPadding = paddingLeft[0];
			//fckWidth = $("#xsl_section_data").parent().width() - paddingLeft[0];
			//removed above line for indented sections
		    fckWidth = $("#xsl_section_data").parent().width();
		}
		else {
			fckLeftPadding=0;
			
			fckWidth = $("#xsl_section_data").parent().width();
		}
	}	
	//SET THE WIDTH
	tpfck.Width = fckWidth;
	//tpfck.Height = 27;
	tpfck.Height = 60;
	if (FCKBrowserInfo.IsSafari)
		tpfck.Height = fckSafariHeight;
	
	//alert(tpfck.CreateHtml());
	$("#fckarea").html('<div id="instructions"></div>'+tpfck.CreateHtml());
		
	setView('edit');
	
	document.onkeypress = stopRKey;
}
function resizeFckArea(newSize,fckSectionId,fckName){
	
	if (newSize!=undefined){
	// Avoiding case of resize after fck initialization
	//alert($("#fckarea").css('display'));
	if ((fckName.indexOf("fckResumeData") > - 1 && $("#fckarea").css('display') == 'none')
		||
		(fckName.indexOf("fckResumeData") == - 1 && $("#fckarea_employer_description").css('display') == 'none'))
		return;


	newSize += 10;
	var index = fckName.indexOf("fckResumeData");

	if (index>-1){
		tp = $("span[id='xsl_section_data']", "#section_" + fckSectionId).parent();
		//alert("Test12 inside resizefck: Height:" + newSize);
		if ($('#documentType').attr("value")=="letter"){
			tp.height(newSize);
			$("#fckarea").height(newSize);
		}else{
			tp.height(newSize);
			$("#fckarea").height(newSize);
			
		}
			tpfck.visible=true;
	
	}else{
		
		$("#toggledescription").height(newSize);
		//$("#toggledescription").attr('edit_size', newSize);
	
		$("#fckarea_employer_description").height(newSize);
	}
	
	// set focus on any text element (to fix issue with ie being unable to set focus in fck)
	
	
	//setEditPlaceHolderSize();
	}
}

function triggerNext(fckSectionId){

	
	posTop = parseInt($("span[id='xsl_section_data']", "#section_" + fckSectionId).parent().offset().top,10);
	posLeft = parseInt($("span[id='xsl_section_data']", "#section_" + fckSectionId).parent().offset().left,10)+parseInt(fckLeftPadding);

	//alert(posTop + " " + posLeft);

	var previousTop = parseInt($("#fckarea").offset().top,10);
	var previousLeft = parseInt($("#fckarea").offset().left,10);

	// to avoid jumping by 1 pixel

	if (Math.abs(previousTop-posTop) > 2 || Math.abs(previousLeft-posLeft) > 2)
	{
		$("#fckarea").offset({
			left: posLeft,
			top: posTop
		});
	}
	next();
	
}

function initFckEmployerDescription(){
	
		
	tpfck2 = new FCKeditor("fckResumeDescription");
	
	tpfck2.ToolbarSet = 'ResumeBuilder';
	tpfck2.Width = fckWidth;
	tpfck2.Height = 60;
	
	if (FCKBrowserInfo.IsSafari)
		tpfck2.Height = fckSafariHeight;
	


	$("#fckarea_employer_description").html(tpfck2.CreateHtml());
	
	isDocumentEmpty();
	
	
}

	
function selectSection(id){
		//add controls to selected section
		 
/*		$("#"+section_id).css("background-color",hoverColor);
	
		$("#"+section_id+" > *").children("span").children("table").css("background-color",hoverColor);
		var type= $("#"+section_id).attr("sectiontype");
		index = section_id.split("_");
		var i=index[1];
		
		if  ((type=="subsection") ||(type=="employer") || (type=="job"))
		{	var parent = $("#"+section_id).attr("myparentnode");
			parentindex = parent.split("_");
			var iparent=parentindex[1];
		}
	*/
	posTop = $("#section_"+id).offset().top;
	posLeft = $("#section_"+id).left-135;
	link= "<div name='handle' id='handle' class='handle' ><span name='handleclose' id='handleclose' style='float:right;width:15px' >x</span><span class='dragHandle'></span><span id='handleopen' name='handleopen' >Options</span><span id='arrow' class='handleopen' >&nbsp;</span></div>"; 
	$(link).appendTo("#maincontent");
	$("#handle").offset({
		left: posLeft,
		top: posTop
	});
}


var sourceContainer;
var dataLoaded='';


function delete_picture(imageToDelete){
	if (confirm (confirmDeletePictureMess)){
		$.post(
		   "/modules/resume/deleteImage.php",
		  {    async: true,
			   imageToDelete: imageToDelete}, function(msg){
		       $("#picture_upload").css("display","block");
		       $("#picture_display").css("display","none");
		   }); 
	}
}


function saveInfobyte(id,fckname)
{
	var position = "inline";
	var infobyteData = $("#infobyteTextarea").val();
	var sectionType = $("#section_"+id).attr("sectiontype");
	var j = getPosition("section_"+id,sectionType,position);

	if (is_adding==true){
		 $("#infobyte","#section_"+id).html(infobyteData);
	}else{
	//TODO: Set proper save path and parameters
		$.ajax({type:'POST',
			   async: false,
			   dataType: 'text',
		   	   url: '/modules/ordocument/saveInfobyte.php',
		   	   data:{ documentType: $('#documentType').attr("value"),
			   documentId :  $('#documentId').attr("value"),
			   sectionType: sectionType,
			   sectionIndex: j,
			   position: position,
			   dataToSave: infobyteData},
		 	   success: function(successData){
				   $("#infobyte","#section_"+id).html(infobyteData);	// TODO: Refresh of section on insert, update value on modify
		           
		        },
		        error: function(errorData){

						alert("The infobyte did not save: "+errorData);
		          
		        }

		    });
	
	}
	
	if ( infobyteData != undefined && jQuery.trim(infobyteData) != '')
	{
		$("#fckInfobyteButton").attr("src", "/images/or20/or20_Infobytes_Button_active.png");
	}
	else
	{
		$("#fckInfobyteButton").attr("src", "/images/or20/or20_Infobytes_Button.png");
	}
	

}

function showInfobytePopup(fckName,id)
{
	var infobyte = $("#infobyte","#section_"+id).html().replace(/\s?jQuery\d+="\d+"/gi,"");
	if (infobyte==undefined ) infobyte='';
	$("body").append('<div id="infobyteWindow" style="display:none;"><ul id="parentSections"></ul>\
								<div id="infobyteInstructions" class="or20_SectionInstructions" style="margin:0px;"> Add additional information or a personal touch to your web resume with an infobyte.</div>\
								<div id="infobyteContent" style="padding:5px;"><textarea id="infobyteTextarea" style="width: 390px; height: 120px;">'+infobyte+'</textarea></div>\
								<p id="saveCancelInfobyteButtons" style="margin-top: 20px; padding: 10px; font-weight: bold;"> <span class="or20_CheckButton"><a href="javascript://" class="or20_BigButton" id="linkSaveInfobyte">Save</a></span>\
								<span class="or20_CheckButton"><a href="javascript://" class="or20_BigButton" id="linkPreviewInfobyte">Preview</a></span>\
								or <a href="javascript://" id="linkCancelSaveInfobyte">Cancel</a></p>\
								</div>');
	var diag = $("#infobyteWindow");
	var topBarContent ='<h3 class="arrowModalWindow">Infobyte</h3>';

	//save infobyte
	$("#linkSaveInfobyte").click(function(){
		$("#saveCancelInfobyteButtons").html('<img src="/images/or20/or20_ajax-loader_small.gif" border="0" />');
		saveInfobyte(id,fckName);
		$("#infobyteWindow").dialog('destroy');
		$("#infobyteWindow").remove();
		//bindSectionEvent();
	});
	
	//cancel add infobyte
	$("#linkCancelSaveInfobyte").click(function(){
		$("#infobyteWindow").dialog('destroy');
		$("#infobyteWindow").remove();
		//bindSectionEvent();
	});
	
	//Preview Infobyte
	$("#linkPreviewInfobyte").click(function(){
		$("#saveCancelInfobyteButtons").append('<span id="infobytePreviewIndicator"><br/><br/>Saving... <img src="/images/or20/or20_ajax-loader_small.gif" border="0" /></span>');
		saveInfobyte(id,fckName);
		previewHref = $("#htmlDownloadLink").attr("href");
		var win = window.open(previewHref,'infobytePreviewWindow','width='+screen.width+',height='+screen.height+',scrollbars=1');
		$("#infobytePreviewIndicator").remove();
	});
	
	diag.dialog({
				modal:true,
				close: function() { $("#infobyteWindow").remove();},
				title: topBarContent,
				width: 410,
				height:330
	});
}

//
//Shows the popup with headline FCK
function showHeadlinePopup(id, sectionType, link, position)
{
	fckSectionId =id;
	fckSectionType=sectionType;
	fckSectionName="fckResumeHeadline";
	
	fckContent= $("#xsl_headline").html();
	
	tpfckHeadline = new FCKeditor('fckResumeHeadline');
	tpfckHeadline.ToolbarSet = 'ResumeHeadline';

	tpfckHeadline.Height = 160;
	tpfckHeadline.Width = (FCKBrowserInfo.IsSafari) ? 575 : 590;
	tpfckHeadline.Value = fckContent;
	
	dataLoadedJSON = $("#general_form").serializeArray();
    var obj = {};
	obj.name = 'headline';
	obj.value = encodeURIComponent(fckContent);
	dataLoadedJSON.push(obj);
    
	
	$("body").append('<div id="headlineWindow" style="display:none;border:1px;"><ul id="parentSections"></ul>\
			<div id="headlineInstructions" style="padding:10px;height:200px;overflow:auto;"></div>\
			<div class="fcklinks" id="fcklinks" style="display:block; text-align:right;clear:both;height:20px;padding-top:3px;padding-right:5px;">\
			<a href="javascript:void(0)" onclick="showFCKExamples(\'tpfckHeadline\',\''+id+'\')" ><img src="images/or20/or20_Examples_Button.png" border="0" /></a>\
			<a href="javascript:void(0)" onclick="showActionWords(\'tpfckHeadline\',\''+id+'\',\'Headline\',\'Headline\')" ><img src="images/or20/or20_ActionVerbs_Button.png" border="0" style="margin:0px 3px;" /></a>\
			</div>\
			<div id="headlineContent" style="margin:5px;"></div>\
			<p id="saveCancelInfobyteButtons" style="margin-top: 20px; padding: 10px; font-weight: bold;"> <span class="or20_CheckButton"><a href="javascript://" class="or20_BigButton" id="linkSaveHealine">Save</a></span>\
			<a href="javascript://"   id="linkRemoveHeadline">Remove</a>\
			or <a href="javascript://" id="linkCancelHeadline">Cancel</a></p>\
			</div>');
	var diag = $("#headlineWindow");
	var topBarContent ='<h3 class="arrowModalWindow">Headline</h3>';
	
	$.ajax({
		type:'POST',
		   async: false,
		   dataType: 'json',
	   	   url: '/modules/ordocument/stylist.php',
	   	   data:{ 
	   	   		action: 'loadHeadlineInstructions',			
	   	   		module: $('#documentType').attr('value') + 's',
	   	   		docid: $('#documentId').attr('value')
	   	   },
	 	   success: function(successData){	 
		   			$('#headlineInstructions').append(successData.instructions);
	       }
	});
	
	
	//save headline
	$("#linkSaveHealine").click(function(){
		SaveData(id, sectionType, "inline",false)
		tpfckHeadline = null; //destroy the fkceditor too
		$(this).dialog('destroy');
		$("#headlineWindow").remove();
		bindSectionEvent();
	});
	
	//hide headline
	$("#linkRemoveHeadline").click(function(){
		HideHeader(id, sectionType);
		tpfckHeadline = null; //destroy the fkceditor too
		$("#headlineWindow").dialog('destroy');
		$("#headlineWindow").remove();
		bindSectionEvent();
	});
	
	//cancel headline
	$("#linkCancelHeadline").click(function(){
		tpfckHeadline = null; //destroy the fkceditor too
		$("#headlineWindow").dialog('destroy');
		$("#headlineWindow").remove();
		bindSectionEvent();
	});
	
	
	
	var html = tpfckHeadline.CreateHtml();
	$('#headlineContent').html(html);

	

	diag.dialog({
				modal:true,
				title: topBarContent,
				close: function() {
						tpfckHeadline = null; //destroy the fkceditor too
						$(this).dialog('destroy');
						$("#headlineWindow").remove();
						bindSectionEvent();
					},	
				width: 600,
				height:530
	});
}


function showActionWords(fckName,sectionId,sectionType,sectionName){
	$("body").append('<div id="actionwordswindow" style="display:none;"><ul id="parentSections"></ul><div id="actionwordscontent"></div></div>');
	var diag = $("#actionwordswindow");
	
	var topBarContent ='<h3 class="or20_TopModalTitle or20_modalTopIcon">Action Verbs</h3>';
	
  diag.dialog({
	  			resizable: false,
				modal:true,
				close: function() { $("#actionwordswindow").remove(); try { hs.close('exampleAfterAdd'); } catch (err) {} },
				title: topBarContent,
				width: 620,
				height:500
			});
			
	$('#actionwordscontent').html('<p><img src="/images/or20/or20_ajax-loader_small.gif" border="0" /> <b>Loading</b></p>');			
	
	var url= '/modules/ordocument/actionWordsCat.php';
	$.ajax({type:'POST',
		   async: false,
		   dataType: 'text',
	   	   url: url,
	   	   data:{ 
	   	   documentType: $('#documentType').attr("value"),
		   documentId :  $('#documentId').attr("value"),
		   sectionType: sectionType,
		   sectionId: sectionId,
		   fckName: fckName,
		   sectionName: sectionName,
		   universityLanguageId : $('#universityLanguageId').val()
	   	   },
	 	   success: function(successData){	 
		   			
		   			$('#actionwordscontent').html(successData);
	        },
	        error: function(errorData){
			   alert("The action verbs did not load");
	           
	        }
	        
	    }); 

	
}


function showFCKExamples(fckName,sectionId){
	$("body").append('<div id="exampleswindow"><ul id="parentSections"></ul><div id="examplescontent"></div></div>');
	var diag = $("#exampleswindow");
	var sectionName= $("#section_name").attr("value");
	var sectionType= $("#section_"+sectionId).attr("sectionType");
	var modalWindowTitle = "Section Examples";
	if (fckName=='SectionInstructions')
	{
		var modalWindowTitle = "Section Instructions";
	}
	var topBarContent ='<h3 class="or20_TopModalTitle or20_modalTopIcon">'+modalWindowTitle+'</h3>';
	
  diag.dialog({
				modal:true,
				close: function() { 
	  				$("#exampleswindow").remove();
	  				// FB745 - wrapped this focus call in a try/catch block because in IE7
	  				//  this call throws an exception which causes the user to be redirected 
	  				// back to the home page.
	  				try
	  				{
	  					$("[type='text']").not(":hidden").focus();
	  				} catch ( err ) {}
					try { hs.close('exampleAfterAdd'); } catch (err) {}
  				},
				title: topBarContent,
				width: 950,
				height:460
			});
			
	$('#examplescontent').html('<p><img src="/images/or20/or20_ajax-loader_small.gif" border="0" /> <b>Loading</b></p>');			
	
	
	var url;
	if ($('#documentType').attr("value")=='resume'){
		url= '/modules/ordocument/examples.php';
		$.ajax({type:'POST',
			   async: false,
		   	   url: url,
		   	   data:{ 
		   	   documentType: $('#documentType').attr("value"),
			   documentId :  $('#documentId').attr("value"),
			   sectionType: sectionType,
			   sectionId: sectionId,
			   fckName: fckName,
			   sectionName: sectionName
		   	   },
		 	   success: function(successData){
			   			$('#examplescontent').html(successData);
		        },
		        error: function(errorData){
				   alert("The examples did not load");
		           
		        }
		        
		    }); 
	}
	else{
		url= '/modules/ordocument/letterExamples.php';
		$.ajax({type:'POST',
		   async: false,
		   dataType: 'text',
	   	   url: url,
	   	   data:{ 
	   	   documentType: $('#documentType').attr("value"),
		   documentId :  $('#documentId').attr("value"),
		   sectionType: sectionType,
		   sectionId: sectionId,
		   fckName: fckName,
		   letterType: $("#letterType").val()
	   	   },
	 	   success: function(successData){	 
		   			
		   			$('#examplescontent').html(successData);
	        },
	        error: function(errorData){
			   alert("The examples did not load");
	           
	        }
	        
	    }); 
	}
	
}




function addslashes( str ) {
 	if (str!=null) {return str.replace(/\'/g, '&#39;').replace(/\"/g, '&#34;');}
	else return str;
}

function findTopParent(currentSection){
	if ($("#"+currentSection).attr("myparentnode")!=undefined){
		var parentNode= $("#"+currentSection).attr("myparentnode");
		return findTopParent(parentNode);
	}
	else
		return  currentSection;
	
}

function showNewSectionForm(currentSection,position){
	unbindSectionEvent(currentSection);
	//removeMenu(currentSection);
	
	var newSection = $("div[sectionCat='duplicate'][sectionType='general']").clone();
	var page = $("div[id='maincontent']:last");
	var newId= findMaxSection(); //$("div[id^='section_']:last").attr("id").split("_");
	var i = parseInt(newId)+1;
	
	newSection.attr("sectionCat","body");
	newSection.attr("id","section_"+i);
	newSection.attr("sectionType","general");
	newSection.css("display","block");
	
	var newBlankSection = $("#spacer").clone();
	newBlankSection.css("display", "block");
	
	if ($("#documentType").attr("value")=="letter" ){
		//THIS IS LETTER
		if ($("[sectiontype='general']").not(":hidden").length==0)
		{
			var newSpacerSection =$("#xsl_space_between_sections").clone();
			$("#lastHeaderSection").after(newSection);
			$("#lastHeaderSection").after(newSpacerSection);
			$("#lastHeaderSection").css("display","none");
			$("#edit_menu").html("EDIT");
			$("#delete_menu").css("display","block");
		}
	}else{
		//THIS IS RESUME
		if ($("[sectioncat='body'],[sectioncat='subsection']").not(":hidden").length==0){
			//THE RESUME HAS NO SECTION OTHER THAN THE HEADER
			var newSpacerSection =$("#xsl_space_between_sections").clone();
			$("#lastHeaderSection").after(newSection);
			$("#lastHeaderSection").after(newSpacerSection);
			$("#lastHeaderSection").css("display","none");
			$("#edit_menu").html("EDIT");
			$("#delete_menu").css("display","block");
			
		}else{
			if ($("#section_"+currentSection).attr("myparentnode")!=undefined){
				currentSection = findTopParent("section_"+currentSection);
			}
			else{
				currentSection ="section_"+currentSection;
			}
			
			if (position=="before"){
				
				$("#"+currentSection).before(newBlankSection);
				$("#"+currentSection).before(newSection);
			}
			else{
				$("#"+currentSection).after(newBlankSection);
				$("#"+currentSection).after(newSection);
			}
		}
	
	}
	is_adding=true;
	showEditor(i,"general",position);
	return i;
	
}



function showNewJobForm(currentExperience,position){
	unbindSectionEvent(currentExperience);
	//removeMenu(currentExperience);
	
	var newSection = $("div[sectioncat='duplicate'][sectiontype='job']").clone();
	var newId=  findMaxSection(); //$("div[id^='section_']:last").attr("id").split("_");
	var i = parseInt(newId)+1;
	
	newSection.css("display","block");
	newSection.attr("sectionCat","body");
	newSection.attr("id","section_"+i);
	newSection.attr("sectionType","job");
	newSection.attr("myparentNode","section_"+currentExperience);
	newSection.css("display","block");
	
	if ( columnarFormat==true){
		$("#section_"+currentExperience).children(":last").append(newSection);
	}
	else{
		$("#section_"+currentExperience).append(newSection);
	}
	
	//if (data!=undefined) $("span[id='xsl_section_data']","#section_"+i).html(data);
	//else $("span[id='xsl_section_data']","#section_"+i).html("");
	
	is_adding=true;

	showEditor(i,"job",position);
	return i;


}

function showNewExperienceForm(currentSection, position){
	unbindSectionEvent(currentSection);
	//removeMenu(currentSection);
	
	var newSection = $("div[sectioncat='duplicate'][sectiontype='experience']").clone();
	var newId = findMaxSection(); 
	var i = parseInt(newId) + 1;
	
	newSection.css("display", "block");
	newSection.attr("sectionCat", "body");
	newSection.attr("id", "section_" + i);
	newSection.attr("sectionType", "experience");
	//newSection.attr("myparentNode", "section_" + currentSection);
	
	var newBlankSection = $("#spacer").clone();
	newBlankSection.css("display", "block");
	
///////////Employer form
		var newSectionEmployer = $("div[sectioncat='duplicate'][sectiontype='employer']").clone();
		var j = i + 1;
		newSectionEmployer.css("display", "block");
		newSectionEmployer.attr("sectionCat", "body");
		newSectionEmployer.attr("id", "section_" + i);
		newSectionEmployer.attr("sectionType", "employer");
		newSectionEmployer.attr("myparentNode", "section_" + i);
////////////////

	if ($("[sectioncat='body'],[sectioncat='subsection']").not(":hidden").length==0){
		//THE RESUME HAS NO SECTION OTHER THAN THE HEADER
		var newSpacerSection =$("#xsl_space_between_sections").clone();
		$("#lastHeaderSection").after(newSection);
		$("#lastHeaderSection").after(newSpacerSection);
		$("#lastHeaderSection").css("display","none");
		$("#edit_menu").html("EDIT");
		$("#delete_menu").css("display","block");
		//ADDING THE EMPLOYER
		if (columnarFormat == true) {
			newSection.children(":eq(0)").append(newSectionEmployer);
		}else{
			
			newSection.children(":last").after(newSectionEmployer);
		}	
		
	}else{
		if ($("#section_"+currentSection).attr("myparentnode")!=undefined){
			currentSection = findTopParent("section_"+currentSection);
		}
		else{
			currentSection ="section_"+currentSection;
		}
		
		if (position=="before"){
				$("#"+currentSection).before(newBlankSection);
				$("#"+currentSection).before(newSection);
		}
		else{
				$("#"+currentSection).after(newSection);
				$("#"+currentSection).after(newBlankSection);
		}
		//ADDING THE EMPLOYER
		if (columnarFormat == true) {
			newSection.children(":eq(0)").append(newSectionEmployer);
		}else{
			
			newSection.children(":last").after(newSectionEmployer);
		}	
	}
	is_adding = true;
	showEditor(i,"experience",position);
	return i;
	
}


function showNewHybridForm(currentSection, position){
	unbindSectionEvent(currentSection);
	//removeMenu(currentSection);
	
	var newSection = $("div[sectioncat='duplicate'][sectiontype='hybrid']").clone();
	var newId = findMaxSection(); 
	var i = parseInt(newId) + 1;
	
	newSection.css("display", "block");
	newSection.attr("sectionCat", "body");
	newSection.attr("id", "section_" + i);
	newSection.attr("sectionType", "hybrid");
	//newSection.attr("myparentNode", "section_" + currentSection);
	
	var newBlankSection = $("#spacer").clone();
	newBlankSection.css("display", "block");

///////////organ form
	var newSectionEmployer = $("div[sectioncat='duplicate'][sectiontype='subsection']").clone();
	var j = i + 1;
	newSectionEmployer.css("display", "block");
	newSectionEmployer.attr("sectionCat", "body");
	newSectionEmployer.attr("id", "section_" + i);
	newSectionEmployer.attr("sectionType", "subsection");
	newSectionEmployer.attr("myparentNode", "section_" + i);
////////////////

	
	if ($("[sectioncat='body'],[sectioncat='subsection']").not(":hidden").length==0){
		//THE RESUME HAS NO SECTION OTHER THAN THE HEADER
		var newSpacerSection =$("#xsl_space_between_sections").clone();
		$("#lastHeaderSection").after(newSection);
		$("#lastHeaderSection").after(newSpacerSection);
		$("#lastHeaderSection").css("display","none");
		$("#edit_menu").html("EDIT");
		$("#delete_menu").css("display","block");
		//ADDING THE orga
		if (columnarFormat == true) {
			newSection.children(":eq(0)").append(newSectionEmployer);
		}else{
			
			newSection.children(":last").after(newSectionEmployer);
		}	
	}else{
		if ($("#section_"+currentSection).attr("myparentnode")!=undefined){
			currentSection = findTopParent("section_"+currentSection);
		}
		else{
			currentSection ="section_"+currentSection;
		}
		
		if (position=="before"){
			/*if (columnarFormat == true) {
				$("#"+currentSection).children().children().before(newBlankSection);
				$("#"+currentSection).children().children().before(newSection);
			}else{*/
				$("#"+currentSection).before(newBlankSection);
				$("#"+currentSection).before(newSection);
			//}
		}
		else{
			/*if (columnarFormat == true) {
				$("#"+currentSection).children().children().after(newBlankSection);
				$("#"+currentSection).children().children().after(newSection);
			}else{*/
				
				$("#"+currentSection).after(newSection);
				$("#"+currentSection).after(newBlankSection);
			//}
		}
		//ADDING THE orga
		if (columnarFormat == true) {
			newSection.children(":eq(0)").append(newSectionEmployer);
		}else{
			
			newSection.children(":last").after(newSectionEmployer);
		}	
	}
		
	showEditor(i,"hybrid",position);
	is_adding = true;
	return i;
	
}

function showNewEmployerForm(currentSection, position,experienceEditing){
	
	$("#loadingAddEmployer").show();
	unbindSectionEvent(currentSection);
	//removeMenu(currentSection);

	
	var newSection = $("div[sectioncat='duplicate'][sectiontype='employer']").clone();
	var newId = findMaxSection(); 
	var i = parseInt(newId) + 1;
	
	if (newSection.length==0){
		alert("You must define a style before you can add an new employer. ");
	}else{
		newSection.css("display", "block");
		newSection.attr("sectionCat", "body");
		newSection.attr("id", "section_" + i);
		newSection.attr("sectionType", "employer");
		newSection.attr("myparentNode", "section_" + currentSection);
		
		var newBlankSection = $("#spacer").clone();
		newBlankSection.css("display", "block");
	
		if ($("#section_"+currentSection).attr("myparentnode")!=undefined){
			currentSection = findTopParent("section_"+currentSection);
		}
		else{
			currentSection ="section_"+currentSection;
		}
		newSection.attr("myparentNode",   currentSection);
	
		if (columnarFormat == true) {
			if (position!='inplace') $("#"+currentSection).children(":eq(0)").append(newBlankSection);
			$("#"+currentSection).children(":eq(0)").append(newSection);
		}else{
			
			if (position!='inplace') $("#"+currentSection).children(":last").after(newBlankSection);
			$("#"+currentSection).children(":last").after(newSection);
		}	
	
		showEditor(i,"employer",position);
		//$.scrollTo($("#section_"+i));
		is_adding = true;
		$("#loadingAddEmployer").hide();
		return i;
	}
	
}

function showNewOrganizationForm(currentSection,position){
	
	$("#loadingAddOrganization").show();
	unbindSectionEvent(currentSection);
	//removeMenu(currentSection);

	var newSection = $("div[sectioncat='duplicate'][sectiontype='subsection']").clone();
	var newId=  findMaxSection(); //$("div[id^='section_']:last").attr("id").split("_");
	var i = parseInt(newId)+1;
	
	newSection.css("display","block");
	newSection.attr("sectionCat","body");
	newSection.attr("id","section_"+i);
	newSection.attr("sectionType","subsection");
	
	var newBlankSection = $("#spacer").clone();
	newBlankSection.css("display", "block");

	if ($("#section_"+currentSection).attr("myparentnode")!=undefined){
		//currentSection = findTopParent("section_"+currentSection);
			currentSection =$("#section_"+currentSection).attr("myparentnode");
	}
	else{
		currentSection ="section_"+currentSection;
	}
	newSection.attr("myparentNode",currentSection);
	
	
	if (columnarFormat == true) {
		$("#"+currentSection).children(":eq(0)").append(newBlankSection);
		$("#"+currentSection).children(":eq(0)").append(newSection);
	}else{
		
		$("#"+currentSection).children(":last").after(newBlankSection);
		$("#"+currentSection).children(":last").after(newSection);
	}	
	
	
	showEditor(i,"subsection",position);
	//$.scrollTo($("#section_"+i));
	$("#loadingAddOrganization").hide();
	is_adding = true;

}

function strip_ortag($text){
	
	if ($text!=null){
	var rx=new RegExp("<ortag[^>]*>(.*?)</ortag>","i");
	$text=$text.replace(rx,"$1");
	}
	return $text;
}

function findMaxSection(){
	var max=0;
	var sectionsList = $("div[id^='section_']");//.attr("id").split("_");
	for (var i=0; i<sectionsList.length; i++){
		var currentIndex = sectionsList[i].id.split("_");
		if (parseInt(currentIndex[1])>max) max = parseInt(currentIndex[1]);
	}
	return max;
}
function setLabels(field,fiedInForm,id,tabindex){
	unhoverElements();  // Added to remove orange highlighting in IE7.
	
			SpellChecker.deactivate();
			var theFieldValue		= $("span[id='xsl_"+field+"']","#section_"+id).html();
			if (tabindex==undefined) tabindex=1;
			
			//theFieldValue = SpellChecker.removeSpellCheckErrorTag(theFieldValue);

			//create the input fields
			var labelStyle="text-align:"+$("span[id='xsl_"+field+"']","#section_"+id).css("text-align");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-family")!=undefined) labelStyle += ";font-family:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-family");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-weight")!=undefined) labelStyle += ";font-weight:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-weight");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-style")!=undefined) labelStyle += ";font-style:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-style");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-size")!=undefined)labelStyle += ";font-size:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-size");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-variant")!=undefined)labelStyle += ";font-variant:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-variant");
			if ($("span[id='xsl_"+field+"']","#section_"+id).css("letter-spacing")!=undefined)labelStyle += ";letter-spacing:"+$("span[id='xsl_"+field+"']","#section_"+id).css("letter-spacing");
			
			var clearVal =$("span[id='xsl_"+field+"']","#section_"+id).parent().css("clear");
			var currentParent = $("span[id='xsl_"+field+"']","#section_"+id).parent();
		  //  $(currentParent).css("padding-top","4px");
			//set the height of the input labels. we have to keep it 100% otherwise the employer description will cover the input boxes
		    $(currentParent).css("height","100%"); 
		    
		    //get the font family to put in the input boxes
		    var inputFontFamily = "";
		    if ($("span[id='xsl_"+field+"']","#section_"+id).css("font-family")!=undefined)
		    	{
		    		inputFontFamily += "font-family:"+$("span[id='xsl_"+field+"']","#section_"+id).css("font-family")+";";
		    	}
		  
			//make sure that the inputs are properly indented
		    //BUT WE DON"T WANT TO CHANGE THE SECTION NAME INDENTATION
		    if (field!="section_name"){
		    	$(currentParent).css("padding-left", $("#xsl_section_data").parent().css("padding-left"));
		    }
		    
		    var parentStyle =currentParent.attr("style");
		    
		    var parentSectionWidth = $(currentParent).width();
		    var pageWidth = $("div[id^='margins_']").width();
		    
		    var clearBoth = "";
			if (clearVal == 'both') {
				//clearBoth = "clear:both;"
			}
		    
		    //get the div alignment
		    var divParentAlign = $("span[id='xsl_"+field+"']","#section_"+id).css("text-align");
			var styleInputAlign = "float:left;";
			if (divParentAlign=="center")
			{
				//styleInputAlign = "margin:0px 2px 2px 40%;";
			}
			else if (divParentAlign=="right")
			{
				styleInputAlign = "float:right;";
			}
		    
			
			//columnar resume
			var colWidth = 150;
			//var widthField=$("input[id='"+fiedInForm+"']","#section_"+id).width()-4;
			if (columnarFormat==true){
				if (field=="section_name"){
					colWidth = currentParent.parent().width()-5;
					$("span[id='xsl_"+field+"']","#section_"+id).css('width', "100%");
					$("span[id='xsl_"+field+"']","#section_"+id).css('clear', "both");
					$("span[id='xsl_"+field+"']","#section_"+id).css('float', "left");
					$("span[id='xsl_"+field+"']","#section_"+id).parent().css('text-decoration', "none"); //there is a problem with text decoration. it is not inherited
					$("div[orstyle='borderUnderSectionHeaderStyle']","#section_"+id).css("clear","both"); //line under headers
				}
				else
				{
					//experience section 7 - date on the left 
					if (field=="employer_dateRange"){
						colWidth = $("span[id='xsl_section_name']","#section_"+id).width();
						if (parseInt(colWidth)>0)
						{
							if (colWidth>150)
							{
								colWidth = 150;
							}
							
							var dateRangePosition = $("span[id='xsl_"+field+"']","#section_"+id).css('position');
							if (dateRangePosition=="absolute")
							{
								$("span[id='xsl_"+field+"']","#section_"+id).css('margin-top',"15px");
							}
						}
						else
						{	
							colWidth = 110;
						}
						
					}
					$("span[id='xsl_"+field+"']","#section_"+id).parent().css("clear","both");
					//$.browser.msie
					if (!$.browser.msie)
					{
						$("span[id='xsl_"+field+"']","#section_"+id).css("display","inline-block");	
					}
					 if (divParentAlign=="right")
					{
						$("span[id='xsl_"+field+"']","#section_"+id).css("clear","right");	
						if ($.browser.msie)
						{
							$("span[id='xsl_"+field+"']","#section_"+id).css("display","inline");	
							$("span[id='xsl_"+field+"']","#section_"+id).css("float","none");
						}
						else
						{
							$("span[id='xsl_"+field+"']","#section_"+id).css("float","right");
						}
					}
					 else
					 {
						 $("span[id='xsl_"+field+"']","#section_"+id).css("float","left");	
					 }
				}
				
				//build the box for the sections 
				$("span[id='xsl_"+field+"']","#section_"+id).html('<div  class="or20_InputBox" id="boxInput_'+field+'" style="width:'+colWidth+'px;'+clearBoth+''+styleInputAlign+'">\
						<div class="or20_InputBoxTopLabel" id="labelInput'+fiedInForm+'"></div>\
							<input type="text" tabindex="'+tabindex+'" style="width:'+colWidth+'px;padding-left:0px;text-align:left;'+inputFontFamily+'" name="'+fiedInForm+'" id="'+fiedInForm+'" value="" >\
						</div>\
						');
				
						
			}else{
				//starndard resume
				colWidth = 190;
				if (field=="section_name"){
					colWidth = 290;
					$("span[id='xsl_"+field+"']","#section_"+id).parent().attr("style","");
					$("span[id='xsl_"+field+"']","#section_"+id).attr("style","");
					$("span[id='xsl_"+field+"']","#section_"+id).css('width', "100%");
					$("span[id='xsl_"+field+"']","#section_"+id).css('clear', "both");
					$("span[id='xsl_"+field+"']","#section_"+id).css('float', "left");
					$("span[id='xsl_"+field+"']","#section_"+id).parent().css('text-decoration', "none"); //there is a problem with text decoration. it is not inherited
					$("div[orstyle='borderUnderSectionHeaderStyle']","#section_"+id).css("clear","both"); //line under headers
				}
				else
				{
					$("span[id='xsl_"+field+"']","#section_"+id).parent().css("clear","both");
					//$.browser.msie
					if (!$.browser.msie)
					{
						$("span[id='xsl_"+field+"']","#section_"+id).css("display","inline-block");	
					}
					
					 if (divParentAlign=="right")
					{
						$("span[id='xsl_"+field+"']","#section_"+id).css("clear","right");	
						if ($.browser.msie)
						{
							$("span[id='xsl_"+field+"']","#section_"+id).css("display","inline");	
							$("span[id='xsl_"+field+"']","#section_"+id).css("float","none");
						}
						else
						{
							$("span[id='xsl_"+field+"']","#section_"+id).css("float","right");
						}
					}
					 else
					 {
						 $("span[id='xsl_"+field+"']","#section_"+id).css("float","left");	
					 }
				}
				
				$("span[id='xsl_"+field+"']","#section_"+id).html('<div  class="or20_InputBox" id="boxInput_'+field+'" style="width:'+colWidth+'px;'+clearBoth+''+styleInputAlign+'">\
						<div  class="or20_InputBoxTopLabel" id="labelInput'+fiedInForm+'"></div>\
						<input type="text" tabindex="'+tabindex+'"  style="width:'+colWidth+'px;padding-left:0px;text-align:left;'+inputFontFamily+'" name="'+fiedInForm+'" id="'+fiedInForm+'" value="">\
						</div>\
						');
			}
			
			$("div[id='xsl_Section_Spacing_Under_Section_Header']","#section_"+id).css("clear","both");
			
			//delete all spaces between tags </span>&nbsp;<span>...
			//$("div","#section_"+id).parent().html($("div","#section_"+id).parent().html().replace("</span>&nbsp;<span>",'11'));
			//$("div","#section_"+id).remove(" ");
			
			//remove field separators in edit mode
			$.each($("span",$("#section_"+id)), function(idx,val){
				var valueEncoded = encodeURI($(val).html().toLowerCase());
				if (valueEncoded == ",&nbsp;" || 
					valueEncoded =="&nbsp;" || 
					valueEncoded ==" " ||
					valueEncoded =="&nbsp;&nbsp;" || 
					valueEncoded=="&nbsp;%E2%97%8A&nbsp;" ||
					valueEncoded== "&nbsp;%E2%80%A2&nbsp;" ||
					valueEncoded== "&nbsp;%E2%80%A1&nbsp;" ||
					valueEncoded== "&nbsp;~&nbsp;"
					)
				{
					 $(val).html("");
				}
			});			
			
		
			
			//SETS THE VALUE OF THE FIELD WHEN IT HAS NO VALUE
			theFieldValueEmpty = eval("label_"+field);
		    hint = eval("hint_"+field);
			if (field=="section_name"){
				switch($("#section_"+id).attr("sectiontype")){
				case "experience" :
				case "hybrid":
					theFieldValueEmpty = eval("label_"+$("#section_"+id).attr("sectiontype")+"_name");
					break;
				}
			}
			
			//$("input[id='"+fiedInForm+"']","#section_"+id).attr("mylabel",theFieldValueEmpty);	
			//set label and tooltip
			if (hint!="" && field!="section_name")
			{
				theFieldValueEmpty+=' <img src="images/or20/stylist/or20_help_Stylist.png" id="imgTip_'+fiedInForm+'" border="0" align="absmiddle" />'; 
			}
			
			$("#labelInput"+fiedInForm).html(theFieldValueEmpty);
			
			if ($("span[id='xsl_"+field+"']","#section_"+id).attr("class")=="orangeFields")
			{	
				 theFieldValue = "";
				 $("span[id='xsl_"+field+"']","#section_"+id).removeClass("orangeFields");
			}
			if (theFieldValue == "<!-- -->") theFieldValue = "";
			
			if (theFieldValue!='' && theFieldValue!=null) theFieldValue= theFieldValue.replace(/\&amp;/g,'&');
			$("input[id='"+fiedInForm+"']","#section_"+id).val(theFieldValue);
			
			
			/*	
			//sets the input fields values
			if ((theFieldValue == "") || (theFieldValue == null)) {
				
				$("input[id='"+fiedInForm+"']","#section_"+id).attr("isempty","true");
				$("input[id='"+fiedInForm+"']","#section_"+id).css("font-style","italic");
				$("input[id='"+fiedInForm+"']","#section_"+id).val(theFieldValueEmpty);
			}
				
			$("input[id='" + fiedInForm + "']").focus(function () { 
			 if (  $(this).attr("isempty")=="true"){
			  	$(this).val(''); 
				$(this).attr("isempty","false");
			  	$(this).css("font-style","normal");
			  } 
			});
			$("input[id='" + fiedInForm + "']").blur(function () { 
			  if ($(this).attr("value") == '') {
					
			  	$(this).val($(this).attr("mylabel"));
			  	$(this).attr("isempty", "true");
			  	$(this).css("font-style", "italic");
			  }
			});*/
			
			
			//show tip
			if (fiedInForm !="section_name")
			{
					showTip(id, fiedInForm, theFieldValueEmpty, hint);
			}
			
			
				$("#section_name").autocomplete("/modules/ordocument/resumeSectionName.php", {
					minChars: 0,
					max: 12,
					mustMatch: false,
					matchContains: false,
					scrollHeight: 220,
					extraParams: {
						module: $('#documentType').attr('value') + 's',
						docid: $('#documentId').attr('value')
					   },
					formatResult: function(data,position,total)
					{
						   data[0] = data[0].capitalize();
					}


				});
				
			
			next();
}


function getElementOffset(arrayElt){
	
	lastElt=0;
	//orderDisplay;
	//for (var i = 0; i < arrayElt.lenght ; i++) {
	//	tpPos = arrayElt[i].offset();
	//	if (lastElt < tpPos.top) lastElt=tpPos.top;
	//}
	arrayElt.sort(offset.top);
	return orderDisplay;
}

function showDataFCK(id,count,tabindex){

		SpellChecker.deactivate();
		fckSectionId=id;
		
		fckContent = $("span[id='xsl_section_data']", "#section_" + id).html().replace(/\s?jQuery\d+="\d+"/gi,"");
		//fckContent = SpellChecker.removeSpellCheckErrorTag(fckContent);
	///	$("span[id='xsl_section_data']", "#section_" + id).html("");
		var el = tpfck.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ;
		el.tabIndex =  tabindex;
		
		var links =displayLinks('fckResumeData',id);
		$("span[id='xsl_section_data']", "#section_" + id).parent().before(links);
		
		if ($("#bodyStyle").attr("value")!="Standard" && $("#section_"+id).attr("sectiontype") == 'general'){
			//move the textbox down the same height as the fcklinks is tall if it's a general section
			$("span[id='xsl_section_name']", "#section_" + id).parent().css("padding-top", $("#fcklinks").outerHeight());
		}
		
		//we need to set data into the section in edit mode so that the positionning works
		//if we do not set data, then the fck overlaps the text area in edit mode	
		$("#fckarea").css("position", "absolute");
		posTop = $("span[id='xsl_section_data']", "#section_" + id).parent().offset().top;
	
		var divParent = $("span[id='xsl_section_data']", "#section_" + id).parent();
		//var size=(divParent.attr('edit_size')==undefined)?50:divParent.attr('edit_size');
		//divParent.css('height', size);
		
		if ($("#bodyStyle").attr("value")=="Standard"){
		//Normal style so we need to left align the fck with the edge of the container
			posLeft = $("span[id='xsl_section_data']", "#section_" + id).parent().parent().parent().offset().left+parseInt(fckLeftPadding);
			}
			else{
		//it is a columnar resume	
		    posLeft = $("span[id='xsl_section_data']", "#section_" + id).parent().offset().left+parseInt(fckLeftPadding);
		}
		$("#fckarea").css("display", "block");
	
		//ELEMENT USES EXTENDED OFFSET FUNCTION - AT TOP OF ORDOCUMENT.JS TO SET THE POSITION
		//NOTE THIS FUNCTION TAKES THE SYNTAX .OFFSET({LEFT:XXX, TOP:YYY}) - SO WE MAY WANT
		//TO USE IT WHEN WE NEED TO POSITION THE FCK TO THE LEFT WITH COLUMNAR RESUMES.
		$("#fckarea").offset({
			left: posLeft,
			top: posTop
		});
	
		
		SetFCKContent("tpfck", fckContent);
		var height = tpfck.Height;
		if (isMSIE())
			height = tpfck.EditingArea.IFrame.offsetHeight;
		//alert('Test1: height ' + height);


resizeFckArea(height,id,"fckResumeData");
  

}

function showDescriptionFCK(id,count,showFck,tabIndex){
		//ELEMENT USES EXTENDED OFFSET FUNCTION - AT TOP OF ORDOCUMENT.JS TO SET THE POSITION
		//NOTE THIS FUNCTION TAKES THE SYNTAX .OFFSET({LEFT:XXX, TOP:YYY}) - SO WE MAY WANT
		//TO USE IT WHEN WE NEED TO POSITION THE FCK TO THE LEFT WITH COLUMNAR RESUMES.
		//Sets the global variable required by the FCK
		fckSectionId=id;
		var el = tpfck2.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ;
		el.tabIndex =  tabIndex;
				
		//get the section padding
		var paddingSection="3px;";
		var paddingDescription = "3px";
		if ($("span[id='xsl_employer_description']", "#section_" + id).parent().css("padding-left")!=undefined) 
		{
			paddingSection =  $("span[id='xsl_employer_description']", "#section_" + id).parent().css("padding-left");
		}

		paddingDescription=parseInt(paddingSection);
		
		
		var sectionType = $("span[id='xsl_employer_description']", "#section_" + id).parent().parent().parent().attr("sectiontype");
		$("span[id='xsl_employer_description']", "#section_" + id).parent().before('\
				<div id="showEmployerDescriptionLink"  style="margin-left:'+paddingDescription+'px;width:100%;float:left;clear:both;height:100%;display:none;padding:5px 0px;"><span id="label_AddDescription">\
					<img src="/images/or20/or20_Menu_Section_Item_Blue.png" border="0" id="img_AddDescription" align="absmiddle"  /> <a id="linkShowCompanyDescription" href="javascript:void(0);" style="font-size:13px;">Show Company Description</a></span>\
				</div>\
				<div  id="employerDescriptionLabelBoxId" style="margin:2px 0px 2px 0px;margin-left:'+paddingDescription+'px;float:left;clear:both;border:2px solid #5593C3;">\
						<div  class="or20_InputBoxTopLabel" id="adddescription">\
						'+label_employer_description +' (Optional)  <img src="images/or20/stylist/or20_help_Stylist.png" id="imgTip_CompanyDescription" border="0" align="absmiddle" />\
						</div>\
					</div>');
		
		
		$("span[id='xsl_employer_description']", "#section_" + id).parent().attr("id","toggledescription");
		
		//get the toggle style
		$("#toggledescription").css("float","left");
		if (isMSIE())
		{
			$("#toggledescription").css("clear","both");
		}
		else
		{
			$("#toggledescription").css("clear","both");
		
		}
		
		//posLeft = $("#toggledescription").offset().left+parseInt(fckLeftPadding);
		posLeft = $("#employerDescriptionLabelBoxId").offset().left+1;
		posTop = $("#employerDescriptionLabelBoxId").offset().top+22;
		
		//hide the description by default
		fckEmployerContent = $("span[id='xsl_employer_description']", "#section_" + id).html();
		
		//there is a company description by default
		$("#toggledescription").show();
		$("#fckarea_employer_description").show();
		$("#fckarea_employer_description").css("position", "absolute");
		$("#fckarea_employer_description").offset({
				left: posLeft,
				top: posTop
			});
		
		SetFCKContent("tpfck2", fckEmployerContent);
		

		var fckEditorDescWidth = $("#fckResumeDescription___Frame").width();
		var fckEditorDescHeight = $("#fckResumeDescription___Frame").height();

		$("#fckarea_employer_description").css("width", fckEditorDescWidth-2);
		$("#fckResumeDescription___Frame").css("width", fckEditorDescWidth-2);
		$("#employerDescriptionLabelBoxId").css("width", fckEditorDescWidth-6); //the border if not part of the box
		
		
		//hide the company description if there is no content
		if (fckEmployerContent == "") 
		{
			$("#showEmployerDescriptionLink").show();
			$("#employerDescriptionLabelBoxId").hide();
			$("#fckarea_employer_description").hide();
			$("#toggledescription").hide();	
		}
		
		//show company description 
		$("#linkShowCompanyDescription").click(function(event) {
			$("#showEmployerDescriptionLink").hide();
			$("#employerDescriptionLabelBoxId").show();
			$("#toggledescription").show();	
			$("#fckarea_employer_description").show();
			SetFCKContent("tpfck2", "");
	});
		
	showTip(id,"CompanyDescription",'',"Enter company description here"); 
		
		//var height = tpfck2.Height;
	/*	if (isMSIE())
		{
			height = tpfck2.EditingArea.IFrame.offsetHeight;
		}*/

		//alert(fckEditorDescHeight);
		//resizeFckArea(fckEditorDescHeight,id,"fckarea_employer_description");
		
		
		if (FCKBrowserInfo.IsSafari)
		{
			triggerNext(fckSectionId);
		}
}

function displayOrganization(id, sectionType, count){
	fckSectionType=sectionType;
	
	var arrayElet = new Array ($("span[id='xsl_organization_name']","#section_"+id),
			$("span[id='xsl_organization_dateRange']","#section_"+id),
			$("span[id='xsl_section_data']","#section_"+id));
		
	//section data will always be on the last position for hybrid section. 
	
	//arrayElet = $(arrayElet).sort("offsetTop", "asc");
//	if (isMSIE())
//		arrayElet = $(arrayElet).sort(["offsetTop","offsetLeft"], "asc");
//	else
//		arrayElet = $(arrayElet).sort("offsetTop", "asc");
	
	
	var tabindex=1;
	var n = [];
	   
	jQuery.each($(arrayElet), function(i, val){
		var labels = $(this).attr("id").split("_");
		
		if (labels[2] == "data") {
			queue(function(){
				tabindex++;
				showDataFCK(id,count,tabindex);
			});
		}
		else {
			queue(function(){
				tabindex++;
				setLabels('organization_' + labels[2], labels[2], id, tabindex);
				
			});
		}
	});
}

function displayEmployerMultipleJobs(id, sectionType, count){
	
	fckSectionType=sectionType;
	
	//strip all nbsp between </span>&nbsp;<span>
	jQuery($("span","#section_"+id).parent()).each(function(i){
		  jQuery(this).html(jQuery(this).html().replace(/\&nbsp;/g," "));
		});
	
	//add a dummy content if the input fields are empty. the offset top is wrong if there is an empty field
	var xslEmployerNameId = $("span[id='xsl_employer_name']","#section_"+id);
	var xslEmployerLinkUrlId = $("span[id='xsl_employer_linkURL']","#section_"+id);
	var xslEmployerLocationId = $("span[id='xsl_employer_location']","#section_"+id);
	var xslEmployerDateRangeId = $("span[id='xsl_employer_dateRange']","#section_"+id);
	
	var xslEmployerNameHtml = xslEmployerNameId.html();
	var xslEmployerLinkUrlHtml = xslEmployerLinkUrlId.html();
	var xslEmployerLocationHtml = xslEmployerLocationId.html();
	var xslEmployerDateRangeHtml = xslEmployerDateRangeId.html();
	
	if (xslEmployerNameHtml=="") xslEmployerNameId.html("Employer Name");
	if (xslEmployerLinkUrlHtml=="") xslEmployerLinkUrlId.html("Employer URL");
	if (xslEmployerLocationHtml=="") xslEmployerLocationId.html("Employer Location");
	if (xslEmployerDateRangeHtml=="") xslEmployerDateRangeId.html("Date Range");
	
	var arrayElet = new Array ($("span[id='xsl_employer_name']","#section_"+id),
			$("span[id='xsl_employer_linkURL']","#section_"+id),
			$("span[id='xsl_employer_location']","#section_"+id),
			$("span[id='xsl_employer_dateRange']","#section_"+id),
			$("span[id='xsl_employer_description']","#section_"+id));
	
	arrayElet = $(arrayElet).sort("offsetTop", "asc");
	
//	if (isMSIE())
//		arrayElet = $(arrayElet).sort(["offsetTop","offsetLeft"], "asc");
//	else
//		arrayElet = $(arrayElet).sort("offsetTop", "asc");
	

		var tabindex=1;
		var n = [];
		   
		jQuery.each($(arrayElet), function(i, val){
			var labels = $(this).attr("id").split("_");
			
			if (labels[2] == "description") {
				   queue(function(){
					   tabindex++;
					   showDescriptionFCK(id,count,0,tabindex);
				});
			}
			else 
				 {
					queue(function(){
						tabindex++;
						setLabels('employer_' + labels[2], labels[2], id, tabindex);
						
					});
				}
		});
					
		if (xslEmployerNameHtml=="") xslEmployerNameId.html("");
		if (xslEmployerLinkUrlHtml=="") xslEmployerLinkUrlId.html("");
		if (xslEmployerLocationHtml=="") xslEmployerLocationId.html("");
		if (xslEmployerDateRangeHtml=="") xslEmployerDateRangeId.html("");
}

function displayLinks(fckName,sectionId){
	switch(fckName){
	case "fckResumeData":
		instance= "tpfck";
		break;
	case "fckResumeDescription":
		instance= "tpfck2";
		break;
	case "fckResumeHeadline":
		instance= "tpfckHeadline";
		break;
	default:
		instance ="FCK.Name";
		break;
	}

	var sectionType =$("#section_"+sectionId).attr("sectiontype");
	var sectionName= $("#section_name").attr("value");
	var infobyteText = $("#infobyte","#section_"+sectionId).html();
	var infobyteButton = "or20_Infobytes_Button.png";
	if ( infobyteText != undefined && jQuery.trim(infobyteText) != '')
	{
		infobyteButton = 'or20_Infobytes_Button_active.png'
	}
	form ='<div class="fcklinks" id="fcklinks" style="display:block; text-align:right;clear:both;height:20px;padding-top:3px;margin-bottom:4px;">';
	form +='<a href="javascript:void(0)" onclick="showFCKExamples(\''+instance+'\',\''+sectionId+'\')" ><img src="images/or20/or20_Examples_Button.png" border="0" /></a>';
	form +='<a href="javascript:void(0)" onclick="showActionWords(\''+instance+'\',\''+sectionId+'\',\''+sectionType+'\',\''+sectionName+'\')" ><img src="images/or20/or20_ActionVerbs_Button.png" border="0" style="margin:0px 3px;" /></a>';
	form +='<a href="javascript:void(0)" onclick="showInfobytePopup(\''+instance+'\',\''+sectionId+'\',\''+sectionType+'\')" ><img id="fckInfobyteButton" src="images/or20/'+infobyteButton+'" border="0" style="margin-right:2px;" /></a>';
	form +='</div>';
	return form;
}

function displayEmployer(id, sectionType, count){
	fckSectionType=sectionType;

	//strip all nbsp between </span>&nbsp;<span>
	/*
	jQuery($("span","#section_"+id).parent()).each(function(i){
		  jQuery(this).html(jQuery(this).html().replace(/\&nbsp;/g," "));
		});
	*/	
	
	
	//TODO: Height10
	//var divParent = $("span[id='xsl_section_data']", "#section_" + id).parent();
	//divParent.css('height', divParent.attr('edit_size') + "px");

	//add a dummy content if the input fields are empty. the offset top is wrong if there is an empty field
	var xslEmployerNameId = $("span[id='xsl_employer_name']","#section_"+id);
	var xslEmployerLinkUrlId = $("span[id='xsl_employer_linkURL']","#section_"+id);
	var xslEmployerTitleId = $("span[id='xsl_employer_title']","#section_"+id);
	var xslEmployerLocationId = $("span[id='xsl_employer_location']","#section_"+id);
	var xslEmployerDateRangeId = $("span[id='xsl_employer_dateRange']","#section_"+id);
	
	var xslEmployerNameHtml = xslEmployerNameId.html();
	var xslEmployerLinkUrlHtml = xslEmployerLinkUrlId.html();
	var xslEmployerTitleHtml = xslEmployerTitleId.html();
	var xslEmployerLocationHtml = xslEmployerLocationId.html();
	var xslEmployerDateRangeHtml = xslEmployerDateRangeId.html();
	
	if (xslEmployerNameHtml=="") xslEmployerNameId.html("Employer Name");
	if (xslEmployerLinkUrlHtml=="") xslEmployerLinkUrlId.html("Employer URL");
	if (xslEmployerTitleHtml=="") xslEmployerTitleId.html("Employer Title");
	if (xslEmployerLocationHtml=="") xslEmployerLocationId.html("Employer Location");
	if (xslEmployerDateRangeHtml=="") xslEmployerDateRangeId.html("Date Range");
		
	var arrayElet = new Array ($("span[id='xsl_employer_name']","#section_"+id),
			$("span[id='xsl_employer_linkURL']","#section_"+id),
			$("span[id='xsl_employer_title']","#section_"+id),
			$("span[id='xsl_employer_location']","#section_"+id),
			$("span[id='xsl_employer_description']","#section_"+id),
			$("span[id='xsl_employer_dateRange']","#section_"+id),
			$("span[id='xsl_section_data']","#section_"+id));
			
			//WE NEED TO KNOW THE ORDER IN WHICH THE ELEMENTS SHOULD BE DISPLAYED ON THE PAGE
			//ONCE THE ELEMENTS ARE ORDERED ACCORDING TO THE ORDER IN WHICH THEY ARE DISPLAYED IN 
			//THE TRANSFORMATION, WE QUEUE THEM TO MAKE SURE EACH ELEMENT IS DIPLAYED BEFORE  
			//THE FOLLOWING ELEMENT IS DISPAYED. THIS ALLOW TO DETERMINE THE CORRECT POSITIONNING
			//OF EACH ELEMENT AND ALLOWS THE FCK(S) TO B DISPLAYED WITH THE PROPER SIZE AFTER THE
			//CALLBACK FUNCTION AUTOGROW IS EXECUTED
	
			arrayElet = $(arrayElet).sort("offsetTop", "asc");
//			if (isMSIE())
//				arrayElet = $(arrayElet).sort(["offsetTop","offsetLeft"], "asc");
//			else
//				arrayElet = $(arrayElet).sort("offsetTop", "asc");
			
			var tabindex=1;
			var n = [];
			   
			jQuery.each($(arrayElet), function(i, val){
				var labels = $(this).attr("id").split("_");
				
				if (labels[2] == "description") {
					   queue(function(){
						   tabindex++;
						showDescriptionFCK(id,count,0,tabindex);
					});
				}
				else if (labels[2] == "data") {
						queue(function(){
							tabindex++;
							showDataFCK(id,count,tabindex);
							
						});
					
					}
				else {
						queue(function(){
							tabindex++;
							setLabels('employer_' + labels[2], labels[2], id, tabindex);
							
						});
					}
			});
		
		//reset the fields
		if (xslEmployerNameHtml=="") xslEmployerNameId.html("");
		if (xslEmployerLinkUrlHtml=="") xslEmployerLinkUrlId.html("");
		if (xslEmployerTitleHtml=="") xslEmployerTitleId.html("");
		if (xslEmployerLocationHtml=="") xslEmployerLocationId.html("");
		if (xslEmployerDateRangeHtml=="") xslEmployerDateRangeId.html("");
}

function displayJob(id, sectionType, count){
	fckSectionType=sectionType;
	
	//strip all nbsp bettween span
	jQuery($("span","#section_"+id).parent()).each(function(i){
		  jQuery(this).html(jQuery(this).html().replace(/\&nbsp;/g," "));
		});
	
	
	var arrayElet = new Array (
			$("span[id='xsl_job_title']","#section_"+id),
			$("span[id='xsl_job_jobLocation']","#section_"+id),
			$("span[id='xsl_job_jobDateRange']","#section_"+id),
			$("span[id='xsl_section_data']","#section_"+id));
			
	if (isMSIE())
		arrayElet = $(arrayElet).sort(["offsetTop","offsetLeft"], "asc");
	else
		arrayElet = $(arrayElet).sort("offsetTop", "asc");
	

					
			var j=0;
			var n = [];
			var tabindex  =1;
			jQuery.each($(arrayElet), function(i, val){
				var labels = $(this).attr("id").split("_");
				
				
				if (labels[2] == "data") {
						queue(function(){
							tabindex++;
							showDataFCK(id,count,tabindex);
						});
					}
				else {
						queue(function(){
							tabindex++;
							setLabels('job_' + labels[2], labels[2], id,tabindex);
							
							
						});
					}
			});
			
}

function HideHeader(id,sectionType){
	if (sectionType=="recipient"){
		//WE DON'T ACTUALY HIDE THE RECIPIENT. WE JUST SET THE DATA TO EMPTY VALUE
		if (($("#opening").val()=='') || ($("#opening").val()==$("#opening").attr("mylabel"))){
			//THE OPENING CANNOT BE EMPTY
			alert("You can hide the recipient, but the letter opening cannot be empty.");
			try {
				$("#opening").focus();
			} catch ( err ) {}
		}
		else{
			dataToSave = $("#general_form").serialize();
			tp = dataToSave.split("&");
			var cleanData='';
			for( var i=0;i< tp.length; i++){  	
		     	var pos = tp[i].indexOf("=");
				var index = tp[i].substr(0,pos);
				var value =tp[i].substr(pos+1);
	
		     	switch (index){
					case "opening":
						cleanData+="&opening="+value;
					break;
					default:
						cleanData+="&"+index+"=";	
					break;
		     	}
			}
			dataToSave=cleanData;
			if (position==undefined) loaction="inplace";
			$('#divWhilePosting').html('<img src="/images/or20/or20_ajax-loader_small.gif" border="0" />');
			var j = getPosition('section_'+id,sectionType,position);
					
			$.ajax({type:'POST',
				   async: false,
				   dataType: 'text',
			   	   url: '/modules/ordocument/save.php',
			   	   data:{ documentType: $('#documentType').attr("value"),
					   documentId :  $('#documentId').attr("value"),
					   sectionType: sectionType,
					   sectionIndex: j,
					   position: position,
					   adding: is_adding,
					   dataToSave: dataToSave},
			 	   success: function(successData){
					   $('#divWhilePosting').html("");
					   $('#moduleCanvas').replaceWith(successData);
					   initDocAjax();
					   is_adding= false;},
				   error: function(errorData){
				         CancelEditor(id,sectionType,dataLoaded);}
			});
		}
	}else{
		$.ajax({
			type: 'POST',
			url: '/modules/ordocument/stylist.php',
			data: {
				action: 'resetSingleHeaderPosition',
				section: sectionType,
				module: $('#documentType').attr('value') + 's',
				docid: $('#documentId').attr('value')
			},
			success:function(data){
				$('#moduleCanvas').replaceWith(data);
				initDocAjax();
			}
		});
	}
	removeEditOverlay();
	
}


function showEditor(id,sectionType,position)
/* displays the fck editor . the content is loaded from FCKeditor_OnComplete*/
{	//.children("span").children("table")
	//fadeOutOtherSections(id, true);
	var isHeader = false;
	
	editableSectionId = "section_"+id;
	if (position==undefined) position="inplace";
	//editMode();
	var nbLines =1;
	
	unbindSectionEvent(id);

	SpellChecker.deactivate();
	var tp= $("#section_"+id).html();
	//tp = SpellChecker.removeSpellCheckErrorTag(tp);
	
	//Sets the section name to the input box
	var sectionName=strip_ortag( $("span[id='xsl_section_name']","#section_"+id).html());
	fckSectionName = sectionName;
	if ( (sectionType=='job') || (sectionType=='subsection') || (sectionType=='employer')){
		if ((sectionType=='job')){
			var parentId=$("#"+$("#section_"+id).attr("myparentnode")).attr("myparentnode");
			fckSectionName=$("#xsl_section_name","#"+parentId).html();
		}
		else{	
			fckSectionName=$("#xsl_section_name","#"+$("#section_"+id).attr("myparentnode")).html();
		}
	   
	}
	
	
	
	setLabels('section_name','section_name',id,1);
	var link='';
	
	switch(sectionType){
	case 'hybrid': 
		if ((is_adding==true) || (($("div[id^='section_'][myparentnode='section_"+id+"']").length<=1))){
			var currentSections = $("#section_" + id).children();
			$("#section_" + id).wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
			if ($("div[id^='section_'][myparentnode='section_"+id+"']").length==0){
				showNewOrganizationForm(id, "inplace");
			/*	queue(function(){
					serializeForm(id,sectionType,link,position);
				});
				queue(function(){
					addEditOverlay(editableSectionId);
					});
					next();
					*/
			}else{
					displayOrganization(id, "subsection", 0);
				
			
				queue(function(){
						serializeForm(id,sectionType,link,position);
				});
				queue(function(){
					addEditOverlay(editableSectionId);
					});
					next();
			}
		}else{
			var currentSections = $("#section_" + id).children().not("div[id^='section_']");
			currentSections.wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
			queue(function(){
				serializeForm(id,sectionType,link,position);
			});
			queue(function(){
				addEditOverlay(editableSectionId);
				});
				next();
		}
		break;
	case 'experience': 
		
	
		if ((is_adding==true) ||
				 (($("div[id^='section_'][myparentnode='section_"+id+"']").length==1) && ($("div[id^='section_'][myparentnode='section_"+id+"']").attr("sectiontype")!="employer_multiple_jobs"))
				||
				(($("div[id^='section_'][myparentnode='section_"+id+"']").length==0))){	var currentSections = $("#section_" + id).children();
			$("#section_" + id).wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
			if ($("div[id^='section_'][myparentnode='section_"+id+"']").length==0){
				experience_is_showing=true;
				showNewEmployerForm(id, "inplace");
				queue(function(){
					serializeForm(id,sectionType,link,position);
				});
				queue(function(){
					addEditOverlay(editableSectionId);
					});
					next();
			}else{
				if($("div[id^='section_'][myparentnode='section_"+id+"']").attr("sectiontype")=="employer"){
					
					displayEmployer(id, "employer", 0);
				}	
				if($("div[id^='section_'][myparentnode='section_"+id+"']").attr("sectiontype")=="employer_multiple_jobs"){
					displayEmployerMultipleJobs(id, "employer_multiple_jobs", 0);	
			
				}
			
				queue(function(){
						serializeForm(id,sectionType,link,position);
				});
				queue(function(){
					addEditOverlay(editableSectionId);
					});
					next();
			}
		}else{
			experience_name_only=true;
			var currentSections = $("span[id='xsl_section_name']","#section_" + id);//.children("#xsl_section_name");//.not("div[id^='section_'][id='xsl_Section_Spacing_Between_Employers']");
			currentSections.wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
			queue(function(){
				serializeForm(id,sectionType,link,position);
			});
			queue(function(){
				addEditOverlay(editableSectionId);
				});
				next();
		}
		
	break;
	case 'subsection':
		if ($("#general_form").length==0){
			var currentSections = $("#section_" + id).children().not("div[id^='section_']");
			currentSections.wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
		}
		displayOrganization(id, "organization", 0);
		 queue(function(){
		 	serializeForm(id,sectionType,link,position);
		 });
		 queue(function(){
				addEditOverlay(editableSectionId);
				});
				next();
		 
		break;
		
	case 'employer':
		if ($("#general_form").length==0){
		var currentSections = $("#section_" + id).children().not("div[id^='section_']");
		currentSections.wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
		}
		displayEmployer(id, "employer", 0);
		if (experience_is_showing==false){
		queue(function(){
		 	serializeForm(id,sectionType,link,position);
		});
		queue(function(){
			addEditOverlay(editableSectionId);
			});
			next();
		}
		
		break;
	
	case 'employer_multiple_jobs':
		var currentSections = $("#section_" + id).children().not("div[id^='section_']");
		currentSections.wrapAll('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
		
		displayEmployerMultipleJobs(id, sectionType, 0);
	    queue(function(){
		 	serializeForm(id,sectionType,link,position);
	    });
	    queue(function(){
	    	addEditOverlay(editableSectionId);
	    	});
	    	next();
		
		break;
	
	case 'job':
		$("#section_" + id).wrap('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');

		displayJob(id, "job",0);
		
		 queue(function(){
		 	serializeForm(id,sectionType,link,position);
		 });
		 queue(function(){
				addEditOverlay(editableSectionId);
				});
				next();
	
		break;	
	case "recipient":
		
		$("#section_" + id).wrap('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');
		showRecipientForm(id);
		queue(function(){
		 	serializeForm(id,sectionType,link,position);
		});
		queue(function(){
			addEditOverlay(editableSectionId);
			});
			next();
		
		break;
		
	case "closing":
		$("#section_" + id).wrap('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');

		showSignatureForm(id);
		queue(function(){
		 	serializeForm(id,sectionType,link,position);
		});
		queue(function(){
			addEditOverlay(editableSectionId);
			});
			next();
		break;
		
	case 'headline':
		
	//NOTE: THE FCK EDITOR OF THE HEADLINE IS SPECIAL - IT ACTUALLY NEEDS TO BE THE ENTIRE WIDTH OF THE PAGE.
	//THIS LOGIC IS NOT IMPLEMENTED YET.
		
		 showHeadlinePopup(id, sectionType, link, position);


		break;
	case 'name':
	case 'email':
	case 'phone1':	
	case 'phone2':		
	case 'phone3':			
	case 'address1':
	case 'address2':
		isHeader = true;
		$("#section_" + id).wrap('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');

		
		if ((sectionType=="address2")){
			//removed so that address is not blank when address city on one line
			//$("#section_"+id+">span").html("");
		}
		if ((sectionType=="address1")){
			//$("#section_"+id+">span").html("");
		}
		
		queue(function(){
			showContactForm(id);
		});
		 queue(function(){
		 	serializeForm(id,sectionType,link,position);
		 });
		 queue(function(){
				addEditOverlay(editableSectionId);
				});
				next();
		
	break;
		
	case 'general':
		$("#section_" + id).wrap('<form name="general_form"  id="general_form" class="generalForm" style="display:inline" ></form>');

		
		showDataFCK(id,0,2);
		
		queue(function(){
		 	serializeForm(id,sectionType,link,position);
		});
		queue(function(){
			addEditOverlay(editableSectionId);
			});
			next();
	break;
}
}

function serializeForm(id,sectionType,link,position){
       
       var formFCK;
       var form = '<div class="buttonbar" id="buttonbar" style="table-layout:fixed;height:35px;display:block;width:100%; text-align:center;marginbackground-color:rgb(233,243,255);clear:both;">\
    	   <table cellpadding="0" cellspacing="0" border="0" style="table-layout:fixed;height:35px;margin:0 auto;text-align:center;">\
       <tr>';
            switch(sectionType){
       case     "recipient":
                      form +='<td style="width:80px;text-align:left;padding:10px 0px;word-spacing:normal;letter-spacing:normal;text-transform: none;"><span class="or20_CheckButton" ><a href="javascript://" class="or20_BigButton" onclick="SaveData('+id+',\''+sectionType+'\',\''+position+'\',\'false\');"><b>Save</b></a></span></td>';
                      form +='<td style="width:44px;text-align:left;padding:10px 0px;word-spacing:normal;letter-spacing:normal;text-transform: none;"><a href="javascript://" onclick="HideHeader('+id+',\''+sectionType+'\');"><b>Remove</b></a></td>';
           break;
       case     "name":
       case    "headline":
       case    "address1":
       case    "address2":
       case    "phone1":
       case    "phone2":
       case    "phone3":
       case    "email":
    	   			form +='<td style="width:80px;text-align:left;padding:10px 0px;word-spacing:normal;letter-spacing:normal;text-transform: none;"><span class="or20_CheckButton" ><a href="javascript://" class="or20_BigButton" onclick="SaveData('+id+',\''+sectionType+'\',\''+position+'\',\'false\');"><b>Save</b></a></span></td>';
                 form +='<td style="width:44px;text-align:left;padding:10px 0px;word-spacing:normal;letter-spacing:normal;text-transform: none;"> <a href="javascript://"  onclick="HideHeader('+id+',\''+sectionType+'\');"><b>Remove</b></a></td>';
           break;
       default:
    	   			form +='<td style="width:70px;text-align:left;padding:10px 0px;word-spacing:normal;letter-spacing:normal;text-transform: none;"><span class="or20_CheckButton"><a href="javascript://" class="or20_BigButton" onclick="SaveData('+id+',\''+sectionType+'\',\''+position+'\',\'false\');"><b>Save</b></a></span></td>';
                  if ((experience_name_only==true) && ( columnarFormat==true   )){
               //form +='<br/>';
           }         break;
       }
               form +='<td nowrap style="padding-left:5px;width:60px;text-align:left;word-spacing:normal;letter-spacing:normal;text-transform: none;">or <a href="javascript://"  onclick="CancelEditor('+id+',\''+sectionType+'\');"><b>Cancel</b></a></td>\
                <td  style="width:40px; text-align:left;"><span  id="divWhilePosting" ></span></td>\
                </tr></table>\
                </div>';
                
                
       $("#general_form:last").append(form);

              dataLoaded = $("#general_form").serialize();
              //GETS THE DATA FROM THE FCK
       if ((is_adding==false) && ((sectionType == 'experience') || (sectionType == 'hybrid'))){
           dataLoaded =dataLoaded;
       }
       else if (((is_adding==true) && ((sectionType == 'experience') || (sectionType == 'hybrid'))) ||(sectionType == 'general')  || (sectionType == 'job') || (sectionType == 'employer') || (sectionType == 'subsection') ) {
           var fckContent = $("span[id='xsl_section_data']", "#section_" + id).html();
           if((fckContent!=''))
               dataLoaded += "&fck=" + encodeURIComponent(fckContent); //tpfck.GetXHTML(true)!=null) &&
           var fckEmployerContent = $("span[id='xsl_employer_description']", "#section_" + id).html();
           if ((fckEmployerContent != ''))
               dataLoaded += "&description=" + encodeURIComponent(fckEmployerContent); //tpfck.GetXHTML(true)!=null) &&
                  $("span[id='xsl_employer_description']", "#section_" + id).html("");
           $("span[id='xsl_section_data']", "#section_" + id).html("");
       }else if (sectionType == 'employer_multiple_jobs'){
           var fckEmployerContent = $("span[id='xsl_employer_description']", "#section_" + id).html();
           if ((fckEmployerContent != ''))
             dataLoaded += "&description=" + encodeURIComponent(fckEmployerContent); //tpfck.GetXHTML(true)!=null) &&
           $("span[id='xsl_employer_description']", "#section_" + id).html("");
                  }
       else if (sectionType == 'headline'){
           var fckContent = $("span[id='xsl_headline']", "#section_" + id).html();
           if((fckContent!=''))
           dataLoaded += "&fck=" + encodeURIComponent(fckContent); //tpfck.GetXHTML(true)!=null) &&
                  }else if(sectionType == 'recipient'){
           $("#buttonbar").css("padding-top", "8px"); // for some reason it was too close to the last text box so I move it down
           $("#buttonbar").css("text-align", "left");
       }
              //CLEARS THE DISPLAY QUEUE
       next();
       
       
}



function getNumberOfJobs(id,sectionType){
	
		var current_parent = $("#section_"+id).attr("myparentNode");
		//gets the position of job
		var positionSubnode = $("div[myparentnode="+current_parent+"]");
		return parseInt(positionSubnode.length);
}


function DeleteSection(id,sectionType,sectionTitle){
	
	var titleBar = "DELETE SECTION";
	var deleteContent = 'Are you sure you want to permanently delete section';
	switch (sectionType){
	case 'job':
		var titleBar = "DELETE JOB";
		var deleteContent = 'Are you sure you want to permanently delete job';
		break;
	case 'employer':
		//$("#xsl_employer_title)
		var titleBar = "DELETE EMPLOYER";
		var deleteContent = 'Are you sure you want to permanently delete employer';
		break;	
	case 'employer_multiple_jobs':	
		var titleBar = "DELETE EMPLOYER";
		var deleteContent = 'Are you sure you want to permanently delete employer';
		break;	
	case 'subsection':
		var titleBar = "DELETE ORGANIZATION";
		var deleteContent = 'Are you sure you want to permanently delete organization';
		break;	
	}
	
	unbindSectionEvent(id);
	$("body").append('<div id="deleteSectionConfirmation">\
			<p style="padding:0px 10px;">\
			<span class="error">'+deleteContent+' <b>' + sectionTitle + '</b>?</span></p>\
			<p style="margin-top: 10px; padding:10px; font-weight: bold; clear: left;"> \
				<span class="or20_DeleteButton"><a href="javascript:void(0);" id="linkDeleteSectionId" class="or20_BigButton">Delete</a>\
				</span> or <a href="javascript://" id="linkCancelDeleteSectionId">Cancel</a></p>\
			</div>');
			
	var topBarContent ='<h3 class="arrowModalWindow">' + titleBar + '</h3>';
	
	$("#linkDeleteSectionId").click(function(){
		$("#deleteEmployersLink"+id).html('<img src="/images/indicator.gif" border="0" />');
		$("#deleteSectionConfirmation").dialog('destroy');
		$("#deleteSectionConfirmation").remove();
		$("#fckarea").css("display","none");
		// set focus on any text element (to fix issue with IE showing blinking cursor even if fck is not visible)
		// FB 746 - wrapped focus event in try/catch block to prevent IE7 from raising an error.
		try
		{
			$("[type='text']").not(":hidden").focus();
		} catch ( err ) {} 
		$("#fckarea").css('top', '-1000px');
		$("#fckarea_employer_description").css('top', '-1000px');

	    $("#fckarea_employer_description").css("display","none");
	  
	    var parentSectionNode = $("#section_"+id).attr("myparentnode");
	    $("#section_"+id).html('<div class="loaderImage"></div>');
		
		var j= getPosition("section_"+id,sectionType);
		$.post("/modules/ordocument/delete.php", {
			async: false,
			documentType: $('#documentType').attr("value"),
			documentId: $('#documentId').attr("value"),
			sectionType: sectionType,
			sectionIndex: j
		}, function(successData){
			$('#moduleCanvas').replaceWith(successData);
			initDocAjax();
			
			//reload employers/jobs on the modal window
			var mainSectionId = $("#parentSectionIdHidden").val();
			var sectionEmployersJobsList= getSectionChildrenMenu("addJobEmployerDialog",mainSectionId);
			$("#listEmployersJobs").html(sectionEmployersJobsList);
			/*if((sectionType=="job")||(sectionType=="employer")||(sectionType=="employer_multiple_jobs")){
				$('#row'+id).remove();
			}*/
		});
		return true;
	});
	
	$("#linkCancelDeleteSectionId").click(function(){
		$("#deleteSectionConfirmation").dialog('destroy');
		$("#deleteSectionConfirmation").remove();
		bindSectionEvent();
		return false;
	});
			
	$("#deleteSectionConfirmation").dialog({
		title:	topBarContent,
		bgiframe: true,
		resizable: false,
		width:500,
		height:160,
		modal: true,
		close: function() {
			$(this).dialog('destroy');
			$("#deleteSectionConfirmation").remove();
			},
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});

}

function removeLabels(id,sectionType,dataToSave){
	
	var tp;
	var cleanedData="";
	var totalData="";
	if (dataToSave==undefined)
		 tp = dataLoaded.replace(/[&]nbsp;/g," ").split("&");
	else 
		tp = dataToSave.split("&");

	for( var i=0;i< tp.length; i++){  	
     	var pos = tp[i].indexOf("=");
		var index = tp[i].substr(0,pos);
		var value =tp[i].substr(pos+1);
		
		if (index!=''){
     	switch (index){
			case "fck":
				if (URLDecode(value)=="<br />") totalData+='';
				else totalData+=value;	
				cleanedData+="&"+index+"="+value;
				
			break;
			case "description":
					if (URLDecode(value)==label_employer_description) value="<!-- -->";
					$("span[id='xsl_employer_description']","#section_"+id).html(URLDecode(value));
					cleanedData+="&"+index+"="+value;
					totalData+=value;
				break;
			default:
				cleanedData+="&"+index+"="+value;
				totalData+=value;
				/*	switch (sectionType){
						
						case "closing":
							if (index=="enclosure") cleanedData+="&"+index+"="+value;
							else{
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
							}
						break;
						case "recipient":
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
								cleanedData+="&"+index+"="+value;
						break;
						case "hybrid":
						case "experience":
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							
							cleanedData+="&"+index+"="+value;
						break;
						case "general":
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
						break;
						case "employer_multiple_jobs":
							
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
						break;
						case "employer":
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
						break;
						case "job":
							
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
						break;
						case "subsection":
							if($("input[id='"+index+"']","#section_"+id).val()==$("input[id='"+index+"']","#section_"+id).attr("mylabel")) value='';
							cleanedData+="&"+index+"="+value;
							break;
						case 'name':
						case 'phone1':
						case 'phone2':
						case 'phone3':
						case 'email':
						case 'address1':
						case 'address2':
							if($("input[id='"+index+"']","#section_"+id).css("font-style")=="italic") value='';
							cleanedData+="&"+index+"="+value;
						break;
						
					}
			break;*/
		}
		}
			
		
	}
	return totalData; //cleanedData.substr(1);
}

function CancelEditor(id,sectionType,dataToSave)
{	
	editableSectionId = undefined;
	experience_is_showing=false;
	$('#divWhilePosting').html('<img src="/images/or20/or20_ajax-loader_small.gif" border="0" />');
		
		$.ajax({
			type: 'POST',
			url: '/modules/ordocument/stylist.php',
			data: {
				action:'displayPage',
				module: $('#documentType').attr('value') + 's',
				docid: $('#documentId').attr('value')
			},
			success:function(data){
				removeEditOverlay();

				// set focus on any text element (to fix issue with IE showing blinking cursor even if fck is not visible)
//				$("[type='text']").not(":hidden").focus();
				$("#fckarea").css('top', '-1000px');
				$("#fckarea_employer_description").css('top', '-1000px');

				$("#fckarea_employer_description").css("display","none");
				
				$("#fckarea").css("display","none");
				
				$('#divWhilePosting').html('');
				$('#moduleCanvas').replaceWith(data);
				initDocAjax();
//				alert("SpellChecker Status:" + SpellChecker.active);
				if ( SpellChecker.active == true )
				{
					SpellChecker.checkAsync();
				}
			}
		});
		
	//move the menu on the page
	jsMoveRightMenu(1);	
}



function FCKeditor_OnComplete( editorInstance )
/* Gets the content of the section and loads it into the FCK*/
{
	var frame = document.getElementById(editorInstance.Name + '___Frame');
	if (FCKBrowserInfo.IsSafari)
		frame.style.height = (parseInt(frame.style.height)+30) + "px";
	if (FCKBrowserInfo.IsSafari)
	{
		
	}
	try
	{
		var editingArea = frame.contentDocument.getElementById('xEditingArea').childNodes[0];
		if ( editorInstance.Name == "fckResumeDescription" || editorInstance.Name == "fckResumeData")
		{
			editingArea.style.overflow = "hidden";
		}
	
		editorInstance.EditorDocument.execCommand( 'enableObjectResizing', false, false) ;
		editorInstance.EditorDocument.execCommand( 'enableInlineTableEditing', false, false) ;
	}
	catch (e)
	{}

		//get style bullet indentation
		var bulletIndentation =  $("ul", $("#maincontent")).css("margin-left");
		var bulletType =  $("ul", $("#maincontent")).css("list-style-type");

		if (editorInstance.Name== "fckResumeData")
		{
			tpfck = FCKeditorAPI.GetInstance(editorInstance.Name); 
			// bindSectionEvent();we can't call it there because other fcks aren't loaded
			tpfck.Config['EditorAreaStyles'] = 'ul{margin-left:'+bulletIndentation+';padding-left:14px;list-style-type: '+bulletType+';}';
		}
		else if (editorInstance.Name== "fckResumeDescription")
		{
			tpfck2 = FCKeditorAPI.GetInstance(editorInstance.Name); 
			tpfck2.Config['EditorAreaStyles'] = 'ul{margin-left:'+bulletIndentation+';padding-left:14px;}';
			setFckEditorDefaultFont(tpfck2);
		}
		else if (editorInstance.Name == "fckResumeHeadline")
		{
			tpfckHeadline = FCKeditorAPI.GetInstance(editorInstance.Name);
			tpfckHeadline.Config['EditorAreaStyles'] = 'ul{margin-left:'+bulletIndentation+';padding-left:14px;}';
			tpfckHeadline.Events.AttachEvent('OnAfterSetHTML', setFckEditorDefaultFont);
			setFckEditorDefaultFont(tpfckHeadline);
		}
}




function diffArrays (Before, After) {
	 var arrDiff =Array();
	 var j=0;
	var before = Before.split("&");
	var after = After.split("&");
	
	for (var i=0; i< before.length;i++){
		//for (var j; j< after.length;j++){
			if (before[i]!=after[i]){
				arrDiff[j] = after[i];
				j++;
			}
		//}
	}
  
  return arrDiff;
}

function getPosition(id,sectionType,position){
	  var arrayIndex = $("div[sectioncat='body']");
	  if (sectionType=="job"){
	  		//var top_parent = $('div[id='+$("#"+id).attr("myparentNode")+']').attr("myparentNode");
	  		
			var current_parent = $("#"+id).attr("myparentNode");
			r=getPosition(current_parent,"employer",position);
		
			//gets the position of job
			var positionSubnode = $("div[myparentnode="+current_parent+"]");
			var l=0;
			for (l=l; l<positionSubnode.length;l++){
				if (positionSubnode[l].id==id) {
					break;
				}
				
			}
			l++;
			index=r+"_"+l;
	  }
	 else if ((sectionType=="employer_multiple_jobs")||(sectionType=="employer")||(sectionType=="subsection")){
			var current_parent = $("#"+id).attr("myparentNode");
			var m=0;
			//gets the position of experience node or hybrid
			for (var k=0; k<arrayIndex.length;k++){
				is_subsection =arrayIndex[k].id.split("_");
				if (is_subsection.length==3){ m--;}
				
				if (arrayIndex[k].id==current_parent) {
					m++;
					break;
				}
				m++;
			}
			//gets the position of employer or subsection
			var positionSubnode = $("div[myparentnode="+current_parent+"]");
			var l=0;
			for (l=l; l<positionSubnode.length;l++){
				if (positionSubnode[l].id==id) {
					
					break;
				}
			}
			l++;
			index=m+"_"+l;
		}else{
			var j=0;
			var index=0;
			for (j=j; j<arrayIndex.length;j++){
				is_subsection =arrayIndex[j].id.split("_");
				
				if (is_subsection.length==3){ index--;}
				
				if (arrayIndex[j].id==id) {
					if (position!="after") index++;
					break;
				}
				index++;
			}
			
		
		}
	  	if (index==0) index=1;
		return index;
}


function getIndex(j,sectionType){
	//J is the position in the xml, such as 4_1 or 3. We need to find the section_id
	//associated with the xml index to be able ot open the section in 
	
	
	  var arrayIndexHeader = $("div[sectioncat='header']");
	  var arrayIndex = $("div[sectioncat!='header'][sectioncat]");
	  var m=0,l=0,k=0;
	  var index='';
	  for (var i = 0; i <= arrayIndex.length; i++) {
	  	if (($(arrayIndex[i]).attr("sectionType") == "employer_multiple_jobs") || ($(arrayIndex[i]).attr("sectionType") == "employer") || ($(arrayIndex[i]).attr("sectionType") == "subsection")) {
	  		//increments the employer or subsection or employer_multiple_jobs counter
	  		l++;
			index="_"+l;
			
		}
		else if($(arrayIndex[i]).attr("sectionType")=="job"){
			
			
			//increments the jobs counter
			k++;
			index="_"+l+"_"+k;
			
		}else{
			//increments the section counter
		  	
			m++;
			l=0;
			k=0;
			index='';
			
		}
		if (m+index == j) {
		//3_1 == 3_1 we have found the proper section_id
			var v = 0; 

			if (sectionType=="employer_multiple_jobs"){
				v = parseInt(arrayIndexHeader.length) + parseInt(i);// +1;
			}
			else{
				v = parseInt(arrayIndexHeader.length) + parseInt(i);// +1;
			}
			return v;
		}
	  }
	  return ;
}


function SaveData(id,sectionType,position, isSpellChecker)
{
	
	unbindSectionEvent(id);
//saves the data for general form
	var newId= id;
	var new_data2='';
	var new_data='';

	var dataToSave = null;

	
	if (isSpellChecker==true){
		dataToSave = SpellChecker.serialize(id, sectionType);
	
	}
	else{
		dataToSave = $("#general_form").serialize();
		
		
		if ((is_adding==false) && ($("div[id^='section_'][myparentnode='section_"+id+"']").length>1) && ((sectionType == 'experience') || (sectionType == 'hybrid'))){
			dataLoaded =dataLoaded;
		}
		else if (( ($("div[id^='section_'][myparentnode='section_"+id+"']").length==1)&& ((sectionType == 'experience') || (sectionType == 'hybrid')))
			|| ((is_adding==true) && ((sectionType == 'experience') || (sectionType == 'hybrid'))) 
			||(sectionType=='employer_multiple_jobs') || (sectionType=='general')  || (sectionType=='job') || (sectionType=='subsection')|| (sectionType=='employer')){
		if((tpfck!=undefined) && (sectionType!='employer_multiple_jobs')) {
			new_data="fck="+encodeURIComponent(tpfck.GetXHTML(true));
		}
		if ((tpfck2!=undefined) && (sectionType!='subsection') && (sectionType!='job')) {
			var tpData = encodeURIComponent(tpfck2.GetXHTML(true));
			if (tpData=="%3Cbr%20%2F%3E")tpData='';
			if(tpfck2.GetXHTML(true)!=null) new_data2="description="+tpData;
			
		}
		if (dataToSave!=''){
			if (new_data!='') dataToSave +="&"+new_data;
		}else{
			dataToSave=new_data;
		}
		if (new_data2!='') dataToSave +="&"+new_data2 ;

		//if (isSpellChecker)
		//	dataToSave = SpellChecker.serialize(id, true);
		}
		if (sectionType == 'headline')
		{
				new_data="fck="+encodeURIComponent(tpfckHeadline.GetXHTML(true));
				(dataToSave!='')? dataToSave +="&"+new_data : dataToSave=new_data;
				
		}
		//REMOVED BECAUSE WE DO NOT NEED TO REMOVE THE LABELS FROM THE INPUT BOXED ANYMORE
		dataToDisplay = removeLabels(id,sectionType,dataToSave);
		
	}
	if ((dataToSave!='') && ( isSpellChecker == true || hasDataChanged(sectionType) == true ) ){
	
		var dataToUpdate = dataToSave;
		var j = getPosition('section_'+id,sectionType,position);
		
		
		
		//if (is_adding==true){
		if ($("#infobyte","#section_"+id).html()!=null)	dataToSave+="&infobyte="+encodeURIComponent($("#infobyte","#section_"+id).html());
		//}
		
		if (position==undefined) loaction="inplace";
		$('#divWhilePosting').html('<img src="/images/or20/or20_ajax-loader_small.gif" border="0" />');
		//alert("DATA TO SAVE: " + dataToSave);
		
		$.ajax({type:'POST',
			   dataType: 'text',
		   	   url: '/modules/ordocument/save.php',
		   	   data:{ documentType: $('#documentType').attr("value"),
			   documentId :  $('#documentId').attr("value"),
			   sectionType: sectionType,
			   sectionIndex: j,
			   position: position,
			   adding: is_adding,
			   dataToSave: dataToSave},
		 	   success: function(successData){
				   $('#divWhilePosting').html("");
				   experience_is_showing=false;
		          /* if ((is_adding == true) || (sectionType=="phone1") || (sectionType=="phone2") || (sectionType=="phone3") ||
		        		   (sectionType=="personal") ||    (sectionType=="recipient") ||    (sectionType=="email")  
		        		   ||   (sectionType=="name")  || (sectionType=="headline") || 
		        		   (sectionType=="address1")|| (sectionType=="address2"))
		           	{*/
									//CancelEditor(id, sectionType, dataToDisplay);
				  // if (!SpellChecker.active){

					// set focus on any text element (to fix issue with IE showing blinking cursor even if fck is not visible)
//				$("[type='text']").not(":hidden").focus();
				$("#fckarea").css('top', '-1000px');
				$("#fckarea_employer_description").css('top', '-1000px');


			   	$("#fckarea").css("display","none");
				$("#fckarea_employer_description").css("display","none");
				$('#moduleCanvas').replaceWith(successData);
				initDocAjax();
				is_adding= false;
//				alert("SpellChecker Status:" + SpellChecker.active);
				if ( SpellChecker.active == true )
				{
					SpellChecker.checkAsync();
				}
				
		      },
		      error: function(XMLHttpRequest, textStatus, errorThrown)
					{
						 alert("The data did not save: "+textStatus + ": " + errorThrown);
		         CancelEditor(id,sectionType,dataLoaded);
		      }
		        
		    }); 
	}else if (dataToDisplay==''){
		alert("Empty section will not be saved.");
		CancelEditor(id,sectionType,dataLoaded);
	}else{
	
		CancelEditor(id,sectionType,dataLoaded);
	}
	
	removeEditOverlay();
	//move the menu on the page
	jsMoveRightMenu(1);
}	

function hasDataChanged(sectionType)
{
	return true;
	/*
	var dataChanged = false;

	var localDataToSaveJSON = $("#general_form").serializeArray();
	var obj = {};
	if ( (tpfck!=undefined) && (sectionType!='employer_multiple_jobs') )
	{
		obj = {};
		obj.name='fck';
		obj.value=encodeURIComponent(tpfck.GetXHTML(true));
		localDataToSaveJSON.push(obj);
	}
	if ( (tpfck2!=undefined) && (sectionType!='subsection') && (sectionType!='job') ) {
		obj = {};
		obj.name = 'description';
		obj.value=encodeURIComponent(tpfck2.GetXHTML(true));
		localDataToSaveJSON.push(obj);
	}
	if ( tpfckHeadline != undefined && sectionType == 'headline')
	{
		obj = {};
		obj.name = 'headline';
		obj.value = encodeURIComponent(tpfckHeadline.GetXHTML(true));
		localDataToSaveJSON.push(obj);
	}
	for(key in dataLoadedJSON)
	{
		var thisPair = dataLoadedJSON[key];

		for( jsonKey in localDataToSaveJSON )
		{
			var values = localDataToSaveJSON[jsonKey];
			if ( values.name != thisPair.name )
			{
				continue;
			}
			
			if ( values.value != thisPair.value )
			{
				dataChanged = true;
				break;
			}
		}
	}
	return dataChanged;
	*/
}


function changeSectionType(id,sectionType,newSectionType){
	var j =0;
	//removeMenu(id);
	unbindSectionEvent(id);
	flush();
	if ((sectionType=="employer_multiple_jobs")&&(newSectionType=="employer")){
		//this case is only used when deleting the last job in an employer_multiple_jobs section
		//and we switch it to an employer section
		 j = getPosition('section_'+id,"job");
	}else{ 
		 j = getPosition('section_'+id,sectionType);
	}
		var data =$("span[id='xsl_section_data']","#section_"+id).html();
		$("#section_"+id).before('<div class="loaderImage"></div>');
	
		$.ajax({type:'POST',
			 async: false,
			 dataType: 'text',
	   		 url: '/modules/ordocument/switchSectionType.php',
	   		 data:{ documentType: $('#documentType').attr("value"),
			 documentId :  $('#documentId').attr("value"),
			 currentSectionType: sectionType,
			 newSectionType: newSectionType,
			 sectionIndex: j},
		 	 success: function(successData){
				$('#moduleCanvas').replaceWith(successData);
				initDocAjax();
		   		//Needs to call init() and not initDoc(), otherwise FCK takes to long to load and breaks
				
				newid = getIndex(j, newSectionType);
				unbindSectionEvent(newid);
				
				if (newSectionType=="employer"){
					bindSectionEvent();
				}
				else if (newSectionType=="employer_multiple_jobs"){
					
					showNewJobForm(newid);
					
				}else if ((newSectionType=="hybrid") || (newSectionType=="experience")){
					is_adding=true;
					showEditor(newid,newSectionType);
				}
				else {
					showEditor(newid,newSectionType);
					
				}
			 
		     },
	        error: function(errorData){

			   bindSectionEvent();
	        }
		        
	}); 
	

}	   



function SaveMarkup(source,editorContainer)
{
	e = FCKeditorAPI.GetInstance(fckEditorLabel);
	$('#'+source).html(e.GetHTML());
	$('#'+editorContainer).hide();
	$('#'+source).show();
	
}

function URLEncode( encoded)
{	
   var decoded='';
   var encoded = encoded;
  if(encoded!=null) decoded = decodeURI(encoded.replace(/[&]amp;/g,"&"));
  
   return decoded;
};

function URLDecode( encoded)
{	
   var decoded='';
   var encoded = encoded;
    if(encoded!=null)decoded = decodeURIComponent(encoded.replace(/[+]/g," "));
  
   return decoded;
};


function encode_utf8( s ){
return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}

function initStylistHelp()
{
	$("img.stylistHelpIcon").css({
		cursor:'pointer'
	});
	
	var btipAnimation = true;
	if(navigator.appName.indexOf("Internet Explorer") != -1) //remove tooltip animation cause it does not work in ie7 
	{
		btipAnimation = false;
	}
	
	$.each($("img.stylistHelpIcon"), function(idx, val){
		$(val).bt('<b>'+$(val).attr("title")+'</b>', {
			trigger: ['hover'],   
			 animate: btipAnimation,
			 centerPointY: -.5,
			 positions: ['most'], 	
			 fill: '#F7F7F7', 
			 strokeStyle: '#B7B7B7', 
//			 commented out the drop shadow to fix a display issue in Chrome, FS#2795
//			 shadow: true, 
//		  	 shadowBlur: 122, 
			 spikeLength: 15, 
			 spikeGirth: 10, 
			 padding: 8, 
			 cornerRadius: 5, 
			 cssStyles: {
			    fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
			    fontSize: '10px',
			    width:'235px',
				zindex:'600'}
		});
	});
	
}

function showTip(id,attribute,label,hint){
	if (attribute.indexOf("address2")!=-1) position="left";
	else position="right";

	var btipAnimation = true;
	if(navigator.appName.indexOf("Internet Explorer") != -1) //remove tooltip animation cause it does not work in ie7 
	{
		btipAnimation = false;
	}
//'<b>'+addslashes(label)+'</b>: '
	$("img[id='imgTip_"+attribute+"']","#section_"+id).bt(addslashes(hint),{
				trigger: ['hover'],   
  				 animate: btipAnimation,
				 centerPointY: -.5,
				 positions: ['left','right'], 	
				 fill: '#F7F7F7', 
				 strokeStyle: '#B7B7B7', 
//				 commented out the drop shadow to fix a display issue in Chrome, FS#2795
//				 shadow: true, 
//			  	 shadowBlur: 122, 
				 spikeLength: 15, 
				 spikeGirth: 10, 
				 padding: 8, 
				 cornerRadius: 5, 
				 cssStyles: {
				    fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
				    fontSize: '11px',
				    width:'180px',
				    zIndex:'30000'}
				  });

}

function showAddressLabels(id){
	var labelHeaderEditable1 = $("#labelHeaderEditable").val().split("@#@");
	var labelHeaderNotEditable1 = $("#labelHeaderNotEditable").val().split("@#@");
	var has2addresses =0;
	if (id_address2==id)  has2addresses =1;
	
	//Shows the fields which labels are not editable 
	for (var i=0;i<labelHeaderNotEditable1.length-1;i++){
		var labelHeaderNotEditable = labelHeaderNotEditable1[i].split('&');
		var attribute =labelHeaderNotEditable[0];
		var label =labelHeaderNotEditable[1];
		var hint =labelHeaderNotEditable[2];
		
		  //get the div alignment
		var divParentAlign = $("span[id='"+this.id+"']","#section_"+id).css("text-align");
		var styleInputAlign = "";
		var sectionWidth = $("#section_"+id).parent().parent().width();
		sectionWidth = sectionWidth/2-70;
		
		if (divParentAlign=="center")
		{
			//styleInputAlign = "margin:0 auto;";
			styleInputAlign = "margin:0px 2px 2px "+sectionWidth+"px;";
		}
		else if (divParentAlign=="left")
		{
			styleInputAlign = "float:left;";
		}
		else if (divParentAlign=="right")
		{
			styleInputAlign = "float:right;";
		}
		
		switch (attribute){
			case "xsl_address1":
				if ( ($("#xsl_Attribute-address1").html()!='') && ($("#xsl_Attribute-address1").html()!='<!-- -->')) label=$("#xsl_Attribute-address1").html();
	
				if ( ($("span[id*='-address1']", "#section_" + id).length != 0) || (has2addresses==1)){
					$("#xsl_Attribute-address1").html(label);
					var widthField=$("input[id='"+fiedInForm+"']","#section_"+id).width()-4;
					
					$("input[id='"+fiedInForm+"']","#section_"+id).before('<div class="or20_form_label" style="width:'+widthField+'px;text-align:left;'+styleInputAlign+'margin-top:2px;">'+theFieldValueEmpty+'</div>');
				
				}	
			break;
			case "xsl_address2":
					if ( ($("#xsl_Attribute-address2").html()!='') && ($("#xsl_Attribute-address2").html()!='<!-- -->')) label=$("#xsl_Attribute-address2").html();
	
				if ( ($("span[id*='-address2']", "#section_" + id).length != 0) || (has2addresses==1)){
					$("#xsl_Attribute-address2").html(label);
					
				}		
			break;
			default:
				var widthField=$("input[id='"+attribute+"']").width()-4;
			$("input[id='"+attribute+"']").before('<div class="or20_form_label" style="width:'+widthField+'px;text-align:left;'+styleInputAlign+'margin-top:2px;">'+label+'</div>');
		
			/*if ($("input[id='" + attribute + "']").length != 0) {
	
					
					$("input[id='" + attribute + "']").attr("mylabel",label);
					if ($("input[id='" + attribute + "']").val() == '') {
						$("input[id='" + attribute + "']").attr("isempty","true");
						$("input[id='" + attribute + "']").val(label);
						$("input[id='" + attribute + "']").css("font-style", "italic");
					}

					$("input[id='" + attribute + "']").focus(function () { 
					 if (  $(this).attr("isempty")=="true"){
					  	$(this).val(''); 
						$(this).attr("isempty","false");
					  	$(this).css("font-style","normal");
			 		  } 
    				});
					$("input[id='" + attribute + "']").blur(function () { 
					  if ($(this).attr("value") == '') {
					  	$(this).val($(this).attr("mylabel"));
					  	$(this).attr("isempty", "true");
					  	$(this).css("font-style", "italic");
					  }
    				});
				}*/
			break;
			}
		showTip(id,attribute,label,hint);
	}
	
	//Shows the fields which labels are  editable 
	for (var i=0;i<labelHeaderEditable1.length-1;i++){
		var labelHeaderEditable = labelHeaderEditable1[i].split('&');
		var attribute =labelHeaderEditable[0];
		var label =labelHeaderEditable[1];
		var hint =labelHeaderEditable[2];
		switch (attribute){
			case "xsl_address1":
				if (($("#xsl_Attribute-address1").html()!='') && ($("#xsl_Attribute-address1").html()!='<!-- -->') )label=$("#xsl_Attribute-address1").html();
	
				
					if (has2addresses == 1) {
						$("#xsl_Attribute-address1").html(label);
					}
					else {
						if (($("span[id*='-address1']", "#section_" + id).length != 0)) {
						
							$("#xsl_Attribute-address1").html('<input type="text" name="xsl_Attribute-address1" id="xsl_Attribute-address1" value="' + label + '" style="'+styleInputAlign+'">');
						}
				
				}	
			break;
			case "xsl_address2":
				if (($("#xsl_Attribute-address2").html()!='')  && ($("#xsl_Attribute-address2").html()!='<!-- -->')) label=$("#xsl_Attribute-address2").html();
	
				if ( ($("span[id*='-address2']", "#section_" + id).length != 0) || (has2addresses==1)){
					$("#xsl_Attribute-address2").html('<input type="text" name="xsl_Attribute-address2" id="xsl_Attribute-address2" value="'+label+'" style="'+styleInputAlign+'">');
					
				}	
			break;
			default:
				var widthField=$("input[id='"+attribute+"']").width()-4;
			$("input[id='"+attribute+"']").before('<div class="or20_form_label" style="width:'+widthField+'px;text-align:left;'+styleInputAlign+'margin-top:2px;">'+label+'</div>');
		
				/*if ($("input[id='" + attribute + "']").length != 0) {
					if ($("input[id='" + attribute + "']").val() == '') {
						$("input[id='" + attribute + "']").attr("isempty","true");
						$("input[id='" + attribute + "']").val(label);
						$("input[id='" + attribute + "']").attr("mylabel",label);
						$("input[id='" + attribute + "']").css("font-style", "italic");
					}
					
					$("input[id='" + attribute + "']").focus(function () { 
					 if (  $(this).attr("isempty")=="true"){
					  	$(this).val(''); 
						$(this).attr("isempty","false");
					  	$(this).css("font-style","normal");
					  } 
    				});
					$("input[id='" + attribute + "']").blur(function () { 
					  if ($(this).attr("value") == '') {
					  	$(this).val($(this).attr("mylabel"));
					  	$(this).attr("isempty", "true");
					  	$(this).css("font-style", "italic");
					  }
    				});
				}*/
			break;
			}

		showTip(id,attribute,label,hint);
	}
}

function showContactForm(id){
	 
	/*takes the data from the HTML transformation and loads it into the contact form*/
	//labelHeaderEditable//labelHeaderNotEditable
	//return an array with the values for address1 and address2 
	
	if ($("span[id^='xsl_address1']", "#section_" + id).attr("class")=="orangeFields") $("span[id^='xsl_address1']", "#section_" + id).html('');
	if ($("span[id^='xsl_address2']", "#section_" + id).attr("class")=="orangeFields") $("span[id^='xsl_address2']", "#section_" + id).html('');

	var myclass = "longDataContact";
	
	
	//dispays the data fields
	var labelHeaderEditable1 = $("#labelHeaderEditable").val().split("@#@");
	var labelHeaderNotEditable1 = $("#labelHeaderNotEditable").val().split("@#@");
	
	var sectionWidth = $("#section_"+id).parent().parent().width();
	sectionWidth = sectionWidth/2-70;
	//Shows the fields which labels are not editable 
	for (var i = 0; i < labelHeaderNotEditable1.length - 1; i++) {
		var labelHeaderNotEditable = labelHeaderNotEditable1[i].split('&');
		var attribute = labelHeaderNotEditable[0];
		var label = labelHeaderNotEditable[1];
		var hint = labelHeaderNotEditable[2];
		//if ((labelHeaderNotEditable[i]!='')&& (labelHeaderNotEditable[i]!=undefined)){
		SpellChecker.deactivate();
		$("span[id^='xsl_']", "#section_" + id).each(function(i){
			if (attribute == this.id) {
				var val = this.innerHTML;
				//val = SpellChecker.removeSpellCheckErrorTag(val);
				if (val == "<!-- -->") 
					val = "";
				myclass = "longDataContact";
				/*if (this.id.indexOf("phone") != -1) 
					myclass = "shortDataContact";
				if (this.id.indexOf("postal") != -1) 
					myclass = "veryShortDataContact";
				if (this.id.indexOf("state") != -1) 
					myclass = "veryShortDataContact";*/
				
				var divParentAlign = $("span[id='"+this.id+"']","#section_"+id).css("text-align");
				
				var styleInputAlign = "";
				if (divParentAlign=="center")
				{
					//styleInputAlign = "margin:0 auto;";
					styleInputAlign = "margin:0px 2px 2px "+sectionWidth+"px;";
				}
				else if (divParentAlign=="left")
				{
					styleInputAlign = "float:left;";
				}
				else if (divParentAlign=="right")
				{
					styleInputAlign = "float:right;";
				}
				
				var clearLeftRight = "";
				if (attribute.indexOf("address2")>-1)  
				{
					//clearLeftRight = "clear:both";
				}
				
				//set label and tooltip
				if (hint!="")
				{
					label+=' <img src="images/or20/stylist/or20_help_Stylist.png" id="imgTip_'+attribute+'" border="0" align="absmiddle" />'; 
				}
				
				if ( navigator.appVersion.indexOf("MSIE 7.0")>-1)
				{
					styleInputAlign += "margin-top:5px;";
				}
				this.innerHTML = '<div  class="or20_InputBox" id="boxInput_'+this.id+'" style="'+clearLeftRight+''+styleInputAlign+'">\
																							<div class="or20_InputBoxTopLabel" id="labelInput'+this.id+'">'+label+'</div>\
																							<input  type="text"  name="' + this.id + '" id="' + this.id + '" value="' + addslashes(val) + '" />\
																						</div>';
																		
				var inputBoxWidth=$("input[id='"+attribute+"']").width();
				$("#boxInput_"+this.id).css("width",inputBoxWidth);																			
										
				//remove field separators in edit mode
				$.each($("span",$("#section_"+id)), function(idx,val){
					var valueEncoded = encodeURI($(val).html().toLowerCase());
					if (valueEncoded == ",&nbsp;" || 
						valueEncoded =="&nbsp;" || 
						valueEncoded ==" " ||
						valueEncoded =="&nbsp;&nbsp;" || 
						valueEncoded=="&nbsp;%E2%97%8A&nbsp;" ||
						valueEncoded== "&nbsp;%E2%80%A2&nbsp;" ||
						valueEncoded== "&nbsp;%E2%80%A1&nbsp;" ||
						valueEncoded== "&nbsp;~&nbsp;"
						)
					{
						 $(val).html("");
					}
				});																				
			}
		});
		
		showTip(id, attribute, label, hint);
		//}
	}
	
	//Shows the fields which labels are  editable 
	for (var i = 0; i < labelHeaderEditable1.length - 1; i++) {
		var labelHeaderEditable = labelHeaderEditable1[i].split('&');
		var attribute = labelHeaderEditable[0];
		var label = labelHeaderEditable[1];
		var hint = labelHeaderEditable[2];
			$("span[id^='xsl_']", "#section_" + id).not(":hidden").each(function(){
				if ((attribute == this.id) && (attribute!="xsl_address1") && (attribute!="xsl_address2") ){
					var val = this.innerHTML;
					if (val == "<!-- -->") 
						val = "";
					myclass = "or20_form_label";
					/*if (this.id.indexOf("phone") != -1) 
						myclass = "shortDataContact";
					if (this.id.indexOf("line2") != -1) 
						myclass = "shortDataContact";
					if (this.id.indexOf("postal") != -1) 
						myclass = "veryShortDataContact";
					if (this.id.indexOf("state") != -1) 
						myclass = "veryShortDataContac;*/
					
					var divParentAlign = $("span[id='"+this.id+"']","#section_"+id).css("text-align");
					var styleInputAlign = "";
					if (divParentAlign=="center")
					{
					//	styleInputAlign = "margin:0 auto;";
						styleInputAlign = "margin:0px 2px 2px "+sectionWidth+"px;";
					}
					else if (divParentAlign=="left")
					{
						styleInputAlign = "float:left;";
					}
					else if (divParentAlign=="right")
					{
						styleInputAlign = "float:right;";
					}

					//set label and tooltip
					if (hint!="")
					{
						label+=' <img src="images/or20/stylist/or20_help_Stylist.png" id="imgTip_'+attribute+'" border="0" align="absmiddle" />'; 
					}
						
					
					this.innerHTML = '<div  class="or20_InputBox" id="boxInput_'+this.id+'" style="'+styleInputAlign+'">\
												<div class="or20_InputBoxTopLabel" id="labelInput'+this.id+'">'+label+'</div>\
												<input type="text" name="' + this.id + '" id="' + this.id + '" value="' + addslashes(val) + '" />\
											</div>';
												
					//get the width of the input box
					var inputBoxWidth=$("input[id='"+attribute+"']").width();
					$("#boxInput_"+this.id).css("width",inputBoxWidth);						
												
					//remove field separators in edit mode
					$.each($("span",$("#section_"+id)), function(idx,val){
						var valueEncoded = encodeURI($(val).html().toLowerCase());
						if (valueEncoded == ",&nbsp;" || 
							valueEncoded =="&nbsp;" || 
							valueEncoded ==" " ||
							valueEncoded =="&nbsp;&nbsp;" || 
							valueEncoded=="&nbsp;%E2%97%8A&nbsp;" ||
							valueEncoded== "&nbsp;%E2%80%A2&nbsp;" ||
							valueEncoded== "&nbsp;%E2%80%A1&nbsp;" ||
							valueEncoded== "&nbsp;~&nbsp;"
							)
						{
							 $(val).html("");
						}
					});										
				
				}
			});
			
			showTip(id, attribute, label, hint);
	}
	
	//*****************/
	//Displays the fields labels within the fields if the fields are empty
	//showAddressLabels should be called AFTER the data fields have been displayed
	//showAddressLabels(id);
	//*****************/
	dataLoadedJSON = $("#general_form").serializeArray();
	next();
}

function showSignatureForm(id){
	var close_value 		=$("span[id='xsl_closing_close_value']","#section_"+id).html();
	var close_signature 	=$("span[id='xsl_closing_close_signature']","#section_"+id).html();
	var enclosure =$("span[id='xsl_closing_close_enclosure']","#section_"+id).html();
	
	
	setLabels("closing_close_value","close_value",id,1);
	setLabels("closing_close_signature","close_signature",id,2);
	
	if (enclosure!=''){
	var firstIndex = enclosure.indexOf("(");
	var lastIndex = enclosure.lastIndexOf(")");
	enclosure = enclosure.slice(firstIndex+1,lastIndex);
	
	}
	
	var enclosures_select='<select name="enclosure" id="enclosure">\
	<option value="0">0</option>\
	<option value="1">1</option>\
	<option value="2">2</option>\
	</select>'; 
	
	$("span[id='xsl_closing_close_enclosure']","#section_"+id).html('Enclosures: '+enclosures_select);//<input type="text" class="veryShortDataContact" name="enclosures" id="enclosures" value="'+addslashes(enclosures)+'">');
	$("#enclosure").val(enclosure);
	$("#close_value").autocomplete("/modules/ordocument/letterSignature.php", {
		minChars: 0,
		max: 12,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		extraParams: {
	       prefix: function() { return $("#prefix").val(); },
	       first_name: function() { return $("#first_name").val(); },
	       last_name: function() { return $("#last_name").val(); },
	       job_title: function() { return $("#job_title").val(); }
	   }

	});
}

function showRecipientForm(id){
	//var divParentValue = $("div","#section_"+id).parent().html().replace("Address","aa");
	//$("div","#section_"+id).parent().html(divParentValue);
	//jQuery(this).replaceWith(jQuery(this).html().replace("span>&nbsp;","span>"));
	
	
	
	jQuery($("span","#section_"+id).parent()).each(function(i){
		  jQuery(this).html(jQuery(this).html().replace(/\&nbsp;/g," "));
		});
	
	var recip_prefix 		=$("span[id='xsl_recip_prefix']","#section_"+id).html();
	var recip_first_name 	=$("span[id='xsl_recip_first_name']","#section_"+id).html();
	var recip_last_name 	=$("span[id='xsl_recip_last_name']","#section_"+id).html();
	var recip_job_title 	=$("span[id='xsl_recip_job_title']","#section_"+id).html();
	var recip_organization_name 	=$("span[id='xsl_recip_organization_name']","#section_"+id).html();
	var recip_address_line_1 =$("span[id='xsl_recip_address_line_1']","#section_"+id).html();
	var recip_address_line_2 =$("span[id='xsl_recip_address_line_2']","#section_"+id).html();
	var recip_city 			 =$("span[id='xsl_recip_city']","#section_"+id).html();
	var recip_state 		=$("span[id='xsl_recip_state']","#section_"+id).html();
	var recip_postal_code 	=$("span[id='xsl_recip_postal_code']","#section_"+id).html();
	var recip_country 		=$("span[id='xsl_recip_country']","#section_"+id).html();
	var recip_opening 		=$("span[id='xsl_recip_opening']","#section_"+id).html();
	
	var arrayElet = new Array ($("span[id='xsl_recip_prefix']","#section_"+id),
			$("span[id='xsl_recip_first_name']","#section_"+id),
			$("span[id='xsl_recip_last_name']","#section_"+id),
			$("span[id='xsl_recip_job_title']","#section_"+id),
			$("span[id='xsl_recip_organization_name']","#section_"+id),
			$("span[id='xsl_recip_address_line_1']","#section_"+id),
			$("span[id='xsl_recip_address_line_2']","#section_"+id),
			$("span[id='xsl_recip_city']","#section_"+id),
			$("span[id='xsl_recip_state']","#section_"+id),
			$("span[id='xsl_recip_postal_code']","#section_"+id),
			$("span[id='xsl_recip_country']","#section_"+id),
			$("span[id='xsl_recip_opening']","#section_"+id));
			
	arrayElet = $(arrayElet).sort("offsetTop", "asc");
	var tabindex=1;

	
	jQuery.each($(arrayElet), function(i, val){
		
		labels = $(this).attr("id").slice($(this).attr("id").indexOf("_")+1);
		index = labels.slice(labels.indexOf("_")+1);
		
		setLabels('recip_' + index, index, id,tabindex);
		tabindex++;
		
	});
	/*setLabels("recip_prefix","prefix",id);
	setLabels("recip_first_name","first_name",id);
	setLabels("recip_last_name","last_name",id);
	setLabels("recip_job_title","job_title",id);
	setLabels("recip_organization_name","organization_name",id);
	setLabels("recip_address_line_1","address_line_1",id);
	setLabels("recip_address_line_2","address_line_2",id);
	setLabels("recip_city","city",id);
	setLabels("recip_state","state",id);
	setLabels("recip_postal_code","postal_code",id);
	setLabels("recip_country","country",id);
	setLabels("recip_opening","opening",id);
	*/
	$("#prefix").autocomplete("/modules/ordocument/letterTitle.php", {
		minChars: 0,
		max: 12,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220

	});
	
	$("#opening").autocomplete("/modules/ordocument/letterGreetingAutocomplete.php", {
		minChars: 0,
		max: 12,
		autoFill: true,
		mustMatch: false,
		matchContains: false,
		scrollHeight: 220,
		extraParams: {
	       prefix: function() { return $("#prefix").val(); },
	       first_name: function() { return $("#first_name").val(); },
	       last_name: function() { return $("#last_name").val(); },
	       job_title: function() { return $("#job_title").val(); }
	   }

	});
	
	
	
	
	
}

function showPersonalInformation(id){
	if ($("#is_personalinfo_visible").css("display")=="block"){ 
			
			if ($("#xsl_marital_status").html()!='' && $("#marital_status_class").css("display")=="none") $("#marital_status").val($("#xsl_marital_status").html());
			if ($("#xsl_age").html()!='' && $("#age_class").css("display")=="none") $("#age").val($("#xsl_age").html());
			if ($("#xsl_dob").html()!='' && $("#dob_class").css("display")=="none") $("#dob").val($("#xsl_dob").html());
			if ($("#xsl_nationality").html()!='' && $("#nationality_class").css("display")=="none") $("#nationality").val($("#xsl_nationality").html());
			if ($("#xsl_driving_license").html()!='' && $("#driving_license_class").css("display")=="none") $("#driving_license").val($("#xsl_driving_license").html());
			if ($("#xsl_work_permit").html()!='' && $("#work_permit_class").css("display")=="none") $("#work_permit").val($("#xsl_work_permit").html());
			if ($("#xsl_number_of_children").html()!='' && $("#number_of_children_class").css("display")=="none") $("#number_of_children").val($("#xsl_number_of_children").html());
			if ($("#xsl_civil_status").html()!='' && $("#civil_status_class").css("display")=="none") $("#civil_status").val($("#xsl_civil_status").html());
			if ($("#xsl_place_of_birth").html()!='' && $("#place_of_birth_class").css("display")=="none") $("#place_of_birth").val($("#xsl_place_of_birth").html());
			if ($("#xsl_religious_affiliation").html()!='' && $("#religious_affiliation_class").css("display")=="none") $("#religious_affiliation").val($("#xsl_religious_affiliation").html());
			if ($("#xsl_summary_information").html()!='' && $("#summary_information_class").css("display")=="none") $("#summary_information").val($("#xsl_summary_information").html());
			if ($("#xsl_website").html()!='' && $("#website_class").css("display")=="none") $("#website").val($("#xsl_website").html());
			if ($("#xsl_gender").html()!='' && $("#gender_class").css("display")=="none") $("#gender").val($("#xsl_gender").html());
		
		}
		else{ 
		
			if (($("#xsl_age").html()) !=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#age_class").css("display","table-row");
				$("#age").val($("#xsl_age").html());
			 }
			if ($("xsl_marital_status").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#marital_status_class").css("display","table-row"); 
				$("#marital_status").val($("#xsl_marital_status").html());
				}
			if ($("#xsl_dob").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#dob_class").css("display","table-row"); 
				$("#dob").val($("#xsl_dob").html());
			}
			if ($("#xsl_nationality").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#nationality_class").css("display","table-row"); 
				$("#nationality").val($("#xsl_nationality").html());
			}
			if ($("#xsl_driving_license").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#driving_license_class").css("display","table-row"); 
				$("#driving_license").val($("#xsl_driving_license").html());
			}
			if ($("#xsl_work_permit").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#work_permit_class").css("display","table-row"); 
				$("#work_permit").val($("#xsl_work_permit").html());
			}
			if ($("#xsl_number_of_children").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#number_of_children_class").css("display","table-row"); 
				$("#number_of_children").val($("#xsl_number_of_children").html());
			}
			if ($("#xsl_civil_status").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				$("#civil_status_class").css("display","table-row"); 
				$("#civil_status").val($("#xsl_civil_status").html());
			}
			if ($("#xsl_place_of_birth").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				
				$("#place_of_birth_class").css("display","table-row"); 
				$("#place_of_birth").val($("#xsl_place_of_birth").html());
			}
			if ($("#xsl_religious_affiliation").html()!=''){
				$("#religious_affiliation_class").css("display","table-row"); 
				$("#religious_affiliation").val($("#xsl_religious_affiliation").html());
			}
			if ($("#xsl_summary_information").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				
				$("#summary_information_class").css("display","table-row"); 
				$("#summary_information").val($("#xsl_summary_information").html());
			}
			if ($("#xsl_website").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				
				$("#website_class").css("display","table-row"); 
				$("#website").val($("#xsl_website").html());
			}
			if ($("#xsl_gender").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				
				$("#gender_class").css("display","table-row"); 
				$("#gender").val($("#xsl_gender").html());
			}
			if ($("#xsl_picture").html()!=''){
				$("#is_personalinfo_visible").css("display","block");
				
				$("#picture_class").css("display","table-row"); 
				$("#picture").val($("#xsl_picture").html());
			}
			
		}
		
		
		if(($("#xsl_relocation_preference").val()!='') || ($("#xsl_allow_relocation_preference").val()==1)){
			$("#relocation_preference").val($("#xsl_relocation_preference").val());
		}
}

function renderTemplateSelect(element)
{
	$('#'+element).templatedSelect({
		selectHandleImage : $("base").attr("href") + "include/js/jquery/plugins/templatedSelect/selectHandle.gif",				
		width : '140px',
		getOption : function(v, t) {
			var txt = "&nbsp;";
			if ( v == "none" )
			{
				txt = t;
			}
			if ($("#"+element).attr("name") != 'headerFormat' && $("#"+element).attr("name") != 'styleExperienceSection') {
				return "<div style=\"font-size:0.75em;width:85%;height:15px;background: transparent url('" + $("base").attr("href") + "images/resumeUnderlining/" + v + ".png') repeat-x scroll center left;\">" + txt + "</div>";
			}
			else if ( $("#"+element).attr("name") == "styleExperienceSection")
			{
				return '<img src="/images/stylist/experience' + v + '.png';
			}
			else{
				return '<img src="/images/stylist/layouts/headerLayout' + v + '.gif"/>';
			}
			
		}
	});
}

function removeHighlight()
{
	$.each($("[orstyle]"), function(idx,val){
		bgColor = $(this).css("background-color");
		if ( bgColor == 'rgb(153, 204, 255)' || bgColor == '#99CCFF' || bgColor =='99CCFF' || bgColor == '#99ccff')
		{
			$(this).css("background-color","");
		}
	});
	lastStyleHighlight = null;
}

function showHighlight(groupId,toggle)
{
//	console.log("lastHighlightGroup = " + lastStyleHighlight + ",groupId=" + groupId);
	
	if ( lastStyleHighlight == groupId && toggle == true )
	{
		$.each($("[column]", $("#"+groupId)), function(i,val){
			$("[orstyle*='"+$(this).attr("column")+"']").
			filter(function(idx){
				atts = $(this).attr("orstyle").split(" ");
				for(att in atts)
				{
					if ( atts[att] == $(val).attr("column") )
					{
						if ( $(this).attr("orHeight") == 0 )
						{
							$(this).css("height","0px");
						}
						else if ( $(val).attr("column").indexOf("border") > -1 || 
								$(val).attr("column").indexOf("Divider") > -1 )
						{
							$(this).css("height",$(this).attr("orHeight"));
						}
						return true;
					}
				}
				return false;
			}).
			css('background-color',"");
		});
		lastStyleHighlight = null;
	}
	else if ( lastStyleHighlight == groupId && toggle == false )
	{
		$.each($("[column]", $("#"+groupId)), function(i,val){
			$("[orstyle*='"+$(this).attr("column")+"']").
			filter(function(idx){
				atts = $(this).attr("orstyle").split(" ");
				for(att in atts)
				{
					if ( atts[att] == $(val).attr("column") )
					{
						if ( $(this).height() <= 0 )
						{
							$(this).attr("orHeight","0");
							$(this).css("height","2px");
						}
						else if ( $(val).attr("column").indexOf("border") > -1 || 
								$(val).attr("column").indexOf("Divider") > -1 )
						{
							$(this).attr("orHeight",$(this).css("height"));
							$(this).css("height",parseInt($(this).css("height"))+4);
						}
						return true;
					}
				}
				return false;
			}).
			css('background-color',"#99CCFF");
		});
	}
	else if ( lastStyleHighlight == undefined || groupId == undefined || lastStyleHighlight != groupId )
	{
		if ( groupId == undefined ){
			groupId = lastStyleHighlight;
		}
		$("[orstyle]").css("background-color","");
		$.each($("[column]", $("#"+groupId)), function(i,val){
			$("[orstyle*='"+$(this).attr("column")+"']").
			filter(function(idx){
				atts = $(this).attr("orstyle").split(" ");
				for(att in atts)
				{
					if ( atts[att] == $(val).attr("column") )
					{
						if ( $(this).height() <= 0 )
						{
							$(this).attr("orHeight","0");
							$(this).css("height","2px");
						}
						else if ( $(val).attr("column").indexOf("border") > -1 || 
								$(val).attr("column").indexOf("Divider") > -1 )
						{
							$(this).attr("orHeight",$(this).css("height"));
							$(this).css("height",parseInt($(this).css("height"))+4);
						}
						return true;
					}
				}
				return false;
			}).
			css('background-color',"#99CCFF");
			
		});
		if ( groupId != undefined )
		{
			lastStyleHighlight = groupId;
		}
	}
}

function scrollToSection(sectionId)
{
	$.scrollTo("#"+sectionId);
}

//apply add section 
function addSection(sectionType)
{
	//var type = $(":input[name='sectiontype']:checked").val();
	var type = sectionType;
	var location = $(":input[name='location'] option:selected").val();
	var target = $(":input[name='targetSection'] option:selected").val();
	var targetId =0;
	(target!= undefined )?  targetId = target.split("_")[1]: targetId = findMaxSection(); 
	var newId = -1;
	switch(type)
	{
		case "experience":
			newId = showNewExperienceForm(targetId, location);
			break;
		case "hybrid":
			newId = showNewHybridForm(targetId, location);
			break;
		default:
			newId = showNewSectionForm(targetId, location);
			break;
	}

	$.scrollTo("#section_"+newId);
}

//reset add section
function resetAddSectionForm()
{
	$.each($(":input[name='location'] option"), function(idx,val){
		if ( idx == 0 )
		{
			$(this).attr("selected","selected");
		} else {
			$(this).attr("selected","");
		}
	});
	$.each($(":input[name='targetSection'] option"), function(idx,val){
		$(this).remove();
	});
}


function resetJobFormCompanies()
{
	$.each($(":input[name='companies'] option"), function(idx,val){
		if ( idx <= 1 )
		{
			$(this).attr("checked","checked");
		}
		else
		{
			$(this).remove();
		}
	});
}

function resetJobFormExperienceSections()
{
	$.each($(":input[name='experienceSections'] option"), function(idx,val){
		if ( idx <= 1 )
		{
			$(this).attr("checked","checked");
		}
		else
		{
			$(this).remove();
		}
	});
}

function resetAddJobForm()
{
//	$("#jobInputForm").hide();
//	$("#newCompanyJobForm").hide();
//	$("#newJobForm").hide();
	resetJobFormCompanies();
	resetJobFormExperienceSections();
}

function getEmployers(sectionId)
{
	var employers = [];
	$.each($("[sectiontype='employer'],[sectiontype='employer_multiple_jobs']",$("#"+sectionId)).not(":hidden"), function(idx,val){
		name = $("#xsl_employer_name",$(this)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Experience Section';
		}
		employers[$(this).attr("id")] = name;
	});
	return employers;
}

function getExperienceSections()
{
	var expSections = [];
	$.each($("[sectiontype='experience']").not(":hidden"), function(idx,val){
		name = $("#xsl_section_name",$(this)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Experience Section';
		}
		expSections[$(this).attr("id")] = name;
	});
	return expSections;
}

function handleCompanyChange()
{
	companySectionId = $(":input[name='companies'] option:selected").val();
	experienceSectionId = $(":input[name='experienceSections'] option:selected").val();
//	console.log("CompanySectionId: " + companySectionId);
//	$("#jobInputForm").hide();
//	$("#newCompanyJobForm").hide();
//	$("#newJobForm").hide();
	if ( companySectionId == 'choose' )
	{
		return;
	} else if ( parseInt(companySectionId) == -1 )
	{
		
		//User wants to add a new Company
		//GET Existing Companies
		companies = getEmployers(sectionId);
		jobSelect = $(":input[name='newJobTargetLocation']");
		for(key in companies)
		{
			jobSelect.append('<option value="'+key +'">' + companies[key] + '</option>');
		}
		$("#newJobLocationWrapper").show();
		$("#newJobTargetWrapper").show();
//		$("#newJobForm").show();
	}
	else
	{
		//Adding Job to existing company
		// GET the jobs for that section
		jobs = getEmployerJobs(companySectionId);
		jobSelect = $(":input[name='newJobTargetLocation']");
		for(key in jobs)
		{
			jobSelect.append('<option value="'+key +'">' + jobs[key] + '</option>');
		}
		$("#newJobLocationWrapper").show();
		$("#newJobTargetWrapper").show();
//		companyLocation = '';
//		if ( $("#"+companySectionId).attr("sectiontype") == 'employer' )
//		{
//			companyLocation = $("#xsl_employer_location",$("#"+companySectionId)).text();
//		}
//		else
//		{
//			companyLocation = $("#xsl_job_jobLocation:first",$("#"+companySectionId)).text();
//		}
//		$(":input[name='jobLocation']").val(companyLocation);
//		$("#jobInputForm").show();
//		$("#newJobForm").show();
	}
}



function handleExperienceSectionChange()
{
	resetJobFormCompanies();
	sectionId = $(":input[name='experienceSections'] option:selected").val();
	if ( sectionId == 'choose' )
	{
		return;
	}
	else if ( sectionId == -1 )
	{
		//User wants to use a new experience section
		$("#sectionLocationWrapper").show();
		$("#targetSectionWrapper").show();
		$("#companySelectorWrapper").hide();
		sections = getTopLevelSections();
		sectionControl = $(":input[name='targetSection']");
		for(key in sections)
		{
			sectionControl.append('<option value="'+key+'">'+sections[key]+'</option>');
		}
		
	}
	else
	{
		// Using existing experience section
		$("#sectionLocationWrapper").hide();
		$("#targetSectionWrapper").hide();
		companySelect = $(":input[name='companies']");
		companies = getEmployers(sectionId);
		for(key in companies)
		{
			val = companies[key];
			companySelect.append('<option value="' + key+ '">'+val+'</option>');
		}
		companySelect.show();
		$("#companySelectorWrapper").show();
	}
}

function showAddJobForm()
{
	var expSections = getExperienceSections();
	var expSelect = $(":input[name='experienceSections']");
	for( key in expSections )
	{
		val = expSections[key];
		expSelect.append('<option value="' + key + '">' + val + '</option>');
	}
	$("#addJobDialog").dialog({
		bgifram:true,
		resizable:false,
		width:600,
		modal:true,
		overlay:{
			backgroundColor:'#000',
			opacity: 0.5
		},
		buttons: {
			'Add':function(){
				companySectionId = $(":input[name='companies'] option:selected").val();
				experienceSectionId = $(":input[name='experienceSections'] option:selected").val();
				newSectionId = -1;
				if( experienceSectionId != 'choose' )
				{
					if ( companySectionId == -1 )
					{
						newSectionId = showNewEmployerForm(experienceSectionId.split("_")[1], 'after');
//						$(":input[name='name']").val($(":input[name='companyName']").val());
//						$(":input[name='linkURL']").val($(":input[name='companyUrl']").val());
//						$(":input[name='title']").val($(":input[name='jobTitle']").val());
//						$(":input[name='location']").val($(":input[name='jobLocation']",$("#jobInputForm")).val());
//						$(":input[name='dateRange']").val($(":input[name='jobDateRange']",$("#jobInputForm")).val());
						
						$.scrollTo("#section_"+newSectionId);
					}
					else
					{
						newSectionId = showNewJobForm(companySectionId.split("_")[1],'after');
//						$(":input[name='title']").val($(":input[name='jobTitle']").val());
//						$(":input[name='jobLocation']").val($(":input[name='jobLocation']",$("#jobInputForm")).val());
//						$(":input[name='jobDateRange']").val($(":input[name='jobDateRange']",$("#jobInputForm")).val());
						
						$.scrollTo("#section_"+newSectionId);
					}
				}
				resetAddJobForm();
				$(this).dialog('destroy');
			},
			'Cancel':function(){
				resetAddJobForm();
				$(this).dialog('destroy');
			}
		}
	});
}

function getEmployerJobs(sectionId)
{
	jobs = [];
	if ( $("#"+sectionId).attr("sectiontype") == 'employer' )
	{
		name = $("#xsl_employer_title",$("#"+sectionId)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Section';
		}
		jobs[sectionId] = name;
	}
	$.each($("[sectiontype='job']",$("#"+sectionId)), function(idx,val){
		name = $(this).attr("sectiontype") == 'job' ?
					$("#xsl_job_title",$(this)).text() : 
					$("#xsl_employer_title",$(this)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Section';
		}
		jobs[$(this).attr("id")] = name;
	});
	return jobs; 
}

function getTopLevelSections()
{
	sections = [];
	$.each($("#margins_1").children("[sectiontype]").not(":hidden"), function(idx,val){
		name = $("#xsl_section_name",$(this)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Section';
		}
		sections[$(this).attr("id")] = name;
	});
	return sections;
}

//open add section form
function showAddSectionForm()
{
	var sectionSelect = $("#targetSection:select"); 
	$.each($("#margins_1").children("[sectiontype]").not(":hidden"), function(idx,val){
		name = $("#xsl_section_name",$(this)).text();
		if ( name == undefined || trim(name,' ') == '')
		{
			name = 'Untitled Section';
		}
		sectionSelect.append('<option value="'+$(this).attr("id") + '" selected="selected">' + name + '</option>');
	});

	//add general section
	$("#linkSection_general").click(function(e){
		addSection('general');
		resetAddSectionForm();
		$("#addSectionDialog").dialog('destroy');
		e.stopPropagation();
		e.preventDefault();
		e.stopImmediatePropagation();
	});

	//add experience section
	$("#linkSection_experience").click(function(e){
		addSection('experience');
		resetAddSectionForm();
		$("#addSectionDialog").dialog('destroy');
		e.stopPropagation();
		e.preventDefault();
		e.stopImmediatePropagation();
	});

	//add hybrid section
	$("#linkSection_hybrid").click(function(){
		addSection('hybrid');
		resetAddSectionForm();
		$("#addSectionDialog").dialog('destroy');
		e.stopPropagation();
		e.preventDefault();
		e.stopImmediatePropagation();
	});

	var topBarContent ='<h3 class="arrowModalWindow">Add Section</h3>';

	if (isDocumentEmpty() ) { $("#insertDetails").hide(); }
	else{
		$("#insertDetails").show();
	}

	//this id is in ordocument/templates/AddSectionDialog.tpl
	$("#addSectionDialog").dialog({
		title: topBarContent,
		bgiframe: true,
		resizable: false,
		height:480,
		width:610,
		modal: true,
		close: function() {
		$(this).dialog('destroy');
		},
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});
}


  
//open add/delete employer/job modal window - experience section
function jsLoadModalExperienceAddJobEmployer(sectionId)
{
	var experienceSectionName = $("#xsl_section_name",$("#"+sectionId)).html();
	if (experienceSectionName=="")
	{
		experienceSectionName = "Untitled Section";
	}
	var diag = $("#addJobEmployerDialog"); //this ID is in ordocument/templates/AddJobDialog.tpl
	var topBarContent ='<h3 class="arrowModalWindow">'+experienceSectionName+'</h3>';
	var sectionEmployersJobsList= getSectionChildrenMenu("addJobEmployerDialog",sectionId);
	var sectionBottomLinks = "";
	var action = "$(\'#addJobEmployerDialog\').dialog('destroy')";
	//experience section
	if (($("#"+sectionId).attr("sectionType")=="experience") || ($("[myparentnode='"+sectionId+"']").attr("sectionType")=="employer") || ($("[myparentnode='"+sectionId+"']").attr("sectionType")=="employer_multiple_jobs") || ($("[myparentnode='"+sectionId+"']").attr("sectionType")=="job")){
		var id=0;
		($("#"+sectionId).attr("sectionType")=="experience")? id=$("#"+sectionId).attr("id").split("_")[1]:id= $("[myparentnode='"+sectionId+"']").attr("id").split("_")[1];
		sectionBottomLinks +='<p style="margin-top:20px; padding:10px; font-weight: bold; clear: left;"> \
	  							<span class="or20_CheckButton"><a href="javascript:void(0);" onclick="showNewEmployerForm('+id+', \'after\',false);scrollToSection(\''+sectionId+'\');'+action+';" class="or20_BigButton">Add Employer</a>\
	  							</span> or <a href="javascript://" onclick="'+action+'.dialog(\'destroy\')">Cancel</a>\
	  							<span id="loadingAddEmployer" style="display:none;"><img src="/images/or20/or20_ajax-loader_small.gif" border="0" /></span>\
	  							</p>';
	}

	//hybrid section
	if (($("#"+sectionId).attr("sectionType")=="hybrid") || ($("[myparentnode='"+sectionId+"']").attr("sectionType")=="subsection")) {
		var id=0;
		($("#"+sectionId).attr("sectionType")=="hybrid")? id=$("#"+sectionId).attr("id").split("_")[1]:id= $("[myparentnode='"+sectionId+"']").attr("id").split("_")[1];
		sectionBottomLinks +='<p style="margin-top: 20px; padding: 10px; font-weight: bold; clear: left;"> \
				<span class="or20_CheckButton"><a href="javascript:void(0);" onclick="showNewOrganizationForm('+id+', \'after\',false);scrollToSection(\''+sectionId+'\');'+action+';" class="or20_BigButton">Add Organization</a>\
				</span> or <a href="javascript://" onclick="'+action+'.dialog(\'destroy\')">Cancel</a>\
				<span id="loadingAddOrganization" style="display:none;"><img src="/images/or20/or20_ajax-loader_small.gif" border="0" /></span>\
				</p>';
	}
	
	var windowContent =  $("#divAddJobJsContent").html('<ul id="listEmployersJobs" class="or20_Work_Experience_Main_List">'+sectionEmployersJobsList+'</ul>'+sectionBottomLinks+'<input type="hidden" name="parentSectionIdHidden" id="parentSectionIdHidden" value="'+sectionId+'" />'); //add content that you build on fly with javascript
	  
  diag.dialog({
				title: topBarContent,
				bgiframe: true,
				resizable: false,
				minHeight:400,
				width:630,
				modal: true,
				close: function() {
  				$(this).dialog('destroy');
  				 $("#divAddJsContent").html();
  				}

		});
}

function handleSectionHighlighting(e)
{
//	console.log(e.type + " = " + e.target.nodeName + " = " + e.target.id);
	section = $(e.target);
	topLevelSection = $(e.target);
	
	while(true)
	{
		if ( topLevelSection.attr('sectiontype') != undefined && topLevelSection.attr('sectiontype') != '' )
		{
			break;
		}
		topLevelSection = topLevelSection.parent();
	}
	while(topLevelSection.attr("myparentnode") != undefined && topLevelSection.attr("myparentnode") != '')
	{
		topLevelSection = $("#"+topLevelSection.attr("myparentnode"));
	}
	while(true)
	{
		if ( section.attr('sectiontype') != undefined && section.attr('sectiontype') != '' )
		{
			break;
		}
		section = section.parent();
	}

	$("li[orsectionid='"+topLevelSection.attr("id")+"']").css({
		backgroundColor: e.type == 'mouseover' ? hoverColor : ''
	});
	$("*", section).add(section).css({
		backgroundColor: e.type == 'mouseover' ? hoverColor : ''
	});
	e.stopPropagation();

}

function disableSectionHighlighting()
{
	$("*", $("[sectiontype]").not(":hidden")).add("[sectiontype]").not(":hidden").css({
		backgroundColor: ''
	});
	//$("[sectiontype]:visible").die('mouseover',handleSectionHighlighting);
	//$("[sectiontype]:visible").die('mouseout',handleSectionHighlighting);
}

function initSectionHighlighting()
{
	//$("[sectiontype]:visible").live('mouseover', handleSectionHighlighting);
	//$("[sectiontype]:visible").live('mouseout', handleSectionHighlighting);
}


function closePrestylePreview()
{
	$("#documentPrestylePreviewWindow").remove();
	$("#transparentBackground").remove();
}

function useThisPrestyle(styleId)
{
	if (confirm("Are you sure you want to use this style?"))
	{
		applyPreStyle(styleId);
		closePrestylePreview();
		JsLoadContent('{moduleTable}','Stylist','hide');
		$(this).dialog('destroy');
	}
	/*too many modal windows
	$("body").append('<div id="confirmDialog">Are you sure you want to use this style?</div>');
	$("#confirmDialog").dialog({
			bgiframe: true,
			title: 'Apply Pre-style?',
			modal:true,
			buttons:{
				Cancel:function(){
					$(this).dialog('destroy');
				},
				Apply:function(){
					applyPreStyle(styleId);
					closePrestylePreview();
					JsLoadContent('{moduleTable}','Stylist','hide');
					$(this).dialog('destroy');
				}
			}
	});
	*/
	
}

var previewRunning = false;

function previewPrestyle(styleId, styleName)
{
	if ( !previewRunning )
	{
		previewRunning = true;
		$.ajax({
			type:'GET',
			url:'/modules/ordocument/stylist.php',
			data:{
				styleId:styleId,
				module:$("#documentType").attr("value")+'s',
				docid:$("#documentId").attr("value"),
				action:'previewPrestyle'
			},
			success: function(data)
			{
				jsonObj = JSON.parse(data);
				
				$("body").append('<div id="transparentBackground" style="opacity:0.5;filter:(Alpha=50);background-color:#555;z-index:500;position:absolute:top:0px;left:0px;height:100%;width:100%;"></div>');
				$("#transparentBackground").css({
					width: $(document).width(),
					height: $(document).height()
				});
				var topBarContent = '<div id="dialogHeader" style="height:30px;cursor:default;" class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">\
					<div style="padding:7px;left:320px;top:0px;position:relative;width:200px;">\
					 <span class="or20_PlusButton">\
					<a href="javascript:void(0);" onclick="useThisPrestyle('+styleId+');"  \
					class="or20_BigButton">USE THIS STYLE</a></span>\
					</div>\
					<a href="javascript:void(0);" onclick="closePrestylePreview();" class="ui-dialog-titlebar-close ui-corner-all" role="button" unselectable="on" style="-moz-user-select: none;">\
					<span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">close</span>\
					</a>\
					</div>';
				
					
				$("body").append('<div id="documentPrestylePreviewWindow" class="ui-dialog ui-widget ui-widget-content ui-corner-all undefined ui-draggable ui-resizable" style="display:none;">'+ 
						topBarContent + '<div id="documentScrollArea"><div id="documentPreviewArea"></div></div></div>');
				$("#documentPrestylePreviewWindow").css({
					width:800,
					position:'fixed',
					zIndex: 9999,
					top:0,
					left:($(window).width() / 2) - 400,
					backgroundColor:'white',
					height:$(window).height()-40,
					overflow:'hidden'
				});
				$("#documentScrollArea").css({
					height:$(window).height()-80,
					overflowY:'auto',
					overflowX:'hidden'
				});
				$("#documentPreviewArea").css({
					marginTop:jsonObj.prestyleValues.marginTop + "in",
					marginLeft: jsonObj.prestyleValues.marginLeftRight + "in",
					marginRight:jsonObj.prestyleValues.marginLeftRight + "in",
					marginBottom:jsonObj.prestyleValues.marginBottom + "in"
				});
				$("#documentPreviewArea").empty().append(jsonObj.documentHtml);
				$("#documentPrestylePreviewWindow").show();
				previewRunning = false;
				
			}
		});
	} else { 
		return false;
	}
}

function fireAutoGrow()
{
	
	if (autoGrowPlugin != null)
		autoGrowPlugin.Check();
}

function findParentSection(element)
{
	var id = undefined;
	var parentEls = $(element).parents("[sectiontype]");
	for( var i = 0; i < parentEls.length; i++ )
	{
		var thisEl = $(parentEls[i]);
		if ( thisEl.attr("id") != undefined && thisEl.attr("id").indexOf("section_") > -1 )
		{
			id = thisEl.attr("id");
			break;
		}
	}
	return id;
}

function displayCurrentlyEditingDialog(e)
{
	var msg = "";
	
	var id = (e.target.id == 'controlPanelOverlay' || e.target.id == 'docTopToolbarOverlay') ? 
			e.target.id : findParentSection($(e.target));
	if ( editableSectionId == undefined || id == undefined ||
			id == editableSectionId || 
			$("#"+editableSectionId).attr("myparentnode") == id 
			|| $("#"+id, "#editBackground").length > 0 ||
			$("#editBackground","#"+id).length > 0 )
	{
		e.stopImmediatePropagation();
		return;
	}
	if ( e.target.id == 'controlPanelOverlay'){
		msg = " the Control Panel."
	}
	else {
		msg = " another section.";
	}
	$("body").append('<div id="currentlyEditingDialog" title="You are currently in edit mode">\
			<p style="padding:10px;">\
			You are currently editing a section of your document.\
			Please save or cancel the active section before accessing '+msg+'\
			</p></div>');
	$("#currentlyEditingDialog").dialog({
		bgiframe: true,
		resizable: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'OK': function() {
				$(this).dialog('destroy');
				$(this).remove();
				$.scrollTo("#"+editableSectionId);
			}
		},
		close: function(event,ui){
			$(this).dialog('destroy');
			$(this).remove();
			$.scrollTo("#"+editableSectionId);
		}
	});
//	e.stopPropagation();
	e.stopImmediatePropagation();
}

function addEditOverlay(sectionId)
{
	$("#general_form").not(":hidden").wrap('<div id="editBackground"></div>');
	
	$("#editBackground").css({
		backgroundColor: 'rgb(233,243,255)',
		borderTop: '1px solid #5593C3',
		borderBottom : '1px solid #5593C3',
		borderLeft : '1px solid #5593C3',	
		borderRight : '1px solid #5593C3'	
	});
	
	$("#editBackground > *").css({
		backgroundColor: 'rgb(233,243,255)'
	});
	
	$("#docTopToolbar").append('<div id="docTopToolbarOverlay"></div>');

	$("#docTopToolbarOverlay").css({
		backgroundColor:'white',
		opacity:0.1,
		position:'absolute',
		width:$("#docTopToolbar").width(),
		height: $("#docTopToolbar").height() + 20, // +20 is to account for the margin
		left:0,
		top:0,
		zIndex:10
	});
	
	$("#controlPanelWrapper").append('<div id="controlPanelOverlay"></div>');
	var overlayHeight = parseInt($("#controlPanelWrapper").height());
	overlayHeight -= parseInt($(".or20_Header_Inside_Menu:last").height());
	$.each($(".or20_Header_Inside_Menu:last").next(),function(idx,val){
		overlayHeight -= parseInt($(val).height());
	});
	
	$("#controlPanelOverlay").css({
		backgroundColor:'white',
		opacity:0.1,
		position:'absolute',
		width: $("#controlPanelWrapper").width(),
		height: overlayHeight,
		left: 0,
		top: 0,
		zIndex: 1000
	});
	
	// Add click event listener to the editBackground div so that when a user is in edit mode 
	// if they click on the control panel they are alerted as to why none of the actions are 
	// enabled.
	$("#controlPanelOverlay").click(function(e){
		displayCurrentlyEditingDialog(e,sectionId);
	});
	
	// Add click event listener to the editBackground div so that when a user is in edit mode 
	// if they click on the control panel they are alerted as to why none of the actions are 
	// enabled.
	$("#docTopToolbarOverlay").click(function(e){
		displayCurrentlyEditingDialog(e,sectionId);
	});
	
	clear();
}

function removeEditOverlay()
{
	$("#editBackground").css({
		backgroundColor: 'white'
	});
	$("#controlPanelOverlay").remove();
	$("#docTopToolbarOverlay").remove();
}
var FCKBrowserInfo =
{
	IsIE		: /*@cc_on!@*/false,
	IsIE7		: /*@cc_on!@*/false && ( parseInt( navigator.userAgent.toLowerCase().match( /msie (\d+)/ )[1], 10 ) >= 7 ),
	IsIE6		: /*@cc_on!@*/false && ( parseInt( navigator.userAgent.toLowerCase().match( /msie (\d+)/ )[1], 10 ) >= 6 ),
	IsSafari	: navigator.userAgent.toLowerCase().indexOf(' applewebkit/') > 0,		// Read "IsWebKit"
	IsOpera		: !!window.opera,
	IsAIR		: navigator.userAgent.toLowerCase().indexOf(' adobeair/') > 0,
	IsMac		: navigator.userAgent.toLowerCase().indexOf('macintosh') > 0
} ;


var divForDebug;
$(document).ready(function()
{
	/*
	var div = document.createElement('div');
	//div.className = 'or20_WrapHorizontal';
	div.style.border = "1px solid black";
	div.innerHTML = "<br><br><br>Dupa<br><Br><Br>";
	div.id = "div_for_debug";
	divForDebug = div;
	document.body.appendChild(div);
	*/
});



function appendDebug(msg)
{
	
//	$("#div_for_debug")[0].innerHTML = msg + "-" + $("#div_for_debug")[0].innerHTML;
}

/*
*	function launchDocumentRevisionTool(docid)
*	this function is used to launch the revision tool interface.
*
*/

function launchDocumentRevisionTool(docid)
{
	$("body").append('<div id="transparentBackground" style="opacity:0.5;filter:(Alpha=50);background-color:#555;z-index:500;position:absolute:top:0px;left:0px;height:100%;width:100%;"></div>');
	$("#transparentBackground").css({
		width: $(document).width(),
		height: $(document).height()
	});
	var topBarContent = '<div id="dialogHeader" style="height:30px;cursor:default;" class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">\
		<div style="padding:10px;left:320px;top:-5px;position:relative;width:200px;">\
		 <span class="or20_PlusButton">\
		<a href="javascript:void(0);" onclick="useThisRevision();"  \
		class="or20_BigButton">USE THIS VERSION</a></span>\
		</div>\
		<a href="javascript:void(0);" onclick="closeRevisionWindow();" class="ui-dialog-titlebar-close ui-corner-all" role="button" unselectable="on" style="-moz-user-select: none;">\
		<span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">close</span>\
		</a>\
		</div>';
	
		
	$("body").append('<div id="documentRevisionWindow" class="ui-dialog ui-widget ui-widget-content ui-corner-all undefined ui-draggable ui-resizable" style="display:none;">'+ 
			topBarContent + '<div id="documentScrollArea"></div></div>');
	$("#documentRevisionWindow").css({
		width:800,
		position:'fixed',
		zIndex: 9999,
		top:0,
		left:($(window).width() / 2) - 400,
		backgroundColor:'white',
		height:$(window).height()-40,
		overflow:'hidden'
	});
	$("#documentScrollArea").css({
		height:$(window).height()-80,
		overflowY:'auto'
	});

	
	$.ajax({
		async: false,
		url: '/modules/revisiontool/entry.php',
		data: {
			action: 'listDocumentRevisions',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value')
		},
		success: function(data,textMessage){
		   	$('#documentScrollArea').append(data);
		   	$("#documentRevisionWindow").show();
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});

	$("#documentWrapper").css({
		'min-height': $(window).height()-80
	});
	
	$("#documentPreview").css({
		'min-height':$(window).height()-80
	});
	
	
}

function getRevision()
{
	$.ajax({
		async: false,
		url: '/modules/revisiontool/entry.php',
		data: {
			action: 'getRevision',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value'),
			revisionId: $(":select#revisionId option:selected").val()
		},
		success: function(data,textMessage){
		   	$("#documentPreview").empty().append(data);
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function useThisRevision()
{
	$.ajax({
		async: false,
		url: '/modules/revisiontool/entry.php',
		data: {
			action: 'applyRevision',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value'),
			revisionId: $(":select#revisionId option:selected").val()
		},
		success: function(data,textMessage){
		   	$("#margins_1").empty().append($("#documentPreview > *"));
		   	$("#transparentBackground").remove();
		   	$("#documentRevisionWindow").remove();
		   	initDocAjax();
		   	if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function closeRevisionWindow()
{
	$("#transparentBackground").remove();
   	$("#documentRevisionWindow").remove();	
}

function undoStyle()
{
	if ( $("#undoDisabledBtn:visible").length > 0 )
	{
		return;
	}
	$.ajax({
		beforeSend: function(xmlReq){
			$("#undoRedoAjaxIndicator").show();
		},
		url: '/modules/ordocument/index.php',
		data: {
			action: 'undoStyle',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value')
		},
		dataType:'json',
		success: function(data,textMessage){
			$('#moduleCanvas').replaceWith(data.document);
//			debugStylist(data);
			handleStylistBufferChanges(data);
			updateStylistControls(data.styleObj);
			initDocAjax();
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
			$("#undoRedoAjaxIndicator").hide();
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function redoStyle()
{
	if ( $("#redoDisabledBtn:visible").length > 0 )
	{
		return;
	}
	$.ajax({
		beforeSend: function(xmlReq){
			$("#undoRedoAjaxIndicator").show();
		},
		url: '/modules/ordocument/index.php',
		data: {
			action: 'redoStyle',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value')
		},
		dataType:'json',
		success: function(data,textMessage){
			$('#moduleCanvas').replaceWith(data.document);
//			debugStylist(data);
			handleStylistBufferChanges(data);
			updateStylistControls(data.styleObj);
			initDocAjax();
			if ( SpellChecker.active == true )
			{
				SpellChecker.checkAsync();
			}
			$("#undoRedoAjaxIndicator").hide();
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function debugStylist(data)
{
	if ( console )
	{
		console.log(data.position);
		console.log(data.showUndo);
		console.log(data.showRedo);
		console.log(data.size);
	}
}

function handleStylistBufferChanges(data)
{
	if ( data.showUndo == false || data.size == 0)
	{
		$("#undoEnabledBtn").hide();
		$("#undoDisabledBtn").show();
	}
	else
	{
		$("#undoEnabledBtn").show();
		$("#undoDisabledBtn").hide();
	}
	if ( data.showRedo == false || data.size == 0 )
	{
		$("#redoEnabledBtn").hide();
		$("#redoDisabledBtn").show();
	}
	else
	{
		$("#redoEnabledBtn").show();
		$("#redoDisabledBtn").hide();
	}
}

function getStylistBufferData()
{
	$.ajax({
		url: '/modules/ordocument/index.php',
		data: {
			action: 'getBufferInfo',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value')
		},
		dataType:'json',
		success: function(data,textMessage){
			handleStylistBufferChanges(data)
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function getStylistValues()
{
	$.ajax({
		url: '/modules/ordocument/index.php',
		data: {
			action: 'getStylistValues',
			docid: $('#documentId').attr('value'),
			module: $('#documentType').attr('value')
		},
		dataType:'json',
		success: function(data,textMessage){
			updateStylistControls(data);
		},
		complete: function (XMLHttpRequest, textStatus) {

		}
	});
}

function updateStylistControls(style)
{
	for( key in style )
	{
		if ( style[key] == undefined || style[key] == "")
		{
			continue;
		}
		// FB 1092
		if ( $('#documentType').attr('value') == 'resume' || $('#documentType').attr('value') == 'resumes' )
		{
			// FB 109
			if ( key == 'styleBody' && style[key] == '2 Columns')
			{
				var src = $("img.experienceOptionImg[src*='or20_Experience7']").attr("src");
				$("img.experienceOptionImg[src*='or20_Experience7']").attr("src",src.replace("or20_Experience7","or20_Experience7_2column"));
			}
			else if ( key == 'styleBody' && style[key] == 'Standard')
			{
				var src = $("img.experienceOptionImg[src*='or20_Experience7']").attr("src");
				$("img.experienceOptionImg[src*='or20_Experience7']").attr("src",src.replace("or20_Experience7_2column","or20_Experience7"));
			}
			
			if ( key == 'styleBody' && style[key] == 'Standard' )
			{
				$(":input[name='firstcellpercentasdecimal']").parent().parent().hide();
			} else if ( key == 'styleBody' && style[key] == '2 Columns')
			{
				$(":input[name='firstcellpercentasdecimal']").parent().parent().show();
			}
		}
		if ( key == 'headerFormat' )
		{
			loadHeaderFormatTemplate($("img[name='"+key+"'][value='"+style[key]+"']"));
		}
		var control = $("[name='"+key+"'][type!='hidden']");
		if ( control.length > 0 )
		{
			var node = control[0].nodeName.toLowerCase();
			if ( node == "input" && control.attr("type") == "checkbox" )
			{
				node = "checkbox";
			}
			else if ( node == "input" && control.attr("type") == "radio" )
			{
				node = "radio";
			}
			
			switch(node)
			{
				case "select":
					control.children("option[value='"+style[key]+"']").attr("selected","selected");
					if ( $("#imageSelect_container_"+key).length > 0 )
					{
						// This is a templatedSelect control
						$("#imageSelect_container_"+key).remove();
						renderTemplateSelect(key);
					}
					break;
				case "img":
					if ( style[key] == undefined || style[key] == null ){
						break;
					}
					if ( key.indexOf("FontCase") > -1 )
					{
						var value = style[key];
						$.each(control, function(idx,val){
							if ( $(this).attr("value") == value && $(this).attr("src").indexOf("_selected") == -1)
							{
								$(this).attr("src",$(this).attr("src").replace(".gif","_selected.gif"));
							}
							else if ( $(this).attr("value") != value )
							{
								$(this).attr("src",$(this).attr("src").replace("_selected",""));
							}
						});
						break;
					}
					else
					{
						var values = style[key].split(' ');
						$.each(control, function(idx,val){
							var tVal = $(this).attr("value");
							var containsValue = values.contains(tVal);
							if ( !containsValue )
							{
								$(this).attr("src",$(this).attr("src").replace(/_selected/,""));
							}
							else if (containsValue && $(this).attr("src").indexOf("_selected") == -1 )
							{
								$(this).attr("src",$(this).attr("src").replace(/\.gif/,"_selected.gif"));
							}
						});
					}
					break;
				case "checkbox":
					var styleValue = style[key];
					$.each(control, function(idx,val){
						if ( styleValue == $(this).attr("value") )
						{
							$(this).attr("checked","checked");
						} else {
							$(this).removeAttr("checked");
						}
					});
					break;
			}
		}
		else
		{
			continue;
		}
	}

}

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
