/**
  *  Functions
  */
// コントロールボタンの描画
function onOverWidget(portal, widget){
 widget.getElement().insertBefore($('control_buttons'), widget.getElement().firstChild);
 $('control_buttons').show();
}

// コントロールボタンの隠蔽
function onOutWidget(portal, widget){
 $('control_buttons').hide();
}

// ウィジェットの削除
function removeWidget(element){

 var widget = $(element).up(".widget").widget;
 var CookieValue   = '';
 var SerializeData = '';
 var CV            = new Array();
 var CVSeq         = new Array();

 if (confirm(portal.DeleteMessage)){ 

  document.body.appendChild($('control_buttons').hide());
  portal.remove(widget);

  // 削除した今回のウィジェット番号の取得
  var DeletedID = widget.getElement().id.replace(/widget_/, '');

  // Cookie に格納された ウィジェットID・カラム番号を取得
  if (typeof (portal.getCookieValue()) != 'undefined'){
   for (i = 0; i < portal.getCookieValue().length; i ++){
    var EachValues = portal.getCookieValue()[i].split(':');
    CV[EachValues[0]] = EachValues[1];
    CVSeq[i] = EachValues[0];
   }

   // Cookie 文字列の再生成
   $('comment_1').innerHTML = '';
   for (i = 0; i < CVSeq.length; i ++){
    if (CVSeq[i] != WidgetObjIDs[DeletedID]){
     CookieValue += CVSeq[i] + ':' + CV[CVSeq[i]] + '&';
    }
   }
  }

  // Set HTTP Cookie
  portal.setCookieValue(CookieValue);
  // Location Reload
  if (this.LocationReload){  window.location.reload();  }
 }
}

/**
  *  ウィジェットを掴んでいるときのアクション
  */
function onChange(){  }

/**
  *  Cookie の取得
  */
function fnc_getCookieValue(CName){
 var CManager = new CookieManager();
 return unescape (CManager.getCookie(CName));
}

/**
  *  Class Override
  */
var MusicEClubPortal = Class.create()
Object.extend(MusicEClubPortal.prototype, Xilinus.Portal.prototype);
Object.extend(
 MusicEClubPortal.prototype, {

  /**
    *  endDrag
    **/
  endDrag: function(eventName, draggable){
   var widget = draggable.element;
   if (! this._widgets.find(function(w) {return w == widget.widget}))
       return;

   var column = widget.ghost.parentNode;

   column.insertBefore(draggable.element, widget.ghost); 
   widget.ghost.remove();

   if (Prototype.Browser.Opera)
     widget.setStyle({top: 0, left: 0, width: "100%", height: widget._originalHeight, zIndex: null, opacity: null, position: "relative"})
   else
     widget.setStyle({top: null, left: null, width: null, height: widget._originalHeight, zIndex: null, opacity: null, position: "relative"})

   widget.ghost = null;
   widget.widget.updateHeight();
   this._updateColumnsHeight();

   // Fire events if changed
   if (this._savePosition != this.serialize()){
    if (this.options.url)
       new Ajax.Request(this.options.url, {parameters: this.serialize()});

    if (this.options.onUpdate)
       this.options.onUpdate(this);

    var CookieValue = '';

    // Set HTTP Cookie
    for (i = 0; i < this.serialize().split('&').length; i ++){
     var EachValues = this.serialize().split('&')[i].split('=');
     if (typeof (this.serialize().split('&')[i].split('=')[1]) != 'undefined'){
      // div 列 // 今回の WidgetObjID
      this.serialize().split('&')[i].split('=')[0].match(/widget_col_(\d+)\[\]/);   var _LineNo   = RegExp.$1;
      this.serialize().split('&')[i].split('=')[1].match(/widget_(\d+)/);           var _WidgetNo = RegExp.$1;
      // 
      if (typeof (WidgetObjIDs[_WidgetNo]) != 'undefined'){
       CookieValue += WidgetObjIDs[_WidgetNo] + ':' + _LineNo + '&';
      }
     }
    }
    // Set HTTP Cookie
    this.setCookieValue(CookieValue);
    // Location Reload
    if (this.LocationReload){  window.location.reload();  }
   }
  },

  /**
    *  setCookieName
    **/
  setCookieName: function(CName){
   this.CName    = CName;
   this.CManager = new CookieManager();
  },

  /**
    *  setCookieOption
    **/
  setCookieOption: function(Expires, Domain, Path){
   if (Expires.length > 0)
     this.CookieOpt = 'expires=' + Expires + '; ';
   if (Domain.length > 0)
     this.CookieOpt += 'domain=' + Domain + '; ';
   if (Path.length > 0)
     this.CookieOpt += 'path=' + Path + '; ';
  },

  /**
    *  getCookieValue
    */
  getCookieValue : function(){
   return unescape (this.CManager.getCookie(this.CName)).split('&');
  },

  /**
    *  setCookieValue
    */
  setCookieValue : function(Line){
   document.cookie = this.CName + '=' + escape(Line.replace(/&$/, '')) + '; ' + this.CookieOpt;
   // $('comment_1').innerHTML = '<font color="blue">' +  Line.replace(/&$/, '') + '</font><br />';
  },

  /**
    *  setLocationReload
    */
  setLocationReload : function(Bool){
   this.LocationReload = Bool;
  },

  /**
    *  setDeleteMessage
    */
  setDeleteMessage : function(Message){
   this.DeleteMessage = Message;
  },

  /**
    *  getViewWidgetsID
    */
  getViewWidgetsID : function(){
   var isView = new Array();;
   var i; var j;
   var CV = new Array();
   var CC = new Array();

   // Cookie に格納された ウィジェットID・カラム番号を取得
   if (typeof (this.getCookieValue()) != 'undefined'){
    for (i = 0; i < this.getCookieValue().length; i ++){
     CV[i] = this.getCookieValue()[i].split(':')[0];
     CC[i] = this.getCookieValue()[i].split(':')[1];
    }
   }
   // 現在の表示状態を isViewByWidgetID にセット
   for (i = 0; i < CV.length; i ++){  isView[CV[i]] = 1;  }
   return isView;
  },

  /**
    *  addWidget
    */
  addWidget : function(WidgetID, DivLine){
   DivLine = (DivLine != null) ? DivLine : 0;
   var addFlag     = 0;
   var CookieValue = '';
   if (typeof (this.getCookieValue()) != 'undefined'){
    for (i = 0; i < this.getCookieValue().length; i ++){
     if ((addFlag == 0) && (this.getCookieValue()[i].split(':')[1] == DivLine)){
      CookieValue += WidgetID + ':' + DivLine + '&';
      addFlag = 1;
     }
     CookieValue += this.getCookieValue()[i] + '&';
    }
    if (addFlag == 0){
     CookieValue += WidgetID + ':' + DivLine + '&';
    }

    // Title[WidgetID], Contents, InitDescription, Thumbnail の読み込み
    var url = WidgetDataURL + '?' + WidgetID;
    // Parse XML
    new Ajax.Request(url, {
         method: "get",
         requestHeaders: ['If-Modified-Since', ModifiedSince],
         onComplete : function (xmlObj){  addWidgetVariables(CookieValue, xmlObj);  }
        });
   }
  }

 }
);


