/*----------------------------------------------------------------
    各種機能プラグイン
    1.画像切り替え
    2.トラッキング抽出用コード挿入
    3.背景ずれようリサイズ
    4.リストタブ
    5.png画像入替（IE6以下のみ）
    6.画像のJSON関連(TOP)
    7.コンテンツ写真制御
    8.画像一覧
    9.地図で一覧用ポップアップ
    10.グーグルマップ
----------------------------------------------------------------*/

/*----------------------------------------------------------------
    画像切り替え
----------------------------------------------------------------*/
(function($){
    $.fn.mouseover = function(settings){

        var settings = $.extend({
            name: "_over"
        }, settings);

        return this.each(function(){
            if (!this) return false;
            var src   = $(this).attr("src");
            var ftype = src.substring(src.lastIndexOf('.'), src.length);
            var hsrc  = src.replace(ftype, settings.name + ftype);
            $(this).hover(function (){
                $(this).attr("src",hsrc);
            }, function(){
                $(this).attr("src",src);
            });
        });
    }

/*----------------------------------------------------------------
    トラッキング抽出用コード挿入
----------------------------------------------------------------*/
    $.fn.tracking = function(settings){

        var settings = $.extend({
            name: "/track/a8/",
            type: ""
        }, settings);

        return this.each(function(){
            if (!this) return false;
            $(this).click(function(){
                var url      = $(this).attr("href");
                var this_url = location.pathname;
                link = url.match(settings.type);
                pageTracker._trackPageview(settings.name + link + this_url);
                //alert("pageTracker._trackPageview( "+ settings.name + link + this_url +" );");
                //return false;
            });
        });
    }

/*----------------------------------------------------------------
    背景ずれようリサイズ
----------------------------------------------------------------*/
    $.fn.resizebg = function(){
        var size   = $(this).width();
        var resize = size - ( size % 2 );
        resize     = resize + "px";
        $(this).width(resize);
        $(window).bind("resize",function(){
            var size   = $(this).width();
            var resize = size - ( size % 2 );
            resize     = resize + "px";
            $(this).width(resize);
        })
    }

/*----------------------------------------------------------------
    リストタブ
----------------------------------------------------------------*/
    $.fn.list_tab = function(){
        var tab    = $(this).attr("class");
        var target = $(this);
        $(this).find("img").hover(function(){
            target.attr("class", $(this).attr("class"));
        },function(){
            target.attr("class", tab);
        });
    }

/*----------------------------------------------------------------
    png画像入替（IE6以下のみ）
----------------------------------------------------------------*/
    $.fn.iepng = function(settings){

        var settings = $.extend({
            url:  "./image/ie6/",
            type: ".gif"
        }, settings);

        if(!$.support.boxModel) {
            return this.each(function(){
                if (!this) return false;
                var src  = $(this).attr("src");
                var file = src.substring(src.lastIndexOf('/'), src.length);
                var csrc = file.replace(".png",settings.type);
                $(this).attr("src", settings.url+csrc);
            });
        }
    }

/*----------------------------------------------------------------
    画像のJSON関連(TOP)
----------------------------------------------------------------*/
    $.fn.json_top = function(settings){

        var settings = $.extend({
            url:  "./lib/json.php",
            img:  "./photo/"
        }, settings);

        var target = $(this);

        //初期データセット
        var data_set = function(data) {
            var item   = {};
            item.line  = data.length -1;
            item.count = 0;
            item.data  = data;
            img_load(item, "");
        }

        //ループ処理
        var loop_img = function(item){
            var loop = setInterval(function(){
                item.count++;
                if(item.count > item.line) item.count = 0;
                img_load(item, loop);
            },3000);
        }

        //画像ローディング処理
        var img_load = function(item, loop){
            clearInterval(loop);
            var img_url = "./lib/resize.php?img=../" + settings.img + item.data[item.count].thum2 + "&w=310?" + (new Date()).getTime();
            target.animate({opacity: 0}, {duration: 1100,
                complete: function(){
                    target.attr("src", img_url);
                    var imgload = new Image();
                    imgload.src = img_url;
                    imgload.onload = function(){
                        target.animate( {opacity: 1},{duration: 1100, complete: function(){loop_img(item)}});
                    }
                }
            });
        }

        $.getJSON(settings.url,data_set);

    }

/*----------------------------------------------------------------
    コンテンツ写真制御
----------------------------------------------------------------*/
    $.fn.photo = function(settings){

        var settings = $.extend({
            url:   "",
            img:   "",
            main:  "",
            text:  "",
            pager: "",
            list:  "",
            limit: "",
            load:  "",
            close: ""
        }, settings);

        /*-------------------------------------------------------
           各種初期指定
        -------------------------------------------------------*/
        var main   = $(settings.main + " #targetImg");
        var zoom   = $(settings.main + " #zoom a");
        var next   = $(settings.main + " #next a");
        var pre    = $(settings.main + " #pre a");
        var name   = $(settings.text + " h4");
        var text   = $(settings.text + " p");
        var list   = $(settings.list + " > li");
        var pager  = $(settings.pager + " li");
        var body   = $("body");
        var limit  = settings.limit;
        var start  = 1;
        var item   = {};
        var box    = "<div id='imgWrap'></div>" +
                     "<div id='popImg'>"+
                         "<img src='" + settings.load + "?" + (new Date()).getTime() + "' alt='' />"+
                         "<div id='popText'>"+
                             "<h4></h4>"+
                             "<p></p>"+
                         "</div>"+
                         "<p id='close'><a href='#'><img src='" + settings.close + "' alt='close' /></a></p>"+
                     "</div>";

        /*-------------------------------------------------------
           メイン写真切り替え共通処理（サムネ・ネクスト・プレ）
        -------------------------------------------------------*/
        var data_change = function(item) {

            //メイン画像読み込み
            var url = "../lib/resize.php?img=" + settings.img + item.data[item.target].thum2 + "&w=400&dummy=" + (new Date()).getTime();
            main.animate({opacity: 0}, {duration: 600,
                complete: function(){
                    main.attr("src",url);
                    var thumload = new Image();
                    thumload.src = url;
                    thumload.onload = function(){
                        main.animate( {opacity: 1},{duration: 600});
                    }
                }
            });

            //拡大画像アドレス入れ替え
            zoom.attr("href", "../photo/" + item.data[item.target].main_img);

            //ネクスト入れ替え
            if(item.target == item.max){
                next.attr("href", "../lib/resize.php?img=" + settings.img + item.data[item.max].thum2 + "&w=400");
            } else {
                next.attr("href", "../lib/resize.php?img=" + settings.img + item.data[item.target+1].thum2 + "&w=400");
            }

            //プレ入れ替え
            if(item.target){
                pre.attr("href", "../lib/resize.php?img=" + settings.img + item.data[item.target-1].thum2 + "&w=400");
            } else {
                pre.attr("href", "../lib/resize.php?img=" + settings.img + item.data[item.max].thum2 + "&w=400");
            }

            //文章入れ替え
            text.html(item.data[item.target].photo_text);
            name.html("『" + item.data[item.target].photo_name + "』");
            name.append("<span>" + item.data[item.target].photo_date + "</span>");
        }

        /*-------------------------------------------------------
           リストイメージ変更処理
        -------------------------------------------------------*/
        var img_list = function(item){
            var list_start = (start - 1) * limit;
            list.css("display","block");
            list.each(function(){
                if(item.max >= list_start){
                    $(this).children().children().attr("src", settings.img + item.data[list_start].thum1);
                    list_start++;
                } else {
                    $(this).css("display","none");
                }
            });
        }

        /*-------------------------------------------------------
           ページャーセット
        -------------------------------------------------------*/
        var pager_set = function(){
            pager.removeClass("pageThis");
            pager.each(function(i,v){
                i++;
                if(start == i){
                    $(this).addClass("pageThis").html("【" + i + "】");
                } else {
                    $(this).html("<a href='javascript:void(0)\;'>" + i + "</a>");
                }
            });
        }

        /*-------------------------------------------------------
           イメージポップアップ
        -------------------------------------------------------*/
        var img_pop = function(item){
            //初期データ設定
            var body_height = body.height() + "px";
            var img_max_h   = Math.floor($(window).height() * 0.8);
            var img_url     = settings.img + item.data[item.target].main_img + "?" + (new Date()).getTime();
            body.prepend(box);
            var wrap      = $("#imgWrap");
            var pop_img   = $("#popImg");
            var pop_text  = $("#popText");
            var pop_close = $("#close");
            pop_text.children("h4").html(item.data[item.target].photo_name);
            pop_text.children("p").html(item.data[item.target].photo_text);
            var text_h   = pop_text.height() + 20;
            pop_img.css("opacity","0");
            pop_text.css("height","0px");
            pop_close.css({display: "none"});

            //アニメーションスタート（暗転開始）
            wrap.css({ height: body_height, opacity: "0"}).animate({opacity: 0.8},{duration: 700,
                complete: function(){
                    //IE6用（後方互換モード対策）
                    if(!$.support.boxModel) {
                        body.scrollTop(0).css("overflow","hidden");
                    }
                    //画像表示ボックス表示
                    var pop_top  = ( 0 - 14 ) + "px";
                    var pop_left = ( 0 - 14 ) + "px";
                    pop_img.css({ left: "50%", top: "50%", "margin-left": pop_left, "margin-top": pop_top, width: "28px", height: "28px"}).animate({opacity: 1.0},{duration: 700,
                        //画像読み込み・表示
                        complete: function(){
                            var imgload = new Image();
                            imgload.src = img_url;
                            imgload.onload = function(){
                                pop_img.children("img").attr("src",img_url);
                                if(img_max_h < pop_img.children("img").height()){
                                    pop_img.children("img").height(img_max_h);
                                    var max_h = img_max_h;
                                    var max_w = pop_img.children("img").width();
                                } else {
                                    var max_h = pop_img.children("img").height();
                                    var max_w = pop_img.children("img").width();
                                }
                                //IE6用（後方互換モード対策）
                                if(!$.support.boxModel) {
                                    max_h += 20;
                                    max_w += 20;
                                }
                                pop_img.children("img").css("opacity", "0");
                                var pop_top  = ( 0 - (max_h / 2 + text_h) ) + "px";
                                var pop_left = ( 0 - (max_w / 2) ) + "px";
                                var img_w    = max_w + "px";
                                var img_h    = ( max_h + text_h ) + "px";
                                text_h       = text_h + "px";
                                pop_img.animate({ marginLeft: pop_left, marginTop: pop_top, height: img_h, width: img_w},{duration: 1000,
                                    complete: function(){
                                        //$(this).children("img").animate({opacity: 1.0},{duration: 1000});
                                        //pop_text.animate({height: text_h},{duration: 1000});
                                        //pop_close.animate({opacity: 1.0},{duration: 1000});
                                        pop_close.css("display","block");
                                        $(this).children("img").css("opacity","1.0");
                                        pop_text.css("height", text_h);
                                    }
                                });
                            }
                        }
                    });
                }
            });

            //閉じる
            $("#imgWrap, #close").click(function(){
                $("#imgWrap, #popImg").remove();
                //IE6用（後方互換モード対策）
                if(!$.support.boxModel) {
                    body.css("overflow","auto");
                }
            });
        }

        /*-------------------------------------------------------
           初期データセット
        -------------------------------------------------------*/
        $.getJSON(settings.url,function(data) {
            item.max    = data.length -1;
            item.target = 0;
            item.data   = data;
            photo_main(item);
        });

        /*-------------------------------------------------------
           メイン処理
        -------------------------------------------------------*/
        function photo_main(item){
            //ページャークリック
            pager.click(function(){
                start = pager.index(this) + 1;
                img_list(item);
                pager_set();
                if(pager.index(this)){
                    item.target = pager.index(this) * limit;
                    data_change(item);
                } else {
                    item.target = pager.index(this);
                    data_change(item);
                }
                return false;
            });

            //サムネイルクリック
            list.click(function(){
                if(start == 1) {
                    item.target = list.index(this);
                } else {
                    item.target = list.index(this) + ((start - 1) * limit);
                }
                data_change(item);
                return false;
            });

            //ネクストクリック
            next.click(function(){
                //メインイメージ切り替え
                if(item.target == item.max){
                    item.target = 0;
                    start = 1;
                    img_list(item);
                    pager_set();
                } else {
                    item.target++;
                }
                //サムネリスト・ページャー切り替え
                if(item.target){
                    var flag = item.target % limit;
                    if(!flag) {
                        start++;
                        img_list(item);
                        pager_set();
                    }
                }
                data_change(item);
                return false;
            });

            //プレクリック
            pre.click(function(){
                //サムネリスト・ページャー切り替え
                if(item.target != 0){
                    var flag = item.target % limit;
                    if(!flag) {
                        start--;
                        img_list(item);
                        pager_set();
                    }
                }
                if(!item.target){
                    item.target = item.max;
                    start = Math.ceil((item.max + 1) / limit);
                    img_list(item);
                    pager_set();
                } else {
                    item.target--;
                }
                data_change(item);
                return false;
            });

            //ズームクリック
            zoom.click(function(){
                img_pop(item);
                return false;
            });

        }

    }

/*----------------------------------------------------------------
    画像一覧
----------------------------------------------------------------*/
    $.fn.photo_list = function(settings){

        var settings = $.extend({
            json_url: "",
            swf_url:  "",
            ex_url:   "",
            img_url:  "",
            msize:    "",
            wsize:    "",
            hsize:    "",
            load:     "",
            close:    ""
        }, settings);

        /*-------------------------------------------------------
           各種初期指定
        -------------------------------------------------------*/
        var target      = $(this);
        var body        = $("body");
        var body_height = body.height() + "px";
        var set_width   = settings.wsize * ( Math.floor(($(window).width() * settings.msize) / settings.wsize ) );
        var set_height  = settings.hsize * ( Math.floor(($(window).height() * settings.msize) / settings.hsize ) );
        var swidth      = Math.floor(($(window).width() * settings.msize) / settings.wsize );
        var sheight     = Math.floor(($(window).height() * settings.msize) / settings.hsize );
        var pop_height  = ( set_height + 40 + sheight ) + "px";
        var pop_width   = ( set_width + swidth + 20 ) + "px";
        //IE6用（後方互換モード対策）
        if(!$.support.boxModel) {
            var pop_height = ( set_height + 60 + sheight ) + "px";
            var pop_width  = ( set_width + swidth + 40 ) + "px";
        }
        var pop_top     = ( 0 - ( ( set_height + sheight + 40 ) / 2 ) ) + "px";
        var pop_left    = ( 0 - ( ( set_width + swidth + 20 ) / 2 ) ) + "px";
        var item        = {};
        var box         = "<div id='imgWrap'></div>" +
                          "<div id='listWrap'>"+
                              "<div id='imgArea'><img src='" + settings.load + "?" + (new Date()).getTime() + "' /></div>"+
                              "<p id='close'><a href='#'><img src='" + settings.close + "' alt='close' /></a></p>"+
                          "</div>";

        /*-------------------------------------------------------
           ポップアップ
        -------------------------------------------------------*/
        target.click( function() {
            //初期データ設定
            //IE6用（後方互換モード対策）
            if(!$.support.boxModel) {
                body.scrollTop(0).css("overflow","hidden");
            }
            body.prepend(box);
            var wrap      = $("#imgWrap");
            var pop_close = $("#close");
            var list_area = $("#listWrap");
            var load_top  = ( 0 - ( $("#imgArea").height() / 2 ) ) + "px";
            var load_left = ( 0 - ( $("#imgArea").width() / 2 ) ) + "px";
            list_area.css({ left: "50%", top: "50%", "margin-left": load_left, "margin-top": load_top});
            pop_close.css({ opacity: 0});

            //アニメーションスタート（暗転開始）
            wrap.css({ height: body_height, opacity: "0"}).animate({opacity: 0.8},{duration: 700,
                complete: function(){
                    $("#imgArea img").remove();
                    list_area.animate({ height: pop_height, width: pop_width, marginLeft: pop_left, marginTop: pop_top},{duration: 1000,
                        complete: function(){
                            var flashvars = {
                                json_url:   settings.json_url,
                                img_url:    settings.img_url,
                                img_height: settings.hsize,
                                img_width:  settings.wsize,
                                stg_width:  set_width
                            }
                            var params = {
                                bgcolor: "#000000"
                            }
                            swfobject.embedSWF( settings.swf_url, "imgArea", set_width + swidth + 20, set_height, "9.0.0", settings.ex_url, flashvars, params);

                        }
                    });
                    pop_close.animate({opacity: 1},{duration: 600});
                }
            });

            //閉じる
            $("#imgWrap, #close").click(function(){
                $("#imgWrap, #listWrap").remove();
                //IE6用（後方互換モード対策）
                if(!$.support.boxModel) {
                    body.css("overflow","auto");
                }
            });
        });

    }

/*----------------------------------------------------------------
    地図で一覧用ポップアップ
----------------------------------------------------------------*/
    $.fn.map_pop = function(settings){

        var settings = $.extend({
            percent: "",
            load:    "",
            close:   "",
            ones:    0,
            url:     "",
            icon1:   "",
            icon2:   "",
            icon3:   "",
            wsize:   "",
            hsize:   ""
        }, settings);

        /*-------------------------------------------------------
           各種初期指定
        -------------------------------------------------------*/
        var target      = $(this);
        var body        = $("body");
        var body_height = body.height() + "px";
        var set_width   = Math.floor( $(window).width() * settings.percent );
        var set_height  = Math.floor( $(window).height() * settings.percent );
        //IE6用（後方互換モード対策）
        if(!$.support.boxModel) {
            set_width  += 35;
            set_height += 20;
        }
        var pop_height  = ( set_height + 30 ) + "px";
        var pop_width   = set_width + "px";
        var pop_top     = ( 0 - ( ( set_height + 30 ) / 2 ) ) + "px";
        var pop_left    = ( 0 - ( set_width / 2 ) ) + "px";
        var box         = "<div id='mapWrap'></div>" +
                          "<div id='mapArea'>" +
                          "<div id='mapAll'><img src='" + settings.load + "?" + (new Date()).getTime() + "' /></div>" +
                          "<p id='close'><a href='#'><img src='" + settings.close + "' alt='close' /></a></p>" +
                          "</div>";

        /*-------------------------------------------------------
           座標指定
        -------------------------------------------------------*/
        if(settings.ones && target.attr("href")){
            var xy   = target.attr("href").split(",");
            var lat  = xy[0];
            var lng  = xy[1];
            var zoom = 14;
        } else {
            var lat  = 38.137437;
            var lng  = 139.42749;
            var zoom = 5;
        }

        /*-------------------------------------------------------
           ポップアップ
        -------------------------------------------------------*/
        target.click( function() {

            //IE6用（後方互換モード対策）
            if(!$.support.boxModel) {
                body.scrollTop(0).css("overflow","hidden");
            }
            //初期データ設定
            body.prepend(box);
            var wrap      = $("#mapWrap");
            var map_area  = $("#mapArea");
            var close     = $("#close");
            var load_left = ( 0 - ( map_area.width() / 2 ) ) + "px";
            var load_top  = ( 0 - ( map_area.height() / 2 ) ) + "px";
            close.css("opacity", "0");
            map_area.css({ left: "50%", top: "50%", "margin-left": load_left, "margin-top": load_top});

            //アニメーションスタート（暗転開始）
            wrap.css({ height: body_height, opacity: "0"}).animate({opacity: 0.8},{duration: 700,
                complete: function(){
                    $("#mapAll img").css( "opacity", "0");
                    map_area.animate({
                        height: pop_height,
                        width: pop_width,
                        marginLeft: pop_left,
                        marginTop: pop_top
                    },{duration: 1000,
                        complete: function(){
                            $("#mapAll").map_list({
                                url:   settings.url,
                                icon1: settings.icon1,
                                icon2: settings.icon2,
                                icon3: settings.icon3,
                                wsize: settings.wsize,
                                hsize: settings.hsize,
                                pmap:  "0.8",
                                lat:   lat,
                                lng:   lng,
                                zoom:  zoom
                            });
                            close.animate({ opacity: 1},{ duration: 700});
                        }
                    });
                }
            });

            //閉じる
            $("#mapWrap, #close").click(function(){
                $("#mapWrap, #mapArea").remove();
                //IE6用（後方互換モード対策）
                if(!$.support.boxModel) {
                    body.css("overflow","auto");
                }
            });
            return false;
        });

    }

/*----------------------------------------------------------------
    グーグルマップ
----------------------------------------------------------------*/
    $.fn.map_list = function(settings){

        var settings = $.extend({
            url:   "",
            icon1: "",
            icon2: "",
            icon3: "",
            wsize: "",
            hsize: "",
            hmap:  "270",
            wmap:  "400",
            pmap:  "",
            lat: "38.137437",
            lng: "139.42749",
            zoom:  4
        }, settings);

        //地図サイズ指定
        if(!settings.pmap){
            var w_map = settings.wmap + "px";
            var h_map = settings.hmap + "px";
        } else {
            var w_map = Math.floor( $(window).width() * settings.pmap ) + "px";
            var h_map = Math.floor( $(window).height() * settings.pmap ) + "px";
        }
        $(this).css({ width: w_map, height: h_map});

        if(GBrowserIsCompatible()) {
            //初期指定
            var map = new GMap2($(this).get(0));
            map.addControl(new GSmallMapControl());
            var miniMap=new GOverviewMapControl(new GSize(150,100));
            map.addControl(miniMap);
            map.setCenter(new GLatLng(settings.lat,settings.lng), settings.zoom);

            //アイコン設定
            var icon1 = new GIcon();
            icon1.image = settings.icon1;
            icon1.iconSize = new GSize(settings.wsize,settings.hsize);
            icon1.iconAnchor = new GPoint(settings.wsize / 2 , settings.hsize / 2);
            var icon2 = new GIcon();
            icon2.image = settings.icon2;
            icon2.iconSize = new GSize(settings.wsize,settings.hsize);
            icon2.iconAnchor = new GPoint(settings.wsize / 2 , settings.hsize / 2);
            var icon3 = new GIcon();
            icon3.image = settings.icon3;
            icon3.iconSize = new GSize(settings.wsize,settings.hsize);
            icon3.iconAnchor = new GPoint(settings.wsize / 2 , settings.hsize / 2);

            //JSON読み込み
            $.getJSON(settings.url,function(data) {
                var data   = data;
                var point  = new Array;
                var marker = new Array;
                $(data).each(function(i, v){
                    //アイコン選択
                    if(data[i].status == "photo"){ var icon = icon1;}
                    else if(data[i].status == "hotel"){ var icon = icon2;}
                    else if(data[i].status == "food"){ var icon = icon3;}
                    point[i]  = new GLatLng(this.lat , this.lng);
                    marker[i] = new GMarker(point[i], icon);
                    map.addOverlay(marker[i]);
                    if(settings.lat == this.lat && settings.lng == this.lng){
                        //吹き出しマークアップ
                        var text = "<div id='balloon'>" +
                                   "<div class='balloonText'>" +
                                   "<h3><a href='" + data[i].url + "'>" + data[i].name + "</a></h3>" +
                                   "<p>" + data[i].read + "</p>" +
                                   "</div>" +
                                   "<div class='balloonLink'></div>" +
                                   "</div>";
                        show(point[i], text);
                    }
                    GEvent.addListener(marker[i], "click", function(){
                        //吹き出しマークアップ
                        var text = "<div id='balloon'>" +
                                   "<div class='balloonText'>" +
                                   "<h3><a href='" + data[i].url + "'>" + data[i].name + "</a></h3>" +
                                   "<p>" + data[i].read + "</p>" +
                                   "</div>" +
                                   "<div class='balloonLink'></div>" +
                                   "</div>";
                        show(point[i], text);
                    })
                });
            });
        }

        $(window).unload(function(){ GUnload();});

        //オリジナル吹き出し表示処理
        var info_win;
        function show(point,box){
            if(info_win){ map.removeOverlay(info_win);}
            info_win = new CO(point,box);
            map.addOverlay(info_win);
        }
        function CO(point,box) {
            this.xy  = point;
            this.box = $("body").prepend(box);
        };
        CO.prototype = new GOverlay();
        CO.prototype.initialize = function() {
            map.panTo(this.xy);
            map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild($("#balloon").get(0));
        }
        CO.prototype.redraw = function(){
            var point = map.fromLatLngToDivPixel(this.xy);
            $("#balloon").css({
                display: "block",
                left: point.x + "px",
                top: point.y - parseInt($("#balloon").height()) + "px"
            })
        }
        CO.prototype.remove = function() {
            $("#balloon").remove();
        }
    }


})(jQuery);