var aPopups = new Array();      // Stores the percentage of the screen that should be used for the popup
aPopups ['none'       ] = [.33, .33, -1, -1, .5, false];  // w, h, x (-1 is center), y, bg opac, click outside to cancel
aPopups ['sequel'     ] = [.50, .50, -1, -1, .5, false];
aPopups ['uploadSong' ] = [.60, .9, -1, -1, .5, false];
aPopups ['uploadVideo'] = [.50, .75, -1, -1, .5, false];

aPopups ['tc'      ] = [.60, .5, -1, -1, .5, false];
aPopups ['privacy' ] = [.60, .9, -1, -1, .5, false];

aPopups ['link'      ] = [800, 300, -1, -1, .5, true ];

aPopups ['register'  ] = [.50, .8, -1, -1, .5, true ];
aPopups ['vote'      ] = [500, 350, -1, -1, .5, true ];

var lastPopup = 'none';

function showPopup (which) {
	lastPopup = which;
	popupOpen = true;
	ajaxGetHTML ('getPopup', lastPopup, null, 'popup_div', function() {fnPopupLoaded(); resized();});
}

function hidePopup() {
	popupOpen = false;
	resized();
	$('darken_div').set ('opacity', 0);
	$('popup_div' ).set ('opacity', 0);
	showPlayer();
	$('popup_div' ).innerHTML = '';
	$('darken_div').removeEvent('mousedown', fnClickedOutsidePopup);
}

function siSpecialFunc(headerText, submitText) {
	var mode = 0;
	var siEmail = $('siEmail_inp').get('value');
	if (siEmail == '') {
		alert ("Please enter your registration email address and try again");
	} else {
		if (headerText.indexOf('Password') != -1) {
			mode = 1;
		} else if (headerText.indexOf('Validation') != -1) {
			mode = 2;
		}
		$('siMode_inp').set('value', mode);
		
		ajaxCheckEmail(siEmail, function(response) {
			var emailResponse = JSON.decode(response);
//			alertObject(emailResponse);
			if (emailResponse.valid) {
				if (emailResponse.in_use) {
					if ((mode == 1) & (!emailResponse.has_password)) {
						alert ('This email does not have a password');
						hideModal('si_div');
					} else if ((mode == 2 ) & (emailResponse.validated == 1)){
						alert ('Your email address was already validated.  You only need to validate once.');
						hideModal('si_div');
					} else {
						$('siEmail_inp').disabled = true;
						$('siPassword_span'       ).setStyle('display', 'none');
						$('siRemember_span'       ).setStyle('display', 'none');
						$('siPasswordReset_span'  ).setStyle('display', 'none');
						$('siValidationEmail_span').setStyle('display', 'none');
						$('siSecurity_tbl'        ).setStyle('display', 'block');
						$('si_form').siSecurityQuestion_sel.value = emailResponse.security_question;
						$('siHeader_span'         ).set('html' , headerText);
						$('siSubmit_inp'          ).set('value', submitText);
						$('siUserId_inp'          ).set('value', emailResponse.user_id);
						$('siAnswer_inp'          ).set('value', emailResponse.security_answer);
					}
				} else {
					alert ('That email address is not registered');
					hideModal('si_div');
				}
			} else {
				alert ('Invalid email address');
				hideModal('si_div');
			}
		
		});
	}
}

function showModal(which, caller, onSuccess, onFailure) {
	modalSuccessFunction = (onSuccess != null) ? onSuccess : function() {};   // Check for defined success & failure functions
	modalFailureFunction = (onFailure != null) ? onFailure : function() {};
	
	$('darken_div').tween ('opacity', .5);
	$(which).tween ('opacity', 1);
	hidePlayer();
	modalCaller = caller;
	
	switch (which) {
		case 'cs_div':
		break;
			
		case 'si_div':
			fnFocus('siEmail_inp');
			$('siMode_inp').set('value', 0);  // Mode 0=signin, 1=password reset, 2=validation email
			$('siEmail_inp').disabled = false;
			$('siPassword_span'       ).setStyle('display', 'inline');	// Reset all fields to normal loook
			$('siRemember_span'       ).setStyle('display', 'inline');
			$('siSecurity_tbl'        ).setStyle('display', 'none');
			$('siPasswordReset_span'  ).setStyle('display', 'inline');
			$('siValidationEmail_span').setStyle('display', 'inline');
			$('siHeader_span'         ).set('html' , 'Sign In');
			$('siSubmit_inp'          ).set('value', 'Sign In');
		
			$('siPasswordReset_span'  ).removeEvents('mousedown');
			$('siValidationEmail_span').removeEvents('mousedown');
			$('siPasswordReset_span'  ).addEvent('mousedown', function() { siSpecialFunc('Request Password Reset', 'Go');});
			$('siValidationEmail_span').addEvent('mousedown', function() { siSpecialFunc('Re-Send Validation Email', 'Go');});

		break;
			
		case 'tcPopup_div':
			lastTc = 0;
			var navHTML = '';
			$('tcPopupContents_div').set('html', '');
			for (var i=0; i<aTcPopupNav.length; i++) {
				navHTML += '<span id="tcPopupNav' + i + '" class="tcLink">' + aTcPopupNav[i][0] + '</span><br /><br />';
			}
			$('tcPopupNav_td').set('html', navHTML);
			
			$('tcPopupNav0').addClass('tcSelected');
			
			for (var i=0; i<aTcPopupNav.length; i++) {
				$('tcPopupNav' + i).addEvent('mousedown', function() {
					currentTc = parseInt(this.id.match (/[0-9]+/));
					if (currentTc != lastTc) {
						$('tcPopupContents_div').set('html', '');
						$('tcPopupNav' + lastTc).removeClass('tcSelected');
						this.addClass('tcSelected');
						lastTc = currentTc;
						ajaxGetHTML ('getPopup', aTcPopupNav[currentTc][1], null, 'tcPopupContents_div', function() {});
					}
				});
			}
			
			ajaxGetHTML ('getPopup', caller, null, 'tcPopupContents_div', function() {});//{fnPopupLoaded(); resized();});
//			ajaxGetHTML ('getPopup', caller, null, 'tcPopupContents_div', function() {});//{fnPopupLoaded(); resized();});
		break;
		
		case 'contact_div':
			if (contactMode == 0) $('contactHeader_div').set('html', 'Contact Us');
			if (contactMode == 1) $('contactHeader_div').set('html', 'Report Offensive Material');
			if (contactMode == 2) $('contactHeader_div').set('html', 'Suggest A City');			
		break;
	}
}

