function getSomeXML(url) {
	var xmlDoc;
	xmlDoc=new window.XMLHttpRequest();
	xmlDoc.open("GET",url,false);
	xmlDoc.send("");
	return xmlDoc.responseXML.documentElement;
}

function playvid(file, d, poster) {
	$('#playpause').fadeOut('fast');

	hideDeets();
	$('#movie_details_button').fadeOut('fast');

	var nvid = 
	"<playlist>" +
	"	<item>" +
	"		<filename>"+file+"</filename>" +
	"		<artist></artist>" +
	"		<title></title>" +
  "   <image>"+poster+"</image>" +
	"	</item>" +
	"</playlist>";

	wimpy_clearPlaylist();
	wimpy_appendPlaylist(nvid, true);

	//pop details buttton
	var deets = '<div id="movie_details_button" style="display:none; position:absolute;z-index:5000;bottom:3px; left:166px;">'+
		'<a href="" onclick="showDeets(\''+d+'\'); return false;"><img src="img/details.png" border=0 /></a>' +
	'</div>';
	
	if ( $('#movie_details_button')[0] ) {
		$('#movie_details_button').remove();
		$('#playwrap').append(deets);
	} else
		$('#playwrap').append(deets);
		
	$('#movie_details_button').fadeIn('normal');	
}

function hideDeets() {
	$('#movie_deets').fadeOut('normal', function(){
		wimpy_play();
	});
}

function showMe(t,callback) {
	$('.vid_detail').hide();
	$('#'+t).fadeIn('normal',callback);
}

function showDeets(d) {

	var bigdeet = 	'<div id="movie_deets" style="display:none; position:absolute; top:0; left:151px; z-index:6000; cursor:pointer;" onclick="hideDeets(); return false;">'+
		'<img src="'+d+'" />' +
	'</div>';
	
	if ( $('#movie_deets')[0] )
		$('#movie_deets').remove();
	
	$('#playwrap').append(bigdeet);
	
	wimpy_pause();
		
	$('#movie_deets').fadeIn('normal');
	
}

// BEGIN: Attempt at writing a better more OO video player. On hold for now due to budget constraints.
var VidPlayer = function()
{
  // The videos we're playing.
  this.vids = [];

  // Track state of video player.
  this.isPlaying = false;

  // Track the current video being played.
  this.currVid = 0;
}

$.extend(VidPlayer.prototype,
{
  // Adds a video to the player
  addVid: function(theMovie, theDeets)
  {
    var currIndex = this.vids.length;
    this.vids[currIndex] = { movie: theMovie, deets: theDeets };
    return currIndex;
  },

  // Plays the video at index.
  playVid: function(index)
  {
    if (this.isPlaying)
    {
      this.stopVid();
    }
    
    // Play video at index using wimpy api.
    
    this.currVid = index;
  },

  // Stops the currently playing video.
  stopVid: function()
  {
    // Stop currVid playing using wimpy api.
  },

  // Toggles play of the currently loaded video.
  toggleVid: function()
  {
    if (this.isPlaying)
    {
      this.stopVid();
    }
    else
    {
      this.playVid(this.currVid);
    }
  }
});

// Instantiate a global video player object.
//var videoPlayer = new VidPlayer();

function buildVidControl(autoplay) {
	var doc = getSomeXML("watch.xml");

	var links = '';
	var mains = '';
	var iter = 0;

	$(doc.childNodes).each(function() {
		//build link item for the table
		var vid = $(this);
	
		if ( vid[0].nodeName == 'vid' ) { 

 			if ( iter == 0 ) {
        fmovie = vid.attr('movie');
				fdeet = vid.attr('deets');
        fposter = vid.attr('poster');
 			}

      // Add video to our global video player object.
 		  //var index = videoPlayer.addVid(vid.attr('movie'), vid.attr('deets'));
				
			links +=
			'<td>' +
				'<div class="vidthumb" onclick="playvid(\''+vid.attr('movie')+'\',\''+vid.attr('deets')+'\',\''+vid.attr('poster')+'\')" onmouseover="$(this).addClass(\'vidthumb_hover\'); showMe(\'vid_detail'+iter+'\');" onmouseout="$(this).removeClass(\'vidthumb_hover\')"><span class="count">' +
				(iter + 1) + '</span></div>' + 
			'</td>';
						
			//and build adjoining content element
			mains += 
			'<div id="vid_detail'+iter+'" class="vid_detail" style="display: none;" onclick="">' +
				'<img class="vidimg" src="'+vid.attr('image')+'" />' +
				'<div class="subvid">' +
					'<p class="vidtitle">'+vid.attr('title')+'</p>' +
					'<span class="viddetails">'+vid.attr('details')+'</span>' +	
				'</div>' +
			'</div>';
			iter++;
		}
	});
	
	var vcon = 
		'<div id="vidcontrol">' +
			mains +
			'<div id="thumbwrapper">' +
				'<table>' +
					'<tr>' +
						links + 
					'</tr>' +
				'</table>' +
			'</div>' + 
		'</div>';
		
	$('#bottomgray').append(vcon);
	
	showMe('vid_detail0', function() {
			if ( autoplay ) 
				playvid( fmovie, fdeet, fposter);
	});
}

