﻿
/*
Author: thetoan.cao
Create Date: 2010-08-10
Description: các scrip thông dụng
*/
String.prototype.replaceQuote = function () {
    return this.replace(/[\']/g, '\'').replace(/[\"]/g, '\"');
}
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) + "...";
}

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;
    }

    /// note: 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'];
        var g = new Date(HomeEnv.server_time); //new Date();
        var j = null;

        if (initDate) {
            j = a;
        }
        else {
            var _match = a.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);
            if (_match) {
                j = new Date(1 * _match[1] + 3600000 * (_match[2] - 7) + 60000 * _match[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 (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://farm01.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 (e) {
                $(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 (e) {
                $(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;
    }
}
    
