dojo.require('dojo.io.iframe');
dojo.require('dijit.form.Form');
dojo.require('dijit.form.Button');
dojo.require('dijit.form.TextBox');
dojo.require('dijit.form.CheckBox');

//**************************
if(!window.DEBUG_TRACE_ID){ window.DEBUG_TRACE_ID = 0; }
//**************************

AdvertiserApp = {
	constants: {
		sizeHelperTextTemplate: 'For ${numBlocks} ${tense} of ad space, we recommend an image size of ${width}px x ${height}px.',
		formatHelperTextTemplate: 'Formats accepted: ${types}.', //${types} generated from this.constants.allowedImageFileTypes;
		adBlockPricingTemplate: '${displayPrice} ${creditTense} per display; ${clickPrice} credits per click',
		sampleAdTitle: '<span class="sample">Sample Title</span>',
		sampleAdText: '<span class="sample">Sample advertisement text</span>',
		//LessInfoLinkText: 
		//		The default link text to display for a 'less info' link. To override the default w/ a custom value, place 
		//		this attribute (LessInfoLinkText) in markup in the 'more info' link element w/ the custom value. E.g.:
		//				<a id="myInfoLink" LessInfoLinkText="(Hide the info that was just shown...)">(More info...)</a>
		LessInfoLinkText: 'Hide info...', 
		allowedImageFileTypes: ['jpg', 'jpeg', 'jpe', 'png', 'gif'], //the file types we allow for upload;
		baseValues: {
			displayRate: 1,
			clickRate: 10,
			//imageHeightPixels: 135,
			imageHeightPixels: 80,
			imageWidthPixels: 135
		}
	},
	adPreviewIsImage: false, //used to determine what kind of ad preview to show: text or image;
	previewImageJson: {},
	isEdit: false, //false for a new ad application, true for editing an existing ad

	//Called from dojo.addOnLoad() at bottom of file;
	init: function()
	{
		console.warn('at AdvertiserApp.init()');
		console.warn('this.isEdit: '+this.isEdit);
		
		this.updateImageRecommendation(); //initialize the image recommendation text (initial value will be for one ad block);
		this.updateAdPreview();
		this.wireEvents();
		
		//-------------------
		/*Removing adblock option from UI
		if(!dojo.isIE){
		//IE reverses the row order, so the first row ends up holding the value for the last, 2nd row holds value for 2nd to last row, and so on. Because 
		//of this, IE is excluded from this logic and will use the default hard-coded values in the html markup. Unfortunately this means the below logic
		//loses its value (of reducing the places code would need to be updated), as the hard-coded values will have to be manually updated for IE anyway
		//The logic below has been left in place in the hopes that IE will some day become a standards-complient browser and be able to understand the logic.
	
			//Set pricing text displayed in the Ad Block Pricing more-info table...
			//Uses the values from this.constants.baseValues to calculate the display values.
			dojo.query('#adBlockPricing td:nth-child(2) span').forEach(function(node, index){
				var numBlocks = index + 1; //should be equal to the row number;
				var calculatedVals = {
					displayPrice: this.constants.baseValues.displayRate * numBlocks,
					clickPrice: this.constants.baseValues.clickRate * numBlocks
				};
				calculatedVals.creditTense = (calculatedVals.displayPrice == 1) ? 'credit' : 'credits';
				node.innerHTML = dojo.string.substitute(this.constants.adBlockPricingTemplate, calculatedVals);
			}, this);
		}
		*/
	},
	
	wireEvents: function()
	{
		/*Removing adblock option from UI
		//Connects onclick handlers to each of the adBlock radios.
		dojo.query('#adBlocks input[type=radio]').forEach(function(node){
			dojo.connect(node, 'onclick', AdvertiserApp, 'updateImageRecommendation');
			dojo.connect(node, 'onclick', AdvertiserApp, 'updateAdPreview');
		});
		*/
		

		dojo.forEach(['Title','Text', 'Link'], function(field){
			dojo.connect(dijit.byId(field), 'onChange', AdvertiserApp, 'updateAdPreview');
			dojo.connect(dijit.byId(field), 'onKeyUp', AdvertiserApp, 'updateAdPreview');
		});
		
		dojo.connect(dojo.byId("AdvertisementImageFile"), 'onchange', this, 'enableImageButtons');

		//Connects onclick handler to location-based checkbox.
		//dojo.connect(dojo.byId('locationBased'), 'onclick', AdvertiserApp, 'toggleLocationBasedFields');
		dojo.connect(dijit.byId('locationBased'), 'onChange', AdvertiserApp, 'toggleLocationBasedFields');
		
		//If 'Enter' key pressed inside given textbox, simulate a click on corresponding button;
		dojo.connect(dojo.byId("PostalCode"), 'onkeypress',function(evt){
				key = evt.keyCode;
				if(key == dojo.keys.ENTER){
					//dojo.byId("updateMap").click();
					AdvertiserApp.map.getZipCodeLatLong();
				}
		});

		//Connects onclick handlers to each of the map "reach" radios.
		dojo.query('#rangeContainer input[type=radio]').forEach(function(node){
			dojo.connect(node, 'onclick', AdvertiserApp.map, 'onRangeClick'); //ORIG // 1/2 works
			//dojo.connect(node, 'onClick', AdvertiserApp.map, 'onRangeClick'); //no work
			//dojo.connect(node, 'onchange', AdvertiserApp.map, 'onRangeClick'); // 1/2 works
			//dojo.connect(node, 'onChange', AdvertiserApp.map, 'onRangeClick'); //no work
		});

		//center the map on the provided zipcode after the update link/button is clicked.
		//dojo.connect(AdvertiserApp, 'getZipCodeLatLong', AdvertiserApp.map.setCenter...);
	},
	
	validate: function(isTempTestCode)
	{
		var isValid = true;
		var errors = [];

		//First Name;
         if(dojo.byId("FirstName").value.length == 0){
            errors.push("First name cannot be empty.");
         }

		//Last Name;
         if(dojo.byId("LastName").value.length == 0){
            errors.push("Last name cannot be empty.");
         }
		 

	 
		//Company Name;
         if(dojo.byId("CompanyName").value.length == 0){
            errors.push("Company name cannot be empty.");
         }


		//Email
		var emailVal = dijit.byId('ContactEmail').attr('value');
		var confirmEmailVal = dijit.byId('ContactEmailConfirm').attr('value');
		if (emailVal.length == 0)
		{
			errors.push("Contact email cannot be empty.");
		} 
		else if(!validators.isValidEmailSyntax(emailVal))
		{
			errors.push("Invalid contact email syntax.");
		} 
		else if(emailVal != confirmEmailVal) //Check that email addresses match
		{
			errors.push("Email addresses do not match.");
		}

		//Location-based
		if(dijit.byId('locationBased').attr('value')) //if checkbox is checked...
		{
			var mapErrors = AdvertiserApp.map.validate();
			errors = errors.concat(mapErrors);
		}
		
		//Title
        var titleVal = dojo.byId("Title").value;
        if(titleVal.length <= 0){
           errors.push("Ad Title cannot be empty.");
        }
      
		//Text
        var TextVal = dojo.byId("Text").value;
        if(TextVal.length <= 0){
          errors.push("Ad Text cannot be empty.");
        }

		//Link
        var LinkVal = dojo.byId("Link").value;
        if(LinkVal.length <= 0){
          errors.push("Ad Link cannot be empty.");
        }

		//Image
		var ImageVal = dojo.byId("AdvertisementImageFile").value;
		if(ImageVal.length > 0)
		{
			var imageTypeError = this.validateImageType(ImageVal);
			errors = errors.concat(imageTypeError);
		}


		if(errors.length > 0)
		{
			this.showAppFormErrors(errors);
		}
		else
		{
			this.save();
			/*if(isTempTestCode)//Remove this 'if' statement after image upload is implemented.
			{
				this.TEST_IMG_save();
			}
			else
			{
				this.save();
			}
			*/
		}
		
	},
	showErrors: function(errors, errorDiv, message)
	{
		
		var errorHtml = '<img src="../../images/error.png" width="16" height="16" style="padding-right:5px;">';
		errorHtml += (typeof(message) == 'undefined') ? '' : message;
		errorHtml += '<ul>';
		dojo.forEach(errors, function(errorString){
			errorHtml += '<li>' + errorString + '</li>';
		});
		errorHtml += '</ul>';
		dojo.byId(errorDiv).innerHTML = errorHtml;
		
		
		dojo.style(errorDiv, {
			'display': 'block',
			'visibility': 'hidden'
		});
        dojo.byId(errorDiv).scrollIntoView(true); //scroll the error div into view if it isn't already;
		setTimeout("dojo.style('"+errorDiv+"', 'visibility', 'visible');", 200);
	},
	showAppFormErrors: function(errors)
	{
		//var message = 'The following errors were found with the data you entered:';
		//var message = 'Oops, we need a few more pieces of information from you. Please fill in the following fields:';
		var message = 'Oops, there were some problems with the information you entered. Please correct the following items:';
		this.showErrors(errors, 'AppFormErrors', message);
	},
	showImagePreviewErrors: function(errors)
	{
		this.showErrors(errors, 'ImagePreviewErrors');
	},
	
	//Original save method. Still in use on live site... soon to be deprecated.
	save: function()
	{
		console.log('at save()');

		dojo.xhrPost({
				url: "/Wikisori/Wikisori_forms.php",
				handleAs: "json",
				content: {
					fn: "ProcessAdvertiserForm", 
					FirstName: dojo.byId("FirstName").value,
					LastName: dojo.byId("LastName").value,
					ContactPhone: dojo.byId("ContactPhone").value,
					ContactEmail: dojo.byId("ContactEmail").value,
					CompanyName: dojo.byId("CompanyName").value,
					Website: dojo.byId("Website").value,
					Title: dojo.byId("Title").value,
					Text: dojo.byId("Text").value,
					Link: validators.formatUrl( dojo.byId("Link").value )
				},
				load: function(response){
					console.debug('response:');
					console.debug(response);
					
					dojo.style('AppFormErrors', 'display', 'none'); //hide any error msgs still hanging around from before the form was successfully submitted;
					AdvertiserApp.showRegistrationComplete(response);
				},
				error: function(error){
					//console.debug(error);
					//Maybe use some kind of generic error handler here if we decide we need one;
				}
				
		});							
	
	},
	//TEST_IMG_save: function(isPreview)
	save: function(isPreview)
	{
		var DEBUG_TRACE_ID = ++window.DEBUG_TRACE_ID;
		console.info('['+ DEBUG_TRACE_ID +']TEST_IMG_save()');

		//dojo.io.iframe.send() grabs the form values and sends them in the request, so
		//before we send, replace the Link url in the form w/ a formatted version of itself. 
		//Kind of hacky, but it works...
		dijit.byId('Link').attr('value', validators.formatUrl( dijit.byId('Link').attr('value') ));
		
		//TEMP MOCKED VALUES...
//		appFormValues = { "FirstName": "test first name", "LastName": "test last name", "ContactPhone": "test contact phone", "ContactEmail": "test.email@wikisori.org", "ContactEmailConfirm": "test.email@wikisori.org", "CompanyName": "test company name", "Website": "test.web.site", "Title": "test ad title", "Text": "test ad text", "Link": "http://test.ad.link" };
//		console.log('appFormValues',dojo.toJson(appFormValues, 1));
		
		console.log('\t['+ DEBUG_TRACE_ID +']dijit.byId("advertiserApplicationForm").attr("value")');
		console.dir(dijit.byId('advertiserApplicationForm').attr('value'));
		var formData = dijit.byId('advertiserApplicationForm').attr('value');
		formData.LocationBased = dijit.byId('locationBased').attr('value') ? true : false;
		if(!isPreview && formData.LocationBased)
		{
			formData.TargetLatitude = AdvertiserApp.map.currentLatLong.lat();
			formData.TargetLongitude = AdvertiserApp.map.currentLatLong.lng();
			formData.TargetRadius = dojo.query('#rangeContainer input[type=radio]:checked')[0].value; //get the radio value.
		}
		console.log('\t['+ DEBUG_TRACE_ID +']formData');
		console.dir(formData);
//return;
		console.log('\t['+ DEBUG_TRACE_ID +']isPreview:'+isPreview);
		if(this.imageRemoved === true)
		{
			formData.imageRemoved = true;
		}

		console.log('\t['+ DEBUG_TRACE_ID +']this.adPreviewIsImage: '+this.adPreviewIsImage);
		console.log('\t['+ DEBUG_TRACE_ID +']this.previewImageJson... ');
		console.log(this.previewImageJson);


		var exceptionExists = false;
		
		var urlQueryString = (isPreview) ? '?fn=PreviewImage' : '?fn=ProcessAdvertiserForm'; //ORIG
		//var urlQueryString = (isPreview) ? '?fn=PreviewImage' : (this.isEdit) ? '?fn=UPDATE_CASE_PLACEHOLDER' : '?fn=ProcessAdvertiserForm'; //TESTING - IN PROGRESS
		console.log('\t['+ DEBUG_TRACE_ID +']urlQueryString: '+urlQueryString);
		
		dojo.io.iframe.send({
				//url: "/Wikisori/Wikisori_forms.php?fn=ProcessAdvertiserForm",
				//url: "/Wikisori/tmp_djv.php"+urlQueryString,
				url: "/Wikisori/Wikisori_forms.php"+urlQueryString,
				form: "advertiserApplicationForm", //id of the form
				handleAs: "json",
				content: formData,
				//timeout: 10000,
				load: function(response,ioArgs)
				{
					console.debug('in load()...');
					console.log(response);
//debugger;					
					if(response.success)
					{
						console.log('success');
						console.log('isPreview:'+isPreview);
						if(isPreview)
						{
							dojo.style('ImagePreviewErrors', 'display', 'none'); //hide any error msgs still hanging around from a previous submit;
							AdvertiserApp.previewImageJson = response.previewImageJson;
							AdvertiserApp.updateAdPreview();
						}
						else
						{
							dojo.style('AppFormErrors', 'display', 'none'); //hide any error msgs still hanging around from before the form was successfully submitted;
							dojo.byId('AdvertisementImageFile').value = '';  // clear file box after successfully saving uploaded image.
							if(AdvertiserApp.isEdit)
							{
								ManageAdvertisement.showAdvertisementSaveComplete(response);		
							}
							else
							{
								AdvertiserApp.showRegistrationComplete(response);
							}
							
						}
					}
					else
					//Doesn't seem to be an xhr object in the ioArgs object, so there isn't a way to access the header
					//info. So instead sending the exception object back inside a "successful" response
					if(!response.success && response.mpExceptionObject)
					{
						//errObj = response.mpExceptionObject;
						exceptionExists = true;
						console.log('exceptionExists: ' + exceptionExists);
					}
				},
				error: function(error,ioArgs)
				{
					console.debug('got an error...');
					console.debug('not a server-side handled exception');
					console.debug(error);
					if(ioArgs && ioArgs.xhr && ioArgs.xhr.getResponseHeader('mpExceptionObject'))
					{
						//errObj = ioArgs.xhr.getResponseHeader('mpExceptionObject');
						exceptionExists = true;
						console.log('exceptionExists: ' + exceptionExists);
					}
					else
					{
						//no custom exception thrown (some other kind of error), so handle that error here.
						console.log('no error object');
					}
			
					//var allHeaders = ioArgs.xhr.getAllResponseHeaders();
					//console.log('all response headers: ' + dojo.toJson(allHeaders,1));
				},
				handle: function(response,ioArgs)
				{
					//called at the end of every request, whether or not an error occurs.
					console.log('in handle()...');
					console.log('exceptionExists: ' + exceptionExists);
					if(exceptionExists)
					{
						var errorObj = response.mpExceptionObject;
						console.log('ExceptionType: %s, Message: %s',errorObj.ExceptionType||'(empty)', errorObj.Message);

						if(isPreview)
						{
							AdvertiserApp.showImagePreviewErrors([errorObj.Message]);
						}
						else
						{
							if(errorObj.ExceptionType == "UnknownFailure")
							{
								AdvertiserApp.showErrors([errorObj.Message], 'AppFormErrors');
							}
							else
							{
								AdvertiserApp.showAppFormErrors([errorObj.Message]);
							}
						}
					}
				}
				
		});							
	
	},
	
	showMoreInfo: function(infoId, linkId)
	{
		//Used w/ a 'Learn more' link to show a hidden 'more info' div;
		// ARGUMENTS
		//		infoId: (string) id of the 'more info' div to show;
		//		linkId: (string) (optional) id of the 'learn more' link;
		
		var linkNode = dojo.byId(linkId);
		var infoNode = dojo.byId(infoId);
		
		if(typeof(linkNode.MoreInfoLinkText) == 'undefined')
		{
			//If it isn't already, store the 'more info' link text used for this link so we can display it again when the info is hidden;
			linkNode.MoreInfoLinkText = linkNode.innerHTML; 
		}
		if(typeof(linkNode.LessInfoLinkText) == 'undefined')
		{
			//If no custom 'less info' link text is defined for this link in markup, e.g.:
			//		<a id="myInfoLink" LessInfoLinkText="hide the info">More info...</a>
			//create a LessInfoLinkText property on the link, using the default text value (this.constants.LessInfoLinkText);

			//Determine if the LessInfoLinkText attribute exists in markup...
			var searchResult = dojo.filter(linkNode.attributes, function(attribute){
				return attribute.nodeName == 'LessInfoLinkText'.toLowerCase();
			});
			//if it does exist, save it's value to a top-level property on the 'less info' link node...
			if(searchResult.length == 1)
			{
				linkNode.LessInfoLinkText = searchResult[0].value || searchResult[0].textContent;
			}
			else //if it doesn't exist, use the default value...
			{
				linkNode.LessInfoLinkText = this.constants.LessInfoLinkText;
			}
		}
		
		//if it's hidden... show it.
		if(dojo.style(infoNode, 'display') == 'none')
		{
			linkNode.innerHTML = linkNode.LessInfoLinkText;
			dojo.style(infoId, 'display', 'block');
		}
		else //it's shown... so hide it.
		{
			linkNode.innerHTML = linkNode.MoreInfoLinkText;
			dojo.style(infoId, 'display', 'none');
		}

	},
	
	getSelectedNumBlock: function()
	{
		return 1;//adblock option has been removed, so retun the only allowable size: 1;
		
		//run a query for any checked radio inputs that are children of a node w/ id == adBlocks, and get their (for a radio, only one will be returned) value...
		//return dojo.query('#adBlocks input[type=radio]:checked')[0].value; //i.e. 1, 2, 3, or 4;
	},
	
	updateImageRecommendation: function()
	{
		/*Removed adblocks option from UI
		var numBlocks = this.getSelectedNumBlock();
		//our new values to use in the helper text string...
		var valueObject = {
			numBlocks: numBlocks, //e.g. 1, 2, 3, or 4
			tense: (numBlocks > 1) ? 'blocks' : 'block',
			width: this.constants.baseValues.imageWidthPixels, //e.g. 130
			height: this.constants.baseValues.imageHeightPixels * numBlocks //e.g. 145, 290, etc.
		};
		var sizeHelperText = dojo.string.substitute(this.constants.sizeHelperTextTemplate, valueObject);
		*/
		var formatHelperText = dojo.string.substitute(this.constants.formatHelperTextTemplate, {types: this.constants.allowedImageFileTypes.join(', ')});
		//dojo.byId('imageSizeRecommendation').innerHTML = sizeHelperText + ' ' + formatHelperText;
		dojo.byId('imageSizeRecommendation').innerHTML = formatHelperText;
	},
	
	validateImageType: function(imageVal)
	{
        var errors = [];
		var fileType = imageVal.substr(imageVal.lastIndexOf('.') + 1);
		var isValidFileType = dojo.some(this.constants.allowedImageFileTypes, function(allowedType){
			return fileType.toLowerCase() == allowedType.toLowerCase();
		});
        if(!isValidFileType){
          errors.push("."+fileType+" file types are not allowed for advertisement images.");
        }
		return errors;
	},
	
	enableImageButtons: function()
	{
		var ImageVal = dojo.byId("AdvertisementImageFile").value;
		var disable = (ImageVal.length > 0) ? false : true;
		dijit.byId("previewImage").attr('disabled', disable);
		//dijit.byId("removeImage").attr('disabled', disable);
	},
	removeImageAd: function()
	{
		this.adPreviewIsImage = false;
		this.imageRemoved = true;//used server-side so we know if an existing image was explicitly removed by user, or just no new image was uploaded (ie, user wants to keep existing img).
		dijit.byId("removeImage").attr('disabled', true);
		this.updateAdPreview();
	},

	previewImageAd: function()
	{
		console.info('['+ (++window.DEBUG_TRACE_ID) +']previewImageAd()');

		var errors = [];
		var ImageVal = dojo.byId("AdvertisementImageFile").value;
		if(ImageVal.length > 0)
		{
			var imageTypeError = this.validateImageType(ImageVal);
			errors = errors.concat(imageTypeError);
		}
		if(errors.length > 0)
		{
			this.showImagePreviewErrors(errors);
			return;
		}

		this.adPreviewIsImage = true;
		this.imageRemoved = false;//used server-side so we know if an existing image was explicitly removed by user, or just no new image was uploaded (ie, user wants to keep existing img).
		dojo.style('ImagePreviewErrors', 'display', 'none'); //hide any error msgs still hanging around from a previous submit;
		dijit.byId("removeImage").attr('disabled', false);

		//this.TEST_IMG_save(true); 
		this.save(true); 

	},
	updateAdPreview: function()
	{
		console.info('['+ (++window.DEBUG_TRACE_ID) +']AdvertiserApp.updateAdPreview()');
		
		//Update the size of the ad box displayed in the preview...
		var widthNum = AdvertiserApp.constants.baseValues.imageWidthPixels;
		var heightNum = (AdvertiserApp.constants.baseValues.imageHeightPixels * AdvertiserApp.getSelectedNumBlock());
		/*
		dojo.style('adPreview', {
//			'width': AdvertiserApp.constants.baseValues.imageWidthPixels + 'px',
//			'height': (AdvertiserApp.constants.baseValues.imageHeightPixels * AdvertiserApp.getSelectedNumBlock()) + 'px'
			'width': widthNum + 'px',
			'height': heightNum + 'px'
		});
		*/
		//Update the ad contents in the preview w/ the user provided values from the form...

		console.log('\t['+ (window.DEBUG_TRACE_ID) +']this.adPreviewIsImage: '+this.adPreviewIsImage);
		console.log('\t['+ (window.DEBUG_TRACE_ID) +']this.previewImageJson: \n %s', dojo.toJson(this.previewImageJson,1));
		//console.log(this.previewImageJson);
		if(this.adPreviewIsImage) //IMAGE AD
		{
			/*Deprecated w/ adblock removal
			dojo.style('textAd', 'display', 'none');
			*/
			dojo.style('imageAd', 'display', 'block');
			
//			dojo.attr('imageAd','innerHTML', this.adPreviewImage);

			//TEMP - MOCK
/*
			this.previewImageJson = {
				//url: 'http://www.wikisori.org/Wikisori/Wikisori_forms.php?fn=GetImage&ImageID=30',
				imageId: 30,
				width: '200',
				height: '800'
			};
*/			
			var _MaxHeight = heightNum;
			var _MaxWidth = widthNum;
			
			var _ImageHeight = this.previewImageJson.height; //of original, unmodified image;
			var _ImageWidth = this.previewImageJson.width; //of original, unmodified image;
			
			var _ImageHeightRatio = _MaxHeight/_ImageHeight;
			var _ImageWidthRatio = _MaxWidth/_ImageWidth;
			
			
			var _Ratio = Math.min(_ImageHeightRatio, _ImageWidthRatio, 1);
			console.log('\t['+ (window.DEBUG_TRACE_ID) +']_Ratio: '+_Ratio);

			_ImageHeight = _ImageHeight * _Ratio;
			_ImageWidth = _ImageWidth * _Ratio;
			
			var processedWidth = _ImageWidth;
			var processedHeight = _ImageHeight;

			//var imgUrl = 'http://www.wikisori.org/Wikisori/Wikisori_forms.php?fn=GetImage&ImageID=27';

			dojo.attr('imageAdImage', 'width', processedWidth);
			dojo.attr('imageAdImage', 'height', processedHeight);
			var imageUrl = 'http://www.wikisori.org/Wikisori/Wikisori_forms.php?fn=GetImage&ImageID='+this.previewImageJson.imageId;
			dojo.attr('imageAdImage', 'src', imageUrl);
			//dojo.attr('imageAdImage', 'src', this.previewImageJson.url);
			//dojo.attr('imageAdImage', 'src', this.adPreviewImage);
			
			
		}
		else //TEXT AD
		{
			dojo.style('imageAd', 'display', 'none');
		}
			//dojo.style('textAd', 'display', 'block');

		//TITLE
		var adTitleVal = dijit.byId('Title').attr('value') || this.constants.sampleAdTitle;
		dojo.attr('textAdTitle','innerHTML', adTitleVal);
		
		//TEXT
		var adTextVal = dijit.byId('Text').attr('value') || this.constants.sampleAdText;
		dojo.attr('textAdText','innerHTML', adTextVal);

		//LINK
		var adLinkVal = dijit.byId('Link').attr('value');
		adLinkVal = (adLinkVal == '') ? '#' : validators.formatUrl(adLinkVal);
		//dijit.byId('Link').attr('value', adLinkVal); //put the formatted link back in the textbox;

		//dojo.attr('textAdLink','href', adLinkVal);
		//dojo.attr('imageAdLink','href', adLinkVal);
		dojo.attr('AdTitleLink','href', adLinkVal);
		dojo.attr('AdBodyLink','href', adLinkVal);

		
	},
	
	toggleLocationBasedFields: function()
	{
		console.info('['+ (++window.DEBUG_TRACE_ID) +']AdvertiserApp.toggleLocationBasedFields()');
		  
		if(!this.map.isInitialized)
		{
			this.map.isInitialized = true; //TESTING for edit
			this.map.initialize();
		}
		//(dojo.style('mapContainer', 'display') == 'none') ? dojo.style('mapContainer', 'display', 'block') : dojo.style('mapContainer', 'display', 'none');
		dijit.byId('locationBased').attr('value') ? dojo.style('mapContainer', 'display', 'block') : dojo.style('mapContainer', 'display', 'none');
	},
	
	//*NOTE: AdvertiserApp.map.currentLatLong should be able to be used as the lat/long when submitting the complete advertiser app.
	//A namespace for map-related properties and methods.
	map: 
	{
		isInitialized: false,
		currentLatLong: null, 
		Map: null, //the actual google map object
		CircleOverlay: null, //The CircleOverlay object
		
		validate: function()
		{
			var errors = [];
			if(this.currentLatLong == null)
			{
//				errors.push('When making an ad location-based, a location must be specified. Please enter a postal code and click Apply, or click your desired location on the map.');
				errors.push('For location-based ads, a location must be specified on the map. Please enter a postal code and click Apply, or click your desired location on the map.');
			}
			return errors;
		},
		clear: function()
		{
			this.currentLatLong = null;
			this.CircleOverlay.clear();
		},
		onRangeClick: function()
		{
			var latLong = (this.currentLatLong != null) ? this.currentLatLong : AdvertiserApp.map.Map.getCenter();
			AdvertiserApp.map.update(null, latLong);
		},
		getZipCodeLatLong: function()
		{
			console.info('at map.getZipCodeLatLong()');
			//If no zipcode is entered, just update the map using the lat/long from center of current map view (i.e. place a 
			//new circle overlay in the center of the current map view). otherwise 0,0 gets returned and used as the lat/long.
			if(dijit.byId('PostalCode').attr('value').length == 0)
			{
				AdvertiserApp.map.currentLatLong = AdvertiserApp.map.Map.getCenter(); //set current lat/long to center of current map view;
				AdvertiserApp.map.update(null, AdvertiserApp.map.currentLatLong);
				return;
			}
			dojo.xhrPost({
					url: "/Wikisori/Wikisori_forms.php?fn=GetZipCodeLatLong",
					handleAs: "json",
					content: { ZipCode: dijit.byId('PostalCode').attr('value') },
					load: function(response){
						console.log('Lat: %d, Long: %d',response.Lat, response.Long);
						AdvertiserApp.map.update(null, new GLatLng(response.Lat, response.Long));
					},
					error: function(error){
						//console.debug(error);
						//Maybe use some kind of generic error handler here if we decide we need one;
					}
					
			});
		},
		
		initialize: function(latLong)
		{
			console.warn('at map.initialize()');
		  
			if (GBrowserIsCompatible())
			{
				dojo.xhrGet({
					url: "/Wikisori/Wikisori_forms.php?fn=GetIPLatLong",
					handleAs: 'json',
					load: function(response)
					{
						console.log('Lat: %d, Long: %d',response.Lat, response.Long);
						console.log(response);

						AdvertiserApp.map.isInitialized = true;
						AdvertiserApp.map.Map = new GMap2(document.getElementById("map_canvas"));
		
						//This is super hacky... map is having issues finishing rendering unless initialized inside this xhr callback. For an edit, we don't need the 
						//xhr request for the lat/long since we already have those values from the saved advertisment object, but doing the initialization
						//inside the callback is a quick workaround to get the map to render completely.
						if(AdvertiserApp.isEdit && ManageAdvertisement.data.locationBased)
						{
							AdvertiserApp.map.Map.setCenter(new GLatLng(ManageAdvertisement.data.TargetLatitude, ManageAdvertisement.data.TargetLongitude), 6); //
							AdvertiserApp.map.update(null, new GLatLng(ManageAdvertisement.data.TargetLatitude, ManageAdvertisement.data.TargetLongitude));
						}
						else
						{
							AdvertiserApp.map.Map.setCenter(new GLatLng(response.Lat, response.Long), 9);
						}


						GEvent.addListener(AdvertiserApp.map.Map, "click", AdvertiserApp.map.update);
						AdvertiserApp.map.Map.addControl(new GSmallMapControl());
						AdvertiserApp.map.Map.addControl(new GMapTypeControl());

					},
					error: function()
					{
						console.error('Error loading map');
					}
				});
				
		  
			}
			else
			{
				console.error('Browser not compatible w/ map');
			}
					
		},
	
		update: function(overlay, latlng) 
		{
			console.info('at map.update()');
			console.log(overlay);
			console.log(latlng);
			
			
			if (latlng) 
			{ 
				AdvertiserApp.map.currentLatLong = latlng;
				console.info('AdvertiserApp.map.currentLatLong: '+AdvertiserApp.map.currentLatLong); //DEBUG;
				//var myHtml = "You are here.";
				//AdvertiserApp.map.Map.openInfoWindow(latlng, myHtml);
		
				// Create and add the CircleOverlay
				var circleRadius = dojo.query('#rangeContainer input[type=radio]:checked')[0].value; //get the radio value.
				console.info('circleRadius: '+circleRadius); //DEBUG;
				AdvertiserApp.map.Map.panTo(latlng); //centers the map on this lat/long.
				if(typeof(AdvertiserApp.map.CircleOverlay) == 'undefined' || AdvertiserApp.map.CircleOverlay == null)
				{
					AdvertiserApp.map.CircleOverlay = new CircleOverlay(latlng, circleRadius);
					AdvertiserApp.map.Map.addOverlay(AdvertiserApp.map.CircleOverlay);
				}
				else
				{
					//---------------
					//this.clear();//TESTING;
					//this.CircleOverlay.clear();
		
					//-----------
					//console.info('containsLatLng: '+AdvertiserApp.map.CircleOverlay.containsLatLng(latlng)); //DEBUG;
					//if(AdvertiserApp.map.CircleOverlay.containsLatLng(latlng)) 
					//{ //TODO: see if this is working. i dont think it is.
					//	AdvertiserApp.map.CircleOverlay.clear();
					//}
					AdvertiserApp.map.CircleOverlay.setLatLng(latlng);
					AdvertiserApp.map.CircleOverlay.setRadius(circleRadius);
					AdvertiserApp.map.CircleOverlay.redraw();
				}
	
			}
			console.warn('END OF AdvertiserApp.map.update()');//DEBUG
		}

	},
	
	
	showRegistrationComplete: function(data)
	{
		
		//dojo.byId('email').innerHTML = data.ContactEmail;
		
		dojo.style('RegistrationForm', 'display', 'none');
		dojo.style('HowDoesAdvertisingWork', 'display', 'none');
		dojo.style('RegistrationComplete', 'display', 'block');
	}

};
dojo.addOnLoad(AdvertiserApp, 'init');


