var so;
var sgenc;
var rcode;
var q;
function createRingTone() {
    var elem1 = document.getElementById("StartTime");
    if (!elem1.value) {
        alert("Vui lòng chờ giây lát");
        return false;
    };
    if (elem1.value < 0) {
        alert("Xin chọn khoảng cắt!ngắn nhất: 5s,dài nhất: 120s");
        return false;
    }
    $("#imgcut").html('<img src="/images/CuttingLoadding.gif" style="margin:4px 0 0 10px;" alt="Waiting"  />');
    CutRingTone();
}

function getcuttingarg() {
    return sgenc + "|" + $("#StartTime").val() + '|' + $("#Duration").val();
}

function OnCuttingComplete(result, context) {
    //if (/^-?\d+$/.test(result) && result != 0) {
    if (result.indexOf("Lỗi:") != -1) {
        $("#imgcut").html('');
        $("#btnrcut").removeAttr("disabled");
        alert(result + "\nXin thử lại");
    }
    else {
        var s = result.split('|');
        if (s.length > 1) {
            rcode = s[0];           
            $("#btndownload").attr("href", $("#btndownload").attr("href") + s[1]);
            $("#lb1step3").text("NN R" + s[0]);
            $("#lb2step3").text("NN R" + s[0]);

            $("#cutting1").hide();
            $("#cutting2").hide();
            $("#cutting2a").hide();
            $("#cutting3").hide();
            $("#cutting2a").show();
        }
        else {
            $("#imgcut").html('');
            $("#btnrcut").removeAttr("disabled");
            alert("Lỗi: Tạo nhạc chuông không thành công\nXin thử lại");
        }
    }
}

function OnUpdateComplete(result) {
    if (result) {
        SetStatus(3);
    }
    else {
        alert("Có lỗi, xin thử lại");
    }
}

function getRingTone(aFromTime, aToTime) {
    var elem1 = document.getElementById("StartTime");
    var elem2 = document.getElementById("Duration");
    if (elem1 && elem2) {
        elem1.value = TimeFromMiliSecond(aFromTime);
        elem2.value = TimeFromMiliSecond(aToTime - aFromTime);        
    }
}

function TimeFromMiliSecond(value) {
    return value/1000;
}

function SetStatus(step) {
    $("#cutting1").hide();
    $("#cutting2").hide();
    $("#cutting2a").hide();
    $("#cutting3").hide();    
    switch (step) {
        case 1:
            $("#cutting1").show();
            $("#step1").attr("class", "sep1Active")
            $(".boxPropertyRing").width(192);
            break;
        case 2:
            $("#cutting2").show();
            $("#step2").attr("class", "sep2Active")
            $(".boxPropertyRing").width(392);
            break;
        case 3:
            $("#lbrname3").text('"' + $("#txtrname").val() + '"');
            $("#cutting3").show();
            $("#step3").attr("class", "sep3Active")
            $(".boxPropertyRing").width(592);
            break;
    }
}

function step2Complete(result) {
    if (result) {
        var o = $.evalJSON(result);
        $("#txtrname").val(o.name);
        q = o.name;
        $("#lbsongname").text(o.name);
        $("#txrtartist").val(o.artist);
        $("#txtrkeyword").val(o.album);
        $("#btndownload").attr("href", "http://data2.nghenhac.info/?t=1&p=");
        var so = new SWFObject('/Nhac-chuong/Js/RingTone.swf', 'CutFlash', '630', '200', '9.0.0');
        so.addParam('allowscriptaccess', 'always');
        so.addParam('allowfullscreen', 'false');
        so.addParam('wmode', 'transparent');        
        so.addParam('flashvars', 'filePath=' + o.fileurl);
        so.write('CutFlash');
        initRing(first);
    }
    else {        
        alert("Có lỗi, xin thử lại");
    }
}

function SearchTopTen(pageIndex, val) {
    if (val.length <3) {
        alert("Xin nhập ít nhất 3 ký tự");
        return false;      
    }
    var rnd = Math.random() * 5;
    $.ajax({
        type: "POST",
        url: "/Nhac-chuong/Ajax/SearchTopSong.aspx",
        data: "rnd=" + rnd + "&pIndex=" + pageIndex + "&filter=" + val,
        cache: true,
        beforeSend: function() {
        $('#b_SearchSong').html('<div style="text-align:center;"><img src="/images/ajax-loader.gif" style="margin-top:10px;" /></div>');
            $('#b_SearchSong').show();
        },
        success: function(req) {
            $('#b_SearchSong').hide();
            $('#b_SearchSong').html(req);            
            $('#b_SearchSong').fadeIn(500);
        }
    });
    return false;
}

function ToCutting(req) {
    sgenc = req;
    PageMethods.GetSong(req, step2Complete);
    SetStatus(2);
}

function LTrim(value) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");

}

function RTrim(value) {

    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");

}