function hideModal(which) {
	if (!popupOpen) {
		$('darken_div').set ('opacity', 0);
		if (currentPage == 'main') showPlayer();
	}
		$(which).set ('opacity', 0);
}

function modalOk(which) {
	$$('.popupInp').each( function(item) { item.removeClass('alert'); } );
	var foundError = false;

	switch (which) {
		case 'cs_div':			// Show the values in the correct fields
			var country = $('csCountry_sel').get('value');
			var city    = $('csCity_sel'   ).get('value');
			if ((country != 'all') & (city != 'all') & (city != 'Choose...')) {
//				$(modalCaller+'Id_div').set('html', city);

//				$(modalCaller+'Id_inp').value = city;
				selectedCityId = city;
				if (modalCaller == 'lbCity') fnSubmitSearchForm();
	
				ajaxGetCityInfo(selectedCityId, function(response) {	// Set city name
						$(modalCaller+'Name_td').innerHTML = JSON.decode(response).city_name;
						if (modalCaller == 'lbCity') {  // If we need to update the user in the database
							user.city_id = city;
//							ajaxReg(user, 'update', function() {});    Disabled because it was messing up password
							fnChangeHomeCity(city);
						} else if (modalCaller == 'regCity') {	// If we're registering, update the language bar too
							tmpUser.city_id = city;
//							$('lbCityId_td').value = city;
							$('lbCityName_td').set('html', JSON.decode(response).city_name);
							fnChangeHomeCity(city);
						} else if (modalCaller == 'landingCity') {
							$('lbCityName_td').set('html', JSON.decode(response).city_name);
							fnChangeHomeCity(city);
						}
						hideModal(which);
					});
				
			} else {
				$('csCity_sel').addClass('alert');
			}
		break;
			
		case 'si_div':
//			alert ('Mode is ' + $('siMode_inp').get('value'));
			var mode     = $('siMode_inp').get('value');
			var userId   = $('siUserId_inp').get('value');
			var email    = $('siEmail_inp'   ).get('value');
			var password = $('siPassword_inp').get('value');
			signInRemember = $('siRemember_chk').checked;
//			alert ("Loggin in: " + email + ", " + password + ".");

			if (mode == 0) {
				fnSignIn(email, password, false, modalSuccessFunction, modalFailureFunction);
			} else if ((mode == 1) | (mode == 2)) {
				var origAnswer = $('siAnswer_inp'        ).get('value').toLowerCase();
				var newAnswer  = $('siSecurityAnswer_inp').get('value').toLowerCase();
				if (origAnswer == newAnswer) {			// If they got the security question right
					if (mode == 1) {
						ajaxResetPassword (userId, function(response) {
								if (response == 'success') {
									alert ('An email with your new password has been sent');
								} else {
									alert ('Error.  Password has not been reset');
								}
								hideModal('si_div');
						});
					} else {
						ajaxResendValidationEmail (userId, function(response) {
								if (response == 'success') {
									alert ('Validation email has been sent');
								} else {
									alert ('Error.  Validation email has not been sent');
								}
								hideModal('si_div');
						});
					}
				} else {								// If they didn't
					alert ('You answered the security question incorrectly.');
					hideModal('si_div');
				}
				
			} else {
				alert ('Bad signin mode.  Please report.');
				hideModal('si_div');
			}

		break;
			
		case 'tcPopup_div':
			hideModal(which);
		break;
		
		case 'contact_div':
			var emailObject = new Object;
			emailObject.contactName     = $('contactName_inp'    ).get('value');
			emailObject.contactCompany  = $('contactCompany_inp' ).get('value');
			emailObject.contactEmail    = $('contactEmail_inp'   ).get('value');
			emailObject.contactComments = $('contactComments_inp').get('value');
			emailObject.to = '';
			
			if (emailObject.contactName     == '') { foundError = true; $('contactName_inp'    ).addClass('alert'); }
			if (emailObject.contactEmail    == '') { foundError = true; $('contactEmail_inp'   ).addClass('alert'); }
			if (emailObject.contactComments == '') { foundError = true; $('contactComments_inp').addClass('alert'); }
			
			if (contactMode == 0) {
				emailObject.to = 'contact@citylovemusic.com'   // Contact Us
				emailObject.subject = "Message to CityLove - Contact Us";
			} else if (contactMode == 1) {
				emailObject.to = 'report@citylovemusic.com'     // Report Offensive Material
				emailObject.subject = "Message to CityLove - Report Offensive Material";
			} else if (contactMode == 2) {
				emailObject.to = 'addcity@citylovemusic.com'   // Suggest A City
				emailObject.subject = "Message to CityLove - Suggest A City";
			} else {
				foundError = true;
			}
					
			if (!foundError) {
				ajaxSendSystemEmail(emailObject, function() {} );
//				alert ('Email disabled for test purposes.\nIt would be sent to: ' + emailObject.to);
				alert ('Your message has been sent.');
				hideModal(which);
			}
		break;
	}
	
}

