﻿
var divhide_arr = new Array();
//var dragDropObj = new DHTMLgoodies_dragDrop();

// HELPER
function alertExclam(str, title) {
    //alert("เตือนอัศเจรีย์");
    if (title == null) {
        alert("<div><br/><table align='center'><tr><td><img src='../images/SSO ico/icon_Exclam.png'/>&nbsp;&nbsp;</td>" +
				"<td id='headBlackM'>" + str + "</td></tr></table></div>", '');
    }
    else {
        alert("<div><br/><table align='center'><tr><td><img src='../images/SSO ico/icon_Exclam.png'/>&nbsp;&nbsp;</td>" +
				"<td id='headBlackM'>" + str + "</td></tr></table></div>", title);
    }
}

var siteMapArrowMode = 0;

function ShowHideDiv(divObj) {

    if (divObj == "toggle-nav") {
        var src = document.getElementById(divObj + "-arrow").src;
        //alert('src from div : ' + src);
        if (siteMapArrowMode == 0) {
            siteMapArrowMode = 1;
           
            src = getBaseURL() + "Content/images/footer/arrow-down.png";

        } else {
            siteMapArrowMode = 0;
            src = getBaseURL() + "Content/images/footer/arrow-up.png";
        }

        //alert('src : ' + src);
        $('#' + divObj + "-arrow").attr("src", src);
    }

    
    $('#' + divObj).slideToggle(500);

}

function ToUnicode(theString) {
    var unicodeString = '';
    for (var i = 0; i < theString.length; i++) {
        var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
        while (theUnicode.length < 4) {
            theUnicode = '0' + theUnicode;
        }
        theUnicode = '\\u' + theUnicode; unicodeString += theUnicode;
    }
    return unicodeString;
}

function SetCookie(name, value, days) {
    var now = new Date();
    var expDate = new Date();
    if (days == null || days == 0) days = 1;
    //create date after no of "days" from now
    expDate.setTime(now.getTime() + 3600000 * 24 * days);

    //create cookie with name, value and expire date
    document.cookie = name + "=" + escape(value) + ";expires=" + expDate.toUTCString();
}

function ReadCookie(name) {
    if (name == "") return "";
    var strCookie = " " + document.cookie;
    var idx = strCookie.indexOf(" " + name + "=");
    if (idx == -1) idx = strCookie.indexOf(";" + name + "=");
    if (idx == -1) return "";

    var idx1 = strCookie.indexOf(";", idx + 1);
    if (idx1 == -1) idx1 = strCookie.length;
    return unescape(strCookie.substring(idx + name.length + 2, idx1));
}

function parseUri(str) {
    var o = parseUri.options,
				m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
				uri = {},
				i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};

// AJAX
function initRequest(url) {
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.open("POST", url, true);
    return req;
}

function goToPage(url) {
    window.location.href = url;
}

//New content page
function content_cancel() {
    window.location.href = getBaseURL () + "Dashboard/ListContent";
}

