var $_GET = {};
var TagMap = {};


/**functions for both pages**/

function createTagMap() {

	for (var i in VideoMap) {

		var videoObj = VideoMap[i];

		for (var j in videoObj.tags) {

			var tag = videoObj.tags[j].toLowerCase();

			if (!TagMap[tag]) {
				TagMap[tag] = [];
			}
			TagMap[tag].push(videoObj.id);
		}
	}
}
var CollectionsMap = {};

function addVideosToCollections() {

	$(Collections).each(function () {

		var collection = this;
		collection.Videos = []; // map of videos in collection

		var ids = []; // temp array of video IDs

		// collect all video IDs from the TagMap
		// for the tags in this collection
		// this includes duplicate IDs, which will be eliminated when creating colleciton.Videos map
		for (var i = 0; i < this.Tags.length; i++) {
			if (TagMap[this.Tags[i]] != null)
				ids = ids.concat(TagMap[this.Tags[i]]);
		}

		ids = $.unique(ids);

		collection.VideoIds = ids.join(","); // VideoIds is used for looking up collection based on video ID

		// add videos to collection.Videos, eliminating duplicates
		for (var i = 0; i < ids.length; i++) {
			collection.Videos.push(VideoMap[ids[i]]);
		}
		CollectionsMap[collection.CollectionName] = collection;
	});
}


/**functions for video page**/
function createAccordianMenu() {
	$('div.accordion-Content').hide();
	$('div.accordion-Button').click(function () {
		if ($(this).hasClass('accordion-Button-Open')) {
			$('div.accordion-Content').slideUp('normal');
			$(this).removeClass('accordion-Button-Open');
			$(this).find('img.arrow').attr('src', CONTENT_ROOT + '/images/down.jpg');
		}
		else {
			$('div').removeClass('accordion-Button-Open');
			$('div.accordion-Content').slideUp('normal');
			$(this).addClass('accordion-Button-Open');
			$(this).find('img.arrow').attr('src', CONTENT_ROOT + '/images/up.jpg');
			$(this).next().slideDown('normal');
		}
	});
}


function populateCollectionsMenu() {
	var content = '';
	$.each(Collections, function (index, currentCollection) {  //'+currentCollection.image+'
		var collectionImageSrc = currentCollection.Videos.length > 0 ? currentCollection.Videos[0].thumbnail.sqDefault : "http://i.ytimg.com/vi/6a4CNcvJk5w/default.jpg";

		content += '<div class="accordion-Button">\
                        <div class="small-img-container" style="background: url(' + collectionImageSrc + ') -20px -15px;">\
                        </div>\
                        <div class="collection-Header" style="color:' + currentCollection.FontColor + '">\
                            ' + currentCollection.CollectionName + '&nbsp;<img class="arrow" src="' + CONTENT_ROOT + '/images/down.jpg" />\
                        </div>\
                        <div class="clear"></div>\
                   </div>\
                   <div class="accordion-Content dark-shadow">';
		$(currentCollection.Videos).each(function () {
			var video = this;

			content += '<div class="single-video-item-home" style="border-color: ' + currentCollection.FontColor + ';" >\
                                    <div class="small-img-container" style="background: url(' + video.thumbnail.sqDefault + ') -20px -15px;">\
			                            <a href="play-video?id=' + video.id + '&col=' + currentCollection.CollectionName + '" class="playVideo" >\
                                        </a>\
                                    </div>\
                                    <div style="font-size: 11px; width: 130px; float: right;">\
                                        ' + video.title + '\
                                    </div>\
                                    <div class="clear"></div>\
                                </div>';

		});

		content += '</div>';

	});
	$('#collections').html(content);
}




