var P = {
  activeClass           : 'active',
  isProcessing          : false,
  baseUrl               : null,
  tabObj                : 'tabs',
  filterObj             : 'tab_filters',
  loadingObj            : 'ajax_working',
  tabContentObj         : 'tab_content',
  scrollerContentClass  : 'scrollbar_content',
  scrollerTrackClass    : 'scrollbar_track',
  playerClass           : 'v_player',
  videosContainer       : 'video_data',
  paramVal              : false,
  dataArray             : new Array(),
  buttonsActions        : 'btn_actions',
  hideClass             : 'hide',
  ajaxFormClass         : 'form',
  errorObj              : 'error_box',
  requestError          : 'Errors: Please reload the page and try again',
  categoryObj           : 'sets',
  inviteObj             : 'invite_to_bid',
  inviteObjHandlerClass : 'handler',
  vimeoPlayerUrl : 'http://player.vimeo.com/video/{id}',
  youtubePlayerUrl : 'http://www.youtube.com/v/{id}',
  videosType : new Array('reelclever', 'vimeo', 'youtube'),
  playerObj : 'v_player',
  //noteClass             : 'note',
 // sidebarObj            : 'leftcontent',

  /**
   * initialization method
   */
  init : function()
  {
    this.tabObj = $(this.tabObj);
    this.loadingObj = $(this.loadingObj);
    this.tabContentObj = $(this.tabContentObj);

    // youtube videos required 2 js files to be loaded before
    if(HistoryManager.getParamValue('type') == "youtube")
    {
      document.observe('dom:loaded', function()
      {
          P.initializeMethods();
      });
    }
    else
    {
      P.initializeMethods();
    }

    this.inviteTobid();

    //this.notificationsEffect();
  },


  /**
   * fade notification object after a period
   */
  /*notificationsEffect : function()
  {
    var note = $($(this.sidebarObj).down("."+this.noteClass));//.getElementsByClassName("."+this.noteClass);
    if(note)
    {
      Effect.Fade(note, {duration: 12});
    }
  },*/

  /**
   * set event in invite to bid object (if exists)
   */
  inviteTobid : function()
  {
    if($(this.inviteObj))
    {
      var obj = $(this.inviteObj);
      $(obj.down("."+this.inviteObjHandlerClass)).observe("click", function()
        {
         obj.toggleClassName("show");
        });

    }
  },

  /**
   * initailize all the required methods
   */
  initializeMethods : function()
  {
    HistoryManager.init( { onUrlUpdate : P.afterUrlUpdate });
    this.loadSection();
    this.setButtonsActions();
    this.setForms();
  },

  /**
   * get category element in reelclever videos
   */
  getCategoryObj : function ()
  {
    if($(this.categoryObj))
    return $(this.categoryObj);
  },

  /**
   * set event on category element
   */
  setCategoryEvent : function ()
  {
    var obj = this.getCategoryObj();
    if(obj)
    {
      $(obj).observe("change", function(event)
      {
        event.stop();
        if(this.value)
          HistoryManager.setHash({'view': 'videos', 'set': this.value});
        else
        HistoryManager.setHash({'view': 'videos'});
      });
    }
  },

  /**
   * set buttons actions
   */
  setButtonsActions : function()
  {
    var container;
    if($(this.buttonsActions))
    {
      var buttonEle = $(this.buttonsActions).getElementsByTagName("a");
      $A(buttonEle).each(function(obj){
        obj = $(obj);
        if($(obj.up("span").className))
        {
          container = $(obj.up("span").className);
          $(obj).observe("click", function(event) { event.stop(); P.toggleButtonActionContainer(this, container);});
        }
      });
    }
  },

  toggleButtonActionContainer : function(buttonObj, container)
  {
  // var container = $(buttonObj.up("span").className);
   container.toggleClassName(this.hideClass);
   container.down("form").reset();

    if(!container.hasClassName(this.hideClass))
    {
      this.removeMessage();
      if(container.id == "send_message")
      {
         this.sendMessage(buttonObj);
      }
      else if(container.id == 'add_contact')
      {
        this.addContact(buttonObj);
      }
      container.scrollTo();
    }
  },

  /**
   *  set message reciever field disabled
   */
  sendMessage : function(thisObj)
  {
    receiverEle = $('receiver');
    receiverEle.value = thisObj.rel;
    receiverEle.stopObserving("keypress");
    receiverEle.observe("keypress", function(event)
    {
      event.stop();
      return false;
    });
    receiverEle.disabled = true;
  },

  /**
   * set add contact form
   */
  addContact : function(thisObj)
  {
    $('requested_user').value = thisObj.rel;
  },

  /**
   * set AJAX form events
   */
  setForms : function ()
  {
    var form;
    $$("."+this.ajaxFormClass).each(function(obj)
     {
        form = $(obj);
        form.observe("submit", function (event) {event.stop();P.submit(this);});
     });
    $$('.cancel').each(function(obj) {
      $(obj).observe("click", function(event) {
        event.stop();
        $($(P.buttonsActions).className).addClassName(P.hideClass);
       });
    });
  },
  /**
   * set element active
   */
  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);
  },

  /**
   * callback methos when reelclever videos loaded
   */
  initReelCleverVideo : function()
  {
    this.setCategoryEvent();
    var container = this.getVideosContainer();
    this.setScroller(container);
    this.setPlayer(container);
  },

  /**
   * set custom scroller
   */
  setScroller : function(obj)
  {
    var scrollerContent = $(obj.down("."+this.scrollerContentClass));
    var scrollerTrack = $(obj.down("."+this.scrollerTrackClass));
    var tracks = scrollerTrack.getElementsByTagName("span");
    var scrollbar = new Control.ScrollBar(scrollerContent, scrollerTrack);
    // set top bottom handle
    $(tracks[0]).observe('click',function(event){
      scrollbar.scrollBy(-30);
      event.stop();
    });

    $(tracks[1]).observe('click',function(event){
      scrollbar.scrollBy(30);
      event.stop();
    });

    return scrollbar;
  },

