(function($) {
	
	$.getScript("http://www.kvewtogo.com/inline/js/flashembed.min.js");
	$.getScript("http://www.kvewtogo.com/inline/js/jquery.metadata.min.js");
	// Leave off until the API is complete
	$.getScript("http://www.kvewtogo.com/inline/js/embed_functions.js");

	$.fn.embtvVideo = function(options) {
		return this.each(function() {
			new $.embtvVideo(this, options);
		});
	};
	
	$.log = function (message) {
		if (window.console && console.log ) {
			console.log(message);
		}
	}
	
	//constructor
	$.embtvVideo = function(el, options) {
	

		this.opts = $.extend({}, $.embtvVideo.defaults);
		this.opts = $.extend({}, this.opts, {playlist: $.embtvVideo.playlist.id, canvas: $.embtvVideo.canvas.id, info: $.embtvVideo.info.id});
		this.opts = $.extend({}, this.opts, $.embtvVideo.canvas);
		this.opts = $.extend({}, this.opts, $.embtvVideo.info);	
		this.opts = $.extend({}, this.opts, $.embtvVideo.playlist);
		this.opts = $.extend({}, this.opts, options);
		
		this.canvas = $(el);
		
		this.opts = $.metadata ? $.extend({}, this.opts, this.canvas.metadata()) : this.opts;
		
		this.info = $(this.opts.info);
		this.list = $(this.opts.playlist);
		this.categories = $(this.opts.categoryListId);
		

		this.opts = $.extend({}, this.opts, {width: this.canvas.attr("width"), height: this.canvas.attr("height")});
		
		if (this.opts.categoryList != null) {
			this.initCategoryList();
			if (! this.opts.category) this.opts.category = this.opts.categoryList[0];
		}
		if (this.opts.category) {
			this.playlistPage({data:{section: this.opts.category}});
		}
		if (this.opts.showSearch) {
			var self = this;
			if (this.opts.searchBarHtml) this.list.before($(this.opts.searchBarHtml));
			$(this.opts.searchFieldId).bind('focus', function() {
				if ($(this).attr('value') == self.opts.searchDefault) $(this).attr('value', '');
			}).bind('blur', function() {
				if ($(this).attr('value') == '') $(this).attr('value', self.opts.searchDefault);
			}).bind('keypress', function(event) {
				if (event.which != 13) return;
				$(this).trigger('submit_search');
			}).bind('submit_search', {"do": "search"}, function(event) {
				if ($(this).attr('value') == '' || $(this).attr('value') ==  self.opts.searchDefault) {
					alert("Please enter a search term.");
					return;
				}
				event.data.search_text = $(this).attr('value');
				self.playlistPage(event);
			});
			$(this.opts.searchButtonId).bind('click', function(event) {
				$(self.opts.searchFieldId).trigger('submit_search');
			});
		}
		if (this.opts.mgid) {
			if (typeof this.opts.mgid == "object") {
				this.playlistPage({data:{'mgid[]': this.opts.mgid}});
				this.playVideo(this.opts.mgid[0]);
			}else {
				this.playVideo(this.opts.mgid);
			}
		}

	};
	
	$.embtvVideo.defaults = {
		player_url: 'http://www.kvewtogo.com/inline/',
		flash_url: 'swf/FlowPlayerLight.swf',
		config_file: 'async_scripts/config.php',
		info_file: 'async_scripts/video_info.php',
		playlist_file: 'async_scripts/video_list.php',
		categorylist_file: 'async_scripts/category_list.php',
		store_url: '',
		playlist: null, //DOM ojbect\string selector
		video_list: null,
		info: null, //DOM object\string selector
		canvas: null, //DOM object\string selector 
		title: null //DOM object\string selector
	};
	
	$.embtvVideo.canvas = {
		mgid: null, //integer
		width: 298, //integer
		height: 250, //integer
		hideControls: false, //bool
		showScrubber: true, //integer
		showStopButton: false, //integer
		showPlayButton: true, //integer
		showVolumeSlider: true, //integer
		noAuto: true //integer
	};
	
	$.embtvVideo.playlist = {
		id: null, //jQuery selector
		categoryListId: null,
		category: null, //integer
		categoryList: null, //array of integers
		categoryListItemHtml: '<li />',
		thumbnailHtml: '<img style="float:left" />', //HTML markup
		thumbnailHeight: 68, //integer
		thumbnailWidth: 90, //integer
		teaserHtml: '<p class="summary" />', //HTML markup
		itemHtml: '<div class="video" />', //HTML markup
		itemPostHtml: '<div style="clear:both" />', //HTML markup
		itemsPerPage: 5, //integer
		itemTitleHtml: '<b/>', //HTML markup
		playlistTitleHtml: '<p class="title" />', //HTML markup
		navHtml: '<div class="nav">', //HTML markup
		navControlHtml: '<span style="color:#0000FF;cursor:pointer;font-weight:800" />',
		navPrevHtml: '&laquo; Prev ',
		navNextHtml: ' Next &raquo;',
		searchBarHtml: '<div><input type="text" id="embtvVideoSearch" Value="Search Videos..." /><button type="button" id="embtvVideoSearchButton" />Search</div>',
		searchDefault: 'Search Videos...',
		showSearch: false, //bool		
		searchFieldId: "#embtvVideoSearch",
		searchButtonId: "#embtvVideoSearchButton"
	};

	$.embtvVideo.info = {
		id: null, //jQuery selector
		titleHtml: '<p class="title" />', //HTML markup
		summaryHtml: '<p class="summary" />', //HTML markup
		dateHtml: '<p class="date" />', //HTML markup
		storeHtml: '', //HTML markup
		storeMessage: '' //String
	};
		
	// Create shortcut for internal use
	$embtv = $.embtvVideo;
	
	$embtv.fn = $embtv.prototype = {
		embtvVideo: '0.7.0'
	};

	$embtv.fn.extend = $embtv.extend = $.extend;

	$embtv.fn.extend({
	
		playVideo: function(mgid, o) {
                    if (o == undefined) o = {};		
		    var opts = $.extend({}, this.opts, o);
		    var config_uri = encodeURIComponent(this.opts.player_url
							+this.opts.config_file
							+'?noauto='+(opts.noAuto ? "true" : "")
							+'&id='+mgid
							+'&cat_id='+this.opts.category);
	            var api = this.canvas.flashembed({
                        src: opts.player_url+opts.flash_url,
                        width:opts.width,
                        height:opts.height,
			wmode: 'transparent'
                    },
                    {config:{
                        configFileName: config_uri,
                        initialScale: "fit",
			hideControls: opts.hideControls,
			showScrubber: opts.showScrubber,
			showStopButton: opts.showStopButton,
			showPlayButton: opts.showPlayButton,
			showVolumeSlider: opts.showVolumeSlider,
			menuItems: [0, 1, 1, 0, 1, 1, 0]
                    }});
		    if (this.opts.info) this.videoInfo(mgid);
		},
		
		videoInfo: function(mgid) {
		    var self = this;
		    $.getJSON(this.opts.player_url + this.opts.info_file + '?jsoncallback=?',{"id": mgid}, function(data){
		        self.info.empty()
			if (self.opts.titleHtml) self.info.append($(self.opts.titleHtml).html(data.title));
			if (self.opts.dateHtml) self.info.append($(self.opts.dateHtml).html(data.date));
			if (self.opts.imgHtml && info.thumb) self.info.append($(self.info.imgHtml).atr("src", info.thumb));
			if (self.opts.summaryHtml) self.info.append($(self.opts.summaryHtml).html(data.description));
			if (data.sell == 'y' && self.opts.storeHtml && self.opts.storeMessage) {
			     self.info.append(
				$(self.opts.storeHtml)
				    .attr('href',self.opts.store_url+String(mgid))
				    .html(self.opts.storeMessage)
			    );
			}
		    });
		},
		
		initCategoryList: function() {
			var self = this;
			var data = {"cat_id[]": this.opts.categoryList}
			$.getJSON(this.opts.player_url+this.opts.categorylist_file+'?jsoncallback=?', data, function(data) {
				for (i in data) {
					self.categories.append(
					    $(self.opts.categoryListItemHtml)
						.html(data[i].title)
						.bind("click", {section: data[i].cat_id, page: 1}, function(event){ self.playlistPage(event);})
					)
				}
			});
		},
		
		playlistPage: function(event) {
		    var self = this;
		    var data = $.extend({page: 1, per_page: this.opts.itemsPerPage}, event.data);
		    $.getJSON(this.opts.player_url+this.opts.playlist_file+'?jsoncallback=?', data, function(data) { self.loadPlaylist(data); } );
		},

		loadPlaylist: function(data) {
		    var self = this;
		    if (data.count > 0) {
			if (! this.opts.mgid) {
				this.opts.mgid=data.playlist[0].vfile;
				this.playVideo(this.opts.mgid);
			}
			if ( ! this.opts.playlist )  return;
			this.list.empty();
			if (this.opts.playlistTitleHtml) this.list.append($(this.opts.playlistTitleHtml).html(data.title));
			if (this.opts.navHtml && data.num_pages > 1) {
			    var nav = $(this.opts.navHtml).append('<span style="float:left">page '+data.page+' of '+data.num_pages+'</span>');
			    var navRight = $('<span style="float:right" />');
			    if (data.prev) navRight.append(
				$(self.opts.navControlHtml)
				    .html(self.opts.navPrevHtml)
				    .bind('click', data.prev, function(event) { self.playlistPage(event) } )
			    );
			    if (data.next) navRight.append(
				$(self.opts.navControlHtml)
				    .html(self.opts.navNextHtml)
				    .bind('click', data.next, function(event) { self.playlistPage(event) } )
			    );
			    nav.append(navRight).append('<div style="clear:both"/>').appendTo(this.list);
			}
			$.each(data.playlist, function(index, item) { 
			    var i = $(self.opts.itemHtml).css("cursor", "pointer").attr("id", "embtv-video-"+item.vfile);
			    if (self.opts.itemTitleHtml) i.append($(self.opts.itemTitleHtml).html(item.title));
			    if (self.opts.thumbnailHtml) {
				thumb = $(self.opts.thumbnailHtml).attr("src", item.thumb_url).attr("title", item.title);
				if (self.opts.thumbnailWidth) thumb.attr("width", self.opts.thumbnailWidth);
				if (self.opts.thumbnailHeight) thumb.attr("height", self.opts.thumbnailHeight);
				i.append(thumb);
			    }
			    if (self.opts.teaserHtml) i.append($(self.opts.teaserHtml).html(item.teaser));
			    if (self.opts.itemPostHtml) i.append($(self.opts.itemPostHtml));
			    i.bind("click", function(event) {
				    event.preventDefault(); 
				    self.playVideo(item.vfile, {noAuto:""});
				}).appendTo(self.list);
			});
		    };
		}
	});
})(jQuery);