function content_save(contentId, forcePublish) {

    if (contentId == undefined || contentId == null || contentId == '') {
        //contentId = '-1';
        return;
    }

    var h_title = ToUnicode( document.getElementById('h_title').value );
    var h_byline = ToUnicode( document.getElementById('h_byline').value );
    //var h_body = document.getElementById('h_body').value;

    //alert("h_body.value = " + h_body);
    
    //if (h_body == undefined || h_body == '') {
        var h_body = CKEDITOR.instances.h_body.getData();
        //alert("h_body.ck = " + h_body);
    //}

        //h_body = escape(h_body);

        h_body = ToUnicode(h_body);
        //h_body = h_body

    var h_design = //document.getElementById('h_radDsgn').value;
               ToUnicode( document.getElementById('h_hdRadDsgn').value );
    var h_newstype = ToUnicode(document.getElementById('sel_newsType').value);
    var h_tags = ToUnicode(document.getElementById('h_tags').value);
    var h_date = document.getElementById('h_datepicker').value;
    var h_allowRead = document.getElementById('sel_allowRole').value;
    var h_comment = document.getElementById('h_chkComment').value;
    var h_poll = document.getElementById('h_chkPoll').value;
    var h_pollTopic = ToUnicode(document.getElementById('h_pollTopic').value);
    var h_pollAns1 = ToUnicode(document.getElementById('h_pollAns1').value);
    var h_pollAns2 = ToUnicode(document.getElementById('h_pollAns2').value);
    var h_pollAns3 = ToUnicode(document.getElementById('h_pollAns3').value);

    var h_uuid = document.getElementById('h_uuid').value;
  
    var url = getBaseURL() + 'Async/SaveContentAsync?h_title=' + h_title + '&h_byline=' + h_byline + '&h_body=' + h_body +
                                            '&h_design=' + h_design + '&h_newstype=' + h_newstype + '&h_tags=' + h_tags +
                                            '&h_date=' + h_date + '&h_allowRead=' + h_allowRead + '&h_comment=' + h_comment +
                                            '&h_poll=' + h_poll + '&h_pollTopic=' + h_pollTopic + '&h_pollans1=' + h_pollAns1 +
                                            '&h_pollans2=' + h_pollAns2 + '&h_pollans3=' + h_pollAns3 + '&contentId=' + contentId +
                                            '&forcePublish=' + forcePublish + '&uuid=' + h_uuid + '&tags=' + h_tags;
                                                     
//    var areq = initRequest(url);
//    areq.onreadystatechange = callback_content_save;
//    areq.send(null);

    $.ajax(
    {
        type: "POST",
        url: getBaseURL() + "Async/SaveContentAsync",
        data: 'h_title=' + h_title + '&h_byline=' + h_byline + '&h_body=' + h_body +
                                            '&h_design=' + h_design + '&h_newstype=' + h_newstype + '&h_tags=' + h_tags +
                                            '&h_date=' + h_date + '&h_allowRead=' + h_allowRead + '&h_comment=' + h_comment +
                                            '&h_poll=' + h_poll + '&h_pollTopic=' + h_pollTopic + '&h_pollans1=' + h_pollAns1 +
                                            '&h_pollans2=' + h_pollAns2 + '&h_pollans3=' + h_pollAns3 + '&contentId=' + contentId +
                                            '&forcePublish=' + forcePublish + '&uuid=' + h_uuid + '&tags=' + h_tags,
        success: function (result) {
            alert('จัดเก็บสำเร็จ');
            window.location.href = getBaseURL() + "Dashboard/ListContent";
        },
        error: function (req, status, error) {
            alert("เกิดข้อผิดพลาดระหว่างการจัดเก็บ กรุณาติดต่อผู้ดูแลระบบ");
        }
    });

}

function callback_content_save() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            alert('จัดเก็บสำเร็จ');
            window.location.href = getBaseURL()+ "Dashboard";
        } else if (req.status == 500) {
            alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        } else if (req.status == 404) {
            alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        } else {
            // alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        }
    }

}

function content_delete(contentId) {

    if (confirm("คุณต้องการลบรายการดังกล่าว ?")) {
        var url = getBaseURL() + 'Async/DeleteContentAsync?contentId=' + contentId;

        var areq = initRequest(url);
        areq.onreadystatechange = callback_content_delete;
        areq.send(null);
    }
}

function callback_content_delete() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            window.location.href = getBaseURL() + "Dashboard/ListContent";
        } else if (req.status == 500) {
            alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        } else if (req.status == 404) {
            alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        } else {
            // alert('ไม่สามารถติดต่อ WebService กรุณาติดต่อผู้ดูแลระบบ');
        }
    }

}

function content_search(searchTerm) {
    //var url = getBaseURL() + 'Async/SearchContentAsync?contentId=' + contentId;
    var url = getBaseURL() + 'Dashboard/Search?searchTerm=' + ToUnicode(searchTerm);
    window.location.href = url;

    //var areq = initRequest(url);
    //areq.onreadystatechange = callback_content_search;
    //areq.send(null);
}

