var TVS_videos = null;
var TVS_channels = null;
var TVS_categories = null;
var TVS_shows = null;
var TVS_music = null;
var TVS_movies = null;
var TVS_cel = null;
var TVS_sports = null;
var TVS_celebrities = null;

var search_str = '';
var change_search_title = 'yes';

if (typeof HTMLElement != 'undefined' && !HTMLElement.prototype.click)
	{
		HTMLElement.prototype.click=function()
			{
				var evt = this.ownerDocument.createEvent('MouseEvents');
				evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
				this.dispatchEvent(evt);
			}			
	}
	
function SiteTitle(title)
	{ document.title = title; }

	
String.prototype.ucFirst = function () 
	{
 		return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
	};
	
Array.prototype.in_array_minus = function(search_term) 
	{
	  var i = this.length;
	  if (i > 0) 
			{
		 		do 
					{
						if (this[i] === search_term) 
							{ return true; }
	 				} 
				while (i--);
  		}
  	return false;
	};

function SetCookie(cookieName, cookieValue, nDays)
	{
		var today = new Date();
		var expire = new Date();
 		if (nDays == null || nDays == 0) 
			{ nDays = 1; }
		
 		expire.setTime(today.getTime() + 3600000 * 24 * nDays);
		
 		document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
	}
	
	
function isArray(obj)
	{
		if (obj.constructor.toString().indexOf('Array') == -1)
			{ return false; }
		else
			{ return true; }
	}

function addTo(obj, selectName, _selected)
	{
		var sn = ""+selectName;
		var _select = document.getElementById(sn);
		if (_select != null)
			{
				 var el;
			    while (_select.hasChildNodes(  ))
						{
			        for (var i = 0; i < _select.childNodes.length; i++)
								{
			            _select.removeChild(_select.firstChild);
			        	}
			    	}
					
					if ( isArray(obj) == false )
						{ obj = obj.split(','); }
					
					var _selectedIndex = 1;
					
					
			    for (var i = 0; i < obj.length + 0; i++)
						{
							var inv_obj = obj[i];

							var v_n = inv_obj.split(':');
							
							var obj_name = v_n[0].replace('#', ':');
											
							var obj_value = v_n[1];
							
			        el = document.createElement("option");
			        el.appendChild(document.createTextNode(obj_name));
			        _select.insertBefore(el,_select.firstChild);
							el.value = obj_value;
							
							if ( (obj_value == 'all') && (_selected == '') )
								{ 
									el.selected = true;
								}
							else if (_selected == obj_value)
								{
									_selectedIndex = i + 1;
								}
							else
							  {
									el.selected = false;
								}
			    	}
					
					if (_selectedIndex != '1')
						{
							_select.selectedIndex = obj.length - _selectedIndex;
						}
					else
						{
							_select.selectedIndex = 1;
						}
					
					return;
			}
		else
			{ return; }
	}

function loadVideoPage(str)
	{
		initVideos('videoContent', str, '0');
	}
	
	
function initTab(type)
	{
		var title = '';
		switch (type)
			{
				case 'search':
					{ 
						title = "Entertainment, Movies, Music, Sports, News, We've Got It";
						initVideos('videoContent', '', '0');
						break;
					}
				case 'categories':
					{
						title = "Top Videos Right Now";
						initCategories('tab_categories', 'categories', '');
						setTimeout('initVideos("videoContent", "", "0")', 1000);
						break;
					}
				case 'channels':
					{
						title = "Find Videos From Around The Web";
						initChannels('tab_channels', 'channels', '');
						break;
					}
				case 'shows':
					{
						title = "Find Videos From Around The Web";
						initShows('tab_shows', 'shows', '');
						break;
					}
				case 'celebrities':
					{
						title = "The Latest Videos in Entertainment";
						initCelebrities('tab_celebrities');
						//setTimeout('initVideos("videoContent", "category: Entertainment", "0")', 1000);
						break;
					}
				case 'music':
					{
						title = "Popular Music Videos";
						initMusic('tab_music');
						setTimeout('initVideos("videoContent", "category: Music", 1)', 1000);
						break;
					}
				case 'hot_topics':
					{
						title = "Hot Topics in Video";
						initHotTopics('tab_topics');
						setTimeout('initVideos("videoContent", "category: Movies", "0")', 1000);
						break;
					}
				case 'movies':
					{
						title = "Popular Movie Videos";
						initMovies('tab_movies');
						//setTimeout('initVideos("videoContent", "category: Movies", "0")', 1000);
						break;
					}
				case 'sports':
					{
						title = "The Latest Sport Videos";
						initSports('tab_sports');
						setTimeout('initVideos("videoContent", "category: Sports", "0")', 1000);
						break;
					}
			}
		
		
		if (change_search_title == 'yes')
			{
				$('title_video').update(title);
			}
	}
	
function initVideos(obj, str, page)
	{ 
		SiteTitle('Video Aggregator');
		
		TVS_videos = new TruveoVideoSearch(key);
		TVS_videos.showRelatedItems = 1;
		TVS_videos.showAdult = 1;
		TVS_videos.results = 50;
		var from = '';
		var to = '';
		if (page == 1)
			{
				from = 1;
				to = 50;
			}
		else if (page > 1)
			{
				from = 50 * page + 1;
				to = from + 50;
			}
		
		TVS_videos.attachEvent('onload', 'loadContent("' + str + '", "videos", "' + from + '", "' + to + '");');
		TVS_videos.attachEvent('onupdate', 'displayVideos("' + str + '", "' + obj + '", ' + page + ');');
		TVS_videos.initialize();
	}

function initRelatedVideos(obj, str)
	{
		TVS_videos = new TruveoVideoSearch(key);
		TVS_videos.showRelatedItems = 1;
		TVS_videos.showAdult = 1;
		TVS_videos.attachEvent('onload', 'loadContent("category:' + str + '", "videos", "", "");');
		TVS_videos.attachEvent('onupdate', 'displayRelatedVideos("' + str + '", "' + obj + '");');
		TVS_videos.initialize();
	}
	
function initChannels(obj, type, str)
	{
		TVS_channels = new TruveoVideoSearch(key);
		TVS_channels.showRelatedItems = 1;
		TVS_channels.showAdult = 1;
		TVS_channels.attachEvent('onload', 'loadContent("", "channels", "", "");');
		TVS_channels.attachEvent('onupdate', 'displayChannels("' + obj + '", "' + type + '", "' + str + '");');
		TVS_channels.initialize();
	}
	
