﻿/*Form validation for registration
*/
var main_path='http://www.cliptricks.com/';
function validate(){
	var pass1=document.getElementsByName('pass')[1];
	var pass2=document.getElementsByName('pass2')[0];
	var valid=1;
	form=document.getElementsByName('register')[0];
	var collection;
	if((collection=document.getElementsByClassName('invalidField'))){
		for(var i=0;i<collection.length;i++){
			collection[i].parentNode.removeChild(collection[i]);
		}
	}
	if(form.user.value.length<=0){
		var holder=document.createElement('span');
		holder.className='invalidField';
		text=document.createTextNode('You must enter a username!');
		holder.appendChild(text);
		form.user.parentNode.appendChild(holder);
		valid=0;		
	}
	var age=parseInt(form.age.value);
	if(form.age.value.length<=0 || isNaN(age)){
		var holder=document.createElement('span');
		holder.className='invalidField';
		text=document.createTextNode('You must enter your age!');
		holder.appendChild(text);
		form.age.parentNode.appendChild(holder);
		valid=0;		
	}
	if(form.email.value.length<=0){
		var holder=document.createElement('span');
		holder.className='invalidField';
		text=document.createTextNode('You must enter an email!');
		holder.appendChild(text);
		form.email.parentNode.appendChild(holder);
		valid=0;		
	}else{
		var regExp=new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$");
		if(!form.email.value.match(regExp)){
			var holder=document.createElement('span');
			holder.className='invalidField';
			text=document.createTextNode('Invalid email!');
			holder.appendChild(text);
			form.email.parentNode.appendChild(holder);
			valid=0;
		}
	}
	var captcha=parseInt(form.captcha.value);	
	if(form.captcha.value.length!=4 || isNaN(captcha)){
		var holder=document.createElement('span');
		holder.className='invalidField';
		text=document.createTextNode('You must enter the numbers from the picture!');
		holder.appendChild(text);
		form.captcha.parentNode.appendChild(holder);
		valid=0;		
	}	
	if(pass1.value.length<=pass2.value.length){
		if(pass1.value!=pass2.value || pass1.value.length<=0){
			var holder=document.createElement('span');
			holder.className='invalidField';
			text=document.createTextNode('The two passwords don\'t match!');
			holder.appendChild(text);
			pass2.parentNode.appendChild(holder);
			valid=0;
		}
	}
	if(valid==1)document.getElementsByName('register')[0].submit();
}
/*toggleBlock(id) Show/hide an element
id - Id of Element to show/hide
*/
function toggleBlock(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
	  e.style.display = 'none';
   else{
	  e.style.display = 'block';
	  e.focus();
	}
}

/*set_active(page) Set the active page in paging
page - number of the page to activate
*/
var current_page=-1;
function set_active(page){
	page=parseInt(page);
	if(current_page>-1)document.getElementById("page_"+current_page).className="";
	document.getElementById("page_"+page).className="active";
	current_page=page;
}

/*rating_stars(star_num) - Change color of rating stars
star_num - the number of the stars to activate 
*/
function rating_stars(star_num){
	star_num=parseInt(star_num);
	if(star_num>=1 && star_num<=5){
		for(i=1;i<=star_num;i++){
			name="star_"+i;
			document.getElementById(name).style.background="transparent url("+main_path+"img/player_opt_star_active.jpg) no-repeat scroll 0%";
		}
	}	
}

//reset_starts() - Reset all stars colour
function reset_stars(){
	for(i=1;i<=5;i++){
		name="star_"+i;
		document.getElementById(name).style.background='transparent url('+main_path+'/img/player_opt_star.jpg) no-repeat scroll 0%';
	}
}

/*rate_video(id,vote,key) - Rate a video
id - clip_id for which the user rates
vote - how the clip was rated (1,2,3,4,5)
key - from php generated session key for validation
*/
function rate_video(id,vote,key){
	new Ajax.Updater('rate_text', main_path+'vote_favourite.php', { 
		method: 'post',
		parameters: {clip_id: id,key: key,vote: vote}
		});
}