function content_searchTermAndCategory(searchTerm) {
    //var url = getBaseURL() + 'Async/SearchContentAsync?contentId=' + contentId;
    var sel_cat1 = document.getElementById('sel_cat1').value;
    var sel_cat2 = document.getElementById('sel_cat2').value;
    var sel_cat3 = document.getElementById('sel_cat3').value;

    var url = getBaseURL() + 'Dashboard/Search?searchTerm=' + ToUnicode(searchTerm)+'&sel1='+sel_cat1+'&sel2='+sel_cat2+'&sel3='+sel_cat3;
    window.location.href = url;

    //var areq = initRequest(url);
    //areq.onreadystatechange = callback_content_search;
    //areq.send(null);
}

function callback_content_search() {

}

function asset_delete(name) {
    var companyId = document.getElementById('h_uuid').value;
    $.ajax(
    {
        type: "POST",
        url: getBaseURL() + "Async/AssetDelete",
        data: 'name=' + name,
        success: function (result) {

            ListDirectory(companyId, "photos");
            ListDirectory(companyId, "videos");
            ListDirectory(companyId, "sounds");
            ListDirectory(companyId, "docs");

        },
        error: function (req, status, error) {
            alert("Error");
        }
    });
}

var src_arr = new Array();
var srcstr = "";

function ListDirectoryReadOnly(uuid, type, ntype) {
    if (ntype == undefined || ntype == '') {
        ntype = 'Content';
    }

    $.ajax(
    {
        type: "GET",
        url: getBaseURL() + "Async/ListDirectory",
        data: 'uuid=' + uuid + '&type=' + type + '&ntype=' + ntype,
        success: function (result) {
            src_arr = new Array();
            ShowListReadOnly(result, type, ntype);
            //window.location.href = "/Dashboard";

            src_arr = srcstr.split("|");
            //alert('src_len : ' + src_arr.length);
            /*
            if (dragDropObj != undefined && dragDropObj != null) {
                for (var i = 0; i < src_arr.length - 1; i++) {
                    //alert('photo id : ' + src_arr[i]);
                    dragDropObj.addSource(src_arr[i], true);
                }
                dragDropObj.init();
            }
            */
        },
        error: function (req, status, error) {
            //alert("Error");
        }
    });
}


function ListDirectory(uuid, type, ntype, override, fnc) {
    if (override == undefined || override == null) {
        override = false;
    }

    if (ntype == undefined || ntype == '') {
        ntype = 'Content';
    }

    $.ajax(
    {
        type: "GET",
        url: getBaseURL() + "Async/ListDirectory",
        data: 'uuid=' + uuid + '&type=' + type + '&ntype=' + ntype,
        success: function (result) {
            src_arr = new Array();
            if (override != true) {
                ShowList(result, type, ntype);
            }

            if (fnc != null && fnc != undefined) {
                fnc;
            }
            //window.location.href = "/Dashboard";

            src_arr = srcstr.split("|");
            //alert('src_len : ' + src_arr.length);

            if (dragDropObj != undefined && dragDropObj != null) {
                for (var i = 0; i < src_arr.length - 1; i++) {
                    //alert('photo id : ' + src_arr[i]);
                    dragDropObj.addSource(src_arr[i], true);
                }
                dragDropObj.init();
            }
        },
        error: function (req, status, error) {
            //alert("Error");
        }
    });
}

