function createPostComment(){
	var error_form = 0;
	var msg = ''; 	
	//var pat = new RegExp("/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/i");	
	comment_email = $('#comment_email').val();
	if(!$('#comment_name').val()){
		error_form = 1;
		msg  += '<li>Please enter your full name</li>';
	}if(!$('#comment_email').val()){
		error_form = 1;
		msg  += '<li>Please enter your E-mail</li>';
	}else if(!checkEmail(comment_email)){
		error_form = 1;
		msg  += '<li>Please enter a valid E-mail</li>';
	}if(!$('#message').val()){
		error_form = 1;
		msg  += '<li>Please enter your message</li>';
	}if(error_form==1){
		$('#flash-error').css("display", "block");
		$('#flash-error').html('<ul class="no-marker">'+ msg +'</ul>');		
		return false;
	}else if(error_form==0){ 	
		$('#flash-error').css("display", "none");		
		//$('#flash-error').fadeOut(50000);			
		$.ajax({
			url: APP_ROOT + '/ajax/add_post_comment',
			data: "id="+$("#post_id").val()+"&name="+$("#comment_name").val()+"&email="+$("#comment_email").val()+"&website="+$("#website").val()+"&message="+$("#message").val(),
			type: 'post',
			cache: false,
			dataType: 'html',
			complete: function (xhr) {
				if (xhr.responseText != "false") {		
					document.blogcomment.reset();
					$('#flash-error').html('Your comment has been submitted for approval. Once it is approved, it will be published on this page.');	
					$('#flash-error').removeClass('flash-error').addClass('flash').show();
					setTimeout(function() { $('#flash-error').fadeOut(2000) },10000);
				} else {
					$('#flash-error').html('There was an error while processing your submission. Please try again');	
					$('#flash-error').removeClass('flash').addClass('flash-error').show();
					setTimeout(function() { $('#flash-error').fadeOut(2000) },10000);
				}				
			}
			//error: RBGUtilities.Modal.error
		});
		return false;
	}
}
function checkEmail(emailvalue) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailvalue)){
		return (true);
	}
	return (false)
}
function deletefavsearch(id){
	var wannaDelete= confirm("Do you really want to delete this search??");
	if(wannaDelete == true){
		$.ajax({
			url: APP_ROOT + '/ajax/delete_favsearch',
			data: "id="+id,
			type: 'post',
			cache: false,
			dataType: 'html',
			complete: function (xhr) {
				if (xhr.responseText != "false") {
					// Address was successfully added - close the modal window
					window.location.reload( true );
				} else {
					alert("There was an error while processing your submission. Please try again");
				}				
			}
			//error: RBGUtilities.Modal.error
		});
	}else{
		return true;
	}
}
/* Utilities javascript */
RBGUtilities = {
	checkTradesSelected: function() {
		var field = $('[@name=supplier_id]');
		if (field.attr("type") == "hidden") {
			return true;
		} else {
			var selected = ($('[@name=supplier_id]:checked').length > 0);
			if (!selected) {
				alert("Please select at least 1 business.")
			}
		}
		return selected;
	},
	showSendToFriendForm: function(e) {
		e.preventDefault();
		
		if (RBGUtilities.checkTradesSelected()) {
			// create a modal dialog with the data
			$("#modalSendToFriend").modal({
				close: false,
				overlayId: 'modal-overlay',
				containerId: 'modal-container',
				onOpen: RBGUtilities.Modal.open,
				onShow: RBGUtilities.Modal.showSendToFriend,
				onClose: RBGUtilities.Modal.close,
				overlay: 65
			});
		}
	},
	showSendEnquiryForm: function(e) {
		e.preventDefault();
		
		if (RBGUtilities.checkTradesSelected()) {
			// create a modal dialog with the data
			$("#modalSendEnquiry").modal({
				close: false,
				overlayId: 'modal-overlay',
				containerId: 'modal-container',
				onOpen: RBGUtilities.Modal.open,
				onShow: RBGUtilities.Modal.showSendEnquiry,
				onClose: RBGUtilities.Modal.close,
				overlay: 65
			});
		}
	},
	showSaveSearchForm: function(e) {
		e.preventDefault();
		
		if (RBGUtilities.checkTradesSelected()) {
			// create a modal dialog with the data
			$("#modalSaveSearch").modal({
				close: false,
				overlayId: 'modal-overlay',
				containerId: 'modal-container',
				onOpen: RBGUtilities.Modal.open,
				onShow: RBGUtilities.Modal.showSaveSearch,
				onClose: RBGUtilities.Modal.close,
				overlay: 65
			});
		}
	},

	/* Remove from Favourites */
	removeFromFavourites: function(e) {
		e.preventDefault();
		
		if (RBGUtilities.checkTradesSelected()) {
			if (confirm('Are you sure you would like to remove the selected businesses from your favourites?')) {
				var form = $("form[@name=frm_searchlist]"); 
				var sids = [];
				$('[@name=supplier_id]:checked').each(function(i){
					sids[i] = $(this).val();
				});
				
				$.ajax({
					url: APP_ROOT + '/ajax/remove_from_favourites',
					data: 'sid=' + $("[@name=sid]").val() + '&selected_ids=' + sids.join("|"),
					type: 'post',
					cache: false,
					dataType: 'html',
					complete: function (xhr) {
						if (xhr.responseText != "false") {
							// Businesses removed successfully - show alert
							var len = sids.length;
							for (var i=0; i<len; i++) {
								$("input[@value=" + sids[i] + "]").parent().each(function() {
									$(this).fadeOut(400, function() {
										$(this).remove();
									});
								});
							}
							
							var numRemaining = $("div.searchresults > div.result").length - len;
							if (numRemaining == 0) {
								$("div.actions, div.pager, a.print").hide();
								$("div.searchresults").after('<div class="results">There are no businesses in this favourite list.</div>');								
							}
						} else {
							alert("There was an error while processing your submission. Please try again");
						}
					},
					error: RBGUtilities.Modal.error
				});	
			}
		}
	},
	
	/* Modal */
	Modal: {
		/* Send to a Friend */
		showSendToFriend: function (dialog) {
			dialog = dialog.data;
			var modalTitle = dialog.find('.modal-title').html();
			dialog.find('[@rel=submit]').click(function (e) {
				e.preventDefault();
				// validate form
				if (RBGUtilities.Modal.validateSendToFriend(dialog)) {
					dialog.find('.modal-message').fadeOut(function () {
						dialog.find('.modal-message').removeClass('modal-error').empty();
					});				
					var sids = [];
					$('[@name=supplier_id]:checked').each(function(i){
						sids[i] = $(this).val();
					});
					dialog.find("[@id=selected_ids]").val(sids);
					
					dialog.find('.modal-loading').hide().fadeIn(200, function () {
						// TODO: custom logic for newsletter subscription
						/* Below is a sample AJAX submission using jQuery:*/
						$.ajax({
							url: APP_ROOT + '/ajax/send_to_friend',
							data: dialog.find('form').serialize(),
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								if (xhr.responseText != "false") {
									// Address was successfully added - close the modal window
									dialog.find('.modalClose').click();
								} else {
									alert("There was an error while processing your submission. Please try again");
								}
								dialog.find('.modal-loading').fadeOut(200);
							},
							error: RBGUtilities.Modal.error
						});						
						
						dialog.find('.modal-loading').fadeOut(200);
						//dialog.find('.modalClose').click();
					});
				} else {
					RBGUtilities.Modal.showValidationError(dialog);
				}
			});
		},
		validateSendToFriend: function (modal) {
			var allFields = new Array('from_name','from_email','to_name','to_email','message');
			var requiredFields = new Array('from_name','from_email','to_name','to_email');		
			var requiredFieldErrors = new Array(
				'Please enter Your Name',
				'Please enter a valid email for Your Email',
				'Please enter Your Friend\'s Name',
				'Please enter a valid email for Your Friend\'s Email'
			);
			
			return RBGUtilities.Modal.validateFields(modal, allFields, requiredFields, requiredFieldErrors);
		},
		
		/* Send enquiry */
		showSendEnquiry: function (dialog) {
			dialog = dialog.data;
			var modalTitle = dialog.find('.modal-title').html();
			dialog.find('[@rel=submit]').click(function (e) {
				e.preventDefault();
				// validate form
				if (RBGUtilities.Modal.validateSendEnquiry(dialog)) {
					dialog.find('.modal-message').fadeOut(function () {
						dialog.find('.modal-message').removeClass('modal-error').empty();
					});
					
					var sids = [];
					$('[@name=supplier_id]:checked').each(function(i){
						sids[i] = $(this).val();
					});
					dialog.find("[@id=selected_ids]").val(sids);					
					dialog.find('.modal-loading').hide().fadeIn(200, function () {					
						/* Below is a sample AJAX submission using jQuery:*/
						
						$.ajax({
							url: APP_ROOT + '/ajax/send_enquiry',
							data: dialog.find('form').serialize(),
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								if (xhr.responseText != "false") {
									// Address was successfully added - close the modal window
									dialog.find('.modalClose').click();
								} else {
									alert("There was an error while processing your submission. Please try again");
								}
								dialog.find('.modal-loading').fadeOut(200);
							},
							error: RBGUtilities.Modal.error
						});
						
						
						
						dialog.find('.modal-loading').fadeOut(200);
						dialog.find('.modalClose').click();
					});
				} else {
					RBGUtilities.Modal.showValidationError(dialog);
				}
			});
		},
		validateSendEnquiry: function (modal) {
			var allFields = new Array('name','email','phone','message','supplier_id');
			var requiredFields = new Array('name','email','phone','message');
		
			var requiredFieldErrors = new Array(
				'Please enter your Name',
				'Please enter a valid email for your Email',
				'Please enter your Contact No',
				'Please enter your Message'
			);
			
			return RBGUtilities.Modal.validateFields(modal, allFields, requiredFields, requiredFieldErrors);
		},
		
		/* Save Search */
		showSaveSearch: function (dialog) {
			dialog = dialog.data;
			dialog.find('[@rel=submit]').click(function (e) {
				e.preventDefault();
				// validate form
				if (RBGUtilities.Modal.validateSaveSearch(dialog)) {
					dialog.find('.modal-message').fadeOut(function () {
						dialog.find('.modal-message').removeClass('modal-error').empty();
					});
					var sids = [];
					$('[@name=supplier_id]:checked').each(function(i){
						sids[i] = $(this).val();
					});
					dialog.find("[@id=selected_ids]").val(sids);					
					dialog.find('.modal-loading').hide().fadeIn(200, function () {
						// TODO: custom logic for newsletter subscription
						/* Below is a sample AJAX submission using jQuery:*/
						
						$.ajax({
							url: APP_ROOT + '/ajax/add_to_favourite',
							data: dialog.find('form').serialize(),
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								if (xhr.responseText != "false") {
									// Searches were saved successfully - close the modal window
									alert('The selected business(es) have been added to your favourites.');
									dialog.find('.modalClose').click();
								} else {
									alert("There was an error while processing your submission. Please try again");
								}
								dialog.find('.modal-loading').fadeOut(200);
							},
							error: RBGUtilities.Modal.error
						});
						
						
						
						dialog.find('.modal-loading').fadeOut(200);
						dialog.find('.modalClose').click();
					});
				} else {
					RBGUtilities.Modal.showValidationError(dialog);
				}
			});
		},
		validateSaveSearch: function (modal) {
			// TODO: custom validation for save search
			var allFields = new Array('type_existing','existing_list','type_new','newlist_name');
			
			if(modal.find("[@id=type_existing]:checked").length){
				var requiredFields = new Array('existing_list');
				var requiredFieldErrors = new Array(
					'please select an existing list.'									
				);
			}else if(modal.find("[@id=type_new]:checked").length){
				var requiredFields = new Array('newlist_name');
				var requiredFieldErrors = new Array(
					'please enter a list name.'									
				);
			}else{
				var requiredFields = new Array('');
				var requiredFieldErrors = new Array(
					'please select any options.'									
				);
			}
			return RBGUtilities.Modal.validateFields(modal, allFields, requiredFields, requiredFieldErrors);
//			return true;
		},
		
		/* Generic modal window functions */
		open: function (dialog) {
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.css("display","block").fadeIn(200, function () {
						dialog.data.find('form').fadeIn(200, function () {
							dialog.data.find('input:first').focus();
						});
					});
				});
			});
		},
		close: function (dialog) {
			$('#modal-container .modal-message').fadeOut();
			dialog.data.fadeOut(200, function () {
				dialog.overlay.fadeOut(200, function () {
					$.modal.close();
				});
			});
		},
		showValidationError: function(dialog) {
			if (dialog.find('.modal-message:visible').length > 0) {
				var msg = dialog.find('.modal-message');
				msg.fadeOut(200, function () {
					msg.empty();
					RBGUtilities.Modal.showError();
					msg.fadeIn(200);
				});
			}
			else {
				RBGUtilities.Modal.showError();
				dialog.find('.modal-message').slideDown();
			}
		},
		validateFields: function(modal, allFields, requiredFields, requiredFieldErrors) {
			var allFieldsLen = allFields.length;
			for (var i=0; i<allFieldsLen; i++) {
				RBGUtilities.Modal.unsetFieldError(modal.find("[@name=" + allFields[i] + "]"));
			}
			
			RBGUtilities.Modal.message = '';
			
			var len = requiredFields.length;
			var errors = new Array();
			
			for(var i=0; i<len; i++) {
				var field = requiredFields[i];
				var control = modal.find("[@name=" + field + "]");
				switch(field) {
					case 'to_email':
					case 'from_email':
					case 'email':
						if (!RBGUtilities.Modal.validateEmail(control.val())) {
							RBGUtilities.Modal.setFieldError(control);
							errors.push(requiredFieldErrors[i]);
						}
						break;
					default:
						if (!control.val()) {
							RBGUtilities.Modal.setFieldError(control);
							errors.push(requiredFieldErrors[i]);
						}
				}
			}
			
			if (errors.length) {
				RBGUtilities.Modal.message = errors.join('<br />');
			}
			return !errors.length;			
		},
		validateEmail: function (email) {
			var at = email.lastIndexOf("@");
	
			// Make sure the at (@) sybmol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;
	
			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;
	
			// Break up the local and domain portions
			var local = email.substring(0, at);
			var domain = email.substring(at + 1);
	
			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;
	
			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;
	
			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}
	
			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	
	
			return true;
		},
		showError: function () {
			$('#modal-container .modal-message')
				.html(RBGUtilities.Modal.message)
				.fadeIn(200);
		},
		setFieldError: function(field) {
			field.addClass('form-error');
		},
		unsetFieldError: function(field) {
			field.removeClass('form-error');
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		message: null
	}
}

