var lastpage = 5;
var carousel = null;
var blocked_routes = null;

$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();
  $.each(a, function()
  {
    if (o[this.name])
    {
      if (!o[this.name].push) o[this.name] = [o[this.name]];
      o[this.name].push(this.value || '');
    }
    else
    {
      o[this.name] = this.value || '';
    }
  });

  return o;
};

function adjust_ui()
{
    $('#next').show();
    $('#prev').show(); 
    $('#sendBud').hide(); 
    $("#button-container").show();
    if (carousel.current == 0) 
    {
        $("#button-container").hide();
        $('#prev').hide(); 
        $('#next').hide();
    }else if (carousel.current == 1)
    {
            var whenw = $("#workwhen input[name='when']:checked").val();
            if (whenw == 'sat' || whenw == 'sat_sun' )
            {
                addStartDates(6);                        
            }else
            {
                addStartDates(0);    
            }
            if ($("#satroute").val() == "dorr")
            {
                $("#your-sel-route-sat").hide();
                $("#your-sel-route-sun").hide();
            }else
            {
                if (whenw == 'sat_sun' )
                {
                    $("#your-sel-route-sat").show().html($("#your-route-sat").html());
                    $("#your-sel-route-sun").show().html($("#your-route-sun").html());
                }else if (whenw == 'sun'  )
                {
                    $("#your-sel-route-sat").hide();
                    $("#your-sel-route-sun").show().html($("#your-route-sun").html());
                }else
                {
                    $("#your-sel-route-sat").show().html($("#your-route-sat").html());;
                    $("#your-sel-route-sun").hide();    
                }
            }
    }else if(carousel.current == 2)
    {
        $('#next').hide();
        $('#sendBud').show();
    }else if(carousel.current == 3)
    {
        $("#button-container").hide();
    }else{
        $('#next').html('Videre')
    }
  /*
  if (carousel.current == lastpage - 1)
  {
    $('#next').html('Send skjema');
    $('#next').css('background-color', '#cfc');
  }
  else if (carousel.current == lastpage)
  {
    $('#prev').hide();
    $('#next').hide();
  }
  else
  {
    $('#next').html('Neste side');
    // $('#next').css('background-color', 'white');
  }
  */

  function transition(v, c1, c2)
  {
    var name = $(v).find('img.num').attr('src');
    $(v).find('img.num').attr('src', name.replace(c1, c2));

    if ($(v).find('img.arrow').length)
    {
      name = $(v).find('img.arrow').attr('src');
      $(v).find('img.arrow').attr('src', name.replace(c1, c2));
    }
  }

  $('#progress td').each(function(k, v)
  {
    if (k <= carousel.current)
    {
      transition(v, 'gray', 'green');
      $(v).addClass('active');
    }
    else
    {
      transition(v, 'green', 'gray');
      $(v).removeClass('active');
    }
  });
}

function chomp(text)
{
  return text.replace(/(\n|\r)+$/, '');
}

function selectRoute( code , day)
{
    txt = $("#route_" +code).find('.routeinfo .name').html();
    dropID = $("#route_" +code).find('.routeinfo .dropid').html();
    dropPlaceSat = $("#route_" +code).find('.routeinfo .dropnamesat').html();
    dropPlaceSun = $("#route_" +code).find('.routeinfo .dropnamesun').html();
    
    if (day == "clear_sat")
    {
        $("#your-route-sat").removeClass('active').find('.myroute').html("");
        $("#satroute").val("");
        $("#satroutetxt").val("");
        $("#satroutedrop").val("");
        $("#satroutedroptxt").val("");
        $("#your-route-sat .img").html("<img src='/resources/images/sitegraphics/noroutebg.png'>");
    }
    
    if (day == "clear_sun")
    {
        $("#your-route-sun").removeClass('active').find('.myroute').html("");
        $("#sunroute").val("");
        $("#sunroutetxt").val("");
        $("#sunroutedrop").val("");
        $("#sunroutedroptxt").val("");
        $("#your-route-sun .img").html("<img src='/resources/images/sitegraphics/noroutebg.png'>");
    }
    
    if (day == "sat" || day == "both")
    {
        $("#your-route-sat").addClass('active').find('.myroute').html(txt+'<br/>Henteplass:<br/>'+dropPlaceSat);
        $("#satroute").val(code);
        $("#satroutetxt").val(txt);
        $("#satroutedrop").val(dropID);
        $("#satroutedroptxt").val(dropPlaceSat);
        $("#route_" +code).effect( 'transfer' ,{to: "#your-route-sat .img" ,className:'transfer'},500 ,function(){
            //$("#your-route-sat .img img").attr('src',$(this).find('img').attr('src')) ;
           $("#your-route-sat .img").load('/getRouteImg?i='+code)
        });
    }
    
    if (day == "sun" || day == "both")
    {
        $("#your-route-sun").addClass('active').find('.myroute').html(txt+'<br/>Henteplass:<br/>'+dropPlaceSun);
        $("#sunroute").val(code);
        $("#sunroutetxt").val(txt);
        $("#sunroutedrop").val(dropID);
        $("#sunroutedroptxt").val(dropPlaceSun);
        $("#route_" +code).effect( 'transfer' ,{to: "#your-route-sun .img" ,className:'transfer'},500 ,function(){
            //$("#your-route-sun .img img").attr('src',$(this).find('img').attr('src')) ;
            $("#your-route-sun .img").load('/getRouteImg?i='+code)
        });
    }
}

