var DirectMail = DirectMail || {};

DirectMail.setWindowTitle = function ( title ) {
    $("title").text(title);
};

DirectMail.refreshEmailIcon = function ( deliveryHistory ) {
	var $emailIconElement = $("#email-icon");
	var thumbnailURL      = deliveryHistory.valueForKeyPath( 'message.thumbnailURL.absoluteString' ) + '/' + $emailIconElement.width() + '/0/' + window.devicePixelRatio;
    var image             = new Image();
    
    image.onload = function() {
        $emailIconElement.attr( 'src', thumbnailURL );
		$emailIconElement.addClass('loaded');
    };
    image.src = thumbnailURL;
};

DirectMail.defaultPopularItemCount = 5;
DirectMail.popularItemSectionExpanded = { 
	'Links' : true,
	'UserAgents' : true,
    'Locations' : true
};

DirectMail.configurePopularItemRows = function( $table, identifier, items, expanded, itemRowCallback ) {
	var $rowTemplate = $("tr.popular-item-template", $table);
	var $expandRow   = $("tr.expand-row", $table);

	$rowTemplate.nextAll("tr.popular-item").remove();

	// Don't use .is(':visible') because that doesn't work with web report (when parent element is hidden during loading)
	if ( items.length == 0 && $table.css('display') != 'none' ) {
		$table.hide();
	} 
	else if ( items.length > 0 && $table.css('display') == 'none' ) {
		$table.css({ opacity: 0 }).show();
        setTimeout( function(){ $table.css({ opacity: 1 }); }, 0 );
	}
	
	this.popularItemSectionExpanded[identifier] = expanded;
	
	for ( var i = 0; i < items.length; i++ ) {
		var item  = items[i];
		var $row  = $rowTemplate.clone().removeClass('popular-item-template');
		
		itemRowCallback( item, $row );
		
		$expandRow.before($row);
		$row.show();
	}
	
	var $tableHeader = $("tr.header > td", $table);
	var $arrow = $("div.arrow", $expandRow);
		
	if ( !expanded || items.length < this.defaultPopularItemCount ) {
		$tableHeader.text($tableHeader.data('top-title'));
		$expandRow.removeClass('expanded');
		$arrow.attr( 'title', $arrow.data('top-title') );
		
		if ( items.length >= this.defaultPopularItemCount ) {
			$expandRow.show();
		}
		else {
			$expandRow.hide();
		}
	}
	else {
		$tableHeader.text($tableHeader.data('all-title'));
		$expandRow.addClass('expanded').show();
		$arrow.attr( 'title', $arrow.data('all-title') );
	}
};

DirectMail.configurePopularLinks = function( expanded ) {
	this.configurePopularItemRows( $("#most-popular-links"), 'Links', window.DirectMail_summaryViewController.dataSource.mostPopularLinkDescriptors( expanded ? 0 : this.defaultPopularItemCount ), expanded, function( link, $row ){
		var title = link.valueForKeyPath("representedObject.title");
		
		if ( !title ) {
			$(".link-title", $row).next().remove();
			$(".link-title", $row).remove();
		}
		else {
			$(".link-title", $row).text(title);
		}
		
		var clickCount 			= link.valueForKeyPath("value");
		var formattedClickCount = link.valueForKeyPathWithFormatterName("value", "IntegerFormatter");
		
		$(".link-url", $row).attr('href', link.valueForKeyPath("representedObject.urlString"));
		$(".link-url", $row).text(link.valueForKeyPath("representedObject.urlString"));
		$(".count", $row).text(formattedClickCount);
		$(".ratio", $row).text(link.valueForKeyPathWithFormatterName("ratio", "RatioFormatter"));
		$(".tooltip", $row).attr( 'title', formattedClickCount + ' ' + ( clickCount == 1 ? 'recipient' : 'recipients' ) + ' clicked this link' );
	});
};

