flex.js 12.9 KB
Newer Older
John Punzalan's avatar
John Punzalan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     js
 * @copyright   Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/**
 * Flex maintance object
 *
 *
 */
Flex = {};
Flex.currentID = 0;
Flex.uniqId = function() {
    return 'flexMovieUID'+( ++Flex.currentID );
};

/**
 * Check flash player version for required version
 *
 * @param Number major
 * @param Number minor
 * @param Number revision
 * @return Boolean
 */
Flex.checkFlashPlayerVersion = function(major, minor, revision) {
    var version = Flex.getFlashPlayerVersion();

    if (version === false) {
        return false;
    }

    var requestedVersion = Flex.transformVersionToFloat([major, minor, revision], 5);
    var currentVersion = Flex.transformVersionToFloat(version, 5);

    return requestedVersion <= currentVersion;
};

/**
 * Get flash player version in internet explorer
 * by creating of test ActiveXObjects
 *
 * @return String|Boolean
 */
Flex._getFlashPlayerVersionAsActiveX = function () {
    var versions = [
        {'default': '7.0.0', 'code':'ShockwaveFlash.ShockwaveFlash.7', 'variable':true},
        {'default': '6.0.0', 'code':'ShockwaveFlash.ShockwaveFlash.6', 'variable':true, 'acceess':true},
        {'default': '3.0.0', 'code':'ShockwaveFlash.ShockwaveFlash.3', 'variable':false},
        {'default': '2.0.0', 'code':'ShockwaveFlash.ShockwaveFlash', 'variable':false},
    ];

    var detector = function (options) {
        var activeXObject = new ActiveXObject(options.code);
        if (options.access && options.variable) {
            activeXObject.AllowScriptAccess = 'always';
        }

        if (options.variable) {
            return activeXObject.GetVariable('$version');
        }

        return options['default'];
    }

    var version = false;

    for (var i = 0, l = versions.length; i < l; i++) {
        try {
            version = detector(versions[i]);
            return version;
        } catch (e) {}
    }

    return false;
};

/**
 * Transforms version string like 1.0.0 to array [1,0,0]
 *
 * @param String|Array version
 * @return Array|Boolean
 */
Flex.transformVersionToArray = function (version) {
    if (!Object.isString(version)) {
        return false;
    }

    var versions = version.match(/[\d]+/g);

    if (versions.length > 3) {
        return versions.slice(0,3);
    } else if (versions.length) {
        return versions;
    }



    return false;
};

/**
 * Transforms version string like 1.1.1 to float 1.00010001
 *
 * @param String|Array version
 * @param Number range - percition range between version digits
 * @return Array
 */
Flex.transformVersionToFloat = function (version, range) {
    if (Object.isString(version)) {
        version = Flex.transformVersionToArray(version)
    }

    if (Object.isArray(version)) {
        var result = 0;
        for (var i =0, l=version.length; i < l; i++) {
            result += parseFloat(version[i]) / Math.pow(10, range*i);
        }

        return result;
    }

    return false;
};

/**
 * Return flash player version as array of 0=major, 1=minor, 2=revision
 *
 * @return Array|Boolean
 */
Flex.getFlashPlayerVersion = function () {
    if (Flex.flashPlayerVersion) {
        return Flex.flashPlayerVersion;
    }

    var version = false;
    if (navigator.plugins != null && navigator.plugins.length > 0) {
       if (navigator.mimeTypes && navigator.mimeTypes.length > 0) {
          if (navigator.mimeTypes['application/x-shockwave-flash'] &&
              !navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
             return false;
          }
       }
       var flashPlugin = navigator.plugins['Shockwave Flash'] || navigator.plugins['Shockwave Flash 2.0'];
       version = Flex.transformVersionToArray(flashPlugin.description);
    } else {
       version = Flex.transformVersionToArray(Flex._getFlashPlayerVersionAsActiveX());
    }

    Flex.flashPlayerVersion = version;
    return version;
};