function validateRouteDate(who,when , day)
{
    if (day == 11 && when == 'sat_sun' && who == 'sat_sun' )
    {
        return true;
    }
    
    if ((day == 5 || day == 11) && (when == 'sat' || when == 'sat_sun') && who == 'sat' )
    {
        return true;    
    }
    
    if ((day == 6 || day == 11) && (when == 'sun' || when == 'sat_sun') && who == 'sun' )
    {
        return true;    
    }
}


function checkRoutes( code )
{
    if (code.length != 4)
    {
        $('#postnr').addClass('warn');
        $('.warn:first').focus();
        return;
    }
    else
    {
        $('#postnr').removeClass('warn');
    }

    $("#select-route-txt").hide();    
    $("#select-route").show().html("søker...");
    $.post("/getRoutes" , 'routes='+code , function(data){
        a = eval('(' + data + ')');
        if( typeof a == "string")
        {
            $("#select-route").show().html("feil i søkning. <br/><br/><small>hint:dd4-webservice-finn-ledige-ruter</small>");    
            return;
        }
        
        $.template( "routetmpl", $("#route-tmpl") );

        data = {}
        data['when'] = $("#workwhen input[name='when']:checked").val();
        b = new Array()
        for (var i = 0 ; i < a.length ; i++)
        {
            route = null;
            var newitem = true;
            for (var ii = 0 ; ii < b.length ; ii++)
            {
                if (b[ii].id == a[i].salgsRute.salgsruteId) 
                {         
                    newitem = false;
                    var drop="";
                    var dropt="";       
                    if (a[i].ukedag == 6)
                    {
                        if ( a[i].salgsRute.dropPunkt )
                        {
                            drop=a[i].salgsRute.dropPunkt.dropPunktId
                            dropt=a[i].salgsRute.dropPunkt.navn
                        }
                        
                        b[ii]['sun'] = { 'free':true , 'drop':drop , 'droptxt':dropt}
                    }else
                    {
                        if ( a[i].salgsRute.dropPunkt )
                        {
                            drop=a[i].salgsRute.dropPunkt.dropPunktId
                            dropt=a[i].salgsRute.dropPunkt.navn
                        }
                        
                        b[ii]['sat'] = { 'free': true , 'drop':drop , 'droptxt':dropt}
                    }
                    b[ii].ukedag = 11;
                }
            }
            
            if ( newitem )
            {
                route = {'id':a[i].salgsRute.salgsruteId ,'ukedag':a[i].ukedag, 'name':a[i].salgsRute.navn, 'sat':null, 'sun':null}
                //b[b.length] = a[i];  
                var drop="";
                var dropt="";
                if (a[i].ukedag == 6)
                {
                    if ( a[i].salgsRute.dropPunkt )
                    {
                        drop=a[i].salgsRute.dropPunkt.dropPunktId
                        dropt=a[i].salgsRute.dropPunkt.navn
                    }
                    route['sun'] = { 'free': true , 'drop':drop , 'droptxt':dropt}
                }else
                {
                    if ( a[i].salgsRute.dropPunkt )
                    {
                        drop=a[i].salgsRute.dropPunkt.dropPunktId
                        dropt=a[i].salgsRute.dropPunkt.navn
                    }
                    route['sat'] = { 'free': true , 'drop':drop , 'droptxt':dropt}
                }
                route['old'] = a[i]
                b[b.length] = route;  
            }
        }

        a = []
        for (var r in b)
        {
            if (isRouteBlocked(b[r].id, 0)) { b[r].sat = null; b[r].ukedag -= 5; }
            if (isRouteBlocked(b[r].id, 1)) { b[r].sun = null; b[r].ukedag -= 6; }
            if (b[r].sat || b[r].sun) a.push(b[r]);
        }

        // a = b;

        b = new Array();
        for (var i = 0 ; i < a.length ; i++)
        {
            if(a[i].ukedag == 6 )
            {
                if (data['when'] == 'sun' || data['when'] == 'sat_sun')
                {
                    b[b.length] = a[i]
                }
            }else if(a[i].ukedag == 11)
            {
                b[b.length] = a[i];
            }else
            {
                if (data['when'] == 'sat' || data['when'] == 'sat_sun')
                {
                    b[b.length] = a[i]
                }  
            }
        }
        
        data['routes'] = b;
        $( "#select-route" ).html( $.tmpl( "routetmpl", data ) );
        $("#select-route .small-img").each(
            function()
            {
                $(this).addClass('loading').load('/getRouteImg?i=1&a='+$(this).parent().attr('id'),function(){ $(this).removeClass('loading')})
            }
        );
        
       // $('#select-route a').lightBox({fixedNavigation:true});
        
    })
}

