var contentBeforeRich, contentBeforePlain, contentAfterRich, contentAfterPlain;
var keyDownCt = 0;
var fontSizeArr = new Array();
var fontSizes = "";
var fontClassList = [];
var textColorArr = new Array();
var textColors = "";
var keyCode;
var REFRESH_DELAY = 500; // 1000 ms = 1 second
var zoom = false;

function loadFontSizes() {
	for (var i = 0; i < fontSizeArr.length; i++) {
		fontSizes += fontSizeArr[i] + "=" + fontSizeArr[i] + "px,";
		fontClassList.push('fontSize' + fontSizeArr[i]);
	}
	fontSizes = fontSizes.substring(0, fontSizes.length - 1);
}

function interceptKeyPress(e) {
	var editor = tinyMCE.get("productText");
	
	if (e.type == "keydown") {
		keyCode = e.keyCode;
	}
	
	if (e.type == "keydown" ||
			e.type == "keypress" ||
			e.type == "keyup") {
		
		if (keyCode == 13) { // enter
			if (editor.selection.getContent().length > 0 ||
					editor.getContent().length == 0) {
				return false;
			} else {
				if (e.type == "keyup") {
					handleNodeChange(editor);
				}
				return true;
			}
		} else if (keyCode == 32) {	// space
			if (editor.selection.getContent().length > 0 ||
					editor.getContent().length == 0) {
				return false;
			} else {
				if (e.type == "keyup") {
					handleNodeChange(editor);
				}
				return true;
			}
		} else if (keyCode == 8) {	// backspace
			return handleDelete(editor, e);
		} else if (keyCode == 46) {	// delete
			return handleDelete(editor, e);
		} else if (keyCode == 16 ||	// shift
				keyCode == 37 ||	// left arrow
				keyCode == 38 ||	// top arrow
				keyCode == 39 ||	// right arrow
				keyCode == 40) {	// bottom arrow
			return true;
		} else if (e.type == "keydown" && tinymce.isMac ? e.metaKey : e.ctrlKey) { // keyboard shortcuts
			if (keyCode == 65) {		// A - select all
				editor.execCommand('SelectAll');
			} else if (keyCode == 66) {	// B - bold
				editor.execCommand('Bold');
			} else if (keyCode == 73) {	// I - italic
				editor.execCommand('Italic');
			} else if (keyCode == 85) {	// U - underline
				editor.execCommand('Underline');
			}
			return false;
		} else {
			e.preventDefault();
			return false;
		}
	}
}