Flex.Object = Class.create({
    /**
     * Initialize object from configuration, where configuration keys,
     * is set of tag attributes for object or embed
     *
     * @example
     * new Flex.Object({'src':'path/to/flashmovie.swf'});
     *
     * @param Object config
     * @return void
     */
    initialize: function (config) {
        this.isIE  = Prototype.Browser.IE;
        this.isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
        this.attributes = {
             quality:"high",
             pluginspage: "http://www.adobe.com/go/getflashplayer",
             type: "application/x-shockwave-flash",
             allowScriptAccess: "always",
             classid: "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
        };
        this.bridgeName = '';
        this.bridge = false;
        this.setAttributes( config );
        this.applied = false;

        var myTemplatesPattern = /(^|.|\r|\n)(\{(.*?)\})/;
        if(this.detectFlashVersion(9, 0, 28)) {
            if(this.isIE) {
                this.template = new Template( '<object {objectAttributes}><param name="allowFullScreen" value="true"/>{objectParameters}</object>', myTemplatesPattern )
            } else {
                this.template = new Template( '<embed {embedAttributes} allowfullscreen="true" />', myTemplatesPattern );
            }
        } else {
            this.template = new Template(  'This content requires the Adobe Flash Player. '
                                               +' <a href=http://www.adobe.com/go/getflash/>Get Flash</a>', myTemplatesPattern );
        }

        this.parametersTemplate = new Template( '<param name="{name}" value="{value}" />', myTemplatesPattern );
        this.attributesTemplate = new Template( ' {name}="{value}" ', myTemplatesPattern );
    },
    /**
     * Set object attribute for generation of html tags
     *
     * @param Sting name
     * @param Object value
     * @return void
     */
    setAttribute : function( name, value ) {
        if(!this.applied) {
            this.attributes[name] = value;
        }
    },
    /**
     * Retrive object attribute value used for generation in html tags
     *
     * @param Sting name
     * @return Object
     */
    getAttribute : function( name ) {
        return this.attributes[name];
    },
    /**
     * Set object attributes in one call
     *
     * @param Object attributesList
     * @return void
     */
    setAttributes : function( attributesList ) {
        $H(attributesList).each(function(pair){
            this.setAttribute(pair.key, pair.value);
        }.bind(this));
    },
    /**
     * Retrieve all object attributes
     *
     * @return Object
     */
    getAttributes : function( ) {
        return this.attributes;
    },
    /**
     * Applies generated HTML content to specified HTML tag
     *
     * @param String|DOMELement container
     * @return void
     */
    apply : function(container) {
        if (!this.applied)    {
            this.setAttribute("id", Flex.uniqId());
            this.preInitBridge();
            var readyHTML = this.template.evaluate(this.generateTemplateValues());
            $(container).update(readyHTML);
        }
        this.applied = true;
    },
    /**
     * Applies generated HTML content to window.document
     *
     * @return void
     */
    applyWrite : function( ) {
        if (!this.applied)    {
            this.setAttribute( "id", Flex.uniqId());
            this.preInitBridge();
            var readyHTML = this.template.evaluate( this.generateTemplateValues() );
            document.write( readyHTML );
        }
        this.applied = true;
    },
    /**
     * Preinitialize FABridge values
     *
     * @return void
     */
    preInitBridge: function () {
        this.bridgeName = this.getAttribute('id') + 'bridge';
        var flashVars = this.getAttribute('flashVars') || this.getAttribute('flashvars') || '';
        if (flashVars != '') {
            flashVars += '&';
        }
        flashVars += 'bridgeName=' + this.bridgeName;
        this.setAttribute('flashVars', flashVars);
        var scopeObj = this;
        FABridge.addInitializationCallback(
             this.bridgeName,
             function () {
                 scopeObj.bridge = this.root();
                 scopeObj.initBridge();
             }
        );
    },
    /**
     * Initialize bridge callback passed to FABridge,
     * calls internal callback if it's presented
     *
     * @return void
     */
    initBridge: function() {
        if(this.onBridgeInit) {
            this.onBridgeInit(this.getBridge());
        }
    },
    /**
     * Retrieve FABridge instance for this object
     *
     * @return Object
     */
    getBridge : function() {
        return this.bridge;
    },
    /**
     * Generate temaplate values object for creation of flash player plugin movie HTML
     *
     * @return Object
     */
    generateTemplateValues : function() {
        var attributesMap = {
            embed: {
                'movie':'src',
                'id':'name',
                'flashvars': 'flashVars',
                'classid':false,
                'codebase':false
            },
            object: {
                'pluginspage':false,
                'src':'movie',
                'flashvars': 'flashVars',
                'type':false,
                'inline': [
                    'type', 'classid', 'codebase', 'id', 'width', 'height',
                    'align', 'vspace', 'hspace', 'class', 'title', 'accesskey', 'name',
                    'tabindex'
                ]
            }
        };
        var embedAttributes = {};
        var objectAttributes = {};
        var parameters = {};
        $H(this.attributes).each(function(pair) {
            var attributeName = pair.key.toLowerCase();
            this.attributes[pair.key] = this.escapeAttributes(pair.value);

            // Retrieve mapped attribute names
            var attributeNameInObject = (attributesMap.object[attributeName] ? attributesMap.object[attributeName] : attributeName);
            var attributeNameInEmbed = (attributesMap.embed[attributeName] ? attributesMap.embed[attributeName] : attributeName);

            if (attributesMap.object[attributeName] !== false) {
                if (attributesMap.object.inline.indexOf(attributeNameInObject) !== -1) { // If it included in default object attribute
                    objectAttributes[attributeNameInObject] = this.attributes[pair.key];
                } else { // otherwise add it to parameters tag list
                    parameters[attributeNameInObject] = this.attributes[pair.key];
                }
            }

            if (attributesMap.embed[attributeName] !== false) { // If this attribute not ignored for flash in Gecko Browsers
                embedAttributes[attributeNameInEmbed] = this.attributes[pair.key];
            }
        }.bind(this));

        var result = {
            objectAttributes: '',
            objectParameters: '',
            embedAttributes : ''
        };


        $H(objectAttributes).each(function(pair){
             result.objectAttributes += this.attributesTemplate.evaluate({
                 name:pair.key,
                 value:pair.value
             });
        }.bind(this));

        $H(embedAttributes).each(function(pair){
             result.embedAttributes += this.attributesTemplate.evaluate({
                 name:pair.key,
                 value:pair.value
             });
        }.bind(this));

        $H(parameters).each(function(pair){
             result.objectParameters += this.parametersTemplate.evaluate({
                 name:pair.key,
                 value:pair.value
             });
        }.bind(this));

        return result;
    },
    /**
     * Escapes attributes for generation of valid HTML
     *
     * @return String
     */
    escapeAttributes: function (value) {
        if(typeof value == 'string') {
            return value.escapeHTML();
        } else {
            return value;
        }
    },
    /**
     * Detects needed flash player version
     *
     * @param Number major
     * @param Number minor
     * @param Number revision
     * @return Boolean
     */
    detectFlashVersion: function (major, minor, revision) {
        return Flex.checkFlashPlayerVersion(major, minor, revision);
    }
});