/*jQuery.fn.log = function (msg) {
	if ($.browser.mozilla) {
		console.log("%s: %o", msg, this);
	}
	return this;
};*/

function fetchEntryForm(selector) {
    if ($(selector).length) {
        
        // Empty the basket
        /*
        $.ajax({
            type	: "POST",
            dataType: "json",
            url		: "/basket1.php",
            data	: "empty=" + 1 + "&key=" + key(10000),
            async   : false,
            success	: function(json){
            }
        });
        */
        
        $.ajax({
            type	: "POST",
            dataType: "html",
            url		: "/entryForm.php",
            data	: "show=1" + "&key=" + key(10000),
            async   : false,
            success	: function(html){
                
                var entryPrice = new Number();
                var productsSubtotal = new Number();
                var total = new Number();
                
                //$('#page_header').hide();
                $(selector).empty().html(html).hide().fadeIn(2000);
                
                $(selector + ' textarea').keyup(function() {FitToContent(this, document.documentElement.clientHeight)});
                $(selector + ' textarea').charCounter(600, {container: selector + " .counter"});
                
                $('input[name="submit"]').button();
                
                $('#team_size').change(function() {
                    
                    // Empty the basket
                    $.ajax({
                        type	: "POST",
                        dataType: "json",
                        url		: "/basket1.php",
                        data	: "empty=" + 1 + "&key=" + key(10000),
                        async   : false,
                        success	: function(json){
                            if (json.emptied) {
                                productsSubtotal = 0
                                $('#products_subtotal_display').empty().html('R' + number_format(productsSubtotal, 2, '.', ','));
                                $('input[name="products_subtotal"]').val(productsSubtotal);
                                $('input[name="products_subtotal"]').parent('p').hide();
                            }
                        }
                    });
                    
                    $.ajax({
                        type	: "POST",
                        dataType: "json",
                        url		: "/entryFee.php",
                        data	: "id=" + $(this).val() + "&key=" + key(10000),
                        async   : false,
                        success	: function(entryFee){
                            
                            // Set the entry fee based on $(this).val()
                            entryPrice = parseInt(entryFee.price);
                            $('#entry_fee_display').empty().html('R' + number_format(entryPrice, 2, '.', ','));
                            $('input[name="entry_fee"]').val(entryPrice);
                            $('input[name="entry_fee"]').parent('p').show();
                            
                            var total = entryPrice;
                            
                            if ($('select[name="payment_method"]').val() == 'Credit Card (iVeri)') {
                                total = total + (total * 0.06);
                            }
                            
                            $('#total_display').empty().html('R' + number_format(total, 2, '.', ','));
                            $('input[name="total"]').val(total);
                            
                        }
                    });
                     
                    if ($(this).val() != '') {
                        $.ajax({
                            type	: "POST",
                            dataType: "html",
                            url		: "/riderInfo.php",
                            data	: "id=" + $(this).val() + "&key=" + key(10000),
                            async   : false,
                            success	: function(html) {
                                $("#riderInfo").empty().html(html).show();
                                
                                $('#tabs').tabs();
                                
                                // NOTE: Add code to toggle lisence number field on and off perhaps using the closest or siblings dom traversal functions
                                // ^= does not work in IE 7
                                $('select[name*="rider_license"]').change( function() {
                                    if ($(this).val() == 'No') {
                                        $(this).parent().next('p').show();
                                        $(this).parent().next('p').children('input[name*="license_number"]').attr('class', 'required').focus();
                                        alert('Please make sure to enter the license number.');
                                    } else {
                                        $(this).parent().next('p').hide();
                                        $(this).parent().next('p').children('input[name*="license_number"]').attr('class', '');
                                        alert('Please make sure to buy a temporary license.');
                                    }
                                });
                                
                                // Uses jQuery autocomplete to populate the rider email field
                                $('input[name*="rider_email"]').autocomplete({
                                    source: "/riders.php",
                                    minLength: 3,
                                    delay: 1000,
                                    select: function(event, ui) {
                                        //alert(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value );
                                        //alert(ui.item.id);
                                        $(this).parent('p').find('input[name*="client_id"]').val(ui.item.id);
                                        $(this).parent().next('div').show();
                                        $(this).data("uiItem", ui.item.value);
                                    }
                                }).bind("blur", function() {
                                    $(this).val($(this).data("uiItem"));
                                }).data("uiItem", $('input[name*="rider_email"]').val());
                            }
                        });
                    }
                });
                
                $('select[name="payment_method"]').change(function() {
                    
                    if ($(this).val() != '') {
                        productsSubtotal = parseInt($('input[name="products_subtotal"]').val());

                        total = entryPrice + productsSubtotal;
                        
                        if ($(this).val() == 'Credit Card (iVeri)') {
                            total = total + (total * 0.06);
                            // Shows the percentage message
                            $(this).parent('p').next('p').show();
                        }
                        
                        if ($(this).val() == 'Bank Deposit (EFT)') {
                            // Hides the percentage message
                            $(this).parent('p').next('p').hide();
                        }
                        
                        $('#total_display').empty().html('R' + number_format(total, 2, '.', ','));
                        $('input[name="total"]').val(total);
                        $('input[name="total"]').parent('p').show();
                    } else {
                        $('input[name="total"]').parent('p').hide();
                    }
                });
                
                $("#entryForm").validate({
                    submitHandler: function(form) {
                        processEntryForm(selector);
                    },
                    invalidHandler: function(form, validator) {
                        var errors = validator.numberOfInvalids();
                        if (errors) {
                            var invalidPanels = $(validator.invalidElements()).closest(".ui-tabs-panel", form);
                            if (invalidPanels.size() > 0) {
                                $.each($.unique(invalidPanels.get()), function(){
                                    //alert(this.id);
                                    alert('Please make sure you have filled in all the required fields for Rider ' + str_replace('tabs-', '', this.id));
                                    //$(this).siblings(".ui-tabs-nav").find("a[href='#" + this.id + "']").parent().not(".ui-tabs-selected").addClass("ui-state-error").show("pulsate",{times: 3});
                                    $(this).siblings(".ui-tabs-nav").find("a[href='#" + this.id + "']").parent().addClass("ui-state-error").show("pulsate",{
                                        times: 3
                                    });
                                });
                            }
                        }
                    },
                    highlight: function(element, errorClass, validClass) {
                        if (element.type === 'radio') {
                            this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                        } else {
                            $(element).addClass(errorClass).removeClass(validClass);
                        }
                        
                        var $tabs = $('#tabs').tabs();
                        var selected = $tabs.tabs('option', 'selected');
                        if ($("#tabs-" + (selected + 1)).find("." + errorClass + ":visible").size() > 0) {
                            //$("a[href='#tabs-" + (selected + 1) + "']").parent().not(".ui-tabs-selected").addClass("ui-state-error");
                            $("a[href='#tabs-" + (selected + 1) + "']").parent().addClass("ui-state-error");
                        }
                    },
                    unhighlight: function(element, errorClass, validClass) {
                        if (element.type === 'radio') {
                            this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                        } else {
                            $(element).removeClass(errorClass).addClass(validClass);
                        }
                        
                        var $tabs = $('#tabs').tabs();
                        var selected = $tabs.tabs('option', 'selected');
                        if ($("#tabs-" + (selected + 1)).find("." + errorClass + ":visible").size() == 0) {
                            $("a[href='#tabs-" + (selected + 1) + "']").parent().removeClass("ui-state-error");
                        }
                    }
                });
            }
        });
    }
}

