﻿function ConvertStringToDateTime(dateString) {
    return new Date(dateString.replace(/-/g, "\/"));
}
function ConvertDateTimeToString(date) {
    if ($.browser.msie) {
        return date.getYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    }
    else {
        return (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    }
}

var lastRefreshTime = $.cookie("lrt");

var currentTime = new Date();
$.cookie("lrt", ConvertDateTimeToString(currentTime));

if (lastRefreshTime == null || lastRefreshTime == "") {
}
else {
    lastRefreshTime = ConvertStringToDateTime(lastRefreshTime);

    if ((currentTime - lastRefreshTime) < 120000) {
        alert("物价表内置了自动刷新功能，每两分钟自动刷新一次。\r\n为了您和大家能更稳定的使用物价表，请不要频繁刷新页面(小于两分钟)！\r\nPS：如果只需刷新价格，请点击“刷新物价”链接。");
    }
}

jQuery.fn.outer = function () {
    return $($('<div></div>').html(this.clone())).html();
}

function CookieHelper() {
    this.getNoticeMusic = function () {
        return $.cookie("nm");
    }
    this.setNoticeMusic = function (path) {
        $.cookie("nm", path, { expires: 60 });
    }
    this.getDefaultCategory = function () {
        return $.cookie("defaultCategory");
    }
    this.setDefaultCategory = function (path) {
        $.cookie("defaultCategory", path, { expires: 60 });
    }
    this.getGuanZhu = function () {
        return $.cookie("guanzhu");
    }
    this.setGuanZhu = function (value) {
        $.cookie("guanzhu", value, { expires: 60 });
    }
    this.getNoticeSettings = function () {
        return $.cookie("ns");
    }
    this.setNoticeSettings = function (value) {
        $.cookie("ns", value, { expires: 60 });
    }
    this.toString = function () {
        return this.getNoticeMusic() + " " + this.getDefaultCategory() + " " + this.getGuanZhu() + " " + this.getNoticeSettings();
    }
}
var cookieHelper = new CookieHelper();



var g_blinkid;
var g_blinktitle = "开心网(Kaixin001)超级大亨实时物价表 -- By Jailu";
var g_blinkswitch = 0;
var g_inputtime = 0;
var default_notice_music = "http://music1.kaixin001.com/privacy/music/27/72/2277221.mp3";
var notice_music = default_notice_music;
var goods = "";
var currentPrices = "";
var lastUpdate = "正在获取...";
var g_countDowTimer;

function AddFavorite(sURL, sTitle) {
    try {
        window.external.addFavorite(sURL, sTitle);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(sTitle, sURL, "");
        }
        catch (e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}
var currentCategoryId = 1;
function ShowGoods(categoryId) {
    $("#cm" + currentCategoryId).toggleClass("cur");
    $("#cm" + categoryId).toggleClass("cur");

    if (categoryId == "0") {
        DisplayAllGoods();
    }
    else {
        $(".goods ul").css("display", "none");
        $("#c" + categoryId).toggle();
    }

    currentCategoryId = categoryId;
}
function DisplayAllGoods() {
    $(".goods ul").css("display", "block");

    return false;
}
function HideOthers() {
    $(".goods ul").css("display", "none");
    $("#c" + $("#categories").val()).toggle();

    return false;
}
function SetDefault(control) {
    var defaultCategory = $(control).parent().attr("id");
    cookieHelper.setDefaultCategory(defaultCategory);
    ShowGoods(defaultCategory.substring(2));
}
function SetGuanZhu(guanZhuControl) {
    var goodId = $(guanZhuControl).parent().parent().attr("id");
    var guanZhuGoodIds = cookieHelper.getGuanZhu();

    if (guanZhuGoodIds == null) {
        guanZhuGoodIds = "";
    }
    if (guanZhuGoodIds.indexOf(goodId + ",") >= 0) {
        return;
    }
    else {
        guanZhuGoodIds += goodId + ",";
        cookieHelper.setGuanZhu(guanZhuGoodIds);
        ShowGuanZhu();
    }
}
function DelGuanZhu(guanZhuControl) {
    if (confirm("你确定要移除该关注商品吗？")) {
        var goodId = $(guanZhuControl).parent().parent().attr("id");
        var guanZhuGoodIds = cookieHelper.getGuanZhu();

        if (guanZhuGoodIds == null) {
            return;
        }
        guanZhuGoodIds = guanZhuGoodIds.replace(goodId + ",", "");
        cookieHelper.setGuanZhu(guanZhuGoodIds);
        ShowGuanZhu();
    }
}
function ShowGuanZhu() {
    var guanZhu = cookieHelper.getGuanZhu();
    var guanZhuContainer = $("#c_guanzhu");
    if (guanZhu == null || guanZhu == "") {
        guanZhuContainer.html("");
        return;
    }
    var items = guanZhu.split(',');

    guanZhuContainer.html("");

    var html = "";
    for (var i = 0; i < items.length - 1; i++) {
        var li = $("<li id=\"" + items[i] + "\">" + $("#" + items[i]).html() + "</li>");
        $(".action", li).prepend("<a href=\"#\" class=\"del\">移除</a><a href=\"#\" class=\"notice\">提醒</a>");
        html += li.outer();
    }

    guanZhuContainer.html(html);
    $("#c_guanzhu .del").click(function () { DelGuanZhu(this); });
    $("#c_guanzhu .notice").click(function () { ShowNoticeDialog(this); });

    $("#c_guanzhu li:even").addClass("even");
    $("#c_guanzhu li:odd").addClass("odd");

    if ($.browser.msie) {
        $("#c_guanzhu li .action").css("display", "none");

        $("#c_guanzhu li").hover(
            function () {
                $(this).toggleClass("hover");
                $(".action", this).css("display", "inline-block");
            },
            function () {
                $(this).toggleClass("hover");
                $(".action", this).css("display", "none");
            }
        );
    }
}
function ShowNoticeDialog(control) {
    var li = $(control).parent().parent();
    var goodId = li.attr("id");
    var goodName = $(".good-name", li).html();

    $("#notice_good_id").val(goodId);
    $("#notice_dialog .good-name").html(goodName);

    $("#notice_dialog").dialog("open");
    return false;
}
function SetNotice() {
    SaveNoticeSetting($("#notice_good_id").val(),
                        $("#notice_option").val(),
                        $("#notice_money").val(),
                        $("#noticy_money_option").val());

    $("#notice_money").val("");
    $("#notice_dialog").dialog("close");
}
function GetNoticeSetting(goodId, option) {
    var settings = cookieHelper.getNoticeSettings();
    if (settings == null) {
        return null;
    }

    var settingItems = settings.split("|");
    var str = goodId + "," + option + ",";
    for (var i = 0; i < settingItems.length; i++) {
        if (settingItems[i].indexOf(str) >= 0) {
            var items = settingItems[i].split(",");

            return [items[0], items[1], items[2], items[3]];
        }
    }

    return null;
}
function SaveNoticeSetting(goodId, option, money, money_option) {
    var settings = cookieHelper.getNoticeSettings();
    if (settings == null) {
        settings = "";
    }

    var settingItems = settings.split("|");
    var str = goodId + "," + option + ",";
    for (var i = 0; i < settingItems.length; i++) {
        if (settingItems[i].indexOf(str) >= 0) {
            var items = settingItems[i].split(",");

            settings = settings.replace(settingItems[i] + "|", "");
            break;
        }
    }

    var newSettingItem = goodId + "," + option + "," + money + "," + money_option + "|";
    settings += newSettingItem;

    cookieHelper.setNoticeSettings(settings);
}
function DeleteNoticeSetting(goodId, option) {
    var settings = cookieHelper.getNoticeSettings();
    if (settings == null) {
        settings = "";
    }

    var settingItems = settings.split("|");
    var str = goodId + "," + option + ",";
    for (var i = 0; i < settingItems.length; i++) {
        if (settingItems[i].indexOf(str) >= 0) {
            var items = settingItems[i].split(",");

            settings = settings.replace(settingItems[i] + "|", "");
            break;
        }
    }

    cookieHelper.setNoticeSettings(settings);
}
function CheckNotice() {
    hasNoticeItem = false;
    var noticeSetting = cookieHelper.getNoticeSettings();
    if (noticeSetting == null || noticeSetting == "") {
        return;
    }

    var settingItems = noticeSetting.split("|");

    for (var i = 0; i < settingItems.length; i++) {
        var items = settingItems[i].split(",");
        var goodId = items[0];
        var option = items[1];
        var moneyOption = items[3];

        var money;
        if (moneyOption == "2") {
            money = parseFloat(items[2]) * 100000000;
        }
        else if (moneyOption == "1") {
            money = parseFloat(items[2]) * 10000;
        }
        else {
            money = parseInt(items[2]);
        }

        var currentPrice = currentPrices[goodId.replace("g", "")];
        if (currentPrice != null) {
            if (option == "0") {
                if (money > parseInt(currentPrice)) {
                    AppendNoticeItem(items);
                }
            }
            else {
                if (money < parseInt(currentPrice)) {
                    AppendNoticeItem(items);
                }
            }
        }
    }

    DisplayNotice();
}
var hasNoticeItem = false;
function AppendNoticeItem(items) {
    var htmlItem = "<li><span class=\"good-name\">" + GetGoodName(items[0]) + "</span><span class=\"" + (items[1] == "0" ? "smaller" : "bigger") + "\">" + (items[1] == "0" ? "小于" : "大于") + "</span><span class=\"money\">" + (items[2] + (items[3] == "0" ? "元" : items[3] == "1" ? "万元" : "亿元")) + "</span></li>";
    var html = $("#notice_display_board ul").html();
    html += htmlItem;
    $("#notice_display_board ul").html(html);
    hasNoticeItem = true;
}

function DisplayNotice() {
    $(".notice-music").html("");
    if (hasNoticeItem) {
        $("#notice_display_board").dialog("open");
        g_blinkid = setInterval(BlinkNewMsg, 1000);
        if ($.browser.msie) {
            $(".notice-music").html("<object classid='clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6' width='0' height='0'><param name='autostart' value='1' /><param name='url' value='" + notice_music + "' /><embed src='" + notice_music + "' autostart='1' type='application/x-mplayer2' width='0' height='0'></embed></object>");
        }
        else {
            $(".notice-music").html("<embed src='" + notice_music + "' autostart='true' loop='0' width='0' height='0' />");
        }
    }
}
function BlinkNewMsg() {
    var now = new Date();
    var nowtime = now.getTime();
    if (nowtime - g_inputtime > 5000) {
        window.document.title = g_blinkswitch % 2 ? "【新提醒】 - " + g_blinktitle : "【　　　】 - " + g_blinktitle;
    }

    g_blinkswitch++;
}
function ShowMyNotice() {
    var noticeSetting = cookieHelper.getNoticeSettings();
    if (noticeSetting == null) {
        $("#my_notice ul").html("<li>你还没有设置提醒</li>");
        $("#my_notice").dialog("open");
        return;
    }

    var settingItems = noticeSetting.split("|");
    var html = "";
    for (var i = 0; i < settingItems.length - 1; i++) {
        var items = settingItems[i].split(",");

        var itemHtml = "<li><span class=\"good-id\">" + items[0] + "</span><span class=\"good-name\">" + GetGoodName(items[0]) + "</span><span class=\"option\">" + (items[1] == "1" ? "大于" : "小于") + "</span><span class=\"money\">" + (items[2] + (items[3] == "0" ? "元" : items[3] == "1" ? "万元" : "亿元")) + "</span><a class=\"delete-notice\" href=\"#\">删除</a></li>";

        html += itemHtml;
    }

    $("#my_notice ul").html(html);
    $("#my_notice .delete-notice").click(function () { DeleteNotice(this); });

    $("#my_notice").dialog("open");

    return false;
}
function DeleteNotice(ctrl) {
    if (confirm("你确定要移除这条提醒吗？")) {
        var li = $(ctrl).parent();
        var goodId = $(".good-id", li).html();
        var option = $(".option", li).html();
        if (option == "小于") {
            option = "0";
        }
        else {
            option = "1";
        }

        DeleteNoticeSetting(goodId, option);

        li.toggle();
    }
}
function SetNoticeMusic() {
    cookieHelper.setNoticeMusic($("#notice_music").val());
    alert("提示音设置成功！");
}
function SetDefaultNoticeMusic() {
    $("#notice_music").val(default_notice_music);
}
function GetGoodName(goodId) {
    return $("#" + goodId + " .good-name").html();
}
var refreshId;
var isRefreshClear = false;
function DoRefresh() {
    $("#loading").css("display", "block");
    $("#count_down").css("display", "none");
    countDownSpan.html("120");
    window.document.title = g_blinktitle;
    $("#notice_display_board ul").html("");
    clearInterval(g_blinkid);
    clearInterval(refreshId);
    clearInterval(g_countDowTimer);

    $.getScript("javascript/GoodsData.js",
        function () { ActionAfterRefresh(); });
}
function ActionAfterRefresh() {
    ShowGuanZhu();
    if (cookieHelper.getDefaultCategory() != null) {
        ShowGoods(cookieHelper.getDefaultCategory().substring(2));
    }
    else {
        ShowGoods("1");
    }

    if ($.browser.msie) {
        $(".categories li").hover(
            function () {
                $("span", this).css("display", "block");
            },
            function () {
                $("span", this).css("display", "none");
            }
        );

        $(".goods ul").each(function () {
            if ($(this).attr("id") != "c_guanzhu") {
                $("li", this).hover(
                    function () {
                        $(this).toggleClass("hover");
                        $(".action", this).css("display", "inline-block");
                    },
                    function () {
                        $(this).toggleClass("hover");
                        $(".action", this).css("display", "none");
                    }
                );
            }
        });
    }

    $(".guan-zhu").click(function () { SetGuanZhu(this); return false; });
    $(".goods ul").each(function () {
        if ($(this).attr("id") != "c_guanzhu") {
            $("li:even", this).addClass("even");
            $("li:odd", this).addClass("odd");
        }
    });

    $(".normal-price span:first-child").toggleClass("min-price");
    $(".normal-price span:last-child").toggleClass("max-price");
    
    CheckNotice();

    refreshId = setInterval(DoRefresh, 1000 * 60 * 2);

    $("#count_down").css("display", "block");
    countDown = 120;
    g_countDowTimer = setInterval(CountDown, 1000);
}
var countDown;
var countDownSpan;
function CountDown() {
    countDown--;
    var str = countDown.toString();
    switch (str.length) {
        case 3:
            countDownSpan.html(str);
            break;
        case 2:
            countDownSpan.html("0" + str);
            break;
        default:
            countDownSpan.html("00" + str);
    }
}
function ShowCookieData() {
    $("#export_dialog").dialog("open");
    $("#export_text").val(cookieHelper.toString());
}
function DoImport() {
    var cookie = $("#import_text").val();
    var items = cookie.split(" ");
    if (items.length != 4) {
        alert("导入文本格式错误！");
        return;
    }

    var nm = items[0];
    var defaultCategory = items[1];
    var guanzhu = items[2];
    var ns = items[3];

    if (nm != "null") {
        cookieHelper.setNoticeMusic(nm);
    }
    else {
        cookieHelper.setNoticeMusic(null);
    }

    if (defaultCategory != "null") {
        cookieHelper.setDefaultCategory(defaultCategory);
    }
    else {
        cookieHelper.setDefaultCategory(null);
    }

    if (guanzhu != "null") {
        cookieHelper.setGuanZhu(guanzhu);
    }
    else {
        cookieHelper.getGuanZhu(null);
    }

    if (ns != "null") {
        cookieHelper.setNoticeSettings(ns);
    }
    else {
        cookieHelper.setNoticeSettings(null);
    }

    $("#import_dialog").dialog("close");
    DoRefresh();
}

$(document).ready(function () {
    $(".goods ul").css("display", "none");
    $("#c1").css("display", "block");

    $(".categories li span").click(function () { SetDefault(this); return false; });

    $("#set_notice").click(function () { SetNotice(); return false; });
    $(".my-notice").click(function () { ShowMyNotice(); return false; });
    $(".refresh-page").click(function () { DoRefresh(); return false; });

    $(".notice-music-setting .button").click(function () { SetNoticeMusic(); });
    $(".notice-music-setting .default").click(function () { SetDefaultNoticeMusic(); return false; });

    $("#import").click(function () { $("#import_dialog").dialog("open"); });
    $("#export").click(function () { ShowCookieData(); });
    $("#btnImport").click(function () { DoImport(); });

    var noticeMusic = cookieHelper.getNoticeMusic();
    if (noticeMusic != null && noticeMusic != "") {
        notice_music = noticeMusic;
    }

    $("#notice_music").val(notice_music);

    window.document.title = g_blinktitle;

    $("#notice_dialog").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false
    });
    $("#my_notice").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false
    });
    $("#notice_display_board").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false
    });
    $("#import_dialog").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false
    });
    $("#export_dialog").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: false
    });

    countDownSpan = $("#count_down span");
    DoRefresh();
});


