if(typeof Surfnet==="undefined") var Surfnet = {};

Surfnet.Frontend = {
  /********************* PAGE DEFINITIONS *********************/
  PAGE_SURFMEDIA_HOME:           Surfnet.PAGE_SURFMEDIA+"index.html",

  PAGE_VIDEO_FRAGMENT :          Surfnet.PAGE_SURFMEDIA+"medialibrary/item.html?id=[[id]]",
  PAGE_PUBLIC_PROFILE :          Surfnet.PAGE_SURFMEDIA+"medialibrary/user/[[id]].html",
  PAGE_PLAYER:                   Surfnet.PAGE_SURFMEDIA+"medialibrary/play.html?id=[[id]]",

  PAGE_SEARCH :                  Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/all.html",
  PAGE_USER_SEARCH :             Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/user/[[id]].html",
  PAGE_USER_COLLECTION_SEARCH :  Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/collections/user/[[id]].html",

  PAGE_SHOW_TAG :                Surfnet.PAGE_SURFMEDIA+"medialibrary/tags/tag/[[tag]].html",
  PAGE_SEARCH_TAGS :             Surfnet.PAGE_SURFMEDIA+"medialibrary/tags/search.html",

  PAGE_COLLECTION :              Surfnet.PAGE_SURFMEDIA+"medialibrary/collection.html?id=[[id]]",

  PAGE_COLLECTIONS_BEST:         Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/collections/best.html",
  PAGE_COLLECTIONS_RECENT:       Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/collections/recent.html",
  PAGE_COLLECTIONS_SEARCH :      Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/collections.html",
  PAGE_USER_ITEMS:               Surfnet.PAGE_SURFMEDIA+"medialibrary/search/results/collections.html",

  PAGE_CHANNELS_SEARCH:          Surfnet.PAGE_SURFMEDIA+"live/search/channels.html",
  PAGE_SUBSCRIBE:                Surfnet.PAGE_SURFMEDIA+"register.html",

  PAGE_COLLECTION_EDIT:          Surfnet.PAGE_MYSURF+"mymedia/collections/collection.html?id=[[id]]",
  PAGE_COLLECTION_EDIT_DETAILS:  Surfnet.PAGE_MYSURF+"mymedia/collections/details.html?id=[[id]]",
  PAGE_COLLECTIONS_ADMIN :       Surfnet.PAGE_MYSURF+"mymedia/collections/index.html",

  PAGE_UPLOAD:                   Surfnet.PAGE_MYSURF+"upload.html",

  PAGE_LOGOUT:                   Surfnet.PAGE_MYSURF+"logout.html",

  PAGE_MYPROFILE:                Surfnet.PAGE_MYSURF+"myprofile/index.html",

  PAGE_MYITEMS_ADMIN:            Surfnet.PAGE_MYSURF+"mymedia/items/index.html",
  PAGE_MIJNVIDEO_FRAGMENT:       Surfnet.PAGE_MYSURF+"mymedia/items/item.html?id=[[id]]",
  PAGE_VIDEO_EDIT:               Surfnet.PAGE_MYSURF+"mymedia/items/item.html?id=[[id]]",
  PAGE_TRANSFER_NEW:             Surfnet.PAGE_MYSURF+"transfer.html",

  /********************* QUERY STRING PARAMETER DEFINITIONS *********************/
  PARAM_VIDEO_ID :               "videoId",
  PARAM_COLLECTION_ID :          "collectionId",
  PARAM_USER_ID :                "personId",

  /********************* MISC. *********************/
  currentSelectedTab : 0,
  currentSelectedTab2 : 0,

  /********************* METHODS *********************/

  /////////////////////// VIDEO METHODS ///////////////////////

  playMediafile : function(videoID, formatID, filename)
  {
    var url = this.PAGE_PLAYER.replace('[[id]]',videoID)+"&format_id="+formatID;

    if (filename!==undefined) url += "&"+filename;
    var popup = window.open(url, 'popup', 'width=500,height=500,location=yes,scrollbars=yes,resizable=yes');
  },

  showVideo : function(videoID)
  {
    window.location.href = this.PAGE_VIDEO_FRAGMENT.replace('[[id]]',videoID);
  },

  editVideo: function(videoID)
  {
    window.location.href = this.PAGE_VIDEO_EDIT.replace('[[id]]',videoID);
  },

  /**
   * Used on /medialibrary/search/results/all and /medialibrary/search/results/user/x.
   * For the former it reloads the entire page, for the later it reloads the /person/videos component.
   */
  searchVideo: function(query, tab)
  {
    var component = $('searchResultsContainer');
    var El = new Element('div').update('<img src=\'/images/spinner.gif\' style=\'display:block; margin:0 auto;\'/>');
    Modalbox.show(El, {title: 'Een moment alsjeblieft.', 
                       width: 300, height: 100, 
                       overlayOpacity: 0.35,
                       slideDownDuration: 0.1, slideUpDuration: 0.1,
                       showClose: false, overlayClose: false});
    if (component)
    {
      var resultbody = $$('.smVideoSearch .smResults')[0];

      Surfnet.Application.Person.videos(resultbody,
      { 
        query: query,
        offset: 0
      });
      Modalbox.hide();
    }
    else
    {
      var url = this.PAGE_SEARCH + "?query=" + encodeURI(query);
      if (tab) url+='&tab='+encodeURI(tab);
      else if (Surfnet.REQUEST['tab']) url+= '&tab='+encodeURI(Surfnet.REQUEST.tab);
      window.location.href = url;
    }
  },

  /////////////////////// REVIEW METHODS ///////////////////////

  updateReviews: function(mediaID)
  {
    var component = $('videoreviewsContainer');
    var url = Surfnet.URLRoot + "/video/" + mediaID + "/reviews";
    new Ajax.Updater(component,url,{evalScripts: false});
  },

  markInappropriateReview : function( reviewID )
  {
    window.location.href = Surfnet.VIPAPP + "/review/"+reviewID+"/mark_inappropriate";
  },

  /////////////////////// TAG METHODS ///////////////////////

  showTag : function( tagName )
  {
    window.location.href= Surfnet.Frontend.PAGE_SHOW_TAG.replace('[[tag]]',encodeURI(tagName));
  },

  showMyTag : function(tagName, personID)
  {
    var component = $('searchResultsContainer');
    if (component)
    {
      var url = Surfnet.URLRoot + "/person/videos?tags=" + encodeURI(tagName) + "&" + Surfnet.Application.Tools.getSID();
      new Ajax.Updater(component, url, {evalScripts: false});
    } else window.location.href = this.PAGE_SEARCH_TAGS + "?tags=" + encodeURI(tagName) + "&" + this.PARAM_USER_ID+'='+personID;
  },

  searchTag : function(query)
  {
    var tagcomponents = $$('.smVideoSearch');
    if (tagcomponents.length>0)
    {
      var component = tagcomponents.shift();
      var url = Surfnet.URLRoot + "/video/search?tags=" + encodeURI(query);

      new Ajax.Updater(component, url, {evalScripts: false});
    } else window.location.href = Surfnet.Frontend.PAGE_SEARCH_TAGS + "?tags=" + encodeURI(query);
  },

  /////////////////////// COLLECTION METHODS ///////////////////////

  showCollection : function( collectionID )
  {
    window.location.href = this.PAGE_COLLECTION.replace('[[id]]', collectionID);
  },

  showCollectionAdmin : function()
  {
    window.location.href = this.PAGE_COLLECTIONS_ADMIN;
  },

  showCollectionTag: function(tagName)
  {
    var collectionID = Surfnet.REQUEST.id;
    if (collectionID)
    {
      var component = $$('.smVideoSearch').shift();
      var url = Surfnet.URLRoot + '/video/search?collection=' + collectionID + '&tags=' + tagName;
      new Ajax.Updater(component, url, {evalScripts: false});
    }
  },

  showRecentCollections : function()
  {
    window.location.href =  this.PAGE_COLLECTIONS_RECENT;
  },

  showPopularCollections : function()
  {
    window.location.href =  this.PAGE_COLLECTIONS_BEST;
  },

  searchCollection: function(query)
  {
    var collectionID = Surfnet.REQUEST.id;
    component = $$('.smVideoSearch').shift();
    var url = Surfnet.URLRoot + "/video/search?query=" + encodeURI(query) + "&collection_id=" + collectionID;

    new Ajax.Updater(component,url,{evalScripts: false});
  },

  collectionNew : function()
  {
    var c = $( "collection-listing" );
    var d = $( "new-collection" );
    if( !c || !d ) return;
    c.style.display = "none";
    d.style.display = "block";
  },

  cancelCollectionNew: function()
  {
    history.back(-1);
  },

  cancelCollectionEdit : function()
  {
    window.history.back(-1);
  },

  cancelCollectionNew : function()
  {
    var c = $( "collection-listing" );
    var d = $( "new-collection" );
    if( !c || !d ) return;
    c.style.display = "block";
    d.style.display = "none";
  },

  editCollectionDetails : function(collectionID)
  {
    window.location.href = this.PAGE_COLLECTION_EDIT_DETAILS.replace('[[id]]',collectionID);

  },

  /////////////////////// CHANNEL METHODS ///////////////////////

  searchChannel: function(query, SID)
  {
    var searchcomponents = $$('.smChannelSearch');
    if (searchcomponents.length>0)
    {
      var component = searchcomponents.shift();
      var url = Surfnet.URLRoot + "/channel/search?query=" + encodeURI(query);
      if (SID)
      {
        url = url + '&' + SID;
      }
      new Ajax.Updater(component, url, {evalScripts: false});
    } else window.location.href = this.PAGE_CHANNELS_SEARCH + "?query=" + encodeURI(query);
  },

  /////////////////////// USER METHODS ///////////////////////

  showUser : function( personID )
  {
    if (personID) window.location.href = this.PAGE_PUBLIC_PROFILE.replace('[[id]]',personID);
  },

  PreviewProfile: function(id)
  {
    return this.showUser(id);
  },

  showPersonCollection: function(collectionID)
  {
    window.location.href = this.PAGE_COLLECTION_EDIT.replace('[[id]]',collectionID);
  },

  showAllPersonMedia : function(personID, orderBy, sortOrder)
  {
    window.location.href = this.PAGE_USER_SEARCH.replace('[[id]]',personID) + '?order=' + orderBy+ '&sort=' + sortOrder;
  },

  showAllPersonCollections : function(personID)
  {
    window.location.href = this.PAGE_USER_COLLECTION_SEARCH.replace('[[id]]',personID); // + '?order=' + orderBy+ '&sort=' + sortOrder;
  },

/////////////////////// TABBING METHODS ///////////////////////

  showTab : function( tabID )
  {
    var tabs = $("video-tabs");
    var tabLen = tabs.childNodes.length;
    var crossBrowserTabs = new Array();

    if( !tabs || this.currentSelectedTab == tabID ) return;

    for( var i=0; i<tabLen; i++ )
    {
      if( tabs.childNodes[ i ].nodeType == 1 )
      // this is a node, not a text element
      crossBrowserTabs.push( tabs.childNodes[ i ] );
    }

    if( crossBrowserTabs.length == 0 ) return;

    crossBrowserTabs[ this.currentSelectedTab ].className = "inactive";

    // -- hide old content
    var contentDiv = $("video-edit-" + (this.currentSelectedTab + 1));
    if( contentDiv ) contentDiv.style.display = "none";

    // -- show new content
    contentDiv = $("video-edit-" + (tabID + 1));
    if( contentDiv ) contentDiv.style.display = "block";

    // -- change the tab
    crossBrowserTabs[ tabID ].className = "active";

    tabs.className = "top tab" + (tabID + 1);
    this.currentSelectedTab = tabID;
  },

  showTab2 : function( tabID )
  {
    var tabs = $("video-tabs-2");
    var tabLen = tabs.childNodes.length;
    var crossBrowserTabs = new Array();

    if( !tabs || this.currentSelectedTab2 == tabID ) return;

    for( var i=0; i<tabLen; i++ )
    {
      if( tabs.childNodes[ i ].nodeType == 1 )
      // this is a node, not a text element
      crossBrowserTabs.push( tabs.childNodes[ i ] );
    }

    if( crossBrowserTabs.length == 0 ) return;

    crossBrowserTabs[ this.currentSelectedTab2 ].className = "inactive";

    // -- hide old content
    var contentDiv = $("similar-edit-" + (this.currentSelectedTab2 + 1));
    if( contentDiv ) contentDiv.style.display = "none";

    // -- show new content
    contentDiv = $("similar-edit-" + (tabID + 1));
    if( contentDiv ) contentDiv.style.display = "block";

    // -- change the tab
    crossBrowserTabs[ tabID ].className = "active";

    tabs.className = "top tab" + (tabID + 1);
    this.currentSelectedTab2 = tabID;
  },
  
  showTabNew: function(link) 
  {
    link = $(link);
    var className = link.classNames().findAll(function(className){ if (className.startsWith('tab-')) return className; });

    $$('div.'+className).each(function(tabContent) {
      tabContent.siblings().each(function(sibling) {
        if (sibling.classNames().any(function(className) { return className.startsWith('tab-'); }) &&
            sibling.classNames().any(function(className){ return (className === "middle");})) sibling.hide();
      });
      tabContent.show();
    });

    link.removeClassName('inactive').addClassName('active');
    link.siblings().each(function(link) { link.removeClassName('active').addClassName('inactive'); });
    $(link.parentNode).classNames().each(function(className) { if (className.startsWith('tab-')) $(link.parentNode).removeClassName(className);});
    $(link.parentNode).addClassName(className);
  },



  /////////////////////// COLLECTION ALPHABET BROWSING ///////////////////////

  addAlphabetEventHandlers: function()
  {
    var collectieBrowse = $( "collectie-browse" );
    if( !collectieBrowse ) return; // -- div doesn't exist

    var listItems = $$("LI");
    var len = listItems.length;

    for( var i=0; i < len; i++ )
    {
      Event.observe(listItems[i],"click",Surfnet.Frontend.letterClicked.bind(this));
    }
  },

  letterClicked: function(e)
  {
    if( Surfnet.Frontend.currentSelectedLetter )
    Surfnet.Frontend.currentSelectedLetter.className = "";

    e.target.className = "selected";
    Surfnet.Frontend.currentSelectedLetter = e.target;

    var component = $$('.smCollectionSearch').shift();
    var url = Surfnet.URLRoot + "/collection/search?name_match=begin&name=" +e.target.title;

    new Ajax.Updater(component,url,{evalScripts: false});
  },

  logout: function()
  {
    Cookie.init({name: 'vip_gui_test', path: '/', domain: 'www.20.test.surfmedia.nl'}); 
    Cookie.erase();
    Surfnet.Frontend.Navigate('logout');
    return true;
  },

  /////////////////////// LOAD DIALOG METHODS ///////////////////////

  hideLoadDialog: function()
  {
    Dialog.closeInfo();
  },

  showLoadDialog: function(text)
  {
    document.body.focus();
    Dialog.info(text, {windowParameters: {className: 'surfnet_waitdialog', width:400, height:200}, showProgress: true});
  },

  /////////////////////// GLOBAL UTILITY METHODS ///////////////////////

  Navigate : function(navLink)
  {
    switch (navLink)
    {
      case "my_media":
        window.location.href = this.PAGE_MYITEMS_ADMIN;
        break;
      case "my_profile":
        window.location.href = this.PAGE_MYPROFILE;
        break;
      case "upload":
        window.location.href = this.PAGE_UPLOAD;
        break;
      case "subscribe":
        window.location.href = this.PAGE_SUBSCRIBE;
        break;
      case "surfmediahome":
        window.location.href = this.PAGE_SURFMEDIA_HOME;
        break;
      case 'login':
        window.location.href = Surfnet.PAGE_LOGIN;
        break;
      case 'logout':
        window.location.href = Surfnet.PAGE_LOGOUT;
        break;
      case 'transfer':
        window.location.href = this.PAGE_TRANSFER_NEW;
        break;
    }
  },

  finishConditionsAccept: function()
  {
    window.location.href = Surfnet.PREV_PAGE;
  },

  showDate : function()
  {
    if($("headerDate"))
    {
      var date = new Date();
      var day = date.getDate();
      var dayName = "";
      var month = date.getMonth();
      var year = date.getUTCFullYear();

      switch(month)
      {
        case  0: month = "januari"; break;
        case  1: month = "februari"; break;
        case  2: month = "maart"; break;
        case  3: month = "april"; break;
        case  4: month = "mei"; break;
        case  5: month = "juni"; break;
        case  6: month = "juli"; break;
        case  7: month = "augustus"; break;
        case  8: month = "september"; break;
        case  9: month = "oktober"; break;
        case 10: month = "november"; break;
        case 11: month = "december"; break;
      }

      switch(date.getDay())
      {
        case 0: dayName = "Zondag"; break;
        case 1: dayName = "Maandag"; break;
        case 2: dayName = "Dinsdag"; break;
        case 3: dayName = "Woensdag"; break;
        case 4: dayName = "Donderdag"; break;
        case 5: dayName = "Vrijdag"; break;
        case 6: dayName = "Zaterdag"; break;
      }
      $("headerDate").innerHTML = dayName +" "+ day +" "+ month +" "+ year;
    }
  },

  fillSearchCounts: function() {
    var tabs = $$('#search-tabs h2');

    $$('.smCount .smValue').each(function(value, index) {
      if (!tabs[index]) return false;
      tabs[index].innerHTML += " ("+value.innerHTML
                                           .replace(/\(\D*(\d+)\D*\)/, "$1")
                                           .strip()+
                               ")";
    });
  }
};

