// MTDSP object
//------------------------------
MTDSP = function() {};
MTDSP.VERSION = '0.1.1';
MTDSP.SWF_VERSION = 'SWF has not loaded.';
MTDSP.mmlPlayerID = 'playerObject';
MTDSP.mmlPlayer = undefined;
MTDSP.loaded = false;
MTDSP.playing = false;
MTDSP.width = 640;
MTDSP.height = 320;
MTDSP.playLimit = 120;
MTDSP.mmlid = '';

//MTDSP.height = 1;

MTDSP.compile = function(_mml) { MTDSP.mmlPlayer._compile(_mml, MTDSP.playLimit); }
MTDSP.play = function(_mml) { MTDSP.mmlPlayer._play(_mml, MTDSP.playLimit); }
MTDSP.stop = function() { MTDSP.mmlPlayer._stop(); }
MTDSP.onStreamStart = function() { 
    MT_message("Play"); 
    $.post(hosturl + 'pc', MTDSP.mmlid + '=1', function() {
        if (arguments[0].match(/([a-z0-9]+)=(\d+)/)) {
            MTDSP.mmlPlayer._playCount(RegExp.$2);
        }
    }, 'text');
}
MTDSP.onFinishSequence = function() { MT_message("Ready"); }
MTDSP.onError = function(errorMessage){ alert(errorMessage); }
MTDSP.onLoad = function() {}
MTDSP.onNext = function() {}


// global valiables
var username;
var hosturl;




function initializePlayer() {
    initializeGlobalValiables();
    
    // check flash players major version
    if (getFlashPlayerVersion(0) < 10) {
        MTDSP.onError("The SiOPM module is only available on Flash Player 10.");
        return;
    }
    
    var swfName  = hosturl + 'script/mtdsp.swf' + '?version=' + MTDSP.VERSION;//'?' + (new Date()).getTime(); //

    // insert swf object in <div id='player'/>
    var div = $('div#player').get(0);
    div.width  = MTDSP.width;
    div.height = MTDSP.height;

    // insert object
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
        // ns
        var o = document.createElement('object');
        o.id = MTDSP.mmlPlayerID;
        o.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
        o.width = MTDSP.width;
        o.height = MTDSP.height;
        o.setAttribute('data', swfName);
        o.setAttribute('type', 'application/x-shockwave-flash');
        var p = document.createElement('param');
        p.setAttribute('name', 'allowScriptAccess');
        p.setAttribute('value', 'always');
        o.appendChild(p);
        div.appendChild(o);
    } else {
        // ie
        var object = '<object id="' + MTDSP.mmlPlayerID + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
        object    += 'width="' + MTDSP.width + '" height="' + MTDSP.height + '">';
        object    += '<param name="movie" value="' + swfName + '" />';
        object    += '<param name="bgcolor" value="#FFFFFF" />';
        object    += '<param name="quality" value="high" />';
        object    += '<param name="allowScriptAccess" value="always" />';
        object    += '</object>';
        div.innerHTML = object;
    }
}


function initializeGlobalValiables() {
    username = $.cookie('username') || "Anonymous";
    hosturl  = 'http://' + location.host + '/';
    if (!$.support['style']) {
        entryLoadLimit = 2;
        entryPageLength = 6;
    }
}


function MT_message(mes) {
    $("div#message").text(mes);
}


function MT_request(functionName, args, callback) {
    if (!args) args = new Array();
    
    var query = 'action=' + encodeURIComponent(functionName);
    for (var key in args) query += '&' + key + '=' + encodeURIComponent(args[key]);
    
    query += '&time=' + new Date().getTime();
    $.post('http://' + location.host + '/rpc', query, callback, 'text');
}

function redirect(url) {
    document.location.href = url;
}


var scope_discription = [
    "All people can listen to your post. The post appears on public time line.",
    "Only MMLTalks users can listen to your post. The post appears on users time line.",
    "The post is stored and permanent link is created. But it doesnt appear on any time lines."
];
var scope_type = [
    "public",
    "protected",
    "private"
];





