$(document).ready(function() {
  /*setTooltips = function(){
    $("input[title], select[title], textarea[title], img[title]").tooltip({ 
        position: "center right", 
        offset: [-2, 10], 
        effect: "fade", 
        opacity: 0.90, 
        tip: '#tooltip' 
    });
  };
  setTooltips();*/
  
  $('#my_profile_edit').live('click', function(e){
    e.preventDefault();
    $.ajax({
      url: "/ajax.php",
      type: "POST",
      data: "plugin_name=my_profile&action=getProfileCardEdit",
      dataType: "html",
      beforeSend: function() {
        $('#my-profile .wrapper').html('<div class="tmp">'+$('#my-profile .wrapper').html()+'</div><div class="loading"><img src="/_items/_new/img/medium-loading.gif" alt="loading" /> Ładowanie edycji profilu</div>');
        $('#my-profile .wrapper .tmp').slideUp('normal', function(){ 
          $('#my-profile .wrapper .loading').slideDown('fast'); 
          $(this).remove(); 
        });
      },
      success: function(html) {        
        $('#my-profile .wrapper').append('<div class="form" style="display:none;">'+html+'</div>');
        $('#my-profile .wrapper .loading').delay(800).slideUp('fast', function(){
          $('#my-profile .wrapper .form').slideDown(); 
          $(this).remove(); 
          //$('#my-profile .wrapper').html($('#my-profile .wrapper .tmp').html()).find('.tmp').remove();
        });
        //setTooltips();
      }
    });
  });
  
	$('#my-profile a#avatar-upload-btn').live('click', function(e){
		window.open( "/_utils/avatar_upload.php?imgid=avatar-img", "Avatar Upload", "status = 0, height = 150, width = 300, resizable = 0" );
	});
  
  $('#my-profile .wrapper #btn-cancel a').live('click', function(e){
    e.preventDefault();
    $.ajax({
      url: "/ajax.php",
      type: "POST",
      data: "plugin_name=my_profile&action=getProfileCard",
      dataType: "html",
      beforeSend: function() {
        //$('#my-profile .wrapper').html('<div class="tmp">'+$('#my-profile .wrapper').html()+'</div><div class="loading"><img src="/_items/_new/img/medium-loading.gif" alt="loading" /> Ładowanie profilu</div>');
        $('#my-profile .wrapper').append('<div class="loading"><img src="/_items/_new/img/medium-loading.gif" alt="loading" /> Ładowanie profilu</div>');
        $('#my-profile .wrapper .form').slideUp('normal', function(){ 
          $('#my-profile .wrapper .loading').slideDown('fast'); 
          $(this).remove(); 
        });
      },
      success: function(html) {
        $('#my-profile .wrapper').append('<div class="tmp" style="display:none;">'+$(html).find('.content .wrapper').html()+'</div>');
        $('#my-profile .wrapper .loading').delay(800).slideUp('fast', function(){
          $('#my-profile .wrapper .tmp').slideDown(); 
          $(this).remove(); 
          $('#my-profile .wrapper').html($('#my-profile .wrapper .tmp').html()).find('.tmp').remove();
        });
      }
    });
  });
  
  $('#my-profile .wrapper #btn-save a').live('click', function(e){
    e.preventDefault();
    var values = '';
    $('#my-profile .wrapper').find('input:not([type=file]), select, textarea').each(function(){
      values += '&'+$(this).attr('name')+'='+$(this).val();
    });
    $.ajax({
      url: "/ajax.php",
      type: "POST",
      data: "plugin_name=my_profile&action=saveProfileCard"+values,
      dataType: "html",
      beforeSend: function() {
        //$('#my-profile .wrapper').html('<div class="tmp">'+$('#my-profile .wrapper').html()+'</div><div class="loading"><img src="/_items/_new/img/medium-loading.gif" alt="loading" /> Ładowanie profilu</div>');
        $('#my-profile .wrapper').append('<div class="loading"><img src="/_items/_new/img/medium-loading.gif" alt="loading" /> Ładowanie profilu</div>');
        $('#my-profile .wrapper .form').slideUp('normal', function(){ 
          $('#my-profile .wrapper .loading').slideDown('fast'); 
          $(this).remove(); 
        });
      },
      success: function(html) {
        $('#my-profile .wrapper').append('<div class="tmp" style="display:none;">'+$(html).find('.content .wrapper').html()+'</div>');
        $('#my-profile .wrapper .loading').delay(500).slideUp('fast', function(){
          $('#my-profile .wrapper .tmp').slideDown(); 
          $(this).remove(); 
          $('#my-profile .wrapper').html($('#my-profile .wrapper .tmp').html()).find('.tmp').remove();
        });
      }
    });
  }); 
  
  $('#alerts .alert:not(.static)').each(function(){
  	var content = $(this).find('.content').html();
	if(content && content!='&nbsp;'){
		showMessageBox($(this).find('.content').html(), 7000, true);
	}
  });
  
  /*****ZMIANA TYPU UŻYTKOWNIKA*****/
  $("#convert-user-type").click(function(){
	$(this).fadeTo(100,0.4);
	$.post("/ajax.php?plugin_name=user_settings",{"changeUserType":true},function(){
		$("#convert-user-type").remove();
		location.reload(true);
	});
  });
  
});