function populateVideos(videoList) {
	var content = '';
	var total = 0;
	$.each(videoList, function (index, currentVideo) {

		if (total % 2 == 0) {
			content += '<div class="video-group">\
                        <div class="video-list-left">\
                            <div class="video-thumb dark-shadow">\
                                <a href="play-video?id=' + currentVideo.id + '" style="background: url(' + currentVideo.thumbnail.hqDefault + ') -40px -48px;">\
                                    <span></span>\
                                </a>\
                            </div>\
                            <div class="video-thumb-caption">\
                                <div class="video-thumb-caption-title">' + currentVideo.title + '</div>\
                                <div class="video-right">' + currentVideo.TimeLength + '</div>\
                                <div class="clear"></div>\
                            </div>\
                            ' + currentVideo.description + '<br/><br/>\
                        </div>';
		}
		else {
			content += '<div class="video-list-right">\
                        <div class="video-thumb dark-shadow">\
                            <a href="play-video?id=' + currentVideo.id + '" style="background: url(' + currentVideo.thumbnail.hqDefault + ') -40px -48px;">\
                                <span></span>\
                            </a>\
                        </div>\
                        <div class="video-thumb-caption">\
                            <div class="video-thumb-caption-title">' + currentVideo.title + '</div>\
                            <div class="video-right">' + currentVideo.TimeLength + '</div>\
                            <div class="clear"></div>\
                        </div>\
                        ' + currentVideo.description + '<br/><br/>\
                    </div>\
                    <div class="clear"></div>\
                </div>';
		}
		total++;
	});

	if (total == 0) {
		$('#video-list').html('<h2>No videos to display</h2>');
	}
	else {
		$('#video-list').html(content);
		pagination(total);
	}
}


function pagination(total) {
	// borrowed from http://web.enavu.com/tutorials/making-a-jquery-pagination-system/
	var show_per_page = 3;
	var number_of_items = $('#video-list').children().size();
	var number_of_pages = Math.ceil(number_of_items / show_per_page);

	$('#current_page').val(0);
	$('#show_per_page').val(show_per_page);
	var navigation_html = '<br/>'
	navigation_html += '<a class="previous_link dark-shadow" href="javascript:previous();">Previous</a>';
	var current_link = 0;
	while (number_of_pages > current_link) {
		navigation_html += '<a class="page_link dark-shadow" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a>';
		current_link++;
	}
	navigation_html += '<a class="next_link dark-shadow" href="javascript:next();">Next</a>';
	navigation_html += '<br/><br/>' + total + ' Items <a href="javascript:all();">View All</a>';
	$('#video-pagination').html(navigation_html);
	$('#video-pagination .page_link:first').addClass('active_page');
	$('#video-list').children().css('display', 'none');
	$('#video-list').children().slice(0, show_per_page).css('display', 'block');
}

function previous() {

	new_page = parseInt($('#current_page').val()) - 1;
	//if there is an item before the current active link run the function
	if ($('.active_page').prev('.page_link').length == true) {
		go_to_page(new_page);
	}

}

function next() {
	new_page = parseInt($('#current_page').val()) + 1;
	//if there is an item after the current active link run the function
	if ($('.active_page').next('.page_link').length == true) {
		go_to_page(new_page);
	}

}
function go_to_page(page_num) {

	var show_per_page = parseInt($('#show_per_page').val());
	var start_from = page_num * show_per_page;
	var end_on = start_from + show_per_page;

	$('#video-list').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

	$('.page_link[longdesc=' + page_num + ']').addClass('active_page').siblings('.active_page').removeClass('active_page');

	$('#current_page').val(page_num);
}
function all() {
	$('.page_link').removeClass('active_page');
	$('#video-list').children().css('display', 'block')
}

function getUrlParams() {
	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
		function decode(s) {
			return decodeURIComponent(s.split("+").join(" "));
		}
		$_GET[decode(arguments[1])] = decode(arguments[2]);
	});
}





// for single video page

function getVideoFromUrl() {
	getUrlParams();
	var videoID = "";

	if ($_GET["id"])
		videoID = $_GET["id"];
	else if ($_GET["col"])
		videoID = CollectionsMap[$_GET["col"]].Videos[0].id;

	createVideoPlayer(videoID);
}