/**
  *  addWidgetVariables (Callback)
  */
function addWidgetVariables(CookieValue, xmlObj){
 //
 var LineNo = 0;
 // Parse
 var Obj = xmlObj.responseXML;
 if (parseInt(Obj.getElementsByTagName('result')[0].firstChild.nodeValue) == 1){
  var id = parseInt(Obj.getElementsByTagName('id')[0].firstChild.nodeValue);
  Title[id]           = (Obj.getElementsByTagName('Title')[0].firstChild != null) ? 
        Obj.getElementsByTagName('Title')[0].firstChild.nodeValue : '';
  Contents[id]        = (Obj.getElementsByTagName('Contents')[0].firstChild != null) ? 
        Obj.getElementsByTagName('Contents')[0].firstChild.nodeValue : '';
  InitDescription[id] = (Obj.getElementsByTagName('InitDescription')[0].firstChild != null) ? 
        Obj.getElementsByTagName('InitDescription')[0].firstChild.nodeValue : '';
  Thumbnail[id]       = (Obj.getElementsByTagName('Thumbnail')[0].firstChild != null) ? 
        Obj.getElementsByTagName('Thumbnail')[0].firstChild.nodeValue : '';
  LineNo              = (Obj.getElementsByTagName('DiVID')[0].firstChild != null) ? 
        Obj.getElementsByTagName('DiVID')[0].firstChild.nodeValue : 0;
  // ウィジェット追加リンクの消去
  $('addW_' + id).innerHTML = '';

  // 
  WidgetObjIDs.push(id);
  // setCookie
  portal.setCookieValue(CookieValue);
  // 
  window.location.reload();
  // WidgetObj[id] = new MusicEClubPortal.Widget().setTitle(Title[id]).setContent(Contents[id]);
  // portal.add(WidgetObj[id], LineNo);

 }
}

/**
  *  Initialize
  */
function init(){
 //
 var WidgetNo = new Array();
 // make Instance
 portal = new MusicEClubPortal("#page div", {onOverWidget: onOverWidget,
                                             onOutWidget:  onOutWidget,
                                             onChange:     onChange,
                                             removeEffect: Effect.SwitchOff});
 // Init
 portal.setCookieName(CookieKey);
 portal.setCookieOption(CookieExpires, CookieDomain, CookiePath);
 portal.setLocationReload(LocationReload);
 portal.setDeleteMessage(DeleteMessage);

 // Cookie の取得 参照データ WidgetObjIDs 配列の生成
 if (typeof (portal.getCookieValue()) != 'undefined'){
  for (i = 0; i < portal.getCookieValue().length; i ++){
   if (typeof (portal.getCookieValue()[i].split(':')[1]) != 'undefined'){
    WidgetNo[i]     = portal.getCookieValue()[i].split(':')[1];
    WidgetObjIDs[i] = portal.getCookieValue()[i].split(':')[0];
   }
  }
 }

 for (i = 0; i < WidgetObjIDs.length; i ++){
  if (typeof (WidgetObjIDs[i]) != 'undefined'){
   portal.add(WidgetObj[WidgetObjIDs[i]], WidgetNo[i]);
  }
 }

 // コントロールボタン
 portal.addWidgetControls("control_buttons");
}

/**
  *  Widget observe
  */
Event.observe(window, "load", init);