function ShowGoodsHtml() {
    $("#last_update").html(lastUpdate)
    $("#goods_container").html("");

    var html = "";

    for (var i = 0; i < goods.length; i++) {
        html += GenerateHtmlByCategoryId(goods[i]["cid"], goods[i]["goods"]);
    }

    $("#goods_container").html(html + "<ul id=\"c_guanzhu\"></ul>");

    $("#loading").css("display", "none");
}

function GenerateHtmlByCategoryId(categoryId, goodsJson) {
    var html = "<ul id=\"c" + categoryId + "\">";
    for (var i = 0; i < goodsJson.length; i++) {
        html += GenerateGoodItemHtml(goodsJson[i]);
    }
    html += "</ul>";

    return html;
}

function GenerateGoodItemHtml(goodJson) {
    var html = "<li id=\"g" + goodJson["gid"] + "\"><div class=\"good-name\">" + goodJson["name"] + "</div><div class=\"percent\">" + goodJson["percent"] + "%</div><div class=\"normal-price\">" + GetPriceHtml(goodJson["prices"], currentPrices[goodJson["gid"]]) + "</div><div class=\"action\"><a href=\"http://www.kaixin001.com/!rich/!purchase.php?iid=" + goodJson["gid"] + "&purchase_price=" + currentPrices[goodJson["gid"]] + "\" class=\"buy\" target=\"_blank\">购买</a><a href=\"#\" class=\"guan-zhu\">关注</a></div></li>";

    return html;
}

