(function($) { 
$.ti.utils = {
    
    // Return viable CSS classname - remove white space, ampersands and apostrophe's from string    
    makeClassName: function(string) {
		//console.log('called');
		//console.log(string);

		//if(string == undefined) { string = 'Accommodation'; }
	
		return string.replace(/\s/g, '')
                     .replace(/'/g, '')
                     .replace(/&/g, '');
    },

    // Return truncated string and add an ellipsis...
    truncate: function(string, length) {
        try {
            if(string.length > length) {
                return (string.substr(0,length) + '&#0133;');   
            } else {
                return string;
            }   
        } catch(err) {
            $.ti.console.log('$.ti.utils.truncate: ' + err);
            return "";
        }
    },
    
    // Return mixed case string (capitalise first letter of each word)
    mixCase: function(string) {
        // Ensure it is a string.
		//if(string == undefined) { string = 'Accommodation11'; }		
        string = string.toString();        
        function capitalise() {
            return arguments[0].toUpperCase();
        }
        // Regex voodoo - checks for first letter of string and then any word character (including gaelic) after a white-space i.e. first letter of every word
        return string.toLowerCase().replace(/^.|\s\w/g, capitalise);        
    },
    
    findPos: function(obj){        
        var curleft = 0, curtop = 0;
      
        if (obj.offsetParent){            
          curleft = obj.offsetLeft;
          curtop = obj.offsetTop;      
          while (obj.nodeName !== 'BODY'){
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
          }          
        }      
        return [curleft,curtop];
    },
    
    // Check against a character limit for text being entered into a textarea    
    checkLimit: function(event, textArea, letterCount){
        // Check if functional keys pressed (delete, arrow keys etc...)
        if(/^(?:8|13|16|17|20|33|34|35|36|37|38|39|40|46)$/.test(event.keyCode)) {            
            return true;				
        } else {
            // Or return false once limit reached                        
            return $(textArea).val().length < letterCount;				
        }            
    },
    
    // Return number of nodes in an object
    objectLength: function(object) {
        var node, count = 0;
        for(node in object) {
            if(object.hasOwnProperty(node)) {
                count = (count +1);   
            }            
        }
        return count;
    },
    
    // Append a node to a JSON object
    appendToObject: function(object, node) {
        var objectLength = this.objectLength(object);           
        object[objectLength] = node;
    },
    
    // Check that a new node is unique or "new" to the object it is about to be appended to
    // object (object) REQUIRED = the object that the node will be appended to
    // node (object) REQUIRED = the node that we want to append
    // identifier (string) OPTIONAL = a unique node of the child & the parents existing children that can be compared to check uniqueness e.g. "id"
    isUnique: function(object, node, identifier) {
        var child;
        
        for (child in object) {
            if(object.hasOwnProperty(child)) {
                if(identifier) {
                    if(object[child][identifier] === node[identifier]) {
                        return false;    
                    }
                } else {                    
                    if(object[child] === node) {
                        return false;
                    }
                }                    
            }
        }        
        return true;
    },
    
    // Removes any instances of double commas ',,' or any commas at the start or end of the string and returns it.
    tidyCommas: function(string) {
        var strLength;
        
        strLength = string.length - 1;
        
        // Remove any doubles
		string = string.replace(',,', ',');
		// Remove if one left at start of string
		if(string.charAt(0).match(',')) {
			string = string.replace(',', '');
		}
		if(string.charAt(strLength).match(',')) {
			string = string.slice(0, strLength);			
		}
        return string;
    },
    
    // Return array item
    getArrayItem: function(array, identifier, value) {
        var  count, length;
        
        length = array.length;
        for(count = 0; count < length; count += 1) {
            if(array[count][identifier] === value) {
                return array[count];   
            }            
        }
        return false;
    
    },
    
    // Return node name
    getNode: function(object, identifier, value) {
        var item;
        
		for(item in object) {
            if(object.hasOwnProperty(item)) {
                if(object[item][identifier] === value) {
                    return item;
                }
            }
        }
        return false;
	},
    
    // Recieves array of IDs and resets their values to default.
    resetFields: function(fields) {
        var length, count;
        length = fields.length;
        for(count = 0; count < length; count += 1) {
            $(fields[count]).val('').blur();
        }
        
    },
    
    clearErrors: function(form) {
      $('label.error', form).remove();  
    },
    
    // Pad a number into date format
    // i.e. 1 becomes 01
    // N.B. returns number as string
    padNumber: function(number) {
        return number < 10? '0' + number : number;
    },
    
    // Receives date string in format yyyy-mm-dd
    // Returns date string in format dd/mm/yyyy
    flipDate: function(date) {
        var dateArray, dateString = '', count;
        
        dateArray = date.split('-');
        for(count = 2; count >= 0; count -= 1) {            
            dateString += dateArray[count];          
            if(count > 0) {
                dateString += '/';
            }            
        }
        return dateString;
    },
    
    // Will return the day as integer from our activity gridreference strings,
    // Expects them in the format dxrx,dxxrxx etc...
    getDay: function(string) {        
        return parseInt(string.split('d')[1], 10);        
    },
    
    // Will return the row as integer from our activity gridreference strings,
    // Expects them in the format dxrx,dxxrxx etc...
    getRow: function(string) {        
        return parseInt(string.split('r')[1], 10);        
    },
    
    // Will return the duration as integer from our activity gridreference strings,
    // Expects them in the format dxrx_DURATION,dxxrxx_DURATION etc...
    getDuration: function(string) {        
        return parseInt(string.split('_')[1], 10);        
    }
    
};
})(jQuery);