DirectMail.configurePopularUserAgents = function( expanded ) {
	this.configurePopularItemRows( $("#most-popular-user-agents"), 'UserAgents', window.DirectMail_summaryViewController.dataSource.mostPopularUserAgentDescriptors( expanded ? 0 : this.defaultPopularItemCount ), expanded, function( ua, $row ){
		var name      = ua.valueForKeyPath("representedObject.displayName");
		var icon1xURL = ua.valueForKeyPath("representedObject.imageURLPrefix.absoluteString") + ".png";
		var icon2xURL = ua.valueForKeyPath("representedObject.imageURLPrefix.absoluteString") + "@2x.png";
					
		$(".user-agent-name", $row).text(name);
		$(".user-agent-icon", $row).attr('title', name);
		$(".user-agent-icon", $row).attr('style', 'background-image: url(' + icon1xURL + '); background-image: -webkit-image-set( url(' + icon1xURL + ') 1x, url(' + icon2xURL + ') 2x )' );			
		$(".count", $row).text(ua.valueForKeyPathWithFormatterName("value", "IntegerFormatter"));
		$(".ratio", $row).text(ua.valueForKeyPathWithFormatterName("ratio", "RatioFormatter"));
	});		
};

DirectMail.configurePopularLocations = function( expanded ) {
	this.configurePopularItemRows( $("#most-popular-locations"), 'Locations', window.DirectMail_summaryViewController.dataSource.mostPopularLocations( expanded ? 0 : this.defaultPopularItemCount ), expanded, function( item, $row ){
		$(".location-name", $row).text(item.valueForKeyPath("representedObject"));
		$(".count", $row).text(item.valueForKeyPathWithFormatterName("value", "IntegerFormatter"));
		$(".ratio", $row).text(item.valueForKeyPathWithFormatterName("ratio", "RatioFormatter"));
	});		
};

DirectMail.togglePopularItemRows = function( identifier, configureCallback ) {
	var newExpanded = this.popularItemSectionExpanded[identifier] ? false : true;
	
	window.DirectMail_summaryViewController.setPopularItemSectionExpanded( identifier, newExpanded );
	configureCallback( newExpanded );
};

