/*<!-----------------------------------------------------------------------------
	Template Name:	video-master.cfm
	Orig Author:	various
	Orig Date:		recently
	Description:	
	Note:				Please leave the version number here and in the actualy, compressed js file
	Inputs:			N/A
	Output:			N/A
-------------------------------------------------------------------------------
		Here's a javascript compressor: http://www.creativyst.com/Prod/3/
-------------------------------------------------------------------------------
April 07: Courts
.001 - moved into this common file, updated, blah, blah for myspacetv
.002 - Launch Day: Courts, validate Music Genres for Upload/Edit
.003 - July 3: courts, hunt for and remove static text, use Resources instead.
.007 - Aug Courts: added the loadDone function, pulls wordbreaker out of pages to here.
.019 - Dec Courts: move comment tools to bottom of table cell. "moveToBottom"
.020 - Dec Courts: search, changed fuseaction and returned it to vids.myspaace (relative) URL for vids search
-------------------------------------------------------------------------------
	To Do:
		-- 
------------------------------------------------------------------------------>*/

if(typeof(MS) === 'undefined') {
	MS = {};
}

if(typeof(MS.Videos) === 'undefined') {
	MS.Videos = {};
}

// store all new variables in the MS.Videos namespace instead of the global one.
MS.Videos.preferredCulture = "";
MS.Videos.bandName = ""; 
MS.Videos.peopleSearchEnabled = false; 

// -------------------------------------------------------------------------------
//	
// -------------------------------------------------------------------------------
function trim(i){i=i.replace(/([ \t\r\n\f])*$/gi,"");	return i.replace(/^([ \t\r\n\f])*/gi,"");}
function isDefined(variable){
  return (!(!( variable||false )));
}

// -------------------------------------------------------------------------------
//	todo: make a resource handler, for now, this "try" is a handy way to 
//		1. determine whether the global "Resources" has been defined (if not, it creates it)
//		2. if the requested key doesn't exist it adds it.
// -------------------------------------------------------------------------------
function tryResource(key,defaultVal){
	if (!isDefined(window.Resources)){
		window.Resources={};
	}
	if (!eval("Resources."+key)){
		eval("Resources."+key+"=\""+defaultVal+"\"");
	}
}


/*!--- ------------------------------------------------------------------------------------------------------------

				More Comment Tools

!--- ------------------------------------------------------------------------------------------------------------ ---*/
// --------------------------------------------------------------- //
//	function: moveToBottom
//	Scope: public
//	Does: adds "margin-top" to a UL to force it to bottom of a table cell.
//		(expects code in format shown below)
// --------------------------------------------------------------- //
/* sample of 
<table id="tblComments" class="comments">
	<td class="poster">---</td>
	<td class="comment">
		<p class="posting_date">Saturday, July 21, 2007 5:13 PM</p>
		<div>i love 50 cent and eminem</div>
		<ul class="commentTools">....
	</td>
*/
function moveToBottom(tableID, className){
	var table = document.getElementById(tableID);
	if (table == null) return;

	var classRegEx = new RegExp("\\b"+ className +"\\b","gi");
	var myHeightGuess = 45;
	var margHeight = 0;
	var lists = [];
	var boxes = [];

	var cells = table.getElementsByTagName('td');
	for (var i=0; i < cells.length; i++){
		if (cells[i].className.match(classRegEx)){
			lists = cells[i].getElementsByTagName('ul');
			if (lists.length > 0){
				boxes = cells[i].getElementsByTagName('div');
				if (boxes.length > 0){
					margHeight = cells[i].offsetHeight - boxes[0].offsetHeight - myHeightGuess;
					lists[0].style.marginTop = ((margHeight > 0)?margHeight:0)+"px";
				} // has box
			} // has list
		} // regex
	} // for
} // moveToBottom


/*!--- ------------------------------------------------------------------------------------------------------------

				Some Search Field Validator for searches in header and page body

!--- ------------------------------------------------------------------------------------------------------------ ---*/

