var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') { // Remove spaces between equal signs
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1'); // Remove spaces between equal signs
  }
};

/*player*/
var Player = { 
	initialize:function() {
	},
	
	getFullDims:function(){
		var scale = ".90"
		var correct = "10"
		var pHeight;
		var pWidth;

		if( window.innerWidth >= window.innerHeight ){
			pHeight = (window.innerHeight);
			pWidth = (window.innerHeight*(1.2121));
		} else {
			pHeight = (window.innerWidth*(1.2121));
			pWidth = (window.innerWidth);
		}

		return [pWidth*scale,pHeight*scale,15]
	}
	
}
/*end player*/

/* thumbs browser */
var activeTab='tabDefault';
var num_pages;
var xshowDetail;
var sliding = false;

var Browser = { 
	initialize:function() {
	},
	
	tabbing:function(tabId){
		$(activeTab).removeClassName('active');
		$(tabId).addClassName('tabContainer active');
		activeTab = tabId;
		if ( $(tabId).id == 'upload_tab' || $(tabId).id == 'sponsor_me' ) {
			var nav_message = "Click <a href=\"/upload\">here</a> to upload your video.";
		} else {
			var nav_message = "";
		}
		$('nav_message').innerHTML = nav_message;
	},
	slide:function( right ){
		var duration = 0.8;
		
		if( !right ){
			new Effect.Move('for_delete', 
				{ x: $('for_delete').offsetWidth, y: 0, duration: duration, mode: 'relative',queue:'',afterFinish:function(){ $('for_delete').remove(); }});
			new Effect.Move('cur_active', 
				{ x: $('cur_active').offsetWidth, y: 0, duration: duration, mode: 'relative',queue:'',afterFinish:function(){sliding = false; } });
		} else {
			new Effect.Move('for_delete', 
				{ x: -$('for_delete').offsetWidth, y: 0, duration: duration, mode: 'relative',queue:'',afterFinish:function(){ $('for_delete').remove(); }});
			new Effect.Move('cur_active', 
				{ x: -$('cur_active').offsetWidth, y: 0, duration: duration, mode: 'relative',queue:'',afterFinish:function(){sliding = false; } });
		}
		
		this.controlArrows();
	},
	
	setNumPages:function( inNumPages ){
		num_pages = inNumPages
		Browser.controlArrows();
	},
	
	controlArrows:function(){
		if( num_pages != 0){ 
			if( $('browserArrowLeft') ){
				if( cur_page == 1 ){
					$('browserArrowLeft').style.display = 'none';
					$('browserArrowLeftDis').style.display = 'inline';
				} else if( cur_page > 1 ){
					$('browserArrowLeft').style.display = 'inline';
					$('browserArrowLeftDis').style.display = 'none';
				}
			}

			if( $('browserArrowRight') ){
				if( cur_page == num_pages ){
					$('browserArrowRight').style.display = 'none';
					$('browserArrowRightDis').style.display = 'inline';
				} else if( cur_page < num_pages ){
					$('browserArrowRight').style.display = 'inline';
					$('browserArrowRightDis').style.display = 'none';
				}
			}
		}
		else {
			$('browserArrowLeft').style.display = 'none';
			$('browserArrowLeftDis').style.display = 'inline';
			$('browserArrowRight').style.display = 'none';
			$('browserArrowRightDis').style.display = 'inline';
		}
	},
	
	insertBrowserContainer:function( prev ){
		$('cur_active').setAttribute( 'id', 'for_delete' ); 
		currentDivContainer = "cur_active";
		var newDiv = document.createElement( "div" );
		newDiv.setAttribute( 'id',currentDivContainer );
		$('slider_main').appendChild( newDiv );

		if( prev ){
			$(currentDivContainer).style.left = $(currentDivContainer).offsetWidth + "px";
		} else {
			$(currentDivContainer).style.left = -$(currentDivContainer).offsetWidth + "px";
		}
	}
}

