//Ajax
var aXmlHttp = new Array();
var aXmlResponse = new Array();
var httpRequest = null;
var fn = ob = null;
function xmlResult()
{
    for (var i = 0; i < aXmlHttp.length; i++)
    {
        if (aXmlHttp[i] && aXmlHttp[i][0] && aXmlHttp[i][0].readyState == 4 && aXmlHttp[i][0].responseText)
        {
            if (aXmlHttp[i][0].status == 200) {
                //must null out record before calling function in case
                //function invokes another xmlHttpRequest.

                var f = aXmlHttp[i][2];
                var o = aXmlHttp[i][1];
                var s = aXmlHttp[i][0].responseText;
                aXmlHttp[i][0] = null;
                aXmlHttp[i][1] = null;
                aXmlHttp[i][2] = null;
                f.apply(o, new Array(s));
            }

        }

    }
}

// u -> url
// o -> object (can be null) to invoke function on
// f -> callback function
// p -> optional argument to specify POST

function call(u, o, f)
{
    var method, dat, tmp, idx;
    method = "GET";
    if (arguments.length == 4) {
        method = "POST";
        tmp = u.split(/\?/);
        u = tmp[0];
        dat = tmp[1];
    }
    idx = aXmlHttp.length;
    for (var i = 0; i < idx; i++)
        if (aXmlHttp[i] == null)
        {
            idx = i;
            break;
        }

    aXmlHttp[idx] = new Array(10);

    aXmlHttp[idx][0] = getXMLHTTP();

    aXmlHttp[idx][1] = o;
    aXmlHttp[idx][2] = f;
    if (aXmlHttp[idx])
    {
        aXmlHttp[idx][0].open(method, u, true);
        if (method == "POST") {
            aXmlHttp[idx][0].setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8; text/xml");
            aXmlHttp[idx][0].send(dat);
        } else if (method == "GET") {
            aXmlHttp[idx][0].send(null);
        }
        aXmlHttp[idx][0].onreadystatechange = xmlResult;
    }
}


function getXMLHTTP()
{
    var A = null;
    if (!A && typeof XMLHttpRequest != "undefined")
    {
        A = new XMLHttpRequest();
        if (A.overrideMimeType) {
            A.overrideMimeType('text/xml');
        }

    }
    if (!A)
    {
        try
        {
            A = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                A = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(oc)
            {
                A = null
            }
        }
    }
    return A;
}

//End of Ajax

var ca = new Array("a", "à.á.ạ.ả.ã.â.ầ.ấ.ậ.ẩ.ẫ.ă.ằ.ắ.ặ.ẳ.ẵ.À.Á.Ạ.Ả.Ã.Â.Ầ.Ấ.Ậ.Ẩ.Ẫ.Ă.Ằ.Ắ.Ặ.Ẳ.Ẵ");
var ce = new Array("e", "è.é.ẹ.ẻ.ẽ.ê.ề.ế.ệ.ể.ễ.È.É.Ẹ.Ẻ.Ẽ.Ê.Ề.Ế.Ệ.Ể.Ễ");
var ci = new Array("i", "ì.í.ị.ỉ.ĩ.Ì.Í.Ị.Ỉ.Ĩ");
var co = new Array("o", "ò.ó.ọ.ỏ.õ.ô.ồ.ố.ộ.ổ.ỗ.ơ.ờ.ớ.ợ.ở.ỡ.Ò.Ó.Ọ.Ỏ.Õ.Ô.Ồ.Ố.Ộ.Ổ.Ỗ.Ơ.Ờ.Ớ.Ợ.Ở.Ỡ");
var cu = new Array("u", "ù.ú.ụ.ủ.ũ.ư.ừ.ứ.ự.ử.ữ.Ù.Ú.Ụ.Ủ.Ũ.Ư.Ừ.Ứ.Ự.Ử.Ữ");
var cy = new Array("y", "ỳ.ý.ỵ.ỷ.ỹ.Ỳ.Ý.Ỵ.Ỷ.Ỹ");
var cd = new Array("d", "đ.Đ");
//var cs = new Array("", "\'.~.@.#.%.^.&");
//var bangkitucoso = new Array(ca, ce, ci, co, cu, cy, cd, cs);
var bangkitucoso = new Array(ca, ce, ci, co, cu, cy, cd);
function mLocDau(bv)
{
    var markhongdau = new Array();
    markhongdau[0] = bv;
    for (var j = 0; j < bangkitucoso.length; j++) // max j = 8
    {
        var marthaythe = bangkitucoso[j][1].split('.'); // tach cac chuoi co dau thanh tung phan tu rieng biet
        for (var i = 0; i < marthaythe.length; i++)
        {
            markhongdau[i + 1] = mThayThe(markhongdau[i], marthaythe[i], bangkitucoso[j][0]);
            markhongdau[0] = markhongdau[i + 1].toLowerCase();
        }
    }

    return markhongdau[0];
}
function mThayThe(ccha, cbithay, cthaythe)
{
    var ccon = "/" + cbithay + "/gi";
    return ccha.replace(eval(ccon), cthaythe);
}