// -------------------------------------------------------------------------------
//	function: validateHeadSearch
//	parameters: 
//				[optional] error message, displayed if no search criteria provided
//				[optional] element ID to be checked
// -------------------------------------------------------------------------------
function validateSearch(){
	var h=document.getElementById((arguments.length>1)?arguments[1]:"srchq");
	if (!h.isValid()){
		alert((arguments.length>0)?arguments[0]:"Please enter one or more search words (minimum length 3 characters)");
		h.focus();
		return false;
	}
	// golly, can't decide... guess escape, right? well, for now let's just do this.
	// Arif: don't encode the &
	//var re = new RegExp('&([^a])','gm');
	//h.value = h.value.replace(re, "&amp;$1");
	// h.value = escape(h.value);
	return true;
}

function validateHeadSearch(event) {		  
	Event.stop(event);
	if (!validateSearch(Resources.header_alert_searchempty, 'srchq')) {
		return false;
	}
	var stype = $('srchtype');
	if (stype.selectedIndex < 0) {
		return false;
	}
	
	var ssrch = Event.element(event);			
	   
	if (stype.options[stype.selectedIndex].value == "tpeople" && MS.Videos.peopleSearchEnabled) {
		var action = "http://searchservice.myspace.com/index.cfm";
		var postparams = { fuseaction: 'search', searchBy: 'First', f_first_name: $F('srchq') };				
	} else if (stype.options[stype.selectedIndex].value != "tvid") {
		action = "http://searchresults.myspace.com/index.cfm";		
		postparams = { fuseaction: 'advancedFind.hub', SearchBoxID: 'SplashHeader', q: $F('srchq'), t: $F('srchtype') };
	} else {
		action = "/index.cfm";		
		postparams = { fuseaction: 'vids.search', SearchBoxID: 'SplashHeader', q: $F('srchq'), t: $F('srchtype') };
	}
	
	submitData(action, postparams);			 
}

function submitData(url, data) {

	var form = document.createElement('form');
	form.action=url;
	form.method='get';	
	for(var i in data) {
		addParam(form, i, data[i]);
	}
	form.style.display='none';
	document.body.appendChild(form);	
	form.submit();
}

function addParam(form, key, value) {
	var input = document.createElement('input');
	input.name=key;
	input.value = value;
	form.appendChild(input);
}

// -------------------------------------------------------------------------------
//	function: wireHeadSearch
//	description: Attaches behaviors to header's search box, showing & hiding some default text.
//	recommend calling this in the footer with optional parameter for text to be show. and, second optional
//		is element ID to get wired.
// -------------------------------------------------------------------------------
var minSearchWordLength = 3;
function wireSearch(){
	var h= document.getElementById((arguments.length>1)?arguments[1]:"srchq");
	h.defaultText= (arguments.length>0)?arguments[0]:"Search everyone's videos";
	if (h.value === "") {
		h.value=h.defaultText;
	}
	if (h.value == h.defaultText) {// doing this because if user's use browser back button may need to handle initial state IS default text
		h.style.color="#999";		
	}

	h.onfocus = function (){
		this.value=trim(this.value);
		if (this.value == this.defaultText){
			this.value="";
			this.style.color="#000";
		}
	}; // onfocus
	
	h.onblur = function (){
		this.value=trim(this.value);
		if (this.value.length<1){
			this.value=this.defaultText;
			this.style.color="#999";
		}
	}; // onblur
	
	h.isValid= function(){
		this.value=trim(this.value);
		return ((this.value.length>=minSearchWordLength) && (this.value!=this.defaultText));
	}; // isValid

} // wireHeadSearch


