//these are used for flash external interface readiness check
var jsReady = false;

function isJavascriptReady() {
    return jsReady;
}

function getJSONData() {
	return $V("TLEVENTDATA");
}

var Timeline = new Class({
    initialize: function() {
		this.memberId = $V('Profile', 'memberId');
		this.confirmDlg = null;

		var tl = $('timeline');
		if (tl !== null) {
			this.startFlash();
			//strip all whitespace, tabs, linefeeds, and carriage rutrns from div, then check content
			var c = tl.innerHTML;
			c = c.split(' ').join('');
			c = c.split('\n').join('');
			c = c.split('\r').join('');
			c = c.split('\t').join('');
			if (c === "") {
				tl.set('html', "" +
						"<!-- this content only displayed if flash player not installed and express install can't be started -->" +
						"<div class='mod-content'>" +
						"<div class='bd'>" +
						"<center>" +
						"<b>Your LifeStory requires the Flash Player</b>" +
						"<br /><br />" +
						"<a href='http://www.adobe.com/go/getflashplayer'>" +
						"<img src='http://s.bebo.com/img/get_adobe_flash_player.png' alt='Get Adobe Flash Player'>" +
						"</a>" +
						"</center>" +
						"<br />" +
						"</div>" +
						"</div>" +
				"");
			}
		}	

		var changeLayout = $('change-layout');
		if (changeLayout !== null) {
			changeLayout.addEvent('click', this.onClickChangeLayout.bindWithEvent(this));
		}

		jsReady = true;	
	},


	startFlash: function() {
		var height = $V('timeline', 'mini') ? "200": "375";
		var flash= new SWFObject("http://" + $V('timeline', 'webDomain') + "/img/flash/timeline.swf?fp=" + $V('timeline', 'fp'), "flash", "760", height, "9.0.0");
		flash.addParam("quality", "high");
		flash.addParam("align", "TL");
		flash.addParam("scale", "showall");
		flash.addParam("menu", "false");
		flash.addParam("wmode", "transparent");
		flash.addParam("AllowScriptAccess", "always");
		flash.addVariable("webDomain", $V('timeline', 'webDomain'));
		flash.addVariable("memberId", $V('Profile', 'memberId'));
		var allowEdit = $V('timeline', 'myProfile')  || $V('timeline', 'moderator');
		flash.addVariable("allowEdit", allowEdit);
		flash.addVariable("flashUrl", "http://" + $V('timeline', 'webDomain') + "/img/flash/timeline.swf?fp=" + $V('timeline', 'fp'));
		var dataUrl = $V('timeline', 'useXml') ? "http://" + $V('timeline', 'webDomain') + "/c/timeline/timeline_xml?memberId=" + this.memberId : "USE_JSON";
		flash.addVariable("dataUrl", dataUrl);
		flash.addVariable("useTimelineSkin", $V('timeline', 'useTimelineSkin'));
		flash.addVariable("skinBgUrl", $V('timeline', 'skinBgUrl'));
		flash.addVariable("scrollToDate", $V('timeline', 'scrollToDate'));
		flash.addVariable("monthNames", $I.transf('Jan', 'profilelayout') + "," + $I.transf('Feb', 'profilelayout') + "," + $I.transf('Mar', 'profilelayout') + "," + $I.transf('Apr', 'profilelayout') + "," + $I.transf('May', 'profilelayout') + "," + $I.transf('Jun', 'profilelayout') + "," + $I.transf('Jul', 'profilelayout') + "," + $I.transf('Aug', 'profilelayout') + "," + $I.transf('Sep', 'profilelayout') + "," + $I.transf('Oct', 'profilelayout') + "," + $I.transf('Nov', 'profilelayout') + "," + $I.transf('Dec', 'profilelayout'));
		flash.addVariable("editLinkText", $I.transf('Edit', 'profilelayout'));
		flash.addVariable("deleteLinkText", $I.transf('Delete', 'profilelayout'));
		flash.addVariable("moreLinkText", $I.transf('See More', 'profilelayout') + "...");
		flash.addVariable("closeButtonText", $I.transf('Close', 'profilelayout'));
		flash.addVariable("createButtonLabel", $I.transf('Create Event', 'profilelayout'));
		flash.addVariable("showOptions", $V('timeline', 'showTimelineOptions'));
		flash.addVariable("optionsButtonLabel", $I.transf('Options', 'profilelayout'));
		flash.addVariable("nuxTextUpper", $I.transf('Hi', 'profilelayout') + " " + $V('timeline', 'firstName') + ", " + $I.transf('welcome to Bebo. Get started by showing off your Timeline!', 'profilelayout'));
		flash.addVariable("nuxTextLower", $I.transf('Start by', 'profilelayout') + " <a href='/PhotoUpload.jsp'><font color='#006699'>" + $I.transf('adding photos', 'profilelayout') + "</font></a> " + $I.transf('or', 'profilelayout') + " <a href='javascript:bebo.Timeline.AddEntry();'><font color='#006699'>" + $I.transf('tell a story', 'profilelayout') + "</font></a> " + $I.transf('and they will automagically show up in this Timeline.', 'profilelayout') + " " + $I.transf('Still not sure?', 'profilelayout') + " <a href='/bebo_lifestory'><font color='#006699'>" + $I.transf('Learn more', 'profilelayout') + "...<font></a>");
		flash.addVariable("nonOwnerTextUpper", $I.transf('This person has not created a Timeline yet!', 'profilelayout'));
		flash.addVariable("nonOwnerTextLower", $I.transf('Why not send them a', 'profilelayout') + " <font color='#006699'><a href='/mail/MailCompose.jsp?ToMemberId=" + this.memberId + "'>" + $I.transf('message', 'profilelayout') + "</a></font> " + $I.transf('and tell them to start it?', 'profilelayout'));
		flash.addVariable("stageWidth", "760");
		flash.addVariable("stageHeight", height);
		flash.useExpressInstall($V('timeline', 'staticServerRoot') + "/img/flash/expressInstall.swf");
		flash.write("timeline");
	},
	
	
	displayOptions: function() {
		var changeLayout = $('change-layout');
		var idArray = changeLayout.get('href').split('-');
		var currentLayout = idArray[2];
		var currentShowPhoto = idArray[3]; 
		
		var checkedA = "";
		var checkedB = "";
		var checkedC = "";
		var checkedD = "";
		var checkedE = "";
		var selectedA = "";
		var selectedB = "";
		var selectedC = "";
		var selectedD = "";
		var selectedE = "";
		var checkedF = "";
		
		if (currentLayout == "A") {
			checkedA = "checked";
			selectedA = " class=\"selected\"";
		}
		if (currentLayout == "B") {
			checkedB = "checked";
			selectedB = " class=\"selected\"";
		}
		if (currentLayout == "C") {
			checkedC = "checked";
			selectedC = " class=\"selected\"";
		}
		if (currentLayout == "D") {
			checkedD = "checked";
			selectedD = " class=\"selected\"";
		}
		if (currentLayout == "E") {
			checkedE = "checked";
			selectedE = " class=\"selected\"";
		}
		if (currentShowPhoto == "true") {	
			checkedF = "checked";
		}
	    var text = '<div id="layout-options" class="box-bd">' +
		        '<h4>'+$I.transf('Main module layout', 'profilelayout')+ '</h4> '+
		        '<ul id="choices">' +
		        '<li' + selectedC + '>' +
		        '<label>' +
		        '<img src="/img/illus_aboutmetimeline.png" width="134" height="123" alt="About Me and Timeline" />' +
		        '<span>' +
		        $I.transf('About Me & Timeline', 'profilelayout') +
		        '</span>' +
		        '</label>' +
		        '<input type="radio" class="layout-choice" name="layout-choice" value="C"' + checkedC + ' />' +
		        '</li>' +
		        '<li' + selectedB + '>' +
		        '<label>' +
		        '<img src="/img/illus_aboutme.png" width="134" height="123" alt="About Me only" />' +
		        '<span>' +
		  		$I.transf('About Me only', 'profilelayout')+
		        '</span>' +
		        '</label>' +
		  		'<input type="radio" class="layout-choice" name="layout-choice" value="B" ' + checkedB + '/>' +
		        '</li>' +
		        '<li' + selectedA + '>' +
		        '<label><img src="/img/illus_timelineonly.png" width="134" height="123" alt="Timeline only" />' +
		        '<span>' +
		  		$I.transf('Timeline only', 'profilelayout') +
		        '</span>' +
		        '</label>' +
		  		'<input type="radio" class="layout-choice" name="layout-choice" value="A" ' + checkedA + ' />' +
		        '</li>' +
	        	'<li' + selectedE + '>' +
	        	'<label><img src="/img/illus_skinbgonly.png" width="134" height="123" alt="Timeline only" />' +
	        	'<span>' +
	  			$I.transf('Skin Image only', 'profilelayout') +
	        	'</span>' +
	        	'</label>' +
	  			'<input type="radio" class="layout-choice" name="layout-choice" value="E" ' + checkedE + ' />' +
	        	'</li>' +	        
	        	'<li' + selectedD + '>' +
	        	'<label>' +
	        	'<img src="/img/illus_nomodule.png" width="134" height="123" alt="No module" />' +	        
		        '<span>' +
		  		$I.transf('Hide entire module', 'profilelayout') +
		        '</span>' +
		        '</label>' +
		  		'<input type="radio" class="layout-choice" name="layout-choice" value="D" ' + checkedD + ' />' +
		        '</li>' +
		        '</ul>' +
		        '<h4>' + $I.transf('Timeline options', 'profilelayout') + '</h4>' +
		        '<input type="checkbox" id="showAlbums" ' + checkedF + ' />' +
		        '<label>' + $I.transf('Show photo albums in Timeline', 'profilelayout') + '</label>' +
		        '</div>' + 
		        '<div class="form-buttons">' +
		        '<span style="display: none;" id="statusMsg"></span>' +
		        '<span class="button-wrapper">' +
		        '<a  href="#" class="button" id="save_button">' + $I.transf('Save Settings', 'profilelayout') + '</a>' +
		        '</span>' +
		        '<span class="button-wrapper cancel">' +
		        '<a href="#"  class="button" id="cancel_button">' + $I.transf('Cancel') + '</a>' +
		        '</span>' +
		        '</div>' +
				'</div>';

		var confirmContainer = new Element('div', {
		    'styles' : {
		       'display': 'none',
		       'text-align': 'left',
		       'position': 'relative'
		    }
		});
	    confirmContainer.set('html', text);
		this.confirmDlg = new bebo.ui.Lightbox( { title : $I.transf('Layout Options', 'profilelayout'), 
			                                 element : confirmContainer, 
			                                 position : 'relative',
			                                 className : 'bebobox layout-box'} );
		$$('#choices input[type=radio].layout-choice').each(function(elem) {
			elem.addEvent('click', function(e) {
				var oldChoice = $('choices').getElement('li[class=selected]');
				if (oldChoice !== null) {
					oldChoice.removeClass('selected');
				}
				elem.getParent('li').addClass('selected');
		    });
		});	
		$('save_button').addEvent('click', this.saveSettingAjax.bindWithEvent(this));
		$('cancel_button').addEvent('click', this.confirmDlg.close.bindWithEvent(this.confirmDlg));
		this.confirmDlg.show();
	},
	
	onClickChangeLayout: function(event) {
		event.preventDefault();
		this.displayOptions();
	},

	sendSaveLayoutAjaxRequest: function(layout, showPhoto) {
	   tmp = new Request.JSON( {
	        url: '/c/profile/ajax_set_profile_layout',
	        data : {
	     	    ProfileLayoutCd: layout,
	     	    DisplayPhotosInTimelineInd: showPhoto,
	     	    MemberId: this.memberId
	        },
	        onComplete : function(json) {
	        	if (json.message == 'error') {
	        		$('statusMsg').show();
                    $('statusMsg').set('text', $I.transf("There was a problem with your request. Please try again later.", 'profilelayout'));
	        	} else {
	        		this.confirmDlg.close();
	        		window.location.href = "/c/profile?MemberId=" + this.memberId;
                }
	        }.bind(this),
	        onRequest : function() {
               $('statusMsg').show();
	        }
	   	}).send();  
	},

	saveSettingAjax: function(event) {
	    var layout;

	    $$('.layout-choice').each(function(item, index){
	        if (item.get('checked')) {
	          layout = item.get('value');
	        }
	    });

	    var showPhotoYN = 'N';
	    var showPhoto = $('showAlbums').get('checked');
	    if (showPhoto) {
	        showPhotoYN = 'Y';
	    }
	    this.sendSaveLayoutAjaxRequest(layout, showPhotoYN);
	},
	
	addEntry: function() {
		document.location = "/c/timeline/add_entry?MemberId="+ $V('Profile', 'memberId');	
	}
});

