/***************************************************************************
 *  Client Side JS functions and global variables for past shows listing.  *
 *  Requires: ShowList.js, SearchUI.js                                     *
 ***************************************************************************/

// *** Global variables BEGIN ***
 
// client side caching for show entries
var shows_cache = [];

// stores the current query when new one is made (see storeCurrentQuery())
var last_query = null;

// client side chache object for guest names, links and descriptions, key = guest_id
var guests_cache = null;

// client side chache object for subjects titles, key = subject_id
var subjects_cache = null;

//current page displayed
var current_page = 0;

// size of font for content
var text_size = "0";

// the global sort order
var sort_order = "down";

//tab shown when search maximized
var active_search_tab = 0;

// loading icon x-position
var loading_icon_pos;

//current query
var current_query = {};

// search term restricting guest list on guest tab
var guest_restriction = "";

//total size of the result set of db query
var rs_length = 0;

// error object
var error = {};

// references on the guest info, options,... pop up 
var guest_win = null;
var news_win = null;
var options_win = null;
var perma_win = null;

// if true a request is pending and applinks are inactive
var req_pending = false;
			 
// if true the search interface is not mininmized
var display_search = true;

// if true the search interface shows navigation bot
var display_nav = true;

// interval for guest list restriction, set in search init
var restriction_ref = null;

// interval for animating NavBot
var nav_bot_ref = null;

// interval for positioning minimized search
var min_search_ref = null;

// minimized and maxmimized search widths
var search_max = 250;
var search_nav = 110;
var search_min = 35;

// will be set when content is "stetched"
var cont_max = 0;
var cont_nav = 0;
var cont_min = 0;

// *** Global variables END ***

// *** Global objects ***

// used to store dates (for datechooser etc.) until next query is issued
var tmp_searchform = {
                       ftquery: notset,
                       andit: true,
                       whole: false,
                       guestid: notset,
                       startdate: notset,
                       enddate: notset,
                       subject: notset
                     };

// the calendar object for start- and enddate chooser
var startDateChooser = new calendar("tmp_searchform.startdate"); 
var endDateChooser = new calendar("tmp_searchform.enddate"); 

// *** Cropfm Header - will be set when all frames loaded ***
var cropfmHeader = null;

// *** the show listing and Search UI objects ***
var showList = new ShowListing("contentDIV");
var searchUI = new SearchUI("searchDIV");

// *** media egg objects, generate enough for max_page_size ***
for ( me=0; me<max_page_size; me++) {
  eval ( "var real" + me + " = new MediaEgg( 'real" + me + "', top.real_speaker, top.real_disk )" );
  eval ( "var mp3" + me + " = new MediaEgg( 'mp3" + me + "', top.mp3_speaker, top.mp3_disk )" );
}

// *** Past Shows functions ***

function paint()
{  
  //check if error occurded and write out error message
  if (error.has_error) {
  	showList.paintError();
  	return;
  }
  
  var start = page_size*current_page;
  var end = start + page_size;

  if (end > rs_length)
  	end = rs_length;
  	
  var cache_query = checkCache(start, end);
  
  if (cache_query.cached) {
  	//all shows are in the cache
  	showList.paint( start, end, false );
  	searchUI.paint();
  } else {
  	//request missing shows
  	getShows(current_query, cache_query.show_ids.join(","));
  }
  
  // adjust text size to current value
  top.frames["contentFrame"].document.getElementById("contentDIV").style.fontSize = lib_getContentFontSize ();
    
  // mozilla...
  correctTableHeight();
}