/**
 *  set player for reelclever videos
 */
  setPlayer : function(container, type)
  {
    var activeVideo = $(this.getActiveObj(container).down("a"));
    var playerObj = this.getPlayerObj();
    var iframe = playerObj.down("iframe");

    if(iframe)
      iframe.remove();

    if((!type) || (type == this.videosType[0]))
    {
      this.setEventsForParam(container);
      var video = HistoryManager.getParamValue('video');
      if(video)
      {
        this.setActiveVideo(video, container);
      }

      this.paramVal = true;
      var updater = this.tabContentObj.down("."+this.playerClass);
      this.getData(container, updater);
    }
    else
    {
      if(playerObj.down("div"))
        $(playerObj.down("div")).remove();

      if (!playerObj.down("iframe")) {
        iframe = document.createElement("iframe");
        iframe.width = "640";
        iframe.height = "355";
        playerObj.insert(iframe);
      }

      var playerUrl;
      if(type == this.videosType[1])
        playerUrl = this.vimeoPlayerUrl;
      else if(type == this.videosType[2])
        playerUrl = this.youtubePlayerUrl;

      if(playerUrl)
      {
        iframe.src = playerUrl.replace("{id}", activeVideo.rel);
      }
    }
  },

  /**
   * set actvie video
   */
  setActiveVideo : function(video, container)
  {
    if(!container)
      container =  this.tabContentObj.down("."+this.scrollerContentClass);
    var videoObj = this.getObjectByAttributeValue(container, 'rel', video);
    if(videoObj)
    {
      this.setActive(videoObj);
    }
  },

  /**
   * set Events on anchors elements
   */
  setEventsForParam : function(container)
  {
    var anchors = container.getElementsBySelector("a");
    $A(anchors).each(function(obj)
    {
       $(obj).observe("click", function(){P.paramVal = true;});
    });
  },

  getTabData : function()
  {
     this.getData(this.tabObj);
  },

