/*
Utility methods
*/
mejs.Utility = {
    encodeUrl: function (url) {
        return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
    },
    escapeHTML: function (s) {
        return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
    },
    absolutizeUrl: function (url) {
        var el = document.createElement('div');
        el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
        return el.firstChild.href;
    },
    getScriptPath: function (scriptNames) {
        var
            i = 0,
            j,
            codePath = '',
            testname = '',
            slashPos,
            filenamePos,
            scriptUrl,
            scriptPath,
            scriptFilename,
            scripts = document.getElementsByTagName('script'),
            il = scripts.length,
            jl = scriptNames.length;

        // go through all <script> tags
        for (; i < il; i++) {
            scriptUrl = scripts[i].src;
            slashPos = scriptUrl.lastIndexOf('/');
            if (slashPos > -1) {
                scriptFilename = scriptUrl.substring(slashPos + 1);
                scriptPath = scriptUrl.substring(0, slashPos + 1);
            } else {
                scriptFilename = scriptUrl;
                scriptPath = '';
            }

            // see if any <script> tags have a file name that matches the 
            for (j = 0; j < jl; j++) {
                testname = scriptNames[j];
                filenamePos = scriptFilename.indexOf(testname);
                if (filenamePos > -1) {
                    codePath = scriptPath;
                    break;
                }
            }

            // if we found a path, then break and return it
            if (codePath !== '') {
                break;
            }
        }

        // send the best path back
        return codePath;
    },
    /*
     * Calculate the time format to use. We have a default format set in the
     * options but it can be imcomplete. We ajust it according to the media
     * duration.
     *
     * We support format like 'hh:mm:ss:ff'.
     */
    calculateTimeFormat: function (time, options, fps) {
        if (time < 0) {
            time = 0;
        }

        if (typeof fps == 'undefined') {
            fps = 25;
        }

        var format = options.timeFormat,
            firstChar = format[0],
            firstTwoPlaces = (format[1] == format[0]),
            separatorIndex = firstTwoPlaces ? 2 : 1,
            separator = ':',
            hours = Math.floor(time / 3600) % 24,
            minutes = Math.floor(time / 60) % 60,
            seconds = Math.floor(time % 60),
            frames = Math.floor(((time % 1) * fps).toFixed(3)),
            lis = [
                [frames, 'f'],
                [seconds, 's'],
                [minutes, 'm'],
                [hours, 'h']
            ];

        // Try to get the separator from the format
        if (format.length < separatorIndex) {
            separator = format[separatorIndex];
        }

        var required = false;

        for (var i = 0, len = lis.length; i < len; i++) {
            if (format.indexOf(lis[i][1]) !== -1) {
                required = true;
            }
            else if (required) {
                var hasNextValue = false;
                for (var j = i; j < len; j++) {
                    if (lis[j][0] > 0) {
                        hasNextValue = true;
                        break;
                    }
                }

                if (!hasNextValue) {
                    break;
                }

                if (!firstTwoPlaces) {
                    format = firstChar + format;
                }
                format = lis[i][1] + separator + format;
                if (firstTwoPlaces) {
                    format = lis[i][1] + format;
                }
                firstChar = lis[i][1];
            }
        }
        options.currentTimeFormat = format;
    },
    /*
     * Prefix the given number by zero if it is lower than 10.
     */
    twoDigitsString: function (n) {
        if (n < 10) {
            return '0' + n;
        }
        return String(n);
    },
    secondsToTimeCode: function (time, options) {
        if (time < 0) {
            time = 0;
        }

        // Maintain backward compatibility with method signature before v2.18.
        if (typeof options !== 'object') {
            var format = 'm:ss';
            format = arguments[1] ? 'hh:mm:ss' : format; // forceHours
            format = arguments[2] ? format + ':ff' : format; // showFrameCount

            options = {
                currentTimeFormat: format,
                framesPerSecond: arguments[3] || 25
            };
        }

        var fps = options.framesPerSecond;
        if (typeof fps === 'undefined') {
            fps = 25;
        }

        var format = options.currentTimeFormat,
            hours = Math.floor(time / 3600) % 24,
            minutes = Math.floor(time / 60) % 60,
            seconds = Math.floor(time % 60),
            frames = Math.floor(((time % 1) * fps).toFixed(3));
        lis = [
            [frames, 'f'],
            [seconds, 's'],
            [minutes, 'm'],
            [hours, 'h']
        ];

        var res = format;
        for (i = 0, len = lis.length; i < len; i++) {
            res = res.replace(lis[i][1] + lis[i][1], this.twoDigitsString(lis[i][0]));
            res = res.replace(lis[i][1], lis[i][0]);
        }
        return res;
    },

    timeCodeToSeconds: function (hh_mm_ss_ff, forceHours, showFrameCount, fps) {
        if (typeof showFrameCount == 'undefined') {
            showFrameCount = false;
        } else if (typeof fps == 'undefined') {
            fps = 25;
        }

        var tc_array = hh_mm_ss_ff.split(":"),
            tc_hh = parseInt(tc_array[0], 10),
            tc_mm = parseInt(tc_array[1], 10),
            tc_ss = parseInt(tc_array[2], 10),
            tc_ff = 0,
            tc_in_seconds = 0;

        if (showFrameCount) {
            tc_ff = parseInt(tc_array[3]) / fps;
        }

        tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;

        return tc_in_seconds;
    },


    convertSMPTEtoSeconds: function (SMPTE) {
        if (typeof SMPTE != 'string')
            return false;

        SMPTE = SMPTE.replace(',', '.');

        var secs = 0,
            decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
            multiplier = 1;

        SMPTE = SMPTE.split(':').reverse();

        for (var i = 0; i < SMPTE.length; i++) {
            multiplier = 1;
            if (i > 0) {
                multiplier = Math.pow(60, i);
            }
            secs += Number(SMPTE[i]) * multiplier;
        }
        return Number(secs.toFixed(decimalLen));
    },

    /* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
    removeSwf: function (id) {
        var obj = document.getElementById(id);
        if (obj && /object|embed/i.test(obj.nodeName)) {
            if (mejs.MediaFeatures.isIE) {
                obj.style.display = "none";
                (function () {
                    if (obj.readyState == 4) {
                        mejs.Utility.removeObjectInIE(id);
                    } else {
                        setTimeout(arguments.callee, 10);
                    }
                })();
            } else {
                obj.parentNode.removeChild(obj);
            }
        }
    },
    removeObjectInIE: function (id) {
        var obj = document.getElementById(id);
        if (obj) {
            for (var i in obj) {
                if (typeof obj[i] == "function") {
                    obj[i] = null;
                }
            }
            obj.parentNode.removeChild(obj);
        }
    },
    determineScheme: function (url) {
        if (url && url.indexOf("://") != -1) {
            return url.substr(0, url.indexOf("://") + 3);
        }
        return "//"; // let user agent figure this out
    }
};