var ResizeElement = Class.create();
ResizeElement.prototype = {
	initialize: function( elt, options) {	 
	  this.options = options || {};		 
	  var args = $A(arguments);	 
	  var h = null;	  
	  if(1 == args.length && 'string' == typeof args[0]) {
		h = $(args[0]);
	  }
	  
	  if(!h) {
		throw 'Element not found';
	  }
	  
	  this.element = h;	  	  	  
					  									  
	  Event.observe(window, 'resize', this.onResizeHandler.bindAsEventListener(this));
	  Event.observe(window, 'scroll', this.onScrollHandler.bindAsEventListener(this));		
	},	
	
	onResizeHandler: function (e){		
		var elt = $(Event.element(e));			   		
		Event.stop(e);		
		
		var elDim = this.element.getDimensions();	   		
				
		if(elDim.height > 365) {		  		  
		  this.element.setStyle({ 'height': '365px', 'overflow-x' : 'hidden', 'overflow-y' : 'scroll'});
		}		
	},		
	
	onScrollHandler: function (e){		
		var elt = $(Event.element(e));			   		
		Event.stop(e);						
		var elDim = this.element.getDimensions();
				
		if(elDim.height > 365) {		  		  
		  this.element.setStyle({ 'height': '365px', 'overflow-x' : 'hidden', 'overflow-y' : 'scroll'});
		}		
	}		
}; 


// -------------------------------------------------------------------------------
//	
// -------------------------------------------------------------------------------
function full(vid, dcTag)
{
  //var fsvURL = "http://vids.myspace.com/index.cfm?fuseaction=vids.fullscreen&videoid=" + vid;
  var fsvURL = "/index.cfm?fuseaction=vids.fullscreen&videoid=" + vid;
  if (dcTag) fsvURL += "&dcTag=" + dcTag;
  // OK, say goodby to: fullscreen=yes,
  var fs = window.open( fsvURL, "fsv", "toolbar=no,width=" + screen.availWidth  + ",height=" + screen.availHeight + ",status=no,resizable=yes,scrollbars=no");
  fs.focus();
}


// -------------------------------------------------------------------------------
//	
// -------------------------------------------------------------------------------
function openPlayer(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

// -------------------------------------------------------------------------------
//	
// -------------------------------------------------------------------------------
/*
function validate(thisForm) {
	noisewords= new Array("a","all","am","an","and","any","are","as","at","be","but","can","did","do","does","for","from","had","has","have","here","how","i","if","in","is","it","in","is","it","no","not","of","on","or","so","that","the","then","there","this","to","too","up","use","what","when","where","who","why","you", "-", ".");
	searchKeywords = thisForm.keyword.value;
	searchKeywords = searchKeywords.toLowerCase().split(" ");
	for(var i = 0 ; i < searchKeywords.length ; i ++ ) {
		for (var j = 0 ; j < noisewords.length ; j ++){
			if(noisewords[j].search(searchKeywords[i]) != -1)	{
				searchKeywords[i]= searchKeywords[i].replace(noisewords[j],"");
			}
		}
	}
	thisForm.searchList.value = searchKeywords;

	if (thisForm.genreID.value == 0) {
		if (thisForm.searchBy.value == 0 && thisForm.keyword.value == "")	{
			alert("Genre, search by and keyword cannot be blank");
			return false;
		}
		else if (thisForm.keyword.value == "") {
			alert("Keyword cannot be blank");
			return false;
		}
	}
}
*/

// -------------------------------------------------------------------------------
//	BrowserDetect, a sexy anonymous object, containing many more anonymous objects
// -------------------------------------------------------------------------------
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; 
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1) {
					return data[i].identity;
				}
			}
			else if (dataProp) {
				return data[i].identity;
			}
		}
		return '';
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) {return;}
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	
			string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};


// -------------------------------------------------------------------------------
//	Function: showCharsRemaining
// 	Does: 
//	Params:	
//			InputId : element id of text to check
//			OuptutId : element id where number of remaining characters is written/displayed
//			maxChars : int, number of characters
//			[optional] text to display should user be OVER, ex. "200 over", pass in "over"
// -------------------------------------------------------------------------------
function showCharsRemaining(InputId,OutputId,maxChars){
	var inh=document.getElementById(InputId);
	var outh=document.getElementById(OutputId);
	if (inh.value.length > maxChars){
		var s= (arguments.length > 3)?arguments[3]:" over";
		outh.innerHTML = "<span style=\"color:#900;font-weight:bold;\">"+(inh.value.length - maxChars)+ " "+s+"</span>";
	} else {
		outh.innerHTML = (maxChars - inh.value.length);
	}
}// showCharsRemaining



