$.autorijden = {

	licenPlateValue:null,

	init:function()
	{
		// init the various tabbed content sections
		$("ul.tabbedContent").tabs();
		$("#homepagetabs").tabs();
		$(".tabsHeader").css({"display":"none"});
		$("div.fbConnectWidgetTopmost").css({'border-top':'none'});
		$("#nieuwtag").css({
			'top':-35,
			'left':100,
			'display':'block'
		});

		// Animate the profile percentage-slider on the Mijn AutoRijden.nl page
		var percentageWidth = $("div#percentage").css("width");
		$("div#percentage").css({width:"0"});
		$("div#percentage").animate({width:percentageWidth},1000, "easeOutElastic");


		// Hide the info
		$("p.info").css({display:"none"});
		// Toggle info
		$("a.iconInfoLink").bind("click", function(){ $(this).next('.info').slideToggle(); return false;});

		// Toggle the login div
		$("#download_extensive").bind("click",function(){
			$("#checktype").val("extensive");
			setTimeOut(500,function(){
				$("#kentekenCheck").submit();
			}); // IE6 has to wait for a few ms...
			return false;
		});
		
		$("#print").bind("click", function(){
			$.fileMaps.printRoute();
			return false;
		});
		
		$("#print").hide();
		
		// Handle the click on a link with class=external
		$('a.external').bind('click', function() {
			window.open($(this).attr('href'));
			return false;
		});
		
		$("#kentekenCheck").bind("submit",function(){
                        if(trim($("#txtKenteken").val())=='') {
                                alert("U heeft geen kenteken ingevuld.");
                                return false;
                        } else {
                                return true;
                        }
                });

		//set focus to licenseplateForm
		if($('#txtKenteken') && !$('#txtKenteken').hasClass('noselect')){
			$('#txtKenteken').focus();
			$('#txtKenteken').bind('keyup', function(e) {$('#txtKenteken').val($('#txtKenteken').val().toUpperCase())} );
		}

		//set focus to licenseplateForm
		if($('#txtKenteken2') && !$('#txtKenteken2').hasClass('noselect')){
			$('#txtKenteken2').focus();
			$('#txtKenteken2').bind('keyup', function(e) {$('#txtKenteken2').val($('#txtKenteken2').val().toUpperCase())} );
		}
		
		//set focus to licenseplateForm
		if($('#txtKentekenPremie') && !$('#txtKentekenPremie').hasClass('noselect')){
			$('#txtKentekenPremie').focus();
			$('#txtKentekenPremie').bind('keyup', function(e) {$('#txtKentekenPremie').val($('#txtKentekenPremie').val().toUpperCase())} );
		}

		//set focus to licenseplateForm
		if($('#txtKentekenAankeiler') && !$('#txtKentekenAankeiler').hasClass('noselect')){
			$('#txtKentekenAankeiler').focus();
			$('#txtKentekenAankeiler').bind('keyup', function(e) {$('#txtKentekenAankeiler').val($('#txtKentekenAankeiler').val().toUpperCase())} );
		}

		//register keyup event on textinput licenseplateChecker and update accordingly
		$('#txtKenteken').bind("keyup", function(e){$.autorijden.parseLicensePlate($('#txtKenteken').val(),'normal');});
		$('#txtKenteken2').bind("keyup", function(e){$.autorijden.parseLicensePlate($('#txtKenteken2').val(),'normal');});
		$('#txtKentekenAankeiler').bind("keyup", function(e){$.autorijden.parseLicensePlate($('#txtKentekenAankeiler').val(),'aankeiler');});
		$('#btnInsuranceCheck').bind('click', function(e){$.autorijden.insuranceCheck()});
		$('#txtKentekenPremie').bind("keyup", function(e){$.autorijden.parseLicensePlate($('#txtKentekenPremie').val(),'normal');});

		if($('#postPaymentForm')) {
			validatePostPaymentForm();
		}

		if($('#blixemEmail')) {
			$('#blixemEmail').html('<a href="mailto:info@blixem.nl">info@blixem.nl</a>');
		}

		if($('#autorijdenEmail')) {
			$('#autorijdenEmail').html('<a href="mailto:info@autorijden.nl">info@autorijden.nl</a>');
		}
	},

	// this helper function parses the input of the licensplate inputfield and check if a valid combination has been entered
	parseLicensePlate: function(value,type){
  		rep = loopUntilMatch(value);
  		var newKtRgxp = new RegExp('^([a-zA-Z]{2}|[0-9]{2})-?([a-zA-Z]{2})-?([a-zA-Z]{1})([0-9]{1})$');
		var success = "false";
		if(newKtRgxp.test(rep)) {
  			rep = rep.replace(newKtRgxp,"$1-$2$3-$4");
  		}
		$.licensePlateValue = rep;
                if(type=="normal"){
                    if($.licensePlateValue.length == 8 && $('#optionsOverlay').css('display') != 'none') {
                            $('#txtKenteken').val($.licensePlateValue);
                            $('#txtKenteken2').val($.licensePlateValue);
                            $('#txtKentekenPremie').val($.licensePlateValue);
							success = "true";
                            $('#optionsOverlay').css({display:'none'});
                    } else if($.licensePlateValue.length != 8 && $('#optionsOverlay').css('display') == 'none') {
                            $('#optionsOverlay').css({display:'block'});
							success = "false";
                    }
                } else {
                    if($.licensePlateValue.length == 8 && $('#optionsOverlay').css('display') != 'none') {
                            $('#txtKentekenAankeiler').val($.licensePlateValue);
                            $('#optionsOverlay').css({display:'none'});
							success = "true";
                    } else if($.licensePlateValue.length != 8 && $('#optionsOverlay').css('display') == 'none') {
                            $('#optionsOverlay').css({display:'block'});
							success = "false";
                    }
                }
				return success;
	},


	//mollie payments
	//this function polls the database to see if the specified transaction has been fullfilled.
	// If not a message will be displayed and the function will poll the database every 2 seconds to get an update on the payment status
	ivrPoll: function()
	{
		if(!MollieTransaction){return false;}
		counter=0;
		$('body').everyTime(2000,'paymentTimer',function()
		{
			$.ajax({
				type:"GET",
				url:"/rapport/ivrCheckStatus?transaction="+ MollieTransaction,
				dataType:"xml",
				success: function(xml){
					$(xml).find('ivrResponse').each(function(){
						if($(this).find('isPaid').text()=='1') {
							$('body').stopTime('paymentTimer');
							window.location = '/rapport/postPayment/basic?transaction_id='+ MollieTransaction;
						}
						$('#ivrPaymentStatus').html($(xml).find('ivrResponse').find('responseBody').text());
					})
				}
			})
		})
	},

	//update insurance data and present links to alternative insurance companies
	insuranceCheck: function(){
		$('#insuranceLinks').html('<h3>Verzekeringen ...laden...</h3>Laden <img src="/images/ajax-loader.gif" alt="Een moment geduld"/>');
		var url = "/mijnautos/saveinsurancedata/" + $('#licenseplate').val() + "?insuranceType=" + $('#insuranceType').val() + "&insuranceCompany=" + $('#insuranceCompany').val() + "&monthPrice=" + $('#monthPrice').val() + "&noClaimYears=" + $('#noClaimYears').val() + "&ownRisk=" + $('#ownRisk').val();
		$.ajax({
				type:"GET",
				url: url,
				success: function(e){
					$('#insuranceLinks').html('<h3>Verzekeringen</h3><ul><li><a target="_blank" href="http://www.independer.nl/autoverzekering/intro.aspx?refer=autorijden" onclick="urchinTracker(\'/extern/independer/home/\');" title="Independer">Independer - verzekeringen vergelijken</a></li></ul>');
				}
		});
	},
	
	/*
	 * Bookmark link event handler
	 */
	bookMark: function(bookmarkURL, bookmarkTitle) {
		if (bookmarkURL == undefined) {
			bookmarkURL = "http://www.autorijden.nl/";
		}
		if (bookmarkTitle == undefined) {
			bookmarkTitle ="AutoRijden.nl";
		}

		try {
			if (document.all) {
				window.external.AddFavorite(bookmarkURL, bookmarkTitle);
			} else {
				window.sidebar.addPanel(bookmarkTitle, bookmarkURL, '');
			}
		} catch (e) {
			alert('Uw browser ondersteunt deze functie niet!');
		}
	},


	/*
	 * Set homepage event handler
	 */
	setHomePage: function(thing) {
		try {
			thing.style.behavior='url(#default#homepage)';
			thing.setHomePage(window.location);
		} catch (e) {
			alert('Uw browser ondersteunt deze functie niet!');
		}
	}
}

