function create_loading(){ 
    if($("div#loadingStatus").length == 0){$("body").append("<div id='loadingStatus'></div>");$("div#loadingStatus").click(function(){$(this).hide("fast");})}
    else{$("div#loadingStatus").show("fast");} 
}

function loading_init(){ 
    create_loading();
    $("div#loadingStatus").html("<div class='loading_init'><i class=\"fa fa-spinner\"></i> <blink>Loading...</blink></div>");     
    var button = $("button[name='submit']");
    if(button.length > 0){   
        var span = $(button).find("span");
        if($(span).length == 0){
            span = $("<span><i class=\"fa fa-spinner\"></i></span>");
            $(button).append(span);
        }
        else{$(span).find("i").attr("class","fa fa-spinner");}
    }    
}
function loading_error(txt){ 
    create_loading();
    $("div#loadingStatus").html("<div class='loading_error'><i class=\"fa fa-exclamation-triangle\"></i> "+txt+"</div>");
    var span = $("button[name='submit']").find("span");
    if(span.length > 0){
        $(span).find("i").attr("class","fa fa-exclamation-triangle");
    }
    window.setTimeout("rm_loading()", 10000);
    window.setTimeout("rm_loadingBtn()", 4000);
         
}
function loading_success(){
    create_loading(); 
    $("div#loadingStatus").html("<div class='loading_success'><i></i><i class=\"fa fa-check\"></i> Success!</div>");
    var span = $("button[name='submit']").find("span");
    if(span.length > 0){
        $(span).find("i").attr("class","fa fa-check-square-o");
    }
    window.setTimeout("rm_loading()", 500);  
    window.setTimeout("rm_loadingBtn()", 4000);
}

function rm_loading(){ $("div#loadingStatus").remove();}
function rm_loadingBtn(){$("button[name='submit']").find("span").remove();}

function loading_proccessBar(){ 
    create_loading();
    $("div#loadingStatus").html('<div class=\'loading_proccess\'><progress id="progressBar" value="0" max="100" style="width:300px;"></progress><label id="status"></label></div>');
    //window.setTimeout("rm_loading()", 1000);
} 

function goToTop(){ $( 'html, body' ).animate( { scrollTop: 0 }, 'slow' );}
function goToAnchor(id){ $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');}
function goToObj(obj){ $('html,body').animate({scrollTop: $(obj).offset().top},'slow');}

function isNumber(str){   str = str.toString(); var re = /^[-]?\d*\.?\d*$/; if (!str.match(re)||str.length=="") return false; else  return true; }
function isEmail(vl) { var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/; if (!vl.match(re)) { return false; } else { return true;}}

function setCookie(c_name, value, exdays = 365){
    var exdate = new Date(); 
    exdate.setDate(exdate.getDate() + exdays); 
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    c_value += "; path=/";
    document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){ var x,y; var ARRcookies = document.cookie.split(";"); var cookie_value = ''; for (var i=0;i<ARRcookies.length;i++){ x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name){ cookie_value = unescape(y); break;} } return cookie_value;}
function clearCookie(name){setCookie(name, "", -1);}

