var apiRoot    = "http://www.mindana.jp/shelf/";
var mypageRoot = "http://www.mindana.jp/mypage/";
var registRoot = "http://www.mindana.jp/regist/";


function limitChars(target, maxlength) {
    if ( target.value.length > maxlength ) {
        alert("プロフィールの文字数は200文字までです。");
        target.value = target.value.substr(0, maxlength);
    }
    target.focus();
}

var coverScrolling = false;
var currentCoverStep = 0;

function coverScroll(vector) {
  var prev = $("cover").down("div.prev");
  var next = $("cover").down("div.next");
  var coverList = $("coverList").down("ul");

  if (!coverScrolling) {
    if (vector == "next") {
      currentCoverStep += 1;
    } else if (vector == "prev") {
      currentCoverStep -= 1;
    }
    var books_array = coverList.select('li');
    var books = books_array.length;

    if (currentCoverStep < 0) {
      currentCoverStep = 0;
    }

    var moveX = - currentCoverStep * 240;
  }
  if (!coverScrolling) {
          coverScrolling = true;
    new Effect.Move(coverList, {x: moveX, y:0,
        fps:60,
        duration: 0.8,
        mode: 'absolute',
        beforeStartInternal: function(effect) {
        },
        afterFinishInternal: function(effect) {
          coverScrolling = false;

          prev.addClassName('on');
          next.addClassName('on');

          if (currentCoverStep == 0) {
            prev.removeClassName('on');
            next.addClassName('on');
          } else if (currentCoverStep == books - 1) {
            prev.addClassName('on');
            next.removeClassName('on');
          } else {
            prev.addClassName('on');
            next.addClassName('on');
          }
        }
      });
  }
}


var isOpenClosingShelfs = false;
var isOpenCloseShelfs = false;
function openCloseShelfs(id, type, icNum, catNum) {
  var item = $(id);
  if (!isOpenCloseShelfs) {
    isOpenCloseShelfs = true;
    isOpenClosingShelfs = true;
    item.addClassName("open");
    var _html = '<img src="/img/loading.gif" id="shelfsLoader" />';
    new Insertion.Top(item, _html);
    var apiUlr = apiRoot + "GetShelfWithItem.php";

    var data = "";
    data += "ic=" + icNum;
    data += "&cat=" + catNum;
    var myAjax = new Ajax.Request(
                                  apiUlr, 
                                  {
                                  method: 'get', 
                                  parameters: data, 
        onSuccess: function(transport){
          var res = transport.responseXML;
          var mes = transport.responseText;

          Element.remove("shelfsLoader");
          new Insertion.Top(item, mes);
          isOpenClosingShelfs = false;
        },
        onFailure: function(){
        }
    });
  } else {
    var current = item.hasClassName("open");
    if (!current) {
      if (!isOpenClosing) {
            item.addClassName("open");
            item.hide();
        new Effect.BlindUp(item, {
          from:1.0,
          to:0.0,
          fps:60,
          duration: 0.4,
          beforeStartInternal: function(effect) {
            isOpenClosing = true;
          },
          afterFinishInternal: function(effect) {
            isOpenClosing = false;
          }
        });
      }
    } else {
      if (!isOpenClosing) {
        item.removeClassName("open");
        item.hide();
      }
    }
  }
}


function showBookDetailEditor(type ,item_no, item_cat) {
  if (type == "hide") {
    var item = parent.document.getElementById("detailEditor");
    parent.document.getElementById("ghSearch").down("select").show();
    Element.remove(item);
  } else {
    $('ghSearch').down("select").hide();
    var ww = $('container').getWidth();
    var hh = $('container').getHeight();
    var base_url = '/shelf/ItemDetailEdit/' + item_no + '/' + item_cat + '/';
    var ww2 = ww - 10;
    var hh2 = hh - 60;

		var pos_str = Position.realOffset($("container")).toString();
		var pos_array = pos_str.split(",");
		var yy = pos_array[1];
    var style = 'border:none; display:block; margin:0 auto; padding:0; background:transparent; margin-top:' + yy + 'px;';
    var _html = '<div id="detailEditor" style="height:' + hh + 'px;"><iframe src="'+base_url+'" name="gadget" width="'+ww2+'" height="'+hh2+'" style="'+style+'" scrolling="no" border="0" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" allowtransparency="true"></iframe></div>';
    new Insertion.Before("container", _html);
  }
}

