﻿
String.prototype.StartsWith = function (str) {
    return (this.match("^" + str) == str);
}

String.prototype.EndsWith = function (str) {
    return (this.match(str + "$") == str);
}

String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.LTrim = function () {
    return this.replace(/(^\s*)/g, "");
}

String.prototype.RTrim = function () {
    return this.replace(/(\s*$)/g, "");
}

String.prototype.InStr = function (str) {
    return this.indexOf((str == null) ? "" : str);
}

String.prototype.InStrRev = function (str) {
    return this.lastIndexOf((str == null) ? "" : str);
}

String.prototype.cnLength = function () {
    var arr = this.match(/[^\x00-\xff]/ig);
    return this.length + (arr == null ? 0 : arr.length);
}

String.prototype.Right = function (n) {
    var len = String(this).length;
    if (n <= 0) { return ""; }
    else if (n > len) { return this; }
    else { return String(this).substring(len, len - n); }
}

String.prototype.Left = function (n) {
    var len = String(this).length;
    if (n <= 0) { return ""; }
    else if (n > len) { return this; }
    else { return String(this).substring(0, n); }
}

String.prototype.CLeft = function (num) {
    if (!/\d+/.test(num)) return (this);
    var str = this.substr(0, num);
    var n = str.cnLength() - str.length;
    num = num - parseInt(n / 2);
    return this.substr(0, num);
}

String.prototype.CRight = function (num) {
    if (!/\d+/.test(num)) return (this);
    var str = this.substr(this.length - num);
    var n = str.cnLength() - str.length;
    num = num - parseInt(n / 2);
    return this.substr(this.length - num);
}

String.prototype.Mid = function (start, len) {
    if (isNaN(start)) start = 0;
    if (isNaN(len)) len = 0;
    return this.substr(start - 1, len);
}

Date.prototype.DayDiff = function (cDate, mode) {
    try {
        cDate.getYear();
    } catch (e) {
        return (0);
    }
    var base = 60 * 60 * 24 * 1000;
    var result = Math.abs(this - cDate);
    switch (mode) {
        case "y":
            result /= base * 365;
            break;
        case "m":
            result /= base * 365 / 12;
            break;
        case "w":
            result /= base * 7;
            break;
        default:
            result /= base;
            break;
    }
    return (Math.floor(result));
}

String.prototype.toDate = function () {
    try {
        return new Date(this.replace(/-/g, "//"));
    }
    catch (e) {
        return null;
    }
}

Number.prototype.toCurrency = function (c, d, t) {
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

var cookieList = function (cookieName) {
    var cookie = $.cookie(cookieName);
    var items = cookie ? cookie.split(/,/) : new Array();
    return {
        "add": function (val, maxLength) {
            items = $.grep(items, function (value) {
                return (value != val);
            });
            if (val && $.trim(val) != '') {
                items.unshift($.trim(val));
            }
            if (!$.isNaN(maxLength) && items.length > maxLength) {
                items.pop();
            }
            //$.cookie(cookieName, items.join(','), { expires: 7, path: '/', domain: 'housefun.com.tw' });
            $.cookie(cookieName, items.join(','), { expires: 7, path: '/'});
        },
        "clear": function () {
            items = null;
            $.cookie(cookieName, null);
        },
        "remove": function (val) {
            items = $.grep(items, function (value) {
                return (value != val);
            });
            $.cookie(cookieName, (items.length > 0 ? items.join(',') : null));
        },
        "items": function () {
            return items;
        }
    }
}

function isEMail(value) {
    //var emailfilter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
    var emailfilter = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return (emailfilter.test(value));
}

function isNumber(n) {
    var RegEx = /^-{0,1}\d*\.{0,1}\d*$/;
    return (!isNaN(parseFloat(n)) && isFinite(n) && RegEx.test(n));
}

//取得網址列所傳的參數
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = decodeURIComponent(hash[1]);
    }
    return vars;
}

if ($) {
    $.fn.limitMaxlength = function (options) {
        var settings = jQuery.extend({
            attribute: "maxlength",
            onLimit: function () { },
            onEdit: function () { }
        }, options);

        // Event handler to limit the textarea
        var onEdit = function () {
            var textarea = jQuery(this);
            var maxlength = parseInt(textarea.attr(settings.attribute));
            if (textarea.val().length > maxlength) {
                textarea.val(textarea.val().substr(0, maxlength));
                // Call the onlimit handler within the scope of the textarea
                jQuery.proxy(settings.onLimit, this)();
            }
            // Call the onEdit handler within the scope of the textarea
            jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
        }
        this.each(onEdit);
        return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
    }
}

function showMsg2(message, width, height) {
    //將myMsg 物件及綁定事件移除
    $("#myMsg").remove();
    //重建myMsg物件
    var InfoBox = $('<a id="myMsg"></a>');
    InfoBox.appendTo('body');

    var url = "/Buy/Info.aspx?cfm=false";
    if (isNumber(width)) url += "&w=" + width + 'px';
    if (isNumber(height)) url += "&h=" + height + 'px';
    url += "&i=" + message;
    //url += "&i=" + encodeURIComponent(message);
    InfoBox.attr('href', url);
    InfoBox.fancybox({
        'type': 'iframe',
        'scrolling': 'no',
        'width': isNumber(width) ? width : 560,
        'height': isNumber(height) ? height : 340,
        'hideOnOverlayClick': false,
        'margin': 0,
        'padding': 0
    });
    InfoBox.trigger('click');
}

