﻿///<reference path="../../scripts/jquery.js"/>
///<reference path="../../scripts/jsr.js"/>

if (window.ubPlayer == null) {
    ubPlayer = {};

    ubPlayer.baseURL = "http://music2.digi.com.my/";
    //ubPlayer.baseURL = "http://localhost:61202/";
    
    //reconfigure
    if (window.ubbase != null) {
        ubPlayer.baseURL = ubbase.siteurl;        
    };
    
    ubPlayer._flashName = "";
    ubPlayer._radioDiv = "";
    ubPlayer.plPerPage = 99;
    ubPlayer.songsPerPage = 99;
    ubPlayer.playSongNow = 0;

    ubPlayer.initUI = function(sFlashName, divUI) {
        ubPlayer._flashName = sFlashName;
        ubPlayer._radioDiv = divUI;
        //post to get UI
        ubPlayer.doPost("getui");
    };

    ubPlayer.loadPlaylist = function(plID) {
        //Initiate a songlist grab of the playlist
        //and flag to play after retrieval

        ubPlayer.playSongNow = 1;
        if (plID == null) {
            plID = $(".divSongListDisplay").attr("playlistid");
        }
        else {
            $(".divSongListDisplay").attr("playlistid", plID);
        }
        $(".slContainer").html("");
        ubPlayer.doPost("sl.getcount", plID);
        ubPlayer.doPost("pl.getinfo", plID);
    };

    ubPlayer.changePlaylist = function(playlistid) {
        var divSong = $(".divSongListDisplay");
        divSong.hide();
        divSong.attr("playlistid", playlistid);        
        divSong.attr("itemcount", NaN);
        $(".cboSongList").text("Pick a song to play");
        $(".slContainer").html("");
        ubPlayer.loadPlaylist(playlistid);
    };
    
ubPlayer.textCrop = function(fullText,cropLength) {

if (fullText.length > cropLength) {
    var tarCrop = cropLength;
        return (fullText.substring(0, tarCrop) + "...");
    }
    else {
        return fullText;
    };
    

};
    
    //initialize the radio player, with the name of the flash element
ubPlayer.init = function(sFlashName) {

    ubPlayer.lastState = "ended";
    ubPlayer.shufflePlaylist = false;
    ubPlayer.repeatPlaylist = false;
    ubPlayer.shuffleSong = false;
    ubPlayer.repeatSong = false;

    ubPlayer.volume = 5;

    $(".player .button").hover(function() {
        $(this).parent().addClass("hover");
    }, function() {
        $(this).parent().removeClass("hover");
    });

    //Drop down playlist selector
    $(".btnDropPlayList").click(function(e) {
        //drop play list
        //get offset of the listbox            
        e.preventDefault();
        var divPlay = $(".divPlayListDisplay");
        if (divPlay.css("display") == "none") {
            //check if we have gotten a page count yet
            if (divPlay.attr("itemcount") == null) {
                //get count fisrt
                ubPlayer.doPost("pl.getcount");
            }
            else {
                if (divPlay.attr("fixed") != "1") {
                    var listOffset = $(".cboPlayList").offset();
                    divPlay.css({ "top": listOffset.top + 1 + $(".cboPlayList").height(), "left": listOffset.left }).show();
                }
                else {
                    divPlay.show();
                    window.resizeBy(0, divPlay.height());
                }
                //TODO : Redropping doesn't fix current page properly.

            }

            //ubPlayer.doPost("pl.getcount");
            //ubPlayer.doPost("pl.getpage","1,10");
        } else {
            divPlay.hide();
            if (divPlay.attr("fixed") == "1") {
                window.resizeBy(0, -divPlay.height());
            };
        };
    });

    //scrollPlaylistUp
    $(".plScrollUp").click(function() {
        //check current page
        var divPlay = $(".divPlayListDisplay");
        var currPage = parseInt(divPlay.attr("currPage"));
        if (currPage == 0)
            return;
        ubPlayer.hideCurrentPage(1);
        currPage--;
        divPlay.attr("currPage", currPage);
        ubPlayer.getplpage(currPage, ubPlayer.plPerPage);
    });

    //scrollPlaylistDown
    $(".plScrollDown").click(function() {
        var divPlay = $(".divPlayListDisplay");
        var currPage = parseInt(divPlay.attr("currPage"));
        var totalPage = parseInt(divPlay.attr("totalpages"));
        if (currPage >= (totalPage - 1))
            return;
        ubPlayer.hideCurrentPage(0);
        currPage++;
        divPlay.attr("currPage", currPage);
        ubPlayer.getplpage(currPage, ubPlayer.plPerPage);

    });

    //scrollSonglistUp
    $(".slScrollUp").click(function() {
        //check current page
        var divSong = $(".divSongListDisplay");
        var currPage = parseInt(divSong.attr("currPage"));
        if (currPage == 0)
            return;
        ubPlayer.hideCurrentSongPage(1);
        currPage--;
        divSong.attr("currPage", currPage);
        ubPlayer.getslpage(currPage, ubPlayer.songsPerPage);
    });

    //scrollSonglistDown
    $(".slScrollDown").click(function() {
        var divSong = $(".divSongListDisplay");
        var currPage = parseInt(divSong.attr("currPage"));
        var totalPage = parseInt(divSong.attr("totalpages"));
        if (currPage >= (totalPage - 1))
            return;
        ubPlayer.hideCurrentSongPage(0);
        currPage++;
        divSong.attr("currPage", currPage);
        ubPlayer.getslpage(currPage, ubPlayer.songsPerPage);

    });

    $(".undock").click(function() {
        var width = $(this).attr("pwidth");
        var height = $(this).attr("pheight");
        
        window.open(ubPlayer.baseURL + "controls/plyr/freeplyr.html", "freeplyr",
        "height="+height+",width="+width+",left=" + (screen.width / 2 - 250 / 2 + 5) + ",top=" + (screen.height / 2 - 280 / 2 + 15) + ",status=no,toolbar=no,menubar=no,location=no")


    });

    //Drop down songlist selector        
    $(".btnDropSongList").click(function(e) {

        e.preventDefault();
        var divSong = $(".divSongListDisplay");

        //only show if a playlist has been selected
        if (divSong.attr("playlistid") == null) {
            alert("Pick a playlist first!");
            return;
        }

        if (isNaN(parseInt(divSong.attr("itemcount")))) {
            //get count fisrt
            ubPlayer.doPost("sl.getcount", divSong.attr("playlistid"));
            return;
        }

        if (divSong.css("display") == "none") {
            if (divSong.attr("fixed") != "1") {
                var listOffset = $(".cboSongList").offset();
                divSong.css({ "top": listOffset.top + 1 + $(".cboSongList").height(), "left": listOffset.left }).show();
            } else {
                divSong.show();
                //resize window to our height
                window.resizeBy(0, divSong.height());
            }

        } else {

            divSong.hide();
            if (divSong.attr("fixed") == "1") {
                window.resizeBy(0, -divSong.height());
            };
        };
    });

    $(".btnClosePlaylist").click(function() {
        $(".btnDropPlayList").click();
    });

    $(".btnCloseSonglist").click(function() {
        $(".btnDropSongList").click();
    });

    //Volume
    $(".player .volume").click(function() {
        ubPlayer.setVol($(this).attr("vol"));
    });

    //the play/pause button
    $(".player .playpause").click(function() {
        //check the curret state first             
        var src = $(".playpause");
        if (src.hasClass("paused")) {
            //paused, play the song again
            //src.removeClass("paused");
            ubPlayer.callSongAction("play");
        }
        else {
            //playing, pause the song
            //src.addClass("paused");
            ubPlayer.callSongAction("pause");
        }
    });

    //mute function
    $(".player .speaker").click(function() {
        var player = $(".player");
        if (player.attr("vol") != 0) {
            //we're not mute, so mute
            if (player.attr("vol") != null)
                player.attr("oldvol", player.attr("vol"));
            ubPlayer.setVol(0);
            $(this).addClass("mute");
        }
        else {
            if (player.attr("oldvol") != null) {
                ubPlayer.setVol(player.attr("oldvol"));
            } else {
                ubPlayer.setVol(60);
            }
            $(this).removeClass("mute");

        }
    });


    //previous track, doesn't work in shuffle mode
    $(".player .rev").click(function() {
        ubPlayer.changeCurrentSong(-1);
    });

    $(".player .forward").click(function() {
        ubPlayer.changeCurrentSong(1);
    });


    //Function for tracking the played time
    window.showTimer = function(str) {
        $(".player .divTime").text(str);
    };

    //function for tracking playstate
    window.playerOnChangeState = function(str) {

        switch (str) {
            case "onSongLoaded":
                ubPlayer.lastState = "loaded";
                //restore volume
                if ($(".player").attr("vol") != null)
                    ubPlayer.setVol($(".player").attr("vol"));
                break;
            case "onSongEnd":
                ubPlayer.lastState = "ended";
                //play next
                window.setTimeout("ubPlayer.changeCurrentSong(1);", 1000);
                break;
            case "onPlay":
                ubPlayer.lastState = "playing";
                // alert("playing song");
                //change play button state to playing
                $(".player .playpause").removeClass("paused");
                break;
            case "onPause":
                ubPlayer.lastState = "paused";
                $(".player .playpause").addClass("paused");
                //alert("paused song");
                break;
        }
    }
};

    //Function to do the posting to the URL, so we can swap out how to do it
    //when necessary
    ubPlayer.doPost = function(action, param) {
        //ubPlayer.getFlashMovie().postData(ubPlayer.baseURL+'process/player/player-ajax.aspx?a='+ action + '&p=' + param);
        $(".divTime").addClass("load");
        var oReq = new JSONscriptRequest(ubPlayer.baseURL + 'process/player/player-ajax.aspx?a=' + action + '&p=' + param);
        oReq.buildScriptTag();
        oReq.addScriptTag();
    };


        //Plays the song in the URL
    ubPlayer.playSong = function(songURL,SongName,SongID) {
        ubPlayer.getFlashMovie().loadSong(songURL, SongName, SongID);
     };
    
    ubPlayer.callSongAction = function(action) {
      ubPlayer.getFlashMovie().playerAction(action);
    };



   
    //results of the json function
    ubPlayer.getPostData = function(val) {
        $(".divTime").removeClass("load");
        if (val == null) {
            //error posting
            alert("Error communicating with Server, please refresh the page!");
            return;
        }

        if (val.errorcode != "0") {
            //got an Error
            alert("Error communicating with server :" + val.errortext);
            return;
        };

        switch (val.action) {
            case "getui":
                //build ui then init                                
                $(ubPlayer._radioDiv).html(val.result);
                ubPlayer.init();
                break;
            case "sl.getcount":
                $(".divSongListDisplay").attr("itemcount", val.result);
                $(".divSongListDisplay").attr("totalpages", Math.ceil(val.result / ubPlayer.songsPerPage));
                $(".divSongListDisplay").attr("currPage", 0);
                if (val.result != 0) {
                    ubPlayer.getslpage(0, ubPlayer.songsPerPage);
                    if (ubPlayer.playSongNow == 0) {
                        $(".btnDropSongList").click();
                    }
                }
                else {
                    $(".cboSongList").text("Playlist is empty!")
                }
                break;
            case "sl.getpage":
                var slPage = $(".slContainer .slPage[page=" + val.result.pageindex + "]");
                slPage.html("");
                //iterate through each result
                $.each(val.result.items, function(key, index) {
                    //alert(val.result.items[key].listname);
                    var item = $('<div class="songlistitem"></div>');
                    item.text(ubPlayer.textCrop(val.result.items[key].songname, 25));
                    item.attr("title", val.result.items[key].songname);
                    //attach click events
                    item.click(function() {
                        //change playlist playlist
                        var divSong = $(".divSongListDisplay");
                        $(".btnDropSongList").click();
                        //Play song
                        //TODO : Probably need to store song ID, and item index
                        //Play song in URL
                        ubPlayer.loadSong($(this).attr("songindex"));
                    });
                    item.attr("songindex", ((key + 1) + (val.result.pageindex * ubPlayer.songsPerPage)));
                    item.attr("songname", val.result.items[key].songname);
                    item.attr("songid", val.result.items[key].songid);
                    item.attr("songurl", val.result.items[key].songurl);
                    slPage.append(item);
                    if (ubPlayer.playSongNow == 1) {
                        ubPlayer.playSongNow = 0;
                        ubPlayer.loadSong(1);
                    }
                });
                slPage.show();
                break;
            case "pl.getinfo":
                //Get info about the playlist
                $(".cboPlayList").attr("title", val.result.listname);
                $(".cboPlayList").text(ubPlayer.textCrop(val.result.listname, 25));
                $(".cboPlayList").attr("playlistid", val.result.listid);
                break;
            case "pl.getcount":

                //got the count , now fire click on the drop button again
                $(".divPlayListDisplay").attr("itemcount", val.result);
                $(".divPlayListDisplay").attr("totalpages", Math.ceil(val.result / ubPlayer.plPerPage));
                $(".divPlayListDisplay").attr("currPage", 0);
                //get first page of data as well
                ubPlayer.getplpage(0, ubPlayer.plPerPage);
                $(".btnDropPlayList").click();
                break;
            case "pl.getpage":
                //alert("No. PL Items :" + val.result.items.length);
                //find the page
                var plPage = $(".plContainer .plPage[page=" + val.result.pageindex + "]");
                plPage.html("");
                //iterate through each result
                $.each(val.result.items, function(key, index) {
                    //alert(val.result.items[key].listname);
                    var item = $('<div class="playlistitem"></div>');
                    item.text(ubPlayer.textCrop(val.result.items[key].listname, 25));
                    item.attr("title", val.result.items[key].listname);
                    //attach click events
                    item.click(function() {
                        //change playlist playlist
                        ubPlayer.changePlaylist(val.result.items[key].listid);
                        $(".cboPlayList").attr("title", val.result.items[key].listname);
                        $(".cboPlayList").text(ubPlayer.textCrop(val.result.items[key].listname, 25));
                        $(".cboPlayList").attr("playlistid", val.result.items[key].listid);
                        $(".btnDropPlayList").click();
                    });
                    plPage.append(item);
                });
                plPage.show();
                break;
        }
    };

  

    //Changes the current song index based on the steps provided
    //0 for random
    ubPlayer.changeCurrentSong = function(steps) {
        var divSong = $(".divSongListDisplay");
        var currIndex = parseInt(divSong.attr("currSongIndex"));
        var totalSongs = parseInt(divSong.attr("itemcount"));
        //change index here, need to include shuffle logic here
        //later
        currIndex += steps;
        if (currIndex <= 0) {
            //Loop by TotalSongs + Step

            currIndex = totalSongs + currIndex;
        }
        else if (currIndex > totalSongs) {
            currIndex = currIndex - totalSongs;
        }
        ubPlayer.loadSong(currIndex);
    };

    //Hides the current page, scrollUp=1 to indicate page should scroll up to hide, 0 to scroll down
    ubPlayer.hideCurrentPage = function(scrollUp) {
        var divPlay = $(".divPlayListDisplay");
        var currPage = divPlay.attr("currPage");
        //in this case we just hide first        
        $(".plContainer .plPage[page=" + currPage + "]").hide();
    };

    //Hides the current page, scrollUp=1 to indicate page should scroll up to hide, 0 to scroll down
    ubPlayer.hideCurrentSongPage = function(scrollUp) {
        var divPlay = $(".divSongListDisplay");
        var currPage = divPlay.attr("currPage");
        //in this case we just hide first        
        $(".slContainer .slPage[page=" + currPage + "]").hide();
    };
    //function to get a page of playlist info
    ubPlayer.getplpage = function(pageindex, pagesize) {
        //first see if the page already exists or not
        if ($(".plContainer .plPage[page=" + pageindex + "]").length != 0) {
            $(".plContainer .plPage[page=" + pageindex + "]").show();
            return;
        }
        var oPage = $('<div class="plPage" page="' + pageindex + '">Loading Page ' + pageindex + '...</div>');
        ubPlayer.doPost("pl.getpage", "" + pageindex + "," + pagesize);
        $(".plContainer").append(oPage);
    };

    ubPlayer.getslpage = function(pageindex, pagesize) {
        if ($(".slContainer .slPage[page=" + pageindex + "]").length != 0) {
            $(".slContainer .slPage[page=" + pageindex + "]").show();
            return;
        };
        var oPage = $('<div class="slPage" page="' + pageindex + '">Loading Page ' + pageindex + '...</div>');
        var divSong = $(".divSongListDisplay");


        ubPlayer.doPost("sl.getpage", "" + divSong.attr("playlistid") + "," + pageindex + "," + pagesize);
        $(".slContainer").append(oPage);
    };
    
    ubPlayer.getFlashMovie = function() {
        return document[ubPlayer._flashName];
    };

    ubPlayer.setVol = function(vol) {
        ubPlayer.getFlashMovie("music_player").setVolume(vol);
        $(".player").attr("vol", vol);
        //find every volume and set anything <= value to selected;
        $(".volume").each(function() {
            var tarvol = parseInt($(this).attr("vol"));
            if (tarvol <= vol) {
                $(this).addClass("selected");
            } else {
                $(this).removeClass("selected");
            }
        });
    };


    //Loads the specified song index from the current list
    ubPlayer.loadSong = function(songIndex) {
        //find the item containing the songindex first
        var divSong = $(".divSongListDisplay");
        var songItem = divSong.find(".songlistitem[songindex=" + songIndex + "]");
        divSong.attr("currSongIndex", songItem.attr("songindex"));
        $(".cboSongList").attr("title", songItem.attr("songname"));
        $(".cboSongList").text(ubPlayer.textCrop(songItem.attr("songname"), 25));
        $(".cboSongList").attr("songid", songItem.attr("songid"));
        ubPlayer.playSong(songItem.attr("songurl"), songItem.attr("songname"), songItem.attr("songid"));
    };
    
    //hook the onGetData function, might need to talk to Kian Huat
    //about customizing this
    window.onGetData = function(str) {
        alert(str);
        var myvar;
        eval("myvar=" + str);
        alert(myvar.errortext);
    };
};

$(document).ready(function() {    
        ubPlayer.initUI("music_player", ".divRadio");
});
///Merging JSON Request SCript

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
};

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function() {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
};

// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function() {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
};

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function() {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
};

