;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);
    },
    showError: function()
    {
        jQuery('#searchResultsContainer:empty').html(jQuery('#searchFailedContainer').html());
    },
    tabToggle: function()
    {
        jQuery('li#newsPaperAds').click(function() {
            jQuery('li#pressReleases').removeClass('first');
            jQuery('li#newsPaperAds').addClass('first');
            jQuery('div#newspaperAdsContent').removeClass('hide');
            jQuery('div#pressReleaseContent').addClass('hide');
        });
        jQuery('li#pressReleases').click(function() {
            jQuery('li#newsPaperAds').removeClass('first');
            jQuery('li#pressReleases').addClass('first');
            jQuery('div#pressReleaseContent').removeClass('hide');
            jQuery('div#newspaperAdsContent').addClass('hide');
        });
    
    },

    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));
        })
    },
 
     fixBrokenProductImages: function($element)
    {
        $element.find('img').each(function()
        {
            if($(this).fclIsImageBroken() === true)
            {
                $(this).attr('src', '/cms_images/web_images/products/default-generic.gif');
            }
        })
    },
   
    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 '';
        }
    },
	
	 /* 
     *  Returns true if the page is a domestic product landing page.
     *  @returns Boolean 
     */
     isDomesticProductPage: function()
     {
         
        // Search through URL for domestic locations in list below, if exist assume domestic product.
        var domesticLocations = {"domestic": 1,"act": 1,"adelaide": 1,"airlie beach": 1,"albury": 1,"alice springs": 1,"armidale": 1,"australia": 1,"australian capital territory": 1,"ayers rock": 1,"ballina": 1,"bathurst": 1,"brisbane": 1,"broome": 1,"bundaberg": 1,"burnie": 1,"cairns": 1,"canberra": 1,"casino": 1,"coffs harbour": 1,"cooma": 1,"cootamundra": 1,"cowra": 1,"cudal": 1,"darwin": 1,"devonport": 1,"dubbo": 1,"emerald": 1,"forbes": 1,"glen innes": 1,"gold coast": 1,"grafton": 1,"griffith": 1,"hamilton island": 1,"hervey bay": 1,"hobart": 1,"inverell": 1,"kalgoorlie": 1,"karratha": 1,"kempsie": 1,"launceston": 1,"lismore": 1,"mackay": 1,"maryborough": 1,"melbourne": 1,"merimbula": 1,"midura": 1,"moree": 1,"moruya": 1,"mount gambier": 1,"mount isa": 1,"mt isa": 1,"mudgee": 1,"narrabri": 1,"narrandera": 1,"new south wales": 1,"newcastle": 1,"newman": 1,"northern territory": 1,"nsw": 1,"nt": 1,"orange": 1,"paraburdoo": 1,"parkes": 1,"perth": 1,"port hedland": 1,"port macquarie": 1,"portland": 1,"proserpine": 1,"qld": 1,"queensland": 1,"rockhampton": 1,"sa": 1,"south australia": 1,"surfers paradise": 1,"sunshine coast": 1,"sydney": 1,"tamworth": 1,"taree": 1,"tas": 1,"tasmania": 1,"tom price": 1,"toowoomba": 1,"townsville": 1,"traralgon": 1,"vic": 1,"victoria": 1,"wa": 1,"waggawagga": 1,"west wyalong": 1,"western australia": 1,"whitsunday": 1,"whitsunday coast airport": 1,"whitsunday islands": 1,"young": 1};    
        var domainPath = decodeURIComponent(window.location.pathname).replace(/[\+-]/g ," ").replace(/\s\d{6,7}/g ,'').split("/");
        var isDomestic = false;
               
        $.each(domainPath, function(x,destination){
            if( domesticLocations[destination.toLowerCase()] )
            {
                isDomestic = true;    
            }
        });

        // Check the product details to see if it is a bookable product
        if(typeof ET!='undefined' && typeof ET.PRODUCTS!='undefined' && ET.PRODUCTS.productProperties)
        {           
            var destination = ET.PRODUCTS.productProperties.destination || '';
            if(domesticLocations[destination.toLowerCase()])
            {
                 isDomestic = true;
            }
        }
        
        // change the phone number to online direct team
        if(isDomestic)
        {
            $('.enquiry-number').html(ET.SETTINGS.onlineDirectNumber); 
        }
        
        return isDomestic;
     },
    createCookie: function(name,value,days)
    {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    },

    readCookie: function(name)
    {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },

    eraseCookie: function(name)
    {
        ET.UTIL.createCookie(name,"",-1);
    },
	 
	parseProductProperties: function()
    {
		var _this = this;
		var productProperties = Array();
        $('head').find('meta[name^="product."]').each(function()
        {
            var key = $(this).attr('name').match(/\.(.*)$/)[1];
            var value = $(this).attr('content');
            productProperties[key] = value;
        });
		return productProperties;
    }
};


/*
 * 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);
    }
})();
