﻿/*  $Id$
 *  
 *  This file is part of the Jamiedia Toolkit.
 *  Copyright 2007/2008, Jamiedia Ltd., http://www.jamiedia.co.uk
 *  
 *  This file may not be used or (re)distributed for any other
 *  purposes than a commercial deployment by Jamiedia of a system
 *  based on the Jamiedia Toolkit. No modifications may be made to
 *  this file by anyone, except for individuals working for Jamiedia Ltd.
 *
 *  File description:
 *
 */ 
 
// Setup generic Jamiedia container
var Jamiedia = {};
 
// Define merging function for merging objects into the Jamiedia container
Jamiedia.apply = function(o, c, defaults) {
    if(defaults){
        // no "this" reference for friendly out of scope calls
        Jamiedia.apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};

// Add flash message object to Jamiedia container
Jamiedia.FlashMessage = {
	process: function() {
		var flashMessage = $('#flash-message');
	
		// If there is a flash message, schedule a fadeout
		if (flashMessage.length > 0) {
			$.timer(3000, function(timer) {
				flashMessage.fadeOut(1500);
				timer.stop();
			});
		}
	},
	message: function(message, type) {
		$('#flashmessage-container').html('<div id="flash-message" class="'+type+'">'+message+'</div>').show();
		this.process();
	},
	error: function(message) {
		this.message(message, 'error');
	},
	success: function(message) {
		this.message(message, 'success');
	},
	warning: function(message) {
		this.message(message, 'warning');
	}
}

// Tree API
Jamiedia.Tree = {};
Jamiedia.Tree.API = function(options) {
	this.init(options);
};

Jamiedia.Tree.API.prototype = {
	endpoint: null,
	actions: {
		addNode: 'addNode',
		deleteNode: 'deleteNode',
		moveNode: 'moveNode'
	},
	init: function(options) {
		Jamiedia.apply(this, options);
	},
	sendAction: function(action, data, successCallback, errorCallback, callback) {
		$.post(this.endpoint+action, data, function(data) {
			if (data.code == 'success')
			{
				if (typeof(successCallback) == 'function')
					successCallback(data);
			}
			else if (data.code == 'error')
			{
				if (typeof(errorCallback) == 'function')
					errorCallback(data);
				else
					alert('Error: '+data.message);
			}
			else
				alert('Unknown response code: '+data.code);
				
		}, 'json');
	},
	moveNode: function(nodeID, refNodeID, type, successCallback, errorCallback) {
		var data = {
			nodeID: nodeID,
			refNodeID: refNodeID,
			type: type
		};
		this.sendAction(this.actions.moveNode, data, successCallback, errorCallback);
	},
	deleteNode: function(nodeID, successCallback, errorCallback) {
		var data = {
			nodeID: nodeID
		};
		this.sendAction(this.actions.deleteNode, data, successCallback, errorCallback);
	},
	addNode: function(refNodeID, type, _data, successCallback, errorCallback) {
		var data = {
			refNodeID: refNodeID,
			type: type
		};
		Jamiedia.apply(data, _data);
		this.sendAction(this.actions.addNode, data, successCallback, errorCallback);
	}
};

// Utilities container
Jamiedia.Util = {};

// URL Helper
Jamiedia.Util.URL = {
	current: function(action) {
		var location = ''+window.location;

		// Remove any query string from the URL
		var qsIndex = location.indexOf('?');
		if (qsIndex != -1)
			location = location.substring(0, qsIndex);
	
		// Remove any possible anchors from the URL
		var anchorIndex = location.indexOf('#');
		if (anchorIndex != -1)
			location = location.substring(0, anchorIndex);

		// Append a trailing slash if none is present
		if (location.charAt(location.length - 1) != '/')
			location += '/';
			
		// Add an action if one was specified
		if (typeof(action) != 'undefined')
			location += action;
		
		return location;
	},
    splice: function(newUrl) {
        var currentUrl = Jamiedia.Util.URL.current();
        var firstChar = newUrl.charAt(0);
        var found = false;
        var pos = currentUrl.lastIndexOf(firstChar);
        if (pos != -1) {
            while(!found && pos != -1) {
                for (i = 1, l = newUrl.length; i < l; i++) {
                    if (currentUrl.charAt(pos + i) != newUrl.charAt(i)) {
                        pos = currentUrl.substring(0, pos).lastIndexOf(firstChar);
                        break;
                    }
                    if (currentUrl.charAt(pos + i) == newUrl.charAt(i) && newUrl.charAt(i) == '/') {
                        found = true;
                        break;
                    }
                }
            }
            if (found) {
                return currentUrl.substring(0, pos) + newUrl;
            } else {
                alert('No Match!');
            }
        } else {
            alert('No Match!')  ;
        }        
    },
	title: function(title, lowerCase, decodeEntities) {
		// Remove whitespace from beginning and end
		title = jQuery.trim(title);
		
		// Remove all ' and "
		title = title.replace("'", '"').replace('"', '');
		
		// Replace all &'s with 'and'
		title = title.replace('&', 'and');
		
		// Replace invalid characters
		var invalid 		= "()!$'?: ,&+-/.ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ";
		var replacements 	= "--------------SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy";
		
		for (var i = 0; i < invalid.length; ++i) {
			title = title.split(invalid.charAt(i)).join(replacements.charAt(i));
		}
		
		// Translate to lower case if requested
		return (typeof(lowerCase) == "undefined" ? title.toLowerCase() : title);
	}
};

// Form helpers
Jamiedia.Util.Form = {
	clear: function(form) {
		$(':input', form).each(function() {
			var type = this.type, tag = this.tagName.toLowerCase();
			if (type == 'text' || type == 'password' || tag == 'textarea')
				this.value = '';
			else if (type == 'checkbox' || type == 'radio')
				this.checked = false;
			else if (tag == 'select')
				this.selectedIndex = -1;
		});
	},
	disable: function(form) {
		this.setDisable(form, true);
	},
	enable: function(form) {
		this.setDisable(form, false);
	},
	setDisable: function(form, disabled) {
		$(':input', form).each(function() {
			this.disabled = disabled;
		});
	},
	clearAndDisable: function(form) {
		this.clear(form);
		this.disable(form);
	}
};

// Initialize flash message processing
$(document).ready(function() {
	// Set fade time for a flash message, if one was specified
	Jamiedia.FlashMessage.process();
	
	// Register AJAX loader with AJAX events
	$('#ajax-loader').ajaxStart(function() { $(this).show(); }).ajaxStop(function() { $(this).hide(); });
});