function GetPriceHtml(prices, currentPrice) {
    var html = "";
    var items = prices.split(',');
    for (var i = 0; i < items.length - 1; i++) {
        if (items[i] == currentPrice) {
            html += "<span class=\"current-price\" title=\"" + items[i] + "\">" + GetDisplayPrice(items[i]) + "</span>,";
        }
        else {
            html += "<span title=\"" + items[i] + "\">" + GetDisplayPrice(items[i]) + "</span>,";
        }
    }

    if (items[items.length - 1] == currentPrice) {
        html += "<span class=\"current-price\" title=\"" + items[items.length - 1] + "\">" + GetDisplayPrice(items[i]) + "</span>,";
    }
    else {
        html += "<span title=\"" + items[i] + "\">" + GetDisplayPrice(items[items.length - 1]) + "</span>";
    }

    return html;
}

function GetDisplayPrice(price) {
    var displayed = "";
    if (price.length > 8) {
        displayed = price.substring(0, price.length - 8);

        var length = displayed.length;

        displayed += ".";

        for (var i = length; i < length + 2; i++) {
            displayed += price.charAt(i);
        }

        return RoundPrice(displayed) + "亿";
    }

    if (price.length > 4) {
        displayed = price.substring(0, price.length - 4);

        var length = displayed.length;

        displayed += ".";

        for (var i = length; i < length + 2; i++) {
            displayed += price.charAt(i);
        }

        return RoundPrice(displayed) + "万";
    }

    return price;
}

function RoundPrice(price) {
    while (true) {
        if (price.charAt(price.length - 1) == '0') {
            price = price.substring(0, price.length - 1);
        }
        else {
            break;
        }
    }

    if (price.charAt(price.length - 1) == '.') {
        price = price.substring(0, price.length - 1);
    }

    return price;
}