var thePlayer= null; // one global (only for the viewTracking)


function WebPlayer(settings)
{
	var settings = $.extend({	// Time in ms before menu shows
							// webservice items (for grouping)
							PID: "amFeed",
							companyCode: "AMATRIX",
							contentURL: "http://media.agencymatrix.net/cms/JSON",
							includeSortFields: true,
							includeSeriesFields: false,
							feedFormats: "FLV",
							
							defaultCategory: "Agency Matrix",
							playerWidth: 480,
							playerHeight: 360,
							requireLogin: false,
							swfPlayerPath: "../swf/UnityPlayer.swf",
							
							debugMode: false,
							tabsDivID: "player_tabs",
							showReviews: false,
							showDiscussion: false,
							showSearch: true,
							searchCarouselDiv: "carousel-search-view",
							releaseViewType: "carousel",
							releaseViewUsesLongDescription: true,

							/* skin options */
							useJWPlayer: false,
							debugMode: false,
							// useSkinOverrideColors: false,
							// skinFrontColor: '0xff0000',
							// skinBackColor: '0x00ff00',
							// skinLightColor: '0x00ffff',
							// skinScreenColor: '0x0000ff',				
							flashVersion: '9.0.0.0',
							playerDiv: "playerDiv",
							autoPlay: true,
							allowFullScreen: true,
							skinPath: "../swf/modieus.swf", skinHeight: 32,
							extraFlashVars: "",
			//				skinPath: "../swf/festival.swf", skinHeight: 39,
			//				skinPath: "../swf/stijl.swf", skinHeight: 46,
			//				skinPath: "../swf/stylish_slim.swf", skinHeight: 32,


							/* Category Options */
/*
							categoryDiv: 'categoryDiv',
							categoryType: 'vertical_menu', // horizontal_menu, vertical_menu, or tab
*/
							categoryDiv: 'player_tabs',
							categoryType: 'tabs', // horizontal_menu, vertical_menu, or tab

							// releaseDiv: "releaseDiv",
							releaseDiv: "carousel-release-view",
							clipInfoDiv: "clipInfoDiv",
							customerReviewDiv: "div#review-tab",
							discussionDiv: "div#discussion-tab",
							releaseViewShowsHoverBalloons: false,
							itemsPerPage: 5, // 500 for carousel, 4, for carousel, unlimited
							loginDiv: "loginDiv",
							reviewsPerPage: 5,
							forgotPwdLink: "https://www.tstn.com/en/Forgot_Password.aspx",						
							signupLink: "https://www.tstn.com/subscribe/default.aspx",						
							discussionItemsPerPage: 5,
							allowOEMLogin: true,
							allowSCORMLogin: true
							}, settings);
							
	this.JWPlayer= null;
	this.WebService= new WebService(settings);
	this.CategoryModel= new CategoryModel(settings, this.WebService);

	this.ReleaseModel= new ReleaseModel(settings, this);
	if(settings.categoryType != 'tabs') {
		if(settings.releaseViewType=='carousel') {
			this.ReleaseView= new CarouselReleaseView(settings, this); 
		} else {
			this.ReleaseView= new ReleaseView(settings, this); 
		}
		this.ReleaseModel.SetView(this.ReleaseView);
		this.ReleaseView.SetModel(this.ReleaseModel);
	}
	
	this.CategoryView= new CategoryView(settings, this);
	this.ClipView= new ClipView(settings, this);
	this.CategoryModel.SetView(this.CategoryView);
	
	this.LoginView= new LoginView(settings, this);
	
	if(settings.showReviews) {
		// this.ReviewView= new CustomerReviewView(settings);
		// this.ReviewModel= new CustomerReviewModel(this, this.ReviewView, settings.reviewsPerPage);
	}

	var player= this;
	
	if(settings.showSearch) {
		if(settings.releaseViewType != 'standard') {
			this.SearchView= new CarouselReleaseView(settings, this, settings.searchCarouselDiv);
			this.SearchModel= new ReleaseModel(settings, this);

			this.SearchModel.SetView(this.SearchView);
			this.SearchView.SetModel(this.SearchModel);
			this.SearchModel.SetCategory("xxx"); // something that doesn't exist.
		} else {
			// right?
			this.SearchModel= this.ReleaseModel;
			this.SearchView= this.ReleaseView;
		}

		$("#search-tab form").bind('submit', function() {
			player.SearchModel.Search(this.input.value);
			return false;
		});
	} else {
		$('div#search-tab').hide();
	}

	// this should be events.
	this.SetCategory= function(cat, callback) {
		// sync the tabs, and set to foremost
		if(settings.categoryType != 'tabs')
		{
   			this.ReleaseModel.SetCategory(cat, callback);

			var split= cat.split('/')
			$("a[href='#main-tab']").html('<span>'+split[split.length-1]+'</span>');
    		$("#"+settings.tabsDivID).tabs('select', 1);
    	} else {
    		alert("do something with set category here?");
		}
	}
	
	// again, should be an event.
	this.SetCurrentRelease= function(release) {
		this.ReleaseModel.SetCurrentRelease(release);
		if(settings.categoryType != 'tabs')
		{
	    	$("#"+settings.tabsDivID).tabs('select', 0);
	    }
	}

	this.ReloadAll= function(resetToDefaultCategory) {
		if(this.WebService.Authenticated())
		{
			$('div.showingPreview').hide();
		} else {
			$('div.showingPreview').show();
		}
	
		this.CategoryModel.Load(function(cm) {
			var found= false;
			if(resetToDefaultCategory) {
				var defaultCategoryName= settings.defaultCategory;
				if(getQueryVariable('defCat') != null) {
					defaultCategoryName= getQueryVariable('defCat');
				}
			
				for(var ii in cm.Categories)
				{
					var category= cm.Categories[ii];
					if(category.fullTitle==defaultCategoryName)
					{
						if(settings.categoryType=='tabs')
						{
						} else {
							player.SetCategory(category.fullTitle, function(rm) {
								// categories are loaded.
								if(settings.autoPlay && rm.Releases.length>0) {
									player.SetCurrentRelease(rm.Releases[0]);
								}
							});
						}
						found= true;
						break;
					}
				}
			} else {
				// just reload the model.
				player.ReleaseModel.ResetTotalCount();
				player.ReleaseModel.Load();
				found= true;
			}
			if(!found) alert("didn't find default category: "+settings.defaultCategory);
		})};
	
	this.CreatePlayer= function() {
		var playerCreationType= 'inline';
		if(settings.debugMode) playerCreationType= 'none'
		if(settings.controlBarPosition=='over') settings.skinHeight= 0; // if it's over, it's over.
		switch(playerCreationType)
		{
			case 'inline':
				var content= '<object id="playerwidget" name="playerwidget" style="outline-style:none" width="'+settings.playerWidth+'" height="'+(settings.playerHeight+settings.skinHeight)+'" data="'+settings.swfPlayerPath+'" type="application/x-shockwave-flash">';
					content += '<param name="movie" value="'+settings.swfPlayerPath+'">';
					content += '<param name="allowfullscreen" value="'+settings.allowFullScreen+'">';
					content += '<param name="quality" value="high">';
					content += '<param name="scale" value="noScale">';
					content += '<param name="wmode" value="transparent">'; // required if you have a video overlay
					content += '<param name="allowScriptAccess" value="always">';
					
					var flashvars= 'skin='+settings.skinPath+'&wmode=transparent';
					if(settings.useJWPlayer) {
						flashvars += '&repeat=list&autostart='+settings.autoPlay;
					} else {
						flashvars += '&autoplay='+settings.autoPlay;
					}
					if(settings.useSkinOverrideColors) {
						flashvars += '&frontcolor='+settings.skinFrontColor+
							'&backcolor='+settings.skinBackColor+
							'&lightcolor='+settings.skinLightColor+
							'&screencolor='+settings.skinScreenColor;
					}
					if(settings.controlBarPosition) {
						flashvars += '&controlbar='+settings.controlBarPosition;
					}
					if(settings.extraFlashVars.length>1) {
						if(settings.extraFlashVars[0] != '&') flashvars+= '&';
						flashvars+= settings.extraFlashVars;
					}
					content += '<param name="flashvars" value="'+flashvars+'">';
				content += '</object>';
		//alert(content);
		
			// replace with the content.
				$('#'+settings.playerDiv).html(content);
				break;
				
			case 'jquery.flash':
				// I like this better, but it doesn't work with IE8- b/c the object isn't setup right or something.
				$('#'+settings.playerDiv).flash(
			        {
			        	id: 'playerwidget',
			        	name: 'playerwidget', 
			        	src: settings.swfPlayerPath,
		    		 	width: settings.playerWidth,
			            height: settings.playerHeight+settings.skinHeight,
			            allowFullScreen: settings.allowFullScreen,
			            allowScriptAccess: 'always',
			            flashvars: { autoplay: settings.autoPlay, skin: settings.skinPath, repeat: 'list' } // FIXME: add useSkinOverrideColors logic, if used
			        },
		    		{ version: settings.flashVersion }
				);	
				if(settings.extraFlashVars.length) alert("extraflashvars not supported with this player creation method");
				break;
				
			case 'swfobject':
				var so = new SWFObject(settings.swfPlayerPath,'playerwidget',settings.playerWidth, settings.playerHeight+settings.skinHeight, settings.flashVersion);
				so.addParam('allowfullscreen', settings.allowFullScreen);
				so.addParam('allowscriptaccess','always');
				so.addParam('wmode','opaque');
				if(settings.useJWPlayer) {
					so.addVariable('autostart', settings.autoPlay);
					so.addVariable('repeat', 'list');
				} else {
					so.addVariable('autoplay',settings.autoPlay);
				}
				so.addVariable('skin', settings.skinPath);
				if(settings.useSkinOverrideColors) {
					so.addVariable('frontcolor', settings.skinFrontColor);
					so.addVariable('backcolor', settings.skinBackColor);
					so.addVariable('lightcolor', settings.skinLightColor);
					so.addVariable('screencolor', settings.skinScreenColor);
				}
				if(settings.controlBarPosition) {
					so.addVariable('controlbar', settings.controlBarPosition);
				}
				so.write(settings.playerDiv);
				if(settings.extraFlashVars.length) alert("extraflashvars not supported with this player creation method");
				break;
				
			case 'none':
				break;
		}
		// force the centering to work...
		$('#'+settings.playerDiv).css({'width': settings.playerWidth, 'height': settings.playerHeight});

		// add the showingPreview div
		$('#'+settings.playerDiv).append('<div class="showingPreview" style="display:none;"></div>');
	};
	
	this.SelectClip= function(url) {
		if(url.indexOf('format=SMIL')==-1)
       	{
        	url += "&format=SMIL";
    	}
    	if(settings.useJWPlayer && url.indexOf('type=JW')==-1) {
    		url += "&type=JW";
    	}

		var success= false;
		if(settings.useJWPlayer) {
			if(this.JWPlayer != null) {
				try {
					this.JWPlayer.sendEvent("LOAD",url);
					success= true;
				} catch(err) {
					alert("Err "+err+" on setting...");
				}
			}
		} else {
			var video_player= document.getElementById('playerwidget');
			if(video_player) {
				try {
					if(video_player.Loaded())
					{
						if(!player.CallbackSet)
						{
							video_player.setStatusCallback('updateVideoStatus');
							player.CallbackSet= true;
						}
	
						video_player.LoadFromSMIL(url);
						success= true;
					}
				} catch(err) {
				}
			}
		}
		
		if(!success) {
			setTimeout(function() {
				player.SelectClip(url); }, 250);
		}
	};


	this.UpdateVideoStatus= function(message) {
		switch(message.type)
		{
			case "sm-video-stop":
			case "sm-video-pause":
				this.WebService.PauseVideo(this.ShowCode, null, null);
				break;
	
			case "sm-video-play":
				this.WebService.PlayVideo(this.ShowCode, null, null);
				break;
                    
            case "sm-clip-changed":
            	if(this.ShowCode != message.clip.ShowCode)
            	{
            		if(this.ShowCode != null)
            		{
            			this.WebService.EndVideo(this.ShowCode, null, null);
            		}
            		this.ShowCode= message.clip.ShowCode;
            		this.WebService.StartVideo(this.ShowCode, null, null);
            	}
//                	this.ClipView.Refresh(message.clip);
            	break;
		}
	};
	
	// create the tabs
	var tabsContainer= $('div#'+settings.tabsDivID);
	var tabsList= $('div#'+settings.tabsDivID+' > ul');
	if(settings.showReviews) {
		tabsList.append('<li><a href="#review-tab"><span>Reviews</span></a></li>');
		tabsContainer.append('<div id="review-tab">Lorem ipsum dolor</div>');
	}

	if(settings.showDiscussion) {
		tabsList.append('<li><a href="#discussion-tab"><span>Discussion</span></a></li>');
		tabsContainer.append('<div id="discussion-tab">Lorem ipsum dolor</div>');
	}

	if(settings.showSearch) {
		tabsList.append('<li><a href="#search-tab"><span>Search</span></a></li>');
	}

	$("#"+settings.tabsDivID).tabs();

	// now create the player (don't really, until after authentication?)		
	this.CreatePlayer();
	// set our global.
	thePlayer= this;

	if(this.LoginView.ValidAutologin()) {
		// will call ReloadALL(true) itself on valid login.
	} else {
		var attempted= false;

		// check for (and try) an OEM Login
	    if(settings.allowOEMLogin) 
	    {
	    	attempted= this.LoginView.AttemptOEMLogin();
	    }
	    
		// check for (and try) a SCORM Login
	    if(!attempted && settings.allowSCORMLogin)
	    {
	    	attempted= this.LoginView.AttemptSCORMLogin();
	    }
	    
	    // default state..
	    if(!attempted) this.ReloadAll(true);
	}
}