function showProblem(passedtxt)
{
    var obj = $('#problemwrapper').html(passedtxt).fadeIn();
    obj.css("top", ( $(window).height() - obj.height()-100 ) / 2+$(window).scrollTop() + "px");
    obj.css("left", ( $(window).width() - obj.width() ) / 2+$(window).scrollLeft() + "px");
    window.setTimeout( "$('#problemwrapper').fadeOut()" , 3000);
    return false;
}


function showMapImage(szFile,routeid)
{
    $("#loadingwrapper").show();
    var obj = $('#imagewrapper').fadeIn();
    obj.css("top", "30px");
    obj.css("left", ( $(window).width() - obj.width() ) / 2+$(window).scrollLeft() + "px");
    szroute=$("#route_"+routeid).find(".routeinfo .name").html() + " = rutenr. " +routeid
    
    var img = $("<img />").attr('src', szFile)
        .css('width','900px')
        .css('margin','22px').
        css('border','1px solid black').error(
        function()
        {   
            var sz = "Vi har ikke fått laget kart for denne ruten. Vi setter pris på om du sender oss en mail via kontaktskjemaet under Kontakt oss med at rutenr "+ routeid + " mangler kart. "
            $('<p style="color:black;padding:60px;padding-top:160px;">'+sz+'</p>').insertBefore($("#imagewrapper").find('img'))
            $("#imagewrapper").find('img').remove();
        }
    );
    
    obj.html("").append(img).append('<div style="margin-right:10px;margin-left:10px;height:40px;"><span style="color:black;clear:both;">'+ szroute +'</span><button style="float:right;" class="black" onclick="return false;">Lukk</button></div>').click(function(){$(this).hide();$("#loadingwrapper").hide()})
}
/*
function get_place(postcode, fn_success)
{
  $.ajax({
    type: 'GET',
    url: 'getPostPlace?postcode=' + postcode,
    success: function(data) {
      data = chomp(data)
      //alert('PostPlace! ' + data + ']');
      if (data == 'INVALID')
        $('#postcode').addClass('warn');
      else
      {
        fn_success(data);
        $('#postcode').removeClass('warn');
      }
    }
  });
}
*/


function submit_form()
{
    //url: '/bli_bud/nytt_bud/submit_bud',
    if (validate())
    {
        ui_loading({txt:'Sender info..'});
        var data = $('#reg').serializeObject();
        $.ajax({
            type: 'POST',
            
            //url: '/templates/bli_bud/nytt_bud/createbud',
            url: '/bli_bud/nytt_bud/submit_bud',
            data: data,
            success: function(data)
                 {
                     if ($.trim(data) == '@ok')
                     {
                        $("#loadingdialog").html('<p>Informasjon motatt</p>');
                        window.setTimeout(function () {
                            ui_loading();
                            $("#next").trigger("click");
                        }, 1500);     
                    }else
                    {
                        $("#loadingdialog").html('<p>Feil, prøv igjen</p>')    
                        window.setTimeout(function () {
                             ui_loading();
                        }, 3000);   
                    }
                 },
            error: function()
            {
                $("#loadingdialog").html('<p>Feil, prøv igjen</p>')    
                window.setTimeout(function () {
                    ui_loading();
                }, 3000);                    
            }
      });
    }
}

