/**
 * @author PeteAllison
 * @copyright Redpin Publishing Ltd 2009
 * @description Handles the new horse/classified adverts
 */
// <![CDATA[

window.addEvent('domready', function() {
	// Add in word counter
	if( $('advert_text') ) {
		// Create counter element
		var width = $('advert_text').getSize().x;
		new Element('span',{
			'id':'advert_text_counter',
			'styles': {
				'width': 82,
				'vertical-align': 'top',
				'padding-left': 4,
				'padding-top': '1.25em',
				'float': 'left'
			}
		} ).inject($('advert_text'),'after');
		$('advert_text').setStyles( {
			'width': width - 100,
			'float': 'left'
		} );
		$('advert_text').addEvent('keyup', function() {
			$('advert_text_counter').set('text', 'You have typed ' + getWordCount(this) + ' words');
		} );
		$('advert_text').fireEvent('keyup');
	}


	/*
	 * If the horse form actually exists then process popups and costings
	 */
	if ($('horseForm')) {
		/*
		 * Enable the popup help box
		 */
		$('popupHelp').setStyle('display', 'block');

		/**
		 * Define the log for information popups
		 */
		var log = new Roar({
			'container': $('log'),
			'position': 'bottomRight',
			'duration': 5000
		});
		/**
		 * Holds the actual running cost of the advert
		 */
		var runningCost = 0;
		/**
		 * Holds the cost currently shown on screen
		 */
		var displayedCost = 0;
		/**
		 * Define the cost popup that displays the cost of the advert
		 */
		var cost = new Roar({
			'container': $('eventCost'),
			'position': 'topRight',
			'duration': false
		});

		/**
		 * Handle advert submission
		 */
		$('horseForm').addEvent('submit', function(e) {
			if (!checkForm()) {
				var e = new Event(e).stop();
			}
		});

		/**
		 * Toggle the horse for sale / loan
		 */
		if ($('advert_loan')) {
			$('advert_loan').addEvent('click', function() {
				if ($('advert_loan').getElement('input[type=radio]:checked').get('value') == 'sell') {
					$('advert_money').getParent('div').setStyle('display','block');
					$('advert_money').getParent('div').addClass('required');
				} else {
					$('advert_money').getParent('div').setStyle('display','none');
					$('advert_money').getParent('div').removeClass('required');
				}
			});
		}

		/*
		 * Loop through every selectable element and make
		 */
		$('horseForm').getElements('input, select,span.information, textarea').each(function(element) {
			var details;
			/*
			 * If the element has a details block then make it so that it displays
			 * popup help and calculates costs
			 */
			if ((details = element.getParent('div').getElement('span.details'))) {
				details = JSON.decode(details.get('text'));
				if (element.nodeName == 'SPAN') {
					/*
					 * Information (i) bubble
					 */
					element.addEvents({
						'mouseover': function() {
							showPopup(this);
						},
						'mouseout': function() {
							hidePopup();
						}
					});
				} else {
					/*
					 * Regular inputable element
					 */
					element.addEvents({
						'focus' : function() { 
							showPopup(this); 
						},
						'blur'  : function() { 
							hidePopup(this); 
						},
						'change': function() { 
							recalculateCost(); 
						},
						'click': function() {
							recalculateCost();
						}
					});
				}
			}
		});

		/**
		 * Shows the popup with the help details within it at the necessary
		 * location
		 */
		function showPopup(element){
			var me = element.getCoordinates();
			var details = JSON.decode(element.getParent('div').getElement('span.details').get('text'))
			if (details.cost) {
				details.help += '<br/><br/>This will cost <strong>&pound;' + details.cost + '</strong>' + (details.textarea ? ' for every 25 words': '');
			}
			if (element.nodeName == 'TEXTAREA') {
				me = {
					'top': me.top,
					'left': me.left + 327
				}
			}
			if (element.nodeName == 'SPAN') {
				me = {
					'top': me.top,
					'left': me.left + 20
				}
			}
			$('popupHelp').setStyles({
				'top': me.top - 3,
				'left': me.left + 310
			}).set('html', details.help).fade('in');
		}

		/**
		 * Hides the currently displayed popup
		 */
		function hidePopup(){
			$('popupHelp').fade('out');
		}

		/**
		 * Calculates the cost for this advert
		 */
		function calcCost(){
			if (runningCost != displayedCost) {
				cost.empty();
				displayedCost = runningCost;
				var amountPaid = '';
				if ($('paid')) {
					amountPaid = '<br/>You have already paid ' + $('paid').get('value').toInt() + ' for this advert';
				}
				if (runningCost > 0)
					cost.alert('Total cost', 'The cost for this event advertisement is &pound;' + runningCost + amountPaid);
			}
		}

		/**
		 * Recalculates the cost for this advert
		 */
		function recalculateCost() {
			runningCost = 0;
			displayedCost = -1;

			$('horseForm').getElements('input, select,span.information, textarea').each(function(element) {
				var details;

				if ((details = element.getParent('div').getElement('span.details'))) {
					details = JSON.decode(details.get('text'));

					if (details.cost) {
						if (element.nodeName == 'INPUT' || this.nodeName == 'TEXTAREA') {
							if (element.get('type') == 'checkbox' || element.get('type') == 'radio') {
								if (element.get('checked') == true) {
									runningCost += details.cost;
								}
							} else {
								if (element.get('value') != '') {
									runningCost += details.cost;
								}
							}
						} else if (element.nodeName == 'SELECT') {
							if (element.selectedIndex != 0) {
								runningCost += details.cost;
							}
						} else if (element.nodeName == 'TEXTAREA') {
							var words = getWordCount(element);
							runningCost += details.cost * Math.floor(words/25);
						}
					}
				}
			});
			/**
			 * Work out photo costs
			 */
			if ($('photos')) {
				var photoCount = 0;
				var photoCost = JSON.decode($('photos').getElement('span.details').get('text'));
				$('photos').getElements('div').each(function(photo) {
					if (photo.getElement('img'))
						photoCount++;
				});
				if (photoCount > 1)
					runningCost += ((photoCount - 1) * photoCost.cost);
			}
			calcCost();
		}

		/**
	* Scans through the photo's and enables any delete buttons
	*/
		function enablePhotoTools() {
			if ($('photos')) {
				$('photos').getElements('div.photoContainer').each(function(element) {
					var toolsBar = element.getElement('div.tools');
					var photoID = element.get('id').substr(5,1);
					if ( toolsBar && !toolsBar.retrieve('photoID'))  {
						toolsBar.getElement('span.delete').addEvent('click', function() {
							new Request.JSON({
								'url':$('horseForm').get('action'),
								'onSuccess': function(result) {
									if (result && result.success) {
										// Remove the image from the box and re-enable the uploader
										var details = JSON.decode($('photos').getElement('span.details').get('text'))
										element.set('html','<a class="uploadable">Upload Photo' + (photoID != '1' ? ' &pound;' + details.cost : '') + '</a>');
										enablePhotoUploader();
									} else {
										if (result.errorText)
											log.alert('Error',result.errorText);
										else
											log.alert('Error','There was a problem removing this photo');
									}
								}
							}).post({
								'photo':photoID
							})
						}).store('photoID',photoID).setStyle('cursor','pointer')
					}
				});
			}
		}

		function enablePhotoUploader() {
			if ($('photos')) {
				$('photos').getElements('a').each(function(link) {
					if (link.hasClass('uploadable') && !link.retrieve('processed')) {
						/*
					 * Bind an upload to this tag
					 */
						var linkIdle = link.get('html');
						var photoID = link.getParent('div').get('id');
						function linkUpdate() {
							if (!swf.uploading)
								return;
							var size = Swiff.Uploader.formatUnit(swf.size, 'b');
							link.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
						}

						var swf = new Swiff.Uploader({
							path: '/js/fancyupload/source/Swiff.Uploader.swf',
							url: $('photos').getParent('form').get('action'),
							verbose: true,
							queued: false,
							target: link,
							instantStart: true,
							typeFilter: {
								'Photos (*.jpg)':'*.jpg;'
							},
							data: {
								'advert': $('advertCode').value,
								'photo': photoID
							},
							fileSizeMax: 4 * 1024 * 1024,
							onSelectSuccess: function(files) {
								if (Browser.Platform.linux)
									window.alert('Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
								log.alert('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
								this.setEnabled(false);
							},
							onSelectFail: function(files){
								log.alert('<em>' + files[0].name + '</em> was not added!', 'Please select an image smaller than 2 Mb. (Error: #' + files[0].validationError + ')');
							},
							appendCookieData: true,
							onQueue: linkUpdate,
							onFileComplete: function(file){
								var response = JSON.decode(file.response.text, true);
								if (file.response.error) {
									log.alert('Failed Upload', 'Uploading <em>' + this.fileList[0].name + '</em> failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
								} else {
									var md5 = JSON.decode(file.response.text, true).hash;
									log.alert('Successful Upload', 'Your photo has been successfully uploaded')
								}
								file.remove();
								if (response.img) {
									var linkParent = link.getParent('div')
									link.dispose();
									swf.reposition();
									linkParent.set('html', '<div class="tools"><span class="delete">&nbsp;</span></div><img src="' + response.img + '" alt="Photo" />');
									enablePhotoTools();
									this.setEnabled(false);
								}
								recalculateCost();
							},
							onComplete: function(result){
							//link.set('html', linkIdle);
							}
						});
					}
					link.store('processed',true);
				});
			}
		}
		
		/**
		 * Now make each photo button uploadable
		 */
		enablePhotoUploader();
		/*
	     * Ensure that we have a cost box in the corner
	     */
		recalculateCost();
		enablePhotoTools();
	} // endif ($('horse_form'))



} );

/**
 * Very primative method of checking all form fields have been completed
 */
function checkForm() {
	if( $('horseForm').getElements('div.error p') ) $('horseForm').getElements('div.error p').destroy();
	$('horseForm').getElements('div.error').removeClass('error');
	
	$('horseForm').getElements('div.required').each( function(item) {
		var errorP = new Element('p',{
			'html':'<span class="errorText">Required</span>'
		});
		var hasError = false;		
		if( item.getElement('select') ) {
			// Select box
			if( item.getElement('select').selectedIndex == 0 ) hasError = true;
		} else if( item.getElement('textarea') ) {
			if( item.getElement('textarea').get('value') == '' ) hasError = true;
		} else if( item.getElement('input') ) {
			if( item.getElement('fieldset') ) {
				// Generally a group of checkboxes or radio buttons
				if( item.getElements('input:checked').length == 0 ) hasError = true;
			} else {
				if( item.getElement('input').get('value') == '' ) hasError = true;
				if( item.getElement('input').get('id') == 'advertiser_email' ) {
					if( !emailValid(item.getElement('input').get('value')) ) {
						hasError = true;
						errorP.getElement('span').set('text','Appears Invalid');
					}
				}
				if( !$('advert_loan') || ($('advert_loan') && $('advert_loan').getElement('input[type=radio]:checked').get('value') == 'sell') ) {
					if( item.getElement('input').get('id') == 'advert_money' ) {
						if (isNaN(item.getElement('input').get('value')) ) {
							hasError = true;
							errorP.getElement('span').set('text','Not a numeric value');
						} else if(item.getElement('input').get('value') <= 0) {
							hasError = true;
							errorP.getElement('span').set('text','Cannot be zero');
						}
					}
				}
			}
		}
		if( hasError ) {
			item.addClass('error');
			errorP.inject(item, 'top');
		} else {
			errorP.destroy();
		}
	} );
	if ($('video_url')) {
		if ($('video_url').get('value') != '') {
			var errorP = new Element('p',{
				'html':'<span class="errorText">Required</span>'
			});
			var hasError = false;
			if (!youtubeURLValid($('video_url').get('value'))) {
				hasError = true;
				errorP.getElement('span').set('text','URL appears invalid')
			}
			if( hasError ) {
				$('video_url').getParent('div').addClass('error');
				errorP.inject($('video_url').getParent('div'), 'top');
			} else {
				errorP.destroy();
			}
		}
	}

	if( $('horseForm').getElements('div.error').length > 0 ) {
		if( $('horseForm').getElement('div.error input[type=text]') ) $('horseForm').getElement('div.error input[type=text]').focus();
		info ('errors on fields:', $('horseForm').getElements('div.error'))
		return false;
	}
	return true;
}


/**
 * Regular expression checker to see if email complies to standard rules
 */
function emailValid(email) {
	return email.test(/^[a-z0-9._\+%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i);
}

/**
 * Regular expression checker to see if the URL complies to a youtube video
 */
function youtubeURLValid(url) {
	/*
	 * Check for http://www.youtube.com/watch?v=XXXXX
	 * and http://www.youtube.com/v/XXXXX
	 */
	var test = url.test(/http:\/\/www\.youtube\.com\/watch\?v\=([a-z0-9]{4,})/i);
	if (!test)
		test = url.test(/http:\/\/www\.youtube\.com\/v\/([a-z0-9]{4,})/i);

	return test;
}


/**
 * Performs a word count on the the passed item
 */
function getWordCount(item) {
	if( $type(item) == 'object' ) item = item.get('text');
	if( $type(item) == 'element' ) item = item.get('value');

	var r = 0;

	// Strip out HTML
	item = item.replace(/(<([^>]+)>)/ig,"")

	// Replace all multiple spaces with a single space
	a = item.replace(/\s/g, ' ');
	a = a.split(' ');
	for( z=0; z<a.length; z++ ) {
		if( a[z].length > 0 ) r++;
	}

	return r;
}

function info() {
	if (window.console && console.info) console.info.apply(console, arguments); 
}

// ]]>
