jQuery(document).ready(function(){

    if ( window.self !== window.top ) { window.top.location.href=window.location.href; }

    var imageResized = false;

    var lazy_instance = jQuery("img.onLoad").Lazy({
        threshold : 200,
        afterLoad: function(element) {
            if(imageResized == false) { resizeImgs(); imageResized = true; }
        },
    });
    
	jQuery('.dropdown').hover(function() {
		jQuery(this).addClass('open');
	  	jQuery(this).find('.my-drop').stop(true, true).show();
	}, function() {
	  	jQuery(this).find('.my-drop').stop(true, true).fadeOut('fast');
	  	jQuery(this).removeClass('open');
	});
    
    jQuery('.movie-panel').hover(function() {
		if (jQuery(this).find('.movie-panel-title')[0].scrollWidth >  jQuery(this).find('.movie-panel-title').innerWidth()) {
            jQuery(this).find('.movie-panel-title').addClass('marquee');
        }
	}, function() {
	  	jQuery(this).find('.movie-panel-title').removeClass('marquee');
	});
	
	jQuery('a.video-remove').on('click', function() { 
	
		var href = jQuery(this).attr('href');
		var vid = jQuery(this).attr('id');
		
		jQuery.get( href+"?format=json", function( data ) {
			
			if(data.status == "S") {
				
				jQuery('.panel-video-'+vid).fadeOut('fast');
			}
		}, "json" );
		
		return false;
	});
	
    jQuery("a.delete-video").on("click", function() {

        var vid = jQuery(this).data('id');

        jQuery.post( "/utility/remVideo", { id: vid },
            function( data ) {
                if(data.status == "S") {

                    var watch = getParameterByName('v'); console.log(watch);

                    if(watch != null && watch != "") {

                        window.location.href='/';
                    }
                    else {

                        jQuery('.panel-video-'+vid).fadeOut();
                    }
                }
            },
        "json");

        return false;
    });

	jQuery('.qtips').qtip({
    	content: function(event, api) {
        	return jQuery(this).attr('title');
        },
       	hide: { fixed: true, delay: 500 },
        show: { solo: true, },
        position: { my: 'center left', at: 'right center'},
        style: { classes: 'qtip-shadow qtip-rounded' },
    	tip: { corner: '' }
 	});
	
	jQuery('a.remove-video').on('click', function() { 
	
		var conf = confirm("Are you sure you want to delete this video?");
		
		if (conf == true) {
		    
			var href = jQuery(this).attr('href');
			var vid = jQuery(this).attr('id');
			
			jQuery.get( href+"&format=json", function( data ) {
				
				if(data.status == "S") {
					
					jQuery('.panel-video-'+vid).fadeOut('fast');
				}
			}, "json" );
		}
			
		return false;
	});
    
    jQuery('.more-descr').on('click', function() { 
        
        var did = jQuery(this).data('id');
        jQuery(this).remove();
        jQuery('#more-'+did).show();
    });

    jQuery('.btn-hoster').on('click', function() {
        jQuery(this).addClass('hoster-clicked');
    });
	
    jQuery('.popup').click(function(event) {
        var width  = jQuery(this).attr('win-width'),
            height = jQuery(this).attr('win-height'),
            left   = ($(window).width()  - width)  / 2,
            top    = ($(window).height() - height) / 2,
            url    = this.href,
            opts   = 'status=1' +
                 ',width='  + width  +
                 ',height=' + height +
                 ',top='    + top    +
                 ',left='   + left;
    
            window.open(url, 'twitter', opts);
 
        return false;
    });
    
    jQuery('.modalButton').on('click', function(e) {

        var title = jQuery(this).attr('data-title');
        var src = jQuery(this).attr('data-src');
        var height = jQuery(this).attr('data-height') || 300;
        var size = jQuery(this).attr('data-size') || 'na';

        if(size != "na") { jQuery('#modal-dialog').addClass(size); }
        else { 
            jQuery('#modal-dialog').removeClass('modal-lg'); 
            jQuery('#modal-dialog').removeClass('modal-sm'); 
             }
        
        jQuery('#myModalLabel').html(title);
        jQuery("#modal-iframe").attr({'src':src,
                                   'height': height});
    });
    
    jQuery('#myModal').on('hidden.bs.modal', function (e) {
        jQuery("#modal-iframe").removeAttr('src');
    });
});

function  watched_vid(id) {

	jQuery('#link-'+id).fadeTo("fast", 0.2);
}

function gaEvents(b, a, l) {
	
    if (typeof ga == 'function') { 
	   ga('send', 'event', b, a, l);
    }
}

function fetch_watched(vids) {
    
    var cct = jQuery("input[name=csrf_token]").val();

    jQuery.post( "/utility/watchedvideos", { csrf_token: cct, vids: vids }, 
        function( data ) {
            if(data.status) {

                jQuery.each(data.result, function (i, v) {
                    jQuery('#watched-'+i).show();
                });
            }
        }, 
    "json");
}

function fetch_channels(vids) {
    
    var cct = jQuery("input[name=csrf_token]").val();

    jQuery.post( "/utility/listchannels", { csrf_token: cct, vids: vids }, 
        function( data ) {
            if(data.status) {

                jQuery.each(data.result, function (i, v) {
                    jQuery(".channel-"+i).html('<a href="'+siteurl+userlang+'/'+v.channel_type+'/'+v.tag_url+'">'+v.tag_name+'</a>');
                    jQuery('.channel-'+i).show();
                });
            }
        }, 
    "json");
}