function fnChangeHomeCity(city) {
	browserSettings.city_id = city;
	fnWriteAccessCookie('ac0');
	ajaxGetBanners(null);
}

function modalCancel(which) {
	hideModal(which);
}

function updatePopup() {
	var w = aPopups[lastPopup][0];
	var h = aPopups[lastPopup][1];
	var x = aPopups[lastPopup][2];
	var y = aPopups[lastPopup][3];
	var dx = parseInt((winCoords.width  - containerDims[2]) / 2);
	var dy = parseInt((winCoords.height - containerDims[3]) / 2);

	var popupWidth  = (w > 1) ? w : parseInt(containerDims[2] * w);  // Check if it's a percentage or a # of pixels
	var popupHeight = (h > 1) ? h : parseInt(containerDims[3] * h);
	
	var popupX = (x != -1) ? x : parseInt((containerDims[2] - popupWidth )/2) + dx;
	var popupY = (y != -1) ? y : parseInt((containerDims[3] - popupHeight)/2) + dy;

	$('popup_div').setStyles({'left'   : popupX,
							  'top'    : popupY,
							  'width'  : popupWidth,
							  'height' : popupHeight});
}

function fnPopupLoaded() {
	hidePlayer();
	$('darken_div').set ('opacity', aPopups[lastPopup][4]);
	$('popup_div' ).set ('opacity', 1);

	switch (lastPopup) {
		case 'register':
			$('regTc_span').removeEvents('mousedown');
			
			$('regTc_span').addEvent('mousedown', function() {
				aTcPopupNav.length = 0;
				aTcPopupNav[0] = ['General User Terms'       , 'generalTerms'];
				aTcPopupNav[1] = ['Songwriter / Artist Terms', 'songwriterTerms'];
				aTcPopupNav[2] = ['Music Video Terms'        , 'musicVideoTerms'];
				aTcPopupNav[3] = ['Media Terms'              , 'mediaTerms'];
				aTcPopupNav[4] = ['Songwriting Agreement'    , 'songwriterAgreement'];
				aTcPopupNav[5] = ['Master Use Agreement'     , 'masterUseAgreement'];
				aTcPopupNav[6] = ['Music Video Agreement'    , 'musicVideoAgreement'];
				showModal('tcPopup_div', 'generalTerms', null, null);
			 } );

			tmpUser = cloneObject(user);
			bNewReg = (tmpUser.id == -1) ? true : false;		// Are we modifying an existing registration?
			$('regEmail_inp').disabled = false;
			
			var hideOpac = .2;

			if (!bNewReg) {								// If it's an existing registration
				oldAccessLevel = parseInt(tmpUser.access_level);
				newAccessLevel = oldAccessLevel;
				$('regWriter_chk'      ).checked = oldAccessLevel & 2;
				$('regVideoMaker_chk'  ).checked = oldAccessLevel & 4;
				$('regMediaCompany_chk').checked = oldAccessLevel & 8;

				if ((oldAccessLevel & 2) | (oldAccessLevel & 4) ) {
					$('registerWarning_div').set('opacity', 1);
				} else {
					$('registerWarning_div').set('opacity', 0);
				}

				if (oldAccessLevel & 2) {
					$('regSuggestCity_text').tween('opacity', 1);
				} else {
					$('regSuggestCity_text').tween('opacity', 0);
				}

				opac = ((oldAccessLevel & 2) | (oldAccessLevel & 4) | (oldAccessLevel & 8)) ? 1 : hideOpac;
				$('regContributor_tbl'     ).set('opacity', opac);
				$('regSecurity_tbl'        ).set('opacity', opac);
				$('regAgree_tbl'           ).set('opacity', opac);
				$('regSecurityQuestion_sel').set('opacity', opac);
//				$('regCompanyType_sel'     ).set('opacity', opac);

				opac = (oldAccessLevel & 8) ? 1 : hideOpac;
				$('regMediaCompany_tbl').set('opacity', opac);

				$('regEmail_inp'           ).set('value', tmpUser.email);
				$('regPassword_inp'        ).set('value', ''); //tmpUser.password);
				$('regRetypePassword_inp'  ).set('value', ''); //tmpUser.password);
				$('regFirstName_inp'       ).set('value', tmpUser.first_name);
				$('regLastName_inp'        ).set('value', tmpUser.last_name);
				$('regSecurityQuestion_sel').set('value', tmpUser.security_question);
				$('regSecurityAnswer_inp'  ).set('value', tmpUser.security_answer);
				if (regNeedCompanyInfo) {   				 // If it's a Media Company Registration
					$('regCompanyName_inp' ).set('value', tmpUser.company_name);
					$('regCompanyType_sel' ).set('value', tmpUser.company_type);
				}
				$('regEmail_inp').disabled = true;
				
			} else {									// If it is a new registration
				newAccessLevel = 1;
				tmpUser.city_id = selectedCityId;
				var opac = hideOpac;
				$('regContributor_tbl'     ).set('opacity', opac);
				$('regSecurity_tbl'        ).set('opacity', opac);
				$('regAgree_tbl'           ).set('opacity', opac);
				$('regSecurityQuestion_sel').set('opacity', opac);
				$('regMediaCompany_tbl'    ).set('opacity', opac);
				$('registerWarning_div'    ).set('opacity', 0);
				$('regSuggestCity_text'    ).set('opacity', 0);
//				$('regCompanyType_sel'     ).setStyle('opacity', opac);

//				$('regMediaCompany_tbl'    ).setStyle('display', 'none');
			}
			
			$$('.popupInp').each( function(item) { item.removeClass('alert'); } );
			
			$$('.reg_chk').each( function(item) {
						item.onmouseup = function() {
							setTimeout( function() {
								newAccessLevel = 1;
								newAccessLevel |= $('regWriter_chk').checked ? 2 : 0;
								newAccessLevel |= $('regVideoMaker_chk').checked ? 4 : 0;
								newAccessLevel |= $('regMediaCompany_chk').checked ? 8 : 0;
								opac = ((newAccessLevel & 2) | (newAccessLevel & 4) | (newAccessLevel & 8)) ? 1 : hideOpac;
								$('regContributor_tbl'     ).tween('opacity', opac);
								$('regSecurity_tbl'        ).tween('opacity', opac);
								$('regAgree_tbl'           ).tween('opacity', opac);
								$('regSecurityQuestion_sel').tween('opacity', opac);
								
								if ( (newAccessLevel & 2) | (newAccessLevel & 4) ) {
									$('registerWarning_div').tween('opacity', 1);
								} else {
									$('registerWarning_div').tween('opacity', 0);
								}
								
								if (newAccessLevel & 2) {
									$('regSuggestCity_text').tween('opacity', 1);
								} else {
									$('regSuggestCity_text').tween('opacity', 0);
								}
								
//								$('regCompanyType_sel'     ).tween('opacity', opac);
								
								opac = (newAccessLevel & 8) ? 1 : hideOpac;
								$('regMediaCompany_tbl').tween('opacity', opac);
	
							}, 50 );
						}
				});
			
			$('regSuggestCity_text').addEvent('mousedown', fnClickButton);    // If they want to add a city

			if (tmpUser.city_id == -1) {
				$('regCityName_td').innerHTML = 'Choose...';
			} else {
				ajaxGetCityInfo(tmpUser.city_id, function(response) {	// Set hidden city id
									 $('regCityName_td').innerHTML = JSON.decode(response).city_name;
				});
			}
	
			$('regCityName_td').addEvent('mousedown', function(event) {
												   event.stop();
												   showModal('cs_div', 'regCity', null, null);
												   });
			fnFocus('regEmail_inp');

		break;
		
		case 'sequel':
			$$('.popupInp').each( function(item) { item.removeClass('alert'); } );
			
			$('sequelInfo_span').removeEvents('mousedown');
			$('sequelTc_span'  ).removeEvents('mousedown');
			
			$('sequelInfo_span').addEvent('mousedown', function() {
				aTcPopupNav.length = 0;
				aTcPopupNav[0] = ['Sequel Info'        , 'sequelInfo'];
				aTcPopupNav[1] = ['Sequel Instructions', 'sequelHelp'];
				showModal('tcPopup_div', 'sequelInfo', null, null);
			 } );
			
			$('sequelTc_span'  ).addEvent('mousedown', function() {
				aTcPopupNav.length = 0;
				aTcPopupNav[0] = ['Sequel EULA'        , 'sequelEULA'];
				showModal('tcPopup_div', 'sequelEULA', null, null);
			 } );
		break;

		case 'uploadSong':
			$('upload_iframe').set('src', 'upload_form.php?id=' + uploadId);
			$('hiddenUploadField').set('name', uploadIdKey);
			$('hiddenUploadField').set('value', uploadId); //alert ('id is ' + uploadId + ', key is ' + uploadIdKey);
		
			ajaxFillHTML ({'whichFunction' : 'buildSelector',			// Build the genre selector in the search
						   'table'         : 'genres',
						   'firstOption'   : 'Choose...',
						   'currentSel'    : 'all',
						   'id'            : 'uploadSongGenre_sel',
						   'parentId'      : 'uploadSongGenre_td'}, function() { $('uploadSongGenre_sel').addClass('popupInp')});
			
			ajaxFillHTML ({'whichFunction' : 'buildSelector',			// Build the mood selector in the search
						   'table'         : 'moods',
						   'firstOption'   : 'Choose...',
						   'currentSel'    : 'all',
						   'id'            : 'uploadSongMood_sel',
						   'parentId'      : 'uploadSongMood_td'}, function() { $('uploadSongMood_sel').addClass('popupInp') });
			
			$('uploadSongTc_span').removeEvents('mousedown');
			$('uploadSongTc_span').addEvent('mousedown', function() {
				aTcPopupNav.length = 0;
				aTcPopupNav[0] = ['Songwriter / Artist Terms', 'songwriterTerms'];
				aTcPopupNav[1] = ['Songwriting Agreement'    , 'songwriterAgreement'];
				aTcPopupNav[2] = ['Master Use Agreement'     , 'masterUseAgreement'];
				showModal('tcPopup_div', 'songwriterTerms', null, null);
			 } );
			
			selectedCityId = browserSettings.city_id;
			ajaxGetCityInfo(selectedCityId, function(response) {
								 $('uploadSongCityName_td').innerHTML = JSON.decode(response).city_name;
			});
			
			$('uploadSongCityName_td').addEvent('mousedown', function(event) {
												   event.stop();
												   showModal('cs_div', 'uploadSongCity', null, null);
												   });
			
			ajaxGetUserSongSelector(0, 'refSong', 'uploadRefSong_sel', 'uploadRefSong_span', function() {
/*						$('uploadRefSong_sel').addEvent('mouseup', function() {
								$('uploadSongTitle_inp').set('value', $('uploadRefSong_sel').get('text'));
						});
*/			});
			
			$('uploadSongCollabType').addEvent('mouseup', function() {
						setTimeout(function() {
							var collab = getRadioValue(document.uploadSongInput_frm.collabType_rad);
							var currentShownTitle   = $('uploadSongTitle_inp'  ).get('value');
							var currentShownArtist  = $('uploadSongArtist_inp' ).get('value');
							var currentShownWriters = $('uploadSongWriters_inp').get('value');
							if (collab == 5) {
								$('uploadSongTitle_inp'  ).set('value', '(Original Song Title)');
								$('uploadSongArtist_inp' ).set('value', '(Original Artist)');
								$('uploadSongWriters_inp').set('value', '(Original Writers)');
								$('uploadSongTitle_inp'  ).disabled = true;
								$('uploadSongArtist_inp' ).disabled = true;
								$('uploadSongWriters_inp').disabled = true;
								$('uploadSongCityName_td').set('opacity', .5);
								$('uploadSongCityName_td').set('html', '(Original City)');
							} else {
								$('uploadSongTitle_inp'  ).disabled = false;
								$('uploadSongArtist_inp' ).disabled = false;
								$('uploadSongWriters_inp').disabled = false;
								if (currentShownTitle == '(Original Song Title)') {
									$('uploadSongTitle_inp').set('value', '');
								}
								if (currentShownArtist == '(Original Artist)') {
									$('uploadSongArtist_inp').set('value', '');
								}
								if (currentShownWriters == '(Original Writers)') {
									$('uploadSongWriters_inp').set('value', '');
									$('uploadSongCityName_td').set('opacity', 1);
									ajaxGetCityInfo(selectedCityId, function(response) {
														 $('uploadSongCityName_td').innerHTML = JSON.decode(response).city_name;
									});
								}
							}
						}, 250);
					});
		break;
		
		case 'uploadVideo':
			ajaxGetUserSongSelector(1, 'videoSong', 'uploadVideoSong_sel', 'uploadVideoSong_span', function() {});
			
			$('uploadVideoTc_span').removeEvents('mousedown');
			$('uploadVideoTc_span').addEvent('mousedown', function() {
				aTcPopupNav.length = 0;
				aTcPopupNav[0] = ['Music Video Terms'    , 'musicVideoTerms'];
				aTcPopupNav[1] = ['Music Video Agreement', 'musicVideoAgreement'];
				showModal('tcPopup_div', 'musicVideoTerms', null, null);
			} );
		break;
		
		case 'tc':
			$$('.tcSpan').each (function(item) {item.removeEvents('mousedown');} );
			$('tcGeneralTerms_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'generalTerms', function() {}, function() {}); });
			$('tcSongwriterTerms_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'songwriterTerms', function() {}, function() {}); });
			$('tcMusicVideoTerms_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'musicVideoTerms', function() {}, function() {}); });
			$('tcMediaTerms_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'mediaTerms', function() {}, function() {}); });
			$('tcSongwriterAgreement_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'songwriterAgreement', function() {}, function() {}); });
			$('tcMasterUseAgreement_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'masterUseAgreement', function() {}, function() {}); });
			$('tcMusicVideoAgreement_span').addEvent('mousedown', function() {
									showModal('tcPopup_div', 'musicVideoAgreement', function() {}, function() {}); });
		break;
		
		case 'privacy':
		break;

		case 'link':
			$('widgetLink').set ('html', 'http://www.citylovemusic.com/index.php?play=' + nowPlaying.token.substr(0, 8));
		break;
		
/*		case 'vote':
			$('votePassword_div').setStyle('display', 'none');
			fnFocus('voteEmailInput_inp');
		break;
*/	}

	$('popupOk_span'    ).addEvent('click', popupOk);
	if ($('popupCancel_span')) $('popupCancel_span').addEvent('click', popupCancel);

	$('darken_div').addEvent('mousedown', fnClickedOutsidePopup);
}

function fnClickedOutsidePopup() {
		if (aPopups[lastPopup][5]) hidePopup();
}

function popupOk() {
	$$('.popupInp').each( function(item) { item.removeClass('alert'); } );
	var foundError = false;
	
	switch (lastPopup) {
		case 'register':
			var regEmail          = $('regEmail_inp'           ).get('value');
			var regPassword       = $('regPassword_inp'        ).get('value');
			var regRetypePassword = $('regRetypePassword_inp'  ).get('value');
			var firstName         = $('regFirstName_inp'       ).get('value');
			var lastName          = $('regLastName_inp'        ).get('value');
			var securityQuestion  = $('regSecurityQuestion_sel').get('value');
			var securityAnswer    = $('regSecurityAnswer_inp'  ).get('value');
			var regTCAgree        = $('regTcAgree_chk'         ).checked;
			var companyName = '';
			var companyType = '';
			
			if (regEmail == "") {										// If they didn't enter an email
				foundError = true;
				$('regEmail_inp').addClass('alert');
			}

			ajaxCheckEmail(regEmail, function(response) {
				if (statusDisplay) alert ('xxx Email check response was ' + response);
				email = JSON.decode(response);
				if (email.valid) {      				    // If it's a valid email address
					if (bNewReg) {							// If we're not modifying an existing registration
						if (email.in_use) {					// If it's already in use
							if (email.has_password) {
								foundError = true;
								$('regEmail_inp').addClass('alert');
								alert ("This email address has a password associated with it.\nI'll take you to the sign-in window.");
								finishPopup();
								$('siEmail_inp').set('value', regEmail);
								modalMsg = '';
								showModal('si_div', null, function() {
																	hideModal('si_div');			// onSuccess
																   },
																   
																   function() {						// onFailure
																		hideModal('si_div');
																   });
							}
						}
					}
				} else {									// If it's not a valid email address
					foundError = true;
					$('regEmail_inp').addClass('alert');
					alert ("Invalid Email Address");
				}
			   
				if (newAccessLevel > 1) {		// Only check validity if necessary
					if ($('regCityName_td').innerHTML == 'Choose...') {		// If they didn't choose a city
						foundError = true;
						$('regCityNameHint_td').addClass('alert');
						$('regCityName_td'    ).addClass('alert');
					}
	
					if (bNewReg) {				// Check password for a new registration
						if ((regPassword != regRetypePassword) | 						// If passwords don't match
							(regPassword.length < 5) | (regPassword.length > 12)) {  	// or they're the wrong length
							foundError = true;
							$('regPassword_inp').addClass('alert');
							$('regRetypePassword_inp').addClass('alert');
						}
					} else {					// Check password for an update
						if ( ((regPassword == '') & (oldAccessLevel <= 1) &
								(newAccessLevel > 1) & (newAccessLevel != oldAccessLevel)) |
							 ((regPassword != regRetypePassword)) |
							 ((regPassword != '') & (regPassword.length < 5)) |
							 ((regPassword != '') & (regPassword.length > 12)) ) {
								foundError = true;
								$('regPassword_inp').addClass('alert');
								$('regRetypePassword_inp').addClass('alert');
						}
					}
					
					if ((securityQuestion == 'Choose...') | (securityQuestion == '')) {
						foundError = true;
						$('regSecurityQuestion_sel').addClass('alert');
					}
					
					if (securityAnswer == '') {
						foundError = true;
						$('regSecurityAnswer_inp').addClass('alert');
					}
					
					if (!regTCAgree) {
						foundError = true;
						$('regTcAgree_chk').addClass('alert');
						$('regTc_span'  ).addClass('alert');
					}
							
					var companyName = '';
					var companyType = '';
					if (newAccessLevel & 8) {   						// If it's a Media Company Registration
						companyName = $('regCompanyName_inp').get('value');
						if (companyName == "") {
							foundError = true; $('regCompanyName_inp').addClass('alert');
						}
						
						companyType = $('regCompanyType_sel').get('value');
						if (companyType == "Choose...") {
							foundError = true; $('regCompanyType_sel').addClass('alert');
						}
					}

				}  // End if newAccessLevel > 1
					
				if (!foundError) {
					tmpUser.email = regEmail;
					if (regPassword != tmpUser.password) {  // If they've changed the password
						tmpUser.password = regPassword;
					} else {
						tmpUser.password = '';
					}
					tmpUser.access_level = newAccessLevel;
					tmpUser.first_name = firstName;
					tmpUser.last_name = lastName;
					tmpUser.company_name = companyName;
					tmpUser.company_type = companyType;
					tmpUser.security_question = securityQuestion;
					tmpUser.security_answer = securityAnswer;
					tmpUser.needs_validation_email = 0;
					
					if ((newAccessLevel > 1) & (newAccessLevel != oldAccessLevel) &
												(tmpUser.sent_validation_email != 1)) {  // Do we need validation email
						tmpUser.needs_validation_email = 1;
					}
					
					if ((email.in_use) & (newAccessLevel == 1)) {	// If they're a voter only who's already registered
						user.id           = email.user_id;
						user.email        = regEmail;
						user.access_level = 1;
//						alertObject (user);
						updateSignIn();
						ajaxGetSongList(function() {});
						
						if (bTryingToVote) {
							ajaxRecordVote(nowPlaying.versionId,
										   getSongNum(nowPlaying.linkId),
										   getRowNum (nowPlaying.linkId),
										   user.id, 1, function() {});

							bTryingToVote = false;
						}

						finishPopup();
					} else {
						var mode = bNewReg ? 'create' : 'update';
						ajaxReg (tmpUser, mode, function(response) {
							if (statusDisplay) alert ('xxx ' + mode + ' user response was ' + response);
							returnedUser=JSON.decode(response);
							if (returnedUser.id >= 0) {
								user = cloneObject(returnedUser);
								tmpUser = cloneObject(defaultUser);
								updateSignIn();
								ajaxGetSongList(function() {
									if ((user.validated != 1) & (user.sent_validation_email == 1)) {
										alert ('Validation email has been sent');
									} else if ((user.validated != 1) & (user.sent_validation_email == 0)) {
										alert ("Error sending validation email.  We're working on the problem.");
									}
									finishPopup();
									if (bTryingToVote) {
										ajaxRecordVote(nowPlaying.versionId,
													   getSongNum(nowPlaying.linkId),
													   getRowNum (nowPlaying.linkId),
													   user.id, 1, function() {});
	
										bTryingToVote = false;
									}
								});
							} else {
								alert ('Registration was not successful');
							}
						});
					}
							
				}  // end if (!foundError)
			});  // end ajaxCheckMail

		break;
		
		case 'sequel':
//			var dlFiles = new Array();
			var sequelFile;
			var vId;
			var sequelTcAgree  = $('sequelTcAgree_chk' ).checked;
			
			if ($('sequelPlatformPC').checked) {
				sequelFile = 'sequel_2_trial.exe';
				vId = -1001;
			} else {
				sequelFile = 'Sequel 2 Trial 448 SnowLeopardFix.dmg';
				vId = -1002;
			}
//			alert ('sequelTcAgree_chk is ' + sequelTcAgree + ", sequelPlatform is " + sequelPlatform);
			if (!sequelTcAgree) {
				foundError = true;
				$('sequelTcAgree_chk').addClass('alert');
				$('sequelTc_span'    ).addClass('alert');
			}

			var path = 'media/software/';
			
			if (!foundError) {
				window.location.href = path + sequelFile;
				ajaxLogActivity ('download', vId, user.id);
				finishPopup();
			}
		break;
		
		case 'uploadSong':
			var uploadedSong = new Object;
			uploadedSong.id = -1;
			uploadedSong.songName    = basename($('uploadSongName_file' ).get('value'));
			uploadedSong.lyricName   = basename($('uploadLyricName_file').get('value'));
			uploadedSong.title       = $('uploadSongTitle_inp'      ).get('value');
			uploadedSong.versionName = $('uploadSongVersionName_inp').get('value');
			uploadedSong.artist      = $('uploadSongArtist_inp'     ).get('value');
			uploadedSong.writers     = $('uploadSongWriters_inp'    ).get('value');
			uploadedSong.bpm         = $('uploadSongBPM_inp'        ).get('value');
			uploadedSong.genre       = $('uploadSongGenre_sel'      ).get('value');
			uploadedSong.mood        = $('uploadSongMood_sel'       ).get('value');
			uploadedSong.collabType  = $('uploadSongCollabType'     ).get('value');
			uploadedSong.refSong     = $('uploadRefSong_sel'        ).get('value');
			uploadedSong.userId      = user.id;
			uploadedSong.cityId      = selectedCityId;
			
			uploadedSong.songInDB    = 0; uploadedSong.lyricInDB   = 0;
//			uploadedSong.songStatus  = 0; uploadedSong.lyricStatus = 0;
				
			if (uploadedSong.songName == '') { foundError = true; $('uploadSongChooseSong_td').addClass('alert'); }
			
			if (uploadedSong.title    == '') { foundError = true; $('uploadSongTitle_inp'  ).addClass('alert'); }
			if (uploadedSong.artist   == '') { foundError = true; $('uploadSongArtist_inp' ).addClass('alert'); }
			if (uploadedSong.writers  == '') { foundError = true; $('uploadSongWriters_inp').addClass('alert'); }
			if (uploadedSong.genre    == 'Choose...') { foundError = true; $('uploadSongGenre_sel').addClass('alert'); }
			if (uploadedSong.mood     == 'Choose...') { foundError = true; $('uploadSongMood_sel' ).addClass('alert'); }

			if (!((parseInt(uploadedSong.bpm) > 0) & (parseInt(uploadedSong.bpm) <= 999))) {
				foundError = true;
				$('uploadSongBPM_inp').addClass('alert');
			}
			
			var cityName = $('uploadSongCityName_td').innerHTML;
			if (cityName == 'Choose...') { foundError = true; $('uploadSongCityName_td').addClass('alert'); }

			var collab = getRadioValue(document.uploadSongInput_frm.collabType_rad);
			if (collab == -1) {
				foundError = true; $('uploadSongCollab_span').addClass('alert');
			} else if ((collab >=0) & (collab <=2)) {
				uploadedSong.writers = 'CityLove, ' + uploadedSong.writers;
			} else if (collab == 4) {
				uploadedSong.writers = 'CityLove';
			} else if (collab == 5) {		// If they said it's a new version of a song they've already uploaded
				if (uploadedSong.versionName == '') {
					foundError = true;
					$('uploadSongVersionName_inp').addClass('alert');
				}
				if (uploadedSong.refSong == -1) {
					foundError = true;
					$('uploadRefSongHint_span').addClass('alert');
				}
			}
			
			uploadedSong.collabType  = collab;
			
			if (uploadedSong.versionName == '') uploadedSong.versionName = uploadedSong.title;
			
			var uploadTCAgree = $('uploadSongTcAgree_chk'    ).checked;
			if (!uploadTCAgree) {
				foundError = true;
				$('uploadSongTcAgree_chk').addClass('alert');
				$('uploadSongTc_span'    ).addClass('alert');
			}

			if (!foundError) {
				ajaxGetCityInfo(uploadedSong.cityId, function(response) {
														uploadedSong.countryCode = JSON.decode(response).country_code;

				$('uploadSongInput_frm').set('action', 'upload_form.php?cityId=' + selectedCityId +
											 					'&countryCode=' + uploadedSong.countryCode);
				
				$('slStatus_div').set('html', 'Uploading File- Please Be Patient');
				$('slStatus_div').setStyle('visibility', 'visible');
//alert ('set form action to ' + $('uploadSongInput_frm').get('action'));
//alertObject(uploadedSong);														
				var finished = false;
				var percent  = 0.0;
				var total    = 0;
				var complete = 0;
				var perform;
				var periodical;
				var token;
				  
				var morph = new Fx.Tween('uploadStatus');
				var request = new Request({
						url: 'status.php?id=' + uploadId,
						method: 'get',
						update: 'uploadStatus',
						onComplete: function(response) {
							objectsReturned = JSON.decode(response);
							$each(objectsReturned, function(item, index){
								if (index=="finished") {
									finished = item;
									if (finished==true) $clear(periodical);
								}
								if (index=="percent")  percent = item;
								if (index=="total")    total = item;
								if (index=="complete") complete = item;
								if (index=="token") uploadedSong.filenameToken = item;
							});
							if (complete != false)
								$('info').set('html', 'Received: ' + complete + ' of ' + total + ' ('+Math.round(percent)+'%)');
//											  +'Total: '+total+'<br />'
//											  +'Finished: '+finished+'<br />'); 
							$('uploadStatus').tween('width', Math.round(percent)*2+'px');
							
							if (finished == true) {
										
					if ((uploadedSong.songName != '') | (uploadedSong.lyricName != ''))
				
					uploadedSong.song_path  = 'media/upload/audio/'  + uploadedSong.countryCode + '/' +
							uploadedSong.cityId + '/' + uploadedSong.filenameToken + getFilenameSuffix(uploadedSong.songName);
					uploadedSong.lyric_path = 'media/upload/lyrics/' + uploadedSong.countryCode + '/' +
							uploadedSong.cityId + '/' + uploadedSong.filenameToken + getFilenameSuffix(uploadedSong.lyricName);
				
					ajaxUploadAudio (uploadedSong, function(response) {	// alert (response);
						var needsProcessing = false;
						var output='';
						var returnedSong = JSON.decode(response);
						uploadedSong = cloneObject(returnedSong	);
						if (uploadedSong.songInDB == 1) {
							if (uploadedSong.collabType == 'collab5') {		// If they said they're uploading a new version
								if (uploadedSong.refSong != -1) {
									output += 'Uploaded ' + uploadedSong.name + ' which is a new version of song #' +
											uploadedSong.refSong + '\n\n';
									output += 'Audio files will be temporarily unavailable\nwhile being processed.\n\n';
									needsProcessing = true;
								} else {
									output += 'No reference song id supplied.  Uploading of ' + uploadedSong.name +
											' was cancelled.' + '\n';
								}
							} else {
								output += 'Uploaded song: ' + uploadedSong.songName + '\n';
								if (uploadedSong.versionName != '')
									output +='Version Name: ' + uploadedSong.versionName + '\n'
								output += '\nAudio files will be temporarily unavailable\nwhile being processed.\n\n';
								needsProcessing = true;
							}
						} else {
							output += 'No song uploaded.\n';
						}
						
						if (uploadedSong.lyricInDB == 1) {
							output += 'Uploaded lyrics: ' + uploadedSong.lyricName + '\n';
						} else {
							output += 'No lyrics uploaded.\n';
						}
						
//						ajaxGetSongList(function() {});
						
						alert (output);
						finishPopup();
						
						if (needsProcessing) { //alertObject(uploadedSong);
							ajaxProcessAudio (uploadedSong, function (response) {
								var processingResponse = JSON.decode(response);
//									alertObject (processingResponse);
//									var vId = processingResponse.version_id;
								if (isSet(processingResponse) & isSet(processingResponse.filenameToken)) {
									window.location.href = "index.php?play=" + (processingResponse.filenameToken.substr(0,8));
								} else {
									alert ('Audio processing has not completed yet.\nPlease wait a minute and refresh the page.');
								}

//									ajaxGetSongList(function() {});


//									$('slStatus_div').setStyle('visibility', 'hidden');
/*									var aProcessing = $$('.processing');
								aProcessing.each( function (item) {
										if (item.getParent().get('version_id') == vId) {
											item.getParent().addClass('slPlayLink');
											item.getParent().getChildren('span')[0].dispose();
										}
								});
*/

							});     // End of ajaxProcessAudio
						}
					} );    // End of ajaxUploadAudio
										
										
										
										
										
										
										
										
										
									}
						}
					});
						
					perform = function () { request.send(); }
					periodical = perform.periodical(1000);
//alert ('about to submit');				
				$('uploadSongInput_frm').submit();
//														finishPopup();
				});
			}
		break;
		
		case 'uploadVideo':
			var videoObj = new Object;
			videoObj.refSong   = $('uploadVideoSong_sel'   ).get('value');
			videoObj.videoName = $('videoName_inp'         ).get('value');
			var videoLink = $('videoLink_inp'         ).get('value');
			var tcAgree   = $('uploadVideoTcAgree_chk').checked;

			if (videoObj.refSong == -1) {
				foundError = true;
				$('uploadVideoSongHint_span').addClass('alert');
			}
			
			if (videoObj.videoName == '') {
				foundError = true;
				$('videoName_inp').addClass('alert');
			}
				
			if (videoObj.youtubeId == '') {
				foundError = true;
				$('videoLink_inp').addClass('alert');
			} else {
				var videoId = videoLink.match (/[A-Za-z0-9-]+$/);
			}

			if (videoId) {
				videoObj.youtubeId = videoId.toString();
				if (videoObj.youtubeId.length == 11) {
//					alert (videoObj.youtubeId + ', type: ' + typeof videoObj.youtubeId);
				} else {
					foundError = true;
					$('videoLink_inp').addClass('alert');
					alert ('The video identifier in your YouTube link is incorrect');
				}
			} else {
				foundError = true;
				$('videoLink_inp').addClass('alert');
				alert ('You have not entered a properly formatted YouTube link.\nExample: http://www.youtube.com/v/oYeyqDKJBv8');
			}
				
			if (!tcAgree) {
				foundError = true;
				$('uploadVideoTcAgree_chk').addClass('alert');
				$('uploadVideoTc_span'    ).addClass('alert');
			}
					
			if (!foundError) {
				ajaxUploadVideo(videoObj, function(r) {
								var response = JSON.decode(r);
//								alertObject (response);
								window.location.href = "index.php?play=" + (response.filenameToken.substr(0,8));
				   					ajaxGetSongList(function() {});
				});
				finishPopup();
			}
		break;
		
		case 'tc':
			finishPopup();
		break;
		
		case 'privacy':
			finishPopup();
		break;
		
		case 'link':
			finishPopup();
		break;
		
	}

}

function popupCancel() {
	switch (lastPopup) {
		case 'register':
		break;
		
		case 'sequel':
		break;
		
		case 'uploadSong':
		break;
		
		case 'uploadVideo':
		break;
		
		case 'facebook':
		break;
		
		case 'myspace':
		break;
		
		case 'twitter':
		break;
		
		case 'vote':
		break;
	}
	
	finishPopup();
}

function finishPopup() {
	if ($('popupOk_span'    )) $('popupOk_span'    ).removeEvent('click', popupOk);
	if ($('popupCancel_span')) $('popupCancel_span').removeEvent('click', popupCancel);
	hidePopup();
}

function setupTcSlide() {
	popupTcSlide = new Fx.Slide('popupTc_div', {link: 'cancel'}).hide();
	$('popupTc_span').addEvent('click', function() {popupTcSlide.toggle()} );
}

function regFromModal() {
	hideModal('tcPopup_div');
	regNeedCompanyInfo = false;
	showPopup('register');
}

