	/* Subfilters (per day/week...) */
	function showFilters(f) {
		$('.subfilters').hide();
	
		if( f != 'n' ) {
			$('#'+f).css('display','block');
		}

	}


	function action() { 
		   $('.action').removeClass('sign');
            if($('.action').hasClass('hid')) {
                $('.load').show();
                $('.action .embed').addClass('hid');
                $('.action .reg').addClass('hid');
                $('.action .fav div').hide();
                $('.action').removeClass('hid');
            } else {
                $('.action').addClass('hid');
                action();
            }
        }
    
        function fav(id) { 
            action();
            $('.fav').show();
            $('.fav div').hide();
           
            $.post("/save/favorites/",{video_id:id, process:'add' },function(data) { 
                    if(data.result) { 
                        $('.fav .conf').show();  $('.load').hide();
                    } else {
                        $('.fav .err').show();  $('.load').hide();
                    }
            },"json");
        }
        
        function delFav(id) {
            $('.err').hide();
            var mess = confirm('Sure?');
            if(mess) { 
                $.post("/save/favorites/",{video_id:id, process:'delete' },function(data) { 
                        if(data.result) { 
                           window.location.reload();
                        } else {
                            $('.err').show();
                        }
                },"json");
            }
        }
        
        function emb() { 
            action();
            $('.embed').removeClass('hid');
            $('.load').hide();
        }
        
        function reg() { 
            action();
		  $('.action').addClass('sign');
            $('.reg').removeClass('hid');
            $('.load').hide();
        }
	   
	   
	   function rep(id,lk) { 
	   		lk.html('Flagged').css('color','#777').css('cursor','default').attr('onclick',';return false');
	   }
    
	
	
