// Copyright © 2006 by JammerMedia, Inc., All Rights Reserved.
//
// jmiPlayer.js
//
// $Source: /tmp/cvsrepo/webapps/binder/public/javascripts/jmiPlayer.js,v $
// $Id: jmiPlayer.js,v 1.13 2008-01-21 00:51:02 kens Exp $

// JSON-RPC controller
var jsonurl = webroot + "services/jsonrpc";
var jsonrpc = null;

// Binder object
var bdr = null;
var tabWidth = 200;
var selectedTabWidth = 120;

// Mode
var mode = "play";

// Retrieve the binder
// arguments:
// id - primary db key for binder
// un - user name
//
function loadPlayer(id, rating) {
	try {
		jsonrpc = new JSONRpcClient(jsonurl);
		bdr = new Binder(id, jsonrpc.details.get(id));
	}
	catch (e) {
		alert(e);
	}	

	bdr.setSelectedTab(0);
 	bdr.tabAt(0).setSelectedSubtab(-1);

	bdr.write();
	
	writeTabs();
	writeSubtabs();
	writeLeadIns();
	
	window.onresize = windowResize;
	windowResize(null);
	
	apply_binder_rating(rating);
	setWarning();
}

var warning = false;

function setWarning() {
	warning = true;
	var t = setTimeout("unsetWarning()", 5000);
}

function unsetWarning() {
	warning = false;
}

function myunload(event) {

	if (warning == false)
	  return;

	var text=".\n.\nIf you are not exiting the binder please click 'Cancel'\n.\n.";

	// If IE -- set event returnValue
	//
	if (isIE) {
	  event.returnValue=text;
	  return;
	}

	return text;
}

//
function unloadPlayer() {

}

/* ----------------------------------------------------------------------------------- */

// Write the binder tabs
//
function writeTabs() {

	// Let's figure out how much room we've got and set the tab width
	var parent = $('tabx-0').parentNode
	var width = parent.clientWidth;
	
        var off = parseInt(bdr.tabOffset());
        var tc = bdr.tabCount() - off;
        tc = (tc > MAX_TABS) ? MAX_TABS : tc;

        tabWidth = Math.round(width / tc) + 1;

	// Clamp tabWidth in the 50 to 200 pixel range
	tabWidth = tabWidth > 200 ? 200 : tabWidth;
	tabWidth = tabWidth < 50 ? 50 : tabWidth;

    selectedTabWidth = (tabWidth > selectedTabWidth) ? tabWidth : selectedTabWidth;

	for (var i = 0; i < MAX_TABS; i++) {

		if ((off+i) < bdr.tabCount()) {

            // Toggle used tabs on	
			$('tabx-'+i).style.display = ''; 
			$('tabx-'+i).title = bdr.tabNameAt(off+i);

			if ((off+i) == bdr.getSelectedTab()) {

				// Selected tab format
				if (bdr.tabAt(off+i).getSelectedSubtab() < 0) {
				    // The tab is selected
					$('tabx-'+i).innerHTML = 
						printf(selectedSupTabHTML_d_d_s_d_player, 
						       i, selectedTabWidth,
						       bdr.tabNameClippedAt(off+i), i);
				}
				else {
				    // A subtab of the tab is selected
					$('tabx-'+i).innerHTML = 
						printf(selectedTabHTML_d_d_s, i, i, bdr.tabAt(off+i).getName());
				}				

			    // Set the tab's width based on our calculation above
                var stabwidth = selectedTabWidth;
                var rwidth = 0;

                // If user is moving to the right, we'll have 2
                // selected tabs at same time after we set tabx width below.
                // So get selected tab width prior - by getting tab width
                // to right.
                var rtab = 'tabx-' + parseInt(i + 1);
                if ((off > 0) && $(rtab))
                  rwidth = Math.ceil(getComputedWidth(rtab));

                // Set selected tab width
			    $('tabx-'+i).style.width = selectedTabWidth + 'px';

                // Get computed width - and use rwidth if it's bigger
                stabwidth = Math.ceil(getComputedWidth('tabx-'+i));
                stabwidth = Math.max(rwidth, stabwidth);
                stabwidth = (stabwidth < 50) ? 50 : stabwidth;

                // Set interior span to correct width
			    $('tab-'+i).style.width = stabwidth - 17 + 'px';
			}

			else {

				// Unselected tab format
				$('tabx-'+i).innerHTML =
					printf(unselectedTabHTML_d_d_s, i, i, bdr.tabAt(off+i).getName());
			    // Set the tab's width based on our calculation above
			    $('tabx-'+i).style.width = tabWidth + 'px';
			    $('ustab-'+i).style.width = tabWidth - 17 + 'px';
			}
			
			$('tabx-'+i).className = "spiffy-tab-content-b";
		}

		// Show extra tab as spacer
		else if ((off+i) == bdr.tabCount()) {
			$('tabx-'+i).style.display = ''; 
			var spacer = width - (tc * tabWidth) + 4;
			spacer = (spacer < 10) ? 10 : spacer;
			$('tabx-'+i).style.width = spacer + 'px';
			$('tabx-'+i).innerHTML = '';
		}

		else {
			$('tabx-'+i).style.display = 'none'; // toggle unused tabs off
		}
	}

    // Display tab arrows as necessary
    // var high = (bdr.tabCount() < MAX_TABS) ? 0 : bdr.tabCount() - MAX_TABS;
    var show_arrows = (bdr.tabCount() > MAX_TABS);

    $('play-left').style.display = show_arrows ? "" : "none";
    $('play-right').style.display = show_arrows ? "" : "none";
}

