;ET.UTIL = 
{
    popup: function(url, name, width, height)
    {
        var name = (typeof name == 'undefined') ? 'popup' : name;
        var width = (typeof width == 'undefined') ? 380 : width;
        var height = (typeof height == 'undefined') ? 220 : height;
        window.open(url, name, 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+width+',height='+height);
    },
    
    isEmailValid: function(email)
    {
        // By Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
        return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
    },
    
    isValidPostcode: function(postCode) 
    {
        var matches = postCode.match(/\d+/g);
        if(matches === null || matches[0].length !== 4)
        {
            alert('Australian postcodes are 3 or 4 digit numbers between 200-300\nor 800-9999. Australian postcodes don\'t contain characters.');
            return false;
        }
        
        return true;
    },
    
    $dump: function($collection, key, val)
    {
        $collection.each(function()
        {
            ET.UTIL.log($(this).attr(key) + ': '+ $(this).attr(val));
        })
    },
    
    formatCurrency: function(amount)
    {
        // Ensure num is a string
        amount = amount + '';
        amount = amount.match(/[\d\.]+/)[0];
        amountArray = [];
        
        // If amount has a decimal, add this to the array and extract it from amount
        if(amount.indexOf('.') > -1)
        {
            amountArray.unshift(amount.substring(amount.indexOf('.')));
            amount = amount.substring(0, amount.indexOf('.'));
        }    
        
        // Split the amount into array elements every three numbers
        for(var i=amount.length; i>0; i-=3)
        {
            amountArray.unshift(amount.substring(i, i-3));
        }
        
        // Put it all back together again (replacing ,. is for numnbers with decimals)
        return amountArray.join(',').replace(',.', '.');
    },
    
    getUrlVars: function(strUrl, param)
    {
        var queryString='', urlVars='', urlObj={};
     
        if (strUrl == '' || typeof strUrl == 'undefined') 
        {
            queryString = window.location.search;
        }
        else
        {
            queryString = strUrl;
        }
     
        // remove '?'
        urlVars = queryString.substring(1).split('&');
     
        for(var i=0; i<urlVars.length; i++)
        {
            var urlVar = urlVars[i].split('=');
            urlObj[urlVar[0]] = decodeURIComponent(urlVar[1]);
        };
     
        if(typeof param != 'undefined')
        {
            if(typeof urlObj[param] != 'undefined')
            {
                return urlObj[param];
            }
            else
            {
                return '';
            }
        }
     
        return urlObj;
    },

    getQueryVariable:function(key) 
    { 
        return this.getUrlVars('', key);
    },
    
    log: function(expression)
    {
        try
        {
            console.log(expression);
        }
        catch(e){};
    },
    
    /**
     * Taken from http://4umi.com/web/javascript/camelcase.php
     *
     * Takes a camelCased string and breaks it into it's word components
     */
    camelCase: function(s) 
    { 
        s = $.trim(s);

        return ( /\S[A-Z]/.test( s ) ) ?
            s.replace(/(.)([A-Z])/g, function(t,a,b) 
            { return a + ' ' + b.toLowerCase(); }) :
            s.replace(/( )([a-z])/g, function(t,a,b) { return b.toUpperCase(); });
    },
        
    camalCaseCapitalise: function(s)
    {
        /** There is a bug with the ET.UTIL.titleCaps which doesn't apply 
         * capitalisation if a number is present. Therefore, we convert all
         * numbers to @ symbols, feed the string into the functions, then 
         * replace the @ symbols with the original number values before 
         * returning result.
         */
         
        // Attempt to replace numbers with @ symbol
        var numbers = s.match(/\d+/g);
        s = s.replace(/\d+/g, '@');

        var result = ET.UTIL.titleCaps(ET.UTIL.camelCase(s));
        
        // Replace @ symbols numbers
        if(numbers === null) { return result; }
        
        for(var i=0; i<numbers.length; i++)
        {
            result = result.replace(/@/, numbers[i]);
        }
        
        return result;
    },
    
    format: function(string) 
    {
        var args = arguments;
        var pattern = new RegExp('{([1-' + arguments.length + '])}','g');
        return String(string).replace(pattern, function(match, index) { return args[index]; });
    },
    
        
    newLineToBr: function(str)
    {
        return String(str).replace(/[\r\n]+/g, function(match, index) 
        { 
            return '<br /><br />'; 
        });
    },
    
    truncateText: function($e, settings)
    {
        if($e.length == 0)
        {
            return false;
        }
        
        var defaults = 
        {
            len: 180,
            finish: '&hellip;',
            stopChar: '.',
            ignoreStopChar: false
        };

        settings = (typeof settings != 'undefined') ? $.extend(defaults, settings) : defaults;
            
        $e.each(function()
        {
            var text = $.trim($(this).text()).replace(/[\n\r\t]+/gm, ' ').replace(/\.[ ]+([A-Z0-9a-z]+)/gm, '. $1').replace(/\.([a-zA-Z0-9]+)/gmi, '. $1')
            var position = settings.len;
            var prevStrPos = 0;
            var search = true;
            var count = 0;
            
            while(search)
            {       
                // Find position of stop character
                var strPos = prevStrPos + text.substring(prevStrPos).indexOf(settings.stopChar);
                
                // If the prev stop char position and the new position are the same, then we're not finding anything new so break
                if(strPos >= settings.len || (prevStrPos - 1) == strPos || count > 10)
                {
                    search = false;
                    break;
                }
                
                // If position of stop char is less than max length (len), then change position
                if(strPos < settings.len) 
                { 
                    position = strPos;
                    prevStrPos = position + 1;
                }
            }
            
            var truncatedString = (settings.ignoreStopChar) ? text.substring(0, settings.len).replace('&hellip;', '').replace('…', '') : text.substring(0, position);
            
            // If stop position is found before max length, display truncated string without finish as it's a complete sentence
            // unless ignoreStopChar is set to true
            if(position != settings.len)
            {
                $(this).html(truncatedString + settings.stopChar);
                if(settings.ignoreStopChar)
                {
                    $(this).html($(this).html().substring(0, $(this).html().length-1) + settings.finish);
                }
            }
            else
            {
                // if stop char not found and length of text is less than max length, append finish to truncated string
                if(truncatedString.indexOf(settings.stopChar) == -1 && text.length < settings.len)
                {
                    $(this).html(truncatedString + settings.finish);
                }
                // We're stuck most likely in the middle of a word so back track until we find the first space char, append finish to truncated string
                else
                {
                    var spaceCharPos = truncatedString.lastIndexOf(' ');
                    $(this).html(truncatedString.substring(0, spaceCharPos) + settings.finish);
                }
            }
            
            var html = $(this).html();
            var lastChar = html.charAt(html.length - 2);
            if(lastChar == settings.stopChar || lastChar == ' ')
            {
                $(this).html(html.substring(0, html.length-2) + settings.finish);
            }
        });
    },
    
    /**
     * Strip out content type tags that are usually embedded within a div or p element
     */
    filterHTMLText: function(text)
    {
        var testToRemove = /<br>|<ul>|<\/ul>|<ol>|<\/ol>|<li>|<\/li>|<p>|<br\/>|<br \/>|<\/p>|<a .*?>|<\/a>|^[ \t]+/gi;
        return text.replace(testToRemove, function (sMatch) 
        {
            return sMatch.replace(/./g, " ").replace(/[\n\r\t]*/, ' ');
        });
    },
    
    /**
     * Strip out all potentially harmful characters from an input field
     */
    filterInputText: function(str)
    {
        try
        {
            return str.match(/[a-zA-Z0-9\(\)\',.!/:%@&?+_=\-\$ ]+/gm).join('');
        }
        catch(e)
        {
            return '';
        }
    }
};


/*
 * Title Caps
 * 
 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
 * License: http://www.opensource.org/licenses/mit-license.php
 */
(function()
{
    var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
    var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
  
    ET.UTIL.titleCaps = function(title)
    {
        var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
        
        while (true) 
        {
            var m = split.exec(title);

            parts.push( title.substring(index, m ? m.index : title.length)
                .replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all)
                {
                    return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
                })
                .replace(RegExp("\\b" + small + "\\b", "ig"), lower)
                .replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word)
                {
                    return punct + upper(word);
                })
                .replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
            
            index = split.lastIndex;
            
            if(m) parts.push(m[0]);
            else break;
        }
        
        return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
            .replace(/(['Õ])S\b/ig, "$1s")
            .replace(/\b(AT&T|Q&A)\b/ig, function(all){
                return all.toUpperCase();
            });
    };
    
    function lower(word)
    {
        return word.toLowerCase();
    }
    
    function upper(word)
    {
      return word.substr(0,1).toUpperCase() + word.substr(1);
    }
})();