function formatCommas(numString) { var re = /(-?\d+)(\d{3})/; while (re.test(numString)) { numString = numString.toString().replace(re, "$1,$2"); } return numString;}
function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function str2Number(str){ return parseFloat(str.toString().replace(/,/gi, ""));}
function addslashes(str) {str = str.replace(/\\/g,'\\\\'); str = str.replace(/\'/g,'\\\''); str = str.replace(/\"/g,'\\"'); str = str.replace(/\0/g,'\\0'); return str;}
function escapeHtml(text) {
  return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

function getTime(){
    var dt = new Date();
    var time = parseInt(dt.getTime()/1000); 
    var date = ("0" + dt.getDate()).slice(-2)+"/"+("0"+(dt.getMonth()+1)).slice(-2)+"/"+dt.getFullYear()+", "+("0"+dt.getHours()).slice(-2) + ":" + dt.getMinutes(); 
    return Array(time, date);
}

function mktime2Text(time){
    var strTime = '';
    if(time < 60 && time >= 0){ //s
        strTime = "<em> <i class=\"fa fa-clock-o\"></i> Cách đây "+ time  + " giây</em>";
    }
    else if(time < 3600){ //m
        strTime = "<em> <i class=\"fa fa-clock-o\"></i> Cách đây "+ Math.ceil(time / 60)  + " phút</em>";
    }
    else if(time < 86400){ //24h
        var h = Math.ceil(time / 3600)
        strTime = "<em> <i class=\"fa fa-clock-o\"></i> Cách đây "+ h + " giờ " + Math.ceil((time % 3600) / 60) + " phút</em>";
    }
    else if(time < 259200){ //72h
        strTime = "<em> <i class=\"fa fa-clock-o\"></i> Cách đây "+ Math.ceil(time / 3600) + " giờ</em>";
    }
    else if(time < 2592000){ //30 d
        strTime = "<em> <i class=\"fa fa-clock-o\"></i> Cách đây "+ Math.ceil(time / 86400)  + " ngày</em>";
    }
    
    else{
        //$(mktime[i]).html("<em><i class=\"fa fa-clock-o\"></i> Ngày đăng "+ $(mktime[i]).html()  + "</em>");
    }
    return strTime;  
}


function clock2Text(time){
    
    var strTime = '';
    if(time < 60){ //s
        if(time < 10) time = "0"+ time;
        strTime = "<label>00</label> giờ <label>00</label> phút <label>"+ time  + "</label> giây";
    }
    else if(time < 3600){ //m
        var m = Math.floor(time / 60);
        var s = time - m*60 ;
        if(m < 10) m = "0"+m;
        if(s < 10) s = "0"+s;
        strTime = "<label>00</label> giờ <label>"+ m + "</label> phút <label>"+s+"</label> giây";
    }
    else if(time < 86400){ //24h
        var h = Math.floor(time / 3600); time = time -  h * 3600;
        var m = Math.floor( time / 60);
        var s = time - m * 60;
        if(h < 10) h = "0"+h;
        if(m < 10) m = "0"+m;
        if(s < 10) s = "0"+s;
        strTime = "<label>"+h+"</label> giờ <label>"+ m + "</label> phút <label>"+s+"</label> giây";
    }
    else{
        var d = Math.floor(time / 86400);
        time = time - d * 86400;
        var h = Math.floor(time / 3600);
        time = time -  h * 3600;
        var m = Math.floor( time / 60);
        var s = time - m * 60;
        if(d < 10) d = "0"+d;
        if(h < 10) h = "0"+h;
        if(m < 10) m = "0"+m;
        if(s < 10) s = "0"+s;
        strTime = "<label>"+d+"</label> ngày <label>"+h+"</label> giờ <label>"+ m + "</label> phút <label>"+s+"</label> giây";
    }
   
    return strTime;  
}

function fixResizePage(obj){
    var imgList = $(obj).find("img");
    if(imgList.length > 0){
        for(var i = 0; i < $(imgList).length; i++){
            var src = $(imgList[i]).attr("src");
            if(src[0] == "/") src = "." + $(imgList[i]).attr("src");
            
            var width  = height = 0;
            
            if($(imgList[i]).css("width")){
                  width = parseInt($(imgList[i]).css("width"));
            }            
            if($(imgList[i]).css("height")){
                height = parseInt($(imgList[i]).css("height"));
            }
            
            if(width == 0){
                width = $(imgList[i]).width();
                if(width > 650 ){
                    width  = 650;
                    height = parseInt($(imgList[i]).height() * width / $(imgList[i]).width()); 
                }                 
            }
            
            if(width > $(window).width()){
                height = parseInt(height * ($(window).width() - 20) / width);
                width = $(window).width() - 20;                    
            }
            
            var css = "width: 100%; max-width: " + width + "px; height: auto";
            
            var title = $(imgList[i]).attr("alt");
            if(title == undefined) title = $(imgList[i]).attr("title");
            if(title == undefined) title = "";
            
            var htm = "<a href=\""+src+"\" target=\"_blank\" class=\"lightGallery\">";
            htm += "<img src=\""+src+"\" title=\""+title+"\" alt=\""+title+"\" style=\""+css+"\"/>"; // width=\""+width+"\" height=\""+height+"\" 
            htm += "</a>";
            $(imgList[i]).replaceWith(htm);
        }
         
        $(obj).lightGallery({
            thumbnail:true,
            selector: '.lightGallery',
            share: false,
            hash: false
        });
    }
    
    var iframeList = $(obj).find("iframe");
    for(var i = 0; i < $(iframeList).length; i++){
        $(iframeList[i]).attr("src",$(iframeList[i]).data("lazy-src"));
        $(iframeList[i]).attr("style","width:100%;");
    }
}

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};

function gotoAnypage(obj){if($("div#gotoAnypage").length == 0){
    $("body").append("<div id='gotoAnypage'></div>");} 
    $("div#gotoAnypage").html("<div class='box'><label>Go page... </label><form onsubmit='submitAnypage();return false;'><input type='text' name='anyPage'/><input type='submit' value='OK'><input type='hidden' name='url' value=\""+$(obj).data("url")+"\"><input type='hidden' name='ext' value=\""+$(obj).data("ext")+"\"/></form></div>"); 
    var pos = $(obj).offset();$("div#gotoAnypage").css({top: (pos.top  + 35) + "px",left: (pos.left) + "px" }); 
    $("div#gotoAnypage").show('slow');
}
function submitAnypage(){
    var url = $("div#gotoAnypage input[name='url']").val(); 
    var ext = $("div#gotoAnypage input[name='ext']").val();
    if($.isNumeric($("input[name='anyPage']").val())) {
        var page = parseInt($("input[name='anyPage']").val());
        var totalPage = parseInt($("input[name='total']").val());
        if(page < 0) page = 1;
        else if(page > totalPage) page = totalPage;                
        window.location.href = url + page + ext;
    }
    else{ alert("Please input number"); }
}
