/* ---------------------------------------------------------
img-portfolio plugin ver 0.5 CUSTOM(for:http://souke-tachibanaryu.jp/photo/index.html)
date      : 23 July, 2009
auth      : H.TANAKA by CVP(http://cvp-web.net/)
copyright : (C) 2009 The School of Soke Tachibana / Core Impressions all rights Reserved. 
--------------------------------------------------------- */


(function() {


//plugin
$.fn.imgPortfolio = function(cfg) {


//cfg
cfg = jQuery.extend({
  lnk_mixi   : set.lnk_mixi,     //mixiプロフィール・リンク
  lnk_twttr  : set.lnk_twttr,    //twttrプロフィール・リンク
  dir_name   : set.dir_name,     //ギャラリー用のフォルダを相対パスで指定
  img_load   : set.img_load,     //ローディングバーのパス
  img_crcl   : set.img_crcl,     //ローディング画像のパス
  img_mixi   : set.img_mixi,     //mixiアイコン画像のパス
  img_twttr  : set.img_twttr,    //twitterアイコン画像のパス
  clr_info   : "#"+set.clr_info, //プロフィール表示の背景色
  clr_over   : "#"+set.clr_over, //オーバーレイの背景色
  opc_over   : set.opc_over,     //オーバーレイの透過度
  menu_fimg  : set.menu_fimg,    //メニューのフォント画像（0=使用しない/1=使用する)
  menu_size  : set.menu_size,    //メニューのフォントサイズ
  menu_fclr  : set.menu_fclr,    //メニューのフォント色
  menu_bclr  : set.menu_bclr,    //メニューの背景色
  menu_numt  : set.menu_numt,    //メニューの始めに表示される件数
  thumb_name : set.thumb_name,   //サムネイルにフォルダ名を表示する（0=表示しない/1=表示する)
  thumb_fimg : set.thumb_fimg,   //サムネイルのフォルダ名を画像で表示する（0=表示しない/1=表示する)
  thumb_size : set.thumb_size,   //サムネイルのフォルダ名のフォントサイズ
  thumb_fclr : set.thumb_fclr,   //サムネイルのフォルダ名のフォント色
  thumb_bclr : set.thumb_bclr,   //サムネイルのフォルダ名の背景色
  thumb_s    : set.thumb_s,      //サムネイルの画像サイズ
  disp_w     : set.disp_w,       //画像の横サイズ上限（ピクセル）
  disp_h     : set.disp_h,       //画像の縦サイズ上限（ピクセル）
  info_w     : set.info_w,       //プロフィール表示の横サイズ上限（ピクセル）
  info_h     : set.info_h,       //プロフィール表示の縦サイズ上限（ピクセル）
  cls_head   : "."+set.cls_head, //ヘッダーのクラス名
  cls_menu   : "."+set.cls_menu, //メニューのクラス名
  cls_thum   : "."+set.cls_thum, //サムネイルのクラス名
  cls_cont   : "."+set.cls_cont, //画像表示のクラス名
  cls_dscr   : "."+set.cls_dscr, //画像キャプションのクラス名
  cls_load   : "."+set.cls_load, //ローディング画像のクラス名
  cls_prof   : "."+set.cls_prof, //プロフィール表示ボタンのクラス名
  cls_info   : "."+set.cls_info, //プロフィールのクラス名
  cls_over   : "#"+set.cls_over  //オーバーレイ背景のID名
},cfg);


var _obj = new Object();
var _loadBar  = new Image();
var _loadcrcl = new Image();
_loadBar.src  = cfg.img_load;
_loadcrcl.src = cfg.img_crcl;


//function
function presetBodyCss(){
  $("body").append("<div id=\""+ cfg.cls_over.replace(/^#/, "") +"\"></div>");
  $(cfg.cls_over).css({
    background: cfg.clr_over,
    zIndex    : 10,
    position  : "fixed",
    opacity   : cfg.opc_over,
    left      : 0,
    top       : 0,
    display   : "none"
  });
  $(cfg.cls_info).css({
    width     : cfg.info_w,
    height    : cfg.info_h,
    background: cfg.clr_info,
    zIndex    : 100,
    position  : "fixed",
    opacity   : 1.0,
    display   : "none"
  });
  if (typeof document.body.style.maxHeight == "undefined") {
    $(cfg.cls_over).css("position","absolute");
    $(cfg.cls_info).css("position","absolute");
  }
  $(cfg.cls_info).children("ul").html("");
  if (cfg.lnk_mixi != "") {
    $(cfg.cls_info).children("ul").append("<li><a href=\"http://mixi.jp/show_friend.pl?id="+cfg.lnk_mixi+"\"><img src=\""+cfg.img_mixi+"\" alt=\""+cfg.lnk_mixi+"\" /></a></li>");
  }
  if (cfg.lnk_twttr != "") {
    $(cfg.cls_info).children("ul").append("<li><a href=\"http://twitter.com/"+cfg.lnk_twttr+"\"><img src=\""+cfg.img_twttr+"\" alt=\""+cfg.lnk_twttr+"\" /></a></li>");
  }
  $(cfg.cls_info).children("ul").find("img").css({border: 0});
  $(cfg.cls_cont).css({width: cfg.disp_w,height:cfg.disp_h,textAlign:"center"});
  $(cfg.cls_cont).html("<p>please wait...</p><img class=\"disp-img\" />");
  $(cfg.cls_cont).children("p").css({marginTop:(cfg.disp_h/2)-50});
  $(cfg.cls_cont).children(".disp-img").css({display:"none"});
  ajaxLoadFeed(0,0);
}


function ajaxLoadFeed(dirnum,num){
  $.ajax({
    type: "GET",
    url:"./include/img-portfolio.xml.php",
    data:{
      dir:cfg.dir_name
    },
    cache: false,
    dataType: "xml",
    timeout: 10000,
    error:function() {
      $(cfg.cls_cont).html("error");
      return true;
    },
    success:function(xml) {
      if($("directory",xml).length != 0 || $("item",xml).length != 0){
        $(cfg.cls_cont).children("p").css("margin-top",(cfg.disp_h/2)-50).text("now loading...");
      } else {
        $(cfg.cls_cont).children("p").css("margin-top",(cfg.disp_h/2)-50).text("no image item");
      }
      if(!num){
        loadMenu(xml,dirnum);
      }
      loadThumb(xml,dirnum);
      return true;
    }
  });
}


function loadMenu(xml,dirnum){
  _obj.dir = new Array();
  _obj.ulclrs = "";
  _obj.len    = $("directory",xml).length;
  //メニュー開閉読込
  $(cfg.cls_menu).html("<ul class=\"menu-ul-top\"></ul><ul class=\"menu-ul-under\"></ul>");
  if(_obj.len > cfg.menu_numt){
    $(".menu-ul-under").css("display","none").before("<p>▼もっと見る</p>");
    presetHoverCss($(cfg.cls_menu).find("p"));
    $(cfg.cls_menu).find("p").toggle(
      function(){
        $(this).html("▲閉じる");
        $(".menu-ul-under").show();
      },
      function(){
        $(this).html("▼もっと見る");
        $(".menu-ul-under").hide();
      }
    );
  }
  //メニューリスト読込
  $("directory",xml).each(function(i){
    _obj.dir[i] = $(this).children("name").text();
    _obj.ulclrs = (i < (cfg.menu_numt))?"menu-ul-top":"menu-ul-under";
    if(cfg.menu_fimg == 0){
      $(cfg.cls_menu).children("ul."+_obj.ulclrs).append("<li class=\"thumb-"+i+"\">"+_obj.dir[i]+"</li>");
    } else {
      $(cfg.cls_menu).children("ul."+_obj.ulclrs).append("<li class=\"thumb-"+i+"\"><img src=\"./include/img-portfolio.font.php?dir="+cfg.dir_name+"&num="+i+"&size="+cfg.menu_size+"&fc="+cfg.menu_fclr+"&bc="+cfg.menu_bclr+"\" /></li>");
    }
  });

  $(cfg.cls_menu).children("ul").children("li").eq(dirnum).addClass("selected");
  presetHoverCss($(cfg.cls_menu).children("ul").children("li"));
}


function loadThumb(xml,dirnum){
  var _dir  = $("directory",xml).eq(dirnum).find("name").text();
  var _node = $("directory",xml).eq(dirnum).find("files").children("item");
  //サムネイルulタグ読込
  $(cfg.cls_thum).html("");
  if(cfg.thumb_name == 0){
    $(cfg.cls_thum).html("<ul></ul>");
  } else {
    //タイトル表示
    if(cfg.thumb_fimg == 0){
      $(cfg.cls_thum).html("<p>&gt;&gt;&nbsp;"+_dir+"</p><ul></ul>");
    } else {
      $(cfg.cls_thum).append("<p><img src=\"./include/img-portfolio.font.php?dir="+cfg.dir_name+"&num="+dirnum+"&size="+cfg.thumb_size+"&fc="+cfg.thumb_fclr+"&bc="+cfg.thumb_bclr+"\" /></p><ul></ul>");
    }
  }
  //サムネイルリスト読込
  _node.each(function(i){
    _obj.cls   = dirnum+"-"+i;
    _obj.title = $(this).children("title").text();
    _obj.src   = $(this).children("link").text();
    _obj.width = $(this).children("width").text();
    _obj.height= $(this).children("height").text();
    $(cfg.cls_thum).append("<li><img src=\"./include/img-portfolio.thumb.php?url="+ _obj.src +"&s="+cfg.thumb_s+"\" class=\""+ _obj.cls +"\" alt=\""+ _obj.title +"\" /></li>");
    $("."+ _obj.cls).css(presetThumbSize(_obj.width,_obj.height,cfg.thumb_s,cfg.thumb_s));
  });
  $(cfg.cls_thum).children("li").css({width:cfg.thumb_s,height:cfg.thumb_s});
  presetHoverCss($(cfg.cls_thum).children("li"));
  dispContent(xml,dirnum);
}


function dispContent(xml,dirnum){
  var _node  = $("directory",xml).eq(dirnum).find("files").children("item");
  _obj.num   = 0;
  _obj.lwdth = Math.floor(cfg.disp_w / 5);
  _obj.dir   = dirnum;
  $(cfg.cls_cont).append("<p class=\"ajax-loadbar\"><img class=\"loader\" src=\""+ _loadBar.src +"\" /></p><p class=\"ajax-loadtxt\"></p>");
  $(cfg.cls_cont).children("p.ajax-loadbar").css({
    width       : _obj.lwdth,
    height      : 10,
    background  : "#FFFFFF",
    border      : "solid 1px #DDDDDD",
    textAlign   : "left",
    marginLeft  : "auto",
    marginRight : "auto",
    marginTop   : 10,
    marginBottom: 10
  });
  //ローディング処理
  _node.each(function(j){
    $(cfg.cls_thum).find("img."+_obj.dir+"-"+j).load(function () {
      _obj.num++;
      $(cfg.cls_cont).children("p.ajax-loadtxt").text((_obj.num + 1)+"/"+_node.length);
      $(cfg.cls_cont).children("p.ajax-loadbar").children("img").css({
        width    : Math.ceil(((_obj.num + 1) / _node.length) * _obj.lwdth),
        height   : 10
      });
      //ローディング完了
      if(_obj.num == _node.length){
        $(cfg.cls_cont).children("p,img.loader").fadeOut().remove();
        $(cfg.cls_menu).fadeIn(function() {
          $(cfg.cls_thum).fadeIn(function() {
            //最初にロードされるファイル
            $(cfg.cls_thum).children("li").eq(0).addClass("selected");
            $(cfg.cls_thum).children("img").eq(0).removeAttr("css");
            _obj.src    = _node.eq(0).children("link").text();
            _obj.width  = _node.eq(0).children("width").text();
            _obj.height = _node.eq(0).children("height").text();
            _obj.dscr   = _node.eq(0).children("description").text();
            if(_obj.dscr == ""){_obj.dscr="&nbsp;";}
            dispImg(_obj.src,_obj.width,_obj.height,_obj.dscr,xml,dirnum);
            profDisp();
          });
        });
        return true;
      }
    });
  });
}


function dispImg(url,width,height,dscr,xml,dirnum){
  $(cfg.cls_dscr).fadeTo("fast", 0,function(){
    $(cfg.cls_cont).find("img").fadeOut(function(){
      $(cfg.cls_cont).html("");
      $(cfg.cls_dscr).html(dscr);
      $(cfg.cls_cont).append("<img class=\"load-img\" src=\""+ _loadcrcl.src +"\" style=\"display:none;\" />");
      $(cfg.cls_cont).find(".load-img").css({marginTop:(cfg.disp_h/2)-$(".load-img").width()});
      $(cfg.cls_cont).find(".load-img").fadeIn(function(){
        $(cfg.cls_cont).append("<img class=\"disp-img\" src=\""+url+"\" style=\"display:none;\" />");
        $(cfg.cls_cont).find(".disp-img").css(presetImgSize(width,height,cfg.disp_w,cfg.disp_h));
        $(cfg.cls_cont).find(".disp-img").load(function(){
          $(cfg.cls_cont).find(".load-img").fadeOut(function(){
            $(cfg.cls_cont).find(".load-img").remove();
            $(cfg.cls_cont).find(".disp-img").fadeIn(function(){
              clickThumb(xml,dirnum);
              clickMenu();
              $(cfg.cls_dscr).fadeTo("fast", 1);
            });
          });
        });
      });
    });
  });
}


function clickThumb(xml,dirnum){
  var _node = $("directory",xml).eq(dirnum).find("files").children("item");
  //サムネイル・クリック処理
  $(cfg.cls_thum).children("li").bind("click", function(){
    $(cfg.cls_menu).children("ul").children("li").unbind("click");
    $(cfg.cls_thum).children("li").unbind("click");
    $(cfg.cls_thum).children("li").removeClass("selected");
    _obj.num    = $(this).children("img").attr("class");
    _obj.num    = _obj.num.replace(/.*-([0-9]+)$/,"$1");
    _obj.src    = _node.eq(_obj.num).children("link").text();
    _obj.width  = _node.eq(_obj.num).children("width").text();
    _obj.height = _node.eq(_obj.num).children("height").text();
    _obj.dscr   = _node.eq(_obj.num).children("description").text();
    if(_obj.dscr == ""){_obj.dscr="&nbsp;";}
    $(cfg.cls_thum).children("li").eq(_obj.num).addClass("selected");
    dispImg(_obj.src,_obj.width,_obj.height,_obj.dscr,xml,dirnum);
  });
}


function clickMenu(){
  $(cfg.cls_menu).children("ul").children("li").bind("click",function(){
    $(cfg.cls_menu).children("ul").children("li").unbind("click").removeClass("selected");
    $(cfg.cls_thum).children("li").unbind("click");
    _obj.dir = $(this).attr("class");
    _obj.dir = _obj.dir.replace(/.*-([0-9]+)$/,"$1");
    $(this).addClass("selected");
    $(cfg.cls_dscr).fadeTo("fast", 0,function(){
      $(".disp-img").fadeOut(function(){
        $(this).removeAttr("src");
        $(cfg.cls_cont).append("<p></p>");
        $(cfg.cls_cont).children("p").css("margin-top",(cfg.disp_h/2)-50).text("please wait...");
        $(cfg.cls_thum).fadeOut(function(){
          ajaxLoadFeed(_obj.dir,1);
        });
      });
    });
  });
}


function profDisp(){
  presetHoverCss($(cfg.cls_prof).children("img"));
  $(window).resize(function(){
    profWindowSize();
  });
  $(window).scroll(function(){
    if (typeof document.body.style.maxHeight == "undefined") {
      profWindowSize();
    }
  });
  $(cfg.cls_prof).children("img").bind("click",function(){
    profWindowSize();
    $("select").hide();
    if (typeof document.body.style.maxHeight == "undefined") {
      $("body").css({height:"100%",width:"100%"});
      $("html").css("overflow","hidden");
    }
    $(cfg.cls_over).unbind("click");
    $(cfg.cls_over).fadeIn(function(){
      $(cfg.cls_info).fadeIn(function(){
        $(cfg.cls_over).bind("click", profHide);
      });
    });
  });
}


function profHide(){
  $(cfg.cls_info).fadeOut(function(){
    $(cfg.cls_over).fadeOut(function(){
      $("select").show();
      if (typeof document.body.style.maxHeight == "undefined") {
        $("body").css({height:"auto",width:"auto"});
        $("html").css("overflow","");
      }
      $(cfg.cls_over).hide();
      $(cfg.cls_info).hide();
    });
  });
}


function profWindowSize(){
  _obj.width  = window.innerWidth || self.innerWidth || (document.documentElement&&document.documentElement.clientWidth) || document.body.clientWidth;
  _obj.height = window.innerHeight || self.innerHeight || (document.documentElement&&document.documentElement.clientHeight) || document.body.clientHeight;
  if (typeof document.body.style.maxHeight == "undefined") {
    _obj.height = $("body:first").height();
  }
  _obj.left = Math.floor(($(window).width() - $(cfg.cls_info).width()) / 2);
  _obj.top  = Math.floor(($(window).height() - $(cfg.cls_info).height()) / 2);
  $(cfg.cls_over).css({width:_obj.width,height:_obj.height});
  $(cfg.cls_info).css({top:_obj.top,left:_obj.left});
  if (typeof document.body.style.maxHeight == "undefined") {
    $(cfg.cls_info).css({top:$(document).scrollTop()+_obj.top});
  }
}


function presetHoverCss(value){
  $(value).hover(function(){
    $(this).css("cursor","pointer");
  },function(){
    $(this).css("cursor","default"); 
  });
}


function presetImgSize(width,height,exWidth,exHeight){
  if(width > height){
      if(width >= exWidth){
        _obj.w_ans  = exWidth;
      } else {
        _obj.w_ans  = width;
      }
      _obj.h_cal  = height / width;
      _obj.h_ans  = Math.floor(_obj.w_ans * _obj.h_cal);
      /*_obj.l_mrg  = Math.floor((exWidth  - _obj.w_ans)/2);*/
      _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
      if(_obj.h_ans > exHeight){
        _obj.h_ans  = exHeight;
        _obj.w_cal  = width / height;
        _obj.w_ans  = Math.floor(_obj.h_ans * _obj.w_cal);
        /*_obj.l_mrg  = Math.floor((exWidth - _obj.w_ans)/2);*/
        _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
      }
  } else {
      if(height >= exHeight){
        _obj.h_ans  = exHeight;
      } else {
        _obj.h_ans  = height;
      }
      _obj.w_cal  = width / height;
      _obj.w_ans  = Math.floor(_obj.h_ans * _obj.w_cal);
      /*_obj.l_mrg  = Math.floor((exWidth - _obj.w_ans)/2);*/
      _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
    if(_obj.w_ans > exWidth){
      _obj.w_ans  = exWidth;
      _obj.h_cal  = height / width;
      _obj.h_ans  = Math.floor(_obj.w_ans * _obj.h_cal);
      /*_obj.l_mrg  = Math.floor((exWidth  - _obj.w_ans)/2);*/
      _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
    }
  }
  var imageSize = {width:_obj.w_ans+"px",height:_obj.h_ans+"px",/*marginLeft:_obj.l_mrg+"px",*/marginTop:_obj.t_mrg+"px"};
  return imageSize;
}


function presetThumbSize(width,height,exWidth,exHeight){
  if(width > height){
    if(width >= exWidth){
      _obj.w_ans  = exWidth;
    } else {
      _obj.w_ans  = width;
    }
    _obj.h_cal  = height / width;
    _obj.h_ans  = Math.floor(_obj.w_ans * _obj.h_cal);
    _obj.l_mrg  = Math.floor((exWidth  - _obj.w_ans)/2);
    _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
  } else {
    if(height >= exHeight){
      _obj.h_ans  = exHeight;
    } else {
      _obj.h_ans  = height;
    }
    _obj.w_cal  = width / height;
    _obj.w_ans  = Math.floor(_obj.h_ans * _obj.w_cal);
    _obj.l_mrg  = Math.floor((exWidth - _obj.w_ans)/2);
    _obj.t_mrg  = Math.floor((exHeight - _obj.h_ans)/2);
  }
  var imageSize = {width:_obj.w_ans+"px",height:_obj.h_ans+"px",marginLeft:_obj.l_mrg+"px",marginRight:_obj.l_mrg+"px",marginTop:_obj.t_mrg+"px",marginBottom:_obj.t_mrg+"px"};
  return imageSize;
}


//return
presetBodyCss();


};
})(jQuery);