/*!--- ------------------------------------------------------------------------------------------------------------

		errorHandler object & related validation tools

				Oh, Overkill
!--- ------------------------------------------------------------------------------------------------------------ ---*/
function errorHandler(){
	this.msgs = []; // store errors here
	this.ids = []; // store element ids here, used in anchors to jump to position of error
	this.focusObj = null; // gonna pop here if an error occurs, it's the first object's (with an error) handle 
	this.outputId = "errorsBox"; // element id where we'll be emitting the list of problems.
	this.errorHeader = "Please fix these problems:";
	this.showAlert = true;

	// -------------------------------------------------
	this.init = function(){
		this.msgs= [];
		this.ids= [];
	}; // init

	// -------------------------------------------------
	// function: add
	// parameters:
	//	msg: error message to display if text field is blank
	//	[optional] id: thing/label id that's going to get the CSS class set, null to ignore
	this.add = function(msg){
		this.msgs[this.msgs.length]= msg;
		this.ids[this.ids.length]= (arguments.length > 1)?arguments[1]:null;
		if ((arguments.length > 1) && (this.focusObj===null)) {this.focusObj=document.getElementById(arguments[1]);}
	}; // add

	// -------------------------------------------------
	this.show = function(){
		if (this.msgs.length < 1){
			document.getElementById(this.outputId).innerHTML="";
			return false;
		}
		var out="";
		var msg="";
		for (var i=0; i < this.msgs.length;i++){
			if (this.ids[i] !== null) {
				// out+="<li><a href=\"#"+this.ids[i]+"\">"+this.msgs[i]+"</a></li>";
				out+="<li><a href=\"#\" onclick=\"document.getElementById('"+this.ids[i]+"').focus();return false;\">"+this.msgs[i]+"</a></li>";
			}
			else {
				out+="<li>"+this.msgs[i]+"</li>";
			}
			msg+= this.msgs[i]+"\n";
		}
		out= "<ul>"+out+"</ul>";
		var e= document.getElementById(this.outputId);
		e.innerHTML= "<p>"+this.errorHeader+"</p>"+out;
		if (this.showAlert) {alert(msg);}
		if (this.focusObj!==null) {this.focusObj.focus();}
		return true;
	}; // show

	// -------------------------------------------------
	// function: checkRequiredText
	// parameters:
	//	id: input to check
	//	msg: error message to display if text field is blank
	//	[optional] id: thing/label id that's going to get the CSS class set
	this.checkRequiredText= function(id,msg){
		var ok=true;
		var h= document.getElementById(id);
		if (h){
			h.value = trim(h.value);
			if (h.value.length < 1){
				this.add(msg,id);
				ok=false;
			}
		}
		if (arguments.length > 2) {
			this.setClass(arguments[2],ok); }
		return ok;
	}; // checkRequiredText

	// -------------------------------------------------
	// function: checkTextMaxLength
	// parameters:
	//	id: input to check
	//	msg: error message to display if text field is blank
	//	maxchars: maximum number of characters allowed
	//	[optional] id: thing/label id that's going to get the CSS class set
	this.checkTextMaxLength= function(id,msg,maxchars){
		var ok=true;
		var h= document.getElementById(id);
		if (h){
			if (h.value.length > maxchars){
				this.add(msg,id);
				ok=false;
			}
		}
		if (arguments.length > 3) {
			this.setClass(arguments[3],ok); }
		return ok;
	}; // checkTextMaxLength

	// -------------------------------------------------
	this.hasErrors = function(){ return (this.msgs.length > 0);};

	// -------------------------------------------------
	this.setClass = function(id,ok){
		document.getElementById(id).className=(ok)?"":"error";
	};
}//errorHandler


// -------------------------------------------------------------------------------
//	function: checkCategories
//	Description: This will break if the id is changed or the checkboxes moved out from
//	inside it. Checks that 1 to 3 of the checkboxes are checked.
// -------------------------------------------------------------------------------
function getCheckCount(id){
	var h=document.getElementById(id).getElementsByTagName("input");
	var m=0;
	for (var i=0; i < h.length; i++) {
		if ((h[i].type=="checkbox") && h[i].checked) {m++;}
	}
	return m;
} // getCheckCount

