var VideoChannel = {

    tag:null,
    host: "http://www.tv.reson.com",
    player: "http://www.tv.reson.com/v.swf",
    playerHeight: 360,
    playerWidth: 640,
    videos: [],
	relatedVideos: [],
    currentVideo: null,

    getVideos: function(filter) {
		var params = $.param(filter);
		var script = escape("<script src='" + VideoChannel.host + "/api/photo/list?format=json&" + params + "&size=100&callback=VideoChannel.videosReceived' type='text/javascript'></script>");
		
		document.write("<div class='mediabox' id='videos'></div><div class='leftclear'></div>");
        document.write(unescape(script));
		
		var script = escape("<script src='" + VideoChannel.host + "/api/photo/list?format=json&related_to_photo_id=" + filter.photo_id + "&size=100&callback=VideoChannel.relatedVideosReceived' type='text/javascript'></script>");
		document.write(unescape(script));
    },

	videosReceived: function(videos) {
        VideoChannel.videos = videos.photos;
        VideoChannel.createVideoPreviews(1);
        //VideoChannel.createMiniVideoScroller();
    },

	relatedVideosReceived: function(videos) {
		VideoChannel.relatedVideos = videos.photos;
	},

    createVideoPreviews: function(max) {

        max = max > VideoChannel.videos.length ? VideoChannel.videos.length : max;

        for (var i = 0; i < max; i++) {

            var video = VideoChannel.videos[i];

            var id = video.photo_id;

            if (typeof id == "undefined") {
                continue;
            }

            var title = video.title;
            var imageSource = VideoChannel.host + video.standard_download;

            var playIcon = $("<img src='" + VideoChannel.host + "/files/videoButton-36px.png'/>");
            playIcon.css("position", "absolute");
            playIcon.css("margin-left", "-160px");
            playIcon.css("margin-top", "70px");
		
            var imageDiv = $("<div></div>");
            imageDiv.append("<img src='" + imageSource + "' height='180px' width='290px'/>");
            imageDiv.append(playIcon);
			
			var titleText = $("<div class='video-title'></div>");
			titleText.append("<a>" + title + "</a>");
			imageDiv.append(titleText);
			
            var div = $("<div class='video'></div>");
            div.append(imageDiv);
            //div.append("<p><a>" + title + "</a></p>");
            div.css("cursor", "pointer");
 
            div.find("a").lightBox({
                imageLoading: '/wp-content/video/loading.gif',
                imageBtnClose: VideoChannel.host + '/files/close-button.png',
				overlayOpacity: 0.6
            });

            (function(video) {
                div.find("a").click(function() {
                    VideoChannel.currentVideo = video;
                    VideoChannel.loadVideo();
                });
            })(video);

            (function(div) {
                div.click(function() {
                    div.find("a").trigger("click");
                });
            })(div);

            $("#videos").append(div);
        }
    },

    createMiniVideoScroller: function() {
		return false;
        var inner = $("<div class='inner'></div>");

        for (var i = 0; i < VideoChannel.videos.length; i++) {

            var video = VideoChannel.videos[i];

            var image = $("<img />");
            image.attr("src", VideoChannel.host + video.standard_download);

            var anchor = $("<a></a>");
            anchor.append(image);

            var item = $("<div class='item'></div>");
            item.append(anchor);

            item.find("a").lightBox({
                imageLoading: '/img/lightbox/loading.gif',
                imageBtnClose: VideoChannel.host + '/files/close-button.png'
            });

            (function(video) {
                item.click(function() {
                    VideoChannel.currentVideo = video;
                    VideoChannel.loadVideo();
                });
            })(video);

            (function(video) {
                item.find("a").click(function() {
                    VideoChannel.currentVideo = video;
                    VideoChannel.loadVideo();
                });
            })(video);

            (function(item) {
                item.click(function() {
                    item.find("a").trigger("click");
                });
            })(item);

            inner.append(item);
        }

        var outer = $("<div class='outer'></div>");
        outer.append(inner);

        var arrows = $("<div class='arrows'></div>");
        arrows.append("<div class='leftarrow'><<</div>");
        arrows.append("<div class='rightarrow'>>></div>");

        var container = $("<div class='miniscroll scroll'></div>");
        container.append(outer);
        container.append(arrows);
        $("#videos").append(container);
        VideoChannel.initializeScrolling("miniscroll");
    },

    loadVideo: function() {

        if (VideoChannel.currentVideo == null) {
            return;
        }

		$('#lightbox-container-image-data-box').append($('#lightbox-secNav'));

        var id = VideoChannel.currentVideo.photo_id;
        var title = VideoChannel.currentVideo.title;
        var description = VideoChannel.currentVideo.content;

        var flashVars = "showDescriptions=0&photo_id=" + id + "";

        var flashObject = "<object height='" + VideoChannel.playerHeight + "' width='" + VideoChannel.playerWidth + "' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'>";
        flashObject += "<param name='movie' value='" + VideoChannel.player + "' />";
        flashObject += "<param name='FlashVars' value='" + flashVars + "' />";
        flashObject += "<param name='allowfullscreen' value='true' />";
        flashObject += "<param name='allowscriptaccess' value='always' />";
        flashObject += "<embed";
        flashObject += " height='" + VideoChannel.playerHeight + "'";
        flashObject += " width='" + VideoChannel.playerWidth + "'";
        flashObject += " flashvars='" + flashVars + "'";
        flashObject += " allowfullscreen='true'";
        flashObject += " allowscriptaccess='always'";
        flashObject += " type='application/x-shockwave-flash'";
        flashObject += " src='" + VideoChannel.player + "'";
        flashObject += "></embed>";
        flashObject += "</object>";

		var html = "<div class='lightbox-header'><div class='logo'></div>";
		html += "<div class='lightbox-controls'><div class='lightbox-see-more'><a href='" + VideoChannel.host + "'>See more videos</a></div></div>";
		html += "</div>";
		html += "<div class='lightbox-content-area'><div class='lightbox-video-area'>" + flashObject + "</div></div>";
		
        var boxContent = $("#lightbox-container-image-box");
        //boxContent.click(function() { return false; });
//        boxContent.css("height", (VideoChannel.playerHeight + 350) + "px");
        boxContent.css("width", (VideoChannel.playerWidth + 40) + "px");
        boxContent.css("padding-top", "10px");
        boxContent.html($(html));

        var descriptionHtml = "<h4>" + title + "</h4>";
//        descriptionHtml += "<br />";
        descriptionHtml += "<div class='description'>" + description + "</div>";

        var infoDiv = document.getElementById('lightbox-video-info');

        if (infoDiv == null) {

            infoDiv = $("<div id='lightbox-video-info'></div>");
            infoDiv.html(descriptionHtml);

//            var boxData = $("#lightbox-container-image-data-box");
            var boxData = $(".lightbox-content-area");
//			boxData.css("height", (VideoChannel.playerHeight + 190) + "px");
            boxData.click(function(e){ 
				if( e.target.tagName != 'A' ) {return false;}
			});
            //boxData.css("width", VideoChannel.playerWidth + "px");
            boxData.append(infoDiv);
            boxData.append(VideoChannel.createVideoScroller());
            VideoChannel.initializeScrolling("videoscroll");
            boxData.show();
			
        }
        else {
            $(infoDiv).html(descriptionHtml);
        }

		$('#lightbox-secNav').insertBefore($('.lightbox-see-more'));
		if( $('.lightbox-close-text').length == 0 ) {
			$("<span class='lightbox-close-text'>CLOSE</span>").insertBefore($('#lightbox-secNav-btnClose img'));
		}
		
    },

    createVideoScroller: function() {

        var inner = $("<div class='inner'></div>");

        for (var i = 0; i < VideoChannel.relatedVideos.length; i++) {

            var video = VideoChannel.relatedVideos[i];

            var image = $("<img />");
            image.attr("src", VideoChannel.host + video.small_download);

            var item = $("<div class='item'></div>");
            item.append(image);

            (function(video) {
                item.click(function(event) {
                    VideoChannel.currentVideo = video;
                    VideoChannel.loadVideo();
					return false;
                });

                item.hover(
                    function() {
                        $(".videoscroll").append("<div class='popuptext'>" + video.title + "</div>");

                    },
                    function() {
                        $(".videoscroll .popuptext").remove();
                    });

            })(video);

            inner.append(item);
        }

        var outer = $("<div class='outer'></div>");
        outer.append(inner);

//        var arrows = $("<div class='arrows'></div>");
        var arrow_left = $("<div class='leftarrow'></div>");
        var arrow_right = $("<div class='rightarrow'></div>");

		var title = $('<h2></h2>');
		title.addClass('related');
		title.html('RELATED VIDEOS');

        var container = $("<div class='videoscroll scroll'></div>");
        container.append(outer);
        container.append(arrow_left);
		container.append(arrow_right);

		var titledContainer = $('<div></div>');
		titledContainer.append(title);
		titledContainer.append(container);
		return titledContainer;
    },

    initializeScrolling: function(name) {

        var scroller = $("." + name + ".scroll");
        var outer = scroller.find(".outer");
        var inner = scroller.find(".inner");
        var items = inner.children(".item");

        var totalWidth = 0;
        var interval = 0;

        for (var j = 0; j < items.length; j++) {

            var item = $(items[j]);

            var width = parseInt(item.css("width"));
            var padding_left = parseInt(item.css("padding-left"));
            var padding_right = parseInt(item.css("padding-right"));
            var margin_left = parseInt(item.css("margin-left"));
            var margin_right = parseInt(item.css("margin-right"));

            if (!isNaN(width)) {
                totalWidth += width;
            }

            if (!isNaN(padding_left)) {
                totalWidth += padding_left;
            }

            if (!isNaN(padding_right)) {
                totalWidth += padding_right;
            }

            if (!isNaN(margin_left)) {
                totalWidth += margin_left;
            }

            if (!isNaN(margin_right)) {
                totalWidth += margin_right;
            }

            if (j == 0) {
                interval = totalWidth * 3;
            }
        }

        inner.css("width", totalWidth + "px");

        (function(interval) {
            scroller.find(".leftarrow").click(function() {
                outer.scrollLeft(outer.scrollLeft() - interval);
            });
        })(interval);

        (function(interval) {
            scroller.find(".rightarrow").click(function() {
                outer.scrollLeft(outer.scrollLeft() + interval);
            });
        })(interval);
    }
};

