﻿function setCookie(name, value, expire) {
    window.document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}

function getCookie(Name) {
    var search = Name + "=";
    if (window.document.cookie.length > 0) { // if there are any cookies
        offset = window.document.cookie.indexOf(search);
        if (offset != -1) { // if cookie exists
            offset += search.length;          // set index of beginning of value
            end = window.document.cookie.indexOf(";", offset)          // set index of end of cookie value
            if (end == -1)
                end = window.document.cookie.length;
            return unescape(window.document.cookie.substring(offset, end));
        }
    }
    return null;
}

function register(name) {
    var today = new Date();
    var expires = new Date();
    expires.setTime(today.getTime() + 1000 * 60 * 60 * 24 * 7);
    setCookie("addFav", name, expires);
}

function addToFavorite(url, title) {

    var c = getCookie("addFav");
    if (c != null) {
        return;
    }
    register("yes");

    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("msie 8") != -1) {
        window.external.addToFavoritesBar(url, title);
    } else {
        try {
            window.external.addFavorite(url, title);
        } catch (e) {
            try {
                window.sidebar.addPanel(title, url, "");
            } catch (e) {
                alert("加入最愛失敗, 請手動添加至最愛!");
            }
        }
    }
    return false;
}
