/*jQuery.fn.log = function (msg) {
	if ($.browser.mozilla) {
		console.log("%s: %o", msg, this);
	}
	return this;
};*/

function FitToContent(id, maxHeight) {
   	var text = id && id.style ? id : document.getElementById(id);
   	if (!text) { return; }

   	var adjustedHeight = text.clientHeight;
   	if (!maxHeight || maxHeight > adjustedHeight) {
    	adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
		if (maxHeight) { adjustedHeight = Math.min(maxHeight, adjustedHeight); }
		if (adjustedHeight > text.clientHeight) { text.style.height = adjustedHeight + "px"; }
	}
}

function createMarker(point, icon, content, listener, state) {
	var marker = new GMarker(point, icon);
	var html = '<div class="map_popup">';
	html = html + content;
	html = html + '</div>';
	
	if (state == 'open') {
		marker.openInfoWindowHtml(html);
	}
	
	GEvent.addListener(marker, listener, function() {
		marker.openInfoWindowHtml(html);
	});
	
	return marker;
}

function createIcon(image) {
	var icon = new GIcon();
	icon.image = "/images/map/" + image;
	icon.shadow = "/images/map/shadow.png";
	icon.iconSize = new GSize(27.0, 34.0);
	icon.shadowSize = new GSize(45.0, 34.0);
	icon.iconAnchor = new GPoint(13.0, 34.0);
	icon.infoWindowAnchor = new GPoint(13.0, 17.0);
	return icon;
}

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_buttons3 : "",
		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(selector, table, link_name) {
	$.ajax({
		type	: "GET",
		url		: "/images.php",
		data	: "table=" + table + "&link_name=" + link_name + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
			
			Shadowbox.setup(".popup");
			
		}
	});
}

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(gallery_id) {
    if (!gallery_id) { gallery_id = ''; }
	$.ajax({
		type	: "GET",
		url		: "/gallery.php",
		data	: "gallery_id=" + gallery_id + "&key=" + key(10000),
		success	: function(html){
			
			$("#gallery").empty();
			$("#gallery").append(html);
			
			Shadowbox.clearCache();

            $('#gallery_category_id').change( function() {
                filterGallery(this);
            });
		}
	});
}

function filterGallery(gallery_category_id) {
	$.ajax({
		type	: "GET",
		url		: "/gallery.php",
        data	: "gallery_category_id=" + gallery_category_id + "&key=" + key(10000),
		success	: function(html){
			
			$("#gallery").empty();
			$("#gallery").append(html);
			
            Shadowbox.clearCache();

            $('#gallery_category_id').change( function() {
                filterGallery(this);
            });
        }
    });
}

function fetchAlbum(gallery_id, gallery_category_id) {
	$.ajax({
		type	: "GET",
		url		: "/gallery.php",
		data	: "gallery_id=" + gallery_id + "&gallery_category_id=" + gallery_category_id + "&key=" + key(10000),
		success	: function(html){

			$("#gallery").empty();
			$("#gallery").append(html);

			Shadowbox.setup(".popup");
		}
	});
}

function fetchAllPhotos() {
	$.ajax({
		type	: "GET",
		url		: "/photos.php",
		data	: "key=" + key(10000),
		success	: function(html){
			
			$("#photos").empty();
			$("#photos").append(html);
			
			Shadowbox.clearCache();
		}
	});
}

function fetchListingPhotos(link_name) {
	$.ajax({
		type	: "GET",
		url		: "/photos.php",
		data	: "link_name=" + link_name + "&key=" + key(10000),
		success	: function(html){
			
			$("#photos").empty();
			$("#photos").append(html);
			
			Shadowbox.setup(".popup");
		}
	});
}

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);
			
			Shadowbox.setup(".popup");
			
		}
	});
}

function fetchListings(selector, limit) {
	$.ajax({
		type	: "GET",
		url		: "/listings.php",
		data	: "limit=" + limit + "&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(".popup");
		}
	});
}

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(".popup");
		}
	});
}

function fetchArticles(limit) {
	var selector = '#articles';
	$.ajax({
		type	: "GET",
		url		: "/articles.php",
		data	: "limit=" + limit + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);

			Shadowbox.setup(".popup");
		}
	});
}

function fetchSnippet(type, limit) {
	var selector = '#' + type + '_snippet';
	$.ajax({
		type	: "GET",
		url		: "/" + type + "_snippet.php",
		data	: "limit=" + limit + "&key=" + key(10000),
		success	: function(html){
			$(selector).empty();
			$(selector).append(html);
			
			Shadowbox.setup(".popup");
		}
	});
}

function fetchSlideshow(selector, width, height) {
	
	$.ajax({
		type	: "GET",
		url		: "/slideshow.php",
		data	: "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 emailExists(table, email, form) {
	$.ajax({
		type	: "GET",
		url		: "/check.php",
		data	: "table=" + table + "&email=" + email + "&key=" + key(10000),
		success	: function(response){
			if (response == 1) {
				alert('The email address you entered already exists in our database.');
			} else {
				checkCaptcha(form);
			}
		}
	});
}

function checkCaptcha(form) {
	if ($('#txtCaptcha').val().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 {
					form.submit();
				}
			}
		});
	} else {
		alert("Please enter the exact code on the image into the text box and try again.");
		document.getElementById("txtCaptcha").focus();
	}
}

timeDifference = function(startDate, endDate) {
	
	date2 = startDate;
	date1 = endDate;
	
	laterdate = date1.split("-");
	laterD = laterdate[0];
	laterM = laterdate[1];
	laterY = laterdate[2];
	
	earlierdate = date2.split("-");
	earlierD = earlierdate[0];
	earlierM = earlierdate[1];
	earlierY = earlierdate[2];
	
	var laterdate = new Date(laterY,laterM,laterD);
	var earlierdate = new Date(earlierY,earlierM,earlierD);
	
	var difference = laterdate.getTime() - earlierdate.getTime();
	
	var daysDifference = Math.floor(difference / 1000 / 60/ 60 / 24);
	difference -= daysDifference * 1000 * 60 * 60 * 24
	var hoursDifference = Math.floor(difference / 1000 / 60 / 60);
	difference -= hoursDifference * 1000 * 60 * 60
	var minutesDifference = Math.floor(difference / 1000 / 60);
	difference -= minutesDifference * 1000 * 60
	var secondsDifference = Math.floor(difference / 1000);
	
	return daysDifference;

}