// On page load...
$(function(){
	// Editor Tabs
	if(document.getElementById("email_editor")){
		tabView = new YAHOO.widget.TabView('email_editor');
	}
	
	// Templates
	if(document.getElementById("templates_wrapper")){
		website_id = document.form_craft_email.website_id.value;
		//xmlhttpPost("/components/email_templates/api/list.php?website_id="+website_id,"templates_wrapper","activate_template_preview()");
	}

	// The Rich Text Editor
	if(document.getElementById("form_message_id")){
	
		// Render an editor
		render_editor("form_message_id");
		
		// Email Editor Tab
		$('#email_editor_tab').click(function(){
			// Set the tab status
			document.form_craft_email.current_tab.value = "email_editor";
		});		
		
		// Templates Tab
		$('#templates_tab').click(function(){
			// Load the content, but don't replace the editor if someone is just getting media.
			if(document.form_craft_email.current_tab.value != "media"){
				website_id = document.form_craft_email.website_id.value;
				xmlhttpPost("/components/email_templates/api/list.php?website_id="+website_id,"templates_wrapper","activate_template_preview()");
			}
			
			// Set the tab status
			document.form_craft_email.current_tab.value = "templates";
		});
		
		// Media Tab
		$('#media_tab').click(function(){
			// Set the tab status
			document.form_craft_email.current_tab.value = "media";
			
			// Load the media.
			xmlhttpPost("/components/broadcast_email/api/list_media.php","media_wrapper","activate_thumbnails()");
		});
	}
});