function doSearch() {
  // does the serach accroding to form, there should only be one!  

  switch (top.active_search_tab) {
    case 0:
      // do content search, search string must be > 2 characters
      var the_ftquery = top.frames["contentFrame"].document.forms[0].ftquery.value;
      var anditFlag = top.frames["contentFrame"].document.forms[0].anditFlag.checked;
      var wholeFlag = top.frames["contentFrame"].document.forms[0].wholeFlag.checked;
      
      if ( the_ftquery.length < 1 ) {
        alert ( top.no_ftquery_ge );
        return;
      }
      
      if ( lib_hasInvalidChars( the_ftquery ) ) {
        var invalid_alert = "";
        var first_c = true;
        for ( var c=0; c<invalid_chars.length; c++ ) {
          if ( !first_c) 
            invalid_alert += ", ";
          invalid_alert += invalid_chars [ c ].substr ( invalid_chars[c].length-1 );
          first_c = false;
        }
        alert ( top.query_has_invalid_chars_ge + ": " + invalid_alert );
        return;
      }
      
      if ( !lib_isValidSearchString( the_ftquery, anditFlag ) ) {
        if ( anditFlag )
          alert( top.query_too_short_and_ge );
        else 
          alert( top.query_too_short_or_ge );        
        return;
      }
      getContentQueryShows( the_ftquery, anditFlag, wholeFlag );
    break;
    case 1:
      // do guest search
      if ( top.tmp_searchform.guestid != notset )  
        getGuestShows ( tmp_searchform.guestid );
    break;  
    case 2:
      // do chronological list search
      var start_date = top.startDateChooser.prs_date ( tmp_searchform.startdate );
      var end_date = top.endDateChooser.prs_date ( tmp_searchform.enddate );
      if ( !start_date || !end_date )
        return;
       
      if ( start_date.getTime() >= end_date.getTime() ) {
        alert ( top.start_after_end_date_ge );
        return;
      }
      getCronologicalShows(
                            lib_prepareDateForDB ( tmp_searchform.startdate ),
                            lib_prepareDateForDB ( tmp_searchform.enddate ),
                            tmp_searchform.subject
                           );
    break;
  }
}
	
function gotoPage(page) {
  current_page = page;
  paint();
  top.frames["contentFrame"].scroll(0,0);
}

function gotoNextPage() {
  current_page++;
  paint();
  top.frames["contentFrame"].scroll(0,0);
}  

function gotoPrevPage() {
  current_page--;
  paint();
  top.frames["contentFrame"].scroll(0,0);
}  

function maximizeShow(showID) {
  // necessary if called from bullet egg
  if ( top.req_pending )
    return;
  shows_cache[showID].maximized = true;
  if (shows_cache[showID].html != null) {
    paint();
  } else {
    // check cache and get html for all shows on page
    var start = page_size*current_page;
    var end = start + page_size;
    var cache_query = checkHtmlCache(start, end);
    if (!cache_query.cached) {
      // just displaying "loading..." info
      shows_cache[showID].html = top.loading_indicator;
      getHtml(cache_query.show_ids.join(","));
      paint();
    }
  }
}

function minimizeShow(showID) {
  shows_cache[showID].maximized = false;
  paint();
}

function gotoShow(showid) {
  /*** checks wheter show is in cache then jumps to show or displays show single mode ***/
  var show_ind = -1;
  // check cache for show requested and remember index
  for (i=0; i<shows_cache.length; i++) {
    if ( shows_cache[i] && shows_cache[i].showid == showid) {
      show_ind = i;
      break;
    }
  }
  if (show_ind > -1 ) {
    // found in cache!
    var page_start = page_size * current_page;
    var page_end = page_start + page_size;
    
    if (page_start<show_ind && page_end>show_ind) {
      // show is on same page!
      maximizeShow( show_ind );
      top.contentFrame.location.href = "#show" + show_ind;
    } else {
      // not on same page but in cache, go there and maximize
      // make sure ALL shows on dest. page are in cache (page size could have changed!)
      var dest_page = Math.floor(show_ind/page_size);
      var dest_start = dest_page * page_size;
      var dest_end = (dest_start + page_size > rs_length) ? rs_length : dest_start + page_size;
      
      var cache_query = checkCache(dest_start, dest_end);
      if (cache_query.cached) {
        gotoPage( dest_page );
        maximizeShow( show_ind );
        top.contentFrame.location.href = "#show" + show_ind;
      } else {
        getSinglemodeShow( showid );
      }
    }
  } else {
    getSinglemodeShow( showid );
  }    
}

function showNavigation() {
  
  if (!top.display_search)
    return;
    
  top.display_nav = true;
  var search_td = top.contentFrame.document.getElementById('searchDIV');

  search_td.style.width = search_nav + 'px';
  top.contentFrame.document.getElementById('contentDIV').style.width = cont_nav + 'px';
  top.contentFrame.document.getElementById('navBot').style.top = '250px';
  
  searchUI.paint();
  
  if ( nav_bot_ref == null )
    nav_bot_ref = top.setInterval( "top.followNav()", 55);

}


