$.fn.extend({
	selectTimeSlot: function () {
		var toggle = typeof(arguments[0]) == "boolean";
		var toggleOn = arguments[0];
		$(this).each(function () {
			if (!toggle) var checked = $("INPUT", this).val() == 0;
			else checked = toggleOn;
			$("INPUT", this).val(checked ? 1 : 0);
			if (checked) $(this).addClass("on");
			else $(this).removeClass("on");
		});
		var slotlength = $("#slotLength").val();
		var selected = $("#timeslots > LI > UL > LI > UL > LI > INPUT[value=1]").length;
		var secs = selected*slotlength;
		var baserate = 0;
		$("INPUT[name^=rates]").each(function () {
			var time = $(this).attr("name").match(/rates\[([0-9]+)\]/);
			if (baserate == 0 || time[1] <= secs) baserate = $(this).val();
		});
		//$("#slotBaserate").text(baserate);
		var days = $("#slotNoofdays").val();
		var dayrate = baserate*selected*slotlength;
		/*var time = new Date(slotlength*selected*1000);
		var hours = time.getHours();
		var minutes = time.getMinutes();
		var seconds = time.getSeconds();
		if (hours + minutes == 0) $("#slotSelectedtime").text(seconds+" secs");
		else if (hours == 0) $("#slotSelectedtime").text(minutes+" mins, "+seconds+" secs");
		else $("#slotSelectedtime").text(hours+" hours, "+minutes+" mins, "+seconds+" secs");
		$("#slotPerdayrate").text(dayrate.toFixed(2));*/
		//$("#slotTotal").text((dayrate*days).toFixed(2));
		$("#slotTotal").text(number_format(dayrate*days, 2));
	},
	clearForm: function () {
		return this.each(function () {
			var type = this.type;
			var tag = this.tagName.toLowerCase();
			if (tag == "form") return $(":input", this).clearForm();
			if (type == "text" || type == "password" || tag == "textarea") this.value = "";
			else if (type == "checkbox" || type == "radio") this.checked = false;
			else if (tag == "select") this.selectedIndex = -1;
		});
	},
	showSlide: function (slide) {
		if (!$("#slide"+slide+":visible").is("*")) {
			var num = $(this).attr("id").match(/\d+\.?\d*/g);
			var back = slide < parseInt(num[0]);
			$(this).css({position: "absolute", top: "167px", left: "0"}).hide("slide", {direction:(back ? "right" : "left"), easing:"easeOutQuart"}, 1000);
			$("#slide"+slide).show("slide", {direction:(back ? "left" : "right"), easing:"easeOutQuart"}, 1000, function () {$(this).css({position: "static"});});
			$(this).parents("FORM").find("#defaultSubmit").attr("name", "slide"+(slide+1));
		}
	},
	showSchedule: function () {
		var offset = $(this).offset();
		var parent = $(this).parent().offset();
		var width = $(this).width();
		var left = offset.left - parent.left + (width/2);
		var half = ($("#adsArrow").parent().innerWidth()-38)/2; //17 each side
		if (left < half) {
			$("#adsArrow").css({marginLeft: left + 17, marginRight: half - 3});
			$("#adsArrowUp").css({right: "auto", left: "-3px"});
			$("#adsArrowDown").css({left: "auto", right: "-3px"});
		} else {
			$("#adsArrow").css({marginLeft: half + 23, marginRight: (half*2)-left});
			$("#adsArrowUp").css({left: "auto", right: "-3px"});
			$("#adsArrowDown").css({right: "auto", left: "-3px"});
		}
		var index = $(this).parent().children().index(this);
		$("#adsSchedule > DIV:not(:eq("+index+"))").hide();
		$("#adsSchedule > DIV:eq("+index+")").show();
	}
});
function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

$(function () {
	var submit = $("#defaultSubmit").attr("name");
	$("INPUT[type=submit]").click(function () {submit = $(this).attr("name");});
	$("#enterForm, #verifyForm, #friendForm").submit(function () {
		var form = $(this);
		$.ajax({
			type: "POST",
			dataType: "json",
			cache: false,
			url: window.location.pathname,
			data: $(form).serialize()+"&method=ajax&"+submit+"=1",
			success: function (json) {
				if (json.slide) $("DIV[id^=slide]:visible").showSlide(json.slide);
				if (json.html != "") {
					if (json.slide && $("#slide"+json.slide+" .msg").is("*")) {
						$("#slide"+json.slide+" .msg").fadeOut(200, function () {
							$(this).replaceWith(json.html); // returns old selector
							$("#slide"+json.slide+" .msg").fadeIn(1000);
						});
					} else {
						$("#slide"+json.slide).prepend(json.html);
						$("#slide"+json.slide+" .msg").css("display", "none").animate({height:"toggle"}, 200, "linear");
					}
				}
				if (json.reset && json.reset == 1) {
					form.clearForm();
				} else if (json.fields) {
					$.each(json.fields, function(name, val) {
						$(":input[name=" + name + "]:not(:submit"+(val == "" ? ", SELECT" : "")+")", form).val(val);
						if (val == "") $("SELECT[name=" + name + "] option:eq(0)", form).attr("selected", "selected");
					});
				}
				if (json.entry && json.entry > 0) $("#verifyForm :input[name=entry]").val(json.entry);
			}
		});
		return false;
	});
	$("#adsList").after('<span id="adsArrow"><span id="adsArrowUp"></span><span id="adsArrowDown"></span></span>');
	$("#adsList LI.on").showSchedule();
	$("#adsList LI").mouseover(function () {$(this).showSchedule();});
	// TIMESLOTS ###################################
	var mouseDown = false;
	$("#timeslots")
		.mousedown(function () {mouseDown = true; return false;})
		.mouseup(function () {mouseDown = false;})
		.click(function () {return true;})
		.each(function() {$(this).get(0).onselectstart = new Function('return false');});
	$("#timeslots INPUT").each(function () {
		$(this).parent().mousedown(function () {$(this).selectTimeSlot();}).mouseover(function () {if (mouseDown) $(this).selectTimeSlot();});
		$(this).replaceWith('<input type="hidden" name="'+$(this).attr("name")+'" value="'+($(this).attr("checked") ? 1 : 0)+'" />');
	})
	$("#timeslots SPAN.name").css("cursor", "pointer").attr("title", "Select/unselect all available slots on this row").click(function () {
		$("LI:has(> INPUT)", $(this).parent()).selectTimeSlot(!$("LI:has(> INPUT[value=1])", $(this).parent()).is("*"));
	});
	$("#adCountry").change(function () {
		$("#vatnum").toggle($(":selected:first", this).hasClass("vatNumReq"));
	});
});