/**
 * callback method when videos tab loaded
 */
  updateTabData : function(response)
  {
    this.tabContentObj.update(response);

    //var type = HistoryManager.getParamValue('type');
   var type = $(this.getActiveObj(this.getFilterObj()).down("a")).rel;


   // if video play id in query parameter
   var video = HistoryManager.getParamValue('video');
   var activeObj = this.getObjectByAttributeValue(this.getVideosContainer(), 'rel', video);
   if(activeObj)
     this.setActive(activeObj);


    if(type == "vimeo")
    {
      this.initVIMEO();
    }
    else if(type == "youtube")
    {
      this.initYoutube();
    }
    else
    {
      this.initReelCleverVideo();
    }

    this.setEventsForParam(this.getFilterObj());
  },

  /**
   * get videos tab filters data
   */
  getFilterData : function()
  {
    this.getData(this.getFilterObj());
  },

  /**
   * send server request to get the data
   */
  getData : function(container, updater, url)
  {
    var type = HistoryManager.getParamValue('type');
    var video = HistoryManager.getParamValue('video');

    // if not reelclever video play
    if(video && this.getVideosContainer() && (type && type != this.videosType[0]))
    {
      var activeObj = this.getObjectByAttributeValue(this.getVideosContainer(), 'rel', video);
      if(activeObj)
      {
        this.setActive(activeObj);
        this.setPlayer(this.getVideosContainer(), type);
        return;
      }
    }

    var activeObj = this.getActiveObj(container);
    var aObj = activeObj.down("a");
   // var url =
    if(!url)
    {
      url = aObj.href;
    }
    url = this.getURLByHashQstr(url);

    if(!updater)
      updater = '';

    this.sendQuery(updater, url, aObj);
  },

  getURLByHashQstr : function(url)
  {
    if(!url)
    {
      url = window.location.href;
    }
    return url.replace("#", "?");
  },

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

  getFirstActionObj :function(container)
  {
    return container.getElementsBySelector("a")[0];
  },

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

  getFilterObj : function()
  {
    return $(this.filterObj);
  },

  getVideosContainer : function()
  {
    return $(this.videosContainer);
  },

  /*
   * Send AJAX request to server
   */
  sendQuery : function(updater, url, thisObj, params, method)
  {
    // for videos and tab filters
    if(this.paramVal)
    {
      params = '&v=1';
    }

    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)
      {
        P.afterResponse(request, updater, thisObj);
      }
    });
  },

  /**
   *  Callback function, execute after completion the AJAX request
   */
  afterResponse : function(request, updater, thisObj)
  {
    this.isRequesting(false, updater);
    this.paramVal = false;
    var response = request.responseText.evalJSON(true);
    var errors = response['errors'];
    var text = response['text'];
    if(errors == 0)
    {
      if(thisObj.up("ul") == this.tabObj)
      {
        this.updateTabData(text);
      }
      else if(thisObj.up("ul").parentNode == this.getFilterObj())
      {
        this.getVideosContainer().update(text);
        if(thisObj.rel == "vimeo")
        {
          this.initVIMEO();
          //dataArray['vimeo'] = text;
        }
        else if(thisObj.rel == "youtube")
        {
          //alert(request.responseText)
          //loadScript('http://gdata.youtube.com/feeds/api/videos?v=2&alt=json-in-script&q=reelclever&callback=showMyVideos2&max-results=5');
          this.initYoutube();
          //dataArray['youtube'] = text;
        }
        else
        {
          this.initReelCleverVideo();
        }
      }
    }
  },

  getPlayerObj : function ()
  {
    //var container = this.getVideosContainer();
    //return container ? $(container.down("."+this.playerClass)) : null;
    return $(this.playerObj);
  },

  initVIMEO : function()
  {
    //VIMEO.init();
    var container = this.getVideosContainer();
    this.setScroller(container);

    this.setPlayer(container, this.videosType[1]);
  },

  initYoutube : function()
  {
    var container = this.getVideosContainer();
    this.setScroller(container);

    this.setPlayer(container, this.videosType[2]);
    //var keyword = Youtube.getVideoBar().className;
   // loadScript('http://gdata.youtube.com/feeds/api/videos?v=2&alt=json-in-script&q='+keyword+'&callback=showYoutubeVideos');
    //Youtube.init(keyword);
  },



  /**
   *  Show processing text (Loading...)
   */

  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);
    }
  },

  /**
   * get values from URL query string
   * set object active by query string values
   */
  afterUrlUpdate : function(val)
  {
    P.getDataByURL(val);
  },

  /**
   * set element active, by url parameter values
   *  send request when URL change
   */
  getDataByURL : function(hashVal)
  {
    if(!hashVal)
    {
      hashVal = window.location.hash;
    }

    var view = HistoryManager.getParamValue('view', hashVal);
    var type = HistoryManager.getParamValue('type', hashVal);
    var video = HistoryManager.getParamValue('video', hashVal);
    var currentTab;
    var currentFilterObj;
    var filterObj = P.getFilterObj();
    if(view)
    {
      currentTab = P.getObjectByAttributeValue(P.tabObj, 'rel', view);
      currentFilterObj = P.getObjectByAttributeValue(filterObj, 'rel', type);
    }
    else
    {
      currentTab = P.getFirstActionObj(P.tabObj);
      currentFilterObj = P.getFirstActionObj(filterObj);
    }

    P.setActive(currentTab);
    if(type && currentFilterObj)
    {
      P.paramVal = true;
      P.setActive(currentFilterObj);
      P.getData(filterObj);
    }
    else
    {
      updater = '';
      if(video)
      {
        var videoContainer = this.tabContentObj.down("."+this.scrollerContentClass);
        if(videoContainer)
        {
          this.setActiveVideo(video, videoContainer);
          updater = this.tabContentObj.down("."+this.playerClass);
        }
      }

      this.getData(this.tabObj, updater, window.location.href);
    }
  },

  loadSection : function()
  {
    if(!window.location.hash)
    {
      this.getTabData();
    }
  },

  submit : function(form)
  {
    if(form.hasClassName('message_form'))
    {
      form.enable();
    }
    form.request({
      parameters:  Form.serialize(form),
      onLoading:   P.onSubmit(form),
      onFailure:   function(){alert(P.requestError);form.enable();},
      onComplete:  function(request) {P.afterSubmit(request, form);}
    });
  },

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

  afterSubmit : function(request, form)
  {
    this.isRequesting(false, form);
    form.enable();
    var resp = request.responseText.evalJSON(true);
    this.setMessage(resp['text'], form);
    if(resp['errors']==0)
    {
       setTimeout(function()
       {
          P.removeMessage();
          var formContainer = $(form.parentNode.parentNode);
          formContainer.addClassName(P.hideClass);

          if(formContainer.id == 'add_contact')
          {
             if($(P.buttonsActions))
             {
               $(P.buttonsActions).remove();
             }
          }
       } , 3000);
    }
  },

  /** Show error messages
   */
  setMessage : function(message, container)
  {
    this.removeMessage();
    var str = "";
    if(message.isJSON())
    {
      var message = message.evalJSON(true);
      for(key in message)
        {
        str += '<div>'+message[key]+ '</div>';
        }
    }
    else
    {
      str = message;
    }
    str = '<div id="'+this.errorObj+'"><a href="#" onclick="P.removeMessage();return false;">Close</a><div>'+str+'</div></div>';
    Element.insert(container, {top: str});
    $(this.errorObj).scrollTo();
  },

  /** Remove Error messages element
   */
  removeMessage : function()
  {
    if($(this.errorObj))
      $(this.errorObj).remove();
  }


};