function set_current_link(current) {
	$('two_link').style.display = "inline";
	$('four_link').style.display = "inline";
	$('twelve_link').style.display = "inline";
	
	$('two_nolink').style.display = "none";
	$('four_nolink').style.display = "none";
	$('twelve_nolink').style.display = "none";
		
	if (current == 2) { $('two_link').style.display="none"; $('two_nolink').style.display="inline"; }
	if (current == 4) { $('four_link').style.display="none"; $('four_nolink').style.display="inline"; }
	if (current == 12) { $('twelve_link').style.display="none"; $('twelve_nolink').style.display="inline"; }
	
	return false;
}
/*end thumbs brower*/

var playlistArray = new Array();
var playlist = Class.create();
playlist.prototype = {
	init: null,
	playListHead: null,
	lastPlayListHead: null,
	playListEnd: null,
	
	right_col_container: null,
	
	initialize: function() {
		this.playListHead = -1;
		this.lastPlayListHead = 0;
		this.playListEnd = false;
		this.init = true;
	},
	
	add:function( video_id, makeNowPlaying ){
		if( $('playlist_help') ){
			$('playlist_help').remove();
		}
		
		if( makeNowPlaying ){
			//replace top element
			playlistArray.splice( 0, 1, images[video_id] );
			
			//remove the div
			if( $('playlistItemContainer0') ){
				$('playlistItemContainer0').remove();
			}
			
			//add the new div
			this.updatePlaylist( 0, true );
		} else {
			playlistArray.push( images[video_id] );
			
			this.updatePlaylist( playlistArray.length-1, false );
		}
		if ( this.right_col_container ) {
			this.right_col_container.event( 'playlist.add' );
		}
		
		//set the playlist navigation
		this.setPrevNext();
		
		this.setCookieArray();

		this.adjustScrollClass();
	},
	setCookieArray:function(){
		var tArray = new Array();
		
		for (var index = 0; index < playlistArray.length; index++ ) {
			tArray.push( playlistArray[index].video_id );
		}
		var joined = tArray.join( "," );
		
		Cookie.set( 'playlist', joined );
	},
	remove:function(id){
		right_col_container.playlist.expand();
		
		//delete from array
		playlistArray.splice( id, 1 );
		
		if( this.playListHead == id ){
			this.playListHead--;
			this.playNextVideo( false );
		} else if ( this.playListHead >= id ){
			this.playListHead--;
		} 
		
		//redraw the entire playlist
		this.updatePlaylistReDraw();
		
		//set the playlist navigation
		this.setPrevNext();
		
		
		this.setCookieArray();
	},
	adjustScrollClass:function() {
		if (playlistArray.length >= 5) {
			var scrolling = true;
		}
		else {
			var scrolling = false;
		}
		
		for (i=0; i<playlistArray.length; i++) {
			if (scrolling) {
				$("playlistItemContainer"+i).addClassName("scrolling");
				$("playlistItem"+i).addClassName("scrolling");
			} else {
				$("playlistItemContainer"+i).removeClassName("scrolling");
				$("playlistItem"+i).removeClassName("scrolling");
			}
		}
		
	},
	setPrevNext:function(){
		if( playlistArray.length == 0 ){
			$('playPrev').style.visibility = "hidden";
			$('playAll').style.visibility = "hidden";
			$('playNext').style.visibility = "hidden";
			
		} else if( playlistArray.length == 1 ){
			$('playPrev').style.visibility = "hidden";
			$('playNext').style.visibility = "hidden";
			$('playAll').style.visibility = "visible";
			
		} else if( playlistArray.length > 1 ){
			if( this.playListHead < (playlistArray.length-1) ){
				$('playNext').style.visibility = "visible";
			} else if( this.playListEnd ){
				$('playNext').style.visibility = "hidden";
			} else {
				$('playNext').style.visibility = "hidden";
			}
			
			if( this.playListHead <= 0 ){
				$('playPrev').style.visibility = "hidden";
			} else {
				$('playPrev').style.visibility = "visible";
			}
		} 
	},
	getNextVisibility:function(){
		if ( playlistArray.length > 1 && this.playListHead < (playlistArray.length-1) ) {
			return "true";
		} else {
			return "false";
		}
	},
	
	getPrevVisibility:function(){
		if ( playlistArray.length > 1 && this.playListHead != 0 ) {
			return "true";
		} else {
			return "false";
		}
	},	
	
	playing: function() {
		return ( !this.playListEnd && this.playListHead != -1 );
	},
	
	getDivHTML:function( i, nowPlaying, opts ){
		if ( !opts ) { opts = {} };
		var newplaylist = "";
		var counter = i + 1;
		
		if( typeof( this.playListHead ) == "undefined" || i == this.playListHead ){
			newplaylist+="<div id='playlistItemContainer" + i + "' class='playlistItemContainer'><div id='playlistItem" + i + "' class='playlistItem playlist_selected'>";
		}
		else {
			newplaylist+="<div id='playlistItemContainer" + i + "' class='playlistItemContainer'><div id='playlistItem" + i + "' class='playlistItem'>";
		}
		
		//counter
		if ( !opts.onclicksDisabled ) {
			newplaylist+="<a href='#' onclick='playlist.playAll( " + i + "); return false;'>"
		} else {
			newplaylist+="<a href='#' onclick='return false;'>";
		}
		newplaylist+="<div class='linked_playlist_container counter'><div class='counter'>"+(counter)+"</div></div>";
		newplaylist+="</a>"
		
		//image
		if ( !opts.onclicksDisabled ) {
			newplaylist+="<a href='#' onclick='playlist.playAll( " + i + "); return false;'>";
		} else {
			newplaylist+="<a href='#' onclick='return false;'>";
		}
		newplaylist+="<div class='linked_playlist_container video_image'>";
		newplaylist+=playlistArray[i]['file'];
		newplaylist+="</div></a>";				
		
		//meta
		if ( !opts.onclicksDisabled ) {
		newplaylist+="<div class='linked_playlist_container playlist_meta' onclick='if (!ob.leaving_page) { playlist.playAll( " + i + "); }'>";
		} else {
		newplaylist+="<div class='linked_playlist_container playlist_meta'>";
		}
		
		if( nowPlaying ){
			newplaylist+="<div id='nowPlaying" + i + "' class='nowPlaying' style='display:inline;'>NOW PLAYING</div>";
		} else {
			newplaylist+="<div id='nowPlaying" + i + "' class='nowPlaying' style='display:none;'></div>";
		}
		
		var detail_link = "<a href='" + playlistArray[i]['detail_link'] + "' onclick='ob.leaving_page = true;'>" 
												+ playlistArray[i]['title'] + "</a>"
		newplaylist+="<div class='video_title'>"+detail_link+"</div>";
		
		if (playlistArray[i]['user']) {
			newplaylist+="<div class='meta'>From: "+playlistArray[i]['user']+"</div>";
		}
	
		newplaylist+="<div class='meta'>"+playlistArray[i]['dur']+"</div>";
		newplaylist+="</div>"
		
		//trash
		newplaylist+="<span id='trash" + i + "' class='trash' onmousedown='playlist.remove("+i+")'><img src='/images/trash.gif'></span>";
		
		newplaylist+="</div></div><div class='clear_both'></div>";
		
		return newplaylist;
	},
	
	updatePlaylist:function( i, nowPlaying ){

		var newplaylist = this.getDivHTML( i, nowPlaying );
		
		var playlistItemContainer = Builder.node( 'div', { 'class':'outer_playlistItemContainer' }, '' );
		playlistItemContainer.innerHTML = newplaylist;
		
		if( nowPlaying && $( 'playlistItemContainer1' ) ){
			var parentDiv = $( 'playlistItemContainer1' ).parentNode;
			parentDiv.insertBefore( playlistItemContainer, $( 'playlistItemContainer1' ) );
			
		} else {
			$('playlist').appendChild( playlistItemContainer );
		}
		
	},
	
	updatePlaylistOneVideo: function() {
		headToUse = this.playListHead;
		if ( !playlistArray[headToUse] ) {
			headToUse = this.lastPlayListHead;
		}
		if( playlistArray[headToUse] ){
			$('playlist').update(
				this.getDivHTML(
					headToUse, this.playing(), { onclicksDisabled: true }
				)
			);
		}
	},
	
	updatePlaylistReDraw:function(){
		newplaylist="";
		for(i=0;i<playlistArray.length;i++){
			if( playlistArray[i] ){
				if( this.playListHead == i ){
					newplaylist += this.getDivHTML( i, true );
				} else {
					newplaylist += this.getDivHTML( i, false );
				}
			} 
		}
		$('playlist').update(newplaylist);
		this.adjustScrollClass();
	},
	
	buildImagesArray:function( video_id, title, username, dur, image_url, detail_link ){
		var images = Array();
		images["file"] = image_url;
		images["title"] = title;
		images["user"] = username;
		images["dur"] = dur;
		images["video_id"] = video_id;
		images["detail_link"] = detail_link;
		return images;
	},
	
	playAll:function( inPlayListHead ){
		this.init = false;
		
		if( inPlayListHead >= 0 ){
			this.movePlayHead( inPlayListHead, null, false );
		} else{
			this.movePlayHead( 0, null, true );
		}
		
		this.playNextVideo( true );
	},
	
	movePlayHead:function( set, inc, scroll ){
		this.lastPlayListHead = this.playListHead;
		
		//unstyle the last played				
		if( $( 'playlistItem' + (this.lastPlayListHead) ) ){
			if (playlistArray.length >= 5) {
				$( 'playlistItem' + (this.lastPlayListHead) ).className = 'playlistItem scrolling';
			}
			else {
				$( 'playlistItem' + (this.lastPlayListHead) ).className = 'playlistItem';
			}
			$('nowPlaying' + (this.lastPlayListHead) ).innerHTML = "";
		}
		
		if( set != null ){
			this.playListHead = set;
		}
		
		if( inc != null ){
			if( (this.playListHead-1) >= 0 && inc < 0 ){
				this.playListHead += inc;
			} else if( this.playListHead < (playlistArray.length) && inc > 0 ) {
				this.playListHead += inc;
			} 
		}
		
		//restyle the div
		if( $( 'playlistItem' + (this.playListHead) ) ){
			if (playlistArray.length >= 5) {
				$( 'playlistItem' + (this.playListHead) ).className = 'playlistItem scrolling playlist_selected';
			}
			else {
				$( 'playlistItem' + (this.playListHead) ).className = 'playlistItem playlist_selected';
			}
			
			$('nowPlaying' + (this.playListHead) ).innerHTML = "NOW PLAYING";
			$('nowPlaying' + (this.playListHead) ).style.display = "inline";
		}
		
		//scoll the div
		if( scroll ){
			$('playlist').scrollTop = (62)*this.playListHead;
		}
		
		if( this.playListHead >= playlistArray.length ){
			this.playListEnd = true;
		} else {
			this.playListEnd = false;
		}
		
		this.setPrevNext();
	},
	
	playPrevVideo:function(){
		this.movePlayHead( null, -1, true );
		this.playVideo();
	},
	
	playNextVideo:function( dontMoveHead ) {
		if ( right_col_container.okToPlayNextVideo() ) {
			if( !dontMoveHead && !this.init ){
				this.movePlayHead( null, 1, true );
			} 
			
			this.playVideo();
		}
	},
	
	playVideo:function(){
		if( this.playListEnd || this.init ){
			thisMovie( 'diversionplayer' ).SetVariable( 'vidID', "-1" );
			thisMovie( 'diversionplayer' ).SetVariable( 'showLogo', "true" );
			
			return;
		} 
		if( playlistArray[ this.playListHead ] != undefined ){
			var video_id = playlistArray[ this.playListHead ]['video_id'];
			if( video_id != undefined ){
				playmovieByID( video_id );
			}
		}
	}
};