function initCategories(obj, type, str)
	{
		TVS_categories = new TruveoVideoSearch(key);
		TVS_categories.showRelatedItems = 1;
		TVS_categories.showAdult = 1;
		TVS_categories.attachEvent('onload', 'loadContent("", "categories", "", "");');
		TVS_categories.attachEvent('onupdate', 'displayCategories("' + obj + '", "' + type + '", "' + str + '");');
		TVS_categories.initialize();
	}
	
function initShows(obj, type, str)
	{
		TVS_shows = new TruveoVideoSearch(key);
		TVS_shows.showRelatedItems = 1;
		TVS_shows.showAdult = 1;
		TVS_shows.results = 30;
		TVS_shows.attachEvent('onload', 'loadContent("", "shows", "", "");');
		TVS_shows.attachEvent('onupdate', 'displayShows("' + obj + '", "' + type + '", "' + str + '");');
		TVS_shows.initialize();
	}
	
function initCelebrities(obj)
	{
		TVS_celebrities = new TruveoVideoSearch(key);
		TVS_celebrities.showRelatedItems = 1;
		TVS_celebrities.showAdult = 1;
		TVS_celebrities.results = 50;
		TVS_celebrities.attachEvent('onload', 'loadContent("", "celebrities", "", "");');
		TVS_celebrities.attachEvent('onupdate', 'displayCelebrities("' + obj + '");');
		TVS_celebrities.initialize();
	}
	
function initMusic(obj)
	{
		TVS_music = new TruveoVideoSearch(key);
		TVS_music.showRelatedItems = 1;
		TVS_music.showAdult = 1;
		TVS_music.results = 50;
		TVS_music.attachEvent('onload', 'loadContent("", "videos", "", "");');
		TVS_music.attachEvent('onupdate', 'displayMusic("' + obj + '");');
		TVS_music.initialize();
	}
	
function initHotTopics(obj)
	{
		
	}
	
function initSports(obj)
	{
		TVS_sports = new TruveoVideoSearch(key);
		TVS_sports.showRelatedItems = 1;
		TVS_sports.showAdult = 1;
		TVS_sports.results = 50;
		TVS_sports.attachEvent('onload', 'loadContent("", "videos", "", "");');
		TVS_sports.attachEvent('onupdate', 'displayMusic("' + obj + '");');
		TVS_sports.initialize();
	}
	
function initMovies(obj)
	{
		TVS_movies = new TruveoVideoSearch(key);
		TVS_movies.showRelatedItems = 1;
		TVS_movies.showAdult = 1;
		TVS_movies.results = 50;
		TVS_movies.attachEvent('onload', 'loadContent("", "videos", "", "");');
		TVS_movies.attachEvent('onupdate', 'displayMovies("' + obj + '");');
		TVS_movies.initialize();
	}
	
function loadContent(str, type, from, to)
	{
		if (type == 'videos')
			{
				TVS_videos.getVideos(str, from, to);
			}
		else if (type == 'channels')
			{
				TVS_channels.getRelatedChannels(str, 0, 50);
			}
		else if (type == 'categories')
			{
				TVS_categories.getRelatedCategories(str, 0, 50);
			}
		else if (type == 'shows')
			{
				TVS_shows.getVideos(str, 0, 50);
			}
		else if (type == 'celebrities')
			{
				TVS_celebrities.getVideos(str, from, to);
			}
	}

function displayVideos(videoId, obj, page)
	{
		var theHTML = '';
		
		try
			{
				for (var i = 0; i < TVS_videos.VideoSet.totalResultsReturned; i++)//TVS_videos.VideoSet.Video[i].id
					{
						theHTML += "<div style='float: left; width: 130px; height: 180px; border: 0px solid red;'>";
						theHTML += "	<div> <a href='Video,item," + TVS_videos.VideoSet.Video[i].id + ".html'><img border='0' width='96' height='72' src='" + TVS_videos.VideoSet.Video[i].thumbnailUrl + "'></a></div>";
						theHTML += "	<div style='font-size: 12px; font-weight: bold; color: blue;'> <a href='Video,item," + TVS_videos.VideoSet.Video[i].id + ".html' style='text-decoration: none;'>" + TVS_videos.VideoSet.Video[i].title + "</a> </div>";
						theHTML += "	<div style='font-size: 12px;'> " + TVS_videos.VideoSet.Video[i].channel + "</div>";
						theHTML += "</div>";
					}
				$(obj).update(theHTML);
			}		
		catch(err) {}
		
	}
	
function generatePagination(total_numbers, per_page, page, obj, str)//initVideos
	{
		var nr_letters = 10;
		var backwords_page = page != '1' ? page - 1 : page;
		var forward_page = page != total_letters ? page + 1 : page;
		var HTML = '';
		
		var total_letters = Math.ceil(total_numbers / per_page);
		
		if ( ( total_letters != '1') && ( total_letters != '') )
			{
				HTML += "<a class='pagin' href=\"javascript: initVideos('" + obj + "', '" + str + "', '" + total_numbers + "')\"><span> << </span></a>";
				HTML += "<a class='pagin' href=\"javascript: initVideos('" + obj + "', '" + str + "', '" + backwords_page + "')\"> <span> previous </span> </a>";
			}
		var at = 1;
		var total = 1;
		
		if (total_letters >= nr_letters)
			{
				at = total_letters - nr_letters + 1 <= page ? total_letters - nr_letters + 1 : page;
				
				total = page == "1" ? nr_letters : total_letters > nr_letters ? (page + nr_letters - 1 ) : total_letters;
			}
		else
			{
				at = 1;
				total = total_letters;
			}
		
		if (total > total_letters)
			{
				total = total_letters;
			}
			
		if ( ( total_letters != '1') && ( total_letters != '') )
			{
				var pag_class = '';
				
				for (var i = at; i <= total; i++)
					{
						if (i == page)
							{
								pag_class = 'btn_pag_pressed';
							} 
						else 
							{
								pag_class = 'btn_pag_not_pressed';
							}
						
						HTML += "<a class='" + pag_class + "'";
						HTML += "href=\"javascript: initVideos('" + obj + "', '" + str + "', '" + i + "')\">";
						HTML += i + "</a>&nbsp;";
			    }
			}
		
		if ( ( total_letters != '1') && ( total_letters != '') )
			{
				HTML += '<a class="pagin" href=\'javascript: initVideos("' + obj + '", "' + str + '", "' + forward_page + '")\'><span> next</span></a>';
				HTML += '<a class="pagin" href=\'javascript: initVideos("' + obj + '", "' + str + '", "' + total_letters + '")\'> <span> >> </span> </a>';
 			}
		
		return HTML;
	}
	
