function kaufm(x) {
    var k = (Math.round(x * 100) / 100).toString();
    k += (k.indexOf('.') == -1) ? '.00' : '00';
    return k.substring(0, k.indexOf('.') + 3);
}
$('.presetlist').ready(function(){
  formate= new Array("DIN A$A2|594|420#A3|420|297#A4|297|210#A5|210|148#A6|148|105#DIN LANG|210|105","DIN B$B4|353|250#B5|250|176#B6|176|125#B7|125|88","DIN C$C4|324|229#C5|229|162#C6|162|114#C7|114|81","DIN D$D3|385|272#D4|272|192#D5|192|136#D6|136|96","US Formate$Legal|356|216#Letter|279|216#Executive|267|184#Invoice|216|140","JIS B$B4|364|357#B5|257|182#B6|182|128#B7|128|91");
var tabs = " "; 
  tabs = "<ul>";
  var sections=" ";
    for(var i=0;i< formate.length;i++) { 
      formatereihe = formate[i].split("$");
      var mySplitResult = formatereihe[1].split("#");
      formatname = formatereihe[0].replace(" ","");
       var Link = $('<button></button>').addClass("lionbutton3 btn-reihe  ").attr('format',formatname).text(formatereihe[0]);
       $('.presetbuttons').append(Link);
  
  tabs= tabs+"<li><a href='#"+formatereihe[0].replace(" ","")+"'>"+formatereihe[0].replace(" ","")+"</a></li>\n";
     sections= sections+"<div id='" + formatereihe[0].replace(" ","") +"'> \n";
      $.each(mySplitResult, function(index, value) {
          splitvalue = value.split("|"); 
          var Link = $('<button></button').css('display','none').addClass("lionbutton3 small btn-preset").addClass(formatereihe[0].replace(" ","")).attr('data-bind','click: function(){ schreib("'+splitvalue[1]+'","'+splitvalue[2]+'") }').text(splitvalue[0]);
                     $('.presetlist').append(Link);
           
             sections= sections+"<button class='lionbutton3  btn-preset "+formatereihe[0].replace(" ","")+" ' data-bind='click: function(){ schreib(" +splitvalue[1]+ "," +splitvalue[2]+ ")}'>"+splitvalue[0]+"</button>\n";

                      
      }); 
 sections= sections+"</div>\n";

 }           

 tabs= tabs+"</ul>"+sections;
       

 
//console.log(tabs);

 $('.presetbuttons button').click(function(){
      $('.btn-reihe').removeClass("aktiv");
   $(this).addClass("aktiv");

   $('.btn-preset').hide();
 format = $(this).attr('format');
   $('.'+format).fadeIn();
   
 });


});