/*lets build our own accordion*/
var accordion = Class.create();
accordion.prototype = {
	container:new Array(),
	effects:new Array(),
	lastExpanded:0,
	lastExpandedObject:0,
	initialize: function() {
		var panels = this._getDirectChildrenByTag($('accordionContainer'), 'DIV');
		for ( var i = 0 ; i < panels.length ; i++ ){
			var tabChildren = this._getDirectChildrenByTag(panels[i],'DIV');
			if ( tabChildren.length != 2 ){continue; }
			tabChildren[0].i=this.container.length;
			tabChildren[0].accordion=this;
			this.container.push(tabChildren[1]);
			tabChildren[0].onclick=function(){this.accordion.toggle(this.i);}
      }
	},
	add:function(object){
		this.container.push(object);
	},
	toggle:function(nr){
			if(this.lastExpanded!=nr){
				Effect.BlindDown(this.container[nr],{queue:'accordionDown'});
				this.lastExpandedObject = Effect.BlindUp(this.container[this.lastExpanded],{queue:'accordionUp'});
				this.lastExpanded=nr;
			}
	},
   _getDirectChildrenByTag: function(e, tagName) {
      var kids = new Array();
      var allKids = e.childNodes;
      for( var i = 0 ; i < allKids.length ; i++ )
         if ( allKids[i] && allKids[i].tagName && allKids[i].tagName == tagName )
            kids.push(allKids[i]);
      return kids;
   }
}

