$().ready(function() {

    //
    // definition
    //

    var duration = 0;

    // for twitter
    var twitter = {
        update: function(query, target) {
            $.getJSON(
                'http://search.twitter.com/search.json?callback=?',
                { 'q' : query },
                function(json) {
                    var results = json.results;
                    for(var i = 0; i < results.length; ++i) {
                        target.append(twitter.createTweetElement(results[i]));
                    }
                }
            )
        },
        createTweetElement: function(result) {
            return $('<li></li>').addClass('group')
            .append($('<div></div>').addClass('img')
                    .append($('<img></img>').attr({
                        'src': result.profile_image_url,
                        'width': 48,
                        'height': 48,
                        'alt': result.from_user
                    })))
            .append($('<div></div>').addClass('txt')
                    .append($('<h4></h4>')
                            .append($('<a></a>')
                                    .attr('href', 'http://twitter.com/' + result.from_user)
                                    .html(result.from_user))
                            .append($('<span></span>').html(twitter.dateFormat(result.created_at))))
                    .append($('<p></p>').addClass('tweetText').html(result.text)))
        },
        dateFormat: function(date_string) {
            var date = new Date(date_string);
            
            var minutes = date.getMinutes();
            if(minutes < 10) {
                minutes = '0' + minutes;
            }

            return date.getFullYear() + '.' +
                (date.getMonth() + 1) + '.' +
                date.getDate() + ' ' +
                date.getHours() + ':' +
                minutes;
        },
        watch: function() {
            var area_tweet = $('#blockMain .unitPostTweet textarea')
            var notice = $('#blockMain .unitPostTweet .notice');
            var btn_tweet = $('#blockMain .unitPostTweet .areaBtnTweet .submit');

            area_tweet.keyup(function() {
                twitter.watchUpdate(area_tweet, notice, btn_tweet)
            });

            area_tweet.keyup();
        },
        watchUpdate: function(area_tweet, notice, btn_tweet) {
            notice.html(140 - area_tweet.val().length);
            
            if(twitter.isValid(area_tweet.val())) {
                area_tweet.removeClass('alert');
                notice.removeClass('alert');
                btn_tweet.removeAttr('disabled');
            }
            else {
                area_tweet.addClass('alert');
                notice.addClass('alert');
                btn_tweet.attr('disabled', 'disabled');
            }
        },
        isValid: function(tweet) {
            if(tweet.length <= 140) {
                return true;
            }
            else {
                return false;
            }
        }
    };

    // content switcher in district pages
    var switcher = {
        width: 685,
        height: 410,
        block: $('#blockAna .right .switch'),
        kml: '',
        types: ['top', 'movie', 'report', 'course'],
        init: function() {
            var type = 0;
            var type_name = 'top';
            var params = location.search.substring(1).split('&');

            for(var i = 0; i < params.length; ++i) {
                var p = params[i].split('=');
                if(p[0] == 'content') {
                    for(var j = 0; j < switcher.types.length; ++j) {
                        if(switcher.types[j] == p[1]) {
                            type = j;
                            type_name = p[1];
                        }
                    }
                }
            }

            switcher.display(type);
            submenuActivate(type_name);
        },
        display: function(index) {
            if(index < 0 || switcher.types.length < index) return;

            // slide to the content
            switcher.block.animate({
                'top': -switcher.height * index  + 'px'
            }, duration);

            // change control face
            var body = $('body');
            $.each(switcher.types, function() {
                body.removeClass(this + '');
            });
            body.addClass(switcher.types[index]);
        }
    };

    // movie
    var movie = {
        pause: function() {
            // player: defined in index.html
            if(player) {
                player.pauseVideo();
            }
        }
    };

    // report
    var report = {
        target: $('#anaReport .report'),
        thumbs: $('#anaReport .thumbList li'),
        display: function(index) {
            report.target.animate({
                'left': -switcher.width * index + 'px'
            }, duration);
        },
        init: function() {
            report.thumbs.each(function() {
                $(this).click(function() {
                    report.display($(this).index());
                    return false;
                });
            });
        }
    };

    // google maps
    var map = {
        target: $('#anaCourse .map').get(0),
        init: function(kml) {
            var map_body = new google.maps.Map(map.target, {
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            
            var layer = new google.maps.KmlLayer(kml)
            layer.setMap(map_body);
        }
    };

    // sub menu button activation
    var submenuActivate = function(name) {
        $('#navL li').each(function() {
            var navi = $(this);
            var class_name = navi.attr('class');
            
            if(name == this.className) {
                $('a', navi).addClass('active');
                $('img', this).hover(
                    function() {
                        $(this).attr('src', '/drive/memories/images/common/navL_' + class_name + '_a.png');
                    },
                    function() {
                        $(this).attr('src', '/drive/memories/images/common/navL_' + class_name + '_a.png');
                    })
                    .attr('src', '/drive/memories/images/common/navL_' + class_name + '_a.png');
            }
            else {
                $('a', navi).removeClass('active');
                $('img', this).hover(
                    function() {
                        $(this).attr('src', '/drive/memories/images/common/navL_' + class_name + '_o.png');
                    },
                    function() {
                        $(this).attr('src', '/drive/memories/images/common/navL_' + class_name + '.png');
                    })
                    .attr('src', '/drive/memories/images/common/navL_' + class_name + '.png');
            }
        });
    };

    
    //
    // dispatcher
    //

    // for all
    dispatcher('.', function () {
        $(function () {
            // for IE6, 7
            var hide_trash = setInterval(function() {
                $('img[name="s_i_sonysonpocojpmain"]').each(function() {
                    $(this).css({
                        position: 'absolute',
                        top: '-100px'
                    });
                    clearInterval(hide_trash);
                });
            }, 100);
            
            // animation
            $(document).keydown(function(e) {
                if(e.keyCode == 16) {
                    duration = 2000;
                }
            });

            $(document).keyup(function(e) {
                if(e.keyCode == 16) {
                    duration = 0;
                }
            });
        });
    });

    // content switcher for district
    dispatcher('^/drive/memories/[^/]+/index.html', function () {
        $(function () {
            // switcher init
            switcher.init();

            // report init
            report.init();

            // control
            $('#blockAna .left .top').click(function() {
                switcher.display(0);
                movie.pause();
                submenuActivate('top');
                return false;
            });
            $('#blockAna .left .movie').click(function() {
                switcher.display(1);
                submenuActivate('movie');
                return false;
            });
            $('#blockAna .left .report').click(function() {
                switcher.display(2);
                movie.pause();
                submenuActivate('report');
                return false;
            });
            $('#blockAna .left .course').click(function() {
                switcher.display(3);
                movie.pause();
                submenuActivate('course');
                return false;
            });

            // tweet
            twitter.watch();
        });
    });
    
    // for top
    dispatcher('^/drive/memories/index.html$|^/drive/memories/$', function () {
        $(function() {
            // update hash tag search
            twitter.update('#drive_kyuoki', $('#blockKyushu .tweetList'));
            twitter.update('#drive_chushikoku', $('#blockChugoku .tweetList'));
            twitter.update('#drive_kinki', $('#blockKinki .tweetList'));
            twitter.update('#drive_chubu', $('#blockChubu .tweetList'));
            twitter.update('#drive_kanto', $('#blockKanto .tweetList'));
            twitter.update('#drive_tohoku', $('#blockTohoku .tweetList'));
            twitter.update('#drive_hokkaido', $('#blockHokkaido .tweetList'));
        });
    });

    // for hokkaido
    dispatcher('^/drive/memories/hokkaido', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_hokkaido', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/hokkaido.kml');
        });
    });

    // for tohoku
    dispatcher('^/drive/memories/tohoku', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_tohoku', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/tohoku.kml');
        });
    });

    // for kantozm
    dispatcher('^/drive/memories/kantozm', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_kanto', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/kantozm.kml');
        });
    });

    // for kantosk
    dispatcher('^/drive/memories/kantosk', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_kanto', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/kantosk.kml');
        });
    });

    // for chubu
    dispatcher('^/drive/memories/chubu', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_chubu', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/chubu.kml');
        });
    });

    // for kinki
    dispatcher('^/drive/memories/kinki', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_kinki', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/kinki.kml');
        });
    });

    // for chugoku_shikoku
    dispatcher('^/drive/memories/chugoku_shikoku', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_chushikoku', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/chugoku_shikoku.kml');
        });
    });

    // for kyushu_okinawa
    dispatcher('^/drive/memories/kyushu_okinawa', function () {
        $(function () {
            // update hash tag search
            twitter.update('#drive_kyuoki', $('#blockMain .tweetList'));

            // map
            map.init('http://with.sonysonpo.co.jp/drive/memories/kml/kyushu_okinawa.kml');
        });
    });

    function dispatcher(path, func) {
        dispatcher.path_func = dispatcher.path_func || []
        if (func) return dispatcher.path_func.push([path, func]);
        for(var i = 0, l = dispatcher.path_func.length; i < l; ++i) {
            var func = dispatcher.path_func[i];
            var match = path.match(func[0]);
            match && func[1](match);
        };
    };
    
    dispatcher(location.pathname);

});