function isRouteBlocked(route, day)
{
    for (var r in blocked_routes)
    {
        var blocked = blocked_routes[r];
        if (route == blocked.route_id && day == blocked.day) return true;
    }

    return false;
}

function validate()
{
  var passed = true;
  page = carousel.items[carousel.current];

    if (carousel.current == 0)
    {
        var whenw = $("#workwhen input[name='when']:checked").val();
        passedtxt = ""
        if (whenw == 'sat_sun')
        {
            if ($("#satroute").val() == "" || $("#sunroute").val() == "")
            {
                var szr = "";
                if ( $("#satroute").val() == "" )
                {
                    szr = "Lørdag" ;
                }
                
                if ( $("#sunroute").val() == "")
                {
                    if (szr.length!=0){ szr = szr + "/" }
                    szr = szr + "Søndag"    
                }
                passedtxt="Du har markert at du ønsker å gå både lørdag og søndag, men ikke valgt noen "+szr+"rute. Legg til riktig rute for at gå vidare."
                passed = false;
            }
        }else if (whenw == 'sun')
        {
            if ( $("#sunroute").val() == "")
            {
                passedtxt="Du har markert at du ønsker søndagsrute, men ikke valgt søndagsrute. Legg til riktig rute for at gå vidare."
                passed = false;
            }
        }else
        {
            if ($("#satroute").val() == "" )
            {
                passedtxt="Du har markert at du ønsker lørdagssrute, men ikke valgt lørdagsrute. Legg til riktig rute for at gå vidare."
                passed = false;
            }
        }

        if (!passed)
        {
            showProblem(passedtxt);
           //$("input[name='postnummer']").val("")
        }
        else
        {
            var sat_route = $('#satroute').val();
            var sun_route = $('#sunroute').val();

            passedtxt = '';

            if (isRouteBlocked(sat_route, 0)) passedtxt = 'Blocked: Saturday\n';
            if (isRouteBlocked(sun_route, 1)) passedtxt += 'Blocked: Sunday\n';

            if (passedtxt.length > 0) 
            {
                passed = false;
                showProblem(passedtxt);
            }
        }
    }

  $(page).find('.force input[type=text]:visible').each(function(k, v)
  {
    var fail = false;
    var type = $(v).attr('type');
    var name = $(v).attr('name');
    var val = $(v).val();

    if (val == '') fail = true;

    if ($(v).attr('id') == 'postcode')
    {
      var re = /\d{4}/;
      if (val.length != 4 || !re.test(val)) fail = true;
    }
    else if ($(v).attr('id') == 'email')
    {
      if (val.indexOf('@') == -1) fail = true;
    }
    else if ($(v).attr('id') == 'kontonr')
    {
      if ( $(v).val().length != 11 ) fail = true;
    }else if ($(v).attr('id') == 'fodselsdato')
    {
      if ( !validateBirthNumber( $(v).val() ) ) fail = true;
    }else if ($(v).attr('id') == 'email2')
    {
      if ($('#email').val() != val) fail = true;
    }

    if (fail)
      { $(v).addClass('warn'); passed = false; }
    else
      $(v).removeClass('warn');
  });

  $(page).find('.force .checkboxes').each(function(k, div)
  {
    cb_all = {};
    cb_checked = {};

    $(div).find('input[type=checkbox]').each(function(k, v) { cb_all[$(v).attr('name')] = true; });
    $(div).find('input[type=checkbox]:checked').each(function(k, v) { cb_checked[$(v).attr('name')] = true; });

    for (c in cb_all)
    {
      if (!cb_checked.hasOwnProperty(c))
      {
        $(div).addClass('warn');
        passed = false;
      }
      else
      {
        $(div).removeClass('warn');
      }
    }
  });

  $(page).find('.force input[type=file]:visible').each(function(k, v)
  {
    $(v).removeClass('warn');

    if (!$(v).val())
    {
      $(v).addClass('warn');
      passed = false;
    }
  });

  if (!passed) $('.warn:first').focus();

  return passed;
}

