$(document).ready(function() {
  /*
  * Common dialogue() function that creates our dialogue qTip.
  * We'll use this method to create both our prompt and confirm dialogues
  * as they share very similar styles, but with varying content and titles.
  */
  function dialogue(content, title) {
    /* 
    * Since the dialogue isn't really a tooltip as such, we'll use a dummy
    * out-of-DOM element as our target instead of an actual element like document.body
    */
    
    
    $('<div />').qtip({
      content: {
        text: content,
        title: title
      },
      position: {
        my: 'center', at: 'center', // Center it...
        target: $(window) // ... in the window
      },
      show: {
        ready: true, // Show it straight away
        modal: {
           on: true, // Make it modal (darken the rest of the page)...
           blur: false // ... but don't close the tooltip when clicked
        }
      },
      hide: false, // We'll hide it maunally so disable hide events
      style: 'ui-tooltip-purple ui-tooltip-rounded ui-tooltip-dialogue', // Add a few styles
      events: {
        // Hide the tooltip when any buttons in the dialogue are clicked
        render: function(event, api) {
           $('button#cancelbutton', api.elements.content).click(api.hide);
        },
        // Destroy the tooltip once it's hidden as we no longer need it!
        hide: function(event, api) { api.destroy(); }
      }
      
    });
  }


  // Our mail form method
  function showMailForm(callback) {
    //fixa engelska/svenska
    var lang = window.location.search;   
    
    var tolabel = $('<p />', { text: ((lang=="") ? "Mottagarens e-post-adress: " : "Recipient's e-mail address: ") }),
    tomail = $('<input />', { id:'to_mail' }),
    fromlabel = $('<p />', { text: ((lang=="") ? "Din e-post-adress: " : "Your e-mail address: ") }),
    frommail = $('<input />', { id: 'from_mail' }),
    namefieldlabel = $('<p />', { text: ((lang=="") ? "Ditt namn: " : "Your name: ") }),
    namefield = $('<input />', { id: 'name_field' }),
    subjectlabel = $('<p />', { text: ((lang=="") ? "Ämne: " : "Subject: ") }),
    subject = $('<input />', { id: 'subject_field' }),
    messagelabel = $('<p />', { text: ((lang=="") ? "Meddelande: " : "Message: ") }),
    messagefield = $('<textarea />', { 
      /*class: 'dialogtext',*/
      id: 'message_field',
      value: ((lang=="") ? "Du har blivit rekommenderad en länk på glimstedt.se: " : "You have been recommended a link at glimstedt.se: ") + "\n\n" + document.location.href + "\n\n" + ((lang=="") ? "Glimstedt är en av Sveriges största advokatbyråer." : "Glimstedt is one of Sweden’s largest law firms.")

    }),
    humanlabel = $('<p />', { 
      text: ((lang=="") ? "Lämna det här fältet tomt: " : "Leave this field empty: "),
      id: 'mymaillabel' 
    }),
    human = $('<input />', { 
      id: 'mymailaddress'
    }),
    sendbutton = $('<button />', { 
      text: ((lang=="") ? "Skicka" : "Send"),
      /*class: 'dialogbutton',*/
      click: function() { 
        var data = new Array();
        data['tomail'] = tomail.val();
        data['frommail'] = frommail.val();
        data['subject'] = subject.val();
        data['message'] = messagefield.val();
        data['namefield'] = messagefield.val();
        data['human'] = human.val();
        data['name'] = namefield.val();
        callback( data ); 
      }
    }),
    cancelbutton = $('<button />', {
      text: ((lang=="") ? "Avbryt" : "Cancel"),
      /*class: 'dialogbutton cancelbutton',*/
      id: "cancelbutton",
      click: function() { callback(null); }
    });

    
    
    dialogue( humanlabel.add(human).add(tolabel).add(tomail).add(fromlabel).add(frommail).add(namefieldlabel).add(namefield).add(subjectlabel).add(subject).add(messagelabel).add(messagefield).add(cancelbutton).add(sendbutton), ((lang=="") ? "Rekommendera sida" : "Recommend page") );
     
  }


  $('#showMailForm').click(function() {
    showMailForm(function(response) {
      if (response) {
        if (isEmailAddress(response['tomail']) && isEmailAddress(response['frommail']) && !isBlank(response['subject']) && !isBlank(response['message']) && !isBlank(response['name'])) {
          /*
          $.post("/wp-content/themes/glimstedt/mailer.php", {
            kaka: 'didmail'
          });
          */
          
          $.post("/wp-content/themes/glimstedt/mailer.php", { 
            to_mail: response['tomail'], 
            from_mail: response['frommail'], 
            subject: response['subject'], 
            name: response['name'], 
            message: response['message'],
            mymail: response['human']
          });
          $('button#cancelbutton').click();
        } else {
          $('#to_mail').css('background','#fff');
          $('#from_mail').css('background','#fff');
          $('#subject_field').css('background','#fff');
          $('#message_field').css('background','#fff');
          $('#name_field').css('background','#fff');
          
          
          if (!isEmailAddress(response['tomail'])) 
            $('#to_mail').css('background','#ffb9b9');
            
          if (!isEmailAddress(response['frommail'])) 
            $('#from_mail').css('background','#ffb9b9');
          
          if (isBlank(response['subject'])) 
            $('#subject_field').css('background','#ffb9b9');
            
          if (isBlank(response['name_field'])) 
            $('#name_field').css('background','#ffb9b9');
          
          if (isBlank(response['message'])) 
            $('#message_field').css('background','#ffb9b9');
        }

      } else {
        
      }
      
    });
  });
  
  
  function setCookie(cookieValue) {
    var today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() + 3600000*24);
    document.cookie = "mailercookie"+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
  }
  
  function isEmailAddress(address) {
    var atpos=address.indexOf("@");
    var dotpos=address.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=address.length)
      return false;
    return true;
  }
  
  function isBlank(str) {
    return (!str || /^\s*$/.test(str));
  }
  

});