var RotatingThumbs = {
    interval    : 400,
    timer       : null,
    img         : null,
    start       : 0,
    base        : '',
    origSRC     : '',
    thumbs      : [],
    current     : 0,
    currentF    : 0,
    rotate : function(img)
    {   
        var start=0,end=9, li = $(img).parent().parent(), loader;
        if (this.timer) window.clearTimeout(this.timer);
		
        //$('a img',li).parent().after($("<span class='vid_lod'/>"));
		//loader = $('.vid_lod',li);
		
		img.onmouseout = function() {
			RotatingThumbs.img.onload = function(){};
            RotatingThumbs.img.onmouseout = function(){};
            window.clearTimeout(RotatingThumbs.timer);
            RotatingThumbs.img.src = RotatingThumbs.origSRC;
            for ( var i=0; i<RotatingThumbs.thumbs.length; i++ ) delete RotatingThumbs.thumbs[i];
	   };
       
        img.onload = function() {           
            window.clearTimeout(RotatingThumbs.timer);          
            RotatingThumbs.timer = window.setTimeout(RotatingThumbs.pump, RotatingThumbs.interval);
        };

        this.img = img;
        this.origSRC = img.src;
        this.current = this.origSRC.substring(this.origSRC.lastIndexOf("_")+1,this.origSRC.lastIndexOf("."));
        this.base = this.origSRC.substring(0,this.origSRC.lastIndexOf("_"));
        this.currentF = this.current-1;
        this.thumbs = [];

        for ( var i=start; i<=end; i++ ) {
                var preload = new Image();
				preload.src = this.base + "_" + (i+1) + ".jpg";
                this.thumbs.push(preload);
				
        }
    
       
        if ( this.thumbs.length == 1 )  return; 
         
        this.thumbs.sort();
        this.pump(); 
		
    
		 
    },
    
    pump : function()
    {	
        if(RotatingThumbs.thumbs[RotatingThumbs.currentF]){
            if ( ++RotatingThumbs.currentF >= RotatingThumbs.thumbs.length)
                 RotatingThumbs.currentF = 0;
                 RotatingThumbs.img.src = RotatingThumbs.thumbs[RotatingThumbs.currentF].src;
		     } else {
				 return;
             }
         }
		 	

    };


    function logout() { 
            $.post("/logout/", 
                 { },
                     function(data) {
                        window.location.reload();
                    }, "json");
    }
    
    function searchGo(arrayOfTerms) { 
        var q ='&term='
        if(arrayOfTerms!='' ) {
            for(i in arrayOfTerms) {
                q += arrayOfTerms[i]+',';
            }
            q = q.substring(0,q.length-1);
            window.location.href = '/browse/search/?'+q;
        }
    }
    
    // Enter on search
    $(window).keypress(function(e) {  if(e.keyCode == 13) {  var t = e.target;   if($(t).hasClass('search')) {   $(t).next().click(); e.stopPropagation();   }  }});
    
    var MAX_PER_PAGE =25;
    function pagination(cp, nov) { 
      
        var maxPage = Math.ceil(nov/MAX_PER_PAGE);
        var curPath = document.location.href;

        // Remove if alreay paged
        curPath = curPath.replace(/&r=(\d*)/gi,'');
        
        if(curPath.charAt(curPath.length-1)=='/') { curPath+= '?'; }

        var pagination = "<div class='pagination clearfix'>";
		
		 if(cp!= 1 && (cp-5)>1) 	pagination+= '<span><a href="'+curPath+'&r=0" title="Go back to first page">|<</a></span> ... ';
		
         if(maxPage>1 && maxPage<=10) { 
            for(i=1; i<=maxPage; i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
        } 
        else if(maxPage>10 && (cp-5)>0) {
         
		    if(cp-5>0) pagination+= '<span><a href="'+curPath+'&r='+(cp-5)+'" title="Previous Page"><</a></span>&nbsp;'
           
		    for(i=cp-5; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>';
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>';
            }
            if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>';
			
        } else if(maxPage>10 && (cp-5)<0) { 
         
		    for(i=1; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
        
		    if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>'
       
	    } else if(maxPage>10 && (cp-5)==0) { 
        
		    for(i=1; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
         
		    if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>'
        } 
		
		if(cp != maxPage && (cp+5)<maxPage) pagination+= '... <span><a href="'+curPath+'&r='+(maxPage)+'" title="Go to last page">>|</a></span>';	
		
	   
	    pagination+='</div>';
	   
	   if(maxPage>1) { 
	    	$(pagination).insertAfter($('h2'));
        	$(pagination).insertAfter($('ul.vids'));
        } 
        
        
   
     
    }


	var MAX_PHOTO_PER_PAGE =96;
    function paginationPhoto(cp, nov) { 
      
        var maxPage = Math.ceil(nov/MAX_PHOTO_PER_PAGE);
        var curPath = document.location.href;

        // Remove if alreay paged
        curPath = curPath.replace(/&r=(\d*)/gi,'');
        
        if(curPath.charAt(curPath.length-1)=='/') {
            curPath+= '?';
        }

        var pagination = "<div class='pagination clearfix'>";
		
		 if(cp!= 1 && (cp-5)>1) 	pagination+= '<span><a href="'+curPath+'&r=0" title="Go back to first page">|<</a></span> ... ';
		
         if(maxPage>1 && maxPage<=10) { 
            for(i=1; i<=maxPage; i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
        } 
        else if(maxPage>10 && (cp-5)>0) {
         
		    if(cp-5>0) pagination+= '<span><a href="'+curPath+'&r='+(cp-5)+'" title="Previous Page"><</a></span>&nbsp;'
           
		    for(i=cp-5; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>';
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>';
            }
            if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>';
			
        } else if(maxPage>10 && (cp-5)<0) { 
         
		    for(i=1; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
        
		    if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>'
       
	    } else if(maxPage>10 && (cp-5)==0) { 
        
		    for(i=1; i<=Math.min(cp+5,maxPage); i++) { 
                if(i==cp)   pagination+= '<span class="n">'+i+'</span>'
                else        pagination+= '<span><a href="'+curPath+'&r='+i+'" title="Page '+i+'">'+i+'</a></span>'
            }
         
		    if(cp+1<=maxPage)   pagination+= '&nbsp;<span><a href="'+curPath+'&r='+(cp+1)+'" title="Next Page">></a></span>'
        } 
		
		if(cp != maxPage && (cp+5)<maxPage) pagination+= '... <span><a href="'+curPath+'&r='+(maxPage)+'" title="Go to last page">>|</a></span>';	
		
	   
	    pagination+='</div>';
	   
	   if(maxPage>1) { 
	     	$(pagination).insertAfter($('h2'));
        	$(pagination).insertAfter($('ul.photos'));
        } 
 }


function rates(total_vote,rating,voted,element_id,type, alreadyVoted) { 
			 // Can now vote without login
			
			 $('.aSs').rating({
				cancelValue: 0,			
				callback: function(value, link){
					//if(loggedIn) { 
						if(typeof value == 'undefined') {
							if(!alreadyVoted) {
								// Vote Cancelled
								$('#ty').hide();
								
								if(voted) { 
									// Already Voted 
									$('#t').html(total_vote); 
									$('#v').html(((rating) / (total_vote + 1)).toFixed(2));
									voted = false;
									if(type=='vid') updateVoteVideo(element_id,0);
									else 		 updateVotePhoto(element_id,0);
								}
								
							}
						} else { 
							if(!alreadyVoted) {
								// Vote
								$('#t').html(total_vote + 1); 
								$('#v').html(((rating + parseInt(value)) / (total_vote + 1)).toFixed(2));
								voted = true; 
								if(type=='vid') updateVoteVideo(element_id,value);
								else 		 updateVotePhoto(element_id,value);
								
								
							} else {
								$('#ty').hide();
								$('#al').show();
							}
						}
						/*
					} else { 
						if(type=='vid') reg();
						else 		 regPhoto();
					}
					*/
				}
			   });
			 
			if(alreadyVoted) {  $('.aSs').rating('disable'); $('#al').show(); }
		
		   
		
}


function regPhoto() { 
	$('#vote').hide(); $('#reg').show();
}

function updateVoteVideo(id,vote) { 
	$.post("/save/user_vote/",{video_id:id, vote:vote },function(data) { 
				    if(data.length==0) { 	$('#ty').show();
                        } else {  $('.err').show();
                        }
	},"json");
}

function updateVotePhoto(id,vote) { 
	$.post("/save/user_photo_vote/",{photo_id:id, vote:vote },function(data) { 
				    if(data.length==0) { 	$('#ty').show();
                        } else {  $('.err').show();
                        }
	},"json");
}


$(function() {
	/* Enter key on search */	 
	$('#h_sch_txt input').keyup(function(e) {
			if(e.keyCode == 13) searchGo($(this).val().split(' '));					  
	});		 
});



/* For Horizontal Scrolling */
	function initialCap(v) {
	  return v.substr(0,1).toUpperCase() + v.substr(1);
	}

	function createVideoLi(data) { 
		var vid = $('<li>'), c ='', rating, totalVote, avR, dur;
	
		c = '<a href="/videos/'+data.title+'/'+data.video_id+'"><img class="thumb"  onmouseover="RotatingThumbs.rotate(this);" src="'+data.thumb+'"  alt="'+data.title+'"></a>';
		c += '<h3 class="mtitle" title="'+initialCap(data.title)+'"><a href="'+data.url+'">'+initialCap(data.title)+'</a></h3>';
	
		dur = data.display_duration;
		c += '<div class="dur l">'+dur+'</div>';
		
		rating = data.vote_cnt;
		totalVote = data.vote_total;
		
		if(totalVote!=0) avR = (totalVote/rating)*20;
		else 		  avR = 0;	
		
		c += '<div class="rating r"><div class="rat" style="width:'+avR+'%"></div></div>';
		
		
		c += '<div class="details"><span class="r">'+data.views+' views</span><span class="l">'+data.released+'</span></div>';
		c += '<div class="usrn"><a href="/users/profile/'+data.username+'/">'+data.short_username+'</a></div>';
		
		vid.html(c);
		return vid;
	}
	


/*
 ### jQuery charCount Plugin v1.00 - 2010-00-08 ###
 * Vincent Perlerin vperlerin[a]gmail[dot]com
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 ###
*/
$.fn.charCount=function(options){var opts=$.extend({},$.fn.charCount.defaults,options);this.each(function(){var $$,maxLength,currentLength,$counter,$counterCharContainer,r=opts.remaining;$$=$(this);maxLength=($$.attr('maxlength')==undefined)?opts.maxChar:$$.attr('maxlength');$counter=$(opts.counterContainer).attr(opts.counterCountainerAttrs)
if(r==true)$counter.html(opts.remainingText);else $counter.html('/'+maxLength);$counterCharContainer=$(opts.counterCharContainer).prependTo($counter);switch(opts.position){case'after':$counter.insertAfter($$);break;default:$counter.insertBefore($$);}
currentLength=$$.val().length;r==true?$counterCharContainer.html(maxLength-currentLength):$counterCharContainer.html(currentLength);$$.keyup(function(e){currentLength=$$.val().length;if(currentLength>=maxLength){$$.val($$.val().substring(0,maxLength));opts.onMaxCharReached.call($$);$counter.css(opts.maxCharCSS);r==false?$counterCharContainer.html(currentLength):$counterCharContainer.html(0)}else{$counter.attr('style','');opts.onMaxCharNotReached.call($$);r==false?$counterCharContainer.html(currentLength):$counterCharContainer.html(maxLength-currentLength)}
e.stopPropagation();});});};$.fn.charCount.defaults={position:'after',remaining:true,remainingText:' characters remaining',counterContainer:'<div/>',counterCountainerAttrs:{'class':'countable'},counterCharContainer:'<span />',maxChar:500,maxCharCSS:{'color':'red'},onMaxCharReached:function(){},onMaxCharNotReached:function(){}};



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'||(name&&typeof name!='string')){if(typeof name=='string'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=name+'='+encodeURIComponent(value)+expires+path+domain+secure;}else{for(var n in name){jQuery.cookie(n,name[n],value||options);}}}else{var returnValue={};if(document.cookie){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(!name){var nameLength=cookie.indexOf('=');returnValue[cookie.substr(0,nameLength)]=decodeURIComponent(cookie.substr(nameLength+1));}else if(cookie.substr(0,name.length+1)==(name+'=')){returnValue=decodeURIComponent(cookie.substr(name.length+1));break;}}}return returnValue;}};