var Profile = new Class({
    initialize: function() {
		this.memberId = $V('Profile', 'memberId');
		this.isWindowsLiveEnabled = $V('profile_options', 'isWindowsLiveEnabled');
		this.canShowMsnIeLinks = $V('profile_options', 'canShowMsnIeLinks');
		this.im_msn_tx = $V('profile_options', 'im_msn_tx');
		this.store_id = $V('profile_options', 'store_id');
		this.storeParam = $V('profile_options', 'storeParam');
		this.partner_id = $V('profile_options', 'partner_id');
		this.partnerPrefix = $V('profile_options', 'PartnerPrefix');
		this.ipCountryCd = $V('profile_options', 'ipCountryCd');
		this.displayName = $V('profile_options', 'display_name');
		this.searchUrl = $V('profile_options', 'searchUrl');
		this.storeUrl = $V('profile_options', 'storeUrl');
		
		$$('h2[id^=profile_mod_h2_]').each(function(item, index) {
			item.addEvent('click', this.onClickBeboModuleHideShow.bindWithEvent(this, item));
		}, this);

		$$('img[id^=app_list_]').each(function(item, index) {
			item.addEvent('click', this.onClickScrollToApp.bindWithEvent(this, item));
		}, this);
		
		
		var el = $('profile_options_delete_entire');
		if (el !== null) {
			el.addEvent('click', this.onClickDeleteEntireGroup.bindWithEvent(this));
		}
		
		el = $('profile_options_buy_songs');
		if (el !== null) {
			//need beboITunes for itunes.js
			if (typeof beboITunes == 'undefined') {
				beboITunes = {
					BandSearchUrl : '',
					PartnerPrefix : '',
					StoreId : '',
					StoreUrl : ''
 				};
			}
			beboITunes.BandSearchUrl = this.searchUrl;
			beboITunes.PartnerPrefix = this.partnerPrefix;
			beboITunes.StoreId = this.storeParam;
			beboITunes.StoreUrl = this.storeUrl;
			
			el.addEvent('click', this.onClickBuySongs.bindWithEvent(this));
		}
		
		var aimWelcome = $('nux-welcome');
		if (aimWelcome !== null) {
			aimWelcome.getElement('a.close').addEvent('click', this.onClickAimWelcome.bindWithEvent(this));
		}
		
 		if (this.isWindowsLiveEnabled) {
 			if (this.canShowMsnIeLinks) {
 				getWindowsLivePresence(this.memberId, $I.transf('Chat', 'profilelayout'), $I.transf('Add Contact', 'profilelayout'));
 			} else {
 	 		  	getWindowsLivePresence(this.memberId, $I.transf('Chat', 'profilelayout'), $I.transf('Add Contact', 'profilelayout'), this.im_msn_tx);
 			}
 		}
 		
 		var skype = $('skype_link');
 		if (skype !== null) {
 			skype.addEvent('click', skypeCheck);
 		}
 		
 		if (typeof loadTips != 'undefined') {
 			loadTips();
 		}
	},
	
	onClickAimWelcome: function(event) {
		event.preventDefault();
		tmp = new Request.JSON({
			'url': '/c/profile/disable_aim_profile_welcome.json',
            'onComplete': function() {
				aimWelcome.fade('out');
				(function() {
					aimWelcome.get('tween', {property: 'height'}).start(0);
				}).delay(500);
			}
		}).send();
	},
	
	onClickScrollToApp: function(event, item) {
		var id = 'app' + item.get('id').replace('app_list_','');
		scrollToApp(id, this.memberId);
	},
	
	onClickDeleteEntireGroup: function(event) {
		window.open("/admin/Member.jsp?SearchMemberId=" + this.memberId, '', 'width=800,height=600,scrollbars=yes');
	},
	
	onClickBuySongs: function(event) {
		var lsParam = (this.ipCountryCd !== null && this.ipCountryCd === 'US') ? "&LS_PARAM=" : "";
		var callback = (this.ipCountryCd !== null && this.ipCountryCd === 'US') ? "&callback=beboITunes.gotoITunes2US" : "&callback=beboITunes.gotoITunes2";
		beboITunes.doITunes("http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?limit=10&media=music&entity=musicArtist&term=" + this.displayName + "&s=" + this.store_id + "&partnerId=" + this.partner_id + lsParam + callback);
	},
	
	onClickBeboModuleHideShow: function(event, item) {
		var id = item.get('id').replace('profile_mod_h2_','');
		BeboModule.hideshow(id, this.memberId);
	}
});


