var numPages = 1;
var dpi = 72;
var pageWidth = 612;
var pageHeight = 792;

var paperWidth = 8.5;
var paperHeight = 11;
var paperType = 'US Letter';
var leftMargin = 18;
var rightMargin = 18;
var topMargin = 18;
var bottomMargin = 18;
var editmode=false; //variable used to find out if the menu is already showing or not
var mode = "edit";

$(document).ready(function(){
	initDoc();
});

function initDoc(){
	// IF the viewMode element exists on the page then we are showing the resume/letter
	// in the module container
	if ($("#viewMode").length > 0){
		initForms();
		init();
		initFck();
		initFckEmployerDescription();
		showMarginMarkers();
		initControlPanel();
	}
}

function initDocAjax(){
	// this function is used when the doc is reloaded with AJAX, but we do not need
	//to reinitialize the fcks. Otherwise it takes too long and there is a synchronization issue
	if ($("#viewMode").length > 0){
		initForms();
		init();
		showMarginMarkers();
		initControlPanel();
		$(window).trigger("scrollTo");
//		bindSectionEvent();
	}
}

//escape \,',"" using javascript
function encodeTitle(string)
{
	string=string.replace(/\\/g,'\\\\');
	string=string.replace(/\'/g,'\\\'');
	string=string.replace(/\"/g,'\\"');
	string=string.replace(/\0/g,'\\0');
	
	return string;
}

function showMarginMarkers()
{
	var offset = $('#maincontent').offset();
	var width = $("#margins_1").outerWidth(true);
	var height = $("#margins_1").outerHeight(true);
	var mcPosition = $("#maincontent").position();

	$('#tbMarginControlLabelTop').css({
		top: topMargin - 3,
		left: -45
	});
	$('#tbMarginControlLabelBottom').css({
		top: $("#maincontent").height() + bottomMargin - 3,
		left: -45
	});
	$('#lrMarginControlLabelLeft').css({
		left: leftMargin - $('#lrMarginControlLabelLeft').outerWidth(true) + 3,
		top: -1 * $("#lrMarginControlLabelLeft").outerHeight(true)
	});
	$('#lrMarginControlLabelRight').css({
		left: pageWidth-rightMargin - 3,
		top: -1 * $("#lrMarginControlLabelRight").outerHeight(true)
	});
	$('.margin-marker').bind("click",function(e){
		if ($("#documentType").val() == 'resume') {
			showStylist(false,true);
		} else if ( $("#documentType").val() == 'letter')
		{
			showStylist(false,true);
		}
		else{
			showStylist(false,false);
		}
	});

	$('.margin-marker').show();
}

function init()
{
	editmode=true
	 
	var mType = $("#viewMode").attr("value");
	mode = mType;

	var pType = $("#paperSize").attr("value");
	paperType = pType;
	if ( pType == 'A4' )
	{
		paperWidth = 8.3;
		paperHeight = 11.7;
	}
	
	numPages = 1;
	var ruler = $('#ruler');
	var inchOrCm = $(":input[name='marginUnit']").val();
	dpi = $('#ruler')[0].offsetWidth;
	pageWidth = paperWidth * dpi;
	pageHeight = paperHeight * dpi;

	if ( inchOrCm == 'in' )
	{
		leftMargin = rightMargin = $("#marginLeftRight").attr("value") * dpi;
		topMargin = $("#marginTop").attr("value") * dpi; 
		bottomMargin = $("#marginBottom").attr("value") * dpi;
	}
	else
	{
		leftMargin = rightMargin = (0.3937008 * parseFloat($("#marginLeftRight").attr("value"))) * dpi;
		topMargin = (0.3937008 * parseFloat($("#marginTop").attr("value"))) * dpi;
		bottomMargin = (0.3937008 * parseFloat($("#marginBottom").attr("value"))) * dpi;
	}
	editMode();
	postEditMode();
	
	/*$("#maincontent:visible").css({
		left: '30px'//( $("#or20_Wrapper").width() - $("#maincontent:visible").width() ) / 2
	});*/

}

function getSectionChildrenMenu(dialog,thisSection)
{
	var name = '';
	var markup = '';
	var action = "$(\'#"+dialog+"\').dialog('destroy')";
	$.each($("[myparentnode='"+thisSection+"']"), function(id2,val2){
		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 +='<li  id="row'+id+'" class="Work_ExperienceJob" >Job: '+name+'<a class="or20_Trash_Item_Work" href="javascript:void(0);" onclick="DeleteSection(\''+id+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(name) + '\');">\
									<img src="/images/or20/or20_Work_Experience_Trash_can.png" alt="Trash" border="0" /></a>\
									</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+='<li id="row'+id+'" class="Work_Experience_List_Item"><span class="or20_Employer_Name">'+name+'</span> \
				<a class="or20_Trash_Item_Work" href="javascript://" onclick="DeleteSection(\''+id+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(name) + '\');"><img src="images/or20/or20_Work_Experience_Trash_can.png" alt="Trash" border="0" /></a>\
				</li>';
				break;
			case 'employer':
				name = $("#xsl_employer_name",$(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Employer';
				}
				var title = $("#xsl_employer_title",$(this)).text();
				var id = $(this).attr("id").split("_")[1];
				markup+='<li id="row'+id+'" class="Work_Experience_List_Item"><span class="or20_Employer_Name">'+name+'</span> \
				<a class="or20_Add_Job_To_Employer" href="javascript:void(0);" onclick="'+action+';changeSectionType('+id+',\'employer\',\'employer_multiple_jobs\'); scrollToSection(\''+$(this).attr("id")+'\');">Add Job at this Employer</a> \
				<a class="or20_Trash_Item_Work" id="deleteEmployersLink'+id+'" href="javascript://" onclick="DeleteSection(\''+id+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(name) + '\');"><img src="images/or20/or20_Work_Experience_Trash_can.png" alt="Trash" border="0" /></a>\
				<ul class="or20_Work_Experience_Job_List">\
				<li  class="Work_ExperienceJob" >Job: '+title+'<a class="or20_Trash_Item_Work" href="javascript:void(0);" onclick="DeleteSection(\''+id+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(title) + '\');">\
				<img src="/images/or20/or20_Work_Experience_Trash_can.png" alt="Trash" border="0" /></a>\
				</li>\
				</ul>\
				</li>';
				break;
			case 'employer_multiple_jobs':
				name = $("#xsl_employer_name", $(this)).text();
				if ( name == '' || name == undefined)
				{
					name = 'Untitled Employer';
				}
				var id = $(this).attr("id").split("_")[1];
				markup+='<li id="row'+id+'" class="Work_Experience_List_Item"><span class="or20_Employer_Name">'+name+'</span> \
									<a class="or20_Add_Job_To_Employer" href="javascript:void(0);" onclick="'+action+';showNewJobForm('+id+',\'after\');scrollToSection(\''+$(this).attr("id")+'\');">Add Job at this Employer</a> \
									<a class="or20_Trash_Item_Work" href="javascript://" onclick="DeleteSection(\''+id+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(name) + '\');"><img src="images/or20/or20_Work_Experience_Trash_can.png" alt="Trash" border="0" /></a>';
				var jobsList = getSectionChildrenMenu(dialog,$(this).attr("id"));
				if (jobsList!='')
				{
					markup+='<ul class="or20_Work_Experience_Job_List">'+jobsList+'</ul>';
				}	

				markup+='</li>';
				break;
			}
			
			
			
		});

	return markup;
}


function initControlPanel()
{
	
	$("#sectionListing").empty();
	$.each($("#margins_1").children("[sectiontype]:visible"), function(idx,val){

		if ($("#documentType").attr("value")=="letter" ){
			if (isDocumentEmpty()==true){
				var targetId = findMaxSection(); 
				$("#controlSectionListing").html('<li><a href="javascript:void(0);" class="or20_AddSection_Menu_Right"  onclick="showNewSectionForm(\''+targetId+'\',\'\');">Add Content</a></li>');
			}else{
				$("#or20_Header_Inside_Menu").css("display","none");
				$("#sectionListingUl").css("display","none");
			}
		}else{
			
			var sectionTitle = $("#xsl_section_name",$(this)).text();
			var classSection = "";	
			if ( sectionTitle == undefined || trim(sectionTitle,' ') == '') 
			{
				sectionTitle = 'Untitled Section';
				classSection = 'class="noSectionName"';	
			}

			var rowMarkup = '<li id="sectionRow_' + idx + '" orsectionid="'+$(this).attr("id")+'" '+classSection+'>\
			<a href="javascript://" class="or20_Section_Item" id="sectionTitle_' + idx + '" onclick="scrollToSection(\''+$(this).attr("id")+'\');"></a>\
			<span class="or20_Section_Delete" id="deleteSectionIcon_' + idx + '">\
				<a href="javascript://" onclick="DeleteSection(\''+$(this).attr("id").split("_")[1]+'\',\'' + $(this).attr("sectiontype") + '\',\''+ encodeTitle(sectionTitle) + '\');">\
					<img src="/images/or20/or20_Menu_Section_Delete.png" border="0" />\
				</a>\
			</span>';
				
			var tpMarkup='';
			switch($(this).attr("sectionType")){
				case "hybrid":
					var hibridSectionId=0; 	
					rowMarkup += '<a class="or20_Add_Delete_Employer_Job" href="javascript:void(0);" onclick="jsLoadModalExperienceAddJobEmployer(\''+$(this).attr("id")+'\')">Add/Delete Organization</a>';
					 break;
				case "experience":
				case "employer":
				case "employer_multiple_jobs":
					var experienceSectionId=0; 	
					rowMarkup += '<a class="or20_Add_Delete_Employer_Job" href="javascript:void(0);" onclick="jsLoadModalExperienceAddJobEmployer(\''+$(this).attr("id")+'\')">Add/Delete Employer/Job</a>';
					break;
			}
			rowMarkup+='</li>';
			var row = $(rowMarkup);
	
			if (sectionTitle.length>18){
				sectionTitle = sectionTitle.substring(0,16)+"...";
			}
		
			$("#sectionTitle_"+idx, row).append(sectionTitle);
			$("#sectionListing").append(row);
		}
	});	
	
	if ($('#sectionListing').children().size()>8)
	 {
		$("#sectionListing li:gt(7)").hide();
		var rowMarkup = '<li class="or20_noListArrow" id="showAllDocsSections"><img src="/images/or20/or20_ShowAllSections.png" border="0" style="cursor:pointer;" onclick="JsSectionsSlide(\'showAllDocsSections\')" /></li>\
			<li class="or20_noListArrow" id="hideAllDocsSections" style="display:none;"><img src="/images/or20/or20_CollapseSections.png" border="0" style="cursor:pointer;" onclick="JsSectionsSlide(\'hideAllDocsSections\')" /></li>';
		var row = $(rowMarkup);
		$("#sectionListing").append(row);
	 }
	
}


//control panel sections slide . if there are more then 8 sections show an expand link
function JsSectionsSlide(id)
{
	if (id=="hideAllDocsSections")
 	{
 		$("#sectionListing li:gt(7)").slideUp(500);
		$("#showAllDocsSections").show();
		$("#hideAllDocsSections").hide();
 	}
 	else
 	{
 		$("#sectionListing li:gt(4)").show();
 		$("#showAllDocsSections").hide();
		$("#hideAllDocsSections").show();
 	}
}


function showHoverMenu(h,idn){
	var yPos = h.offsetTop;
	var xPos = h.offsetLeft;
	var seDiv = $("#experienceMenuOpen"+idn);
	
	$("#sectionListing li").removeClass("or20_Section_Select");
	$('#sectionRow_'+idn).addClass("or20_Section_Select");
	$('div .or20_Box_Outside_Resume_Menu').hide();
	
	//var wrapperOffsetTop = $("#controlPanelWrapper").offset().top;
	var varScrollTop = $(window).scrollTop();
	$("#experienceMenuOpen"+idn).css("position","absolute");
	$("#experienceMenuOpen"+idn).css("display","block");

	$("#experienceMenuOpen"+idn).css("right", "141px"); 
	if (varScrollTop>323)
	{

		$("#experienceMenuOpen"+idn).css("top", yPos-50+"px");

	}
	else
	{

		$("#experienceMenuOpen"+idn).css("top", yPos-50+"px");

	
	}
	
}


function hideHoverMenu(idn)
{
	$("div[id^='experienceMenuOpen']").css("display","none");
	//var seDiv = document.getElementById('experienceMenuOpen'+idn);
	//seDiv.style.display = 'none';
}

function previewMode()
{
//	editmode=false;
	$('.maincontent',$('#printPreviewDisplayContainer')).css(
		{
			width:pageWidth+'px',
			height:pageHeight+'px',
			padding:0,
			marginTop: 30,
			marginLeft:10
		});

	setPageMargins();

	$(".pageMargins",$("#printPreviewContainer")).trigger("resize");
}

function postEditMode()
{
	var firstPageMargin = $("#margins_1");
	firstPageMargin.css("height", "auto");
	$(".maincontent").css({
		"min-height": pageHeight+'px',
		width: pageWidth,
		paddingBottom: (bottomMargin)+'px',
		paddingTop: topMargin+'px'
//		paddingLeft: leftMargin,
//		paddingRight: rightMargin
	});
	firstPageMargin.css({
		"min-height":(pageHeight)+'px',
		width: (pageWidth-leftMargin-rightMargin)+'px',
		left: leftMargin+'px'
	});
}

function editMode()
{
	 editmode=true;
	var firstPageMargin = $("#margins_1");
	
	// Move all content to the first page
	jQuery.each($(".pageMargins").contents(), function(index, val){
		// if this is the first page skip
		if ( $(val).parent().parent().attr("page") > 1)
		{
			// if the section was split remove the overflow
			if ( $(val).attr("issplit") == "true" && $(val).attr("ischild") == "true")
			{
				$(val).remove();
			}
			else
			{
				$(val).appendTo(firstPageMargin);
			}
		}
	});
	
	
	
	// Unhide all content that was previously hidden
	$('*[overflow="true"]', firstPageMargin).show();
	
	jQuery.each($('.maincontent'), function( index, val) {
		// remove all pages except the first
		if ( $(val).attr("page") > 1 )
		{
			$(val).remove();
		}
	});
	
	
	$('*',firstPageMargin).queue(function(){
		$(this).removeAttr("ischild");
		$(this).removeAttr("issplit");
		$(this).removeAttr("overflow");
	});
	
	$.each($("span.ortag"), function ( index, val ) {
		$(val).replaceWith($(val).text());
	});
	
	numPages = 1;

	//setPageMargins();
}

function setView(view)
{
	if ( view == 'preview' )
	{
		previewMode();
	}
	else
	{
		editMode();
		postEditMode();
	}
	$("#viewMode").attr("value", view);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function getWordCount()
{
	var wordCount = 0;
	var pages = $('.maincontent');
	for ( var i = 0; i < pages.length; i++ )
	{
		var page = $(pages[i]);
		var elements = $('*', page).contents();
		for ( var i = 0; i < elements.length; i++ )
		{
			var element = elements[i];
			if ( element.nodeType == 3 )
			{
				if ( element.nodeValue != null )
				{
					var txt = element.nodeValue.replace(/\f|\v|\t|\r|\n/gi, " ");
					txt = txt.replace(/  /gi, " ");
					txt = trim(txt);
					if ( txt.length > 0 )
					{
						wordCount += txt.split(" ").length;
					}
				}
			}
		}
	}
	return wordCount;
}

function getCharacterCount()
{
	var charCount = 0;
	var pages = $('.maincontent');
	for ( var i = 0; i < pages.length; i++ )
	{
		var page = $(pages[i]);
		var elements = $('*', page).contents();
		for ( var i = 0; i < elements.length; i++ )
		{
			var element = elements[i];
			if ( element.nodeType == 3 )
			{
				if ( element.nodeValue != null )
				{
					var txt = element.nodeValue.replace(/\f|\v|\t|\r|\n/gi, " ");
					txt = txt.replace(/  /gi, " ");
					txt = trim(txt);
					if ( txt.length > 0 )
					{
						charCount += txt.length;
					}
				}
			}
		}
	}
	return charCount;
}

function getTotalPages()
{
	return $(".maincontent[page]",$("#printPreviewContainer")).length;
}

function getCurrentPage()
{
	return $(".maincontent:in-viewport",$("#printPreviewContainer")).attr("page");

}

function bindMarginEvents()
{
	$('.pageMargins',$("#printPreviewContainer")).bind('change resize', function(e) {
		var pmDiv = $('.pageMargins',$("#printPreviewContainer"));
		
		for( var i = 0; i < pmDiv.length; i++ )
		{
			var thisDiv = $(pmDiv[i]);
			//console.log(e.type + ", checking overflow for pageMargins["+i+"]");
			//console.log(thisDiv[0].scrollHeight);
			var scrollHeight = Math.max(thisDiv[0].scrollHeight, thisDiv[0].clientHeight);
			var divHeight = thisDiv.height()+2;  // Add the 1px border value to the div height
			
			//console.log("Scroll Height: " + scrollHeight + ", DivHeight: " + divHeight);
			if ( scrollHeight > divHeight )
			{
				//console.log("Overflow detected: rolling to new page - " + thisDiv.attr("id") + " - " + thisDiv.parent().attr("page"));
				var p = thisDiv.parent().attr("page");
				rollToNewPage(scrollHeight,divHeight,p);
			}
			pmDiv = $('.pageMargins',$("#printPreviewContainer"));
		}
	});
}

function resetMarginEvents()
{
	$('.pageMargins',$("#printPreviewContainer")).unbind('change resize');
	bindMarginEvents();
}

function setPageMargins(initialize)
{
	$('.maincontent',$('#printPreviewDisplayContainer')).css(
		{
			width:pageWidth+'px',
			height:pageHeight+'px',
			padding:0,
			marginTop:0,
			marginRight:0,
			marginLeft: 10,
			marginTop:30,
			'float':'left'
		});
	$('.pageMargins',$("#printPreviewDisplayContainer")).css(
		{
			width:(pageWidth-leftMargin-rightMargin)+'px',
			height:(pageHeight-topMargin-bottomMargin)+'px',
			top: topMargin+'px',
			left: leftMargin+'px',
			minHeight:(pageHeight-topMargin-bottomMargin)+'px',
			overflowY: 'hidden'
		});
//	$('.pageMargins',$("#printPreviewDisplayContainer")).css('height',(pageHeight-topMargin-bottomMargin)+'px');
//	$('.pageMargins',$("#printPreviewDisplayContainer")).css('top',topMargin+'px');
//	$('.pageMargins',$("#printPreviewDisplayContainer")).css('left',leftMargin+'px');
}

function rollToNewPage(scrollHeight,divHeight,page)
{
	var t = $("div[page="+(parseInt(page)+1)+"]",$("#printPreviewContainer"));
	if ( t.length == 0 )
	{
		var template = $('#pageTemplate').clone();
		template.css({
			padding:0
		});
		template.attr("id","maincontent");
		template.append('<div id="margins_' + (numPages+1) + '" class="pageMargins"></div>');
		template.removeClass('hidden');
		numPages++;
		template.attr("page",numPages);
		$("div[page='" + (numPages-1) + "']",$("#printPreviewContainer")).parent().append(template);
		setPageMargins();
		//resetMarginEvents();
		//bindSortableEvents();
		
	}
	
	moveContentToNewPage(scrollHeight,divHeight,page);
	//$('#margins_'+(numPages)).trigger('change');
	$('#moduleCanvas',$("#printPreviewContainer")).css('height',(pageHeight*numPages) + 'px');
}

function processPartialOverflowElement(rootElement,destElement,divHeight)
{
	var rEl = $(rootElement);
	
	jQuery.each($('*',rEl).contents(), function(index, val){
		if ( val.nodeValue != null && val.nodeType == 3  && jQuery.trim(val.nodeValue).length > 0
				&& val.parentNode.childNodes.length > 1)
		{
			$(val).wrap("<span class=\"ortag\"/>");
		}
	});
	
	$('*',rEl).show();
	var stack = $("*",rEl);
	//console.log("Stack Size : " + stack.length);
	for (var i = stack.length-1, j = 0; i > j; i--) 
	{
		var cElement = stack[i];
		var jElement = $(cElement);
		var top = Math.round(jElement.position().top);
		var height = Math.round(jElement.height());
//		console.log(cElement.nodeName + " id= " + jElement.attr("id") + " Top: " +top + ", Height: " + height + ", Total: " + (top + height));
		
		if ( (top + height) >= divHeight && 
				$('*[overflow="true"]',cElement).size() == $('*',cElement).size())
		{
			jElement.attr("overflow","true");
		}
		else if ( (top + height) >= divHeight && 
				$('*[overflow="true"]',cElement).size() != $('*',cElement).size())
		{
			jElement.attr("overflow","partial");
		}
		else 
		{
			jElement.attr("overflow","false");
		}

//			console.log("TOP : " + top + ", HEIGHT : " + height + 
//					", TOTAL : " + (top + height) + 
//					", DIV HEIGHT: " + divHeight + ", TAG: " + cElement.nodeName + ",VALUE: "+jElement.attr("id"));
//			
		cElement = null;
		jElement = null;
	}
	var cloneElement = rEl.clone(true);
	$('*[overflow="true"]',rEl).hide();
	$('*[overflow="false"]',cloneElement).hide();
	
	destElement.prepend(cloneElement.children());
	$('table[overflow="partial"]').each(function(idx,val){
		if ( idx % 2 == 0 )
		{
			$(this).css('border-bottom','');
		}
		else
		{
			$(this).css('border-top','');
		}
	});
}

function moveContentToNewPage(scrollHeight,divHeight,page)
{
	var source = $('#margins_'+page,$("#printPreviewContainer"));
	var dp = parseInt(page) + 1;
	var dest = $('#margins_' + dp,$("#printPreviewContainer"));
	var overflowElements = new Array();

	jQuery.each(source.contents(), function(i,section) {
		if ( (section.offsetHeight + section.offsetTop) > divHeight ) {
			overflowElements.push(section);
		}		
	});

	for ( var x = overflowElements.length-1; x >= 0; x--)
	{
		var section = overflowElements[x];
		if ( section.offsetTop >= divHeight || 
				(section.offsetTop + section.offsetHeight > divHeight &&
				section.hasChildNodes() == false))  // Elements that have completely overflown get moved as is.
		{
			section= $(section);
			section.prependTo(dest);
		}
		else  // Partially overflown elements.  
		{
			var jSection = $(section).clone(true);
			$(section).attr("issplit", "true");
			if ( $("#"+section.id+"_1").length == 0 )
			{
				jSection.attr("id",section.id + "_1");
				jSection.attr("issplit", "true");
				jSection.attr("ischild", "true");
				jSection.empty();
				jSection.prependTo(dest);
			}
			else
			{
				jSection = $('#'+section.id+'_1');
				jSection.attr("issplit", "true");
				jSection.attr("ischild","true");
				jSection.empty();
			}
			processPartialOverflowElement(section,jSection,divHeight);
		}
			
	}
}

$.fn.textNodes = function() {
	  var ret = [];
	  this.each( function() {
	    var fn = arguments.callee;
	    $(this).contents().each( function() {
	      if ( this.nodeType == 3  ) 
	        ret.push( this );
	      else fn.apply( $(this) );
	    });
	  });
	  return $(ret);
	}

function closePrintPreview()
{
	$("#printPreviewContainer").remove();
	numPages = 1;
}

function setScale(scale)
{
	$.each($("#moduleCanvas .maincontent,.pageMargins", $("#printPreviewContainer")),function(idx,val){
		$(this).css({
			height: $(this).attr("orHeight") * scale,
			width: $(this).attr("orWidth") * scale,
			minHeight:''
		});
	});
	$.each($("#moduleCanvas .pageMargins", $("#printPreviewContainer")), function(idx,val){
		$(this).css({
			left: $(this).attr("orLeft") * scale,
			top: $(this).attr("orTop") * scale
		});
	});
	
	$.each($("#moduleCanvas .pageMargins > *",$("#printPreviewContainer")),function(idx,val){
			try
			{
				$(this).css("font-size",(parseInt($(this).attr("orFontSize"))*scale));
			} catch (err){}
	});
}

function setOriginalValues()
{
	$.each($("#moduleCanvas .maincontent,.pageMargins", $("#printPreviewContainer")),function(idx,val){
		$(this).attr("orHeight",$(this).height());
		$(this).attr("orMinHeight",$(this).css("min-height"));
		$(this).attr("orWidth",$(this).width());
	});
	$.each($("#moduleCanvas .pageMargins", $("#printPreviewContainer")), function(idx,val){
		$(this).attr("orLeft", $(this).position().left);
		$(this).attr("orTop", $(this).position().top);
	});
	
	$.each($("#moduleCanvas .pageMargins > *",$("#printPreviewContainer")),function(idx,val){
		var fsize = parseInt($(this).css("font-size"));
		$(this).attr("orFontSize", fsize);
	});
}

function sideBySidePreview(scale)
{
	$(':input[name="zoomLevel"] option').attr("selected","");
	$(':input[name="zoomLevel"] option[value=".50"]').attr("selected","selected");
	setScale(.50);
	$("#printPreviewDisplayContainer").scrollTo($(".maincontent[page='1']",$("#printPreviewContainer")),1000,{margin:true});
}

function gotoPage(pageNumber)
{
	
	try{
		if (pageNumber == undefined) {
			pageNumber = $(':input[name="gotoPageNumber"]').val();
		}
		if ( pageNumber < 1 || pageNumber > getTotalPages() )
		{
			return;
		}
		$("#printPreviewDisplayContainer").scrollTo($(".maincontent[page='"+pageNumber+"']",$("#printPreviewContainer")),1000,{margin:true});
		$("#pageX").html(pageNumber);
		$(":input[name='gotoPageNumber']").val("");
		if ( pageNumber >= getTotalPages() ){
			$("#nextPageBtn,#lastPageBtn,#previousPageBtn,#firstPageBtn").removeClass("buttonDisabled");
			$("#nextPageBtn,#lastPageBtn").addClass("buttonDisabled");
			$("#nextPageBtn,#lastPageBtn").unbind("click");
		}
		else if ( pageNumber <= 1)
		{
			$("#nextPageBtn,#lastPageBtn,#previousPageBtn,#firstPageBtn").removeClass("buttonDisabled");
			$("#previousPageBtn,#firstPageBtn").addClass("buttonDisabled");
			$("#previousPageBtn,#firstPageBtn").unbind("click");
		}
		else if ( pageNumber > 1 && $("#previousPageBtn,#firstPageBtn").hasClass("buttonDisabled"))
		{
			$("#previousPageBtn,#firstPageBtn").removeClass("buttonDisabled");
			$("#previousPageBtn").bind("click",function(){
				gotoPreviousPage();
			});
			$("#firstPageBtn").bind("click", function(){
				gotoPage(1);
			});
		}
		else if ( pageNumber < getTotalPages() && $("#lastPageBtn,#nextPageBtn").hasClass("buttonDisabled"))
		{
			$("#lastPageBtn,#nextPageBtn").removeClass("buttonDisabled");
			$("#lastPageBtn").bind("click",function(){
				gotoLastPage();
			});
			$("#nextPageBtn").bind("click",function(){
				gotoNextPage();
			});
		}
	}catch (err){
		throw err;
	}
}

function gotoLastPage()
{
	gotoPage(getTotalPages());
}

function gotoNextPage()
{
	var pagesInView = $(".maincontent:in-viewport",$("#printPreviewContainer"));
	if ( pagesInView.length > 0 ){
		var pNumber = parseInt($(pagesInView[pagesInView.length-1]).attr("page"))+1;
		gotoPage(pNumber);
	}
}

function gotoPreviousPage()
{
	var pagesInView = $(".maincontent:in-viewport",$("#printPreviewContainer"));
	if ( pagesInView.length > 0 ){
		var pNumber = parseInt($(pagesInView[0]).attr("page"));
		gotoPage(pNumber);
	}
}


function setupDocumentPrint()
{
	var popWin="width=510,height=480,resizable=yes,scrollbars=yes"; 
	var win = window.open('','printWindow',popWin);
	
	win.document.write('<html>\
			<head>\
			<style type="text/css">\
				@media print {\
					#printLink{\
						display:none;\
					}\
				}\
			</style>\
			<script type="text/javascript" language="JavaScript1.2">\
			function printDocument()\
			{\
				agt = navigator.userAgent.toLowerCase();\
				if (self.print) {\
					self.print();\
				}\
				else if (agt.indexOf("mac") != -1) {\
					alert("Press \'Cmd+p\' on your keyboard to print document.");\
				}\
				else {\
					alert("Press \'Ctrl+p\' on your keyboard to print document.");\
				} \
			}\
			</script>\
			</head>\
			<body><div><a id="printLink" href="javascript:void(printDocument());">Print</a></div>');
			
	setScale(1);		
	var ordocument = $("#margins_1").html().replace(/\s?jQuery\d+="\d+"/gi,"");
	setScale($("#zoomLevel option:selected").attr("value"));
	win.document.write(ordocument);
	win.document.write('</body></html>');
	win.document.close();
	win.focus();
	win.print();
}


function launchPrintPreview()
{
	try
	{
		hs.close('exampleAfterAdd'); // closes any highslide windows.
	} catch ( err ) {}
	unhoverElements(null);
	removeHighlight();
	$("div[sectiontype]").css("background-color","white");
	
	var documentId = $("input[id='documentId']").val();
	var documentType = $("input[id='documentType']").val();
	
	var markup = '<div id="printPreviewContainer"> \
				<div style="border: 1px solid black;background-color:silver;">\
				<table width="100%">\
					<tr><td style="text-align:left;">\
						<span class="or20_CheckButton" style="display:block;float:left;">\
							<a class="or20_BigButton" href="javascript:void(0);" onclick="closePrintPreview();">Back To Builder</a>\
						</span> \
						</td>\
						<td></td>\
						<td style="text-align:right;font-size:10px;font-face:Arial;">Print Preview is a read only view.</td></tr>\
					<tr><td style="text-align:left;">Zoom <select id="zoomLevel" name="zoomLevel" onchange="setScale(this.value);"><option value=".25">25%</option><option value=".50" selected="selected">50%</option> \
					 <option value=".75">75%</option><option value="1">100%</option></select> </td> \
					 <td><span style="text-align:center;display:block;padding-left:5px;padding-top:7px;">\
					 	<img align="absmiddle" src="/images/or20/or20_Toolbar_Menu_PDF.png"> <a href="/modules/'+documentType+'/edit.php?outputType=pdf&docid='+documentId+'">Print using PDF</a> \
						 </span>\
					</td>\
					<td style="text-align:right">\
					<span style="text-align=right;">\
					 <a href="javascript:void(0);" id="firstPageBtn" class="buttonDisabled"> << </a>\
					 <a href="javascript:void(0);" id="previousPageBtn" class="buttonDisabled"> < </a>\
					 Page <span id="pageX" class="pageX"/> of <span id="pageY" class="pageY"/>  \
					 <a href="javascript:void(0);" id="nextPageBtn"> > </a>\
					 <a href="javascript:void(0);" id="lastPageBtn"> >> </a>\
					 </span> \
					</td>\
					</tr>\
				</table>\
				</div>\
				 <div id="printPreviewDisplayContainer"/>\
				 </div>';
	
	$("body").append(markup);
	var moduleCanvasClone = $("#moduleCanvas").not(":hidden").clone();

	$(moduleCanvasClone).find("span.______SpellCheckError______, span.______SpellCheckError______Corrected").each(function(index)
			{
				$(this).before(this.firstChild.data).remove();
			}
		);

	$("*", $(moduleCanvasClone)).die();
	$("#handle", $(moduleCanvasClone)).remove();
	$(".margin-marker",$(moduleCanvasClone)).remove();
	
	$("#printPreviewDisplayContainer").append(moduleCanvasClone);
	
	$("#moduleCanvas", $("#printPreviewDisplayContainer")).removeClass("or20_Resume_Container");
	$(".maincontent",$("#printPreviewDisplayContainer")).css("left","");
	bindMarginEvents();
	$("#printPreviewContainer").css({
		position:'absolute',
		top: $("#or20_Header").height(),
		left:0,
		height: $(document).height(),
		width: '100%',
		zIndex:900,
		opacity: 1,
		backgroundColor: '#eee'
	});
	
	$("#printPreviewToolbar").css({
		backgroundColor: 'silver',
		width: '100%',
		textAlign:'center'
	});
	$("#printPreviewNavigationBar").css({
		backgroundColor:'silver',
		width: '100%',
		textAlign:'center'
	});
	$("#printPreviewNavigationBar > span").css(
	{
		padding: '5px',
		margin: '1px'
	});
	
//	$("#printPreviewDisplayContainer").css({
//		height: $(window).height() - $("#or20_Header").height(),
//		overflowY:'auto'
//	});
	previewMode();
	setOriginalValues();
	
	$.each($(".maincontent", $("#printPreviewContainer")),function(idx,val){
		var pnContainer = $('<div id="pageNumberContainer">Page <span id="pageX" class="pageX"/> of <span id="pageY" class="pageY"/></div>');
		$(this).append(pnContainer);
		$("#pageNumberContainer",$(this)).css({
			position:'absolute',
			top: -15,// * $("#pageNumberContainer",$(this)).height(),
			left: 0,
			fontSize: '0.7em',
			backgroundColor:'black',
			color:'white',
			textAlign:'center',
			width:'100%'
		});
		
	});
	
	$("#pageX").html("1");
	
	$.each($(".pageX",$("#printPreviewContainer")), function(idx,val){
		$(this).html($(this).parent().parent().attr("page"));
	});
	$.each($(".pageY"), function(idx,val){
		$(this).html(getTotalPages());
	});
	
	$(":input[name='gotoPageNumber']").keypress(function(e){
		if ( e.keyCode == 13 )
		{
			gotoPage();
		}
	});
	
	$("#nextPageBtn").bind("click",function(){
		gotoNextPage();
	});
	
	$("#lastPageBtn").bind("click",function(){
		gotoLastPage();
	});
	setScale(.50);
}