function ShowListReadOnly(result, type, ntype) {
    //alert('ntype == ' + ntype);

    var photos = result.photos;
    var uuid = document.getElementById('h_uuid').value;
    var imgDiv = '<b>ไม่มีรูปภาพในระบบ</b><br/>';
    var urlPath = '/Upload/' + ntype + '/' + uuid;

    var photoPath = urlPath + '/Photos/';
    if (type == 'videos') {
        photoPath = urlPath + '/VDOs/';
    } else if (type == 'sounds') {
        photoPath = urlPath + '/Sounds/';
    } else if (type == 'docs') {
        photoPath = urlPath + '/Docs/';
    }

    var photo_arr = new Array();


    photo_arr = photos.split("|");
    //alert('result in ShowPhotos (photos) : ' + photos + ", size : " + photo_arr.length);
    for (var i = 0; i < photo_arr.length; i++) {
        if (i == 0) {
            imgDiv = '';
        }

        var photoName = photo_arr[i];
        if (photoName != undefined && photoName != null && photoName != '') {
            //alert('photo : ' + i + ' : ' + photoName);
            var name = photoPath + photoName;

            if (type == 'photos') {
                var srcId = type + i;
                src_arr[srcId] = srcId;
                srcstr += srcId + "|";

                imgDiv +=
                    '<table width="100%">' +
                        '<tr>' +
                            '<td>' +
                                '<img width="150px" src="' + getBaseURL() + name.substring(1) + '" alt="' + photoName + '" title="' + photoName + '"  border="0" id="' + srcId + '" draggable="true" />' +
                             '</td>' +
                             '<td>' +
                                //'<img src="' + getBaseURL() + 'Content/images/icon/btn-delete.png" onclick="asset_delete(\'' + name + '\')" style="vertical-align:middle;cursor:pointer;" border="0" />' +

                             '</td>' +
                         '</tr>' +
                     '</table>' +
                     '<br/>';

            } else if (type == 'videos' || type == 'sounds') {

                imgDiv +=
                        '<a href="' + name + '">' +
                        '<img src="' + getBaseURL() + 'Content/images/shelf/cd.png" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';

            } else if (type == 'docs') {
                if (name.indexOf(".pdf") != -1) {
                    imgDiv +=
                            '<a href="' + name + '">' +
                            '<img width="75px" src="' + getBaseURL() + 'Content/images/icon/doc/logo_pdf_75x75.jpg" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';
                } else {
                    imgDiv +=
                            '<a href="' + name + '">' +
                            '<img width="150px" src="' + getBaseURL() + 'Content/images/shelf/doc_plain.png" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';
                }
            }
        }
    }

    var div_pv = 'div_pv_photo';
    if (type == 'videos') {
        div_pv = 'div_pv_vdo';
    } else if (type == 'sounds') {
        div_pv = 'div_pv_sound';
    } else if (type == 'docs') {
        div_pv = 'div_pv_doc';
    }

    //alert('imgDiv : ' + imgDiv);
    document.getElementById(div_pv).innerHTML = imgDiv;
}

function ShowList(result, type, ntype) {
    //alert('ntype == ' + ntype);

    var photos = result.photos;
    var uuid = document.getElementById('h_uuid').value;
    var imgDiv = '<b>ไม่มีรูปภาพในระบบ</b><br/>';
    var urlPath = '/Upload/' + ntype + '/' + uuid;

    var photoPath = urlPath + '/Photos/';
    if (type == 'videos') {
        photoPath = urlPath + '/VDOs/';
    } else if (type == 'sounds') {
        photoPath = urlPath + '/Sounds/';
    } else if (type == 'docs') {
        photoPath = urlPath + '/Docs/';
    }

    var photo_arr = new Array();
    
    photo_arr = photos.split("|");
    //alert('result in ShowPhotos (photos) : ' + photos + ", size : " + photo_arr.length);
    for (var i = 0; i < photo_arr.length; i++) {
        if (i == 0) {
            imgDiv = '';
        }

        var photoName = photo_arr[i];
        if (photoName != undefined && photoName != null && photoName != '') {
            //alert('photo : ' + i + ' : ' + photoName);
            var name = photoPath + photoName;

            if (type == 'photos') {
                var srcId = type + i;
                src_arr[srcId] = srcId;
                srcstr += srcId + "|";

                imgDiv +=
                    '<table width="100%">' +
                        '<tr>' +
                            '<td>' +
                                '<img width="150px" src="' + getBaseURL() + name.substring(1) + '" alt="' + photoName + '" title="' + photoName + '"  border="0" id="' + srcId + '" draggable="true" />' +
                             '</td>' +
                             '<td>' +
                                '<img src="' + getBaseURL() + 'Content/images/icon/btn-delete.png" onclick="asset_delete(\'' + name + '\')" style="vertical-align:middle;cursor:pointer;" border="0" />' +
                                
                             '</td>' +
                         '</tr>' +
                     '</table>' +
                     '<br/>';

            } else if (type == 'videos' || type == 'sounds') {

                imgDiv +=
                        '<a href="' + name + '">' +
                        '<img src="' + getBaseURL() + 'Content/images/shelf/cd.png" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';

            } else if (type == 'docs') {
                if (name.indexOf(".pdf") != -1) {
                    imgDiv +=
                            '<a href="' + name + '">' +
                            '<img width="75px" src="' + getBaseURL() + 'Content/images/icon/doc/logo_pdf_75x75.jpg" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';
                } else {
                    imgDiv +=
                            '<a href="' + name + '">' +
                            '<img width="150px" src="' + getBaseURL() + 'Content/images/shelf/doc_plain.png" alt="' + photoName + '" title="' + photoName + '"  border="0"/></a><br/>';
                }
            }
        }
    }

    var div_pv = 'div_pv_photo';
    if (type == 'videos') {
        div_pv = 'div_pv_vdo';
    } else if (type == 'sounds') {
        div_pv = 'div_pv_sound';
    } else if (type == 'docs') {
        div_pv = 'div_pv_doc';
    }

    //alert('imgDiv : ' + imgDiv);
    document.getElementById(div_pv).innerHTML = imgDiv;

}