var hnWindow;
var width, height, left, top, styleStr;
function XemHinh(imgId) {
    width = "650";
    height = "656";
    left = (screen.width / 2) - width / 2;
    //left = 20;
    top = (screen.height / 2) - height / 2;
    //top = ((screen.height / 2) - height / 2);
    styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=0,copyhistory=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',screenX=' + left + ',screenY=' + top;
    hnWindow = window.open('popup.jsp?id=' + imgId + '&ran=' + (new Date()).getTime(), "hnWindow", styleStr);
    hnWindow.focus();
}

function XemAlbum(imgId) {
    width = "650";
    height = "656";
    left = (screen.width / 2) - width / 2;
    //left = 20;
    top = (screen.height / 2) - height / 2;
    //top = ((screen.height / 2) - height / 2);
    styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=0,copyhistory=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',screenX=' + left + ',screenY=' + top;
    hnWindow = window.open('popup-a.jsp?id=' + imgId + '&ran=' + (new Date()).getTime(), "hnWindow", styleStr);
    hnWindow.focus();
}

var keepIt = false;

function MM_preloadImages() { //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i,j = d.MM_p.length,a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
    }
}

function changeSelectCate(newCate, cateName, jsp, status) {
    var current = document.getElementById('select-cate');
    var currentName = document.getElementById('select-cate-name');
    var currentJsp = document.getElementById('select-jsp');
    var currentStatus = document.getElementById('select-status');
    var html, nhtml;
    if (newCate != '') {
        var newC = document.getElementById(newCate);
        html = '<a class="scategory" ' +
               'onclick="return false;"' +
               'href="#">' + cateName +
               '</a>';
        if (status == '2') {
            html += '<img src="../images/cate/new.gif" alt=""/>';
        } else if (status == '3') {
            html += '<img src="../images/cate/hot.gif" alt=""/>';
        }
        newC.innerHTML = html;
    }
    var newStatus;
    if (currentStatus.value == 'undefined') {
        newStatus = '1';
    } else {
        newStatus = currentStatus.value;
    }
    if (current.value != '') {
        nhtml = '<a class="category" ' +
                'onclick="changeSelectCate(\'' + current.value + '\',\'' + currentName.value + '\',\'' + currentJsp.value + '\',\'' + newStatus + '\');displayItems(\'' + currentJsp.value + '\',\'' + current.value + '\',\'\',\'\',\'\');return false;"' +
                'href="#">' + currentName.value +
                '</a>';

        if (newStatus == '2') {
            nhtml += '<img src="../images/cate/new.gif" alt=""/>';
        } else if (newStatus == '3') {
            nhtml += '<img src="../images/cate/hot.gif" alt=""/>';
        }

        var oldC = document.getElementById(current.value);

        oldC.innerHTML = nhtml;
    }
    current.value = newCate;
    currentName.value = cateName;
    currentJsp.value = jsp;
    currentStatus.value = status;
}