var VideoScroller = new Class({
	initialize: function() {
		this.memberId = $V('Profile', 'memberId');
		this.logView = false;
		this.flashBoxId = 0;
		this.callbackGetCurrVideo = { success:this.handleGetVideoSuccess, failure:this.handleGetVideoFailure, cache:false, scope:this };
		this.currentFlashBoxId = $V('flashbox_top', 'currentFlashBoxId');
		this.moderator = $V('flashbox_top', 'moderator');
		this.sponsored = $V('flashbox_top', 'isSponsored');
		this.flashBoxHashes = $V('flashbox_top', 'jsonFlashBoxHashes');
		
		if ($defined(this.flashBoxHashes) && this.flashBoxHashes.length > 0) {
			this.flashBoxHashes.each(function(item, index) {
			    var el = $('videoThumb_' + item.flash_box_id);
			    el.addEvent('click', this.switchFlashBoxTop.bindWithEvent(this, [item.flash_box_id, item.logView]));
			    el = $('videoThumbLink_' + item.flash_box_id);
			    el.addEvent('click', this.switchFlashBoxTop.bindWithEvent(this, [item.flash_box_id, item.logView]));
			    
			    if (index === 0) {
			    	this.switchFlashBoxTop.delay(200, this, ["", item.flash_box_id, item.logView]);
			    }
			}, this);
		}
	},

	handleGetVideoSuccess: function(o) { 
		if (o.responseText === undefined) {
			return;
		}
   
		var currBuff = JSON.decode(o.responseText);

		var flashName = currBuff.title;
		var width = currBuff.width;
		var height = currBuff.height;

		var scrollSidebar = true;
		if (!width) { width = 450; }
		if (!height) { height = 370; }

		var div = $('flashBoxTop').getElement('.bd');
		div.innerHTML = "<h4>" + flashName + "</h4>" +
			(currBuff.contentLabel ? "<div class='guidance'>" + currBuff.contentLabel + "</div>" : "") +
			currBuff.flashBoxHtml;
         
		var oldThumbDiv = $('videoThumb_' + this.currentFlashBoxId);
		var oldThumbPlayButton = $('play_' + this.currentFlashBoxId);
		if (oldThumbDiv) {
			oldThumbPlayButton.className = 'play';
			oldThumbPlayButton.innerHTML = '';
		}
		var newThumbDiv = $('videoThumb_' + this.flashBoxId);
		var newThumbRow = $('videoThumbRow_' + this.flashBoxId);
		var newThumbPlayButton = $('play_' + this.flashBoxId);
       
		if (newThumbDiv) {
			newThumbPlayButton.className = '';
			newThumbPlayButton.innerHTML = '<div class="nowShowing"><span>' + $I.transf('Showing', 'profilelayout') + '</span></div>';
          
			if (scrollSidebar) {
				document.getElementById('videoThumbSidebar').scrollTop = newThumbRow.offsetTop - 120;
			}
		}
		this.currentFlashBoxId = this.flashBoxId;
	},
	
	handleGetVideoFailure: function(o) { 
		if (o.responseText === undefined) {
			return;
		}
		currBuff = '<p>' + $I.transf('Error occurred while retrieving videos', 'profilelayout') + '</p>';
	},
	
	getCurrentVideo: function(currFlashBoxId) {
		var isModerator = this.moderator ? 'Y' : 'N';
		var isSponsored = this.sponsored ? 'Y' : 'N';
		var getVideoInfoUrl = '/ajaxjsps/getVideoInfoHtml.jsp?ProfileMemberId=' + this.memberId + '&FlashBoxId=' + currFlashBoxId + '&IsModerator=' + isModerator + '&IsSponsored=' + isSponsored;
		tmp = YAHOO.util.Connect.asyncRequest('GET', getVideoInfoUrl, this.callbackGetCurrVideo);
	},
	
	switchFlashBoxTop: function(event, currFlashBoxId, currLogView) {
		this.flashBoxId = currFlashBoxId;
		this.logView = currLogView;
		this.getCurrentVideo(this.flashBoxId);
	}	
});

//need bebo.Timeline.AddEntry and .displayOptions to work with Flash timeline
if	(typeof bebo == 'undefined') {
	bebo = {};
}

if (typeof bebo.Timeline == 'undefined') {
	bebo.Timeline = {
		AddEntry: null,
		displayOptions: null
	};
}

$(document).addEvent('endofbody', function() {	
	tmp = new Profile();
	tmp = new VideoScroller();
	var timeline = new Timeline();
	
	bebo.Timeline.AddEntry = timeline.addEntry.bind(timeline);
	bebo.Timeline.displayOptions = timeline.displayOptions.bind(timeline);
});