jQuery.fn.log = function (msg) {
	if ($.browser.mozilla) {
		console.log("%s: %o", msg, this);
	}
	return this;
};

function tinymceStart(selector, table, id) {
	
	// Compress
	tinyMCE_GZ.init({
		plugins : "safari,save,iespell,inlinepopups,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,spellchecker",
		themes : 'advanced',
		languages : 'en',
		disk_cache : true,
		debug : false
	});
	
	// Render
	tinyMCE.init({
		mode : "exact",
		elements : selector,
		
		width : "460",
		height : "450",
		
		theme : "advanced",
		plugins : "safari,save,iespell,inlinepopups,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,spellchecker", 
		
		theme_advanced_buttons1 : "undo,redo,|,bold,italic,bullist,numlist,|,cut,copy,paste,pastetext,pasteword,|,spellchecker,|,help",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons2 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		//theme_advanced_resizing : true,
		
		spellchecker_languages : "+English=en", 
		spellchecker_rpc_url : "/control/scripts/tiny_mce_3_2_7/plugins/spellchecker/rpc.php"
	});
}

Shadowbox.init({
	skipSetup: true, 
	clearCache: function() {
		each(S.cache, function(obj) {
			if( obj.el) {
				S.lib.removeEvent(obj.el, 'click', handleClick);
				try {
					delete obj.el.shadowboxCacheKey;
				} catch(e) {
					if (obj.el.removeAttribute) {
						obj.el.removeAttribute('shadowboxCacheKey');
					}
				}
			}
		});
		S.cache = [];
	}
});

function key(number) {
	return Math.floor(Math.random() * number);
}

function fetchImages(link_name) {
	$.ajax({
		type	: "GET",
		url		: "/images.php",
		data	: "link_name=" + link_name + "&key=" + key(10000),
		success	: function(html){
			$("#listing_images").empty();
			$("#listing_images").append(html);
			
			Shadowbox.setup(".listing_image", {
				gallery:	link_name
			});
			
		}
	});
}

function fetchInfo(link_name) {
	$.ajax({
		type	: "GET",
		url		: "/info.php",
		data	: "link_name=" + link_name + "&key=" + key(10000),
		success	: function(html){
			$("#listing_info").empty();
			$("#listing_info").append(html);
		}
	});
}

function fetchCalendar() {
	$.ajax({
		type	: "GET",
		url		: "/calendar.php",
		data	: "key=" + key(10000),
		success	: function(html){
			$("#calendar").empty();
			$("#calendar").append(html);
		}
	});
}

function nextMonth() {
	$.ajax({
		type	: "GET",
		url		: "/calendar.php",
		data	: "go=next&key=" + key(10000),
		success	: function(html){
			$("#calendar").empty();
			$("#calendar").append(html);
		}
	});
}

function prevMonth() {
	$.ajax({
		type	: "GET",
		url		: "/calendar.php",
		data	: "go=prev&key=" + key(10000),
		success	: function(html){
			$("#calendar").empty();
			$("#calendar").append(html);
		}
	});
}

function fetchGallery(width) {
	$.ajax({
		type	: "GET",
		url		: "/gallery.php",
		data	: "width=" + width + "&key=" + key(10000),
		success	: function(html){
			
			$("#gallery").empty();
			$("#gallery").append(html);
			
			Shadowbox.clearCache();
		}
	});
}

function fetchAlbum(gallery_id, width) {
	$.ajax({
		type	: "GET",
		url		: "/gallery.php",
		data	: "width=" + width + "&gallery_id=" + gallery_id + "&key=" + key(10000),
		success	: function(html){
			
			$("#gallery").empty();
			$("#gallery").append(html);
			
			Shadowbox.setup(".album", {
				gallery:	"gallery"
			});
		}
	});
}

function fetchMenu(position, selector) {
	$.ajax({
		type	: "GET",
		url		: "/menu.php",
		data	: "position=" + position + "&key=" + key(10000),
		success	: function(html){
			
			$(selector).empty();
			$(selector).append(html);
			
			if (position == 'top') {
				$("ul.sf-menu").supersubs({ 
					minWidth:    12, 
					maxWidth:    27, 
					extraWidth:  1    
				}).superfish({
					dropShadows : false
				});
			}
			
			if (position == 'left') {
				$("ul.sf-menu").superfish({
					dropShadows : false
				});
			}
			
		}
	});
}