var scrollable = true;
var loading;
var pageText = new Object();
var lastView;
var lastSortBy = '';
var now;
function processStateChange(text) {
    document.getElementById("listImage").innerHTML = text;
    hideLoading();
    pageText[lastView] = text;
    window.scroll(0, 950);
    var titleValue = document.getElementById('titleValue');
    if ((null != titleValue) || (titleValue == 'undefined')) {
        document.title = titleValue.value;
    } else {
        document.title = 'Siêu thị hình nền HOT nhất dành cho điện thoại di động. Uy tín và chất lượng nhất Việt Nam!';
    }
}

function showLoading() {
    loading = document.getElementById('loading');
    loading.style.visibility = 'visible';
    loading.style.display = 'inline';
    loading.style.left = '';
    loading.style.zIndex = '20';
}

var alertTimerId = -1;
function hideLoading() {
    loading = document.getElementById('loading');
    loading.style.visibility = 'hidden';
    loading.style.left = '-350px';
    loading.style.zIndex = '0';

    if (alertTimerId > -1) {
        clearTimeout(alertTimerId);
    }
    alertTimerId = setTimeout("checkImages()", 1250);
}

function IsImageOk(img) {
    if (true)return true;
    try {
        if (!img.complete) {
            return false;
        }

        if ((typeof img.naturalWidth != "undefined")
                && (img.naturalWidth == 0)) {
            return false;
        }

        return true;
    } catch(e) {
        return true;
    }
}

function checkImages() {
    if (!document.images) return;
    var failCount;
    failCount = 0;
    var newImg;
    for (var i = 0; i < document.images.length; i++) {
        if (!IsImageOk(document.images[i])) {
            newImg = new Image();
            newImg.src = document.images[i].src;
            newImg.alt = document.images[i].alt;
            document.images[i] = newImg;
            failCount = failCount + 1;
        }
    }
    if (failCount > 0) {
        alertTimerId = setTimeout("checkImages()", 1250);
    }
}

function displayItems(jsp, cate, sortBy, page, searchStr, lId) {
    cancel();
    hideddrivetip();

    var params;
    params = 'cate=' + cate;
    params += '&page=' + page;
    params += '&sortBy=' + sortBy;
    searchStr = mLocDau(searchStr);
    searchStr = encodeURIComponent(searchStr);
    params += '&search=' + searchStr;

    var compactAdd;
    compactAdd = "#";
    lastView = '';
    if (jsp != '') {
        compactAdd += 'j=' + jsp;
        lastView += jsp;
    }
    if (cate != '') {
        compactAdd += '&c=' + cate;
        lastView += cate;
    }
    if (sortBy != '') {
        compactAdd += '&s=' + sortBy;
        //Reload pageText
        if (lastSortBy != sortBy) pageText = new Object();
        lastSortBy = sortBy;
    }
    if (page != '') {
        compactAdd += '&p=' + page;
        lastView += '&' + page;
    } else {
        lastView += '&1';
    }
    if (searchStr != '') {
        compactAdd += '&kw=' + searchStr;
        lastView += '&' + searchStr;
    }
    if ((arguments.length == 6) && (lId != '')) {
        document.getElementById(lId).href = compactAdd;
    } else {
        window.location = compactAdd;
    }

    var txt = pageText[lastView];
    if ((null != txt) && (txt.length > 0)) {
        document.getElementById("listImage").innerHTML = txt;
        hideLoading();

        window.scroll(0, 950);
        var titleValue = document.getElementById('titleValue');
        if ((null != titleValue) || (titleValue == 'undefined')) {
            document.title = titleValue.value + ' - Siêu thị hình nền HOT nhất dành cho điện thoại di động. Uy tín và chất lượng nhất Việt Nam!';
        } else {
            document.title = 'Siêu thị hình nền HOT nhất dành cho điện thoại di động. Uy tín và chất lượng nhất Việt Nam!';
        }
        return;
    }

    var url = getJsp(jsp);
    if (url.indexOf('?') < 1) {
        url = url + '?' + params;
    } else {
        url = url + '&' + params;
    }
    showLoading();
    call(url, null, processStateChange);
}

