var FILM = {

  playerObj : 'video_player',
  activeClass : 'active',
  videoContainer : 'videos_gallery',
  videoTypesContainer : 'video_types',
  playParam : null,
  videosType : new Array('reelclever', 'vimeo', 'youtube'),
  loadingObj : 'ajax_working',
  vimeoPlayerUrl : 'http://player.vimeo.com/video/{id}',
  youtubePlayerUrl : 'http://www.youtube.com/v/{id}',
  commentUrl : null,
  commentsContainer : 'diary_comments',
  innerCommentClass : 'childs',
  hideClass : 'hide',
  commentForm : 'comment_form',
  commentLabelText : 'Write Comment...',
  replyCommentClass : 'reply',
  viewCommentClass : 'comments_num',
  baseUrl : null,
  sidebarObj : 'sidebar',

  init : function() {
    if ($(this.playerObj)) {
      this.playerObj = $(this.playerObj);

      this.videoTypesContainer = $(this.videoTypesContainer);
      this.videoContainer = $(this.videoContainer);
    }

    this.baseUrl = $($('tabs').down('a')).href;
    this.sidebarObj = $(this.sidebarObj);

    // add random number to avoid caching
    this.commentUrl = this.baseUrl + '/comment?v='
        + Math.floor(Math.random() * 11);
    this.commentsContainer = $(this.commentsContainer);

    if ($(this.commentForm)) {
      this.commentForm = $(this.commentForm);
      this.setCommentForm();
    }

    this.loadingObj = $(this.loadingObj);
    this.loadSection();

    this.setImagePreviewEvent();

    this.setStoryboardInfoEvent();


      if($('storyboard')) {
      var items = [];
      var tooltipObj = $($('storyboard').down('.info_wrapper'));
      if(tooltipObj) {
        tooltipObj.style.visibility = 'hidden';
        var mainObj = $('storyboard');
        var previewObj = $(mainObj.down('.preview'));
        if (previewObj) {
          var liEle = $(previewObj.next(0)).getElementsBySelector('li');
          $A(liEle).each(function(obj) {
            FILM.shotStoryobardInfo($(obj), true);
            var thumbSrc = $(obj).down('img').src;
            var clone = previewObj.cloneNode(true);
            $(clone.down('img')).src = FILM.getStoryboardPreviewSrc(thumbSrc);
            $(clone.down('.info_wrapper')).style.visibility = 'visible';
              items.push(clone);
          });
        }
        tooltipObj.style.visibility = 'visible';
        tooltipObj.addClassName(this.hideClass);

        // enable slideshow
        Lightbox.initialize();
        $($('lightboxImage').up('div')).addClassName('image');
        //$($('storyboard').down('.info_wrapper'));
        $('sb_play').observe('click', function(event) {
          event.stop();
          Lightbox.startSlide(items);
        });
    }
      }

  },

  setCommentForm : function(form) {
    if (!form) {
      form = this.commentForm;
    }
    if (form == this.commentForm) {
      this.setCommentFormLabel();
    }

    form.observe('submit', function(event) {
      event.stop();
      FILM.updateComment(this);
    });

  },

  updateComment : function(form) {
    this.submit(form);
  },

  setCommentFormLabel : function() {
    var form = this.commentForm;
    var textareaObj = $(form.down('textarea'));
    textareaObj.value = this.commentLabelText;

    this.setFormTextareaEvent(textareaObj, form);
  },

  setFormTextareaEvent : function(textareaObj, form) {
    textareaObj.stopObserving();
    textareaObj.observe('focus', function() {
      if (this.value == FILM.commentLabelText) {
        form.addClassName(FILM.activeClass);
        form.reset();
      }
    });

    textareaObj.observe('blur', function(event) {
      setTimeout(function() {
        if (!textareaObj.value) {
          if (form == FILM.commentForm) {
            form.removeClassName(FILM.activeClass);
            textareaObj.value = FILM.commentLabelText;
          } else {
            form.remove();
          }
        }
      }, 100);
    });
  },

  setInnerCommentForm : function(thisObj) {
    // var parentObj = $(thisObj.parentNode);
    // var relObj = parentObj.next(0);
    var container = $($(thisObj.up('li')).down('.' + this.innerCommentClass));
    if (!container.down('form')) {
      var newForm = this.commentForm.cloneNode(true);
      newForm = $(newForm);
      newForm.id = '';
      Element.insert(container, {
        'before' : newForm
      });

      var val = this.getButtonValue(thisObj);
      newForm.insert('<input name="id" type="hidden" value="' + val + '" />');

      newForm.addClassName(this.activeClass);
      var textareaObj = newForm.down('textarea');
      textareaObj.value = '';

      this.setFormTextareaEvent(textareaObj, newForm);

      newForm.focusFirstElement();
      this.setCommentForm(newForm);
      return false;
    }
  },

  afterAddComment : function(updater, form) {
    this.resetCommentForm(form);
    this.afterGetComments(updater);
  },

  resetCommentForm : function(form) {
    if (form == this.commentForm) {
      form.removeClassName(this.activeClass);
      var textareaObj = $(form.down('textarea'));
      textareaObj.value = FILM.commentLabelText;
    } else {
      form.remove();
    }
  },

  getComments : function() {
    if ($(this.commentsContainer)) {
      var page = HistoryManager.getParamValue('page');
      var params = page ? 'page=' + page : null;
      this.sendQuery(this.commentsContainer, this.commentUrl, null, params);
    }
  },

  afterGetComments : function(updater) {
    if (updater == this.commentsContainer) {
      var buttons = updater.getElementsByTagName('button');
      $A(buttons).each(function(obj) {
        obj = $(obj);
        $(obj).stopObserving();
        obj.observe('click', function(event) {
          if (this.hasClassName(FILM.viewCommentClass))
            FILM.getChildComments(this);
          else if (this.hasClassName(FILM.replyCommentClass))
            FILM.setInnerCommentForm(this);
        });
      });
    } else {
      this.updateCommentsNumber(updater);
    }
  },

  updateCommentsNumber : function(updater) {
    var len = updater.getElementsBySelector('li').length;
    var cNum = $($(updater.up('li')).down('.' + this.viewCommentClass));
    var buttonStr = cNum.innerHTML;
    var s = buttonStr.match(/[\d\.]+/g);
    cNum.update(buttonStr.replace(s[0], len));
  },

  getChildComments : function(thisObj) {
    var updater = $($(thisObj.up('li')).down('.' + this.innerCommentClass));
    if (updater.down('ul')) {
      updater.toggleClassName(this.hideClass);
      return false;
    }
    var params = 'id=' + this.getButtonValue(thisObj);

    this.sendQuery(updater, this.commentUrl, thisObj, params);
  },

  getFormUpdater : function(form) {
    return (form == this.commentForm) ? this.commentsContainer : form.next(0);
  },

  getPlayer : function() {
    /*
     * if (type == 'reelclever') { }
     */
    var activeVideo = this.getActiveObj(this.videoContainer).down('a');
    var url = activeVideo.href;
    url = this.genUrl(url);

    var type = HistoryManager.getQueryStringParameter('type', url)
        || this.videosType[0];

    var iframe = this.playerObj.down('iframe');
    if (type == this.videosType[0]) {
      var params = 'v=1';
      this.sendQuery(this.playerObj, url, null, params);
      this.playerObj.addClassName('play');

      if (iframe)
        iframe.remove();
    } else {

      // this.isRequesting(true, this.playerObj);
      if (this.playerObj.down('div'))
        $(this.playerObj.down('div')).remove();
      this.playerObj.removeClassName('play');
      if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.width = '632';
        iframe.height = '355';
        this.playerObj.insert(iframe);
      }

      var playerUrl;
      if (type == this.videosType[1])
        playerUrl = this.vimeoPlayerUrl;
      else if (type == this.videosType[2])
        playerUrl = this.youtubePlayerUrl;
      if (playerUrl) {
        var id = activeVideo.id.substring(4);
        iframe.src = playerUrl.replace('{id}', id);
      }
      // iframe.onload = function(){ FILM.isRequesting(true, FILM.playerObj);};
    }
  },

  getVideos : function() {
    if ($(this.videoContainer)) {
      var thisObj = this.getActiveObj(this.videoTypesContainer).down('a');
      var url = this.genUrl(thisObj.href);
      thisObj.updater = this.videoContainer;

      this.sendQuery('', url, thisObj);
    }
  },

  afterGetVideos : function() {
    this.setVideoActiveStatus();
    this.getPlayer();
  },

  setImagePreviewEvent : function() {
    $$('.preview_gallery li a').each(function(obj) {
      $(obj).observe('click', function(event) {
        event.stop();
        FILM.showPreview(this);
      });
    });
  },

  getStoryboardPreviewSrc: function(oldSrc) {
    return oldSrc.replace('_Small.', '_Large.');
  },

  showPreview : function(thisObj) {
    var previewObj = $($(thisObj.up('ul')).previous(0));
    var dummy = new Image();
    var newSrc;
    var previewImage = $(previewObj.down('img'));

    previewObj.setOpacity(0.5);

    if (thisObj.rel == 'photo_preview') {
      newSrc = this.getStoryboardPreviewSrc(thisObj.down('img').src);
    } else if (thisObj.rel == 'flickr') {
      newSrc = thisObj.down('img').src.replace('_s.', '.');
    }
    dummy.src = newSrc;
    this.loadingObj.show();
    dummy.onload = function() {
      previewImage.src = newSrc;
      previewObj.setOpacity(1);
      FILM.loadingObj.hide();
    }

    this.setActive(thisObj);
  },

  getSidebarData : function() {
    var url = this.baseUrl + '/data';
    var params = 'url_for=' + window.location.href;
    this.sendQuery('', url, this.sidebarObj, params, 'post');
  },

  genUrl : function(url) {
    return unescape(url.replace('#', '?'));
  },

  getButtonValue : function(btn) {
    if (window.ActiveXObject) {
      if (navigator.appName == 'Microsoft Internet Explorer'
          && parseFloat(navigator.appVersion.split('MSIE')[1]) == 7)
        $(btn).outerHTML = $(btn).outerHTML;
    }
    return btn.value;
  },

  submit : function(form) {
    form.request( {
      parameters : Form.serialize(form),
      onLoading : FILM.onSubmit(form),
      onComplete : function(request) {
        FILM.afterSubmit(request, form);
      }
    });
  },

  onSubmit : function(form) {
    this.isRequesting(true, form);
    form.disable();
  },

  afterSubmit : function(request, form) {
    this.isRequesting(false, form);
    var resp = request.responseText.evalJSON(true);
    form.enable();

    if (resp['errors'] == 0) {
      var updater = this.getFormUpdater(form);
      updater.update(resp['text']);
      this.afterAddComment(updater, form);
      // this.resetCommentForm(form);
      // if (updater == this.container)
      // this.setParentEvents();
      // else
      // this.updateCommentNum(updater);
    }
  },

  /*
   * Send AJAX request to server
   */
  sendQuery : function(updater, url, thisObj, params, method) {
    if (!method)
      method = 'get';
    if (!params)
      params = false;

    this.isRequesting(true, updater);
    new Ajax.Updater(updater, url, {
      method : method,
      parameters : params,
      evalScripts : true,
      onComplete : function(request) {
        FILM.afterResponse(request, updater, thisObj);
      }
    });
  },

  /**
   * Callback function, execute after completion the AJAX request
   */
  afterResponse : function(request, updater, thisObj) {
    this.isRequesting(false, updater);
    var response = request.responseText;
    if (response.isJSON()) {
      response = response.evalJSON(true);
      var errors = response['errors'];
      var text = response['text'];
      if (errors == 0) {
        if (thisObj == this.sidebarObj) {
          text = text.evalJSON(true);
          for (key in text) {
            $(key).update(text[key]);
          }
        }
      }
    }
    
    if (!updater && thisObj.updater) {
      updater = thisObj.updater;
    }
    
    
  //  alert(this.commentsContainer.id+'=='+updater.id+'=='+this.videoContainer)
    if (updater && (updater == this.videoContainer)) {
      this.videoContainer.update(text);
      this.afterGetVideos();
    } 

    else if ((updater == this.commentsContainer) ) {
      this.afterGetComments(updater, thisObj);
    }
  },

  isRequesting : function(opt, obj) {
    var loadingEle = this.loadingObj;
    if (opt) {
      loadingEle.show();
      if (obj)
        obj.setOpacity(0.4);
    } else {
      loadingEle.hide();
      if (obj)
        obj.setOpacity(1);
    }
  },

  getObjectByAttributeValue : function(container, attr, value) {
    return container.getElementsBySelector('[' + attr + '="' + value + '"]')[0]
        || null;
  },

  setActive : function(thisObj) {
    var ulObj = thisObj.up('ul');
    var allEle = ulObj.childElements();
    var activeClass = this.activeClass;
    $A(allEle).each(function(obj) {
      $(obj).removeClassName(activeClass);
    });
    $(thisObj.up('li')).addClassName(activeClass);
  },

  getActiveObj : function(container) {
    return container.down('.' + this.activeClass);
  },

  setVideoActiveStatus : function() {
    var video = HistoryManager.getParamValue('video');
    if (video && this.videoContainer.down('ul')) {
      activeVideo = this.getObjectByAttributeValue(this.videoContainer, 'id',
          'vid_'+video);
      this.setActive(activeVideo);
    }
  },

  setContent : function() {
    // set content
    var activeVideoType;
    var activeVideo;
    var isHash = window.location.href;
    if (isHash) {

      var type = HistoryManager.getParamValue('type');
      if (type) {
        activeVideoType = this.videoTypesContainer.down('.' + type);
        this.setActive(activeVideoType);
      }
      // this.setVideoActiveStatus();
    }
  },

  setStoryboardInfoEvent : function() {
    if ($('storyboard')) {
      var mainObj = $('storyboard');
      var previewObj = $(mainObj.down('.preview'));
      if (previewObj) {
        var liEle = $(previewObj.next(0)).getElementsBySelector('li');
        $A(liEle).each(function(obj) {
          obj = $(obj);
          obj.observe('mouseover', function(event) {
            FILM.shotStoryobardInfo(this, true);
          });
          obj.observe('mouseout', function(event) {
            FILM.shotStoryobardInfo(this, false);
          });
        });

        var liObj;
        previewObj.observe('mouseover', function(event) {
          liObj = $(mainObj.down('.active'));
          FILM.shotStoryobardInfo(liObj, true);
        });
        previewObj.observe('mouseout', function(event) {
          FILM.shotStoryobardInfo(this, false);
        });
      }
    }
  },

  shotStoryobardInfo : function(thisObj, opt) {
      var tooltipObj = $($('storyboard').down('.info_wrapper'));// $('storyboard_tooltip');
      if (opt == false) {
        tooltipObj.addClassName(this.hideClass);
      } else {
        var data = $(thisObj.down('span')).innerHTML.evalJSON(true);
        var dataEle = tooltipObj.getElementsByTagName('li');
        var key, labelObj;
        // prepare and write shot data
      $A(dataEle).each(function(obj) {
        obj = $(obj);
        labelObj = $(obj.down('span'));
        key = labelObj.innerHTML.replace(':', '').toLowerCase();
        $(labelObj.next(0)).update(data[key]);
      });
      tooltipObj.setOpacity(0.6);
      // var offset = thisObj.cumulativeOffset();
      tooltipObj.removeClassName(this.hideClass);
      // tooltipObj.setStyle({top: offset[1] + 85 + 'px', left: offset[0] - 90 +
      // 'px'});
    }
  },

  afterUrlUpdate : function(val) {
    FILM.setContent();

    var view = HistoryManager.getParamValue('view', val);
    var video = HistoryManager.getParamValue('video', val);
    if (view == 'video' || (video && (!FILM.videoContainer.down('ul')))) {
      FILM.getVideos();
    } else if (video) {
      FILM.setVideoActiveStatus();
      FILM.getPlayer();
    }

    var page = HistoryManager.getParamValue('page', val);
    if (page) {
      FILM.getComments();
    }
  },

loadSection : function() {
  if (typeof HistoryManager != 'undefined') {
   // if (!window.location.hash) {
  //  }
    HistoryManager.init( {
      onUrlUpdate : FILM.afterUrlUpdate
    });

    var video = HistoryManager.getParamValue('video');
    var type = HistoryManager.getParamValue('type');
    var page = HistoryManager.getParamValue('page');
    if ((!video) && (!type)) {
      this.setContent();
      this.getVideos();
    }
    if (!page) {
      this.getComments();
    }

  }
  this.getSidebarData();
}

};
