var currentGenre = 'AllClips';
var c_loading = 2;
var isMobile = 	( ( DetectTierTablet() === true ) || ( DetectTierIphone() === true ) );

function RecordDownload(fileName) {
    $.ajax({
        url: '/Ajax/LinkHandler.ashx?fileName=' + fileName,
        success: function (data) {
        },
        error: function () {
        }
    });
};

function createDropDown() {
    //	dropdown
    drop = $(".btns .first form");

	function ddDown() {
		$(drop, this).slideDown(100);
		$('.firstA').addClass("sel");
	};
	function ddUp() {
		$(drop, this).slideUp(100);
		$('.firstA').removeClass("sel");
	};
	
	var hiConfig = {
		over: ddDown,
		timeout: 2000,
		out: ddUp
	};
	
    $('.btns .first').hoverIntent(hiConfig);
};

function setTabs() {
    $('#catTabs li a').each(function (index) {
        $(this).click(function (event) {
            event.preventDefault();
            var url = this['href'];
            var genreIndex = url.indexOf('=');
            var genre = url.substring(genreIndex + 1);

            currentGenre = genre;
            $.ajax({
                url: '/Ajax/VideoHandler.ashx?genre=' + genre,
                cache: false,
                success: function (data) {
                    $('.videoLst').empty();
                  
                    $('.videoLst').html(data);
                    $("#catTabs>li").removeClass("sel");

                    $('#' + genre).attr('class', 'sel');
                    bindVideoListEvents();
                    c_loading = 2;
                    loadForMobile();

                    if ($('.resInfo').length) {
                        $('.resInfo').hide();

                    }
                },
                error: function () {
                }
            });
        });

    });
};

function populateVideoMeta(_this) {
	this.targetElement = $('.vidOL');

	this.metaElement = _this.parents('.videoLstItem').find('.videoMetaData');

	if ( metaElement.length ) {
		/* default video item with "videoMetaData" div 
		
		<div data-reference="ITSN_FIREFARM_REDFEARN_01" data-duration="03:01:720" data-restrictions="No restrictions" data-genre="People" data-date="10/1/2011 11:29:00 AM" data-title="FIRE FARM - Intv Assist Chief Fire Officer, Martin Redfearn &amp; gvs of fire services" data-index="4" class="videoMetaData hidden">
			<div class="description">The body of a child has been found and two people have been injured in a fire at a farm in West Yorkshire.  Emergency services were called to Hessle Farm, Wragby, at about 17:30 BST.  A 37-year-old man and a one-year-old were taken to Pinderfields Hospital for burn injuries.
		</div>	
		*/
		targetElement.find('h2').html(metaElement.attr('data-title'));		
		targetElement.find('.vidOLftr').removeAttr('style');
		targetElement.find('.vidOLftr .date').html(metaElement.attr('data-date'));
		targetElement.find('.vidOLftr .genre').html(metaElement.attr('data-genre'));
		targetElement.find('.vidOLftr .restrictions').html(metaElement.attr('data-restrictions'));
		targetElement.find('.vidOLftr .duration').html('00:'+metaElement.attr('data-duration'));
		targetElement.find('.vidOLftr .description').html(metaElement.find('.description').html());				
		var dataReference = metaElement.attr('data-reference');
	} else {
		/* special item without metadata (like showreel video)
			the code grabs the title only which is applied to the triggering element
			
			<a data-title="Showreel" href="http://itnsourcenewsumbraco.gbdev.net//media/1879/showreel.mp4" class="vidPrev" data-bound="1">View Showreel</a>			
			
			and clears + hides the rest of the fields
		*/		
		targetElement.find('h2').html(_this.attr('data-title'));
		targetElement.find('.vidOLftr').css('display','none');
		targetElement.find('.vidOLftr .date').html('');
		targetElement.find('.vidOLftr .genre').html('');
		targetElement.find('.vidOLftr .restrictions').html('');
		targetElement.find('.vidOLftr .duration').html('');
		targetElement.find('.vidOLftr .description').html('');			
		var dataReference = _this.attr('href');
	};
	
   $.ajax({	
			url: '/Ajax/VideoPlayer.ashx?reference=' + dataReference,
			success: function (data) {
				$('.video-js-box').html(data);			  
				$('.video-js').load();
				VideoJS.setupAllWhenReady();
			},
			error: function () {
			}
		});
		
};

