	/*global $, Cookie, ActiveXObject, checkDL, navigator, console, clearInterval, alert, window, setInterval, setTimeout, clearTimeout, DUMAS, jQuery, load*/
	(function(){
		var status, dlmPluginIntervalID, dlmPluginTimeoutID, downloadLink = {}, dlm = false, activeX, secondaryText, downloadManagerLink, dlmChoice,
			mediaType, oHref, dlmCheckDialogStatusCookie = Cookie({name: 'dlmCheckDialogStatusCookie', path: '/', expires: 3650}), i = 1,
			loadingImage = "<img src='/images/oneclick/processing.gif' alt='(loading download manager information)' class='loading' />";
			status = dlmCheckDialogStatusCookie.get('status');


		/*reset view*/
		function resetDLMCheck(){
			if ($.browser.msie) {
				$('body.ie #downloadDialog.fancyBorderBoxWrapper').css('width', '789px');
			}
			$('#noDLMView, #thanks, #confirmation').hide();
			$('#initialView').show();
		}

		/*check for download manager plugin, return true or false*/
		function hasDLMPlugin() {
			/*check for ActiveX (for IE)*/
			if (typeof ActiveXObject != 'undefined') {
				try {
					activeX = new ActiveXObject("EMusicActiveX.eMusicDownloadManager.1");
					if (activeX) {
						dlm = true;
					}
				}
				catch(e) {
					dlm = false;
				}
			}
			if (navigator.plugins) { //check for plugin
				navigator.plugins.refresh(false);
				if (navigator.plugins['eMusic Remote Plugin'] !== undefined) {
					dlm = true;
				}
			}
			 //fallback to checking userAgent string
			if (navigator.userAgent && (navigator.userAgent.indexOf('eMusic DLM/4') != -1 || navigator.userAgent.indexOf('eMusic Remote/1') != -1)) {
					dlm = true;
			}
			if (dlm) {
				if( !DUMAS.sessionDlmChoice || DUMAS.sessionDlmChoice.dlmChoice != 'hasDLM') {
					$.ajax({type: "GET", data: {'dlmChoice':'hasDLM'}, async: false, url: "/sessions/remote.html"}); //for users upgrading from DLM3, swap from emp to emx and set to emx
				}
				$('a.downloadAlbum, a.downloadTrack, span.downloadTrack a').each( function(){
					if ($(this).attr('href')) {
						var oHref = $(this).attr('href').replace(/([\/\.])emp/g, "$1emx");
						$(this).attr('href', oHref);
					}
				});
			}
			return dlm;
		}

		/*stop checking for plugin after install*/ 
		function endInstallCheck(downloadManagerLink, hash){
//			console.log('ending install check');
			clearInterval(dlmPluginIntervalID);
			$('img.loading').hide();
			$('#confirmation h1').text('We have not yet detected that the Download Manager has been installed. ');
			$('#confirmation p:first').html('Please make sure your installation is complete. If there was a problem with the installation please <a href="" class="reinstall">reinstall the Download Manager</a>.');
			$('a.reinstall').attr('href',downloadManagerLink);
			$('p:first, div, div *', '#confirmation').show(function(){
				$('#confirmation a.jqmClose').click(function(){
					hash.w.jqmHide();
					return false;
				})
			});

		}

		/*display correct text after dlm install or other choice has been made*/
		function confirmationTextDisplay(linkInfo, input){
			dlmChoice = 'with the eMusic Download Manager.';
			$('#confirmation h1').text('Success!');
			if (input !== undefined)  {
				if (input == 'mp3' || input == 'other') {
					dlmChoice = 'without a Download Manager.';
				} else if (input == 'emp') {
					dlmChoice = 'with an older version of the eMusic Download Manager.';
				} else if (input == 'emx') {
					dlmChoice = 'with eMusic Download Manager 4.0, eMusic/J, or eMusic Remote.';
				}
			} else {
				$('#confirmation p:eq(0)').remove();
			}
			secondaryText = "Your account is now configured to download "+dlmChoice;
			$('#confirmation h3').text(secondaryText);
				$('#confirmation p span').text("the "+linkInfo.mediaType);
			$('#confirmation p em').text(linkInfo.title);
			$('#confirmation p a.downloadTrackDLM').attr('href',linkInfo.href);
			$('#confirmation h3, #confirmation p').fadeIn();
			if (input == 'emp') {
				$('#confirmation p a.downloadTrackDLM').attr('href',$('#confirmation p a.downloadTrackDLM').attr('href').replace(/([\/\.])emx/g, "$1emp"));
			} else if (input  == 'emx' || input === undefined) {
				$('#confirmation p a.downloadTrackDLM').attr('href',$('#confirmation p a.downloadTrackDLM').attr('href').replace(/([\/\.])emp/g, "$1emx"));
			}
		}

		/*clearTimeouts for plugin checking after download; call confirmation text display function*/
		function dlmInstallSuccess(linkInfo, downloadManagerLink,hash)	{
			if (hasDLMPlugin()) {
				clearInterval(dlmPluginIntervalID);
				clearTimeout(dlmPluginTimeoutID);
				confirmationTextDisplay(linkInfo);
				$('#confirmation *').show(function(){
					$('a.jqmClose').click(function(){
						hash.w.jqmHide();
						return false;
					})
				});
				$('#confirmation h1 img').hide();
				if ($(linkInfo.target).attr('data-dlm') == 'no') {
					$('#confirmation p:eq(0)').text('Please click the close button to enable the download manager. You may then try your download again.');
					$('#confirmation p:eq(1)').hide();
					$('#confirmation a.jqmClose, p.jqmClose').click(function(){
						window.location.reload(false);
					});
				} else {
					$('#confirmation p a.downloadTrackDLM').click(function(){
						$('#downloadDialog.fancyBorderBoxWrapper').hide();
						return DUMAS.checkDL(linkInfo.mediaType,this.href);
					});

				}
			} else {
				if ( i == 1) {
					dlmPluginTimeoutID = setTimeout(function(){endInstallCheck(downloadManagerLink,hash);}, '18000');
				}
			}
			i++;
		}

		/*check for dlm plugin after download button clicked*/
		function checkForDLMInstall(linkInfo, downloadManagerLink,hash){
			if ($.browser.msie) {
				$('body.ie #downloadDialog.fancyBorderBoxWrapper').css('width', '685px');
			}
//			console.log('href is ', linkInfo.href);
			$('#confirmation h1').text('Checking for install. . . ');
			$('#confirmation h1').append(loadingImage);
			$('#confirmation').show();
			$('#confirmation *').hide();
			
			$('#confirmation h1, #confirmation h1 img').fadeIn();
//			console.log('title in checkForDLMInstall is: ',linkInfo.title);
			dlmPluginIntervalID = setInterval(function() {
				dlmInstallSuccess(linkInfo, downloadManagerLink,hash);
			},'3000');
		}

		/*download the dlm*/ 
		function dlmInstall(linkInfo, downloadManagerLink,hash){
			$('#dlmHref').click(function(){
				$('#initialView').hide();
				$('p.jqmClose').click(function(){
					clearInterval(dlmPluginIntervalID);
				});
				if ($(linkInfo.target).attr('data-dlm') && $(linkInfo.target).attr('data-dlm') == 'no') {
					if( !DUMAS.sessionDlmChoice || DUMAS.sessionDlmChoice.dlmChoice != 'emx') {
						$.get('/sessions/remote.html',{'dlmChoice': 'emx'});
					}
				}
				checkForDLMInstall(linkInfo, downloadManagerLink,hash); //setInterval function here
				return true;
			});
		}

		/*change view after user makes dlm choice*/
		function dlmChoiceDisplay(input,linkInfo,hash){
			confirmationTextDisplay(linkInfo,input);
			$('#noDLMView').hide();
			if ($.browser.msie) {
				$('#downloadDialog.fancyBorderBoxWrapper').css('width', '689px');
			}
			$('#confirmation').show();
			if (input == 'mp3' || input == 'other' || $(linkInfo.target).attr('data-dlm') == 'no') {
//				console.log('should hide ',$('#confirmation p:eq(1)').html());
				if ($('#confirmation p:eq(1)').length >0) {
					$('#confirmation p:eq(1)').hide();
				} else {
				$('#confirmation p:eq(0)').hide();
				}
				$('a.whiteWebButtonGray, p.jqmClose, a.jqmClose').click(function(){
					window.location.reload(false);
				});
			}
			$('a.jqmClose, p.jqmClose').click(function(){
				$('#downloadDialog.fancyBorderBoxWrapper').jqmHide();
				return false;
			});
				$('#confirmation p a.downloadTrackDLM').click(function(){
					$('#downloadDialog.fancyBorderBoxWrapper').jqmHide();
					if (DUMAS.checkDL) {
						return DUMAS.checkDL(linkInfo.mediaType,this.href);
					}
					else {
						return true;
					}
					return false;
//					return DUMAS.checkDL(linkInfo);
				});
//			console.log('you have made '+ input+' your dlm choice!');
		}

		function updateDownloadLinksAfterChoice(input, linkInfo) {
			if (linkInfo !== null) {
					dlmChoiceDisplay(input,linkInfo);
					if (linkInfo.mediaType != 'book') {
						if (input == 'emp') { /*change links on page from emx or emp depending on what dlm has been chosen*/
								$('a.downloadAlbum, a.downloadTrack, span.downloadTrack a').each( function(){
									if ($(this).attr('href')) {
										var oHref = $(this).attr('href').replace(/([\/\.])emx/g, "$1emp");
										$(this).attr('href', oHref);
									}
								});
						} else if (input  == 'emx') {
								$('a.downloadAlbum, a.downloadTrack, span.downloadTrack a').each( function(){
									if ($(this).attr('href')) {
										var oHref = $(this).attr('href').replace(/([\/\.])emp/g, "$1emx");
										$(this).attr('href', oHref);
									}
								});
						}
					}
				}
		}

		/*send user dlm choice to server to set download links*/
		function setDLMChoice(input,linkInfo){
			if( !DUMAS.sessionDlmChoice || DUMAS.sessionDlmChoice.dlmChoice != input) {
				$.get('/sessions/remote.html',{'dlmChoice': input}, function() {
					updateDownloadLinksAfterChoice(input, linkInfo);
				});	
			} else {
				updateDownloadLinksAfterChoice(input, linkInfo);	
			}
		}


		/*display the dlm download dialog box* -- uses jqmodal */
		function showDLMDialog(dlmCheckDialogStatusCookie, linkInfo){
//			console.log('In Show Dialog before clicking status is: ',dlmCheckDialogStatusCookie.get('status'));
			var open=function(hash) {
            $('#processing').hide();
				hash.w.css({'top': DUMAS.scrollTop()+50+"px", 'left':(DUMAS.clientWidth()/2)-(hash.w.width()/2)+"px" });

            
				$('#downloadDialog').addClass('installCheck');
				$('#downloadDialog .fancyBoxContent').load('/dlm/dlmInstallCheck.html',function(){loadDLMInfo(hash, false);});

				var load = function(hash, data, errored) {
                  if (!errored) {
						   $('#initialView h1, #initialView h2').show();
					   }
               if ($.browser.msie) {
						$('#downloadDialog.fancyBorderBoxWrapper').css('width', '789px');
					} else {
						$('#downloadDialog.fancyBorderBoxWrapper').css('width', 'auto');
					}
					$('#initialView h1 span').text(linkInfo.mediaType);
					$('#initialView, #initialView h1, #initialView h2').show();
					$('#initialView div.close').hide();
					$('a.no').show();
					$("div.dlmInfo").html(data);
					downloadManagerLink = $('#dlmButton a').attr('href');
					dlmInstall(linkInfo, downloadManagerLink,hash);
					$('a.no').click(function(){
//						console.log('status: ',dlmCheckDialogStatusCookie.get('status'));
						$('p.jqmClose').hide();
//						console.log('clicked no thanks');
						$('#initialView').fadeOut('fast',function(){
							$('#noDLMView').fadeIn(function(){
								if ($.browser.msie) {
									$('#downloadDialog.fancyBorderBoxWrapper').css('width', '689px');
								}
							});
						});
						$('a.back').click(function(){
							$('#noDLMView').hide();
							$('#initialView').show();
							$('p.jqmClose').show();
							if ($.browser.msie) {
								$('#downloadDialog.fancyBorderBoxWrapper').css('width', '789px');
							}
							return false;
						});
						$('button').click(function(){
							if ($('input:radio[name=dlmChoice]:checked').length >0) {
								dlmCheckDialogStatusCookie.set('status','2');
								setDLMChoice($('input:radio[name=dlmChoice]:checked').val(),linkInfo);
								$(this).unbind('click');
							} else {
								if ($('#dlmOptions p.error').length === 0) {
									$('#dlmOptions').prepend('<p class="error">You must choose one of the download options.</p>');
								}
							}
							return false;
						});
						return false;
					});
				};

				/*ajax in dlm info*/
				function loadDLMInfo(hash, errored) {
//					console.log('errored is: '+ errored);
//               $('img.loading, div.close').hide();
               $('#initialView h1, #initialView h2').hide();
               

               hash.w.fadeIn('slow');
               
					$.ajax({
					type: "GET",
					timeout: 5000,
					url: "/dlm/downloadCheck.html",
					data: "installCheck=true", 
					success : function(data){
//                  console.log('success?');

						load(hash,data, errored);
					},
					error: function(){
						$('#initialView h1, #initialView h2, img.loading').hide();
						$('div.dlmInfo').append("<p>We apologize but we could not load the download manager information at this time. Please <a href='#' class='reTry'>try</a> again.</p>");
						$('#initialView div.close').show();
						$('a.reTry').click(function(){
							$('#initialView div.close').hide();
							$('div.dlmInfo p').remove();
							$('img.loading').show();
							 loadDLMInfo(hash, true);
						});
					}
				});
			}


				resetDLMCheck(); //maybe only run this once;
			};


			var close=function(hash) {
				hash.w.fadeOut('4000',function(){ hash.o.remove(); });
			};

			var top = true;
			if ($.browser.msie) {
				top = false;
			}

			$('#downloadDialog.fancyBorderBoxWrapper').jqm({onShow: open, modal: true, onHide: close, overlay: 80, toTop: top}).jqmShow();
				return false;
		}

		/*check to see if user has dlm plugin and/or has cookie that shows they have seen the dialog already*/
		function checkDLMStatus(dlmCheckDialogStatusCookie,linkInfo) {
			var status = dlmCheckDialogStatusCookie.get('status');
			if (status !== undefined) { //if they have the cookie
				if (!hasDLMPlugin()) {
					if (status == 1 ) {
						showDLMDialog(dlmCheckDialogStatusCookie,linkInfo);
						return false;
					} else {
						if (status >= 2) {
//							console.log('won\'t show');
							return true; 
						}
					}
					//If user has plugin but something else isn't right, like dlm disabled
				} else if (status === '') {
//					console.log('got the dlm, but dlm is disabled or sumptin, what do i do now?');
					return false;
				} else {
//					console.log('has dlm and plugin status is good: good to go');
					return true; //CHANGE TO TRUE FOR PROD
				}
			} else { /*If the user does not have the cookie set*/
				/*and if the user does not have the plugin, show the dialog box*/
				if (!hasDLMPlugin()) {
					showDLMDialog(dlmCheckDialogStatusCookie,linkInfo);
//					console.log('should have stopped here');
					return false;
				}
				else {
					/*otherwise they have the plugin */
//					console.log('no cookie,  but yes dlm'); // let them download and ignore the cookie situation, we don't care
					return true; //OR WHAT? CHANGE TO TRUE FOR PROD
				}
			}
			return true;
		}

	function dlmInstallCheck(downloadInfo) { //adding this in the profile section turned it into a mess
			if ((window.location.href.indexOf('wmp') > -1) || (navigator.userAgent.indexOf('Linux') > -1)) { //if wmp or linux, don't run install check, just pass to checkDL
				return true;
			} else {
				if (checkDLMStatus(dlmCheckDialogStatusCookie,downloadInfo)) {
					if (downloadInfo.mediaType == "book") {
	//					return checkAS(); //Removing the book Download Check until back end is fixed; in the meantime just add the iframe for downloading
						if ( $("#downloadBook").length && !$.browser.msie) {
							$("#downloadBook").attr('target','emxframe');
							var iframe = "<iframe id='myFrame' name='emxframe' src='about:blank' width='0' height='0' style='position:absolute; left:-2000px;'></iframe>";
							if( $('#myFrame').length === 0){
								$("body").prepend(iframe);
							}
							$('#myFrame').attr('src','about:blank');
							return true;
						}
						// if (DUMAS.checkDL) {
						// 	return DUMAS.checkDL(downloadLink.mediaType,this.href);
						// }
						// else {
							return true;
						// }
					}
				} else {
					downloadInfo.e.preventDefault();
					return false;
			}
			return true;	
	}
}

			DUMAS.dlmInstallCheck = dlmInstallCheck;
			$('#enableDownloadManager').click(function(){
				setDLMChoice('enable',null);
				setTimeout(function(){window.location.reload(false);}, '500');
				return false;
			}
		);

})();