function displayRelatedVideos(str, obj)
	{
		try
			{
				if ($(obj))
					{
						var theHTML = '<br>';
				
						for (var i = 0; i < TVS_videos.VideoSet.totalResultsReturned; i++)//aici
							{
								theHTML += "<div style='float: left; width: 130px; height: 180px; border: 0px solid red;'>";
								theHTML += "	<div> <a href='Video,item," + TVS_videos.VideoSet.Video[i].id + ".html'><img border='0' width='96' height='72' src='" + TVS_videos.VideoSet.Video[i].thumbnailUrl + "'></a></div>";
								theHTML += "	<div style='font-size: 12px; font-weight: bold; color: blue;'> <a style='text-decoration: none;' href='Video,item," + TVS_videos.VideoSet.Video[i].id + ".html'>" + TVS_videos.VideoSet.Video[i].title + "</a> </div>";
								theHTML += "	<div style='font-size: 12px;'> " + TVS_videos.VideoSet.Video[i].channel + "</div>";
								theHTML += "</div>";
							}
						
						$(obj).update(theHTML);
					}
			}
		catch(err) {}
	}

function displayChannels(obj, type, str)
	{
		try
			{
				var theHTML = '';
				var all = 'All:All,';
				var channels = new Array();
				var val = '';
				
				//TVS_channels.ChannelSet.Channel.sort();
				
				for (var i = 0; i < TVS_channels.ChannelSet.totalResultsReturned; i++)
					{
						val = TVS_channels.ChannelSet.Channel[i].name;
						channels[i] = val.ucFirst();
					}
				
				channels.sort();
				
				if (type == 'search')
					{
						for (var i = channels.length - 1; i >= 0; i--)
							{
								theHTML += channels[i]+ ':' + channels[i] + ',';
							}
						
						//str = str.split(':');	
						addTo(theHTML + all, obj, str);
					}
				else if (type == 'channels')
					{
						var tr0 = '<tr>';
						var tr1 = '</tr>';
						var per_line = 4;
						
						var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
						var td1 = '</td>';
						
						theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
						var j = 0;
						
						
						for (var i = 0; i < channels.length; i++)
							{
								var chan1 = channels[i].replace(/&/g, 'and');
								var chan = chan1.replace(/ /g, '+');
								
								theHTML += td0 + '<span style="font-size: 12px;"><a href="Video,Channel,' + chan + '.html">' + channels[i] + '</a></span>' + td1;
								j++;
								if (j % per_line == 0)
									{ 
										theHTML += tr1;
										theHTML += tr0;
										j = 0; 
									}
							}
						
						theHTML += '</table>';
						
						$(obj).update(theHTML);
					}
			}
		catch(err) {}
	}
	
function displayCategories(obj, type, str)
	{
		try
			{
				var theHTML = '';
				var all = 'All:All,';
				var categories = new Array();
				var val = '';
				
				//TVS_channels.ChannelSet.Channel.sort();
				
				for (var i = 0; i < TVS_categories.CategorySet.totalResultsReturned; i++)
					{
						val = TVS_categories.CategorySet.Category[i].name;
						categories[i] = val.ucFirst();
					}
				
				categories.sort();
				
				if (type == 'search')
					{
						for (var i = categories.length - 1; i >= 0; i--)
							{
								theHTML += categories[i]+ ':' + categories[i] + ',';
							}
						
						addTo(theHTML + all, obj, str);
					}
				else if (type == 'categories')
					{
						var tr0 = '<tr>';
						var tr1 = '</tr>';
						var per_line = 4;
						
						var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
						var td1 = '</td>';
						
						theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
						var j = 0;
						
						
						for (var i = 0; i < categories.length; i++)
							{
								var categ1 = categories[i].replace(/&/g, 'and');
								var categ = categ1.replace(/ /g, '+');
								
								theHTML += td0 + '<span style="font-size: 12px;"><a href="Video,Search,+,Category,' + categ + '.html">' + categories[i] + '</a></span>' + td1;
								j++;
								if (j % per_line == 0)
									{ 
										theHTML += tr1;
										theHTML += tr0;
										j = 0; 
									}
							}
						
						theHTML += '</table>';
						
						$(obj).update(theHTML);
					}
			}
		catch(err) {}
	}
	
function displayShows(obj, type, str)
	{
		try
			{
				var theHTML = '';
				var all = 'All:All,';
				var shows = new Array();
				var val = '';
				
				var k = 0;
				for (var i = 0; i < TVS_shows.VideoSet.totalResultsReturned; i++)
					{
						val = TVS_shows.VideoSet.Video[i].showName;
						if (TVS_shows.VideoSet.Video[i].showName != undefined)
							{
								if (!shows.in_array_minus(val))
									{
										shows[k] = val.ucFirst();
										k++;
									}
							}
						val = '';
					}
				
				shows.sort();
				
				if (type == 'search')
					{
						for (var i = shows.length - 1; i >= 0; i--)
							{
								theHTML += shows[i]+ ':' + shows[i] + ',';
							}
						
						
						addTo(theHTML + all, obj, str);
					}
				else if (type == 'shows')
					{
						var tr0 = '<tr>';
						var tr1 = '</tr>';
						var per_line = 4;
						
						var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
						var td1 = '</td>';
						
						theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
						var j = 0;
						
						
						for (var i = 0; i < shows.length; i++)
							{
								var show1 = shows[i].replace(/&/g, 'and');
								var _show = show1.replace(/ /g, '+');
								
								theHTML += td0 + '<span style="font-size: 12px;"><a href="Video,Show,' + _show + '.html">' + shows[i] + '</a></span>' + td1;
								j++;
								if (j % per_line == 0)
									{ 
										theHTML += tr1;
										theHTML += tr0;
										j = 0; 
									}
							}
						
						theHTML += '</table>';
						
						$(obj).update(theHTML);
					}
			}
		catch(err) {}
	}
	