// -------------------------------------------------------------------------------
//  function: getRadioBtnValue
//	Radio Button Validation
//	pass in form-handle and name glued to the desired radio button set
// -------------------------------------------------------------------------------
function getRadioBtnValue(radioId){
	var f = document.getElementById(radioId).form;
	var n = document.getElementById(radioId).name; // radio button's name
	var c = -1;
	for (var i=0; i < f.elements.length; i++){
		if ((f.elements[i].type=="radio") && (f.elements[i].name == n) && (f.elements[i].checked)){
			c = i;
			break;
		}
	}
	if (c > -1) {
		return f.elements[c].value; }
	else  {
		return null; }
}// getRadioBtnValue


/*!--- ------------------------------------------------------------------------------------------------------------

		Form Validation

!--- ------------------------------------------------------------------------------------------------------------ ---*/
// -------------------------------------------------------------------------------
//	creating an object with attributes for id's and error messages
// -------------------------------------------------------------------------------
/*
var clientIds = new Object();
clientIds.Title = "";
clientIds.Description = "";
clientIds.Tags = "";
clientIds.IAgree="";
clientIds.isPrivate="";

tdLanguage
*/

var checker = {
	ErrorHeader: "", // i18l text
	CharsOver: " over", // i18l text
	UserType: 1, // fields vary by user type
	Title: {id: "", msg: "", label: "tdTitle" },
	Description: { id: "", msg: "", length_msg: "", label: "tdDescription" },
	Tags: {id: "", msg: "", label: "tdTags" },	   
	Categories: {msg: "", label: "tdCategories" },
	IAgree: {id: "", msg: "", label: "tdTOS" },
	isPrivate: {id: "", msg: "", label: "tdVisibility" },
	MediaType: {id: "", msg: "", label: "tdMediaType" },
	FilmCategories: {msg: "", label: "tdFilmCategories" },
	ComedyCategories: {msg: "", label: "tdComedyCategories" },
	MusicGenres: {msg: "Please select 1 (one) Music Genre", label: "tdBandCategories" },
	UserID:1, 
	IsMusic: {id: "", msg: "", label: "spanIsMusic" }, 
	MusicTitle: {id: "", msg: "", label: "spanMusicTitle" }, 
	ArtistName: {id: "", msg: "", label: "spanArtistName" }, 
	AlbumName: {id: "", msg: "", label: "spanAlbumName" }, 
	MusicLabel: {id: "", msg: "", label: "spanMusicLabel" }, 
	SongWriter: {id: "", msg: "", label: "spanSongWriter" }, 
	Composer: {id: "", msg: "", label: "spanComposer" }, 
	IsVocalExists: {id: "", msg: "", label: "spanVocalExists" }, 
	IsNoVocalExists: {id: "", msg: "", label: "" }, 
	VocalDetails: {id: "", msg: "", label: "spanVocalDetails" }
};// checker object