function addStartDates(day)
{
    if (new Date().getDay() < 3)
    {
        adjustments = 0    
    }else
    {
        adjustments = 7 
    }
    
    szd = szDate.split("-");
    var calcDate = new Date()
    calcDate.setFullYear(szd[0],parseInt(szd[1])-1,szd[2]);
    
    $("#posdates").html(
    $("<select name='posdates'>").append(
        $('<option>').html($.datepicker.formatDate('dd.mm.yy',findNearest( new Date(calcDate) , day ,  adjustments )))
    ).append(
        $('<option>').html($.datepicker.formatDate('dd.mm.yy',findNearest( new Date(calcDate)  , day ,  (adjustments+8) )))    
    ).append(
        
        $('<option>').html($.datepicker.formatDate('dd.mm.yy',findNearest( new Date(calcDate)  , day ,  (adjustments+16) )))
    )
)
}

$(document).ready(function()
{
    if ($("#progress").length == 1)
    {
        $.ajax({url: '/getBlockedRoutes', async: false, success:
            function(data)
            {
                blocked_routes = JSON.parse(data);
            }
        });
    }
    carousel = $('#form-pages').carousel({ transmode:'dissolve', transition: .5 });      
    adjust_ui();
    $("#your-routes .img").each(
        function()
        {
            $(this).mouseover(function(){$(this).addClass('remove')});
            $(this).mouseout(function(){$(this).removeClass('remove')});
            $(this).click(function()
            {
                $(this).find('img').attr('src','/resources/images/sitegraphics/noroutebg.png');
                $(this).parent().removeClass('active').find('.myroute').html('');
                if($(this).parent().attr('id').indexOf('sat')!= -1)    
                {
                    $("#satroute").val("");
                    
                }else
                {
                    $("#sunroute").val("")
                }
            });
        }
    );  
    
    $("#postnr").keydown(function(evt){if(evt.keyCode==13){checkRoutes($('#postnr').val());return false;}})
    $("#workwhen *").click(
        function()
        {
            if ( $(this).val() == "sat" )
            {
                $("#your-route-sun").fadeTo('slow',0.2)
                $("#your-route-sat").fadeTo('fast',1)
                selectRoute('','clear_sun')
            }else if ($(this).val() == "sun")
            {
                $("#your-route-sat").fadeTo('slow',0.2)
                $("#your-route-sun").fadeTo('fast',1)
                selectRoute('','clear_sat')
            }else
            {
                $("#your-route-sun").fadeTo('fast',1)
                $("#your-route-sat").fadeTo('fast',1)
            }
        }
    )
  // highlight_item(1);
    $('#skip').click(function()
    {
        if($("#wantto:checked").length != 1)
        {showProblem('Du har ikke valgt rute eller valgt at Dagbladet Bud skal velge rute for deg. Legg inn valg før du går videre.');return false;}
        $("#postnr").val('0000');
        selectRoute('','clear_sat')
        selectRoute('','clear_sun')
        $("#satroute").val('dorr');
        $("#sunroute").val('dorr')
        $("#next").trigger('click');
        return false;
    });
    
  $('#next').click(function()
  {
    if (validate())
    {
        if (carousel.current == 2)
        {
            $("#button-container").hide();    
        }
        
        if ( carousel.current == 0 )
        {
            $("#nyttbud_license").load("/templates/default/bli_bud/nytt_bud/vilkar_avtale_for_engasjement_som_salgsbud_hos_dorsalg_as_for_dagbladet_as/license");
        }else if ( carousel.current == 2 )
        {
            vav = $('#reg').serializeObject();
            $.template( "rtemplate", $("#recite-route-tmpl") );
            $( "#routeinfo" ).html( $.tmpl( "rtemplate", vav ) );
            $.template( "rtemplate", $("#recite-tmpl") );
            $( "#yourinfo" ).html( $.tmpl( "rtemplate", vav ) );
            $.template( "rtemplate", $("#recite-parents-tmpl") );
            $( "#parentinfo" ).html( $.tmpl( "rtemplate", vav ) );
            
            if (vav.when == 'sat_sun')
            {
                vav.days = "lørdag og søndag"    
            }else if( vav.when == 'sat' )
            {
                vav.days = "lørdag"    
            }else{
                vav.days = "søndag"    
            }
            $.template( "rtemplate", $("#recite-hva-tmpl") );
            $( "#hvaskjertxt" ).html( $.tmpl( "rtemplate", vav ) );
            
        }
        
    carousel.next();
    adjust_ui();
    }
  });

  $('#prev').click(function()
  {
    carousel.prev();
    adjust_ui();
    $("#next").html("Videre");
  });

  //

  // $('.explanation').each(function()
  // {
  //   var expl_left = 0;
  //   //$(this).css({ bottom: 2, left: expl_left });
  //   //$(this).css({ bottom: 0 });
  // });

  //

  var show_explanation = function()
  {
    var ex = $(this).parent().find('.explanation');
    if ($(ex).css("display") == "none") $(ex).animate({ opacity: 'toggle', left: '-=10' }, 250);
  }

  var hide_explanation = function()
  {
    var ex = $(this).parent().find('.explanation');
    if ($(ex).css("display") != "none") $(ex).animate({ opacity: 'toggle', left: '+=10' }, 250);
  }

  $('.warn').live('focus', show_explanation);
  $('.warn').live('blur',  hide_explanation);

  $('.checkboxes.warn').live('mouseenter', show_explanation);
  $('.checkboxes.warn').live('mouseleave', hide_explanation);

  $('[name=omfattet]').click(function()
  {
    ta = $('#omfattet_' + $(this).val());
    if ($(this).is(':checked')) ta.slideDown(); else ta.slideUp();
  });

  $('textarea').focus(function() { if ($(this).val() == $(this).attr('alt')) { $(this).val(''); $(this).addClass('active'); }  });
  $('textarea').blur(function() { if ($(this).val() == '') { $(this).val($(this).attr('alt')); $(this).removeClass('active'); }  });

  // $('#postcode').blur(function()
  // {
  //   var postcode = $('#postcode').val();
  //   get_place(postcode, function(place) { $('#postplace').html(place); });
  // });

  // length limits
  // $("#postcode").bind('keypress', function(e)
  // {
  //   var ch = String.fromCharCode(e.which);
  //   if (e.which != 8 && /\D/.test(ch))
  //   {
  //     e.preventDefault();
  //   }
  //   else
  //   {
  //     $(this).val($(this).val().replace(/\D/, ''));
  //     if ($(this).val().length >= 4) $(this).val($(this).val().substring(0, 3));
  //   }
  // });
  // end of length limits

  // setInterval(function()
  // {
  //   if (carousel)
  //   {
  //     var li = carousel.items[carousel.current];
  //     var y = $(li).offset().top + $(li).height();
  //     $('#button-container').offset({ top: y + 10 });
  //     $('#form-container').height($(li).height() + 50 );
  //   }
  // }, 15);

  //$(".jui-radio").buttonset();

  // carousel.goto(4);
  // carousel.goto(3);

  $('#same-address input[type=radio]').click(function()
  {
    if ($('#same-yes').is(':checked')) $('#same-fields').slideUp('slow');
                                  else $('#same-fields').slideDown('slow');
  });

  $('#contract-post').click(function()
  {
    if ($(this).is(':checked')) $('#contract-file').removeClass('force').find('input').removeClass('warn');
                           else $('#contract-file').addClass('force');
  });

  $('#progress td').click(function()
  {
    var num = $(this).attr('name');
    if (num < carousel.current)
    {
      carousel.goto(num);
      adjust_ui();
    }
  });
});


