var signInOutState = null;
function signInOut(newState){
signInOutState = newState;
if( newState=='signin' ) {
var awesomeMessage = "To perform this action, you must first sign in or create an account.";
SignInAccountCreationDialog.showOverlay(awesomeMessage, null);
}
else {
SignInAccountCreationDialog.signOut();
}
}
var TEMP_AUTH_REMEMBER_ME;
var TEMP_AUTH_TOKEN;
var GLOBAL_sendMessage = function(url, querystring, callback){
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data;
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
data.hasError=true;
callback(data);
}
}
new Ajax.Request(url,{
onSuccess: wrappedCallback,
method: 'post',
parameters: querystring
});
}
function onLoginSWFReady(){
SignInOutDialogBox.onLoginSWFReady();
}
function onLoginFormClose() {
SignInOutDialogBox.hideDialog();
}
function onEngineReady() {
inoutdebug("onEngineReady");
}
function onDialogHeightChanged(height) {
inoutdebug("onDialogHeightChanged");
SignInOutDialogBox.updateHeight(height);
}
function onLogout( status ) {
//alert("onLogout("+status+")");
// If the signin/account-creation overlay is being shown, ignore these...
if( SignInAccountCreationDialog.isShown ) return;
// Prevent this from being called too soon after onAuthenticateDoneWithToken...
var rightNow = new Date().valueOf();
if( rightNow-onAuthenticateDoneWithTokenTimeout < 10000 ) { return; }
if( status==0 ) {
// if the user is already signed out, do nothing...
var cookieGroup = new CookieGroup("RhapWeb");
if( cookieGroup.hasCookie("RhapAuth",CookieManager.PERMANENT_USER) ) {
if( !cookieGroup.getCookie("RhapAuth",CookieManager.PERMANENT_USER) ) { return; }
if( cookieGroup.getCookie("RhapAuth",CookieManager.PERMANENT_USER) == "guid=" ) { return; }
}
else { return; }
var cookieGroup = new CookieGroup("RhapWeb");
cookieGroup.deleteCookie("RhapAuth");
setTokenInCookie( "", true );
CookieManager.setCookie( "authRefreshTime", "" + new Date().valueOf() );
// Kill "popout state" cookie, to re-detect proper popout state...
document.cookie = RhapsodyPlayer.POPOUT_STATE_COOKIE + "=; domain=.rhapsody.com; path=/;";
createCannedRhapsodyMember();
}
if( signInOutState=="signin" ) { return; }
// If we're on a catalog page, try to close the sign-out div...
try { SignInOutDialogBox.slideUp(); } catch(e) { }
// If we're in the player, show any appropriate messaging...
try { playerUI_onLogout(status); } catch(e) { }
try { document.getElementById("topNavSignInOut").innerHTML = '<img src="http://static.realone.com/rotw/images/libraryloading_overwhite.gif" \/>'; } catch(e){ }
}
var onAuthenticateDoneWithTokenTimeout = 0;
var onAuthenticateDoneWithTokenTimeoutArray = new Array();
function onAuthenticateDoneWithToken( token, rememberMe ) {
if( !token ) { return; }
// Prevent this from being called too frequently...
var rightNow = new Date().valueOf();
var lastTimeWithThisToken = onAuthenticateDoneWithTokenTimeoutArray[token]
? onAuthenticateDoneWithTokenTimeoutArray[token] : 0;
if( rightNow-lastTimeWithThisToken < 30000 ) { return; }
onAuthenticateDoneWithTokenTimeout = rightNow;
onAuthenticateDoneWithTokenTimeoutArray[token] = rightNow;
// If we're on a catalog page, try to close the sign-in div...
if( signInOutState!="signout" ) { try { SignInOutDialogBox.slideUp(); } catch(e) { } }
TEMP_AUTH_REMEMBER_ME = rememberMe;
TEMP_AUTH_TOKEN = token;
GLOBAL_sendMessage( rhapsodyURL+'/webservice/json/userinfo', "token="+token+"&.r="+(new Date()).valueOf() , onAuthenticateDoneStep2 );
}
function onAuthenticateDoneStep2( data ) {
if( data.status == "fail" ) {
showSigninError();
return;
}
// ignore anonymous account authentications from the engine...
if( data.isAnonymous ) { return; }
try {
if( SignInAccountCreationDialog.isShown && SignInAccountCreationDialog.successEvent ) {
SignInAccountCreationDialog.throwSuccessEvent();
}
}
catch(e){}
var userGuid = "";
try {
var cookieGroup = new CookieGroup("RhapWeb");
if( cookieGroup.hasCookie("RhapAuth",CookieManager.PERMANENT_USER) ) {
if( cookieGroup.getCookie("RhapAuth",CookieManager.PERMANENT_USER).indexOf("guid=")==0 ) {
userGuid = cookieGroup.getCookie("RhapAuth",CookieManager.PERMANENT_USER);
}
}
if( RhapsodyTracking && ( typeof RhapsodyTracking != 'undefined' ) ) RhapsodyTracking.setRhapsodyMember( rhapsodyMember );
} catch(e) { }
try { eval( data.personalizationJs ); } catch(e) { }
// If this happens to be in the player, we also need to call doTrackingCalls()...
try { doTrackingCalls( rhapsodyMember ); } catch(e) { }
if( userGuid == "guid="+data.guid ) {
return;
}
// If the user is now a named user, set the "refresh" cookie to
// trigger other pages to reload (PR238681)...
try {
var isAnon = rhapsodyMember.getMemberAttribute("isAnonymousUser");
var isLoggedIn = rhapsodyMember.getMemberAttribute("isLoggedIn");
if( isLoggedIn && !isAnon ) {
CookieManager.setCookie( "authRefreshTime", "" + new Date().valueOf() );
}
}
catch(e) { }
// Kill "popout state" cookie, to re-detect proper popout state...
document.cookie = RhapsodyPlayer.POPOUT_STATE_COOKIE + "=; domain=.rhapsody.com; path=/;";
setGuidInCookie( data.guid, TEMP_AUTH_REMEMBER_ME );
setTokenInCookie( TEMP_AUTH_TOKEN, TEMP_AUTH_REMEMBER_ME );
}
function onAuthenticateDone( status ) {
// alert("onAuthenticateDone("+status+")");
if( status==1 ) {
SignInAccountCreationDialog.showAuthenticationError();
return;
}
}
function onAccountCreated(statusCode, errorMessage) {
alert("onAccountCreated("+statusCode+","+errorMessage+")");
SignInAccountCreationDialog.accountCreated(statusCode,errorMessage);
}
var SignInAccountCreationDialog = {
isShown:false,
isOkToUpsell:true,
overlayWidth:400,
overlayHeight:385,
usingOverlay:true, // use the overlay by default...
modalDialogBoxInstance: null,
successEvent:null,
justSubmittedSignInForm:false,
authTimeout:null,
signInCallToAction:"Sign in to your account",
_signInButtonText: "Sign In",
_createAccountButtonText: "Create the Account",
_spinnerVariant: null,
_spinnerMessage: null,
setShowUpsell: function( val ) {
this.isOkToUpsell=val;
},
throwSuccessEvent: function() {
try { this.clearError(); } catch(e) {}
try { this.successEvent(); } catch(e) {}
},
spawnPasswordRetrieval: function(){
window.open( "https://rhapreg.real.com/rhapsody_account/account?page=login.remind", "passwordRetrieve", "toolbar=yes,location=yes,directories=yes,resizable=yes,scrollbars=yes" );
},
isStore: function() {
return document.location.host.indexOf("mp3")>=0;
},
showInElements: function( signInElement, accountCreationElement, successEvent ) {
if( this.isShown ) { return ;}
if( !signInElement && !accountCreationElement ) { return; /*what the heck?*/ }
if( successEvent ) this.successEvent = successEvent;
var emt_s = document.getElementById(signInElement);
var emt_a = document.getElementById(accountCreationElement);
if( (!signInElement || emt_s) && (!accountCreationElement || emt_a) ) {
this.isShown = true;
this.usingOverlay = false;
if( emt_s ) { emt_s.innerHTML = SignInAccountCreationDialog.getSignInFormHtml(); }
if( emt_a ) { emt_a.innerHTML = SignInAccountCreationDialog.getAccountCreationFormHtml(); }
SignInAccountCreationDialog.focusOnUsernameField();
}
else {
setTimeout( function(){ SignInAccountCreationDialog.showInElements( signInElement, accountCreationElement ); }, 500 );
}
},
showOverlay: function( specialText, successEvent ) {
if( this.isShown ) {return;}
this.isShown=true;
this.successEvent = successEvent;
var overlayHtmlContent = '';
var closeXSpan = '<div id="signinOverlayClose"><a href="#" onclick="SignInAccountCreationDialog.destroy(); return false;">Close<\/a><\/div>';
overlayHtmlContent = closeXSpan;
overlayHtmlContent += '<div id="signinOverlayBody" style="background:url('+staticPath+'/images/signin/clouds.jpg); background-position:top center;">';
overlayHtmlContent += '<div id="inPageSignInDivElement" style="padding-left:70px;">' + this.getSignInFormHtml() + '</div>';
overlayHtmlContent += '<\/div>';
SignInAccountCreationDialog.init(overlayHtmlContent);
SignInAccountCreationDialog.focusOnUsernameField();
},
focusOnUsernameField: function() {
var thefield = document.getElementById('SignInAccountCreationDialog_s_username');
if( thefield ) { thefield.focus(); }
else {
setTimeout("SignInAccountCreationDialog.focusOnUsernameField();",100);
}
},
getSignInFormHtml: function() {
var mReturn = '';
mReturn += '<div id="SignInDialogWrapper">';
mReturn += '<form onSubmit="SignInAccountCreationDialog.submitSignIn(); return false;" >';
mReturn += '<div id="SignInDialogSpinner_s" style="visibility:hidden;"><img src="'+staticPath +'/images/loading_spin_alt_grey.gif" /></div>';
if( this.signInCallToAction ) {
mReturn += '<br style="line-height:45px;" /><h3>'+this.signInCallToAction+'<\/h3><br style="line-height:5px;" />';
}
mReturn += '<table><tr>';
mReturn += '<td align="right" valign="bottom"><div class="signInDialogFormFieldLabel">Username:<\/div></td>';
mReturn += '<td><div id="SignInAccountCreationDialog_s_un_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<div class="signInDialogUsernameInput"><input type="text" name="username" id="SignInAccountCreationDialog_s_username" \/><\/div>';
mReturn += '<div class="signInDialogFormFieldFootnote">Usually your email address</div></td>';
mReturn += '</tr><tr>';
mReturn += '</tr><tr>';
mReturn += '<td align="right" valign="bottom"><div class="signInDialogFormFieldLabel">Password:<\/div></td>';
mReturn += '<td><div id="SignInAccountCreationDialog_s_pw_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<div class="signInDialogPasswordInput"><input type="password" name="password" id="SignInAccountCreationDialog_s_password" \/><\/div>';
mReturn += '<div class="signInDialogFormFieldFootnote"><a href="javascript:SignInAccountCreationDialog.spawnPasswordRetrieval();" style="font-family:Trebuchet MS,Arial; font-size:10px; color:#0094DE; font-weight:normal;">Forgot your password?<\/a></div>';
mReturn += '</td></tr><tr>';
mReturn += '</tr><tr>';
mReturn += '<td></td><td><br style="line-height:10px;" />';
mReturn += '<div class="signInDialogSignInButtonDiv"><input type="image" value="submit" name="submit" ';
mReturn += ' src="' + staticPath + 'images/signin/signin_btn_default.png" ';
mReturn += ' onMouseOver="this.src=\'' + staticPath + 'images/signin/signin_btn_over.png\';" ';
mReturn += ' onMouseOut="this.src=\'' + staticPath + 'images/signin/signin_btn_default.png\';" ';
mReturn += ' onMouseDown="this.src=\'' + staticPath + 'images/signin/signin_btn_click.png\';" ';
mReturn += ' onMouseUp="this.src=\'' + staticPath + 'images/signin/signin_btn_over.png\';" ';
mReturn += '\/></div>';
mReturn += '<input type="checkbox" name="rememberme" checked="checked" id="SignInAccountCreationDialog_s_rememberme" \/>';
mReturn += '<label for="SignInAccountCreationDialog_s_rememberme" class="signInDialogFormFieldFootnote">Remember me<\/label></td>';
mReturn += '</tr></table>';
mReturn += '<\/form>';
mReturn += '</div>';
if( !SignInAccountCreationDialog.isStore() && this.isOkToUpsell ) {
mReturn += '<div class="signInDialogUpgradeWrapper">';
mReturn += '<div class="signInDialogUpgradeTextDiv"><img ';
mReturn += ' src="' + staticPath + 'images/signin/new_to_rhap_text.png" \/></div>';
mReturn += '<div class="signInDialogUpgradeButtonDiv">';
mReturn += '<a href="'+rhapsodyURL+'/signup?cpath=redux&rsrc=signin"><img ';
mReturn += ' src="' + staticPath + 'images/signin/trial_btn_default.png" ';
mReturn += ' onMouseOver="this.src=\'' + staticPath + 'images/signin/trial_btn_over.png\';" ';
mReturn += ' onMouseOut="this.src=\'' + staticPath + 'images/signin/trial_btn_default.png\';" ';
mReturn += ' onMouseDown="this.src=\'' + staticPath + 'images/signin/trial_btn_click.png\';" ';
mReturn += ' onMouseUp="this.src=\'' + staticPath + 'images/signin/trial_btn_over.png\';" ';
mReturn += '\/></a></div>';
mReturn += '&nbsp;</div>';
}
return mReturn;
},
getAccountCreationFormHtml: function() {
var mReturn = '<form onSubmit="SignInAccountCreationDialog.submitAccountCreation();return false;">';
mReturn += '<div id="AccountCreationDialogWrapper">';
mReturn += '<div id="SignInDialogSpinner_a" style="visibility:hidden;"><img src="'+staticPath +'/images/loading_spin_alt_grey.gif" /></div>';
mReturn += '<h3>Create a free account<\/h3>';
mReturn += "It\'s quick, easy, and blah blah, blah...";
mReturn += '<div id="SignInAccountCreationDialog_a_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<div class="accountCreateDialogEmailAddress">Your Email Address:<\/div>';
mReturn += '<div class="accountCreateDialogUsernameInput"><input type="text" name="username" id="SignInAccountCreationDialog_a_username" \/><\/div>';
mReturn += '<div id="SignInAccountCreationDialog_a_un_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<div class="accountCreateDialogPassword">Password:<\/div>';
mReturn += '<div class="accountCreateDialogPasswordInput"><input type="password" name="password" id="SignInAccountCreationDialog_a_password" \/><\/div>';
mReturn += '<div id="SignInAccountCreationDialog_a_pw_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<div class="accountCreateDialogPasswordConfirm">Password (again):<\/div>';
mReturn += '<div class="accountCreateDialogPasswordConfirmInput"><input type="password" name="password2" id="SignInAccountCreationDialog_a_password2" \/><\/div>';
mReturn += '<div id="SignInAccountCreationDialog_a_pw2_error" class="SignInDialogError">&nbsp;<\/div>';
mReturn += '<a class="signinOverlayCreateAccountButton" href="javascript:SignInAccountCreationDialog.submitAccountCreation()">' + this._createAccountButtonText + '<\/a>';
mReturn += '<div id="SignInAccountCreationDialog_a_contacting">&nbsp;<\/div>';
mReturn += '<input type="checkbox" name="rememberme" checked="checked" id="SignInAccountCreationDialog_a_rememberme" \/>';
mReturn += '<label for="SignInAccountCreationDialog_a_rememberme">Remember me<\/label>';
mReturn += '<input type="image" value="submit" name="submit" src="' + staticPath + 'images/dot_clear.gif" \/>';
mReturn += '<\/div>';
mReturn += '<\/form>';
return mReturn;
},
showAuthenticationError: function() {
this.clearError();
this.clearAuthTimeout();
this.showError("Your account was not found.<br />Check the spelling and try again.");
},
accountCreated: function(statusCode,errorMessage) {
this.clearError();
this.clearAuthTimeout();
if( statusCode==0 ) {
// Should we show any "success" messaging here...?
}
else {
// Temporary hack: sometimes RDS returns the user's email address when the account is
// already existing. Can be removed (along with the IF below) once bug 252986 is fixed.
var theUsername = document.getElementById("SignInAccountCreationDialog_a_username").value;
if( errorMessage==theUsername ) {
this.showError("An account exists for that email address.","un");
}
else if( errorMessage=="account already exists" ) {
this.showError("An account exists for that email address.","un");
}
else if( errorMessage=="timeoutError" ) {
this.showError("The server is not responding. Please try again.","un");
}
else {
this.showError("There was a problem creating the account. ("+errorMessage+")");
}
}
},
clearError: function() {
this.showError("");
this.showError("","un");
this.showError("","pw");
this.showError("","pw2");
this.showContactingSpinner(false);
},
showError: function( message, optionalDestination ) {
if( message ) {
var reportmessage = optionalDestination ? optionalDestination+":"+message : message;
if( this.justSubmittedSignInForm ) { try { this.logSignInError(reportmessage);} catch(e) { } }
else {try { this.logAccountCreationError(reportmessage);} catch(e) { } }
}
// there is no "default error" region currently, so send those to the Username error region...
if( !optionalDestination ) { optionalDestination = "un"; }
this.clearAuthTimeout();
var theElementId =
"SignInAccountCreationDialog" +
( this.justSubmittedSignInForm ? "_s" : "_a" ) +
( optionalDestination ? "_"+optionalDestination : "" ) + "_error";
var theElement = document.getElementById( theElementId );
if( !theElement ) { return; }
if( !message ) { message = "&nbsp;"; }
theElement.innerHTML = message;
},
logSignInError: function( message ) {
RhapsodyTracking.sendLinkEvent( { eVar17: 'Account: Err: Login Failure: ' + message, prop18: 'E: Account: Err: Login Failure: ' + message }, { type: 'custom', linkName: 'Error', events: 'event21' } );
},
logAccountCreationError: function( message ) {
alert("Reporting account-creation error to omniture: "+message);
},
showContactingSpinner:function( showIt ) {
var theElementId =
"SignInDialogSpinner" +
( this.justSubmittedSignInForm ? "_s" : "_a" );
document.getElementById(theElementId).style.visibility = showIt?"visible":"hidden";
},
submitSignIn: function() {
this.justSubmittedSignInForm=true;
this.clearError();
var theUsername = document.getElementById("SignInAccountCreationDialog_s_username").value;
var thePassword = document.getElementById("SignInAccountCreationDialog_s_password").value;
var theRememberme = document.getElementById("SignInAccountCreationDialog_s_rememberme").checked;
if( !theUsername || !thePassword ) {
if( !theUsername ) { this.showError("Required field.","un"); }
if( !thePassword ) { this.showError("Required field.","pw"); }
return;
}
else {
this.showContactingSpinner(true);
RhapsodyPlayer.getFlashApp("engine").setCredentials( theUsername, thePassword, theRememberme );
RhapsodyPlayer.getFlashApp("engine").authenticate();
SignInAccountCreationDialog.tryAuthTimeout();
return;
}
},
submitAccountCreation: function() {
this.justSubmittedSignInForm=false;
this.clearError();
var theUsername = document.getElementById("SignInAccountCreationDialog_a_username").value;
var thePassword = document.getElementById("SignInAccountCreationDialog_a_password").value;
var thePassword2 = document.getElementById("SignInAccountCreationDialog_a_password2").value;
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if( !theUsername || !thePassword || !thePassword2 ) {
if( !theUsername ) { this.showError("The username field is required","un"); }
if( !thePassword ) { this.showError("The password field is required ","pw"); }
if( !thePassword2 ) { this.showError("Please enter the password again","pw2"); }
return;
}
else if( !filter.test(theUsername) ) {
this.showError("Your username must be a valid email address","un");
return;
}
else if( thePassword != thePassword2 ) {
this.showError("The password does not match","pw2");
return;
}
else {
this.showContactingSpinner(true);
alert("Calling createNamedAccount()...");
RhapsodyPlayer.getFlashApp("engine").createNamedAccount(theUsername,thePassword,"40134");
SignInAccountCreationDialog.tryAuthTimeout();
return;
}
return;
},
init: function(overlayHtmlContent){
if( overlayHtmlContent != null && overlayHtmlContent != 'undefined' && overlayHtmlContent != '' ){
SignInAccountCreationDialog.modalDialogBoxInstance = new DialogBox(
{
width: SignInAccountCreationDialog.overlayWidth+'px',
height: SignInAccountCreationDialog.overlayHeight+'px',
maskOpacityPercent: 60,
zIndex: '999999999',
maskBgColor: '#000',
maskZIndex: '10000',
htmlContent: overlayHtmlContent
}
);
SignInAccountCreationDialog.modalDialogBoxInstance.centerInPage( .90 );
SignInAccountCreationDialog.modalDialogBoxInstance.toggleMeddlesomeElements();
SignInAccountCreationDialog.modalDialogBoxInstance.setMask( true );
SignInAccountCreationDialog.modalDialogBoxInstance.setShadow( true );
Event.observe( window, 'scroll', function(e){
SignInAccountCreationDialog.modalDialogBoxInstance.centerInPage( .90 );
SignInAccountCreationDialog.modalDialogBoxInstance.setMask( true );
} );
Event.observe( window, 'resize', function(e){
SignInAccountCreationDialog.modalDialogBoxInstance.centerInPage( .90 );
SignInAccountCreationDialog.modalDialogBoxInstance.setMask( true );
} );
}
},
overrideUiComponents: function( orObj ){
if( ( orObj.signInButtonText != null ) && ( typeof orObj.signInButtonText != 'undefined' ) ){
this._signInButtonText = orObj.signInButtonText;
}
if( ( orObj.createAccountButtonText != null ) && ( typeof orObj.createAccountButtonText != 'undefined' ) ){
this._createAccountButtonText = orObj.createAccountButtonText;
}
if( ( orObj.spinnerMessage != null ) && ( typeof orObj.spinnerMessage != 'undefined' ) ){
this._spinnerMessage = orObj.spinnerMessage;
}
if( ( orObj.spinnerVariant != null ) && ( typeof orObj.spinnerVariant != 'undefined' ) ){
this._spinnerVariant = orObj.spinnerVariant;
}
},
showAuthTimeout:function() {
this.clearError();
this.showError("The server is not responding. Try again.");
},
clearAuthTimeout:function() {
clearTimeout( SignInAccountCreationDialog.authTimeout );
},
tryAuthTimeout:function() {
SignInAccountCreationDialog.authTimeout = setTimeout("SignInAccountCreationDialog.showAuthTimeout()",30000);
},
signOut:function() {
var theLinkInTheHeader = document.getElementById("topNavSignInOut");
if( theLinkInTheHeader ) { theLinkInTheHeader.innerHTML = "Signing out..."; }
RhapsodyPlayer.getFlashApp("engine").logout();
},
destroy: function(){
this.isShown=false;
Event.unloadCache();
SignInAccountCreationDialog.modalDialogBoxInstance.toggleMeddlesomeElements();
SignInAccountCreationDialog.modalDialogBoxInstance.destroy();
SignInAccountCreationDialog.modalDialogBoxInstance = null;
}
};
function CookieManager(){}
/** For more information on these cookies, please refer to the documentation attached to bug 199824 **/
CookieManager.SESSION = "RhapWeb.Session";
CookieManager.PERMANENT = "RhapWeb.Permanent";
CookieManager.PERMANENT_USER = "RhapWeb.PermanentUser";
CookieManager.SESSION_COOKIE_LIST = new Array(
"autoReloadingTime", "AlreadySentToWelcomePage", "alreadyLoggedCampaignEvent",
"agreedToUseAnonymousAccount", "RhapPlayerShowUpsells", "doPlayerLoadWithoutTrackLoad",
"alreadyShowedPlaysLeftOverlay", "RhapPlayerDebug", "simulateUdsError",
"RhapPlayer.TrackList", "RhapPlayer.hasSeenPopupTip" );
CookieManager.PERMANENT_USER_COOKIE_LIST = new Array(
"libStateMgr", "RhapWeb.AuthKey", "RhapWeb.RhapUser", "RhapWeb.RhapMember", 'srvrDt', 'srvrDelta' );
CookieManager.PERMANENT_COOKIE_LIST = new Array(
"didAutoplayBounce", "rhapsodyInstalled", "rhapwebPluginVersion", "rhapwebPluginInstalled", "rhapwebFlashInstalled",
"autoPlayChoice", "editRemind", "playedMusic", "rhapPlayerRandom", "hasPurchasedMusic",
"RhapWeb.RhapPrefs", "has-seen-b-test", "trialCookieExpire", "trialCookieNoThanks", "anon_cart", "lastViewedUrl", "lastViewedUrlStore",
"welcome-overlay", "flashPlayerRequiredMsgOverlay", 'RhapsodySampleModeSegment' );
CookieManager.DELETE_ME = "RhapWeb.DeleteMe.Value";
/** Retreives the value of a specified cookie.
* @param name the name of the cookie to look up
* @returns the cookie's stored value
*/
CookieManager.getCookie = function( name, packageName, okToReturnDeleteMe ) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) {
var cookieValue = unescape( c.substring(nameEQ.length,c.length) );
if( cookieValue == CookieManager.DELETE_ME ) {
return okToReturnDeleteMe ? CookieManager.DELETE_ME : null;
}
else {
return cookieValue;
}
}
}
if( packageName ) {
var cookieValueFromPackage = CookieManager.getCookieMemberByName( packageName, name );
return cookieValueFromPackage;
}
return null;
}
CookieManager.getCookieMemberByName = function( name, memberName, packageName )
{
var cookieHashString = CookieManager.getCookie( name, packageName );
if( cookieHashString != null ){
var cookieHashStringArray = cookieHashString.split( "&" );
for( var i=0; i<cookieHashStringArray.length; i++ ){
var hashPair = cookieHashStringArray[i].split( "=" );
var hashName = hashPair[0];
var hashValue = hashPair[1];
if( hashName == memberName ) return unescape(hashValue);
}
}
return null;
}
/** Sets the value and meta data for a named cookie.
* @param name the name of the cookie
* @param value string value to store in the cookie
* @param lifeInMillis number of milliseconds before the cookie expires
* @param path the path to which this cookie is assigned
* @param cookieDomain the domain to which this cookie is assigned
* @param secure boolean indicating whether this cookie is to be stored securely
*/
CookieManager.setCookie = function( name, value, lifeInMillis, path, cookieDomain, secure )
{
if ( lifeInMillis )
{
var date = new Date();
date.setTime( date.getTime() + lifeInMillis );
var expires = date.toGMTString();
}
else
{
var expires = null;
}
var cookie = name + "=" + escape(value) +
( expires ? "; expires=" + expires : "" ) +
( path ? "; path=" + path : "; path=/" ) +
( cookieDomain ? "; domain=" + cookieDomain : "; domain=.rhapsody.com" ) +
( secure ? "; secure" : "" );
document.cookie = cookie;
}
/** Determines if a named cookie currently exists with a non-null value.
* @param name the name of the cookie to test.
* @returns true if the cookie exists with a non-null value or false otherwise.
*/
CookieManager.hasCookie = function( name, packageName ) {
return CookieManager.getCookie( name, packageName ) != null;
}
/** Removes a named cookie
* @param name the name of the cookie to remove.
*/
CookieManager.deleteCookie = function( name ) {
CookieManager.setCookie( name, CookieManager.DELETE_ME, 100000 );
}
CookieManager.actuallyDeleteCookie = function( name ) {
CookieManager.setCookie( name, "", -100000 );
}
CookieManager.doCookieConsolidation = function( packageName, sourceCookies, isPermanent ) {
// At some point, this might get set to true...
var shouldSetPackageCookie = false;
// Go through each cookie, and determine what its value ought to be (either from the
// source cookie itself or from the package cookie)...
var currentValues = new Array();
var packageCookieValue = CookieManager.getCookie( packageName );
for( var i=0 ; i < sourceCookies.length ; i++ ) {
var sourceCookieName = sourceCookies[i];
var sourceCookieValueFromPackageCookie = null;
if( packageCookieValue ) {
sourceCookieValueFromPackageCookie = CookieManager.getCookieMemberByName( packageName, sourceCookieName );
}
var sourceCookieValue = CookieManager.getCookie( sourceCookieName, null, true );
if( sourceCookieValue==CookieManager.DELETE_ME ) {
// Source-cookie is set to be deleted; set the value to null...
sourceCookieValue = null;
shouldSetPackageCookie = true;
currentValues[ sourceCookieName ] = null;
}
else if( sourceCookieValue && sourceCookieValueFromPackageCookie && sourceCookieValue!=sourceCookieValueFromPackageCookie ) {
// Package-cookie and source-cookie both have value, but they don't match; use the source-cookie's value...
shouldSetPackageCookie = true;
currentValues[ sourceCookieName ] = sourceCookieValue;
}
else if( sourceCookieValue && !sourceCookieValueFromPackageCookie ) {
// Value isn't in the package-cookie, need to set it to the source-cookie's value...
shouldSetPackageCookie = true;
currentValues[ sourceCookieName ] = sourceCookieValue;
}
else if( !sourceCookieValue && sourceCookieValueFromPackageCookie ) {
// Source-cookie is gone, need to keep the package-cookie value...
shouldSetPackageCookie = true;
currentValues[ sourceCookieName ] = sourceCookieValueFromPackageCookie;
}
else {
// Just resetting the same value back into the package-cookie...
currentValues[ sourceCookieName ] = sourceCookieValue;
}
CookieManager.actuallyDeleteCookie( sourceCookieName );
}
// Now, if there was anything that needs to be updated in the package cookie, go
// ahead and set the package cookie...
if( shouldSetPackageCookie ) {
var newPackageCookieValue = "";
for( var i=0 ; i < sourceCookies.length ; i++ ) {
var cookieName = sourceCookies[i];
var cookieValue = currentValues[cookieName];
if( cookieValue ) {
if( newPackageCookieValue.length ) { newPackageCookieValue += "&"; }
newPackageCookieValue += cookieName + "=" + escape(cookieValue);
}
}
if( isPermanent ) {
var date = new Date();
date.setTime( date.getTime() + 1000 * 3600 * 24 * 500 ); // 500 days
var expires = date.toGMTString();
document.cookie = packageName + "=" + escape(newPackageCookieValue) + "; expires=" + expires + "; path=/; domain=.rhapsody.com;";
}
else {
document.cookie = packageName + "=" + escape(newPackageCookieValue) + "; path=/; domain=.rhapsody.com;";
}
}
}
CookieManager.doCookieConsolidation( CookieManager.SESSION, CookieManager.SESSION_COOKIE_LIST, false );
CookieManager.doCookieConsolidation( CookieManager.PERMANENT_USER, CookieManager.PERMANENT_USER_COOKIE_LIST, true );
CookieManager.doCookieConsolidation( CookieManager.PERMANENT, CookieManager.PERMANENT_COOKIE_LIST, true );
/**
* @class Static class for global cookie operations
* @constructor
* @param groupName the name of this cookie group
*/
function CookieGroup( groupName )
{
this.__prefix = groupName ? groupName + "." : "";
}
/**
* namespace prefix for this group
* @private
*/
CookieGroup.prototype.__prefix = null;
/** Retreives the value of a specified cookie in this group.
* @param name the name of the cookie to look up
* @returns the cookie's stored value
*/
CookieGroup.prototype.getCookie = function( name, packageName )
{
return CookieManager.getCookie( this.__getFullName( name ), packageName );
}
/** Sets the value and meta data for a named cookie in this group.
* @param name the name of the cookie
* @param value string value to store in the cookie
* @param lifeInMillis number of milliseconds before the cookie expires
* @param path the path to which this cookie is assigned
* @param cookieDomain the domain to which this cookie is assigned
* @param secure boolean indicating whether this cookie is to be stored securely
*/
CookieGroup.prototype.setCookie = function( name, value, lifeInMillis, path, domain, secure )
{
CookieManager.setCookie( this.__getFullName( name ), value, lifeInMillis, path, "rhapsody.com", secure );
}
/** Determines if a named cookie currently exists in this group with a non-null value.
* @param name the name of the cookie to test.
* @returns true if the cookie exists with a non-null value or false otherwise.
*/
CookieGroup.prototype.hasCookie = function( name, packageName )
{
return CookieManager.hasCookie( this.__getFullName( name ), packageName )
}
/** Removes a named cookie from this group
* @param name the name of the cookie to remove.
*/
CookieGroup.prototype.deleteCookie = function( name )
{
return CookieManager.deleteCookie( this.__getFullName( name ) )
}
/** Builds the fully-qualified name of a cookie in this group
* @private
* @param name the local name of the cookie.
*/
CookieGroup.prototype.__getFullName = function( name )
{
return this.__prefix + name;
}
CookieGroup.prototype.appendToCookie = function (cookie, nvObjs, life, packageName){
var originalCookieValueObjectArray = new Array();
var cookieValueObjectArray = new Array();
var cookieValueString = "";
var delimiter = "";
if (this.hasCookie(cookie, packageName)){
var cookieHashString = this.getCookie(cookie, packageName);
if( cookieHashString != null ){
var cookieHashStringArray = cookieHashString.split( "&" );
for( var i=0; i<cookieHashStringArray.length; i++ ){
var hashPair = cookieHashStringArray[i].split( "=" );
originalCookieValueObjectArray.push( { cookieName: hashPair[0], cookieValue: hashPair[1] } );
}
}
}
if( RhapsodyUtility.isArray( nvObjs ) ){
for( var i=0; i<nvObjs.length; i++ ){
var theCookieName = nvObjs[i].cookieName;
var theCookieValue = ( nvObjs[i].cookieValue == "" ) ? 'null' : nvObjs[i].cookieValue;
cookieValueObjectArray.push( { cookieName: theCookieName, cookieValue: theCookieValue } );
}
} else if( typeof nvObjs == 'object' ) {
var theCookieName = nvObjs.cookieName;
var theCookieValue = ( nvObjs.cookieValue == "" ) ? 'null' : nvObjs.cookieValue;
cookieValueObjectArray.push( { cookieName: theCookieName, cookieValue: theCookieValue } );
} else return false;
for( var i=0; i<cookieValueObjectArray.length; i++ ){
for( var j=0; j<originalCookieValueObjectArray.length; j++ ){
if( originalCookieValueObjectArray[j].name != cookieValueObjectArray[i].name ) cookieValueObjectArray.push( originalCookieValueObjectArray[j] );
}
}
for( var i=0; i<cookieValueObjectArray.length; i++ ){
cookieValueString += delimiter + cookieValueObjectArray[i].cookieName + "=" + cookieValueObjectArray[i].cookieValue;
delimiter = "&";
}
if( this.getCookie( cookie, packageName ) != cookieValueString ) {
this.setCookie( cookie, cookieValueString, life );
}
}
function isInWmp() {
try {
if(opener.window.external.version && opener.window.external.version != "" && opener.window.external.version != "undefined"){
return true;
}
} catch (e) {
return false;
}
return false;
}
var guidWasChangedInThisPage = false;
function setGuidInCookie(guid, rememberMe){
guidWasChangedInThisPage = true;
var cookieGroup = new CookieGroup("RhapWeb");
if (rememberMe) {
/* set it for a month */
cookieGroup.setCookie("RhapAuth","guid="+guid,2629743000);
} else if (isInWmp()) {
/* Set a short permenant cookie for the wmp integratgion */
cookieGroup.setCookie("RhapAuthWMP","guid="+guid,600000);
} else {
/* Set it for the session */
cookieGroup.setCookie("RhapAuth","guid="+guid,null);
}
cookieGroup.setCookie("AuthKey","",null);
}
function setRhapFlashInstalledCookie( ) {
try {
var COOKIE_LIFE_DAYS = 700;
var expireDate = new Date();
expireDate.setTime( expireDate.getTime() + COOKIE_LIFE_DAYS*24*60*60*1000 );
var theRhapFVersionString;
if( RhapsodyPlayer.getFlashApp("embedded")!=null ) {
theRhapFVersionString = "rhapE_" + RhapsodyPlayer.getFlashApp("embedded").getPlayerVersion();
}
else if( RhapsodyPlayer.getFlashApp("popout")!=null ) {
theRhapFVersionString = "" + RhapsodyPlayer.getFlashApp("popout").getPlayerVersion();
}
else {
return;
}
document.cookie = "rhapwebFlashInstalled=" + theRhapFVersionString + "; path=/; domain=.rhapsody.com; expires="+expireDate.toGMTString()+";";
}
catch( e ) {
debug("Exception:"+e);
}
}
function setTokenInCookie(token, rememberMe){
var cookieGroup = new CookieGroup("RhapWeb");
if (rememberMe) {
/* set it for a month */
cookieGroup.setCookie( "FlashToken","token="+escape(token), 2629743000 );
} else {
/* Set it for the session */
cookieGroup.setCookie( "FlashToken","token="+escape(token), null );
}
}
function setSubTypeInCookie(subtype, rememberMe){
var cookieGroup = new CookieGroup("RhapWeb");
if (rememberMe == "true") {
/* set it for a month */
cookieGroup.setCookie("RhapUser","subtype="+subtype,2629743000);
} else if (isInWmp()) {
/* Set a short permenant cookie for the wmp integratgion */
cookieGroup.setCookie("RhapUser","subtype="+subtype,600000);
} else {
/* Set it for the session */
cookieGroup.setCookie("RhapUser","subtype="+subtype,null);
}
}
function setAnonGuidInCookie(guid){
var cookieGroup = new CookieGroup("RhapWeb");
cookieGroup.setCookie("RhapAnon","anonguid="+guid,2629743000);
}
function setUserNameInCookie(username, rememberMe){
var cookieGroup = new CookieGroup("RhapWeb");
if (rememberMe == "true") {
/* set it for a month */
cookieGroup.setCookie("RhapUser","username="+username,2629743000);
} else if (isInWmp()) {
/* Set it for ten minutes */
cookieGroup.setCookie("RhapUser","username="+username,600000);
} else {
/* Set it for the session */
cookieGroup.setCookie("RhapUser","username="+username,null);
}
}
function getUserNameFromCookie(){
var mReturn = CookieManager.getCookie( "RhapWeb.RhapUser", CookieManager.PERMANENT_USER );
return mReturn ? mReturn : "";
}
function setWMPDetectCookie(){
var cookieGroup = new CookieGroup("RhapWeb");
cookieGroup.setCookie("wmp","inWMP=true",null);
}
function getCookieByGroup(group, cookie, packageName) {
var cookieGroup = new CookieGroup(group);
return cookieGroup.getCookie(cookie, packageName);
}
function hasCookieByGroup(group, cookie, packageName) {
var cookieGroup = new CookieGroup(group);
return cookieGroup.hasCookie(cookie, packageName);
}
var rhapPlayer;
var theScreenWidth = screen.width;
var theScreenHeight = screen.height;
var openFromLeftAt = (theScreenWidth-290);
function resizeWindowInnerSize( width, height ) {
if( navigator.userAgent.toLowerCase().indexOf("chrome")>=0 ) {
var diffw = window.outerWidth - window.innerWidth;
var diffh = window.outerHeight - window.innerHeight;
return window.resizeTo( width + diffw, height + diffh );
return;
}
else {
window.resizeTo( width, height );
var diffw = width - ((typeof window.innerWidth == 'undefined')?document.documentElement.clientWidth:window.innerWidth);
var diffh = height - ((typeof window.innerHeight == 'undefined')?document.documentElement.clientHeight:window.innerHeight);
return window.resizeTo( width + diffw, height + diffh );
}
}
function fixNameForJS( theName ) {
theName = theName.replace(/\'/g,"&#39;");
theName = theName.replace(/\"/g,"&quot;");
return theName;
}
function fixNameForHtml( theName ) {
theName = theName.replace(/</g,"&lt;");
theName = theName.replace(/>/g,"&gt;");
return theName;
}
function wmpDetect(){
try {
if(window.external.version && window.external.version !== "" && window.external.version != "undefined"){
setWMPDetectCookie();
}
} catch (e) {
}
}
wmpDetect();
var RhapsodyUtility = {
meddlesomeElements: [ 'ad_homepageSlideshow', 'homepageBillboardAd', 'ad_homepageBillboardAd_holder', 'query', 'searchtype', 'ad_C2', 'ad_C2_holder', 'ad_B1', 'ad_subnavPromoSpotAkaTheHat', 'ad_adTall_holder', 'videoPlaybackAdSpace','hasPlayerTrue'],
getCheckboxes: function getCheckboxes() {
var node_list = document.getElementsByTagName('input');
var items = [];
for (var i=0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox') {
items.push(node);
}
}
return items;
},
getSystemClockDeltaFromCookie: function(){
var toReturn = CookieManager.hasCookie( 'srvrDelta', CookieManager.PERMANENT_USER )? CookieManager.getCookie( 'srvrDelta', CookieManager.PERMANENT_USER ): null;
return parseInt( toReturn, 10 );
},
setSystemClockDeltaToCookie: function( systemDate, serverDate ){
var storedServerDate = CookieManager.getCookie( 'srvrDt', CookieManager.PERMANENT_USER );
if( storedServerDate != serverDate.getTime() ){
var newDelta = serverDate - systemDate;
CookieManager.setCookie( 'srvrDt', serverDate.getTime() );
CookieManager.setCookie( 'srvrDelta', newDelta );
return newDelta;
} else { return this.getSystemClockDeltaFromCookie(); }
},
getChildrenByClassName: function( theElement, theClassName ){
var elementsToReturn = [];
if( typeof theElement == 'string' ){ theElement = document.getElementById( theElement ); }
for( var i=0; i<theElement.childNodes.length; i++ ){
var elementsClassName = theElement.childNodes[i].className;
if( typeof elementsClassName == 'string' ){
if( ( elementsClassName == theClassName )
|| ( elementsClassName.match( ' ' + theClassName ) )
|| ( elementsClassName.match( theClassName + ' ' ) )
) {
elementsToReturn.push( theElement.childNodes[i] );
}
}
}
return elementsToReturn.length > 0 ? elementsToReturn : null;
},
getChildrenByTagName: function( theElement, theTagName ){
var elementsToReturn = [];
for( var i=0; i<theElement.childNodes.length; i++ ){
if( theElement.childNodes[i].tagName == theTagName ){ elementsToReturn.push( theElement.childNodes[i] ); }
}
return elementsToReturn.length > 0 ? elementsToReturn : null;
},
addLoadEvent: function(func){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
};
}
},
isArray: function(arr){
if( ( typeof arr == 'object' ) && ( typeof arr.pop != 'undefined' ) ){ return true; }
else{ return false; }
},
addEvent: function( theElement, theEvent, theCallback ){
if( theElement.addEventListener ){
theElement.addEventListener( theEvent, theCallback, false );
}
else if( theElement.attachEvent ){
theElement.attachEvent( "on" + theEvent, theCallback );
} else { return; }
},
setAlpha: function( theElement, percentage ) {
if( typeof theElement == 'string' ){ theElement = document.getElementById( theElement ); }
if( typeof theElement.style.opacity != 'undefined' ){
theElement.style.opacity = percentage / 100;
}
else if( typeof theElement.style.filter != 'undefined' ){
theElement.style.filter = "alpha(opacity=" + percentage + ")";
}
},
doFadein: function( theElementId, maximum, speedMulitplier, start ){
var theSpeedMultiplier = speedMulitplier ? speedMulitplier : 1;
var theStart = start? start: 0;
RhapsodyUtility.setAlpha( theElementId, theStart );
for( var i=0 + theStart; i <= maximum; i += 3 ) {
var doFadeinTO = setTimeout( "RhapsodyUtility.setAlpha('" + theElementId + "'," + i + ")", ( i * 8 ) / theSpeedMultiplier );
}
var doFadeinTO = setTimeout( "RhapsodyUtility.setAlpha('" + theElementId + "'," + maximum + ")", ( maximum * 8 ) / theSpeedMultiplier );
},
doFadeout: function( theElementId, maximum, speedMultiplier ) {
var theSpeedMultiplier = speedMultiplier ? speedMultiplier : 1;
var i;
for( i=maximum; i <= 100 ; i += 3 ) {
var doFadeoutTO = setTimeout( "RhapsodyUtility.setAlpha('" + theElementId + "'," + ( 100 - i ) + ")", i * 8 / theSpeedMultiplier );
}
var doFadeoutTO = setTimeout( "RhapsodyUtility.setAlpha('" + theElementId + "',0)", i * 8 / theSpeedMultiplier );
},
doBuildMask: function( theElementToMask ){
if( typeof theElementToMask == 'string' ){ theElementToMask = document.getElementById( theElementToMask ); }
var maskElement = document.createElement( "DIV" );
var maskElementText = document.createTextNode( " " );
var maskElementWidth = theElementToMask.offsetWidth;
var maskElementHeight = theElementToMask.offsetHeight;
maskElement.appendChild( maskElementText );
maskElement.className = "maskElement";
maskElement.style.width = maskElementWidth + "px";
maskElement.style.height = maskElementHeight + "px";
theElementToMask.parentNode.insertBefore( maskElement, theElementToMask );
RhapsodyUtility.setAlpha( maskElement, 80 );
return maskElement;
},
setSliderThingie: function( theX, theY, theWidth, theHeight ) {
var theSliderThing = document.getElementById( "topNavSliderThing" );
theSliderThing.style.visibility = ( theWidth && theHeight )? "visible" : "hidden";
theSliderThing.style.left = theX + "px";
theSliderThing.style.top = theY + "px";
theSliderThing.style.width = theWidth + "px";
theSliderThing.style.height = theHeight + "px";
},
getLeft: function( element ) {
if( element ) {
return element.offsetLeft + RhapsodyUtility.getLeft(element.offsetParent);
}
else{ return 0; }
},
getTop: function( element ) {
if( element ) {
return element.offsetTop + RhapsodyUtility.getTop(element.offsetParent);
}
else{ return 0; }
},
doThrob: function( theElementId, fromElement ) {
var numBlinks = 10;
var blinkMsec = 200;
var theTargetElement = document.getElementById( theElementId );
var theSliderThing = document.getElementById( "topNavSliderThing" );
if( theTargetElement && fromElement && theSliderThing ) {
var theToX = RhapsodyUtility.getLeft(theTargetElement) + theTargetElement.clientWidth / 2;
var theToY = RhapsodyUtility.getTop(theTargetElement) + theTargetElement.clientHeight / 2;
var theFromX = fromElement.offsetLeft + document.body.scrollLeft;
var theFromY = fromElement.offsetTop + document.body.scrollTop;
var theWidth = fromElement.clientWidth;
var theHeight = fromElement.clientHeight;
var numSteps = 25;
var amountOfTime = 500;
var theDeltaX = (theToX - theFromX) / numSteps;
var theDeltaY = (theToY - theFromY) / numSteps;
var theDeltaWidth = theWidth / numSteps;
var theDeltaHeight = theHeight / numSteps;
for( var i=0 ; i <= numSteps ; i++ ) {
var thisX = theFromX + i*theDeltaX;
var thisY = theFromY + i*theDeltaY;
var thisWidth = theWidth - i*theDeltaWidth;
var thisHeight = theHeight - i*theDeltaHeight;
setTimeout( "RhapsodyUtility.setSliderThingie("+thisX+","+thisY+","+thisWidth+","+thisHeight+")", i * amountOfTime / numSteps );
}
setTimeout( "RhapsodyUtility.setSliderThingie(0,0,0,0)", amountOfTime );
for( var i=0 ; i<numBlinks ; i++ ) {
var theColor = i%2 ? "#e0e0e0" : "#d8d8d8";
setTimeout( "document.getElementById('" + theElementId + "').style.backgroundColor = '" + theColor + "'", i * blinkMsec + amountOfTime );
}
setTimeout( "document.getElementById('" + theElementId + "').style.backgroundColor = '#EFEFEF'", numBlinks * blinkMsec + amountOfTime );
}
},
/**
* @method toggleMeddlesomeElements
* @param {boolean} showOnly (Optional)
* @return {String} Returns a string value containing name and greeting
* @description show or hide meddlesome elements on a page
* @note the input param is optional by design. If you omit the input param, it should just toggle between visible and hidden states for the visibility style of the meddlesome elements
*/
toggleMeddlesomeElements: function( showOnly ){
var elementsToToggleIds = this.meddlesomeElements;
var ettidsLength = elementsToToggleIds.length;
for( var i=0; i < ettidsLength; i++ ){
var elementToToggle = document.getElementById( elementsToToggleIds[ i ] );
if( elementToToggle && ( typeof elementToToggle != 'undefined' ) ){
if( elementToToggle.style.visibility == 'hidden' ){//if the elementToToggle has the visibility style defined and it is hidden, make it visible.
elementToToggle.style.visibility = 'visible';
}
else if( !showOnly ){//if the elementToToggle does not have the visibility style defined and the element should not be shown, make its visibility style hidden.
elementToToggle.style.visibility = 'hidden';
}
else { return; }
}
}
},
getBrowserOs: function(){
var os = null;
if( navigator.appVersion.indexOf( 'Win' ) != -1 ) os = "Windows";
else if( navigator.appVersion.indexOf( 'Mac' ) != -1 ) os = "Macintosh";
else if( ( navigator.appVersion.indexOf( "X11" ) != -1 ) || ( navigator.appVersion.indexOf( "Linux" ) != -1 ) ) os = "Unix";
else os = "other";
return os;
},
Client: {
isIE6: function(){
return ( window.external && typeof window.XMLHttpRequest == "undefined" );
},
isFirefox: function(){
return ( navigator.userAgent.toLowerCase().indexOf( "firefox" ) > -1 );
}
},
StringUtil: {
truncateTextByElement: function( elemId, maxChars, cutClean) { //hasn't been used. needs to be tested
var clipElement = document.getElementById( elemId) ;
var clipContents = clipElement.innerHTML;
var origLength = clipContents.length;
clipContents = clipContents.substring( 0, maxChars );
if( origLength > ( maxChars + 4 ) ){
if(cutClean){
clipContents = clipContents.replace(/\w+$/, '...');
}else{
clipContents = clipContents+"...";
}
}
clipElement.innerHTML = clipContents;
},
truncateTextString: function( text, maxChars, cutClean ){
var resultText = text.substring( 0, maxChars );
if( text.length > ( maxChars + 4 ) ){
if(cutClean){
resultText = resultText.replace(/\w+$/, '...');
}else{
resultText = resultText+"...";
}
}
return resultText;
}
},
Node: {
getNextSiblingByType: function( nextFromElement, theNodeType ){
do{
nextFromElement = nextFromElement.nextSibling;
}
while( nextFromElement && nextFromElement.nodeType != theNodeType )
return nextFromElement?nextFromElement:null;
}
},
Ajax: {
includeHtml: function( argObj ){
var theTarget = argObj.target;
var theAjaxParameters = ( typeof argObj.params != 'undefined' )? argObj.params: null;
var disableShowError = ( ( typeof argObj.disableShowError != 'undefined' ) && ( argObj.disableShowError ) );
var passedSuccessCallback = ( typeof argObj.successCallback != 'undefined' )? argObj.successCallback: null;
if( typeof theTarget == 'string' ) theTarget = document.getElementById( argObj.target );
var theAjaxCall = function(){
if( argObj.useLoadMessage ){
if( argObj.useLoadMessageVariant ){
theTarget.innerHTML = RhapsodyUtility.Ajax.getSpinnerHtml( null, argObj.useLoadMessageVariant);
} else theTarget.innerHTML = RhapsodyUtility.Ajax.getSpinnerHtml();
}
theTarget.style.display = "block";
theTarget.style.visibility = "visible";
var ajaxReq = new Ajax.Request(
argObj.ajaxUrl, {
method: 'get',
parameters: theAjaxParameters,
onSuccess: function( theRequest ){
theTarget.ajaxStatus = "success";
theTarget.innerHTML = theRequest.responseText;
var innerScripts = theTarget.getElementsByTagName( "SCRIPT" );
if( innerScripts ) {
for( var i=0; i<innerScripts.length ; i++ ) {
eval( innerScripts[i].innerHTML );
}
}
if( passedSuccessCallback ){ passedSuccessCallback() };
},
onFailure: function( theRequest ){
theTarget.innerHTML = "";
if( !disableShowError ){
RhapsodyUtility.Ajax.writeErrorInElement( argObj.target, theAjaxCall );
}
},
onException: function( e ){
//alert( e );
}
} );
theTarget.ajaxStatus = "loading";
if( argObj.timeoutMillis && !disableShowError ) {
theTarget.theAjaxCall = theAjaxCall;
setTimeout( "RhapsodyUtility.Ajax.tryTimeout('" + argObj.target + "')", argObj.timeoutMillis );
}
}
if( theTarget.innerHTML.length > 10 && !argObj.forceReload ) {
theTarget.style.display = "block";
theTarget.style.visibility = "visible";
} else theAjaxCall();
},
writeErrorInElement: function( elementId, theAjaxCall ) {
var theTarget = document.getElementById(elementId);
theTarget.ajaxStatus = "error";
theTarget.innerHTML = "";
var errorText = document.createTextNode( "We are sorry, there was an error retrieving your content. " );
var errorDiv = document.createElement( "DIV" );
var errorLink= document.createElement( "A" );
var errorLinkText = document.createTextNode( "Click here to try again" );
var tryAgainFunc = function(){
theAjaxCall();
return false;
}
if( errorLink.addEventListener ){
errorLink.href = "javascript:void();";
errorLink.addEventListener( "click", tryAgainFunc, false );
}
else if( errorLink.attachEvent ){
errorLink.attachEvent( "onclick", tryAgainFunc );
errorLink.setAttribute( "href", "javascript:void();" );
} else return;
errorLink.appendChild( errorLinkText );
errorDiv.className = "ajaxError";
errorDiv.appendChild( errorText );
errorDiv.appendChild( errorLink );
theTarget.appendChild( errorDiv );
},
getSpinnerHtml: function( message, variant ){
var theMessage = 'Loading';
var theImageSrc = staticPath;
var toReturn = "";
theImageSrc += ( variant && ( typeof variant != 'undefined' ) )? 'images\/loading_spin_' + variant + '.gif': 'images\/loading_spin_alt_grey.gif';
if( ( message != null ) && ( typeof message != 'undefined' ) ){ theMessage = message };
toReturn = '<div class="loadingSpin"><img src="' + theImageSrc + '" \/>';
if( theMessage !== "" ){
toReturn += '<br \/>' + theMessage + '...';
}
toReturn += '<\/div>';
return toReturn;
},
tryTimeout: function( elementId ) {
var theTarget = document.getElementById(elementId);
var theAjaxCall = theTarget.theAjaxCall;
if( theTarget.ajaxStatus == "loading" ) {
theTarget.ajaxStatus = "timeout";
RhapsodyUtility.Ajax.writeErrorInElement( elementId, theAjaxCall );
}
}
}
}
function AjaxManager() {
this.onError = function (data){Ajax.Responders.dispatch('AjaxManagerOnError', null, null, data); };
this.onTransportError = function (data){Ajax.Responders.dispatch('AjaxManagerOnError', null, null, data); };
this.onContacting = function(){Ajax.Responders.dispatch('AjaxManagerOnContacting', null, null, null);};
this.onGetRating = function(data){Ajax.Responders.dispatch('AjaxManagerOnGetRating', null, null, data);};
this.onSetRating = function(data){Ajax.Responders.dispatch('AjaxManagerOnSetRating', null, null, data);};
this.onGetVideoPlaylist = function(data){Ajax.Responders.dispatch('AjaxManagerOnGetVideoPlaylist', null, null, data);};
this.onGetClipList = function(data){Ajax.Responders.dispatch('AjaxManagerOnGetClipList', null, null, data);};
this.sendMessage = function(url, content, callback){
this.onContacting();
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
if (data.hasError){
new AjaxManager().onError(data);
}
callback(data);
} else {
var data;
data.hasError = true;
data.exception.message = "Bad response from ajax request. " + requestObj.status;
new AjaxManager().onTransportError(data);
}
}
new Ajax.Request(url,{
onSuccess: wrappedCallback,
method: 'get',
parameters: content.toQueryString()
});
}
}
function getQsParam( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
AjaxManager.prototype.getRating = function ( rcid, handler) {
if (handler == null){
handler = this.onGetRating;
}
var url = rhapsodyURL + "/webservice/json/ratings";
var action = "get-ratings";
var content = $H({rcid: rcid,
action: action});
var callback = function (data){
if(data.hasError){
this.onError("Whoops - " + data.exception.message + ' ' + data.exception.code);
}else{
handler(data);
}
}
this.sendMessage(url, content, callback);
}
AjaxManager.prototype.setRating = function ( rcid, rating, handler) {
if (handler == null){
handler = this.onSetRating;
}
var url = rhapsodyURL + "/webservice/json/ratings";
var action = "set-rating";
var content = $H({rcid: rcid,
rating: rating,
action: action});
var callback = function (data){
if(data.hasError){
this.onError("Whoops - " + data.exception.message + ' ' + data.exception.code);
}else{
handler(data);
}
}
this.sendMessage(url, content, callback);
}
AjaxManager.prototype.getVideoPlaylist = function ( playlistId, handler) {
if (handler == null){
handler = this.onGetVideoPlaylist;
}
var url = rhapsodyURL + "/webservice/json/video-playlist";
var content = $H({playlistId: playlistId
});
var callback = function (data){
if(data.hasError){
this.onError("Whoops - " + data.exception.message + ' ' + data.exception.code);
}else{
handler(data);
}
}
this.sendMessage(url, content, callback);
}
AjaxManager.prototype.getClipList = function ( clipIds, handler) {
if (handler == null){
handler = this.onGetClipList;
}
var url = rhapsodyURL + "/webservice/json/video-playlist";
var content = $H({clipId: clipIds
});
var callback = function (data){
if(data.hasError){
this.onError("Whoops - " + data.exception.message + ' ' + data.exception.code);
}else{
handler(data);
}
}
this.sendMessage(url, content, callback);
}
AjaxManager.prototype.getPersonalization = function ( passedGuid, passedECode, handler) {
var url = rhapsodyURL + "/js/personalization.json";
var content = $H( { guid: passedGuid, ecode: passedECode } );
var callback = function( data ){
if(data.hasError){
this.onError( "Whoops - " + data.exception.message + ' ' + data.exception.code );
} else {
handler( data );
}
}
this.sendMessage( url, content, callback );
}
AjaxManager.prototype.getMenu = function ( passedPrefix, handler) {
var url = "/menu.json"
if( rhapsodyMember.usersPartner == "verizon" ){
var content = $H( { prefix: passedPrefix, usersPartner:rhapsodyMember.usersPartner } );
} else {
var content = $H( { prefix: passedPrefix } );
}
var callback = function( data ){
if(data.hasError){
this.onError( "Whoops - " + data.exception.message + ' ' + data.exception.code );
} else {
handler( data );
}
}
this.sendMessage( rhapsodyURL + url, content, callback );
}
AjaxManager.prototype.getWelcomeOverlay = function ( handler) {
var url = "/welcomeOverlay.json";
var content = $H({});
var callback = function( data ){
if(data.hasError){
this.onError( "Whoops - " + data.exception.message + ' ' + data.exception.code );
} else {
handler( data );
}
}
this.sendMessage( rhapsodyURL + url, content, callback );
}
var RhapsodyAdvertisement = {
forceAds: false,
serveHomepageSlideshowTakeover: false,
elementsToHideOnSlideshowTakeover: null,
registerForAdvertisement: function( type, adDiv, adServerUrl, adParams, isHouseArt ){
var theAdUrl = this._getAdUrl( adServerUrl, adParams );
if( type == "block" ) return;
if( type == "iframe" ){
if( isHouseArt ) this.getHouseArt( adDiv, adServerUrl, isHouseArt );
else if( RhapsodyUtility.Client.isFirefox() ) adDiv.src = theAdUrl;
else RhapsodyUtility.addLoadEvent( function(){
adDiv.src = theAdUrl;
} );
} else if( type == "debug" ) {
document.write( theAdUrl );
} else {
if( isHouseArt ){
this.getHouseArt( adDiv, adServerUrl, isHouseArt );
} else {
document.write( '<scr' + 'ipt src="' + theAdUrl + '">' );
document.write( '<\/scr' + 'ipt>' );
}
}
},
reloadAds: function( ids ){
var args = arguments;
for( var i=0; i < args.length; i++ ){
var theAdElement = document.getElementById( args[ i ] );
try{
if( theAdElement && ( typeof theAdElement != 'undefined' ) && ( theAdElement.tagName.toLowerCase() == 'iframe' ) ){
theAdElement.src = theAdElement.src.replace( /ord=[^;]*/, "ord=" + this._getOrd() );
}
} catch( e ){};
}
},
getHouseArt: function( insertInto, houseArtUrl, isHouseArt ){
var rndmOrd = Math.round( Math.random() * 10 );
RhapsodyUtility.addLoadEvent( function(){
RhapsodyUtility.Ajax.includeHtml( {
ajaxUrl: houseArtUrl + "&rndm=" + rndmOrd,
target: insertInto,
forceReload: true
} );
} );
},
_getAdUrl: function( adServerUrl, adParams ){
var theSubplan = 0;
var theDartValuesString = "";
try{
theSubplan = RhapsodyPersonalization.AdvertisingValues.dartKeyValuesHash[ 'subplan' ];
} catch(e) {}
try{
theDartValuesString = RhapsodyPersonalization.AdvertisingValues.dartKeyValuesString;
} catch(e) {}
var theAdUrl = adServerUrl +
theSubplan +
adParams +
";" +
theDartValuesString +
"ord=" +
this._getOrd() +
";";
return theAdUrl;
},
_getOrd: function(){
return Math.round( Math.random() * 10000000 );
}
}
function openPlayer(id,type,title,page,pageRegion,guid,origin) {
RhapsodyPlayer.playRcid(id);
}
function openPlayerWindow(id, type, title, remote, page, pageRegion, guid, origin) {
try {
if (!rhapPlayer || rhapPlayer.closed) {
openThis(id, type, title, remote, page, pageRegion, guid, origin)
} else {
rhapPlayer.getMetaData(type,id,title,remote);
rhapPlayer.focus();
}
} catch (e) {
openThis(id, type, title, remote, page, pageRegion, guid, origin);
}
}
function openPlayerFromRhaplink(origin, id, type, title, remote, page, pageRegion, guid) {
//Temp - fix the jill code on the rhaplink landing page
var playerLocation = 'http://www.rhapsody.com/player';
var successfulOpen = false;
wname="rhapPlayer";
width=270;
height=570;
if (title) {
playerLocation += "?type=" + type + "&id="+id +"&title="+title +"&remote="+remote + "&page=" + page + "&pageregion=" + pageRegion + "&guid=" + guid + "&from=" + origin;
} else {
playerLocation += "?type=" + type + "&id="+id +"&remote="+remote + "&page=" + page + "&pageregion=" + pageRegion + "&guid=" + guid + "&from=" + origin;
}
var openFunction=function(){
if (!rhapPlayer || rhapPlayer.closed) {
rhapPlayer = window.open(playerLocation,wname,"width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,top=20,left="+openFromLeftAt+"");
} else {
rhapPlayer.getMetaData(type,id,title,remote);
rhapPlayer.location.setParameter('page',page);
}
if((rhapPlayer!=null) && (typeof rhapPlayer!="undefined")){
if (!rhapPlayer.opener) rhapPlayer.opener = self;
rhapPlayer.focus();
return true;
}
}
successfulOpen=openFunction();
if(!successfulOpen){
SimplePopUpBlockHandler.alertUser(openFunction);
}
}
function openWin(name,url,width,height){
newwindow = window.open(url,name,"width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
newwindow.focus();
return newwindow;
}
/* This function does not return anything. Returning causes the parent window to refresh with the returned value.
*/
function openWin2(name,url,width,height){
newwindow = window.open(url,name,"width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0");
newwindow.focus();
}
function openWinNoFocus(name,url,width,height){
newwindow = window.open(url,name,"width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
window.focus();
return newwindow;
}
function signOut() {
signOutWindow = openWin("signin","/signin?signout=true",270,200);
}
/* ********* BEGIN: Radio Station List Code ********* */
var radioFilterLastSelectedIndex = 0;
function processFilterSelection( object ) {
var genreSelection = document.radioFilter.genreId.options[document.radioFilter.genreId.selectedIndex].value;
if( genreSelection != 'SEPARATOR' ) {
saveFilterIndex();
document.getElementById("updatingDiv").innerHTML = "Loading.&nbsp;&nbsp;Please wait...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
location.href = "/radio?genreId=" + genreSelection;
} else {
resetFilterIndex();
}
}
function saveFilterIndex() {
radioFilterLastSelectedIndex = document.radioFilter.genreId.selectedIndex;
}
function resetFilterIndex() {
document.radioFilter.genreId.selectedIndex = radioFilterLastSelectedIndex;
}
/* ********** END: Radio Station List Code ********* */
/* ********* BEGIN: Playlist Central Browse Playlists Code ********* */
function toggleElementDisplay(elementName)
{
var elementObj = document.getElementById(elementName);
if( elementObj ) {
var currState = elementObj.style.display;
if( currState == 'block' ) {
elementObj.style.display = 'none';
}
else {
elementObj.style.display = 'block';
}
}
}
function toggleImgState(imgID, srcRoot, altState)
{
var elementObj = document.getElementById(imgID);
if( elementObj ) {
var currState = elementObj.src;
if( currState.indexOf(altState) > -1 ) {
elementObj.src = staticPath + 'images/buttons/' + srcRoot + '.gif';
}
else {
elementObj.src = staticPath + 'images/buttons/' + srcRoot + altState + '.gif';
}
}
}
/* ********** END: Playlist Central Browse Playlists Code ********* */
function submitFormById( formId ) {
var theForm = document.getElementById(formId);
if ( theForm ) {
theForm.submit();
}
}
function doSearch( missingQueryMsg, defaultMessage ) {
var theForm = document.getElementById('navbarSearchForm');
var theQueryObj = document.getElementById('headerSearchQuery');
var theQuery = document.getElementById('headerSearchQuery').value;
// Trim spaces off end
theQuery = trimString(theQuery);
// Reset the query string value on the page
theQueryObj.value = theQuery;
var theSearchType = document.getElementById('searchtype').value;
if ( ( theQuery.length > 0 ) && ( theQuery != defaultMessage ) ){
theQuery = escape(encodeutf8(theQuery));
document.location.href = rhapsodyURL + "/-search?query=" + theQuery + "&searchtype=" + theSearchType;
return false;
} else {
alert(missingQueryMsg);
theQueryObj.focus();
return false;
}
}
function encodeutf8( pstring ) {
var lstring = pstring.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < lstring.length; n++) {
var c = lstring.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
function trimString(psInString) {
var sInString = psInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
function getSignedInStatus() {
var userGuid = "";
var authRefreshTime = CookieManager.getCookie("authRefreshTime");
var isNamed = false;
var entCode = "";
try {
userGuid = rhapsodyMember.getMemberAttribute("guid");
var isAnon = rhapsodyMember.getMemberAttribute("isAnonymousUser");
var isLoggedIn = rhapsodyMember.getMemberAttribute("isLoggedIn");
isNamed = isLoggedIn && !isAnon;
if( isNamed ) entCode = rhapsodyMember.getMemberAttribute("entitlementCode");
} catch(e) { }
var mReturn = "";
if( isNamed ) {
mReturn = authRefreshTime + "_" + userGuid + "_" + isNamed + "_" + entCode;
}
else {
mReturn = authRefreshTime + "_" + "notNamed";
}
return mReturn;
}
/* default thing to do on sign in status change, can be overriden in a page */
function onSignedInStatusChange() {
var changedInThisPage = false;
try {
changedInThisPage = guidWasChangedInThisPage;
} catch(e) { /** do nothing **/ }
if( changedInThisPage ) {
try {
RhapsodyPlayer.getFlashApp("embedded").doStorePlayerState();
return;
}
catch( e ) {
// IN the case of an exception trying to call doStorePlayerState(), just refresh the page...
onAuthenticationRefreshPage();
}
}
// If that didn't happen on this page, just refresh it...
onAuthenticationRefreshPage();
}
function onPlayerStateStored() {
if( guidWasChangedInThisPage ) {
// alert("embedded player state storing is done... reloading the page...");
onAuthenticationRefreshPage( RhapsodyPlayer.playbackWasInterrupted() );
}
}
function onAuthenticationRefreshPage( restoreEmbeddedPlayer ) {
var theLocation = top.document.location.href;
var theRand = ".rand=";
var indexOfRand = top.document.location.href.indexOf(".rand=");
if( indexOfRand>=0 ) {
var theLocation = top.document.location.href.substring( 0, indexOfRand );
var indexOfAmpersand = top.document.location.href.indexOf( "&", indexOfRand );
if( indexOfAmpersand >= 0 ) {
theLocation += top.document.location.href.substring(indexOfAmpersand);
}
}
try {
document.getElementById("topNavSignInOut").innerHTML = '<img src="http://static.realone.com/rotw/images/libraryloading_overwhite.gif" \/>';
} catch(e){ }
top.document.location.replace( theLocation );
}
var lastSignedInStatus = null;
function watchSignedInStatus() {
if( !lastSignedInStatus ) {
lastSignedInStatus = getSignedInStatus();
setTimeout("watchSignedInStatus()",100);
return;
}
if( getSignedInStatus()!=lastSignedInStatus ) {
document.cookie = "autoReloadingTime="+(6000 + new Date().valueOf())+"; path=/; domain=.rhapsody.com;";
setTimeout("onSignedInStatusChange()",1000);
}
else {
setTimeout("watchSignedInStatus()",100);
}
}
/**
var CURRENTMOUSEOVER_RCID = 0;
var INFOMOUSEOVER_CACHE = new Array();
var CURRENTMOUSEOVERACTION = 0;
var INFOBOXMOUSEDOVER = false;
function isValidInfoMouseoverPrefix( rcid ) {
return rcid.indexOf("art.")==0 || rcid.indexOf("alb.")==0 || rcid.indexOf("g.")==0 || rcid.indexOf("sta.")==0 || rcid.indexOf("ply.")==0;
}
function showInfoMouseover( jsonObject, mousex, mousey ) {
CURRENTMOUSEOVERACTION++;
var mouseoverDiv = document.getElementById("infoMouseOverDiv");
var offsetFromLeft = Math.max( document.body.scrollLeft, document.documentElement.scrollLeft );
var offsetFromTop = Math.max( document.body.scrollTop, document.documentElement.scrollTop );
if( window.pageYOffset ) offsetFromTop = Math.max( offsetFromTop, window.pageYOffset );
var docWidth = document.documentElement.clientWidth + offsetFromLeft;
var docHeight = document.documentElement.clientHeight + offsetFromTop;
mouseoverDiv.innerHTML = jsonObject.html;
if( mousex + 15 + jsonObject.width > docWidth ) {
mouseoverDiv.style.left = (mousex - 30 - jsonObject.width) + "px";
}
else {
mouseoverDiv.style.left = (mousex + 15) + "px";
}
if( mousey + jsonObject.height + offsetFromTop > docHeight ) {
mouseoverDiv.style.top = (mousey + offsetFromTop - jsonObject.height) + "px";
}
else {
mouseoverDiv.style.top = (mousey + document.documentElement.scrollTop) + "px";
}
mouseoverDiv.style.width = jsonObject.width + "px";
mouseoverDiv.style.height = jsonObject.height + "px";
mouseoverDiv.style.opacity = "0.90";
mouseoverDiv.style.filter = "alpha(opacity=90)";
mouseoverDiv.style.visibility = "visible";
}
function infoMouseOverAjax( rcid, mousex, mousey ) {
if( isValidInfoMouseoverPrefix(rcid) ) {
var mouseoverDiv = document.getElementById("infoMouseOverDiv");
mouseoverDiv.style.visibility = "hidden";
var ajaxReq = new Ajax.Request(
rhapsodyURL + "/infomouseover.json", {
parameters: "rcid="+rcid,
method: 'get',
onSuccess: function( theRequest ) {
var theJsonObject = eval('('+theRequest.responseText+')');
if( theJsonObject.rcid == CURRENTMOUSEOVER_RCID ) {
INFOMOUSEOVER_CACHE[rcid] = theJsonObject;
showInfoMouseover(theJsonObject, mousex, mousey);
}
}
} );
}
}
function getMousedoverRcid( element ) {
var thercid = element.getAttribute("rcid");
for( var i=0 ; !thercid && i<3 ; i++ ) {
element = element.parentNode;
if( !element ) { break; }
try { thercid = element.getAttribute("rcid"); } catch (e) { }
}
return thercid;
}
function doInfoMouseOver( eventElement, mouseEvent ) {
thercid = getMousedoverRcid(eventElement);
if( thercid ) {
thercid = thercid.toLowerCase();
CURRENTMOUSEOVER_RCID = thercid;
setTimeout( "doInfoMouseOverDelayed('" + thercid + "', "+mouseEvent.clientX+", "+mouseEvent.clientY+")", 100 );
}
}
function doInfoMouseOverDelayed( thercid, mousex, mousey ) {
if( CURRENTMOUSEOVER_RCID != thercid ) { return; }
if( INFOMOUSEOVER_CACHE[thercid] ) showInfoMouseover( INFOMOUSEOVER_CACHE[thercid], mousex, mousey );
else infoMouseOverAjax( thercid, mousex, mousey );
}
function doInfoMouseOut( eventElement ) {
if( INFOBOXMOUSEDOVER ) return;
thercid = getMousedoverRcid(eventElement);
if( thercid ) {
setTimeout( "doInfoMouseOutDelayed('" + thercid + "', "+CURRENTMOUSEOVERACTION+")", 250 );
}
}
function doInfoMouseOutDelayed( thercid, theaction ) {
if( INFOBOXMOUSEDOVER ) return;
if( CURRENTMOUSEOVERACTION != theaction ) { return; }
if( CURRENTMOUSEOVER_RCID != thercid ) { return; }
CURRENTMOUSEOVER_RCID = 0;
var mouseoverDiv = document.getElementById("infoMouseOverDiv");
mouseoverDiv.style.visibility = "hidden";
}
function captureMouseOverFF( mouseEvent ) {
doInfoMouseOver( mouseEvent.target, mouseEvent );
}
function captureMouseOutFF( mouseEvent ) {
doInfoMouseOut( mouseEvent.target );
}
function captureMouseOverIE( ) {
var mouseEvent = window.event;
var eventElement = mouseEvent.srcElement;
doInfoMouseOver( eventElement, mouseEvent );
}
function captureMouseOutIE( ) {
var mouseEvent = window.event;
var eventElement = mouseEvent.srcElement;
doInfoMouseOut( eventElement );
}
var theUa = navigator.userAgent.toLowerCase();
if( theUa.indexOf("win")>=0 && theUa.indexOf("msie")>=0 ) {
document.onmouseover = captureMouseOverIE; // IE
document.onmouseout = captureMouseOutIE; // IE
}
else {
document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
document.onmouseover = captureMouseOverFF; // FF
document.onmouseout = captureMouseOutFF; // FF
}
function doMousedOverInfoBox( element ) {
INFOBOXMOUSEDOVER = true;
element.style.opacity = "1.00";
element.style.filter = "alpha(opacity=100)";
}
function doMousedOutInfoBox( event ) {
INFOBOXMOUSEDOVER = false;
var mouseoverDiv = document.getElementById("infoMouseOverDiv");
if( !Position.within( mouseoverDiv, Event.pointerX( event ), Event.pointerY( event ) ) ) {
mouseoverDiv.style.visibility = "hidden";
}
}
document.write("<div id='infoMouseOverDiv' style='position:absolute; visibility:hidden; background-color:#ffffff; border:1px solid #666666; z-index:110;' onMouseOver='doMousedOverInfoBox(this)'></div>");
function doInfoMouseoverEventCapture() {
var element = document.getElementById('infoMouseOverDiv');
if( !element ) {setTimeout( "doInfoMouseoverEventCapture()", 500 );}
else {
try { Event.observe( element, 'mouseout', doMousedOutInfoBox ); } catch(e) {}
}
}
doInfoMouseoverEventCapture();
**/
function Member(){};
Member.prototype = {
entitlementCode: null,
userName: "",
guid: "",
rhapUserId: "",
entitlement: "",
isLoggedIn: null,
isAnonymousUser: null,
isUnlimitedPlays: null,
isPremiumUser: null,
isRadioPremiumUser: null,
isShowNoAds: null,
isRhapsodyToGo: null,
truncatedUserName: "",
genderAsNumeric: null,
birthYear: null,
postalCode: null,
initialLetter: "",
payment: "",
hasRhapF: null,
rhapFVersion: null,
isUS: null,
usersPartner: "",
cobrandPartner: "",
cpath: "",
ocode: "",
rsrc: "",
Browser: {
os: ""
},
isCanned: null,
objectBornOn: null,
postalCode: "",
getMemberAttribute: function( maName ){
return this[ maName ];
},
setMemberAttribute: function( maName, maValue ){
this[ maName ] = maValue;
return maValue;
}
}
var RhapsodyTestAndTarget = {};
var RhapsodyTracking = {
_accountId: null,
_category: null,
_pageName: null,
_environment: null,
_siteCode: "rotw",
_events: [],
primaryContentId: null,
primaryContentName: null,
artistId: null,
artistName: null,
albumId: null,
albumName: null,
browseResultsCount: null,
browseQuery: null,
defaultClientName: 'rhapf',
secondaryClientName: 'rhape',
tertiaryClientName: 'rhapx',
treatSearchAsBrowse: false,
errorType: null,
genreName: null,
lsrc: null,
musicVideoId: null,
pageId: null,
publicationDate: null,
_rhapsodyMember: null,
searchCategory: null,
searchResultsCount: null,
searchQuery: null,
searchType: null,
testVariant: null,
topLevelGenreName: null,
profileFriends: null,
profilePublicPlaylists: null,
okToDebug: false,
_registeredInitCallbacks: new Array(),
debugElement: null,
getAccountId: function(){
return this._accountId;
},
getEnvironment: function(){
return this._environment;
},
getCategory: function(){
return this._category?this._category:"";
},
getPageName: function(){
return this._pageName?this._pageName:"";
},
getSiteCode: function(){
return this._siteCode?this._siteCode:"";
},
setAccountId: function( aid ){
this._accountId = aid;
},
setEnvironment: function( env ){
this._environment = env;
},
setCategory: function( cat ){
this._category = cat;
},
setPageName: function( pn ){
this._pageName = pn;
},
setSiteCode: function( sc ){
this._siteCode = sc;
},
getBreadcrumbs: function(){
var crumbs = null;
var crumbTrail = document.getElementById( 'crumbtrail' );
if( crumbTrail ) crumbs = crumbTrail.innerHTML;
if( crumbs ){
crumbs = crumbs.stripTags();
crumbs = crumbs.replace( /&gt;/g, ' : ' );
crumbs = crumbs.replace( /&[^;]+;/g, '' );
crumbs = crumbs.replace( /\s+/g, ' ' );
crumbs = crumbs.replace( /Home :/gi, ' ' );
crumbs = crumbs.strip();
return crumbs;
} else return null;
},
getLocalSrc: function( raw ){
var returnLsrc = this.lsrc;
if( !raw && returnLsrc ) returnLsrc = returnLsrc.replace( /_/g, ':' );
return returnLsrc;
},
setLocalSrc: function( ls ){
this.lsrc = ls;
},
getLinkInternalFilters: function(){
return "javascript:,rhapsody.com,static.";
},
getCustomMetric: function( cmName, castTo ){
var cmReturn = this[ cmName ];
if( ( cmReturn != null ) && ( castTo == 'String' ) ) cmReturn = cmReturn.toString();
return cmReturn != null?cmReturn:"";
},
setCustomMetric: function( cmName, cmValue ){
if( cmValue.strip != '' ) this[ cmName ] = cmValue;
return cmValue;
},
getClientName: function(){
var toReturn = '0';
if( this.getRhapsodyMember() && this.defaultClientName == 'rhapf'){
if( this.getRhapsodyMember().getMemberAttribute( "hasRhapF" ) ) toReturn = ( this.getRhapsodyMember().getMemberAttribute( "rhapFVersion" ).indexOf( 'rhapE' ) > -1 )? this.secondaryClientName: this.defaultClientName;
else if ( this.getRhapsodyMember().getMemberAttribute( "hasRhapX" ) ) toReturn = this.tertiaryClientName;
} else if( this.getRhapsodyMember() && this.defaultClientName == 'dlm'){
toReturn = this.defaultClientName;
}
return toReturn;
},
getClientVersion: function(){
var toReturn = null;
if( ( this.getClientName() == 'rhapf' ) || ( this.getClientName() == 'rhape' ) ){
toReturn = ( this.getRhapsodyMember() && this.getRhapsodyMember().getMemberAttribute( "rhapFVersion" ) && this.getRhapsodyMember().getMemberAttribute( "hasRhapF" ) )?this.getRhapsodyMember().getMemberAttribute( "rhapFVersion" ):toReturn;
} else if( this.getClientName() == 'rhapx' ){
toReturn = ( this.getRhapsodyMember() && this.getRhapsodyMember().getMemberAttribute( "rhapXVersion" ) && this.getRhapsodyMember().getMemberAttribute( "hasRhapX" ) )?this.getRhapsodyMember().getMemberAttribute( "rhapXVersion" ):toReturn;
} else if ( this.getClientName() == 'dlm' ) {
toReturn = ( this.getRhapsodyMember() && this.getRhapsodyMember().getMemberAttribute( "dlmVersion" ) && this.getRhapsodyMember().getMemberAttribute( "hasDlm" ) )?this.getRhapsodyMember().getMemberAttribute( "dlmVersion" ):toReturn;
}
return toReturn;
},
getEvents: function(){
var toReturn = "";
for( var i=0; i < this._events.length; i++ ){
var nextVal = this._events[ i ];
toReturn += i > 0?"," + nextVal :nextVal;
}
return toReturn;
},
addEvent: function( ev ){
this._events.push( ev );
},
getRhapsodyMember: function(){
return this._rhapsodyMember;
},
setRhapsodyMember: function( rm ){
this._rhapsodyMember = rm;
},
registerInitCallback: function( cb ){
this._registeredInitCallbacks.push( cb );
},
executeRegisteredInitCallbacks: function(){
var riCallbacks = this._registeredInitCallbacks;
if( riCallbacks.length < 1 ) return;
for( var i=0; i< riCallbacks.length; i++ ){
riCallbacks[ i ]();
}
},
getCampaignData: function(){
var delim = ":";
var cdString = "";
var thePcode = ( this.getRhapsodyMember() && this.getRhapsodyMember().cobrandPartner && this.getRhapsodyMember().cobrandPartner != '' )?this.getRhapsodyMember().cobrandPartner:"RN";
var theCpath = ( this.getRhapsodyMember() && this.getRhapsodyMember().cpath && this.getRhapsodyMember().cpath != '' )?this.getRhapsodyMember().cpath:"RN";
var theRsrc = ( this.getRhapsodyMember() && this.getRhapsodyMember().rsrc && this.getRhapsodyMember().rsrc != '' )?this.getRhapsodyMember().rsrc:"RN";
if( this.getRhapsodyMember() ) cdString = thePcode + delim + theCpath + delim + theRsrc;
return cdString;
},
sendPageView: function( overridesObj, optionsObj ){
var disableCall = false;
var persistPreviousOverrides = ( optionsObj && optionsObj.persistPreviousOverrides )? ( optionsObj && optionsObj.persistPreviousOverrides ): false;
try{
s = s_gi( this.getAccountId() );
} catch( e ){ disableCall = true }
if( !persistPreviousOverrides ) this.setDefaultConfig();
if( !disableCall ){
this._setOverrides( overridesObj );
void( s.t() );
if( this.okToDebug ){
if( this.debugElement ) this.debug( true );
this.debug();
}
}
},
sendLinkEvent: function( overridesObj, optionsObj, rd ){
// if i want original data set s.linkTrackVars = ""; and s.linkTrackEvents = "";
var disableCall = false;
try{
s = s_gi( this.getAccountId() );
} catch( e ){ disableCall = true }
var linkTypeHash = new Object();
linkTypeHash[ 'exit' ] = 'e';
linkTypeHash[ 'download' ] = 'd';
linkTypeHash[ 'custom' ] = 'o';
var linkTypeAbbrev = optionsObj.type?linkTypeHash[ optionsObj.type ]:null;
var linkName = optionsObj.linkName?optionsObj.linkName:null;
var ltvString = "eVar18,eVar37";
var moreThanOne = false;
if( !disableCall && optionsObj && overridesObj ){
s.eVar18 = this.getPageName();
s.eVar37 = this.getSiteCode();
for( var i in overridesObj ){
s[ i ] = overridesObj[ i ];
ltvString += "," + i;
moreThanOne = true;
}
if( optionsObj.events ){
s.linkTrackEvents = optionsObj.events;
s.events = optionsObj.events;
ltvString += ",events";
}
s.linkTrackVars = ltvString;
if( linkTypeAbbrev && linkName ){
void( s.tl( this, linkTypeAbbrev, linkName ) );
}
}
if( rd ){
setTimeout( function(){
document.location.href = rd;
}, 200 );
}
},
_setOverrides: function( or ){
for( var i in or ){
s[ i ] = or[ i ];
}
},
debug: function( closeDebug ){
var timeoutTilClose = 5000;
var omnitureImgHolder = document.getElementById( 'omnitureCodeToPaste' );
var omnitureImg = null;
var debugInfo = 'Tracking Info:<br\/>' +
'Category: ' + this.getCategory()+ '<br\/>' + 'Page Name: ' + this.getPageName() + '<br\/>' +
'<a href="#" onclick="RhapsodyTracking.debug( true ); return false;">close<\/a>';
if( omnitureImgHolder && ( typeof omnitureImgHolder != 'undefined' ) ){
omnitureImg = window[ 's_i_realnetworks' ];
}
if( omnitureImg && omnitureImg.src != '' ) debugInfo += "<p>sent a request to omniture<\/p>";
else debugInfo += '<p style="color: red;">no request sent to omniture!<\/p>';
if( !closeDebug && typeof DialogBox != 'undefined' ){
this.debugElement = new DialogBox(
{
elementId: "RhapsodyTrackingDebugBox",
width: '230px',
height: '180px',
htmlContent: debugInfo
}
);
this.debugElement.show();
with( this.debugElement.getHoldingElement().style ){
backgroundColor = "#CCC";
padding = "10px";
overflow = "auto";
}
if( !RhapsodyTracking.getPageName() || !RhapsodyTracking.getCategory() ){
timeoutTilClose = 15000;
with( this.debugElement ){
hide();
setMask( true );
getHoldingElement().style.backgroundColor = "red";
centerInPage();
show();
loadContent( { htmlContent: debugInfo + '<p><b>set a category and pagename in /conf/rotw.reporting-services.xml<\/b><\/p>' } );
}
}
RhapsodyUtility.setAlpha( "RhapsodyTrackingDebugBox", 80 );
var omnitureDebugHolderElement = document.createElement( "DIV" );
var omnitureDebugAnchor = document.createElement( "A" );
var rhapsodyMemberDebugAnchor = document.createElement( "A" );
var omnitureDebugAnchorText = document.createTextNode( "view omniture debugger" );
var rhapsodyMemberDebugText = document.createTextNode( "view rhapsodyMember debugger" );
omnitureDebugAnchor.appendChild( omnitureDebugAnchorText );
rhapsodyMemberDebugAnchor.appendChild( rhapsodyMemberDebugText );
omnitureDebugAnchor.setAttribute( "href", "javascript:RhapsodyTracking.launchOmnitureDebug();" );
rhapsodyMemberDebugAnchor.setAttribute( "href", rhapsodyURL + "/test/rhapsodyMember.html" );
omnitureDebugHolderElement.appendChild( omnitureDebugAnchor );
omnitureDebugHolderElement.appendChild( document.createElement( "BR" ) );
omnitureDebugHolderElement.appendChild( rhapsodyMemberDebugAnchor );
this.debugElement.getHoldingElement().appendChild( omnitureDebugHolderElement );
setTimeout( "RhapsodyTracking.debug( true )", timeoutTilClose );
} else {
if( RhapsodyTracking.debugElement ){
RhapsodyTracking.debugElement.removeHoldingElement();
if( RhapsodyTracking.debugElement.getMask() ) RhapsodyTracking.debugElement.setMask( false );
RhapsodyTracking.debugElement = null;
}
}
},
launchOmnitureDebug: function(){
window.open( '','stats_debugger','width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1' ).document.write( '<script type="text/javascript" src="https://sitecatalyst.omniture.com/sc_tools/stats_debugger.html"><\/' + 'script>' + '<script type="text/javascript">window.focus();<\/' + 'script>' );
}
}
var RhapsodyDom = {
bodyLoaded: false,
init: function(){
RhapsodyUtility.addLoadEvent(
function(){ RhapsodyDom.bodyLoaded = true; }
);
}
};
RhapsodyDom.init();
var RhapsodyDynamicNav = {
_menuPrefix: "",
ddDialogBoxInstance: null,
_ddCounter: 0,
TOP_NAV_HOLDER_ELEMENT_ID: 'topNavMenuHolder',
_srcVersion: 0,
TOP_NAV_MENU_ITEM_CLASS_NAME: 'topNavMenuItem',
TOP_NAV_SUB_MENU_ITEM_CLASS_NAME: 'topNavSubMenuItem',
evaluateAndToggleElements: [],
init: function( rdnArgObj){
this._menuPrefix = rdnArgObj.prefix;
this._srcVersion = rdnArgObj.version;
this._buildDynamicMenu();
this._handleClientLogic( this.evaluateAndToggleElements );
this.colorActiveMenu();
},
buildDropDown: function( ddArgObj ){
var dropDownParentElement = ddArgObj.menuParent;
var dropDownHTML = this._getDropdownMenuHTML( dropDownParentElement );
var dropDownElementId = 'topNavDropDownMenu' + this._ddCounter++;
if( this.ddDialogBoxInstance ){ this.destroyDialogBox(); }
this.ddDialogBoxInstance = new DialogBox(
{
elementId: dropDownElementId,
elementClassName: 'topNavDropDownMenu',
elementType: "UL",
spawnFrom: dropDownParentElement,
spawnFromOffset: [ 0, 31 ],
height: 'auto',
width: '15em',
htmlContent: dropDownHTML
}
);
try{
if( this.ddDialogBoxInstance ){
var theSlideshow = document.getElementById( 'slideshow' );
var hasSlideshow = ( theSlideshow && ( typeof theSlideshow != 'undefined' ) )? true: false;
var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var isFFMac = ( RhapsodyUtility.getBrowserOs() == 'Macintosh' ) && isFF;
if( !( isFFMac && hasSlideshow ) ){
RhapsodyUtility.doFadein( this.ddDialogBoxInstance.getHoldingElement().id, 95, 3, 60 );
} else { document.getElementById( dropDownElementId ).style.opacity = '1'; }
this.ddDialogBoxInstance.registerOuterClickListener( this.destroyDialogBox );
// registerOuterLoiteringListener( this.destroyDialogBox );
this.ddDialogBoxInstance.show();
Event.observe( window, 'resize', RhapsodyDynamicNav.destroyDialogBox );
}
} catch( e ){}
},
colorActiveMenu: function(){
var topLevelMenusItems = Element.getElementsByClassName( this._getTopNavHolderElement(), this.TOP_NAV_MENU_ITEM_CLASS_NAME );
for( var i=0; i < topLevelMenusItems.length; i++ ){
var tlMenuItem = topLevelMenusItems[ i ];
var tlMenuItemAnchor = tlMenuItem.getElementsByTagName( 'A' )[ 0 ];
var theNextElementSibling = RhapsodyUtility.Node.getNextSiblingByType( tlMenuItem, 1 );
var hasChildren = theNextElementSibling && ( theNextElementSibling.tagName == "UL" );
if( hasChildren ){
var tlMenuItemChildren = Element.getElementsByClassName( theNextElementSibling, this.TOP_NAV_SUB_MENU_ITEM_CLASS_NAME );
for( var j=0; j < tlMenuItemChildren.length; j++ ){
var tlSubMenuItem = tlMenuItemChildren[ j ];
var tlSubMenuItemAnchor = tlSubMenuItem.getElementsByTagName( 'A' )[ 0 ];
this._doCheckAndMakeActiveItem( tlMenuItem, tlSubMenuItemAnchor );
}
} else { this._doCheckAndMakeActiveItem( tlMenuItem, tlMenuItemAnchor ); }
}
},
_doCheckAndMakeActiveItem: function( elementToChange, elementToCompare ){
var currentAddress = window.location.pathname;
var currentQS = window.location.search;
var currentAddressWithQS = currentQS !== ''? currentAddress + '?' + currentQS: currentAddress;
var classNameTextOn = 'navBarMenuLinkon';
var isHome = ( elementToCompare.href == rhapsodyURL + "/" ) && currentAddress == "/home.html";
var elementToCompareHref = elementToCompare.href;
elementToCompareHref = elementToCompareHref.replace( /[^\/]*:\/\/[^\/]*(\/.*)/, "$1" );
if( ( ( elementToCompareHref == currentAddressWithQS ) || elementToCompareHref == currentAddress ) || isHome ){
Element.addClassName( elementToChange, classNameTextOn );
}
},
_buildDynamicMenu: function(){
var menuMgr = new AjaxManager();
menuMgr.getMenu( this._menuPrefix, this._renderDynamicMenu );
},
_shouldRenderDynamicMenu: function( menuData ){
return ( menuData && ( typeof menuData != 'undefined' && ( menuData.version != RhapsodyDynamicNav._srcVersion ) ) );
},
_renderDynamicMenu: function( menuData ){
var dynamicMenuHTML = '';
if( RhapsodyDynamicNav._shouldRenderDynamicMenu( menuData ) ){
for( var i=0; i < menuData.children.length; i++ ){
var aMenuItem = menuData.children[ i ];
var listParentId = 'topNav' + aMenuItem.id;
var userAgentPattern = aMenuItem.useragentpattern;
var rhapsodyMemberPropertyName = aMenuItem.rhapsodymemberpropertyname;
var rhapsodyMemberPropertyValue = aMenuItem.rhapsodymemberpropertyvalue;
var defaultDisplayNone = userAgentPattern || rhapsodyMemberPropertyName;
if( defaultDisplayNone ){
var evalType = rhapsodyMemberPropertyName? "rhapsodyMember": "userAgent";
var evalName = rhapsodyMemberPropertyName? rhapsodyMemberPropertyName: "userAgent";
var evalValue = rhapsodyMemberPropertyValue? rhapsodyMemberPropertyValue: userAgentPattern;
RhapsodyDynamicNav.evaluateAndToggleElements.push( {
elemId: listParentId,
evalType: evalType,
evalName: evalName,
evalValue: evalValue
} );
}
var menuChildren = aMenuItem.children;
var hasChildren = menuChildren.length > 0;
dynamicMenuHTML += '<li';
if( hasChildren || defaultDisplayNone ){
dynamicMenuHTML += ' id="' + listParentId + '"';
if( defaultDisplayNone ){
dynamicMenuHTML += ' style="display: none;"';
}
}
dynamicMenuHTML += '>' +
'<div class="navBarMenuLinkoff ' + RhapsodyDynamicNav.TOP_NAV_MENU_ITEM_CLASS_NAME + '">';
if( hasChildren ){
dynamicMenuHTML +=
'<a href="#" title="' + aMenuItem.title + '" onClick="RhapsodyDynamicNav.buildDropDown( { menuParent: \'' + listParentId + '\' } ); return false;">' +
aMenuItem.title +
'<\/a> ' +
'<a href="#" onClick="RhapsodyDynamicNav.buildDropDown( { menuParent: \'' + listParentId + '\' } ); return false;" class="topNavLinksArrow" style="text-decoration: none;" title="' + aMenuItem.title + '">' +
'&nbsp;&nbsp;&nbsp;' +
'<\/a>';
} else {
dynamicMenuHTML +=
'<a href="' + aMenuItem.url + '" title="' + aMenuItem.title + '"';
if( aMenuItem.imageurl && ( typeof aMenuItem.imageurl != 'undefined' ) ){
dynamicMenuHTML += ' class="topNavMenuHasImage' + aMenuItem.id + '"' +
' style="background-image: url(' + aMenuItem.imageurl + ');"';
}
dynamicMenuHTML += '>' +
aMenuItem.title +
'<\/a>';
}
dynamicMenuHTML +=
'<\/div>';
if( hasChildren ){
dynamicMenuHTML +=
'<ul class="totallyHidden displayNone topNavDropDown">';
for( var j=0; j < menuChildren.length; j++ ){
var aSubmenuItem = menuChildren[ j ];
dynamicMenuHTML +=
'<li>' +
'<div class="' + RhapsodyDynamicNav.TOP_NAV_SUB_MENU_ITEM_CLASS_NAME + '">' +
'<a href="' + aSubmenuItem.url + '">' +
aSubmenuItem.title +
'<\/a>' +
'<\/div>' +
'<\/li>';
}
dynamicMenuHTML += '<\/ul>';
}
dynamicMenuHTML +=
'<\/li>';
}
RhapsodyDynamicNav._getTopNavHolderElement().innerHTML = dynamicMenuHTML;
RhapsodyDynamicNav._handleClientLogic( RhapsodyDynamicNav.evaluateAndToggleElements );
RhapsodyDynamicNav.colorActiveMenu();
}
},
_handleClientLogic: function( ete ){
if( ete.length > 0 ){
var i=0;
while( i < ete.length ){
if( this._shouldToggleElement( ete[ i ] ) ){
document.getElementById( ete[ i ].elemId ).style.display = 'block';
}
i++;
}
} else { return false; }
},
_shouldToggleElement: function( eteObj ){
if( eteObj.evalType == "userAgent" ){
return this._evalUserAgent( eteObj.evalValue );
} else if( eteObj.evalType == "rhapsodyMember" ){
return this._evalRhapsodyMember( rhapsodyMember, eteObj );
}
},
_getUserAgent: function(){
return "" + navigator.userAgent;
},
_evalUserAgent: function( uaToMatch ){
var ua = this._getUserAgent();
var regex = new RegExp( uaToMatch );
return regex.test( ua );
},
_evalRhapsodyMember: function( rm, eteObj ){
return rm.getMemberAttribute( eteObj.evalName ).toString() === eteObj.evalValue + "";
},
_getDropdownMenuHTML: function( menuParent ){
var defaultMenuParent = document.getElementById( menuParent );
var defaultMenuParentChildren = defaultMenuParent.getElementsByTagName( 'UL' );
for( var i=0; i < defaultMenuParentChildren.length; i++ ){
var menuChild = defaultMenuParentChildren[ i ];
if( Element.hasClassName( menuChild, 'topNavDropDown' ) ){ return menuChild.innerHTML; }
} return null;
},
_getTopNavHolderElement: function(){
return document.getElementById( this.TOP_NAV_HOLDER_ELEMENT_ID );
},
destroyDialogBox: function(){
RhapsodyDynamicNav.ddDialogBoxInstance.destroy();
RhapsodyDynamicNav.ddDialogBoxInstance = null;
Event.unloadCache();
}
};
document.write('<div id="signinoutpreload" style="visibility:hidden; position:absolute;"><\/div>');
function signinoutswfpreload() {
var thediv = document.getElementById("signinoutpreload");
if( thediv ) {
try {
var flashVars = { "state":"signin", "pcode":"rn" };
var rhapSwfObject = RhapsodyPlayer.getRhapsodySwfObject( "signin", "signinoutpreload", "window", flashVars );
var theerror = rhapSwfObject.getEmbedStatus();
if( theerror ) { setTimeout("signinoutswfpreload()",100); }
else { setTimeout( function(){ document.getElementById('signinoutpreload').innerHTML = '&nbsp;'; }, 500 ); }
}
catch( e ) { }
}
else { setTimeout( function(){ signinoutswfpreload(); }, 100); }
}
signinoutswfpreload();
document.write('<div id="signinoutdebug" style="position:absolute;"><\/div>');
var inoutstart = (new Date()).valueOf();
function inoutdebugreset() { inoutstart = (new Date()).valueOf(); }
function inoutdebug(s) {
var timedelta = (new Date()).valueOf() - inoutstart;
// document.getElementById("signinoutdebug").innerHTML += timedelta + " -- " + s + "<br />";
}
var SignInOutDialogBox = {
signInOutDialog : null,
getMovie: function(){
return document.getElementById("popoutPlayer_signin");
},
showDialog: function( state ) {
if( SignInOutDialogBox.signInOutDialog ){ SignInOutDialogBox.hideDialog(); }
inoutdebug("showDialog");
var innerHTML = '&nbsp';
if( SignInOutDialogBox.signInOutDialog ) {
SignInOutDialogBox.signInOutDialog.loadContent( { htmlContent:innerHTML } );
}
else {
SignInOutDialogBox.signInOutDialog = null;
SignInOutDialogBox.signInOutDialog = new DialogBox(
{
spawnFrom: document.getElementById("topNavSignInOut"),
spawnFromOffset: [ -180, 0 ],
elementId: "signInOutDialogDiv",
elementClassName: "signInOutDialogClass",
width: '302px',
height: '385px',
htmlContent: innerHTML
}
);
SignInOutDialogBox.signInOutDialog.registerOuterClickListener( SignInOutDialogBox.outerClickHandler );
SignInOutDialogBox.signInOutDialog.show();
SignInOutDialogBox.signInOutDialog.toggleMeddlesomeElements();
}
SignInOutDialogBox.tryFlashEmbed(state);
},
updateHeight: function( h ){
if(document.getElementById('signInOutDialogDiv') !== null && document.getElementById('signInOutDialogDiv') != 'undefined'){
document.getElementById('signInOutDialogDiv').style.height = h + 'px';
}
},
slideUp: function(){
if(document.getElementById('signInOutDialogDiv') !== null && document.getElementById('signInOutDialogDiv') != 'undefined'){
document.getElementById('signInOutDialogDiv').style.height='0px';
document.getElementById('signInOutDialogDiv').style.visibility='hidden';
}
},
tryFlashEmbed: function( state ) {
inoutdebug("tryFlashEmbed...");
var theDiv = document.getElementById("signInOutDialogDiv");
if( theDiv ) {
var flashVars = { "state":state, "pcode":RhapsodyPlayer.getPcode() };
inoutdebug("embedding swf...");
var isFF = navigator.userAgent.indexOf("Firefox")>=0;
var rhapSwfObject = RhapsodyPlayer.getRhapsodySwfObject( "signin", "signInOutDialogDiv", (isFF?"window":"transparent"), flashVars );
var embedResult = rhapSwfObject.getEmbedStatus();
inoutdebug("...done embedding swf.");
if( embedResult > 0 ) {
this.signInOutDialog.setMask( true );
this.signInOutDialog.setWidth( 350 );
this.signInOutDialog.setHeight( 'auto' );
this.signInOutDialog.loadContent(
{
htmlContent:
'<div class="signInOutDialogDivNoFlash">' +
'A new version of Flash is required to use this feature.<br \/>' +
'<a href="http://www.adobe.com/support/flashplayer/downloads.html" target="_blank" onclick="SignInOutDialogBox.hideDialog();">Download Flash from Macromedia<\/a>.' +
'<\/div>'
}
);
this.signInOutDialog.centerInPage();
RhapsodyUtility.addEvent( window, 'scroll', function(e){ this.signInOutDialog.centerInPage(); } );
RhapsodyUtility.addEvent( window, 'resize', function(e){ this.signInOutDialog.centerInPage(); } );
return;
}
}
else {
setTimeout( function(){ SignInOutDialogBox.tryFlashEmbed('"+state+"'); }, 50);
}
},
onLoginSWFReady: function(){
if( RhapsodyUtility.Client.isIE6() ){ SignInOutDialogBox.getMovie().unfocusAll(); }
else { SignInOutDialogBox.getMovie().focus(); }
},
outerClickHandler: function(){
SignInOutDialogBox.hideDialog();
},
hideDialog: function(){
if( SignInOutDialogBox.signInOutDialog ){
SignInOutDialogBox.signInOutDialog.setMask();
SignInOutDialogBox.signInOutDialog.toggleMeddlesomeElements( true );
SignInOutDialogBox.signInOutDialog.hide();
SignInOutDialogBox.signInOutDialog.destroy();
SignInOutDialogBox.signInOutDialog = null;
Event.unloadCache();
}
}
};
var SampleModeUpsell = {
overlayWidth: 375,
overlayHeight: 340,
modalDialogBoxInstance: null,
_dialogBoxOverrides: null,
setDialogBoxOverrides: function( dbOverrideObj ){
this._dialogBoxOverrides = dbOverrideObj;
},
init: function(overlayHtmlContent){
if( overlayHtmlContent != null && overlayHtmlContent != 'undefined' && overlayHtmlContent != '' ){
var dbWidth = ( this._dialogBoxOverrides && this._dialogBoxOverrides.dbWidth )? this._dialogBoxOverrides.dbWidth: this.overlayWidth;
var dbClassName = ( this._dialogBoxOverrides && this._dialogBoxOverrides.dbClassName )? this._dialogBoxOverrides.dbClassName: null;
SampleModeUpsell.modalDialogBoxInstance = new DialogBox(
{
width: this.overlayWidth + 'px',
height: this.overlayHeight + 'px',
maskOpacityPercent: 60,
holdingElementBgColor: '#363636',
zIndex: '999999999',
maskBgColor: '#000',
maskZIndex: '10000',
htmlContent: overlayHtmlContent,
elementClassName: dbClassName
}
);
SampleModeUpsell.modalDialogBoxInstance.centerInPage( .90 );
SampleModeUpsell.modalDialogBoxInstance.toggleMeddlesomeElements();
SampleModeUpsell.modalDialogBoxInstance.setMask( true );
SampleModeUpsell.modalDialogBoxInstance.setShadow( true );
Event.observe( window, 'scroll', function(e){
SampleModeUpsell.modalDialogBoxInstance.centerInPage( .90 );
SampleModeUpsell.modalDialogBoxInstance.setMask( true );
} );
Event.observe( window, 'resize', function(e){
SampleModeUpsell.modalDialogBoxInstance.centerInPage( .90 );
SampleModeUpsell.modalDialogBoxInstance.setMask( true );
} );
}
},
destroy: function(){
Event.unloadCache();
SampleModeUpsell.modalDialogBoxInstance.toggleMeddlesomeElements();
SampleModeUpsell.modalDialogBoxInstance.destroy();
SampleModeUpsell.modalDialogBoxInstance = null;
},
resumePlayback: function(answer){
var app = RhapsodyPlayer.getFlashApp("embedded");
if(app != null && app != 'undefined'){
if(answer)
app.doPlay();
else
app.doStop();
}
},
closeAndResume: function(){
SampleModeUpsell.destroy();
SampleModeUpsell.resumePlayback(true);
},
closeAndStop: function(){
SampleModeUpsell.destroy();
SampleModeUpsell.resumePlayback(false);
}
}
function onSampleModeUpsell(){
var closeXSpan = '<div class="shareOverlayClose"><a href="#" onclick="SampleModeUpsell.closeAndStop(); return false;">Close <span>X</span></a></div>';
var overlayContent = closeXSpan;
overlayContent += '<div class="sampleModeInnards"><p class="sampleModeInnardsTitle">Join Now</p><p class="sampleModeInnardsHeading">You&#39;re hearing <span style="color:#ffcc33;">30-second samples</span>.</p><p class="sampleModeInnardsBodyText">To get unlimited access to full-length tracks, join Rhapsody now.</p><p class="sampleModeInnardsOfferText">Listen all you want for $12.99&#47;month</p><div class="sampleModeInnardsButtons"><a href="#" onclick="SampleModeUpsell.closeAndResume(); return false;"><img src="' + staticPath + '/images/buttons/btn_keep_playing_samples.gif"/></a><a onclick="SampleModeUpsell.closeAndStop(); return false;" href="http://learn.rhapsody.com/plans/unlimited?src=rcom_efp&pcode=rn&cpath=rcom_efp&ocode=rn"><img src="' + staticPath + '/images/buttons/btn_sub_now.gif"/></a></div><p><a href="http://learn.rhapsody.com/?src=rcom_efp_lm&pcode=rn&cpath=rcom_efp">Learn more</a></p><div align="center"><a href="http://www.rhapsody.com/-privacy_policy">Privacy Policy</a> | <a href="http://www.rhapsody.com/-terms_of_use">Terms and Conditions</a></div></div>';
SampleModeUpsell.init(overlayContent);
}
//setTimeout("onSampleModeUpsell();",5000);
function TabbedDisplay( holderId ){
this.init( holderId );
}
TabbedDisplay.prototype = {
tabNamesToIndicesMapping: new Array(),
defaultTabIndex: null,
defaultUrlToLoad: null,
defaultPersonalPassedProp: null,
holderDiv: {},
tabScreenObjArray: null,
init: function( holderId ){
this.holderDiv = document.getElementById( holderId );
this.tabScreenObjArray = [];
this._setInitTabObjArray();
},
registerName: function( tabIndex, name ) {
// when we look it up later, it'll be with document.location.hash, which includes the pound
this.tabNamesToIndicesMapping["#"+name] = tabIndex;
},
setDefaultBehavior: function( tabIndex, urlToLoad, personalPassedProp ){
this.defaultTabIndex = tabIndex;
this.defaultUrlToLoad = urlToLoad;
this.defaultPersonalPassedProp = personalPassedProp;
},
startUp: function() {
var hash = document.location.hash;
if( hash && this.tabNamesToIndicesMapping[hash] ) {
this.selectTab(this.tabNamesToIndicesMapping[hash]);
}
else {
this.selectTab( this.defaultTabIndex, this.defaultUrlToLoad, this.defaultPersonalPassedProp );
}
},
selectTab: function( tabIndex, urlToLoad, personalPassedProp ){
var theClassName = this.tabScreenObjArray[ tabIndex ].tab.className;
for( var i = 0; i < this.tabScreenObjArray.length; i++ ){
if( i != tabIndex ){
var theOtherClassName = this.tabScreenObjArray[ i ].tab.className;
if( !theOtherClassName.match( ' tabbedOptionsTabOff' ) ){
this.tabScreenObjArray[ i ].screen.style.display = 'none';
this.tabScreenObjArray[ i ].tab.className = theOtherClassName + " tabbedOptionsTabOff";
}
}
}
this.tabScreenObjArray[ tabIndex ].screen.style.display = 'block';
this.tabScreenObjArray[ tabIndex ].screen.style.visibility = 'visible';
theClassName = theClassName.replace( ' tabbedOptionsTabOff', '' );
this.tabScreenObjArray[ tabIndex ].tab.className = theClassName;
if( urlToLoad ){
if( personalPassedProp ) {
var mPersonalVal = "0";
try{
if( rhapsodyMember.isLoggedIn ){
mPersonalVal = rhapsodyMember.getMemberAttribute( personalPassedProp );
}
}
catch( e ) { mPersonalVal = "0"; }
urlToLoad += (urlToLoad.indexOf("?")==-1?"?":"&") + personalPassedProp + "=" + mPersonalVal;
}
RhapsodyUtility.Ajax.includeHtml( { ajaxUrl: urlToLoad, target: this.tabScreenObjArray[ tabIndex ].screen, useLoadMessage: true } );
}
return false;
},
_setInitTabObjArray: function(){
var tabbedDisplayTabHolder = RhapsodyUtility.getChildrenByClassName( this.holderDiv, 'tabbedOptionsTabs' )[0];
var tabbedDisplayMainHolder = RhapsodyUtility.getChildrenByClassName( this.holderDiv, 'tabbedOptionsMain' )[0];
var theTabbedDisplayTabs = RhapsodyUtility.getChildrenByClassName( tabbedDisplayTabHolder, 'tabbedOptionsTab' );
var theTabbedDisplayMains = RhapsodyUtility.getChildrenByTagName( tabbedDisplayMainHolder, 'DIV' );
if( theTabbedDisplayTabs !== null && theTabbedDisplayMains !== null ){
for( var i=0; i<theTabbedDisplayTabs.length; i++ ){
this.tabScreenObjArray.push( { tab: theTabbedDisplayTabs[ i ], screen: theTabbedDisplayMains[ i ] } );
}
}
}
};
/***** Base Class for a Dialog Box Object ******/
function DialogBox( argObj ){
this.init( argObj );
}
DialogBox.prototype = {
elementId: null,
elementClassName: null,
elementType: "DIV",
spawnFrom: null,
spawnFromOffset: [ 0, 0 ],
spawnFromScrollingParent: null,
topPos: "0px",
leftPos: "0px",
width: null,
height: null,
stylePosition: "absolute",
srcUrl: null,
htmlContent: null,
zIndex: "1000", /* DialogBox z-index*/
shadowZIndex: "900",
maskZIndex: "500",
styleOverflow: "hidden",
outerClickHandler: null,
maskOpacityPercent: 70,
holdingElementBgColor: null,
maskBgColor: '#999',
_holdingElement: null,
_maskElement: null,
_shadowElement: null,
_shadowOffset: 3,
_loiteringTimeout: null,
init: function( argObj ){
if( argObj ){
if( typeof argObj.elementId != 'undefined' ){ this.elementId = argObj.elementId; }
if( typeof argObj.elementClassName != 'undefined' ){ this.elementClassName = argObj.elementClassName; }
if( typeof argObj.elementType != 'undefined' ){ this.elementType = argObj.elementType; }
if( typeof argObj.spawnFrom != 'undefined' ){ this.spawnFrom = ( typeof argObj.spawnFrom == 'string' )? document.getElementById( argObj.spawnFrom ): argObj.spawnFrom; }
if( typeof argObj.spawnFromOffset != 'undefined' ){ this.spawnFromOffset = argObj.spawnFromOffset; }
if( typeof argObj.spawnFromScrollingParent != 'undefined' ){ this.spawnFromScrollingParent = ( typeof argObj.spawnFromScrollingParent == 'string' )? document.getElementById( argObj.spawnFromScrollingParent ): argObj.spawnFromScrollingParent; }
if( typeof argObj.topPos != 'undefined' ){ this.topPos = argObj.topPos; }
if( typeof argObj.leftPos != 'undefined' ){ this.leftPos = argObj.leftPos; }
if( typeof argObj.width != 'undefined' ){ this.width = argObj.width; }
if( typeof argObj.height != 'undefined' ){ this.height = argObj.height; }
if( typeof argObj.srcUrl != 'undefined' ){ this.srcUrl = argObj.srcUrl; }
if( typeof argObj.htmlContent != 'undefined' ){ this.htmlContent = argObj.htmlContent; }
if( typeof argObj.maskOpacityPercent != 'undefined' ){ this.maskOpacityPercent = argObj.maskOpacityPercent; }
if( typeof argObj.holdingElementBgColor != 'undefined' ){ this.holdingElementBgColor = argObj.holdingElementBgColor; }
if( typeof argObj.maskBgColor != 'undefined' ){ this.maskBgColor = argObj.maskBgColor; }
if( typeof argObj.zIndex != 'undefined' ){ this.zIndex = argObj.zIndex; }
if( typeof argObj.maskZIndex != 'undefined' ){ this.maskZIndex = argObj.maskZIndex; }
if( typeof argObj.shadowZIndex != 'undefined' ){ this.shadowZIndex = argObj.shadowZIndex; }
}
this._buildHoldingElement();
var theThis = this;
this.listenForOuterClicks = function( e ) {
if( !theThis.outerClickHandler || ( typeof theThis.outerClickHandler == 'undefined' ) ){ return; } // Shouldn't happen, but what the heck...
if( theThis._isMouseOutside( e ) ){
if( theThis.loiteringTimeout ){ clearTimeout( theThis.loiteringTimeout ); }
theThis.outerClickHandler();
}
};
this.listenForOuterLoitering = function() {
if( !theThis.outerLoiteringHandler || ( typeof theThis.outerLoiteringHandler == 'undefined' ) ){ return; }
var doTheCheckAndClose = function( e ){
if( theThis._isMouseOutside( e ) ){
theThis.outerLoiteringHandler();
clearTimeout( theThis.loiteringTimeout );
}
else{ return; }
};
theThis.loiteringTimeout = setTimeout( function(){
RhapsodyUtility.addEvent( document, 'mousemove', doTheCheckAndClose );
}, 4000 );
};
},
_isMouseOutside: function( e ){
var isOutside = false;
if( typeof Position.within != 'undefined' ){
if( !Position.within( this.getHoldingElement(), Event.pointerX( e ), Event.pointerY( e ) ) ){ isOutside = true; }
} else {
if( !theThis._localWithin( Event.pointerX( e ), Event.pointerY( e ) ) ){ isOutside = true; }
}
return isOutside;
},
registerOuterClickListener: function( theHandler ){
this.outerClickHandler = theHandler;
Event.observe( document.body, 'mousedown', this.listenForOuterClicks );
},
registerOuterLoiteringListener: function( theHandler ){
this.outerLoiteringHandler = theHandler;
Event.observe( this.spawnFrom, 'mouseout', this.listenForOuterLoitering );
},
_buildHoldingElement: function(){
// TODO - see if we really are detecting whether the body exists
// if( document.body != null && ( typeof document.body != 'undefined' ) && RhapsodyDom.bodyLoaded ){
this._holdingElement = document.createElement( this.elementType );
document.getElementById("DialogManagerInitialHoldingElement").appendChild( this.getHoldingElement() );
if( this.spawnFrom ){
var positions =[ 0, 0 ];
if( Position.cumulativeOffset ){
positions = Position.cumulativeOffset( this.spawnFrom );
} else { // had to move this locally from prototype.js b/c "Position" is randomly undefined
var valueT = 0, valueL = 0;
var element = this.spawnFrom;
do{
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while( element );
positions = [ valueL, valueT ];
}
if( this.spawnFromScrollingParent ){ positions = this._adjustSpawnFromForScrollingParent( positions ); }
this.leftPos = ( positions[ 0 ] + this.spawnFromOffset[ 0 ] ) + 'px';
this.topPos = ( positions[ 1 ] + this.spawnFromOffset[ 1 ] ) + 'px';
}
var he = this.getHoldingElement();
he.style.display = 'none';
he.style.top = this.topPos;
he.style.left = this.leftPos;
if( this.width ){ he.style.width = this.width; }
if( this.height ){ he.style.height = this.height; }
he.style.position = this.stylePosition;
he.style.zIndex = this.zIndex;
he.style.overflow = this.styleOverflow;
if( this.elementId ){ he.setAttribute( "id", this.elementId) ; }
if( this.elementClassName ){ he.className = this.elementClassName; }
if( this.holdingElementBgColor ){ he.style.backgroundColor = this.holdingElementBgColor; }
this.loadContent();
// } else this.destroy();
},
loadContent: function( lcObj ){
if( lcObj ){
if( lcObj.srcUrl ){ this.srcUrl = lcObj.srcUrl; }
if( lcObj.htmlContent ){ this.htmlContent = lcObj.htmlContent; }
}
if( this.srcUrl ){
RhapsodyUtility.Ajax.includeHtml( {
ajaxUrl: this.srcUrl,
target: this.getHoldingElement(),
useLoadMessage: true,
forceReload: true
} );
} else if( this.htmlContent ){ this.getHoldingElement().innerHTML = this.htmlContent; }
},
getHoldingElement: function(){
return this._holdingElement;
},
hide: function(){
this.getHoldingElement().style.display = 'none';
},
show: function( disableVisible ){
this.getHoldingElement().style.display = 'block';
if( !disableVisible ){ this.setVisibility( 'visible' ); }
},
setVisibility: function( visibility ){
this.getHoldingElement().style.visibility = visibility;
},
giveLayout: function(){
this.setVisibility( 'hidden' );
this.show( true );
},
getLeft: function(){
return parseInt( this.leftPos, 10 );
},
getTop: function(){
return parseInt( this.topPos, 10 );
},
setLeft: function( l ){
this.leftPos = l + "px";
this.getHoldingElement().style.left = this.leftPos;
},
setTop: function( t ){
this.topPos = t + "px";
this.getHoldingElement().style.top = this.topPos;
},
setWidth: function( w ){
this.width = ( typeof w == 'string' ) ? w : w + 'px';
this.getHoldingElement().style.width = this.width;
},
setHeight: function( h ){
this.height = ( typeof h == 'string' ) ? h : h + 'px';
this.getHoldingElement().style.height = this.height;
},
setSize: function( w, h ){
this.setWidth( w );
this.setHeight( h );
},
centerInPage: function( hm, wm ){
var hadShadow = false;
var heightMultiplier = ( ( typeof hm != 'undefined' ) && hm !== null )? hm: 0.75;
var widthMultiplier = ( ( typeof wm != 'undefined' ) && wm !== null )? wm: 1;
this.giveLayout();
if( this.getShadow() ){
hadShadow = true;
this.setShadow();
}
var offsetFromTop = Math.max( document.body.scrollTop, document.documentElement.scrollTop );
if( window.pageYOffset ){ offsetFromTop = Math.max( offsetFromTop, window.pageYOffset ); }
var docWidth = document.documentElement.clientWidth;
var docHeight = document.documentElement.clientHeight;
if( ( navigator.appVersion.toLowerCase().indexOf( 'safari' ) != -1 ) ){ docHeight = self.screen.availHeight * 0.75; }
var elementHeight = Element.getHeight( this.getHoldingElement() );
var newLeft = Math.round( ( docWidth * widthMultiplier ) - parseInt( this.width ) ) / 2;
var newTop = ( Math.round( ( docHeight * heightMultiplier ) - elementHeight ) / 2 ) + offsetFromTop;
if( ( this.getLeft() != newLeft ) || ( this.getTop() != newTop ) ){
if( newTop < offsetFromTop ){ newTop = offsetFromTop; }
this.setLeft( newLeft );
this.setTop( newTop );
}
this.show();
if( hadShadow ){ this.setShadow( true ); }
},
getMask: function(){
return this._maskElement;
},
setMask: function( maskOn ){
if( document.getElementById("DialogManagerInitialHoldingElement") && this.getMask() ){
this.getMask().style.display = 'none';
document.getElementById("DialogManagerInitialHoldingElement").removeChild( this.getMask() );
this._maskElement = null;
}
if( maskOn ){
var maskOpacityPercent = this.maskOpacityPercent;
var maskElement = document.createElement( "DIV" );
var maskHeight = Math.max( document.documentElement.clientHeight, document.body.clientHeight );
var maskWidth = Math.max( Math.max( document.documentElement.clientWidth, document.body.clientWidth ), document.documentElement.scrollWidth );
var mes = maskElement.style;
mes.position = 'absolute';
mes.top = '0px';
mes.left = '0px';
mes.width = maskWidth + 'px';
mes.height = maskHeight + 'px';
if( typeof mes.opacity != 'undefined' ){
mes.opacity = maskOpacityPercent / 100;
}
if( typeof mes.filter != 'undefined' ){
mes.filter = "alpha(opacity=" + maskOpacityPercent + ")";
}
mes.zIndex = this.maskZIndex;
mes.backgroundColor = this.maskBgColor;
document.getElementById( "DialogManagerInitialHoldingElement" ).appendChild( maskElement );
Event.observe( maskElement, 'mousedown', function(){ return false; }, true );
this._maskElement = maskElement;
}
},
toggleMeddlesomeElements: function( showOnly ){
RhapsodyUtility.toggleMeddlesomeElements( showOnly );
},
getShadow: function(){
return this._shadowElement;
},
setShadow: function( shadowOn ){
if( this.getShadow() ){
this.getShadow().style.display = 'none';
document.getElementById( 'DialogManagerInitialHoldingElement' ).removeChild( this.getShadow() );
this._shadowElement = null;
}
if( shadowOn ){
var parentElementHeight = Element.getHeight( this.getHoldingElement() );
var shadowOpacityPercent = 20;
var shadowElement = document.createElement( "DIV" );
var ses = shadowElement.style;
ses.position = 'absolute';
ses.top = ( parseInt( this.topPos, 10 ) + this._shadowOffset ) + 'px';
ses.left = ( parseInt( this.leftPos, 10 ) + this._shadowOffset ) + 2 + 'px';
ses.width = this.width;
ses.height = parentElementHeight + 'px';
if( typeof ses.opacity != 'undefined' ){
ses.opacity = shadowOpacityPercent / 100;
}
if( typeof ses.filter != 'undefined' ){
ses.filter = "alpha(opacity=" + shadowOpacityPercent + ")";
}
ses.zIndex = this.shadowZIndex;
ses.backgroundColor = 'black';
document.getElementById("DialogManagerInitialHoldingElement").appendChild( shadowElement );
this._shadowElement = shadowElement;
}
},
adjustForBleed: function(argObj){
this.giveLayout();
var headerHeight = 250; // let's not have the menu bleed over the header
var top = parseInt( this.getHoldingElement().style.top, 10 );
var dialogBoxHeight = Element.getHeight( this.getHoldingElement() );
var visibleHeight = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var scrolledFromTop = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var newTop = top;
if( ( top + dialogBoxHeight ) > ( visibleHeight + scrolledFromTop ) ){
newTop = top - dialogBoxHeight;
if( argObj && argObj.alignBottomOnFlip && this.spawnFrom ){ newTop += Element.getHeight( this.spawnFrom ); }
if( newTop < headerHeight ){ newTop = headerHeight; }
else if( newTop < scrolledFromTop ){
newTop = newTop + ( dialogBoxHeight / 2 );
}
}
this.setTop( newTop );
},
_adjustSpawnFromForScrollingParent: function( pArr ){
var scrollingParentOffsetTop = this.spawnFromScrollingParent.scrollTop;
var scrollingParentOffsetLeft = this.spawnFromScrollingParent.scrollLeft;
var adjustedLeft = ( ( scrollingParentOffsetLeft > 0 ) && ( scrollingParentOffsetLeft ) && ( scrollingParentOffsetLeft != 'undefined' ) )? pArr[ 0 ] - scrollingParentOffsetLeft: pArr[ 0 ];
var adjustedTop = ( ( scrollingParentOffsetTop > 0 ) && ( scrollingParentOffsetTop ) && ( scrollingParentOffsetTop != 'undefined' ) )? pArr[ 1 ] - scrollingParentOffsetTop: pArr[ 1 ];
return [ adjustedLeft, adjustedTop ];
},
removeHoldingElement: function(){
try {
this.hide();
} catch(e) {}
if( document.getElementById("DialogManagerInitialHoldingElement") && this.getHoldingElement() ){
document.getElementById("DialogManagerInitialHoldingElement").removeChild( this.getHoldingElement() );
}
},
_localWithin: function( clickX, clickY ){
/* had to borrow from prototype.js b/c prototype.js Position object was
randomly 'undefined', bug in prototype.js? */
var element = this.getHoldingElement();
var offset, valueT = 0, valueL = 0;
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
do {
var elementToRecurse = element;
valueT += elementToRecurse.offsetTop || 0;
valueL += elementToRecurse.offsetLeft || 0;
if (elementToRecurse.offsetParent == document.body)
if (Element.getStyle(elementToRecurse, 'position') == 'absolute') break;
elementToRecurse = elementToRecurse.offsetParent;
} while (elementToRecurse);
} else {
var elementToRecurse = element;
do {
valueT += elementToRecurse.offsetTop || 0;
valueL += elementToRecurse.offsetLeft || 0;
elementToRecurse = elementToRecurse.offsetParent;
} while (elementToRecurse);
}
offset = [ valueL, valueT ];
return ( clickY >= offset[1] &&
clickY < offset[1] + element.offsetHeight &&
clickX >= offset[0] &&
clickX < offset[0] + element.offsetWidth );
},
destroy: function() {
this.removeHoldingElement();
if( this.getMask() ){ this.setMask( false ); }
if( this.getShadow() ){ this.setShadow( false ); }
this.toggleMeddlesomeElements( true );
}
};
// This is used instead of document.body to "attach" dialog-box elements to (see 218455)
document.write( '<div id="DialogManagerInitialHoldingElement" style="position: absolute; height: 0; width: 0; z-index: 9999999; top: 0; left: 0;"><\/div>');
/***** Static Class for managing the Dialog Box Objects for playlists ******/
var PlaylistDialogBoxManager = {
plDialogBoxClassName: "playlistDialogBox",
plDialogBoxInstance: null,
plMenuItemClassName: "playlistMenuItem",
plSubHeaderClassName: "playerSubHeader",
plAddToPlayerQueueText: "Add to Player Queue",
plAddToLibraryText: "Add to Library",
plAddToNewPlaylistText: "[ New Playlist ]",
plAddToNewPlaylistDialogElement: null,
plListOfPlaylistsHolderClassName: "playListsDialogBoxListOfPlaylists",
plListOfPlaylistsHolder: null,
plCurrentListOfPlaylists: null,
plAddToPlaylistText: "Add to Playlist:",
plSignInPromptClassName: "playlistSignInPrompt",
playlistMgr: {},
activePlaylist: null,
activePlaylistName: null,
activeRcid: null,
activeNewPlaylistTitle: null,
activeContactingText: null,
closeDialogBoxCallback: null,
libraryMgr: {},
libraryValidContentTypes: [ 'alb', 'tra' ],
accountType: null,
disableAddToLibrary: false,
_meddlesomesToggledOff: false,
_lastTransaction: null,
_lastTransactionSuccess: false,
_lastTransactionStrings: [ 'PLAYLIST_MANAGEMENT_ADD', 'PLAYLIST_MANAGEMENT_CREATE', 'LIBRARY_MANAGEMENT' ],
getNumberOfRecentPlaylistsToShow: function(){
var recentToShow = 1;
return recentToShow;
},
getShowRecentPlaylistsIf: function(){
return 10;
},
showDialogBox: function( mediaObj, argObj, callback ){
var playlistArgObj = {};
var doAdjustForBleed = false;
playlistArgObj.elementClassName = this.plDialogBoxClassName;
playlistArgObj.height = 'auto';
if( argObj.spawnFrom ){
argObj.spawnFromOffset = [ 5, 5 ];
doAdjustForBleed = true;
}
for( var i in argObj ){
if( argObj.hasOwnProperty( i ) ) {
playlistArgObj[ i ] = argObj[ i ];
}
}
this.closeDialogBoxCallback = callback;
this.activeRcid = mediaObj.rcid;
var isTrackRegexp = this.activeRcid.match( /^tra\.[0-9]+$/ );
if( !isTrackRegexp ) {
this.activeNewPlaylistTitle = mediaObj.title;
}
if( this.plDialogBoxInstance ){ this.destroy(); }
if( playlistArgObj.accountType ){ this.accountType = playlistArgObj.accountType; }
if( playlistArgObj.disableAddToLibrary ){ this.disableAddToLibrary = playlistArgObj.disableAddToLibrary; }
this.plDialogBoxInstance = new DialogBox( playlistArgObj );
try{
if( this.plDialogBoxInstance ){
this._initContent();
if( doAdjustForBleed ){ this.plDialogBoxInstance.adjustForBleed(); }
this.plDialogBoxInstance.getHoldingElement().id =
this.plDialogBoxClassName +
this.plDialogBoxInstance.topPos +
this.plDialogBoxInstance.leftPos;
RhapsodyUtility.doFadein( this.plDialogBoxInstance.getHoldingElement().id, 100, 5 );
this.plDialogBoxInstance.show();
setTimeout( function(){ PlaylistDialogBoxManager.setShadow( true ); }, 100 );
return this.plDialogBoxInstance;
}
} catch(e){}
},
loadContent: function( lcObj ){
this.plDialogBoxInstance.loadContent( lcObj );
},
destroy: function(){
var savedTitle = this.activeNewPlaylistTitle;
var success = this._lastTransactionSuccess;
var pdbm = PlaylistDialogBoxManager;
var pdbi = pdbm.plDialogBoxInstance;
pdbm.toggleMeddlesomeElements( true );
Event.unloadCache();
if( pdbi.getMask() ){ pdbi.setMask(); }
if( pdbi.getShadow() ){ pdbi.setShadow(); }
pdbi.removeHoldingElement();
pdbm.plDialogBoxInstance = null;
pdbm.playlistMgr = null;
pdbm.libraryMgr = null;
pdbm.activeNewPlaylistTitle = null;
this.closeDialogBoxCallback(success, savedTitle);
},
isLibraryValidContentType: function( rcid ){
var rcidToCheck = rcid? rcid.toLowerCase(): this.activeRcid.toLowerCase();
for( var i=0; i < this.libraryValidContentTypes.length; i++ ){
if( rcidToCheck.indexOf( this.libraryValidContentTypes[ i ] ) != -1 ){ return true; }
} return false;
},
insertIntoPlaylist: function( id, rcid, idx ){
this._setActiveContactingText( 'Adding' );
this._lastTransaction = this._lastTransactionStrings[ 0 ];
this._lastTransactionSuccess = false;
this._onContacting();
this.playlistMgr.insertIntoPlaylist( id, rcid, idx, this._destroyResponder );
},
insertIntoLibrary: function(){
PlaylistDialogBoxManager._setActiveContactingText( 'Adding' );
PlaylistDialogBoxManager._lastTransaction = PlaylistDialogBoxManager._lastTransactionStrings[ 2 ];
PlaylistDialogBoxManager._lastTransactionSuccess = false;
PlaylistDialogBoxManager._onContacting();
PlaylistDialogBoxManager.libraryMgr.add( PlaylistDialogBoxManager.activeRcid, PlaylistDialogBoxManager._destroyResponder );
},
processAddToNewPlaylistOverwrite: function(){
this._lastTransaction = this._lastTransactionStrings[ 1 ];
this._lastTransactionSuccess = false;
this._onContacting();
this.playlistMgr.setExistingByName( this.activeNewPlaylistTitle, this.activeRcid, this._destroyResponder );
},
processAddToNewPlaylist: function( formElement ){
var lengthCap = 80;
var theInput = formElement.getElementsByTagName( 'INPUT' )[ 0 ];
var submittedPlaylistTitle = theInput.value;
var titleChanged = (this.activeNewPlaylistTitle != submittedPlaylistTitle);
this.activeNewPlaylistTitle = submittedPlaylistTitle;
if( !submittedPlaylistTitle || submittedPlaylistTitle === '' || submittedPlaylistTitle.charAt( 0 ) === ' ' || submittedPlaylistTitle.length < 0 ){
alert( 'Please enter a name for your new playlist.' );
theInput.focus();
} else if ( submittedPlaylistTitle.length > lengthCap ){
alert( 'Playlist names must not exceed ' + lengthCap + ' characters.' );
} else {
formElement.innerHTML = RhapsodyUtility.Ajax.getSpinnerHtml( 'Creating Playlist' );
this._lastTransaction = this._lastTransactionStrings[ 1 ];
this._lastTransactionSuccess = false;
this._onContacting();
if (titleChanged)
this.playlistMgr.setPlaylist( submittedPlaylistTitle, this.activeRcid, this._destroyResponder );
else
this.playlistMgr.setExistingByName( submittedPlaylistTitle, this.activeRcid, this._destroyResponder );
}
},
renderPlaylists: function( data ){
if( data.hasError ){
PlaylistDialogBoxManager._onError( data, 'PLAYLIST_ERROR' );
} else {
this.plCurrentListOfPlaylists = data;
/*
the Ajax.Responders.dispatch method is tripping up on
'this.' references to this object. Using 'PlaylistDialogBoxManager.'
seems to work however
*/
PlaylistDialogBoxManager._populateListOfPlaylists( data );
}
},
_initContent: function(){
this.activeContactingText = 'Loading';
this.playlistMgr = new PlaylistMgr();
this.playlistMgr.setSort( 2 );
this.playlistMgr.setMwidth( 20 );
this.libraryMgr = new LibraryManager();
try {
if( !RhapsodyPlayer.useEmbeddedPlayer() || RhapsodyEmbeddedPlayerManager.isSliverMode ){
this._showAddToPlayerQueue();
}
} catch( e ){ }
try{
var canUseMenu = ( ( typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && rhapsodyMember.isRadioPremiumUser );
if( !canUseMenu ){
if( !RhapsodyPlayer.useEmbeddedPlayer() || RhapsodyEmbeddedPlayerManager.isSliverMode ){
this._showDividerElement();
}
this._showSignInPrompt();
}
else {
if( this.isLibraryValidContentType() && !this.disableAddToLibrary ){
this._buildAddToLibrary();
}
this._showDividerElement();
this._buildListOfPlaylistsHolder();
this._onContacting();
this.playlistMgr.getPlaylists( 0, this.renderPlaylists );
}
} catch( f ){
this._showDividerElement();
this._showSignInPrompt();
}
this.plDialogBoxInstance.registerOuterClickListener( this.destroy );
},
_onContacting: function( message ){
var putSpinnerIn = PlaylistDialogBoxManager.plListOfPlaylistsHolder;
if( PlaylistDialogBoxManager.activeContactingText == 'Adding' ){
putSpinnerIn = PlaylistDialogBoxManager.plDialogBoxInstance.getHoldingElement();
PlaylistDialogBoxManager.setShadow();
}
putSpinnerIn.innerHTML = RhapsodyUtility.Ajax.getSpinnerHtml( PlaylistDialogBoxManager.activeContactingText );
if( PlaylistDialogBoxManager.activeContactingText == 'Adding' ){
PlaylistDialogBoxManager.setShadow( true );
}
},
_onError: function( errorObj, condition ){
var errorCode = -4;
var displayInPlace = ( condition && condition == 'PLAYLIST_ERROR' );
try{
errorCode = errorObj.exception.code;
} catch( e ){}
var isLibraryError = PlaylistDialogBoxManager._lastTransaction == PlaylistDialogBoxManager._lastTransactionStrings[ 2 ];
var errorMessages = {
code1: {
getMessage: function(){
var msg = "There is an error in this data and tracks cannot be added. Click 'Cancel' to try again.";
return msg;
}
},
code2: {
getMessage: function(){
var msg = isLibraryError
? "There is an error in this data and tracks cannot be added. Click 'Cancel' to try again."
: "This playlist title is already in use.";
return msg;
}
},
code3: {
getMessage: function(){
var msg = isLibraryError
? "There is an error in this data and tracks cannot be deleted. Click 'Cancel' to try again."
: "There is an error in this data and tracks cannot be added. Click 'Cancel' to try again.";
return msg;
}
},
code4: {
getMessage: function(){
var msg = "The Rhapsody servers may be busy or your internet connection may have been interrupted. Please click 'Cancel' and try again.";
return msg;
}
}
};
var errorMsgObj = errorMessages[ 'code' + Math.abs( errorCode ) ];
var errorHolderElement = document.createElement( "DIV" );
if(Math.abs(errorCode) == 2 && !isLibraryError)
{
// Handle error by showing replace dialog
var pdbm = PlaylistDialogBoxManager;
var pdbmi = pdbm.plDialogBoxInstance;
var pdbmHe = pdbmi.getHoldingElement();
pdbmi.hide();
pdbmi.setSize( 374, 158 );
pdbmi.centerInPage();
pdbmi.setMask( true );
pdbmi.setShadow();
Event.stopObserving( document.body, 'mousedown', pdbmi.listenForOuterClicks );
pdbmi.show();
RhapsodyUtility.addEvent( window, 'scroll', function(e){ pdbmi.centerInPage(); });
pdbm.toggleMeddlesomeElements();
pdbm._prepCenteredHoldingElementStyles();
pdbmHe.innerHTML = "";
pdbmHe.appendChild( pdbm.plAddToNewPlaylistDialogElement );
pdbm.plAddToNewPlaylistDialogElement.innerHTML =
'<b class="xtop">' +
'<b class="xb1"><\/b>' +
'<b class="xb2"><\/b>' +
'<b class="xb3"><\/b>' +
'<b class="xb4"><\/b>' +
'<\/b>' +
'<h2 class="boxHeader">Add to New Playlist<\/h2>' +
'<div class="addToNewPlaylistContentHolder">' +
'<form action="#" id="playlistDialogNewPlaylistForm" name="playlistDialogNewPlaylistForm" onSubmit="PlaylistDialogBoxManager.processAddToNewPlaylist( this ); return false;">' +
'<h3>The playlist &quot;' + PlaylistDialogBoxManager.activeNewPlaylistTitle + '&quot; already exists. Do you want to replace it?</h3><p>Replacing it will overwrite its current contents.</p>' +
'<div style="text-align: center; padding-top: 0px;">' +
'<div style="width: 10px; height: 23px; float: right; font-size: 0.1em;">&nbsp;<\/div>' +
'<div class="whiteButtonRight" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<div class="whiteButton" style="float: right; line-height: 23px; width: 40px;">' +
'<a href="#" title="Cancel" onClick="PlaylistDialogBoxManager.destroy(); return false;" class="boldWhiteLink"><b>Cancel<\/b><\/a>' +
'<\/div>' +
'<div class="whiteButtonLeft" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<div class="whiteButtonRight" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.processAddToNewPlaylistOverwrite(); return false;">&nbsp;<\/div>' +
'<div class="whiteButton" style="float: right; line-height: 23px; width: 40px;">' +
'<a href="#" title="Save" onClick="PlaylistDialogBoxManager.processAddToNewPlaylistOverwrite(); return false;" class="boldWhiteLink"><b>Replace<\/b><\/a>' +
'<\/div>' +
'<div class="whiteButtonLeft" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.processAddToNewPlaylistOverwrite(); return false;">&nbsp;<\/div>' +
'<\/div>' +
'<\/form>' +
'<\/div>';
}
else if( displayInPlace ){
errorHolderElement.className = this.plMenuItemClassName;
this.toggleMeddlesomeElements();
this.plListOfPlaylistsHolder.innerHTML = "";
this.plListOfPlaylistsHolder.appendChild( errorHolderElement );
errorHolderElement.innerHTML =
'<div style="color: red;">There was an error retrieving your playlists. Please try again later.<\/div>' +
'<div><a href="javascript:PlaylistDialogBoxManager.destroy();">Close<\/a><\/div>';
} else {
errorHolderElement.className = "errorMessage";
var pdbm = PlaylistDialogBoxManager;
var pdbmi = pdbm.plDialogBoxInstance;
var pdbmHe = pdbmi.getHoldingElement();
var ehm = errorHolderElement;
pdbmHe.innerHTML = "";
pdbmHe.appendChild( errorHolderElement );
pdbmi.hide();
pdbmi.setSize( 280, 'auto' );
pdbmi.centerInPage();
pdbmi.setMask( true );
pdbmi.setShadow();
Event.stopObserving( document.body, 'mousedown', pdbmi.listenForOuterClicks );
pdbmi.show();
RhapsodyUtility.addEvent( window, 'scroll', function( e ){ pdbmi.centerInPage(); });
pdbm._prepCenteredHoldingElementStyles();
pdbm.toggleMeddlesomeElements();
ehm.innerHTML =
'<table cellpadding="0" cellspacing="0" border="0"><tr><td valign="top">' +
'<img src="' + staticPath + '/images/exclamation.gif" width="27" height="27" alt="Attention: Error" style="padding-right: 10px;" \/><\/td>' +
'<td valign="top">' +
errorMsgObj.getMessage() +
'<\/td><\/tr>' +
'<\/table>' +
'<div style="text-align: center; padding-top: 15px;">' +
'<div class="whiteButtonRight" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<div class="whiteButton" style="float: right; line-height: 23px; width: 40px; text-align: center;">' +
'<a href="#" title="Cancel" onClick="PlaylistDialogBoxManager.destroy(); return false;" class="boldWhiteLink"><b>Cancel<\/b><\/a>' +
'<\/div>' +
'<div class="whiteButtonLeft" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<div style="width: 10px; height: 23px; float: right; font-size: 0.1em;">&nbsp;<\/div>';
ehm.innerHTML +=
'<\/div>';
}
},
setShadow: function( shadowOn ){
PlaylistDialogBoxManager.plDialogBoxInstance.setShadow( shadowOn );
},
toggleMeddlesomeElements: function( showOnly ){
if( !this._meddlesomesToggledOff && !showOnly ){
PlaylistDialogBoxManager.plDialogBoxInstance.toggleMeddlesomeElements();
this._meddlesomesToggledOff = true;
} else if( showOnly ) {
PlaylistDialogBoxManager.plDialogBoxInstance.toggleMeddlesomeElements( showOnly );
this._meddlesomesToggledOff = false;
}
},
_setListItemMouseEvents: function( theElement, theTargetElement ){
var targetElement = theTargetElement?theTargetElement:theElement;
var originalBackgroundColor = Element.hasClassName( targetElement, 'mostRecentPlaylist' )?'#D1E7F3':'transparent';
RhapsodyUtility.addEvent( theElement, 'mouseover', function(){
targetElement.style.backgroundColor = '#D1E7F3';
} );
RhapsodyUtility.addEvent( theElement, 'mouseout', function(){
targetElement.style.backgroundColor = originalBackgroundColor;
} );
RhapsodyUtility.addEvent( theElement, 'mousedown', function(){
targetElement.style.backgroundColor = '#CBECFC';
} );
},
_showAddToPlayerQueue: function(){
var addToPlayerQueueAnchor = document.createElement( "A" );
var addToPlayerQueueText = document.createTextNode( this.plAddToPlayerQueueText );
/* need to set these in block scope for the addToPlayerQueueFunction .. shrug */
var localActiveRcid = this.activeRcid;
var localDestroy = this.destroy;
var addToPlayerQueueFunction = function(){
if( localActiveRcid ){
RhapsodyPlayer.queueRcid( localActiveRcid );
localDestroy();
}
else{ alert( 'There is no active rcid' ); }
};
Event.observe( addToPlayerQueueAnchor, 'click', addToPlayerQueueFunction );
addToPlayerQueueAnchor.appendChild( addToPlayerQueueText );
addToPlayerQueueAnchor.setAttribute( "href", "javascript:void(null);" );
addToPlayerQueueAnchor.className = this.plMenuItemClassName;
this._setListItemMouseEvents( addToPlayerQueueAnchor );
this.plDialogBoxInstance.getHoldingElement().appendChild( addToPlayerQueueAnchor );
},
_showAddToNewPlaylist: function(){
var addToNewPlaylistAnchor = document.createElement( "A" );
var addToNewPlaylistText = document.createTextNode( this.plAddToNewPlaylistText );
/* need to set these in block scope for the addToNewPlaylistFunction .. shrug */
var localBuildAddToNewPlaylist = this.buildAddToNewPlaylist;
var addToNewPlaylistFunction = function(){
localBuildAddToNewPlaylist();
};
RhapsodyUtility.addEvent( addToNewPlaylistAnchor, 'click', addToNewPlaylistFunction );
addToNewPlaylistAnchor.appendChild( addToNewPlaylistText );
addToNewPlaylistAnchor.className = this.plMenuItemClassName;
addToNewPlaylistAnchor.setAttribute( "href", "javascript:void(null);" );
this._setListItemMouseEvents( addToNewPlaylistAnchor );
this.plListOfPlaylistsHolder.appendChild( addToNewPlaylistAnchor );
},
_showDividerElement: function(){
var dividerElement = document.createElement( "DIV" );
var dividerElementText = document.createTextNode( " " );
dividerElement.appendChild( dividerElementText );
dividerElement.className = "line999";
this.plDialogBoxInstance.getHoldingElement().appendChild( dividerElement );
},
_buildSubHeader: function(){
var subHeaderHolder = document.createElement( "DIV" );
var subHeaderText = document.createTextNode( " " );
subHeaderHolder.appendChild( subHeaderText );
subHeaderHolder.className = this.plSubHeaderClassName;
this.plDialogBoxInstance.getHoldingElement().appendChild( subHeaderHolder );
},
_buildAddToLibrary: function(){
var addToLibraryAnchor = document.createElement( "A" );
var addToLibraryText = document.createTextNode( this.plAddToLibraryText );
var localInsertIntoLibrary = this.insertIntoLibrary;
var insertIntoLibraryFunction = function(){
localInsertIntoLibrary();
};
RhapsodyUtility.addEvent( addToLibraryAnchor, 'click', insertIntoLibraryFunction );
addToLibraryAnchor.appendChild( addToLibraryText );
addToLibraryAnchor.className = this.plMenuItemClassName;
addToLibraryAnchor.setAttribute( "href", "javascript:void(null);" );
this._setListItemMouseEvents( addToLibraryAnchor );
this.plDialogBoxInstance.getHoldingElement().appendChild( addToLibraryAnchor );
},
_buildListOfPlaylistsHolder: function(){
var addToPlaylistHolderElement = document.createElement( "DIV" );
var localPlAddToPlaylistText = this.plAddToPlaylistText;
var listOfPlaylistsHolder = document.createElement( "DIV" );
var localAddToPlaylistClassName = this.plMenuItemClassName;
var addToPlaylistText = document.createTextNode( localPlAddToPlaylistText );
addToPlaylistHolderElement.appendChild( addToPlaylistText );
addToPlaylistHolderElement.className = localAddToPlaylistClassName;
listOfPlaylistsHolder.className = this.plListOfPlaylistsHolderClassName;
this.plDialogBoxInstance.getHoldingElement().appendChild( addToPlaylistHolderElement );
this.plDialogBoxInstance.getHoldingElement().appendChild( listOfPlaylistsHolder );
this.plListOfPlaylistsHolder = listOfPlaylistsHolder;
},
buildAddToNewPlaylist: function(){
var passedPlaylistName = PlaylistDialogBoxManager.activeNewPlaylistTitle;
var newPlaylistName = passedPlaylistName ? passedPlaylistName : "";
PlaylistDialogBoxManager.plAddToNewPlaylistDialogElement = document.createElement( "DIV" );
var pdbm = PlaylistDialogBoxManager;
var pdbmi = pdbm.plDialogBoxInstance;
var pdbmHe = pdbm.plDialogBoxInstance.getHoldingElement();
pdbmi.hide();
pdbmi.setSize( 433, 140 );
pdbmi.centerInPage();
pdbmi.setMask( true );
pdbmi.setShadow();
Event.stopObserving( document.body, 'mousedown', pdbmi.listenForOuterClicks );
pdbmi.show();
RhapsodyUtility.addEvent( window, 'scroll', function(e){ pdbmi.centerInPage(); });
pdbm.toggleMeddlesomeElements();
pdbm._prepCenteredHoldingElementStyles();
pdbmHe.innerHTML = "";
pdbmHe.appendChild( pdbm.plAddToNewPlaylistDialogElement );
pdbm.plAddToNewPlaylistDialogElement.innerHTML =
'<b class="xtop">' +
'<b class="xb1"><\/b>' +
'<b class="xb2"><\/b>' +
'<b class="xb3"><\/b>' +
'<b class="xb4"><\/b>' +
'<\/b>' +
'<h2 class="boxHeader">Add to New Playlist<\/h2>' +
'<div class="addToNewPlaylistContentHolder">' +
'<form action="#" id="playlistDialogNewPlaylistForm" name="playlistDialogNewPlaylistForm" onSubmit="PlaylistDialogBoxManager.processAddToNewPlaylist( this ); return false;">' +
'<h3>Playlist Name:<\/h3>' +
'<input type="text" value="' + newPlaylistName + '" id="playlistDialogNewPlaylistName" maxlength="80" style="width: 98%" onFocus="this.select();" \/>' +
'<div style="text-align: center; padding-top: 15px;">' +
'<div class="whiteButtonRight" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.processAddToNewPlaylist( $( \'playlistDialogNewPlaylistForm\' ) ); return false;">&nbsp;<\/div>' +
'<div class="whiteButton" style="float: right; line-height: 23px; width: 40px;">' +
'<a href="#" title="Save" onClick="PlaylistDialogBoxManager.processAddToNewPlaylist( $( \'playlistDialogNewPlaylistForm\' ) ); return false;" class="boldWhiteLink"><b>Save<\/b><\/a>' +
'<\/div>' +
'<div class="whiteButtonLeft" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.processAddToNewPlaylist( $( \'playlistDialogNewPlaylistForm\' ) ); return false;">&nbsp;<\/div>' +
'<div style="width: 10px; height: 23px; float: right; font-size: 0.1em;">&nbsp;<\/div>' +
'<div class="whiteButtonRight" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<div class="whiteButton" style="float: right; line-height: 23px; width: 40px;">' +
'<a href="#" title="Cancel" onClick="PlaylistDialogBoxManager.destroy(); return false;" class="boldWhiteLink"><b>Cancel<\/b><\/a>' +
'<\/div>' +
'<div class="whiteButtonLeft" style="width: 7px; height: 23px; float: right; font-size: 0.1em;" onClick="PlaylistDialogBoxManager.destroy(); return false;">&nbsp;<\/div>' +
'<\/div>' +
'<\/form>' +
'<\/div>';
setTimeout( function(){ $( 'playlistDialogNewPlaylistName' ).focus(); }, 300 );
},
_populateListOfPlaylists: function( playlists ){
/* TODO - changed how the function attached to A tag behaves, so my be able to ditch these locals */
var localActiveRcid = this.activeRcid;
var localNumberOfRecentPlaylists = this.getNumberOfRecentPlaylistsToShow();
var localShowRecentPlaylistsIf = this.getShowRecentPlaylistsIf();
var listOfRecentPlaylistsHolder, listOfRecentPlaylists, dividerElement, dividerElementText;
var useRecentPlaylists = false;
this.plListOfPlaylistsHolder.innerHTML = "";
this._showAddToNewPlaylist();
if( playlists.length > localShowRecentPlaylistsIf ){
listOfRecentPlaylistsHolder = document.createElement( "DIV" );
listOfRecentPlaylists = document.createElement( "DIV" );
dividerElement = document.createElement( "DIV" );
dividerElementText = document.createTextNode( " " );
dividerElement.appendChild( dividerElementText );
dividerElement.className = "line999";
dividerElement.style.marginLeft = '20px';
listOfRecentPlaylistsHolder.appendChild( listOfRecentPlaylists );
listOfRecentPlaylistsHolder.appendChild( dividerElement );
this.plListOfPlaylistsHolder.appendChild( listOfRecentPlaylistsHolder );
useRecentPlaylists = true;
}
for( var i=0; i < playlists.length; i++ ){
var playlistItemAnchor = document.createElement( "A" );
var playlistName = playlists[i].getName();
if( playlists[i].getTrunc() != -1 ){
playlistName = playlists[i].getName().substring( 0, playlists[i].getTrunc() ) + "...";
}
var playlistItemText = document.createTextNode( playlistName );
var localPlaylist = playlists[i];
/* use this method of playlist object to get int of ranking: getModDateRanking() */
playlistItemAnchor.appendChild( playlistItemText );
playlistItemAnchor.setAttribute( "href", "javascript:PlaylistDialogBoxManager.insertIntoPlaylist( '" + localPlaylist.getId() + "', '" + localActiveRcid + "' );" );
playlistItemAnchor.setAttribute( "title", playlists[i].getName() );
playlistItemAnchor.className = this.plMenuItemClassName;
if( ( playlists[i].getModDateRanking() <= localNumberOfRecentPlaylists ) ){
if( useRecentPlaylists && listOfRecentPlaylists ){
var recentPlaylistItem = playlistItemAnchor.cloneNode( true );
this._setListItemMouseEvents( recentPlaylistItem );
listOfRecentPlaylists.appendChild( recentPlaylistItem );
}
}
this.plListOfPlaylistsHolder.appendChild( playlistItemAnchor );
this._setListItemMouseEvents( playlistItemAnchor );
}
},
_prepCenteredHoldingElementStyles: function(){
var pdbmHe = PlaylistDialogBoxManager.plDialogBoxInstance.getHoldingElement();
pdbmHe.style.backgroundColor = "transparent";
pdbmHe.style.border = "0";
pdbmHe.style.padding = "0";
},
_setActiveContactingText: function( contactingText ){
PlaylistDialogBoxManager.activeContactingText = contactingText;
},
_showSignInPrompt: function(){
var signInOnClick = "signInOut( 'signin' ); PlaylistDialogBoxManager.destroy();";
var upgradeAnchor = '<a href="' + upsellURL + '?src=rcom_plist_menu" target="upgradeRhapsody" onClick="RhapsodyTracking.sendLinkEvent( { eVar17: \'Nav : Upsell: Upgrade - 14 Day Trial : Plus Menu\', prop18: \'E: Nav : Upsell: Upgrade - 14 Day Trial : Plus Menu\' }, { type: \'custom\', linkName: \'Navigation\', events: \'event8\' } ); PlaylistDialogBoxManager.destroy();">';
var upgradeSlug = "";
var signInSlug = "";
try{
if( RhapsodyCustomization && RhapsodyCustomization.PlusMenu ){
upgradeSlug = RhapsodyCustomization.PlusMenu.getUpgradeSlug();
if( RhapsodyCustomization.PlusMenu.appendAccountDetail ){
signInSlug = ' using your ' + RhapsodyCustomization.AccountMessaging.accountName + ' account';
}
}
} catch( e ){}
var signInHolderElement = document.createElement( "DIV" );
var signInHtml =
'<h4>Sign In or Upgrade<\/h4>' +
'<p>To bookmark music using My Library, or to create a Playlist, please <a href="javascript:' + signInOnClick + '">sign in<\/a> to Rhapsody' + signInSlug + '.' +
'<p \/>' +
'<p>Don\'t have Rhapsody? ' + upgradeAnchor + upgradeSlug + '<\/a>.<\/p>';
if( ( ( typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && !rhapsodyMember.isRadioPremiumUser && !rhapsodyMember.isAnonymousUser ) || this.accountType == 'RHAPSODY_FREE_USER' ){
signInHtml =
'<h4>Upgrade your Membership<\/h4>' +
'<p>To create a playlist, upgrade your Rhapsody Membership. ' + upgradeAnchor + 'Try it free<\/a>.<\/p>';
}
/* special override for verizon users, we should consider making this whole bit configurable also */
if( ( ( typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && !rhapsodyMember.isRadioPremiumUser && !rhapsodyMember.isAnonymousUser ) && rhapsodyMember.usersPartner == 'verizon' ){
signInHtml =
'<h4>Upgrade your Membership<\/h4>' +
'<p>To create a playlist, <a href="http://www.real.com/offer/rhapsody/upgrade/vcast" target="upgradeRhapsody">upgrade your Rhapsody Membership<\/a>.<\/p>';
}
signInHolderElement.className = this.plSignInPromptClassName;
signInHolderElement.innerHTML = signInHtml;
this.plDialogBoxInstance.getHoldingElement().appendChild( signInHolderElement );
},
_sendReportingEvent: function( eCat, eAction, eNum, eContentType ){
RhapsodyTracking.sendLinkEvent( { eVar17: eCat + ' : ' + eAction + " : " + eContentType, prop18: 'E: ' + eCat + ' : ' + eAction + " : " + eContentType }, { type: 'custom', linkName: eCat + ' Management', events: 'event' + eNum } );
},
_destroyResponder: function( message ){
if( message.hasError ){
PlaylistDialogBoxManager._onError( message );
} else {
PlaylistDialogBoxManager._lastTransactionSuccess = true;
var contentName = RhapsodyPlayer._getTypeStringByMoniker( PlaylistDialogBoxManager.activeRcid );
var wasLibrary = PlaylistDialogBoxManager._lastTransaction == PlaylistDialogBoxManager._lastTransactionStrings[ 2 ];
var createdNewPlaylist = PlaylistDialogBoxManager._lastTransaction == PlaylistDialogBoxManager._lastTransactionStrings[ 1 ];
var toThrob = "topNavMyMusic";
var eventReportingObject = {
eventNum: wasLibrary?10:9,
category: wasLibrary?'Library':'Playlist'
};
RhapsodyUtility.doThrob( toThrob, PlaylistDialogBoxManager.plDialogBoxInstance.getHoldingElement() );
PlaylistDialogBoxManager._sendReportingEvent( eventReportingObject.category, 'Add', eventReportingObject.eventNum, contentName );
if( createdNewPlaylist ) {
PlaylistDialogBoxManager._sendReportingEvent( eventReportingObject.category, 'Create', eventReportingObject.eventNum, contentName );
}
PlaylistDialogBoxManager.destroy();
}
}
};
function __typeAheadSearchDialogManager() {
this.instanceName = null;
this.typeAheadSearchDialog = null;
this.theLastTypeAheadSearch = null;
this.jsonSearchMgr = new jsonSearchManager();
this.genericXmlMgr = new genericXmlManager();
this.typeaheadSelected = -1;
this.typeaheadNumResults = 0;
this.typeaheadData = [];
this.theDefaultSearchMsg = null;
this.useRdsSource = false;
this.setRdsSource= function() { this.useRdsSource=true; }
/* These are the defaults used by the header search instance.
Should you find yourself wanting to use a typeahead search elsewhere,
you'll need to override these bits.
*/
this.setTypeAheadWidth = 448;
this.setSpawnFromOffset = 44;
this.goToSearchPage = true; /* set to false in your instance to keep searches in-page */
this.typeAheadDialogSpawnFrom = "topNavSearchContainerDiv";
this.typeAheadDialogSpawnFromElementId = "typeAheadSearchDialogDiv";
this.searchQueryElementId = "headerSearchQuery";
this.searchTypeElementId = "searchtype";
/* All of these instance variables are required if you want to use doFullSearch ala playlist builder */
this.fullSearchCallback = null;
this.clearableContainers = null; /* expects an array */
this.hideableContainers = null; /* expects an array */
this.albumQuickSearchCallback = null;
this.getDiscographyCallback = null;
this.getTopTracksCallback = null;
this.artistInfoDelegator = null;
this.resultOnClickHandler = null;
this.__isFirstSearchInWindow = true;
this.TYPEAHEAD_REPORTING_SEARCH_TYPE = "RhapTypeAheadFast";
this.instanceReportingMethod = null;
/* an internal representation of "this" */
var cThis = this;
/* get the searchtype from the page itself, not the instance */
this.getSearchType = function(){
return document.getElementById(cThis.searchTypeElementId).value;
};
this.getSearchTypeString = function(){
var mSearchtype = cThis.getSearchType();
var mSearchTypeString = "";
if(mSearchtype == "RhapArtist"){
mSearchTypeString = "Artist";
}
if(mSearchtype == "RhapAlbum"){
mSearchTypeString = "Album";
}
if(mSearchtype == "RhapTrack"){
mSearchTypeString = "Track";
}
return mSearchTypeString;
};
/* By default this methods throws you to the full search page.
If you want in-page results, set your instance var goToSearchPage to false.
*/
this.doSearchOrQuickSearch = function ( message ) {
if( cThis.typeaheadSelected >= 0 ) {
cThis.doQuickSearch(cThis.typeaheadSelected);
return;
}
else {
if(cThis.goToSearchPage === true){
doSearch(message); return;
}else{
cThis.doFullSearch(); return;
}
}
};
this.showTypeAheadSearchDialog = function (innerHTML) {
if( cThis.typeAheadSearchDialog ) {
cThis.typeAheadSearchDialog.loadContent( { htmlContent:innerHTML } );
}
else {
cThis.typeAheadSearchDialog = null;
cThis.typeAheadSearchDialog = new DialogBox(
{
spawnFrom: document.getElementById(this.typeAheadDialogSpawnFrom),
spawnFromOffset: [ 0, cThis.setSpawnFromOffset ],
elementId: this.typeAheadDialogSpawnFromElementId,
elementClassName: "typeAheadSearchDialogClass",
width: cThis.setTypeAheadWidth+'px',
htmlContent: innerHTML
}
);
cThis.typeAheadSearchDialog.registerOuterClickListener( cThis.outerClickHandler );
cThis.typeAheadSearchDialog.show();
}
};
this.outerClickHandler = function(){
cThis.typeAheadSearchDialog.destroy();
cThis.typeAheadSearchDialog = null;
Event.unloadCache();
};
this.hideTypeAheadSearchDialog = function () {
if( cThis.typeAheadSearchDialog ) {
cThis.typeaheadSelected = -1;
cThis.typeAheadSearchDialog.hide();
cThis.typeAheadSearchDialog.destroy();
cThis.typeAheadSearchDialog = null;
Event.unloadCache();
}
};
this.typeAheadSelect = function (i) {
cThis.typeAheadUnselect(cThis.typeaheadSelected);
cThis.typeaheadSelected = i;
var div = document.getElementById("typeAheadResult"+i);
if( div ){ div.style.backgroundColor = "#D1E7F3"; }
};
this.typeAheadUnselect = function (i) {
var div = document.getElementById("typeAheadResult"+i);
if( div ){ div.style.backgroundColor = "#ffffff"; }
};
this.getDefaultType = function () {
return cThis.isV2() ? "RhapKeyword" : "RhapArtist";
};
this.isV2 = function() {
var query = window.location.search.substring(1);
return query.indexOf("search=v2")>=0;
};
this.doQuickSearch = function ( i ) {
if(cThis.goToSearchPage == true){
if( !cThis.typeaheadData.results[i] ) { cThis.justDoWildcardSearch(); return; }
var theUrl = rhapsodyURL + "/goto?rcid=" + cThis.typeaheadData.results[i].rcid + "&lsrc=topnav_typeaheadsearch";
if( cThis.instanceReportingMethod ){
cThis.instanceReportingMethod( "Accepted", theUrl );
} else {
cThis.__goToResult( theUrl );
}
}
else if( cThis.resultOnClickHandler ) {
cThis.resultOnClickHandler(cThis.typeaheadData.results[i]);
} else {
/* TODO how much of this can be abstracted into the rendering manager? */
var searchType = cThis.getSearchType();
cThis.clearAllPreviousResults();
cThis.showThis("playlistLoadingDiv");
cThis.hideThis("playlistDefaultContent");
if( cThis.typeAheadSearchDialog ){
cThis.hideTypeAheadSearchDialog();
}
var mArtistRcid = "";
var mAlbumRcid = "";
if(searchType == "RhapArtist"){
mArtistRcid = cThis.typeaheadData.results[i].rcid.toLowerCase();
}
if(searchType == "RhapAlbum"){
mArtistRcid = cThis.typeaheadData.results[i].artistrcid.toLowerCase();
mAlbumRcid = cThis.typeaheadData.results[i].rcid.toLowerCase();
}
if(searchType == "RhapTrack"){
mArtistRcid = cThis.typeaheadData.results[i].artistrcid.toLowerCase();
mAlbumRcid = cThis.typeaheadData.results[i].albumrcid.toLowerCase();
}
cThis.artistInfoDelegator( i );
/* all quick searches (searches from the rcid of an artist/album/track) will have Top Tracks and Discography */
var mTopTracksFeedUrl = "data.json?datafeed=goto&rcid="+mArtistRcid+"&variant=artist-top-tracks-rss-feed";
var mDiscographyFeedUrl = "data.json?datafeed=goto&rcid="+mArtistRcid+"&variant=discography-rss-feed";
/* Call the rendering callbacks with status=loading... */
cThis.getDiscographyCallback( { "status":"loading" } );
cThis.getTopTracksCallback( { "status":"loading" } );
/* Now go get all the data, callbacks fire off rendering */
cThis.genericXmlMgr.getXmlAsData( mDiscographyFeedUrl , cThis.getDiscographyCallback );
cThis.genericXmlMgr.getXmlAsData( mTopTracksFeedUrl , cThis.getTopTracksCallback );
/* if the search type was an album or track, we fetch that album feed as well */
if(searchType == "RhapAlbum" || searchType == "RhapTrack"){
cThis.doJustAlbumQuickSearch( mAlbumRcid );
}
}
};
/* doJustAlbumQuickSearch will retrieve the album feed for a given rcid
and pass it off to whatever is specified for albumQuickSearchCallback.
*/
this.doJustAlbumQuickSearch = function ( rcid ){
var mAlbumFeedUrl = "data.json?datafeed=goto&rcid="+rcid+"&variant=rss-feed";
cThis.albumQuickSearchCallback({"status":"loading"});
cThis.genericXmlMgr.getXmlAsData( mAlbumFeedUrl , cThis.albumQuickSearchCallback );
};
this.doTypeAheadArtistSearch = function (evt) {
if( evt && cThis.typeAheadSearchDialog ) {
if( evt.keyCode == 38 ) { // up
if( cThis.typeaheadSelected==0 ) { return; }
cThis.typeAheadSelect(cThis.typeaheadSelected-1);
return;
}
else if( evt.keyCode == 40 ) { // down
if( cThis.typeaheadSelected >= cThis.typeaheadNumResults-1 ) { return; }
cThis.typeAheadSelect(cThis.typeaheadSelected+1);
return;
}
else if( evt.keyCode == 27 ) { // ESC
cThis.hideTypeAheadSearchDialog();
return;
}
}
var theQuery = document.getElementById(this.searchQueryElementId).value;
if( theQuery == cThis.theLastTypeAheadSearch || theQuery == cThis.theDefaultSearchMsg) { return; }
cThis.theLastTypeAheadSearch = theQuery;
if( theQuery.length<1 ) {
cThis.renderTypeAheadArtistSearchResults(null);
return;
}
if( cThis.useRdsSource ) {
var searchType = document.getElementById(cThis.searchTypeElementId).value;
cThis.jsonSearchMgr.getTypeAheadSearch( theQuery, cThis.renderTypeAheadArtistSearchResults, searchType );
}
else {
if( cThis.instanceReportingMethod ){
cThis.instanceReportingMethod( "Initiated" );
}
cThis.jsonSearchMgr.getNewTypeAheadSearch( theQuery, cThis.renderTypeAheadArtistSearchResults );
}
};
this.clearAllPreviousResults = function(){
/* A convenience method to help out with clearing result containers. Keep in mind this manager doesn't and shouldn't know
what they are, it just acts on the values of the instance variables clearableContainers and hideableContainers.
clearableContainers are containers that ONLY have search result data pushed into them. These can be CLEARED, not just hidden.
hideableContainers are containers that contain other containers, they should never be cleared, just hidden
*/
for(var i=0; i<cThis.clearableContainers.length; i++){
document.getElementById(cThis.clearableContainers[i]).innerHTML = "";
}
for(var j=0; j<cThis.hideableContainers.length; j++){
cThis.hideThis(cThis.hideableContainers[j]);
}
};
/* This runs a search against Fast for the search term, then calls whatever callback you specify for your instance variable fullSearchCallback. */
this.doFullSearch = function () {
var theQuery = document.getElementById(cThis.searchQueryElementId).value;
if(theQuery.length == 0 || theQuery == cThis.theDefaultSearchMsg){
alert("You must enter a searchterm.");
document.getElementById(cThis.searchQueryElementId).focus();
return;
}
cThis.clearAllPreviousResults();
var searchType = cThis.getSearchType();
if( theQuery.length<1 ) {
cThis.renderTypeAheadArtistSearchResults(null);
return;
}
cThis.hideTypeAheadSearchDialog();
/* TODO maybe this shouldn't be handling ANY ui for full search? */
cThis.showThis("playlistLoadingDiv");
cThis.fullSearchCallback({"status":"loading"});
cThis.jsonSearchMgr.getFullSearch( theQuery, "fsf", cThis.fullSearchCallback, searchType );
};
this.renderTypeAheadArtistSearchError = function (message) {
cThis.showTypeAheadSearchDialog("<div class=\"typeAheadSearchDialogResultError\">"+message+"<\/div>");
};
this.renderTypeAheadArtistSearchResults = function (data) {
if( data === null || data.query.length == 0 ) {
cThis.hideTypeAheadSearchDialog();
return;
}
if( data.hasError ) {
cThis.renderTypeAheadArtistSearchError("Error.");
return;
}
var theInnerHtml = "";
var numResults = 0;
if( data.results && data.results.length > 0 ){
for( var i=0; i < data.results.length; i++) {
var result = data.results[i];
if( result.type=='artist' ) {
theInnerHtml += "<div title=\"" + result.namenomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchDialogResult\">"
+ result.name
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>Artist<\/div>"
+ (result.blurb ? result.blurb : "&nbsp;")
+ "<\/span>"
+ "<\/div>";
numResults++;
}
if( result.type=='album' ) {
theInnerHtml += "<div title=\"" + result.namenomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchDialogResult\">"
+ result.name
+ (result.albumtypes ? " <span class='typeaheadUnbold'>"+result.albumtypes+"<\/span>" : "" )
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>Album<\/div>"
+ (result.artistname ? "by "+result.artistname : "(Various Artists)")
+ "<\/span>"
+ "<\/div>";
numResults++;
}
if( result.type=='track' ) {
theInnerHtml += "<div title=\"" + result.namenomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchDialogResult\">"
+ result.name
+ (result.musicvideoid ? " <img src='"+staticPath+"/images/typeahead_video_icon.gif'\/>" : "")
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>"+(result.musicvideoid ? "Track / Video" : "Track")+"<\/div>"
+ (result.albumandartist ? result.albumandartist+"" : "&nbsp;")
+ "<\/span>"
+ "<\/div>";
numResults++;
}
if( result.type=='playlist' ) {
theInnerHtml += "<div title=\"" + result.namenomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+ "onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+ "onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+ "class=\"typeAheadSearchDialogResult\">"
+ result.name
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>Playlist<\/div>"
+ ( result.artists ? result.artists : "" )
+ "<\/span>"
+ "<\/div>";
numResults++;
}
if( result.type=='featured' ) {
theInnerHtml += "<div title=\"" + result.textnomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchDialogResult\">"
+ result.text
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>" + (result.label?result.label:"Page") + "<\/div>"
+ (result.description ? result.description : "&nbsp;")
+ "<\/span>"
+ "<\/div>";
numResults++;
}
if( result.type=='genre' ) {
theInnerHtml += "<div title=\"" + result.textnomarkup +"\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".doQuickSearch(" + numResults + ")\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchDialogResult\">"
+ result.text
+ "<span class='typeaheadSubtext'>"
+ "<div class='typeAheadTypeLabel'>Genre<\/div>"
+ (result.description ? result.description : "&nbsp;")
+ "<\/span>"
+ "<\/div>";
numResults++;
}
theInnerHtml += "<div class='typeAheadDividerLine'>&nbsp;<\/div>";
}
}
if( numResults==0 ) {
cThis.renderTypeAheadArtistSearchError(
"<div class=\"typeaheadNoResultsDiv\" "
+"onClick=\""+cThis.instanceName+".justDoKeywordSearch()\">"
+"No suggestions found.<br \/>"
+"<span class=\"typeaheadNoResultsDivHighlight\">View all search results &gt;<\/span>"
+"<\/div>");
return;
}
else {
if( cThis.goToSearchPage ) {
theInnerHtml += "<div title=\"View All Search Results\" id=\"typeAheadResult"+numResults+"\" "
+"onClick=\""+cThis.instanceName+".justDoWildcardSearch()\" "
+"onMouseOver=\""+cThis.instanceName+".typeAheadSelect("+numResults+")\" "
+"class=\"typeAheadSearchSeeMoreDiv\">View All Search Results &gt;<\/div>";
// Continue to add to "num results", since this item is supposed to be treated just like a result...
numResults++;
}
}
cThis.typeaheadSelected = -1;
cThis.typeaheadNumResults = numResults;
cThis.typeaheadData = data;
cThis.showTypeAheadSearchDialog(theInnerHtml);
};
this.justDoWildcardSearch = function (query) {
var searchUrl = rhapsodyURL + "/-search?searchtype=RhapKeyword&query=";
document.location = searchUrl + encodeURIComponent(cThis.theLastTypeAheadSearch) + "*";
};
this.justDoKeywordSearch = function (query) {
var searchUrl = rhapsodyURL + "/-search?searchtype=RhapKeyword&query=";
document.location = searchUrl + encodeURIComponent(cThis.theLastTypeAheadSearch);
};
this.hideThis = function(someIds){
for (var i=0; i<arguments.length;i++){
document.getElementById(arguments[i]).style.display="none";
document.getElementById(arguments[i]).style.visibility="hidden";
}
};
this.showThis = function(theId){
for (var i=0; i<arguments.length;i++){
document.getElementById(arguments[i]).style.display="block";
document.getElementById(arguments[i]).style.visibility="visible";
}
};
this.doRhapsodyComReporting = function( type, arg ){
if( type === "Initiated" ){
cThis.__reportRhapsodyComSearchInitiated();
} else if ( type === "Accepted" ){
cThis.__reportRhapsodyComSearchResultAcceptedAndGo( arg );
} else if ( type === "NoResults" ){
cThis.__reportRhapsodyComSearchResultAcceptedAndGo( arg );
}
};
this.__reportRhapsodyComSearchInitiated = function(){
if( cThis.__isFirstSearchInWindow ){
cThis.__isFirstSearchInWindow = false;
try{
RhapsodyTracking.sendLinkEvent(
{
eVar17: 'Nav: TypeAheadSearch: Initiated',
prop18: 'E: Nav: TypeAheadSearch: Initiated',
prop22: cThis.TYPEAHEAD_REPORTING_SEARCH_TYPE,
eVar22: cThis.TYPEAHEAD_REPORTING_SEARCH_TYPE
},
{
type: 'custom',
linkName: 'TypeAheadSearch',
events: 'event8'
}
);
} catch( e ){}
} else {
return;
}
};
this.__reportRhapsodyComSearchResultAcceptedAndGo = function( rdUrl ){
var numResultsAsString = cThis.typeaheadData.totalresults + "";
var taQuery = cThis.typeaheadData.query;
try{
RhapsodyTracking.sendLinkEvent(
{
// eVar17: 'Nav: TypeAheadSearch: Accepted',
eVar17: 'Search',
prop18: 'E: Nav: TypeAheadSearch: Accepted',
prop23: taQuery,
prop24: numResultsAsString,
eVar24: numResultsAsString
},
{
type: 'custom',
linkName: 'TypeAheadSearch',
events: 'event8'
}, rdUrl
);
} catch( e ){
cThis.__goToResult( rdUrl );
}
};
this.__goToResult = function( rdUrl ){
window.location.href = rdUrl;
};
}
function possiblyRemoveAutoComplete() {
if( navigator.userAgent.toLowerCase().indexOf("firefox")>=0 ) { return; }
var theInput = document.getElementById(this.searchQueryElementId);
if( theInput ) { theInput.autocomplete = "off"; }
else { setTimeout( function(){ possiblyRemoveAutoComplete(); }, 500); }
}
possiblyRemoveAutoComplete();
function ShoppingCartBuyButton( rcid, divId ) {
this.id = divId;
this.rcid = rcid;
this.divId = divId;
this.altText = "";
this.variant = "";
this.recSrc = "";
this.albumOnly = false;
this.albumOnlyId = "";
this.albumPreorderAvailable = false;
this.price = null;
}
function __shoppingCartManager() {
this.isFulfillmentFlow = false;
this.NEVER_DO_OVERLAY = false;
this.statusDivName = null;
this.statusDivShowIfEmpty = false;
this.shoppingCart = null;
this.updatedCartCallbacks = []; // Any callbacks on the page that should be notified on cart changes...
this.buttonsById = []; // Maps from Button IDs to ShoppingCartBuyButton objects...
this.buttonsByRcid = []; // Maps from RCIDs to an Array of ShoppingCartBuyButton objects...
this.playlistJustAddedToCart = ""; //special case for playlists, since one isn't really in your cart, we track it per page instance.
this.url = "/webservice/json/shoppingcart";
this.setIsFulfillmentFlow = function( value ) {
SHOPPING_CART_MANAGER.isFulfillmentFlow = value;
};
this.registerCartStatusDiv = function( divName, divShow ) {
SHOPPING_CART_MANAGER.statusDivName = divName;
SHOPPING_CART_MANAGER.statusDivShowIfEmpty = divShow;
SHOPPING_CART_MANAGER.getCart( SHOPPING_CART_MANAGER.updateStatusDiv );
};
this.registerUpdatedCartCallback = function( fn ) {
// if we already got it, just call the sucker right away...
if( SHOPPING_CART_MANAGER.shoppingCart ){ fn(SHOPPING_CART_MANAGER.shoppingCart); }
SHOPPING_CART_MANAGER.updatedCartCallbacks.push( fn );
};
this.updateStatusDiv = function( responseData ) {
if( !responseData.totalCount ) { responseData.totalCount = 0; }
if( !responseData.success ) {
var theAction = ( typeof responseData.action != 'undefined' )?responseData.action:'default';
if( ( responseData.actionFailure != 'geoblocked' ) || ( ( responseData.actionFailure == 'geoblocked' ) && theAction != 'default' ) ){
var sendFailureEvent = function(){
RhapsodyTracking.sendLinkEvent( { eVar17: 'C: Err: scFailure: ' + theAction + ': ' + responseData.actionFailure, prop18: 'E: C: Err: scFailure' }, { type: 'custom', linkName: 'Error', events: 'event21' } );
};
if( RhapsodyDom.bodyLoaded ){ sendFailureEvent(); }
else { RhapsodyUtility.addLoadEvent( sendFailureEvent ); }
}
SHOPPING_CART_MANAGER.showAddUI( responseData );
}
SHOPPING_CART_MANAGER.shoppingCart = responseData;
for( var i=0 ; i < SHOPPING_CART_MANAGER.updatedCartCallbacks.length ; i++ ) {
try { SHOPPING_CART_MANAGER.updatedCartCallbacks[i](responseData); } catch(e) { }
}
var downloadReminderHtml = '';
if( responseData.hasRemainingDownloads && !SHOPPING_CART_MANAGER.isFulfillmentFlow ) {
RhapsodyUtility.addLoadEvent( function(){
var downloadReminderHtml = 'You have '+responseData.remainingDownloadCount+' items awaiting download. <a href="'+storeUrl+'/mydownloads.html">Click here<\/a> to review and download these items.';
var theCartReminderDiv = document.getElementById("cartReminderDiv");
if(theCartReminderDiv){
theCartReminderDiv.style.display = 'block';
/* removing to see if it fixes 220903 RhapsodyUtility.doFadein( 'cartReminderDiv', 100, .5 ); */
theCartReminderDiv.style.position = 'relative';
theCartReminderDiv.innerHTML = downloadReminderHtml;
}
} );
}
if( responseData.action == "add" && responseData.add ) {
if(responseData.add.indexOf( "ply." ) == 0){
SHOPPING_CART_MANAGER.playlistJustAddedToCart = responseData.add;
}
SHOPPING_CART_MANAGER.updateBuyButtons(responseData.add);
SHOPPING_CART_MANAGER.updateBuyButtons(responseData.addTrackIds);
SHOPPING_CART_MANAGER.showAddUI( SHOPPING_CART_MANAGER.shoppingCart );
if( responseData.createdCart && typeof responseData.createdCart != 'undefined' ){
RhapsodyTracking.sendLinkEvent( { eVar17: 'C: scOpen', prop18: 'E: C: scOpen' }, { type: 'custom', linkName: 'Commerce', events: 'scOpen' } );
}
} else if( responseData.action == "addPreorder" && responseData.addPreorder ){
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.addPreorder );
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.addPreorderTrackIds );
SHOPPING_CART_MANAGER.showAddUI( SHOPPING_CART_MANAGER.shoppingCart );
}
if( !( responseData.action == "addPreorder" || responseData.addPreorder ) && !( responseData.action == "removePreorder" || responseData.removePreorder ) ){
SHOPPING_CART_MANAGER.pulseCartDiv();
if( SHOPPING_CART_MANAGER.statusDivName === null ) { return; } // Do something more responsible here???
if( SHOPPING_CART_MANAGER.statusDivShowIfEmpty || ( !SHOPPING_CART_MANAGER.statusDivShowIfEmpty && responseData.totalCount > 0 ) ){
var mHtml = '<div id="ShoppingCartManagerDiv">' +
SHOPPING_CART_MANAGER.getDebugSettingsDiv() +
'<a href="' + cartUrl + '" class="shoppingCartAnchor">Cart (' + responseData.totalCount + ')<\/a><\/div>';
document.getElementById(SHOPPING_CART_MANAGER.statusDivName).style.display = 'block';
document.getElementById( 'topNavTopRowMessaging' ).style.paddingTop = '2px';
document.getElementById( 'topNavTopRowMessaging' ).style.height = '55px';
document.getElementById(SHOPPING_CART_MANAGER.statusDivName).innerHTML = mHtml;
}
}
if( responseData.action == "remove" && responseData.remove ){
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.remove );
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.removeTrackIds );
RhapsodyShoppingCartFlyout.destroy();
} else if( responseData.action == "removePreorder" && responseData.removePreorder ){
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.removePreorder);
SHOPPING_CART_MANAGER.updateBuyButtons( responseData.removePreorderTrackIds );
RhapsodyShoppingCartFlyout.destroy();
}
SHOPPING_CART_MANAGER.shoppingCart.add = ''; // (might be able to remove after ABC testing...)
SHOPPING_CART_MANAGER.shoppingCart.remove = ''; // (might be able to remove after ABC testing...)
// If this is part of an "auto add-to-cart" request, add the sucker...
var mAutoAdd = CookieManager.getCookie("autoAddToCart");
if( mAutoAdd ) {
SHOPPING_CART_MANAGER.autoAddToCart(mAutoAdd.toLowerCase());
CookieManager.actuallyDeleteCookie("autoAddToCart");
}
};
this.autoAddToCart = function( rcid ) {
// special case: if we want to add all the tracks in the querystring,
// the value will be "alltracks"...
if( rcid=="alltracks" ) {
var dummyButton = new ShoppingCartBuyButton( getQsParam("tracks"), "autoadd_dummy_Div_Id" );
SHOPPING_CART_MANAGER.registerButton(dummyButton);
SHOPPING_CART_MANAGER.add(dummyButton.id);
return;
}
var buttonObjectList = SHOPPING_CART_MANAGER.buttonsByRcid[rcid];
if( !buttonObjectList || !buttonObjectList.length ) {
setTimeout( "SHOPPING_CART_MANAGER.autoAddToCart('"+rcid+"')", 100 );
}
else {
var firstButtonObject = buttonObjectList[0];
if( !firstButtonObject.albumOnly ){
if( firstButtonObject.albumPreorderAvailable ) {
SHOPPING_CART_MANAGER.add(firstButtonObject.id,"preorder");
}
else {
SHOPPING_CART_MANAGER.add(firstButtonObject.id);
}
}
}
};
this.doDebug = function( val ) {
document.cookie = "cartDebug=" + val + "; path=/;";
SHOPPING_CART_MANAGER.updateStatusDiv( SHOPPING_CART_MANAGER.shoppingCart );
};
this.getDebugSetting = function() {
var mSetting = 'b';
if( document.cookie.indexOf("cartDebug=a")>0 ){ mSetting = 'a'; }
if( document.cookie.indexOf("cartDebug=b")>0 ){ mSetting = 'b'; }
if( document.cookie.indexOf("cartDebug=c")>0 ){ mSetting = 'c'; }
return mSetting;
};
this.getDebugSettingsDiv = function() {
return ""; // Comment this out to actually see the debug thingie...
var mSetting = SHOPPING_CART_MANAGER.getDebugSetting();
var mReturn = '<div style="float:left; z-index:100;">';
if( mSetting=='a' ) { mReturn += '<span style="font-weight:bold;">A<\/span>'; }
else { mReturn += '<a style="padding:0; margin:0; background-image:none; color:#000000;" href="javascript:SHOPPING_CART_MANAGER.doDebug(\'a\')">A<\/a>'; }
if( mSetting=='b' ) { mReturn += '<span style="font-weight:bold;">B<\/span>'; }
else { mReturn += '<a style="padding:0; margin:0; background-image:none; color:#000000;" href="javascript:SHOPPING_CART_MANAGER.doDebug(\'b\')">B<\/a>'; }
// if( mSetting=='c' ) { mReturn += "<span style='font-weight:bold;'>C</span>"; }
// else { mReturn += "<a style='padding:0; margin:0; background-image:none; color:#000000;' href=\"javascript:SHOPPING_CART_MANAGER.doDebug('c')\">C</a>"; }
return mReturn + '<\/div>';
};
this.neverDoOverlay = function(){ this.NEVER_DO_OVERLAY = true; };
this.pulseCartDiv = function(){
if( SHOPPING_CART_MANAGER.shoppingCart.success && ( SHOPPING_CART_MANAGER.shoppingCart.action=="add" || SHOPPING_CART_MANAGER.shoppingCart.action=="remove" ) ) {
for( var i=0 ; i<13 ; i+=2 ){
var c = i + "";
if( i==10 ){ c='a'; }
if( i==11 ){ c='b'; }
if( i==12 ){ c='c'; }
var f;
if( i<3 ){ f='f'; }
else if( i<6 ){ f='e'; }
else if( i<9 ){ f='d'; }
else { f='c'; }
setTimeout( "document.getElementById('ShoppingCartManagerDiv').style.backgroundColor='#" + f+f+f+f+c+c + "';", i * 75 );
}
setTimeout( function(){ document.getElementById('ShoppingCartManagerDiv').style.backgroundColor='transparent'; }, 15 * 75 );
}
};
this.showAddUI = function( passedData ){
if( !SHOPPING_CART_MANAGER.NEVER_DO_OVERLAY ) {
RhapsodyShoppingCartFlyout.init( passedData );
}
};
this.alreadyInCart = function( rcid ) {
if( !SHOPPING_CART_MANAGER.shoppingCart ){ return false; }
if( !SHOPPING_CART_MANAGER.shoppingCart.items ){ return false; }
for( var i=0 ; i < SHOPPING_CART_MANAGER.shoppingCart.items.length ; i++ ) {
if( SHOPPING_CART_MANAGER.shoppingCart.items[i].rcid == rcid ) { return true; }
}
return false;
};
this.alreadyInCartInPackage = function( rcid ) {
if( !SHOPPING_CART_MANAGER.shoppingCart ) { return false; }
if( !SHOPPING_CART_MANAGER.shoppingCart.trackIds ) { return false; }
// Tracks might be in the cart as part of other objects (albums, playlists, etc.)...
if( rcid.indexOf("tra.")==0 ) {
for( var i=0 ; i < SHOPPING_CART_MANAGER.shoppingCart.trackIds.length ; i++ ) {
if( SHOPPING_CART_MANAGER.shoppingCart.trackIds[i] == rcid ) { return true; }
}
}
return false;
};
this.alreadyPreordered = function( rcid ) {
if( !SHOPPING_CART_MANAGER.shoppingCart ) { return false; }
if( !SHOPPING_CART_MANAGER.shoppingCart.preorderitems ) { return false; }
for( var i=0 ; i < SHOPPING_CART_MANAGER.shoppingCart.preorderitems.length ; i++ ) {
if( SHOPPING_CART_MANAGER.shoppingCart.preorderitems[i].rcid == rcid ) { return true; }
}
return false;
};
this.registerButton = function( theButton ) {
var buttonObjectList = SHOPPING_CART_MANAGER.buttonsByRcid[theButton.rcid];
if( !buttonObjectList ) {
buttonObjectList = [];
SHOPPING_CART_MANAGER.buttonsByRcid[theButton.rcid] = buttonObjectList;
}
buttonObjectList.push( theButton );
SHOPPING_CART_MANAGER.buttonsById[ theButton.id ] = theButton;
SHOPPING_CART_MANAGER.updateBuyButtons( theButton.rcid );
};
this.thePlaylistJustAdded = function( rcid ){
if( SHOPPING_CART_MANAGER.playlistJustAddedToCart == rcid) {
return true;
}
};
this.updateBuyButtons = function( rcid ) {
if( typeof( rcid ) == "object" ) {
for( var i=0 ; i < rcid.length ; i++ ) { SHOPPING_CART_MANAGER.updateBuyButtons( rcid[i] ); }
return;
}
if( !SHOPPING_CART_MANAGER.shoppingCart ) {
setTimeout( "SHOPPING_CART_MANAGER.updateBuyButtons('" + rcid + "')", 100 );
return;
}
var buttonObjectList = SHOPPING_CART_MANAGER.buttonsByRcid[rcid];
if( !buttonObjectList ){ return; }
var needToRetry = false;
var theDivHtml = '';
for( var j=0 ; j < buttonObjectList.length ; j++ ) {
var thisButtonObject = buttonObjectList[j];
if( document.getElementById( thisButtonObject.divId ) ){
/* make this the already preordered condition */
if( this.alreadyInCart( rcid ) || this.alreadyInCartInPackage( rcid ) || this.thePlaylistJustAdded( rcid ) ){
theDivHtml = '<div class="cartButton cartButtonInCart' + thisButtonObject.variant + '"><\/div>';
}
else if( this.alreadyPreordered( rcid ) ){
theDivHtml = '<div class="cartButton cartButtonPreordered' + thisButtonObject.variant + '"><\/div>';
}
else if( thisButtonObject.albumOnly ) {
if(thisButtonObject.albumOnlyId){
theDivHtml = '<a href="/goto?rcid='+thisButtonObject.albumOnlyId+'" style="font-weight:normal;">Album&nbsp;Only<\/a>';
} else {
theDivHtml = 'Album&nbsp;Only';
}
}
else if( thisButtonObject.albumPreorderAvailable ){
theDivHtml = '<a class="cartButton cartButtonPreorder' + thisButtonObject.variant + '" ' +
'href="javascript: SHOPPING_CART_MANAGER.add( \'' + thisButtonObject.id + '\', \'preorder\' );"' +
' title="' + thisButtonObject.altText + '"><\/a>';
}
else {
theDivHtml = '<a class="cartButton cartButtonAdd' + thisButtonObject.variant + '" ' +
'href="javascript: SHOPPING_CART_MANAGER.add( \'' + thisButtonObject.id + '\' );"' +
' title="' + thisButtonObject.altText + '"><\/a>';
}
// some extra steps to make sure it will work consitently in IE
var newdiv = document.createElement( "DIV" );
newdiv.innerHTML = theDivHtml;
var container = document.getElementById( thisButtonObject.divId );
while (container.firstChild) {
container.removeChild( container.firstChild );
}
container.appendChild( newdiv );
}
else {
needToRetry = true;
}
}
if( needToRetry ) {
setTimeout( "SHOPPING_CART_MANAGER.updateBuyButtons('"+rcid+"')", 500 );
}
};
this.getCart = function( handler ){
var queryStringParams = ".r=" + ( new Date().valueOf() );
var callback = function (data){
handler(data);
};
this.sendMessage( rhapsodyURL + this.url, queryStringParams, callback);
};
this.add = function( buttonId, modifier ){
var theButton = SHOPPING_CART_MANAGER.buttonsById[buttonId];
if( modifier == 'preorder' ){ SHOPPING_CART_MANAGER.addPreorderRcid( theButton.rcid, theButton.recSrc ); }
else{ SHOPPING_CART_MANAGER.addRcid( theButton.rcid, theButton.recSrc, theButton.price ); }
};
this.addRcid = function( rcid, recSrc, price ){
var handler = SHOPPING_CART_MANAGER.updateStatusDiv;
var queryStringParams = "action=add&rcid=" + rcid + "&price=" + price + "&.r=" + ( new Date().valueOf() );
var callback = function( data ){ handler( data ); };
this.sendMessage( rhapsodyURL + this.url, queryStringParams, callback );
RhapsodyTracking.sendLinkEvent( { eVar17: 'C: scAdd', prop18: 'E: C: scAdd', eVar29: recSrc, prop29: recSrc }, { type: 'custom', linkName: 'Commerce', events: 'scAdd' } );
};
this.removeRcid = function( rcid, modifier, passedHandler ){
var handler = passedHandler || SHOPPING_CART_MANAGER.updateStatusDiv;
var theAction = ( modifier === 'preorder' )?'removePreorder':'remove';
var queryStringParams = "action=" + theAction + "&rcid=" + rcid + "&.r=" + ( new Date().valueOf() );
var callback = function( data ){ handler( data ); };
this.sendMessage( rhapsodyURL + this.url, queryStringParams, callback );
if( modifier != 'preorder' ){
RhapsodyTracking.sendLinkEvent( { eVar17: 'C: scRemove', prop18: 'E: C: scRemove' }, { type: 'custom', linkName: 'Commerce', events: 'scRemove' } );
} else {
RhapsodyTracking.sendLinkEvent( { eVar17: 'Nav: Click: Remove MP3Preorder', prop18: 'E: Nav: Click: Remove MP3Preorder' }, { type: 'custom', linkName: 'Navigation', events: 'event8' } );
}
};
this.addPreorderRcid = function( rcid, recSrc ){
if( (typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && !rhapsodyMember.isAnonymousUser ){
var handler = SHOPPING_CART_MANAGER.updateStatusDiv;
var queryStringParams = "action=addPreorder&rcid=" + rcid + "&.r=" + ( new Date().valueOf() );
var callback = function( data ){ handler( data ); };
this.sendMessage( rhapsodyURL + this.url, queryStringParams, callback );
RhapsodyTracking.sendLinkEvent( { eVar17: 'Nav: Click: Add MP3Preorder', prop18: 'E: Nav: Click: MP3Preorder', eVar29: recSrc, prop29: recSrc }, { type: 'custom', linkName: 'Navigation', events: 'event8' } );
}
else {
var successEvent = function() {
alert("Hey, it's successful!");
}
var awesomeMessage = "To sign up for alerts, you must first sign in or create an account. This is placeholder text, since the text has not been specified, nor has its position or layout. Yippie!";
SignInAccountCreationDialog.showOverlay(awesomeMessage, successEvent);
}
};
this.sendMessage = function( url, queryStringParams, callback ){
if( rhapsodyURL.indexOf( window.location.host ) < 0 ){ return; }
if( SHOPPING_CART_MANAGER.isFulfillmentFlow ) {
if( queryStringParams ) { queryStringParams += "&isFulfillmentFlow=true"; }
else { queryStringParams = "isFulfillmentFlow=true"; }
}
var CURRENTINSTANCE = this;
var wrappedCallback = function( requestObj, emptyData ){
var data;
if( requestObj.status == 200 ){
var text = requestObj.responseText;
if( text.substring(0,2) == "[{" ){
data = eval(text);
} else {
data = eval('('+text+')');
}
callback( data );
} else {
data = [];
data.exception = [];
data.exception.message = "Bad response from ajax request. ";
data.exception.code = requestObj.status;
callback( data );
return;
}
};
var theRequest = new Ajax.Request( url,{
onSuccess: wrappedCallback,
method: 'get',
parameters: queryStringParams }
);
};
this.reloadCallback = function(){
window.location.reload();
};
}
var SHOPPING_CART_MANAGER = new __shoppingCartManager();
var RhapsodyShoppingCartFlyout = {
scfDialogBoxInstance: null,
init: function( data ){
var rcids = "";
var lastRcid = "";
var isError = false;
var appropriateItems = data.items || data.preorderitems;
for( var i=0; i < appropriateItems.length; i++ ) {
if( i ){ rcids += ","; }
rcids += appropriateItems[i].rcid;
lastRcid = appropriateItems[i].rcid;
}
if( data.action == "add" ){
lastRcid = data.add;
} else if( data.action == "addPreorder" ){
lastRcid = data.addPreorder;
}
if( data.priceChange ) {
if( data.priceChange > 0 ) {
// alert("We're sorry to say that the price\nhas increased from $" + data.priceChangeOriginal + " to $" + data.priceChangeCurrent + "." );
}
else {
// alert("Hey, guess what!\nThe price has gone down from $" + data.priceChangeOriginal + " to $" + data.priceChangeCurrent + "!\nLooks like today's your lucky day!" );
}
}
var theAjaxUrl;
if( !data.success ) {
theAjaxUrl = rhapsodyURL + "/errorCartOverlay.html?error=" + data.actionFailure + "&country=" + data.geoblockCountry;
isError = true;
}
else {
theAjaxUrl = rhapsodyURL + "/viewCartCenterFlyout.html?.r=" + new Date().valueOf() + "&rcids=" + rcids + "&thercid=" + lastRcid + "&cartAction=" + data.action;
}
if( this.scfDialogBoxInstance ){ this.destroy(); }
this.scfDialogBoxInstance = new DialogBox( {
width: '290px',
elementClassName: 'cartOverlay',
srcUrl: theAjaxUrl
} );
try{
var thisScfDialogBoxInstance = this.scfDialogBoxInstance;
if( thisScfDialogBoxInstance ){
if( isError ){
thisScfDialogBoxInstance.centerInPage();
thisScfDialogBoxInstance.setMask( true );
Event.observe( window, 'scroll', function(e){
thisScfDialogBoxInstance.centerInPage();
thisScfDialogBoxInstance.setMask( true );
} );
Event.observe( window, 'resize', function(e){
thisScfDialogBoxInstance.centerInPage();
thisScfDialogBoxInstance.setMask( true );
} );
} else {
thisScfDialogBoxInstance.centerInPage( 0.47,1.48 );
thisScfDialogBoxInstance.setShadow( true );
RhapsodyUtility.addEvent( window, 'scroll', function(e){ thisScfDialogBoxInstance.centerInPage( 0.47,1.48 ); } );
RhapsodyUtility.addEvent( window, 'resize', function(e){ thisScfDialogBoxInstance.centerInPage( 0.47,1.48 ); } );
thisScfDialogBoxInstance.registerOuterClickListener( this.destroy );
}
thisScfDialogBoxInstance.toggleMeddlesomeElements();
return thisScfDialogBoxInstance;
}
} catch(e){}
},
destroy: function(){
if( RhapsodyShoppingCartFlyout.scfDialogBoxInstance ){
Event.unloadCache();
RhapsodyShoppingCartFlyout.scfDialogBoxInstance.toggleMeddlesomeElements();
RhapsodyShoppingCartFlyout.scfDialogBoxInstance.destroy();
RhapsodyShoppingCartFlyout.scfDialogBoxInstance = null;
}
}
};
var mboxCopyright = "&copy; 2003-2009. Omniture, Inc. All rights reserved.";mboxUrlBuilder = function(a, b) { this.a = a; this.b = b; this.c = new Array(); this.d = function(e) { return e; }; this.f = null;};mboxUrlBuilder.prototype.addParameter = function(g, h) { var i = new RegExp('(\'|")'); if (i.exec(g)) { throw "Parameter '" + g + "' contains invalid characters"; } for (var j = 0; j < this.c.length; j++) { var k = this.c[j]; if (k.name == g) { k.value = h; return this; } } var l = new Object(); l.name = g; l.value = h; this.c[this.c.length] = l; return this;};mboxUrlBuilder.prototype.addParameters = function(c) { if (!c) { return this; } for (var j = 0; j < c.length; j++) { var m = c[j].indexOf('='); if (m == -1 || m == 0) { continue; } this.addParameter(c[j].substring(0, m), c[j].substring(m + 1, c[j].length)); } return this;};mboxUrlBuilder.prototype.setServerType = function(n) { this.o = n;};mboxUrlBuilder.prototype.setBasePath = function(f) { this.f = f;};mboxUrlBuilder.prototype.setUrlProcessAction = function(p) { this.d = p;};mboxUrlBuilder.prototype.buildUrl = function() { var q = this.f ? this.f : '/m2/' + this.b + '/mbox/' + this.o; var r = document.location.protocol == 'file:' ? 'http:' : document.location.protocol; var e = r + "//" + this.a + q; var s = e.indexOf('?') != -1 ? '&' : '?'; for (var j = 0; j < this.c.length; j++) { var k = this.c[j]; e += s + encodeURIComponent(k.name) + '=' + encodeURIComponent(k.value); s = '&'; } return this.t(this.d(e));};mboxUrlBuilder.prototype.getParameters = function() { return this.c;};mboxUrlBuilder.prototype.setParameters = function(c) { this.c = c;};mboxUrlBuilder.prototype.clone = function() { var u = new mboxUrlBuilder(this.a, this.b); u.setServerType(this.o); u.setBasePath(this.f); u.setUrlProcessAction(this.d); for (var j = 0; j < this.c.length; j++) { u.addParameter(this.c[j].name, this.c[j].value); } return u;};mboxUrlBuilder.prototype.t = function(v) { return v.replace(/\"/g, '&quot;').replace(/>/g, '&gt;');};mboxStandardFetcher = function() { };mboxStandardFetcher.prototype.getType = function() { return 'standard';};mboxStandardFetcher.prototype.fetch = function(w) { w.setServerType(this.getType()); document.write('<' + 'scr' + 'ipt src="' + w.buildUrl() + '" language="JavaScript"><' + '\/scr' + 'ipt>');};mboxStandardFetcher.prototype.cancel = function() { };mboxAjaxFetcher = function() { };mboxAjaxFetcher.prototype.getType = function() { return 'ajax';};mboxAjaxFetcher.prototype.fetch = function(w) { w.setServerType(this.getType()); var e = w.buildUrl(); this.x = document.createElement('script'); this.x.src = e; document.body.appendChild(this.x);};mboxAjaxFetcher.prototype.cancel = function() { };mboxMap = function() { this.y = new Object(); this.z = new Array();};mboxMap.prototype.put = function(A, h) { if (!this.y[A]) { this.z[this.z.length] = A; } this.y[A] = h;};mboxMap.prototype.get = function(A) { return this.y[A];};mboxMap.prototype.remove = function(A) { this.y[A] = undefined;};mboxMap.prototype.each = function(p) { for (var j = 0; j < this.z.length; j++ ) { var A = this.z[j]; var h = this.y[A]; if (h) { p(A, h); } }};mboxFactory = function(B, b, C) { this.D = false; this.B = B; this.C = C; this.E = new mboxList(); mboxFactories.put(C, this); this.F = typeof document.createElement('div').replaceChild != 'undefined' && (function() { return true; })() && typeof document.getElementById != 'undefined' && typeof (window.attachEvent || document.addEventListener || window.addEventListener) != 'undefined' && typeof encodeURIComponent != 'undefined'; this.G = this.F && mboxGetPageParameter('mboxDisable') == null; var H = C == 'default'; this.I = new mboxCookieManager( 'mbox' + (H ? '' : ('-' + C)), (function() { return mboxCookiePageDomain(); })()); this.G = this.G && this.I.isEnabled() && (this.I.getCookie('disable') == null); if (this.isAdmin()) { this.enable(); } this.J = mboxGenerateId(); this.K = new mboxSession(this.J, 'mboxSession', 'session', 31 * 60, this.I); this.L = new mboxPC('PC', 1209600, this.I); this.w = new mboxUrlBuilder(B, b); this.M(this.w, H); this.N = new Date().getTime(); this.O = this.N; var P = this; this.addOnLoad(function() { P.O = new Date().getTime(); }); if (this.F) { this.addOnLoad(function() { P.D = true; P.getMboxes().each(function(Q) { Q.setFetcher(new mboxAjaxFetcher()); Q.finalize(); }); }); this.limitTraffic(100, 10368000); if (this.G) { this.R(); this.S = new mboxSignaler(function(T, c) { return P.create(T, c); }, this.I); } }};mboxFactory.prototype.isEnabled = function() { return this.G;};mboxFactory.prototype.getDisableReason = function() { return this.I.getCookie('disable');};mboxFactory.prototype.isSupported = function() { return this.F;};mboxFactory.prototype.disable = function(U, V) { if (typeof U == 'undefined') { U = 60 * 60; } if (typeof V == 'undefined') { V = 'unspecified'; } if (!this.isAdmin()) { this.G = false; this.I.setCookie('disable', V, U); }};mboxFactory.prototype.enable = function() { this.G = true; this.I.deleteCookie('disable');};mboxFactory.prototype.isAdmin = function() { return document.location.href.indexOf('mboxEnv') != -1;};mboxFactory.prototype.limitTraffic = function(W, U) {};mboxFactory.prototype.addOnLoad = function(p) { if (window.addEventListener) { window.addEventListener('load', p, false); } else if (document.addEventListener) { document.addEventListener('load', p, false); } else if (document.attachEvent) { window.attachEvent('onload', p); }};mboxFactory.prototype.getEllapsedTime = function() { return this.O - this.N;};mboxFactory.prototype.getEllapsedTimeUntil = function(X) { return X - this.N;};mboxFactory.prototype.getMboxes = function() { return this.E;};mboxFactory.prototype.get = function(T, Y) { return this.E.get(T).getById(Y || 0);};mboxFactory.prototype.update = function(T, c) { if (!this.isEnabled()) { return; } if (this.E.get(T).length() == 0) { throw "Mbox " + T + " is not defined"; } this.E.get(T).each(function(Q) { Q.getUrlBuilder() .addParameter('mboxPage', mboxGenerateId()); Q.load(c); });};mboxFactory.prototype.create = function( T, c, Z) { if (!this.isSupported()) { return null; } var e = this.w.clone(); e.addParameter('mboxCount', this.E.length() + 1); e.addParameters(c); var Y = this.E.get(T).length(); var _ = this.C + '-' + T + '-' + Y; var ab; if (Z) { ab = new mboxLocatorNode(Z); } else { if (this.D) { throw 'The page has already been loaded, can\'t write marker'; } ab = new mboxLocatorDefault(_); } try { var P = this; var bb = 'mboxImported-' + _; var Q = new mbox(T, Y, e, ab, bb); if (this.G) { Q.setFetcher(this.D ? new mboxAjaxFetcher() : new mboxStandardFetcher()); } Q.setOnError(function(cb, n) { Q.setMessage(cb); Q.activate(); if (!Q.isActivated()) { P.disable(60 * 60, cb); window.location.reload(false); } }); this.E.add(Q); } catch (db) { this.disable(); throw 'Failed creating mbox "' + T + '", the error was: ' + db; } var eb = new Date(); e.addParameter('mboxTime', eb.getTime() - (eb.getTimezoneOffset() * 60000)); return Q;};mboxFactory.prototype.getCookieManager = function() { return this.I;};mboxFactory.prototype.getPageId = function() { return this.J;};mboxFactory.prototype.getPCId = function() { return this.L;};mboxFactory.prototype.getSessionId = function() { return this.K;};mboxFactory.prototype.getSignaler = function() { return this.S;};mboxFactory.prototype.getUrlBuilder = function() { return this.w;};mboxFactory.prototype.M = function(e, H) { e.addParameter('mboxHost', document.location.hostname) .addParameter('mboxSession', this.K.getId()); if (!H) { e.addParameter('mboxFactoryId', this.C); } if (this.L.getId() != null) { e.addParameter('mboxPC', this.L.getId()); } e.addParameter('mboxPage', this.J); e.addParameter('mboxXDomain', "enabled"); e.setUrlProcessAction(function(e) { e += '&mboxURL=' + encodeURIComponent(document.location); var fb = encodeURIComponent(document.referrer); if (e.length + fb.length < 2000) { e += '&mboxReferrer=' + fb; } e += '&mboxVersion=' + mboxVersion; return e; });};mboxFactory.prototype.gb = function() { return "";};mboxFactory.prototype.R = function() { document.write('<style>.' + 'mboxDefault' + ' { visibility:hidden; }</style>');};mboxFactory.prototype.isDomLoaded = function() { return this.D;};mboxSignaler = function(hb, I) { this.I = I; var ib = I.getCookieNames('signal-'); for (var j = 0; j < ib.length; j++) { var jb = ib[j]; var kb = I.getCookie(jb).split('&'); var Q = hb(kb[0], kb); Q.load(); I.deleteCookie(jb); }};mboxSignaler.prototype.signal = function(lb, T ) { this.I.setCookie('signal-' + lb, mboxShiftArray(arguments).join('&'), 45 * 60);};mboxList = function() { this.E = new Array();};mboxList.prototype.add = function(Q) { if (Q != null) { this.E[this.E.length] = Q; }};mboxList.prototype.get = function(T) { var mb = new mboxList(); for (var j = 0; j < this.E.length; j++) { var Q = this.E[j]; if (Q.getName() == T) { mb.add(Q); } } return mb;};mboxList.prototype.getById = function(nb) { return this.E[nb];};mboxList.prototype.length = function() { return this.E.length;};mboxList.prototype.each = function(p) { if (typeof p != 'function') { throw 'Action must be a function, was: ' + typeof(p); } for (var j = 0; j < this.E.length; j++) { p(this.E[j]); }};mboxLocatorDefault = function(g) { this.g = 'mboxMarker-' + g; document.write('<div id="' + this.g + '" style="visibility:hidden;display:none">&nbsp;</div>');};mboxLocatorDefault.prototype.locate = function() { var ob = document.getElementById(this.g); while (ob != null) { if (ob.nodeType == 1) { if (ob.className == 'mboxDefault') { return ob; } } ob = ob.previousSibling; } return null;};mboxLocatorDefault.prototype.force = function() { var pb = document.createElement('div'); pb.className = 'mboxDefault'; var qb = document.getElementById(this.g); qb.parentNode.insertBefore(pb, qb); return pb;};mboxLocatorNode = function(rb) { this.ob = rb;};mboxLocatorNode.prototype.locate = function() { return typeof this.ob == 'string' ? document.getElementById(this.ob) : this.ob;};mboxLocatorNode.prototype.force = function() { return null;};mboxCreate = function(T ) { var Q = mboxFactoryDefault.create( T, mboxShiftArray(arguments)); if (Q) { Q.load(); } return Q;};mboxDefine = function(Z, T ) { var Q = mboxFactoryDefault.create(T, mboxShiftArray(mboxShiftArray(arguments)), Z); return Q;};mboxUpdate = function(T ) { mboxFactoryDefault.update(T, mboxShiftArray(arguments));};mbox = function(g, sb, w, tb, bb) { this.ub = null; this.vb = 0; this.ab = tb; this.bb = bb; this.wb = null; this.xb = new mboxOfferContent(); this.pb = null; this.w = w; this.message = ''; this.yb = new Object(); this.zb = 0; this.sb = sb; this.g = g; this.Ab(); w.addParameter('mbox', g) .addParameter('mboxId', sb); this.Bb = function() {}; this.Cb = function() {}; this.Db = null;};mbox.prototype.getId = function() { return this.sb;};mbox.prototype.Ab = function() { if (this.g.length > 250) { throw "Mbox Name " + this.g + " exceeds max length of " + "250 characters."; } else if (this.g.match(/^\s+|\s+$/g)) { throw "Mbox Name " + this.g + " has leading/trailing whitespace(s)."; }};mbox.prototype.getName = function() { return this.g;};mbox.prototype.getParameters = function() { var c = this.w.getParameters(); var mb = new Array(); for (var j = 0; j < c.length; j++) { if (c[j].name.indexOf('mbox') != 0) { mb[mb.length] = c[j].name + '=' + c[j].value; } } return mb;};mbox.prototype.setOnLoad = function(p) { this.Cb = p; return this;};mbox.prototype.setMessage = function(cb) { this.message = cb; return this;};mbox.prototype.setOnError = function(Bb) { this.Bb = Bb; return this;};mbox.prototype.setFetcher = function(Eb) { if (this.wb) { this.wb.cancel(); } this.wb = Eb; return this;};mbox.prototype.getFetcher = function() { return this.wb;};mbox.prototype.load = function(c) { if (this.wb == null) { return this; } this.setEventTime("load.start"); this.cancelTimeout(); this.vb = 0; var w = (c && c.length > 0) ? this.w.clone().addParameters(c) : this.w; this.wb.fetch(w); var P = this; this.Fb = setTimeout(function() { P.Bb('browser timeout', P.wb.getType()); }, 15000); this.setEventTime("load.end"); return this;};mbox.prototype.loaded = function() { this.cancelTimeout(); if (!this.activate()) { var P = this; setTimeout(function() { P.loaded(); }, 100); }};mbox.prototype.activate = function() { if (this.vb) { return this.vb; } this.setEventTime('activate' + ++this.zb + '.start'); if (this.show()) { this.cancelTimeout(); this.vb = 1; } this.setEventTime('activate' + this.zb + '.end'); return this.vb;};mbox.prototype.isActivated = function() { return this.vb;};mbox.prototype.setOffer = function(xb) { if (xb && xb.show && xb.setOnLoad) { this.xb = xb; } else { throw 'Invalid offer'; } return this;};mbox.prototype.getOffer = function() { return this.xb;};mbox.prototype.show = function() { this.setEventTime('show.start'); var mb = this.xb.show(this); this.setEventTime(mb == 1 ? "show.end.ok" : "show.end"); return mb;};mbox.prototype.showContent = function(Gb) { if (Gb == null) { return 0; } if (this.pb == null || !this.pb.parentNode) { this.pb = this.getDefaultDiv(); if (this.pb == null) { return 0; } } if (this.pb != Gb) { this.Hb(this.pb); this.pb.parentNode.replaceChild(Gb, this.pb); this.pb = Gb; } this.Ib(Gb); this.Cb(); return 1;};mbox.prototype.hide = function() { this.setEventTime('hide.start'); var mb = this.showContent(this.getDefaultDiv()); this.setEventTime(mb == 1 ? 'hide.end.ok' : 'hide.end.fail'); return mb;};mbox.prototype.finalize = function() { this.setEventTime('finalize.start'); this.cancelTimeout(); if (this.getDefaultDiv() == null) { if (this.ab.force() != null) { this.setMessage('No default content, an empty one has been added'); } else { this.setMessage('Unable to locate mbox'); } } if (!this.activate()) { this.hide(); this.setEventTime('finalize.end.hide'); } this.setEventTime('finalize.end.ok');};mbox.prototype.cancelTimeout = function() { if (this.Fb) { clearTimeout(this.Fb); } if (this.wb != null) { this.wb.cancel(); }};mbox.prototype.getDiv = function() { return this.pb;};mbox.prototype.getDefaultDiv = function() { if (this.Db == null) { this.Db = this.ab.locate(); } return this.Db;};mbox.prototype.setEventTime = function(Jb) { this.yb[Jb] = (new Date()).getTime();};mbox.prototype.getEventTimes = function() { return this.yb;};mbox.prototype.getImportName = function() { return this.bb;};mbox.prototype.getURL = function() { return this.w.buildUrl();};mbox.prototype.getUrlBuilder = function() { return this.w;};mbox.prototype.Kb = function(pb) { return pb.style.display != 'none';};mbox.prototype.Ib = function(pb) { this.Lb(pb, true);};mbox.prototype.Hb = function(pb) { this.Lb(pb, false);};mbox.prototype.Lb = function(pb, Mb) { pb.style.visibility = Mb ? "visible" : "hidden"; pb.style.display = Mb ? "block" : "none";};mboxOfferContent = function() { this.Cb = function() {};};mboxOfferContent.prototype.show = function(Q) { var mb = Q.showContent(document.getElementById(Q.getImportName())); if (mb == 1) { this.Cb(); } return mb;};mboxOfferContent.prototype.setOnLoad = function(Cb) { this.Cb = Cb;};mboxOfferAjax = function(Gb) { this.Gb = Gb; this.Cb = function() {};};mboxOfferAjax.prototype.setOnLoad = function(Cb) { this.Cb = Cb;};mboxOfferAjax.prototype.show = function(Q) { var Nb = document.createElement('div'); Nb.id = Q.getImportName(); Nb.innerHTML = this.Gb; var mb = Q.showContent(Nb); if (mb == 1) { this.Cb(); } return mb;};mboxOfferDefault = function() { this.Cb = function() {};};mboxOfferDefault.prototype.setOnLoad = function(Cb) { this.Cb = Cb;};mboxOfferDefault.prototype.show = function(Q) { var mb = Q.hide(); if (mb == 1) { this.Cb(); } return mb;};mboxCookieManager = function mboxCookieManager(g, Ob) { this.g = g; this.Ob = Ob == '' || Ob.indexOf('.') == -1 ? '' : '; domain=' + Ob; this.Pb = new mboxMap(); this.loadCookies();};mboxCookieManager.prototype.isEnabled = function() { this.setCookie('check', 'true', 60); this.loadCookies(); return this.getCookie('check') == 'true';};mboxCookieManager.prototype.setCookie = function(g, h, U) { if (typeof g != 'undefined' && typeof h != 'undefined' && typeof U != 'undefined') { var Qb = new Object(); Qb.name = g; Qb.value = escape(h); Qb.expireOn = Math.ceil(U + new Date().getTime() / 1000); this.Pb.put(g, Qb); this.saveCookies(); }};mboxCookieManager.prototype.getCookie = function(g) { var Qb = this.Pb.get(g); return Qb ? unescape(Qb.value) : null;};mboxCookieManager.prototype.deleteCookie = function(g) { this.Pb.remove(g); this.saveCookies();};mboxCookieManager.prototype.getCookieNames = function(Rb) { var Sb = new Array(); this.Pb.each(function(g, Qb) { if (g.indexOf(Rb) == 0) { Sb[Sb.length] = g; } }); return Sb;};mboxCookieManager.prototype.saveCookies = function() { var Tb = new Array(); var Ub = 0; this.Pb.each(function(g, Qb) { Tb[Tb.length] = g + '#' + Qb.value + '#' + Qb.expireOn; if (Ub < Qb.expireOn) { Ub = Qb.expireOn; } }); var Vb = new Date(Ub * 1000); document.cookie = this.g + '=' + Tb.join('|') + '; expires=' + Vb.toGMTString() + '; path=/' + this.Ob;};mboxCookieManager.prototype.loadCookies = function() { this.Pb = new mboxMap(); var Wb = document.cookie.indexOf(this.g + '='); if (Wb != -1) { var Xb = document.cookie.indexOf(';', Wb); if (Xb == -1) { Xb = document.cookie.indexOf(',', Wb); if (Xb == -1) { Xb = document.cookie.length; } } var Yb = document.cookie.substring( Wb + this.g.length + 1, Xb).split('|'); var Zb = Math.ceil(new Date().getTime() / 1000); for (var j = 0; j < Yb.length; j++) { var Qb = Yb[j].split('#'); if (Zb <= Qb[2]) { var _b = new Object(); _b.name = Qb[0]; _b.value = Qb[1]; _b.expireOn = Qb[2]; this.Pb.put(_b.name, _b); } } }};mboxSession = function(ac, bc, jb, cc, I) { this.bc = bc; this.jb = jb; this.cc = cc; this.I = I; this.dc = false; this.sb = typeof mboxForceSessionId != 'undefined' ? mboxForceSessionId : mboxGetPageParameter(this.bc); if (this.sb == null || this.sb.length == 0) { this.sb = I.getCookie(jb); if (this.sb == null || this.sb.length == 0) { this.sb = ac; this.dc = true; } } I.setCookie(jb, this.sb, cc);};mboxSession.prototype.getId = function() { return this.sb;};mboxSession.prototype.forceId = function(ec) { this.sb = ec; this.I.setCookie(this.jb, this.sb, this.cc);};mboxPC = function(jb, cc, I) { this.jb = jb; this.cc = cc; this.I = I; this.sb = typeof mboxForcePCId != 'undefined' ? mboxForcePCId : I.getCookie(jb); if (this.sb != null) { I.setCookie(jb, this.sb, cc); }};mboxPC.prototype.getId = function() { return this.sb;};mboxPC.prototype.forceId = function(ec) { if (this.sb != ec) { this.sb = ec; this.I.setCookie(this.jb, this.sb, this.cc); return true; } return false;};mboxGetPageParameter = function(g) { var mb = null; var fc = new RegExp(g + "=([^\&]*)"); var gc = fc.exec(document.location); if (gc != null && gc.length >= 2) { mb = gc[1]; } return mb;};mboxSetCookie = function(g, h, U) { return mboxFactoryDefault.getCookieManager().setCookie(g, h, U);};mboxGetCookie = function(g) { return mboxFactoryDefault.getCookieManager().getCookie(g);};mboxCookiePageDomain = function() { var Ob = (/([^:]*)(:[0-9]{0,5})?/).exec(document.location.host)[1]; var hc = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/; if (!hc.exec(Ob)) { var ic = (/([^\.]+\.[^\.]{3}|[^\.]+\.[^\.]+\.[^\.]{2})$/).exec(Ob); if (ic) { Ob = ic[0]; } } return Ob ? Ob: "";};mboxShiftArray = function(jc) { var mb = new Array(); for (var j = 1; j < jc.length; j++) { mb[mb.length] = jc[j]; } return mb;};mboxGenerateId = function() { return (new Date()).getTime() + "-" + Math.floor(Math.random() * 999999);};if (typeof mboxVersion == 'undefined') { var mboxVersion = 38; var mboxFactories = new mboxMap(); var mboxFactoryDefault = new mboxFactory('rhapsody.tt.omtrdc.net', 'rhapsody', 'default');};if (mboxGetPageParameter("mboxDebug") != null || mboxFactoryDefault.getCookieManager() .getCookie("debug") != null) { setTimeout(function() { if (typeof mboxDebugLoaded == 'undefined') { alert('Could not load the remote debug.\nPlease check your connection' + ' to Test&amp;Target servers'); } }, 60*60); document.write('<' + 'scr' + 'ipt language="Javascript1.2" src=' + '"http://admin9.testandtarget.omniture.com/admin/mbox/mbox_debug.jsp?mboxServerHost=rhapsody.tt.omtrdc.net' + '&clientCode=rhapsody"><' + '\/scr' + 'ipt>');};
/* Prototype JavaScript framework, version 1.5.0_rc1
* (c) 2005 Sam Stephenson <sam@conio.net>
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://prototype.conio.net/
*
/*--------------------------------------------------------------------------*/
var Prototype = {
Version: '1.5.0_rc1',
ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
emptyFunction: function() {},
K: function(x) {return x}
}
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Abstract = new Object();
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
Object.extend(Object, {
inspect: function(object) {
try {
if (object == undefined) return 'undefined';
if (object == null) return 'null';
return object.inspect ? object.inspect() : object.toString();
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
},
keys: function(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
},
values: function(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
},
clone: function(object) {
return Object.extend({}, object);
}
});
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
}
Function.prototype.bindAsEventListener = function(object) {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
}
}
Object.extend(Number.prototype, {
toColorPart: function() {
var digits = this.toString(16);
if (this < 16) return '0' + digits;
return digits;
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
}
});
var Try = {
these: function() {
var returnValue;
for (var i = 0; i < arguments.length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) {}
}
return returnValue;
}
}
/*--------------------------------------------------------------------------*/
var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.callback(this);
} finally {
this.currentlyExecuting = false;
}
}
}
}
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += (replacement(match) || '').toString();
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = count === undefined ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return this;
},
truncate: function(length, truncation) {
length = length || 30;
truncation = truncation === undefined ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : this;
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var div = document.createElement('div');
var text = document.createTextNode(this);
div.appendChild(text);
return div.innerHTML;
},
unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
},
toQueryParams: function() {
var pairs = this.match(/^\??(.*)$/)[1].split('&');
return pairs.inject({}, function(params, pairString) {
var pair = pairString.split('=');
var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
params[decodeURIComponent(pair[0])] = value;
return params;
});
},
toArray: function() {
return this.split('');
},
camelize: function() {
var oStringList = this.split('-');
if (oStringList.length == 1) return oStringList[0];
var camelizedString = this.indexOf('-') == 0
? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
: oStringList[0];
for (var i = 1, len = oStringList.length; i < len; i++) {
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}
return camelizedString;
},
inspect: function(useDoubleQuotes) {
var escapedString = this.replace(/\\/g, '\\\\');
if (useDoubleQuotes)
return '"' + escapedString.replace(/"/g, '\\"') + '"';
else
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (typeof replacement == 'function') return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
}
String.prototype.parseQuery = String.prototype.toQueryParams;
var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
return before + (object[match[3]] || '').toString();
});
}
}
var $break = new Object();
var $continue = new Object();
var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
try {
iterator(value, index++);
} catch (e) {
if (e != $continue) throw e;
}
});
} catch (e) {
if (e != $break) throw e;
}
},
all: function(iterator) {
var result = true;
this.each(function(value, index) {
result = result && !!(iterator || Prototype.K)(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator) {
var result = false;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
});
return result;
},
collect: function(iterator) {
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},
detect: function (iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator) {
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(pattern, iterator) {
var results = [];
this.each(function(value, index) {
var stringValue = value.toString();
if (stringValue.match(pattern))
results.push((iterator || Prototype.K)(value, index));
})
return results;
},
include: function(object) {
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.collect(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value >= result)
result = value;
});
return result;
},
min: function(iterator) {
var result;
this.each(function(value, index) {
value = (iterator || Prototype.K)(value, index);
if (result == undefined || value < result)
result = value;
});
return result;
},
partition: function(iterator) {
var trues = [], falses = [];
this.each(function(value, index) {
((iterator || Prototype.K)(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value, index) {
results.push(value[property]);
});
return results;
},
reject: function(iterator) {
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator) {
return this.collect(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.collect(Prototype.K);
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (typeof args.last() == 'function')
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
}
Object.extend(Enumerable, {
map: Enumerable.collect,
find: Enumerable.detect,
select: Enumerable.findAll,
member: Enumerable.include,
entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) {
return iterable.toArray();
} else {
var results = [];
for (var i = 0; i < iterable.length; i++)
results.push(iterable[i]);
return results;
}
}
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse)
Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0; i < this.length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != undefined || value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(value && value.constructor == Array ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
indexOf: function(object) {
for (var i = 0; i < this.length; i++)
if (this[i] == object) return i;
return -1;
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
reduce: function() {
return this.length > 1 ? this : this[0];
},
uniq: function() {
return this.inject([], function(array, value) {
return array.include(value) ? array : array.concat([value]);
});
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
var Hash = {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
if (typeof value == 'function') continue;
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
merge: function(hash) {
return $H(hash).inject($H(this), function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
toQueryString: function() {
return this.map(function(pair) {
return pair.map(encodeURIComponent).join('=');
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
}
function $H(object) {
var hash = Object.extend({}, object || {});
Object.extend(hash, Enumerable);
Object.extend(hash, Hash);
return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
}
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
}
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responderToAdd) {
if (!this.include(responderToAdd))
this.responders.push(responderToAdd);
},
unregister: function(responderToRemove) {
this.responders = this.responders.without(responderToRemove);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (responder[callback] && typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) {}
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
}
});
Ajax.Base = function() {};
Ajax.Base.prototype = {
setOptions: function(options) {
this.options = {
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
parameters: ''
}
Object.extend(this.options, options || {});
},
responseIsSuccess: function() {
return this.transport.status == undefined
|| this.transport.status == 0
|| (this.transport.status >= 200 && this.transport.status < 300);
},
responseIsFailure: function() {
return !this.responseIsSuccess();
}
}
Ajax.Request = Class.create();
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
this.request(url);
},
request: function(url) {
var parameters = this.options.parameters || '';
if (parameters.length > 0) parameters += '&_=';
/* Simulate other verbs over post */
if (this.options.method != 'get' && this.options.method != 'post') {
parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
this.options.method = 'post';
}
try {
this.url = url;
if (this.options.method == 'get' && parameters.length > 0)
this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
Ajax.Responders.dispatch('onCreate', this, this.transport);
this.transport.open(this.options.method, this.url,
this.options.asynchronous);
if (this.options.asynchronous)
setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
var body = this.options.postBody ? this.options.postBody : parameters;
this.transport.send(this.options.method == 'post' ? body : null);
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
} catch (e) {
this.dispatchException(e);
}
},
setRequestHeaders: function() {
var requestHeaders =
['X-Requested-With', 'XMLHttpRequest',
'X-Prototype-Version', Prototype.Version,
'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
if (this.options.method == 'post') {
requestHeaders.push('Content-type', this.options.contentType);
/* Force "Connection: close" for Mozilla browsers to work around
* a bug where XMLHttpReqeuest sends an incorrect Content-length
* header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType)
requestHeaders.push('Connection', 'close');
}
if (this.options.requestHeaders)
requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
for (var i = 0; i < requestHeaders.length; i += 2)
this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState != 1)
this.respondToReadyState(this.transport.readyState);
},
header: function(name) {
try {
return this.transport.getResponseHeader(name);
} catch (e) {}
},
evalJSON: function() {
try {
return eval('(' + this.header('X-JSON') + ')');
} catch (e) {}
},
evalResponse: function() {
try {
return eval(this.transport.responseText);
} catch (e) {
this.dispatchException(e);
}
},
respondToReadyState: function(readyState) {
var event = Ajax.Request.Events[readyState];
var transport = this.transport, json = this.evalJSON();
if (event == 'Complete') {
try {
(this.options['on' + this.transport.status]
|| this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(transport, json);
} catch (e) {
this.dispatchException(e);
}
if ((this.header('Content-type') || '').match(/^text\/javascript/i))
this.evalResponse();
}
try {
(this.options['on' + event] || Prototype.emptyFunction)(transport, json);
Ajax.Responders.dispatch('on' + event, this, transport, json);
} catch (e) {
this.dispatchException(e);
}
/* Avoid memory leak in MSIE: clean up the oncomplete event handler */
if (event == 'Complete')
this.transport.onreadystatechange = Prototype.emptyFunction;
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Updater = Class.create();
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
this.containers = {
success: container.success ? $(container.success) : $(container),
failure: container.failure ? $(container.failure) :
(container.success ? null : $(container))
}
this.transport = Ajax.getTransport();
this.setOptions(options);
var onComplete = this.options.onComplete || Prototype.emptyFunction;
this.options.onComplete = (function(transport, object) {
this.updateContent();
onComplete(transport, object);
}).bind(this);
this.request(url);
},
updateContent: function() {
var receiver = this.responseIsSuccess() ?
this.containers.success : this.containers.failure;
var response = this.transport.responseText;
if (!this.options.evalScripts)
response = response.stripScripts();
if (receiver) {
if (this.options.insertion) {
new this.options.insertion(receiver, response);
} else {
Element.update(receiver, response);
}
}
if (this.responseIsSuccess()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
}
});
Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
initialize: function(container, url, options) {
this.setOptions(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = {};
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(request) {
if (this.options.decay) {
this.decay = (request.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = request.responseText;
}
this.timer = setTimeout(this.onTimerEvent.bind(this),
this.decay * this.frequency * 1000);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $() {
var results = [], element;
for (var i = 0; i < arguments.length; i++) {
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results.push(Element.extend(element));
}
return results.reduce();
}
document.getElementsByClassName = function(className, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
return $A(children).inject([], function(elements, child) {
if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
elements.push(Element.extend(child));
return elements;
});
}
/*--------------------------------------------------------------------------*/
if (!window.Element)
var Element = new Object();
Element.extend = function(element) {
if (!element) return;
if (_nativeExtensions || element.nodeType == 3) return element;
if (!element._extended && element.tagName && element != window) {
var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
if (element.tagName == 'FORM')
Object.extend(methods, Form.Methods);
if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
Object.extend(methods, Form.Element.Methods);
for (var property in methods) {
var value = methods[property];
if (typeof value == 'function')
element[property] = cache.findOrStore(value);
}
}
element._extended = true;
return element;
}
Element.extend.cache = {
findOrStore: function(value) {
return this[value] = this[value] || function() {
return value.apply(null, [this].concat($A(arguments)));
}
}
}
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
$(element).style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: function(element, html) {
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
return element;
},
replace: function(element, html) {
element = $(element);
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
var range = element.ownerDocument.createRange();
range.selectNodeContents(element);
element.parentNode.replaceChild(
range.createContextualFragment(html.stripScripts()), element);
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
ancestors: function(element) {
return $(element).recursivelyCollect('parentNode');
},
descendants: function(element) {
element = $(element);
return $A(element.getElementsByTagName('*'));
},
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
nextSiblings: function(element) {
return $(element).recursivelyCollect('nextSibling');
},
siblings: function(element) {
element = $(element);
return element.previousSiblings().reverse().concat(element.nextSiblings());
},
match: function(element, selector) {
element = $(element);
if (typeof selector == 'string')
selector = new Selector(selector);
return selector.match(element);
},
up: function(element, expression, index) {
return Selector.findElement($(element).ancestors(), expression, index);
},
down: function(element, expression, index) {
return Selector.findElement($(element).descendants(), expression, index);
},
previous: function(element, expression, index) {
return Selector.findElement($(element).previousSiblings(), expression, index);
},
next: function(element, expression, index) {
return Selector.findElement($(element).nextSiblings(), expression, index);
},
getElementsBySelector: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},
getElementsByClassName: function(element, className) {
element = $(element);
return document.getElementsByClassName(className, element);
},
getHeight: function(element) {
element = $(element);
return element.offsetHeight;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
return Element.classNames(element).include(className);
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).add(className);
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
Element.classNames(element).remove(className);
return element;
},
observe: function() {
Event.observe.apply(Event, arguments);
return $A(arguments).first();
},
stopObserving: function() {
Event.stopObserving.apply(Event, arguments);
return $A(arguments).first();
},
// removes whitespace-only text node children
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.match(/^\s*$/);
},
childOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var x = element.x ? element.x : element.offsetLeft,
y = element.y ? element.y : element.offsetTop;
window.scrollTo(x, y);
return element;
},
getStyle: function(element, style) {
element = $(element);
var value = element.style[style.camelize()];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css.getPropertyValue(style) : null;
} else if (element.currentStyle) {
value = element.currentStyle[style.camelize()];
}
}
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';
return value == 'auto' ? null : value;
},
setStyle: function(element, style) {
element = $(element);
for (var name in style)
element.style[name.camelize()] = style[name];
return element;
},
getDimensions: function(element) {
element = $(element);
if (Element.getStyle(element, 'display') != 'none')
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = '';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = 'none';
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return;
element._overflow = element.style.overflow || 'auto';
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
}
}
// IE is missing .innerHTML support for TABLE-related elements
if(document.all){
Element.Methods.update = function(element, html) {
element = $(element);
var tagName = element.tagName.toUpperCase();
if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
var div = document.createElement('div');
switch (tagName) {
case 'THEAD':
case 'TBODY':
div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
depth = 2;
break;
case 'TR':
div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
depth = 3;
break;
case 'TD':
div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
depth = 4;
}
$A(element.childNodes).each(function(node){
element.removeChild(node)
});
depth.times(function(){ div = div.firstChild });
$A(div.childNodes).each(
function(node){ element.appendChild(node) });
} else {
element.innerHTML = html.stripScripts();
}
setTimeout(function() {html.evalScripts()}, 10);
return element;
}
}
Object.extend(Element, Element.Methods);
var _nativeExtensions = false;
if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
/* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
and HTMLSelectElement in Safari */
['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
var klass = window['HTML' + tag + 'Element'] = {};
klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
});
}
Element.addMethods = function(methods) {
Object.extend(Element.Methods, methods || {});
function copy(methods, destination) {
var cache = Element.extend.cache;
for (var property in methods) {
var value = methods[property];
destination[property] = cache.findOrStore(value);
}
}
if (typeof HTMLElement != 'undefined') {
copy(Element.Methods, HTMLElement.prototype);
copy(Form.Methods, HTMLFormElement.prototype);
[HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
copy(Form.Element.Methods, klass.prototype);
});
_nativeExtensions = true;
}
}
var Toggle = new Object();
Toggle.display = Element.toggle;
/*--------------------------------------------------------------------------*/
Abstract.Insertion = function(adjacency) {
this.adjacency = adjacency;
}
Abstract.Insertion.prototype = {
initialize: function(element, content) {
this.element = $(element);
this.content = content.stripScripts();
if (this.adjacency && this.element.insertAdjacentHTML) {
try {
this.element.insertAdjacentHTML(this.adjacency, this.content);
} catch (e) {
var tagName = this.element.tagName.toLowerCase();
if (tagName == 'tbody' || tagName == 'tr') {
this.insertContent(this.contentFromAnonymousTable());
} else {
throw e;
}
}
} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.insertContent([this.range.createContextualFragment(this.content)]);
}
setTimeout(function() {content.evalScripts()}, 10);
},
contentFromAnonymousTable: function() {
var div = document.createElement('div');
div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
return $A(div.childNodes[0].childNodes[0].childNodes);
}
}
var Insertion = new Object();
Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
initializeRange: function() {
this.range.setStartBefore(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment, this.element);
}).bind(this));
}
});
Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(true);
},
insertContent: function(fragments) {
fragments.reverse(false).each((function(fragment) {
this.element.insertBefore(fragment, this.element.firstChild);
}).bind(this));
}
});
Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
initializeRange: function() {
this.range.selectNodeContents(this.element);
this.range.collapse(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.appendChild(fragment);
}).bind(this));
}
});
Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
initializeRange: function() {
this.range.setStartAfter(this.element);
},
insertContent: function(fragments) {
fragments.each((function(fragment) {
this.element.parentNode.insertBefore(fragment,
this.element.nextSibling);
}).bind(this));
}
});
/*--------------------------------------------------------------------------*/
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set(this.toArray().concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set(this.select(function(className) {
return className != classNameToRemove;
}).join(' '));
},
toString: function() {
return this.toArray().join(' ');
}
}
Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
initialize: function(expression) {
this.params = {classNames: []};
this.expression = expression.toString().strip();
this.parseExpression();
this.compileMatcher();
},
parseExpression: function() {
function abort(message) { throw 'Parse error in selector: ' + message; }
if (this.expression == '') abort('empty expression');
var params = this.params, expr = this.expression, match, modifier, clause, rest;
while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
params.attributes = params.attributes || [];
params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
expr = match[1];
}
if (expr == '*') return this.params.wildcard = true;
while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
modifier = match[1], clause = match[2], rest = match[3];
switch (modifier) {
case '#': params.id = clause; break;
case '.': params.classNames.push(clause); break;
case '':
case undefined: params.tagName = clause.toUpperCase(); break;
default: abort(expr.inspect());
}
expr = rest;
}
if (expr.length > 0) abort(expr.inspect());
},
buildMatchExpression: function() {
var params = this.params, conditions = [], clause;
if (params.wildcard)
conditions.push('true');
if (clause = params.id)
conditions.push('element.id == ' + clause.inspect());
if (clause = params.tagName)
conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
if ((clause = params.classNames).length > 0)
for (var i = 0; i < clause.length; i++)
conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
if (clause = params.attributes) {
clause.each(function(attribute) {
var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
var splitValueBy = function(delimiter) {
return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
}
switch (attribute.operator) {
case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break;
case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
case '|=': conditions.push(
splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
); break;
case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break;
case '':
case undefined: conditions.push(value + ' != null'); break;
default: throw 'Unknown operator ' + attribute.operator + ' in selector';
}
});
}
return conditions.join(' && ');
},
compileMatcher: function() {
this.match = new Function('element', 'if (!element.tagName) return false; \
return ' + this.buildMatchExpression());
},
findElements: function(scope) {
var element;
if (element = $(this.params.id))
if (this.match(element))
if (!scope || Element.childOf(element, scope))
return [element];
scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
var results = [];
for (var i = 0; i < scope.length; i++)
if (this.match(element = scope[i]))
results.push(Element.extend(element));
return results;
},
toString: function() {
return this.expression;
}
}
Object.extend(Selector, {
matchElements: function(elements, expression) {
var selector = new Selector(expression);
return elements.select(selector.match.bind(selector));
},
findElement: function(elements, expression, index) {
if (typeof expression == 'number') index = expression, expression = false;
return Selector.matchElements(elements, expression || '*')[index || 0];
},
findChildElements: function(element, expressions) {
return expressions.map(function(expression) {
return expression.strip().split(/\s+/).inject([null], function(results, expr) {
var selector = new Selector(expr);
return results.inject([], function(elements, result) {
return elements.concat(selector.findElements(result || element));
});
});
}).flatten();
}
});
function $$() {
return Selector.findChildElements(document, $A(arguments));
}
var Form = {
reset: function(form) {
$(form).reset();
return form;
}
};
Form.Methods = {
serialize: function(form) {
var elements = Form.getElements($(form));
var queryComponents = new Array();
for (var i = 0; i < elements.length; i++) {
var queryComponent = Form.Element.serialize(elements[i]);
if (queryComponent)
queryComponents.push(queryComponent);
}
return queryComponents.join('&');
},
getElements: function(form) {
form = $(form);
var elements = new Array();
for (var tagName in Form.Element.Serializers) {
var tagElements = form.getElementsByTagName(tagName);
for (var j = 0; j < tagElements.length; j++)
elements.push(tagElements[j]);
}
return elements;
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name)
return inputs;
var matchingInputs = new Array();
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) ||
(name && input.name != name))
continue;
matchingInputs.push(input);
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
var elements = Form.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.blur();
element.disabled = 'true';
}
return form;
},
enable: function(form) {
form = $(form);
var elements = Form.getElements(form);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.disabled = '';
}
return form;
},
findFirstElement: function(form) {
return Form.getElements(form).find(function(element) {
return element.type != 'hidden' && !element.disabled &&
['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
form = $(form);
Field.activate(Form.findFirstElement(form));
return form;
}
}
Object.extend(Form, Form.Methods);
/*--------------------------------------------------------------------------*/
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
}
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
var parameter = Form.Element.Serializers[method](element);
if (parameter) {
var key = encodeURIComponent(parameter[0]);
if (key.length == 0) return;
if (parameter[1].constructor != Array)
parameter[1] = [parameter[1]];
return parameter[1].map(function(value) {
return key + '=' + encodeURIComponent(value);
}).join('&');
}
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
var parameter = Form.Element.Serializers[method](element);
if (parameter)
return parameter[1];
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
element.focus();
if (element.select)
element.select();
return element;
},
disable: function(element) {
element = $(element);
element.disabled = '';
return element;
},
enable: function(element) {
element = $(element);
element.blur();
element.disabled = 'true';
return element;
}
}
Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
/*--------------------------------------------------------------------------*/
Form.Element.Serializers = {
input: function(element) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element);
default:
return Form.Element.Serializers.textarea(element);
}
return false;
},
inputSelector: function(element) {
if (element.checked)
return [element.name, element.value];
},
textarea: function(element) {
return [element.name, element.value];
},
select: function(element) {
return Form.Element.Serializers[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
},
selectOne: function(element) {
var value = '', opt, index = element.selectedIndex;
if (index >= 0) {
opt = element.options[index];
value = opt.value || opt.text;
}
return [element.name, value];
},
selectMany: function(element) {
var value = [];
for (var i = 0; i < element.length; i++) {
var opt = element.options[i];
if (opt.selected)
value.push(opt.value || opt.text);
}
return [element.name, value];
}
}
/*--------------------------------------------------------------------------*/
var $F = Form.Element.getValue;
/*--------------------------------------------------------------------------*/
Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
initialize: function(element, frequency, callback) {
this.frequency = frequency;
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
this.registerCallback();
},
registerCallback: function() {
setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
onTimerEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
}
}
Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
/*--------------------------------------------------------------------------*/
Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
initialize: function(element, callback) {
this.element = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
var elements = Form.getElements(this.element);
for (var i = 0; i < elements.length; i++)
this.registerCallback(elements[i]);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
}
Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) {
var Event = new Object();
}
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
element: function(event) {
return event.target || event.srcElement;
},
isLeftClick: function(event) {
return (((event.which) && (event.which == 1)) ||
((event.button) && (event.button == 1)));
},
pointerX: function(event) {
return event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft));
},
pointerY: function(event) {
return event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop));
},
stop: function(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
} else {
event.returnValue = false;
event.cancelBubble = true;
}
},
// find the first node with the given tagName, starting from the
// node the event was triggered on; traverses the DOM upwards
findElement: function(event, tagName) {
var element = Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase())))
element = element.parentNode;
return element;
},
observers: false,
_observeAndCache: function(element, name, observer, useCapture) {
if (!this.observers) this.observers = [];
if (element.addEventListener) {
this.observers.push([element, name, observer, useCapture]);
element.addEventListener(name, observer, useCapture);
} else if (element.attachEvent) {
this.observers.push([element, name, observer, useCapture]);
element.attachEvent('on' + name, observer);
}
},
unloadCache: function() {
if (!Event.observers) return;
for (var i = 0; i < Event.observers.length; i++) {
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers[i][0] = null;
}
Event.observers = false;
},
observe: function(element, name, observer, useCapture) {
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.attachEvent))
name = 'keydown';
Event._observeAndCache(element, name, observer, useCapture);
},
stopObserving: function(element, name, observer, useCapture) {
element = $(element);
useCapture = useCapture || false;
if (name == 'keypress' &&
(navigator.appVersion.match(/Konqueror|Safari|KHTML/)
|| element.detachEvent))
name = 'keydown';
if (element.removeEventListener) {
element.removeEventListener(name, observer, useCapture);
} else if (element.detachEvent) {
try {
element.detachEvent('on' + name, observer);
} catch (e) {}
}
}
});
/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
// set to true if needed, warning: firefox performance problems
// NOT neeeded for page scrolling, only if draggable contained in
// scrollable elements
includeScrollOffsets: false,
// must be called before calling withinIncludingScrolloffset, every time the
// page is scrolled
prepare: function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
realOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return [valueL, valueT];
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
p = Element.getStyle(element, 'position');
if (p == 'relative' || p == 'absolute') break;
}
} while (element);
return [valueL, valueT];
},
offsetParent: function(element) {
if (element.offsetParent) return element.offsetParent;
if (element == document.body) return element;
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return element;
return document.body;
},
// caches x/y coordinate pair to use with overlap
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = this.cumulativeOffset(element);
return (y >= this.offset[1] &&
y < this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x < this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = this.realOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = this.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp < this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp < this.offset[0] + element.offsetWidth);
},
// within must be called directly before
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
page: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
// Safari fix
if (element.offsetParent==document.body)
if (Element.getStyle(element,'position')=='absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (!window.opera || element.tagName=='BODY') {
valueT -= element.scrollTop || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return [valueL, valueT];
},
clone: function(source, target) {
var options = Object.extend({
setLeft: true,
setTop: true,
setWidth: true,
setHeight: true,
offsetTop: 0,
offsetLeft: 0
}, arguments[2] || {})
// find page position of source
source = $(source);
var p = Position.page(source);
// find coordinate system to use
target = $(target);
var delta = [0, 0];
var parent = null;
// delta [0,0] will do fine with position: fixed elements,
// position:absolute needs offsetParent deltas
if (Element.getStyle(target,'position') == 'absolute') {
parent = Position.offsetParent(target);
delta = Position.page(parent);
}
// correct by body offsets (fixes Safari)
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
// set position
if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
if(options.setWidth) target.style.width = source.offsetWidth + 'px';
if(options.setHeight) target.style.height = source.offsetHeight + 'px';
},
absolutize: function(element) {
element = $(element);
if (element.style.position == 'absolute') return;
Position.prepare();
var offsets = Position.positionedOffset(element);
var top = offsets[1];
var left = offsets[0];
var width = element.clientWidth;
var height = element.clientHeight;
element._originalLeft = left - parseFloat(element.style.left || 0);
element._originalTop = top - parseFloat(element.style.top || 0);
element._originalWidth = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top = top + 'px';;
element.style.left = left + 'px';;
element.style.width = width + 'px';;
element.style.height = height + 'px';;
},
relativize: function(element) {
element = $(element);
if (element.style.position == 'relative') return;
Position.prepare();
element.style.position = 'relative';
var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top = top + 'px';
element.style.left = left + 'px';
element.style.height = element._originalHeight;
element.style.width = element._originalWidth;
}
}
// Safari returns margins on body which is incorrect if the child is absolutely
// positioned. For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
Position.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return [valueL, valueT];
}
}
Element.addMethods();
function PlaylistMgr() {
this.url = rhapsodyURL + "/webservice/playlistmgr";
this.globalPlaylists;
this.mwidth = 10000;
this.trackmwidth = 10000;
this.albummwidth = 10000;
this.artistmwidth = 10000;
this.sort = 0;
/** Sort values are
NATURAL = 0;
REVERSE_NATURAL_SORT = 1;
NAME_SORT = 2;
REVERSE_NAME_SORT = 3;
MOD_DATE_SORT = 4;
REVERSE_MOD_DATE_SORT = 5;
TRACK_NAME_SORT = 6;
REVERSE_TRACK_NAME_SORT = 7;
ARTIST_NAME_SORT = 8;
REVERSE_ARTIST_NAME_SORT = 9;
ALBUM_NAME_SORT = 10;
REVERSE_ALBUM_NAME_SORT = 11;
**/
this.messageCount = 0;
this.messagesReceivedMapping = new Array();
this.instanceId = Math.floor(Math.random()*10000000);
this.returnAsArrays = function(data) {
if (data){
var playlists = new Array();
for (var i=0; i < data.length; i++){
playlists[i] = new Playlist(data[i]);
}
return playlists;
}
};
this.sendMessage = function( url, content, callback){
var CURRENTMESSAGECOUNT = "" + (this.messageCount++);
var MESSAGEMAPPING = this.messagesReceivedMapping;
var wrappedCallback = function (requestObj, emptyData) {
if( MESSAGEMAPPING[CURRENTMESSAGECOUNT]=="true" ) { return; }
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data = new Array();
data.exception = new Array();
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
callback(data);
return;
}
}
new PeriodicalExecuter( function(pe) {
if( MESSAGEMAPPING[CURRENTMESSAGECOUNT]!="true" ) {
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
var data = new Array();
data.hasError = true;
callback(data);
}
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
// Need to stop this thread the first time through...
pe.stop();
}, 30 /* 30s */ );
new Ajax.Request( url,{
onSuccess: wrappedCallback,
method: 'post',
parameters: content.toQueryString()+"&sort="+this.sort+"&mwidth="+this.mwidth+"&albummwidth="+this.albummwidth+"&artistmwidth="+this.artistmwidth+"&trackmwidth="+this.trackmwidth
});
}
this.innerHasPlaylist = function (id, callback) {
var localHandler = function(data){
for (var i =0; i<data.length; i++){
if (data[i].getId() == id){
callback(null, true);
return;
}
}
callback(null, false);
};
if (this.globalPlaylists == null){
this.innerGetPlaylists( localHandler);
} else {
localHandler(this.globalPlaylists);
}
}
this.innerGetPlaylists = function (handler, sort) {
var action = "get-playlists";
var content = $H({
returntype: "array",
todo: action});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists;
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
}
PlaylistMgr.prototype.getPlaylists = function ( sort, handler ) {
this.innerGetPlaylists(handler, sort);
}
PlaylistMgr.prototype.getPlaylist = function ( id, handler ) {
// see if we have it in our local cache first.
if (this.globalPlaylists != null) {
for (var i = 0; i<this.globalPlaylists.length; i++){
if (this.globalPlaylists[i].getId() == id){
handler(data);
return;
}
}
}
var action = "get";
var content = $H({id: id,
returntype: "object",
todo: action});
var callback = function (data){
if(data.hasError){
handler(data);
}else{
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.getNewestPlaylist = function ( handler) {
// see if we have it in our local cache first.
if (this.globalPlaylists != null) {
var newestCreateDate = 0;
var newestPlaylist;
for (var i = 0; i<this.globalPlaylists.length; i++){
var itemCreateDate = this.globalPlaylists[i].getCreatedate();
if (itemCreateDate > newestCreateDate){
newestCreateDate = itemCreateDate;
newestPlaylist = this.globalPlaylists[i];
}
}
handler(newestPlaylist);
return;
}
var action = "get-newest";
var content = $H({
returntype: "object",
todo: action});
var callback = function (data){
if(data.hasError){
handler(data);
}else{
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
// Name can be null to set a new untitled playlist.
PlaylistMgr.prototype.setPlaylist = function ( name, ids, handler) {
var action = "set";
var content = $H({name: unescape( encodeURIComponent(name)),
ids: ids,
returntype: "object",
todo: action});
var callback = function (data){
if(data.hasError){
handler(data);
}else{
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists;
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.setExistingByName = function ( name, ids, handler) {
var action = "set-existing";
var content = $H({name: unescape( encodeURIComponent(name)),
ids: ids,
returntype: "object",
todo: action});
var callback = function (data){
if(data.hasError){
handler(data);
}else{
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists;
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.setExisting = function (playlistId, ids, handler) {
var action = "set-existing";
var content = $H({id: playlistId,
todo: action,
returntype: "object",
ids: ids
});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.removePlaylist = function ( id, handler) {
var action = "remove-playlist";
var content = $H({id: id,
returntype: "array",
todo: action});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.renamePlaylist = function ( id, newname, handler) {
var action = "rename";
var content = $H({id: id,
newname:unescape( encodeURIComponent(newname)),
returntype: "object",
todo: action});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.insertIntoPlaylist = function ( id, trackid, idx, handler) {
var action = "insert-into-playlist";
var content = $H({id: id,
trackid:trackid,
index:idx,
returntype: "object",
todo: action});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
var playlists = new PlaylistMgr().returnAsArrays(data);
this.globalPlaylists = playlists
handler(playlists);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.hasPlaylist = function ( id, handler) {
var callback = function (data){
handler(data);
}
this.innerHasPlaylist( id, callback);
}
PlaylistMgr.prototype.getNextUntitledPlaylistName = function (handler) {
var action = "get-next-untitled-playlist-name";
var content = $H({todo: action,
returntype: "object"});
var callback = function (data){
if (data.hasError){
handler(data);
} else {
handler(data.value);
}
}
this.sendMessage(this.url, content, callback);
}
PlaylistMgr.prototype.setSort = function (sort) {
this.sort = sort
}
PlaylistMgr.prototype.setMwidth = function (mwidth) { this.mwidth = mwidth; }
PlaylistMgr.prototype.setTrackMwidth = function (mwidth) { this.trackmwidth = mwidth; }
PlaylistMgr.prototype.setAlbumMwidth = function (mwidth) { this.albummwidth = mwidth; }
PlaylistMgr.prototype.setArtistMwidth = function (mwidth) { this.artistmwidth = mwidth; }
PlaylistMgr.prototype.toString = function () {
var output = '';
for (var i = 0; i<this.list.length; i++){
output = output + this.list[i].id + " " + this.list[i].rcid + " " + this.list[i].playlength + " " + this.list[i].name + " " + this.list[i].discindex + " " + this.list[i].remoteid + " " + this.list[i].artistdisplayname;
}
return output;
}
function genericXmlManager() {
/* give it a URL that will return XML, like an RSS feed, and it will wrap it up in a JSON object and spit it back to you. */
this.getXmlAsData = function( urlLocation, handler ) {
if( !urlLocation || !handler){
return;
}
this.sendMessage( rhapsodyURL + "/" + urlLocation, handler);
};
this.getXmlAsDataViaPost = function( urlLocation, handler ) {
if( !urlLocation || !handler){
return;
}
this.sendMessagePost( rhapsodyURL + "/" + urlLocation, handler);
};
this.MSGCOUNT = 0;
this.sendMessage = function( url, callback){
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data = new Array();
data.exception = new Array();
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
callback(data);
return;
}
}
new Ajax.Request( url,{
onSuccess: wrappedCallback,
method: 'get'});
}
this.sendMessagePost = function( url, callback){
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data = new Array();
data.exception = new Array();
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
callback(data);
return;
}
}
new Ajax.Request( url,{
onSuccess: wrappedCallback,
method: 'post'
});
}
}
function jsonSearchManager() {
/* Will search against artist, album or track as specified by searchType */
this.typeAheadUrl = "/searchwidget.json"; /* Searches against RDS, used for type ahead */
this.newTypeAheadUrl = "/typeahead.json";
this.fullUrl = "/webservice/search.json"; /* Searches against FAST, used for search when you want JSON artist/album/track results back */
this.metaDataUrl = "/webservice/librarymeta"; /* returns the same meta data for an artist used in LibraryManager. */
this.getTypeAheadSearch = function( searchString, handler, searchType ) {
var theRhapsodyBID = ".";
try { theRhapsodyBID=rhapsodyBID; } catch(e) { }
var queryStringParams = "type=" + searchType + "&name=" + escape(this.stripVowelAccent(searchString)) + "&source=rd&page=1&bid=" + theRhapsodyBID;
queryStringParams += "&mwidth1=36&mwidth2=40";
var callback = function (data){
handler(data);
}
var firstChar = "-";
try { firstChar=searchString.charAt(0).toLowerCase(); } catch(e) {}
if( firstChar<'a' || firstChar>'z' ) { firstChar="_"; }
this.sendMessage( rhapsodyURL + "/" + firstChar + this.typeAheadUrl, queryStringParams, callback);
};
this.getNewTypeAheadSearch = function( searchString, handler ) {
var theRhapsodyBID = ".";
try { theRhapsodyBID=rhapsodyBID; } catch(e) { }
var queryStringParams = "name=" + escape(this.stripVowelAccent(searchString)) + "&bid=" + theRhapsodyBID;
queryStringParams += "&mwidth1=36&mwidth2=40";
var callback = function (data){
handler(data);
}
var firstChar = "-";
try { firstChar=searchString.charAt(0).toLowerCase(); } catch(e) {}
if( firstChar<'a' || firstChar>'z' ) { firstChar="_"; }
this.sendMessage( rhapsodyURL + "/" + firstChar + this.newTypeAheadUrl, queryStringParams, callback);
};
this.getFullSearch = function( searchString, dataSource, handler, searchType, start ) {
var theRhapsodyBID = ".";
try { theRhapsodyBID=rhapsodyBID; } catch(e) { }
if(!start){
start = 1;
}
var queryStringParams = "type=" + searchType + "&name=" + escape(this.stripVowelAccent(searchString)) + "&source="+dataSource+"&page="+start+"&bid=" + theRhapsodyBID;
var callback = function (data){
handler(data);
}
this.sendMessage( rhapsodyURL + "/" + this.fullUrl, queryStringParams, callback);
};
this.getArtistInfo = function( rcid, handler ) {
var theRhapsodyBID = ".";
try { theRhapsodyBID=rhapsodyBID; } catch(e) { }
var callback = function (data){
handler(data);
}
var queryStringParams = "todo=get-metadata&ids=" + rcid + "&bid=" + theRhapsodyBID;
this.sendMessage( rhapsodyURL + "/" + this.metaDataUrl, queryStringParams , callback);
};
this.stripVowelAccent = function (str) {
var s=str;
var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];
var repChar=['A','a','E','e','I','i','O','o','U','u'];
for(var i=0; i<rExps.length; i++)
s=s.replace(rExps[i],repChar[i]);
return s;
};
this.MSGCOUNT = 0;
this.sendMessage = function( url, queryStringParams, callback){
var CURRENTMESSAGECOUNT = ++this.MSGCOUNT;
var CURRENTINSTANCE = this;
var wrappedCallback = function (requestObj, emptyData) {
if (CURRENTMESSAGECOUNT != CURRENTINSTANCE.MSGCOUNT){
return;
}
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data = new Array();
data.exception = new Array();
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
callback(data);
return;
}
}
new Ajax.Request( url,{
onSuccess: wrappedCallback,
method: 'get',
parameters: queryStringParams });
}
}
function Playlist(JSONObject) {
this.url = "/webservice/playlistmgr";
this.list;
this.name;
this.edition;
this.guid;
this.createDate;
this.modDate;
this.id;
this.trunc = 10000;
this.sort = 0;
this.size;
this.modDateRanking;
/** Sort values are
NATURAL = 0;
REVERSE_NATURAL_SORT = 1;
TRACK_NAME_SORT = 6;
REVERSE_TRACK_NAME_SORT = 7;
ARTIST_NAME_SORT = 8;
REVERSE_ARTIST_NAME_SORT = 9;
ALBUM_NAME_SORT = 10;
REVERSE_ALBUM_NAME_SORT = 11;
**/
this.mwidth = 10000;
this.trackmwidth = 10000;
this.albummwidth = 10000;
this.artistmwidth = 10000;
if (JSONObject){
if (JSONObject.list) {
this.list = JSONObject.list;
}
this.size = JSONObject.size;
this.name = JSONObject.name;
this.trunc = JSONObject.trunc;
this.edition = JSONObject.edition;
this.guid = JSONObject.guid;
this.id = JSONObject.id;
this.createDate = JSONObject.createdate;
this.modDate = JSONObject.moddate;
this.modDateRanking = JSONObject.modDateRanking;
}
this.onSet = function(data){Ajax.Responders.dispatch('PlaylistOnSet', data); };
this.onMove = function(data){Ajax.Responders.dispatch('PlaylistOnMove', data); };
this.onClear = function(data){Ajax.Responders.dispatch('PlaylistOnClear', data); };
this.onRemoveTrackById = function(data){Ajax.Responders.dispatch('PlaylistOnRemoveTrackById', data); };
this.onRemoveTrack = function(data){Ajax.Responders.dispatch('PlaylistOnRemoveTrack', data); };
this.onAddTrack = function(data){Ajax.Responders.dispatch('PlaylistOnAddTrack', data); };
this.onError = function(data){Ajax.Responders.dispatch('PlaylistOnError', data); };
this.onContacting = function(){Ajax.Responders.dispatch('PlaylistOnContacting', "CONTACTING");};
this.sendMessage = function(url, content, callback){
this.onContacting();
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
//alert(data);
if (data.hasError){
//alert("Whoops - " + data.exception.message + ' ' + data.exception.code);
// all onError calls aren't working for some strange reason
new Playlist().onError("Whoops - " + data.exception.message + ' ' + data.exception.code);
}
callback(data);
} else {
var data;
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
new Playlist().onTransportError(data);
}
}
new Ajax.Request(url,{
onSuccess: wrappedCallback,
method: 'post',
parameters: content.toQueryString()+"&sort"+this.sort
});
}
}
Playlist.prototype.setList = function (aList) {
this.list = aList;
}
Playlist.prototype.getList = function () {
return this.list;
}
Playlist.prototype.getLength = function () {
return this.list.length;
}
Playlist.prototype.get = function (idx) {
return this.list[idx];
}
Playlist.prototype.setName = function(aName){
this.name = aName;
}
Playlist.prototype.getName = function(){
return this.name;
}
Playlist.prototype.getTrunc = function(){
return this.trunc;
}
Playlist.prototype.setId = function(anId){
this.id = anId;
}
Playlist.prototype.getId = function(){
return this.id;
}
Playlist.prototype.setGuid = function(aValue){
this.guid = aValue;
}
Playlist.prototype.getGuid = function(){
return this.guid;
}
Playlist.prototype.setEdition = function(aValue){
this.edition = aValue;
}
Playlist.prototype.getEdition = function(){
return this.edition;
}
Playlist.prototype.setCreateDate = function(aValue){
this.createDate = aValue;
}
Playlist.prototype.getCreateDate = function(){
return this.createDate;
}
Playlist.prototype.setModDate = function(aValue){
this.modDate = aValue;
}
Playlist.prototype.getModDate = function(){
return this.modDate;
}
Playlist.prototype.getModDateRanking = function(){
return this.modDateRanking;
}
Playlist.prototype.clear = function (handler) {
if (handler == null){
handler = this.onClear;
}
var action = "clear";
var content = $H({name: this.name,
returntype: "object",
todo: action});
var callback = function (data){
if (data.hasError){
this.onError(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
Playlist.prototype.move = function (from, to, handler) {
if (handler == null){
handler = this.onMove;
}
if (from > this.list.length || to > this.list.length) {
this.onError("Can't do a move operation beyond the length of the playlist");
return;
}
var action = "move";
var content = $H({name: this.name,
todo: action,
returntype: "object",
from: from,
to: to});
var callback = function (data){
if (data.hasError){
this.onError(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
Playlist.prototype.removeTrack = function (idx, handler) {
if (handler == null){
handler = this.onRemoveTrack;
}
if (idx != null) {
if (idx >= this.getLength()) {
this.onError("Can't do a remove operation beyond the length of the playlist");
return;
}
}
var action = "remove";
var content = $H({id: this.id,
todo: action,
returntype: "object",
index: idx});
var callback = function (data){
if (data.hasError){
this.onError(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
Playlist.prototype.addTrack = function (id, idx, handler) {
if (handler == null){
handler = this.onAddTrack;
}
if (idx != null) {
if (idx > this.getLength()) {
idx = this.getLength()
}
}
var action = "insert";
var content = $H({name: this.name,
todo: action,
returntype: "object",
id: id,
index: idx});
var callback = function (data){
if (data.hasError){
this.onError(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
Playlist.prototype.set = function (ids, handler) {
if (handler == null){
handler = this.onSet;
}
var action = "set-existing";
var content = $H({id: this.id,
todo: action,
returntype: "object",
ids: ids
});
var callback = function (data){
if (data.hasError){
this.onError(data);
} else {
data = new Playlist(data);
handler(data);
}
}
this.sendMessage(this.url, content, callback);
}
Playlist.prototype.logError = function (message) {
this.onError(message);
}
Playlist.prototype.setSort = function (sort) {
this.sort = sort;
}
Playlist.prototype.setSize = function (size) {
this.size = size;
}
Playlist.prototype.getSize = function () {
return this.size;
}
Playlist.prototype.toString = function () {
var output = 'playlist name: ' + this.name + ' edition: ' + this.edition + ' guid: ' + this.guid;
for (var i = 0; i<this.list.length; i++){
output = output + this.list[i].id + " " + this.list[i].rcid + " " + this.list[i].playlength + " " + this.list[i].name + " " + this.list[i].discindex + " " + this.list[i].remoteid + " " + this.list[i].artistdisplayname;
}
return output;
}
function LibraryManager( ) {
this.url = "/webservice/librarymgr";
this.metadataUrl = "/webservice/librarymeta";
this.trunc = 10000;
this.sort = 0;
/** Sort values are
NATURAL = 0;
REVERSE_NATURAL_SORT = 1;
TRACK_NAME_SORT = 6;
REVERSE_TRACK_NAME_SORT = 7;
ARTIST_NAME_SORT = 8;
REVERSE_ARTIST_NAME_SORT = 9;
ALBUM_NAME_SORT = 10;
REVERSE_ALBUM_NAME_SORT = 11;
**/
this.mwidth = 10000;
this.trackmwidth = 10000;
this.albummwidth = 10000;
this.artistmwidth = 10000;
this.tracklist_trackmwidth = 10000;
this.tracklist_albummwidth = 10000;
this.tracklist_artistmwidth = 10000;
this.doSort = function( theArray, theField, reverseOrder ) {
theArray.sort(
function(a,b) {
return (a[theField]>b[theField]) ? 1 : ( (a[theField]<b[theField]) ? -1 : 0 )
} );
if( reverseOrder ) { theArray.reverse(); }
return theArray;
}
this.doFieldSort = function( theArray, theField, reverseOrder, callbackMethod ) {
callbackMethod(this.doSort(theArray,theField,reverseOrder));
}
this.doTrackNumSort = function( theArray, reverseOrder, callbackMethod ) {
theArray.sort(
function(a,b) {
if( a["index"] > b["index"] ) return 1;
else if( a["index"] < b["index"] ) return -1;
else {
if( a["discindex"] > b["discindex"] ) return 1;
else if( a["discindex"] < b["discindex"] ) return -1;
else {
if( a["albumname"] > b["albumname"] ) return 1;
else if( a["albumname"] < b["albumname"] ) return -1;
else {
return (a["artistdisplayname"]>b["artistdisplayname"]) ? 1 : ( (a["artistdisplayname"]<b["artistdisplayname"]) ? -1 : 0 )
}
}
}
} );
if( reverseOrder ) { theArray.reverse(); }
callbackMethod( theArray );
}
this.doDiscSort = function( theArray, reverseOrder, callbackMethod ) {
theArray.sort(
function(a,b) {
if( a["discindex"] > b["discindex"] ) return 1;
else if( a["discindex"] < b["discindex"] ) return -1;
else {
if( a["index"] > b["index"] ) return 1;
else if( a["index"] < b["index"] ) return -1;
else {
if( a["albumname"] > b["albumname"] ) return 1;
else if( a["albumname"] < b["albumname"] ) return -1;
else {
return (a["artistdisplayname"]>b["artistdisplayname"]) ? 1 : ( (a["artistdisplayname"]<b["artistdisplayname"]) ? -1 : 0 )
}
}
}
} );
if( reverseOrder ) { theArray.reverse(); }
callbackMethod( theArray );
}
this.doAlbumSort = function( theArray, reverseOrder, callbackMethod ) {
theArray.sort(
function(a,b) {
if( a["albumname"] > b["albumname"] ) return 1;
else if( a["albumname"] < b["albumname"] ) return -1;
else {
if( a["albumid"] > b["albumid"] ) return 1;
else if( a["albumid"] < b["albumid"] ) return -1;
else {
if( a["discindex"] > b["discindex"] ) return 1;
else if( a["discindex"] < b["discindex"] ) return -1;
else {
return (a["index"]>b["index"]) ? 1 : ( (a["index"]<b["index"]) ? -1 : 0 )
}
}
}
} );
if( reverseOrder ) { theArray.reverse(); }
callbackMethod( theArray );
}
this.doArtistSort = function( theArray, reverseOrder, callbackMethod ) {
theArray.sort(
function(a,b) {
if( a["artistdisplayname"] > b["artistdisplayname"] ) return 1;
else if( a["artistdisplayname"] < b["artistdisplayname"] ) return -1;
else {
if( a["albumname"] > b["albumname"] ) return 1;
else if( a["albumname"] < b["albumname"] ) return -1;
else {
if( a["discindex"] > b["discindex"] ) return 1;
else if( a["discindex"] < b["discindex"] ) return -1;
else {
return (a["index"]>b["index"]) ? 1 : ( (a["index"]<b["index"]) ? -1 : 0 )
}
}
}
} );
if( reverseOrder ) { theArray.reverse(); }
callbackMethod( theArray );
}
this.messageCount = 0;
this.messagesReceivedMapping = new Array();
this.sendMessage = function(url, content, callback){
var CURRENTMESSAGECOUNT = "" + (this.messageCount++);
var MESSAGEMAPPING = this.messagesReceivedMapping;
var wrappedCallback = function (requestObj, emptyData) {
if( MESSAGEMAPPING[CURRENTMESSAGECOUNT]=="true" ) { return; }
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
}
else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data = new Array();
data.exception = new Array();
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
data.hasError=true;
callback(data);
}
}
var theParameters = content.toQueryString()+"&sort="+this.sort;
theParameters += "&mwidth="+this.mwidth+"&albummwidth="+this.albummwidth+"&artistmwidth="+this.artistmwidth+"&trackmwidth="+this.trackmwidth;
if( content.todo=="get-children" && content.type=="tra" ) {
theParameters += "&tracklist_albummwidth="+this.tracklist_albummwidth+"&tracklist_artistmwidth="+this.tracklist_artistmwidth+"&tracklist_trackmwidth="+this.tracklist_trackmwidth;
}
new PeriodicalExecuter( function(pe) {
if( MESSAGEMAPPING[CURRENTMESSAGECOUNT]!="true" ) {
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
var data = new Array();
data.hasError = true;
callback(data);
}
MESSAGEMAPPING[CURRENTMESSAGECOUNT] = "true";
// Need to stop this thread the first time through...
pe.stop();
}, 30 /* 30s */ );
new Ajax.Request(url,{
onSuccess: wrappedCallback,
method: 'get',
parameters: theParameters
});
}
this.add = function ( ids, handler) {
handler = this.getSynchHandler( handler );
var action = "add";
var content = $H({
ids: ids,
todo: action
});
var callback = function (data){
handler(data);
}
this.sendMessage(this.url, content, callback);
}
this.remove = function (rcids, handler) {
var action = "remove";
var content = $H({
todo: action,
ids: rcids
});
var callback = function (data){
handler(rcids);
}
this.sendMessage(this.url, content, callback);
}
this.get = function (type, rcid, children, tiedToAction, handler) {
if( tiedToAction ) { handler = this.getSynchHandler( handler ); }
if (children) {
var action = "get-children";
} else {
var action = "get";
}
var content = $H({
todo: action,
parent: rcid,
type: type
});
var callback = function (data){
handler(data);
}
this.sendMessage(this.url, content, callback);
}
this.getMeta = function (ids, childIds, handler) {
handler = this.getSynchHandler( handler );
var action = "get-metadata";
var content = $H({
todo: action,
ids: ids,
childids: childIds
});
var callback = function (data){
handler(data);
}
this.sendMessage(this.metadataUrl, content, callback);
}
this.ACTIONID = 0;
this.getSynchHandler = function( anotherHandler ) {
var currentActionId = this.ACTIONID;
var currentLibInstance = this;
return function(data) {
if( currentLibInstance.ACTIONID == currentActionId ) {
anotherHandler(data);
}
else {
// alert( "Ignoring response this.ACTIONID="+currentLibInstance.ACTIONID+" currentActionId="+currentActionId );
}
}
};
this.newAction = function() {
this.ACTIONID ++;
};
}
LibraryManager.prototype.setMwidth = function (mwidth) { this.mwidth = mwidth; }
LibraryManager.prototype.setTrackMwidth = function (mwidth) { this.trackmwidth = mwidth; }
LibraryManager.prototype.setAlbumMwidth = function (mwidth) { this.albummwidth = mwidth; }
LibraryManager.prototype.setArtistMwidth = function (mwidth) { this.artistmwidth = mwidth; }
LibraryManager.prototype.setTracklistTrackMwidth = function (mwidth) { this.tracklist_trackmwidth = mwidth; }
LibraryManager.prototype.setTracklistAlbumMwidth = function (mwidth) { this.tracklist_albummwidth = mwidth; }
LibraryManager.prototype.setTracklistArtistMwidth = function (mwidth) { this.tracklist_artistmwidth = mwidth; }
LibraryManager.prototype.getLibraryByType = function (type, handler) {
this.get(type, null, null, true, handler);
}
LibraryManager.prototype.getChildrenByType = function (type, rcid, handler) {
this.get(type, rcid, true, true, handler);
}
LibraryManager.prototype.getChildrenByTypeUntied = function (type, rcid, handler) {
this.get(type, rcid, true, false, handler);
}
LibraryManager.prototype.getMetadata = function (ids, childIds, handler) {
this.getMeta(ids, childIds, handler);
}
LibraryManager.prototype.setSort = function (sort) {
this.sort = sort;
}
function ratingsManager( ) {
this.LAST_GET_REQUEST_TIME = 0;
this.LAST_GET_CALL_MADE_TIME = 0;
this.DEADTIME_WAIT_MSEC = 50;
this.REPEAT_WAIT_MSEC = 500;
this.url = "/webservice/json/ratings";
this.onGet = function( rcid, value ) { };
this.ratingsQueue = new Array();
this.ratingsMapping = new Array();
this.sendMessage = function(url, content, callback){
var wrappedCallback = function (requestObj, emptyData) {
if(requestObj.status == 200){
var text = requestObj.responseText;
if (text.substring(0,2) == "[{"){
var data = eval(text);
} else {
var data = eval('('+text+')');
}
callback(data);
} else {
var data;
data.exception.message="Bad response from ajax request. "
data.exception.code=requestObj.status
data.hasError=true;
callback(data);
}
}
new Ajax.Request(url,{
onSuccess: wrappedCallback,
method: 'get',
parameters: content.toQueryString()
});
}
this.setRating = function ( rcid, rating ) {
if(rating == this.getRatingValue(rcid)){
rating = 0;
}
this.ratingsMapping[rcid.toLowerCase()] = rating;
this.onGet( rcid, rating );
var content = $H({ rcid:rcid, rating:rating, action:"set-rating" });
this.sendMessage( rhapsodyURL + this.url, content, this.dataCallback );
}
this.getRatingValue = function( rcid ) {
if( this.ratingsMapping[rcid.toLowerCase()] ) {
return this.ratingsMapping[rcid.toLowerCase()];
}
}
this.getRating = function( rcid ) {
if( this.ratingsMapping[rcid.toLowerCase()] ) {
this.onGet( rcid, this.ratingsMapping[rcid.toLowerCase()] );
}
else {
this.LAST_GET_REQUEST_TIME = new Date().valueOf();
this.ratingsQueue.push(rcid);
}
}
this.getRatingObjects = function( startIndex, endIndex, type, callbackMethod ) {
var content = $H({ action:"get-objects", startIndex:startIndex, endIndex:endIndex, type:type });
this.sendMessage( rhapsodyURL + this.url, content, callbackMethod );
}
this.getSummary = function( callbackMethod ) {
var content = $H({ action:"get-summary" });
this.sendMessage( rhapsodyURL + this.url, content, callbackMethod );
}
this.getNotYetRated = function( callbackMethod ) {
var content = $H({ action:"recent-not-yet-rated" });
this.sendMessage( rhapsodyURL + this.url, content, callbackMethod );
}
this.getForgotten = function( callbackMethod ) {
var content = $H({ action:"have-you-forgotten" });
this.sendMessage( rhapsodyURL + this.url, content, callbackMethod );
}
this.getRandomPlaylist = function( maxNum, include5, include4, include3, include2, include1, includeNeg1, weight, rcid, callbackMethod ) {
this.getRandomPlaylistForUser( maxNum, include5, include4, include3, include2, include1, includeNeg1, weight, rcid, null, callbackMethod );
}
this.getRandomPlaylistForUser = function( maxNum, include5, include4, include3, include2, include1, includeNeg1, weight, rcid, rhapuserid, callbackMethod ) {
var artistValue = rcid.toLowerCase().indexOf("art.")==0 ? rcid : "";
var genreValue = rcid.toLowerCase().indexOf("g.")==0 ? rcid : "";
var content = $H({ action:"get-random-playlist", maxnum:maxNum, include5:include5,
include4:include4, include3:include3, include2:include2,
include1:include1, includeNeg1:includeNeg1, weight:weight,
artist:artistValue, genre:genreValue, rhapuserid:rhapuserid });
this.sendMessage( rhapsodyURL + this.url, content, callbackMethod );
}
this.dataCallback = function( data ) {
for( var i=0 ; i<data.length ; i++ ) {
ratingsMgr.ratingsMapping[ data[i].rcid.toLowerCase() ] = data[i].value;
ratingsMgr.onGet( data[i].rcid, data[i].value );
}
}
this.queueWatcherThread = function() {
var RIGHTNOW = new Date().valueOf();
if( this.ratingsQueue.length
&& RIGHTNOW-this.LAST_GET_REQUEST_TIME > this.DEADTIME_WAIT_MSEC
&& RIGHTNOW-this.LAST_GET_CALL_MADE_TIME > this.REPEAT_WAIT_MSEC ) {
this.LAST_GET_CALL_MADE_TIME = RIGHTNOW;
var content = $H({ rcid:this.ratingsQueue, action:"get-ratings" });
this.ratingsQueue = new Array();
this.sendMessage( rhapsodyURL + this.url, content, this.dataCallback );
}
setTimeout( "ratingsMgr.queueWatcherThread()", 50 );
}
this.queueWatcherThread();
}
var ratingsMgr = new ratingsManager();
/* begin rating widget */
function canRate(){
try{
if(getAccountType() == "RHAPSODY_PREMIUM_USER"){
return true;
}
}catch(e){}
try{
if((typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && rhapsodyMember.isRadioPremiumUser){
return true;
}
}catch(e){}
return false;
}
function showRhap25Msg(){
var isRhap25;
try{
if((typeof rhapsodyMember != 'undefined' ) && rhapsodyMember.isLoggedIn && !rhapsodyMember.isRadioPremiumUser && !rhapsodyMember.isAnonymousUser){
return true;
}
}catch(e){}
try{
if(getAccountType() == "RHAPSODY_FREE_USER"){
return true;
}
}catch(e){}
return false;
}
ratingsMgr.onGet = function( rcid, value ) {
noclickSetRating(rcid,value);
}
var defaultRatingClass="ratings_0";
function mouseoverRating(uid,pos,iconsize){
var theVisRatingClass = "ratings_"+pos+"_"+iconsize;
document.getElementById(uid).className = theVisRatingClass;
}
function mouseoutRating(rcid){
if(canRate()){
noclickSetRating(rcid,ratingsMgr.getRatingValue(rcid));
}else{
noclickSetRating(rcid,0);
}
}
function mouseclickRating(rcid,rating,uid){
if(canRate()){
noclickSetRating(rcid,rating);
ratingsMgr.setRating(rcid,rating);
}else{
noclickSetRating(rcid,0);
if( RhapsodyDom.bodyLoaded ) renderRatingUpgrade(rcid,uid);
else RhapsodyUtility.addLoadEvent( function() { renderRatingUpgrade(rcid,uid); } );
}
}
function noclickSetRating(rcid,rating){
if(!rating){
rating = 0;
}
if(numWidgetsPerRcid[rcid] > 0){
for(var i = 1; i < numWidgetsPerRcid[rcid]+1; i++){
var eachRcid = rcid+"."+i;
if(document.getElementById(eachRcid)){
document.getElementById(eachRcid).className = "ratings_"+rating+"_"+getSizeByRcid(eachRcid);
}
}
}else{
document.getElementById(rcid).className = "ratings_"+rating+"_"+getSizeByRcid(rcid);
}
}
var numWidgetsPerRcid = new Array();
function getNextWidgetId( rcid ) {
if( numWidgetsPerRcid[rcid] ) {
numWidgetsPerRcid[rcid]++;
}else{
numWidgetsPerRcid[rcid] = 1;
}
return rcid+"."+numWidgetsPerRcid[rcid];
}
var rcidSizeMap = new Array();
function mapRcidsAndSizes(rcid,iconsize){
var eachMapItem = rcid+":"+iconsize;
rcidSizeMap.push(eachMapItem);
}
function getSizeByRcid(rcid){
for(var i = 0; i < rcidSizeMap.length; i++){
var sizeMap = rcidSizeMap[i];
var theRcid = sizeMap.split(":")[0];
var theSize = sizeMap.split(":")[1];
if(rcid == theRcid){
return theSize;
}
}
}
function getRateType(rcid){
var type = rcid.substring(0,rcid.indexOf(".")).toLowerCase();
switch(type){
case "art":{
return "artist";
}case "alb":{
return "album";
}case "tra":{
return "track";
}case "g":{
return "genre";
}
}
}
function openRatingsUpgradePage(theUrl) {
var newWin;
newWin = window.open( theUrl, "_blank", "toolbar=yes,location=yes,directories=yes,resizable=yes,scrollbars=yes" );
newWin.focus();
destroyRatingUpgrade();
}
var ratingsDialog;
function destroyRatingUpgrade(){
if(ratingsDialog){
with( ratingsDialog ){
toggleMeddlesomeElements();
}
ratingsDialog.removeHoldingElement();
ratingsDialog = null;
}
}
function renderRatingUpgrade(rcid,uid){
destroyRatingUpgrade();
var baseElement = document.getElementById(uid);
var messageDiv = document.getElementById("ru_"+uid);
var upgradeMsg = 'To rate music, please <a href="#" onclick="javascript:signInOut(\'signin\'); destroyRatingUpgrade();">sign in</a> to Rhapsody.<br/><br/>Don\'t have Rhapsody? <a href="javascript:openRatingsUpgradePage(\''+upsellURL+'?src=rcom_rat\');">Try it free</a>.<br/>';
if(showRhap25Msg()){
upgradeMsg = 'To rate music, <a href="javascript:openRatingsUpgradePage(\''+upsellURL+'?src=rcom_rat25\');">upgrade for a free trial</a>.<br/>';
}
var messageDivHTML = '<div class="ratingsUpgrade" id="ru_'+uid+'">'+
'<strong>Sign in or Upgrade</strong><br/><br/>'+
upgradeMsg+
'<a href="#" style="position:absolute; bottom:10px; right:10px;" onclick="destroyRatingUpgrade(); return false;" class="s notBold">close</a></div>';
if(DialogBox){
ratingsDialog = new DialogBox( { spawnFrom:baseElement, spawnFromOffset:[0,0], htmlContent:messageDivHTML} );
with( ratingsDialog ){
toggleMeddlesomeElements();
}
ratingsDialog.adjustForBleed({alignBottomOnFlip: true});
ratingsDialog.show();
}
}
function getRatingWidget(rcid,iconsize){
if(!iconsize){ iconsize = "big"; }
rcid = rcid.replace(rcid.charAt(0),rcid.charAt(0).toUpperCase());
var uniqueid = getNextWidgetId(rcid);
mapRcidsAndSizes(uniqueid,iconsize);
var ratingWidgetHTML='<div style="text-decoration:none;" id="'+uniqueid+'" class="ratings_0_'+iconsize+'" title="Rate this '+getRateType(rcid)+'">'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'-1\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'-1\',\''+uniqueid+'\'); return false;"></a>'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'1\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'1\',\''+uniqueid+'\'); return false;"></a>'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'2\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'2\',\''+uniqueid+'\'); return false;"></a>'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'3\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'3\',\''+uniqueid+'\'); return false;"</a>'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'4\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'4\',\''+uniqueid+'\'); return false;"></a>'+
'<a href="#" class="ratingslistitem_'+iconsize+'" onmouseover="mouseoverRating(\''+uniqueid+'\',\'5\',\''+iconsize+'\')" onmouseout="mouseoutRating(\''+rcid+'\')" onclick="mouseclickRating(\''+rcid+'\',\'5\',\''+uniqueid+'\'); return false;"></a>'+
'</div>';
if(canRate()){
setTimeout("ratingsMgr.getRating('"+rcid+"')",500);
}
return ratingWidgetHTML;
}
/* end rating widget */
RhapsodyShareManager = {
twitterHeight: 436,
twitterWidth: 774,
facebookHeight: 436,
facebookWidth: 626,
overlayWidth: 395,
overlayHeight: 380,
iframeWidth: 395,
iframeHeight: 340,
_shareMask: null,
_windowVariant: null,
genericJsonMgr: new Object(),
instanceName: "RhapsodyShareManager",
init: function(){
cThis = this; /* the actual instance of "this" */
cThis.genericJsonMgr = new genericXmlManager();
},
_utilGetWindowTop: function(height){
var top = ((screen.height/2)-(height/2));
return top;
},
_utilGetWindowLeft: function(width){
var left = ((screen.width/2)-(width/2));
return left;
},
_utilGetMediaTypeFlag: function(sharetype){
/* needs to return an expected type. if it's not, fix and return. */
switch(sharetype){
case "video":
return "musicvideo";
break;
default: /* is an expected type */
return sharetype;
}
},
_utilGetTwitterMessage: function( passedTitle, subtitle, sharetype ){
var message = "";
if(sharetype == "video" || sharetype == "musicvideo" || sharetype == "musicvideoplaylist"){
message = "Watching "+unescape(passedTitle);
}else{
message = "Listening to "+unescape(passedTitle);
}
if(subtitle && subtitle != undefined && subtitle != " "){
message+=" by "+unescape(subtitle);
}
return message;
},
_utilCreateShareableUrl: function( rcids , sharetype ){
var shareableUrl = rhapsodyStreamURL + "/goto?rcid=" + rcids;
var cleanShareType = this._utilSanitizeShareType(sharetype);
if(cleanShareType == "album" || cleanShareType == "albums" || cleanShareType == "tracks" || cleanShareType == "track" || cleanShareType == "playlist" || cleanShareType == "radio"){
shareableUrl += "&variant=play";
}
/* User playlists are different (playlist central playlists) */
if( cleanShareType == "userplaylist"){
shareableUrl = rhapsodyPlayURL + "/playlistcentral/playlistdetail?tracks=" + rcids;
}
/* and member playlists are different yet again (myrhapsody and member pages) */
if(cleanShareType == "myrhapsodyplaylist"){
var sharetype = sharetype.split("_");
shareableUrl = rhapsodyStreamURL + "/_playlist?id=" + rcids;
if(sharetype[1] && sharetype[1] != "undefined" && sharetype[1] != undefined){
shareableUrl += "&u=" + sharetype[1];
}
}
return shareableUrl;
},
_utilSanitizeShareType: function(sharetype){
if(sharetype.indexOf("myrhapsodyplaylist") >= 0){
var sharetype = sharetype.split("_");
return sharetype[0];
}else{
return sharetype;
}
},
shareItem: function( rcids, passedTitle, subtitle, shareto, sharetype ){
switch(shareto){
case "twitter":
this._buildShareForTwitter( rcids, passedTitle, subtitle, sharetype );
break;
case "facebook":
this._buildShareForFacebook( rcids, sharetype );
break;
default: /* rhapcom */
this._buildShareForRhapcom( rcids, passedTitle, subtitle, sharetype );
}
},
_buildShareForTwitter: function( rcids, passedTitle, subtitle, sharetype ){
var msg = this._utilGetTwitterMessage( passedTitle, subtitle, sharetype );
var longurl = this._utilCreateShareableUrl( rcids, sharetype );
this._shareToTwitter( msg , longurl );
},
_buildShareForFacebook: function( rcids, sharetype ){
this._shareToFacebook( this._utilCreateShareableUrl( rcids, sharetype ) );
},
_buildShareForRhapcom: function( rcids, passedTitle, subtitle, sharetype ){
this._shareFromRhapcom( rcids, passedTitle, subtitle, sharetype );
},
_shareToTwitter: function( msg, longurl ){
var passedUrl = longurl;
var listeningToMsg = msg;
var top = this._utilGetWindowTop(this.twitterHeight);
var left = this._utilGetWindowLeft(this.twitterWidth);
window.open(rhapsodyStreamURL + "/share/twitter.html?msg="+encodeURIComponent(msg)+"&longurl="+encodeURIComponent(longurl), 'twittersharer', 'toolbar=0,status=0,width=774,height=436,top=' + top + ',left=' + left );
RhapsodyShareManager._sendReportingEvent( 'Twitter' );
return false;
},
_shareToFacebook: function( passedUrl ){
var top = this._utilGetWindowTop( this.facebookHeight) ;
var left = this._utilGetWindowLeft( this.facebookWidth );
window.open( 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent( passedUrl ) + '&t=' + encodeURIComponent( document.title ), 'sharer', 'toolbar=0,status=0,width=626,height=436,top=' + top + ',left=' + left );
RhapsodyShareManager._sendReportingEvent( 'Facebook' );
return false;
},
_shareFromRhapcom: function( rcids, pTitle, subtitle, sharetype ){
var passedTitle = unescape( pTitle );
if( subtitle && subtitle != " " && ( typeof subtitle != 'undefined' ) ){
passedTitle += " - " + unescape( subtitle) ;
}
var mediaTypeFlag = this._utilGetMediaTypeFlag(sharetype);
var passedUrl = this._utilCreateShareableUrl( rcids , sharetype );
this._showShareOverlay( rcids, mediaTypeFlag, passedTitle, passedUrl );
RhapsodyShareManager._sendReportingEvent( 'Rhapcom' );
},
_sendReportingEvent: function( serviceName ){
RhapsodyTracking.sendLinkEvent( {
eVar17: 'Nav: Click: Share: ' + serviceName,
prop18: 'E: Nav: Click: Share: ' + serviceName
},
{
type: 'custom',
linkName: 'Navigation',
events: 'event8'
} );
},
renderButtons: function( rcids, passedTitle, subtitle, sharetype, size, disabled ){
document.write( this._getButtonHtml( rcids , passedTitle, subtitle, sharetype, size, disabled ) );
},
renderButtonsJS: function( rcids, passedTitle, subtitle, sharetype, size, disabled ){
return this._getButtonHtml( rcids , passedTitle, subtitle, sharetype, size, disabled );
},
_getButtonHtml: function( rcids, passedTitle, subtitle, sharetype, size, disabled ){
if(passedTitle.indexOf("&#039;") > 0){
/* there are some instances where this still gets through, catch and fix here */
passedTitle = passedTitle.replace(/&#039;/g, "'");
}
var imgDir = staticPath + "images/shareicons/";
var sizeStateString = "";
var theHtml="";
var twitterIcon="";
var facebookIcon="";
var rhapcomIcon="";
if( size == "" || ( typeof size == 'undefined' ) ){
sizeStateString += "_med";
} else {
sizeStateString += "_" + size;
}
if( disabled ){
sizeStateString+="_disabled";
twitterIcon = imgDir + "icon_twitter" + sizeStateString + ".jpg";
facebookIcon = imgDir + "icon_facebook" + sizeStateString + ".jpg";
rhapcomIcon = imgDir + "icon_email" + sizeStateString + ".jpg";
theHtml =
'<img src="' + facebookIcon + '" class="shareFacebook' + sizeStateString + '"/>' +
'<img src="' + twitterIcon + '" class="shareTwitter' + sizeStateString + '"/>' +
'<img src="' + rhapcomIcon + '" class="shareRhapcom' + sizeStateString + '"/>';
} else {
twitterIcon = imgDir+"icon_twitter"+sizeStateString+".jpg";
facebookIcon = imgDir+"icon_facebook"+sizeStateString+".jpg";
rhapcomIcon = imgDir+"icon_email"+sizeStateString+".jpg";
theHtml =
'<a href="#" onclick="RhapsodyShareManager.shareItem(\'' + rcids + '\' , \'' + escape(passedTitle) + '\', \'' + escape(subtitle) + '\', \'facebook\' , \'' + sharetype + '\'); return false;" title="Post to Facebook"><img title="Post to Facebook" src="' + facebookIcon + '" class="shareFacebook' + sizeStateString + '" \/><\/a>' +
'<a href="#" onclick="RhapsodyShareManager.shareItem(\'' + rcids + '\' , \'' + escape(passedTitle) + '\', \'' + escape(subtitle) + '\', \'twitter\' , \'' + sharetype + '\'); return false;" title="Post to Twitter"><img title="Post to Twitter" src="' + twitterIcon + '" class="shareTwitter' + sizeStateString + '" \/><\/a>' +
'<a href="#" onclick="RhapsodyShareManager.shareItem(\'' + rcids + '\' , \'' + escape(passedTitle) + '\', \'' + escape(subtitle) + '\', \'rhapcom\' , \'' + sharetype + '\'); return false;" title="Share by link or HTML"><img title="Share by link or HTML" src="' + rhapcomIcon + '" class="shareRhapcom' + sizeStateString + '"\/><\/a>';
}
return theHtml;
},
_showShareOverlay: function( rcids, mediaTypeFlag, passedTitle, passedUrl ){
var overlayHtmlContent = '';
var closeXSpan = '<div class="shareOverlayClose"><a href="#" onclick="RhapsodyShareManager.ModalDialogBoxManager.destroy(); return false;">Close <span>X<\/span><\/a><\/div>';
var mShareOverlayIFrame = rhapsodyStreamURL + '/share/shareoverlay.html?prepop=overlay&mediaTypeFlag=' + mediaTypeFlag + '&mediaId=' + rcids + '&title=' + encodeURIComponent(passedTitle) + '&passedurl=' + encodeURIComponent(passedUrl);
if( this.getWindowVariant() ){
mShareOverlayIFrame += '&variant=' + this.getWindowVariant();
}
var closeXSpanBottom = '<div class="shareOverlayCloseBottom"><a href="#" onclick="RhapsodyShareManager.ModalDialogBoxManager.destroy(); return false;">Close<\/a><\/div>';
overlayHtmlContent = closeXSpan;
overlayHtmlContent += '<iframe id="shareOverlayIFrame" src="' + mShareOverlayIFrame + '" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" width="' + this.iframeWidth + '" height="' + this.iframeHeight + '" style="overflow: hidden; background-color: #0099CC;">';
overlayHtmlContent += 'Your browser does not appear to support iframes.';
overlayHtmlContent += '<\/iframe>';
RhapsodyShareManager.ModalDialogBoxManager.init(overlayHtmlContent);
},
getWindowVariant: function(){
return this._windowVariant;
},
setWindowVariant: function( wv ){
this._windowVariant = wv;
},
ModalDialogBoxManager: {
modalDialogBoxInstance: null,
_dialogBoxOverrides: null,
setDialogBoxOverrides: function( dbOverrideObj ){
this._dialogBoxOverrides = dbOverrideObj;
},
init: function(overlayHtmlContent){
if( overlayHtmlContent != null && overlayHtmlContent != 'undefined' && overlayHtmlContent != '' ){
var dbWidth = ( this._dialogBoxOverrides && this._dialogBoxOverrides.dbWidth )? this._dialogBoxOverrides.dbWidth: RhapsodyShareManager.overlayWidth;
var dbClassName = ( this._dialogBoxOverrides && this._dialogBoxOverrides.dbClassName )? this._dialogBoxOverrides.dbClassName: null;
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance = new DialogBox(
{
width: dbWidth + 'px',
height: RhapsodyShareManager.overlayHeight+'px',
maskOpacityPercent: 60,
holdingElementBgColor: '#363636',
zIndex: '999999999',
maskBgColor: '#000',
maskZIndex: '10000',
htmlContent: overlayHtmlContent,
elementClassName: dbClassName
}
);
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.centerInPage( .90 );
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.toggleMeddlesomeElements();
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.setMask( true );
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.setShadow( true );
Event.observe( window, 'scroll', function(e){
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.centerInPage( .90 );
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.setMask( true );
} );
Event.observe( window, 'resize', function(e){
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.centerInPage( .90 );
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.setMask( true );
} );
}
},
destroy: function(){
Event.unloadCache();
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.toggleMeddlesomeElements();
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance.destroy();
RhapsodyShareManager.ModalDialogBoxManager.modalDialogBoxInstance = null;
}
}
}
RhapsodyShareManager.init();
/* for the flash player */
function ShareItem( rcids, passedTitle, subtitle, shareto, sharetype ){
RhapsodyShareManager.shareItem( rcids, passedTitle, subtitle, shareto, sharetype );
}