function displayCelebrities(obj)
	{
		try
			{
				var theHTML = '';
				var celebr = new Array();
				var val = '';
				
				var k = 0;
				if (TVS_celebrities.VideoSet.totalResultsReturned != null)
					{
						for (var i = 0; i < TVS_celebrities.VideoSet.totalResultsReturned; i++)
							{
								val = TVS_celebrities.VideoSet.Video[i].actor;
								
								if (TVS_celebrities.VideoSet.Video[i].actor != undefined)
									{
										if (!celebr.in_array_minus(val))
											{
												celebr[k] = val.ucFirst();
												k++;
											}
									}
								val = '';
							}
						
						celebr.sort();
						
						var tr0 = '<tr>';
						var tr1 = '</tr>';
						var per_line = 4;
						
						var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
						var td1 = '</td>';
						
						theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
						var j = 0;
						
						for (var i = 0; i < celebr.length; i++)
							{
								theHTML += td0 + '<span style="font-size: 12px;"><a href="javascript: void(0)" onclick=\'javascript: loadVideosFromCelebrities("' + celebr[i] + '")\'>' + celebr[i] + '</a></span>' + td1;
								j++;
								if (j % per_line == 0)
									{ 
										theHTML += tr1;
										theHTML += tr0;
										j = 0; 
									}
							}
						
						theHTML += '</table>';
						
						//$(obj).update(theHTML);
					}
			}
		catch(err) { };
	}
	
function displayMusic(obj)
	{
		try
			{
				var theHTML = '';
				var music = new Array();
				var val = '';
				
				var k = 0;
				
				for (var i = 0; i < TVS_music.VideoSet.totalResultsReturned; i++)
					{
						val = TVS_music.VideoSet.Video[i].artist;
						
						if (TVS_music.VideoSet.Video[i].artist != undefined)
							{
								if (!celebr.in_array_minus(val))
									{
										music[k] = val.ucFirst();
										k++;
									}
							}
						val = '';
					}
				
				music.sort();
				
				var tr0 = '<tr>';
				var tr1 = '</tr>';
				var per_line = 4;
				
				var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
				var td1 = '</td>';
				
				theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
				var j = 0;
				
				
				for (var i = 0; i < music.length; i++)
					{
						theHTML += td0 + '<span style="font-size: 12px;"><a href="javascript: void(0)" onclick=\'javascript: loadVideosFromMusic("' + music[i] + '")\'>' + music[i] + '</a></span>' + td1;
						j++;
						if (j % per_line == 0)
							{ 
								theHTML += tr1;
								theHTML += tr0;
								j = 0; 
							}
					}
				
				theHTML += '</table>';
				
				$(obj).update(theHTML);
			}
		catch(err) {}
	}
	
function displayMovies(obj)
	{
		try
			{
				var theHTML = '';
				var movies = new Array();
				var val = '';
				
				var k = 0;
				
				for (var i = 0; i < TVS_movies.VideoSet.totalResultsReturned; i++)
					{
						val = TVS_movies.VideoSet.Video[i].showName;
						
						if (TVS_movies.VideoSet.Video[i].showName != undefined)
							{
								if (!movies.in_array_minus(val))
									{
										movies[k] = val.ucFirst();
										k++;
									}
							}
						val = '';
					}
				
				movies.sort();
				
				var tr0 = '<tr>';
				var tr1 = '</tr>';
				var per_line = 4;
				
				var td0 = '<td valign="top" align="left" width="200" style="padding: 1px">';
				var td1 = '</td>';
				
				theHTML = '<table border="0" cellpadding="3" cellspacing="3" align="center">' + tr0;
				var j = 0;
				
				
				for (var i = 0; i < movies.length; i++)
					{
						theHTML += td0 + '<span style="font-size: 12px;"><a href="javascript: void(0)" onclick=\'javascript: loadVideosFromMusic("' + movies[i] + '")\'>' + movies[i] + '</a></span>' + td1;
						j++;
						if (j % per_line == 0)
							{ 
								theHTML += tr1;
								theHTML += tr0;
								j = 0; 
							}
					}
				
				theHTML += '</table>';
				
				$(obj).update(theHTML);
			}
		catch(err) {}
	}
	
function searchVideos()
	{
		var channels = '';
		var title = '';
		var categories = '';
		var shows = '';
		
		var video_name = $('video_name').value;
		if (video_name != '')
			{
				title = "search '" + video_name + "'";
			}
		var comma1 = '';
		
		if ( ($('channels').value != '') && ($('channels').value != 'All') )
			{
				channels = 'channel,' + $('channels').value;
				var channel = $('channels').value;
				title = 'channel ' + "'" + channel + "'";
				if (video_name != '')
					{
						comma1 = ',';
					}
			}
		if ( ($('categories').value != '') && ($('categories').value != 'All') )
			{
				categories = ',category,' + $('categories').value;
				var category = $('categories').value;
				title = 'category ' + "'" + category + "'";
			}
		if ( ($('shows').value != '') && ($('shows').value != 'All') )
			{
				shows = ',showName,' + $('shows').value;
				var show = $('shows').value;
				title = 'show ' + "'" + show + "'";
			}

		search_str = video_name + comma1 + channels + categories  + shows;
		
		if (title != '')
			{ 
				$('title_video').update("Results for the " + title);
				change_search_title = 'no';
			}
		else
			{
				change_search_title = 'yes';
			}
		
		var ss1 = search_str.replace(/ /g, '+');
		var ss2 = ss1.replace(/&/g, 'and');
		var ss = ss2;
		
		window.location = 'Video,search,' + ss + '.html';
		//initVideos('videoContent', search_str, '1');
		//Video,search,Prison+Break.html
	}
	
function loadVideosFromCategory(categories, type)
	{
		/*$("tab_search_id").click();
		initVideos("videoContent", "category: " + categories, '0');
		
		for (var i = 1; i < $('categories').length; i++)
			{
				if ($('categories')[i].value == categories)
					{
						$('categories')[i].selected = true;
						break;
					}
			}
		$('title_video').update("Results for the category '" + categories + "'");*/
		window.location = 'Video,search,,,all,category,' + categories + '.html';
	}
	
function loadVideosFromChannels(channels)
	{
		/*channels = channels.replace("`", "'");
		$('tab_search_id').click();
		initVideos("videoContent", "channel: " + channels, '0');
		
		for (var i = 1; i < $('channels').length; i++)
			{
				if ($('channels')[i].value == channels)
					{
						$('channels')[i].selected = true;
						break;
					}
			}
		$('title_video').update("Results for the channel '" + channels + "'");*/
		window.location = 'Video,channel,' + channels.replace(/ /g, "+") + '.html';
	}
	