//------------------------------------------------------------------------------------------------------------------------
// page operations
//------------------------------
var currentListType = -1;
var playingIndex = -1;
var $entryCache = {};
var mmlidList = [];
var entryPageLength = 8;
var entryPageIndex = 0;
var entryListLength = 100;
var entryListIndex = 0;
var entryListTag = '';
var entryLoadLimit = 8;
var allListLoaded = false;
var favlist = {};
var $loading = $("<div class='entrytitle'>Loading ...</div><div class='author'>&nbsp;</div>");


function onCommentOver(img)  { $(img).attr("src", hosturl + "image/open_ov.gif"); }
function onCommentOut(img)   { $(img).attr("src", hosturl + "image/open.gif"); }
function onCommentClick(img) { $(img).parents("div.entry").children("div.toggleDisplay").toggle(); }
function onShowMMLOver(img)  { $(img).attr("src", hosturl + "image/showmml_ov.gif"); }
function onShowMMLOut(img)   { $(img).attr("src", hosturl + "image/showmml.gif"); }
function onHatenaBMOver(img) { $(img).attr("src", hosturl + "image/hatenabm_ov.gif"); }
function onHatenaBMOut(img)  { $(img).attr("src", hosturl + "image/hatenabm.gif"); }
function onDeliciousOver(img){ $(img).attr("src", hosturl + "image/delicious_ov.gif"); }
function onDeliciousOut(img) { $(img).attr("src", hosturl + "image/delicious.gif"); }
function onEntryTitleOver(h2) { $(h2).addClass("mouseon"); }
function onEntryTitleOut(h2)  { $(h2).removeClass("mouseon"); }

function onClickStar(star) {
    if ($.cookie('sid')) {
        var $star = $(star);
        var $entry = $star.parents('div.entry');
        var $favcount = $star.next();
        if ($star.hasClass('checked')) {
            MT_request('removefavorite', { 'mmlid':$entry.attr('mmlid') }, function() {
                if (arguments[0] != -1) {
                    $star.attr("src", hosturl + "image/star.gif").removeClass('checked');
                    if (arguments[0] == 0) $favcount.text('0');
                    else $favcount.text(arguments[0]);
                    delete favlist[$entry.attr('mmlid')];
                }
            });
        } else {
            MT_request('addfavorite', { 'mmlid':$entry.attr('mmlid') }, function() {
                if (arguments[0] != -1) {
                    $star.attr("src", hosturl + "image/star_ov.gif").addClass('checked');
                    if (arguments[0] == 0) $favcount.text('0');
                    else $favcount.text(arguments[0]);
                    tag = {"tags":""};
                    favlist[$entry.attr('mmlid')] = tag;
                    _updateUserTags($entry.children('div.usertags'), tag);
                }
            });
        }
    }
}

function onEntrySelected(header) {
    var $header = $(header);
    var $h2 = $header.children('h2');
    if ($h2.hasClass("selected")) {
        $h2.removeClass("selected");
        _stop();
    } else {
        _play($header.parents('div.entry'));
    }
}

function selectListType(selected, selectedType, tag) {
    var $selected = $(selected);
    $selected.siblings().removeClass('selected');
    $selected.addClass('selected');
    if (tag == undefined) tag = '';
    if (currentListType != selectedType || entryListTag != tag) {
        currentListType = selectedType;
        mmlidList = [];
        entryListTag = tag;
        entryListIndex = 0;
        entryPageIndex = 0;
        allListLoaded = false;
        _updateList();
    }
}