function trim(value) {

    return LTrim(RTrim(value));

}
//Index
function playMedia(obj, file, pr, duration, istop) {
    if (obj.className == 'adStop') {
        $(".boxPlay").attr('class', 'adStop');
        totaltime = duration;
        if (currentbg) currentbg.width(0);
        if (istop == true) {
            maxWidth = 262;
            currentbg = $("#divBackgroundT" + pr);
        }
        else {
            maxWidth = 430;
            currentbg = $("#divBackground" + pr);
        }
        obj.className = "boxPlay";
        player.sendEvent("LOAD", file);
        player.sendEvent("PLAY", "true");
        addListeners();
        updatelisten(pr);
    }
    else {
        obj.className = "adStop";
        player.sendEvent("STOP", "false");
        resetState();
    }
}
var maxWidth;
var totaltime;
var currentbg;
function updatetime(val) {
    if (currentbg) {
        var currentwidth = val * maxWidth / totaltime;
        if (currentwidth <= maxWidth) currentbg.width(currentwidth);

    }
}
function addListeners() {
    playlist = player.getPlaylist();
    if ((playlist !== null) && (playlist !== undefined)) {
        player.addModelListener('STATE', 'stateMonitor');
        player.addModelListener('TIME', 'timeMonitor');
    }
    else {
        setTimeout("addListeners()", 100);
    }
};
function timeMonitor(obj) {
    updatetime(obj.position);
}
function stateMonitor(obj) {
    if (obj.newstate == 'COMPLETED') {
        $(".boxPlay").attr('class', 'adStop');
        resetState();
        if (currentbg) currentbg.width(maxWidth);
        return;
    }
};
function resetState() {
    player.removeModelListener('STATE', 'stateMonitor');
    player.removeModelListener('TIME', 'timeMonitor');
}
function updatelisten(r) {
    $.ajax({
        type: "POST",
        url: "Ajax/updatelisten.aspx",
        data: "r=" + r,
        cache: false
    });
}
function initRing(pageIndex) {
    if (q) {
        var rnd = Math.random() * 5;
        $.ajax({
            type: "POST",
            url: "/Nhac-chuong/Ajax/RelativeRing.aspx",
            data: "rnd=" + rnd + "&pIndex=" + pageIndex + "&q=" + q,
            cache: true,
            beforeSend: function() {
            $('#ringPanel').html('<div style="width:100%;height:200px;vertical-align:top;text-align:center;"><img src="/Images/ajax-loader.gif" width="50" height="50" style="margin-top:30px;" /></div>');
            },
            success: function(req) {
                $('#ringPanel').html(req);
            }
        });
    }
}
function reload() {
    var url = new String(window.location);
    location.href = url.replace(/\?.*$/, "");
}
//Check plugins
var agt = navigator.userAgent.toLowerCase();
var ie = (agt.indexOf("msie") != -1);
var ns = (navigator.appName.indexOf("Netscape") != -1);
var win = ((agt.indexOf("win") != -1) || (agt.indexOf("32bit") != -1));
var mac = (agt.indexOf("mac") != -1);

if (ie && win) { pluginlist = detectIE("Adobe.SVGCtl", "SVG Viewer") + detectIE("SWCtl.SWCtl.1", "Shockwave Director") + detectIE("ShockwaveFlash.ShockwaveFlash.1", "Shockwave Flash") + detectIE("rmocx.RealPlayer G2 Control.1", "RealPlayer") + detectIE("QuickTimeCheckObject.QuickTimeCheck.1", "QuickTime") + detectIE("MediaPlayer.MediaPlayer.1", "Windows Media Player") + detectIE("PDF.PdfCtrl.5", "Acrobat Reader"); }
if (ns || !win) {
    nse = ""; for (var i = 0; i < navigator.mimeTypes.length; i++) nse += navigator.mimeTypes[i].type.toLowerCase();
    pluginlist = detectNS("image/svg-xml", "SVG Viewer") + detectNS("application/x-director", "Shockwave Director") + detectNS("application/x-shockwave-flash", "Shockwave Flash") + detectNS("audio/x-pn-realaudio-plugin", "RealPlayer") + detectNS("video/quicktime", "QuickTime") + detectNS("application/x-mplayer2", "Windows Media Player") + detectNS("application/pdf", "Acrobat Reader");
}

function detectIE(ClassID, name) { result = false; document.write('<SCRIPT LANGUAGE=VBScript>\n on error resume next \n result = IsObject(CreateObject("' + ClassID + '"))</SCRIPT>\n'); if (result) return name + ','; else return ''; }
function detectNS(ClassID, name) { n = ""; if (nse.indexOf(ClassID) != -1) if (navigator.mimeTypes[ClassID].enabledPlugin != null) n = name + ","; return n; }

pluginlist += navigator.javaEnabled() ? "Java," : "";
if (pluginlist.length > 0) pluginlist = pluginlist.substring(0, pluginlist.length - 1);