function processEntryForm(selector) {
    $.ajax({
        type	: "POST",
        dataType: "json",
        url		: "/entryForm.php",
        data	: $("#entryForm").serialize() + "&key=" + key(10000),
        success	: function(result) {
            if (result.success) {
                
                if (result.paymentMethod == 'EFT') {
                    $.ajax({
                        type	: "POST",
                        dataType: "html",
                        url		: "/entryForm.php",
                        data	: "success=1" + "&key=" + key(10000),
                        success	: function(html){
                            $(selector).empty();
                            $(selector).append(html);
                            //alert("Thank you.");
                        }
                    });
                }
                
                if (result.paymentMethod == 'IVERI') {
                    window.location = "/page/iveri1";
                }
                
            } else {
                alert("Error!");
            }
        }
    });
}

function addToBasket1(rider, product_id, type, object) {
	var quantity = 1;
	var size_id = 0;
	var remove = 1;
    
    var client_id = $('input[name="client_id_' + rider + '"]').val();
    
    //alert(client_id);
	
	//alert(type + ' ' + object.value);

    if (type == 'quantity') {
		if (object.value != '') {
			quantity = object.value;
			remove = 0;
        }
	}

	if (type == 'size') {
		if (object.value != '') {
			size_id = object.value;
			remove = 0;
		}
	}
	
	if (type == 'checkbox') {
		if (object.checked) {
			remove = 0;
		}
	}
	
	$.ajax({
		type	: "GET",
		url		: "/basket1.php",
		data	: "remove=" + remove + "&client_id=" + client_id + "&product_id=" + product_id + "&size_id=" + size_id + "&quantity=" + quantity + "&key=" + key(10000),
		success	: function(html){
			updateTotals();
		}
	});
}

function updateTotals() {
	$.ajax({
		type	: "POST",
        dataType: "json",
		url		: "/basket1.php",
		data	: "fetchTotal=" + 1 + "&key=" + key(10000),
		success	: function(json) {
            
            var entryPrice = parseInt($('input[name="entry_fee"]').val());
            var productsSubtotal = json.total;
            
			$('#products_subtotal_display').empty().html('R' + number_format(productsSubtotal, 2, '.', ','));
            $('input[name="products_subtotal"]').val(productsSubtotal);
            $('input[name="products_subtotal"]').parent('p').show();
            
            var total = entryPrice + productsSubtotal;
            
            if ($('select[name="payment_method"]').val() == 'Credit Card (iVeri)') {
                total = total + (total * 0.06);
            }
            
            $('#total_display').empty().html('R' + number_format(total, 2, '.', ','));
            $('input[name="total"]').val(total);
            
		}
	});
}

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 == 'quantity') {
		if (object.value != '') {
			quantity = object.value;
			remove = 0;
        }
	}

	if (type == 'size') {
		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");
		}
	});
}