// Write subtabs
//
function writeSubtabs() {
	var tab = bdr.tabAt(bdr.getSelectedTab());
	var subtabs = "";
	
	if (tab.hasSubtabs()) {
		for (var i = 0; i < tab.subtabCount(); i++) {
			if (i == tab.getSelectedSubtab()) {
				var subtab = tab.subtabAt(i);
				if (subtab.getSelectedSubtab() < 0) {
					subtabs += printf(selectedSubtabHTML_d_s_player, i, subtab.getName());
				}
				else {
					subtabs += printf(selectedSupSubtabHTML_d_d_s, i, i, subtab.getName());
				}	
			}
			else {
				subtabs += printf(unselectedSubtabHTML_d_d_s, i, i, tab.subtabAt(i).getName());
			}
			
			if (i < (tab.subtabCount() - 1)) {
				subtabs += "&nbsp;|&nbsp;";
			}
		}
	}
	else {
		subtabs = "<span class='binder-subtab'>&nbsp;</span>";
	}
	
	$('binder-subtab-pane').innerHTML = subtabs;
}

// Write leadins
//
function writeLeadIns() {
	var tab = bdr.tabAt(bdr.getSelectedTab());
	
	if (tab.hasSubtabs()) {
		var selectedSubtab = tab.getSelectedSubtab();
		
		if (selectedSubtab >= 0) {
			var subtab = tab.subtabAt(selectedSubtab);
			var leadins = "";
			
			if (subtab.hasSubtabs()) {
				for (var i = 0; i < subtab.subtabCount(); i++) {
					if (i == subtab.getSelectedSubtab()) {
						leadins += printf(jmi_selectedLeadInHTML_d, parseInt(i)+1);
					}
					else {
						leadins += printf(jmi_unselectedLeadInHTML_d_d, i, parseInt(i)+1);
					}
					if (i < (subtab.subtabCount() - 1)) {
						leadins += "<div class=\'lead-in-padding\'>&nbsp;</div>";
					}					
				}
				$('binder-lead-in').innerHTML = leadins;
			}
			else {
				$('binder-lead-in').innerHTML = "";
			}
		}
		else {
			$('binder-lead-in').innerHTML = "";
		}
	}
	else {
		$('binder-lead-in').innerHTML = "";
	}
}

var _displayCredits = false;

function writeCredits(originalRequest) {

    // var sel = bdr.getSelectedTab();    
    // $('tabx-'+sel).innerHTML = printf(unselectedTabHTML_d_d_s, sel, sel, bdr.tabNameAt(sel));
    //
    // $('binder-subtab-pane').innerHTML = "&nbsp;";
    // $('binder-lead-in').innerHTML = "&nbsp;";

    deselectTabs();
    
    var credits = new Template(eval("({'type':12, 'media':[{'content_type': 'credits'}]})"));
    credits.insert();
    
    _displayCredits = true;    
}

/* ----------------------------------------------------------------------------------- */

// Tab selection
// arguments:
// sel - tab selection
//
function sel_t(sel) {
    var off = parseInt(bdr.tabOffset());
	var prevSel = bdr.getSelectedTab() - off;
	
	// I'm not sure why we need to sync in the player
	if (!_displayCredits) {
	    // bdr.sync();
	}
	_displayCredits = false;
	
	if (sel != prevSel) { 

		// Make previous selection unselected - we pass in tab width as well
        if ((prevSel >= 0) && (prevSel < MAX_TABS)) {
		  $('tabx-'+prevSel).innerHTML = 
			  printf(unselectedTabHTML_d_d_d_s, prevSel, prevSel, 
                     tabWidth-17, bdr.tabNameClippedAt(off+prevSel));
        }

		// Set selected tab - also
		// set width based on calculated tabWidth - bug #172
		bdr.setSelectedTab(off+sel);

		// Lets always go back to first subtab for now
		bdr.tabAt(off+sel).setSelectedSubtab(-1);
		
		// Make current selection selected
		if (bdr.tabAt(off+sel).getSelectedSubtab() < 0) {
			$('tabx-'+sel).innerHTML = 
				printf(selectedSupTabHTML_d_d_s_d_player, sel, selectedTabWidth-17, bdr.tabAt(off+sel).getName(), sel);
		} 
		else {
			$('tabx-'+sel).innerHTML = 
				printf(selectedTabHTML_d_d_s, sel, sel, bdr.tabAt(off+sel).getName());
		}
				
        // Set width based on calculated tabWidth
        if ((prevSel >= 0) && (prevSel < MAX_TABS)) 
          $('tabx-'+prevSel).style.width = tabWidth + 'px';

        $('tabx-'+sel).style.width = selectedTabWidth + 'px';
        var stabwidth = Math.ceil(getComputedWidth('tabx-'+sel));
        $('tab-'+sel).style.width = stabwidth - 17 + 'px';
	}
	else {
		// Supremum
		$('tabx-'+sel).innerHTML = 
			printf(selectedSupTabHTML_d_d_s_d_player, sel, 
			       selectedTabWidth-17, bdr.tabNameClippedAt(off+sel), sel);

		// This indicates a top-level selection
		bdr.tabAt(off+sel).setSelectedSubtab(-1);

		// Set width based on calculated tabWidth
        $('tabx-'+sel).style.width = selectedTabWidth + 'px';
        var stabwidth = Math.ceil(getComputedWidth('tabx-'+sel));
        $('tab-'+sel).style.width = stabwidth - 17 + 'px';
	}

	// Write the tab
	bdr.write();
	
	// Write subtabs
	writeSubtabs();
	writeLeadIns();

	// Get media object
	var midx = 0;
	var mymedia = bdr.getTemplate().media[midx];

	// Open window for url that breaks out of iframe
	// Rating = 1 means that it should open in a new window
	// if (mymedia && mymedia.rating) {
	if (mymedia && mymedia.properties) {

	  var url = mymedia.originating_url;
	  // pop_lb_win(url);
	}
	
	setWarning();
}