// Render a Yahoo Editor
function render_editor(target_textarea){
	var Dom = YAHOO.util.Dom,Event = YAHOO.util.Event;

	configuration = {
	    height: 		'450px'
	    ,width: 		'695px'
	    ,dompath: 		true
	    ,animate: 		true
	    ,collapse: 		false
		,draggable:		false
		,buttonType:	'advanced'
		,toolbar: {
			titlebar: 	''
			,buttons: [
			    { group: 'fontstyle', label: 'Font Name and Size',
			        buttons: [
			            { type: 'select', label: 'Arial', value: 'fontname', disabled: true,
			                menu: [
			                    { text: 'Arial', checked: true },
			                    { text: 'Arial Black' },
			                    { text: 'Comic Sans MS' },
			                    { text: 'Courier New' },
			                    { text: 'Lucida Console' },
			                    { text: 'Tahoma' },
			                    { text: 'Times New Roman' },
			                    { text: 'Trebuchet MS' },
			                    { text: 'Verdana' }
			                ]
			            },
			            { type: 'spin', label: '13', value: 'fontsize', range: [ 8, 75 ], disabled: true }
			        ]
			    },
			    { type: 'separator' },
			    { group: 'textstyle', label: 'Font Style',
			        buttons: [
			            { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
			            { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
			            { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
			            { type: 'separator' },
			            { type: 'push', label: 'Subscript', value: 'subscript', disabled: true },
			            { type: 'push', label: 'Superscript', value: 'superscript', disabled: true },
			            { type: 'separator' },
			            { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
			            { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
			            { type: 'separator' },
			            { type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true },
			            { type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' }
			        ]
			    },
			    { type: 'separator' },
			    { group: 'alignment', label: 'Alignment',
			        buttons: [
			            { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
			            { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
			            { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
			            { type: 'push', label: 'Justify', value: 'justifyfull' }
			        ]
			    },
			    { type: 'separator' },
			    { group: 'parastyle', label: 'Paragraph Style',
			        buttons: [
			        { type: 'select', label: 'Normal', value: 'heading', disabled: true,
			            menu: [
			                { text: 'Normal', value: 'none', checked: true },
			                { text: 'Header 1', value: 'h1' },
			                { text: 'Header 2', value: 'h2' },
			                { text: 'Header 3', value: 'h3' },
			                { text: 'Header 4', value: 'h4' },
			                { text: 'Header 5', value: 'h5' },
			                { text: 'Header 6', value: 'h6' }
			            ]
			        }
			        ]
			    },
			    { type: 'separator' },
			    { group: 'indentlist', label: 'Lists',
			        buttons: [
			            { type: 'push', label: 'Indent', value: 'indent', disabled: true },
			            { type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
			            { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
			            { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
			        ]
			    },
			    { type: 'separator' },
			    { group: 'insertitem', label: 'Insert Item',
			        buttons: [
			            { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }
			            ,{ type: 'push', label: 'Insert Image', value: 'insertimage' }
			        ]
			    }
			]
		}
	};
		
	var state = 'off';
    YAHOO.log('Set state to off..', 'info', 'example');

    YAHOO.log('Create the Editor..', 'info', 'example');
    var myEditor = new YAHOO.widget.Editor(target_textarea,configuration);
    myEditor.on('toolbarLoaded', function() {
        var codeConfig = {
            type: 'push', label: 'Edit HTML Code', value: 'editcode'
        };
        YAHOO.log('Create the (editcode) Button', 'info', 'example');
        this.toolbar.addButtonToGroup(codeConfig, 'insertitem');
        
        this.toolbar.on('editcodeClick', function() {
            var ta = this.get('element'),
                iframe = this.get('iframe').get('element');

            if (state == 'on') {
                state = 'off';
                this.toolbar.set('disabled', false);
                YAHOO.log('Show the Editor', 'info', 'example');
                YAHOO.log('Inject the HTML from the textarea into the editor', 'info', 'example');
                this.setEditorHTML(ta.value);
                if (!this.browser.ie) {
                    this._setDesignMode('on');
                }

                Dom.removeClass(iframe, 'editor-hidden');
                Dom.addClass(ta, 'editor-hidden');
                this.show();
                this._focusWindow();
            } else {
                state = 'on';
                YAHOO.log('Show the Code Editor', 'info', 'example');
                this.cleanHTML();
                YAHOO.log('Save the Editors HTML', 'info', 'example');
                Dom.addClass(iframe, 'editor-hidden');
                Dom.removeClass(ta, 'editor-hidden');
                this.toolbar.set('disabled', true);
                this.toolbar.getButtonByValue('editcode').set('disabled', false);
                this.toolbar.selectButton('editcode');
                this.dompath.innerHTML = 'Editing HTML Code';
                this.hide();
            }
            return false;
        }, this, true);

        this.on('cleanHTML', function(ev) {
            YAHOO.log('cleanHTML callback fired..', 'info', 'example');
            this.get('element').value = ev.html;
        }, this, true);
        
        this.on('afterRender', function() {
            var wrapper = this.get('editor_wrapper');
            wrapper.appendChild(this.get('element'));
            //this.setStyle('width', '100%');
            //this.setStyle('height', '100%');
            this.setStyle('visibility', '');
            this.setStyle('top', '');
            this.setStyle('left', '');
            this.setStyle('position', '');

            this.addClass('editor-hidden');
        }, this, true);
    }, myEditor, true);

	// Invalid HTML Tags
	var invalidTags = {
		"abbr":{ "keepContents":true }
		,"acronym":{ "keepContents":true }
		,"address":{ "keepContents":true }
		,"applet":""
		,"area":""
		,"base":""
		,"basefont":""
		,"bdo":""
		,"big":""
		,"blockquote":{ "keepContents":true }
	}
			//,"body":{ "keepContents":true }

	// Generate the editor with no content.
	myEditor.invalidHTML = invalidTags;
	myEditor.render();
}

// Save a new template
function start_add_template(){
	document.form_add_template.submit_add_template.value = "Saving...";
	document.form_add_template.submit_add_template.disabled = true;
	return(true);
}

// Edit a selected template.
function edit_template(template_id){
	// Load the edit form.
	xmlhttpPost("/components/email_templates/api/edit.php?id="+template_id,"templates_wrapper","render_template_editor()");
}

// Edit an existing template.
function start_edit_template(){
	document.form_edit_template.save_changes.value = "Saving...";
	document.form_edit_template.save_changes.disabled = true;
	
	document.getElementById("edit_template_message").innerHTML = "";
	
	// Get a reference to the editor.
	myEditor = window.YAHOO.widget.EditorInfo.getEditorById('template_content_editor');
	
	// Place the editor content into a form field.
	document.form_edit_template.template_content_editor_content.value = myEditor.getEditorHTML()
	
	return(true);
}

// The response to editing a template.
function end_edit_template(response){
	document.form_edit_template.save_changes.value = "Saving Changes";
	document.form_edit_template.save_changes.disabled = false;
	
	document.getElementById("edit_template_message").innerHTML = "The template has been saved.";
}

// Delete a template.
function delete_template(template_id){
	// Load the content.
	website_id = document.form_craft_email.website_id.value;
	xmlhttpPost("/components/email_templates/api/list.php?website_id="+website_id+"&delete="+template_id,"templates_wrapper","activate_template_preview()");
}

// The form is complete by default.
function start_upload_file(){
	document.form_media_management.submit_upload_file.value = "Uploading...";
	document.form_media_management.submit_upload_file.disabled = true;
	return(true);
}

// Indicate success or failure.
function end_upload_file(response){
	if(response == "success"){
		// Reset the form.
		document.form_media_management.submit_upload_file.disabled = false;
		document.form_media_management.submit_upload_file.value = "Upload File";
		document.form_media_management.reset();
		
		// Load the media.
		xmlhttpPost("/components/broadcast_email/api/list_media.php","media_wrapper","activate_thumbnails()");
	}else{
		document.form_media_management.submit_upload_file.disabled = false;
		document.form_media_management.submit_upload_file.value = "Upload File";
		alert(response);
	}
}

// Select Image
function activate_thumbnails(){
	// Add a listener to the parent of the images
	$(".media_source").each(function(i){
	
		// On click
		$(this).mousedown(function(){
			document.getElementById('selected_image_wrapper').style.display = "";
			document.getElementById('selected_image_value').value = this.src;
			
			$("#selected_image").attr("src",this.src);
		});			
	});

};

// Insert Image
function insert_image(image_size){
	active_editor = "";
	
	if(document.form_craft_email.current_tab.value == "templates"){
		if(window.YAHOO.widget.EditorInfo.getEditorById('template_content_editor')){
			active_editor = "template_content_editor";
		}else{
			alert("Please select an editor to paste this image into.");
		}
	}else if(document.form_craft_email.current_tab.value == "email_editor"){
		active_editor = "form_message_id";
	}else{
		alert("Please select an editor to paste this image into.");
	}
	
	if(active_editor != ""){
		// Get the correct image size.
		selected_image_source = document.getElementById('selected_image_value').value;
		if(image_size == "thumbnail"){
			image_url = selected_image_source;
		}else{
			image_url = selected_image_source.replace("_100x100","");
			image_url = image_url.replace("/resized/","");
		}
		
		// Get a reference to the editor on the other page
		myEditor = window.YAHOO.widget.EditorInfo.getEditorById(active_editor);
		
		// Focus the editor's window
		myEditor._focusWindow();
		
		// Fire the execCommand for insertimage
		myEditor.execCommand('insertimage',image_url);
		
		// Clear the selected image.
		clear_image();	
	}
}

// Clear Image
function clear_image(){
	// Clear the selected image.
	document.getElementById('selected_image_wrapper').style.display = "none";
}

// Delete Image
function delete_image(){
	response = confirm("Are you sure you want to delete this file?");
	
	if(response){
		selected_image_source = document.getElementById('selected_image_value').value;
		
		// Select the original.
		delete_file = selected_image_source.replace("_100x100","");
		delete_file = delete_file.replace("/resized/","");
		
		delete_file_parts = delete_file.split("/");
		file_to_delete = delete_file_parts[(delete_file_parts.length-1)];
		
		xmlhttpPost("/components/broadcast_email/api/delete_file.php?file="+file_to_delete,"","image_deleted()");
	}
}

// Image Deleted
function image_deleted(){
	document.getElementById("selected_image_wrapper").style.display = "none";
	xmlhttpPost("/components/broadcast_email/api/list_media.php","media_wrapper","activate_thumbnails()");
}

// Save the Email
function start_save_email(){	
	// Get a reference to the editor.
	myEditor = window.YAHOO.widget.EditorInfo.getEditorById('form_message_id');
	
	// Add the editor's content to the form.
	document.form_craft_email.broadcast_email_content.value = myEditor.getEditorHTML();	
	
	// Saving
	document.getElementById("sending_test").innerHTML = "Saving...";
	
	return(true);
}

// Save Email Response
function end_save_email(email_id){
	// Save the returned email ID.
	document.form_craft_email.broadcast_email_id.value = email_id;
	
	// validate the form
	if(document.form_craft_email.broadcast_email_subject.value == ""){
		alert("A subject is required.");
	}else{
		// send_test 		
		if(document.form_craft_email.form_action.value == "send_test"){
			if(document.form_craft_email.test_email_address.value == ""){
				alert("To send a test email, an email address is required.");
			}else{
				xmlhttpPost("/components/broadcast_email/api/send_test.cfm?id="+email_id,"sending_test","");
			}
		}
		
		// send_test 		
		if(document.form_craft_email.form_action.value == "broadcast_it"){
			document.location.href = "/broadcast_email/step2/"+email_id+"/";
		}
	}
}

// Select a Template
function select_template(template_id){
	// Get a reference to the editor.
	myEditor = window.YAHOO.widget.EditorInfo.getEditorById('form_message_id');
	
	// Get any existing content.
	existing_content = myEditor.getEditorHTML();
	
	// Check if there's any existing content.
	if(existing_content == "<br>" || existing_content == ""){
		// Load the template content.
		xmlhttpPost_field("/components/email_templates/api/template.php?id="+template_id,"template_content","add_template_to_editor()");
	}else{
		var answer = confirm("Adding this template will overwrite the content in the editor window.");
		if(answer){
			// Load the template content.
			xmlhttpPost_field("/components/email_templates/api/template.php?id="+template_id,"template_content","add_template_to_editor()");
		}else{
			return;
		}
	}
}

// Add the template content to the editor.
function add_template_to_editor(){
	// Switch to the email editor tab.
	var newTab = tabView.getTab(0) ; 
	tabView.set("activeTab",newTab); 
	
	// Get a reference to the editor.
	myEditor = window.YAHOO.widget.EditorInfo.getEditorById('form_message_id');
	
	// Focus the editor's window
	myEditor._focusWindow();
	
	// Place the template content into the editor.
	myEditor.setEditorHTML(document.form_craft_email.template_content.value);
}

// Template Preview
function activate_template_preview(){
	fancybox_options = {
		'frameHeight':			600
		,'hideOnContentClick':	true
		,'overlayOpacity':		0.5
	}
	
	$(".template_preview").fancybox(fancybox_options);
};

// Render the Template Editor
function render_template_editor(){
	// Render an editor
	render_editor("template_content_editor");
}