(function($){

	$.SITE = {};

	$.SITE._makePopup = function($popup) {

		var $form = $popup.find("form"),
			$submit = $popup.find("a.submit");

		$popup.data("opts", {
			resizable: false,
            modal: true,
            closeOnOverlay: true,
            dialogueClass: 'dark',
            width: 600,
            title: "Request a demo",
            handle: '.ui-dialogue-title',
            open: function(event, ui) {
                $.SITE.uniform(this);
            }
		});
		
		var validator = $form.validieren({
            debug: true,
            rules: {
                name: "required",
                lastname: "required",
                email: "required email",
                country: "required",
                state: {
                	required: function() {
                		return $form.find("select[name=country]").val() == "United States";
                	}
                }
            },
            messages: {
                name: "",
                lastname: "",
                email: "",
                country: "",
                state: ""
            },
            submitHandler: function(form) {
            	form.submit();
            }
        }, true);

		$submit.click(function(){
			$form.submit();
			return false;
		});

		return $popup;
	}

	$.SITE.bindButtons = function() {
		$("a.big-button, a.small-button")
			.mousedown(function(){
				$(this).addClass("click");
			})
			.mouseup(function(){
				$(this).removeClass("click");
			});
	};

	$.SITE.uniform = function(context) {
		$("input:visible, select:visible, textarea:visible", context).not(".no-uniform").uniform();
	};

	$.SITE.indexPage = function() {
		$.SITE.bindButtons();
		$.SITE.uniform();

		// ------------------------------ Email Subscribe -----------------------------

		var $emailSubscribeForm = $("#email-subscribe"),
			$emailSubscribeInput = $("#email-subscribe").find("input[name=email]"),
			emailSubscribeInitialText = $emailSubscribeInput.val(),
			$subscribeButton = $("#email-subscribe").find("a.subscribe");

		$emailSubscribeInput.focus(function(){
			if ($emailSubscribeInput.val() == emailSubscribeInitialText)
				$emailSubscribeInput.val("");
		}).blur(function() {
			if (!$emailSubscribeInput.val())
				$emailSubscribeInput.val(emailSubscribeInitialText);
		});

		$emailSubscribeForm.validate({
            debug: true,
            rules: {
                email: "required email"
            },
            messages: {
                email: ""
            },
            submitHandler: function(form) {
            	form.submit();
            }
        });

        $subscribeButton.click(function(){ $emailSubscribeForm.submit(); return false; });


        $popup = $.SITE._makePopup($("#popup"));

        $("#try-it").click(function(){
        	$popup.find("input[name=trial-or-what]").val("trial");
			$popup.dialogue($.extend({}, $popup.data("opts"), {
				title: "Request a demo"
			}));
			return false;
		});
		
		/*
		$("#buy-now").click(function(){
        	$popup.find("input[name=trial-or-what]").val("buy-now");
			$popup.dialogue($.extend({}, $popup.data("opts"), {
				title: "Buy Now"
			}));
			return false;
		});
		*/
		
	};


	$.SITE.featuresPage = function() {
		$.SITE.bindButtons();
		
		var scrollTarget = $("#scroll-pane"),
			scrollDuration = 500,
			onBefore = function(e, anchor, $target){
				$("#page-navigation li").removeClass("active");
				if (e) {
					$(e.currentTarget).closest("li").addClass("active");
				} else {
					var link = $("#page-navigation").find("a[href=#"+$(anchor).attr("id")+"]");
					link.closest("li").addClass("active");
				}
			},
			options = {
				target: scrollTarget,
				stop: true,
				hash: true,
				duration: scrollDuration,
				onBefore: onBefore
			};
	
		var initial = true;
		$.History.bind(function(state){
			if (!initial)
				$.localScroll.hash(options);
			initial = false;
		});
		
		$.localScroll.hash(options);
		$.localScroll(options);

		$("#scroll-pane .pane").each(function(){
			var id = $(this).attr("id");
			$(this).find("a.thumbnail")
				.attr('rel', 'gallery-'+id)
				.fancybox({
					centerOnScroll: true,
					hideOnContentClick: true,
					titlePosition: 'over',
					showNavArrows: true
				})
				.append("<span></span>");
		});
	}

	$.SITE.singleFeaturePage = function() {
		$.SITE.bindButtons();
		
		$("a.thumbnail")
			.attr('rel', 'gallery')
			.fancybox({
				centerOnScroll: true,
				hideOnContentClick: true,
				titlePosition: 'over',
				showNavArrows: true
			})
			.append("<span></span>");
	}

	$.SITE.templatesPage = function() {
		$("#templates-scroller").serialScroll({
			target: '#templates-scroller-wrap',
			items: 'li',
			prev: $("#templates-scroller").find(".prev"),
			next: $("#templates-scroller").find(".next"),
			axis: 'x',
			constant: false,
			cycle: true,
			force: true,
			duration: 500,
			stop: true,
			offset: -230,
			lock: false,
			start: 1
		});
		$("#templates-scroller-wrap").find("a.thumbnail").attr("rel", "gallery").fancybox({
			autoScale: false
		});

		$popup = $.SITE._makePopup($("#popup"));

        $("#try-it-banner").click(function(){
        	$popup.dialogue($.extend({}, $popup.data("opts"), {
				title: "Request a demo"
			}));
			return false;
		});
	}



	$.SITE.contactPage = function() {
		$.SITE.bindButtons();
		$.SITE.uniform();

		var $contactForm = $("#contact-form"),
			$sendButton = $contactForm.find("a.send");
		
		var validator = $contactForm.validieren({
            debug: true,
            rules: {
                name: "required",
                email: "required email",
                subject: "required",
                message: "required"
            },
            messages: {
                name: "required",
                email: "required email",
                subject: "required",
                message: "required"
            },
            submitHandler: function(form) {
            	form.submit();
            }
        }, true);

        $sendButton.click(function(){
			$contactForm.submit();
			return false;
		});
    }

    $.SITE.pricesPage = function() {
		$.SITE.bindButtons();
		$.SITE.uniform();

		$popup = $.SITE._makePopup($("#popup"));
		var $pricingPlan = $("<input type='hidden' name='pricing-plan'/>");
		$popup.find("form").prepend($pricingPlan);

		$(".pricing-grid .buttons a").click(function(){
        	var $this = $(this);
        	var title;
			
			if ($this.is(".trial")) {
        		$popup.find("input[name=trial-or-what]").val("trial");
        		title = "Request a Trial";
        		$pricingPlan.val("");
        	} else if ($this.is(".business")) {
        		$popup.find("input[name=trial-or-what]").val("buy-now");
        		title = "Buy a Business plan";
        		$pricingPlan.val("business");
        	} else if ($this.is(".team")) {
        		$popup.find("input[name=trial-or-what]").val("buy-now");
        		title = "Buy a Team plan";
        		$pricingPlan.val("team");
        	} else if ($this.is(".solo")) {
        		$popup.find("input[name=trial-or-what]").val("buy-now");
        		title = "Buy a Solo plan";
        		$pricingPlan.val("solo");
        	}
			$popup.dialogue($.extend({}, $popup.data("opts"), {
				title: title
			}));
			return false;
		});
	};















    $.fn.validieren = function(options, createMessages) {
    	var self = this;
        if (createMessages) {
        	$.each(options.rules, function(name){
        		self.find(":input[name="+name+"]").each(function(){
	                $(this).data("error-element", $("<span class='validation-message'/>").insertAfter(this));
	            });
        	});
        }
        var opts = $.extend({
            errorClass: "input-validation-error",
            errorElement: "span",
            errorPlacement: function (error, element) {
                var messageSpan = element.data("error-element");
                $(messageSpan).empty();
                $(messageSpan).removeClass("field-validation-valid");
                $(messageSpan).addClass("field-validation-error");
                error.removeClass("input-validation-error");
                error.data("_for_validation_message", messageSpan);
                error.appendTo(messageSpan);
            },
            success: function (label) {
                var messageSpan = label.data("_for_validation_message");
                $(messageSpan).empty();
                $(messageSpan).addClass("field-validation-valid");
                $(messageSpan).removeClass("field-validation-error");
            },
            highlight: function(element, errorClass, validClass) {
                $(element).removeClass(validClass).addClass(errorClass);
                $(element).parents(".label").addClass("validation-error");
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass(errorClass).addClass(validClass);
                $(element).parents(".label").removeClass("validation-error");
                $(element).trigger("unhighlight", { errorClass: errorClass, validClass: validClass });
            }
        }, options);

        return this.validate(opts);
    }

})(jQuery);