DirectMail.refreshHistory = function() {
    $("#mas-review-prompt").toggle( window.DirectMail_summaryViewController.shouldPromptForMASReview() ? true : false );

	var dataSource      = window.DirectMail_summaryViewController.dataSource;
	var deliveryHistory = dataSource.valueForKeyPath("deliveryHistory");
	
    DirectMail.setWindowTitle( deliveryHistory.valueForKeyPath("title") );
    DirectMail.refreshEmailIcon( deliveryHistory );
	$("#email-title").text(deliveryHistory.valueForKeyPath("title"));
	$("#notes-content").prop( 'readOnly', !window.DirectMail_summaryViewController.isDocumentEditable() ).val(deliveryHistory.valueForKeyPath("notes") || '');
	$("#email-summary").text(deliveryHistory.valueForKeyPath("localizedSummaryDescription"));
	
    var deliveryIsAutoresponder        = deliveryHistory.valueForKeyPath("isAutoresponderHistory");
	var deliveryCanBeRescheduled       = deliveryHistory.valueForKeyPath("canBeRescheduled");
	var deliveryCanBeCanceled          = deliveryHistory.valueForKeyPath("canBeCanceled");
    var deliveryCancellationInProgress = deliveryHistory.valueForKeyPath("cancellationInProgress");
	var deliveryIsRestartable          = deliveryHistory.valueForKeyPath("canBeRestarted");
	var deliveryIsDraft			       = deliveryHistory.valueForKeyPath("sendDate") ? false : true;
	
	$("#delivery-actions").toggle( deliveryCanBeRescheduled || deliveryCanBeCanceled || deliveryIsRestartable || deliveryIsAutoresponder ? true : false);
	$("#deliver-now-button, #reschedule-button").toggle( deliveryCanBeRescheduled && !deliveryIsAutoresponder ? true : false ).prop( 'disabled', false );
	$("#reschedule-button").text( deliveryIsDraft ? "Schedule Delivery" : "Reschedule Delivery" );
    $("#cancel-delivery-button").toggle( deliveryCanBeCanceled && !deliveryIsAutoresponder ? true : false ).text( deliveryCancellationInProgress ? "Canceling…" : "Cancel Delivery" ).prop( 'disabled', deliveryCancellationInProgress );
	$("#restart-delivery-button").toggle( deliveryIsRestartable && !deliveryIsAutoresponder ? true : false ).prop( 'disabled', false );
	$("#summary-period-select, #view-autoresponder-button").toggle( deliveryIsAutoresponder ? true : false );
	$("#summary-period-select").val( dataSource.numberOfDays );
	
	var shouldShowManualReviewNotice   = deliveryHistory.valueForKeyPath("shouldShowManualReviewNotice");
	var $manualReviewNotice		       = $("#manual-review-notice");
	var shouldShowDeliveryStatusAlerts = false;
	
	if ( shouldShowManualReviewNotice ) {
		$(".manual-review-recipients", $manualReviewNotice).text( deliveryHistory.valueForKeyPath("localizedManualReviewEmailRecipientsDescription") );
		$manualReviewNotice.show();
		shouldShowDeliveryStatusAlerts = true;
	}
	else {
		$manualReviewNotice.hide();
	}
		
	var status    = deliveryHistory.valueForKeyPath("status");
	var $inReview = $("#in-review");
	
	$("#in-review-draft").toggle( deliveryIsDraft );
	$("#in-review-scheduled").toggle( !deliveryIsDraft );
	
	if ( status == 4 ) {
		$inReview.show();
		shouldShowDeliveryStatusAlerts = true;
	}
	else {
		$inReview.hide();
	}
	
	var $updateError = $("#update-error");
	var updateError  = deliveryHistory.valueForKeyPath( "lastError" );
	
	if ( updateError ) {
		var updateErrorDescription = deliveryHistory.valueForKeyPath( "lastError.localizedDescription" );
		
		if ( updateErrorDescription ) {
			$updateError.text( "An error occurred while updating this report: " + updateErrorDescription );
		}
		else {
			$updateError.text( "An error occurred while updating this report." );
		}
		
		$updateError.show();
		shouldShowDeliveryStatusAlerts = true;
	}
	else {
		$updateError.hide();
	}
	
	var $deliveryStatusAlerts = $("#delivery-status-alerts");
	
	if ( shouldShowDeliveryStatusAlerts ) {
		$deliveryStatusAlerts.show();
	}
	else {
		$deliveryStatusAlerts.hide();
	}
    
	var numberOfAddresses = dataSource.valueForKeyPath("numberOfAddresses");
	var numbersContainer = $("#report .numbers-container" );
	var numbersDIVs = {
		bounce: 	 [$("div.bounce", numbersContainer), 'numberOfBounces', 'bounceRate', 'canShowBounces', 'Bounces'],
		open: 		 [$("div.open", numbersContainer), 'numberOfRecipientsWhoOpened', 'openRate', 'isTrackable', 'Recipients'],
		spam: 		 [$("div.spam", numbersContainer), 'numberOfSpamComplaints', 'spamComplaintRate', 'canShowSpamComplaints', 'Complaints'],
		unsubscribe: [$("div.unsubscribe", numbersContainer), 'numberOfUnsubscribes', 'unsubscribeRate', true, 'Unsubscribes'],
		click: 		 [$("div.click", numbersContainer), 'numberOfRecipientsWhoClicked', 'clickRate', 'isTrackable', 'Links'],
		noOpen: 	 [$("div.no-open", numbersContainer), 'numberOfUnopened', 'unopenRate', 'isTrackable', null]
	};
	
	for ( var key in numbersDIVs ) {
		var div 	    = numbersDIVs[key];
		var canShow     = ( div[3] === true || deliveryHistory.valueForKeyPath( div[3] ) );
		var numberValue = ( canShow ? dataSource.valueForKeyPath(div[1]) : null );
        
		$("span.current-number", div[0]).text( canShow ? dataSource.valueForKeyPathWithFormatterName(div[1], "IntegerFormatter") : '-' );
		$("span.current-percentage", div[0]).text( canShow ? dataSource.valueForKeyPathWithFormatterName( div[2], "RatioFormatter" ) : '-' );
		
		var historyViewControllerIdentifier = div[4];
		
		if ( numberValue && historyViewControllerIdentifier ) {
			$(div[0]).attr('data-hvc-identifier', historyViewControllerIdentifier).click(function(){
				window.DirectMail_summaryViewController.switchToHistoryViewControllerWithIdentifier($(this).attr('data-hvc-identifier'));
			});
		}
		else {
			$(div[0]).removeAttr('data-hvc-identifier').unbind('click');
		}
	}
	
	if ( !deliveryHistory.isTrackable() ) {
		$("#report div.bar").hide();
		$("#most-popular-links").hide();
		$("#most-popular-user-agents").hide();
		$("#most-popular-locations").hide();
	}
	else {
		var bars = {
			bounced: { selector: ".bounce", title: "bounced", ratioTitle: "recipients", valueKeyPath: "numberOfBounces", ratioValueKeyPath: "bounceRate", hvcIdentifier: "Bounces" },
			delivered: { selector: ".delivered", valueKeyPath: "numberOfDelivered", ratioValueKeyPath: "deliveredRate" },
			open: { 
				selector: ".open", 
				title: function() {
					var totalOpens = dataSource.valueForKeyPathWithFormatterName( 'numberOfViews', 'IntegerFormatter' );
					var s = dataSource.valueForKeyPathWithFormatterName( 'numberOfRecipientsWhoOpened', 'IntegerFormatter' )
						+ " opened ("
						+ dataSource.valueForKeyPathWithFormatterName( 'openRate', 'RatioFormatter')
						+ " of delivered emails, "
						+ totalOpens + " total open" + ( totalOpens != '1' ? 's' : '' )
						+ ")";
					return s;
				},
				valueKeyPath: "numberOfRecipientsWhoOpened",
	            ratioValueKeyPath: "openRate",
				hvcIdentifier: "Recipients"
			},
			click: { 
				selector: ".click", 
				title: function(){
					var totalClicks = dataSource.valueForKeyPathWithFormatterName( 'numberOfLinkClicks', 'IntegerFormatter' );
					var s = dataSource.valueForKeyPathWithFormatterName( 'numberOfRecipientsWhoClicked', 'IntegerFormatter' )
						+ " clicked ("
						+ dataSource.valueForKeyPathWithFormatterName( 'clickRate', 'RatioFormatter')
						+ " of delivered emails, "
						+ totalClicks + " total click" + ( totalClicks != '1' ? 's' : '' )
						+ ")";
					return s;
				}, 
				valueKeyPath: "numberOfRecipientsWhoClicked",
	            ratioValueKeyPath: "clickRate",
				hvcIdentifier: "Links"
			},
			spam: { selector: ".spam", title: "marked as spam", valueKeyPath: "numberOfSpamComplaints", ratioValueKeyPath: "spamComplaintRate", hvcIdentifier: "Complaints" },
			unsubscribe: { selector: ".unsubscribe", title: "unsubscribed", valueKeyPath: "numberOfUnsubscribes", ratioValueKeyPath: "unsubscribeRate", hvcIdentifier: "Unsubscribes" }
		};

		var $bar = $("#report .bar");

		for ( var key in bars ) {
			var bar   = bars[key];
			var $div  = $(bar.selector, $bar);
			var value = dataSource.valueForKeyPath( bar.valueKeyPath );
			
			$div.attr( 'data-bar-visible', value > 0 ? 'true' : 'false' );
			
			if ( !value ) {
				$div.hide();
			}
			else {				
	            var ratio = dataSource.valueForKeyPath( bar.ratioValueKeyPath );
				var width = ( ratio * 100 );
				
				$div.width( width + '%' ).show();
				
				if ( bar.title ) {
					var valueFormatted = dataSource.valueForKeyPathWithFormatterName( bar.valueKeyPath, 'IntegerFormatter' );
					var ratioFormatted = dataSource.valueForKeyPathWithFormatterName( bar.ratioValueKeyPath, 'RatioFormatter' );
					var title 		   = ( typeof bar.title === 'function' ? bar.title() : valueFormatted + ' ' + bar.title + ' (' + ratioFormatted + ' of ' + ( bar.ratioTitle ? bar.ratioTitle : 'delivered emails' )  + ')' );
			
					$div.data('tooltip-title', title);
				}
				
				if ( bar.hvcIdentifier ) {
					$div.attr('data-hvc-identifier', bar.hvcIdentifier).click(function() {
						window.DirectMail_summaryViewController.switchToHistoryViewControllerWithIdentifier($(this).attr('data-hvc-identifier'));
					});					
				}
			}
		}
		
		var $visibleDeliveredBars = $(".delivered > div[data-bar-visible=\"true\"]", $bar);
		
		if ( $visibleDeliveredBars.length ) {
			$visibleDeliveredBars.css( 'height', $bar.height() / $visibleDeliveredBars.length );
		}
								
		this.configurePopularLinks( window.DirectMail_summaryViewController.isPopularItemSectionExpanded( 'Links' ) );
		this.configurePopularUserAgents( window.DirectMail_summaryViewController.isPopularItemSectionExpanded( 'UserAgents' ) );
		this.configurePopularLocations( window.DirectMail_summaryViewController.isPopularItemSectionExpanded( 'Locations' ) );
	}
	
	var lastUpdated      = deliveryHistory.valueForKeyPathWithFormatterName( "lastUpdateTime", "PhraseLongShortDateFormatter" );
	var reportFooterText = ( lastUpdated ? "Last updated " + lastUpdated : "" );
	
	if ( deliveryHistory.isTrackable() ) {
		if ( reportFooterText.length ) {
			reportFooterText += ". ";
		}
		
		reportFooterText += "Email image blocking may prevent some opens from being reported.";
	}
	
	$("#report-footer").text( reportFooterText );
	$("#notes-content").data('AutoResizer').check(null, true);
	
	window.DirectMail_summaryViewController.historyDidRefresh();
};