Date.prototype.adjust = function(obj) 
{
    var m,t;
    yr = (obj.year?obj.year:0);
    mn = (obj.month?obj.month:0);
    dy = (obj.day?obj.day:0);
    hr = (obj.hour?obj.hour:0);
    mi = (obj.min?obj.min:0);
    se = (obj.sec?obj.sec:0);
    
    this.setYear(this.getFullYear() + yr);
    m = this.getMonth() + mn;
    if(m != 0) this.setYear(this.getFullYear() + Math.floor(m/12));
    if(m < 0) 
    {
        this.setMonth(12 + (m%12));
    } else if(m > 0) 
    {
        this.setMonth(m%12);
    }
    t = this.getTime();
    t += (dy * 86400000);
    t += (hr * 3600000);
    t += (mi * 60000);
    t += (se * 1000);
    this.setTime(t);
}

function changeNation(obj)
{
    if ($(obj).attr('name')== 'hearabout')
    {
        $("#hearabout-verva").hide();
        $("#hearabout-annet").hide();
        $("#hearabout-" + $(obj).val()).show();
    }else
    {
        $('#mynat .norsk').hide();$("#mynat .eu").hide();$("#mynat .other").hide();$('#mynat .' + $(obj).val()).show();
    }
}

function findNearest( date ,  find ,days)
{
    var blocked = [{'date':'01.01','adjust':14},{'date':'25.12','adjust':14}];
    if (days){date.adjust({day:days})}
    while ( find != date.getDay())
    {
        date.adjust({day:1})
    }
    var isblocked = false;
    for ( var i = 0 ; i < blocked.length ; i++ )
    {
        if ( blocked[i].date == $.datepicker.formatDate('dd.mm',date) )
        {
            isblocked = true;
            date.adjust({day:blocked[i].adjust})
            break;
        }
    }
    
    return date
}
function validateReciteKey(value,webvalue)
{
    $.post('/submitValidateCode' , {'valikey':value,'webkey':webvalue}, function(data){
        // this will be checked on the last post as well, so dont use...
        if ($.trim(data) == '@okkey')    
        {
            $("#next").trigger('click');
        }else
        {
            $("#lookstepkey").css('border-color','red')
        }
    });
    
}


