// log shortcut
var log = function (m) {
   // console.log(m);
} 

// ### movimenti del box contenente l'email form
var mailFormController = {
   // settaggio variabili di controllo
   formUp: true,
   formAnimationBlocked: false,
   // assegna l'height del cover in base all'height del documento
   coverHeight: function () {
      var cover = nouFw.get("cover");
      var body_y = document.getElementsByTagName("body")[0].offsetHeight;   
      cover.style.height = body_y + "px";
   },
   // funzione chiamata dall'onclick sul controllo del box mail
   showHideForm: function () {
      
      // se la mail non e' in spedizione (blocco_mail == 1)  
      if (this.formAnimationBlocked === false) {
      
         if (this.formUp) {   
         
            this.formUp = false;
            

            var mailDown = {
               id: "contacts",
               cssProp: "top",
               vals: [-310,0],
               totTime: 280,
               uom: "px"
            }
            
            var coverOn = {
               id: "cover",
               cssProp: "opacity",
               vals: [0,0.5],
               totTime: 280
            }
            
            
            this.coverHeight();             
            nouFw.get("cover").style.display = "block"; 
            nouFw.anim(coverOn, function () {
               nouFw.anim(mailDown, function () {
                  // nothing happens here!
               })();
            })();                  
         
       
         }
         else {
      
            this.formUp = true;
            
            var mailUp = {
               id: "contacts",
               cssProp: "top",
               vals: [0,-310],
               totTime: 280,
               uom: "px"
            }
            
            var coverOff = {
               id: "cover",
               cssProp: "opacity",
               vals: [0.5,0],
               totTime: 280
            }
            
            nouFw.anim(mailUp, function () {
               nouFw.anim(coverOff, function () {
                  nouFw.get("cover").style.display = "none";
               })();
            })(); 
            
            // ripulisco i campi del form mail
            nouFw.get("email_mitt").value = '';
            nouFw.get("captcha").value = '';
            nouFw.get("mess").value = '';
            nouFw.get("dialog_box_send").innerHTML = '';
            
         }
      }
      
      // prevent the default action of the element (A) on which this 
      // function is registered as an event listener
      return false;
      
   }      
};

// ### gestione random quote
var randQuote = {
   // metodo e proprieta' privata dichiarata usando l'underscore notation
   _randNum: function (min, max) {
       var r = min + Math.round(Math.random() * max);
       return r;
   },
   // qui salvo il riferimento al timeout lanciato da init()
   // chiaramento lo pulisco ognivolta con clearTimeout() prima di istanziare un nuovo contatore 
   _timing: null,
   // metodo pubblico che inizializza e perpetua il quoting
   init: function () {
      var q = new Array();
      q[0] = [
               "Or you can just leave the image of me in the background I guess, and watch your own reflection superimpose",
               "Ani Difranco"
            ];
      q[1] = [
               "Honey don't tell me the whole story you are boring me. Tell me do you like me? Tell me what you are gonna do now that you are free",
               "Ani Difranco"
            ];
      q[2] = [
               "I'm Arturo Bandini, a lover of men and beasts alike!",
               "John Fante"
            ];       
      q[3] = [
               "I Don't even remember what her lips felt like on mine ... most of the time",
               "Bob Dylan"
            ];       
      q[4] = [
               "You know, man, when I was a young man in high school, you believe in or not I wanted to play football for the coach", 
               "Lou Reed"
            ];
      q[5] = [
               "L'imagination ce n'est pas le mensonge",
               "Daniel Pennac"
            ]
      q[6] = [
               "The eagle and the serpent are at war in me, the serpent fighting for blind desire, the eagle for clarity",
               "Joni Mitchell"
            ]
      q[7] = [
               "Un automne a London, un hiver au Cap Vert, jour de l'an Milan, tout ma vie a Paris ...",
               "Dj Cam"
            ]
      q[8] = [
               "This may be god's country but it's my country too",
               "Ani Difranco"
            ]
      q[9] = [
               "Doctor, Doctor ... Always do the right thing!",
               "The Major"
            ]
      q[10] = [
               "Do you want to get off? Is this your stop? Do you gotta have a tripledecker super fudge sundae with a goddamn cherry on top?",
               "Ani Difranco"
            ]      
      q[11] = [
               "Ma c'è anche un'altro motivo perché lo faccio. Karmayoga! Fare ogni cosa meglio che puoi, anche quello che ti sembra impossibile!",
               "Naima"
            ]   
      q[12] = [
               "Anche se comunque tranquillo tranquillo non ci puoi stare mai perché mica ci stanno solamente i vivi a questo mondo",
               "Joystick"
            ]  
      var rand = this._randNum(0, parseInt(q.length)-1);
      var arrayQuote = q[rand];
      nouFw.get("quote").innerHTML = "&laquo; " +
                        arrayQuote[0] +
                        " &raquo;" +
                        "<span>" +
                        arrayQuote[1] +
                        "</span>";
      // ricorsione
      this._timing = setTimeout("clearTimeout(this._timing); randQuote.init()", "10000");      
   }
};