var messageboard = Class.create();
messageboard.prototype = {
	expanded: false,
	inSizeTransition: false,
	owner: null,
	initialize: function( owner ) {
		this.owner = owner;
		mb_header = _childWithClass( $('messageboardContainer'), 'header' );
		mb_header.messageboard = this;
		mb_header.onclick = function() { this.messageboard.toggleExpand(); }
	},
	collapse: function() {
		if ( this.expanded && !this.inSizeTransition ) {
			this.expanded = false;
			this.inSizeTransition = true;
			// mostly copied from effects.js
			afi_func = function( effect ) {
				effect.element.hide();
				effect.element.undoClipping();
				right_col_container.event( 'messageboard.inSizeTransitionEnd' );
			};
			Effect.BlindUp( 'messageboard', { afterFinishInternal: afi_func } );
			this.owner.event( 'messageboard.collapse' );
		}
	},
	expand: function() {
		if ( !this.expanded && !this.inSizeTransition ) {
			this.expanded = true;
			this.inSizeTransition = true;
			// mostly copied from effects.js
			afi_func = function( effect ) {
				effect.element.undoClipping();
				right_col_container.event( 'messageboard.inSizeTransitionEnd' );
			};
			Effect.BlindDown( 'messageboard', { afterFinishInternal: afi_func } );
			this.owner.event( 'messageboard.expand' );
		}
	},
	reloadMessages: function( video_id ) {
		new Effect.Fade( 'messageboardInner', { duration: 0 } );
		new Ajax.Updater(
			'messageboardInner', '/video/comments/' + video_id,
			{ asynchronous: true, evalScripts: true,
			  onComplete: function( request ) {
					new Effect.Appear( 'messageboardInner', { duration: 0.5 } )
				}
			}
		);
	},
	reset_inputs: function() {
		if ( $('comment_box').value == "Your comment here" ) {
			$('comment_box').value = '';
		}
	},
	toggleExpand: function() {
		if ( this.expanded ) {
			this.collapse();
		} else {
			this.expand();
		}
	}
}

