/* -*- Encoding: utf8n -*- */

var loc = window.location.href;
var cmd = window.location.pathname;

// 拡張
Array.prototype.shuffle = function() {
    var i = this.length;
    while(i){
        var j = Math.floor(Math.random()*i);
        var t = this[--i];
        this[i] = this[j];
        this[j] = t;
    }
    return this;
}

// jQueryプラグイン
;(function($) {
    $.fn.top = function() {
        return parseInt($(this).css("top"));
    };
    $.fn.left = function() {
        return parseInt($(this).css("left"));
    };
    $.fn.fadeToggle = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle'}, speed, easing, callback);
    };
    $.fn.swapAttr = function(obj, name, callback) {
        var temp = $(this).attr(name);
        $(this).attr(name, obj.attr(name));
        obj.attr(name, temp);
        if (callback) {callback.call(this);}
    };
    // indexのグローバルメニューの展開用
    $.fn.globalMenuToggle = function(speed, easing, callback) {
        $(this).find(".arrow").toggle();
        $(this).children(".sub").fadeToggle(speed, easing, callback);
        $(this).children(".bar").children("a").toggleClass("mouseover");
    };
    // 配列となっているハッシュから指定のハッシュ値を取り出し、それを配列で返す
    $.fn.getHashValue4ArrayHash = function(key) {
        var result = new Array();
        $(this).each(function() {
            result.push(this[key]);
        });
        return $(result);
    };
    // 配列となっている画像URLをプリロードする
    $.fn.preload = function(callback) {
        var temp = new Array();
        $.each(this, function(i,v) {
            if (typeof(v) == "string") {
                temp[i] = new Image(); temp[i].src = v;
            } else {
                temp[i] = new Image(); temp[i].src = $(v).attr("src");
            }
        });
        if (callback) {
            var instance = this;
            window.setTimeout(function() {
                var completa = true;
                $.each(temp, function(i,v) {
                    completa &= v.complete;
                });
                if (completa) {
                    callback.call(instance);
                } else {
                    window.setTimeout(function(){instance.preload(callback)}, 0);
                }
            }, 0);
        }
    };
    // スクロール
    $.fn.smooth_scroll = function(speed, easing) {
        ref = $(this).attr("href");
        if (!ref || ref == "#") {
            ref = "#wrapper";
        }
        return $(this).each(function() {
            $('html,body').animate({scrollTop:$(ref).offset().top}, speed, easing);
        });
    };
    $.fn.smooth_scroll_name = function(speed, easing) {
        ref = $(this).attr("href");
        return $(this).each(function() {
            $('html,body').animate({scrollTop:$("a[name='" + ref.replace("#","") + "']").offset().top}, speed, easing);
        });
    };
})(jQuery);

// 拡張プロパティ（window）
CSky = window.csky = {};
CSky.timer_tile_draw = false;
if (CSky.timer_tile_draw) {
    CSky.timer_tile_draw_name  = 'tile_draw';
    CSky.timer_tile_draw_cycle = 5000;
}

// タイルのロゴ（紫）部分のフェードの速さ
CSky.speed_tile_logo_fade = 500;
// タイルの画像のフェードのずれ
CSky.delay_tile_pict_draw = 25;
CSky.speed_tile_pict_fade = 500;
// スライドショーのフェードの速さ
CSky.speed_slideshow_fade = 300;
// リンクの点線を消すか？（IE限定。それ以外のブラウザはCSS（outline）で対応）
CSky.link_outline = true;

// 拡張メソッド（window）
$.extend(CSky, {
    draw_tiles_image : function(tile_items, callback) {
        var item = tile_items.shuffle().slice(0, 14);
        $("#tiles").children("div.tile").remove();
        $.each(item, function(i) {
            var area = item[i]["title"];
            var text = item[i]["text"];
            var link = item[i]["ref"];
            $("#tiles").append(
                '<div class="tile img' + ("0"+(i+1)).slice(-2) + '">'                                               +
                '  <div class="img_over">'                                                                          +
                '    <a class="a" href="' + link + '" title="'+area+'">'+area+'</a>'                                +
                '    <a class="t" href="' + link + '" title="'+text+'">'+text+'</a>'                                +
                '  </div>'                                                                                          +
                '  <img src="' + item[i]["img"] + '" width="157" height="116" alt="' + (area + '-' + text) + '" />' +
                '  <p>'                                                                                             +
                '    <span class="area">' + area + '</span>'                                                        +
                '    <span class="text">' + text + '</span>'                                                        +
                '  </p>'                                                                                            +
                '</div>'
                );

            $("#tiles img:last").oneTime(i*CSky.delay_tile_pict_draw, null, function() {
                $(this).fadeIn(CSky.speed_tile_pict_fade);
            });
        });
        if (callback) {callback.call();}
    }
});

