/*///////////////////////////////////////////////////////////////////
    File        site.js
    Author      Terence McDevitt
    Purpose     Site-wide javascript enhancements
    Requires    jquery 1.2.6
                jqueryUI 1.6
                shadowbox.js
///////////////////////////////////////////////////////////////////*/

Shadowbox.init({
    troubleElements: ["select", "canvas"],
    onOpen: moveCloseLink
});

var DA = {

	CONST_USER_SURVEY_LINK : "https://spreadsheets.google.com/viewform?hl=en&formkey=dFV5NHlsQllUVWVhY2tDWlhyQ0luTVE6MA#gid=0",
	CONST_USER_SURVEY_RESPONSE_CHECKER_URL : "/components/usersurvey.cfc",
	CONST_USER_SURVEY_RESPONSE_YES : 1,
	CONST_USER_SURVEY_RESPONSE_NOT_NOW : 2,
	CONST_USER_SURVEY_RESPONSE_NO : 3,
	CONST_VIDEO_ROI_FEEDBACK_SUBMIT_URL : "/components/videoroifeedback.cfc",
	CONST_VIDEO_ROI_FEEDBACK_SUBMIT_METHOD : "SubmitVideoROIFeedback",
	CONST_VIDEO_ROI_AFFIDAVIT_SUBMIT_URL : "/components/affidavitupload.cfc?method=UploadAffidavit",
	CONST_VIDEO_ROI_AFFIDAVIT_SUBMIT_METHOD : "UploadAffidavit",

	videoPlayerSWFLocation: "/systemincludes/videoplayer/simplePlayer.swf",
	
	swfUpload : null,
	affidavitSelected : false,
	isUserSubmittingAnAdvertiser : false,
	videoSurveyDialog : null,
	networkIDsSelectedFromMultiselect : {},
	videoROIFormValidator : null,
	sourceElementForVideoSurveyDialog : null,

	// Video Player JavaScript functions
	launchVideoPlayer: function(videoURL, videoWidth, videoHeight)
	{

		var playerSettings = {
			_videoUrl: videoURL,
			_skinUrl: "/systemincludes/videoplayer/SkinUnderPlayStopSeekFullVol.swf",
			_coverImageUrl: "bolt.jpg",
			_autoPlay: "true",
			_player_w: videoWidth,
			_playerColor: '0x808080'
			};
		
		var soParameters = {wmode: "transparent", allowScriptAccess: "always", allowFullScreen: "true", menu: "false"};

		Shadowbox.open({
			content:    	this.videoPlayerSWFLocation,
			player:     	"swf",
			title:      	"",
			height:     	playerSettings._player_w*9/16+38,
			width:      	playerSettings._player_w,
			options:		{flashParams: soParameters, flashVars: playerSettings, overlayOpacity: .85}
		});
		
	},
	
	launchSurveyPrompt : function(surveyURL)
	{

		var surveyDetailsPDFURL = "/userimages/DAcom_Sweepstakes_Rules_7_11.pdf";
	
		$('<div></div>').html('<div id="survey_content_main">Discoveryaffiliate.com values your partnership. As a reward, we are offering all registered users the chance to win an Apple iPad. By choosing YES, your name and information (as listed in your user profile) will automatically be entered into the drawing.<p>If you choose YES you will also be directed to a short survey that evaluates your experience on discoveryaffiliate.com. Completing the survey is not required for eligibility. Your feedback is critical to ensuring that this website remains a useful and convenient resource for all its users.</div><div id="survey_content_legal"><a href="#" id="surveyDetailsPDF">See Official Rules</a></div>').dialog({
			resizable: false,
			draggable: false,
			width : 500,
			modal: true,
			title: 'Discovery Affiliate User Survey',
			buttons: {
				"Not now" : function() {
					DA.setUserOptOutOfSurveyFlag(DA.CONST_USER_SURVEY_RESPONSE_NOT_NOW);
					$(this).dialog("destroy");
				},
				"No thanks": function() {
					DA.setUserOptOutOfSurveyFlag(DA.CONST_USER_SURVEY_RESPONSE_NO);
					$(this).dialog("destroy");
				},
				"Yes": function() {
					DA.setUserOptOutOfSurveyFlag(DA.CONST_USER_SURVEY_RESPONSE_YES);
					
					// If a survey URL is passed in, it means it's coming from the admin
					// Otherwise, default to the constant defined above
					if (surveyURL !== null && surveyURL !== undefined && surveyURL !== "")
					{
						window.open(surveyURL);
					}
					else
					{
						window.open(DA.CONST_USER_SURVEY_LINK);
					}
					
					$(this).dialog("destroy");
				}
				
			},
			open: function(event) {
			
				 // Add a specific class for the yes button so it can be styled slightly differently
				 $('.ui-dialog-buttonpane').find('button:contains("Yes")').addClass('yesButton');
				 
				 // set up event handler for survey details link
				 $("#surveyDetailsPDF").click(function(e) {
				 	window.open(surveyDetailsPDFURL);
				 });
				 
			 },
			 close : function(event, ui) {
			 	// If the user decides to simply hit the "x" button
			 	// we want to act like they clicked "Not Now"
			 	DA.setUserOptOutOfSurveyFlag(DA.CONST_USER_SURVEY_RESPONSE_NOT_NOW);
			 }
		});

		return false;
	},
	
	hasUserTakenOrOptedOutOfSurvey : function()
	{
		var returnValue = true;
		
		$.ajax({
			type : "GET",
			url : DA.CONST_USER_SURVEY_RESPONSE_CHECKER_URL,
			data : "method=HasUserOptedOut&returnformat=json",
			async : false,
			dataType : "json",
			success : function(data) {
			
						// Since we're only returning one value from the query,
						// it will be in the first row and first column (e.g. "0,0")
						var response = data.DATA[0][0];
			
						if (response == DA.CONST_USER_SURVEY_RESPONSE_NO || response == DA.CONST_USER_SURVEY_RESPONSE_YES)
						{
							// user has asked not to take the survey or has already taken it"
							returnValue = true;
						}
						else
						{
							//User has not taken survey
							returnValue = false;
						}			
			}
		});
		
		
		return returnValue;
		
	},
	
	setUserOptOutOfSurveyFlag : function(userResponse)
	{
		$.post(DA.CONST_USER_SURVEY_RESPONSE_CHECKER_URL, { method : "SetUserSurveyRequestResponse", responseValue : userResponse }, 
			function (data) {
				//NO-OP for now
			});
	},
	
	launchVideoROIFeedbackSurveyPrompt : function(sourceElement)
	{
	
		DA.sourceElementForVideoSurveyDialog = sourceElement;
	
		// Grab coordinates for positioning dialog (default of dead center in screen isn't working
		// due to dynamic nature of content
		var x = document.body.clientWidth / 2;
		var y = 60;	// hardcode this value for now

		DA.videoSurveyDialog = $('<div></div>').html('<div id="video_roi_feedback_form_main"></div>').dialog({
			resizable: false,
			draggable: false,
			//position : 'fixed',
			width : 540,
			position : ['center', 50],
			modal: true,
			title: 'Video Performance Feedback',
			open: function(event) {
			
				var $this = $(this);
			
				$('html, body').animate({scrollTop : $this.scrollTop() - 20},'slow');
			
				DA.showAJAXLoader("Loading.........");
			
				 $('#video_roi_feedback_form_main').load('/videoroifeedback/videoroi_base_form.cfm', function() {
				 	// Upon loading the dialog, be sure to show the video type selection div
				 	$('#roi_video_type_selection').show();
				 	
				 	// Initialize all page level variables used for form
					DA.initializeROIFormVariables();
				 	
				 	/*********************************************************/
				 	/* BEGIN - EVENT LISTENER SETUP							 */
				 	/*********************************************************/

					// Handle the video type selection when the user changes the radio value
				 	$('#video_roi_form_container #roi_video_type_selection input[type="radio"]').click(function() {
				 		var selectedId = $(this).attr('id');
				 		DA.handleROIVideoTypeSelection(selectedId);				 		
				 	});

				 	// Set up event handler for user clicking "back"
				 	$('#video_roi_form_container #video_roi_form_nav_controls #back').click(function() {
				 		DA.videoROIBackToBeginningOfForm();

						return false;

				 	});
				 	
				 	$('#video_roi_form_container #submit_form').click(function() {
				 		// Call form submission function
				 		
				 		$('#videoroiform').submit();				 		

						return false;

				 	});

				 	$('#video_roi_form_container #submit_more_feedback').click(function(e) {
				 	
				 		e.preventDefault();
				 		
				 		DA.videoROIBackToBeginningOfForm();

						return false;
				 	});

				 	$('#video_roi_form_container #done').click(function() {
				 	
					 	DA.videoSurveyDialog.dialog("destroy").remove();

					 	// Get rid of the swfupload instance
					 	DA.swfUpload = null;

						return false;
				 	});

					$('#submit_and_add_another_button').click(function(e) {
					
						e.preventDefault();
					
						// Indicate that this is an added advertiser
						// TODO: Find a better way to handle this
						DA.isUserSubmittingAnAdvertiser = true;
						
						DA.submitVideoROIForm();
						
						return false;
					});

					$('#videoroiform').submit(function(e) {
					
						e.preventDefault();
						
						DA.submitVideoROIForm();
						
						return false;
					});

				 	/*********************************************************/
				 	/* END - EVENT LISTENER SETUP							 */
				 	/*********************************************************/
				
					DA.hideAJAXLoader();
				
				 });
			

				
			 },
			 close : function(event, ui) {
			 	$(this).dialog("destroy").remove();
			 	
			 	// POsition the user back where they started
			 	if (DA.sourceElementForVideoSurveyDialog)
			 	{
				 	$('html, body').animate({scrollTop : $(DA.sourceElementForVideoSurveyDialog).scrollTop() - 20},'slow');
				}
			 	
				// Get rid of the swfupload instance
				DA.swfUpload = null;
			 	
			 }
		});

		return false;
	},
	setNetworkSelectionFieldLabel : function(videoTypeString)
	{
		$('label[for="fld_networkid"]').html(videoTypeString);
	},
	handleROIVideoTypeSelection : function(selectedVideoType)
	{

		$('#roi_video_type_selection').hide();
		$('#video_roi_form_nav_controls').show();
		$('#common_fields').show();

		// Show the uploader and force it as required. We need
		// to do this to handle the case where a user goes to "Other"
		// first then back to another part of the form where this is required
		$('#upload_flash_container').addClass('required');
		$('#upload_flash_container').show();
		
		DA.initializeSWFUploader();
		
		var networkSelectionLabel = '';

		switch(selectedVideoType)
		{
			case "radTaggableSpot":
				DA.renderTaggableSpotFields();
				networkSelectionLabel = "For a <span>Taggable Spot</span> on*";
				break;
			
			case "radProgrammingClip":
				DA.renderProgrammingClipFields();
				networkSelectionLabel = "For a <span>Programming Clip</span> on*";
				break;
			
			case "radOther":
				DA.renderOtherFields();
				networkSelectionLabel = "For <span>Other Video Type</span> on*";
				break;
			
			default:
				break;
		}
		
		// Update the network field label
		DA.setNetworkSelectionFieldLabel(networkSelectionLabel);
		
		$('#submission_fields').show();
		
		
		$('#network_selection').show();
		
	},
	handleProgammingClipTypeSelection : function(selectedProgrammingClipType)
	{
		// reset any form validation errors upon change
		DA.clearAllFormErrors();

		$('#programming_clip_type_specific_fields > div').hide();
		
		// Special case to get rid of any existing errors related to the upload widet
		$('#file_upload_error').html('');
		
		// Upon changing a programming clip, we need to clear out existing form field values
		DA.clearAllProgrammingClipFields();

		switch(selectedProgrammingClipType)
		{
			case "radProgrammingClipTypePromoSpot":
				DA.showProgrammingClipConsumerPromoFields();
				break;
			
			case "radProgrammingClipTypePresentation":
				DA.showProgrammingClipPresentationFields();
				break;
			
			case "radProgrammingClipTypeRetail":
				DA.showProgrammingClipRetailFields();
				break;

			case "radProgrammingClipTypeOther":
				DA.showProgrammingClipOtherFields();
				break;
			
			default:
				break;
		}
		
	},
	handleCampaignTypeSelection : function(selectedCampaignType)
	{
		//NOOP for now
/*		switch(selectedCampaignType)
		{
			case "radCampaignTypeOther":
				$('#fld_campaigntypeother').show();
				break;
			
			default:
				$('#fld_campaigntypeother').hide();
				break;
		}
*/		
	},
	handleRetailOutletTypeSelection : function(selectedCampaignType)
	{

		//NOOP for now
	},	
	videoROIBackToBeginningOfForm : function()
	{
		DA.showAJAXLoader("Please wait...");
	
		// Reinitialize all page level variables used by the form
		DA.initializeROIFormVariables();
		
		// TODO: Figure out a better way to handle all of the hide/shows
	
		// Clear the form validator
		DA.clearAllFormErrors();
	
		// Reset the video type radio selection
		$('#roi_video_type_selection input:checked').attr('checked', false);
	
		// Reset network selection
		DA.clearSelectedNetwork();
		$('#network_not_selected_error').hide();
	
		// Reset currnetly selected affidavit
		$('#currently_selected_affidavit').html('');
	
		// Hide all existing divs and error messages
		$('label.error').hide();
		
		$('#network_selection_informational_text').hide();
		$('#videoroiform > #type_specific_form_fields').hide();
		$('#common_fields').hide();
		//$('#type_specific_form_fields').hide();
		
		$('#roi_video_type_selection').show();
		$('#video_roi_form_nav_controls').hide();

		$('#submission_thankyou').hide();
		$('#upload_flash_container').hide();		
		$('#taggable_spot_submission_fields').hide();
		$('#submission_fields').hide();

		DA.hideAJAXLoader();
	},
	
	renderTaggableSpotFields : function()
	{
		DA.showAJAXLoader("Loading Fields...");
	
		$('#type_specific_form_fields').load('/videoroifeedback/videoroi_taggable_form.cfm', function() {
			$('#type_specific_form_fields').show();
			
			$('#taggable_spot_submission_fields').show('');
			
			DA.setupNetworkDropdown(false);
			
			DA.initializeFields();

			DA.centerDialog();
			
			DA.hideAJAXLoader();
		});
	
	},
	renderProgrammingClipFields : function()
	{
		DA.showAJAXLoader("Loading Fields...");
	
		$('#type_specific_form_fields').load('/videoroifeedback/videoroi_programming_clip_form.cfm', function() {
			$('#type_specific_form_fields').show();
			
			DA.setupNetworkDropdown(true);		
			
			/***************************
				Begin event handlers
			****************************/

			// Handle change to programming clip type			
			$('#videoroiform #clip_type_inputs input[type="radio"]').click(function() {
				var selectedProgrammingClipTypeId = $(this).attr('id');
				DA.handleProgammingClipTypeSelection(selectedProgrammingClipTypeId);				 		
			});

			// Handle change to campaign type
			$('#videoroiform #campaign_type_inputs input[type="radio"]').click(function() {
				var selectedCampaignTypeId = $(this).attr('id');
				DA.handleCampaignTypeSelection(selectedCampaignTypeId);				 		
			});

			// Handle change to campaign type
			$('#videoroiform #retail_outlet_type_inputs input[type="radio"]').click(function() {
				var selectedOutletTypeId = $(this).attr('id');
				DA.handleRetailOutletTypeSelection(selectedOutletTypeId);				 		
			});

			$('#fld_campaigntypeother').click(function() {
				// select the "other" radio button
				$('#radCampaignTypeOther').attr('checked', true);
			});
			
			$('#fld_retailoutlettypeother').click(function() {
				// select the "other" radio button
				$('#radRetailOutletTypeOther').attr('checked', true);
			});
						
			/***************************
				End event handlers
			****************************/
			
			// Preselect the Consumer Promo Spot field
			$('#radProgrammingClipTypePromoSpot').attr('checked', true);
			
			// Force the change event to fire (shows dynamic fields)
			$('#radProgrammingClipTypePromoSpot').click();
			
			DA.initializeFields();

			DA.hideAJAXLoader();
			
		});

	},
	renderOtherFields : function()
	{
		DA.showAJAXLoader("Loading Fields...");
	
		$('#type_specific_form_fields').load('/videoroifeedback/videoroi_other_form.cfm', function() {
			$('#type_specific_form_fields').show();
			$('#network_selection_informational_text').show();
			
			DA.setupNetworkDropdown(false);
	
			DA.initializeFields();

			DA.centerDialog();
			
			DA.hideAJAXLoader();
			
		});
	
	},
	setupNetworkDropdown : function(isMultiple) {
		if (isMultiple)
		{
			/* Multi select is a very special case. We use a jQuery plugin
			 to give the multi select effect. However, in order to do this
			 we need an actual "select" object to begin with. Unfortunately,
			 the plugin destroys the original select when instantiated. This
			 poses a problem since we need to show the original select
			 for the "taggable" and "other" types. Since the user can switch
			 between types before submitting, we can't destroy the original.
			 As a result, we first clone the original, then base the plugin
			 off of the clone. When the user makes selections, we store the 
			 selected values in a hidden field
			 */
			 
			 // Hide the original in case it's visible
			 $('#selectednetworkid').hide();
			 
			 if (!$('#selectednetworkidclone').length)
			 {
				 var selectNetworkClone = $('#selectednetworkid').clone()

				 selectNetworkClone.attr('id', 'selectednetworkidclone');
				 
				 // We need to remove the "Select a Network" empty option
				 // since the multi-select plugin will already put this
				 // type of option in the list (whereas for the single
				 // select mode of the dropdown, it will not)
//				 selectNetworkClone.find('option[value=""]').remove();
				 
				 selectNetworkClone.appendTo('#network_selection');

				// Code to ensure that the network dropdown is not multi-select
				$('#selectednetworkidclone').attr('multiple', '');

				// Set up multi-select widget. For taggable spots, users can select multiple networks
				// at a time. When they do this, we'll want to append to a comma separated list
				// stored in a hidden field with id "selectednetworkid"
				$("#selectednetworkidclone").multiSelect( { noneSelected : 'Select Networks' },
					function(el) {

						var selectedValue = el.val();

						// Hide any validation errors, if present
						//$('#network_not_selected_error').html('');
						$('#network_not_selected_error').hide();

						// Any time a user selects/deselects an item, we need to update a local
						// data structure, which we'll then use to create a comma separated list
						// to store in a hidden field for form submission

						// Item already exists, remove it
						if (DA.networkIDsSelectedFromMultiselect[selectedValue])
						{
							delete DA.networkIDsSelectedFromMultiselect[selectedValue];
						}
						else
						{
							DA.networkIDsSelectedFromMultiselect[selectedValue] = selectedValue;
						}

						// Loop through each selected network and add to hidden field
						
						// reset the hidden field
						$('#fld_networkid').val('');

						$.each(DA.networkIDsSelectedFromMultiselect, function(key, value) {

								var currentValue = value;

								var currentNetworkSelection = $.trim($('#fld_networkid').val());

								if (currentNetworkSelection !== "")
								{
									$('#fld_networkid').val(currentNetworkSelection + ',' + currentValue);
								}
								else
								{
									$('#fld_networkid').val(currentValue);
								}						
						
						});
						
						
					});	

			}
			
			$('#selectednetworkidclone').show();
			
		}
		else
		{
		
			 // Hide the multi-select clone in case it's visible
			 $('#selectednetworkidclone').hide();
		
			// Code to ensure that the network dropdown is not multi-select
			$('#selectednetworkid').removeAttr('multiple');
			
			// Set the first option in the select as selected (should be the "Select a Network" option)
			$("#selectednetworkid").find('option:first').attr('selected', 'selected');

			$("#selectednetworkid").change(function () {
					  var selectedValue = "";
					  $("#selectednetworkid option:selected").each(function () {
							selectedValue += $(this).val() + "";
						  });
					  
					  if($.trim(selectedValue) != "")
					  {
					  	// clear any existing error messaging
					  	//$('#network_not_selected_error').html('');
					  	$('#network_not_selected_error').hide();
					  }
					  // Set the hidden field that captures network id
					  $('#fld_networkid').val(selectedValue);
					  
					  
					})
					.change();
		
			$('#selectednetworkid').show();
		
		}
	},
	initializeFields : function()
	{
		$('.jcalendar').datepicker({
			showAnim: "fadeIn",
			dateFormat: 'm/d/yy',
			showOn: 'both',
			buttonImage: '/systemimages/icons/calendar.png',
			buttonImageOnly: true,
			changeMonth: false,
			changeYear: false,
			onClose: function() { if (DA.videoROIFormValidator != null) { $(this).valid(); }}	// ensures validation is cleared
	    });
	    
		// Handle placeholder support
		//$('input[placeholder], textarea[placeholder]').placeholder({blankSubmit:true});


	},
	removeFormPlaceholders : function(formWithPlaceholders) {
		var $fieldsWithPlaceholder = formWithPlaceholders.find('input[placeholder!=""]')
		
		$fieldsWithPlaceholder.each(function() {
			var currentInput = $(this);
			
			var currentPlaceholderText = currentInput.attr('placeholder');
			currentInput.removeAttr('placeholder');
			currentInput.attr('placeholder_temp', currentPlaceholderText);
			
		});
	},
	submitVideoROIForm : function()
	{
		// Perform any form validation required
		
		// Before validation, we need to remove any placeholders as these are actually considered
		// values
		var formToValidate = $('#videoroiform');
		
		DA.removeFormPlaceholders(formToValidate);

		// Add any custom validation methods
		// Code slightly modified from: http://stackoverflow.com/questions/833997/end-date-greater-than-start-date-jquery-validation
		$.validator.addMethod("compareFlightEndDateToStartDate", function(value, element, params) {
		
		var returnValue = false;
		
		// If the start date hasn't been specified, don't check since we'll be showing the 
		// "required" message for that field

		if ($.trim($(params.greaterThan).val()) != "")
		{
			if (!/Invalid|NaN/.test(new Date(value))) {
				returnValue = new Date(value) >= new Date($(params.greaterThan).val());
			}
			else
			{
				returnValue = isNaN(value) && isNaN($(params.greaterThan).val()) || (parseFloat(value) >= parseFloat($(params.greaterThan).val())); 
			}
		
		}
		else
		{
			returnValue = true;
		}
		
		return returnValue;
		
    },'End date must be on or after the start date.');

		var validationRules = {
			cliplengthid : {
						required : true
						},
			cliptitles : {
						required : true
						},	
			advertisername : {
						required : false
						},
			advertisertype : {
						required : false
						},
			dmasserved : {
						required : $('#dmas_served').is(":visible")
						},
			spotsran : {
						required : $('#group_video_details').is(":visible"),
						number : true
						},
			estimatedimpressions : {
						required : false,
						number : true
						},
			subscribersreached : {
						required : $('#group_video_details').is(":visible"),
						number : true
						},
			retailoutlettypeid : {
						required : $('#retail_outlet_types').is(":visible")
						},
			retailoutletname : {
						required : $('#retail_outlet_types').is(":visible")
						},
			retailoutletlocation : {
						required : $('#retail_outlet_types').is(":visible")
						},
			retailoutlettypeother : {
						required : false
						},												
			campaigntypeid : {
						required : $('#campaign_types').is(":visible")
						},
			campaigntypeother : {
						required : false
						},						
			zones : {
					required : false,
					number : true
				},
			flightdatestart : {
						required : true,
						date : true
						},
			flightdateend : {
						required : true,
						date : true,
						compareFlightEndDateToStartDate : { greaterThan : "#fld_flightdatestart" }
						},	
			crosschannelnetworks : {
						required : false	
						},
			descriptionofuse : {
						required : false	
						}
						

		};
		
		var validationMessages = {
			cliplengthid : "Please select a clip length.",
			campaigntypeid : "Please select a campaign type.",
			cliptitles : "Please enter at least one clip title.",
			advertisername : "Please enter an advertiser name.",
			advertisertype : "Please enter an advertiser type.",
			dmasserved : "Please enter at least one DMA name.",
			retailoutlettypeid: "Please select a retail outlet type.",
			retailoutletname : "Please enter a retail outlet name.",
			retailoutletlocation : "Please enter a retail outlet location.",
			spotsran : {
					required : "Please enter the total number of spots ran.",
					number : "Please enter a number for spots ran."
				},
			subscribersreached : {
					required : "Please enter the total number of subscribers reached.",
					number : "Please enter a number for subscribers reached."
				},
			estimatedimpressions : {
					number : "Please enter a number for number of impressions."
				},
			zones : {
					number : "Please enter a number for zones."
				},
			flightdatestart : {
					required : "Please select a flight start date.",
					date : "Please enter a valid date for flight start date."
				},
			flightdateend : {
					required : "Please select a flight end date.",
					date : "Please enter a valid date for flight end date."
				}
		};
		
		DA.videoROIFormValidator = $('#videoroiform').validate(
			{ 
				rules : validationRules,
				messages : validationMessages,
				 errorPlacement: function (error, element) { 
                                     if (element.attr("name") == "spotsran")
                                            $("#video_details_errors").append(error);
                                     else if (element.attr("name") == "subscribersreached") 
                                     		$("#video_details_errors").append(error);
                                     else if (element.attr("name") == "zones") 
                                     		$("#video_details_errors").append(error);
                                     else if (element.attr("name") == "advertisername") 
                                     		$("#advertiser_errors").append(error);
                                     else if (element.attr("name") == "advertisertype") 
                                     		$("#advertiser_errors").append(error);
                                     else if (element.attr("name") == "flightdatestart") 
                                     		$("#flight_dates_errors").append(error);
                                     else if (element.attr("name") == "flightdateend") 
                                     		$("#flight_dates_errors").append(error);
                                     else if (element.attr("name") == "cliplengthid") 
                                     		$("#clip_length_inputs").append(error);
                                     else if (element.attr("name") == "campaigntypeid") 
                                     		$("#campaign_type_inputs").append(error);
                                     else if (element.attr("name") == "retailoutlettypeid") 
                                     		$("#retail_outlet_type_inputs").append(error);
                                     else 
                                             error.insertAfter(element); 
                             } 				
			}
		);

		// Validate the form
		var isFormValid = DA.videoROIFormValidator.form();		

		// Check if network is selected
		var isNetworkSelected = DA.isNetworkSelected();

		// Affidavits CAN be optional. As a result, we only need to check if it's
		// selected if the field is marked as required
		var isAffidavitValid = DA.validateAffidavit(); 
		
		if (isFormValid && isAffidavitValid && isNetworkSelected) {			
			// First, attempt to upload the affidavit. The success handler
			// of the upload will then submit the form
			if (this.affidavitSelected)
			{
				this.swfUpload.startUpload();
			}
			else
			{
				// Affidavit upload isn't needed. Move directly to form submission
				DA.postAffidavitUpload();
				
			}
		}
		else
		{
			// Center the dialog so the user can see all errors
			DA.centerDialog();
			
		}
		
	},
	validateAffidavit : function() {
		// Used to determine if the user can move forward
		// on the submission process
		var returnValue = false;
		
		if (DA.isAffidavitRequired())
		{
			// Affidavit is required. Check if it's selected
			if (this.affidavitSelected)
			{
				returnValue = true;
			}
			else
			{
				// Display validation error messages
				$('#file_upload_error').html('You must select an affidavit before submitting.');
				$('#file_upload_error').show();				
			}
		}
		else
		{
			// Not required - move forward
			returnValue = true;
		}
		
		return returnValue;
	},
	isAffidavitRequired : function() {
		
		var returnValue = false;
		
		if ($('#upload_flash_container.required').length > 0)
		{
			returnValue = true;
		}
		
		return returnValue;
		
	},	
	isNetworkSelected : function() {
		
		var returnValue = false;
		
		var currentlySelectedNetworkID = $.trim($('#fld_networkid').val());
		
		if (currentlySelectedNetworkID !== "" && currentlySelectedNetworkID !== undefined && currentlySelectedNetworkID !== null)
		{
			returnValue = true;
		}
		else
		{
			$('#network_not_selected_error').html(DA.getNetworkValidationMessage());
			$('#network_not_selected_error').show();
		}
		
		return returnValue;
		
	},
	initializeROIFormVariables : function() {
		DA.affidavitSelected = false;
		DA.isUserSubmittingAnAdvertiser = false
		DA.networkIDsSelectedFromMultiselect = {};
		DA.videoROIFormValidator = null;
	},
	initializeSWFUploader : function() {
	
		if (this.swfUpload === null || this.swfUpload === "undefined")
		{
		
			var jSessionID = $.cookie('JSESSIONID');
			var cfToken = $.cookie('CFTOKEN');
			var cfID = $.cookie('CFID');

			var submissionURL = "/components/affidavitupload.cfc?method=UploadAffidavit&JSESSIONID=" + jSessionID + "&CFTOKEN=" + cfToken + "&CFID=" + cfID;
		
			//alert(submissionURL);
		
			//alert("******************Initializing swf upload");
		
			// Initialize the SWFUpload object
			this.swfUpload = new SWFUpload({
					upload_url : submissionURL,
					useQueryString : true,
					flash_url : "/systemincludes/js/swfupload/Flash/swfupload.swf",
					file_size_limit : "30 MB",						
					// Button Settings
					button_placeholder_id : "spanButtonPlaceholder",
					button_width: 123,
					button_height: 25,
					button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
					button_cursor: SWFUpload.CURSOR.HAND,
					button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,
					upload_start_handler: DA.affidavitUploadStartHandler,
					upload_progress_handler : DA.affidavitUploadProgressHandler,
					upload_success_handler : DA.affidavitUploadSuccessHandler,
					file_queued_handler : DA.affidavitFileQueuedHandler,
					file_queue_error_handler: DA.affidavitFileQueueErrorHandler,
					debug : false

				});		
		}	
	
	},
	postAffidavitUpload : function() {
	
		var dataToBePosted = $('#videoroiform').serialize() + '&method=' + DA.CONST_VIDEO_ROI_FEEDBACK_SUBMIT_METHOD;
		
		// AJAX call to submit form. Success handler should show success form
		// TODO: Need to handle error case
		$.post(DA.CONST_VIDEO_ROI_FEEDBACK_SUBMIT_URL, 		
			dataToBePosted, 
			function (data) {
			
				if (DA.isUserSubmittingAnAdvertiser)
				{
					// Reset the advertiser submission field in case the user
					// decides to submit the overall form, not just an 
					// advertiser (this can only happen on taggable spots)
					DA.isUserSubmittingAnAdvertiser = false;

					var submittedAdvertiserName = $.trim($('#fld_advertisername').val());
										
					// Since advertiser name is optional, we will need to show default
					// text in the advertiser grid if not specified by the user
					if (submittedAdvertiserName == "" || submittedAdvertiserName == null)
					{
						submittedAdvertiserName = "No Name Specified";
					}
					
					// Clear out advertiser form fields and show the newly added
					// advertiser in the advertisers list
					DA.clearAdvertiserFieldsAfterSubmission();

					DA.hideAJAXLoader();

					DA.addSubmittedAdvertiserToList(submittedAdvertiserName);
				}
				else
				{

					// This is an actual form submission. In this case, show the thank you page

					// Hide all existing divs
					$('#videoroiform > #type_specific_form_fields').hide();
					$('#common_fields').hide();
					
					$('#video_roi_form_nav_controls').hide();
					$('#submission_fields').hide();
					$('#upload_flash_container').hide();
					$('#taggable_spot_submission_fields').hide();
					$('#submission_thankyou').show();

					DA.hideAJAXLoader();
				
				}
				
				// Set the affidavit selected flag to false in case
				// the user decides to submit another form
				DA.affidavitSelected = false;
				
				
			});	


	},
	affidavitUploadStartHandler : function() {
		// Show the loading animaton
		DA.showAJAXLoader("Uploading Affidavit");
	},
	affidavitUploadProgressHandler : function(file, bytesComplete, bytesTotal) {
		
	
/*		var percentageComplete = 0;
		
		if (bytesComplete > 0)
		{
			percentageComplete = Math.round(bytesComplete / bytesTotal, 2)*100;
		}
	
		$('#video_roi_form_container .loading span').html('Uploading affidavit - ' + percentageComplete + '%');
*/
	},
	affidavitUploadSuccessHandler : function(file, serverData, responseReceived) {
	
		// Hide the loading animaton and any information text
		$('#video_roi_form_container .loading span').html('');
		$('#video_roi_form_container .loading').hide();
		
		// Since this affidavit was uploaded, we need to clear out the 
		// span where we show the current affidavit name
		$('#currently_selected_affidavit').html('');
		
		//alert(serverData);
		
		var serverDataAsJSON = $.evalJSON(serverData);

		var statusCodeFromUpload = serverDataAsJSON.statusCode;
		
		if (statusCodeFromUpload == 200)
		{
			// Success!!
			
			//alert('success');
			
			// Set the hidden field containing the affidavit name
			// that was generated on the server
			var generatedFileName = serverDataAsJSON.generatedFileName;
			
			$('#fld_affidavitfilename').val(generatedFileName);

			// After a successful upload, we'll want to submit the feedback form
			DA.postAffidavitUpload();
		}
		else if (statusCodeFromUpload == 500)
		{
			DA.hideAJAXLoader();
			alert('There was a problem uploading the file. Please try again');		
		}
		
	},
	affidavitUploadFailureHandler : function (file, errorCode, message) {
		
		DA.hideAJAXLoader();
		alert('There was a problem uploading the file. Please try again');		
	},
	affidavitFileQueuedHandler : function(file) {
		$('#currently_selected_affidavit').html('Current affidavit: ' + file.name);
		
		// Clear any existing errors
		$('#file_upload_error').html('');
		
		DA.affidavitSelected = true;
	},
	affidavitFileQueueErrorHandler : function(file, errorCode) {
		if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
		        $('#file_upload_error').html('Affidavits larger than 30MB cannot be uploaded.');
    	}
	},
	addSubmittedAdvertiserToList : function(advertiserName) {
		
		var itemKey = parseInt(Math.random()*99999999);
	
		$('<li class="recent" style="display:hidden"><div class="advertiser_list_name">' + advertiserName + '</div><div class="advertiser_list_status recent" id="ad_list_' + itemKey + '">This Advertiser Has Been Successfully Submitted</div></li>').hide().appendTo('#submitted_advertisers_list ul').fadeIn('slow');
	
		setTimeout(function(){
			  var $recentDiv = $("#ad_list_" + itemKey);
			  $recentDiv.fadeOut("slow", function () {
			  $recentDiv.parent().removeClass('recent');
			  $recentDiv.removeClass('recent');
			  $recentDiv.html('Submitted');
			  $recentDiv.fadeIn('fast');
		  });
		}, 3000);
 
	},
	clearAdvertiserFieldsAfterSubmission : function() {
		$('#fld_advertisername').val('');
		$('#fld_advertisertype').val('');
		$('#fld_dmasserved').val('');
		$('#fld_spotsran').val('');
		$('#fld_zones').val('');
		$('#fld_subscribersreached').val('');
		$('#fld_flightdatestart').val('');
		$('#fld_flightdateend').val('');
		$('#fld_crosschannelnetworks').val('');
		
	},
	clearSelectedNetwork : function() {
		$('#fld_networkid').val('');
		$('#selectednetworkid').val('');
		
		// Special case to clear the mult-select plugin
		$('#selectednetworkidclone').remove();
		$('.multiSelectOptions').remove();

	},
	clearAllFormErrors : function() {

		if (DA.videoROIFormValidator)
		{
			DA.videoROIFormValidator.resetForm();
			
		}

		// Get rid of the actual form validator
		// This is to get around issues with jQuery validation
		// and dynamic rules. Lame, but it works
		var roiForm = $('#videoroiform').get(0); 
		$.removeData(roiForm,'validator');
		
	},
	clearAllProgrammingClipFields : function() {
		
		// Clear out standard inputs
		$(':input', '#programming_clip_type_specific_fields')
			.not(':button, :submit, :reset, :hidden, :radio').val('').removeAttr('checked').removeAttr('selected');

		// Clear out radios
		$(':input:radio', '#programming_clip_type_specific_fields').removeAttr('checked').removeAttr('selected');

	},
	getNetworkValidationMessage : function() {
		var returnValue = "Please select a network.";
		
		var selectedVideoType = $('#roi_video_type_selection input:checked').attr('id');
		
		switch(selectedVideoType)
		{
			case "radProgrammingClip":
				returnValue = "Please select at least one network.";
				break;
			default:
				break;
		}
		
		return returnValue;
	
	},
 	showProgrammingClipConsumerPromoFields : function() {
		// Despite being the same underlying fields, there are
		// a few fields that need to have labels changed
		$('#upload_flash_container').addClass('required');
		$('#upload_flash_container').show();
		// reinitialize the SWFupload tool. This is due to a defect in FireFox and Flash
		DA.initializeSWFUploader();
		
		$('label[for="fld_estimatedimpressions"]').not('error').html('Estimated Impressions (Reach)');
		$('label[for="fld_flightdatestart"]').not('error').html('Flight Dates*');
 	
		$('#clip_titles').show();
		$('#campaign_types').show();
		$('#dmas_served').show();
		$('#group_video_details').show();
		$('#group_flight_dates').show();
		$('#cross_channel_networks').show();
		$('#description_of_use').show();
		
			DA.centerDialog();
			
		
	},
	showProgrammingClipRetailFields : function() {
		$('#upload_flash_container').removeClass('required');
		$('#upload_flash_container').hide();
	
		// Despite being the same underlying fields, there are
		// a few fields that need to have labels changed

		$('label[for="fld_estimatedimpressions"]').not('error').html('Estimated Impressions (Reach)');
		$('label[for="fld_flightdatestart"]').not('error').html('Flight Dates*');
	
		$('#clip_titles').show();
		$('#retail_outlet_types').show();
		$('#retail_outlet_location').show();
		$('#retail_outlet_name').show();
		$('#dmas_served').show();		
		$('#estimated_impressions').show();		
		$('#group_flight_dates').show();
		$('#description_of_use').show();
		
			DA.centerDialog();
			
		
	},
	showProgrammingClipPresentationFields : function() {
		$('#upload_flash_container').removeClass('required');
		$('#upload_flash_container').hide();
	
		// Despite being the same underlying fields, there are
		// a few fields that need to have labels changed
		
		$('label[for="fld_estimatedimpressions"]').not('error').html('Number of Impressions');
		$('label[for="fld_flightdatestart"]').not('error').html('Use Dates*');
	
		$('#clip_titles').show();
		$('#estimated_impressions').show();		
		$('#group_flight_dates').show();
		$('#description_of_use').show();
		
			DA.centerDialog();
			
		
	},
	showProgrammingClipOtherFields : function() {
		$('#upload_flash_container').removeClass('required');
		$('#upload_flash_container').show();
		// reinitialize the SWFupload tool. This is due to a defect in FireFox and Flash
		DA.initializeSWFUploader();

		// Despite being the same underlying fields, there are
		// a few fields that need to have labels changed
		
		$('label[for="fld_estimatedimpressions"]').not('error').html('Estimated Impressions (Reach)');
		$('label[for="fld_flightdatestart"]').not('error').html('Flight Dates*');
	
		$('#clip_titles').show();
		$('#campaign_types').show();
		$('#dmas_served').show();
		$('#group_video_details').show();
		$('#group_flight_dates').show();
		$('#cross_channel_networks').show();
		$('#description_of_use').show();
		
				DA.centerDialog();
			
	
	},
	showAJAXLoader : function(loadingTextToDisplay) {
		
		// Don't show loader with FireFox. This is causing the SWFUpload Flash
		// object to crash the browser
		if (!$.browser.mozilla)
		{
			$('#video_roi_feedback_form_main').mask(' ');
		}
	},
	hideAJAXLoader : function() {
		if (!$.browser.mozilla)
		{
			$('#video_roi_feedback_form_main').unmask();
		}
	},
	centerDialog : function() {
		DA.videoSurveyDialog.dialog("option", "position", "['center', 20]");
		
		// Update the height of the overlay since the UI dialog plugin doesn't
		// do this automatically
		var documentHeight = $(document).height();

		$('.ui-widget-overlay').attr('style', 'height: ' + documentHeight + 'px !important; z-index: 1001;')

	}
	
	
	
};