function fetchAdverts(page, position, selector) {
	$.ajax({
		type	: "GET",
		url		: "/adverts.php",
		data	: "page=" + page + "&position=" + position + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
		}
	});
}

function fetchLogin(selector, domain) {
	$.ajax({
		type	: "POST",
		url		: "/login.php",
		data	: "show=1" +
				  "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
			$("#authenticate").click(function () { 
				
				//$("#username").log('USERNAME');
				//$("#password").log('PASSWORD');
				//$("#login").log('MD5: ' + md5($("#username").val() + $("#password").val()))
				
				$.ajax({
					type	: "POST",
					url		: "/login.php",
					data	: "username=" + $("#username").val() + 
							  "&password=" + $("#password").val() + 
							  "&md5=" + md5($("#username").val() + $("#password").val()) + 
							  "&key=" + key(10000),
					success	: function(authenticated){
						
						$("#login").log('AUTHENTICATED: ' + authenticated);
						
						if (authenticated == 1) {
							//fetchBasket(); $('#basket').log("basket is shown");
							$("#login").empty();
							//$("#login").append('<a href="/login.php?logout=1" target="_self"><img src="/website/styles/default/logout_large.png" alt="logout" width="80" height="30" border="0" /></a> <a href="/page/edit_listings" target="_self"><img src="/website/styles/default/edit_listings_large.png" alt="edit listings" width="160" height="30" border="0" /></a> <a href="/page/edit_profile" target="_self"><img src="/website/styles/default/edit_profile_large.png" alt="edit profile" width="160" height="30" border="0" /></a>');
							//alert("Thank you. You may now proceed to edit your listings.");
							alert("Thank you. You are now logged in.");
							top.location = "http://" + domain + "/page/edit_listings";
						} else {
							alert("ERROR! Please enter a correct username and password.");
						}
						
					}
				});
			});
		}
	});
}

function fetchNews(limit) {
	var selector = '#news';
	$.ajax({
		type	: "GET",
		url		: "/news.php",
		data	: "limit=" + limit + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
			
			Shadowbox.setup(".listing_thumb");
		}
	});
}

function fetchEvents(limit) {
	var selector = '#events';
	$.ajax({
		type	: "GET",
		url		: "/events.php",
		data	: "limit=" + limit + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
			
			Shadowbox.setup(".listing_thumb");
		}
	});
}

function fetchSlideshow(name, width, height, selector) {
	
	$.ajax({
		type	: "GET",
		url		: "/slideshow.php",
		data	: "name=" + name + "&width=" + width + "&height=" + height + "&key=" + key(10000),
		success	: function(html){
			
			$(selector).empty();
			$(selector).append(html);
			
			$(selector).cycle({
				fx:     'fade', 
				timeout: 8000, 
				//next:   '#slideshow', 
				pause:   1,
				random:  1
				//before:  onBefore, 
				//after:   onAfter 
			});
		}
	});
}

function fetchBasket() {
	var selector = '#basket';
	$(selector).show();
	$.ajax({
		type	: "GET",
		url		: "/basket.php",
		data	: "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
		}
	});
}

function emptyBasket() {
	var selector = '#basket';
	$.ajax({
		type	: "GET",
		url		: "/basket.php",
		data	: "empty=1&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
		}
	});
}

function fetchSpecials() {
	var selector = '#specials';
	$(selector).show();
	$.ajax({
		type	: "GET",
		url		: "/specials.php",
		data	: "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
		}
	});
}

function echeck(str) {

	var at = "@";
	var dot = ".";
	var lat = str.indexOf(at);
	var lstr = str.length;
	var ldot = str.indexOf(dot);
	
	if (str.indexOf(at) ==- 1) { return false; }
	if (str.indexOf(at) ==- 1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) { return false; }
	if (str.indexOf(dot) ==- 1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) { return false; }
	if (str.indexOf(at, (lat + 1)) !=- 1) { return false; }
	if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) { return false; }
	if (str.indexOf(dot, (lat + 2)) ==- 1) { return false; }
	if (str.indexOf(" ") !=- 1 ) { return false; }
	 
	return true;
}

function isInteger (s) {
	var i;
	
	if (isEmpty(s))
	if (isInteger.arguments.length == 1) return 0;
	else return (isInteger.arguments[1] == true);
	
	for (i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}
	
	return true;
}

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

function isDigit (c) {
	return ((c >= "0") && (c <= "9"))

}