function onClickTags(link) {
    entryListTag = $(link).children('span#tag').text();
    mmlidList = [];
    entryListIndex = 0;
    entryPageIndex = 0;
    allListLoaded = false;
    _updateList();
}
function clearTagSelect() {
    entryListTag = "";
    mmlidList = [];
    entryListIndex = 0;
    entryPageIndex = 0;
    allListLoaded = false;
    _updateList();
}
function onEditTags(link) {
    var $divtags = $(link).parents('div.usertags');
    var $entry = $divtags.parents('div.entry');
    var $divedit = $entry.children('div.tagedit');
    var mmlid = $entry.attr('mmlid');
    if (mmlid in favlist) {
        $divedit.children('input#tagsinput').val(favlist[mmlid].tags);
        $divedit.show();
    }
}
function onSubmitTags(button) {
    var $tagsinput = $(button).prev();
    var $tagedit = $(button).parent();
    var $entry = $tagedit.parent();
    var $divusertags = $entry.children('div.usertags');
    var mmlid = $entry.attr('mmlid');
    favlist[mmlid] = {"tags":$tagsinput.val()};
    $tagedit.hide();
    $divusertags.text('submit your tags ...');
    MT_request('edittag', { 'mmlid':mmlid, 'tags':favlist[mmlid].tags }, function() {
        $entry.children('div.tags').html(arguments[0]);
        _updateUserTags($divusertags, favlist[mmlid]);
    });
}

function addComment(submit_button) {
    if (MTDSP.mmlid == '') {
        MT_message("The MML entry is not selected.");
    } else {
        var cont = $('input#newcomment_cont').val();
        if (cont == '') {
            MT_message("Please input some comment text.");
        } else {
            var $entry = $entryCache[MTDSP.mmlid];
            $('input#newcomment_cont').val('');
            if (cont.search(/https?:/i) != -1) {
                MT_message("The comment should not include any URLs.");
            } else {
                MT_message("Posting your comment ...");
                var args = {
                    'mmlid' : MTDSP.mmlid, 
                    'name' : $('input#newcomment_name').val(), 
                    'cont' : cont
                };
                MT_request('addcomment', args, function() {
                    MT_message("Ready");
                    var $newcomment = $(arguments[0]);
                    $entry.children('div#comments').show().prepend($newcomment);
                });
            }
        }
    }
}

function removeComment(link) {
    var $cc = $(link).parents('div.commentcolumn');
    var args = {
        'comid' : $cc.attr('comid'),
        'mmlid' : $cc.parents('div.entry').attr('mmlid')
    };
    MT_message("Deleting your comment ...");
    MT_request('removecomment', args, function() {
        MT_message("Ready");
        $cc.hide();
    });
}

function getNext() {
    entryPageIndex += entryPageLength;
    if (entryListIndex <= entryPageIndex) _updateList();
    else _updateMain();
}

function getPrev() {
    entryPageIndex -= entryPageLength;
    if (entryPageIndex < 0) entryPageIndex = 0;
    _updateMain();
}

function _updateMain(callback) {
    var listNotCached = [];
    var imax = entryPageIndex + entryPageLength;
    var $entry;
    if (imax > entryListIndex) imax = entryListIndex;
    var entries = [];
    var $main = $('div#main');
    $main.html('');
    for (var i=entryPageIndex; i<imax; i++) {
        var mmlid = mmlidList[i];
        if (mmlid in $entryCache) {
            $entry = $entryCache[mmlid];
            $entry.attr('index', i);
            $main.append($entry);
        } else {
            if (listNotCached.length < entryLoadLimit) listNotCached.push(mmlid);
            $main.append($loading.clone());
        }
    }

    $('div.tagedit').hide();
    if (currentListType == 2) {
        $('div.usertags').show();
        $('div.tags').hide();
    } else {
        $('div.usertags').hide();
        $('div.tags').show();
    }
    
    if (listNotCached.length > 0) _updateCache(listNotCached, _updateMain);
    else if (callback) callback();
}

function _updateList(callback) {
    if (allListLoaded) return;
    args = { offset:entryListIndex, length:entryListLength };
    if (currentListType == 0) args['permission'] = 0;
    else if (currentListType == 2) args['mylist'] = username;
    if (entryListTag != '') args['tag'] = entryListTag;
    MT_message("Loading entry list ...");
    MT_request('getlist', args, function (mmllist) {
        if (mmllist != '') {
            var recieved = mmllist.split(',');
            Array.prototype.push.apply(mmlidList, recieved);
            entryListIndex += recieved.length;
            allListLoaded = (recieved.length != entryListLength || recieved.length == 0);
            if (entryListTag != '') {
                $('span#selectedTag').html("tag:["+entryListTag+"]&nbsp;<a href='#' onClick='clearTagSelect(); return false;'>clear</a>");
            } else {
                $('span#selectedTag').html("");
            }
            _updateMain(callback);
        }
        MT_message("Ready");
    });
}