Surfnet.Frontend.Updater = function (container, url, options)
{
  if (container)
  {
    var oldStyle = container.style;
    container.setStyle({
      opacity: 0.5,
      cursor: 'wait'
    });
  }
  new Ajax.Updater(container, url, options);
  if (container)
  {
    container.style = oldStyle;
  }
};

Surfnet.Frontend.advancedSearchMedia = function( parameters )
{
  var component = $('advancedSearchContainer');
  if (!component) { if (window['console']) console.warn('No advancedSearchContainer found!'); return true; }
  
  var url = Surfnet.URLRoot + "/media/advanced_search?"+
              Surfnet.Application.Tools.getSID();
  Surfnet.Application.Tools.redirect(url, component, null, {
                                      onLoading: Surfnet.Application.Tools.showBox,
                                      onComplete: Surfnet.Application.Tools.hideBox,
                                      parameters: parameters,
                                      insertion: Element.update,
                                      evalScripts: true});
};

/**
 * Get a CMS frontend text through Javascript
 */
Surfnet.Frontend.setText = function(elementId, textId)
{
  value = false;
  new Ajax.Request('/gettext', { 
    method: 'get',
    parameters: {id: textId, atkpartial: 1},
    onSuccess: function(transport) {
      if ($(elementId)) {
        $(elementId).update(transport.responseText);
      }
    }
  });
};

