﻿
/*
Author: thetoan.cao
Create Date: 2010-08-10
Description: các scrip thông dụng
*/
if (typeof HomeEnv == "undefined")
    var HomeEnv = {
        version: "9.5",
        domain: "go.vn",
        accountId: -1,
        urlHome: "http://my.go.vn/",
        urlMedia: "http://static.gox.vn/media/",
        processing: "<div class='aligncenter'>Đang xử lý dữ liệu...<br /><img src='http://static.gox.vn/media/homepage/images/awaiting.gif' alt='loading' border='0' /></div>",
        loading: "<div class='aligncenter'>Đang tải dữ liệu...<br /><img src='http://static.gox.vn/media/homepage/images/awaiting.gif' alt='loading' border='0' /></div>",
        error: "Không lấy được dữ liệu. Vui lòng <a class='hlkReload' href='javascript:void(0);' onclick='window.location.reload();'>thử lại</a>."        
    };
String.prototype.replaceQuote = function() {
    return this.replace( /[\']/g , '\'').replace( /[\"]/g , '\"');
};
String.prototype.removeHtml = function() {
    return this.replace( /<(?:.|\n)*?>/gm , '');
};

String.prototype.subWords = function(length) {
    //if (typeof this !== String) return "";
    if (this == "") { return ""; }
    if (this.length <= length) { return this; }
    var trim = length;
    if (this[trim] != undefined) {
        while (trim > 0 & this[trim] != " ") { trim--; }
    }
    return this.substring(0, trim) + "...";
};

function _StringFormatInline() {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}

function _StringFormatStatic() {
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        arguments[0] = arguments[0].replace(exp, arguments[i]);
    }
    return arguments[0];
}

if (!String.prototype.format) {
    String.prototype.format = _StringFormatInline;
}

if (!String.format) {
    String.format = _StringFormatStatic;
}
function go_loadScripts(array, callback) {
    var loader = function (src, handler) {
        var script = document.createElement("script");
        script.src = src + "?" + new Date().getDate();
        script.onload = script.onreadystatechange = function() {
            script.onreadystatechange = script.onload = null;
            if ( /MSIE ([6-9]+\.\d+);/ .test(navigator.userAgent)) {
                var timeout = 100;
                window.setTimeout(function() {
                    try { handler(); }
                    catch(ex) {
                        timeout += 500;
                        window.setTimeout(function() {
                            try { handler(); } catch(e) { }
                        }, timeout, this);
                    }
                }, timeout, this);
            }
            else handler();
        };
        var head = document.getElementsByTagName("head")[0];
        (head || document.body).appendChild(script);
    };
    (function () {
        if (array.length != 0) {
            loader(array.shift(), arguments.callee);
        } else {
            callback && callback();
        }
    })();
}

var MyGoLib = new function () {
    // Hàm convert chuỗi json Datetime sang Date
    // value: chuỗi jSon datetime
    this.jSonToDate = function (value) {
        value = value.replace('/Date(', '');
        value = value.replace(')/', '');
        var expDate = new Date(parseInt(value));
        return expDate;
    };
    this.stringFormat = function (str) {
        if (str == null || str == "") return "";
        for (var i = 1; i < arguments.length; i++) {
            var j = i - 1;
            str = str.replace(new RegExp('\\{' + j + '\\}', 'g'), arguments[i]);
        }
        return str;
    };
    // Hàm convert chuỗi json Datetime sang chuối ngày tháng
    // value: chuỗi jSon datetime
    // option:
    //      0: dd-MM-yyyy hh:mm:ss
    //      1: dd-MM-yyyy
    this.jSonDateToString = function (value, option) {
        var expDate = COMMON.jSonToDate(value);
        if (option == 0)
            return expDate.getDate() + '-' + (expDate.getMonth() + 1) + '-'
                + expDate.getFullYear() + ' ' + expDate.getHours() + ':'
                    + expDate.getMinutes() + ':' + expDate.getSeconds();
        if (option == 1)
            return expDate.getDate() + '-' + (expDate.getMonth() + 1) + '-' + expDate.getFullYear();

        if (option == 2)
            return expDate.getHours() + ':'
                + expDate.getMinutes() + ':' + expDate.getSeconds() + " " + expDate.getDate() + '/' + (expDate.getMonth() + 1) + '/' +
                    +expDate.getFullYear();
        if (option == 3)
            return expDate.getMonth() + '-' + (expDate.getDate() + 1) + '-'
                + expDate.getFullYear() + ' ' + expDate.getHours() + ':'
                    + expDate.getMinutes();
        return expDate.toString();
    };

    this.formatMyDate = function (date) {
        if (date != null) {
            if (date < 10)
                date = "0" + date;
            return date;
        }
        else return "";
    };
    this.formatValue = function (value) {
        return value < 10 ? ('0' + value) : value;
    };

    /// chu y: sẽ có 2 trường hợp a giá trị chuyền vào.
    /// 1: là 1 chuỗi
    /// 2: là 1 object Date -ví dụ: new Date()
    /// vì vậy khi mà chuyền vào 1 đối tượng Date thì thêm 1 param initDate và chuyền vào là true.
    this.formatDateTime = function (a, initDate) {
        var e = [[11, 'sáng'], [14, 'trưa'], [19, 'chiều']];
       // var f = ['Chủ Nhật', 'Thứ Hai', 'Thứ Ba', 'Thứ Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy'];
        if (typeof HomeEnv != "undefined")
            var serverTime = HomeEnv.server_time;
        else serverTime = new Date().getTime();
        var g = new Date(serverTime); //new Date();
        var j;

        if (initDate) {
            j = a;
        }
        else {
            var mymatch = a.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);
            if (mymatch) {
                j = new Date(1 * mymatch[1] + 3600000 * (mymatch[2] - 7) + 60000 * mymatch[3]);
            } else {
                j = new Date(a);
            }
        }
        var padding = '<div class="clearfix" style="height:14px;"></div>';
        var d = Math.floor(g.getTime() / 1000) - Math.floor(j / 1000);
        if (d < 0) {
            return j.getHours() + ':' + formatValue(j.getMinutes()) + '<br />' + formatValue(j.getDate()) + '/' + formatValue(j.getMonth() + 1) + '/' + j.getFullYear();
        }
        if (d < 60) {
            return (d == 0 ? padding + 'vài' : d) + ' giây trước';
        }
        if (d < 3600) return padding + Math.floor(d / 60) + ' phút trước';
        if (d < 43200) return padding + Math.floor(d / 3600) + ' tiếng trước';
        var h = j.getHours();
        var m = formatValue(j.getMinutes());
        if (d < 518400) {
            var b = 'tối';
            for (var i = 0; i < 3; i++)
                if (h < e[i][0]) {
                    b = e[i][1];
                    break;
                }
            d = (g.getDay() + 7 - j.getDay()) % 7;
            var k;
            if (d == 0)
                k = 'hôm nay';
            /*else if (d == 1)
            k = 'hôm qua';*/
            else
                return h + ':' + m + '<br />' + formatValue(j.getDate()) + '/' +
                    formatValue(j.getMonth() + 1) + '/' + j.getFullYear(); //f[j.getDay()];
            return padding + (h % 12).toString() + ':' + m + ' ' + b + ' ' + k;
        }
        h = formatValue(h);
        return h + ':' + m + '<br />' + formatValue(j.getDate()) + '/' +
            formatValue(j.getMonth() + 1) + '/' + j.getFullYear();
    };
    this.formatJSONDate = function (jsonDate) {
        if (jsonDate != null) {

            jsonDate = jsonDate.replace('/Date(', '');
            jsonDate = jsonDate.replace(')/', '');
            var ticks = parseInt(jsonDate);
            var newDate = new Date(ticks);
            return newDate.getHours() + ":" + MyGoLib.formatMyDate(newDate.getMinutes()) + " "
                + MyGoLib.formatMyDate(newDate.getDate()) + "/"
                    + MyGoLib.formatMyDate(newDate.getMonth() + 1) + "/"
                        + newDate.getUTCFullYear();
        }
        else return "";
    };
    this.checkBrowser = function () {
        if (navigator.userAgent.indexOf('MSIE 6.0') != -1) {
            return 'IE6';
        }
        // do later
        return 'other';
    };
    this.checkValid = function (e) {
        if (e != null && e != '' && e != 'undefined')
            return true;
        else return false;
    };
    this.addScript = function (url) {
        if (MyGoLib.checkValid(url)) {
            var script = document.createElement('script');
            script.src = url;
            script.type = 'text/javascript';
            document.body.appendChild(script);
        }
    };

    this.checkLength = function (o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            //updateTips("Giới hạn " + n + " từ " + min + " đến " + max + ".");
            return false;
        } else {
            return true;
        }
    };

    this.getTimeNow = function () {
        var newDate = new Date();
        return newDate.getHours() + ":" + formatMyDate(newDate.getMinutes()) + " " + formatMyDate(newDate.getDate()) + "/" + formatMyDate(newDate.getMonth() + 1) + "/" + newDate.getUTCFullYear();
    };
    this.stripHtml = function (content) {
        // What a tag looks like
        var matchTag = /<(?:.|\s)*?>/g;
        // Replace the tag
        //content = content.replace("&", "&amp;")
        content = content.replace(/^\s+|\s+$/, '');
        content = content.replace(matchTag, "");
        return content;
    };
    this.focusTxt = function (selector) {
        var value = $("#" + selector).val();
        switch (value) {
            case 'Tìm':
                value = '';
                break;
            case '':
                value = 'Tìm';
                break;
            default:
                break;
        }
        $("#" + selector).val(value);
    };
    this.removeByElement = function (arrayName, arrayElement) {
        for (var i = 0; i < arrayName.length; i++) {
            if (arrayName[i] == arrayElement)
                arrayName.splice(i, 1);
        }
    };
    this.GetAvatarPath = function (id, w, h) {
        return "http://avatar.go.vn/avatar/store/account/" 
            + Math.floor(id / 1000000, 0) + '/' + Math.floor(id / 1000, 0) + '/' + id + '/' + id + '.png.'
                + w + '.' + h + '.cache';
    };
    this.appendCssToHead = function (url) {
        if (url) {
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.href = url;
            head.appendChild(link);
        }
    };
    this.breakWordCss = function (id) {
        if ($(id)) {
            $(id).css("word-wrap:", "break-word");
        }
    };
    // apply style tranparent for a element (valid CSS)
    this.setOpacity = function (id, value) {
        if ($(id)) {
            $(id).css("filter:", "alpha(opacity=" + value * 100 + ")");
            $(id).css("-moz-opacity", value);
            $(id).css("-khtml-opacity", value);
            $(id).css("opacity", value);

            $(id).mouseover(function () {
                $(id).css("filter:", "alpha(opacity=100)");
                $(id).css("-moz-opacity", "1.0");
                $(id).css("-khtml-opacity", "1.0");
                $(id).css("opacity", "1.0");
            });

            $(id).mouseout(function () {
                $(id).css("filter:", "alpha(opacity=" + value * 100 + ")");
                $(id).css("-moz-opacity", value);
                $(id).css("-khtml-opacity", value);
                $(id).css("opacity", value);
            });
        }
    };
    this.replaceQuote = function (s) {
        return s.replace("'", "\'").replace("\"", "\\\"");
    };
};