(function($){
	var videoLinkCounter = 0;
	
	function videoLinkResultHandler(elementID, data) {
		//console.log(elementID, videoID, data);
		$('#'+elementID).lightBox({
            imageLoading: '/wp-content/video/loading.gif',
            imageBtnClose: VideoChannel.host + '/files/close-button.png',
			overlayOpacity: 0.6
        });

		$('#'+elementID).data('video', data.photos[0]);

		$('#'+elementID).click(function(){
			var video = $(this).data('video');
			var relatedVideos = $(this).data('related');
			VideoChannel.currentVideo = video; //data.photos[0];
			VideoChannel.relatedVideos = relatedVideos;
	        VideoChannel.loadVideo();
		});
	};
	
	function videoLinkRelatedResultHandler(elementID, data) {
		$('#'+elementID).data('related', data.photos);
	};
	
	$.fn.videoLink = function(videoID) {
		return $(this).each(function() {
			var myID = 'videolink-' + videoLinkCounter;
			$(this).attr('id', myID);

			var funcName = 'videoLinkResultHandler_' + videoLinkCounter;
			var functionStr = funcName + ' = function(data) { videoLinkResultHandler("' + myID + '", data); }';
			eval(functionStr);
			$('<script />').attr('src', VideoChannel.host + "/api/photo/list?format=json&photo_id=" + videoID + "&size=100&callback=" + funcName).appendTo('body');

			funcName = 'videoLinkRelatedResultHandler_' + videoLinkCounter;
			functionStr = funcName + ' = function(data) { videoLinkRelatedResultHandler("' + myID + '", data); }';
			eval(functionStr);
			$('<script />').attr('src', VideoChannel.host + "/api/photo/list?format=json&related_to_photo_id=" + videoID + "&size=100&callback=" + funcName).appendTo('body');
			
			videoLinkCounter++;
		});
	};
	
})(jQuery);

$(function(){
	$('a').each(function(){
		var href = $(this).attr('href');
		if( href && href.substring(0,7) == '(popup:' ) {
			$(this).attr('href', '#');
			var videoID = href.substring(7, href.length-1);
			$(this).videoLink(videoID);
		}
	});
});