function loadVideosFromTags(tag)
	{
		$('tab_search_id').click();
		initVideos("videoContent", "tag: " + tag, '0');
		
		$('title_video').update("Results for the tag '" + tag + "'");
	}
	
function loadVideosFromShows(shows)
	{
		/*shows = shows.replace(/`/g, "'");
		$('tab_search_id').click();
		initVideos("videoContent", "-show: " + shows, '0');
		
		for (var i = 1; i < $('shows').length; i++)
			{
				if ($('shows')[i].value == shows)
					{
						$('shows')[i].selected = true;
						break;
					}
			}
		$('title_video').update("Results for the show '" + shows + "'");*/
		window.location = 'Video,show,' + shows.replace(/ /g, "+") + '.html';
	}
	
function loadVideosFromCelebrities(celebs)
	{
		celebs = celebs.replace(/`/g, "'");
		$('tab_search_id').click();
		initVideos("videoContent", "-actor: " + celebs, '0');
		
		$('title_video').update("Results for the actor '" + celebs + "'");
	}
	
function loadVideosFromMusic(music)
	{
		music = music.replace(/`/g, "'");
		$('tab_search_id').click();
		initVideos("videoContent", "-artist: " + music, '0');
		
		$('title_video').update("Results for the music '" + music + "'");
	}
	
var mywindow;
	
function displaySendMail(id, title)
	{
		mywindow = new Window(
				    {
					    "name": "TestWindow",
					    "z_index": -1,
					    "min_height": 10,
					    "action": "debug",
					    "id": "window_7179",
					    "scrollbars": 1,
					    "is_minimized": 0,
					    "stayontop": 0,
					    "min_width": 10,
					    "height": 400,
					    "posx": 100,
					    "posy": 100,
					    "width": 400
						}
				);
		
		if (mywindow != 'undefined')
			{
				new Effect.Appear('window_7179', {duration: 2});
			}
		
		$('send_mail_iframe').src = 'emailThisVideo.php?id=' + id + '&title=' + title;
	}
	
function displayBadLink(site_id)
	{
		mywindow = new Window(
				    {
					    "name": "TestWindow",
					    "z_index": -1,
					    "min_height": 10,
					    "action": "debug",
					    "id": "window_7179",
					    "scrollbars": 1,
					    "is_minimized": 0,
					    "stayontop": 0,
					    "min_width": 10,
					    "height": 400,
					    "posx": 100,
					    "posy": 100,
					    "width": 400
						}
				);
		
		if (mywindow != 'undefined')
			{
				new Effect.Appear('window_7179', {duration: 2});
			}
		
		$('report_bad_link').src = 'reportBadLink.php?site_id=' + site_id;
	}
	
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

	
function displayVideoMoreOptions()
	{
		var expand = 'images/expand.gif';
		var collapse = 'images/collapse.gif';
		
		if (readCookie('MoreOptions') == 'expand')
			{
				$('expand_collapse').hide();
				$('img_more_options').src = expand;
				SetCookie('MoreOptions', 'collapse', '365');
			}
		else if ( (readCookie('MoreOptions') == "") || (readCookie('MoreOptions') == null) || (readCookie('MoreOptions') == 'collapse') )
			{
				$('expand_collapse').show();
				$('img_more_options').src = collapse;
				SetCookie('MoreOptions', 'expand', '365');
			}
	}
	
function setVideoMoreOptions()
	{
		var expand = 'images/expand.gif';
		var collapse = 'images/collapse.gif';
		$('expand_collapse').show();
		$('img_more_options').src = collapse;
		SetCookie('MoreOptions', 'expand', '365');
	}
	