function deleteFromShelfShow(id) {
  var item = $(id).down("div.deleteShelf");
  Element.setStyle(item, {
                          }); 
  item.appear({ duration: 0.6 });
}

function deleteFromShelfHide(id) {
  var item = $(id).down("div.deleteShelf");
  Element.setStyle(item, {
                          'display': 'none' 
                          }); 
}

function deleteItem(item_no, item_cat) {
  DeleteUrl = apiRoot + "DeleteItem/" + item_no + "/" + item_cat + "/";
  location.href= DeleteUrl;
}


var currentShelf;
function showEditShelf(id, type) {
  currentShelf = id;
  var div = "div." + type;
  var item = $(id).down("div." + type);

  var xx = mouse_x - 40;
  var yy = mouse_y + 5;

  Element.setStyle(item, {
                          'left': xx + 'px',
                          'top': yy + 'px' 
                          }); 
  item.appear({ duration: 0.6 });
  if (type == "deleteShelf") {
    hideEditShelf(id, 'changeShelfName');
    hideEditShelf(id, 'publishShelf');

  } else if (type == "changeShelfName") {
    hideEditShelf(id, 'deleteShelf');
    hideEditShelf(id, 'publishShelf');
  } else if (type == "publishShelf") {
    hideEditShelf(id, 'deleteShelf');
    hideEditShelf(id, 'changeShelfName');
  }
}


function deleteShelf(id, shelf_no) {
  DelShelfUrl = mypageRoot + "DeleteShelf/" + shelf_no + "/"
  location.href= DelShelfUrl;
}

function changeShelfName(id, shelf_no) {
	var updForm = "upd" + id;
	document.updForm.action = "/mypage/UpdateShelfName.php";
	document.updForm.method = "POST";
	document.updForm.no = shelf_no;
	document.updForm.submit();
}

/* ここまで */


function hideEditShelf(id, type) {
  var item = $(id).down("div." + type);
  Effect.DropOut(item);
  Element.setStyle(item, {
                          'display': 'none' 
                          }); 
}

var currentBook;
function selectShelfShow2(id) {
  currentBook = id;
  var item = $(id).down("div.selectShelf");
  item.appear({ duration: 0.6 });
}

function selectShelfHide2(id) {
  var item = $(id).down("div.selectShelf");
  Effect.DropOut(item);
  Element.setStyle(item, {
                          'display': 'none' 
                          }); 

  Element.removeClassName(item, 'onComplate');

}

var isMoreInfoOpenClosing = false;
function openCloseMoreInfo(id) {
  var item = $(id).down("div.moreInfo");
  var body = $(id).down("div.body");
  var current = item.hasClassName("headerOpen");
  if (!current) {
    if (!isMoreInfoOpenClosing) {
          item.addClassName("headerOpen");
          body.addClassName("open");
          body.hide();
      new Effect.BlindUp(body, {
        from:1.0,
        to:0.0,
        fps:60,
        duration: 0.4,
        beforeStartInternal: function(effect) {
          isMoreInfoOpenClosing = true;
        },
        afterFinishInternal: function(effect) {
          isMoreInfoOpenClosing = false;
        }
      });
    }
  } else {
    if (!isMoreInfoOpenClosing) {
      item.removeClassName("headerOpen");
      body.removeClassName("open");
      body.hide();
    }
  }
}