function validateProfile() {
	
	// first_name
	if (document.getElementById("first_name").value.length < 1) {
		alert("Please enter a valid first name.");
		document.getElementById("first_name_label").style.color = "red";
		document.getElementById("first_name").focus();
		return false;
	} else {
		document.getElementById("first_name_label").style.color = "black";
	}
	
	// last_name
	if (document.getElementById("last_name").value.length < 1) {
		alert("Please enter a valid last name.");
		document.getElementById("last_name_label").style.color = "red";
		document.getElementById("last_name").focus();
		return false;
	} else {
		document.getElementById("last_name_label").style.color = "black";
	}
	
	// email_1 (validate)
	if (echeck(document.getElementById("email_1").value) == false) {
		alert("Please enter a valid email address.");
		document.getElementById("email_1_label").style.color = "red";
		document.getElementById("email_1").focus();
		return false;
	} else {
		document.getElementById("email_1_label").style.color = "black";
	}
	
	// email_2
	if (document.getElementById("email_2").value != document.getElementById("email_1").value) {
		alert("Please make sure the email addresses are the same.");
		document.getElementById("email_2_label").style.color = "red";
		document.getElementById("email_2").focus();
		return false;
	} else {
		document.getElementById("email_2_label").style.color = "black";
	}
	
	// password
	if (document.getElementById("password").value.length < 6) {
		alert("Please enter a password with more than 6 characters.");
		document.getElementById("password_label").style.color = "red";
		document.getElementById("password").focus();
		return false;
	} else {
		document.getElementById("password_label").style.color = "black";
	}
	
	// street_address
	if (document.getElementById("street").value.length < 1) {
		alert("Please enter a valid street address.");
		document.getElementById("street_label").style.color = "red";
		document.getElementById("street").focus();
		return false;
	} else {
		document.getElementById("street_label").style.color = "black";
	}
	
	// town
	if (document.getElementById("town").value.length < 1) {
		alert("Please enter a valid town.");
		document.getElementById("town_label").style.color = "red";
		document.getElementById("town").focus();
		return false;
	} else {
		document.getElementById("town_label").style.color = "black";
	}
	
	// province
	if (document.getElementById("province").value.length < 1) {
		alert("Please enter a valid province.");
		document.getElementById("province_label").style.color = "red";
		document.getElementById("province").focus();
		return false;
	} else {
		document.getElementById("province_label").style.color = "black";
	}
	
	// postal_code
	if (document.getElementById("postal_code").value.length < 1) {
		alert("Please enter a valid postal code.");
		document.getElementById("postal_code_label").style.color = "red";
		document.getElementById("postal_code").focus();
		return false;
	} else {
		document.getElementById("postal_code_label").style.color = "black";
	}
	
	// phone
	if (!isInteger(document.getElementById("phone").value)) {
		alert("Please enter a valid phone number.");
		document.getElementById("phone_label").style.color = "red";
		document.getElementById("phone").focus();
		return false;
	} else {
		document.getElementById("phone_label").style.color = "black";
	}
			
	if (document.getElementById("txtCaptcha").value.length == 5) {
		$.ajax({
			type	: "POST",
			url		: "/control/captcha/captcha.php",
			data	: "txtCaptcha=" + document.getElementById("txtCaptcha").value + "&key=" + key(10000),
			success	: function(html){
				$("#result").empty();
				$("#result").append(html);
				
				if (html == "FAIL") {
					alert("The code you entered was incorrect. Please try again.");
					$("#imgCaptcha").attr("src", "/control/captcha/image.php?key=" + key(10000));
				} else {
					document.edit_profile.submit();
				}
			}
		});
		return false;
	} else {
		alert("Please enter the exact code on the image into the text box and try again.");
		document.getElementById("txtCaptcha").focus();
		return false;
	}	
}