function doFollowMinSearch(doit) {
  if (doit) {
    top.followMinSearch();
    if ( min_search_ref == null ) {
      min_search_ref = top.setInterval( "top.followMinSearch()", 200 );
    }
  } else {
    if ( min_search_ref != null ) {
      clearInterval(min_search_ref);
      min_search_ref = null;
    }
  }
}

function doFollowNav(doit) {
  if (doit) {
    nav_bot_ref = top.setInterval( "top.followNav()", 55);
  } else {
    // nav is still displayed, so don't set ref to null
    clearInterval(nav_bot_ref);
    top.frames["contentFrame"].document.images["bot_engine"].src = icon_location + bot_engine_arr[0];
  }
}

function hideNavigation() {
  top.clearInterval(nav_bot_ref);
  nav_bot_ref = null;
  top.display_nav = false;

  top.frames["contentFrame"].document.getElementById('searchDIV').style.width = search_max + 'px';
  top.frames["contentFrame"].document.getElementById("navBot").style.visibility='hidden';  
  top.frames["contentFrame"].document.getElementById("contentDIV").style.width = cont_min + "px";

  searchUI.paint();
  stretchToWindowSize();
}

function changeOptionSettings( aPagesize, aSortorder, aTextsize ) {

  // check if repaint is necessary
  var do_paint = false;
  if ( page_size != aPagesize || sort_order != aSortorder )
    do_paint = true;

  // set page size
  page_size = parseInt ( aPagesize );

  // -1 so it can be matched to current_page 
  var newNumPages = Math.ceil(rs_length/page_size) - 1;
  if ( newNumPages > -1 && newNumPages < current_page )
    current_page = newNumPages;
  
  if ( sort_order != aSortorder ) 
    lib_reverseShowsCache();
  
  // set the sort_order, not part of query object!
  sort_order = aSortorder;
  
  // set the font size
  text_size = aTextsize;
  top.frames["contentFrame"].document.getElementById("contentDIV").style.fontSize = lib_getContentFontSize();
  // mozilla...
  correctTableHeight();

  if ( do_paint )
    paint();
} 

function toggleSearch() {
  // togles search UI (x button), NS needs the timeout to adjust table width...
  
  display_search = !display_search;
  
  
  if (!display_search) {
    // minimize search
    top.frames["contentFrame"].document.getElementById("navBot").style.visibility='hidden';
    top.contentFrame.document.getElementById('searchDIV').style.width = search_min + 'px'; top.contentFrame.document.getElementById('contentDIV').style.width = cont_max + 'px';
  } else {
    // maximize search or show nav 
    if ( display_nav ) {
      top.frames["contentFrame"].document.getElementById("navBot").style.visibility='visible';
      top.contentFrame.document.getElementById('searchDIV').style.width = search_nav + 'px'; top.contentFrame.document.getElementById('contentDIV').style.width = cont_nav + 'px';
    } else {
      top.frames["contentFrame"].document.getElementById("navBot").style.visibility='hidden';
      top.contentFrame.document.getElementById('searchDIV').style.width = search_max + 'px'; top.contentFrame.document.getElementById('contentDIV').style.width = cont_min + 'px';
    }
  }
  
  searchUI.paint();
}

function changeTab(aTab) {
  active_search_tab = aTab;
  searchUI.paint();
}

function stretchToWindowSize() {
  var window_width = top.lib_docWidth() - 48;
  
  if (window_width < 1000) {
    display_width = window_width;
    cont_max = display_width - 35;
    cont_nav = display_width - 110;
    cont_min = display_width - 250;
    display_width = (display_width <= 790) ? 790 : display_width;
    cont_max = (cont_max <= 755) ? 755: cont_max;
    cont_nav = (cont_nav <= 680) ? 680 : cont_nav;
    cont_min = (cont_min <= 540) ? 540 : cont_min;
  } else {
    display_width = 1000;
    cont_max = 965;
    cont_nav = 890;
    cont_min = 750;
  }
  
  if ( display_search ) {
    if ( display_nav ) {
      top.contentFrame.document.getElementById('contentDIV').style.width = cont_nav + 'px';
      top.contentFrame.document.getElementById('searchDIV').style.width = search_nav + 'px';      
    } else {
      top.contentFrame.document.getElementById('contentDIV').style.width = cont_min + 'px';
      top.contentFrame.document.getElementById('searchDIV').style.width = search_max + 'px';
    }
  } else { 
    top.contentFrame.document.getElementById('contentDIV').style.width = cont_max + 'px';
    top.contentFrame.document.getElementById('searchDIV').style.width = search_min + 'px';
  }

  top.contentFrame.document.getElementById('mainTable').style.width = display_width +'px';
  top.contentFrame.document.getElementById('headerDiv').style.width = display_width +'px';
  
  // place loading icon
  loading_icon_pos = Math.floor ( display_width - display_width* 0.16 );
  top.frames["contentFrame"].document.getElementById("loadingIconContent").style.left = loading_icon_pos + "px";
}

