function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

//Add JS class to HTML tag
if (document.documentElement && document.getElementById) {
    var docClass = document.documentElement.className != null ? document.documentElement.className : document.documentElement.getAttribute('class');
    docClass = docClass != '' ? docClass + ' jsEnabled' : 'jsEnabled';
    document.documentElement.setAttribute('class', docClass);
    document.documentElement.className = docClass; //For IE
}

/**
* @author Inigo.Villalba
*/

createCategoryFilter = {
	init: function() {
		var btnText = $('#filter #dropList a[class="True"]').html() != null ? $('#filter #dropList a[class="True"]').html() : 'CHOOSE A CATEGORY';
		$('#filter #dropList a span').html(btnText);
		$('#filter #dropList a span').css('display', 'inline-block');
	}
}

registrationBubble = {
    init: function() {
        $("#register input#Email, #register textarea, #register input#Mobile").bind('focus blur', function() {
            if (!registrationBubble.visible) {
                $(this).parent().find('.bubble').show();
                registrationBubble.visible = true;
            }
            else {
                $('.bubble').hide();
                registrationBubble.visible = false;
            }

        });
    },
    visible: false
}

registrationValidation = {
    init: function() {
        $("#register").validate({
            rules: {
                FirstName: {
                    required: true,
                    minlength: 2
                },
                LastName: {
                    required: true,
                    minlength: 2
                },
                Email: {
                    required: true,
                    email: true
                },
                AgreedToTermsAndConditions: "required"
            },
            errorElement: "span",
            errorPlacement: function(error, element) {
                if (element.attr("name") == "FirstName" || element.attr("name") == "LastName" || element.attr("name") == "Email" || element.attr("name") == "AgreedToTermsAndConditions") {
                    var el = $(element).parent().parent().find('label span.inner');
                    error.insertAfter(el);
                }
                else {
                    error.insertAfter(element);
                }
            },
            highlight: registrationValidation.validateHighlightError,
            unhighlight: registrationValidation.validateUnhighlightError,
            messages: {
                FirstName: "- Please enter your first name.",
                LastName: "- Please enter your surname",
                AgreedToTermsAndConditions: "- Please read and accept the Army's Terms &amp; Conditions and Privacy Statement.",
                Email: {
                    required: "- Please enter your email.",
                    email: "- Please enter your email in the correct format."
                }
            }

        });
        $('#register').submit(function(event) {
            if (event.result && registrationValidation.validateCompleteDOB()) {
                $('#Suggestions:not(.touched)').val('');
            } else {
                return false;
            }
        });
    },
    validateHighlightError: function(element) {
        $(element).parent().parent().find('label').addClass('error');
    },
    validateUnhighlightError: function(element) {
        $(element).parent().parent().find('label').removeClass('error');
    },
    validateCompleteDOB: function() {
        var dobDay = parseInt($('#DateOfBirthDay').val() === '' ? 0 : $('#DateOfBirthDay').val());
        var dobMonth = parseInt($('#DateOfBirthMonth').val() === '' ? 0 : $('#DateOfBirthMonth').val()) - 1;
        var dobYear = parseInt($('#DateOfBirthYear').val() === '' ? 0 : $('#DateOfBirthYear').val());
        var myDate = new Date(dobYear, dobMonth, dobDay);

        if (dobDay === myDate.getDate() && dobMonth === myDate.getMonth() && dobYear === myDate.getFullYear()) {
            return true;
        } else {
            $('#DateOfBirthLabel').addClass('error');
            $('#DateOfBirthLabel').append('<span class="error">- Please enter a valid date of birth.</span>');
            return false;
        }
    }
}

categoryFilter = {
    init: function() {
    $('#filter #dropList').live('click', function() {
            if (categoryFilter.filterShown) {
                $('#filter #dropList ul').hide();
                $('#filter #dropList').removeClass('on');
                categoryFilter.filterShown = false;
            }
            else {
                $('#filter #dropList ul').show();
                $('#filter #dropList').addClass('on');
                categoryFilter.filterShown = true;
            }

        });
    },
    filterShown: false
}

function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") //IE route
        target.onselectstart = function() { return false }
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
        target.style.MozUserSelect = "none"
    else //All other route (ie: Opera)
        target.onmousedown = function() { return false }
    target.style.cursor = "default"
}

