/*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:    10, 
					maxWidth:    25, 
					extraWidth:  1    
				}).superfish({
					dropShadows : false
				});
				/*$("ul.sf-menu").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_form").log('md5: ' + md5($("#username").val() + $("#password").val()));
						//$("#login_form").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/waver";
						} 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);
		}
	});
}

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);
			//alert('Basket Emptied!');
		}
	});
}

function license(object) {
	if (object.value != '') {
		if (object.value == 'No') {
			$('#rider_license_number_fields').show();
			$('#rider_license_number').attr("class", "required");
			alert('Please make sure to enter the license number.');
			$('#rider_license_number').focus();
		} else {
			$('#rider_license_number_fields').hide();
			$('#rider_license_number').attr("class", "");
			alert('Please make sure to buy a temporary license.');
		}
	}
}

function addToBasket(product_id, type, object) {
	var quantity = 1;
	var size_id = 0;
	var remove = 1;
	
	//alert(type + ' ' + object.value);

	if (type == 'select') {
		if (object.value != '') {
			size_id = object.value;
			remove = 0;
		}
	}
	
	if (type == 'checkbox') {
		if (object.checked) {
			remove = 0;
		}
	}
	
	$.ajax({
		type	: "GET",
		url		: "/basket.php",
		data	: "remove=" + remove  + "&product_id=" + product_id + "&size_id=" + size_id + "&quantity=" + quantity + "&key=" + key(10000),
		success	: function(html){
			fetchTotal();
		}
	});
}

function fetchTotal() {
	$.ajax({
		type	: "GET",
		url		: "/basket.php",
		data	: "total=" + 1 + "&key=" + key(10000),
		success	: function(response){
			$("#temp_total").empty();
			$("#temp_total").append(response);
			$("#total").empty();
			$("#total").append('Total: R' + number_format(response, 2, '.', ','));
		}
	});
}

function emailExists(email, form) {
	$.ajax({
		type	: "GET",
		url		: "/check.php",
		data	: "email=" + email + "&key=" + key(10000),
		success	: function(response){
			if (response == 1) {
				alert('The email address you are using already exists in our database. Please LOGIN to enter the event.');
			} 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();
	}
}

function addRiders(count) {
	$("#rider_info").empty();
	var current = 0;
	var html = '<legend>Rider Info</legend>';
	while (current < count) {
		
		current++;
		
		html += '<p>';
		html += '<label for="ride_' + current  + '_license">Rider 1 License No.</label>';
		html += '<div>*</div>';
		html += '<input name="ride_' + current  + '_license" type="text" id="ride_' + current  + '_license" size="26" class="required"/>';
		html += '</p>';	
		
		//$("#rider_info").log('counter = ' + current);
	}
	
	$("#rider_info").append(html);
}

function fetchRiders(count) {
	$.ajax({
		type	: "GET",
		url		: "/riders.php",
		data	: "count=" + count + "&key=" + key(10000),
		success	: function(html){
			$("#rider_team").empty();
			$("#rider_team").append(html);
			
			emptyBasket();
			
			Shadowbox.setup(".popup");
		}
	});
}