function loopUntilMatch(value)
{
	var rgxp =  new RegExp("([a-zA-Z0-9]{2}(?!-)(?=[a-zA-Z0-9]+))");
	if(!rgxp.test(value)){
		return value;
	} else {
		value = value.replace(rgxp,"$1-");
		return loopUntilMatch(value);
	}

}

/* function sloganAnimation
 * Handles the animation of the slogans in the header
 */

// How many repeats of the animation
var animationRepeats = 1;
var animationCounter = 0;

function sloganAnimation(){
	// Disable the color-hover on the "Check/Beheer/Bespaar" links
	$("ul#headerSlogans li a").css({"color":"#000000","cursor":"default"});
	// Display all slogans, users with no JS see the slogans on hover
	// For some reason this doesn't work with multiple selectors
	$("em#slogan1").css({"left":"1500px","display":"block","background":"#3590c3"});
	$("em#slogan2").css({"left":"1500px","display":"block","background":"#3590c3"});
	$("em#slogan3").css({"left":"1500px","display":"block","background":"#3590c3"});
	activateSlogan(1);
	setTimeout("activateSlogan(2)",3500);
	setTimeout("activateSlogan(3)",7000);
}

/* function activateSlogan
 * @param id - the number of the slogan (1,2 or 2)
 * Animates the slogan sliding into the screen & hiding the previous one.
 */

