/*
Copyright (c) 2008 Toby Somerville, http://ikonize.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

//window.onload = iKonize; // Another way to initialise the code but, only executes after all the media in the page has fully downloaded

function iKonize(){
    /*** START OF CONFIGURATION AREA ***/
    
    var classPrefix = 'iKon_'; // any prefix of the class names
    var classExternal = 'iKon_external'; // the external class name
    var externalIconLoc = '/images/interface/external.gif'; // the external icons location
    
    // Individual classes
    var IndividualClassArray = Array('txt', 'xls', 'css', 'torrent', 'exe', 'vcard', 'ical', 'pps', 'pdf');
    
    // Group file classes - an array of arrays
    // Note: First item in each list is the base CSS class name
	// Full CSS class name = classPrefix + base CSS class name
    var classArray = Array(IndividualClassArray, 
						    Array('doc', 'doc', 'rtf'),
						    Array('feed', 'rss', 'atom'),
						    Array('archive', 'zip', 'sit', 'tar', 'rar', 'gzip', 'ace', 'bzip'),
						    Array('image', 'gif', 'jpg', 'jpeg', 'png', 'bmp', 'eps', 'svg'),
						    Array('movie', 'mov', 'wmv', 'mp4', 'avi', 'mpg'),
						    Array('audio', 'mp3', 'wav', 'ogg', 'wma', 'm4a'),
						    Array('flash', 'swf', 'fla')
	);
    
	// You shouldn't need to change this
	var url = parseURL(qualifyHREF(document.location.href)).hostname; // the site URL
	
    /*** END OF CONFIGURATION AREA ***/
	
    var aElements = document.getElementsByTagName("a");
    var iElements = aElements.length;
    var iLen = classArray.length; // Length of: classArray 
    var bExternal = false;
    var bFound = false;
    var linkClass = '';
    
    if (iElements > 0) { // There are some links
        for (iv = 0; iv < iElements; iv++) {
            // Reset variables
            bFound = false;
            bExternal = false;
            linkHref = aElements[iv].href; // Get the link's href
            linkClass = '';
            
            oUrl = parseURL(qualifyHREF(linkHref)); // get the full url and parse it into chunks
            fileExt = oUrl.extension;
            
            // External links
            if (oUrl.hostname.indexOf(url) == -1) { // not our url
                bExternal = true;
            }
            for (ii = 0; ii < iLen; ii++) { // Loop the array
                iArr = classArray[ii].length; // Get the length of the array
                for (i = 0; i < iArr; i++) { // Loop the array
                    if (fileExt == classArray[ii][i]) { // Compare the file extension with the array value					
                        if (ii === 0) { // First array
                            linkClass = fileExt; // Make the CSS base class the first item in the array
                        }
                        else {
                            linkClass = classArray[ii][0]; // Make the CSS base class the first item in the array
                        }
                        bFound = true; // The file extension matches
                        break; // ok you can exit the loop
                    }
                }
            }
            
            if (bFound && linkClass !== '') { // we need to add an icon after the link
                // add the appropriate class
                addClass(aElements[iv], classPrefix + linkClass);
            }
            if (bExternal) { //  an external link
                img = document.createElement('img'); // Create a new img element
                img.id = 'Newimg' + iv; // assign an id to the new tag
                img.src = externalIconLoc; // set image location
                img.alt = 'external site'; // set image alt text
                img.title = 'links to an external web site'; // set the title of the new image element
                void (aElements[iv].appendChild(img)); // add the tag after the link
                oimg = document.getElementById("Newimg" + iv); // get the new img
                addClass(oimg, classExternal); // add the external class
            }
        }
    }
    //parse a URL to form an object of properties
    function parseURL(url){
        var loc = {
            'href': url
        };
        var parts = url.replace('//', '/').split('/');
        loc.protocol = parts[0];
        loc.host = parts[1];
        parts[1] = parts[1].split(':');
        loc.hostname = parts[1][0];
        loc.port = parts[1].length > 1 ? parts[1][1] : '';
        parts.splice(0, 2);
        loc.pathname = '/' + parts.join('/');
        loc.pathname = loc.pathname.split('#');
        loc.hash = loc.pathname.length > 1 ? '#' + loc.pathname[1] : '';
        loc.pathname = loc.pathname[0];
        loc.pathname = loc.pathname.split('?');
        loc.search = loc.pathname.length > 1 ? '?' + loc.pathname[1] : '';
        loc.pathname = loc.pathname[0];
        var dotty = loc.pathname.split('.');
        if (dotty.length > 1) {
            loc.extension = dotty[(dotty.length - 1)];
        }
        else {
            loc.extension = '';
        }
        return loc;
    }
    //qualify an HREF to form a complete URI
    function qualifyHREF(href, context){
        var here = document.location.href;
        var bases = document.getElementsByTagName('base');
        if (bases.length > 0) {
            var basehref = bases[0].getAttribute('href');
            if (basehref && basehref != '') {
                here = basehref;
            }
        }
        if (typeof context == 'string' && context != '') {
            here = context;
        }
        var parts = here.replace('//', '/').split('/');
        var loc = {
            'protocol': parts[0],
            'host': parts[1]
        }
        parts.splice(0, 2);
        loc.pathname = '/' + parts.join('/');
        var uri = loc.protocol + '//' + loc.host;
        if (/^(\.\/)([^\/]?)/.test(href)) {
            href = href.replace(/^(\.\/)([^\/]?)/, '$2');
        }
        if (/^([a-z]+)\:\/\//.test(href)) {
            uri = href;
        }
        else 
            if (href.substr(0, 1) == '/') {
                uri += href;
            }
            else 
                if (/^((\.\.\/)+)([^\/].*$)/.test(href)) {
                    var lastpath = href.match(/^((\.\.\/)+)([^\/].*$)/);
                    lastpath = lastpath[lastpath.length - 1];
                    var references = href.split('../').length - 1;
                    var parts = loc.pathname.split('/');
                    parts = parts.splice(0, parts.length - 1);
                    for (var i = 0; i < references; i++) {
                        parts = parts.splice(0, parts.length - 1);
                    }
                    var path = '';
                    for (i = 0; i < parts.length; i++) {
                        if (parts[i] != '') {
                            path += '/' + parts[i];
                        }
                    }
                    path += '/';
                    path += lastpath;
                    uri += path;
                }
                else {
                    path = '';
                    parts = loc.pathname.split('/');
                    parts = parts.splice(0, parts.length - 1);
                    for (var i = 0; i < parts.length; i++) {
                        if (parts[i] != '') {
                            path += '/' + parts[i];
                        }
                    }
                    path += '/';
                    uri += path + href;
                }
        return uri;
    }
    function hasClass(target, theClass){// Excellent function adapted from the Core library
        var pattern = new RegExp("(^| )" + theClass + "( |$)");
        if (pattern.test(target.className)) {
            return true;
        }
        return false;
    };
    function addClass(target, theClass){ // Excellent function adapted from the Core library
        if (!hasClass(target, theClass)) {
            if (target.className == "") {
                target.className = theClass;
            }
            else {
                target.className += " " + theClass;
            }
        }
    };
}