/*add_favourite(id,key) - Add a clip to the users favourite list
id - clip_id which should be added to favourites
key - from php generated session key for validation 
*/
function add_favourite(id,key){
	new Ajax.Updater('toFavourites', main_path+'add_favourite.php', { 
		method: 'post',
		parameters: {add_id: id,key: key}
		});
}

/*delete_album(to_del) - Delete an album
to_del - album_id which should be deleted
*/
function delete_album(to_del){
	id=parseInt(to_del);
	new Ajax.Request(main_path+'ajax_album.php',{
		method: 'post',
		parameters: {del_id: id},
		onSuccess: function(transport){
			var obj=document.getElementById('album_'+id);
			//window.location='http://www.cliptricks.com/album.php';
			obj.parentNode.removeChild(obj);//Remove From albums list
			
			var collection=document.getElementsByName('select_options');//Remove from add to album lists
			end_loop:
			for(var i=0;i<collection.length;i++){
				for(var j=0;j<collection[i].childNodes.length;j++){
					if(collection[i].childNodes[j].value==id){
						collection[i].childNodes[j].parentNode.removeChild(collection[i].childNodes[j]);
						break end_loop;
					}
				}
			}
			
		}
	});
}

/*edit_album(album_id) - Edit an album name
album_id - The album_id which the users edits
*/
function edit_album(album_id){
	var element=document.getElementById("title_"+album_id);//Get the <a> element where the title is shown
	if(element.tagName!='DIV'){//Check if Edit box is already displayed
		var old_name=element.innerHTML;
		
		var wrapper=document.createElement('div');//Edit box wrapper
		
		try{//IE
			var input=document.createElement("<input type='text' name='new_name' value='"+old_name+"' />");
			var button=document.createElement("<input type='button' value='Done' class='editButton' onclick='finish_edit("+album_id+")' />");
		}catch(err){//FIREFOX
			var button=document.createElement('input');
			button.setAttribute('type','button');
			button.setAttribute('onclick','finish_edit('+album_id+');return true;');
			button.value='Done';
			button.className='editButton';
			var input=document.createElement('input');
			input.type='text';
			input.name='new_name';
			input.value=old_name;		
		}
		wrapper.id="title_"+album_id;//Set id of the edit box
	
		//alternative.href='#';
		//alternative.setAttribute('onClick','finish_edit('+album_id+');return false;');
		//alternative.innerHTML='Finish Edit';
		
		wrapper.appendChild(input);
		wrapper.appendChild(button);
		//wrapper.appendChild(alternative);
		
		element.parentNode.replaceChild(wrapper,element);//Replace <a> tag with the edit box
	}
}

/*finish_edit(album_id) - Send an ajax request to change the album name and hide edit box
album_id - The album id, which name will be changed
*/
function finish_edit(album_id){
	id=parseInt(album_id);
	var new_name=document.getElementsByName('new_name')[0].value;
	new Ajax.Request(main_path+'ajax_album.php',{
		method: 'post',
		parameters: {edit_album: id,name: new_name},
		onSuccess: function(transport){
			var element=document.getElementById("title_"+album_id);
			var link=document.createElement('a');
			link.id="title_"+album_id;
			link.setAttribute('href','view_album.php?id='+album_id);
			link.className='title';
			link.innerHTML=new_name;
			link.setAttribute('onclick','edit_album('+album_id+');return false;');
			element.parentNode.replaceChild(link,element);//Replace edit box with <a> tag with the new name
			//Change edited album in add to album list
			var collection=document.getElementsByName('select_options');
			end_loop:
			for(var i=0;i<collection.length;i++){
				for(var j=0;j<collection[i].childNodes.length;j++){
					if(collection[i].childNodes[j].value==album_id){
						collection[i].childNodes[j].innerHTML=new_name;
						break end_loop;
					}
				}
			}
			
		}
	});
}

