﻿var Site = {
    start: function() {
        ExternalLinks.start();
        IE6FlickerFix.start();
        WordLimit.start();
    }
};

var IE6FlickerFix =
{
    start: function() {
        try { document.execCommand("BackgroundImageCache", false, true); }
        catch (err) { }
    }
};

var ExternalLinks = {
    start: function() {
        if (!document.getElementsByTagName) return;
        var anchors = document.getElementsByTagName('a');
        for (var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            try {
            if (anchor.getAttribute('href') && anchor.getAttribute('rel').indexOf('external') > -1 && anchor.getAttribute('href') != "javascript:void(0);")
                anchor.target = '_blank';
            }catch(err) {}
        }
    }
};

function replaceWithFlash(elementId, swfFile, width, height)
{
    var so = new SWFObject(swfFile, "movie", width, height, "6");
    so.write(elementId);
}

var WordLimit = {
    start: function() {
        // Get a collection of all the inputs with word limits
        var wordLimited = $$('.wordlimit');

        // Loop through each of these inputs and add a onkeyup event
        wordLimited.each(function (input){           
            // Get the full class attribute
            var classAtr = input.className;
            
            // From the class get the word limit
            var wordLimit = classAtr.replace(new RegExp("([^0-9]+)", "g"), "")
            
            // From the class get the id of the span that contains the word limit
            var idOfSpan = classAtr.substring(classAtr.lastIndexOf(" ") + 1);

            Event.observe(input, 'keyup', function()
            {
                // Words
                var words = input.value.split(' ');
            
                // Count the number of spaces in the text
                var wordCount = (words.length * 1) - 1;

                // Display the number of spaces
                $(idOfSpan).innerHTML = wordCount;
                
                // If we have gone over the word limit then delete the excess
                if (wordCount > wordLimit)
                {
                    // Build up a string of the words up to the limit
                    var wordsToLimit = '';
                    var counter = 0;
                    
                    while (counter < wordLimit)
                    {
                        wordsToLimit += words[counter] + ' ';
                        counter++;
                    }
                
                    input.value = wordsToLimit;
                }
            });
        });
    }
};

Event.observe(window, 'load', function() { Site.start(); });