﻿function changeLanguage() {
    var url = location.href;
    if (url.indexOf("#") > 0) url = url.replace("#", "");
    if (url.indexOf("lang=en") > 0) {
        url=url.replace("lang=en", "lang=vn")
    }
    else if (url.indexOf("lang=vn") > 0) {
        url = url.replace("lang=vn", "lang=en")
    }
    else if (url.indexOf("aspx?")>0) {
        url += "&lang=en";
    }
    else {
        url += "?lang=en";
    }
    location.href=url;
}
function openwindow(url, width, height)
 {
  window.open (url,'_blank','resizable=1,location=0,status=0,scrollbars=1,width=' + width + ',height=' +height);
 }
 // Success=0, Error=1, Warning=2
 function showAlertMessage(containerid, msg, type) {
   
     switch (type) {
         case 0:
             document.getElementById(containerid).innerHTML = "<div class='alertboxscc'><div>" + msg + "</div></div>";
             break;
         case 1:
             document.getElementById(containerid).innerHTML = "<div class='alertboxerr'><div>" + msg + "</div></div>";
             break;
         case 2:
             document.getElementById(containerid).innerHTML = "<div class='alertboxwrn'><div>" + msg + "</div></div>"; ;
             break;
         default:
             break
     }
     window.scroll(0, 0);
     parent.scroll(0, 0);
 }
 
 function backToTop() {
     var x1 = x2 = x3 = 0;
     var y1 = y2 = y3 = 0;

     if (document.documentElement) {
         x1 = document.documentElement.scrollLeft || 0;
         y1 = document.documentElement.scrollTop || 0;
     }

     if (document.body) {
         x2 = document.body.scrollLeft || 0;
         y2 = document.body.scrollTop || 0;
     }

     x3 = window.scrollX || 0;
     y3 = window.scrollY || 0;

     var x = Math.max(x1, Math.max(x2, x3));
     var y = Math.max(y1, Math.max(y2, y3));

     window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));

     if (x > 0 || y > 0) {
         window.setTimeout("backToTop()", 25);
     }
 }
 
 function BlockUI(msg) {
     if (msg == null || msg == "") {
         jQuery.blockUI({
             message: '<table class="blockUI"><tr><td class="tdloading"></td></tr></table>',
             fadeIn: 0,
             fadeOut: 0,
             css: {
                 top: ($(window).height() - 16) / 2 + 'px',
                 left: ($(window).width() - 16) / 2 + 'px',
                 border: 'none'
             }
         });
     } else {
         jQuery.blockUI({
         message: '<table class="blockUI"><tr><td class="tdloading"></td></tr><tr><td><b>' + msg +'</b></td></tr></table>',
             fadeIn: 0,
             fadeOut: 0,
             css: {
                 top: ($(window).height() - 36) / 2 + 'px',
                 left: ($(window).width() - 36) / 2 + 'px',
                 border: 'none'
             }
         });
     }
 }
 function DivBlockUI(id) {
     $("#" + id).block({
         message: '<table class="blockUI"><tr><td class="tdloading"></td></tr><tr><td><b>Loading...</b></td></tr></table>',
         fadeIn: 1000,
         fadeOut: 1000,
         css: {
             top:'0px',   
             border: 'none'
         }
     });
 }
 function DivUnBlockUI(id) {
     $("#" + id).unblock();
 }
 function gup(name) {
     name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
     var regexS = "[\\?&]" + name + "=([^&#]*)";
     var regex = new RegExp(regexS);
     var results = regex.exec(window.location.href);
     if (results == null)
         return "";
     else
         return results[1];
 }

 function initHTMLArea(id) {
     $("#" + id).htmlarea({
         toolbar: [
                ["html"], ["bold", "forecolor", "italic", "underline", "strikethrough", "|", "subscript", "superscript"],
                ["increasefontsize", "decreasefontsize"],
                ["orderedlist", "unorderedlist"],
                ["indent", "outdent"],
                ["justifyleft", "justifycenter", "justifyright"],
                ["link", "unlink"], ["image", "horizontalrule"],
                ["p", "h1", "h2", "h3", "h4", "h5", "h6"],
                ["cut", "copy", "paste"]
                 , [{
                     // This is how to add a completely custom Toolbar Button
                     css: "image",
                     text: "Upload image",
                     action: function(btn) {
                         $("#" + id +"_divUploadBar").css("display", "none");
                         $("#" + id + "_divUploadBar").slideDown("slow");
                     }
                }]
           ]
           });
           var uploadBar = '<div style="clear:both;float:left;display:none;" id="' + id + '_divUploadBar">'
                            + '    <div style="float:left;width:420px;">'
                            + '	        <input type="file" class="' + id + '_inputfile" onchange="return IsValidFileExtension(\'' + id + '_txtfile\',\'' + id + '_divcontainer\',\'' + id + '_msgError\',\'' + id + '_btnUpload\')"'
                            + '            size="32" name="txtfile" id="' + id + '_txtfile" />'
                            + '         <div class="uploadbuttonbar">'
                            + '             <input type="button" class="btn" id="' + id + '_btnUpload"  onclick="UploadFile(\'' + id + '\',\'' + id + '_txtfile\',\'' + id + '_divcontainer\',\'' + id + '_msgError\',\'' + id + '_btnUpload\');" value="Upload" />'
                            + '             <input type="button" class="btn" onclick="CancelUploadImage(\'' + id + '_divUploadBar\');" value="Cancel" />'                            
                            + '         </div>'
                            + '    </div>'
                            + '    <div id="' + id + '_divcontainer" class="bg_table" style="display:none;float:left;clear:both;">'
                            + '        <div id="' + id + '_msgError" class="errMsg">'
                            + '            &nbsp</div>'
                            + '    </div>'
                            + '</div>'
        $("div.jHtmlArea div.ToolBar").append(uploadBar);
        $("div.jHtmlArea div.ToolBar ul li a.html").click(function() {
        obj(id + "_divUploadBar").style.display = "none";
        });
 }

 // --- Upload File --- // 
 function obj(id) {
     return document.getElementById(id);
 }

 function CancelUploadImage(id) {
     $("#" + id).slideUp("slow");
 }

 function IsValidFileExtension(fileID, divContainer, divErrorMessage, uploadButtonID) {

     var filename = obj(fileID).value;
     var isOK = false;
     if (filename != "") {
         var ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length).toLowerCase();
         var validExtension = "|bmp|dib|gif|jpg|jpeg|jpe|jfif|tif|tiff|png|";

         isOK = validExtension.indexOf("|" + ext + "|") >= 0 ? true : false;
         obj(divContainer).style.display = isOK ? 'none' : '';
         if (!isOK) {
             showAlertMessage(divErrorMessage, "Sorry, You have chosen an invalid file extension. Please choose an image file.", 1);
         }
         else {
             obj(divErrorMessage).innerHTML = "";
             isOK = true;
         }
         obj(uploadButtonID).disabled = isOK ? false : true;
     }
     return isOK;
 }

 function UploadFile(editerid, fileID, divContainer, divErrorMessage, uploadButtonID) {
     if (IsValidFileExtension(fileID, divContainer, divErrorMessage, uploadButtonID)) {
         BlockUI("Loading...");
         $.ajaxFileUpload
            (
                {
                    url: '../Handlers/ImageUpload.ashx',
                    secureuri: false,
                    fileElementId: fileID,
                    dataType: 'html',
                    success: function(data, status) {
                        var dataMessage = data.split('|');
                        var isError = dataMessage[0] == "True" ? true : false;
                        var errorMessage = dataMessage[1];
                        var imageUrl = dataMessage[2];
                        obj(divContainer).style.display = isError ? '' : 'none';
                        if (isError) {
                            showAlertMessage(divErrorMessage, errorMessage, 1);
                        }
                        else {
                            $("#" + editerid).htmlarea("image", "http://www.kafabric.com.vn/Assest/" + imageUrl);
                        }
                        jQuery.unblockUI();
                    }
                }
            )
     }
 }
 // --- End Upload File --- //
 
 
 /*Global function*/
 function roundNumber(num, dec) {
     var result = Math.round(Math.round(num * Math.pow(10, dec + 1)) / Math.pow(10, 1)) / Math.pow(10, dec);
     return result;
 }

 function toString(obj) {
     if (obj == null)
         return "";
     else return obj.toString();
 }
 
 function CheckInputOnlyNumber(e)
 {
     var code = "";
     if (e.which)
         code = e.which;
     else if (e.keyCode)
         code = e.keyCode;
     if (code == 69 || code == 101 || code == 39) //e or E or "-"
         return true;
     if ((code < 48 || code > 57) && code != 8 && code != 13 && code != 0 && code != 46 && code != 9)
         return false;
     return true;
 }

 var Url = {

     // public method for url encoding
     encode: function(string) {
         return escape(this._utf8_encode(string));
     },

     // public method for url decoding
     decode: function(string) {
         return this._utf8_decode(unescape(string));
     },

     // private method for UTF-8 encoding
     _utf8_encode: function(string) {
         string = string.replace(/\r\n/g, "\n");
         var utftext = "";

         for (var n = 0; n < string.length; n++) {

             var c = string.charCodeAt(n);

             if (c < 128) {
                 utftext += String.fromCharCode(c);
             }
             else if ((c > 127) && (c < 2048)) {
                 utftext += String.fromCharCode((c >> 6) | 192);
                 utftext += String.fromCharCode((c & 63) | 128);
             }
             else {
                 utftext += String.fromCharCode((c >> 12) | 224);
                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                 utftext += String.fromCharCode((c & 63) | 128);
             }

         }

         return utftext;
     },

     // private method for UTF-8 decoding
     _utf8_decode: function(utftext) {
         var string = "";
         var i = 0;
         var c = c1 = c2 = 0;

         while (i < utftext.length) {

             c = utftext.charCodeAt(i);

             if (c < 128) {
                 string += String.fromCharCode(c);
                 i++;
             }
             else if ((c > 191) && (c < 224)) {
                 c2 = utftext.charCodeAt(i + 1);
                 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                 i += 2;
             }
             else {
                 c2 = utftext.charCodeAt(i + 1);
                 c3 = utftext.charCodeAt(i + 2);
                 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                 i += 3;
             }

         }

         return string;
     }
 }

 function renderPager(totalPage, currentPage) {
     var pagerHTML = "";
 }