/*add_album() - Create a new album
*/
function add_album(){
album=document.getElementById('album_title').value;
new Ajax.Request(main_path+'ajax_album.php',
  {
  //TODO if thereis an error show it using create_status_box()
    method:'post',
    parameters: {new_album: album},
    onSuccess: function(transport){
    	info=transport.responseText.split('#;#');
		id=parseInt(info[0]);
		if(!isNaN(id)){//If we don't have an id this means an error ocurred
			if(document.getElementById('error_1')){
				document.getElementById('list_albums').innerHTML="";
			}
			var html=document.getElementById('list_albums').innerHTML;
			var add=html+info[1];//Adding the new album to the list of albums
			document.getElementById('list_albums').innerHTML=add;
			
			var collection=document.getElementsByName('select_options');//Add the new album to the options list for the videos
			for(var i=0;i<collection.length;i++){
				var option=document.createElement('option');
				option.value=info[0];
				option.innerHTML=album;
				collection[i].appendChild(option);
			}
		}else{
		var element=create_status_box(2,info[1],info[2]);
		var content=document.getElementsByClassName('videoList')[0];
		if(!document.getElementsByClassName('message msgError')[0] && !document.getElementsByClassName('message msgSuccess')[0]){//Check if status box is already displayed
			content.insertBefore(element,content.firstChild);
		}else{//If status box is displayed replace it with the new one
			var replace=document.getElementsByClassName('message msgError')[0];
			if(replace){
				replace.parentNode.replaceChild(element,replace);
			}else{
				replace=document.getElementsByClassName('message msgSuccess')[0];
				replace.parentNode.replaceChild(element,replace);
			}
		}
		 
		} 
    },
    onFailure: function(){document.getElementById('status').innerHTML="There was an error! Please try again later!";}
  });
 }
 
 /*add_comment() - Add a comment for a video
 */
 function add_comment(){
	if(document.getElementById('writeComment').style.display!='none'){
		new Ajax.Request(main_path+'add_comment.php', {
  			parameters: $('form2').serialize(true),
  			onSuccess: function(transport){
				//Reset and hide comment box
				var form=document.getElementById('form2');
				form.comment.value='';//Reset for other comments
				form.captcha.value='';//Reset for other comments
				//Reload captcha image
				var imgSender=document.getElementById('captcha_img');
    			var imgsrc = imgSender.src;
    			var pos = imgsrc.indexOf("#") < 0 ? imgsrc.length : imgsrc.indexOf("#");
   				imgSender.src = imgsrc.substring(0, pos) + '#' + new Date();
   				
   				//Check status
   				info=transport.responseText.split('#;#');

   				if(parseInt(info[0])==1){//All ok add comment
					var holder=document.getElementById('videoComments');
					var commentBlock=document.createElement('div');
					var old_comments=document.getElementsByClassName('commentBlock');
					commentBlock.className='commentBlock';
					commentBlock.innerHTML=info[1];
					holder.insertBefore(commentBlock,holder.childNodes[0]);//Insert comment
					for(var i=0;i<holder.childNodes.length;i++){
						if(holder.childNodes[i].nodeType==1 && holder.childNodes[i].tagName=='P'){
							holder.childNodes[i].parentNode.removeChild(holder.childNodes[i]);
						}
					}
					
					if(old_comments.length>=5){
						for(var i=holder.childNodes.length-1;i>0;i--){//Remove last comment
							if(holder.childNodes[i].nodeType==1){
								holder.removeChild(holder.childNodes[i]);
								break;
							}
						}
					}
					if(old_comments.length==5){
						//Fix paging
						
						var collection=document.getElementsByClassName('paging p-bottom');
						if(collection.length<=0){
						//Construct paging
							var clip_id=document.getElementsByName('id');
							clip_id=parseInf(clip_id);
							var wrapper=document.createElement('div');
							wrapper.className='paging p-bottom';
							var page_1=document.createElement('a');
							var page_2=document.createElement('a');
	
							page_1.href='#';
							page_2.href='#';
							
							page_1.id='page_0'
							page_2.id='page_1';
							
							page_1.innerHTML='1';
							page_2.innerHTML='2';
							
							page_1.setAttribute('onclick','browse_comments('+clip_id+','+0+');set_active(0);return false;');
							page_2.setAttribute('onclick','browse_comments('+clip_id+','+15+');set_active(1);return false;');
							wrapper.appendChild(page_1);
							wrapper.appendChild(page_2);
							var playVideo=document.getElementById('playVideo');
							playVideo.insertBefore(wrapper,playVideo.lastChild.nextSibling);
						}
					}
				}else{//Display error message
					if(document.getElementsByClassName('message msgError').length<=0){//No error message has been displayed yet
						var element=create_status_box(2,'',info[1]);
						document.getElementById('videoComments').appendChild(element);
					}else{
						var element=create_status_box(2,'',info[1]);
						var box=document.getElementsByClassName('message msgError')[0];
						box.parentNode.replaceChild(element,box);
					}
				}
    		}
  		});
	}
 }
 function browse_comments(clip_id,ot,lang){
	new Ajax.Updater('videoComments', main_path+'ajax_comments.php', { 
		method: 'post',
		parameters: {clip_id: clip_id,ot: ot,lang: lang}
	}); 
 }
 /*add_to_album(clip_id) - Add a video to an album
 clip_id - Id of the clip 
 */
 function add_to_album(clip_id){
 	var album_id=document.getElementById('album_id_'+clip_id).value;
 	album_id=parseInt(album_id);
 	if(album_id!=0){//Check if user selected an album
	 	new Ajax.Request(main_path+'ajax_album.php',{
	 			method: 'post',
	 			parameters: {album_id: album_id,add_clip: clip_id},
	  			onSuccess: function(transport){
					info=transport.responseText.split(';');
					var element=create_status_box(info[0],info[1],info[2]);//Create a status box success/error, info[0]=1 - success,info[0]=2 - error,info[1]-text header,info[2]-paragraph text
					var content=document.getElementsByClassName('videoList')[0];
					if(!document.getElementsByClassName('message msgError')[0] && !document.getElementsByClassName('message msgSuccess')[0]){//Check if status box is already displayed
						content.insertBefore(element,content.firstChild);
					}else{//If status box is displayed replace it with the new one
						var replace=document.getElementsByClassName('message msgError')[0];
						if(replace){
							replace.parentNode.replaceChild(element,replace);
						}else{
							replace=document.getElementsByClassName('message msgSuccess')[0];
							replace.parentNode.replaceChild(element,replace);
						}
					}
	    		}
	 	});
 	}
 }
 
 /*create_status_box(type,sub,text) - Create a status box error/success, returns the status box as an element
 type - type of the status box - 1 success,2 error
 sub - text header
 text - paragraph text
 */
function create_status_box(type,sub,text){
/*
	<div class="message msgError">
		<h4>{t}You must login to see your personal album!{/t}</h4>
		<p>{t}In order to see this section you must first login. If you don't have an account yet you can register from{/t} <a href="register.php">{t}here{/t}.</a></p>
	</div>
*/
	var holder=document.createElement('div');
	var header=document.createElement('h4');
	type=parseInt(type);
	switch(type){
		case 1:holder.className='message msgSuccess';break;
		case 2:holder.className='message msgError';break;
		default: holder.className='message msgError';
	}
	header.innerHTML=sub;
	if(text!=''){
		var paragraph=document.createElement('p');
		paragraph.innerHTML=text;
		holder.appendChild(header);
		holder.appendChild(paragraph);
		
	}else{
		holder.appendChild(header);
	}
	
	return holder;
}