var sendMail = function () {
   
   /* con mailFormController.formAnimationBlocked gestisco sia il blocco del form 
   che il blocco di ulteriori chiamate ajax quando ce ne già una in corso */
   if (mailFormController.formAnimationBlocked) {
      return false; 
   }
   
   /* JSON will look like this (at ALL TIMES)
   {
      mailSent: true | false,
      hackAttempt: true | false, 
      msg: "bla bla bla"
   } */
   
   var dialogBox = nouFw.get("dialog_box_send");
   
   var conf = {      
      server: "index.php?action=sendmail",
      method: "post",
      onLoading: function () {
         // blocca l'up and down del form
         log("form blocked");
         mailFormController.formAnimationBlocked = true;
         dialogBox.innerHTML = "<img src='img/loading.gif' />";
      },  
      onSuccess: function (respText) {
         // alert(respText);
         var JSON = eval("(" + respText + ")"); 
         if (!JSON.hackAttempt) {
            dialogBox.innerHTML = JSON.msg;
            // sblocca l'up and down del form
            mailFormController.formAnimationBlocked = false;
            // se la mail viene anche spedita pulisco il form
            if (JSON.done) {
               nouFw.get("email_mitt").value = "";
               nouFw.get("captcha").value = "";
               nouFw.get("mess").value = "";
            }
         }
         // hack attempt in action!
         else {
            for (var i = 0; i < 100; i++) {
               alert("don't ya dare fucking with my site mate!");
            }   
         }      
      }      
   };
   
   var XHR = new nouFw.Ajax(conf);   
   var queryStr = nouFw.stringify("form_contact");
   XHR.send(queryStr);  
   
   // to block default behaviour of the form
   return false;
}

var submitComment = function () {
   
   // stops everything if there is a call going on
   if (submitComment.blocked) {
      return false; 
   }

   var dialogBox = nouFw.get("dialog_box_comm");
   var cover = nouFw.get("comment_cover");
   var loadImg = nouFw.get("load_img_comment");
   
   var conf = {      
      server: "index.php?action=submitcomment",
      method: "get",
      onLoading: function () {
         submitComment.blocked = true;
         cover.style.display = "block";
         loadImg.style.display = "block";
      },
      onSuccess: function (respText) {
         // alert(respText);
         var JSON = eval("(" + respText + ")"); 
         if (!JSON.hackAttempt) {
            loadImg.style.display = "none";
            dialogBox.style.display = "block";
            dialogBox.innerHTML = JSON.msg;
            // vario la durata di permanenza a seconda della lunghezza del messaggio
            var len = (JSON.done) ? 4000 : 2500;
            var time = window.setTimeout(function () {
            dialogBox.style.display = "none";
            dialogBox.innerHTML = "";
               cover.style.display = "none";
            }, len);
            dialogBox.innerHTML = JSON.msg;
            // toglie il blocco alle chiamate ajax
            submitComment.blocked = false;
            // se il commento viene anche salvato pulisco il form
            if (JSON.done) {
               nouFw.get("name_comm").value = "";
               nouFw.get("contact_comm").value = "";
               nouFw.get("text_comm").value = "";
            }
         }
         // hack attempt in action! >>> not implemented for comments
         else {
            for (var i = 0; i < 100; i++) {
               alert("don't ya dare fucking with my site mate!");
            }   
         }      
      }      
   };
   
   var XHR = new nouFw.Ajax(conf);   
   var queryStr = nouFw.stringify("form_comment");
   // log(queryStr);
   XHR.send(queryStr);  
   
   // to block default behaviour of the form
   return false;   
}