/**
 * Script for viemo Videos
 */
/*
var VIMEO = {
  oEmbedCallback : 'VIMEO.embedVideo', // Tell Vimeo what function to call
  oEmbedUrl : 'http://www.vimeo.com/api/oembed.json', // Set up the URL
  loadFirst : true, // Load the first one in automatically?
  oWidth : 640,
  oHeight : 352,
  embedObj : 'vimeo_embed',
  thumbContainer : 'vimeo_thumbs',
  thumbClass :     'vimeo_thumb',

  init : function()
  {
    if ($(this.thumbContainer))
    {
      this.embedObj = $(this.embedObj);
      var links = $(this.thumbContainer).getElementsByClassName(this.thumbClass);
      $A(links).each(function(aObj)
       {
          $(aObj).observe("click", function(event) {
          event.stop();
          P.isRequesting(true, this.embedObj);
          VIMEO.getPlayer(this.href);
        });
      });
      if (this.loadFirst) {
        this.getPlayer(links[0].href);
      }
    }
  },

  getPlayer : function(url) {
    this.loadScript(this.oEmbedUrl + '?url=' + url + '&height=' + this.oHeight
        + '&width=' + this.oWidth + '&callback=' + this.oEmbedCallback);
  },

  embedVideo : function(video) {
    var videoEmbedCode = video.html;
    videoEmbedCode = videoEmbedCode.replace(/height="(\d+)"/,
        'height="' + VIMEO.oHeight + '"');
    P.isRequesting(false, this.embedObj);
    P.getVideosContainer().down("div").update(unescape(videoEmbedCode));
  },

  loadScript : function(url) {
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', url);
    document.getElementsByTagName('head').item(0).appendChild(js);
  }

};

*/