function posFromEdgeX(idNum) {
  var tf;
  if (idNum == 4 || idNum == 5 || idNum == 9 || idNum == 10 || idNum == 14 || idNum == 15) {
    tf = true;
  } else {
    tf = false;
  }


    tf = true;

  return tf;
}

function posFromEdgeY(idNum) {
  var tf;
  if (idNum <= 5) {
    tf = true;
  } else {
    tf = false;
  }
  return tf;
}

var titleHover = false;
var descriptioneHover = false;
var popHover = false;

function viewTitle(id,type) {

	shelfZ ++;
  var book = $(id);
  var idNum = id.split("book")[1];
  var xx;
  if (posFromEdgeX(idNum)) {
    xx = -120;
  } else {
    xx = 100;
  }
  var yy;
  if (posFromEdgeY(idNum)) {
    var yy = 0;
  } else {
    var yy = 0;
  }

  var ww = book.down("img.cover").getWidth();
  var hh = book.down("img.cover").getHeight();

  if (type == "show") {
    book.down("div.title").addClassName("open");
    book.down("img.hover").addClassName("open");
    Element.setStyle(book.down("div.title"), {
                            'left': xx + 'px',
                            'z-index': shelfZ,
                            'top': yy + 'px'
                            }); 

    Element.setStyle(book.down("img.hover"), {
                            'width': ww + 'px',
                            'height': hh + 'px'
                            }); 
  } else if (type == "hide"){
    book.down("div.title").removeClassName("open");
    book.down("img.hover").removeClassName("open");
  }
}

function goDetail(id,afid) {
  if(typeof afid == "undefined"){ afid = "";}
  DetailUrl = apiRoot + "ItemDetail/" + id + "/" + afid;
  location.href= DetailUrl;
}

var shelfZ = 1000;
function viewPop(id,type) {
	shelfZ ++;

  var book = $(id);
  var idNum = id.split("book")[1];
  var xx;
  if (posFromEdgeX(idNum)) {
    xx = -90;
  } else {
    xx = 100;
  }
  var yy;
  if (posFromEdgeY(idNum)) {
    var yy = -20;
  } else {
    var yy = -20;
  }
  if (type == 'show') {
    book.down("div.pop").addClassName("open");
    book.down("div.title").removeClassName("open");
    Element.setStyle(book.down("div.pop"), {
                            'left': xx + 'px',
                            'z-index': '1000',
                            'top': yy + 'px'
                            }); 
  } else {
    book.down("div.pop").removeClassName("open");
  }
}

function viewPopSelf(id,type) {
  var book = $(id);
  if (type == 'show') {
    book.down("div.pop").addClassName("open");
  } else {
    book.down("div.pop").removeClassName("open");
  }
}

function showSubMenu(id, type) {
  openClose(id, 'switch');
}


function changeSkin(id, type) {
  var item;
  if (type == "theme") {
    var skins = 13;
    item = $('myThemeEdit');
  } else {
    var skins = 31;
    item = $('shShelfDesign');
  }
  for (var i = 1; i <= skins; i++) {
    var radio = item.down("li.s" + i).down("input")
    radio.checked = false;
  }
  var radio = item.down("li.s" + id).down("input")
  radio.checked = true;
  if (type == "theme") {
    var skinId;
    skinId = 's' + id;
    var CSSes = document.getElementsByTagName("link");
    for (var j = 0; j < CSSes.length; j++) {
      var cssPath = CSSes[j].href;
      var cssPath_array = cssPath.split("/");
      if (cssPath_array[cssPath_array.length - 3] == "skins") {
        if (cssPath_array[cssPath_array.length - 1] == "colors.css") {
          CSSes[j].href = '/css/skins/' + skinId + '/colors.css';
        } else if (cssPath_array[cssPath_array.length - 1] == "image.css") {
          CSSes[j].href = '/css/skins/' + skinId + '/image.css';
        }
      }
    }
  }
}

