var settings = new Array();
settings['registrationConfirm'] = 'Geef uw gekozen wachtwoord nogmaals op om uw registratie te bevestigen:<input id="passwordConfirm" type="password"/><input type="submit" value="Registratie bevestigen" class="button">';

var Effects = {
	highlight: function(p) {
  		p.effect("highlight", {color:'#bef3ff'}, 1650);
	}
};

var Bar = {

	init: function() {
		this.login = $('#barWrapper form p:first').html();
		$('#barWrapper form div:first').bind('click', function(e){
 	 		$('#barWrapper')
				.hide()
 	 			.stopTime('shake');
			Bar.makeLogin();	
   		});
		this.makeLogin();
	},

	shake: function(end) {
		if (Bar.shakking)
			return;
		Bar.shakking = true;
		$("#barWrapper").effect('shake', {direction:'down', times:3, distance:12}, 120, function() {
			Bar.shakking = false;
			if (end != undefined)
				end();
		});
		
	},

	focusRegistrationConfirm: function() {
			$("#passwordConfirm").focus();
	},
	
	showRegistrationConfirm: function(form) {
		$('#barWrapper form p:first').html(settings['registrationConfirm']);
		$('#barWrapper')
	 		.addClass('middle')
	 		.show()
 	 		.everyTime(4500, 'shake', function() {
				Bar.shake(Bar.focusRegistrationConfirm);
  	 		});
 	 	$("#passwordConfirm")
 	 		.focus()
 	 		.keypress(function (e) {
 	 			$('#barWrapper').stopTime('shake');
 			});
			$("#barWrapper form").submit(function () {
				$("#barWrapper").stopTime('shake');
				if ($("#passwordConfirm").val() != $('input[name|="user[password]"]').val()) {
					Bar.shake(Bar.focusRegistrationConfirm);
					return false;
				}
				$('input[name|="user[password_confirmation]"]').val($("#passwordConfirm").val());
				form.submit();
				return false;
 				});
	},
	
	focusLogin: function() {
			if ($('[name=username]').val() == '')
				$('[name=username]').focus();
			else
				$('[name=password]').focus();
	},
	
	makeLogin: function() {
		$('#barWrapper form p:first').html(this.login);
		$('#barWrapper').removeClass('middle')
		//$('#barWrapper form')
		//	.unbind('submit')
		//	.submit(function () {
		//		Bar.shake(Bar.focusLogin);
		//		return false;
		//});
	}
};



$(function (){

	$.ajax({
  		url: '/elements.html',
  		success: function(html){
		    $('body').append(html);
		    Bar.init();
  		}
	});

	$('.loginLink').bind('click', function(e){
		$('#barWrapper').show();
		Bar.focusLogin();
		return false;
    });
    
	$("#user_new").validate({
	   rules: {
    	 'user[username]': {
    	   required: true,
	       minlength: 4
  	   },
    	 'user[email]': {
   	       required: true,
   	       email: true,
   	       remote: '/account/check_email'
 	    },
    	 'user[password]': {
  	       required: true,
   	       minlength: 6
    	 }
 	  },
   	messages: {
 	    'user[username]': {
  	       required: "Gebruikersnaam ontbreekt",
   	       minlength: jQuery.format("Minimum {0} tekens")
 	    },
	    'user[email]': {
   	       required: "Mailadres ontbreekt",
  	       email: "Ongeldig adres.",
  	       remote: "test"
   	    },
 	    'user[password]': {
   	       required: "Wachtwoord ontbreekt",
   	       minlength: jQuery.format("Minimum {0} tekens")
   	    }     
 	  },
 	  errorPlacement: function(error, element) {
	    var p = element.parent('p');
	    p.children().remove('span');
   	    $('<span></span>')
		 	.addClass("box")
		 	.appendTo(p)
	 		.append($('<span></span>').html(error.html()));
   	 },
   	 highlight: function(element, errorClass) {
    	 $(element).parent("p").addClass('wrong');
   	 },
  	 unhighlight: function(element, errorClass) {
 	    $(element).parent("p").removeClass('wrong')
    						  .children().remove('span');
  	 },
 	  submitHandler: function(form) {
 	  	 //form.submit();
  	 	 Bar.showRegistrationConfirm(form);
 	  }   
	});

    // setup plot
    function getData(x1, x2) {
        var d = [];
        for (var i = 0; i <= 25; ++i) {
            var x = x1 + i * (x2 - x1) / 50;
            d.push([x, (Math.sin(x)+2)*25]);
        }

        return [
            { label: "Brandstofverbruik Peugeot 206", data: d, color: "lightblue" }
        ];
    }

    var options = {
        legend: {
        	show: true,
        	position: "sw"
        },
        series: {
            lines: { show: true, fill: true, lineWidth: 2 },
            points: { show: false }
        },
        xaxis: { ticks: 9 },
        x2axis: { ticks: 9 },
        yaxis: { ticks: 6 },
        selection: { mode: "x" },
        grid: {
    		borderWidth: 1,
    		borderColor: "#d8d8d8",
    		labelMargin: 8,

			color: "#444",
			backgroundColor: "#fafafa",
			borderColor: "#fff",
			tickColor: "#ddd",
			borderWidth: 0,
			hoverable: true,
			autoHighlight: true,
			mouseActiveRadius: 50
  		}
    };

    var startData = getData(0, 3 * Math.PI);
    
    var plot = $.plot($("#plotTest div"), startData, options);
    
    $("#plotTest div").bind("plotselected", function (event, ranges) {
        // clamp the zooming to prevent eternal zoom
        if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
            ranges.xaxis.to = ranges.xaxis.from + 0.00001;
        if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
            ranges.yaxis.to = ranges.yaxis.from + 0.00001;
        
        // do the zooming
        plot = $.plot($("#plotTest div"), getData(ranges.xaxis.from, ranges.xaxis.to),
                      $.extend(true, {}, options, {
                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                          yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                      }));
        
        // don't fire event on the overview to prevent eternal loop
        overview.setSelection(ranges, true);
    });
    
    // Preloading
        // Inlogbar laden
        var cache = [];
	    var cacheImage = document.createElement('img');
    	cacheImage.src = '/login.png';
    	cache.push(cacheImage);

});