function submitReciteKey()
{
    if (validate())
    {
        a = $("#bestep1 *").serializeObject();
        $("#parentemail").html(a.f_epost);
        $("#bestep1").hide();
        $("#bestep2").fadeIn();
        
        $.post('/submitValidateCode' , a , function(data){alert(data)});
    }
    
}

function ui_loading( obj )
{
    if (!obj)
    {
    	$("#loadingwrapper").remove();
		$("#loadingdialog").remove();
	}else
	{
 		$(document.body).append("<div id='loadingwrapper'></div>");
		
         //Get the screen height and width  
         var maskHeight = $(document).height();  
         var maskWidth = $(document).width();  
       
         //Set height and width to mask to fill up the whole screen  
         $('#loadingwrapper').css({'width':maskWidth,'height':maskHeight});  
           
         //transition effect       
         $('#loadingwrapper').fadeIn(1000);      
//         $('#loadingwrapper').fadeTo("fast",0.4);    
       
                var maskHeight = $(window).height();  
         var maskWidth = $(window).width();  

       	$(document.body).append("<div id='loadingdialog'><p>&nbsp;&nbsp;"+obj.txt+"</p></div>");       	
       	var obj = $('#loadingdialog');
   	 	obj.css("top", ( $(window).height() - obj.height()-100 ) / 2+$(window).scrollTop() + "px");
	    obj.css("left", ( $(window).width() - obj.width() ) / 2+$(window).scrollLeft() + "px");
   
    
	}
}

function validateBirthNumber(num, allowEmpty) {
    if(num == '0000')
    {return true;}
    num = $.trim(num);
    if (allowEmpty && !num.length) return true;
    // Check number format  
    if (!(/^([0-7][0-9])([0-5][0-9])(\d{7})$/.test(num))) return false;
    var numDigits = [];
    for (var i=0,ii=num.length;i<ii;i++) numDigits.push(parseInt(num[i]));
    // Control digit 1
    var c1 = 11 - ((3 * numDigits[0] + 7 * numDigits[1] + 6 * numDigits[2] + 1 * numDigits[3] + 8 * numDigits[4] + 9 * numDigits[5] + 4 * numDigits[6] + 5 * numDigits[7] + 2 * numDigits[8]) % 11)
    if (c1==11) c1=0;
    if (c1!=numDigits[9]) return false;
    // Control digit 2
    var c2 = 11 - ((5 * numDigits[0] + 4 * numDigits[1] + 3 * numDigits[2] + 2 * numDigits[3] + 7 * numDigits[4] + 6 * numDigits[5] + 5 * numDigits[6] + 4 * numDigits[7] + 3 * numDigits[8]  + 2 * c1) % 11)
    if (c2==11) c2=0;
    if (c2!=numDigits[10]) return false;
    // If we have come this far, it is correct
    return true;
}


/*
 * jQuery Templates Plugin 1.0.0pre
 * http://github.com/jquery/jquery-tmpl
 * Requires jQuery 1.4.2
 *
 * Copyright Software Freedom Conservancy, Inc.
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);