function bindVideoListEvents() {
	_target = $('.vidPrev');
	
	_target.each(function() {	
		/* check if event binding already happened to this set of elements, if not, do the binding (click+fancybox) */	
		if ( $(this).attr('data-bound') === undefined  ) {	
		
			$(this).click(function(evt) { 
				evt.preventDefault();
				var _this = $(this);
				populateVideoMeta(_this);
				changeHref(_this);	
			});
				
			$(this).fancybox({
				'padding': '0',
				'overlayOpacity': '0.6',
				'overlayColor': '#000',
				'onClosed': function() { 
					changeHref($('#activeLink'));
					$('.videoLst').removeAttr('data-noscroll');
				},
				'onStart': function() { 
					$('.videoLst').attr('data-noscroll','1');
				},
				'transitionIn': 'none',
				'transitionOut': 'none'				
			});

			$(this).attr('data-bound','1');			
		};
	});
}

function changeHref(_target) {							
	/* accessibility solution for pointing the href to the video file whenever fancybox is not loaded */
	if ( _target.attr('data-href') === undefined ) {
		_target.attr('data-href', _target.attr('href'));
		_target.attr('href', '#videoOverlay');
		_target.attr('id', 'activeLink')
	} else {
		_target.attr('href', _target.attr('data-href'));
		_target.removeAttr('data-href');
		_target.removeAttr('id');	
	}
};

function loadMore(number) {
    if (c_loading != -999) {        
        var currentUrl = window.location.href;
        var searchIndex = currentUrl.indexOf('SearchTerm');
        var searchTerm = '';
        var tabContents = $(".videoLst");      

        if (searchIndex > -1) {
            var searchIndex = currentUrl.indexOf('=');
            searchTerm = currentUrl.substring(searchIndex + 1);
        }

        $.ajax({
            "url": '/Ajax/VideoHandler.ashx?genre=' + currentGenre + '&page=' + c_loading + '&searchTerm=' + searchTerm,
            success: function (data) {
                if (data.length > 50) {
                    $.ajax({
                        "url": '/Ajax/VideoHandler.ashx?genre=' + currentGenre + '&page=' + c_loading + '&searchTerm=' + searchTerm + '&action=preload',
                        dataType: 'json',
                        success: function (data) {                           
                            preLoadImages(data);
                        }
                    });

                    tabContents.append('<li class=\'clips_loading\' style=\'display:none;\'><a href="#">More...</a></li>');
                    $('.clips_loading').slideDown();
                    $('.clips_loading').click(function (evt) {
                        evt.preventDefault();
                        setTimeout(function () {
                            $('.clips_loading').fadeOut(250, function () {
                                $('.clips_loading').remove();
                                tabContents.append(data);
                                c_loading++;
                                bindVideoListEvents();
                                loadForMobile();

                            });
                        }, 250);
                    });
                }
            },
            error: function (msg) {
                c_loading = -999;
            }
        });
    }
};

function doScroll() {
	
	if ( isMobile ) {
		loadForMobile();	
	} else {
		$(window).scroll( $.debounce( 50, helper ) );  /* preventing ie8 from triggering multiple scroll events */	
	}
	
	function helper() {
			if ( $(window).scrollTop() == $(document).height() - $(window).height() ) /* if the scroll position is not at the bottom */
			{
				if ( $('.clips_loading').length === 0 ) /* the loading of a batch of items already started*/
					{ loadMore(16) };		
			};
		}
};

function backToTop() {
	$('.backToTop').click(function(evt) {
		evt.preventDefault();
		$.scrollTo( this.hash, 250 );
	});
}

function loadForMobile() {
	if ( isMobile ) { loadMore(16) };
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var cache = [];
// Arguments are image paths relative to the current page.
function preLoadImages(arguments) {  
    var args_len = arguments.length; 
    for (var i = args_len; i--; ) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];      
        cache.push(cacheImage);
    }
}

$(document).ready(function () {
    createDropDown();

    if ($('.videoLst').length) { /* just on the videos page */
        setTabs();

        if (window.location.href.indexOf('showall') == '-1') {
            doScroll();
        }
    };

    bindVideoListEvents();
    VideoJS.setupAllWhenReady();

    backToTop();

    $('#searchForm').keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            $("#submitSearch").focus().click();
        }
    });
    $('#searchForm2').keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            $("#submitSearch2").focus().click();
        }
    });

    $('.restriction a').each(function (index) {
        $(this).click(function (event) {
            event.preventDefault();
        });
    });


    $('.restriction a[title]').tooltip();

    $(function () {
        var id = getUrlVars()["pid"];
        if ($('#nvp_' + id)) {
            $('#nvp_' + id).click();
        }
    });
});
