/**
 * @class HD.UploadWidget
 * @description The purpose of UploadWidget is to provide a mechanism for users to upload
 * 				a photo or video for user generated content.
 * 				Registered as hd_upload_widget.
 * @constructor
 * @extends HD.Widget
 * @see HD.UploadWidget.hooks
 * @see HD.UploadWidget.templates
 * @property {object} 	config
 *                    	The configuration for the widget.
 * @property {object} 	[config.hooks=HD.UploadWidget.hooks]
 *                 		Customized subset of hooks (merged with the defaults).
 * @property {array} 	config.actions
 *                    	Creates an array of buttons for the confirmation overlay.
 *                    	Default is empty.
 * @property {object}	config.dialog
 * 						Can be used to store dimensions for confirmation, but
 * 						should be deprecated
 * 						Default is empty
 * @property {array} 	config.categories
 *                 		List of category names
 * @property {array} 	config.categoriesFriendly
 *                 		List of friendly category names corresponding to config.categories 
 * @property {string} 	config.siteSection
 *                 		Subsection of current site
 *                 		Default is empty
 * @property {string}	config.overlayWidth
 * 						Pixel width of main overlay
 * 						Default is 590px
 * @property {string}	config.overlayHeight
 * 						Pixel height of main overlay
 * 						Default is 525px
 * @property {string}	config.overlayConfirmationWidth
 * 						Pixel width of confirmation overlay
 * 						Default is 580px
 * @property {string}	config.overlayConfirmationHeight
 * 						Pixel height of confirmation overlay
 * 						Default is 150px
 * @property {object} 	[config.templates=HD.UploadWidget.templates]
 *                 		Customized subset of templates (merged with the defaults).			         
 */
HD.UploadWidget = function(config) {
    this.config = config || {};
	// Actions is an array of action names to add to the upload dialog after confirmation.
	this.config.actions = this.config.actions || [];
	this.config.dialog = this.config.dialog || {};
	
	// Friendly names for category dropdown
    this.config.categoriesFriendly = this.config.categoriesFriendly || this.config.categories;
    this.config.siteSection = this.config.siteSection || "";
    
    this.config.overlayWidth = this.config.overlayWidth || '590px';
    this.config.overlayHeight = this.config.overlayHeight || '525px';
    this.config.overlayConfirmationWidth = this.config.overlayConfirmationWidth || this.config.dialog.confirm ? this.config.dialog.confirm[0] : '580px';
    this.config.overlayConfirmationHeight = this.config.overlayConfirmationHeight || this.config.dialog.confirm ? this.config.dialog.confirm[1] : '150px';
    this.config.overlayParent = this.config.overlayParent || 'hdwcUGCSubmission';
    this.config.showNewMemberMessage = false;
    this.observers = [];
    this.user = null;
    this.loggedInLevel = null;
	this.progress = null;
	this.file = null;
	this.loadTemplates(arguments.callee);
};