DirectMail.notes = function() {
	return $("#notes-content").val();
};

$(document).ready(function() {
    var $masReviewPrompt = $("#mas-review-prompt");
    
	$( "#mas-write-review", $masReviewPrompt).click(function() {
		window.DirectMail_summaryViewController.writeMASReview();
		DirectMail.refreshHistory();
		return false;
	});

	$( "#mas-decline-review", $masReviewPrompt).click(function() {
		window.DirectMail_summaryViewController.declineMASReview();
		DirectMail.refreshHistory();
		return false;
	});                  

	$( "#mas-support", $masReviewPrompt).click(function() {
		window.DirectMail_summaryViewController.openMASSupport();
		return false;
	});                  
                  
	var $numbers     = $('.numbers-container .current-number');
	var $percentages = $('.numbers-container .current-percentage');
	
	$('.number').hover(
		function() { 
			$percentages.css('display', 'block'); 
			$numbers.css('display', 'none');
		},
		function() { 
			$numbers.css('display', 'block'); 
			$percentages.css('display', 'none');
		}
	);
		
	var tooltipEdgePadding = 20, tooltipRightEdgeLimit = 0, tooltipLeftEdgeLimit;
	var $wrapper = $("#wrapper");
    var calculateTooltipEdgeLimits = function() {
		var wrapperLeftOffset = $wrapper.offset().left;
        tooltipRightEdgeLimit = wrapperLeftOffset + $wrapper.width() - tooltipEdgePadding;
        tooltipLeftEdgeLimit  = wrapperLeftOffset + tooltipEdgePadding;
    };

    calculateTooltipEdgeLimits();

    $(window).resize(function() {
        calculateTooltipEdgeLimits();
    });

	var $tooltip = null, $tooltipTriangle = null;
		
	var destroyTooltip = function () {
		if ( $tooltip ) {
			$tooltip.remove();
			$tooltip = $tooltipTriangle = null;
		}
	};
	
	var destroyTooltipIfOutOfBounds = function( x, y ) {
		var destroyed    = false;
        var mouseElement = document.elementFromPoint( x, y );
        
        if ( !mouseElement || !$(mouseElement).hasClass('with-tooltip') ) {
            destroyTooltip();
			destroyed = true;
        }

		return destroyed;
	};
	
    var positionTooltip = function ( x, element, animate ) {	
		if ( !$tooltip ) {
			$tooltip = $("#tooltip");
			$tooltipTriangle = $("#triangle");
		}

		var y = $(element).offset().top + 8;

		if ( destroyTooltipIfOutOfBounds( x, y ) ) {
			return;
		}
	
		var tooltipHeight = $tooltip.height();
        var top      	  = y - ( tooltipHeight + $tooltipTriangle.height() );
        var tooltipWidth  = $tooltip.width();
        var triangleWidth = $tooltipTriangle.width();
        var left 	 	  = x - tooltipWidth / 2;
		var triangleLeft  = 0;

        if ( left + tooltipWidth > tooltipRightEdgeLimit ) {
            left = tooltipRightEdgeLimit - tooltipWidth;
            triangleLeft = x - left - triangleWidth / 2;
        }
        else if ( left < tooltipLeftEdgeLimit ) {
            left = tooltipLeftEdgeLimit;
            triangleLeft = x - left - triangleWidth / 2;
        }
        else {
            triangleLeft = tooltipWidth / 2 - triangleWidth / 2;
        }

		$tooltip.css({ top: top, left: left });
		$tooltipTriangle.css( 'left', triangleLeft );
		
		if ( animate ) {
			$tooltip.css({
				'-webkit-transform-origin-x' : ( 100 * ( triangleLeft + triangleWidth / 2 ) / tooltipWidth ) + '%',
				'-webkit-transform-origin-y' : ( ( tooltipHeight ) + ( 0.5 * Math.sqrt( 2 * Math.pow( triangleWidth, 2 ) ) ) ) + 'px'
			}).addClass('popped');
		}
    };
                  
    $('.with-tooltip').mouseover(function(e) {
        destroyTooltip();
        $("body").append('<div id="tooltip"><div class="tip-body">' + $(this).data('tooltip-title') + '</div><div class="tip-footer"><div id="triangle"></div></div></div>');
		positionTooltip( e.pageX, this, true );
    }).mousemove(function(e) {
		positionTooltip( e.pageX, this, false );
    }).mouseout(function(e) {
        destroyTooltipIfOutOfBounds( e.pageX, $(this).offset().top );
    });

	$(".bar").mouseleave(function(e) {
		destroyTooltip();
	});

	$("#email-icon").click(function() {
		window.DirectMail_summaryViewController.switchToHistoryViewControllerWithIdentifier("Message");
		return false;
	});
                  
	if ( window.matchMedia !== undefined ) {
	    window.matchMedia('(-webkit-device-pixel-ratio:2)').addListener(function( mediaQueryList ) {
	        var deliveryHistory = window.DirectMail_summaryViewController.dataSource.valueForKeyPath("deliveryHistory");
                                                                    
	        if ( deliveryHistory ) {
		        DirectMail.refreshEmailIcon( deliveryHistory );
	        }
	    });
	}
	
	$("#view-autoresponder-button").click(function() {
		window.DirectMail_summaryViewController.viewAutoresponder();
		return false;
	});
	
	$("#summary-period-select").change(function() {
		window.DirectMail_summaryViewController.dataSource.numberOfDays = parseInt( $(this).val() );
		return false;
	});
	
	$("#cancel-delivery-button").click(function() {
		window.DirectMail_summaryViewController.cancelDelivery();
		return false;
	});

	$("#restart-delivery-button").click(function() {
		$(this).prop( 'disabled', true );
		window.DirectMail_summaryViewController.restartDelivery();
		return false;
	});

	$("#deliver-now-button").click(function() {
		window.DirectMail_summaryViewController.deliverNow();
		return false;
	});

	$("#reschedule-button").click(function() {
		window.DirectMail_summaryViewController.rescheduleDelivery();
		return false;
	});
    
	$("#most-popular-links tr.expand-row div.arrow").click(function() {
		DirectMail.togglePopularItemRows( "Links", function( expanded ) { DirectMail.configurePopularLinks(expanded); } );
	});

	$("#most-popular-user-agents tr.expand-row div.arrow").click(function() {
		DirectMail.togglePopularItemRows( "UserAgents", function( expanded ) { DirectMail.configurePopularUserAgents(expanded); } );
	});

	$("#most-popular-locations tr.expand-row div.arrow").click(function() {
		DirectMail.togglePopularItemRows( "Locations", function( expanded ) { DirectMail.configurePopularLocations(expanded); } );
	});

	$("#delivery-status-alerts, .popular-item-template, .expand-row").hide();
	$("#notes-content").autoResize();
	
	window.DirectMail_summaryViewController.setMessageThumbnailElementCSSSelector( '#email-icon' );
	DirectMail.refreshHistory();
});