function write(input) {
    //$("#debugoutput").append("<p>" + input + "</p>");
}


jQuery(document).ready(function() {
	//$('#preview .carousel').show();

	categoryFilter.init();
	createCategoryFilter.init();
	registrationValidation.init();
	registrationBubble.init();

	Cufon.replace('blockquote');
	Cufon.replace('#filter a span');
	Cufon.replace('.video_text h1');

	var isIe6 = jQuery.browser.msie && jQuery.browser.version == 6;
	if (!isIe6) {
		$('#DateOfBirthDay, #DateOfBirthMonth, #DateOfBirthYear').sSelect({ ddMaxHeight: '200px' });
		$('#DateOfBirthDay, #DateOfBirthMonth, #DateOfBirthYear').focus();
	}

	if (document.getElementById('mycarousel')) { disableSelection(document.getElementById('mycarousel')); }

	$(".close").click(function() {
		history.go(-1);
		return false;
	});

	if (jQuery('#mycarousel li').size() > 3) {
		jQuery('#mycarousel').append('<li/><li/><li/><li/><li/><li/><li/>');
	}

	$('#preview .carousel').css("visibility", "visible");

	var startIndex = readCookie("cmici");
	if (!startIndex || startIndex === "undefined")
		startIndex = 1;

	$("#topBanner a").click(function() {
		createCookie("cmici", 1);
	});

	$("#tags a").click(function() {
		createCookie("cmici", 1);
	});

	$(".back").click(function() {
		history.go(-1);
		return false;
	});

	// There are dummy items in the carousel plus one in the front and one at the back.
	//    var upperCarouselIndex = jQuery('#mycarousel li').size() - 2;

	var setStateNext = function(carousel) {
		write("setStateNext");
		carousel.shouldMoveNext = true;
		carousel.shouldMovePrev = false;
	};
	var setStatePrev = function(carousel) {
		write("setStatePrev");
		carousel.shouldMoveNext = false;
		carousel.shouldMovePrev = true;
	};
	var setStateStop = function(carousel) {
		write("setStateStop");
		carousel.shouldMoveNext = false;
		carousel.shouldMovePrev = false;
	};

	jQuery('#mycarousel').jcarousel({
		scroll: 1,
		animation: 750,
		buttonNextEvent: "mousedown",
		buttonPrevEvent: "mousedown",
		initCallback: function(carousel) {
			carousel.shouldMoveNext = false;
			carousel.shouldMovePrev = false;

			$(".jcarousel-next").mousedown(function() {
				write("next mousedown");
				setStateNext(carousel);
			});

			$(".jcarousel-next").bind("mouseup", function() {
				write("next mouseup");
				setStateStop(carousel);
			});

			$(".jcarousel-next").bind("mouseout", function() {
				write("next mouseout");
				setStateStop(carousel);
			});


			$(".jcarousel-prev").mousedown(function() {
				if (carousel.first > 1) {
					write("prev mousedown");
					setStatePrev(carousel);
				}
			});

			$(".jcarousel-prev").bind("mouseup", function() {
				write("prev mouseup");
				setStateStop(carousel);
			});

			$(".jcarousel-prev").bind("mouseout", function() {
				write("prev mouseout");
				setStateStop(carousel);
			});
		},
		start: startIndex,
		itemFirstInCallback: {
			onAfterAnimation: function(instance, element, index) {
				write("after animation:");
				write("--instance.shouldMoveNext=" + instance.shouldMoveNext);
				write("--instance.shouldMovePrev=" + instance.shouldMovePrev);
				write("--instance.last=" + instance.last);
				write("--instance.first=" + instance.first);
				write("--index=" + index);

				var atEndOfCarousel = $(".jcarousel-next:visible").length === 0;

				if (instance.shouldMoveNext && !atEndOfCarousel) {
					write("instance.next();");
					instance.next();
				}
				else if (instance.shouldMovePrev && instance.first > 1) {
					write("instance.prev();");
					instance.prev();
				}
				else {
					createCookie("cmici", index);
				}
			}
		}
	});

	$('#Suggestions').click(function() {
		if (!$(this).hasClass('touched')) {
			$(this).val('');
			$(this).addClass('touched');
		}
	});
	if ($('#Suggestions').val() === '') {
		$('#Suggestions').val('Let us know what you want to see on the all-new Camouflage website. More interactive stuff? More competitions?');
	}
});