// 即時実行
$(document).ready(function() {
    // index（本番とテスト環境ではパスが違うのでUP時に気をつける）
    if (cmd.match(/^\/$/) || cmd.match(/^\/index\.html.*$/)) {
        // タイル画像を非同期でプリロードする
        $(CSky.tile_items).getHashValue4ArrayHash("img").preload();
        // タイルロゴをプリロードし完了時にフェードする。最後のフェードが完了したら、
        // タイル画像のプリロードの完了をまって、フェードする
        $(".tile-logo").preload(function() {
            $(this.get(0)).fadeIn(CSky.speed_tile_logo_fade,function() {
                if ($(this).next().length != 0) {
                    $(this).next().fadeIn(CSky.speed_tile_logo_fade, arguments.callee);
                } else {
                    $(CSky.tile_items).getHashValue4ArrayHash("img").preload(function() {
                        CSky.draw_tiles_image(CSky.tile_items, function() {
                            if (CSky.timer_tile_draw) {
                                $(document).everyTime(CSky.timer_tile_draw_cycle, CSky.timer_tile_draw_name, function() {
                                    CSky.draw_tiles_image(CSky.tile_items);
                                });
                            }
                        });
                    });
                }
            });
        });

        // おすすめの一覧
        $(".open-recommended").fancybox({
            'margin'            :0,
            'padding'           :0,
            'scrolling'         :'no',
            'transitionOut'     :'none',
            'overlayColor'      :'#000',
            'overlayOpacity'    :0.8,
            'centerOnScroll'    :false,
            'titleShow'         :false,
            'showCloseButton'   :false,
            'hideOnOverlayClick':false,
            'hideOnContentClick':false,
            'onComplete' : function() {
                var overlay_height = $("#fancybox-overlay").height();
                var content_height = $("#fancybox-wrap").outerHeight(true) + $("#fancybox-wrap").top();
                if (content_height > overlay_height) {
                    $("#fancybox-overlay").css("height", content_height);
                }
                $(".recommended_close a").click(function() {
                    $.fancybox.close();
                });
            }
        });

        // indexのグローバルメニューの展開用
        $.fn.globalMenuToggle = function(speed, easing, callback) {
            $(this).find(".arrow").toggle();
            $(this).children(".sub").fadeToggle(speed, easing, callback);
            $(this).children(".bar").children("a").toggleClass("mouseover");
        };
    }

    // lightbox
    if ($.fn.lightBox) {
        $(function() {
            $('.thumb-img a , .zoom-img a ,  .honki-contents .images a , .blog-images a').lightBox({fixedNavigation:true});
        });
    }

    // 施工実績の外部リンクの色かえ（CSSでやらないのはCMSを意識して）
    $(".construction-detail .point a").each(function() {
        if ($(this).attr("target") == "_blank") {
            $(this).addClass("blank");
        }
    });
    // 店舗改装物語
    if ($('#mybook').length != 0) {
        $(function() {
            var $mybook         = $('#mybook');
            var $bttn_next      = $('#next_page_button');
            var $bttn_prev      = $('#prev_page_button');
            var $loading        = $('#loading');
            var $mybook_images  = $mybook.find('img');
            var cnt_images      = $mybook_images.length;
            var loaded          = 0;
            $mybook_images.each(function(){
                var $img    = $(this);
                var source  = $img.attr('src');
                $('<img/>').load(function(){
                    ++loaded;
                    if(loaded == cnt_images){
                        $loading.hide();
                        $bttn_next.show();
                        $bttn_prev.show();
                        // 準備が出来てから表示する。そうしないと読み込み中に
                        // 画面レイアウトが崩れて見えるタイミングがある（高速回線だと見えないが）
                        $(".b-load").css("display", "block");
                        $mybook.show().booklet({
                            width:              660,
                            height:             385,
                            speed:              600,
                            pageNumbers:        false,
                            hovers:             false,
                            overlays:           false,
                            hash:               true,       // これをTRUEにするとURLHashでページ番号を管理。F5しても大丈夫。
                            keyboard:           true,
                            next:               $bttn_next,
                            prev:               $bttn_prev,
                            shadows:            false
                        });
                    }
                }).attr('src',source);
            });
        });
    }
});

