
(function($) {

	$.fn.screen = function() {

	   	return this.each(function() {  
  
			var $this = $(this);          
			if ('undefined'==typeof(screen_registry)) {
				screen_registry = new Array;
				screen_index = 0;
			}
			screen_registry.push($this);

			init();
		
			function init() {
				var my_li = document.createElement('li');
				var href = '#'+urlEncode($this.attr('title'));
				if ($this.attr('id')=='Screen_Launch') href = '#';
				my_li.innerHTML = '<a class="hl'+(($this.hasClass('initial_screen'))?' sel':'')+'" href="'+href+'" onclick="changeScreenTo('+(screen_registry.length-1)+');">'+$this.attr('title')+'</a>';
				$('#Screen_Nav').append(my_li);
				if ($this.hasClass('initial_screen')) screen_index = (screen_registry.length-1);
			}	
		
		});

	} // $.fn.texteo

})(jQuery);

// from http://brainerror.net/scripts/javascript/blendtrans
function opacity(id, opacStart, opacEnd, millisec, respHandle) {
    var speed = Math.round(millisec / 100);
    var timer = 0;
    if(opacStart > opacEnd) {
      for(i = opacStart; i >= opacEnd; i--) {
        setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
        timer++;
      }
    } else if(opacStart < opacEnd) {
      for(i = opacStart; i <= opacEnd; i++) {
        setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
        timer++;
      }
    }
    if (respHandle != null) setTimeout("eval(\""+respHandle+"\");", ((timer*2) * speed));
}

// from http://brainerror.net/scripts/javascript/blendtrans
function changeOpac(opacity, id) {
    var object = document.getElementById(id);
    if (object) {
	    object.style.opacity = (opacity / 100);
	    object.style.MozOpacity = (opacity / 100);
	    object.style.KhtmlOpacity = (opacity / 100);
	    object.style.filter = "alpha(opacity=" + opacity + ")";
	}
}

function resetNavOptionsLinks() {
  var theTags = $('navOptions').getElementsByTagName("H1");
  for (var a = 0; a < theTags.length; a++) {
    var anchors = theTags[a].getElementsByTagName("A");
    if (anchors.length == 0) {
      theTags[a].innerHTML = '<a href="javascript:void(null);" onclick="screenTo(this.innerHTML); resetNavOptionsLinks(); this.parentNode.innerHTML=this.innerHTML;">'+theTags[a].innerHTML+'</a>';
    }
  }
}

function setDbVizIframeSrc() {
  var screen_content = $('View_Contents');
  var iframes = screen_content.getElementsByTagName("IFRAME");
  if (iframes.length>0) iframes[0].src = 'http://vectors.usc.edu/visualizer/#/88';
}

