/**
 * jQuery Link Icons v1.3.3
 * http://www.swansonrussell.com
 *
 * Copyright 2011 Quiller Caudill
 *
 * Free to use and abuse under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */

(function($)
{
    $.fn.linkIcons = function(options) {
    
        /**
         * Default Settings
         */
        var settings = {
            'direction'  : 'left',                          // change to "right" to append rather than prepend the icon
            'filePath'   : '/dc_CUS_EXT/_ui/libs/jquery/img/icons/',   // absolute path to image files; must include trailing and leading slashes; @todo currently all icons must originate in the same folder
            'extensions' : {                                // object with key/value pairs representing the allowed extensions and corresponding files names
                'pdf'    : 'page_white_acrobat.png',
                'doc'    : 'page_white_word.png',
                'xls'    : 'page_white_excel.png',
                'zip'    : 'page_white_zip.png',
                'www'    : 'page_white_world.png',          // custom extension for external links
                'mailto' : 'link_email_link.png'                // custom extension for mailto links
            },
            'underline'  : false,                           // try to avoid underlining the icon
            'documents'  : true,                            // process file extension links
            'externals'  : true,                            // process external links
            'mailto'     : true,                            // process mailto links
            'class'      : 'link-icons-icon-image'          // override <img class"" /> attribute
        };
    
        /**
         * Use $context and base for reliable back references
         */
        var $context = $(this);
        var base = this;
        
        /**
         * Extend Default Settings
         */
        if(options) { 
            // First extend any children objects
            $.extend(settings.extensions, options.extensions);
            
            // Remove processed child objects
            delete options.extensions;
            
            // Finish
            $.extend(settings, options);
        }
        
        // PRIVATE FUNCTIONS
        
        function transformLinkFilepath(filename) {
            return (filename.indexOf('/') != -1) ? filename : settings.filePath + filename;
        }
         
        function transformLinkInternal(selector, filepath, suffix) {
            // Prepare image markup
            var image = '<img class="link-icons-icon-image" src="' + filepath + '" />';
            
            // Iterate over each matching link and add classes, markup, etc
            $context.filter(selector).each(function() {
                $(this).addClass('link-icon link-icon-' + suffix);
                $(this).data('link-icon-extension', suffix);
                $(this).not('.link-icon-incomplete').addClass('link-icon-incomplete');
                
                if(settings.direction == 'left') {
                    $(this).prepend(image);
                }
                else if(settings.direction == 'right') {
                    $(this).append(image);
                }
            });
        } // end function
        
        /**
         * Document Icons
         */
        function transformLinksByExtension() {
            $.each(settings.extensions, function(ext, filename) {
                // Skip this extension and continue to the next one
                if(filename == '' || filename == 'disabled' || ext == 'www' || ext == 'mailto') {
                    return true;
                }
                
                // Only use settings.filePath if the current filename doesn't include its own path
                var filepath = transformLinkFilepath(filename);
                
                transformLinkInternal('a[href$=".' + ext + '"]:not(.link-icon)', filepath, ext);
            });
        } // end function
        
        /**
         * External Links
         */
        function transformLinksExternals() {
            $context.filter('a[href^=http]:not(.link-icon)').filter(function() {
                return this.hostname && this.hostname !== location.hostname;
            }).each(function() {
                // Open in new window
                $(this).bind('click', function() { window.open($(this).attr('href')); return false; })
                
                // Adjust the title attribute
                if($(this).attr('title')) {
                    $(this).attr('title', $(this).attr('title') + ' (opens in new window)');
                } else {
                    $(this).attr('title', '(Opens in new window)');
                }
                
                // Only use settings.filePath if the current filename doesn't include its own path
                var filename = settings.extensions.www;
                var filepath = transformLinkFilepath(filename);
                
                $(this).addClass('link-icon-incomplete');
                transformLinkInternal('a.link-icon-incomplete[href^=http]:not(.link-icon)', filepath, 'ext');
            });
        } // end function
        
        /**
         * Mailto Links
         */
        function transformLinksMailto() {
            $context.filter('a[href^="mailto:"]:not(.link-icon)').each(function() {
                // Only use settings.filePath if the current filename doesn't include its own path
                var filename = settings.extensions.mailto;
                var filepath = transformLinkFilepath(filename);
            
                transformLinkInternal(this, filepath, 'mailto');
            });
        }

        /**
         * Universal adjustments after processing links
         */
        function transformLinksCleanup() {
            $context.filter('a.link-icon-incomplete').each(function() {
                // Avoid underline on the icon image itself
                if(!settings.underline && $(this).css('text-decoration').indexOf('underline') != -1) {
                    // Remember image markup
                    var image = $('img.link-icons-icon-image', this).clone().wrap('<div></div>').parent().html();
                    
                    // Remember the link contents
                    var $contents = $('<span style="text-decoration: underline">' + $(this).html() + '</span>');
                    
                    // Remove the image in preparation for move
                    $('img.link-icons-icon-image', $contents).remove();
                    
                    // Add space and image on the appropriate side
                    var contents = $contents.clone().wrap('<div></div>').parent().html();
                    if(settings.direction == 'right') {
                        contents = contents + '&nbsp;' + image;
                    } 
                    else if(settings.direction == 'left') {
                        contents = image + '&nbsp;' + contents;
                    }
                    
                    // Move underline to span element
                    $(this).css('text-decoration', 'none');
                    $(this).html(contents);
                    
                    // Mark as completed
                    $(this).removeClass('link-icon-incomplete');
                }
            });
        } // end function
        
        /**
         * Safe and Silent Logging
         */
        function log(data) {
            try {
                console.log(data);
            }
            catch(error) {
                // return null
            }
        }
        
        // PUBLIC FUNCTIONS
        
        /**
         * Initialize
         */
        this.initTransformLinks = function() {
            if(settings.documents && $(settings.extensions).length) {
                transformLinksByExtension();
            }
            
            if(settings.externals && settings.extensions.www != '') {
                transformLinksExternals();
            }
            
            if(settings.mailto && settings.extensions.mailto != '') {
                transformLinksMailto();
            }
            
            transformLinksCleanup();
        } // end function
    
        this.each(function() {
            base.initTransformLinks();
        });
        
        return this;
    };

})(jQuery);