function _updateCache(list, callback) {
    MT_request('getmml', { 'mmlids':list.join(',') }, function(res) {
        $(res).filter('div.entry').each(function() {
            var $entry = $(this);
            var mmlid = $entry.attr('mmlid');
            $entryCache[mmlid] = _modifyEntry($entry);
        });
        callback();
    });
}

function _modifyEntry($entry) {
    if ($.cookie('sid')) {
        var mmlid = $entry.attr('mmlid');
        if (mmlid in favlist) {
            $entry.children('div.control').children('img.favorite').attr("src", hosturl + "image/star_ov.gif").addClass('checked');
            _updateUserTags($entry.children('div.usertags'), favlist[mmlid]);
        } else {
            $entry.children('div.control').children('img.favorite').attr("src", hosturl + "image/star.gif").removeClass('checked');
        }
        $entry.children('div#comments').children('div.'+username).each(function () {
            $(this).append(" <a href='#' onClick='removeComment(this); return false'>[delete]</a>");
        });
    } else {
        var $imgfav = $entry.children('div.control').children('img.favorite');
        $imgfav.click(function(){});
        $imgfav.css('cursor', 'default');
    }
    return $entry;
}

function _updateUserTags($div_usertags, usertags) {
    if (!usertags.html) {
        var usertags_string = [];
        var tags = usertags.tags.split(' ');
        for (var i = 0; i<tags.length; i++) {
            if (tags[i] != '') {
                usertags_string.push("<a href='#' onClick='onClickTags(this); return false;'>[<span id='tag'>");
                usertags_string.push(tags[i]);
                usertags_string.push("</span>]</a>");
            }
        }
        usertags_string.push("&nbsp;<a href='#' onClick='onEditTags(this); return false;'>Edit</a>");
        usertags.html = usertags_string.join('');
    }
    $div_usertags.html(usertags.html);
}

function _play($entry) {
    $('h2').removeClass("selected");
    $entry.children('div.entrytitle').children('h2').addClass("selected");
    MTDSP.mmlid = $entry.attr('mmlid');
    playingIndex = parseInt($entry.attr('index'));
    MTDSP.play($entry.children("div.mml").text());
}

function _stop() {
    MTDSP.stop();
}

function _playNext() {
    if (entryPageIndex + entryPageLength <= playingIndex+1) {
        entryPageIndex += entryPageLength;
        if (entryListIndex <= entryPageIndex) _updateList(_playNext);
        else _updateMain(_playNext);
    } else {
        if (playingIndex < mmlidList.length) {
            var mmlid = mmlidList[playingIndex+1];
            if (mmlid in $entryCache) _play($entryCache[mmlid]);
        } else if (playingIndex != -1) {
            playingIndex = -1;
            _playNext();
        }
    }
}


//------------------------------------------------------------------------------------------------------------------------
// internal functions
//------------------------------
// get Flash player version numbers. argument requires sub numbers.
function getFlashPlayerVersion(subs) {
    return (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) ? 
        navigator.plugins["Shockwave Flash"].description.match(/([0-9]+)/)[subs] : 
        (new ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version").match(/([0-9]+)/)[subs];
}


// callback from siopm.swf
MTDSP._internal_onLoad = function(version) {
    MTDSP.SWF_VERSION = version;
    MTDSP.loaded = true;
    MTDSP.mmlPlayer = document.getElementById(MTDSP.mmlPlayerID);
    MTDSP.onLoad();
}
MTDSP._internal_onError = function(message) {
    MTDSP.onError(message);
}
MTDSP._internal_onStreamStart = function() {
    MTDSP.playing = true;
    MTDSP.onStreamStart();
}
MTDSP._internal_onFinishSequence = function() {
    MTDSP.playing = false;
    MTDSP.onFinishSequence();
}
MTDSP._internal_onNext = function(repeat) {
    MTDSP.onNext(repeat);
}