function validateListing() {
	
	// phone
	//if (!isInteger(document.getElementById("phone").value)) {
	if (document.getElementById("phone").value.length < 10) {
		alert("Please enter a valid phone number.");
		document.getElementById("phone_label").style.color = "red";
		document.getElementById("phone").focus();
		return false;
	} else {
		document.getElementById("phone_label").style.color = "black";
	}
	
	// email (validate)
	if (echeck(document.getElementById("email").value) == false) {
		alert("Please enter a valid email address.");
		document.getElementById("email_label").style.color = "red";
		document.getElementById("email").focus();
		return false;
	} else {
		document.getElementById("email_label").style.color = "black";
	}
	
	// website
	if (document.getElementById("website").value.length < 1) {
		alert("Please enter a valid website URL (example: http://www.mywebsite.com).");
		document.getElementById("website_label").style.color = "red";
		document.getElementById("website").focus();
		return false;
	} else {
		document.getElementById("website_label").style.color = "black";
	}
	
	// content
	if (document.getElementById("content").value.length < 10) {
		alert("Please enter a valid establishment long description.");
		document.getElementById("content_label").style.color = "red";
		document.getElementById("content").focus();
		return false;
	} else {
		document.getElementById("content_label").style.color = "black";
	}
	
	// short_description
	if (document.getElementById("short_description").value.length < 10) {
		alert("Please enter a valid establishment short description.");
		document.getElementById("short_description_label").style.color = "red";
		document.getElementById("short_description").focus();
		return false;
	} else {
		document.getElementById("short_description_label").style.color = "black";
	}
			
	if (document.getElementById("txtCaptcha").value.length == 5) {
		$.ajax({
			type	: "POST",
			url		: "/control/captcha/captcha.php",
			data	: "txtCaptcha=" + document.getElementById("txtCaptcha").value + "&key=" + key(10000),
			success	: function(html){
				$("#result").empty();
				$("#result").append(html);
				
				if (html == "FAIL") {
					alert("The code you entered was incorrect. Please try again.");
					$("#imgCaptcha").attr("src", "/control/captcha/image.php?key=" + key(10000));
				} else {
					document.edit_listing.submit();
				}
			}
		});
		return false;
	} else {
		alert("Please enter the exact code on the image into the text box and try again.");
		document.getElementById("txtCaptcha").focus();
		return false;
	}	
}

function validateEnquire() {
	
	// first_name
	if (document.getElementById("first_name").value.length < 1) {
		alert("Please enter a valid first name.");
		document.getElementById("first_name_label").style.color = "red";
		document.getElementById("first_name").focus();
		return false;
	} else {
		document.getElementById("first_name_label").style.color = "black";
	}
	
	// last_name
	if (document.getElementById("last_name").value.length < 1) {
		alert("Please enter a valid last name.");
		document.getElementById("last_name_label").style.color = "red";
		document.getElementById("last_name").focus();
		return false;
	} else {
		document.getElementById("last_name_label").style.color = "black";
	}
	
	// email_1 (validate)
	if (echeck(document.getElementById("email_1").value) == false) {
		alert("Please enter a valid email address.");
		document.getElementById("email_1_label").style.color = "red";
		document.getElementById("email_1").focus();
		return false;
	} else {
		document.getElementById("email_1_label").style.color = "black";
	}
	
	// email_2
	if (document.getElementById("email_2").value != document.getElementById("email_1").value) {
		alert("Please make sure the email addresses are the same.");
		document.getElementById("email_2_label").style.color = "red";
		document.getElementById("email_2").focus();
		return false;
	} else {
		document.getElementById("email_2_label").style.color = "black";
	}
	
	// phone
	if (document.getElementById("phone").value.length < 1) {
		alert("Please enter a valid telephone number.");
		document.getElementById("phone_label").style.color = "red";
		document.getElementById("phone").focus();
		return false;
	} else {
		document.getElementById("phone_label").style.color = "black";
	}
	
	// message
	if (document.getElementById("message").value.length < 10) {
		alert("Please enter a valid message.");
		document.getElementById("message_label").style.color = "red";
		document.getElementById("message").focus();
		return false;
	} else {
		document.getElementById("message_label").style.color = "black";
	}
	
	/*if (!document.getElementById("agree").checked) {
		alert("Please read our terms and conditions and tick the checkbox if you agree with them.");
		return false;
	}*/
			
	if (document.getElementById("txtCaptcha").value.length == 5) {
		$.ajax({
			type	: "POST",
			url		: "/control/captcha/captcha.php",
			data	: "txtCaptcha=" + document.getElementById("txtCaptcha").value + "&key=" + key(10000),
			success	: function(html){
				$("#result").empty();
				$("#result").append(html);
				
				if (html == "FAIL") {
					alert("The code you entered was incorrect. Please try again.");
					$("#imgCaptcha").attr("src", "/control/captcha/image.php?key=" + key(10000));
				} else {
					document.enquire.submit();
				}
			}
		});
		return false;
	} else {
		alert("Please enter the exact code on the image into the text box and try again.");
		document.getElementById("txtCaptcha").focus();
		return false;
	}	
}