/**
 * tube.js
 * Copyright (c) 2010 Too Much Media LLC
 * http://www.toomuchmedia.org/licenses
 *
 * @copyright Too Much Media LLC
 * @authot Daniel Boland <dan.boland@toomuchmedia.com>
 * @version 1.0
 * @package TUBE
 *
*/
/*	$Id: tube.js,v 1.42 2010/03/04 14:51:38 encoder Exp $ */ 

	
	var show_errors = false;
	var build_available_reel_list=false;
	var build_current_reel_list=false;
	var video_data = Array();
	var video_count = 0;
	
	////////////////////////
	// Utility functions
	
	var elements = Array();
	
	function verifyLink(url, text) {
	  var confirmed = confirm(text);
	  if (confirmed) document.location.href = url;
	}
	
	function CheckAll(fname) {
	  mylist=document[fname];
	  len = mylist.elements.length;
	  var i=0;
	  for( i=0; i < len; i++) {
			mylist.elements[i].checked = 1;
	  }
	}
	function UncheckAll(fname) {
	  mylist=document[fname];
	  len = mylist.elements.length;
	  var i=0;
	  for( i=0; i < len; i++) {
			mylist.elements[i].checked = 0;
	  }
	}
	function InvertAll(fname) {
	  mylist=document[fname];
	  len = mylist.elements.length;
	  var i=0;
	  for( i=0; i < len; i++) {
	      if (mylist.elements[i].checked == 1){
					mylist.elements[i].checked = 0;
	      }else{
					mylist.elements[i].checked = 1;
	      }	
	  }
	}
	
	function Get_Query_String(ji) {
	  hu = window.location.search.substring(1);
	  gy = hu.split("&");
	  for (i=0;i<gy.length;i++) {
	    ft = gy[i].split("=");
	    if (ft[0] == ji) {
	      return ft[1];
	    }
	  }
	}
	
	function ShowHide(id, hidden) {
	  if((elements[id] && hidden) || (!elements[id] && !hidden)) {
	    document.getElementById(id).style.display = 'block';
	    elements[id] = !hidden;
	  }
	  else {
	    document.getElementById(id).style.display = 'none';
	    elements[id] = hidden;
	  }
	}
	
	function update_login(){
		var username = document.getElementById("login").value;
		new Ajax.Updater('login_options', 'ajax_data.php?function=ajax_admin_get_usernames&username='+username, { method: 'get' });
	}
	
	
	function set_login(username){
		document.getElementById("login").value = username;
		document.getElementById("login_options").innerHTML = '';
		document.getElementById("login_options").style.visibility = 'hidden';
	}
	
	function open_popup(url, name, width, height) {
	  window.open(url, name, 'width='+width+',height='+height+',scrollbars=yes,menubar=0,toolbar=0,location=0,personalbar=0,status=0,resizable=0');
	  return false;
	}
	
		//flip the disalbed state of a field
	function field_flip_disable(id, start_state) {
		
		if(start_state == undefined) {
			start_state = false;  //assume it is not be set to begin with
		}
		
		current_state = $("."+id).attr("disabled");
		
		if((current_state == 'true') || (current_state == undefined && start_state)) {
			new_state = 'false';
		}
		else {
			new_state = 'true';
		}
			
		$("."+id).attr("disabled", new_state); 
		
		return;
	}
	
	/////////////////
	// image rotator
	
	var images = new Array();
	var current = null;
	var timer = null;
	var time_out = 400;
	
	
	function StartRotateImages(tag_id, image_dir, max_images) {
	  
	  if(!tag_id || !image_dir || !max_images)
	    return;
	  
	  if(timer) //stop currently running timer
	    StopRotateImages();
	  
	  if(!images[tag_id]) {  //create new entry
	    images[tag_id] = new Array();
	    images[tag_id].current = 1;
	    images[tag_id].total = max_images;
	    images[tag_id].dir = image_dir;
	  }
	  
	  current = tag_id;
	  
	  timer = setTimeout("RotateImages()", time_out); 
	}
	
	function StopRotateImages() {
	  clearTimeout(timer);
	  timer = null;
	  current = null;
	}
	
	
	function RotateImages() {
	  
	  if(current) {
	    document.getElementById(current).src = images[current].dir + images[current].current + ".jpg";
	    
	    if(images[current].current >= images[current].total)
	      images[current].current = 1;
	    else
	      images[current].current += 1;
	
	    timer = setTimeout("RotateImages()", time_out); 
	  }
	  else  {  //can't rotate 'nothing'
	    StopRotateImages();
	  }
	}
	

		


	//called by jqueries ready event and anytime we change the html structure 
	function TubeStudio_init() {
			$(".ttip[title]").tooltip({ 
	      tip: '#tooltip', 
				position: 'top center',
	      offset: [-5, 10],
	      lazy: false, 
	      delay: 0 
	    });
	    
			// make all links with the 'rel' attribute open jquery tools overlays
		$("a[rel]").overlay({
			expose: 'black',
			onBeforeLoad: function() {
				var wrap = this.getContent().find(".contentWrap");
				wrap.load(this.getTrigger().attr("href"));
			}
		});
		
		
			//add css actions to our input boxes
		$(".option_boxes > .box_option").mouseover(function() { 
			$(this).addClass('box_option_mouseover');
		});
		$(".option_boxes > .box_option").mouseout(function() { 
			$(this).removeClass('box_option_mouseover');
		});
		$(".option_boxes > .box_option").click(function() { 
			$(".box_option").removeClass('box_option_active');
			$(this).addClass('box_option_active');
		});
	}


	/////////////////////////////////
	//TubeStudio Reel System code

	function register_video(video_id, title, thumb_path, state) {
		video_data[video_id] = {video_id: video_id, title: title, thumb_path: thumb_path, state: state};
	}
	
	function modifiy_video_state(name, video_id)  {
		if(video_data[video_id].state) {
			remove_from_reel(name, video_id);
		}
		else {
			
			$('#reelInstructions').hide();
			$('#currentReel').show();
			
			var start = $("#video_"+video_id+"_pl").position();  
			var end = $("#currentReel").position();
			
			$(document.body).append("<div class='reelSlide' id='clipSlide"+video_id+"' style='top: "+start.top+"px; left: "+start.left+"px;'><img src='"+SITE_URL+"thumbs/"+video_data[video_id].thumb_path+"160x120/sample.jpg' width='140' height='100' /></div>");
			
			$("#clipSlide"+video_id).animate({ 
        top: end.top,
        left: end.left
    		}, 750, function() {
    			$("#clipSlide"+video_id).remove();
    			add_to_reel(name, video_id);
    		}
     	);
			
		}
		return false;
	}
	
	function add_to_reel(name, video_id) {	
		$.ajax({
			type: "POST",
			url: SITE_URL+"process.php",
			data: "action=reel_add&ajax=1&name="+name+"&video_id="+video_id,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0] == 1) {
					video_data[video_id].state = 1;
						//add to display list
					$("#currentReel").append(write_reel_row(video_id, video_data[video_id].title, video_data[video_id].thumb_path)); 
					
					obj = $("#video_"+video_id+"_pl");
					if(obj) {
	    			obj.removeClass('removeClip');
			  		obj.addClass('removeClipHover');
						obj.removeClass('addClip');
				  	obj.removeClass('addClipHover');
				  }
				  video_count++;
				  CheckVisibleSideBar();
				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
	 	return false;
	}
	
	function remove_from_reel(name, video_id) {	
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"process.php",
			data: "action=reel_remove&ajax=1&name="+name+"&field=video_id&value="+video_id,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0] == 1) {
					$("#reelEntry"+ video_id).remove();
					video_data[video_id].state = 0;
					
					obj = $("#video_"+video_id+"_pl");
					if(obj) {
						obj.addClass('addClip');
					  obj.removeClass('addClipHover');
		    		obj.removeClass('removeClip');
				  	obj.removeClass('removeClipHover');
	    		}
					video_count--;
					CheckVisibleSideBar();
				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
	 	
	 	return false;
	}
		
	function LoadCurrentReel() {
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=load_current_reel&dump=xml",
			dataType: "xml",
			success: function(xml) {
				var response = $(xml).find('response').attr("status");
				
					//get the video count and see if we should show or hide side bar
				video_count = $(xml).find('response').attr("videos");							
				CheckVisibleSideBar();
			    
				if(response == "ok") {
					$(xml).find('video').each(function() {
						
						var video_id = $(this).find('video_id').text();
						var title = $(this).find('title').text();
						var thumb_path = $(this).find('thumb_path').text();
					
						$("#currentReel").append(write_reel_row(video_id, title, thumb_path));

					});
				}
			}
		});
				
				
	 	return false;
	}	
		
		
		//writes out reel entry where ever needed
	function write_reel_row(video_id, title, thumb_path) {
		
		return "<div class='reelEntry' id='reelEntry"+ video_id +"'>" +
	 					"<img src='"+SITE_URL+"thumbs/"+thumb_path+"/160x120/sample.jpg' />" +
	 					"<div id='text'>"+title+"</div>" +
	 					"<div id='action' onclick=\"remove_from_reel('default', '"+video_id+"', '"+title+"', '"+thumb_path+"');\">[remove]</div>" +
	 					"<div id='actionImg'> </div>" +
	 					"</div>";
		
	}
	
	function edit_reel_save(save_changes) {
		
		var new_name = $('#active_reel_name').val();
		var x_params = '';
		var action = "save";
		
		if(save_changes && active_reel_id) {
			x_params = "&id="+active_reel_id;
			action = "save_changes";
		}
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=my_reels&action="+action+"&new_name="+new_name+x_params,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0]) {
					if(active_reel_id != result[0]) {
						//we got a new element
						active_reel_id = result[0];
						$("#available_reels").append(write_available_reel_row(active_reel_id, new_name));
					}
					else {
						//lets update the name just in cae we had changed it
						$('#my_reel_'+active_reel_id+"_name").html(new_name);
					}

				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
	 	return false;
	}
	
	function edit_reel_remove_item(video_id) {
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"process.php",
			data: "action=reel_remove&ajax=1&name=default&field=video_id&value="+video_id,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0] == 1) {
					//$("#edit_reel_entry_"+ video_id).fadeOut(function()  { 
						$("#edit_reel_entry_"+ video_id).remove();
					//});
				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
		
	 	return false;
	}
	
	function edit_reel_delete(id) {
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=my_reels&action=delete&id="+id,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0] == 1) {
					$("#my_reel_"+id).fadeOut(function()  { 
						$("#my_reel_"+id).remove();
			    });
				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
	 	return false;
	}
	
	function edit_reel_clear(id) {
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=my_reels&action=clear&id="+id,
			success: function(msg) {
				var result = msg.split("|");
				if(result[0] == 1) {

				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
	 	});
	 	return false;
	}
		
	function edit_reel_clear_active_reel() {
	 	return false;
	}
	
	function edit_reel_load(id) {
					
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=my_reels&dump=xml&action=load&id="+id,
			dataType: "xml",
			success: function(xml) {
				var new_html = '';
				var response = $(xml).find('response').attr("status");
				
				if(response == "ok") {
					active_reel_id = id;
					$('#my_reel_'+active_reel_id+"_name").html($(xml).find('response').attr("name"));
					$(xml).find('video').each(function() {
						
						var video_id = $(this).find('video_id').text();
						var title = $(this).find('title').text();
						var thumb_path = $(this).find('thumb_path').text();
						var length = $(this).find('length').text();
						var min = Math.floor(length/60);
						var sec = length%60;
						if(min < 10) {
							min = "0"+min;
						}
						if(sec < 10) {
							sec = "0"+sec;
						}
						
						var length_str = min +':'+ sec;

						new_html += '<tr id="edit_reel_entry_'+video_id+'"><td style="padding: 1px 0pt 0pt;"><table width="100%"><tr>';
						new_html += '<td width="30" aligh="center" rowspan="2"><img src="'+SITE_URL+'thumbs/'+thumb_path+'/160x120/sample.jpg" width="30" height="30"></td>';
						new_html += '<td class="style5" style="margin-top: 5px; font-size: 10pt; font-weight: normal;">'+title+'</td>';
						new_html += '<td width="30" aligh="center" rowspan="2"><img src="'+SITE_URL+'tube_images/trash_16.gif" class="ttip" title="Remove Clip" border="0" onclick="edit_reel_remove_item('+video_id+');"></td>';
						new_html += '</tr><tr><td>'+length_str+' min</td></tr></table></td></tr>';
												
					});
					
					$("#current_video_list").html("<table>"+new_html+"</table>");
						
				}
				else {
					if(show_errors) {
						alert("Error: " +result[1]);
					}
				}
			}
		});
				
				
	 	return false;
	}		
	
	function write_available_reel_row(reel_id, name) {
		
		var output = '';
				
		output += '<tr id="my_reel_'+reel_id+'">';
		output += '<td id="my_reel_'+reel_id+'_name" style="width:100px;">'+name+'</td>';
		output += '<td>';
		output += '<a href="'+SITE_URL+'pages/play_reel/?id='+reel_id+'"><img src="'+SITE_URL+'tube_images/videotrack_16.gif" class="ttip" title="Play Reel" border="0" /></a>';
		output += '<img src="'+SITE_URL+'tube_images/pen_16.gif" class="ttip" title="Load Reel" border="0" style="cursor:pointer;" onclick="edit_reel_load('+reel_id+')" />';
		output += '<img src="'+SITE_URL+'tube_images/delete_table_16.gif" class="ttip" title="Clear Reel" border="0" style="cursor:pointer;" onclick="edit_reel_clear('+reel_id+')" />';
		output += '<img src="'+SITE_URL+'tube_images/trash_16.gif" class="ttip" title="Delete Reel" border="0" style="cursor:pointer;" onclick="edit_reel_delete('+reel_id+')" />';
		output += '</td>';
		output += '</tr>';
										
		return output;
	}	

	
		//check which side bar should be active
	function CheckVisibleSideBar() {
	  if(video_count > 0) {
			$('#reelInstructions').hide();
			$('#currentReel').show();
		}
		else {
			$('#reelInstructions').show();
			$('#currentReel').hide();
		}
	}
	 
		//called by onready any anytime we change the html structure and need to re-run this code.
	function TubeSite_init() {
		$(".ttip[title]").tooltip({ 
      tip: '#tooltip', 
			position: 'top center',
      offset: [-5, 10],
      lazy: false,
      delay: 0 
    });
  	
  		//lets output intitial reel for side display
  	if(build_current_reel_list) {
			LoadCurrentReel();
		}
		
		
			//lets build the available reel list (if we want it)
		if(build_available_reel_list) {
			$.each(my_reel_list, function(index, entry) {
				$("#available_reels").append(write_available_reel_row(entry.reel_id, entry.name));
			});
		}
		
			//add action functions for video list elements
	  $('.reelAction').click(function(){
	    var obj_id = this.id.split("_");
	    
			modifiy_video_state('default', obj_id[1]);
	    
	  }).mouseover(function() {
	  	
	  	var obj_id = this.id.split("_");
	  	
	  	if(video_data[obj_id[1]].state) {
	  		$(this).addClass('removeClipHover');
	    	$(this).removeClass('removeClip');
		  	$(this).removeClass('addClipHover');
		    $(this).removeClass('addClip');
	  	}
	  	else {
		  	$(this).addClass('addClipHover');
		    $(this).removeClass('addClip');
	  		$(this).removeClass('removeClipHover');
	    	$(this).removeClass('removeClip');
	  	}
	  }).mouseout(function() {
	  	
	    var obj_id = this.id.split("_");
	    
	  	if(video_data[obj_id[1]].state) {
	    	$(this).addClass('removeClip');
	  		$(this).removeClass('removeClipHover');
		  	$(this).removeClass('addClipHover');
		    $(this).removeClass('addClip');
	  	}
	  	else {
		    $(this).addClass('addClip');
		  	$(this).removeClass('addClipHover');
	  		$(this).removeClass('removeClipHover');
	    	$(this).removeClass('removeClip');
	  	}
	  	
	  });
		return;
	}
   
	function refresh_related_videos(video_id, start, count, tpl, html_id) {
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=refresh_related_videos&video_id="+video_id+"&start="+start+"&count="+count+"&tpl="+tpl,
			success: function(response) {
				$("#"+html_id).html(response);
			}
		});

		return false;
	}

      
	function refresh_video_list(start, count, order, tpl, html_id) {
		$.ajax({
			type: "POST",
			url: SITE_URL+"index.php",
			data: "ajax=refresh_video_list&order="+order+"&start="+start+"&count="+count+"&tpl="+tpl,
			success: function(response) {
				$("#"+html_id).html(response);
			}
		});

		return false;
	}
  
     
	///////////////////////////////////////////
	//TubeStudio Miscellaneous Site Functions

	function rate_video(img_id, video_id, rating, new_img) {
		
		$.ajax({
			type: "POST",
			url: SITE_URL+"process.php",
			data: "action=rating_add&ajax=1&video_id="+video_id+"&rating="+rating,
			success: function(response) {
				orig_star_img = new_img;
				$("#"+img_id).attr("src", new_img);
				return false;
			}
		});
		
		return false;  //return false so link does not get followed
	}
	
	var orig_star_img='';
	function stars_mouseover(img_id, new_img) {
		orig_star_img = $("#"+img_id).attr("src");
		$("#"+img_id).attr("src", new_img);
		return false;
	}
	
	function stars_mouseout(img_id) {
		$("#"+img_id).attr("src", orig_star_img);
		return false;
	}
	
	///////////////////////////////////////////
	//TubeStudio Miscellaneous Admin Functions
	
	
	
	function quick_edit(video_id) {
		
		$('#video_edit_'+video_id).show();
		$('#video_view_'+video_id).hide();
		
		return false;  //return false so link does not get followed
	}
	
	function quick_edit_cancel(video_id) {
		
		$('#video_edit_'+video_id).hide();
		$('#video_view_'+video_id).show();
		
		return false;  //return false so link does not get followed
	}
	function quick_edit_save(video_id) {
		
		var update_query = ''; 
		
		title = $("title_edit_"+video_id).val();
		if(title) { //can't be blank
			update_query += "&video[title]="+title;
		}
		
		description = $("description_edit_"+video_id).val();
		update_query += "&video[description]="+description;
		
		channel_id = $("channel_id_edit_"+video_id).val();
		update_query += "&video[channel_id]="+channel_id;
		
		date_active = $("date_active_edit_"+video_id).val();
		update_query += "&video[date_active]="+date_active;
		
		$.ajax({
			type: "POST",
			url: "ajax_data.php",
			data: "function=ajax_admin_update_video&&video_id="+video_id+update_query,
			success: function(response) {
				
				
				
				$('#video_edit_'+video_id).hide();
				$('#video_view_'+video_id).show();
				return false;
			}
		});
		
		return false;  //return false so link does not get followed
	}