function changeMenu(id)
	{
		if ( id == 1 )
			{
				document.getElementById('left2').style.display = 'none';
				document.getElementById('left3').style.display = 'none';
				document.getElementById('left1').style.display = 'block';
				
				document.getElementById('link1').className = 'leftMenuLink2';
				document.getElementById('link2').className = 'leftMenuLink';
				document.getElementById('link3').className = 'leftMenuLink';
			}
		
		if ( id == 2 )
			{
				document.getElementById('left1').style.display = 'none';
				document.getElementById('left3').style.display = 'none';
				document.getElementById('left2').style.display = 'block';
				
				document.getElementById('link1').className = 'leftMenuLink';
				document.getElementById('link2').className = 'leftMenuLink2';
				document.getElementById('link3').className = 'leftMenuLink';
			}
		
		if ( id == 3 )
			{
				document.getElementById('left1').style.display = 'none';
				document.getElementById('left2').style.display = 'none';
				document.getElementById('left3').style.display = 'block';
				
				document.getElementById('link1').className = 'leftMenuLink';
				document.getElementById('link2').className = 'leftMenuLink';
				document.getElementById('link3').className = 'leftMenuLink2';
			}
		
		if ( id == 4 )
			{
				$('second1').show();
				$('second2').hide();
				$('second3').hide();
				$('second4').hide();
				$('second5').hide();
				$('top_rated').hide();
				$('last_added').hide();
				$('most_visited').show();
				
				document.getElementById('week1').style.fontWeight = 'bold';
				document.getElementById('week1').style.fontSize = '13px';
				document.getElementById('all_time1').style.fontWeight = 'normal';
				document.getElementById('all_time1').style.fontSize = '12px';
				
				document.getElementById('link4').className = 'leftMenuLink2';
				document.getElementById('link5').className = 'leftMenuLink';
				document.getElementById('link6').className = 'leftMenuLink';
			}
		
		if ( id == 5 || id == 11 )
			{
				document.getElementById('second1').style.display = 'none';
				document.getElementById('second2').style.display = 'none';
				document.getElementById('second3').style.display = 'block';
				document.getElementById('second4').style.display = 'none';
				document.getElementById('second5').style.display = 'none';
				document.getElementById('last_added').style.display = 'none';
				document.getElementById('most_visited').style.display = 'none';
				document.getElementById('top_rated').style.display = 'block';
				
				document.getElementById('all_time2').style.fontWeight = 'normal';
				document.getElementById('all_time2').style.fontSize = '12px';
				document.getElementById('week2').style.fontWeight = 'bold';
				document.getElementById('week2').style.fontSize = '13px';
				
				document.getElementById('link4').className = 'leftMenuLink';
				document.getElementById('link5').className = 'leftMenuLink2';
				document.getElementById('link6').className = 'leftMenuLink';
			}
		
		if ( id == 6 )
			{
				document.getElementById('second1').style.display = 'none';
				document.getElementById('second2').style.display = 'none';
				document.getElementById('second3').style.display = 'none';
				document.getElementById('second4').style.display = 'none';
				document.getElementById('second5').style.display = 'block';
				
				document.getElementById('link4').className = 'leftMenuLink';
				document.getElementById('link5').className = 'leftMenuLink';
				document.getElementById('link6').className = 'leftMenuLink2';
				document.getElementById('most_visited').style.display = 'none';
				document.getElementById('top_rated').style.display = 'none';
				document.getElementById('last_added').style.display = 'block';
			}
			
		if ( id == 7 )
			{
				document.getElementById('second1').style.display = 'none';
				document.getElementById('second2').style.display = 'block';
				document.getElementById('second3').style.display = 'none';
				document.getElementById('second4').style.display = 'none';
				document.getElementById('second5').style.display = 'none';
				
				document.getElementById('all_time1').style.fontWeight = 'bold';
				document.getElementById('all_time1').style.fontSize = '13px';
				document.getElementById('week1').style.fontWeight = 'normal';
				document.getElementById('week1').style.fontSize = '12px';
				
				document.getElementById('link4').className = 'leftMenuLink2';
				document.getElementById('link5').className = 'leftMenuLink';
				document.getElementById('link6').className = 'leftMenuLink';
				document.getElementById('most_visited').style.display = 'block';
				document.getElementById('top_rated').style.display = 'none';
				document.getElementById('last_added').style.display = 'none';
			}
			
		if ( id == 8 )
			{
				document.getElementById('second1').style.display = 'block';
				document.getElementById('second2').style.display = 'none';
				document.getElementById('second3').style.display = 'none';
				document.getElementById('second4').style.display = 'none';
				document.getElementById('second5').style.display = 'none';
				
				document.getElementById('all_time1').style.fontWeight = 'normal';
				document.getElementById('all_time1').style.fontSize = '12px';
				document.getElementById('week1').style.fontWeight = 'bold';
				document.getElementById('week1').style.fontSize = '13px';
				
				document.getElementById('link4').className = 'leftMenuLink2';
				document.getElementById('link5').className = 'leftMenuLink';
				document.getElementById('link6').className = 'leftMenuLink';
				document.getElementById('most_visited').style.display = 'block';
				document.getElementById('top_rated').style.display = 'none';
				document.getElementById('last_added').style.display = 'none';
			}
			
		if ( id == 10 )
			{
				document.getElementById('second1').style.display = 'none';
				document.getElementById('second2').style.display = 'none';
				document.getElementById('second3').style.display = 'none';
				document.getElementById('second4').style.display = 'block';
				document.getElementById('second5').style.display = 'none';
				
				document.getElementById('week2').style.fontWeight = 'normal';
				document.getElementById('week2').style.fontSize = '12px';
				document.getElementById('all_time2').style.fontWeight = 'bold';
				document.getElementById('all_time2').style.fontSize = '13px';
				
				document.getElementById('link4').className = 'leftMenuLink';
				document.getElementById('link5').className = 'leftMenuLink2';
				document.getElementById('link6').className = 'leftMenuLink';
				document.getElementById('most_visited').style.display = 'none';
				document.getElementById('top_rated').style.display = 'block';
				document.getElementById('last_added').style.display = 'none';
			}
	}
	
function selectThis(id)
	{
		if ( id == 1 )
			{
				document.getElementById('pic1').src = 'images/star1.gif';
			}
		if ( id == 2 )
			{
				document.getElementById('pic1').src = 'images/star1.gif';
				document.getElementById('pic2').src = 'images/star1.gif';
			}
		if ( id == 3 )
			{
				document.getElementById('pic1').src = 'images/star1.gif';
				document.getElementById('pic2').src = 'images/star1.gif';
				document.getElementById('pic3').src = 'images/star1.gif';
			}
		if ( id == 4 )
			{
				document.getElementById('pic1').src = 'images/star1.gif';
				document.getElementById('pic2').src = 'images/star1.gif';
				document.getElementById('pic3').src = 'images/star1.gif';
				document.getElementById('pic4').src = 'images/star1.gif';
			}
		if ( id == 5 )
			{
				document.getElementById('pic1').src = 'images/star1.gif';
				document.getElementById('pic2').src = 'images/star1.gif';
				document.getElementById('pic3').src = 'images/star1.gif';
				document.getElementById('pic4').src = 'images/star1.gif';
				document.getElementById('pic5').src = 'images/star1.gif';
			}
	}
	
function clearThis()
	{
		document.getElementById('pic1').src = 'images/star0.gif';
		document.getElementById('pic2').src = 'images/star0.gif';
		document.getElementById('pic3').src = 'images/star0.gif';
		document.getElementById('pic4').src = 'images/star0.gif';
		document.getElementById('pic5').src = 'images/star0.gif';
	}
	
function rateThis(id, thisLink)
	{
		window.location = thisLink + ',vote,' + id + '.html';
	}
	
//** Tab Content script v2.0- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
//** Updated Oct 7th, 07 to version 2.0. Contains numerous improvements:
//   -Added Auto Mode: Script auto rotates the tabs based on an interval, until a tab is explicitly selected
//   -Ability to expand/contract arbitrary DIVs on the page as the tabbed content is expanded/ contracted
//   -Ability to dynamically select a tab either based on its position within its peers, or its ID attribute (give the target tab one 1st)
//   -Ability to set where the CSS classname "selected" get assigned- either to the target tab's link ("A"), or its parent container 

////NO NEED TO EDIT BELOW////////////////////////

function ddtabcontent(tabinterfaceid){
	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container
	this.enabletabpersistence=true
	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values)
	this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
}

ddtabcontent.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

ddtabcontent.setCookie=function(name, value){
	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
}

