var BIMUGCJS = {
	api: {
		autocompleteStart: function(element){
			this.dmaSearchSceElement = element;
			var str = $(this.dmaSearchSceElement).val();
			this.dmaSearchMode = this.utilCheckAreaEntry(str);
			
			//younews.stationmodel.getdma(friendly,id,dmaid,zipcode,shtfriendly,full)
			if(this.getDmaPermitted && this.dmaSearchMode !== "") {
				if(this.dmaSearchMode === "zip" ) {
					$.ajax({
						data: 'get=dmainfo&zip='+str,
						success: function(json) {
							BIMUGCJS.api.dmaResponse(json);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							if(typeof(console) !== 'undefined' && console !== null) {
								console.log("Problem with data!  textStatus: " +textStatus+ "  && Error thrown: " +errorThrown);
							}
						}
					});
				} else if (this.dmaSearchMode === "name" ) {
					$.ajax({
						data: 'get=dmainfo&name='+str,
						success: function(json) {
							BIMUGCJS.api.dmaResponse(json);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							if(typeof(console) !== 'undefined' && console !== null) {
								console.log("Problem with data!  textStatus: " +textStatus+ "  && Error thrown: " +errorThrown);
							}
						}
					});
				}
				this.getDmaPermitted = false;
				var timeout2 = null;
				timeout2 = setTimeout(function(){BIMUGCJS.api.getDmaPermitted = true;}, 500);			
			}
		},
		dmaResponse: function(response) {
			this.utilProcessForAutocomplete(response.dmas);
			if(response.dmas.length > 0) {
				$(this.dmaSearchSceElement)
					.autocomplete("option","source",this.autoCompleteData)
					.autocomplete("search");
			} 
		},
		eventHandlerStatusloginform: function(e) {
			//events from the login/status box in header
			if (e.target.id === 'userLoggedOut_signin') {
				$('#loginModal').jqmShow();
				$('#loginModal_uid').focus();
				$('#loginModal_pwd, #loginModal_uid').val("");
				this.utilClearErrors();
				return false;
			} else if(e.target.id === 'userLoggedIn_logout') {
				$('#userLoggedIn').hide();
				bimreg.logout();
				return false;
			} else if(e.target.id === 'resetModal_submit'|| (e.target.id === 'resetModal_email' && e.which === 13)) {
				if($('#resetModal_email').val() !== "") {
					this.activeElement = $('#resetModal');
					bimreg.rememberpassword($('#resetModal_email').val());
				}
				return false;
			} else if (e.target.id === 'userLoggedOut_join') {
				var registerUrl = (this.nationalSite) ? 
					this.BASE_PATH+'/register' :
					this.BASE_PATH+'?form=signup';
				window.location.replace(registerUrl);
				return false;
			} else if(e.target.id === 'loginModal_submit' || (e.target.id === 'loginModal_pwd' && e.which === 13)){
				this.sumbitLogin($('#loginModal_uid'), $('#loginModal_pwd'), $('#loginModal'));
				return false;
			}			
		},
		eventHandlerLoginform: function(e) {
			//events from login page (/login)
			if(e.target.id === 'YNloginformSubmit' || (e.target.id === 'YNloginformPass' && e.which === 13)){
				this.sumbitLogin($('#YNloginformUser'), $('#YNloginformPass'), $('#login-form'));
				return false;
			}
			if(e.target.id === "YNloginForgotPassword") {
				$('#YNloginform').hide();
				$('#YNforgotpasswordform').show();
			}
			if(e.target.id === 'YNloginformRestPass' || (e.target.id === 'YNloginformEmail' && e.which === 13)) {
				if($('#YNloginformEmail').val() !== "") {
					this.activeElement = $('#login-form');
					bimreg.rememberpassword($('#YNloginformEmail').val());
				} else {
					$('#login-form').find('.errormessage').html("<li>Please enter a valid email address</li>");
					$('#login-form').find('.error').show();																
				}
				return false;
			}
		},
		eventHandlerRegionsNav: function(e){
			if(e.type === 'mouseenter') {
				$('#locationSearch').show();
				$('#locationsNav').addClass('selected');
				$('#locationSearchInput').focus();
				$('#locationsNav, #locationSearch').bind('mouseleave', function(e) {
					BIMUGCJS.api.eventHandlerRegionsNav(e);
				});
			} else if (e.type === 'mouseleave') {
				$('#locationsNav').removeClass('selected');
				$('#locationSearch').hide();
				$('#locationSearchInput').autocomplete("close");
			}
			if((e.target.id === "locationSearchInput" || e.target.id === "locationSearchInputRT") && e.type === "keypress") {
				var timeout = null;
				timeout = setTimeout(function(){BIMUGCJS.api.autocompleteStart(e.target);}, 250);			
				return false;
			}				
			return false;
		},
		eventHandlerProfileform: function(e){
			if (e.target.id === "saveChanges") {
				this.profileMode = "undefined";
				return false;
			} 
			if (e.target.id === "cancelChanges") {
				this.profileMode = "undefined";
				this.profilePrivateSetup();
				this.profileSwitchMode();
				return false;
			}
			if (e.target.id === "editProfile") {
				this.profileMode = "edit";
				this.profileSwitchMode();					
				return false;
			}
		},
		handleAuthFailure: function(event) {
			$('#userLoggedOut').hide();
			$('#userLoggedIn').hide();
		},
		handleAvatarUpdate: function(event) {
			document["AvatarEditor"].loadimage('http://bim-storage.s3.amazonaws.com/BIM/'+bimreg.getuserkey('key')+'.jpg');
		},
		handleRegAuthNoUser: function(event) {
			$(BIMUGCJS.api.activeElement).jqmHide();
			$('#userLoggedIn').hide();
			$('#userLoggedOut').show();
			if($('#profile').length > 0 && BIMUGCJS.api.userProfileRequested !== "undefined"){
				bimreg.getusers(BIMUGCJS.api.userProfileRequested);
			}
		},
		handlePasswordSent: function(event) {
			BIMUGCJS.api.utilClearErrors();
			$('#resetModal').jqmHide();
			$('#resetConfirmModal').jqmShow();	
		},
		handleCheckedUserNameAvailable: function(event) {
			BIMUGCJS.api.utilClearErrors();
			BIMUGCJS.api.utilShowError($(BIMUGCJS.api.activeElement), event.error);
		},
		handleFailedLogin: function(event) {
			$(BIMUGCJS.api.activeElement).find('.progress').hide().html('');
			BIMUGCJS.api.utilShowError($(BIMUGCJS.api.activeElement), event.error);
		},
		handleModalOpen: function(hash){
			hash.w.bind('click keypress', function(e) {
				BIMUGCJS.api.eventHandlerStatusloginform(e);
			});
			hash.w.show();
		},
		handleModalClose: function(hash){
			if($('#YNsubmission').length > 0 && !bimreg.loggedin) {
				$('#YNsubmission').hide();
				$('#YNsubmissionNotLoggedIn').show();
			}
			hash.w.unbind('click keypress');		
			hash.w.hide();
			hash.o.remove();
		},
		handleUserCreated: function(event){
			var redirectUrl = (BIMUGCJS.api.nationalSite) ? 
				BIMUGCJS.api.BASE_PATH+'/register?confirm=y' :
				BIMUGCJS.api.BASE_PATH+'?form=signup&confirm=y';
			window.location.replace(redirectUrl);		
		},
		handleUserNotCreated: function(event) {
			if(event.error !== 'undefined'){
				errortext = '<label for="general" generated="true" class="error">'+event.error+'</label>';
				$('#submitRegistration').parent().append(errortext);
			}
		},
		handleUserLogin: function() {
			var profileUrl = (BIMUGCJS.api.nationalSite) ? 
				BIMUGCJS.api.BASE_PATH+'/profile?user='+bimreg.getuserkey("username") :
				BIMUGCJS.api.BASE_PATH+'?profile='+bimreg.getuserkey("username");
			if($(BIMUGCJS.api.activeElement).hasClass('jqmWindow')) {
				$(BIMUGCJS.api.activeElement).jqmHide();
			}
			$(BIMUGCJS.api.activeElement).find('.progress').hide().html('');
			$(BIMUGCJS.api.activeElement).find('input:text, input:password').each(function(){ $(this).val(""); });
			$('#userLoggedOut').hide();
			$('#userLoggedIn').show();
				$('#userLoggedIn_welcome').html('Welcome, <a href="'+ profileUrl +'">'+bimreg.getuserkey("username")+'</a>');
			if(bimreg.getuseravatar()) {
				$("#userLoggedIn_image").html('<a href="'+ profileUrl +'" ><img src="http://bim-storage.s3.amazonaws.com/BIM/'+bimreg.getuserkey('key')+'.jpg" border="0"></a>');
			}
			if($('form[name=commentForm]').length > 0) {
				$('form[name=commentForm]').find('input[name=name]').val(bimreg.getuserkey("username"));
			}
			if($('#profile').length > 0 && BIMUGCJS.api.userProfileRequested !== "undefined"){
				if (BIMUGCJS.api.userProfileRequested === bimreg.getuserkey("username")) {
					BIMUGCJS.api.profilePrivateSetup();
					BIMUGCJS.api.profileSwitchMode();
					$('#profile-save').bind('click',function(e) {
						BIMUGCJS.api.eventHandlerProfileform(e);
					});
				} else {
					bimreg.getusers(BIMUGCJS.api.userProfileRequested);
				}
			}
		},
		handleUserLogout: function() {
			$('#loginModal').jqmHide();
			$('#userLoggedIn').hide();
			$('#userLoggedOut').show();
		},
		initLocationSearch: function() {
			$('#locationsNav, #locationSearch').bind('mouseenter', {api: this}, function(e) {
				e.data.api.eventHandlerRegionsNav(e);
			});
			$('#locationSearchInput, #locationSearchInputRT').bind('click keypress', {api: this}, function(e) {
				e.data.api.eventHandlerRegionsNav(e);
			});
			$('#locationSearchInput').autocomplete({
				source: BIMUGCJS.api.autoCompleteData,
				focus: function(event, ui) { 
					$('#locationsNav').addClass('selected');
					return false;
				},
				select: function(event, ui) {
					var url="/location/"+ui.item.shtareaname;
					window.location.replace(url);		
					return false;
				},
				open: function(event, ui) {
					$('#locationsNav').addClass('selected');
					$('#locationsNav, #locationSearch').unbind('mouseleave');
				},
				close: function(event, ui) {
					//$('#locationSearchInput').val('');
				},
				position: {
					at: "center bottom",
					collision: "none",
					my: "center top",
					offset: "0 10"
				}
			})
			.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + " | " + item.areaname + "</a>" )
					.appendTo( ul );
			};
			$('#locationSearchInputRT').autocomplete({
				source: BIMUGCJS.api.autoCompleteData,
				focus: function(event, ui) { 
					return false;
				},
				select: function(event, ui) {
					var url="/location/"+ui.item.shtareaname;
					window.location.replace(url);		
					return false;
				},
				open: function(event, ui) {
					$('#rightcol').find('.border').addClass('tall');
				},
				close: function(event, ui) {
					$('#rightcol').find('.border').removeClass('tall');	
	//				$('#locationSearchInputRT').val('');
				}
			})
			.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + " | " + item.areaname + "</a>" )
					.appendTo( ul );
			};
			$('#locationSearchInputRT').autocomplete( "widget" ).addClass('rtCol');
		},
		initRegFormValidation: function() {
			$("#YNregisterform").validate({
				rules: {
					firstname: "required",
					lastname: "required",
					username: {
						required: true,
						minlength: 5,
						nospaces: true
					},
					password1: {
						required: true,
						minlength: 5
					},
					password2: {
						required: true,
						minlength: 5,
						equalTo: "#password1"
					},
					email1: {
						required: true,
						email: true
					},
					email2: {
						required: true,
						email: true,
						equalTo: "#email1"
					}
				},
			   submitHandler: function(form) {
					var user = {
						username : $(form).find('input[name=username]').val(),
						first_name : $(form).find('input[name=firstname]').val(),
						last_name : $(form).find('input[name=lastname]').val(),
						birth_date : $(form).find('#birthyear option:selected').val()+"-"+$(form).find('#birthmonth option:selected').val()+"-"+$(form).find('#birthday option:selected').val()+"T00:00:00Z",
						zip_code : $(form).find('input[name=zip]').val(),
						phone_number : $(form).find('input[name=phonenumber]').val(),
						email: $(form).find('input[name=email1]').val(),
						password: $(form).find('input[name=password1]').val()
					};
					if($(form).find('input[name=newsletter]').checked) {
						user.newsletter_younews = 1;
					} else {
						user.newsletter_younews = 0;
					}
					bimreg.createuser(user);
			   },
			   invalidHandler: function(form, validator) {
				  var errors = validator.numberOfInvalids();
				  if (errors) {
					var message = errors === 1
					  ? 'You missed 1 field. It has been highlighted'
					  : 'You missed ' + errors + ' fields. They have been highlighted';
					$("div.error span").html(message);
					$("div.error").show();
				  } else {
					$("div.error").hide();
				  }
				}
			});	
		},
		initProfileFormValidation: function() { // Take values from form and update the avatar
			$("#ynprofileform").validate({
				rules: {
					zipcode:{postalcode : true},
					phonenumber:{phoneUS : true}
				},
			   submitHandler: function(form) {
					BIMUGCJS.api.utilClearErrors();
					var user = {
						first_name : $(form).find('input[name=firstname]').val(),
						last_name : $(form).find('input[name=lastname]').val(),
						about_me : $(form).find('input[name=about]').val(),
						website : $(form).find('input[name=website]').val(),
						location : $(form).find('input[name=location]').val(),
						zip_code : $(form).find('input[name=zip]').val(),
						phone_number : $(form).find('input[name=phonenumber]').val()
					};
					if($(form).find('input[name=newsletter]').checked) {
						user.newsletter_younews = 1;
					} else {
						user.newsletter_younews = 0;
					}
					bimreg.updateprofile(user);
			   },
			   invalidHandler: function(form, validator) {
				  var errors = validator.numberOfInvalids();
				  if (errors) {
					var message = errors === 1
					  ? 'You missed 1 field. It has been highlighted'
					  : 'You missed ' + errors + ' fields. They have been highlighted';
					$("div.error span").html(message);
					$("div.error").show();
				  } else {
					$("div.error").hide();
				  }
				}
			});	
		},
		profilePrivateSetup: function() {
			$('#profile-mini').hide();
			$('#profile-bio div[name=username]').html(bimreg.getuserkey('username'));
			$('#profile-bio input[name=website]').val(bimreg.getuserkey('website'));
			$('#profile-bio input[name=location]').val(bimreg.getuserkey('location'));
			$('#profile-bio textarea[name=about]').val(bimreg.getuserkey('about_me'));
			$('#profile-personalInfo input[name=firstname]').val(bimreg.getuserkey('first_name'));
			$('#profile-personalInfo input[name=lastname]').val(bimreg.getuserkey('last_name'));
			$('#profile-personalInfo').find('#email').html(bimreg.getuserkey('email'));
			$('#profile-mobile input[name=phonenumber]').val(bimreg.getuserkey('phone_number'));
			$('#profile-zip input[name=zipcode]').val(bimreg.getuserkey('zip_code'));
			if(bimreg.getuseravatar() === "undefined"){
				$('#avatarImage').html('<img src="http://media.younewstv.com/designimages/yn_default_avatar_100x100.png"/>');		
			}else{
				$('#avatarImage').html('<img src="http://bim-storage.s3.amazonaws.com/BIM/'+bimreg.getuserkey('key')+'.jpg"/>');				
			}
		},
		profileSwitchMode: function() {
			$('#profile-edit').show();
			if (BIMUGCJS.api.profileMode === "edit") {
				$('#profile-user-content, #paginate-user-content').hide();
				$(':input').removeAttr("disabled");
				$('#editProfile').hide();
				$('#saveChanges, #cancelChanges, #deleteAccount').show();
				BIMUGCJS.api.utilLoadAvatarEditor();
				$('#profile-avatar h2, #avatarEditor, #profile-avatar span').show();
				$('#avatarImage').hide();
			} else {
				$('#avatarImage').show();
				$('#profile-avatar h2, #avatarEditor, #profile-avatar span').hide();
				$('#profile-user-content, #paginate-user-content').show();
				$('#profile-edit :input').attr('disabled', 'disabled');
				$('#editProfile').removeAttr("disabled").show();
				$('#saveChanges, #cancelChanges, #deleteAccount').hide();
			}
			$('#profileUserContent').show();
			$('#profile-personalInfo input[name=password1]').password_strength({
				container: "#passStrengthMeter", 
				minLength: 6
			});
			$('#profile-bio textarea[name=about]').NobleCount('#charCount1',{
				on_negative: 'charCountRed',
				on_positive: 'charCountGreen',
				max_chars: 160
			});		
		},
		profilePublicSetup: function(){
			$('#profile-mini #userName').html(bimreg.getexternaluserkey('username', BIMUGCJS.api.userProfileRequested));
			$('#profile-mini #userBio').html(bimreg.getexternaluserkey('aboutme', BIMUGCJS.api.userProfileRequested));
			$('#profile-mini #userLocation').html(bimreg.getexternaluserkey('location', BIMUGCJS.api.userProfileRequested));
			var website = bimreg.getexternaluserkey('website', BIMUGCJS.api.userProfileRequested);
			if (website.indexOf('http://') > -1){
				$('#profile-mini #userWeb').html('<a href="'+website+'" target="_blank">'+website.substring(7)+'</a>');
			} else {
				$('#profile-mini #userWeb').html('<a href="http://'+website+'" target="_blank">'+website+'</a>');						
			}
			var userAvatar;
			if (bimreg.getexternaluserkey('url', BIMUGCJS.api.userProfileRequested)) {
				userAvatar = bimreg.getexternaluseravatar(BIMUGCJS.api.userProfileRequested);
			} else {
				userAvatar = 'http://media.younewstv.com/designimages/yn_default_avatar_100x100.png';
			}
			$('#profile-mini #userAvatar').html('<img src="'+userAvatar+'" border="0" />');
			$('#profile-mini').show();
		},
		profileUpdateResponse: function(event) {
			//this.utilClearErrors();
			$('#profile-personalInfo input[name=password1], #profile-personalInfo input[name=password2]').val('');
			if (this.profileMode === "edit") {
				$(':input').removeAttr("disabled");
				$('#editProfile').hide();
				$('#saveChanges, #cancelChanges, #deleteAccount').show();
			} else {
				$('#profile-edit :input').attr('disabled', 'disabled');
				$('#editProfile').removeAttr("disabled").show();
				$('#saveChanges, #cancelChanges, #deleteAccount').hide();
			}
		},
		sumbitLogin: function(userEL, passEL, formEL) {
			this.utilClearErrors();
			if(userEL.val() === '' || passEL.val() === '') {
				$(formEL).find('.progress').hide();
				$(formEL).find('.errormessage').html('<li>Please enter a username and password before logging in.</li>');
				$(formEL).find('.error').show();
			} else {
				/*--- Assemble Object for xhrStatus() ---*/
				var imgObj = BIMJS.xhrGen.prototype.loadingImg = {
					tag : 'img',
					src : 'http://media.younewstv.com/designimages/yn_think_FFFFFF_011209.gif',
					id : 'loading'
				};
				$(formEL).find('.progress').html('<'+imgObj.tag+' src="'+imgObj.src+'" id="'+imgObj.id+'" /><p class="updating">Logging in...</p>').show();
				this.activeElement = formEL;
				bimreg.login(userEL.val(),passEL.val());
			}
		},
		utilAdjustAutocompletePosition: function(inputObj) {
			var temp = $('#locationSearchInput').autocomplete('option', 'position');
		},
		utilCheckAreaEntry: function(str) {
			var digitTest = /^\d+$/;
			var zipTest = /^\d{5}$/;
			if (digitTest.test(str) && zipTest.test(str)) {
				return "zip";
			} else if (!digitTest.test(str)) {
				return "name";
			} else {
				return "";
			}
		},
		utilClearErrors: function() {
			$('.error').hide();
			$('.errormessage').html('');
		},
		utilFixCapitalization: function(str) {
			var strArray = str.split(" ");
			var tempStr = "";
			var k;
			for (k=0; k<strArray.length; k++) {
				tempStr += strArray[k].substr(0, 1).toUpperCase() + strArray[k].substr(1).toLowerCase();
				if(k !== strArray.length-1) {tempStr += " ";}
			}
			return tempStr;		
		},
		utilLoadAvatarEditor: function(){
			var avatar;
			var avatarso;
			if (bimreg.getuseravatar() && bimreg.getuseravatar().length > -1) {
				avatar = encodeURIComponent('http://bim-storage.s3.amazonaws.com/BIM/'+bimreg.getuserkey('key')+'.jpg');
			} else {
				avatar = encodeURIComponent('http://media.younewstv.com/designimages/yn_default_avatar_100x100.png');
			}
			if(gup('swf')){
				avatarso = new SWFObject("http://media.younewstv.com/designvideo/"+gup('swf')+".swf", "AvatarEditor", "210", "210", "9", "#000000");				
			} else {
				avatarso = new SWFObject("http://media.younewstv.com/designvideo/AvatarEditor20110308.swf", "AvatarEditor", "210", "210", "9", "#000000");
			}
			avatarso.useExpressInstall('http://media.younewstv.com/designvideo/expressinstall.swf');
			avatarso.addParam("wmode", "opaque");
			avatarso.addParam("AllowScriptAccess", "always");
			avatarso.addParam("AllowFullScreen", "true");
			avatarso.addVariable("img", avatar);
			if(document.domain.indexOf('stage') > -1 || document.domain.indexOf('dev') > -1){
				avatarso.addVariable("env", "stage");
			}
			avatarso.write("avatarEditor");
		},
		utilMoveToError: function() {
			var targetDiv = $('li[name=error]:first').parents('fieldset');
			var destinationVal = $(targetDiv).offset();
			$(document).scrollTop(destinationVal.top);			
		},
		utilProcessForAutocomplete: function(dmaList) {
			this.autoCompleteData = [];
			var dmaCompare = [];
			var i, j, k;
			for (i=0; i<dmaList.length; i++) {
				var matchFound = false;
				for (j=0; j<dmaCompare.length; j++) {
					if (dmaList[i].zipcodename === dmaCompare[j].zipcodename && dmaList[i].stateabbreviation === dmaCompare[j].stateabbreviation) {
						matchFound = true;
						if(dmaList[i].destid!=="0" && dmaList[i].destid!=="" ) {
							for (k=0; k<this.autoCompleteData.length; k++) {
								if (this.autoCompleteData[k].id === dmaList[i].zipcode) {
									this.autoCompleteData[k].destidarray.push(dmaList[i].destid);									
								}
							}
						}
						break;							
					}
				}
				if (!matchFound) {
					dmaCompare.push(dmaList[i]);
					var label;
					if(this.dmaSearchMode === "zip"){
						label = dmaList[i].zipcode + " - " + this.utilFixCapitalization(dmaList[i].zipcodename)+", "+dmaList[i].stateabbreviation;
					} else {
						label = this.utilFixCapitalization(dmaList[i].zipcodename)+", "+dmaList[i].stateabbreviation;
					}
					var destIds = [];
					destIds.push(dmaList[i].destid);
					var temp = {"id":dmaList[i].zipcode, "label": label , "value": dmaList[i].zipcode, "dmaid":dmaList[i].dma, "destid":dmaList[i].destid, "areaname":dmaList[i].areaname,"shtareaname":dmaList[i].shtareaname, "destidarray": destIds };
					this.autoCompleteData.push(temp);
				}
			}
			return true;
		},
		utilShowError: function(el, errortext) {
			$(el).find('.errormessage').html(errortext);
			$(el).find('.error').show();
		},
		activeElement: "undefined", //this is a placeholder EL for whatever form, etc. is currently being processed through GENUS, so the callbacks can reference it.
		apiParams: "undefined",
		apiPath: "undefined",
		autoCompleteData: [],
		dmaSearchMode: "undefined",
		dmaSearchSceElement: "undefined",
		getDmaPermitted: true,
		nationalSite: false,
		uploadProgressTimer: "undefined",
		userProfileRequested: "undefined",
		profileMode: "undefined",
		reinitCount: 0,
		BASE_PATH: 'undefined',
		BASE_URL: "http://"+document.domain+"/internal/"
	},
	init: function(basePath, isNatSite) {
		this.api.BASE_PATH = basePath;
		this.api.nationalSite = isNatSite;
		if(this.api.nationalSite) {
			this.api.initLocationSearch();
		}
		// XHR Default Config
		bimreg.listener.addListener("regAuthNoUser",this.api.handleRegAuthNoUser);
		bimreg.listener.addListener("failedLogin",this.api.handleFailedLogin);
		bimreg.listener.addListener("userLogin", this.api.handleUserLogin);
		bimreg.listener.addListener("userLogout",this.api.handleUserLogout);
		bimreg.listener.addListener("passwordSent",this.api.handlePasswordSent);
		bimreg.listener.addListener("checkedUserNameAvailable",this.api.handleCheckedUserNameAvailable);
		bimreg.listener.addListener("checkedUserExists",this.api.handleCheckedUserNameAvailable);
		bimreg.listener.addListener("userCreated",this.api.handleUserCreated);
		bimreg.listener.addListener("userNotCreated",this.api.handleUserNotCreated);
		bimreg.listener.addListener("initfail",this.api.handleInitfail);
		bimreg.listener.addListener("externaluserloaded",this.api.profilePublicSetup);
		bimreg.listener.addListener("avatarupdated",this.api.handleAvatarUpdate);
		bimreg.listener.addListener("updateProfile",this.api.profileUpdateResponse);
		
		if(gup('user')){
			this.api.userProfileRequested = gup('user');
			this.api.profileMode = gup('mode');
		} else if (gup('profile')){
			this.api.userProfileRequested = gup('profile');
			this.api.profileMode = gup('mode');			
		}
		
		$.ajaxSetup({
			async: false,
			cache: false,
			dataType: "json",
			url: this.api.BASE_URL
		});
		$('.spotlight-border').bind('click', function(e){
			$('.spotlightVideo').show();
			return false;
		});
		$('#loginModal').jqm({
			trigger: '.openLoginModal',
			onShow: BIMUGCJS.api.handleModalOpen,
			onHide: BIMUGCJS.api.handleModalClose
		});
		$('#loginModal').jqmAddClose('.closeModal, .openResetModal');
		$('#resetModal').jqm({
			trigger: '.openResetModal',
			onShow: BIMUGCJS.api.handleModalOpen
		});
		$('#resetModal').jqmAddClose('.closeModal');
		$('#resetConfirmModal').jqm({onHide: function(){ location.reload(true); }});
		$('#resetConfirmModal').jqmAddClose('.closeModal');
		if($("#deleteConfirm").length == 1){
			$("#deleteConfirm").jqm();
			$("#deleteAccount").click(function(){
				$("#deleteConfirm").removeClass("hide").jqmShow();
			});
			$("#deleteConfirm .proceed").click(function(){
				bimreg.deleteuser();
				return false;
			});
			$("#deleteConfirm .cancel").click(function(){
				$("#deleteConfirm").jqmHide();
				return false;
			});
		}
		$('#userStatus').bind('click', {api: this.api}, function(e) {
			e.data.api.eventHandlerStatusloginform(e);
		});
		if($('#login-form').length > 0){
			$('#login-form').bind('click keypress', {api: this.api}, function(e) {
				e.data.api.eventHandlerLoginform(e);
			});
		}
		if($('#YNregisterform').length > 0) {
			$('#signup-username-password input[name=username]').focus();
			$('#signup-username-password input[name=password1]').password_strength({
				container: "#passStrengthMeter", 
				minLength: 6
			});
			bimreg.listener.addListener("validatitonLibLoaded", this.api.initRegFormValidation);			
		} 
		if($('#profile').length > 0) {
			bimreg.listener.addListener("validatitonLibLoaded", this.api.initProfileFormValidation);			
		} 

		if($('#flagModal').length > 0) {
			var flagModal = $('#flagModal');
			function openFlagModal(){
				flagModal.show();	
			};
			flagModal.jqm({trigger: '.openFlagModal',onShow:openFlagModal});
			flagModal.jqmAddClose('.closeModal');
			$(flagModal).find('select').change(function(e) {
				if($(this).find('option:selected').val() === 'Other') {
					$(flagModal).find('textarea').show();
				} else {
					$(flagModal).find('textarea').hide();
				}
			});
			$('#flagModal form').bind('submit', {api: this.api}, function(e) {
				e.preventDefault();
				e.stopPropagation();
				e.cancelBubble = true; //MSIE
				if($('#flagModal select option:selected').val() === 'Select One') {
					$('#flagModal p[name=flagError]').text('Please choose an option from the menu or click the X to cancel.').show();
				}
				else if($('#flagModal select option:selected').val() === 'Other' && $('#flagModal textarea').val() === '') {
					$('#flagModal p[name=flagError]').text('Please specify why you\'re flagging this content, choose another option from the menu or click the X to cancel.').show();
				}
				else {
					$('#flagModal p[name=flagError]').hide();
					$('#flag a.openFlagModal').replaceWith('This has been flagged for moderation.');
					var body;
					if($('#flagModal select option:selected').val() === 'Other') {
						body = 'element.body='+$('#flagModal textarea').val();
					} else {
						body = 'element.body='+$('#flagModal select option:selected').val();
					}
					var formVal = $(e.target).serialize();
					var params = body+'&'+formVal;
					$('#flagModal').jqmHide(); //hide modal window
					$.ajax({
					   type: "GET",
					   url: 'http://'+document.domain+'/m',
					   data: params,
					   dataType: "html"
					 });					
				}
			});
		}
		return this.api;
	}
};

