// Avoid FOUC 
var elements = document.getElementsByTagName("html");
elements[0].className += " JSEnabled"

$(document).ready(function() {
	
	// Search form select on focus.
	$('#mainSearch input').focus(function(){
	    this.select();
	});
	
	// Business details gallery
	$('.detailGallery ul li a').click(
			function() {
				var currentPic = $(this).attr('href');
				$('.detailGallery p img').attr('src', currentPic);
				return false;
			}
		);
	
	// Business postcode look up 
	$('#postcodeLookup').click(function(event) {
		$('#postcodeLookup').before('<img src="/mediaflux/images/loader16.gif" width="16" height="16" alt="loading" class="loader" />');
		$('#addressResults').empty();
		$.ajax({
			dataType: 'json',
			data: 'postcode='+$("#advertiserPostcode").val()+'&number=none',
			url: $("#postcodeLookup").attr('href'),
			error: function(){
				if ($('.addressError').length == 0) {
						$('#postcodeLookup').parent().after('<li class="addressError" style="display: none">Sorry, we could not find your address, please fill in the fields below.</li>');
						$('.addressError').show('slow');
					}
				$('.loader').remove();
			},
			success: function (data) {
				$('.addressError').remove();
				if (data.length == 1) {
					for (var i in data) {
						$('#advertiserAddress1').val(data[i].line1);
						$('#bizaddress2').val(data[i].line2);
						$('#advertiserTown').val(data[i].town);
						$('#advertiserCounty').val(data[i].county);
					}
				} else {
					var options="";
					if ($('#addressResults').length == 0) {
						$('#postcodeLookup').parent().after('<li class="addressResults" style="display: none"><label>Select your address from the list</label><select size="5" id="addressResults"></select></li>');
					}
					$('#addressResults').empty();
					for (var i in data) {
						options=options + data[i].number + ' ' + data[i].line1 + ' ' + data[i].line2 + ', ' + data[i].town + ', ' + data[i].county;
						$('#addressResults').append('<option value="' + options + '">' + options + '</option>');
						options="";
					}
					$('.addressResults').show('slow');
					
					$('#addressResults').change(function(event) {
						var selected = $('#addressResults option:selected').index();
						$('#advertiserAddress1').val(data[selected].line1);
						$('#bizaddress2').val(data[selected].line2);
						$('#advertiserTown').val(data[selected].town);
						$('#advertiserCounty').val(data[selected].county);
					});
				} 
				$('.loader').remove();
			} 
		});
		return false;
	});

	// Reg step1 validation
	if ($('body.reg1').length > 0) {
		if ($('.validateError').length == 0) $('.regBizForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');
	
		$('.regBizForm').validate({
			ignoreTitle: true,
			errorContainer: ".validateError",
			errorLabelContainer: ".validateError ul",
			wrapper: "li",
			errorClass: "fieldInvalid",
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.removeClass(errorClass);
			},
			
			rules: {
				service_name: {
					required: true,
					minlength: 2
				},
				advertiserTelephoneFixed: {
					required: true,
					minlength : 5,
		            maxlength : 15
				},
				advertiserEmailAddress: {
					required: true,
					email: true
				},
				advertiserPostcode: {
					required: true,
					minlength: 4
				},
				advertiserAddress1: {
					required: true,
					minlength: 4
				},
				advertiserTown: {
					required: true,
					minlength: 2
				},
				advertiserCounty: {
					required: true,
					minlength: 2
				}
			},
			
			messages: {
				service_name: {
					required: "Please specify a <strong>business name</strong>.",
					minlength: jQuery.format("Your <strong>business name</strong> must contain at least {0} characters.")
				},
				advertiserTelephoneFixed: {
					required: "Please specify a <strong>business telephone</strong>.",
					minlength : "Please specify a <strong>UK business telephone</strong>",
		            maxlength : "Please specify a <strong>UK business telephone</strong>"
				},
				advertiserEmailAddress: {
					required: "Please specify a <strong>business email</strong>.",
					email: "You must enter a valid <strong>business email</strong>."
				},
				advertiserPostcode: {
					required: "Please specify a <strong>postcode</strong>.",
					minlength: "You must enter a valid UK <strong>postcode</strong>."
				},
				advertiserAddress1: {
					required: "Please specify a street name in <strong>address line 1</strong>.",
					minlength: "You must enter a valid street name in <strong>address line 1</strong>."
				},
				advertiserTown: {
					required: "Please specify a <strong>town</strong>.",
					minlength: "You must enter a valid <strong>town name</strong>."
				},
				advertiserCounty: {
					required: "Please specify a <strong>county</strong>.",
					minlength: "You must enter a valid <strong>county name</strong>."
				}
			}

		});
	} // End reg step1 val
	
	// Reg step4 validation
	if ($('body.reg4').length > 0) {
		if ($('.validateError').length == 0) $('.regBizForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');
	
		$('.regBizForm').validate({
			ignoreTitle: true,
			errorContainer: ".validateError",
			errorLabelContainer: ".validateError ul",
			wrapper: "li",
			errorClass: "fieldInvalid",
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.removeClass(errorClass);
			},
			
			rules: {
				ownerFirstname: {
					required: true,
					minlength: 2
				},
				ownerLastname: {
					required: true,
					minlength: 2
				},
				ownerPhone: {
					required: function(element) {
						return $("#email").val() == 0;
					},
					minlength : 5,
		            maxlength : 15
				},
				ownerEmail: {
					required: function(element) {
						return $("#tel").val() == 0;
					},
					email: true
				},
				confirmTerms: {
					required: true
				}
			},
			
			messages: {
				ownerFirstname: {
					required: "Please specify your <strong>first name</strong>.",
					minlength: jQuery.format("Your <strong>first name</strong> must contain at least {0} characters.")
				},
				ownerFirstname: {
					required: "Please specify your <strong>last name</strong>.",
					minlength: jQuery.format("Your <strong>last name</strong> must contain at least {0} characters.")
				},
				ownerPhone: {
					required: "Please specify either a <strong>personal telephone</strong> or a <strong>personal email</strong>.",
					minlength : "Please specify a <strong>UK personal telephone</strong>",
		            maxlength : "Please specify a <strong>UK personal telephone</strong>"
				},
				ownerEmail: {
					required: "Please specify either a <strong>personal telephone</strong> or a <strong>personal email</strong>.",
					email: "You must enter a valid <strong>email</strong> address."
				},
				confirmTerms: {
					required: "You must agree to the site <strong>terms &amp; conditions</strong>."
				}
			}

		});
	} // End reg step4 val
	
	// Contact form validation
	if ($('body.contact').length > 0 || $('body.contactBiz').length > 0) {
		if ($('.validateError').length == 0) $('.contactForm').prepend('<div class="validateError" style="display: none;"><h4>Sorry, it appears some details are missing or incorrect.</h4><ul></ul></div>');
	
		$('.contactForm').validate({
			ignoreTitle: true,
			errorContainer: ".validateError",
			errorLabelContainer: ".validateError ul",
			wrapper: "li",
			errorClass: "fieldInvalid",
			highlight: function(element, errorClass) {
				$(element).addClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.addClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
				$(element.form).find("label[for=" + element.id + "]").parent()
						.removeClass(errorClass);
			},
			
			rules: {
				name: {
					required: true,
					minlength: 2
				},
				email: {
					required: function(element) {
						return $("#tel").val() == 0;
					},
					email: true
				},
				tel: {
					required: function(element) {
						return $("#email").val() == 0;
					},
					minlength : 5,
		            maxlength : 15
				},
				query: {
					required: true,
					minlength: 10
				}
			},
			
			messages: {
				name: {
					required: "Please specify your <strong>name</strong>.",
					minlength: jQuery.format("Your <strong>name</strong> must contain at least {0} characters.")
				},
				email: {
					required: "Please specify either a <strong>telephone</strong> or a <strong>email</strong>.",
					email: "You must enter a valid <strong>email</strong> address."
				},
				tel: {
					required: "Please specify either a <strong>telephone</strong> or an <strong>email</strong>.",
					minlength : "Please specify a <strong>UK telephone number</strong>",
		            maxlength : "Please specify a <strong>UK telephone number</strong>"
				},
				query: {
					required: "Please specify your <strong>query</strong>.",
					minlength: jQuery.format("It looks like your <strong>query</strong> should be a little longer than that.")
				}
			}

		});
	} // End contact form val
	
	// Call regBizSelector 
	if ($('.regBizSelector').length > 0) {
		regBizSelector('.regBizSelector');
		regBizSelector('.regBizLocSelector');
	} // End call regBizSelector
	
	function regBizSelector(el) {
		// Set height for sub-cats list
		var bizSelectorHeight = $(el).height();
		$(el + ' ul').css('height',bizSelectorHeight-3);
		
		// Show first group on load
		//$(el + ' li:first').addClass('selectorOn');
		$(el + ' li h3').wrapInner('<a href="#" />')
		
		if (el.indexOf('Loc') < 0) {
			$(el).after('<div class="regBizSelected"><h3>Your chosen categories</h3><ul></ul></div>')
		} else {
			$(el).after('<div class="regBizLocSelected"><h3>Your chosen locations</h3><ul></ul></div>')
		}
		
		// Get list of checked items and append to list of selected cats
		var currentEl = $(el).siblings('div').attr('class');
		
		function getCatChecked(id) {
			//alert(id);
			$('.' + currentEl + ' li').remove();
			$(el + ' input:checked').next().each(function() { 
				$('.' + currentEl + ' ul').append('<li><label for="' + $(this).attr("for") + '">' + $(this).html() + '<a href="#">remove</a></label></li>');
			})
			$('.' + currentEl + ' label[for=' + id + ']').parent().animate({opacity: 0}, 400 ).animate({opacity: 1}, 400 ).animate({opacity: 0}, 400 ).animate({opacity: 1}, 400 );

			return false;
		};
		getCatChecked();
		
		$(el + ' input').change(function() {
			var bizCurrentCat = $(this).attr('id');
			getCatChecked(bizCurrentCat);
			// adjust height according to selected items
			bizSelectedHeight = $(el + ' + div').height();
			if ($(el).height() < bizSelectedHeight) {
			  $(el).css('height',bizSelectedHeight);
			  $(el + ' ul').css('height',bizSelectedHeight-3);
			}
		});
		
		$('.regBizSelected li label a').live('click', function() {
			var bizSelected = $(this).parent().attr("for");
			$('.regBizSelector li input[id=' + bizSelected + ']').removeAttr('checked');
			$(this).parent().parent().fadeOut('fast', function() { $(this).remove() });
			return false;
		});
		$('.regBizLocSelected li label a').live('click', function() {
			var bizSelected = $(this).parent().attr("for");
			$('.regBizLocSelector li input[id=' + bizSelected + ']').removeAttr('checked');
			$(this).parent().parent().fadeOut('fast', function() { $(this).remove() });
			return false;
		});
		

		// Hover style for groups
		$(el + ' li').hover(function() {
			$(this).addClass('selectorHover');
		},
		function() {
			$(this).removeClass('selectorHover');
		});
		
		// Show sub-cats for selected group
		$(el + ' li h3').click(function() {
			$(this).parent().siblings().removeClass('selectorOn');
			$(this).parent().addClass('selectorOn');
			return false;
		});
	
	} //end Reg Business selector function
	
	// Location selector 
	/*if ($('.regBizLocSelector').length > 0) {
		
		$('.regBizLocSelector').after('<div class="regBizLocSelected"><h3>Your chosen locations</h3><ul></ul></div>')
		
		// Get list of checked items and append to list of selected cats
		function getLocChecked(id) {
			//alert(id);
			$('.regBizLocSelected li').remove();
			$('.regBizLocSelector input:checked').next().each(function() { 
				$('.regBizLocSelected ul').append('<li><label for="' + $(this).attr("for") + '">' + $(this).html() + '<a href="#">remove</a></label></li>');
			})
			$('.regBizLocSelected label[for=' + id + ']').parent().animate({opacity: 0}, 400 ).animate({opacity: 1}, 400 ).animate({opacity: 0}, 400 ).animate({opacity: 1}, 400 );

			return false;
		};
		getLocChecked();
		
		$('.regBizLocSelector input').change(function() {
			var bizCurrentLoc = $(this).attr('id');
			getLocChecked(bizCurrentLoc);
		});
		
		$('.regBizLocSelected li label a').live('click', function() {
			var bizLocSelected = $(this).parent().attr("for");
			$('.regBizLocSelector li input[id=' + bizLocSelected + ']').removeAttr('checked');
			$(this).parent().parent().fadeOut('fast', function() { $(this).remove() });
			return false;
		});
	
	}*/ //endif Location selector
	
	
	// Listing type 
	if ($('.regBizType').length > 0) {
		var previewInitialOK;
		var previewEditOK = false;
		// append buttons to li for each choice
		$('.bizBasic').append('<a href="#" class="genericButton blueButton largeButton">Choose BASIC</a>');
		$('.bizEnhanced').append('<a href="#" class="genericButton blueButton largeButton">Choose ENHANCED</a>');
		$('.bizSuper').append('<a href="#" class="genericButton blueButton largeButton">Choose SPONSORED</a>');
		
		$('.detailLogo, .detailGallery, .detailVoucher, .detailDesc, .detailLongDesc, .detailAcc').prepend('<span class="bizEditClick">Click to edit</span>');
		$('.detailBullets').prepend('<li class="bizEditClick">Click to edit</li>');
		
		
		// listing type selection
		function selectListing() {
			$('.regBizType input:checked').parent().addClass('regBizTypeSelected');
			$('.regBizType input:not(:checked)').parent().removeClass('regBizTypeSelected');
			var selected = $('.regBizTypeSelected').index();
			$('form').removeClass().addClass('genericForm clearfix regBizTypeIndex' + selected);
			if (selected == 0) {
				$('.bizDynViewHead,.bizDynView .grid_2, .bizDynView .grid_10').removeClass('enhanced');
				$('.bizDynView').addClass('basic');
			} else {
				$('.bizDynViewHead,.bizDynView .grid_2, .bizDynView .grid_10').addClass('enhanced');
				$('.bizDynView').removeClass('basic');
			}
			if (previewInitialOK != true) { //Add initial preview modal only if it has not been previously dismissed
				var initialHeight = $('.bizDynView').height();
				$('.previewInitial').remove();
				if (selected == 0) {
				    $('.bizDynView').prepend('<div class="previewInitial" style="height:' + initialHeight + 'px;"><div class="clearfix"><h3>This is a preview of your listing</h3><p>To publish more information about your business, <strong>consider the Enhanced listing</strong>.</p><a href="/" class="genericButton blueButton">OK</a></div></div>');
				} else {
				    $('.bizDynView').prepend('<div class="previewInitial" style="height:' + initialHeight + 'px;"><div class="clearfix"><h3>This is a preview of your listing</h3><p>You can <strong>add extra information</strong> about your business here.</p><p>Simply <strong>click on an editable area</strong> to change it.</p><a href="/" class="genericButton blueButton">OK</a></div></div>');
			    }
			}
			// create overlay on hover over editable areas
			var previewHeight = $('.bizDynView .grid_10').height();
			$('.previewOverlay').remove();
			$('.bizDynView .grid_10').prepend('<div class="previewOverlay" style="height:' + previewHeight + 'px;"></div>');
			$('.previewOverlay').css({ opacity:0.4 });
			$('button').show();
		}
		
		// add 'regBizTypeSelected' class to current selection
		$('.regBizType input').change(selectListing);
		$('.regBizType a').click(function() {
			$(this).siblings('input').attr('checked','checked');
			selectListing();
			return false;
		});
		
		// Fade out initial preview modal
		$('.previewInitial a').live('click', function() {
			$('.previewInitial').fadeOut('slow').remove();
			previewInitialOK = true;
			return false;
		});
		
		// override default behaviour of anchors in utilities box
		$('.bizDynView .detailUtils a').click(function() {
			return false;
		});
		
				
		// Edit details preview on hover
		function editPreviewIn(liItem,prevItem) {
			if (previewInitialOK == true && previewEditOK != true) {
				$('.' + liItem).toggleClass('bizDynOn');		
				$('.previewOverlay').stop(false,true).fadeIn(1000);
				$('.' + prevItem).toggleClass('previewEdit');
			}
		}
		
		function editPreviewOut(liItem,prevItem) {
			if (previewInitialOK == true && previewEditOK != true) {
				$('.' + liItem).toggleClass('bizDynOn');
				$('.bizDynView .grid_10 .previewOverlay').stop(false,true).css({ display:'none' });
				$('.' + prevItem).toggleClass('previewEdit');
			}
		}
		
	
		// Hover and click handlers
		$('.bizDynView .bizDynShortDesc, .bizDynView .detailDesc').hover(
			function() {
				editPreviewIn('bizDynShortDesc','detailDesc');
				
					$(this).click(function() {
						edit('bizDynShortDesc','detailDesc','bizshortdesc',editShortDesc);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynShortDesc','detailDesc');
		});
		$('.bizDynView .bizDynBullet, .bizDynView .detailBullets').hover(
			function() {
				editPreviewIn('bizDynBullet','detailBullets');
				
					$(this).click(function() {
						edit('bizDynBullet','detailBullets','bizbullets',editBullets);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynBullet','detailBullets');
		});
		$('.bizDynView .bizDynLongDesc, .bizDynView .detailLongDesc').hover(
			function() {
				editPreviewIn('bizDynLongDesc','detailLongDesc');
				
					$(this).click(function() {
						edit('bizDynLongDesc','detailLongDesc','bizlongdesc',editLongDesc);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynLongDesc','detailLongDesc');
		});
		$('.bizDynView .bizDynLogo, .bizDynView .detailLogo').hover(
			function() {
				editPreviewIn('bizDynLogo','detailLogo');
				
					$(this).click(function() {
						edit('bizDynLogo','detailLogo','bizlogo',editLogo);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynLogo','detailLogo');
		});
		$('.bizDynView .bizDynVoucher, .bizDynView .detailVoucher').hover(
			function() {
				editPreviewIn('bizDynVoucher','detailVoucher');
				
					$(this).click(function() {
						edit('bizDynVoucher','detailVoucher','bizvoucher',editVoucher);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynVoucher','detailVoucher');
		});
		$('.bizDynView .bizDynAccreds, .bizDynView .detailAcc').hover(
			function() {
				editPreviewIn('bizDynAccreds','detailAcc');
				
					$(this).click(function() {
						edit('bizDynAccreds','detailAcc','bizaccreds',editAccreds);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynAccreds','detailAcc');
		});
		$('.bizDynView .bizDynPhotos, .bizDynView .detailGallery').hover(
			function() {
				editPreviewIn('bizDynPhotos','detailGallery');
				
					$(this).click(function() {
						edit('bizDynPhotos','detailGallery','bizpics',editPhotos);
						return false;
					});
				
			},
			function() {
				editPreviewOut('bizDynPhotos','detailGallery');
		});
		
			
		// Edit details
		$('.regBizVoucher .genericRadio').hide(); // Hide 'add voucher' checkbox 
		var editShortDesc = $('#bizshortdesc').parent().children();
		var editBullets = $('.regBizDesc li:gt(0)');
		var editLongDesc = $('.regBizDescLong li').children();
		var editVoucher = $('.regBizVoucher li');
		var editAccreds = $('.regBizAccreds li');
		var editLogo = $('#bizlogo').parent().children();
		var editPhotos = $('.regBizImages li:gt(0)');
		var fieldValues = {};
		
		function edit(listItem,previewItem,divClass,formField) {
			if (previewEditOK != true) {
				$('.' + previewItem).mouseout();
				$('.previewOverlay').addClass('bizEditOn').css({ opacity:0.4 });
				previewEditOK = true; // Prevents hover or click event being triggered on left hand side list while in edit mode
				var currentObj = $('.' + previewItem);
				var editX = $('.' + previewItem).offset().left;
				var editY = $('.' + previewItem).offset().top;	
				if ($('.' + divClass).length > 0) {
					$('.' + divClass).css({ 'top' : editY+'px', 'left' : editX+'px' });
					$('.' + divClass).show();
				} else {
					if (previewItem == 'detailDesc' || previewItem == 'detailLongDesc' || previewItem == 'detailLogo') {
						$('.bizDynView').prepend('<div class="bizEditForm ' + divClass + '" style="top:'+editY+'px;left:'+editX+'px;"><a href="#" class="genericButton blueButton" id="saveBtn">Save &amp; close</a></div>');
					} else if (previewItem == 'detailAcc') {
						$('.bizDynView').prepend('<ul class="bizEditForm ' + divClass + '" style="top:'+editY+'px;left:'+editX+'px;"><li><a href="#" class="genericButton blueButton" id="saveBtn">Save &amp; close</a></li></ul>');
					} else {
						$('.bizDynView').prepend('<ul class="bizEditForm ' + divClass + '" style="top:'+editY+'px;left:'+editX+'px;"><li><a href="#" class="genericButton blueButton" id="saveBtn">Save &amp; close</a></li></ul>');
					}
					$(formField).prependTo('.' + divClass);
				}
				if (previewItem == 'detailAcc') {
					var editH = $('.' + divClass).height();	
					$('.' + divClass).css({'margin-top' : '-'+editH+'px'});
				}
				/* if (previewItem == 'detailGallery' || previewItem == 'detailLogo') {
					Impossible to manipulate input type=file elements so useless!
					jQuery.each($('.' + divClass + ' :input'), function(i, object){
							var name = $(object).attr('name');
							var value = $(object).val();
							var o = {'name': name, 'value': value};
							fieldValues = new Array();
							fieldValues.push(o);
					});
					
				} */
				fieldValues = $('.' + divClass + ' :input[type!=checkbox]').serializeArray();	
			}
			
		}
		
		// Close modal 
		function closeEdit(obj) {
			//alert($(obj).html());
			$(obj).parents('.bizEditForm').hide(); 
			$('.previewOverlay').removeClass('bizEditOn');
			previewEditOK = false;
		}
		// Close modal without saving
		$('.closeButton').live('click', function() {
			//alert(fieldValues[0].name);
			jQuery.each(fieldValues, function(i, field){
					$(this).parents('.bizEditForm :input[type!=checkbox]:eq(' + i + ')').val(field.value); 
			});
			fieldValues = {};
			closeEdit(this);
			return false;
		});


		// trim input values
		function trimVal() {
			var len = $(':input[type!="file"]').length;
			for(var i=0;i<len;i++){
			 var input = $.trim( $(':input[type!="file"]:eq(' + i + ')').val() );
			 $(':input[type!="file"]:eq(' + i + ')').val(input);
			}
		}
		
		// Save and close modal, update preview content
		var shortDescDefault = $('.detailDesc').html();
		$('.bizshortdesc .genericButton').live('click', function() {
			trimVal();
			var shortDescVal = $('#bizshortdesc').val();
			if (shortDescVal == '') {
				closeEdit(this);
				$('.detailDesc').removeClass('detailEdited').html(shortDescDefault);
			} else {
				closeEdit(this);
				$('.detailDesc').addClass('detailEdited').html('<span class="bizEditClick">Click to edit</span>' + shortDescVal);
			}
			return false;
		});
		
		var bulletsDefault = $('.detailBullets').html();
		$('.bizbullets .genericButton').live('click', function() {
			trimVal();
			var bulletValues = $('.bizbullets :input').serializeArray();
			
			if ($('.bizbullets :input[value!=""]').length == 0) {
				closeEdit(this);
				$('.detailBullets').removeClass('detailEdited').html(bulletsDefault);
			} else {
				closeEdit(this);
				$('.detailBullets li:gt(0)').remove();
				$('.detailBullets').addClass('detailEdited');
				jQuery.each(bulletValues, function(i, field){
					if (field.value.length > 0) {
						$('.detailBullets').append('<li>' + field.value + '</li>');
					}
				});
			}
			return false;
		});
		
		var longDescDefault = $('.detailLongDesc').html();
		$('.bizlongdesc .genericButton').live('click', function() {
			trimVal();
			var longDescVal = $('#bizlongdesc').val();
			longDescVal = longDescVal.replace(new RegExp( "\\n", "g" ),"<br />");
			if (longDescVal == '') {
				closeEdit(this);
				$('.detailLongDesc').removeClass('detailEdited').html(longDescDefault);
			} else {
				closeEdit(this);
				$('.detailLongDesc').addClass('detailEdited').html('<span class="bizEditClick">Click to edit</span>' + longDescVal);
			}
			return false;
		});
		
		var voucherDefault = $('.detailVoucher').html();
		$('.bizvoucher .genericButton').live('click', function() {
			trimVal();
			var voucherVal = $('#bizvouchersummary').val();
			if (voucherVal == '') {
				closeEdit(this);
				$('.detailVoucher').removeClass('detailEdited').html(voucherDefault);
				$('.bizvoucher .genericRadio input').removeAttr('checked'); // update 'add voucher' checkbox 
			} else {
				closeEdit(this);
				$('.detailVoucher').addClass('detailEdited').html('<span class="bizEditClick">Click to edit</span><a href="/"><img alt="Voucher offer available" src="/mediaflux/images/business_directory/c2f_voucher.png"><span>' + voucherVal + '</span></a>');
				$('.bizvoucher .genericRadio input').attr('checked','checked'); // update 'add voucher' checkbox 
			}
			return false;
		});
		
		var accredDefault = $('.detailAcc').html();
		$('.bizaccreds .genericButton').live('click', function() {
			//trimVal();
			//var accredValues = $('.bizaccreds :input').serializeArray();
			var accredValues = new Array();
			jQuery.each($('.bizaccreds :input:checked'), function(i, value){
				accredValues.push($(this).next('label').text());
			});
			if ($('.bizaccreds :input:checked').length == 0) {
				closeEdit(this);
				$('.detailAcc').removeClass('detailEdited').html(accredDefault);
			} else {
				closeEdit(this);
				$(".detailAcc").html('<span class="bizEditClick">Click to edit</span>Accreditations: ' + accredValues);
				$(".detailAcc").addClass('detailEdited');
				
				
				/*jQuery.each(accredValues, function(i, field){
					if (field.value.length > 0) {
						$('.detailAcc').append(field.value + ', ');
					}
				});*/
				//$('.detailAcc').append(accredValues);
				//$('.detailAcc').html($('.detailAcc').html().substring(0,$('.detailAcc').html().lastIndexOf(",")));
			}
			return false;
		});
		
		// Image upload extension checker
		var extensionOk = false;
		function checkExtension(imgField) {
			var extension = new Array(".png",".gif",".jpg",".jpeg");
			var fieldvalue = $(imgField).val();
			var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
			for(var i = 0; i < extension.length; i++) {
				if(thisext == extension[i]) {  
					extensionOk = true;
				}
			}
		}

		var logoDefault = $('.detailLogo').html();
		$('.bizlogo .genericButton').live('click', function() {
			var logoVal = $('#bizlogo').val();
			if (logoVal == '') {
				$('.bizlogo .inlineError').remove();
				closeEdit(this);
				$('.detailLogo').html(logoDefault);
			} else {
				closeEdit(this); // TEMP solution until validation is made possible
				$('.detailLogo').html('<span class="bizEditClick">Click to edit</span><a href="/"><img alt="" src="/mediaflux/images/business_directory/placeholder_logo_ok.png"></a>');  // TEMP solution until validation is made possible
				/* INITIAL VALIDATION relying on input value's file extension - WILL NOT WORK IF USER HAS 'HIDE FILE EXTENSIONS' ENABLED IN WIN EXPLORER
				checkExtension('#bizlogo');
				if (extensionOk == true) {
					$('.bizlogo .inlineError').remove();
					closeEdit(this);
					$('.detailLogo').html('<span class="bizEditClick">Click to edit</span><a href="/"><img alt="" src="images/business_directory/placeholder_logo_ok.png"></a>');
				*/	
									/* // Ajax upload solution - requires server-side set up & test
									var thumb = $('.detailLogo img');	
								
									new AjaxUpload('saveBtn', {
										action: 'urlGoesHere',
										name: 'logo',
										onSubmit: function(file, extension) {
											$('.detailLogo').addClass('loading');
										},
										onComplete: function(file, response) {
											thumb.load(function(){
												$('.detailLogo').removeClass('loading');
												thumb.unbind();
											});
											thumb.attr('src', response);
										}
									}); 
									*/ // END Ajax upload solution
				/*
				} else if (extensionOk == false) {
					if ($('.bizlogo .inlineError').length == 0) {
							$('.bizlogo').prepend('<span class="inlineError">Sorry, the file you chose is not a gif, jpg, or png image.</span>');
						}
						$('#bizlogo').attr('value', '');
						return false;
				}
				extensionOk = false;
				*/
			}
			return false;
		});
		
		var photosDefault = $('.detailGallery').html();
		$('.bizpics .genericButton').live('click', function() {
			var photosValues = new Array();
			jQuery.each($('.bizpics :input'), function(i, value){
				if ($(this).val() != '') {
					photosValues.push($(this).val());
				}
			});
			// 	alert(photosValues);
			if (photosValues.length == 0) {
				closeEdit(this);
				$('.detailGallery').html(photosDefault);
			} else {
				var u = 0;
				var y = 0;
				jQuery.each(photosValues, function(i, value){
					$('.detailGallery p img').attr('src','/mediaflux/images/business_directory/placeholder_photo_ok.png'); // TEMP solution until validation is made possible
					$('.detailGallery li:eq(' + u + ') img').attr('src','/mediaflux/images/business_directory/placeholder_thumb_ok.png'); // TEMP solution until validation is made possible
					u = u+1;
					/* INITIAL VALIDATION relying on input value's file extension
					checkExtension($('.bizpics :input[value=' + value + ']'));
					if (extensionOk == true) {
						$('.detailGallery p img').attr('src','images/business_directory/placeholder_photo_ok.png');
						$('.detailGallery li:eq(' + u + ') img').attr('src','images/business_directory/placeholder_thumb_ok.png');
						u = u+1;
					} else if (extensionOk == false) {
						if ($('.bizpics .inlineError').length == 0) {
							$('.bizpics li:eq(0)').prepend('<span class="inlineError">Sorry, one or more of the files you chose were not gif, jpg, or png images.</span>');
						}
						$('.bizpics :input[value=' + value + ']').attr('value', '');
						y = y+1;
					} 
					extensionOk = false;
					*/
				});
				if (y == 0) {
					$('.bizpics .inlineError').remove();
					closeEdit(this);
				}
			}
			return false;
		});
	} //endif Listing type selector
	
	
});


function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
      createCookie(name,"",-1);
}

cookieName='jlist';
cookieLifetime=60;
itemSeparator='|';
valueSeparator='^';
shortlistArr = [];
shortlistStr = null;
shortlistItemsToShow = 5;

searchcookieName='jsearch';

function toArr(str){
    arr = []
    if(str == null ) { return arr }
    arr = str.split(itemSeparator);
    return arr;
  
}

function toStr(arr){
    str = arr.join(itemSeparator)
  	return str
}

function redrawShortlist() {

    //read shortlist data from cookie
    shortlistStr = readCookie(cookieName); 
    //alert(shortlistStr)
    shortlistArr= toArr(shortlistStr)
    if(shortlistArr.length == 0) {
    //alert('Empty Shortlist')
            // remove/hide div if no data
        $("#recentlyViewedAdverts").empty()
    } else {
				shortlistArr = shortlistArr.reverse(); // show most recent first
        //for(i=0;i<shortlistArr.length;i++) {
        for(i=0;i<shortlistItemsToShow;i++) {
            $("#recentlyViewedAdvertsList").append(shortlistArr[i])
        }
        $("#recentlyViewedAdverts").show()
    }
} 

function addToShortlist(fragment) {
    // add data to cookie
    shortlistStr = readCookie(cookieName);
    shortlistArr = toArr(shortlistStr);
    // avoid duplicates
    isNew = true
	    for(i=0;i<shortlistArr.length;i++) {
		    if (shortlistArr[i] == fragment) {
			    isNew = false
		    }
	    }
    if(isNew) {
        shortlistArr[shortlistArr.length] = fragment;
        shortlistStr = toStr(shortlistArr)
        eraseCookie(cookieName)
        createCookie(cookieName,shortlistStr,cookieLifetime)
    }
}

function redrawSearchList() {

    searchlistStr = readCookie(searchcookieName); 
    searchlistArr= toArr(searchlistStr)
		//alert(searchlistArr.length)
    if(searchlistArr.length == 0) {
        $("#recentSearches").empty()
    } else {
				searchlistArr = searchlistArr.reverse(); // show most recent first
        //for(i=0;i<searchlistArr.length;i++) {
        for(i=0;i<shortlistItemsToShow;i++) {
            $("#recentSearchesList").append(searchlistArr[i])
        }
        $("#recentSearches").show()
    }
} 

function addToSearchList(fragment) {
    // add data to cookie
    searchlistStr = readCookie(searchcookieName);
    searchlistArr = toArr(searchlistStr);
    // avoid duplicates
    isNew = true
		for(i=0;i<searchlistArr.length;i++) {
						if (searchlistArr[i].toLowerCase() == fragment.toLowerCase()) {
										isNew = false
						}
		}
    if(isNew) {
        searchlistArr[searchlistArr.length] = fragment;
        searchlistStr = toStr(searchlistArr)
        eraseCookie(searchcookieName)
        createCookie(searchcookieName,searchlistStr,cookieLifetime)
    }
}