ddtabcontent.prototype={

	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers
		this.cancelautorun() //stop auto cycling of tabs (if running)
		var tabref=""
		try{
			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=this.tabs[tabid_or_position]
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tabref!="") //if a valid tab is found based on function parameter
			this.expandtab(tabref) //expand this tab
	},

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
		this.selectedClassTarget=objstr || "link"
	},

	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to
		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref
	},

	expandtab:function(tabref){
		var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand
		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		this.expandsubcontent(subcontentid)
		this.expandrevcontent(associatedrevids)
		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"
			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "selected" : ""
		}
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)
	},

	expandsubcontent:function(subcontentid){
		for (var i=0; i<this.subcontentids.length; i++){
			var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)
			subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value
		}
	},


	expandrevcontent:function(associatedrevids){
		var allrevids=this.revcontentids
		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface
			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		var currentTabIndex=this.automode_currentTabIndex //index within this.hottabspositions to begin
		var hottabspositions=this.hottabspositions //Array containing position numbers of "hot" tabs (those with a "rel" attr)
		this.expandtab(this.tabs[hottabspositions[currentTabIndex]])
		this.automode_currentTabIndex=(currentTabIndex<hottabspositions.length-1)? currentTabIndex+1 : 0 //increment currentTabIndex
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var persisterror=true //Bool variable to check whether persisted tab position is valid (can become invalid if user has modified tab structure)
		this.automodeperiod=automodeperiod || 0
		for (var i=0; i<this.tabs.length; i++){
			this.tabs[i].tabposition=i //remember position of tab relative to its peers
			if (this.tabs[i].getAttribute("rel")){
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)
				this.tabs[i].onclick=function(){
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
				}
				if (this.enabletabpersistence && parseInt(persistedtab)==i || !this.enabletabpersistence && this.getselectedClassTarget(this.tabs[i]).className=="selected"){
					this.expandtab(this.tabs[i]) //expand current tab if it's the persisted tab, or if persist=off, carries the "selected" CSS class
					persisterror=false //Persisted tab (if applicable) was found, so set "persisterror" to false
					//If currently selected tab's index(i) is greater than 0, this means its not the 1st tab, so set the tab to begin in automode to 1st tab:
					this.automode_currentTabIndex=(i>0)? 0 : 1
				}
			}
		} //END for loop
		if (persisterror) //if an error has occured while trying to retrieve persisted tab (based on its position within its peers)
			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){
			this.automode_currentTabIndex=this.automode_currentTabIndex || 0
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	} //END int() function

} //END Prototype assignment

// formatDate :
// a PHP date like function, for formatting date strings
// authored by Svend Tofte <www.svendtofte.com>
// the code is in the public domain
//
// see http://www.svendtofte.com/code/date_format/
// and http://www.php.net/date
//
// thanks to 
//  - Daniel Berlin <mail@daniel-berlin.de>,
//    major overhaul and improvements
//  - Matt Bannon,
//    correcting some stupid bugs in my days-in-the-months list!
//
// input : format string
// time : epoch time (seconds, and optional)
//
// if time is not passed, formatting is based on 
// the current "this" date object's set time.
//
// supported switches are
// a, A, B, c, d, D, F, g, G, h, H, i, I (uppercase i), j, l (lowecase L), 
// L, m, M, n, N, O, P, r, s, S, t, U, w, W, y, Y, z, Z
// 
// unsupported (as compared to date in PHP 5.1.3)
// T, e, o