var jspMap = null;

function Onload() {
    var lc = window.location + '';
//    alert(lc);
    var id = lc.indexOf('#');
//    alert(id);
    if (id > 0) {
        var jsp, cate, sortBy, search, searchW, page, searchType, view;
        var pr = lc.substr(id + 1, (lc.length - id) - 1);
        var spls = pr.split('&');

        jsp = '';
        cate = '';
        sortBy = '';
        search = '';
        page = '';
        searchType = '';
        searchW = '';
        view = '';
        var sub1;
        var sub2;

        for (var i = 0; i < spls.length; i++) {
            id = spls[i].indexOf('=');
            if (id > 0) {
                sub1 = spls[i].substr(0, id);
                sub2 = spls[i].substr(id + 1, (spls[i].length - id) - 1);
                if (('j' == sub1) || ('jsp' == sub1))jsp = sub2;
                if (('c' == sub1) || ('cate' == sub1))cate = sub2;
                if (('s' == sub1) || ('sortBy' == sub1))sortBy = sub2;
                if (('kw' == sub1) || ('search' == sub1))search = sub2;
                if (('p' == sub1) || ('page' == sub1))page = sub2;
                if ('v' == sub1)view = sub2;
            }
        }
        jsp = getJsp(jsp);
        if (jsp != '') {
            var url;
            var params;
            lastView = jsp;
            params = 'cate=' + cate;
            if (cate != '') {
                lastView += cate;
            }
            params += '&page=' + page;
            if (page != '') {
                lastView += '&' + page;
            } else {
                lastView += '&1';
            }
            params += '&sortBy=' + sortBy;
            if (sortBy != '') {
                lastSortBy = sortBy;
            }

            params += '&search=' + search;
            if (search != '') {
                lastView += '&' + search;
            }
            params += '&searchType=' + searchType;
            if (jsp.indexOf('?') < 1) {
                url = jsp + '?' + params;
            } else {
                url = jsp + '&' + params;
            }
            showLoading();
            call(url, null, processStateChange);
            alertTimerId = setTimeout("checkImages()", 2000);
            return;
        }
    }

    hideLoading();
    alertTimerId = setTimeout("checkImages()", 2000);
}

function getJsp(jsp) {
    if (null == jspMap) {
        jspMap = new Object();
        jspMap['sc'] = 'show-cate.jsp';
        jspMap['t'] = 'show-cate.jsp?j=t';
        jspMap['a'] = 'album.jsp';
        jspMap['m'] = 'show-cate.jsp?j=m';
        jspMap['tt'] = 'show-cate.jsp?j=tt';
        jspMap['x'] = 'show-cate.jsp?j=x';
        jspMap['h'] = 'show-cate.jsp?j=h';
        jspMap['s'] = 'search.jsp';
        jspMap['hn'] = 'image.jsp?j=hn';
        jspMap['hd'] = 'image.jsp?j=hd';
        jspMap['lg'] = 'image.jsp?j=lg';
        jspMap['tnh'] = 'image.jsp?j=tnh';
        jspMap['g'] = 'gprs.jsp';
    }
    var result;
    result = jspMap[jsp];
    if (null != result) return result;

    return '';
}

function restoreMenu(idx) {
    if (idx == document.getElementById('main-menu').value) {
        document.getElementById('mn' + idx).style.color = 'gold';
    } else {
        document.getElementById('mn' + idx).style.color = 'white';
    }
}

