/*
 * tanabicom.js
 *
 * Javascript managing the Tanabicom website.
 * Copyright (c) 2009 Tanabicom, LLC
 * http://www.tanabi.com
 *
 * Released under the MIT license:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/* Initialize TinyMCE */
tinyMCE.init({
    mode: "none",
    theme: "simple"
});

/* TanabiCom class to manage all the functionality of the site under one
 * namespace.
 */
var TanabiCom = new function(){
	return {
	/* Keep track of the current URL (initializing it to whatever URL the
	 * user landed on) so that we can have dynamic bookmarks.
	 */
		current_url: window.location.href,
	/* Is the user logged in?  This is just a helper for javascript.
	 * The PHP back-end doesn't rely on this variable, and therefore
	 * messing with it in FireBug won't help you out :)
	 */
		logged_in: false,
    /* Is the user an administrator?  Note, you can hack this but nothing
     * on the back-end relies on this :)  It will just make some hidden
     * fields show up.
     */
        admin: false,
	/* Have we cleared the user field on purpose yet?
	 * This is also an indication if the user has put in a name yet.
	 */
		cleared_user_field: false,
    /* This is needed to help make TinyMCE work with Ajax */
        tinymce_tmp: new Array(),
	/* Reload the browser on login ? */
		reload_on_login: false,
	/*
	 * function emailCheck(email)
	 *
	 * Checks an email address to be sure it's valid, returns boolean.
	 */
		emailCheck: function(email){
			/* The email regex used here was found on:
			 * http://xyfer.blogspot.com/2005/01/javascript-regexp-email-validator.html
			 * Credit goes to that site!
			 */
			var email_check = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
			
			return email.match(email_check);
		},
	/*
	 * function resize()
	 *
	 * There's probably a really good way to do this with just CSS, but
	 * I'm really not sure.  This javascript will keep resizes nice and
	 * make sure the background box / layout remains intact.
	 */
		resize: function(){
			var sidebar_height = $('#sidebar_container').height();
			var content_height = $('#content').height();

			if(sidebar_height > content_height){
				var background_height = sidebar_height + 45;
			}else{
				var background_height = content_height + 45;
			}

			$('#background_box').css('height',background_height + 'px');
		},

	/*
	 * function load(page,query)
	 *
	 * Does an ajax page load into the given query, and calls resize.
	 */
		load: function(page,query){
			if((typeof query == 'undefined') || (!query.length)){
				alert('You forgot the query!');
				return;
			}
			
			var target = $(query);

		/* If we did everything right, we should never get this
		 * error.
		 */
			if(!target.length){
				alert("The link you just clicked isn't functional.  Your jQuery failed.");
				return;
			}

		/* Make a nice little loading message ... */
			target.empty().text('Loading...');

		/* Call ajax */
			$.ajax({
				async: true,
				dataType: 'html',
			/* If cache is true, then IE 6 will lock up so hard
			 * you have to Task Manager kill it.
			 */
				cache: false,
				error: function(req,stat,err){
					var error = 'Could not load the page: ';

					/* Check for 404's */
					if(req.status == 404){
						error = error + 'File not found.';
					}else if(stat && stat.length){
						error = error + stat;
					}else if(err && err.length){
						error = error + err;
					}

					target.empty().html(error);
					TanabiCom.resize();
				},
				success: function(data,stat){
				/* On success, let's update the
				 * current_url to a direct link.
				 */
					TanabiCom.current_url = window.location.protocol + '//' + window.location.hostname;

				/* Handle relative or absolute link */
					if(page.match(/^\//)){
						TanabiCom.current_url = TanabiCom.current_url + page;
					}else{
						TanabiCom.current_url = TanabiCom.current_url + '/' + page;
					}

					target.empty().html('<p id="bookmark_link"><a href="' + TanabiCom.current_url + '" title="Direct Link">Tanabicom: Right-Click Here to Bookmark</a></p>' + data);
					TanabiCom.resize();
				},
				url: page
			});
		},
	/*
	 * function buildMailForm(query)
	 *
	 * Builds an email form, appending to element 'query'
	 */
		buildMailForm: function(query){
		/* Make sure we only have 1 email form */
			if($('#generated_email_form').length){
				return;
			}
			
			$(query).append('<form id="generated_email_form"><div class="form_label">Your Name: <input name="name" type="text" /></div><div class="form_label">Your Email: <input name="email" type="text" /></div><div class="form_label" style="text-align: left;">Your Message</div><textarea name="message"></textarea><div class="form_label"><input type="button" name="submit" value="Send Mail" style="width: 80px;" /></div></form>');

			$('#generated_email_form input[type="button"]').click(function(){
				if((!$('input[name="name"]').val().length)||
				   (!TanabiCom.emailCheck($('input[name="email"]').val()))||
				   (!$('textarea[name="message"]').val().length)){
					alert('Please enter your name, a valid email address, and a message.');
					return;
				}
				
				$.ajax({
					async: false,
					data: $('#generated_email_form').serialize(),
					type: 'POST',
					dataType: 'text',
					cache: false,
					error: function(req,stat,err){
						alert('Failed to send the email -- try emailing directly to answers@tanabi.com');
					},
					success: function(data,stat){
						$('#generated_email_form').replaceWith('<div>Thank you for your email!</div>');
					},
					url: '/index/email'
				});
			});
		},
	/*
	 * function loginUser()
	 *
	 * This is the on click handler for the login button.
	 */
		loginUser: function(){
			$.ajax({
				async: false,
				data: $('#user_form').serialize(),
				type: 'POST',
				dataType: 'text',
				cache: false,
				url: '/user/login',
				error: function(req,stat,err){
					alert('Failed to submit login attempt.');
				},
				success: function(data,stat){
					if((data != 'Admin') && (data != 'Success')){
						alert(data);
					}else{
						$('#login_form').empty().text('You are logged in.');
						TanabiCom.logged_in = true;
                        TanabiCom.admin = (data == 'Admin');
						$('.logged_in').show();
                        
                        if(TanabiCom.admin){
                            $('.logged_in_admin').show();
                        }
						
						// Reload the page if it's desired.
						if(TanabiCom.reload_on_login){
							document.location.reload();
						}
					}
				}
			});
		},
	/*
	 * function createUser()
	 *
	 * This is the click handler for the create button.
	 */
		createUser: function(){
			if(!TanabiCom.cleared_user_field){
				alert('Please enter your name first.');
				return;
			}
			
			$.ajax({
				async: false,
				data: $('#user_form').serialize(),
				type: 'POST',
				dataType: 'text',
				cache: false,
				url: '/user/create',
				error: function(req,stat,err){
					alert('Failed to submit login create attempt.');
				},
				success: function(data,stat){
					if(data != 'Success'){
						alert(data);
					}else{
						$('#login_form').empty().text('You are logged in.');
						TanabiCom.logged_in = true;
						if(TanabiCom.reload_on_login){
                                                        document.location.reload();
                                                }

						$('.logged_in').show();
					}
				}
			});
		},
    /*
     * function renderTinyMCE()
     *
     * This is to help render TinyMCE for ajax.
     */
        renderTinyMCE: function(){
            var ed = TanabiCom.tinymce_tmp.pop();
            ed.render();
        },
    /*
     * function createTinyMCE(ele)
     *
     * Turns 'ele' into a tinyMCE text area.  'ele' should be the text of
     * an id.
     */
        createTinyMCE: function(ele){
            var ed = new tinymce.Editor(ele,{theme: 'simple'});
            TanabiCom.tinymce_tmp.push(ed);
            tinyMCE.add(ed);
            setTimeout('TanabiCom.renderTinyMCE()',0);
        },
    /*
     * function destroyTinyMCE(ele)
     *
     * Cleanly deletes a tinyMCE instance.
     */
        destroyTinyMCE: function(ele){
            tinyMCE.execCommand('mceRemoveControl',false,ele);
            tinymce.EditorManager.remove(ele);
            tinymce.EditorManager.activeEditor = null;
            tinyMCE.activeEditor = tinyMCE.selectedInstance = null;
        },
    /*
     * function adminDeleteJournal(id)
     *
     * This is a click handler for deleting a journal entry.  It will only
     * work if you're logged in as an admin though.
     */
        adminDeleteJournal: function(id){
            if(!TanabiCom.logged_in){
                alert('You are not logged in.');
                return;
            }
            
            if(!confirm('Are you sure you want to delete this entry?')){
                return;
            }
            
            $.ajax({
                async: false,
                data: "id=" + id,
                type: 'POST',
                dataType: 'text',
                cache: false,
                url: '/journal/delete',
                error: function(req,stat,err){
                    alert('Failed to submit delete request.');
                },
                success: function(data,stat){
                    if(data != 'Success'){
                        alert(data);
                    }else{
                        $('#journal_' + id).hide();
                    }
                }
            });
        },
    /*
     * function adminBeginEditJournal(id)
     *
     * This is a click handler for editing a journal entry.  It will only
     * work if you're logged in as an admin.
     */
        adminBeginEditJournal: function(id){
            if(!TanabiCom.logged_in){
                alert('You are not logged in.');
                return;
            }
            
            /* Replace the journal_{id}_body div contents with a text area.
             * But only if we don't already have a text area there.
             */
            if($('#journal_' + id + '_body textarea').length){
                /* Clear away the edit area in this case */
                TanabiCom.destroyTinyMCE('journal_' + id + '_textarea');
                var contents = $('#journal_' + id + '_textarea').val();
                $('#journal_' + id + '_body').empty().html(contents);
                
                var title = $('#journal_' + id + '_title_text').val();
                $('#journal_' + id + '_title').empty().html(title);
                
                $('#journal_' + id + '_submit').hide();
                return;
            }
            
            /* Change the title to a text area */
            var journal_title = $('#journal_' + id + '_title');
            var title = journal_title.html();
            journal_title.empty().html('<input type="text" id="journal_' + id + '_title_text" class="journal_title_text" value="' + title + '" />');
            
            var journal_body = $('#journal_' + id + '_body');
            var contents = journal_body.html();
            journal_body.empty().html('<textarea id="journal_' + id + '_textarea" class="journal_textarea">' + contents + '</textarea>');
            TanabiCom.createTinyMCE('journal_' + id + '_textarea');
            $('#journal_' + id + '_submit').show();
        },
    /*
     * function adminSubmitEdit(id)
     *
     * This does an edit submit.  This may also create a new entry.
     */
        adminSubmitEdit: function(id){
            if(!TanabiCom.logged_in){
                alert('You are not logged in.');
                return;
            }
            
            /* Let's call adminBeginEditJounal to close the journal entry
             * first.
             */
            TanabiCom.adminBeginEditJournal(id);
            
            /* Send the data over. */
            $.ajax({
                async: false,
                data: "id=" + id + "&title=" + encodeURIComponent($('#journal_' + id + '_title').html()) + "&body=" + encodeURIComponent($('#journal_' + id + '_body').html()),
                type: 'POST',
                dataType: 'text',
                cache: false,
                url: '/journal/edit',
                error: function(req,stat,err){
                    alert('Failed to submit edit request.');
                },
                success: function(data,stat){
                    if(data != 'Success'){
                        alert(data);
                        TanabiCom.adminBeginEditJournal(id);
                    }else{
                        window.location.reload();
                    }
                }
            });
        }
	};
};

$(document).ready(function(){
	TanabiCom.buildMailForm('#email_form');
	TanabiCom.resize();
	
	$('#login_button').click(TanabiCom.loginUser);
	$('#create_button').click(TanabiCom.createUser);

/* Put a handler in so that when the user clicks the 'name' field, it empties,
 * but only the first time it's clicked.
 */
	$('input[name="name"]').focus(function(){
		if(!TanabiCom.cleared_user_field){
			TanabiCom.cleared_user_field = true;
			this.value='';
		}
	});
});