showMessageBox = function(text, delay, noJump){
  if(!noJump)
    document.location = '#alerts';
  bro = $($('#alerts .alert')[0]).clone().hide().appendTo('#alerts');
  bro.find('.content').html('<p>'+text+'</p>');
  if(delay)
    bro.fadeIn('fast').delay(delay).fadeOut('fast');
  else
    bro.fadeIn('fast');
};

//Forms submit & validation
validateAndSubmit = function(form_selector, ajax) {
  var errors = 0;
  var values = '';
  var radios = {};
  var groups = {};
  $(form_selector).find('input, select, textarea').each(function(){
    if($(this).hasClass('required') && $(this).attr('type')!='radio'){
      if($(this).val()==''){
        $(this).addClass('error');
        errors++;
      }else{
        $(this).removeClass('error');
      }
    }else if($(this).hasClass('required-one') && $(this).attr('type')!='radio'){
      if(!groups[$(this).attr('group')]){
        if($(this).val()==''){
          groups[$(this).attr('group')] = false;
        }else{
          groups[$(this).attr('group')] = true;
        }
      }
    }else if($(this).hasClass('email') && $(this).attr('type')!='radio'){
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if(reg.test($(this).val()) == false){
        $(this).addClass('error');
        errors++;
      }else{
        $(this).removeClass('error');
      }
    }
    if($(this).val() && $(this).attr('name')){
      if($(this).attr('type')=='checkbox'){
        if($(this).is(':checked'))
          values += '&'+$(this).attr('name')+'=1';
        else
          values += '&'+$(this).attr('name')+'=0';
      }else if($(this).attr('type')=='radio' && !radios[$(this).attr('name')]){
        radios[$(this).attr('name')] = true;
        values += '&'+$(this).attr('name')+'='+$(form_selector).find("input[name='"+$(this).attr('name')+"']:checked").val();
      }else if($(this).attr('type')!='radio'){
        values += '&'+$(this).attr('name')+'='+$(this).val();
      }
    }
  });
  
  for (i in groups) {
    if(!groups[i]){
      $('.required-one[group='+i+']').addClass('error');
      errors++;
    }else{
      $('.required-one[group='+i+']').removeClass('error');
    }
  }
  if(errors>0){
    showMessageBox('<b>Wystąpił problem z zapisem.</b><br /><br />Proszę sprawdzić dane.', 5000);
    return false;
  }else{
    if(ajax){
      $(form_selector).unbind('submit');
      $(form_selector).submit(function() {
        $.ajax({
          url: "/ajax.php",
          type: "POST",
          data: $(this).attr('action')+""+values,
          dataType: "xml",
          beforeSend: function() {
            $(".form-loading").show();
          },
          success: function(xml) {
            var status = $(xml).find("status").text();
            if(status!='ok') {
              var errors = $(xml).find("error");
              errors.each(function(i, val) {
                var field = $(val).find("field").text();
                $(form_selector).find('[name='+field+']').addClass('error');
              });
              showMessageBox('<b>Wystąpił problem z zapisem.</b><br /><br />Proszę sprawdzić dane.', 5000);
            }else{
              $(form_selector+' .error').removeClass('error');
              showMessageBox('<b>Dane zaktualizowane</b>', 5000);
            }
          },
          complete: function() {
            $(".form-loading").hide();
          }
        });
        return false;
      });
    }
    $(form_selector).submit();
  }
};
//////////////////////////////////////////////////////////////////

function setAvatarImg(filename, fileurl, imgid){
	if(filename && fileurl && imgid){
		var date = new Date();
		$('.avatar-area #'+imgid).attr('src', fileurl+'115x115_'+filename+'?'+date.getTime());
	}
}