function showNewContent(responseText, status, response) {
  // Attach behaviors to links that launch new windows
  attachNewWinBehaviors();

  // Contact form AJAX submit and validation.
	$('#contact').submit(function(event)
  {
    // Don't post a submit.
	  event.preventDefault();
			
    // Get the input values.
    var varContactname = $('#contact #contactname').val(),
        varContactemail = $('#contact #contactemail').val(),
        varFulltext = $('#contact #fulltext').val();
    
	  if (!varContactname || varContactname == 'Your Name')
    {
		  $('#response').html('All fields are required');
			return false;
		}
    else if (!varContactemail || varContactemail == 'Your Email' || !varContactemail.toString().match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
    {
		  $('#response').html('A valid email is required');
			return false;				 
		}
    else if (!varFulltext || varFulltext == 'Your Message' )
    {
      $('#response').html('A message is required');
		  return false;
		}

    // Reset the form, clear the error messages.
    this.reset();
    $('#contact input, #contact textarea').css('color', '');
    $('#response').html('');

		$('#response').load('ajax_email.php', {
  		contactname: varContactname,
	  	contactemail: varContactemail,
		  fulltext: varFulltext				
		});
	});

	// On focus behavior for contact form input fields.
	// Also applies to the submit button, but this doesn't create a problem because it is an image button.
	$('#contact input, #contact textarea').focus(function()
	{
	  if (this.style.color == '')
	  {
	    this.style.color = '#000000';
	    this.value = '';
	  }
  });

	$('#maincontent').fadeIn('normal',function() {
		sIFR.replaceAll();
  });
		
	if ( $('.scroll') ) {
		$('.scroll').jScrollPane({
			dragMaxHeight:40,
			scrollbarWidth:8
		});
	}
}

// Attach behaviors to links that launch new windows
function attachNewWinBehaviors()
{
  $("a[rel='_newwin']").click(function()
  {
    window.open(this.href, 'newwin');
    return false;
  });
}

$().ready(function() {

  // Attach behaviors to links that launch new windows
	attachNewWinBehaviors();

  // Mail form AJAX submit and validation.
	$('#mailform').submit(function(event)
  {
    // Don't post a submit.
	  event.preventDefault(); 

    // Get the input values.
	  var varYourname = $('#mailform #yourname').val(),
	      varEmail = $('#mailform #email').val(),
        varZip = $('#mailform #zip').val();

    // Validate and display errors.
		if (!varYourname || varYourname == 'Your Name')
    {
  		$('#mailmessage').html('All fields are required');
	  	return false;
		}
    else if (!varEmail || varEmail == 'Your Email' || !varEmail.toString().match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
    {
		  $('#mailmessage').html('A valid email is required');
		  return false;				 
	  }
    else if (!varZip || varZip == 'Your Zip')
    {
		  $('#mailmessage').html('Zip is required');
		  return false;
		}

    // Reset the form, clear the error messages.
    this.reset();
    $('#mailform input').css('color', '');
    $('#mailmessage').html('');

    // Submit thie mailling list via ajax.
		$('#mailmessage').load('ajax_mailinglist.php',
    {
			yourname:varYourname,
			email:varEmail,
			zip:varZip 
		});
	});

  // On focus behavior for mail form input fields.
  // Also applies to the submit button, but this doesn't create a problem because it is an image button.
	$('#mailform input').focus(function()
  {
    if (this.style.color == '')
    {
      this.style.color = '#000000';
      this.value = '';
    }
  });

  // Check for hash value in URL
	var hash = window.location.hash.substr(1);
	if (!hash)
  {
    // Default to home page.
		hash = 'home';
	}

	// Check to make sure the hash matches one of the nav links.
	$('#nav li a').each(function()
  {
		var href = $(this).attr('href');
		if (hash == href.substr(0, href.length - 5))
    {
        var toLoad = hash + '.html';
      // Load the href that matches.
			$('#maincontent').load(toLoad, {}, showNewContent);
		} 
	});

	$('#nav li a').click(function()
  {
	  var toLoad = $(this).attr('href');
		$('#mailinglist').show();
    $('#mailmessage').html('');
		$('#mailmessage').show();
	  $('#vidcontrol').remove();
	  $('#maincontent').fadeOut('fast',function()
    {
		  $('#maincontent').load(toLoad + '?rnd=' + Math.floor(Math.random()*1000000001), {}, showNewContent);
    });

		window.location.hash = toLoad.substr(0, toLoad.length - 5);

		return false;
	});

});

//wimpy