function showRemoveFavorite() {
  var item = $('aFRemoveComp');
  item.appear({ duration: 0.6 });
}

function closeRemoveFavorite() {
  var item = $('aFRemoveComp');
  Effect.DropOut(item);
  Element.setStyle(item, {
    'display': 'none' 
  }); 

}

function addFavorite(type, fav_uno) {
  if (type == 'remove') {
    closeRemoveFavorite();
    var apiUlr = apiRoot + "DeleteFavUser.php";
  }else{
    var apiUlr = apiRoot + "RegistFavUser.php";
  }

  var data = "";
  data += "uno=" + fav_uno;

  var myAjax = new Ajax.Request(
                                apiUlr, 
                                {
                                method: 'post', 
                                parameters: data, 
        onSuccess: function(transport){
          var res = transport.responseXML;
          var result = res.getElementsByTagName('Result')[0];
          var id = result.getAttribute("id");
          if (id == "1") {
            if (type == 'add') {
              $('addFavorite').addClassName("addedFavorite");
            } else {
              $('addFavorite').removeClassName("addedFavorite");
            }
          } else {
            alert(result.firstChild.nodeValue);
          }
          Element.remove("connecting");
        },
        onFailure: function(){
        }
  });
}

function selectShelf(item_code, item_cat) {
  var sheldId = $F("selectedShelf");
  if (sheldId == 'x') {
    alert("本棚を選択してください。");
  } else {
    var hh = $('container').getHeight();
    var _html = '<div id="connecting" style="display:none; height:' + hh + 'px;">&nbsp;</div>';
    new Insertion.Before("container", _html);
    new Effect.Appear("connecting", { duration: 0.1, from: 0.0, to: 0.8 });
    var apiUlr = apiRoot + "RegistItem.php";

    var data = "";
    data += "ic=" + item_code;
    data += "&cat=" + item_cat;
    data += "&sno=" + sheldId;
    var myAjax = new Ajax.Request(
                                  apiUlr, 
                                  {
                                  method: 'post', 
                                  parameters: data, 
          onSuccess: function(transport){
            var res = transport.responseXML;
            var result = res.getElementsByTagName('Result')[0];
            var id = result.getAttribute("id");

            var message = res.getElementsByTagName('Message')[0];
            var mes = message.textContent;

            if(typeof mes == "undefined"){ mes = "";}

            var item = $('selectShelf');
            if (item) {
              Element.addClassName(item, 'onComplate');
              if (item.down("p.mes")) {
                Element.remove(item.down("p.mes"));
              }
              new Insertion.Top(item.down("div.complate"), "<p class='mes'>" + mes + "</p>");
            } else {
              var item2 = $(currentBook).down("div.selectShelf");
              if (item2) {
                Element.addClassName(item2, 'onComplate');
                if (item2.down("p.mes")) {
                  Element.remove(item2.down("p.mes"));
                }
                new Insertion.Top(item2.down("div.complate"), "<p class='mes'>" + mes + "</p>");
              }
            }
            Element.remove("connecting");
          },
          onFailure: function(){
          }
    });
  }
}

