if (Garmin == undefined) var Garmin = {};
if (Garmin.Communicator == undefined) Garmin.Communicator = {};
if (Garmin.Communicator.Display == undefined) Garmin.Communicator.Display = {};

/** 
 * This class configures Garmin DeviceDisplay appropriately to send a course to device.
 * 
 * @constructor 
 */
Garmin.Communicator.Display.SendCourse = Class.create();
Garmin.Communicator.Display.SendCourse.prototype = {

	garminDisplayId: 				"garminDisplay",
	headerId:          				"wizardHeader",
	plugInNotInstalledDialogId: 	"pluginNotInstalled",

	/* Header */
	headerText:        				bundle_activity_api.sendToDevice,
	closeButtonText:   				bundle_activity_api.close,
	
	initialize: function() {
		this.display = null;
	    this.initializeHeader();
	    this.overrideMessages();
		this.createGarminDeviceDisplay();
	},
	
	initializeHeader: function() {
	    var header = $(this.headerId);
	    var closeButton = new Element('a', {id: 'closeWizardButton', className: 'wizardCloseIcon', href: ''}).update(this.closeButtonText);
	    
	    closeButton.onclick = function() {
	        Effect.Fade('wizardBackground', { duration: 0.5 }); 
	        return false;
	    }
	    
	    header.insert(this.headerText);
	    header.insert(closeButton);
	},

	createGarminDeviceDisplay: function() {
		var coursePayload = Garmin.Communicator.Display.SendCourse.Data.coursePayload;
		var filePath = "Courses";
		
 		// Configure Communicator DeviceDisplay instance for software updates.
	    this.display = new Garmin.DeviceDisplay(this.garminDisplayId, {
	    	
	    	/* Unlock key */
	    	pathKeyPairsArray: 								Garmin.Communicator.Constants.API_KEYS,
	    	
	    	showReadDataElement: 							false,
			showProgressBar: 								true,
			showFindDevicesElement: 						true,
			showFindDevicesButton: 							false,
			autoFindDevices: 								true,
			showDeviceButtonsOnFound: 						true,
			showDeviceSelectOnLoad: 						false,
			showSendDataElement:							true,
			showSendDataElementOnDeviceFound: 				true,
			
			deviceSelectLabel: 								bundle_activity_api.sendToDevice_label_chooseDevice + " <br/>",
			downloadAndInstall:             				bundle_activity_api.sendToDevice_link_downloadAndInstall,
			foundDevice: 				    				bundle_activity_api.sendToDevice_status_foundDevice,
			foundDevices: 				    				bundle_activity_api.sendToDevice_status_foundDevices,
			lookingForDevices: 								bundle_activity_api.sendToDevice_status_searching + ' <br/><br/> <img src="/api/activity/component/sendToDevice/images/icon-loading.gif"/>',
			poweredByGarmin:                				bundle_activity_api.sendToDevice_label_poweredBy + " <a href='http://www.garmin.com/products/communicator/' target='_new'>Garmin Communicator</a>",
			dataDownloadProcessing:         				bundle_activity_api.sendToDevice_status_processing,
			sendDataButtonText: 							bundle_activity_api.sendToDevice_button_sendCourse,
			sendingDataToServer:							bundle_activity_api.sendToDevice_status_preparingCourse,
			unsupportedWriteDataType:       				bundle_activity_api.sendToDevice_error_deviceNotSupported,
			usingDevice:         							bundle_activity_api.sendToDevice_status_usingDevice,
						
			sendDataUrl: 									'/proxy/activity-service-1.1/tcx/course/' + ACTIVITY_ID,
			sendDataOptions:								{
                                                            	method: 'GET',
																parameters:  
																{
																	random: Math.floor(Math.random()*1000)
																}
															},
												
			pluginRequiredVersion:							[2,5,0,2],
			pluginLatestVersion:							[2,5,1,0],
			showDetailedStatus:								false,
			
			afterFinishSendData: function (ajaxResponse) {
				if (ajaxResponse == null) {
    				// Developer error, doesn't need to be localized
					throw new Error("Error getting response from server. Check the request URL and try again.");
				}
				
				coursePayload = ajaxResponse.responseText;
				
				if (coursePayload == null) {
    				// Developer error, doesn't need to be localized
					throw new Error("Could not retrieve course payload from the response.  Check that the response has a responseText element.");
				}
				
				this.writeToDevice();
			},
			
			afterSelectDevice: function(deviceNumber, devices, deviceXml) {				
				// Determine if the device supports the data type for writing
				var device = devices[deviceNumber];
				var supported = null;
				
				for (var i = 0; i < this.options.writeDataTypes.length; i++) {
					var dataType = this.options.writeDataTypes[i];
					var deviceWriteSupport = device.supportDeviceDataTypeWrite(dataType);
					
					if (supported == null && deviceWriteSupport == true) {
						supported = dataType;
						
						switch (dataType) {
                            // If the dataType is of fitCourse, we need to override the endpoint and get the FIT course instead.
							case Garmin.DeviceControl.FILE_TYPES.fitCourse:
								filePath = device.getDeviceDataType(Garmin.DeviceControl.FILE_TYPES.fitCourse).getFilePath();								
								break;
						}
					}
				}				
			},
			
			//writeDataType:                     Garmin.DeviceControl.FILE_TYPES.crs,
			writeDataTypes:                      [Garmin.DeviceControl.FILE_TYPES.fitCourse, Garmin.DeviceControl.FILE_TYPES.crs],
			getWriteData:                        function() { return coursePayload; },
			getBinaryWriteDescription:           function() { return ["/proxy/activity-service-1.1/fit/course/" + ACTIVITY_ID, filePath + "\\course_" + ACTIVITY_ID + ".FIT"] },
			
			afterFinishWriteToDevice: function(success) {
				if(success) {
					this.setStatus(bundle_activity_api.sendToDevice_status_success);
				} else {
					this.setStatus(bundle_activity_api.sendToDevice_status_fail);
				}
			}
	    });
	},
	/*
	 * Reset the display to initial screen.
	 */
	resetDisplay: function() {
       $(this.headerId).innerHTML = '';
       sendToDeviceDisplay.initializeHeader();
       
       $(this.garminDisplayId).innerHTML = '';
       sendToDeviceDisplay.createGarminDeviceDisplay();
	},
	
    /** 
     * Override - Constants defining possible errors messages for various errors on the page
     */
	overrideMessages: function() {
        Garmin.DeviceControl.MESSAGES = {
        	browserNotSupported: bundle_activity_api.sendToDevice_error_browserNotSupported,
        	pluginNotInstalled: bundle_activity_api.sendToDevice_error_pluginNotDetected,
        	outOfDatePlugin1: bundle_activity_api.sendToDevice_error_versionOutdated + "<br/>" + bundle_activity_api.sendToDevice_error_versionOutdated_required + " ",
        	outOfDatePlugin2: bundle_activity_api.sendToDevice_error_versionOutdated_current + " "
        };
	}
};

/**
 * Data storage to allow for transfer of objects between the components of this display layer.
 */
Garmin.Communicator.Display.SendCourse.Data = function(){};
Garmin.Communicator.Display.SendCourse.Data = {
	/** The course payload to transfer to device. */
	coursePayload:			null
};