// イベント
$(document).ready(function() {
    // index
    if (cmd.match(/^\/$/) || cmd.match(/^index\.html.*$/)) {
        // タイルの画像のマウスオーバーLive
        $("#tiles .tile").live("mouseover", function() {
            $(this).children(".img_over").show();
            if (CSky.timer_tile_draw) {
                $(document).stopTime(CSky.timer_tile_draw_name);
            }
        });
        // タイル画像のマウスアウトLive
        $("#tiles .tile").live("mouseout", function() {
            $(this).children(".img_over").hide();
            if (CSky.timer_tile_draw) {
                $(document).everyTime(CSky.timer_tile_draw_cycle, CSky.timer_tile_draw_name, function() {
                    CSky.draw_tiles_image(window.csky.tile_items);
                });
            }
        });
        // ニュースのスクロール（前）
        $("#news_digest .prev").click(function() {
            var height = $("#news_digest dl").stop(true, true).children(":first").height();
            if ($("#news_digest dl").top() < 0) {
                $("#news_digest dl").animate({top:"+="+height+"px"},"fast");
            }
            return false;
        });
        // ニュースのスクロール（次）
        $("#news_digest .next").click(function() {
            var height = $("#news_digest dl").stop(true, true).children(":first").height();
            if (($("#news_digest dl").top()-height)*-1 < $("#news_digest dl").height()) {
                $("#news_digest dl").animate({top:"-="+height+"px"},"fast");
            }
            return false;
        });
        // おすすめのスクロール関連
        (function() {
            // ボタン制御
            var scroll_finish = function() {
                var page_pos = $("#scroll_pos").children("a");
                var page_idx = page_pos.index($("#scroll_pos").children("a.a"));
                if (page_idx == 0) {
                    $("#scroll_operation .prev").addClass("inactive");
                    $("#scroll_operation .next").removeClass("inactive");
                } else if (page_pos.length <= page_idx+1) {
                    $("#scroll_operation .prev").removeClass("inactive");
                    $("#scroll_operation .next").addClass("inactive");
                } else {
                    $("#scroll_operation .prev").removeClass("inactive");
                    $("#scroll_operation .next").removeClass("inactive");
                }
            };
            // おすすめの移動（ページ指定）
            $("#scroll_pos .direct_recommend").click(function() {
                if ($(this).hasClass("u")) {
                    $("#recommended-scroll ul").stop(true, false);
                    $(this).children().swapAttr($(this).siblings(".a").children(), "src", function() {
                        $(this).parent().toggleClass("u").toggleClass("a").siblings().removeClass("a u").addClass("u");
                    });
                    $("#recommended-scroll ul").animate({left:(($("#recommended-scroll ul li").width()*-3) * ($("#scroll_pos .direct_recommend").index(this)))}, "slow", scroll_finish);
                }
                return false;
            });
            // おすすめのスクロール（前）
            $("#scroll_operation .prev").click(function() {
                if ($("#scroll_pos").children("a:first").hasClass("u")) { 
                    $("#scroll_pos").find(".a img").swapAttr($("#scroll_pos").children(".a").prev().children(), "src", function() {
                        $("#scroll_pos").children(".a").toggleClass("a").toggleClass("u").prev().removeClass("u").toggleClass("a");
                    });
                    $("#recommended-scroll ul").stop(true, true).animate({left:"-="+($("#recommended-scroll ul li").width()*-3)+"px"}, "slow", scroll_finish);
                }
                return false;
            });
            // おすすめのスクロール（次）
            $("#scroll_operation .next").click(function() {
                if ($("#scroll_pos").children("a:last").hasClass("u")) { 
                    $("#scroll_pos").find(".a img").swapAttr($("#scroll_pos").children(".a").next().children(), "src", function() {
                        $("#scroll_pos").children(".a").toggleClass("a").toggleClass("u").next().removeClass("u").toggleClass("a");
                    });
                    $("#recommended-scroll ul").stop(true, true).animate({left:"+="+($("#recommended-scroll ul li").width()*-3)+"px"}, "slow", scroll_finish);
                }
                return false;
            });
        })();
    }

    // IE向け リンクの点線消去
    if (CSky.link_outline) {
        $("a").focus(function() {
            $(this).blur();
        });
    }

    // グローバルメニューのクリック
    $("#global_menu li.menu1,#global_menu li.menu2,#global_menu li.menu3").click(function() {
        if ($(this).hasClass("click1")) {
            return true;
        } else {
            $(this).children(".bar").children("a").toggleClass("mouseover");
            $(this).globalMenuToggle("fast");
            $(this).addClass("click1");
            return false;
        }
    });

    // グローバルメニューのホバー
    $("#global_menu li.menu1,#global_menu li.menu2,#global_menu li.menu3").hover(
        function() {
            $(this).children(".bar").children("a").addClass("mouseover");
        },
        function() {
            if ($(this).hasClass("click1")) {
                $(this).globalMenuToggle(0);
            }
            $(this).removeClass("click1");
            $(this).children(".bar").children("a").removeClass("mouseover");
        }
    );

    // フッタメニューのスライド
    $("#footer .t5").click(function() {
        if ($("#footer .slide dd:hidden").length != 0) {
            var height = $("#footer .slide dd").show().outerHeight(true);
            $('html, body').animate({scrollTop:"+="+height+"px"}, "fast", null);
        } else {
            // 以下の方法をとらないとFireFoxで画面が激しくちらつく
            var height = $("#footer .slide dd").show().outerHeight(true);
            $('html, body').animate({scrollTop:"-="+height+"px"}, "fast", null);
            $("#footer .slide dd").hide("fast");
        }
        return false;
    });
	
	
	// フッタメニューのスライド
    $("#footer .slide_btn").click(function() {
        if ($("#footer .slide dd:hidden").length != 0) {
            var height = $("#footer .slide dd").show().outerHeight(true);
            $('html, body').animate({scrollTop:"+="+height+"px"}, "fast", null);
            $(this).addClass("down");
        } else {
            // 以下の方法をとらないとFireFoxで画面が激しくちらつく
            var height = $("#footer .slide dd").show().outerHeight(true);
            $('html, body').animate({scrollTop:"-="+height+"px"}, "fast", null);
            $("#footer .slide dd").hide("fast");
            $(this).removeClass("down");
        }
        return false;
    });
	
    // テキストのフォーカス
    $(".text").focus(function() {
        $(this).toggleClass("text-active");
    });
    $(".text").blur(function() {
        $(this).toggleClass("text-active");
    });
    // ページへ移動
    $(".goto-top a, .page-navi a").click(function() {
        $(this).smooth_scroll("fast", "swing"); return false;
    });
    $(".page-navi-all a").click(function() {
        $(this).smooth_scroll_name("fast", "swing"); return false;
    });

    // スライドショー（高速化の為に無名関数化）
    (function(target){
        var zoom  = $(target).find(".zoom-img img:first").css("z-index", 100).parent(), thumb = $(target).find(".thumb-img img:first").addClass("active").parent();
/*
        thumb.find("img").click(function() {
            if (!$(this).hasClass("active")) {
                zoom.find("img:animated").stop(true, true);
                $(this).siblings().removeClass("active");
                $(this).addClass("active");

                zoom.children("[style]").each(function() {
                    var zindex = $(this).css("z-index");
                    if (!isNaN(zindex)) {
                        $(this).css("z-index", zindex-1);
                    }
                });
                $(zoom.children().get(thumb.children().index(this))).css("z-index", 100).hide().fadeIn(CSky.speed_slideshow_fade, function() {
                    var active = this;
                    zoom.children().each(function() {
                        if ($(active).get(0) != $(this).get(0)) {
                            $(this).removeAttr("style");
                        }
                    });
                });
            }
        });
*/
    })($(".slideshow .photo"));
});


