﻿(function ($) {
    var methods = {
        init: function (options) {
            var $this = this;
            //default option values
            this.options = {
                swf: "/website-player-270.swf",
                swfBgColor: "ffffff"
            };
            if (typeof options == "object") { merge(this.options, options); }

            var htmlAudio5Test = document.createElement('audio');
            if (htmlAudio5Test.canPlayType && htmlAudio5Test.canPlayType("audio/mpeg")) {//we can play the mp3 file via html5
                $(this).find('.html5Player').show();
                this.audio = $(this).find('audio').get(0);
                this.duration = $(this).find('.duration');
                this.currentTime = $(this).find('.currentTime');
                this.playToggle = $(this).find('.playToggle');
                this.buffer = $(this).find('.ipadioPlayerBuffer');
                this.gutter = $(this).find('.ipadioPlayerGutter');
                this.scrubber = $(this).find('.ipadioPlayerScrubber');
                this.manualSeek = false;
                this.loaded = false;
                if ((this.audio.buffered != undefined) && (this.audio.buffered.length != 0)) {
                    $(this.audio).bind('progress', function () {
                        $this.loaded = parseInt(((this.buffered.end(0) / this.duration) * 100), 10);
                        $this.buffer.css({ width: $this.loaded + '%' });
                    });
                }
                else {
                    this.buffer.remove();
                }

                $($this.audio).bind('timeupdate', function () {
                    if (this.duration != null && !isNaN(this.duration)) {
                        $this.duration.html(setTime(this.duration));
                    }
                    $this.currentTime.html(setTime(this.currentTime));
                    // var pos = (audio.currentTime / audio.duration) * gutter.width;
                    if (!$this.manualSeek) { $this.gutter.slider("value", this.currentTime) }
                    if (!$this.loaded) {
                        $this.loaded = true;

                        $this.gutter.slider({
                            value: 0,
                            step: 0.01,
                            orientation: "horizontal",
                            range: "min",
                            max: this.duration,
                            animate: true,
                            slide: function () {
                                $this.manualSeek = true;
                            },
                            stop: function (e, ui) {
                                $this.audio.currentTime = ui.value;
                                $this.manualSeek = false;
                            }
                        });
                    }
                });

                $($this.audio).bind('play', function () {
                    $this.playToggle.addClass('playing');
                }).bind('pause', function () {
                    $this.playToggle.removeClass('playing');
                }).bind('ended', function () {
                    $this.playToggle.removeClass('playing');
                    $this.audio.pause();
                    $this.audio.currentTime = 0;
                });


                $this.playToggle.click(function () {
                    if ($this.audio.paused) { $this.audio.play(); }
                    else { $this.audio.pause(); }
                });

                if ($(this).attr("data-autoplay") == "true") {
                    $this.audio.play();
                }

            } else {//need to use the flashplayer instead
                flashembed($(this), this.options.swf + "?nocache=20111209114036"+ ($(this).attr("data-autoplay") == "true" ? "&autoplay=1":"") +"&backgroundColour=" + this.options.swfBgColor + "&phlogId=" + $(this).attr("data-channelid") + "&wmode=transparent&phonecastId=" + $(this).attr("data-broadcastid"), "");
            }
        }
    };

    /**
    * @license 
    * jQuery Tools 3.2.6 / Flashembed - New wave Flash embedding
    * 
    * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
    * 
    * http://flowplayer.org/tools/toolbox/flashembed.html
    *
    * Since : March 2008
    * Date  : @DATE 
    */
    (function () {

        var IE = document.all,
		 URL = 'http://www.adobe.com/go/getflashplayer',
		 JQUERY = typeof jQuery == 'function',
		 RE = /(\d+)[^\d]+(\d+)[^\d]*(\d*)/,
		 GLOBAL_OPTS = {
		     // very common opts
		     width: '100%',
		     height: '100%',
		     id: "_" + ("" + Math.random()).slice(9),

		     // flashembed defaults
		     allowfullscreen: true,
		     allowscriptaccess: 'always',
		     quality: 'high',

		     // flashembed specific options
		     version: [3, 0],
		     onFail: null,
		     expressInstall: null,
		     w3c: false,
		     cachebusting: false
		 };

        // version 9 bugfix: (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
        if (window.attachEvent) {
            window.attachEvent("onbeforeunload", function () {
                __flash_unloadHandler = function () { };
                __flash_savedUnloadHandler = function () { };
            });
        }

        // simple extend
        function extend(to, from) {
            if (from) {
                for (var key in from) {
                    if (from.hasOwnProperty(key)) {
                        to[key] = from[key];
                    }
                }
            }
            return to;
        }

        // used by asString method	
        function map(arr, func) {
            var newArr = [];
            for (var i in arr) {
                if (arr.hasOwnProperty(i)) {
                    newArr[i] = func(arr[i]);
                }
            }
            return newArr;
        }

        window.flashembed = function (root, opts, conf) {

            // root must be found / loaded	
            if (typeof root == 'string') {
                root = document.getElementById(root.replace("#", ""));
            }

            // not found
            if (!root) { return; }

            if (typeof opts == 'string') {
                opts = { src: opts };
            }

            return new Flash(root, extend(extend({}, GLOBAL_OPTS), opts), conf);
        };

        // flashembed "static" API
        var f = extend(window.flashembed, {

            conf: GLOBAL_OPTS,

            getVersion: function () {
                var fo, ver;

                try {
                    ver = navigator.plugins["Shockwave Flash"].description.slice(16);
                } catch (e) {

                    try {
                        fo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
                        ver = fo && fo.GetVariable("$version");

                    } catch (err) {
                        try {
                            fo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                            ver = fo && fo.GetVariable("$version");
                        } catch (err2) { }
                    }
                }

                ver = RE.exec(ver);
                return ver ? [ver[1], ver[3]] : [0, 0];
            },

            asString: function (obj) {

                if (obj === null || obj === undefined) { return null; }
                var type = typeof obj;
                if (type == 'object' && obj.push) { type = 'array'; }

                switch (type) {

                    case 'string':
                        obj = obj.replace(new RegExp('(["\\\\])', 'g'), '\\$1');

                        // flash does not handle %- characters well. transforms "50%" to "50pct" (a dirty hack, I admit)
                        obj = obj.replace(/^\s?(\d+\.?\d+)%/, "$1pct");
                        return '"' + obj + '"';

                    case 'array':
                        return '[' + map(obj, function (el) {
                            return f.asString(el);
                        }).join(',') + ']';

                    case 'function':
                        return '"function()"';

                    case 'object':
                        var str = [];
                        for (var prop in obj) {
                            if (obj.hasOwnProperty(prop)) {
                                str.push('"' + prop + '":' + f.asString(obj[prop]));
                            }
                        }
                        return '{' + str.join(',') + '}';
                }

                // replace ' --> "  and remove spaces
                return String(obj).replace(/\s/g, " ").replace(/\'/g, "\"");
            },

            getHTML: function (opts, conf) {

                opts = extend({}, opts);

                /******* OBJECT tag and it's attributes *******/
                var html = '<object width="' + opts.width +
				'" height="' + opts.height +
				'" id="' + opts.id +
				'" name="' + opts.id + '"';

                if (opts.cachebusting) {
                    opts.src += ((opts.src.indexOf("?") != -1 ? "&" : "?") + Math.random());
                }

                if (opts.w3c || !IE) {
                    html += ' data="' + opts.src + '" type="application/x-shockwave-flash"';
                } else {
                    html += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
                }

                html += '>';

                /******* nested PARAM tags *******/
                if (opts.w3c || IE) {
                    html += '<param name="movie" value="' + opts.src + '" />';
                }

                // not allowed params
                opts.width = opts.height = opts.id = opts.w3c = opts.src = null;
                opts.onFail = opts.version = opts.expressInstall = null;

                for (var key in opts) {
                    if (opts[key]) {
                        html += '<param name="' + key + '" value="' + opts[key] + '" />';
                    }
                }

                /******* FLASHVARS *******/
                var vars = "";

                if (conf) {
                    for (var k in conf) {
                        if (conf[k]) {
                            var val = conf[k];
                            vars += k + '=' + (/function|object/.test(typeof val) ? f.asString(val) : val) + '&';
                        }
                    }
                    vars = vars.slice(0, -1);

                    html += '<param name="flashvars" value=\'' + vars.replace(/'/gi, "&#39;") + '\' />';
                }

                html += "</object>";

                return html;
            },

            isSupported: function (ver) {
                return VERSION[0] > ver[0] || VERSION[0] == ver[0] && VERSION[1] >= ver[1];
            }

        });

        var VERSION = f.getVersion();

        function Flash(root, opts, conf) {
            // version is ok
            if (f.isSupported(opts.version)) {
                root.html(f.getHTML(opts, conf));
            } else {
            }

            // http://flowplayer.org/forum/8/18186#post-18593
            if (IE) {
                window[opts.id] = document.getElementById(opts.id);
            }

            // API methods for callback
            extend(this, {

                getRoot: function () {
                    return root;
                },

                getOptions: function () {
                    return opts;
                },


                getConf: function () {
                    return conf;
                },

                getApi: function () {
                    return root.firstChild;
                }

            });
        }
    })();

    $.fn.ipadioPlayer = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ipadioPlayer');
        }
    };
})(jQuery);

// Combine Objects - Use "safe" to protect from overwriting existing items
function merge  (obj1, obj2, safe) {
    for (var attrname in obj2) {
        if (obj2.hasOwnProperty(attrname) && (!safe || !obj1.hasOwnProperty(attrname))) { obj1[attrname] = obj2[attrname]; }
    }
    return obj1;
};

function setTime(seconds){
	mins = Math.floor(seconds / 60, 10), 2;
	secs = Math.floor(seconds - mins * 60);
	return mins + ':' + (secs > 9 ? secs : '0' + secs);
}