function selectShelf2(item_code, item_cat, selshelf) {

  var sheldId = $F("selectedShelf-" + selshelf);
  if (sheldId == 'x') {
    alert("本棚を選択してください。");
  } else {
    var hh = $('container').getHeight();
    var _html = '<div id="connecting" style="display:none; height:' + hh + 'px;">&nbsp;</div>';
    new Insertion.Before("container", _html);
    new Effect.Appear("connecting", { duration: 0.1, from: 0.0, to: 0.8 });
    var apiUlr = apiRoot + "RegistItem.php";

    var data = "";
    data += "ic=" + item_code;
    data += "&cat=" + item_cat;
    data += "&sno=" + sheldId;
    var myAjax = new Ajax.Request(
                                  apiUlr, 
                                  {
                                  method: 'post', 
                                  parameters: data, 
          onSuccess: function(transport){
            var res = transport.responseXML;
            var result = res.getElementsByTagName('Result')[0];
            var id = result.getAttribute("id");

            var message = res.getElementsByTagName('Message')[0];
            var mes = message.textContent;

            if(typeof mes == "undefined"){ mes = "";}

            var item = $('selectShelf');
            if (item) {
              Element.addClassName(item, 'onComplate');
              if (item.down("p.mes")) {
                Element.remove(item.down("p.mes"));
              }
              new Insertion.Top(item.down("div.complate"), "<p class='mes'>" + mes + "</p>");
            } else {

              var item2 = $(currentBook).down("div.selectShelf-" + selshelf);


              if (item2) {
                Element.addClassName(item2, 'onComplate');
                if (item2.down("p.mes")) {
                  Element.remove(item2.down("p.mes"));
                }
                new Insertion.Top(item2.down("div.complate"), "<p class='mes'>" + mes + "</p>");
              }
            }
            Element.remove("connecting");
          },
          onFailure: function(){
          }
    });
  }
}


var isOpenClosing = false;
function openClose(id, type) {
  var item = $(id);
  var current = item.hasClassName("open");
  if ((type == "open" && !current) || (type == "switch" && !current)) {
    if (!isOpenClosing) {
          item.addClassName("open");
          item.hide();
      new Effect.BlindUp(item, {
        from:1.0,
        to:0.0,
        fps:60,
        duration: 0.4,
        beforeStartInternal: function(effect) {
          isOpenClosing = true;
        },
        afterFinishInternal: function(effect) {
          isOpenClosing = false;
        }
      });
    }
  } else if ((type == "close" && current) || (type == "switch" && current)) {
    if (!isOpenClosing) {
      item.removeClassName("open");
      item.hide();
    }
  }
}


/* Fixed ---------------------------------------------------- */
function toPageTop() {
  new Effect.ScrollTo("container", {fps:60, duration: 1.0});
}

function showPasteAlert(id) {
    new Effect.Highlight(id, {
                              from:0.0,
                              to:1.0,
                              fps:60,
                              duration: 2
                              });
}

function viewShelf(){
  var item = $('shelfs');
  Effect.BlindDown('shelfs', { duration: 0.7 });
}

function selectShelfShow() {
  $('selectShelf').appear({ duration: 0.6 });
}

function selectShelfHide() {
  Effect.DropOut('selectShelf');
  var item = $('selectShelf');
  Element.setStyle(item, {
                          'display': 'none' 
                          }); 
}

function readFaq(id){
  new Effect.ScrollTo(id, {fps:60, duration: 1.0});
}


if (typeof Effect == 'undefined')
  throw("You must have the script.aculo.us library to use this accordion");

