﻿//json2.js
if(!this.JSON)this.JSON={}; (function(){function k(a){return a<10?"0"+a:a}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+k(this.getUTCMonth()+1)+"-"+k(this.getUTCDate())+"T"+k(this.getUTCHours())+":"+k(this.getUTCMinutes())+":"+k(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var n=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o= /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,f,l,q={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function p(a){o.lastIndex=0;return o.test(a)?'"'+a.replace(o,function(c){var d=q[c];return typeof d==="string"?d:"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function m(a,c){var d,g,j=f,e,b=c[a];if(b&&typeof b==="object"&&typeof b.toJSON==="function")b=b.toJSON(a); if(typeof i==="function")b=i.call(c,a,b);switch(typeof b){case "string":return p(b);case "number":return isFinite(b)?String(b):"null";case "boolean":case "null":return String(b);case "object":if(!b)return"null";f+=l;e=[];if(Object.prototype.toString.apply(b)==="[object Array]"){g=b.length;for(a=0;a<g;a+=1)e[a]=m(a,b)||"null";c=e.length===0?"[]":f?"[\n"+f+e.join(",\n"+f)+"\n"+j+"]":"["+e.join(",")+"]";f=j;return c}if(i&&typeof i==="object"){g=i.length;for(a=0;a<g;a+=1){d=i[a];if(typeof d==="string")if(c= m(d,b))e.push(p(d)+(f?": ":":")+c)}}else for(d in b)if(Object.hasOwnProperty.call(b,d))if(c=m(d,b))e.push(p(d)+(f?": ":":")+c);c=e.length===0?"{}":f?"{\n"+f+e.join(",\n"+f)+"\n"+j+"}":"{"+e.join(",")+"}";f=j;return c}}if(typeof JSON.stringify!=="function")JSON.stringify=function(a,c,d){var g;l=f="";if(typeof d==="number")for(g=0;g<d;g+=1)l+=" ";else if(typeof d==="string")l=d;if((i=c)&&typeof c!=="function"&&(typeof c!=="object"||typeof c.length!=="number"))throw new Error("JSON.stringify");return m("", {"":a})};if(typeof JSON.parse!=="function")JSON.parse=function(a,c){function d(g,j){var e,b,h=g[j];if(h&&typeof h==="object")for(e in h)if(Object.hasOwnProperty.call(h,e)){b=d(h,e);if(b!==undefined)h[e]=b;else delete h[e]}return c.call(g,j,h)}n.lastIndex=0;if(n.test(a))a=a.replace(n,function(g){return"\\u"+("0000"+g.charCodeAt(0).toString(16)).slice(-4)});if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){a=eval("("+a+")");return typeof c==="function"?d({"":a},""):a}throw new SyntaxError("JSON.parse");}})();
//weather
window.ThinkPage = window.ThinkPage || {};
window.ThinkPage.Weather = window.ThinkPage.Weather || {};
window.ThinkPage.Weather.Common = (function () {
    var Weather = function () {

        var that = this;
        var isLoading = false;

        //fixPng
        this.FixPng = function (a) { var b = window.navigator.userAgent.toLowerCase(); if (/msie 6/.test(b)) { b = "display:inline-block;" + a.style.cssText; b = '<span id="' + a.id + '" class="' + a.className + '" title="' + a.title + '" style="width:' + a.clientWidth + 'px; height:' + a.clientHeight + 'px;' + b + ';filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + a.src + '\', sizingMethod=\'scale\');"></span>'; a.outerHTML = b; } };

        var onBeginRequest = function () {
            isLoading = true;
            //$("#ThinkpageWeatherWidget img").fadeOut('fast');
            $("#ThinkpageWeatherWidget span[id$='ltlCity']").fadeOut('fast');
            $("#ThinkpageWeatherWidget span[id$='ltlText']").fadeOut('fast');
            $("#ThinkpageWeatherWidget .forecastText").fadeOut('fast');
            $("#ThinkpageWeatherWidget .temp").fadeOut('fast');
            $("#ThinkpageWeatherWidget .value").fadeOut('fast');
            $("#ThinkpageWeatherWidget #Loading").fadeIn();
        };

        var onEndRequest = function () {
            isLoading = false;
            //$("#ThinkpageWeatherWidget img").fadeIn('fast');
            $("#ThinkpageWeatherWidget span[id$='ltlCity']").fadeIn('fast');
            $("#ThinkpageWeatherWidget span[id$='ltlText']").fadeIn('fast');
            $("#ThinkpageWeatherWidget .forecastText").fadeIn('fast');
            $("#ThinkpageWeatherWidget .temp").fadeIn('fast');
            $("#ThinkpageWeatherWidget .value").fadeIn('fast');
            $("#ThinkpageWeatherWidget #Loading").fadeOut();
        };

        var onFailure = function (xhr, status, error) {
            $("div[id$='weatherAJAX']").html("Error: " + error);
            onEndRequest();
        };

        this.DisplayWeather = function (city) {
            if (!isLoading) {
                onBeginRequest();
                $(window).trigger("THINKPAGE_WEATHER_REQUEST", city);
                thinkpage_weather_req["City"] = city;
                thinkpage_weather_req["CityName"] = null;
                var that = this;
                $.ajax({
                    type: "POST",
                    url: "/weather/WeatherService.asmx/GetWeatherJson",
                    data: "{jsonReq:'" + JSON.stringify(thinkpage_weather_req) + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        onEndRequest();
                        var obj = result["d"];
                        var weather = obj["Weathers"][0];
                        $(window).trigger("THINKPAGE_WEATHER_RESPONSE", obj);
                        $(".linkCity[href*='cid=']").attr("href", "/weather/?cid=" + obj["Request"]["City"]);
                        $("span[id$='ltlCity']").text(weather["City"]);
                        if ($(".currentIcon").length != 0) {
                            $(".currentIcon").attr({ "src": that.GetIcon("cip", weather["Current"]["Code"], weather["LastBuildDate"]), "title": $(".currentIcon").attr("title").replace(/:(.*)$/ig, ": " + weather["LastBuildDate"]) });
                            if ($.browser.msie && $.browser.version == "6.0") {
                                var style = $(".currentIcon").attr("style").replace(/src='(.*?)'/ig, "src='" + that.GetIcon("cip", weather["Current"]["Code"], weather["LastBuildDate"]) + "'");
                                $(".currentIcon").attr("style", style);
                            }
                        }
                        $("span[id$='ltlText']").text(weather["Current"]["Text"]);
                        $("span[id$='ltlTemperature'] .temp").text(weather["Current"]["Temperature"]);
                        $("span[id$='ltlFeel'] .temp").text(weather["Current"]["Chill"]);
                        if (obj["Request"]["Language"] == "en") {
                            $("span[id$='ltlSpeed'] .value").text(weather["Current"]["Direction"] + " " + weather["Current"]["Speed"]);
                        } else {
                            $("span[id$='ltlSpeed'] .value").text(weather["Current"]["Direction"] + convertWind(weather["Current"]["Speed"]));
                        };
                        $("span[id$='ltlSpeed']").attr("title", weather["Current"]["Speed"] + "km/h");
                        $("span[id$='ltlVisibility'] .value").text(weather["Current"]["Visibility"]);
                        $("span[id$='ltlSunrise'] .value").text(weather["Current"]["Sunrise"]);
                        $("span[id$='ltlSunset'] .value").text(weather["Current"]["Sunset"]);
                        $("span[id$='ltlHumidity'] .value").text(weather["Current"]["Humidity"]);
                        $("span[id$='ltlPressure'] .value").text(weather["Current"]["Pressure"]);
                        $("span[id$='ltlDate']").text(weather["LastBuildDate"]);

                        var forecast = $("div[id$='divForecastWeather'] .forecast");
                        for (var i = 0; i < forecast.length; i++) {
                            $(forecast[i]).find(".forecastDay").text(weather["Forecast"][i]["Day"]);
                            $(forecast[i]).find(".forecastIcon").attr({ "src": that.GetIcon("fip", weather["Forecast"][i]["Code"], weather["LastBuildDate"]), "title": weather["Forecast"][i]["Info"], "alt": weather["Forecast"][i]["Text"] });
                            if ($.browser.msie && $.browser.version == "6.0") {
                                var style = $(forecast[i]).find(".forecastIcon").attr("style").replace(/src='(.*?)'/ig, "src='" + that.GetIcon("fip", weather["Forecast"][i]["Code"], weather["LastBuildDate"]) + "'");
                                $(forecast[i]).find(".forecastIcon").attr("style", style);
                            }
                            if ($(forecast[i]).find(".forecastTemp").length != 0)
                                $(forecast[i]).find(".forecastTemp").attr({ "title": $(forecast[i]).find(".forecastTemp").attr("title").match(/^(.*):/ig) + weather["Forecast"][i]["Cop"] });
                            $(forecast[i]).find(".forecastText").text(weather["Forecast"][i]["Text"]);
                            $(forecast[i]).find(".forecastCop").text($(forecast[i]).find(".forecastCop").text().match(/^(.*):/ig) + weather["Forecast"][i]["Cop"]);
                            $(forecast[i]).find(".high").text(weather["Forecast"][i]["High"]);
                            $(forecast[i]).find(".low").text(weather["Forecast"][i]["Low"]);
                        };
                        that.ToggleAD(true);
                    },
                    error: onFailure
                });
            }
        };

        this.SearchCity = function (keyword, context, callback) {
            if (!isLoading) {
                onBeginRequest();
                var that = this;
                $.ajax({
                    type: "POST",
                    url: "/weather/WeatherService.asmx/SearchCity",
                    data: "{keyword:'" + keyword + "', lang:'" + thinkpage_weather_req["Language"] + "', provider:'" + thinkpage_weather_req["Provider"] + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var obj = result["d"];
                        onEndRequest();
                        callback.call(context, obj);
                    },
                    error: onFailure
                });
            }
        };

        this.GetCities = function (state) {
            if (!isLoading) {
                onBeginRequest();
                var that = this;
                $.ajax({
                    type: "POST",
                    url: "/weather/WeatherService.asmx/GetCities",
                    data: "{state:\"" + state + "\", lang:\"" + thinkpage_weather_req["Language"] + "\", provider:\"" + thinkpage_weather_req["Provider"] + "\"}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        isLoading = false;
                        $("select[id$='ddlCity']").empty();
                        jQuery.each(result["d"], function (i, val) {
                            $("select[id$='ddlCity']")[0].options.add(new Option(val["value"], val["name"]));
                        });
                        that.DisplayWeather($("select[id$='ddlCity']").val());
                    },
                    error: onFailure
                });
            }
        };

        this.ToggleAD = function (closeAD) {
            if ($("#divAD")) {
                if ($("#divAD").css("display") != "none" || closeAD) {
                    $("#divAD").hide();
                    if ($("#spanDate")) {
                        $("#spanDate").show();
                    }
                } else {
                    $("#divAD").show();
                    if ($("#spanDate")) {
                        $("#spanDate").hide();
                    }
                }
            }
        };

        this.GetIcon = function (type, code, time) {
            var p = $("span[id$='" + type + "']").text() || type;
            if (p.match(/{QQ}/ig) != null) {
                var q = ["lrain", "lrain", "lrain", "lrain", "lrain", "rs", "rs", "rs", "rs", "srain", "mrain", "brain", "drain", "ssnow", "bsnow", "sand", "msnow", "lrain", "rs", "fog", "fog", "fog", "fog", "sand", "sand", "shade", "shade", "night", "cloud", "night", "cloud", "3", "sun", "night", "cloud", "lrain", "sun", "lrain", "lrain", "srain", "drain", "ssnow", "bsnow", "bsnow", "sun", "srain", "ssnow", "lrain"];
                return p.replace("{QQ}", q[code]);
            } else if (p.match(/{YAHOO}/ig) != null) {
                var h = new Date(time.replace(/-/ig, "/")).getHours();
                var suffix = "";
                if (h > 5 && h < 19)
                    suffix = "d";
                else
                    suffix = "n";
                return p.replace("{YAHOO}", code + suffix);
            } else {
                return p.replace("{CODE}", code);
            }
        };

        var convertTempUnit = function (value, unit) {
            return Math.round(unit == "F" ? value * 9 / 5 + 32 : (value - 32) * 5 / 9);
        };

        var convertWind = function (kmh) {
            if (isNaN(kmh))
                return "";
            return Math.round(Math.pow(kmh / (3.6 * 0.836), 2 / 3));
        };

        var toggleTempUnit = function () {
            if (isLoading)
                return;
            thinkpage_weather_req["Unit"] = thinkpage_weather_req["Unit"] == "C" ? "F" : "C";
            $(".temp").each(function () { $(this).text(convertTempUnit(parseFloat($(this).text()), thinkpage_weather_req["Unit"])) });
            $(".unit").each(function () { $(this).text(thinkpage_weather_req["Unit"]) });
            var temp = $("span[id$='ltlTemperature']");
            temp[0].title = temp[0].title.replace(temp[0].title.match(/(\d+)/ig), convertTempUnit(parseFloat(temp[0].title.match(/(\d+)/ig)), thinkpage_weather_req["Unit"])).replace(thinkpage_weather_req["Unit"] == "C" ? "F" : "C", thinkpage_weather_req["Unit"]);
        };

        var bindTempUnitEvent = function () {
            $(".temp").css("cursor", "pointer").click(toggleTempUnit);
        };

        var unbindTempUnitEvent = function () {
            $(".temp").css("cursor", "").unbind();
        };

        var updateHits = function (bIconHits, bLinkHits, bAdHits) {
            $.ajax({
                type: "POST",
                url: "/weather/WeatherService.asmx/UpdateHits",
                data: "{bIconHits:\"" + bIconHits + "\", bLinkHits:\"" + bLinkHits + "\", bAdHits:\"" + bAdHits + "\"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        };

        var init = function () {
            if (thinkpage_weather_req["LinksType"] == 0) {
                $("a.linkCity").each(function (i, l) { $(l).replaceWith($(l).html()) });
            };

            bindTempUnitEvent();

            $(".linkCity:has(img)").click(function () {
                updateHits(true, false, false);
            });
            $(".linkCity[href*='thinkpage.cn']:not(:has(img))").click(function () {
                updateHits(false, true, false);
            });
            $("#divInfo a").click(function () {
                updateHits(false, false, true);
            });
        };

        $("#ThinkpageWeatherWidget").ready(init);
    };
    return new Weather();
})();