function show_photo() {
    
    $('#div_pv_photo').slideDown(500);
    $('#div_pv_vdo').slideUp(500);
    $('#div_pv_sound').slideUp(500);
    $('#div_pv_doc').slideUp(500);

    document.getElementById('li_photo').setAttribute("class", "current");
    document.getElementById('li_vdo').setAttribute("class", "");
    document.getElementById('li_sound').setAttribute("class", "");
    document.getElementById('li_doc').setAttribute("class", "");
}

function show_vdo() {
    $('#div_pv_vdo').slideDown(500);
    $('#div_pv_photo').slideUp(500);
    $('#div_pv_sound').slideUp(500);
    $('#div_pv_doc').slideUp(500);

    document.getElementById('li_photo').setAttribute("class", "");
    document.getElementById('li_vdo').setAttribute("class", "current");
    document.getElementById('li_sound').setAttribute("class", "");
    document.getElementById('li_doc').setAttribute("class", "");
}

function show_sound() {
    $('#div_pv_sound').slideDown(500);
    $('#div_pv_photo').slideUp(500);
    $('#div_pv_vdo').slideUp(500);
    $('#div_pv_doc').slideUp(500);
    

    document.getElementById('li_photo').setAttribute("class", "");
    document.getElementById('li_vdo').setAttribute("class", "");
    document.getElementById('li_sound').setAttribute("class", "current");
    document.getElementById('li_doc').setAttribute("class", "");

}

function show_doc() {
    $('#div_pv_doc').slideDown(500);
    $('#div_pv_photo').slideUp(500);
    $('#div_pv_vdo').slideUp(500);
    $('#div_pv_sound').slideUp(500);


    document.getElementById('li_photo').setAttribute("class", "");
    document.getElementById('li_vdo').setAttribute("class", "");
    document.getElementById('li_sound').setAttribute("class", "");
    document.getElementById('li_doc').setAttribute("class", "current");

}

function enablePoll(flag) {
    //alert('enablePoll ? : ' + flag);
    if (flag == true) {
        $('#div_pollTopic').slideDown(500);
    } else {
        $('#div_pollTopic').slideUp(500);
    }
}

function changeFont(div, multiply) {
    //var sz = document.body.style.fontSize;
    //if (sz == '') sz = 10; //default font size

    //var size = parseFloat(sz) + (multiply * 0.2) + "px";
    var size = multiply;
    document.body.style.fontSize = size;

}

function changeBodyBackground(bgimg) {
    //alert('bg = ' + bgimg);
    //document.body.background = bgimg;
    //$("html").css("background", "url('" + bgimg + "')");
    document.body.style.backgroundImage = "url(" + bgimg + ")";
}

function clearSelectBox(selObjId) {
    var obj = document.getElementById(selObjId);
    var len = obj.options.length;
    for (var i = len; i > 0; i--) {
        obj.options[i] = null;
    }
}

function fillSelectBox(sel_id, c_arr) {
    for (var i = 0; i < c_arr.length; i++) {
        document.getElementById(sel_id).options[i] = new Option(c_arr[i].desc, c_arr[i].value);
    }
}

var baseURL = "";

function getBaseURL() {
    baseURL = document.getElementById('h_baseURL').value;
    return baseURL;
}


