/**
 * Библиотека за оправяне на png изображения при IE6
 *
 * Изисква mootools 1.11 минимум
 *
 * @author Красимир Йосифов
 * @version 1.0  11.04.2008 г.
 */

var mooPngFix = new Class({
    version : '1.0',
    options : {
        debug : false,              // debug = ( true | false )
        debugConainer : 'debugContainer',
        spacerFile : 'spacer.gif',  // файл с размер 1x1 px прозрачен
        spacerSrc : './',            // път до spacerFile, зададен от root пътя на файла
        autoFix : true,
        imgFixClass : 'pngFixImg',
        bgFixClass : 'pngFixBg',
        inputFixClass : 'pngFixInput'
    },

    initialize : function( options ) {
        // инициализиране на променливи
        this.setOptions( options );
        this.debug = [];

        if ( this.options.autoFix ) {
            // поправяне на всички картинки
            this.fixAll();
        }
        if ( this.options.debug ) {
            this.showDebug();
        }
    },

    fixAll : function( container ) {
        // продължава само ако е IE6
        if (!window.ie6) {
            return;
        }

        var selectorPrefix = '';
        if (container) {
            selectorPrefix = '#' + container + ' ';
        }
        $$( selectorPrefix + '.' + this.options.imgFixClass ).each(function(pngImage, index){
            this.pngFixImage(pngImage);
        }, this);
        $$( selectorPrefix + '.' + this.options.bgFixClass ).each(function(pngBgImage, index){
            this.pngFixBgImage(pngBgImage);
        }, this);
        $$( selectorPrefix + '.' + this.options.inputFixClass ).each(function(pngInputImage, index){
            this.pngFixImage(pngInputImage);
        }, this);
    },

    fixContainer : function( container ) {
        if ( $( container ) ) {
            this.fixAll( container );
        }
    },

    pngFixImage : function( imgObj ) {
        imgObj.removeClass(this.options.imgFixClass);
        if (this.isFixed(imgObj)) {
            return;
        }
        oldSrc = imgObj.getProperty('src');
        imgSize = imgObj.getSize();
        imgBorders = imgObj.getStyle('borderWidth');
        imgBorders = imgBorders.replace(/px/g, '');
        imgBorders = imgBorders.split(' ');
        imgBordersStyle = imgObj.getStyle('borderStyle');
        imgBordersStyle = imgBordersStyle.split(' ');
        // проверка, дали е видима рамката и тогава се взима под внимание широчината й
        imgBordersStyle.each(function(imgBorderStyle, index){
            if (imgBorderStyle == 'none') {
                imgBorders[index] = 0;
            } else {
                imgBorders[index] = parseInt(imgBorders[index], 10);
            }
        });
        imgObj.setProperty('width', imgSize.size.x - imgBorders[1] - imgBorders[3]);
        imgObj.setProperty('height', imgSize.size.y  - imgBorders[0] - imgBorders[2]);
        imgObj.setProperty('src', this.getSpacer());
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + oldSrc + "', sizingMethod='scale');";
        if (this.options.debug) {
            var debugMsg = '';
            debugMsg += 'imgFix [' + this.options.imgFixClass + ']' + "\n";
            debugMsg += 'oldSrc = [' + oldSrc + ']' + "\n";
            debugMsg += 'newSrc = [' + imgObj.getProperty('src') + ']' + "\n";
            debugMsg += 'newFilter = [' + imgObj.getStyle('filter') + ']' + "\n\n";
            debugMsg += "=============================\n\n";
            this.debug.push(debugMsg);
        }
        this.attachSrcEvent( imgObj );
    },

    pngFixBgImage : function( obj ) {
        obj.removeClass(this.options.bgFixClass);
        if (this.isFixed(obj)) {
            return;
        }
        oldBg = obj.getStyle('backgroundImage');
        oldBg = oldBg.replace(/url\(/, '');
        oldBg = oldBg.replace(/\"/g, '');
        oldBg = oldBg.replace(/\)/g, '');
        obj.setStyle('background', 'none');
        obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + oldBg + "', sizingMethod='scale');";
        if (this.options.debug) {
            var debugMsg = '';
            debugMsg += 'bgFix [' + this.options.bgFixClass + ']' + "\n";
            debugMsg += 'oldBg = [' + oldBg + ']' + "\n";
            debugMsg += 'newBg = [' + obj.getStyle('background') + ']' + "\n";
            debugMsg += 'newFilter = [' + obj.getStyle('filter') + ']' + "\n\n";
            debugMsg += "=============================\n\n";
            this.debug.push(debugMsg);
        }
    },

    attachSrcEvent : function ( imgObj ) {
        imgObj.onpropertychange = function(){
            if (event.propertyName.toLowerCase() == 'src') {
                imgObj.style.filter = '';
                imgObj.onpropertychange = null;
                this.pngFixImage( imgObj );
                this.attachSrcEvent( imgObj );
            }
        }.bind(this);
    },

    isFixed : function( obj ) {
        if (obj.style.filter != '') {
            return true;
        } else {
            return false;
        }
    },

    getSpacer : function( ) {
        return this.options.spacerSrc + this.options.spacerFile;
    },
    
    showDebug : function( ) {
        var debugTxt = this.debug.join('');
        if ($(this.options.debugConainer)) {
            $(this.options.debugConainer).setStyle('display', 'block');
        } else {
            var debugElement = new Element('textarea', {
                'rows' : 40,
                'cols' : 100,
                'id' : this.options.debugConainer,
                'styles' : {
                    'position' : 'absolute',
                    'top' : 0,
                    'left' : 0
                },
                'events' : {
                    'blur' : function(){
                        $(this.options.debugConainer).setStyle('display', 'none');
                    }.bind(this)
                }
            });
            debugElement.injectInside($E('body'));
        }
        $(this.options.debugConainer).setProperty('value', debugTxt);
    }
});
mooPngFix.implement(new Options, new Events);

