/*
 * On the basis of
 * SimpleModal Basic Modal Dialog,  SimpleModal Contact Form 
 * 
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2008 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 *   modify by KK
 */

$(document).ready(function () { } );

function formAdd(admin) 
{
    if(admin)
       ksiega = 'ksiega_form.php?admin=2';   // 2 -  admin ale formularz tylko dla nowych wpisów
    else
       ksiega = 'ksiega/ksiega_form.php';
    
    $.get(ksiega, function(data){
  	    $(data).modal({
          close: true,
			 position: ["25%",],
       	 overlayId: 'simplemodal-overlay',
			 containerId: 'simplemodal-container',
			 onOpen: contact.open,
			 onShow: contact.show,
  			 onClose: contact.close
       });
    });
}

function noteEdit(noteid, action) {
   		$.get('ksiega_form_admin.php?noteid='+noteid+'&action='+action, function(data){
  			$(data).modal({
       		close: true,
				position: ["25%",],
       		overlayId: 'simplemodal-overlay',
				containerId: 'simplemodal-container',
				onOpen: contact.open,
				onShow: contact.show,
  				onClose: contact.close
			});
     });
}

function noteAdd(comment, action)
{
    // validate form
    if (contact.validate()) 
    {
       $('#action').val(action);
       if($('#admin').val() == 1 )
          {
             if (confirm (comment) )
             {
                $('.simplemodal-content form').submit();
             }
          }
          else
             $('.simplemodal-content form').submit();
    }
    else
    {
       if ($('.message:visible').length > 0) 
       {
		    var msg = $('.message div');
    			 msg.fadeOut(250, function () {
	    		    msg.empty();
		    		 contact.showError();
			    	 msg.fadeIn(250);
          });
       }
       else 
       {
    	    $('.message').animate({
	    	    height: '24px'
			 }, contact.showError);
		  }
    }
}

function noteSave(noteid, action)
{
    // validate form
    if (contact.validate()) 
    {
       $('#noteid').val(noteid);
       $('#action').val(action);
       $('.simplemodal-content form').submit();
    }
    else
    {
       if ($('.message:visible').length > 0) 
       {
		    var msg = $('.message div');
    			 msg.fadeOut(250, function () {
	    		    msg.empty();
		    		 contact.showError();
			    	 msg.fadeIn(250);
          });
       }
       else 
       {
    	    $('.message').animate({
	    	    height: '24px'
			 }, contact.showError);
		  }
    }
}

var contact = {
   open: function (dialog) {
       dialog.overlay.fadeIn(200, function () {
  	       dialog.container.fadeIn(200, function () {
             dialog.data.fadeIn(200, function () {
                $('.modalCloseImg').fadeIn(200);
                $('#author').focus();
             });  
          });  
    }); 
  },

  show: function (dialog) {
    $('.add').click(function (e) {
	    e.preventDefault();
       // validate form
       if (contact.validate()) 
       {
          $('#action').val('ADDSAVENOTE');
          if($('#admin').val() == 1 )
          {
             if (confirm ('zapisaa') )
             {
                $('.simplemodal-content form').submit();
             }
          }
          else
              $('.simplemodal-content form').submit();

       }
       else
       {
          if ($('.message:visible').length > 0) 
          {
		       var msg = $('.message div');
    			 msg.fadeOut(250, function () {
	    		    msg.empty();
		    		 contact.showError();
			    	 msg.fadeIn(250);
             });
			 }
          else 
          {
    		    $('.message').animate({
	    		    height: '24px'
				 }, contact.showError);
		    }
        }
     });
  },

  close: function (dialog) {
		//window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';
		//callback.apply();
    	dialog.data.fadeOut(200, function () {
		    dialog.container.fadeOut(200, function () {
			    dialog.overlay.fadeOut(200, function () {
				    $.modal.close();
				 });
			 });
		});
  },

  error: function (xhr) {
    alert(xhr.statusText);
  },

  validate: function () {
		contact.message = '';
		if (!$('#author').val()) {
			contact.message += 'Autor jest wymagany. ';
		}

		var email = $('#email').val();
		if (email) {
			if (!contact.validateEmail(email)) {
				contact.message += 'Nieprawidłowy Email. ';
			}
		}

		if (!$('#note').val()) {
			contact.message += 'Komentarz jest wymagany.';
		}

		if (contact.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	
   validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	},
	showError: function () {
		$('.message')
			.html($('<div class="error">').append(contact.message))
         .fadeIn(250);
	}
}

function Reset()
{
    document.ksiegagosciedit.reset();		
    countNoteChars(0, '', '');
}

function countNoteChars(maxsize, comments1, comments2)
{
    if(maxsize == 0)
       limit = 250;
    else
       limit = maxsize;

	 var writenChars = document.ksiegagosciedit.note.value.length;
    if(comments1.length == 0)
        comments1 = "Wprowadzono zbyt dużo znaków !";
    if(comments2.length == 0)
        comments2 = "Limit znaków - ";
    
	 if(writenChars > limit) 
    {
	    alert(comments1);
			    	
		 var tmp = document.ksiegagosciedit.note.value;
		 tmp = tmp.substring(0, limit);
		 document.ksiegagosciedit.note.value = tmp;	
		 writenChars = document.ksiegagosciedit.note.value.length;
    }
    $('#noteLimit').html( comments2 + limit + "/" + writenChars);
}			

function noteDel(noteid, comments, action)
{
    if(confirm(comments)) 
	 {
       document.ksiegagosci.noteid.value = noteid;
		 document.ksiegagosci.action.value = action;
		 document.ksiegagosci.submit();
	 }
}
