// PwdGenSite - A tiny script to generate secure passwords on a website
// Copyright (C) 2010 Knut Ahlers <knut@ahlers.me>
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

var pwdlength = 12;
var special = true;
var clip = null;

$(function(){
  $('.button').button();
  $('#generatebtn').click(function() { updatepassword(); });
  $('#settingsbtn').click(function() { 
    $('#settings').dialog({
      modal: true,
      resizable: false,
      title: "Settings",
      open: function(event, ui) {
        $('#lengthslider').slider({
          min: 8,
          max: 30,
          value: pwdlength,
          slide: function(event, ui) {
            $('#lengthdisplay').text(ui.value);
          },
          stop: function(event, ui) {
            save_settings();
            updatepassword();
          }
        });
        $('#lengthdisplay').text($('#lengthslider').slider('value'));
        $('#usespecial').attr('checked', special);
      }
    }); 
  });
  $('#usespecial').change(function() {
    special = $(this).attr('checked');
    save_settings();
    updatepassword();
  });
  load_settings();
  $('#lengthdisplay').text($('#lengthslider').slider('value')); 
  ZeroClipboard.setMoviePath( '/lib/zeroclip/ZeroClipboard.swf' );
  clip = new ZeroClipboard.Client();
  clip.glue('copytoclip', 'main');
  setTimeout(updatepassword, 500);
  setTimeout(function(){ window.scrollTo(0,1); }, 400);
});

function load_settings() {
  var content = $.cookie('settings');
  if(content != null) {
    content = content.split(';');
    pwdlength = content[0];
    special = content[1] == "true";
  } else {
    pwdlength = 12;
    special = true;
  }
}

function save_settings() {
  pwdlength = $('#lengthslider').slider('value');
  var content = pwdlength + ";";
  if(special)
    content = content + "true";
  else
    content = content + "false";
  
  $.cookie('settings', content, { expires: 365 });
}

function updatepassword() {
  var length = $('#lengthslider').slider('value');
  $.getJSON('/api/getSecurePassword', {'chars':pwdlength, 'special':special}, function(data) {
    $('#pwd').text(data.password);
    clip.setText(data.password);
  });
}