// Attach events on document load
$(document).ready(function() {
	$("[@rel=modalSaveSearch]").bind("click", RBGUtilities.showSaveSearchForm);
	$("[@rel=modalSendEnquiry]").bind("click", RBGUtilities.showSendEnquiryForm);
	$("[@rel=modalSendToFriend]").bind("click", RBGUtilities.showSendToFriendForm);
	$("[@rel=modalRemoveFromFavourites]").bind("click", RBGUtilities.removeFromFavourites);

	// PNG Fix
	$("img[@src$=.png]").pngfix();
	
	// Print function
	$("a.print").click(function() { window.print() });
});


function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

/* Regions and Suburbs */
$(document).ready(function(){
	$("div").filter(".state").css("display","none");
});
function showRegion(state){ 
	$("div").filter(".state").css("display","none");
	$('#state'+state).css('display','block');
}
function showSuburbs(e, area, region) {
	// get the layer, load content into iframe
	var layer = document.getElementById("suburbPopup");
	var title = document.getElementById("areaTitle");
	var frame = document.getElementById("suburbFrame");
	
	title.innerHTML = area;
	frame.src = APP_ROOT + '/suburbpopup/' + escape(area.replace('/', '{SLASH}')) + '/' + escape(region.replace('/', '{SLASH}'));
	
	// update the display
	if (document.all)
	{
		// IE
		layer.style.left	= findPosX(event.srcElement) + 100;
		layer.style.top		= findPosY(event.srcElement) - 15;
		layer.style.display	= "block";
	}
	else
	{
		// FireFox, NN
		layer.style.left	= findPosX(e.target) + 100 + "px";
		layer.style.top		= findPosY(e.target) - 15 + "px";
		layer.style.display	= "block";
		
		// cancel the event so it doesn't select the checkbox in the label
		e.preventDefault();
	}
}
function showSuburbsByArea(e, areaId, areaName) {
	// get the layer, load content into iframe
	var layer = document.getElementById("suburbPopup");
	var title = document.getElementById("areaTitle");
	var frame = document.getElementById("suburbFrame");
	
	title.innerHTML = areaName;
	frame.src = APP_ROOT + '/suburbpopup/' + parseInt(areaId);
	
	// update the display
	if (document.all)
	{
		// IE
		layer.style.left	= findPosX(event.srcElement) + 100;
		layer.style.top		= findPosY(event.srcElement) - 15;
		layer.style.display	= "block";
	}
	else
	{
		// FireFox, NN
		layer.style.left	= findPosX(e.target) + 100 + "px";
		layer.style.top		= findPosY(e.target) - 15 + "px";
		layer.style.display	= "block";
		
		// cancel the event so it doesn't select the checkbox in the label
		e.preventDefault();
	}
}
//hides the current layer
function hideSuburbList()
{
	document.getElementById("suburbPopup").style.display = "none";
}