// This routine will open the child window for url's that can't be
// contained in a iframe - right now it will just pop the window
// if it's already open - we should probably open it again to load
// the new url
/***
var mywin = null;
function pop_lb_win(url) {

  // If it exists pop it to the top
  if (mywin) {
    mywin.focus();
  }

  // Otherwise - create a new child window - and save it in global mywin
  else {
    if (view == "present") {
	var params = "resizable=yes,scrollbars=yes,statusbar=no,toolbar=no,location=yes,menubar=no";
    }
    else {
	var params = "resizable=yes,scrollbars=yes,statusbar=yes,toolbar=yes,location=yes,menubar=yes";
    }

    var win = window.open(url, "LiveBinder", params);

    if (win) {
      win.focus();
      mywin = win;
    }
  }
}
****/

/* ----------------------------------------------------------------------------------- */

// Subtab selection
// arguments:
// sel - subtab selection
//
function sel_st(sel) {
	var curr = bdr.getSelectedTab();
	var prevSel = bdr.tabAt(curr).getSelectedSubtab();
	
	// bdr.sync();
	
	if (prevSel != sel) {
		bdr.tabAt(curr).setSelectedSubtab(sel);
	}
	else {
		bdr.tabAt(curr).subtabAt(sel).setSelectedSubtab(-1);
	}

	bdr.write();

	writeTabs();
	writeSubtabs();	
	writeLeadIns();
	
	// Get media object
	var midx = 0;
	var mymedia = bdr.getTemplate().media[midx];

	// Open window for url that breaks out of iframe
	// Rating = 1 means that it should open in a new window
	// if (mymedia && mymedia.rating) {
	if (mymedia && mymedia.properties) {

	  var url = mymedia.originating_url;
	  // pop_lb_win(url);
	}

	// Set the values in the tab settings dialog
	// if ($('tsd-subtab'))  
	// $('tsd-subtab').value = bdr.tabAt(curr).subtabAt(sel).getName(); 
	// new Effect.Highlight('tsd-subtab'); 
	// 
	setWarning();
}

/* ----------------------------------------------------------------------------------- */

// Leadin selection
// arguments:
// sel - leadin selection
//
function sel_lit(sel) {
	var curr = bdr.getSelectedTab();
	var subtab = bdr.tabAt(curr).getSelectedSubtab();

	// bdr.sync();
	bdr.tabAt(curr).subtabAt(subtab).setSelectedSubtab(sel);
	bdr.write();
	
	writeSubtabs();
	writeLeadIns();

	setWarning();
}

/* ----------------------------------------------------------------------------------- */

// Handle window resize events
//
function windowResize(e) {    
	var width = document.body.clientWidth - 80;
	if (view == "present") {
		var height = document.body.clientHeight - 100;	// 210;}
	}
	else {
		var height = document.body.clientHeight - 200;	// 210;}
	}
	$('binder-content').style.width = width + 'px';
	$('binder-content').style.height = height + 'px';


	var template = bdr.getTemplate();
	template.resize();

	// Rewrite tabs - to resize them
	writeTabs();
}

function edm() {
}

// Add back in - probably not needed but it's being 
// called on click from media frames
function desel() {
}

function set_tab_offset(n) {

    var mult = 1;
    n *= mult;

    var off = bdr.tabOffset();
    var low = 0;
    var high = (bdr.tabCount() < MAX_TABS) ? 0 : bdr.tabCount() - MAX_TABS;

    off += n;

    off = (off < low) ? low : off;
    off = (off > high) ? high : off;

    bdr.setTabOffset(off);
    writeTabs();

    // If set_tab_offset is getting called - arrows are displayed
    // $('play-left').style.display = ""; // (off == 0) ? "none" : "";
    // $('play-right').style.display = ""; // ((bdr.tabCount() >= MAX_TABS) && (off < high)) ? "" : "none";
}