/*
 * Youtube video script
 */
/*var vbar;
var Youtube = {

    keywords : null,
    videoBar : 'videoBar-bar',
    yPlayer :  'y_player',

    init : function(keyword) {
    this.keywords = keyword;
      if (this.getVideoBar())
      {
        window._uds_vbw_donotrepair = true;
        Youtube.LoadVideoBar();
      }
    },

    getVideoBar : function ()
    {
      return $(this.videoBar);
    },

    LoadVideoBar : function() {
      var videoBar;
      var options = {
        largeResultSet : !true,
        horizontal : true,
        string_allDone : ' ',
        autoExecuteList : {
          cycleTime : GSvideoBar.CYCLE_TIME_MEDIUM,
          cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
          executeList : [ Youtube.keywords ]
        }
      };
    //videoBar = new GSvideoBar(document.getElementById("videoBar-bar"),
    //     GSvideoBar.PLAYER_ROOT_FLOATING, options);
      videoBar = new GSvideoBar(document.getElementById("videoBar-bar"),
          $(Youtube.yPlayer), options);

      //videoBar.execute("ytplaylist:t27BGll2adA");


      // arrange for this function to be called during body.onload
      // event processing
      // GSearch.setOnLoadCallback(LoadVideoBar);
    }
  };

function loadVideo(playerUrl, autoplay) {
  swfobject.embedSWF(
      playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
      (autoplay?1:0), 'player', '640', '370', '9.0.0', false,
      false, {allowfullscreen: 'true'});
}

function showYoutubeVideos(data) {

  var feed = data.feed;
  var entries = feed.entry || [];
  var html = ['<ul>'];
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];
    var title = entry.title.$t.substr(0, 20);
    var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    var playerUrl = entries[i].media$group.media$content[0].url;
    html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
              '<img src="',thumbnailUrl, '" width="175" height="100"/><br /><span class="titlec">', title, '...</span>', '</span></li>');
  }
  html.push('</ul>');
  document.getElementById('scrollbar_content').innerHTML = html.join('');
  if (entries.length > 0) {
    loadVideo(entries[0].media$group.media$content[0].url, false);
  }
  var container = P.getVideosContainer();
  P.setScroller(container);
}

function loadScript(url) {
  var js = document.createElement('script');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', url);
  document.getElementsByTagName('head').item(0).appendChild(js);
}*/