function correctTableHeight() {
  var search_td = top.contentFrame.document.getElementById('searchTd');
  var content_td = top.contentFrame.document.getElementById('contentTd');
  
  var content_height = top.contentFrame.document.getElementById('contentDIV').offsetHeight;
  
  var the_height = (content_height > 550) ? content_height : 550;
  search_td.style.height = the_height;
  content_td.style.height = the_height;
}

function deactivateAppLinks() {
  req_pending = true;
  showList.paint( false, false, true );
  searchUI.paint();
}

function checkCache(start, end) {
  var ret_count = 0;
  var ret_obj = {cached:true,show_ids:[]};
  
  for( var i=start; i<end; i++) {
    if (shows_cache[i] == null) {
      ret_obj.cached = false;
      ret_obj.show_ids[ret_count] = i;
      ret_count++; 
    }
  }
  
  // if subject or guest cache is empty retrieve these (no show entries need to be set!)
  if (subjects_cache == null || guests_cache == null)
  	ret_obj.cached = false;
  	
  return ret_obj;
}

function checkCache(start, end) {
  var ret_count = 0;
  var ret_obj = {cached:true,show_ids:[]};
  for(i=start; i<end; i++) {
    if (shows_cache[i] == null) {
      ret_obj.cached = false;
      ret_obj.show_ids[ret_count] = i;
      ret_count++; 
    }
  }
  
  // if subject or guest cache is empty retrieve these (no show entries need to be set!)
  if (subjects_cache == null || guests_cache == null)
  	ret_obj.cached = false;
  	
  return ret_obj;
}

function checkHtmlCache(start, end) {
  var ret_count = 0;
  var ret_obj = {cached:true,show_ids:[]};
  for(i=start; i<end; i++) {	
    if (shows_cache[i] == null) {
      //** this should not happen ** just do nothing...
      return ret_obj;
    }
    
    if (shows_cache[i].html == null) {
      ret_obj.cached = false;
      ret_obj.show_ids[ret_count] = i;
      ret_count++; 
    }
  }
  return ret_obj;
}

function openNewsWin(aShowid, aCacheid) {

  if ( top.shows_cache && top.shows_cache[aCacheid] ) {
    // didn't want to supply it directly, would need escaping of '"'...
    // jsp can also live without it.
    var title = top.shows_cache[aCacheid].title;
  }

  var news_url = host_name + "/cropfm/jsp/getshownews.jsp?showid=" + aShowid;
  if (title) {
    news_url += "&title=" + title;
  }
  
  if ( top.news_win == null || top.news_win.closed == true ) {
    top.news_win = window.open("about:blank", news_win_obj.name, news_win_obj.properties);
  }

  try {
    // try catch for IE...
    top.news_win.document.open();
    top.news_win.document.write(header_style + loading_res_style + footer);
    top.news_win.document.close();
  } catch (e) {
    // nothing to do...
  }

  news_win.location.href = news_url;

  try {
    // FIXME IE...
    top.news_win.focus();
  } catch (e) {
  }
}


function initContent() {
  top.frames["contentFrame"].document.getElementById("loadingIconContent").style.top = "-120px";
  top.frames["contentFrame"].document.getElementById("loadingImageContent").src = top.icon_location + top.loading_icon;
}

function initSearch() {
  // function is defined in page due to IE (5.0) bug...
  setNavFrame("contentFrame");
  restriction_ref = top.setInterval("top.frames['contentFrame'].restrictGuestList()", 1000);
}

// *** Past Shows functions END ***
