/*
 * jDigiClock plugin 2.1
 *
 * http://www.radoslavdimov.com/jquery-plugins/jquery-plugin-digiclock/
 *
 * Copyright (c) 2009 Radoslav Dimov
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */


(function($) {

	startUp = 0;
	curr_icon = 0;
	curr_text = "";
	curr_temp = 0;
		
    $.fn.extend({

        jdigiclock: function(options) {

            var defaults = {
                clockImagesPath: 'images/clock/',
                weatherImagesPath: 'images/weather/',
                lang: 'en',
                am_pm: false,
                weatherLocationCode: 'ASI|JP|JA013|KOBE',
                weatherMetric: 'C',
                weatherUpdate: 0,
                proxyType: 'php'
                
            };

            var regional = [];
            regional['en'] = {
                monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                dayNames: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
            }


            var options = $.extend(defaults, options);

            return this.each(function() {
                
                var $this = $(this);
                var o = options;
                $this.clockImagesPath = o.clockImagesPath;
                $this.weatherImagesPath = o.weatherImagesPath;
                $this.lang = regional[o.lang] == undefined ? regional['en'] : regional[o.lang];
                $this.am_pm = o.am_pm;
                $this.weatherLocationCode = o.weatherLocationCode;
                $this.weatherMetric = o.weatherMetric == 'C' ? 1 : 0;
                $this.weatherUpdate = o.weatherUpdate;
                $this.proxyType = o.proxyType;
                $this.currDate = '';
                $this.timeUpdate = '';


                var html = '<div id="plugin_container">';
//              html    += '<p id="left_arrow"><img src="/service/js/jdigiclock/images/icon_left.png" /></p>';
//              html    += '<p id="right_arrow"><img src="/service/js/jdigiclock/images/icon_right.png" /></p>';
//              html    += '<div id="digital_container">';
//              html    += '<div id="clock"></div>';
                html    += '<div id="weather"></div>';
                html    += '</div>';
//              html    += '<div id="forecast_container"></div>';
//              html    += '</div>';

                $this.html(html);

//              $this.displayClock($this);

                $this.displayWeather($this);               

/*
                var panel_pos = ($('#plugin_container > div').length - 1) * 500;
                var next = function() {
                    $('#right_arrow').unbind('click', next);
                    $('#plugin_container > div').filter(function(i) {
                        $(this).animate({'left': (i * 500) - 500 + 'px'}, 400, function() {
                            if (i == 0) {
                                $(this).appendTo('#plugin_container').css({'left':panel_pos + 'px'});
                            }
                            $('#right_arrow').bind('click', next);
                        });                        
                    });
                };
                $('#right_arrow').bind('click', next);

                var prev = function() {
                    $('#left_arrow').unbind('click', prev);
                    $('#plugin_container > div:last').prependTo('#plugin_container').css({'left':'-500px'});
                    $('#plugin_container > div').filter(function(i) {
                        $(this).animate({'left': i * 500 + 'px'}, 400, function() {
                            $('#left_arrow').bind('click', prev);
                        });
                    });
                };
                $('#left_arrow').bind('click', prev);
*/
            });
        }
    });
   
/*
    $.fn.displayClock = function(el) {
        $.fn.getTime(el);
        setTimeout(function() {$.fn.displayClock(el)}, $.fn.delay());
    }
*/
    $.fn.displayWeather = function(el) {
        $.fn.getWeather(el);
        if (el.weatherUpdate > 0) {
            setTimeout(function() {$.fn.displayWeather(el)}, (el.weatherUpdate * 60 * 1000));
        }
    }

    $.fn.delay = function() {
        var now = new Date();
        var delay = (60 - now.getSeconds()) * 1000;
        
        return delay;
    }
/*
    $.fn.getTime = function(el) {
        var now = new Date();
        var old = new Date();
        old.setTime(now.getTime() - 60000);
        
        var now_hours, now_minutes, old_hours, old_minutes, timeOld = '';
        now_hours =  now.getHours();
        now_minutes = now.getMinutes();
        old_hours =  old.getHours();
        old_minutes = old.getMinutes();

        if (el.am_pm) {
            var am_pm = now_hours > 11 ? 'pm' : 'am';
            now_hours = ((now_hours > 12) ? now_hours - 12 : now_hours);
            old_hours = ((old_hours > 12) ? old_hours - 12 : old_hours);
        } 

        now_hours   = ((now_hours <  10) ? "0" : "") + now_hours;
        now_minutes = ((now_minutes <  10) ? "0" : "") + now_minutes;
        old_hours   = ((old_hours <  10) ? "0" : "") + old_hours;
        old_minutes = ((old_minutes <  10) ? "0" : "") + old_minutes;
        // date
        el.currDate = el.lang.dayNames[now.getDay()] + ',&nbsp;' + now.getDate() + '&nbsp;' + el.lang.monthNames[now.getMonth()];
        // time update
        el.timeUpdate = el.currDate + ',&nbsp;' + now_hours + ':' + now_minutes;

        var firstHourDigit = old_hours.substr(0,1);
        var secondHourDigit = old_hours.substr(1,1);
        var firstMinuteDigit = old_minutes.substr(0,1);
        var secondMinuteDigit = old_minutes.substr(1,1);
        
        timeOld += '<div id="hours"><div class="line"></div>';
        timeOld += '<div id="hours_bg"><img src="' + el.clockImagesPath + 'clockbg1.png" /></div>';
        timeOld += '<img src="' + el.clockImagesPath + firstHourDigit + '.png" id="fhd" class="first_digit" />';
        timeOld += '<img src="' + el.clockImagesPath + secondHourDigit + '.png" id="shd" class="second_digit" />';
        timeOld += '</div>';
        timeOld += '<div id="minutes"><div class="line"></div>';
        if (el.am_pm) {
            timeOld += '<div id="am_pm"><img src="' + el.clockImagesPath + am_pm + '.png" /></div>';
        }
        timeOld += '<div id="minutes_bg"><img src="' + el.clockImagesPath + 'clockbg1.png" /></div>';
        timeOld += '<img src="' + el.clockImagesPath + firstMinuteDigit + '.png" id="fmd" class="first_digit" />';
        timeOld += '<img src="' + el.clockImagesPath + secondMinuteDigit + '.png" id="smd" class="second_digit" />';
        timeOld += '</div>';

        el.find('#clock').html(timeOld);

        // set minutes
        if (secondMinuteDigit != '9') {
            firstMinuteDigit = firstMinuteDigit + '1';
        }

        if (old_minutes == '59') {
            firstMinuteDigit = '511';
        }

        setTimeout(function() {
            $('#fmd').attr('src', el.clockImagesPath + firstMinuteDigit + '-1.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg2.png');
        },200);
        setTimeout(function() { $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg3.png')},250);
        setTimeout(function() {
            $('#fmd').attr('src', el.clockImagesPath + firstMinuteDigit + '-2.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg4.png');
        },400);
        setTimeout(function() { $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg5.png')},450);
        setTimeout(function() {
            $('#fmd').attr('src', el.clockImagesPath + firstMinuteDigit + '-3.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg6.png');
        },600);

        setTimeout(function() {
            $('#smd').attr('src', el.clockImagesPath + secondMinuteDigit + '-1.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg2.png');
        },200);
        setTimeout(function() { $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg3.png')},250);
        setTimeout(function() {
            $('#smd').attr('src', el.clockImagesPath + secondMinuteDigit + '-2.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg4.png');
        },400);
        setTimeout(function() { $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg5.png')},450);
        setTimeout(function() {
            $('#smd').attr('src', el.clockImagesPath + secondMinuteDigit + '-3.png');
            $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg6.png');
        },600);

        setTimeout(function() {$('#fmd').attr('src', el.clockImagesPath + now_minutes.substr(0,1) + '.png')},800);
        setTimeout(function() {$('#smd').attr('src', el.clockImagesPath + now_minutes.substr(1,1) + '.png')},800);
        setTimeout(function() { $('#minutes_bg img').attr('src', el.clockImagesPath + 'clockbg1.png')},850);

        // set hours
        if (now_minutes == '00') {
           
            if (el.am_pm) {
                if (now_hours == '00') {                   
                    firstHourDigit = firstHourDigit + '1';
                    now_hours = '12';
                } else if (now_hours == '01') {
                    firstHourDigit = '001';
                    secondHourDigit = '111';
                } else {
                    firstHourDigit = firstHourDigit + '1';
                }
            } else {
                if (now_hours != '10') {
                    firstHourDigit = firstHourDigit + '1';
                }

                if (now_hours == '20') {
                    firstHourDigit = '1';
                }

                if (now_hours == '00') {
                    firstHourDigit = firstHourDigit + '1';
                    secondHourDigit = secondHourDigit + '11';
                }
            }

            setTimeout(function() {
                $('#fhd').attr('src', el.clockImagesPath + firstHourDigit + '-1.png');
                $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg2.png');
            },200);
            setTimeout(function() { $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg3.png')},250);
            setTimeout(function() {
                $('#fhd').attr('src', el.clockImagesPath + firstHourDigit + '-2.png');
                $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg4.png');
            },400);
            setTimeout(function() { $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg5.png')},450);
            setTimeout(function() {
                $('#fhd').attr('src', el.clockImagesPath + firstHourDigit + '-3.png');
                $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg6.png');
            },600);

            setTimeout(function() {
            $('#shd').attr('src', el.clockImagesPath + secondHourDigit + '-1.png');
            $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg2.png');
            },200);
            setTimeout(function() { $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg3.png')},250);
            setTimeout(function() {
                $('#shd').attr('src', el.clockImagesPath + secondHourDigit + '-2.png');
                $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg4.png');
            },400);
            setTimeout(function() { $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg5.png')},450);
            setTimeout(function() {
                $('#shd').attr('src', el.clockImagesPath + secondHourDigit + '-3.png');
                $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg6.png');
            },600);

            setTimeout(function() {$('#fhd').attr('src', el.clockImagesPath + now_hours.substr(0,1) + '.png')},800);
            setTimeout(function() {$('#shd').attr('src', el.clockImagesPath + now_hours.substr(1,1) + '.png')},800);
            setTimeout(function() { $('#hours_bg img').attr('src', el.clockImagesPath + 'clockbg1.png')},850);
        }
    }
*/
    $.fn.getWeather = function(el) {
		var dict_weathertext = [];
		dict_weathertext = {
			"Sunny": "快晴",
			"Clear": "晴れ(晴天)",
			"Fair": "晴れ",
			"Sunny/Windy": "快晴/強風",
			"Clear/Windy": "晴れ(晴天)/強風",
			"Fair/Windy": "晴れ/強風",
			"Windy": "強風",
			"Partly Sunny": "曇り一時快晴",
			"Mostly Cloudy": "薄曇り",
			"Mostly cloudy": "薄曇り",
			"Partly Cloudy": "所により曇り",
			"Partly cloudy": "所により曇り",
			"Mostly Clear": "晴れ所により曇り",
			"Partly Sunny/Windy": "曇り一時快晴/強風",
			"Mostly Clear/Windy": "晴れ所により曇り/強風",
			"Mostly Sunny": "快晴所により曇り",
			"Mostly Sunny/Windy": "快晴所により曇り/強風",
			"Cloudy": "曇り",
			"Some Clouds":"一時曇り",
			"Overcast": "曇り(雲量多)",
			"Cloudy/Windy": "曇り/強風",
			"Overcast/Windy": "曇り(雲量多)/強風",
			"Mostly Cloudy/Windy": "薄曇り / 強風",
			"Mostly Cloudy": "薄曇り",
			"Light Drizzle": "弱い霧雨",
			"Drizzle": "霧雨",
			"Light Rain": "小雨",
			"Rain": "雨",
			"Heavy Rain": "大雨",
			"Light Rain/Fog": "弱い雨/霧",
			"Rain/Fog": "雨/霧",
			"Light Drizzle/Windy": "弱い霧雨/強風",
			"Drizzle/Windy": "霧雨/強風",
			"Light Rain/Windy": "小雨/強風",
			"Rain/Windy": "雨/強風",
			"Heavy Rain/Windy": "大雨/強風",
			"AM Light Rain": "午前中小雨",
			"PM Light Rain": "午後より小雨",
			"AM Light Rain/Windy": "午前中 弱いにわか雪/強風",
			"PM Light Rain/Windy": "午後から 弱いにわか雪/強風",
			"Rainshower": "にわか雨",
			"Shower": "にわか雨",
			"Heavy Rainshower": "強いにわか雨",
			"Heavy Rain Shower/Windy": "強いにわか雨/強風",
			"Light Rain Shower": "弱いにわか雨",
			"Lgt.rainshower": "弱いにわか雨",
			"AM Shower": "午前 にわか雨",
			"PM Shower": "午後 にわか雨",
			"Scattered Shower": "所により にわか雨",
			"Rain Shower/Windy": "にわか雨/強風",
			"Shower/Windy": "にわか雨/強風",
			"Light Rain Shower/Windy": "弱いにわか雨/強風",
			"AM Shower/Windy": "午前 にわか雨/強風",
			"PM Shower/Windy": "午後 にわか雨/強風",
			"Scattered Shower/Windy": "所により にわか雨/強風",
			"Few Showers": "曇り時々にわか雨",
			"Few Showers/Windy": "曇り時々にわか雨/強風",
			"Showers in the Vicinity": "狭い範囲でにわか雨",
			"Thunder in the Vicinity": "狭い範囲で雷",
			"Light Snow": "小雪",
			"Snow": "雪",
			"Heavy Snow": "大雪",
			"Light Snow Pellets": "弱い霙(みぞれ)",
			"Snow Pellets": "霙(みぞれ)",
			"Light Ice Pellets": "霰(あられ)",
			"Ice Pellets": "雹(ヒョウ)",
			"Wintery Weather": "厳しい寒さ",
			"Light Freezing Rain": "弱い凍雨",
			"Freezing Rain": "凍雨",
			"Flurries/Windy": "曇り一時雨又は雪/強風",
			"Light Flurries/Windy": "曇り一時小雨又は小雪/強風",
			"Light Snow/Windy": "小雪/強風",
			"Snow/Windy": "吹雪",
			"Heavy Snow/Windy": "強い吹雪",
			"Light Snow Pellets/Windy": "弱い霙(みぞれ)/強風",
			"Snow Pellets/Windy": "霙(みぞれ)/強風",
			"Light Ice Pellets/Windy": "霰(あられ)/強風",
			"Ice Pellets/Windy": "雹(ヒョウ)/強風",
			"Light Freezing Rain/Windy": "弱い凍雨/強風",
			"Freezing Rain/Windy": "凍雨/強風",
			"Wintery Mix": "厳冬",
			"Light Snow Grains": "弱い霰(あられ)",
			"Snow Grains": "霰(あられ)",
			"Rain/Snow": "雨時々雪",
			"Rain/snow": "雨時々雪",
			"Rain/Show/Windy": "雨時々雪/強風",
			"Light Rain/Freezing Rain": "弱い雨時々みぞれ",
			"Rain/Freezing Rain": "雨時々みぞれ",
			"Light Rain/Freezing Rain/Windy": "弱い雨時々みぞれ/強風",
			"Rain/Freezing Rain/Windy": "雨時々みぞれ/強風",
			"AM Snow": "午前中雪",
			"PM Snow": "午後より雪",
			"AM Light Snow": "午前中小雪",
			"PM Light Snow": "午後より小雪",
			"Ice Crystals": "氷晶",
			"Ice Crystals/Windy": "氷晶/強風",
			"Snow Showers": "にわか雪",
			"Heavy Snow Shower": "強いにわか雪",
			"Heavy Snow Shower/Windy": "強いにわか雪/強風",
			"PM Snow Showers": "午後にわか雪",
			"AM Snow Showers": "午前にわか雪",
			"Rain/Snow Showers": "雨のちにわか雪",
			"Snow Showers/Windy": "にわか雪/強風",
			"PM Snow Showers/Windy": "午後にわか雪/強風",
			"AM Snow Showers/Windy": "午前にわか雪/強風",
			"Rain/Snow Showers/Windy": "雨のちにわか雪/強風",
			"Light Snow Showers": "弱いにわか雪",
			"Lgt.snowshower": "弱いにわか雪",
			"Light Snow Showers/Windy": "弱いにわか雪/強風",
			"Flurries": "曇り一時雨又は雪",
			"Light Flurries": "曇り一時小雨又は小雪",
			"Scattered Flurries": "所により 曇り一時雨又は雪",
			"Few Flurries": "曇り 所により一時雨又は雪",
			"Few Flurries/Windy": "曇り 所により一時雨又は吹雪",
			"Scattered Snow Showers": "所によりにわか雪",
			"Scattered Snow Showers/Windy": "所によりにわか雪/強風",
			"Few Snow Showers": "曇り時々にわか雪",
			"Few Snow Showers/Windy": "曇り時々にわか雪/強風",
			"Freezing Drizzle": "霧氷",
			"Light Freezing Drizzle": "弱い霧氷",
			"Freezing Drizzle/Windy": "霧氷/強風",
			"Light Freezing Drizzle/Windy": "弱い霧氷/強風",
			"Thunderstorms": "雷又は雷雨",
			"Scattered Thunderstorms": "所により雷又は雷雨",
			"Thunderstorms/Windy": "雷又は雷雨/強風",
			"Scattered Thunderstorms/Windy": "所により雷又は雷雨/強風",
			"Rain/Thunder": "雷雨",
			"Light Thunderstorms/Rain": "弱い雷又は雷雨",
			"Thunderstorms/Rain": "雷又は雷雨",
			"Light Rain with Thunder": "弱い雷雨",
			"Rain with Thunder": "雷雨",
			"Fog": "霧",
			"Haze": "靄(もや)",
			"Mist": "霞(かすみ)",
			"Fog/Windy": "霧/強風",
			"Haze/Windy": "靄(もや)/強風",
			"Mist/Windy": "霞(かすみ)/強風",
			"Partial Fog": "部分的に霧気味",
			"Smoke": "もや",
			"Foggy": "霧がかった",
			"AM Fog/PM Sun": "午前霧/午後晴れ"
		};

//		if (startUp==1) {
//        	el.find('#weather').html('<p class="loading">Update Weather ...</p>');
//			startUp=0;
//		}
//      el.find('#forecast_container').html('<p class="loading">Update Weather ...</p>');
        var metric = el.weatherMetric == 1 ? 'C' : 'F';
        var proxy = '';

//        switch (el.proxyType) {
//            case 'php':
//                proxy = 'php/proxy.php';
//            break;
//            case 'asp':
//                proxy = 'asp/WeatherProxy.aspx';
//            break;
//        }
//
//        $.getJSON('js/digiclock/lib/proxy/' + proxy + '?location=' + el.weatherLocationCode + '&metric=' + el.weatherMetric, function(data) {
        proxy = '/test.php';
        $.getJSON(proxy + '?location=' + el.weatherLocationCode + '&metric=' + el.weatherMetric, function(data) {
			/* 天気情報（英語－日本語）変換 */
			if (dict_weathertext[data.curr_text]) {	/* 変換データあり */
				curr_text = dict_weathertext[data.curr_text];
				curr_icon = data.curr_icon;
				curr_temp = data.curr_temp;
				startUp=1;
			}
			
			if (startUp!=1)	 {							/* 変換データなし */
				return;
			}

			/* 更新中メッセージ表示消去 */
//            el.find('#weather .loading, #forecast_container .loading').hide();

			var p_temp = '<p class="temp">' + curr_temp + '&deg;<span class="metric">' + metric + '</span></p>';

//          el.find('#weather').css('background','url(' + el.weatherImagesPath + data.curr_icon + '.png) no-repeat');
            var weather = '<div id="local"><a class="city">' + '神戸の天気は</a>';
            weather += '<img src="' + el.weatherImagesPath + curr_icon + '.png" alt="' + curr_text + '" title="' + curr_text + '"/>';
			weather += '<div id="current_text">' + curr_text + '</div></div>';
            weather += '<div id="temp"><p id="date">' + el.currDate + '</p>' + p_temp + '</div>';
            el.find('#weather').html(weather);

            // forecast
/*
            el.find('#forecast_container').append('<div id="current"></div>');
            var curr_for = curr_temp + '<p class="high_low">' + data.forecast[0].day_htemp + '&deg;&nbsp;/&nbsp;' + data.forecast[0].day_ltemp + '&deg;</p>';
            curr_for    += '<p class="city">' + data.city + '</p>';
            curr_for    += '<p class="text">' + data.forecast[0].day_text + '</p>';
            el.find('#current').css('background','url(' + el.weatherImagesPath + data.forecast[0].day_icon + '.png) 50% 0 no-repeat').append(curr_for);

            el.find('#forecast_container').append('<ul id="forecast"></ul>');
            data.forecast.shift();
            for (var i in data.forecast) {
                var d_date = new Date(data.forecast[i].day_date);
                var day_name = el.lang.dayNames[d_date.getDay()];
                var forecast = '<li>';
                forecast    += '<p>' + day_name + '</p>';
                forecast    += '<img src="' + el.weatherImagesPath + data.forecast[i].day_icon + '.png" alt="' + data.forecast[i].day_text + '" title="' + data.forecast[i].day_text + '" />';
                forecast    += '<p>' + data.forecast[i].day_htemp + '&deg;&nbsp;/&nbsp;' + data.forecast[i].day_ltemp + '&deg;</p>';
                forecast    += '</li>';
                el.find('#forecast').append(forecast);
            }

            el.find('#forecast_container').append('<div id="update"><img src="/service/js/jdigiclock/images/refresh_01.png" alt="reload" title="reload" id="reload" />' + el.timeUpdate + '</div>');
*/
            $('#reload').click(function() {
                el.find('#weather').html('');
                el.find('#forecast_container').html('');
                $.fn.getWeather(el);
            });
        });
    }

})(jQuery);