HD.UploadWidget.templates = {
	overlayTitle            : 'Upload',
	unsupportedFileTypeText : [	"You must submit a photo or a video.<br/>",
						       	"Photo must use the following format: (.jpg, .gif)<br/>",
						       	"Video must use the following format: (.flv, .wmv, .asf, .avi, .mov, .3gp, .mpg, .mpeg, .mp4)<br/>"
						      ].join(""),
	
	/**
	 * Title label for the widget
	 * @memberOf HD.UploadWidget
	 */
	uploadLabel : "UPLOAD",	
	
	/**
	 * Personalized label for the widget
	 * @memberOf HD.UploadWidget
	 */
	personalizedLabel : "You are logged in as: [${USERNAME}] <a href=\"javascript:void(0)\" onclick=\"login.view.logoutUser.call(login.view);HD.util.Common.hideOverlay();\">Not ${USERNAME}?</a>",
	
	/**
	 * Generic label for the widget
	 * @memberOf HD.UploadWidget
	 */
	personalizedLabelGeneric : "Your online profile has been created. You will receive a confirmation email shortly.",
	
	/**
	 * Intro text for the widget
	 * @memberOf HD.UploadWidget
	 */
	introText : "Just give it a title, upload a file, and type in a description.",
	
	/**
	 * Required text for the widget
	 * @memberOf HD.UploadWidget
	 */
	requiredText : "* Indicates required fields",
	
	/**
	 * Category default text for the widget
	 * @memberOf HD.UploadWidget
	 */
	categoryLabel : "Category",
	
	/**
	 * Category label for the widget
	 * @memberOf HD.UploadWidget
	 */
	categoryDefaultText : "Select a Category",
	
	/**
	 * Media Upload label for the widget
	 * @memberOf HD.UploadWidget
	 */
	uploadMediaLabel : "Title",
	
	/**
	 * Upload Media Type Both label for the widget
	 * @memberOf HD.UploadWidget
	 */	
	uploadMediaTypeBothLabel : "Upload Photo OR Video",
	
	/**
	 * Upload Media Type Photo label for the widget
	 * @memberOf HD.UploadWidget
	 */	
	uploadMediaTypePhotoLabel : "Upload Photo",
	
	/**
	 * Upload Media Type Video label for the widget
	 * @memberOf HD.UploadWidget
	 */	
	uploadMediaTypeVideoLabel : "Upload Video",
	
	/**
	 * Media instructional text Both for the widget
	 * @memberOf HD.UploadWidget
	 */	
	mediaInstructionsBothText : "<ul>" +
								"<li>Your Photo must be in .jpg or .gif format and no more than 10 MB.  Horizontal formatting is preferred.</li>" +
								"<li>Your Video must be less than 4 minutes, no more than 100 MB and be in one of the following formats: .flv, .wmv, .asf, .avi, .mov, .3gp, .mpg, .mpeg, or .mp4. </li>" +
								"<li>Do not include music in your video.</li>" +
								"</ul>",
								
	/**
	 * Media instructional text Photo for the widget
	 * @memberOf HD.UploadWidget
	 */	
	mediaInstructionsPhotoText : "<ul>" +
								 "<li>Your Photo must be in .jpg or .gif format and no more than 10 MB.  Horizontal formatting is preferred.</li>" +
								 "</ul>",
	
	/**
	 * Media instructional text Photo for the widget
	 * @memberOf HD.UploadWidget
	 */	
	mediaInstructionsVideoText : "<ul>" +
								 "<li>Your Video must be less than 4 minutes, no more than 100 MB and be in one of the following formats: .flv, .wmv, .asf, .avi, .mov, .3gp, .mpg, .mpeg, or .mp4. </li>" +
								 "<li>Do not include music in your video.</li>" +
								 "</ul>",
		
	/**
	 * Description label for the widget
	 * @memberOf HD.UploadWidget
	 */	
	descriptionLabel : "Description",
	
	/**
	 * Description instruction text for the widget
	 * @memberOf HD.UploadWidget
	 */	
	descriptionInstructionText : "Please describe your submission in 2500 characters or less.",
	
	/**
	 * Terms agreement intro text for the widget
	 * @memberOf HD.UploadWidget
	 */	
	termsAgreeText : "By submitting your content, you confirm that you are at least 18 years of age (or the age of majority in your state of residence) and agree to the terms and conditions stated in <a onclick=\"javascript:window.open('http://www.harley-davidson.com/wcm/Content/Pages/Utility/user_content_policy.jsp?locale=en_US', '', 'width=598,height=540,scrollbars=yes,resizable=yes,toolbar=no,location=no,menubar=no,directories=no,status=no')\" href=\"javascript:void(0)\">Harley-Davidson's Policy For User-Submitted Content</a>.",
	
	/**
	 * Submit button label for the widget
	 * @memberOf HD.UploadWidget
	 */
	submitLabel : "SUBMIT",
	
	/**
	 * Cancel button label for the widget
	 * @memberOf HD.UploadWidget
	 */
	cancelLabel : "CANCEL",
	
	/**
	 * Suggestions swivel text for the widget
	 * @memberOf HD.UploadWidget
	 */
	suggestionsSwivelText : "&#62",
	
	/**
	 * Suggestions swivel text (active) for the widget
	 * @memberOf HD.UploadWidget
	 */
	suggestionsSwivelTextActive : "v",
	
	/**
	 * Confirmation label for the widget
	 * @memberOf HD.UploadWidget
	 */
	confirmationLabel : "THANK YOU",
	
	/**
	 * Thank you text for the widget
	 * @memberOf HD.UploadWidget
	 */
	thankYouText : "Thank you for your submission.  Subject to our <a onclick=\"javascript:window.open('http://www.harley-davidson.com/wcm/Content/Pages/Utility/user_content_policy.jsp?locale=en_US', '', 'width=598,height=540,scrollbars=yes,resizable=yes,toolbar=no,location=no,menubar=no,directories=no,status=no')\" href=\"javascript:void(0)\">Policy for User-Submitted Content</a>, it generally takes 1-2 business days to post content.",
	
	/**
	 * Continue button label for the widget
	 * @memberOf HD.UploadWidget
	 */
	continueLabel : "CONTINUE",
						      
	suggestionsAndGuidelinesText : '',					      
	
	getOverlayTitle : function() {
		return this.overlayTitle;
	},
	
	getUnsupportedFileTypeText : function() {
		return this.unsupportedFileTypeText;
	},
	
	getSuggestionsAndGuidelinesText : function() {
		return this.suggestionsAndGuidelinesText;
	},
	
	/**
	 * @constant
	 * @return {string} Suggestions swivel diplay for for the widget: suggestionsSwivelText
	 * @memberOf HD.UploadWidget
	 */
	getSuggestionsSwivelText : function() {
		return this.suggestionsSwivelText;
	},	
	
	/**
	 * @constant
	 * @return {string} Suggestions swivel diplay (active) for for the widget: suggestionsSwivelTextActive
	 * @memberOf HD.UploadWidget
	 */
	getSuggestionsSwivelTextActive : function() {
		return this.suggestionsSwivelTextActive;
	},	
	
	/**
	 * @constant
	 * @return {string} Title label for the widget: uploadLabel
	 * @memberOf HD.UploadWidget
	 */
	getUploadLabel : function() {
		return this.uploadLabel;
	},
	
	/**
	 * @constant
	 * @return {string} Personalized label for the widget: personalizedLabel
	 * @memberOf HD.UploadWidget
	 */
	getPersonalizedLabel : function(user, loggedInLevel, showNewMemberMessage) {
		if (user && loggedInLevel > 1 && !showNewMemberMessage){
			return this.personalizedLabel.replace(/\$\{USERNAME\}/g, user.screenName);
		}
		else{
			return this.personalizedLabelGeneric;			
		}
	},
	
	/**
	 * @constant
	 * @return {string} Introduction text for the widget: introText
	 * @memberOf HD.UploadWidget
	 */
	getIntroText : function() {
		return this.introText;
	},
	
	/**
	 * @constant
	 * @return {string} Required text for the widget: requiredText
	 * @memberOf HD.UploadWidget
	 */
	getRequiredText : function() {
		return this.requiredText;
	},
	
	/**
	 * @constant
	 * @return {string} Category label for the widget: categoryLabel
	 * @memberOf HD.UploadWidget
	 */
	getCategoryLabel : function() {
		return this.categoryLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Category default text for the widget: categoryDefaultText
	 * @memberOf HD.UploadWidget
	 */
	getCategoryDefaultText : function() {
		return this.categoryDefaultText;
	},	
	
	/**
	 * @constant
	 * @return {string} Upload media label for the widget: uploadMediaLabel
	 * @memberOf HD.UploadWidget
	 */
	getUploadMediaLabel : function() {
		return this.uploadMediaLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Upload media type label for the widget: uploadMediaTypeLabel
	 * @memberOf HD.UploadWidget
	 */
	getUploadMediaTypeLabel : function(mediaType) {
		var uploadMediaTypeLabel = this.uploadMediaTypeBothLabel;
		if (HD.community.isPhoto(mediaType)){
			uploadMediaTypeLabel = this.uploadMediaTypePhotoLabel;
		}
		else if (HD.community.isVideo(mediaType)){
			uploadMediaTypeLabel = this.uploadMediaTypeVideoLabel;
		}
		return uploadMediaTypeLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Media instructional text for the widget: mediaInstructionsText
	 * @memberOf HD.UploadWidget
	 */
	getMediaInstructionsText : function(mediaType) {
		var mediaInstructionsText = this.mediaInstructionsBothText;
		if (HD.community.isPhoto(mediaType)){
			mediaInstructionsText = this.mediaInstructionsPhotoText;
		}
		else if (HD.community.isVideo(mediaType)){
			mediaInstructionsText = this.mediaInstructionsVideoText;
		}
		return mediaInstructionsText;
	},	
	
	/**
	 * @constant
	 * @return {string} Description label for the widget: descriptionLabel
	 * @memberOf HD.UploadWidget
	 */
	getDescriptionLabel : function() {
		return this.descriptionLabel;
	},
	
	/**
	 * @constant
	 * @return {string} Description instructional text for the widget: descriptionInstructionsText
	 * @memberOf HD.UploadWidget
	 */
	getDescriptionInstructionText : function() {
		return this.descriptionInstructionText;
	},	
	
	/**
	 * @constant
	 * @return {string} Terms & conditions introductory text for the widget: termsAgreeText
	 * @memberOf HD.UploadWidget
	 */
	getTermsAgreeText : function() {
		return this.termsAgreeText;
	},	
	
	/**
	 * @constant
	 * @return {string} Submit button label for for the widget: submitLabel
	 * @memberOf HD.UploadWidget
	 */
	getSubmitLabel : function() {
		return this.submitLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Cancel button label for for the widget: submitLabel
	 * @memberOf HD.UploadWidget
	 */
	getCancelLabel : function() {
		return this.cancelLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Confirmation label for for the widget: confirmationLabel
	 * @memberOf HD.UploadWidget
	 */
	getConfirmationLabel : function() {
		return this.confirmationLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Thank you text for for the widget: thankYouText
	 * @memberOf HD.UploadWidget
	 */
	getThankYouText : function() {
		return this.thankYouText;
	},	
	
	/**
	 * @constant
	 * @return {string} Continue label for for the widget: continueLabel
	 * @memberOf HD.UploadWidget
	 */
	getContinueLabel : function() {
		return this.continueLabel;
	},	
	
	/**
	 * @constant
	 * @return {string} Overlay template for the widget
	 * @memberOf HD.UploadWidget
	 */
	getOverlayHtml : function() {
		return this.overlayHtml;
	},
	
	/**
	 * @constant
	 * @return {string} Overlay confirmation template for the widget
	 * @memberOf HD.UploadWidget
	 */
	getOverlayConfirmationHtml : function() {
		return this.overlayConfirmationHtml;
	},
	
	/** 
	 * Overlay template for the widget
	 * @memberOf HD.UploadWidget
	 * @type jst_template
	 */	
	overlayHtml :  '\
		<div id="hdwcUGCSubmission">\
			<div class="dblRuleBtm">\
				<div class="head">${templates.getUploadLabel()}</div>\
			</div>\
			<div class="hdwcLrgPadBtm">\
		    	<div id="hdwcInstructions">\
		    		${templates.getPersonalizedLabel(user, loggedInLevel, config.showNewMemberMessage)}\
		    	</div>\
			</div>\
			<div id="hdwcBody">\
				<div class="hdwcLrgPadBtm ${hooks.SCROLLER}" id="scrollableDiv" style="height:410px;overflow-y:auto;overflow-x:hidden;padding:0;">\
					<div class="hdwcLrgPadBtm">\
					    <div id="submissionInstructions">\
			    			<div class="hdInstructionsBox">\
			    				<div class="hdwcMedPadBtm">${templates.getIntroText()}</div>\
				    			<div class="hdInstructionsBox ${hooks.SUGGESTIONS}" id="suggestionsAndGuidelines"></div>\
								<div class="boldText">${templates.getRequiredText()}</div>\
							</div>\
						</div>\
				        <div class="hdwcLrgPadBtm">\
				        	<div id="submissionContent">\
					        	<form name="hdUploadForm" id="hdUploadForm" class="hdUpload hdWidget ${hooks.FORM}" action="/Community/services/fileUpload" enctype="multipart/form-data" method="post">\
					        		{if errors && errors.length > 0}\
						        		<div id="hdValidationErrors">\
						                    <div id="hdwcErrorOverlayLarge ${hooks.ERRORS}">\
						                    {if _MODIFIERS.hasError(errors,"error.required")}\
							                    <div class="hdwcValidationError ${hooks.ERROR_VALIDATION}">\
						                            <p class="formLabel">Fields in bold with an asterisk (*) are required.</p>\
						                        </div>\
						                    {/if}\
						                    {var reqErrorsDone = false}\
											{for error in _MODIFIERS.sortErrors(errors,["error.required"])}\
												{if error.errorType == "error.required"}\
													<div class="hdwcErrorOverlayLarge">- ${error|getError}</div>\
												{else}\
													{if !reqErrorsDone}\
														<br />\
														{var reqErrorsDone = true}\
													{/if}\
													<div class="hdwcErrorOverlayLarge">${error|getError}</div>\
												{/if}\
											{/for}\
						                    </div>\
						                  </div>\
				                    {/if}\
				                    {if _MODIFIERS.hasError(errors,"error.required","category")}\
										<div class="hdwcValidationError ${hooks.ERROR_VALIDATION}">\
									{else}\
										<div>\
									{/if}\
									{if config.categories.length > 1}\
										<div class="formLabel">${templates.getCategoryLabel()}<span class="reqIndicator">*</span></div>\
										<select name="category">\
											<option value="">${templates.getCategoryDefaultText()}&nbsp;</option>\
											{for category in config.categories}\
												{if upload.category == category}\
													<option value="${category}" selected>${config.categoriesFriendly[category_index]}</option>\
												{else}\
													<option value="${category}">${config.categoriesFriendly[category_index]}</option>\
												{/if}\
											{/for}\
										</select>\
									</div><br/>\
									{else}\
										<input type="hidden" value="${config.categories[0]}" name="category" style="display:none;"></input>\
									{/if}\
									{if _MODIFIERS.hasError(errors,"error.required","title")}\
										<div class="hdwcValidationError ${hooks.ERROR_VALIDATION}">\
									{else}\
										<div>\
									{/if}\
										<div class="formLabel">${templates.getUploadMediaLabel()}<span class="reqIndicator">*</span></div>\
										<input type="text" maxlength="23" class="title" name="title" value="${upload.title}"></input>\
									</div><br/>\
									{if _MODIFIERS.hasError(errors,"error.required","path")}\
										<div class="hdwcValidationError ${hooks.ERROR_VALIDATION}">\
									{else}\
										<div>\
									{/if}\
										<div class="formLabel">\
				                            ${templates.getUploadMediaTypeLabel(config.contentType)}<span class="reqIndicator">*</span>\
				                        </div>\
										<div class="hdFormattedDiv hdwcSmlPadBtm">\
											${templates.getMediaInstructionsText(config.contentType)}\
										</div>\
										<input type="file" value="Browse" name="path" id="browseFile"></input>\
										<input type="hidden" value="${config.contentType}" name="type" style="display:none;"></input>\
										<input type="hidden" value="${config.siteName}" name="siteName" style="display:none;"></input>\
									</div>\
									<div id="progressBar" class="${hooks.PROGRESSBAR}" style="display: none;">\
							            <div id="theMeter">\
							                <div id="progressBarBox">\
							                    <div id="progressBarBoxContent" class="${hooks.PROGRESSBAR_METER}"></div>\
							                </div>\
							                <div id="progressBarText" class="${hooks.PROGRESSBAR_TEXT}"></div>\
							            </div>\
							        </div><br/>\
							        {if _MODIFIERS.hasError(errors,"error.required","story")}\
										<div class="hdwcValidationError ${hooks.ERROR_VALIDATION}">\
									{else}\
										<div>\
									{/if}\
										<div class="formLabel">${templates.getDescriptionLabel()}<span class="reqIndicator">*</span></div>\
										<textarea cols="70" rows="4" name="story">${upload.story}</textarea>\
										<br />${templates.getDescriptionInstructionText()}\
									</div>\
									<div class="hdwcLrgPadBtm">\
								  		<br/>\
								  		<div id="submitStatement">\
								  			${templates.getTermsAgreeText()}\
								  		</div>\
								  	</div>\
						        	<div class="hdwcMedPadBtm">\
						        	     <input id="submitVideoButton" type="submit" value="SUBMIT" style="display:none;"></input>\
						        		 <div class="btnOrange">\
						        		 	<a onclick="document.getElementById(\'submitVideoButton\').click();" id="hdwcLoginSaveButton" href="javascript:void(0)">${templates.getSubmitLabel()}</a>\
						        		 </div>\
						            	<div class="btnDarkGrey hdClose">\
						            		<a href="javascript:void(0)">${templates.getCancelLabel()}</a></div>\
						        	</div>\
								</form>\
				        	</div>\
					  </div>\
				</div>\
			</div>\
		</div>',
			
		overlayConfirmationHtml : '\
			<div id="hdwcUGCSubmission" class="thankYou">\
	    		<div class="dblRuleBtm">\
		    		<div class="head">${templates.getConfirmationLabel()}</div>\
		    	</div>\
		    	<div class="hdwcLrgPadBtm">\
			  		<p id="submitStatement">\
			  		${templates.getThankYouText()}\
			  		</p>\
			  	</div>\
			  	<div class="hdwcMedPadBtm ${hooks.CONF_ACTIONS}">\
			  		<div class="btnContinue btnOrange hdClose"><a href="javascript:void(0)">${templates.getContinueLabel()}</a></div>\
			  	</div>\
			  </div>'
};

(function() {
	var classes = HD.CSS_CLASSES;
	
	/**
	 * The collection of hooks
	 */
	HD.UploadWidget.hooks = {
		
		/**
		 * Standalone: (1)<br />
		 * Use: Contains action buttons<br />
		 * @memberOf HD.UploadWidget
		 */
		CONF_ACTIONS : classes.CONFIRMATION + '-' + classes.ACTION + 's',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Tag cloud container<br />
		 * Type: Form<br />
		 * @memberOf HD.UploadWidget
		 */
		FORM : classes.UPLOAD + '-form',
		
		/**
		 * Standalone: 0..n<br />
		 * Use: Error string<br />
		 * @memberOf HD.UploadWidget
		 */
		ERRORS : classes.UPLOAD + '-' + classes.ERROR + 's',
		
		/**
		 * Standalone: 0..n<br />
		 * Use: Validation error string<br />
		 * @memberOf HD.UploadWidget
		 */
		ERROR_VALIDATION : classes.UPLOAD + '-validation-' + classes.ERROR,
		
		/**
		 * Standalone: (1)<br />
		 * Use: Progessbar container<br />
		 * @memberOf HD.UploadWidget
		 */
		PROGRESSBAR : classes.UPLOAD + '-progressbar',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Progessbar container<br />
		 * @memberOf HD.UploadWidget
		 */
		PROGRESSBAR_METER : classes.UPLOAD + '-progressbar-meter',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Progessbar container<br />
		 * @memberOf HD.UploadWidget
		 */
		PROGRESSBAR_TEXT : classes.UPLOAD + '-progressbar-text',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Terms and conditions container<br />
		 * @memberOf HD.UploadWidget
		 */
		TERMS_CONDITIONS : classes.UPLOAD + '-terms',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Swivel character for terms and conditions<br />
		 * @memberOf HD.UploadWidget
		 */
		TERMS_SWIVEL : classes.UPLOAD + '-terms-swivel',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Scroller container for overlay<br />
		 * @memberOf HD.UploadWidget
		 */
		SCROLLER : classes.UPLOAD + '-scroller',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Suggestions container<br />
		 * @memberOf HD.UploadWidget
		 */
		SUGGESTIONS : classes.UPLOAD + '-suggestions',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Swivel character for suggestions<br />
		 * @memberOf HD.UploadWidget
		 */
		SUGGESTIONS_SWIVEL : classes.UPLOAD + '-suggestions-swivel',
		
		/**
		 * Standalone: (1)<br />
		 * Use: Suggestions button<br />
		 * @memberOf HD.UploadWidget
		 */
		SUGGESTIONS_BUTTON : classes.UPLOAD + '-suggestions-button'
		
	};
})();

HD.UploadWidget.prototype = {
	supportedVideoTypes : [".flv", ".wmv", ".asf", ".avi", ".mov", ".3gp", ".mpg", ".mpeg", ".mp4"],
	
	supportedPhotoTypes : [".jpeg", ".jpg", ".gif"],
	
	getUnsupportedFileTypeError : function(extension) {
		return HD.UploadWidget.templates.getUnsupportedFileTypeText();
	},
	
	render: function(contentType, category, categories, categoriesFriendly) {
	    	    
		this.config.contentType = contentType || this.config.contentType;
		this.config.category = category || this.config.category;
		this.config.categories = categories || this.config.categories;
		this.config.categoriesFriendly = categoriesFriendly || categories || this.config.categoriesFriendly;
	    
    	 var cb=this;
    	 
    	// TODO: This is for older communities. Once all community sites are converted to HD.Profile
		// this should be changed
		if(!login){
			login = HD.Profile.profile;
		} 
    	login.model.isUserLoggedIn(function(userResponse) {
    		if(userResponse.loggedInLevel > 1 || (userResponse.token && userResponse.user && userResponse.user.hasScreenName)) {
    			// Store the user for the overlay
				cb.user = userResponse.user;
				cb.loggedInLevel = userResponse.loggedInLevel;
 				cb.getHtml(null);

 				var observer = {
 					update : function(eventName, eventData) {
 						if (eventName == "overlayClose_Click") {
 							HD.util.Common.getObservable().removeObserver(this);
							cb.clearProgress();
 						}
 					}
 				};
 				HD.util.Common.getObservable().addObserver(observer);
 			} 
 			else {
 				var observer = {
 					update : function(eventName, eventData) {
 						if (eventName == "logged_In" || eventName == "LOGGED_IN") {
 							// TODO: remove the old login code after profile is migrated everywhere
 							if (!eventData && HD.Profile && HD.Profile.token){
 								login.model.getUser(function(userResponse){});
 							}
 							else{
	 							// Store the user for the overlay
	 							cb.user = eventData.user;
	 							cb.loggedInLevel = eventData.loggedInLevel;
	 							// Only show the new member message once
	 							var thisUser = cb.user;
	 							if (thisUser.passwordConfirm != null){
	 								cb.config.showNewMemberMessage = true;
	 							}
	 							cb.getHtml(null);
	 							cb.config.showNewMemberMessage = false;
	 							login.model.removeObserver(this);
	 							HD.util.Common.getObservable().removeObserver(this);
 							}
 						} else if (eventName == "overlayClose_Click") {
 							login.model.removeObserver(this);
 							HD.util.Common.getObservable().removeObserver(this);
 						}
 					}
 				};
 				
 				HD.util.Common.getObservable().addObserver(observer);
 				login.model.addObserver(observer);
 				
 				login.model.addObserver(observer);
 				if(userResponse.loggedInLevel > 0 || (userResponse.user && !userResponse.user.hasScreenName)){
 					login.view.promptCreateScreenName();
 				}else{
 					login.view.promptAuthentication();
 				}
 			}
 		});		
	    
	},
	
	renderPhoto: function(category, categories, categoriesFriendly) {
	    this.render('photo', category, categories, categoriesFriendly);
	},
	
	renderVideo: function(category, categories, categoriesFriendly) {
	    this.render('video', category, categories, categoriesFriendly);
	},
	
	renderBoth: function(category, categories, categoriesFriendly) {
	    this.render('both', category, categories, categoriesFriendly);
	},
    
    loading : function(isShow) {
		var parentEl = this.getParent();
		if(isShow) {
			HD.addClass(parentEl, HD.CSS_CLASSES.LOADING);
		} else {
			HD.removeClass(parentEl, HD.CSS_CLASSES.LOADING);
		}
    },
    
    update : function(eventName, eventData) {
		var config = this.config;
		var uploadEl = HD.get('hdwcLoginSaveButton');
    	if(eventName == "submitMedium_Start") {
    		this.loading(true);
    		if (uploadEl){
    			uploadEl.onclick = null;
    		}
    	} else if(eventName == "submitMedium_Finish") {
    		this.loading(false);
    		if (uploadEl){
    			uploadEl.onclick = function() {
    				document.getElementById('submitVideoButton').click();				
    	    	};
    		}
			this.clearProgress();
    		this.getConfirmationHtml(eventData);  	
    	} else if(eventName == "submitMedium_Error") {
    		this.loading(false);
    		if (uploadEl){
    			uploadEl.onclick = function() {
    				document.getElementById('submitVideoButton').click();				
    	    	};
    		}
			this.clearProgress();
    		this.getHtml(eventData);
    	}
    },
	
	getHtml : function(eventData, selectedCategory) {
    	
		var cb = this;
		var config = this.config;
		var timestamp = HD.util.Common.timestamp();
					
		var category = config.category;
		if(selectedCategory != null) {
			category = selectedCategory;
		}
		
		HD.util.Analytics.track(this.analyticsUploadString());
		var overlayEl = HD.util.Common.showOverlay(this.processTemplate(config.templates.getOverlayHtml(), {
			errors: (eventData && eventData.errors) || [],
			upload : (eventData && eventData.media) || [],
			user : cb.user || {},
			loggedInLevel : cb.loggedInLevel || 0
		}), config.templates.getOverlayTitle(), config.overlayWidth, config.overlayHeight);
		
			

		cb.setListeners.call(cb);
	},
	
	getConfirmationHtml : function(eventData) {
		var cb = this;
		var config = this.config;
		var classes = HD.CSS_CLASSES;
		HD.util.Analytics.track(this.analyticsUploadConfirmationString(eventData[3] || '', eventData[4] || ''));	
		
		var overlayEl = HD.util.Common.showOverlay(this.processTemplate(config.templates.getOverlayConfirmationHtml()), 
				config.templates.getOverlayTitle(),  config.overlayConfirmationWidth, config.overlayConfirmationHeight);
		
		// Add action buttons.
		if (config.actions.length > 0) {
			var wrapper = HD.getByClass(this.config.hooks.CONF_ACTIONS, '*', overlayEl)[0]; 
			if(wrapper){
				var actionEl = document.createElement('div');
				actionEl.className = "btnOrange " + classes.ACTION;
				actionEl.innerHTML = "<a href='#'></a>";
				for (var i = 0; i < config.actions.length; i++) {
					var el = actionEl.cloneNode(true);
					(function() {
						var action = config.actions[i];
						el.firstChild.innerHTML = action;
						el.firstChild.onclick = function() {
							HD.util.Common.hideOverlay();
							self.model.notifyObservers("submitMedium_Action", action);
						};
					})();
					wrapper.appendChild(el);
				}
			}
		}
	},
	
	setListeners : function() {
		var cb = this;
		var modelCb = this.model;
		this.getByHook("FORM", function(el) {
			el.onsubmit = function() {
				var formEl = this;
				var filePath = formEl.path.value;
		
				var extension = cb.getFileExtension.call(cb, filePath);
		
				var type = null;
			
				cb.removeErrors(formEl);
			
				if(cb.isSupportedVideoFile(extension) || cb.config.contentType == 'video') {
					formEl.type.value = "video";
				} else if(cb.isSupportedPhotoFile(extension) || cb.config.contentType == 'photo') {
					formEl.type.value = "photo";
				} else {
					formEl.type.value = "";
				}
			
				var selectedCategory = formEl.category.value;
				
				var mediaObj = {
					title: formEl.title.value,
					path: formEl.path.value,
					story: formEl.story.value,
					type: formEl.type.value,
					category : selectedCategory
				};
		
				ValidationService.validateUpload(mediaObj, function(mediaResponse){
					if(mediaResponse.errors.length > 0){
						cb.getHtml(mediaResponse, selectedCategory);
					} else {
						cb.startProgress();
						cb.file = modelCb.submitMedium.call(modelCb, formEl);
					}				
					return false;
				});
				return false;
			};
		}, 'form', this.config.overlayParent);
				
		cb.setToggleSuggestions();
	},
	
	removeErrors : function(formEl) {	
		this.getByHook('ERRORS', function(el){
			el.parentNode.removeChild(el);
		}, '*', formEl);
		
		this.getByHook('ERROR_VALIDATION', function(el){
			for (var i = 0, l = el.length; i < l; i++) {
				HD.removeClass(el[i], 'hdwcValidationError');
			}	
		},'*', formEl);	
	},
	
	refreshProgress : function (delay) {
		var cb = this;
		this.progress = setTimeout(function() {
			UploadMonitor.getUploadInfo(function(data){
				cb.updateProgress(data);
				return false;
			});
		}, delay || 5000);
	},

	updateProgress : function (uploadInfo){
		if (uploadInfo.inProgress){ 
	    	try{
	    		var fileIndex = uploadInfo.fileIndex;
		        var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
				if (this.progress) {
					this.refreshProgress();
				}
		        
		        this.getByHook('PROGRESSBAR_TEXT', function(el){
					el.innerHTML = progressPercent + '%';
				},'*', this.config.overlayParent);
		        
		        this.getByHook('PROGRESSBAR_METER', function(el){
					el.style.width = parseInt(progressPercent * 3.5) + 'px';
				},'*', this.config.overlayParent);
		        
	    	} catch (e){}	    	
	    } 
	},

	startProgress : function () {
		this.getByHook('PROGRESSBAR', function(el){
			el.style.display = 'block';
		},'*', this.config.overlayParent);
		
		this.getByHook('PROGRESSBAR_TEXT', function(el){
			el.innerHTML = '0%';
		},'*', this.config.overlayParent);
        	    
	    // wait a little while to make sure the upload has started ..
	    this.refreshProgress(500);
	},
	
	clearProgress : function() {
		this.progress = null;
		if (this.file) {
			try {
				YAHOO.util.Connect.abort(this.file);
			} catch(e) {}
			this.file = null;
		}
	},
	
	toggleSuggestions : function(){
		
		var self = this;
		var swivelEl = HD.util.Common.get('sgSwivel');
		this.getByHook('SUGGESTIONS', function(el){

			if (el.style.display != 'block'){
				
				YAHOO.util.Dom.setStyle(el, 'display', 'block');
				el.innerHTML = HD.UploadWidget.templates.getSuggestionsAndGuidelinesText();
				swivelEl.innerHTML = self.config.templates.getSuggestionsSwivelTextActive();	 
				
	
			}
			else{
				YAHOO.util.Dom.setStyle(el, 'display', 'none');
				swivelEl.innerHTML = self.config.templates.getSuggestionsSwivelText();	 
			}			
		},'*', this.config.overlayParent);
	},
	
	setToggleSuggestions : function(){
		var cb = this;
		var suggestionsEl = HD.util.Common.get('sgButton');
		if(suggestionsEl){
			suggestionsEl.onclick = function(){
				cb.toggleSuggestions();
				return false;
			};
		}
	},
	
	getFileExtension : function(file) {
		if(file == null) {
			return "";
		}
		return file.substring(file.lastIndexOf("."));
	},
	
	isSupportedVideoFile : function(fileExtension) {
		return this.isSupportedType(fileExtension, this.supportedVideoTypes);
	},
	
	isSupportedPhotoFile : function(fileExtension) {
		return this.isSupportedType(fileExtension, this.supportedPhotoTypes);
	},
	
	isSupportedType : function(type, supportedTypes) {
		if(type == null || supportedTypes == null) {
			return false;
		}
		
		type = type.toLowerCase();
		
		for(var i = 0, len = supportedTypes.length; i < len; i++) {
			if(supportedTypes[i] == type) {
				return true;
			}
		}
		
		return false;
	},
	
	showError : function(errorText, refEl) {
		refEl = HD.get(refEl);
		refEl.innerHTML += "<div id='hdwcErrorOverlayLarge'>" + errorText + "</div>"
	},
	
	analyticsUploadBothString : function() {
		return "default_analyticsUploadBothString";
	},
	
	analyticsUploadPhotoString : function() {
		return "default_analyticsUploadPhotoString";
	},
	
	analyticsUploadVideoString : function() {
		return "default_analyticsUploadVideoString";
	},
	
	analyticsUploadString : function() {
		if (this.config.contentType == 'photo') {
			HD.util.Analytics.track(this.analyticsUploadPhotoString());
		}
		else if (this.config.contentType == 'video') {
			HD.util.Analytics.track(this.analyticsUploadVideoString());
		}
		else if (this.config.contentType == 'both') {
			HD.util.Analytics.track(this.analyticsUploadBothString());
		}
		else {
			return "default_analyticsUploadString";
		}
	},
	
	analyticsUploadConfirmationString : function(contentType, category) {
		return "default_analyticsUploadConfirmationString";
	}
};

HD.extend(HD.UploadWidget, [HD.Widget]);

HD.register('hd_upload_widget', 'HD.UploadWidget', {version: "1.0", build: "1"});