Surfnet.Frontend.showFavoriteVideos = function( )
{
  Surfnet.Frontend.showFavorites("video");
  $('showFavoriteVideosLink')     .className = 'selected';
  $('showFavoriteCollectionsLink').className = '';
  $('showFavoriteChannelsLink')   .className = '';
}

Surfnet.Frontend.showFavoriteCollections = function( )
{
  Surfnet.Frontend.showFavorites("collection");
  $('showFavoriteVideosLink')     .className = '';
  $('showFavoriteCollectionsLink').className = 'selected';
  $('showFavoriteChannelsLink')   .className = '';

}

Surfnet.Frontend.showFavoriteChannels = function( )
{
  Surfnet.Frontend.showFavorites("channel");
  $('showFavoriteVideosLink')     .className = '';
  $('showFavoriteCollectionsLink').className = '';
  $('showFavoriteChannelsLink')   .className = 'selected';
}

Surfnet.Frontend.showFavorites = function ( type )
{
  var actionContainer = $('actionsContainer');
  var actionsElement = actionContainer.firstChild;
  while(actionsElement != null && actionsElement.nodeType != 1 && actionsElement.nodeName != "DIV")
  {
    actionsElement = actionsElement.nextSibling;
  }
  var url = Surfnet.URLRoot + "/person/favorites_actions?type=" + type +'&'+Surfnet.Application.Tools.getSID();
  new Ajax.Updater(actionContainer, url, {evalScripts: true});

  var favoritesContainer = $('favoritesContainer');
  var favoritesElement = favoritesContainer.firstChild;

  while(favoritesElement != null && favoritesElement.nodeType != 1 && favoritesElement.nodeName != "DIV")
  {
    favoritesElement = favoritesElement.nextSibling;
  }

  url = Surfnet.URLRoot + "/person/my_favorites?type=" + type+'&'+Surfnet.Application.Tools.getSID();
  new Ajax.Updater(favoritesContainer, url, {evalScripts: true} );
}

document.observe("dom:loaded", function() {
  Surfnet.Frontend.showDate();
  Surfnet.Frontend.addAlphabetEventHandlers ();
});