var isOneClick= true;
function validateUpload(){
	if (!isOneClick) {return false;}
	var ok=true;
	var e = new errorHandler();
	var h;
	e.init();
	e.showAlert = false;
	e.errorHeader= checker.ErrorHeader;
	e.checkRequiredText(checker.Title.id, checker.Title.msg, checker.Title.label );
	e.checkRequiredText(checker.Tags.id, checker.Tags.msg, checker.Tags.label);
	if (e.checkRequiredText(checker.Description.id, checker.Description.msg, checker.Description.label)) {
		e.checkTextMaxLength(checker.Description.id,checker.Description.length_msg, 3000, checker.Description.label, checker.CharsOver); }

	// culture for JP
	if ( (MS.Videos.preferredCulture === "ja-JP") && (checker.UserID > 1000000000 && checker.UserID < 1300000000)) {
		e.checkRequiredText(checker.MusicTitle.id, checker.MusicTitle.msg, checker.MusicTitle.label);
		e.checkRequiredText(checker.ArtistName.id, checker.ArtistName.msg, checker.ArtistName.label);
		e.checkRequiredText(checker.SongWriter.id, checker.SongWriter.msg, checker.SongWriter.label);
		e.checkRequiredText(checker.IsVocalExists.id, checker.IsVocalExists.msg, checker.IsVocalExists.label);
		e.checkRequiredText(checker.Composer.id, checker.Composer.msg, checker.Composer.label);
	}

	var m= getCheckCount("category_container");
	ok= ((m > 0) && (m < 4));
	if (!ok) { e.add(checker.Categories.msg); }
	e.setClass(checker.Categories.label,ok);

	ok= getRadioBtnValue(checker.isPrivate.id) !== null;
	if(!ok) {e.add(checker.isPrivate.msg);}
	e.setClass(checker.isPrivate.label,ok);

	if ((checker.UserType==15) && (document.getElementById(checker.MediaType.id))){
		// comedy Extras
		ok= getRadioBtnValue(checker.MediaType.id) !== null;
		if(!ok) {e.add(checker.MediaType.msg);}
		e.setClass(checker.MediaType.label,ok);
		
		// Comedy Categorys: 1 to 3 required.
		m= getCheckCount("comedycats_container");
		ok= ((m > 0) && (m < 4));
		if (!ok) {e.add(checker.ComedyCategories.msg);}
		e.setClass(checker.ComedyCategories.label,ok);

	} else if (checker.UserType==9){
		// Filmmaker Extras
		m= getCheckCount("filmcats_container");
		ok= (m ==1);
		if (!ok) {e.add(checker.FilmCategories.msg);}
		e.setClass(checker.FilmCategories.label,ok);
	} else if (checker.UserType==7){
		// Band Extras
		m= getCheckCount("bandcats_container");
		ok= (m ==1);
		if (!ok) {e.add(checker.MusicGenres.msg);} // checker.MusicGenres.msg: "Please select 1 (one) Music Genre"
		e.setClass(checker.MusicGenres.label,ok); // checker.MusicGenres.label : "tdBandCategories"
	}
	
	
	h= document.getElementById(checker.IAgree.id);
	if (h){
		ok=h.checked;
		if (!ok) {e.add(checker.IAgree.msg, checker.IAgree.id);}
		e.setClass(checker.IAgree.label,ok);
	}

	e.show();
	
	ok= !e.hasErrors();
	if (ok){
		isOneClick= false;
		
		if(h){
			document.getElementById(checker.IAgree.id).form.submit();
		}
		else {
			document.getElementById(checker.Title.id).form.submit();
		}
	}
	return ok;
	// return false;
} // validateUpload

function initUpload(){
	/*
		document.metaForm.title.value = "";
		document.metaForm.description.value = "";
		document.metaForm.tags.value = "";
		resetInputs(document.metaForm.channels);
		resetInputs(document.termsForm.tos);
	*/
	document.getElementById(checker.Description.id).onkeyup= function(){
		showCharsRemaining(checker.Description.id,"chLeft",3000);
		};
	document.getElementById(checker.Title.id).onkeyup= function(){
		showCharsRemaining(checker.Title.id,"titleCharsLeft",64);
		};
	
} // initUpload