function activateSlogan(id){
	$("ul#headerSlogans li a").removeClass("active"); // remove all "active" classes
	$("#action" + id).parent().addClass("active");

	// Hide previous slogan
	if(id == 2){
		hideSlogan(1);
	} else if(id == 3){
		hideSlogan(2);
	}

	// Animate the slogan - if it's the last slogan, hide it after 2000 ms.
	$("#slogan" + id).animate({ "left" : "0px" }, 2500, "easeInOutElastic",function(){
		if(id == 3){
			animationCounter++;
			setTimeout("hideSlogan(3)",2000);
		}
	});
}

/* function hideSlogan
 * @param id - the number of the slogan (1,2 or 3)
 * Animates the slogan sliding out of the screen
 */

function hideSlogan(id){
	$("em#slogan" + id).animate({ "left" : "-1500px" }, 1500, "easeInOutElastic");
	if(id == 3){
		if(animationCounter <= animationRepeats){
			sloganAnimation();
		} else { // reset
			$("ul#headerSlogans li a").css({"cursor":"pointer"});
			$("#action1").parent().addClass("active");
			$("#action3").parent().removeClass("active");
			$("em#slogan1").css({"left":"0px","display":"block"});
			$("#action1").bind("mouseover",function(){ hoverSlogan(1) });
			$("#action2").bind("mouseover",function(){ hoverSlogan(2) });
			$("#action3").bind("mouseover",function(){ hoverSlogan(3) });
		}
	}
}

/* function hoverSlogan
 * @param id - the number of the slogan (1,2 or 3)
 */

function hoverSlogan(id){
	$("ul#headerSlogans li a em").css({"display":"none"});
	$("em#slogan" + id).css({"display":"block","left":"0px"});
	$("ul#headerSlogans li a").removeClass("active");
	$("#action" + id).parent().addClass("active");
}

function trim(value) {
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  return value;
}

$(function(){
	$.autorijden.init();
	sloganAnimation();
});

function submitHomepage(checkType){
	$('#kentekenCheck').unbind('submit');
	$('#checktype').val(checkType);
	$('#txtButton').val('true');
	
	//if($("#txtKenteken").val() == ""){
		//alert("U heeft geen kenteken ingevuld.");
	//}
	
	$('#kentekenCheck').submit();
}