function createVideoPlayer(id) {

	$('#video-player').html('<iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/' + id + '?wmode=transparent" frameborder="0"></iframe>');
	var content = '';
	var currentVideo = VideoMap[id];
	if (typeof (currentVideo) == 'undefined') { // sometimes VideoMap is passed as an array instead of object
	    for (var i = 0; i < VideoMap.length; i++) {
	        if (VideoMap[i].id != id) {
	            continue;
	        } else {
	            currentVideo = VideoMap[i];
	            break;
	        }
	    }
	}

    if (currentVideo.title) content += '<div class="video-title">' + currentVideo.title + '</div>';
    if (currentVideo.TimeLength) content += '<div class="video-time">' + currentVideo.TimeLength + '</div><div class="clear"></div>';
	if (currentVideo.description) content += currentVideo.description + '<br/><br/>';
	if (currentVideo.tags) {
	    content += 'Tags: ';
	    $.each(currentVideo.tags, function (index, tag) {
	        //content += '<a href="video.html?s='+tag+'">'+tag+'</a> '
	        content += tag + ', ';
	    });
	}

	$('#video-attributes').html(content.replace(/, $/, ""));
}

function populateSmallVideoCollections() {
	var content = '';
	var total = 0;
	$.each(Collections, function (index, currentCollection) { //'+currentCollection.image+'

		total++;
		var collectionImageSrc = currentCollection.Videos.length > 0 ? currentCollection.Videos[0].thumbnail.sqDefault : "http://i.ytimg.com/vi/6a4CNcvJk5w/default.jpg";
		var collectionLink = currentCollection.Videos.length > 0 ? "/play-video?col=" + currentCollection.CollectionName : "#";

		if (index % 2 == 0) {
			content += '<div class="small-collection-item">\
                        <div class="collection-video-left">\
                            <div class="small-img-container" style="margin-left: 20px; background: url(' + collectionImageSrc + ') -20px -15px;">\
                                <a href="' + collectionLink + '" class="openCollection"></a>\
                            </div>\
                            <p style="clear: both;">' + currentCollection.CollectionName + '</p>\
                        </div>';
		}
		else {
			content += '<div class="collection-video-right">\
                            <div class="small-img-container" style="margin-left: 20px; background: url(' + collectionImageSrc + ') -20px -15px;">\
                                <a href="' + collectionLink + '" class="openCollection"></a>\
                            </div>\
                            <p style="clear: both;">' + currentCollection.CollectionName + '</p>\
                         </div>\
                        <div class="clear"></div>\
                    </div>';
		}
	});

	if (total % 2 == 0) {
		content += '</div>';
	}


	$('#small-collection').html(content);
}

function populateSingleVideoList() {

	getUrlParams();

	var SingleCollection = {};

	if ($_GET["col"]) {
		SingleCollection = CollectionsMap[$_GET["col"]];
	}
	else if ($_GET["id"]) {
		for (var i = 0; i < Collections.length; i++) {
			if (Collections[i].VideoIds.indexOf($_GET["id"]) > -1) {
				SingleCollection = Collections[i];
				break;
			}
		}
	}

    if (typeof (SingleCollection.CollectionName) != "undefined")  {
	$(".txtCollectionName").html(SingleCollection.CollectionName);

	var content = '';
	$.each(SingleCollection.Videos, function (index, currentVideo) {
		content += '<div class="single-video-item">\
                        <div class="small-img-container" style="background: url(' + currentVideo.thumbnail.sqDefault + ') -20px -15px;">\
                             <a href="play-video?id=' + currentVideo.id + '&col=' + SingleCollection.CollectionName + '" class="playVideo">\
                            </a>\
                        </div>\
                        <div class="small-img-info">\
                            ' + currentVideo.title + '<br/>' + currentVideo.TimeLength + '\
                        </div>\
                        <div class="clear"></div>\
                   </div>';
	});
	$('#single-video-list').show();
	$('#single-video-list').html(content);
    } else {
	$('#single-video-list').hide();
    }
}