function setMenu(idx) {
    document.getElementById('main-menu').value = idx + '';
    document.getElementById('searchType').value = idx + '';
    for (var i = 1; i <= 5; i++) {
        if (idx == i) {
            document.getElementById('mn' + i).style.color = 'gold';
        } else {
            document.getElementById('mn' + i).style.color = 'white';
        }
    }
}

function NChim(str) {
    var whitespace = ' \n\r\t\f';
    var counter;
    counter = 0;
    for (var i = 0; i < str.length; i++) {
        if (whitespace.indexOf(str.charAt(i)) == -1) {
            str = str.substring(i);
            break;
        }
        counter++;
    }
    if (counter == str.length)return '';

    for (i = str.length - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) == -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return whitespace.indexOf(str.charAt(0)) == -1 ? str : '';
}


function showVote(newVote, sId) {
    var elm;
    for (var i = 1; i <= 5; i++) {
        elm = document.getElementById(sId + '_' + i);
        elm.className = ((i <= newVote) ? 'saocam' : 'saoden');
    }
}

function restoreVote(originVote, sIdh) {
    var elm;
    for (var i = 1; i <= 5; i++) {
        elm = document.getElementById(sIdh + '_' + i);
        elm.className = ((i <= originVote) ? 'saovang' : 'saoden');
    }
}

function showResult(text) {
    var result = text.split(',');
    if (result.length == 2) {
        var voteStar = NChim(result[0]);
        var voteCount = NChim(result[1]);
        document.getElementById('voteImg').innerHTML = '<table><tr><td class="saovang' + voteStar + '"><img src="../images/spacer.gif" alt=""/></td></tr></table>';
        document.getElementById('voteCount').innerHTML = '&nbsp;(' + voteCount + ' lượt)';
        setTimeout("alert('Cảm ơn bạn đã đánh giá!')", 500);
    }
}

function sendVote(v, sid) {
    document.getElementById('voteImg').innerHTML = '<img src="../images/vote/loading1.gif" alt="Đang xử lý..." border="0"/>';
    call('vote.jsp?v=' + v + '&sid=' + sid, null, showResult);
}

function sendAlbumVote(v, sid) {
    document.getElementById('voteImg').innerHTML = '<img src="../images/vote/loading1.gif" alt="Đang xử lý..." border="0"/>';
    call('vote.jsp?a=1&v=' + v + '&sid=' + sid, null, showResult);
}

function clear(cid) {
    alert(cid);
    var e = document.getElementById(cid);
    e.value = '';
    e.focus();
}

//0: System error
//1: Success
//2: Name too large
//3: Comment too large
//4: Name null
//5: Comment null
function showCmResult(text) {
    var result = NChim(text);
    var commentResult = document.getElementById('commentResult');
    var enableSend;
    enableSend = true;
    if (result == '1') {
        commentResult.innerHTML = '<span class="trang11">Lời bình của bạn đã được gửi thành công!</span>';
        document.getElementById('comment').value = '';
    } else if (result == '2') {
        commentResult.innerHTML = '<span class="error">Tên người gửi quá dài<span>';
        document.getElementById('commenter').focus();
        document.getElementById('commenter').select();
    } else if (result == '3') {
        commentResult.innerHTML = '<span class="error">Lời bình quá dài<span>';
        document.getElementById('comment').focus();
        document.getElementById('comment').focus();
    } else if (result == '4') {
        commentResult.innerHTML = '<span class="error">Chưa nhập người gửi<span>';
        document.getElementById('commenter').focus();
        document.getElementById('commenter').select();
    } else if (result == '5') {
        commentResult.innerHTML = '<span class="error">Chưa nhập lời bình<span>';
        document.getElementById('comment').focus();
        document.getElementById('comment').focus();
    } else if (result == '6') {
        commentResult.innerHTML = '<span class="error">Bạn chỉ được phép gửi 3 lời bình cho 1 bài<span>';
        enableSend = false;
    } else {
        commentResult.innerHTML = '<span class="error">Hiện tại hệ thống chưa sẵn sàng, mời bạn thử lại sau<span>';
    }

    document.getElementById('sendbt').enabled = enableSend;
}