function auto_scroll(anchor, top) {
    var $target = $(anchor);

    $target = $target.length && $target || $('[name=' + anchor.slice(1) + ']');

    if ($target.length) {
        var targetOffset = $target.offset().top - top;

        $('html,body').animate({ scrollTop: targetOffset }, 1000);

        return false;
    }
    return true;
}

/* Cookie Functions*/
function createCookie(name, value, min) {
    var expires;
    if (min) {
        var date = new Date();
        date.setTime(date.getTime() + (min * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var nameEq = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEq) == 0) return c.substring(nameEq.length, c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}

/* end Cookie Functions*/
function getQuerystringSharp() {
    var search = unescape(location.href);
    if (search == "") {
        return "";
    }
    //search = search.substr(1);

    if (search.indexOf("#") == -1)
        return "";
    var params = search.split("#");

    return params[1];
}
    /* xu ly focus comment*/
function getQuerystringSharp() {
    var search = unescape(location.href);
    if (search == "") {
        return "";
    }
    //search = search.substr(1);

    if (search.indexOf("#") == -1)
        return "";
    var params = search.split("#");

    return params[1];
}
function auto_scroll(anchor, top) {
    var $target = $(anchor);

    $target = $target.length && $target || $('[name=' + anchor.slice(1) + ']');

    if ($target.length) {
        var targetOffset = $target.offset().top - top;

        $('html,body').animate({ scrollTop: targetOffset }, 1000);

        return false;
    }
    return true;
}

function focusComment(accountId,frmCommentId){
    auto_scroll( frmCommentId, 0);
    var govnRegisterUrl = "http://go.vn/accounts/account.register.aspx";
    if (accountId < 1) {
        var message = "Bạn cần <a href=\"" + govnRegisterUrl + "\" style=\"color:#007EBF\" >đăng ký</a> hoặc <a href=\"" + mygo_obj.loginUrl + "\" style=\"color:#007EBF\" >đăng nhập</a> để thực hiện chức năng này.";
        if (typeof GoDialog != "undefined")
            GoDialog.Alert(message);
        else alert(message);
    }
    else {
        $(frmCommentId).show().focus(); 
    }
}
function autoFocusComment( accountId, frmCommentId) {
    $(document).ready(function() {
        var action = getQuerystringSharp();
        switch (action) {
        case "comment":
            focusComment(accountId, frmCommentId);
            break;
        }
    });
}
function setRequestHeader(x) {
    var tokenName = "X-Request-Verification-Token"; //__RequestVerificationToken
    var verificationToken = $("meta[name='" + tokenName + "']").attr('content');
    if (verificationToken) {
        x.setRequestHeader(tokenName, verificationToken);
    }
}
function setAjaxRequestHeader() {
    $.ajaxSetup({
        beforeSend: function (x) {
            setRequestHeader(x);
        }
    });
}
setAjaxRequestHeader();
function unicodeToIso(b) {
    var c = '';
    for (var i = 0; i < b.length; i++) {
        if (b.charCodeAt(i) > 127) { c += '&#' + b.charCodeAt(i) + ';'; } else { c += b.charAt(i); }
    }
    return c;
}
function valInArray(arr, obj) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == obj) return true;
    }

    return false;
}