// -------------------------------------------------------------------------------
//	section: postloading function(s), generally wordbreaker
//	function: 
//	description: 
// -------------------------------------------------------------------------------
function loadDone(fuse){
	switch (fuse){
		case "Categories":
			wordBreaker.fixNested( "title", "H2", "A");
			wordBreaker.fixNested( "text", "div", "A");
			break;
			
		case "Channels":
			wordBreaker.fixNested( "title", "H2", "A");
			break;
			
		case "Home":
			wordBreaker.setMaxLength( 35 );
			wordBreaker.isPreserveBreaks = true;
			wordBreaker.isRewriteLinks = true;
			wordBreaker.fixByClass( "description", "div" );
			
			wordBreaker.setMaxLength( 18 );
			wordBreaker.isPreserveBreaks = false;
			wordBreaker.isRewriteLinks = false;
			wordBreaker.fixNested( "title", "h2", "a" );
			setSubNavSelected();
			break;
			
		case "MyFavorites":
			wordBreaker.fixNested( "title", "H2", "A");
			wordBreaker.fixNested( "text", "div", "A");
			break;
		case "MyVideos":
			wordBreaker.fixNested( "title", "H2", "A");
			wordBreaker.isPreserveBreaks = true;
			wordBreaker.setMaxLength( 35 );
			wordBreaker.addMoreLink("div", "description" );
			break;
		case "MySubscriptionsDetail":
		case "MySubscriptions":
			wordBreaker.fixNested( "title", "H2", "A");
			wordBreaker.fixNested( "text", "div", "A");
			// hit those in "sidebarnav"
			wordBreaker.fixNested( "sidebarnav", "div", "A");
			break;

		case "Search":
			// just like the header...
			wireSearch( Resources.search_default_text, "bodyq" );
			/* Prototype way */
			/*wireSearch = new WireSearch( Resources.search_default_text, "bodyq" );*/

			wordBreaker.isPreserveBreaks = true;
			wordBreaker.setMaxLength( 33 );
			wordBreaker.addMoreLink("div", "description" );
			break;

		case "ViewChannel":
			wordBreakerForChannel();
			break;
		case "VideoCharts":
			wordBreaker.fixNested( "title", "H2", "A");
			wordBreaker.fixNested( "text", "div", "A");
			break;
		case "ViewFavorites":
			wordBreaker.fixNested( "title", "H2", "A");
			break;
		case "ViewFriends":
			wordBreaker.fixNested( "title", "H2", "A");
			break;
		case "ViewSubscribers":
			wordBreaker.fixNested( "title", "H2", "A");
			break;
		case "ViewSubscriptions":
			wordBreaker.fixNested( "title", "H2", "A");
			break;
		case "ViewVideos":
			wordBreaker.fixNested( "title", "H2", "A");
			break;

		case "ViewVideo":
			var outStr = makePaging();
			document.getElementById( "PagingHeader" ).innerHTML = outStr;
			document.getElementById( "PagingFooter" ).innerHTML = outStr;
			
			wordBreaker.fixNested( "comment", "TD", "div" );
		
			var h=document.getElementById("vid_description");
			if (h){
				wordBreaker.isPreserveBreaks = true;
				wordBreaker.isRewriteLinks = true;
				wordBreaker.setMaxLength(25);
				h.innerHTML = "<strong>" + Resources.description +"</strong> &nbsp;"+ wordBreaker.fix(h.innerHTML);
			}
			moveToBottom("tblComments", "comment");
			break;


		default :
			alert("loadDone: default");
			break;
	}
}


// -------------------------------------------------------------------------------
//	section: View Videos 
//	function: 
//	description: 
// -------------------------------------------------------------------------------
function initViewVideo(){
	return false;
	document.getElementById("ajax_comment").onkeyup= 
		function(){
			showCharsRemaining("ajax_comment","ajax_comment_length",250);
		};
} // initViewVideo


function initViewChannel(){
	return false;
	document.getElementById("ajax_comment").onkeyup= 
		function(){
			showCharsRemaining("ajax_comment","ajax_comment_length",250);
		};
} // initViewChannel

function validateViewVideo(){
	if (!isOneClick) {return false;}
	var ok=true;
	var h= document.getElementById("ajax_comment");
	if (h){
		h.value = trim(h.value);
		if (h.value.length < 1){
			h.focus();
			alert( Resources.alert_commentempty);
			ok=false;
		}
	}
	return ok;
}

/*!--- ------------------------------------------------------------------------------------------------------------

		Let's figure the home's Selected sub nav...

!--- ------------------------------------------------------------------------------------------------------------ ---*/
// adds class="selected" to the anchor 
function setSubNavSelected(){
	var s = document.URL;
	var re=new RegExp("[&?]placement=(.+)(\\b|$)","gi");
	var m = s.match(re);
	var subnav= "all";
	if (m) {
		subnav= m[0].substring(m[0].lastIndexOf("=", m[0].length )+1); }
		
	var e = document.getElementById("nav_sub").getElementsByTagName("a");
	re=new RegExp("&placement="+subnav+"(\\b|$)","gi");
	for (var i =0; i < e.length; i++){
		s = e[i].getAttribute("href");
		if (s.match(re)){
			e[i].className= "selected";
		}
	}
}

