/*Copyright 2008, RadioTime Inc www.radiotime.com */
function RTBadge() {
    this._baseUrl = "http://content.radiotime.com/";
    this._requestTimeout = 10;
    this.scanSpeed = 2;
    this._band = "FM";
    this._freq = 93.45;
    this._station_index = 0;
    this._dial = this.$("dial");
    this._dial_pos = 0;
    this._target_pos = 0;
    this._dial_speed = 0;
    this.isScanning = false;
    this._scan_index = 0;
    this._dial_last_pos = 0;
    this.isTuning = false;
    this.isTuned = false;
    this._stations = null;
    this._genres_visible = false;
    var B = this;
    var A = function() {
        B.onTimer()
    };
    this._dial.onmousedown = function(C) {
        if (!C) {
            var C = window.event;
            C.cancelBubble = true;
            C.returnValue = false
        } else {
            C.preventDefault();
            C.stopPropagation()
        }
        B.tuneStart(C)
    };
    this._timer = setInterval(A, 40);
    if (this.cookie.read("zip") && this.cookie.read("zip") != "undefined") {
        this.setLocation(this.cookie.read("zip"))
    } else {
        this.sendRequest("autodetect=true", 1)
    }
}
RTBadge.prototype.dim = {
    FM: {
        def_freq: 93.45,
        ppu: 23.2,
        min_freq: 87,
        max_freq: 109,
        scale_size: 510
    },
    AM: {
        def_freq: 775,
        ppu: 0.465,
        min_freq: 450,
        max_freq: 1750,
        scale_size: 605
    }
};
RTBadge.prototype.setLocation = function(A) {
    this._zip = A;
    this.$("caption").innerHTML = "Loading...";
    this.sendRequest("PostalCode=" + A, 1);
    this.$("about_link").href = "http://radiotime.com/Search.aspx?query=" + A
};
RTBadge.prototype.sendRequest = function(D, A, C) {
    if (C == undefined) {
        this._requestCompleted = false
    }
    if (this.$("rt_api_loader")) {
        this.$("rt_api_loader").parentNode.removeChild(this.$("rt_api_loader"))
    }
    var B = document.createElement("script");
    B.id = "rt_api_loader";
    B.src = this._baseUrl + "json/LocalRadioJson.aspx?" + D + "&callback=badge.init&z=" + Math.floor(Math.random() * 1000000);
    document.body.appendChild(B);
    if (A != undefined && A > 0) {
        A--;
        var E = this;
        setTimeout(function() {
            if (!E._requestCompleted) {
                E.sendRequest(D, A, true)
            }
        },
        this._requestTimeout * 1000)
    }
};
RTBadge.prototype.zipControl = {
    show: function() {
        badge.$("zipLink").style.display = "none";
        badge.$("zipInput").style.display = "inline";
        badge.$("caption").style.display = "none"
    },
    update: function() {
        badge.$("zipLink").style.display = "inline";
        badge.$("zipInput").style.display = "none";
        badge.$("caption").style.display = "block";
        badge.setLocation(badge.$("zipInput").value);
        badge.$("zipInput").value = "ZIP...";
        badge.reset()
    },
    filter: function(B) {
        var D;
        var C;
        var A;
        if (window.event) {
            D = B.keyCode
        } else {
            if (B.which) {
                D = B.which
            }
        }
        if (D > 13) {
            C = String.fromCharCode(D);
            return /\d/.test(C)
        } else {
            if (13 == D) {
                this.update()
            }
            return true
        }
    }
};
RTBadge.prototype.init = function(D) {
    this._requestCompleted = true;
    if ("" == D.Name) {
        this.setLocation(75220);
        return
    }
    this._city = D.Name;
    this._state = D.StateCode;
    this._country = D.CountryCode;
    this._stations = ["AM", "FM"];
    this._stations.AM = [];
    this._stations.FM = [];
    this._genre = "All";
    this._genres = [];
    this._genres_map = {
        All: {
            AM: 0,
            FM: 0,
            Stations: []
        }
    };
    this._data = D.Results;
    for (var A in D.Results) {
        D.Results[A].stationIndex = A;
        var C = D.Results[A];
        if (this._stations[C.Band][C.Frequency] == undefined) {
            this._stations[C.Band][C.Frequency] = []
        }
        var B = 0;
        while (this._stations[C.Band][C.Frequency][B] != undefined) {
            B++
        }
        this._stations[C.Band][C.Frequency][B] = C;
        if (!this.inArray(this._genres, C.Genre)) {
            this._genres.push(C.Genre)
        }
        if (this._genres_map[C.Genre] == undefined) {
            this._genres_map[C.Genre] = {
                AM: 0,
                FM: 0,
                Stations: []
            }
        }
        this._genres_map[C.Genre].Stations.push(A);
        this._genres_map[C.Genre][C.Band]++;
        this._genres_map.All.Stations.push(A);
        this._genres_map.All[C.Band]++
    }
    this._genres.sort();
    this._genres.unshift("All");
    this.$("caption").innerHTML = this._city + ", " + (this._state ? this._state: this._country);
    if (this.cookie.read("freq")) {
        this.switchBand(this.cookie.read("band"));
        this.moveDial(this.freq2pos(this.cookie.read("freq")))
    } else {
        this.startScan()
    }
};
RTBadge.prototype.startScan = function() {
    this.isScanning = true;
    this._scan_index = 0;
    var A = this._data[this._genres_map[this._genre].Stations[this._scan_index]];
    this.tuneByStation(A)
};
RTBadge.prototype.stopScan = function() {
    this._dial_speed = 0;
    this.isScanning = false
};
RTBadge.prototype.saveSettings = function() {
    this.cookie.save("band", this._band, 365);
    this.cookie.save("freq", this._freq, 365);
    if (this._zip != undefined) {
        this.cookie.save("zip", this._zip, 365)
    }
};
RTBadge.prototype.switchBand = function(A) {
    if (A != this._band) {
        this._band = A;
        this.isTuned = false;
        if ("AM" == A) {
            this.$("am_tab").className = "active";
            this.$("fm_tab").className = "";
            this.$("dial").style.backgroundImage = "url(../images/tuner/am_scale.jpg)"
        } else {
            this.$("am_tab").className = "";
            this.$("fm_tab").className = "active";
            this.$("dial").style.backgroundImage = "url(../images/tuner/fm_scale.jpg)"
        }
    }
};
RTBadge.prototype.populateGenres = function() {
    if (!this._genres_visible) {
        var C = this;
        setTimeout(function() {
            document.onclick = function() {
                C.populateGenres();
                return false
            }
        },
        100);
        this.$("genre_panel").className = "expanded";
        for (var A in this._genres) {
            var B = document.createElement("div");
            B.innerHTML = '<a href="#" onclick="badge.applyGenreFilter(\'' + this._genres[A] + "');return false;\"><div>" + this._genres[A] + "</div></a>";
            this.$("genre_panel").appendChild(B)
        }
        this._genres_visible = true
    } else {
        this.applyGenreFilter(this._genre)
    }
};
RTBadge.prototype.applyGenreFilter = function(A) {
    document.onclick = null;
    this._genre = A;
    this.$("genre-title").innerHTML = A.toUpperCase();
    this.$("genre_panel").className = "";
    this.$("genre_panel").innerHTML = '<a href="#" onclick="badge.populateGenres();return false;"><div>' + A + "</div></a>";
    this._genres_visible = false;
    this.tuneByStation(this._data[this._genres_map[A].Stations[0]]);
    this.stopScan();
    if (this._genres_map[A].Stations.length > 1) {
        var B = this;
        setTimeout(function() {
            B.startScan()
        },
        2000)
    }
};
RTBadge.prototype.tuneByStation = function(C) {
    if (C == undefined) {
        if (this.isScanning) {
            return
        }
        C = this._stations[this._band][this._freq][this._station_index]
    }
    this.switchBand(C.Band);
    this.moveDial(this.freq2pos(C.Frequency), true);
    this.$("logo").src = C.LogoUrl.replace(".gif", ".png");
    if (C.Name.length > 15) {
        this.$("name").style.fontSize = Math.round(15 / C.Name.length * 10) / 10 + "em"
    } else {
        this.$("name").style.fontSize = "0.7em"
    }
    this.$("name").innerHTML = C.Name;
    this.$("name").title = C.Slogan;
    this.$("onnow").innerHTML = C.OnNow;
    this.$("play_btn").title = "Listen to " + C.Name;
    this.$("logo").title = C.Name + " info";
    this.$("logo-link").href = C.Url;
    this._station = C;
    this._TuneCountDown = 60;
    this.isTuned = true;
    this.$("play_btn").src = "images/tuner/active_play.jpg";
    this.saveSettings();
    if (this.isScanning) {
        var E = this;
        var B = null;
        if (this._genres_map[this._genre].Stations[this._scan_index + 1]) {
            this._scan_index++
        } else {
            this._scan_index = 0
        }
        B = this._data[this._genres_map[this._genre].Stations[this._scan_index]];
        var A = this.getScanSpeed(B);
        var D = B.Band;
        this._dial_speed = 0;
        setTimeout(function() {
            if (E.isScanning) {
                E.switchBand(D);
                E._dial_speed = A;
                setTimeout(function() {
                    E.tuneByStation(B)
                },
                2000)
            }
        },
        2000)
    }
};
RTBadge.prototype.getScanSpeed = function(A) {
    this._target_pos = this.freq2pos(A.Frequency, A.Band);
    var C = this._target_pos - this._dial_pos;
    if (C > this.dim[this._band].scale_size) {
        C -= this.dim[this._band].scale_size
    }
    if (C < -this.dim[this._band].scale_size) {
        C += this.dim[this._band].scale_size
    }
    var B = C / 50;
    return B;
    if (B > 0) {
        return Math.max(this.scanSpeed, B)
    } else {
        return Math.min( - this.scanSpeed, B)
    }
};
RTBadge.prototype.reset = function() {
    this.isTuned = false;
    this.$("logo").src = "images/tuner/1.gif";
    this.$("name").innerHTML = "";
    this.$("name").title = "";
    this.$("onnow").innerHTML = "";
    this.$("play_btn").title = "Use dial to tune";
    this.$("play_btn").src = "images/tuner/play.jpg";
    this._station_index = 0;
    this.cookie.clear("freq")
};
RTBadge.prototype.isStation = function(A) {
    if (A == undefined) {
        A = this._station_index
    }
    if (this._stations[this._band][this._freq] && this._stations[this._band][this._freq][A] != undefined) {
        if (this._genre == "All" || this._genre == this._stations[this._band][this._freq][A].Genre) {
            return true
        }
    }
    return false
};
RTBadge.prototype.seek = function(A) {
    this.isScanning = false;
    if (this.isStation()) {
        if (this.isStation(this._station_index + 1)) {
            this._station_index++;
            this.tuneByStation();
            return
        }
    }
    this._station_index = 0;
    this._dial_speed = A * this.scanSpeed
};
RTBadge.prototype.tuneStart = function(A) {
    this.isTuning = true;
    this.isScanning = false;
    this.initialData = {
        mouse: A.clientX,
        dialPos: this._dial_pos
    };
    this._oldMouseUp = document.onmouseup;
    this._oldMouseMove = document.onmousemove;
    var B = this;
    document.onmouseup = function() {
        B.tuneEnd()
    };
    document.onmousemove = function(C) {
        if (!C) {
            var C = window.event;
            C.cancelBubble = true;
            C.returnValue = false
        } else {
            C.preventDefault();
            C.stopPropagation()
        }
        B.tuneProgress(C)
    };
    return true
};
RTBadge.prototype.tuneProgress = function(B) {
    if (!this.isTuning) {
        return
    }
    var A = B.clientX - this.initialData.mouse;
    this.moveDial(this.initialData.dialPos + A);
    return true
};
RTBadge.prototype.tuneEnd = function() {
    this.isTuning = false;
    document.onmousemove = this._oldMouseMove;
    document.onmouseup = this._oldMouseUp;
    return true
};
RTBadge.prototype.freq2pos = function(A, B) {
    B = (B == undefined ? this._band: B);
    return (this.dim[B].def_freq - A) * this.dim[B].ppu
};
RTBadge.prototype.pos2freq = function(B) {
    var A = this.dim[this._band].def_freq - B / this.dim[this._band].ppu;
    if (A < this.dim[this._band].min_freq) {
        A = this.dim[this._band].max_freq + (A - this.dim[this._band].min_freq)
    }
    if (A > this.dim[this._band].max_freq) {
        A = this.dim[this._band].min_freq + (A - this.dim[this._band].max_freq)
    }
    if ("FM" == this._band) {
        return (Math.round(10 * A) / 10).toFixed(1)
    } else {
        return Math.round(A / 10) * 10
    }
};
RTBadge.prototype.moveDial = function(C, A) {
    if (C >= this.dim[this._band].scale_size) {
        C -= this.dim[this._band].scale_size
    }
    if (C <= 0) {
        C += this.dim[this._band].scale_size
    }
    this._dial_pos = C;
    this._dial.style.backgroundPosition = this._dial_pos + "px 0px";
    if (A == undefined) {
        var B = this.pos2freq(C);
        if (Math.abs(this._freq - B) > 0.09) {
            this.$("freq").innerHTML = B;
            this._freq = B;
            if (this.isStation()) {
                this.tuneByStation();
                if ((!this.isTuning && Math.abs(this._dial_speed) < this.scanSpeed + 0.01) || this.isScanning) {
                    this._dial_speed = 0
                }
            } else {
                this.reset()
            }
        }
    }
};
RTBadge.prototype.onTimer = function() {
    if (this.isTuning) {
        this._dial_speed = this._dial_pos - this._dial_last_pos;
        this._dial_last_pos = this._dial_pos
    } else {
        if (Math.abs(this._dial_speed) > 100) {
            this._dial_speed = 100 * this._dial_speed / Math.abs(this._dial_speed)
        }
        if (this.isScanning) {
            this.moveDial(this._dial_pos + this._dial_speed, true)
        } else {
            this.moveDial(this._dial_pos + this._dial_speed);
            if (Math.abs(this._dial_speed) > this.scanSpeed) {
                this._dial_speed *= 0.9
            }
        }
    }
};
RTBadge.prototype.playNow = function(B) {
    if (!this.isTuned) {
        return false
    }
    this.isScanning = false;
    if (B == undefined) {
        B = this._station.TunerUrl
    }
    var D = 490;
    var G = 400;
    var E = (screen.width - D) / 2;
    var C = (screen.height - G) / 4;
    try {
        var A = window.open(B, "Player", "left=" + E + ", top=" + C + ", height=" + G + ", width=" + D + ", scrollbars=no, resizable=yes, toolbar=no, screenX=0, screenY=0, status=no");
        A.resizeTo(D, G);
        A.moveTo(E, C);
        A.focus()
    } catch(F) {}
};
RTBadge.prototype.$ = function(A) {
    return document.getElementById("radiotime-" + A) ? document.getElementById("radiotime-" + A) : document.getElementById(A)
};
RTBadge.prototype.cookie = {
    save: function(C, D, E) {
        if (E) {
            var B = new Date();
            B.setTime(B.getTime() + (E * 24 * 60 * 60 * 1000));
            var A = "; expires=" + B.toGMTString()
        } else {
            var A = ""
        }
        document.cookie = C + "=" + D + A + "; path=/"
    },
    read: function(B) {
        var D = B + "=";
        var A = document.cookie.split(";");
        for (var C = 0; C < A.length; C++) {
            var E = A[C];
            while (E.charAt(0) == " ") {
                E = E.substring(1, E.length)
            }
            if (E.indexOf(D) == 0) {
                return E.substring(D.length, E.length)
            }
        }
        return null
    },
    clear: function(A) {
        this.save(A, "", -1)
    }
};
RTBadge.prototype.inArray = function(A, C) {
    for (var B in A) {
        if (A[B] == C) {
            return true
        }
    }
    return false
};