$(document).ready(function() {

		$( "#sortable-kisten" ).sortable({ items: 'li' });
				$( "#sortable-kisten" ).disableSelection();


$( "#accordion2" ).accordion({
			collapsible: true
		});
$( "#accordion" ).accordion({
			collapsible: true
		});
$('.DINA').fadeIn();
   
$('.datatab2').hide();
/* $('#liste').hide(); */

$('#rating-note').hide();
$('#contact-note').hide();

$('#contact-form').submit(function(){

    event.preventDefault(); 
    $('#contact-form').append('<input type="hidden" name="rating" value=' + $('#faceslider').slider('value') + ' />');

    var str = $(this).serialize();

   $.ajax({
            type: "POST",
            url: "etc/formrobot.php",
            data: str,
            success: function(msg){
                $("#contact-note").ajaxComplete(function(event, request, settings){
                //alert(str+" "+msg); 
                    $('#loading').fadeOut(300);
                    if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
                    { // console.log(msg);
                        result = '<div class="notification_ok">Ihre Nachricht wurde verschickt.<\/div>';
                    $('#faceslider').fadeOut(900);
                    $('#contact-form .msgbutton').fadeOut(900);
                    $('textarea.contact-message').fadeOut(900);
                    $('#face-wrap').fadeTo('slow',0.2);

                    }
                    else
                    { //console.log(msg);
                           result = msg;
                    }
                    $(this).html(result);
                });
            }
        });
        return false;
    });





 $(".warning").remove();
 
  $.get("etc/token.php",function(txt){
          $('#contact-form').append('<input type="hidden" name="ts" value='+txt+' />');
          $('#rating-form').append('<input type="hidden" name="ts" value='+txt+' />');

              });


// FACE
var newWidth,
face=$('#face-wrap'),
    mouth = $("#mouth");
skala =$('#skala');

$( "#faceslider" ).slider({
   slide: function(event, ui) {
        
        red= parseInt((100-ui.value)  *2.55);
        green=   parseInt(ui.value * 2.55);
        blue= 60+ui.value;
        //console.log('R'+red+ ' G'+green); 


xpos = parseInt(130-(ui.value*1.30)-30);
//console.log(xpos);
       skala.css({
       backgroundPositionX : xpos
       });


     if (ui.value > 51 ) {
     green=255;
             red=red*2;  
       mouth.css({ bottom: 0, top: "auto" });

       newWidth = 130 - ui.value;

       mouth.css({
         width           : newWidth,
         height          : newWidth,
         "border-radius" : newWidth / 2,
         left            : -25 + ((ui.value-50) / 2)
       })
       .removeClass("straight");

     } else if ((ui.value > 48) && (ui.value < 52)) {
red=255;
green=255;
       mouth.addClass("straight");
     }  else {
   red=255;
   green=green*2
       mouth.css({ top: 0, bottom: "auto" });

       newWidth = ui.value + 40;

       mouth.css({
         width           : newWidth,
         height          : newWidth,
         "border-radius" : newWidth / 2,
         left            : -ui.value / 2
       })
       .removeClass("straight");

     }
     
      face.css({          backgroundColor: 'rgb('+red+','+green+','+blue+')' });

   },
  value: 50
});

// END of FACE


$(".loginform").submit(function() {
   $.post("authenticate.php",{ email:$('#log-email').val(),password:$('#log-password').val(),rand:Math.random() } ,function(data) {
   //console.log(data);
    var antwort= jQuery.parseJSON(data); 
    if(antwort.auth=="true") {
          viewModel.updateLoginStatus();
          $('.loginzone').html(antwort.user_id+" | "+antwort.email+" | <a href='index.php?logout'>Logout</a>");

          $('.login-note').html('Eingeloggt');                        
          }
          else 
          { 
               $('.login-note').html('Fehler. Nicht eingeloggt.');
                      }
       });
       return false;//not to post the  form physically
});

$(".signupform").submit(function(){
  $.post("as_signup.php",{email:$('#signup-email').val(),password:$('#signup-password').val(),rand:Math.random() } ,function(data) {
    //console.log(data);
    var antwort= jQuery.parseJSON(data);

    if(antwort.auth=="true") {  //console.log(antwort.auth);           
      viewModel.updateLoginStatus();
      $('.loginzone').html(antwort.user_id+" | "+antwort.email+" | <a href='index.php?logout'>Logout</a>");
      $('.login-note').html('Angemeldet');
      $('.btn-signup').qtip('toggle');
/*           alert(antwort.auth);              */

    } else { 
      $('.signup-note').html('Fehler. '+antwort.fehler);
     // alert("feller="+data);
    }
  });
  return false;//not to post the  form physically
});



$('button.signup').click(function(){
  $('.btn-login').qtip('toggle');
  $('.btn-signup').qtip('toggle');

});
$('.btn-signup').qtip({
   content: {
      text: $('.signupform-wrap'),
      title: {
         text: 'Anmelden auf papiergewichtrechner.de',
         button: true
      }
   },
   position: {
      my: 'center',
      at: 'center',
      target: $(document.body)
   },
   show: {
      event: 'click',
      modal: {
         on: true,
         blur: false
      }
   },
   style: {
      classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
   }

});


$('.btn-login').qtip({
   content: {
      text: $('.loginform-wrap'),
      title: {
         text: 'Login',
         button: true
      }
   },
   position: {
      my: 'center',
      at: 'center',
      target: $(document.body)
   },
   show: {
      event: 'click',
      modal: {
         on: true,
         blur: false
      }
   },
   style: {
      classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
   }

});

  $('.infotip').qtip({
   content: { attr: 'title'},
   position: {
      my: 'bottom center', 
      at: 'top center'
   },
   show: 'mouseenter',
   style: {
      tip: true,
      classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
   }
});

    $('.unavailable').qtip({
   content: 'In dieser Beta nicht verfügbar',
   position: {
      my: 'bottom center', 
      at: 'top center'
   },
   show: 'mouseenter',
   style: {
      tip: true,
      classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-rounded'
   }
});
$('.signupform-wrap').hide();
$('.loginform-wrap').hide();
/* VERSTECKEN */
/* $('.presetlist').hide(); */

/*
    $('#auflage').parent().parent().hide();
    $('#extragewicht').parent().parent().hide();
*/
/* ENDE VESTECKEN */
 $('button.presetToggle').click(function(){
      $('.presetlist').toggle('slow'); 
    });
    $('a.auflage').click(function(){
      $('#auflage').parent().parent().toggle('slow');
      //malen();
    });
    $('a.extragewicht').click(function(){
    $('#extragewicht').parent().parent().toggle('slow');
    });

/* MODEL  */
var seatReservation = function(name,laenge,breite,grammatur,blaetter,extragewicht) {
    this.name = ko.observable(name);
    this.laenge = ko.observable(laenge);
    this.breite = ko.observable(breite);
    this.grammatur = ko.observable(grammatur);
    this.blaetter = ko.observable(blaetter);
    this.extragewicht = ko.observable(extragewicht);
    this.malen = ko.computed(function() {

$(".showpaper").clearCanvas()
    abstandx= 1;
    abstandy= 5;

    for(i=0; i < this.blaetter() ;i++){
    if(i > 5){  break; }
    var malx = this.breite() / 3.5 ;
    var maly = this.laenge() / 3.5 ;
    var canvasx = 170;
    var canvasy = 170;    
    var centerx = (canvasx / 2) - (malx / 2);
    var centery = (canvasy / 2) - (maly / 2);
   // var centery = 200- maly-10; // Unten anfangen
    centerx= centerx +i*abstandx;
    centery= centery -i*abstandy;
        $("#showpaper").drawRect({
          fillStyle: "#fff",
          shadowColor: "#6a7074",
          shadowBlur: 3,
          shadowX: 0, shadowY: 2,
          x: centerx,
          y: centery,
          width: malx,
          height: maly,
          fromCenter: false
        });
        }
        if(this.blaetter() > 5){
            $("#showpaper").drawText({
            fillStyle: "#3F515E",
            strokeWidth: 0,
            text: this.blaetter()+"x",
            align: "center",
            baseline: "middle",
            font: "normal 12pt Arial",
            x: (canvasx / 2) - (malx / 2)+31,
            y: (canvasy / 2) - (maly / 2)+20
          });
      }



  /*
    $("#showpaper").drawRect({   
          fillStyle: "#fff",
          shadowColor: "#939393",
          shadowBlur: 5,
          shadowX: 0, shadowY: 3,
          x: 40,
          y: 40,
          width:    this.breite(),
          height: this.laenge(),
          fromCenter: false
        });
*/
  var flaeche = (this.laenge() * this.breite()) / 1000000;
         var gesamteinzel = parseFloat(this.blaetter() * (flaeche * this.grammatur())) ;
        return gesamteinzel.toFixed(2);

}, this);
     this.formattedGewicht = ko.computed(function() {
        var flaeche = (this.laenge() * this.breite()) / 1000000;
         var gesamteinzel = parseFloat(this.blaetter() * (flaeche * this.grammatur())) ;
        return gesamteinzel.toFixed(2)+' g';
    }, this);

    this.malen= function(){
      $(this).hide();
      
     /*
 $(".showpaper").drawRect({   
          fillStyle: "#fff",
          shadowColor: "#939393",
          shadowBlur: 5,
          shadowX: 0, shadowY: 3,
          x: 40,
          y: 40,
          width:     this.laenge(),
          height: this.breite(),
          fromCenter: false
        });
*/
    }
    this.remove = function() { viewModel.drucksachen.remove(this);     piwikTracker.trackGoal(4); 
 }

}

var viewModel = {
      loginStatus: ko.observable(false),
       // optionValues : ["Alpha", "Beta", "Gamma"],
      laenge: ko.observable("297",{persist: 'laengePersist'}),
      breite: ko.observable("210",{persist: 'breitePersist'}),
      grammatur: ko.observable("80",{persist: 'grammaturPersist'}),       
      blaetter: ko.observable("1",{persist: 'blaetterPersist'}),       
      extragewicht: ko.observable("0"),       
      auflage: ko.observable("1",{persist: 'auflagePersist'}),              
      drucksachen: ko.observableArray([
       // new seatReservation("Mailing",210,297,80,1,0),
       // new seatReservation("Brief",150,150,80,1,0),
    ]),  
    updateLoginStatus: function(){
     $.get('as_isauth.php', function(data){
          data = jQuery.parseJSON(data);
          if(data.auth=="true")
            {   viewModel.loginStatus(true) }
            else { viewModel.loginStatus(false);}
      })   
      },
          


    addSeat: function() {
    piwikTracker.trackGoal(3); 
    $('table.datatab2').fadeIn();
    $('#liste').fadeIn();

       // this.drucksachen.push(new seatReservation());
       name= "Papier " + (this.drucksachen().length+1);   
      this.drucksachen.push(new seatReservation(name,this.laenge(),this.breite(),this.grammatur(), this.blaetter(), this.extragewicht()));
         
    },
    saveJSON: function() { 
      var jsonData = ko.toJSON(viewModel);
      $.post("as_write.php", {data: jsonData}, function(msg){
         //console.log(msg);
      });
      /*
$.ajax({
        url: 'wrap_write.php',
        data: { data: jsonData},
        success : function(msg){
          alert(msg);
        }
      
      });
*/
      
     //document.write(jsonData);
    },
    
    loadJSONfromRails: function() { 
    
    $.ajax({
url: "http://beta.papiergewichtrechner.de:3000/formatlists/latest.js",
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
//console.log(data);
    
      alert(data.formatlist.rohdaten);

      data= jQuery.parseJSON(data.formatlist.rohdaten);
      viewModel.drucksachen.removeAll();
       $.each(data.drucksachen,function(index,value){
        viewModel.drucksachen.push(new seatReservation(value.name,value.laenge,value.breite,value.grammatur, value.blaetter, 0));   
        });
}
});
    
   /*
 $.ajax({
      type: 'POST',
      url:'http://beta.papiergewichtrechner.de:3000/formatlists/latest.js?callback=magic',
      success: function(data){ console.log(data);
      data= jQuery.parseJSON(data);
      viewModel.drucksachen.removeAll();
       $.each(data.drucksachen,function(index,value){
        viewModel.drucksachen.push(new seatReservation(value.name,value.laenge,value.breite,value.grammatur, value.blaetter, 0));   
        });
      }
    
    });
*/
    },
    
    loadJSON: function() { 

    $.ajax({
      type: 'POST',
      url:'as_read.php',
      success: function(data){  //console.log(data);
      data= jQuery.parseJSON(data);
      viewModel.drucksachen.removeAll();
       $.each(data.drucksachen,function(index,value){
        viewModel.drucksachen.push(new seatReservation(value.name,value.laenge,value.breite,value.grammatur, value.blaetter, 0));   
        });
      }
    
/*
    $.ajax({
      type: 'POST',
      url:'test.json',
      success: function(data){ 
      data= jQuery.parseJSON(data);
       $.each(data.drucksachen,function(index,value){
        viewModel.drucksachen.push(new seatReservation(value.name,value.laenge,value.breite,value.grammatur, value.blaetter, 0));   
        });
      }
    
*/
    });
    
    
      /*
$.getJSON('test.json', function(data){
      $.each(data.drucksachen,function(index,value){
        //alert(index+' '+value.laenge +' '+ value.breite);
        viewModel.drucksachen.push(new seatReservation(value.name,value.laenge,value.breite,value.grammatur, value.blaetter, 0));   
      
      });
        viewModel.laenge(data.laenge);

      });
*/

    },    
      getSummary: function() {
/*       MALEN */
        $("#myDrawing").clearCanvas()
    abstandx= 1;
    abstandy= 5;

    for(i=0; i < this.blaetter() ;i++){
    if(i > 5){  break; }
    var malx = this.breite() / 3.5 ;
    var maly = this.laenge() / 3.5 ;
    var canvasx = 170;
    var canvasy = 170;    
    var centerx = (canvasx / 2) - (malx / 2);
    var centery = (canvasy / 2) - (maly / 2);
   // var centery = 200- maly-10; // Unten anfangen
    centerx= centerx +i*abstandx;
    centery= centery -i*abstandy;
        $("#myDrawing").drawRect({
          fillStyle: "#fff",
          shadowColor: "#6a7074",
          shadowBlur: 3,
          shadowX: 0, shadowY: 2,
          x: centerx,
          y: centery,
          width: malx,
          height: maly,
          fromCenter: false
        });
        }
        if(this.blaetter() > 5){
            $("#myDrawing").drawText({
            fillStyle: "white",
            shadowColor: "#000",
            shadowBlur: 2,
            strokeWidth: 0,
            text: this.blaetter()+"x",
            align: "center",
            baseline: "middle",
            font: "normal 12pt Arial",
           // x: (canvasx / 2) - (malx / 2)+31,
            //y: (canvasy / 2) - (maly / 2)+20
            x: 40, y: 140
          });
      }
/*       MALEN ENDE */
    var gesamt = 0;
    var flaeche = 0;
    flaeche = (this.laenge() * this.breite()) / 1000000;
    gesamteinzel = this.blaetter() * (flaeche * this.grammatur()) ;
    gesamt = gesamteinzel * this.auflage();
    gesamt = gesamteinzel ;

    if (gesamt > 1000) {
        gesamt = kaufm(gesamt / 1000);
        return kaufm(gesamt) + " kg";
    } else {
        return kaufm(gesamt) + " g";
    }
  
      }
  };
  viewModel.schreib =  function(x,y) {
    this.laenge(x);
    this.breite(y);
    }

  viewModel.summary = ko.computed(
      viewModel.getSummary, viewModel);
  
  viewModel.zwischensumme = ko.computed(function() {
   var total = 0;
   for (var i = 0; i < this.drucksachen().length; i++)
       total += parseFloat(this.drucksachen()[i].formattedGewicht());
   return total;
}, viewModel);


     viewModel.showElement = function(elem) { if (elem.nodeType === 1) $(elem).hide().fadeIn() };
     viewModel.hideElement = function(elem) { if (elem.nodeType === 1) $(elem).fadeOut(function() { $(elem).remove(); }) }

viewModel.totalGewicht = ko.computed(function() {
   var total = 0;
   for (var i = 0; i < this.drucksachen().length; i++)
       total += parseFloat(this.drucksachen()[i].formattedGewicht());
   total += this.extragewicht();
   total = total * this.auflage();
   if(this.drucksachen().length<1) { total=0;}
   return total;
}, viewModel);

viewModel.formattedTotalGewicht = ko.computed(function() {
total= this.totalGewicht();
    if (total > 1000) {
        total = kaufm(total / 1000);
        return kaufm(total) + " kg";
    } else {
        return kaufm(total) + " g";
    }
   return total;
}, viewModel);

 ko.applyBindings(viewModel);
});