function sendComment(songId) {
    var commentResult = document.getElementById('commentResult');
    commentResult.innerHTML = '<img src="../images/vote/loading1.gif" alt="Đang xử lý..." border="0"/>';
    var sendBt = document.getElementById('sendbt');
    sendBt.enabled = false;

    var commenter = document.getElementById('commenter').value;
    var comment = document.getElementById('comment');

    var url;
    url = 'commenter.jsp?songId=' + songId +
          '&commenter=' + encodeURIComponent(commenter) +
          '&comment=' + encodeURIComponent(comment.value);

    call(url, null, showCmResult);
}

function sendAlbum(songId) {
    var commentResult = document.getElementById('commentResult');
    commentResult.innerHTML = '<img src="../images/vote/loading1.gif" alt="Đang xử lý..." border="0"/>';
    var sendBt = document.getElementById('sendbt');
    sendBt.enabled = false;

    var commenter = document.getElementById('commenter').value;
    var comment = document.getElementById('comment');

    var url;
    url = 'commenter.jsp?a=1&songId=' + songId +
          '&commenter=' + encodeURIComponent(commenter) +
          '&comment=' + encodeURIComponent(comment.value);

    call(url, null, showCmResult);
}

function checkInput() {
    var commenter = document.getElementById('commenter');
    var cmter = NChim(commenter.value);
    if ((cmter == '') || (cmter == 'Người gửi...')) {
        alert('Chưa nhập người gửi');
        commenter.value = '';
        commenter.focus();
        return false;
    }

    var comment = document.getElementById('comment');
    if (NChim(comment.value) == '') {
        alert('Chưa nhập lời bình');
        comment.focus();

        return false;
    }

    return true;
}

function showQuiz(quizId) {
    popup('quizResult.jsp?quizId=' + quizId);
}

function checkAndSubmit(theForm, quizId) {
    var chked;
    chked = false;
    var q;
    q = '';
    for (var i = 0; i < theForm.length; i++) {
        var e = theForm.elements[i];
        if ((e.type.toLowerCase() == "checkbox") && e.checked) {
            chked = true;
            if (q != '')q = q + ',';
            q += e.value;
            //e.checked = false;
        }
    }
    if (!chked) {
        alert('Hãy chọn một trong các mục trước khi biểu quyết');
        return false;
    }
    popup('quizing.jsp?quizId=' + quizId + '&q=' + q + '&ran=' + (new Date()).getTime());

    return true;
}

var quizWindow;

function popup(url) {
    width = "500";
    height = "220";
    left = (screen.width / 2) - width / 2;
    //left = 20;
    top = (screen.height / 2) - height / 2;
    //top = ((screen.height / 2) - height / 2);
    styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=0,copyhistory=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',screenX=' + left + ',screenY=' + top;
    quizWindow = window.open(url + '&ran=' + ((new Date()).getTime()), "QuizWindow", styleStr);

    quizWindow.focus();
}

function chooseElement(theForm, chooseId, single) {
    var chooseCb = document.getElementById(chooseId);
    if (chooseCb.checked && single) {
        for (var i = 0; i < theForm.length; i++) {
            var e = theForm.elements[i];
            if ((e.type.toLowerCase() == "checkbox") && (e.id != chooseId)) {
                e.checked = false;
            }
        }
    }
}

var gopyWindow;
function gopy() {
    width = "1004";
    height = "310";
    left = (screen.width / 2) - width / 2;
    top = (screen.height / 2) - height / 2;
    styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=0,copyhistory=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',screenX=' + left + ',screenY=' + top;
    gopyWindow = window.open('../jsps/gopy.jsp', "gopyWindow", styleStr);

    gopyWindow.focus();
}