var Accordion = Class.create({
  initialize: function(id, defaultExpandedCount) {
    if(!$(id)) throw("Attempted to initalize accordion with id: "+ id + " which was not found.");
    this.accordion = $(id);
    this.options = {
      openClass: "open",
      closeClass: "close"
    }
    this.contents = this.accordion.select('li.menu');
    this.isAnimating = false;
    this.maxHeight = 0;
    this.selectedId = $("selectedId").innerHTML;

	if (this.selectedId) {
    this.accordion.down('li#' + this.selectedId).addClassName("selected");
    this.current = this.accordion.down('li#' + this.selectedId).up('li.menu');
	}

    this.checkMaxHeight();
    this.initialHide();
    var clickHandler =  this.clickHandler.bindAsEventListener(this);
    this.accordion.observe('click', clickHandler);
  },

  checkMaxHeight: function() {
    for(var i=0; i<this.contents.length; i++) {
      this.contents[i].hh = this.contents[i].down('ul').getHeight();
    }
  },

  clickHandler: function(e) {
    var el = e.element();
    if (!this.isAnimating) {
      if(el.up(0).hasClassName('menu') || el.up(1).hasClassName('menu') || el.hasClassName('minus') || el.hasClassName('plus')) {
        if (el.up(0).hasClassName('menu')) {
					if (el.hasClassName('minus') || el.hasClassName('plus')) {
	          this.current = el.up(1);
					} else {
	          this.current = el.up(0);
					}
        } else {
          this.current = el.up(1);
        }

        var effects = new Array();
        if(this.current.hasClassName('close')) {
          this.current.down('ul').show();
          this.current.down('ul').setStyle({height: 20});
          this.current.addClassName('open');
          this.current.removeClassName('close');
          var options = {
            sync: true,
            scaleFrom: 0,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleMode: {
              originalHeight: this.current.hh,
              originalWidth: this.accordion.getWidth()
            },
            scaleX: false,
            scaleY: true
          };
          effects.push(new Effect.Scale(this.current.down('ul'), 100, options));
        } else {
          this.current.addClassName('close');
          this.current.removeClassName('open');
          var options = {
            sync: true,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleX: false,
            scaleY: true
          };
          effects.push(new Effect.Scale(this.current.down('ul'), 0, options));
        }

        var myDuration = 0.5;
        new Effect.Parallel(effects, {
          duration: myDuration,
          fps: 35,
          queue: {
            position: 'end',
            scope: 'accordion'
          },
          beforeStart: function() {
            this.isAnimating = true;
          }.bind(this),
          afterFinish: function() {
            if(this.current.hasClassName('open')) {
              this.current.down('ul').setStyle({ height: this.current.hh+"px" });
              this.current.down('ul').show();
              this.current.show();
            } else {
              this.current.down('ul').hide();
            }
            this.isAnimating = false;
          }.bind(this)
        });
      }
    }
  },

  initialHide:function(){
    for(var i=0; i<this.contents.length; i++){
      if(this.contents[i] != this.current) {
        this.contents[i].down('ul').hide();
        this.contents[i].down('ul').setStyle({height: 0});
        this.contents[i].addClassName(this.options.closeClass);
      } else {
        this.contents[i].addClassName(this.options.openClass);
      }
    }
  }
});


function selectTab(id) {
  for (var i = 1; i < 3; i ++) {
    var tab = $('tab' + i).removeClassName('on');
    var page = $('tab' + i + '-page').removeClassName('on');
  }
  var tab = $(id).addClassName('on');
  var page = $(id + '-page').addClassName('on');
}

function setSideAccordionMenu() {
  accordion = new Accordion("lnShelfMenu");
  accordion = new Accordion("lnMyNoteMenu");
}

function includeModule(id, file, func) {
  new Ajax.Updater(id,file,{method: 'get', onComplete: func});
}


var mouse_x;
var mouse_y;
function handler(e) { 
  mouse_x = Event.pointerX(e); 
  mouse_y = Event.pointerY(e); 
}

Event.observe(window, 'load', function() {
  if ($("container")) {
    Event.observe('container', 'click', handler);
  }
  var bodyElement = document.getElementsByTagName('body')[0];
  var bodyClasses = Element.classNames(bodyElement);
  var classNames = bodyClasses.toString();
  var className_array = classNames.split(" ");
  var categoryId = className_array[0];
  var contentId = className_array[1];
  
  if ($("lnShelfMenu")) {
    accordion = new Accordion("lnShelfMenu");
  }


  try {
    document.execCommand('BackgroundImageCache', false, true);
  } catch(e) {}
  
});

function HeadSechShelf(){
	document.HeadSearch.t.value = 2;
	document.HeadSearch.action = "/search/ItemSearch.php";
	document.HeadSearch.submit();
}
function HeadSechAll(){
	document.HeadSearch.t.value = 1;
	document.HeadSearch.action = "/search/ItemSearch.php";
	document.HeadSearch.submit();
}

function goNewUser() {
  NewUserUrl = registRoot + "NewNetOffUser/"
  location.href= NewUserUrl;
}