function showMsg(message, width, height, fnOK) {

    var w = '';
    var h = '';
    if (isNumber(width)) w = 'width:' + width + 'px;';
    if (isNumber(height)) h = 'height' + height + 'px;';
    $('#MsgBox').parent().remove();
    var MsgBox = $('<div class="lightbox_dialogue" id="MsgBox" style="overflow: none;' + w + h + '">' +
                          '  <div style="padding: 13px;">' +
                          '    <h2>系統訊息</h2>' +
                          '    <table border="0" cellpadding="10" cellspacing="10" class="lightable">' +
                          '      <tr><td align="left" valign="top" style="padding-top: 10px;line-height:22px">' + message + '</td></tr>' +
                          '      <tr>' +
                          '        <td style="width:100%;"><div style="width:75px;margin: 0 auto; text-align:center;"><a id="btnOK" href="javascript:void(0);" title="確定" class="orange_btn" style="width:70px;" >確 定<span style=""></span></div></td>' +
                          '      </tr>' +
                          '    </table>' +
                          '  </div>' +
                          '</div>');
    $('body').append($('<div style="display:none;"></div>').html(MsgBox));
    if (typeof (fnOK) === 'function') {
        $('#btnOK', MsgBox).bind('click', function () { $.fancybox.close(); setTimeout(fnOK, 500); });
    }
    else {
        $('#btnOK', MsgBox).bind('click', function () { $.fancybox.close(); });
    }

    $('#MsgBoxTrigger').remove();
    var MsgBoxTrigger = $('<a id="MsgBoxTrigger" href="#MsgBox"></a>');
    $('body').append(MsgBoxTrigger);
    MsgBoxTrigger.fancybox({
        'type': 'inline',
        'scrolling': 'no',
        'hideOnOverlayClick': false,
        'overlayShow': true,
        'enableEscapeButton': false,
        'showCloseButton': false,
        'width': isNumber(width) ? width : 300,
        'height': isNumber(height) ? height : 180,
        'margin': 0,
        'padding': 0
    });
    MsgBoxTrigger.trigger('click');
    return (false);
}

function ConfrimFB(message, fnOK, fnCancel, width, height) {
    var w = '';
    var h = '';
    if (isNumber(width)) w = 'width:' + width + 'px;';
    if (isNumber(height)) h = 'height' + height + 'px;';
    $('#ConfrimMsgBox').parent().remove();
    var ConfrimMsgBox = $('<div class="lightbox_dialogue" id="ConfrimMsgBox" style="overflow: none;' + w + h + '">' +
                          '  <div style="padding: 13px;">' +
                          '    <h2>系統訊息</h2>' +
                          '    <table border="0" cellpadding="10" cellspacing="10" class="lightable">' +
                          '      <tr><td align="left" colspan="3" valign="top" style="padding-top: 10px;line-height:22px">' + message + '</td></tr>' +
                          '      <tr>' +
                          '        <td style="width:49%;"><div style="float:right;"><a id="btnOK" href="javascript:void(0);" title="確定" class="orange_btn" style="width:70px;" >確 定<span style=""></span></div></td>' +
                          '        <td style="width:2%;"></td>' +
                          '        <td style="width:49%;"><div style="float:left;"><a id="btnCancel" href="javascript:void(0);" title="取消" class="orange_btn" style="width:70px;" >取 消<span style=""></span></div></td>' +
                          '      </tr>' +
                          '    </table>' +
                          '  </div>' +
                          '</div>');

    $('body').append($('<div style="display:none;"></div>').html(ConfrimMsgBox));
    if (typeof (fnOK) === 'function') {
        $('#btnOK', ConfrimMsgBox).bind('click', function () { $.fancybox.close(); setTimeout(fnOK, 500); });
    }
    else {
        $('#btnOK', ConfrimMsgBox).bind('click', function () { $.fancybox.close(); });
    }
    if (typeof (fnCancel) === 'function') {
        $('#btnCancel', ConfrimMsgBox).bind('click', function () { $.fancybox.close(); setTimeout(fnCancel, 500); });
    }
    else {
        $('#btnCancel', ConfrimMsgBox).bind('click', function () { $.fancybox.close(); });
    }
    $('#ConfrimTrigger').remove();
    var ConfrimTrigger = $('<a id="ConfrimTrigger" href="#ConfrimMsgBox"></a>');
    $('body').append(ConfrimTrigger);
    ConfrimTrigger.fancybox({
        'type': 'inline',
        'scrolling': 'no',
        'hideOnOverlayClick': false,
        'overlayShow': true,
        'enableEscapeButton': false,
        'showCloseButton': false,
        'width': isNumber(width) ? width : 300,
        'height': isNumber(height) ? height : 200
    });
    ConfrimTrigger.trigger('click');
    return (false);
}