var playlist_container = Class.create();
playlist_container.prototype = {
	expanded: true,
	inSizeTransition: false,
	owner: null,
	scaleDownRatio: 22,
	scaleUpRatio: 455,
	waitingToPlay: false,
	initialize: function( owner ) {
		this.owner = owner;
		pl_header = $('playlist_header');
		pl_header.playlist = this;
		pl_header.onclick = function() { this.playlist.toggleExpand(); }
		if ( browser_safari() ) {
			this.scaleDownRatio = 26;
			this.scaleUpRatio = 385;
		}
	},	
	collapse: function() {
		if ( this.expanded && !this.inSizeTransition ) {
			this.expanded = false;
			this.inSizeTransition = true;
			afi_func = function( effect ) {
				right_col_container.event( 'playlist_container.inSizeTransitionEnd' );
				playlist.updatePlaylistOneVideo();
			};
			new Effect.Scale(
				'playlist', this.scaleDownRatio,
				{ scaleX: false, scaleContent: false, afterFinishInternal: afi_func, scaleMode: { originalHeight: 305, originalWidth: 334 } }
			);
			Effect.BlindUp( 'playlist_controls' );
			$('playlist_header').style.borderWidth = "0px 0px 1px 1px";
			this.owner.event( 'playlist_container.collapse' );
		}
	},
	expand: function() {
		if ( !this.expanded && !this.inSizeTransition ) {
			this.expanded = true;
			this.inSizeTransition = true;
			afi_func = function( effect ) {
				right_col_container.event( 'playlist_container.inSizeTransitionEnd' );
			};
			new Effect.Scale(
				'playlist', this.scaleUpRatio,
				{ scaleX: false, scaleContent: false, afterFinishInternal: afi_func }
			);
			if ( this.waitingToPlay ) {
				playlist.playNextVideo();
				this.waitingToPlay = false;
			}
			Effect.BlindDown( 'playlist_controls' );
			$('playlist_header').style.borderWidth = "0px 0px 0px 1px";
			playlist.updatePlaylistReDraw();
			this.owner.event( 'playlist_container.expand' );
		}
	},
	okToPlayNextVideo: function() {
		if ( this.expanded ) {
			return true;
		} else {
			return false;
		}
	},
	toggleExpand: function() {
		if ( this.expanded ) {
			this.collapse();
		} else {
			this.expand();
		}
	}
}

