if (Garmin == undefined) var Garmin = {};
if (Garmin.Communicator == undefined) Garmin.Communicator = {};
if (Garmin.Communicator.Display == undefined) Garmin.Communicator.Display = {};

Garmin.Communicator.Display.SendCourseConstants = {
    DEFAULT_SEND_DATA_URL								: 'proxy/activity-service-1.1/tcx/course/' + ACTIVITY_ID,
    DEFAULT_SEND_DATA_URL_GPX							: 'proxy/activity-service-1.1/gpx/course/' + ACTIVITY_ID,
    DEFAULT_BINARY_WRITE_DESCRIPTION					: 'proxy/activity-service-1.1/fit/course/' + ACTIVITY_ID,
    ID													: ACTIVITY_ID,
	TYPE_ACTIVITY							: 'activity',
	TYPE_COURSE							: 'course'
};

if(typeof(ACTIVITY_OR_COURSE) != 'undefined' && ACTIVITY_OR_COURSE == Garmin.Communicator.Display.SendCourseConstants.TYPE_COURSE) {
    Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL = '/proxy/course-service-1.0/tcx/course/' + COURSE_ID;
    Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL_GPX = '/proxy/course-service-1.0/gpx/course/' + COURSE_ID;
    Garmin.Communicator.Display.SendCourseConstants.DEFAULT_BINARY_WRITE_DESCRIPTION = '/proxy/course-service-1.0/fit/course/' + COURSE_ID;
}

/** 
 * 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",
	plugInNotInstalledDialogId: 	"pluginNotInstalled",

	/* Header */
	headerText:        				bundle_activity_api.sendToDevice,
	closeButtonText:   				bundle_activity_api.close,
	
	initialize: function(activityOrCourse) {
		this.display = null;
	    	this.overrideMessages();
		this.createGarminDeviceDisplay();
	},
	
	setActivityOrCourse: function(activityOrCourse){
		this.activityOrCourse = activityOrCourse;

		if(typeof(activityOrCourse) != 'undefined' && activityOrCourse == Garmin.Communicator.Display.SendCourseConstants.TYPE_COURSE) {
			Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL = '/proxy/course-service-1.0/tcx/course/' + COURSE_ID;
		    Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL_GPX = '/proxy/course-service-1.0/gpx/course/' + COURSE_ID;
		    Garmin.Communicator.Display.SendCourseConstants.DEFAULT_BINARY_WRITE_DESCRIPTION = '/proxy/course-service-1.0/fit/course/' + COURSE_ID;
		    Garmin.Communicator.Display.SendCourseConstants.ID = COURSE_ID;
		}
	},
	
	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,
			poweredByGarmin:                                '<div class="sendToDeviceNoticeWrapper">'
                                                            + '<div class="noticeHeader">'+bundle_activity_api.sendToDevice_tips+'</div>'
			                                                + '<div class="noticeBody">'+bundle_activity_api.sendToDevice_tips_one+'</div>'
                                                    		+ '<div class="noticeBody">'+bundle_activity_api.sendToDevice_tips_two+'</div>'
                                                    		+'</div>',
						
			sendDataUrl: 									Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL,
			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:
								this.options.sendDataUrl = Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL;
								filePath = device.getDeviceDataType(Garmin.DeviceControl.FILE_TYPES.fitCourse).getWriteFilePath();								
								break;
							case Garmin.DeviceControl.FILE_TYPES.crs:
								this.options.sendDataUrl = Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL;
								this.options.sendOptions = {
                                    method: 'GET',
                                    parameters:  
							        {
								       random: Math.floor(Math.random()*1000)
							        }
                                };
                                
                                break;
							case Garmin.DeviceControl.FILE_TYPES.gpx:
								this.options.sendDataUrl = 	Garmin.Communicator.Display.SendCourseConstants.DEFAULT_SEND_DATA_URL_GPX;							
								this.options.sendOptions = {
                                   method: 'GET',
								   parameters:  
							       {
								      random: Math.floor(Math.random()*1000)
							       }
							   };
								break;							
						}
					}
				}				
			},
			
			//writeDataType:                     Garmin.DeviceControl.FILE_TYPES.crs,
			writeDataTypes:                      [Garmin.DeviceControl.FILE_TYPES.fitCourse, Garmin.DeviceControl.FILE_TYPES.crs, Garmin.DeviceControl.FILE_TYPES.gpx],
			getWriteDataFileName:                function() { return "course_" + Garmin.Communicator.Display.SendCourseConstants.ID + ".gpx"; },
			getWriteData:                        function() { return coursePayload; },
			getBinaryWriteDescription:           function() { return [Garmin.Communicator.Display.SendCourseConstants.DEFAULT_BINARY_WRITE_DESCRIPTION, filePath + "\\course_" + Garmin.Communicator.Display.SendCourseConstants.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(activityOrCourse) {
		if(activityOrCourse == 'undefined'){
			activityOrCourse = Garmin.Communicator.Display.SendCourseConstants.TYPE_ACTIVITY;
		};
		
       $(this.garminDisplayId).innerHTML = '';
       sendToDeviceDisplay.setActivityOrCourse(activityOrCourse);
       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
};

jQuery(document).ready(function(){
   sendToDeviceDisplay = new Garmin.Communicator.Display.SendCourse();
});