function track_view(vid, tok) {
    		
	jQuery.get( "/utility/videoviewed", { vid: vid }, 
		function( data ) {
			if(data.status == "S") {

				gaEvents('Button', 'Watched', 'Video');
		   	}
		}, 
	"json");
}

function save_watch_list(vid) {
	
	var cct = jQuery("input[name=csrf_token]").val();
	   		
	jQuery.post( "/utility/savewatchlist", { csrf_token: cct, vid: vid }, 
		function( data ) {
			if(data.status == "S") {
				
				jQuery("#watch-"+vid).attr('disabled', 'disabled');
				jQuery("#watch-span-"+vid).html('<i class="fa fa-check"></i>');
				jQuery("#watch-span-"+vid).css('color', '#5FC62B');
				gaEvents('Button', 'Watchlist', 'Add to Playlist');
		   	}
		}, 
	"json");
}

function save_favourite(vid) {
	
	var cct = jQuery("input[name=csrf_token]").val();
	   		
	jQuery.post( "/utility/savefavourite", { csrf_token: cct, vid: vid }, 
		function( data ) {
			if(data.status == "S") {
				
				jQuery("#btn-favourite-"+vid).attr('disabled', 'disabled');
				jQuery("#favourite-span-"+vid).html('<i class="fa fa-check"></i>');
				jQuery("#favourite-span-"+vid).css('color', '#5FC62B');
				gaEvents('Button', 'Favourite', 'Add Video to Favourites');
		   	}
		}, 
	"json");
}

function save_likes(vid,type) {

	var cct = jQuery("input[name=csrf_token]").val();
	   		
	jQuery.post( "/utility/savelikes", { csrf_token: cct, type: type, vid: vid }, 
		function( data ) {
			if(data.status == "S") {
				
				jQuery('.btn-likes').attr('disabled', 'disabled');
				jQuery('.btn-dislikes').attr('disabled', 'disabled');
				jQuery('#video_like_percentage').html(data.likes_percentage);
				jQuery('#video_total_votes').html(data.total);
				if(type == "like") { gaEvents('Button', 'Likes', 'Like Video'); }
				else { gaEvents('Button', 'Dislikes', 'Dislike Video'); }
		   	}
		}, 
	"json");
}

function channel_subscribe(channel) {

	var cct = jQuery("input[name=csrf_token]").val();
	   		
	jQuery.post( "/utility/subscribechannel", { csrf_token: cct, channel: channel }, 
		function( data ) {
			if(data.status == "S") {
				
				jQuery('#btn-subs-'+channel).removeClass('btn-default');
				jQuery('#btn-subs-'+channel).addClass('btn-success');
				jQuery('#btn-subs-'+channel).prepend('<i class="fa fa-check"></i> ');
				gaEvents('Button', 'Channel', 'Subscribed');
		   	}
            else if(data.status == "U") {
                
                jQuery('#btn-subs-'+channel).removeClass('btn-success');
				jQuery('#btn-subs-'+channel).addClass('btn-default');
				jQuery('#btn-subs-'+channel).find('.fa-check').remove();
				gaEvents('Button', 'Channel', 'Unsubscribed');
            }
		}, 
	"json");
}

function setCookie(cname, cvalue, hours) {
    var expires = '';
    if(hours > 0) {
        var d = new Date();
        d.setTime(d.getTime() + (hours*60*60*1000));
        expires = "expires="+ d.toUTCString();
    }
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/"; 
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
}

function showAllTags() {
    jQuery('.more-tags').show();
    jQuery('.btn-more-tags').hide();
}
    
function format_num(x) {
    return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} 

function resizeFrame() {
    
    var width = jQuery('#video').width();
    var height = ( width * 9/16);
    jQuery("#video").css('height', height);
    var pw = ((width / 2) - 48);
    var ph = ((height / 2) - 48);
    jQuery(".video-play").css('left', pw+'px');
    jQuery(".video-play").css('top', ph+'px');
    
    var pwd = ((width - 310) / 2);
    var phd = ((height - 310) / 2);
    jQuery("#play-video").css('margin-left', pwd+'px');
    jQuery("#play-video").css('margin-top', phd+'px');
    jQuery("#play-video").show();
}

function ea_monitFn() {
    
    var ea_monitor = setInterval(function() {
        
        var elem = document.activeElement;
        if(elem && (elem.tagName == 'IFRAME' || elem.tagName == 'OBJECT')){
            clearInterval(ea_monitor);
            setCookie('_click', 1, 3);
            setTimeout(function() { jQuery("#in-video").remove(); }, 2000);
            document.activeElement.blur();
        }
    }, 100);
}

function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function resizeImgs() {

    var maxHeight = global_imgH;
    jQuery('.panel-img').each(function(){
        jQuery(this).find('a > img').each(function(){
            var H = jQuery(this).height();
            if (H > 100 && H < maxHeight) {
              maxHeight = H;
            }
        });
    });

    if (maxHeight) {
        jQuery('.panel-img').css({height:maxHeight});
    }
}