Date.prototype.formatDate = function (input,time) {
    
    var daysLong =    ["Sunday", "Monday", "Tuesday", "Wednesday", 
                       "Thursday", "Friday", "Saturday"];
    var daysShort =   ["Sun", "Mon", "Tue", "Wed", 
                       "Thu", "Fri", "Sat"];
    var monthsShort = ["Jan", "Feb", "Mar", "Apr",
                       "May", "Jun", "Jul", "Aug", "Sep",
                       "Oct", "Nov", "Dec"];
    var monthsLong =  ["January", "February", "March", "April",
                       "May", "June", "July", "August", "September",
                       "October", "November", "December"];

    var switches = { // switches object
        
        a : function () {
            // Lowercase Ante meridiem and Post meridiem
            return date.getHours() > 11? "pm" : "am";
        },
        
        A : function () {
            // Uppercase Ante meridiem and Post meridiem
            return (this.a().toUpperCase ());
        },
    
        B : function (){
            // Swatch internet time. code simply grabbed from ppk,
            // since I was feeling lazy:
            // http://www.xs4all.nl/~ppk/js/beat.html
            var off = (date.getTimezoneOffset() + 60)*60;
            var theSeconds = (date.getHours() * 3600) + 
                             (date.getMinutes() * 60) + 
                              date.getSeconds() + off;
            var beat = Math.floor(theSeconds/86.4);
            if (beat > 1000) beat -= 1000;
            if (beat < 0) beat += 1000;
            if ((String(beat)).length == 1) beat = "00"+beat;
            if ((String(beat)).length == 2) beat = "0"+beat;
            return beat;
        },
        
        c : function () {
            // ISO 8601 date (e.g.: "2004-02-12T15:19:21+00:00"), as per
            // http://www.cl.cam.ac.uk/~mgk25/iso-time.html
            return (this.Y() + "-" + this.m() + "-" + this.d() + "T" + 
                    this.h() + ":" + this.i() + ":" + this.s() + this.P());
        },
        
        d : function () {
            // Day of the month, 2 digits with leading zeros
            var j = String(this.j());
            return (j.length == 1 ? "0"+j : j);
        },
        
        D : function () {
            // A textual representation of a day, three letters
            return daysShort[date.getDay()];
        },
        
        F : function () {
            // A full textual representation of a month
            return monthsLong[date.getMonth()];
        },
        
        g : function () {
            // 12-hour format of an hour without leading zeros
            return date.getHours() > 12? date.getHours()-12 : date.getHours();
        },
        
        G : function () {
            // 24-hour format of an hour without leading zeros
            return date.getHours();
        },
        
        h : function () {
            // 12-hour format of an hour with leading zeros
            var g = String(this.g());
            return (g.length == 1 ? "0"+g : g);
        },
        
        H : function () {
            // 24-hour format of an hour with leading zeros
            var G = String(this.G());
            return (G.length == 1 ? "0"+G : G);
        },
        
        i : function () {
            // Minutes with leading zeros
            var min = String (date.getMinutes ());
            return (min.length == 1 ? "0" + min : min);
        },
        
        I : function () {
            // Whether or not the date is in daylight saving time (DST)
            // note that this has no bearing in actual DST mechanics,
            // and is just a pure guess. buyer beware.
            var noDST = new Date ("January 1 " + this.Y() + " 00:00:00");
            return (noDST.getTimezoneOffset () == 
                    date.getTimezoneOffset () ? 0 : 1);
        },
        
        j : function () {
            // Day of the month without leading zeros
            return date.getDate();
        },
        
        l : function () {
            // A full textual representation of the day of the week
            return daysLong[date.getDay()];
        },
        
        L : function () {
            // leap year or not. 1 if leap year, 0 if not.
            // the logic should match iso's 8601 standard.
            // http://www.uic.edu/depts/accc/software/isodates/leapyear.html
            var Y = this.Y();
            if (         
                (Y % 4 == 0 && Y % 100 != 0) ||
                (Y % 4 == 0 && Y % 100 == 0 && Y % 400 == 0)
                ) {
                return 1;
            } else {
                return 0;
            }
        },
        
        m : function () {
            // Numeric representation of a month, with leading zeros
            var n = String(this.n());
            return (n.length == 1 ? "0"+n : n);
        },
        
        M : function () {
            // A short textual representation of a month, three letters
            return monthsShort[date.getMonth()];
        },
        
        n : function () {
            // Numeric representation of a month, without leading zeros
            return date.getMonth()+1;
        },
        
        N : function () {
            // ISO-8601 numeric representation of the day of the week
            var w = this.w();
            return (w == 0 ? 7 : w);
        },
        
        O : function () {
            // Difference to Greenwich time (GMT) in hours
            var os = Math.abs(date.getTimezoneOffset());
            var h = String(Math.floor(os/60));
            var m = String(os%60);
            h.length == 1? h = "0"+h:1;
            m.length == 1? m = "0"+m:1;
            return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
        },
        
        P : function () {
            // Difference to GMT, with colon between hours and minutes
            var O = this.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2));
        },      
        
        r : function () {
            // RFC 822 formatted date
            var r; // result
            //  Thu         ,     21               Dec              2000
            r = this.D() + ", " + this.d() + " " + this.M() + " " + this.Y() +
            //    16          :    01          :    07               0200
            " " + this.H() + ":" + this.i() + ":" + this.s() + " " + this.O();
            return r;
        },

        s : function () {
            // Seconds, with leading zeros
            var sec = String (date.getSeconds ());
            return (sec.length == 1 ? "0" + sec : sec);
        },        
        
        S : function () {
            // English ordinal suffix for the day of the month, 2 characters
            switch (date.getDate ()) {
                case  1: return ("st"); 
                case  2: return ("nd"); 
                case  3: return ("rd");
                case 21: return ("st"); 
                case 22: return ("nd"); 
                case 23: return ("rd");
                case 31: return ("st");
                default: return ("th");
            }
        },
        
        t : function () {
            // thanks to Matt Bannon for some much needed code-fixes here!
            var daysinmonths = [null,31,28,31,30,31,30,31,31,30,31,30,31];
            if (this.L()==1 && this.n()==2) return 29; // ~leap day
            return daysinmonths[this.n()];
        },
        
        U : function () {
            // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
            return Math.round(date.getTime()/1000);
        },

        w : function () {
            // Numeric representation of the day of the week
            return date.getDay();
        },
        
        W : function () {
            // Weeknumber, as per ISO specification:
            // http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        
            var DoW = this.N ();
            var DoY = this.z ();

            // If the day is 3 days before New Year's Eve and is Thursday or earlier,
            // it's week 1 of next year.
            var daysToNY = 364 + this.L () - DoY;
            if (daysToNY <= 2 && DoW <= (3 - daysToNY)) {
                return 1;
            }

            // If the day is within 3 days after New Year's Eve and is Friday or later,
            // it belongs to the old year.
            if (DoY <= 2 && DoW >= 5) {
                return new Date (this.Y () - 1, 11, 31).formatDate ("W");
            }
            
            var nyDoW = new Date (this.Y (), 0, 1).getDay ();
            nyDoW = nyDoW != 0 ? nyDoW - 1 : 6;

            if (nyDoW <= 3) { // First day of the year is a Thursday or earlier
                return (1 + Math.floor ((DoY + nyDoW) / 7));
            } else {  // First day of the year is a Friday or later
                return (1 + Math.floor ((DoY - (7 - nyDoW)) / 7));
            }
        },
        
        y : function () {
            // A two-digit representation of a year
            var y = String(this.Y());
            return y.substring(y.length-2,y.length);
        },        
        
        Y : function () {
            // A full numeric representation of a year, 4 digits
    
            // we first check, if getFullYear is supported. if it
            // is, we just use that. ppks code is nice, but wont
            // work with dates outside 1900-2038, or something like that
            if (date.getFullYear) {
                var newDate = new Date("January 1 2001 00:00:00 +0000");
                var x = newDate .getFullYear();
                if (x == 2001) {              
                    // i trust the method now
                    return date.getFullYear();
                }
            }
            // else, do this:
            // codes thanks to ppk:
            // http://www.xs4all.nl/~ppk/js/introdate.html
            var x = date.getYear();
            var y = x % 100;
            y += (y < 38) ? 2000 : 1900;
            return y;
        },

        
        z : function () {
            // The day of the year, zero indexed! 0 through 366
            var t = new Date("January 1 " + this.Y() + " 00:00:00");
            var diff = date.getTime() - t.getTime();
            return Math.floor(diff/1000/60/60/24);
        },

        Z : function () {
            // Timezone offset in seconds
            return (date.getTimezoneOffset () * -60);
        }        
    
    }

    function getSwitch(str) {
        if (switches[str] != undefined) {
            return switches[str]();
        } else {
            return str;
        }
    }

    var date;
    if (time) {
        var date = new Date (time);
    } else {
        var date = this;
    }

    var formatString = input.split("");
    var i = 0;
    while (i < formatString.length) {
        if (formatString[i] == "\\") {
            // this is our way of allowing users to escape stuff
            formatString.splice(i,1);
        } else {
            formatString[i] = getSwitch(formatString[i]);
        }
        i++;
    }
    
    return formatString.join("");
}


// Some (not all) predefined format strings from PHP 5.1.1, which 
// offer standard date representations.
// See: http://www.php.net/manual/en/ref.datetime.php#datetime.constants
//

// Atom      "2005-08-15T15:52:01+00:00"
Date.DATE_ATOM    = "Y-m-d\\TH:i:sP";
// ISO-8601  "2005-08-15T15:52:01+0000"
Date.DATE_ISO8601 = "Y-m-d\\TH:i:sO";
// RFC 2822  "Mon, 15 Aug 2005 15:52:01 +0000"
Date.DATE_RFC2822 = "D, d M Y H:i:s O";
// W3C       "2005-08-15T15:52:01+00:00"
Date.DATE_W3C     = "Y-m-d\\TH:i:sP";