function Screen (myWidth) {

  // variables
  this.instance_index = null;
  this.currentViewIndex = 0;
  this.dbVizIndex = null;
  this.isMoving = false;
  this.insertIntoId = null;
  this.width = 0;
  this.backgroundColor = '#000000';
  this.views = new Array;
  this.backgroundImage = null;
  this.minViewHeight = 0;

  // methods
  this.constructor = constructor;
  this.addView = addView;
  this.insertInto = insertInto;
  this.addBackgroundImage = addBackgroundImage;
  this.moveTo = moveTo;
  this.resizeScreen = resizeScreen;
  this.changeScreenHeight = changeScreenHeight;
  this.checkScreenHeight = checkScreenHeight;

  this.constructor(myWidth);

  function constructor(myWidth) {

    this.width = parseInt(myWidth);

    this.instance_index = Screen.instances.length;
    Screen.instances[this.instance_index] = this;

  }

  function addView(viewTitle, viewContent, isDefault) {

    var contents = null;
    var url = null;

    if (typeof(viewContent) != 'object') url = viewContent;

    var newViewIndex = this.views.length;
    this.views[newViewIndex] = new ScreenView(viewTitle, viewContent, url);
    if (isDefault) this.currentViewIndex = newViewIndex;
    if (viewTitle == 'Database Visualization') this.dbVizIndex = newViewIndex;

  }

  function returnAnchor(myStr) {

  }

  function insertInto(divId) {

    var divObj = $(divId);
    if (!divObj) return false;

    // first view

    var viewContents = document.createElement("DIV");
    viewContents.id = 'View_Contents';
	viewContents.style.position = 'absolute';
	viewContents.style.top = '0px';
	viewContents.style.left = '0px';
    viewContents.style.zIndex = 3;
    viewContents.innerHTML = this.views[0].contentObj.innerHTML;

    divObj.appendChild(viewContents);

    this.insertIntoId = divId;

    divObj.style.height = parseInt(viewContents.offsetHeight) + 'px';
    this.minViewHeight = viewContents.offsetHeight;

    // background image

    if (this.backgroundImage != null) {
      var myImg = new Image();
	  myImg.src = this.backgroundImage;
	  myImg.id = 'View_Background_Image';
	  myImg.style.position = 'absolute';
	  myImg.style.top = '0px';
	  myImg.style.left = '0px';
	  myImg.style.zIndex = 2;
	  divObj.appendChild(myImg);
    }

    // navigation bar

    var navOptionsDiv = document.createElement("DIV");
    navOptionsDiv.id = 'navOptions';
    navOptionsDiv.style.zIndex = 4;

    var myOption, iHtml;
    for (var a = 0; a < this.views.length; a++) {

      myOption = null;
      iHtml = '';

      myOption = document.createElement("H1");
      myOption.className = "navOption";

  	  iHtml += '<a id="ViewSelect_'+a+'" '+((a == this.currentViewIndex)?'class="selected"':'')+' href="javascript:Screen.instances['+this.instance_index+'].moveTo('+a+');">';

      iHtml += this.views[a].title;

      if (a != this.defaultViewIndex) {
  	    iHtml += '</a>';
      }

      myOption.innerHTML = iHtml;

      navOptionsDiv.appendChild(myOption);

    }

    divObj.appendChild(navOptionsDiv);

  }

  function addBackgroundImage(url) {

    if (url.length == 0) return false;

	this.backgroundImage = url;

  }

  function moveTo(viewIndex) {

    if (viewIndex == this.currentViewIndex) return;

    // see if the view selected has a url... if so, redirect
    if (this.views[viewIndex].url != null && this.views[viewIndex].url.length > 0) {
      document.location.href = this.views[viewIndex].url;
      return;
    }

    // get info about current screen
    var current_screen = $('View_Contents');

    // get info about upcoming screen
    var next_screen = this.views[viewIndex];

    // special: current screen is DB Vizualizer
    if (this.currentViewIndex == this.dbVizIndex) {
      var iframes = current_screen.getElementsByTagName("IFRAME");
      if (iframes.length>0) iframes[0].src = '';
    }

    // fade out screen, switch content, and fade screen back in
    opacity(current_screen.id, 100, 0, 500, "$('"+current_screen.id+"').innerHTML=$('"+next_screen.contentObj.id+"').innerHTML; "+((viewIndex == this.dbVizIndex)?"setDbVizIframeSrc();":"")+" opacity('"+current_screen.id+"', 0, 100, 500);");

    // TODO: magic numbers starting to appear a lot...
    // There should be math going on here to make ratios, not set heights and values

    // fade background image
    var insertIntoDiv = $(this.insertIntoId);
    if (next_screen.contentObj.id == 'View_Launch') {
      if (insertIntoDiv.offsetHeight > 420) {
        setTimeout("opacity('View_Background_Image', 0, 100, 1100);", (500+(insertIntoDiv.offsetHeight-420)));
      } else {
        opacity('View_Background_Image', 0, 100, 1100);
      }
    } else if (this.currentViewIndex == 0) {
      opacity('View_Background_Image', 100, 0, 700);
    }

    this.currentViewIndex = viewIndex;  // CHANGING CURRENT VIEW INDEX

    // special: insert DB Vizualizer (if applicable)
    // TODO: the .swf is locked in... make this dynamic with a field from the database
    if (this.currentViewIndex == this.dbVizIndex) {

    }

    // special: insert flash video (if applicable)
    if (this.views[this.currentViewIndex].contentObj.id == 'View_VideoTutorial') {
       	 flashembed("VideoTutorialMedia",
		 {
			src:'/common/flash/flowplayer/FlowPlayerLight.swf',
			width: 490,
			height: 369
		 },
		 {config: {
			autoPlay: false,
			autoBuffering: false,
			controlBarBackgroundColor:'0xEEEEEE',
			initialScale: 'scale',
			videoFile: '/projects/uploaded/redl5.flv',
			videoLink: 'http://vectors.usc.edu/projects/index.php?project=93',
			splashImageFile: '/projects/uploaded/redl5_start.jpg',
			embedCode: 'This feature is presently unsupported'
		 }}
	     );
	     //videoFile: 'http://blip.tv/file/get/N8inpasadena-Flowers457.flv'
		//	width: 408,
		//	height: 308
    }

    // move screen height
    var heightFrom = current_screen.offsetHeight;
    var heightTo = (this.currentViewIndex != this.dbVizIndex) ? next_screen.contentObj.offsetHeight : 500;
    if (heightTo < this.minViewHeight) heightTo = this.minViewHeight;
    if (heightTo > 0 && heightTo != current_screen.offsetHeight) {
      this.resizeScreen(heightTo, heightFrom);  // setIframeSource('"+nextScreen.id+"','"+iframeSource+"');
    }

    // special consideration
    if (next_screen.contentObj.id == 'View_Screengrabs') {
      preloadScreengrabImages();
    }

    // reset nav options
    var navOptionsElements = $('navOptions').childNodes;
    for (var a in navOptionsElements) {
      if (typeof(navOptionsElements[a]) != 'object') continue;
      if (navOptionsElements[a].firstChild.id == 'ViewSelect_'+this.currentViewIndex) {
        navOptionsElements[a].firstChild.className = 'selected';
        try {
          navOptionsElements[a].firstChild.blur();
        } catch (e) {}
      } else {
        navOptionsElements[a].firstChild.className = '';
      }
    }

  }

  function resizeScreen(resizeTo, resizeFrom, respHandle) {
        resizeFrom = parseInt(resizeFrom);
		var millisec = (resizeFrom > 0) ? 5000 - (Math.abs(resizeFrom-resizeTo)*2) : 5000; // magic number
		var currentHeight = $(this.insertIntoId).offsetHeight;
	    var speed = Math.round(millisec / 100);
	    var timer = 0;
	    if (currentHeight < resizeTo) {
	      for(i = currentHeight; i <= resizeTo; i= i + 10) {
	        setTimeout("Screen.instances["+this.instance_index+"].changeScreenHeight(" + i + ")",(timer * speed));
	        timer++;
	      }
	    } else {
	      for(i = currentHeight; i >= resizeTo; i = i - 10) {
	        setTimeout("Screen.instances["+this.instance_index+"].changeScreenHeight(" + i + ")",(timer * speed));
	        timer++;
	      }
	    }
	    if (respHandle != null) setTimeout("eval(\""+respHandle+"\");", ((timer*2) * speed));
  }

  function changeScreenHeight(myHeight) {
    $(this.insertIntoId).style.height = myHeight + 'px';
  }

  function checkScreenHeight() {

	// this function checks if the initial screen height has been rendered properly
	// ... Firefox sometimes doesn't give the screen enough height onload

    var screen_div = $(this.insertIntoId);
    var screen_div_height = screen_div.offsetHeight;
    var navOptions_div = $('navOptions');  // Hard-coding
    var navOptions_div_height = navOptions_div.offsetHeight + 20;  // Magic number
    var view_height = this.views[0].contentObj.offsetHeight;

    if (screen_div_height > 0 && view_height > 0 && screen_div_height < view_height) {
      //alert(screen_div_height + ' '+view_height);
      //this.resizeScreen(view_height, screen_div_height);
      screen_div.style.height = view_height + 'px';
      // also set the default hight
      this.minViewHeight = view_height;
    }

    var screen_div_height = screen_div.offsetHeight;
    if (navOptions_div_height > screen_div_height) {
      screen_div.style.height = navOptions_div_height + 'px';
      // also set the default hight
      this.minViewHeight = view_height;
    }

  }

} // Screen

function ScreenView(viewTitle, contentObj, url) {

  this.title = '';
  this.contentObj = null;
  this.url = '';  // 'url' takes precidence over 'contents'

  this.constructor = constructor;

  this.constructor(viewTitle, contentObj, url);

  function constructor(viewTitle, contentObj, url) {

    this.title = viewTitle;
    this.contentObj = contentObj;
    this.url = url;

  }

} // ScreenView

Screen.instances = [];