var right_col_container = Class.create();
right_col_container.prototype = {
	dashboard: null,
	messageboard: null,
	playlist: null,
	initialize: function() {
		this.messageboard = new messageboard( this );
		this.playlist = new playlist_container( this );
		this.dashboard = new dashboard( { owner: this } );
	},
	event: function( event_name ) {
		if ( event_name == 'messageboard.collapse' ) {
			this.playlist.expand();
		} else if ( event_name == 'messageboard.expand' ) {
			this.playlist.collapse();
		} else if ( event_name == 'messageboard.inSizeTransitionEnd' ) {
			this.messageboard.inSizeTransition = false;
		} else if ( event_name == 'playlist.add' ) {
			this.playlist.expand();
		} else if ( event_name == 'playlist_container.collapse' ) {
			this.messageboard.expand();
		} else if ( event_name == 'playlist_container.expand' ) {
			this.messageboard.collapse();
		} else if ( event_name == 'playlist_container.inSizeTransitionEnd' ) {
			this.playlist.inSizeTransition = false;
		}
	},
	okToPlayNextVideo: function() {
		ok = this.playlist.okToPlayNextVideo();
		if ( !ok ) {
			this.playlist.waitingToPlay = true;
		}
		return ok;
	},
	reloadMessages: function( video_id ) {
		this.messageboard.reloadMessages( video_id );
	},
	resetMessageCount: function( num ) {
		this.messageboard.resetMessageCount( num );
	},
	resetMessageboardInner: function() {
		this.messageboard.resetMessageboardInner();
	}
}

function _childWithClass( elt, className ) {
	var kids = new Array();
		var allKids = elt.childNodes;
		for( var i = 0 ; i < allKids.length ; i++ )
			 if ( allKids[i] && allKids[i].tagName && allKids[i].className == className )
					kids.push(allKids[i]);
		return kids[0];
}

function moveHoverText(event){
		var pointer = [Event.pointerX(event),Event.pointerY(event)];
		if ($('hoverText')!=undefined) {
			$('hoverText').style.left = (pointer[0] + 20) + "px";
			$('hoverText').style.top = pointer[1] + "px";
			$('hoverText').style.display = "inline";
		}
}

function browser_safari() {
	return ( navigator.userAgent.indexOf( 'AppleWebKit/' ) != -1 );
}