// don't know how to fold this into a closure; must investigate (one global function...)
function updateVideoStatus(message) {
	thePlayer.UpdateVideoStatus(message);
}

// if using the jwPlayer, this is called when the player is instantiated....
function playerReady(obj) {
	thePlayer.JWPlayer = document.getElementById(obj['id']);

	thePlayer.JWPlayer.addControllerListener("STOP","jw_stop_listener");
	thePlayer.JWPlayer.addControllerListener("PLAY","jw_play_pause_listener");
	thePlayer.JWPlayer.addControllerListener("ITEM", "jw_item_listener");
/*	
	thePlayer.JWPlayer.addControllerListener("PLAYLIST","jw_playlist_listener");
	thePlayer.JWPlayer.addControllerListener("ITEM","jw_item_listener");
	thePlayer.JWPlayer.addControllerListener("MUTE","jw_event_listener");
	thePlayer.JWPlayer.addControllerListener("PLAYLIST","jw_event_listener");
	thePlayer.JWPlayer.addControllerListener("RESIZE","jw_event_listener");
	thePlayer.JWPlayer.addControllerListener("SEEK","jw_event_listener");
	thePlayer.JWPlayer.addControllerListener("VOLUME","jw_event_listener");
*/

//	player.setStatusCallback('updateVideoStatus');
};

function jw_stop_listener(obj) {
	var message= new Object();
	
	message.type= 'sm-video-stop';
	thePlayer.UpdateVideoStatus(message);
}

function jw_play_pause_listener(obj) {
	var message= new Object();
	
	message.type= ((obj.state)?'sm-video-play':'sm-video-pause');
	thePlayer.UpdateVideoStatus(message);
}

function jw_item_listener(obj) {
	var items= thePlayer.JWPlayer.getPlaylist();
	if(obj.index>=0 && obj.index<items.length) {
		var item= items[obj.index];
		
		// determine the show code...
		var parts= item.copyright.split("|");
		if(parts.length>1) {
			// show code is parts[1]
			var message= new Object();
			message.type= 'sm-clip-changed';
			message.clip= new Object();
			message.clip.ShowCode= parts[1];
			thePlayer.UpdateVideoStatus(message);
		}
	}
}

/* Utility functions */
function getQueryVariableFromString(query, variable) {
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
	
	return null;
}

function getQueryVariable(variable) {
	return getQueryVariableFromString(window.location.search.substring(1), variable);
}