/*
var AdvertisementForm = {
};
*/




/* EOD code from firebug console *

(function(){
console.log('********************************************************');
var use_fb_method = 0;
if(use_fb_method){//use firebug method to send request...

appFormValues = { 
    "FirstName": "test first name", 
    "LastName": "test last name", 
    "ContactPhone": "test contact phone", 
    "ContactEmail": "test.email@wikisori.org", 
    "ContactEmailConfirm": "test.email@wikisori.org", 
    "CompanyName": "test company name", 
    "Website": "test.web.site", 
    "Title": "test ad title", 
    "Text": "test ad text", 
    "Link": "test.ad.link", 
    "NumBlocks": 1
};
dijit.byId('advertiserApplicationForm').attr('value',appFormValues);

var exceptionExists = false;
//var errObj;
dojo.io.iframe.send({
//dojo.xhrPost({
    url: '/Wikisori/tmp_djv.php?fn=ProcessAdvertiserForm',
    form: "advertiserApplicationForm", //id of the form
    handleAs: 'json',
    load: function(response,ioArgs){
        console.debug('in load()...');
        console.log(response);

        //Doesn't seem to be an xhr object in the ioArgs object, so there isn't a way to access the header
        //info. So instead sending the exception object back inside a "successful" response
        if(!response.success && response.mpExceptionObject)
        {
            //errObj = response.mpExceptionObject;
            exceptionExists = true;
            console.log('exceptionExists: ' + exceptionExists);
        }
	//dojo.style('AppFormErrors', 'display', 'none'); //hide any error msgs still hanging around from before the form was successfully submitted;
	//AdvertiserApp.showRegistrationComplete(response);
    },
    error: function(error,ioArgs){
        console.debug('got an error...');
        console.debug('not a server-side handled exception');
        console.debug(error);
        if(ioArgs && ioArgs.xhr && ioArgs.xhr.getResponseHeader('mpExceptionObject'))
        {
            //errObj = ioArgs.xhr.getResponseHeader('mpExceptionObject');
            exceptionExists = true;
            console.log('exceptionExists: ' + exceptionExists);
        }
        else
        {
            //no custom exception thrown (some other kind of error), so handle that error here.
            console.log('no error object');
        }

        //var allHeaders = ioArgs.xhr.getAllResponseHeaders();
        //console.log('all response headers: ' + dojo.toJson(allHeaders,1));
    },
    handle: function(response,ioArgs)
    {
        //called at the end of every request, whether or not an error occurs.
        console.log('in handle()...');
        console.log('exceptionExists: ' + exceptionExists);
        if(exceptionExists)
        {
            var errorObj = response.mpExceptionObject;
            console.log('ExceptionType: %s, Message: %s',errorObj.ExceptionType||'(empty)', errorObj.Message);
            AdvertiserApp.showErrors([errorObj.Message]);
        }
    }
});

}else{//use AdvertiserApp.js method to send request..

appFormValues = { 
    "FirstName": "djv test first name", 
    "LastName": "djv test last name", 
    "ContactPhone": "test contact phone", 
    "ContactEmail": "test.email@wikisori.org", 
    "ContactEmailConfirm": "test.email@wikisori.org", 
    "CompanyName": "djv test company name", 
    "Website": "djvtest.web.site", 
    "Title": "djv test ad title", 
    "Text": "djv test ad text", 
    "Link": "djvtest.ad.link", 
    "NumBlocks": 1,
    "PostalCode": 23464
};

dijit.byId('advertiserApplicationForm').attr('value',appFormValues);
dojo.byId('submitAdvertiserAppForm').click();

}//end code switch.

})();




*/



