$(function() { 
	// Resize	
	function resize(){
		$('.resize-height').height(window.innerHeight - 220);
		$('.resize-width').width(window.innerWidth - 370);
		//if(window.innerWidth<=1150){$('.resize-width').css('overflow','auto');}
		$('body').css('overflow','hidden');
	};
	$( window ).resize(function() {
		resize();
	});
	resize();
	
	// Template screen width
	$("button.template-width").click(function(e) {
		e.preventDefault();
		new_width = $(this).attr('data-width');
		$('#template-iframe').width(new_width);
		//$('#template-body table.wrapper').css({ 'width': new_width + 'px' });
	});
	
	// Add Sections
	$("#newsletter-builder-area-center-frame-buttons-add").hover(
		function() {
			$("#newsletter-builder-area-center-frame-buttons-dropdown").fadeIn(200);
		}, function() {
			$("#newsletter-builder-area-center-frame-buttons-dropdown").fadeOut(200);
		}
	);

	$("#newsletter-builder-area-center-frame-buttons-dropdown").hover(
		function() {
			$(".newsletter-builder-area-center-frame-buttons-content").fadeIn(200);
			$('#template-body').hide();
		}, function() {
			$(".newsletter-builder-area-center-frame-buttons-content").fadeOut(200);
			$('#template-body').show();
		}
	);

	$("#add-header").hover(function() {
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='header']").show()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='content']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='footer']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='extra']").hide()
	});

	$("#add-content").hover(function() {
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='header']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='content']").show()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='footer']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='extra']").hide()
	});

	$("#add-footer").hover(function() {
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='header']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='content']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='footer']").show()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='extra']").hide()
	}); 

	$("#add-extra").hover(function() {
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='header']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='content']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='footer']").hide()
		$(".newsletter-builder-area-center-frame-buttons-content-tab[data-type='extra']").show()
	});  
	
	$(".newsletter-builder-area-center-frame-buttons-content-tab").hover(
		function() {
			$(this).append('<div class="newsletter-builder-area-center-frame-buttons-content-tab-add"><i class="fa fa-plus"></i>&nbsp;beszúr</div>');
			$('.newsletter-builder-area-center-frame-buttons-content-tab-add').click(function() {
				$("#template-body").append($("#newsletter-preloaded-rows .sim-row[data-id='"+$(this).parent().attr("data-id")+"']").clone());
				hover_edit();
				perform_delete();
				$("#newsletter-builder-area-center-frame-buttons-dropdown").fadeOut(200);
			});
		}, function() {
			$(this).children(".newsletter-builder-area-center-frame-buttons-content-tab-add").remove();
		}
	); 

	// mso background image src change
	function replaceHrefWithNew(myMso,newHrefValue) {
		var newMso=myMso;
		var indexOfStartHref=myMso.indexOf("src")+6;
		if(indexOfStartHref>=6) {
			var indexOfEndHref=myMso.indexOf("\"",indexOfStartHref);

			var part1=myMso.substring(0,indexOfStartHref);
			var part2=myMso.substring(indexOfStartHref,indexOfEndHref);
			var part3=myMso.substring(indexOfEndHref);

			newMso= part1 + newHrefValue + part3;
		}

		return newMso;
	}
  
	// Edit
	function hover_edit(){
		
		$(".sim-row-edit").hover(
			function() {
				$(this).append('<div class="sim-row-edit-hover"><span title="Szerkesztéshez klikk ide"><i class="fa fa-pencil" style="line-height:34px;"></i></span></div>');
				$(".sim-row-edit-hover").click(function(e) {
					e.preventDefault()
				});
				$(".sim-row-edit-hover span").click(function(e) {
					e.preventDefault();
					big_parent = $(this).parent().parent();

					//edit background image
					if(big_parent.attr("data-type")=='background-image'){
						$("#sim-edit-background-image .image img").attr("src", big_parent.attr("background"));
						
						$('#sim-edit-background-image').modal('show');

						$("#sim-edit-background-image .sim-edit-box-buttons-save").click(function() {
							var src = $("#sim-edit-background-image .image img").attr("src");
							
							big_parent.attr("background", src);
							
							$(big_parent).contents().filter(
								function(){
									return this.nodeType == 8;
									}).each(function(i,e){
										if(i==0)
										{
										   $(this)[0].data = replaceHrefWithNew($(this)[0].data, src);
										 }
									});
							
							$('#sim-edit-background-image').modal('hide');
						});
					}

					//edit image
					if(big_parent.attr("data-type")=='image'){
						$("#sim-edit-image .image img").attr("src", big_parent.children('a').children('img').attr("src"));
						$("#sim-edit-image .title").val(big_parent.children('a').attr("title"));
						$("#sim-edit-image .url").val(big_parent.children('a').attr("href"));
						var attr_href = big_parent.children('a').attr("href");
						if ($('#sim-edit-image select[name=selectWGlink]').find('option[value="'+attr_href+'"]').length) {
						   $("#sim-edit-image select[name=selectWGlink]").val(attr_href);
						} else {
							$("#sim-edit-image select[name=selectWGlink]").val('');
						}
						
						$('#sim-edit-image').modal('show');

						$("#sim-edit-image .sim-edit-box-buttons-save").click(function() {
							var src = $("#sim-edit-image .image img").attr("src");
							
							big_parent.children('a').attr("title",$("#sim-edit-image .title").val());
							big_parent.children('a').attr("href",$("#sim-edit-image .url").val());
							big_parent.children('a').children('img').attr("src", src);
							big_parent.children('a').children('img').attr("alt",$("#sim-edit-image .title").val());
							
							
							$('#sim-edit-image').modal('hide')
						});
					}

					//edit rating
					if(big_parent.attr("data-type")=='rating'){
						$("#sim-edit-rating .image img").attr("src", big_parent.children('a').children('img').attr("src"));
						$("#sim-edit-rating .title").val(big_parent.children('a').attr("title"));
						
						$('#sim-edit-rating').modal('show');

						$("#sim-edit-rating .sim-edit-box-buttons-save").click(function() {
							var src = $("#sim-edit-rating .image img").attr("src");
							
							big_parent.children('a').attr("title",$("#sim-edit-rating .title").val());
							big_parent.children('a').children('img').attr("src", src);
							big_parent.children('a').children('img').attr("alt",$("#sim-edit-rating .title").val());							
							
							$('#sim-edit-rating').modal('hide')
						});
					}
			
					//edit link
					if(big_parent.attr("data-type")=='link'){
						$("#sim-edit-link .title").val(big_parent.text());
						$("#sim-edit-link .url").val(big_parent.attr("href"));
						
						var attr_href = big_parent.attr("href");
						if ($('#sim-edit-link select[name=selectWGlink]').find('option[value="'+attr_href+'"]').length) {
						   $("#sim-edit-link select[name=selectWGlink]").val(attr_href);
						} else {
							$("#sim-edit-link select[name=selectWGlink]").val('');
						}
						
						$('#sim-edit-link').modal('show')

						$("#sim-edit-link .sim-edit-box-buttons-save").click(function() {
							$('#sim-edit-link').modal('hide')

							big_parent.text($("#sim-edit-link .title").val());
							big_parent.attr("href",$("#sim-edit-link .url").val());
							big_parent.attr("title",$("#sim-edit-link .title").val());
						});
					}
			
					//edit button
					if(big_parent.attr("data-type")=='button'){
						$("#sim-edit-button .title").val(big_parent.text());
						$("#sim-edit-button .url").val(big_parent.attr("href"));
						$("#sim-edit-button .text-color").val(rgb2hex(big_parent.css("color")));
						$("#sim-edit-button .background-color").val((big_parent.parent().parent().parent().parent().attr("bgcolor")));
						$("#sim-edit-button select[name=radius]").val(big_parent.parent().parent().parent().parent().css("borderTopLeftRadius"));
						$("#sim-edit-button .font-size").val(big_parent.parent().css("font-size"));
						$("#sim-edit-button select[name=font-family]").val(big_parent.css("font-family"));
						
						var attr_href = big_parent.attr("href");
						if ($('#sim-edit-button select[name=selectWGlink]').find('option[value="'+attr_href+'"]').length) {
						   $("#sim-edit-button select[name=selectWGlink]").val(attr_href);
						} else {
							$("#sim-edit-button select[name=selectWGlink]").val('');
						}

						$('#sim-edit-button').modal('show');

						$("#sim-edit-button .sim-edit-box-buttons-save").click(function() {
							$('#sim-edit-button').modal('hide')
							
							if(!$("#sim-edit-button .title").val()) {
								big_parent.parent().parent().parent().parent().remove();
							} else {
								big_parent.text($("#sim-edit-button .title").val());
								big_parent.attr("href",$("#sim-edit-button .url").val());
								big_parent.attr("title",$("#sim-edit-button .title").val());
								
								lineheight = (parseInt($("#sim-edit-button .font-size").val(), 10) + 14) + ('px');
								big_parent.parent().attr('style', 'font-size: ' + $("#sim-edit-button .font-size").val() + ' !important; font-family' + $("#sim-edit-button select[name=font-family]").val());
								big_parent.parent().parent().parent().parent().css({ 'color':$("#sim-edit-button .text-color").val(), 'border-radius':$("#sim-edit-button select[name=radius]").val() });
								big_parent.parent().parent().parent().parent().attr({ 'bgcolor':$("#sim-edit-button .background-color").val() });
								big_parent.css({ 'color':$("#sim-edit-button .text-color").val(), 'font-family':$("#sim-edit-button select[name=font-family]").val(), 'line-height': lineheight });
							}
						});
					}
			
					//edit title			
					if(big_parent.attr("data-type")=='title'){			
						$("#sim-edit-title .title").val(big_parent.text());
						$("#sim-edit-title .text-color").val(rgb2hex(big_parent.css("color")));
						$("#sim-edit-title select[name=align]").val(big_parent.css("textAlign"));
						$("#sim-edit-title .font-size").val(big_parent.css("font-size"));
						$("#sim-edit-title select[name=font-family]").val(big_parent.css("font-family"));
						$('#sim-edit-title').modal('show')

						$("#sim-edit-title .sim-edit-box-buttons-save").click(function() {
							$('#sim-edit-title').modal('hide')

							big_parent.text($("#sim-edit-title .title").val());
							big_parent.css({ 'color':$("#sim-edit-title .text-color").val(), 'text-align':$("#sim-edit-title select[name=align]").val(), 'font-size':$("#sim-edit-title .font-size").val(), 'font-family':$("#sim-edit-title select[name=font-family]").val() });
						});
					}
			
					//edit text
					if(big_parent.attr("data-type")=='text'){
						big_parent.children(".sim-row-edit-hover").remove();
						$("#sim-edit-text .text").val(big_parent.html());
						
						$('#sim-edit-text').modal('show');

						tinymce.init(tinymce_options_email_editor);
						tinymce.get('myTextArea').setContent(big_parent.html());
																
						$("#sim-edit-text .sim-edit-box-buttons-save").click(function() {
							html = tinymce.get('myTextArea').getContent();
							big_parent.html(html);
							$('#sim-edit-text').modal('hide');
						});
					}
					
					//edit icon
					if(big_parent.attr("data-type")=='icon'){
						$('#sim-edit-icon').modal('show');

						$("#sim-edit-icon i").click(function() {
							$('#sim-edit-icon').modal('hide');
							big_parent.children('i').attr('class',$(this).attr('class'));
						});
					}
				});
			}, function() {
				$(this).children(".sim-row-edit-hover").remove();
			}
		);
		block_settings();
	}
	hover_edit();
	
	  
	// Drag & Drop
	function add_block_tools(){
		$(".sim-row").append('<div class="sim-row-settings"><i class="fa fa-edit"></i></div>');
		$(".sim-row").append('<div class="sim-row-delete"><i class="fa fa-times" ></i></div>');
	}
	add_block_tools();
	
	$("#template-body").sortable({
		//dropOnEmpty: false,
		revert: true,
		//handle: '.sim-row-reorder',
	});
		
	$(".sim-row").draggable({
		/*
		connectToSortable: "#template-body",
		//helper: "clone",
		revert: "invalid",
		handle: ".sim-row-reorder"
		*/
		
      connectToSortable: "#newsletter-builder-area-center-frame-content",
      //helper: "clone",
      revert: "invalid",
	  handle: ".sim-row-move"
	});
	
	// Delete
	function perform_delete(){
		$(".sim-row-delete").click(function() {
			$(this).parent().remove();
		});
	}
	perform_delete();
	
	function block_settings(){
		$(".sim-row-settings").click(function(e) {
			e.preventDefault();
			big_parent = $(this).parent().children('table:first');

			$("#sim-edit-settings .background-color").val(rgb2hex(big_parent.attr("bgcolor")));

			$('#sim-edit-settings').modal('show');

			$("#sim-edit-settings .sim-edit-box-buttons-save").click(function() {
				$('#sim-edit-settings').modal('hide');

				big_parent.attr("bgcolor", $("#sim-edit-settings .background-color").val());
			});
		});
	}
	block_settings();
	
	// preview
	$("#show-preview").click(function(){
		//$('#template-iframe')[0].contentWindow.location.reload(true);
		
		
		
		$("#newsletter-preloaded-export").html($("#template-body").html());
		$("#newsletter-preloaded-export .sim-row-delete").remove();
		$("#newsletter-preloaded-export .sim-row-settings").remove();
		export_content = $("#newsletter-preloaded-export").html();
		
		
		$('#template-iframe').contents().find('div#template-body').html(export_content);
		
		
		
		$('#mail-preview').modal('show');
 
	});

	// Download
	$("#newsletter-builder-sidebar-buttons-abutton").click(function(){
	
		$("#newsletter-preloaded-export").html($("#template-body").html());
		$("#newsletter-preloaded-export .sim-row-delete").remove();
		$("#newsletter-preloaded-export .sim-row-settings").remove();
		/*
		$("#newsletter-preloaded-export .sim-row").removeClass("ui-draggable");
		$("#newsletter-preloaded-export .sim-row-edit").removeAttr("data-type");
		$("#newsletter-preloaded-export .sim-row-edit").removeClass("sim-row-edit");
		*/
		export_content = $("#newsletter-preloaded-export").html();
		
		$("#export-textarea").val(export_content)
		$("#save-form").submit();
		$("#export-textarea").val(' ');
	});
	
	function rgb2hex(rgb) {
		if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

		rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		function hex(x) {
			return ("0" + parseInt(x).toString(16)).slice(-2);
		}
		return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	};
	
	
	tinymce.init(tinymce_options_image_editor);
	tinymce.init(tinymce_options_email_editor);
	// prevent Bootstrap from hijacking TinyMCE modal focus    
	$(document).on('focusin', function(e) {
        if ($(e.target).closest(".mce-window").length) {
            e.stopImmediatePropagation();
        }
    });
});