function handleDelete(editor, e) {
	var allow = false;
	
	if (editor.selection.isCollapsed()) {
		allow = true;
		switch (e.type) {
			case 'keydown':
				if (keyDownCt == 0) {
					contentBeforeRich = editor.getContent( { format : 'raw' } );
					contentBeforePlain = contentBeforeRich
							.replace(/<.[^<>]*?>/g, ' ')
							.replace(/&nbsp;|&#160;/gi, ' ')
							.replace(/\n/g, ' ')
							.replace(/\s+/g, '');
				}
				keyDownCt++;
				break;
			case 'keypress':
				break;
			case 'keyup':
				contentAfterRich = editor.getContent( { format : 'raw' } );
				contentAfterPlain = contentAfterRich
						.replace(/<.[^<>]*?>/g, ' ')
						.replace(/&nbsp;|&#160;/gi, ' ')
						.replace(/\n/g, ' ')
						.replace(/\s+/g, '');
				if (contentBeforePlain != contentAfterPlain) {
					editor.setContent(contentBeforeRich);
				} else {
					handleNodeChange(editor);
				}
				keyDownCt = 0;
				break;
		}
		return allow;
	} else {
		return allow;
	}
	
	return allow;
}

function tinyMceInit() {
	tinymce.create('tinymce.plugins.ExternalControls', {
		createControl : function(n, cm) {
			switch (n) {
				case 'align' :
					var c = cm.createMenuButton('align', {
						title : '',
						image : '/images/textAlignment/center.gif',
						icons : true
					});
					
					c.onRenderMenu.add(function(c, m) {
						m.add({
							title : '',
							icon : 'justifyleft',
							onclick : function() {
								$('#productText_align img').attr('src', '/images/textAlignment/left.gif');
								$("#update_lyricProduct_alignment").val('left');
								designDetails[v].textAlign = 'left';
								updatePreviewText();
							}
						});
						m.add({
							title : '',
							icon : 'justifycenter',
							onclick : function() {
								$('#productText_align img').attr('src', '/images/textAlignment/center.gif');
								$("#update_lyricProduct_alignment").val('center');
								designDetails[v].textAlign = 'center';
								updatePreviewText();
							}
						});
						m.add({
							title : '',
							icon : 'justifyright',
							onclick : function() {
								$('#productText_align img').attr('src', '/images/textAlignment/right.gif');
								$("#update_lyricProduct_alignment").val('right');
								designDetails[v].textAlign = 'right';
								updatePreviewText();
							}
						});
					});
					
					return c;
				case 'textcolor' :
					var c = cm.createMenuButton('textcolor', {
						title : '',
						image : '',
						icons : true
					});
					
					c.onRenderMenu.add(function(c, m) {
						for (var i = 0; i < textColorArr.length; i++) {
							m.add({
								title : '',
								icon : textColorArr[i].hexVal,
								tcid : textColorArr[i].tcid,
								onclick : function() {
									$('.mce_textcolor').css('background-color', $('ul#colorList li.currentColor').css('background-color'));
									$('.mce_textcolor').css('color', '#' + this.icon);
									
									$('#update_tcid').val(this.tcid);
									updatePreviewText();
									designDetails[v].fontColor = this.icon;
									designDetails[v].tcid = this.tcid;
								}
							});
						}
					});
					
					return c;
			}
		
			return null;
		}
	});
	tinymce.PluginManager.add('externalcontrols', tinymce.plugins.ExternalControls);
	tinyMCE.init({
		// General options
		mode : "textareas",
		theme : "advanced",
		plugins : "-externalcontrols,inlinepopups,contextmenu,paste",
		dialog_type : "modal",
		
		// Theme options // fontselect,formatselect,styleselect
		theme_advanced_buttons1 : "fontselect,bold,italic,underline,fontsizeselect,fontsizeselect_plus,fontsizeselect_minus,textcolor,linespacing,linespacing_plus,linespacing_minus,align,nudge,nudge_up,nudge_right,nudge_down,nudge_left",
		theme_advanced_buttons2 : "", // code
		theme_advanced_buttons3 : "",
		
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : false,
		theme_advanced_resize_horizontal : false,
		theme_advanced_path : false,
		
		paste_block_drop : true,
		
		// dialog_type : 'modal', // fades the rest of the screen
		
		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",
	
		// handle key press events
		handle_event_callback : "interceptKeyPress",
		
		// Further customization
		imagemanager_contextmenu : false,
		custom_shortcuts : false,
		custom_undo_redo_keyboard_shortcuts : false,
		cleanup : true,
		cleanup_on_startup : true,
		convert_urls : false,
		convert_fonts_to_spans : true,
		convert_newlines_to_brs : true,
		relative_urls : false,
		fix_nesting : true,
		forced_root_block : false,
		force_br_newlines : true,
		force_p_newlines : false,
		inline_styles : false,
		remove_linebreaks : false,
		remove_redundant_brs : false,
		valid_elements : '-p[id],-span[id|class|style],b/strong,i/em,u,br,fake[id]',
		custom_elements : '~fake',
		removeformat_selector : 'b,i,span[style]',
		
		theme_advanced_fonts : 
			'arial=arial;' +
			'arial black=arial_black;' + 
			'bankoli bold=bankoli_bold;' + 
			'barbara hand=barbara_hand;' + 
			'bauer=bauer;' + 
			'beatsville=beatsville;' + 
			'bebas=bebas;' + 
			'brush script mt italic=brush_script_mt_italic;' + 
			'cantarell regular=cantarell_regular;' + 
			'carnevalee freakshow=carnevalee_freakshow;' + 
			'coolvetica=coolvetica;' + 
			'courier new=courier_new;' + 
			'day roman=day_roman;' + 
			'diamond gothic=diamond_gothic;' + 
			'do not eat this=do_not_eat_this;' + 
			'eager naturalist=eager_naturalist;' + 
			'edttf-gothic=edttf-gothic;' + 
			'english wd=english_wd;' + 
			'folks-normal=folks-normal;' + 
			'fontin regular=fontin_regular;' + 
			'harabara bold=harabara_bold;' + 
			'i love derwin=i_love_derwin;' +  
			'imperatorsmallcaps bold=imperatorsmallcaps_bold;' +  
			'jailbird jenna=jailbird_jenna;' +
			'journal=journal;' +
			'justus roman=justus_roman;' +
			'komika axis=komika_axis;' +
			'ma sexy=ma_sexy;' +
			'machinescript=machinescript;' +
			'madison square incised=madison_square_incised;' +  
			'oasis=oasis;' +  
			'old newspaper types=old_newspaper_types;' +  
			'old typefaces=old_typefaces;' +  
			'olijo-bold=olijo-bold;' +  
			'panam text=panam_text;' +  
			'paramount=paramount;' +
			'petitlatin=petitlatin;' +  
			'phoenix=phoenix;' +    
			'pirulen=pirulen;' +  
			'press start k=press_start;' +  
			'rafika=rafika;' +  
			'raspoutine medium italic=raspoutine_medium_italic;' +  
			'rogue hero italic=rogue_hero_italic;' +  
			'sanford book=sanford_book;' +  
			'sansation regular=sansation;' + 
			'slabtallx=slabtallx;' +  
			'tahoma bold=tahoma_bold;' +  
			'times=times_new_roman;' +
			'vahika=vahika;' +  
			'walkway condensed bold=walkway_condensed_bold;' +  
			'warehouse medium=warehouse;' +  
			'yellowjacket=yellowjacket',
		
		theme_advanced_font_sizes : fontSizes,
		
		setup : function(ed) {
			// increase font size button
			ed.addButton('fontsizeselect_plus', {
				title : '',
				image : '',
				onclick : function() {
					//if (ed.dom.getParent(ed.selection.getNode(), 'span') != null) {
					if (ed.selection.getContent() != null && ed.selection.getContent().length > 0) {
						var sizenum = $('#productText_fontsizeselect_text').html();
						sizenum = parseInt(sizenum);
						if (sizenum < 36) {
							sizenum = sizenum + 1;
						}
						
						if (ed.selection.getContent().length > 0) {
							ed.execCommand('FontSize', false, sizenum + 'px');
							$('#productText_fontsizeselect_text').html(sizenum);
						}
					}
				}
			});
			
			// decrease font size button
			ed.addButton('fontsizeselect_minus', {
				title : '',
				image : '',
				onclick : function() {
					if (ed.selection.getContent() != null && ed.selection.getContent().length > 0) {
						var sizenum = $('#productText_fontsizeselect_text').html();
						sizenum = parseInt(sizenum);
						if (sizenum > 4) {
							sizenum = sizenum - 1;
						}
						
						if (ed.selection.getContent().length > 0) {
							ed.execCommand('FontSize', false, sizenum + 'px');
							
							$('#productText_fontsizeselect_text').html(sizenum);
						}
					}
				}
			});
			
			// line spacing button placeholder
			ed.addButton('linespacing', {
				title : '',
				image : '',
				onclick : function() {
					
				} // do nothing
			});
			
			// increase line spacing button
			ed.addButton('linespacing_plus', {
				title : '',
				image : '',
				onclick : function() {
					$("#update_lyricProduct_lineSpacing").val(Math.round((parseFloat($("#update_lyricProduct_lineSpacing").val()) + 0.1) * 100)/100); // Update form input	
					designDetails[v].lineSpacing = parseFloat($("#update_lyricProduct_lineSpacing").val()); // Assign to current view detail object	
					updatePreviewText();
				}
			});
			
			// decrease line spacing button
			ed.addButton('linespacing_minus', {
				title : '',
				image : '',
				onclick : function() {
					if (designDetails[v].lineSpacing > 0.3) {
						$("#update_lyricProduct_lineSpacing").val(Math.round((parseFloat($("#update_lyricProduct_lineSpacing").val()) - 0.1) * 100)/100); // Update form input	
						designDetails[v].lineSpacing = parseFloat($("#update_lyricProduct_lineSpacing").val()); // Assign to current view detail object	
						updatePreviewText();
					}
				}
			});
			
			// nudge tool placeholder
			ed.addButton('nudge', {
				title : '',
				image : '',
				onclick : function() {}
			});
			
			// nudge tool - move up
			ed.addButton('nudge_up', {
				title : '',
				image : '',
				onclick : function() {
					$("#update_lyricProduct_yPosition").val(parseInt($("#update_lyricProduct_yPosition").val()) - 10); // Update form input	
					designDetails[v].yPosition = parseInt($("#update_lyricProduct_yPosition").val()); // Assign to current view detail object	
					designDetails[v].defaultPosition = false; // Do not use the default position anymore
					updatePreviewText();
				}
			});
			
			// nudge tool - move right
			ed.addButton('nudge_right', {
				title : '',
				image : '',
				onclick : function() {
					$("#update_lyricProduct_xPosition").val(parseInt($("#update_lyricProduct_xPosition").val()) +10); // Update form input	
					designDetails[v].xPosition = parseInt($("#update_lyricProduct_xPosition").val()); // Assign to current view detail object	
					designDetails[v].defaultPosition = false; // Do not use the default position anymore
					updatePreviewText();
				}
			});
			
			// nudge tool - move down
			ed.addButton('nudge_down', {
				title : '',
				image : '',
				onclick : function() {
					$("#update_lyricProduct_yPosition").val(parseInt($("#update_lyricProduct_yPosition").val()) +10); // Update form input	
					designDetails[v].yPosition = parseInt($("#update_lyricProduct_yPosition").val()); // Assign to current view detail object	
					designDetails[v].defaultPosition = false; // Do not use the default position anymore
					updatePreviewText();
				}
			});
			
			// nudge tool - move left
			ed.addButton('nudge_left', {
				title : '',
				image : '',
				onclick : function() {
					$("#update_lyricProduct_xPosition").val(parseInt($("#update_lyricProduct_xPosition").val()) - 10); // Update form input	
					designDetails[v].xPosition = parseInt($("#update_lyricProduct_xPosition").val()); // Assign to current view detail object	
					designDetails[v].defaultPosition = false; // Do not use the default position anymore
					updatePreviewText();
				}
			});
			
			ed.onActivate.add(function(ed) {
			});
			ed.onDeactivate.add(function(ed) {
			});
			ed.onInit.add(function(ed) {
				$('#productText_textcolor span').html('A');
				
				// load product text if existing
				loadProductText();
				
				createHoverEffects();
			});
			
			// disallow paste
			ed.onEvent.add(function(ed, e) {
				if (e.type == "paste") {
					return tinymce.dom.Event.cancel(e);
				}
				handleNodeChange(ed);
			});
			
			// allow/deny text
			// currently handled by separate callback function
			ed.onKeyDown.add(function(ed, e) {
			});
			ed.onKeyPress.add(function(ed, e) {
			});
			ed.onKeyUp.add(function(ed, e) {
			});
			
			// do nothing on paste
			ed.onPaste.add(function(ed, e, o) { return false; });

			// update text
			ed.onChange.add(function(ed, l, um) {
				handleNodeChange(ed);
			});
			ed.onNodeChange.add(function(ed, cm, e, c, o) {
				handleNodeChange(ed);
			});
			ed.onClick.add(function(ed, e) {
				handleNodeChange(ed);
			});
			ed.onMouseDown.add(function(ed, e) {
				handleNodeChange(ed);
			});
			ed.onMouseUp.add(function(ed, e) {
				handleNodeChange(ed);
			});
			ed.onDblClick.add(function(ed, e) {
				handleNodeChange(ed);
			});
			ed.onPostProcess.add(function(ed, o) {
				/* do nothing. continually fires, and causes session problems if enabled. */
				// handleNodeChange(ed);
			});
		}
	});
}

var nodeChangeTimer;
function handleNodeChange(ed) {
	clearTimeout(nodeChangeTimer);
	nodeChangeTimer = setTimeout(function() {
		if ($("#productText").val() != ed.getContent() && ed.getContent() != "") {
			$("#productText").val(ed.getContent());
			updatePreviewText();
		}
	}, REFRESH_DELAY);
}

var v = 0;
var t = 0;
var addImage = "/images/addLyricBlock.gif";
var addImageHover = "/images/addLyricBlockHover.gif";
var removeImage = "/images/removeLyricBlock.gif";
var removeImageHover = "/images/removeLyricBlockHover.gif";
var changedViews = false;
var previousText = "";

var CTRL = tinymce.isMac ? 'CMD' : 'CTRL';

function createHoverEffects() {
	$('#productText_toolbar1').hover(
		function() {
			$('#tooltipz').fadeIn('fast');
		},
		function() {
			$('#tooltipz').fadeOut('fast');
		}
	);
	
	$('#productText_fontselect').mousemove(function(event) {
		$('#tooltipz')
				.html('Select font')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_bold').mousemove(function(event) {
		$('#tooltipz')
				.html('Bold (' + CTRL + ' + B)')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_italic').mousemove(function(event) {
		$('#tooltipz')
				.html('Italic (' + CTRL + ' + I)')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_underline').mousemove(function(event) {
		$('#tooltipz')
				.html('Underline (' + CTRL + ' + U)')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_fontsizeselect').mousemove(function(event) {
		$('#tooltipz')
				.html('Select font size')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_fontsizeselect_plus').mousemove(function(event) {
		$('#tooltipz')
				.html('Increase font size')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_fontsizeselect_minus').mousemove(function(event) {
		$('#tooltipz')
				.html('Decrease font size')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_textcolor').mousemove(function(event) {
		$('#tooltipz')
				.html('Select text color')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_linespacing').mousemove(function(event) {
		$('#tooltipz')
				.html('Change line spacing')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_linespacing_plus').mousemove(function(event) {
		$('#tooltipz')
				.html('Increase line spacing')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_linespacing_minus').mousemove(function(event) {
		$('#tooltipz')
				.html('Decrease line spacing')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_align').mousemove(function(event) {
		$('#tooltipz')
				.html('Change text alignment')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_nudge').mousemove(function(event) {
		$('#tooltipz')
				.html('Move text')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_nudge_up').mousemove(function(event) {
		$('#tooltipz')
				.html('Move text up')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_nudge_down').mousemove(function(event) {
		$('#tooltipz')
				.html('Move text down')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_nudge_left').mousemove(function(event) {
		$('#tooltipz')
				.html('Move text left')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
	$('#productText_nudge_right').mousemove(function(event) {
		$('#tooltipz')
				.html('Move text right')
				.css('margin-left', event.pageX - ($('#tooltipz').width() / 2));
	});
}