/*!--- ------------------------------------------------------------------------------------------------------------

		misc Functions

!--- ------------------------------------------------------------------------------------------------------------ ---*/


/*!--- ------------------------------------------------------------------------------------------------------------

		Word Breaker for specific pages

!--- ------------------------------------------------------------------------------------------------------------ ---*/
/*
	function: wordBreakerVideoDescription
	does: ...
*/
function wordBreakerVideoDescription(){
	wordBreaker.setMaxLength( 22 );
	wordBreaker.addMoreLink("div", "description" );
}


function wordBreakerForChannel(){
	// wordBreaker.isDebug = true;
	
	// let's get MyInfo block:
	wordBreaker.isRewriteLinks = false;
	wordBreaker.isPreserveBreaks = false;
	wordBreaker.setMaxLength( 12 );
	wordBreaker.fixNested( "myinfo", "table", "h1");
	
	var h=document.getElementById("featuredvideotitle");
	if (h){
		h= h.getElementsByTagName("a");
		if (h) {h[0].innerHTML = wordBreaker.fix(h[0].innerHTML);}
	}
	// wordBreaker.fixById( "featuredvideotitle" );
	// wordBreaker.fixByTag( "h1" );
	
	// MySubscribers & MyFriends:
	wordBreaker.setMaxLength( 8 );
	wordBreaker.fixNested( "friendName", "H2", "a");
	wordBreaker.fixNested( "friend_name", "H2", "a");
	
	// MySubscriptions:
	wordBreaker.setMaxLength( 8 );
	wordBreaker.fixNested( "channel_name", "H2", "a");
	wordBreaker.fixNested( "channelName", "H2", "a");
	
	// MyFavorites & MyVideos:
	wordBreaker.fixNested( "title", "H2", "A"); // video title
	wordBreaker.fixNested( "text", "div", "A"); // user name

	// MyVideos & MyFeaturedVideo (description):
	// div class="description
	wordBreakerVideoDescription();
	
	// comments
	// wordBreaker.fixByClass( "friendName", "div" );
	wordBreakerDoComments();
	
}

function wordBreakerDoComments()
{
	// MyComments:
	wordBreaker.setMaxLength( 12 );
	wordBreaker.fixByClass( "friend_name", "A" ); // commenter's name
	wordBreaker.fixByClass( "friendName", "div" ); // newer format

	// comment body:
	wordBreaker.isRewriteLinks = true;
	wordBreaker.isPreserveBreaks = true;
	wordBreaker.setMaxLength( 35 );
	wordBreaker.fixNested( "comment", "td", "div");

	moveToBottom("tblComments", "comment");

}

function fl_start(){}
function fl_pause(){}
function fl_finish(){}
function fl_count(){}
function fl_init(){}

// peer to peer 
function onRedSwooshCompleted( success, handle ) {
	if( success ) { alert( 'Initialization succeeded, handle=' + handle ); }
	else { alert( 'Initialization failed, handle=' + handle ); }
}


Object.extend(Event, {
    /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */
	_domReady: function() {	
		if (arguments.callee.done) {return; }
		
		arguments.callee.done = true;

		if (Event._timer) {clearInterval(Event._timer);}

		Event._readyCallbacks.each(function(f) {f();});
		Event._readyCallbacks = null;
	},
	onReady: function(f) {	    
		if (!this._readyCallbacks) {
			var domReady = this._domReady;

			if (domReady.done){return f();}
			
     		if (document.addEventListener) {
                if (Prototype.Browser.WebKit) {
                  this._timer = window.setInterval(function() {
                    if (/loaded|complete/.test(document.readyState)) domReady(); }, 10);                    
                    Event.observe(window, "load", domReady);

                } else {                    
                    document.addEventListener("DOMContentLoaded", domReady, false);
                }

            } else {
                document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
                $("__onDOMContentLoaded").onreadystatechange = function() {
                  if (this.readyState == "complete") {
                    this.onreadystatechange = null;                    
                    domReady();
                  }
                };
            }
                    		
            
			Event._readyCallbacks = [];
		}
		Event._readyCallbacks.push(f);
	}
});



randomseed = Date.parse(new Date());



