var al_sack = new sack();
var modal;
var login_load = '<div class="user-form"><p class="login-load">Загрузка...</p></div><div class="user-form-footer"></div>';

function set_uploader() {
  var uID = jQuery('#user-id').attr('value');
  jQuery('#upload1').upload({
    method: 'post',
    enctype: 'multipart/form-data',
    action: '/upload.php?user-ID='+uID,
    onSubmit: function() {
      jQuery('#p_avatar').attr({src:'/avatars/loading.gif'});
      jQuery('#progress1').text('Отправка файла...');
    },
    onComplete: function(data) {
      var s = data.split('|');
      if (s[0] == 3) {
        jQuery('#progress1').text('');
        jQuery('#p_avatar').attr({src:s[1]+'?nocache='+(new Date().getTime() / 1000) });
      } else
        jQuery('#progress1').text(data);
    }
  });
}

function setModal() {
  if (jQuery('#prof_close').lenght > 0) jQuery('#prof_close').addClass('disable');  
  modal = new Control.Modal($('modal'),{
    overlayOpacity: 0.75,
    className: 'modal',
    closeOnClick: false,
    fade: true
  });             
};

function closeModal() {
  //jQuery('#modal').attr({href:'/profile/?nocache='+(new Date().getTime() / 1000) });
  jQuery('#control_window_2').load('/profile/');
  modal.close();
}

function saveProfile() {
  if (!jQuery('#prof_save').is('.disable')) {
    al_sack.setVar("email", jQuery('#pemail').attr('value'));
    al_sack.setVar("pwd", jQuery('#ppass').attr('value'));
    al_sack.setVar("name", jQuery('#name').attr('value'));
    al_sack.setVar("city", jQuery('#city').attr('value'));
    al_sack.requestFile =  "/saveinfo.php";
    al_sack.method = "POST";
    al_sack.onError = al_ajaxError;
    al_sack.onCompletion = al_profileHandleResponse;
    al_sack.runAJAX();
    al_status = 1;
  }
}

function bindpass2 () {
  if (document.getElementById('upass').value && /^[^@]+@[^@]+$/.test(jQuery('#uemail').attr('value')) && /^.+$/.test(jQuery('#upass').attr('value'))) {
    jQuery('#registerNow').removeClass('disable');
  } else {
    jQuery('#registerNow').addClass('disable');
  }
}
function login_functions() {
  if (jQuery('#signOut').length > 0) return;
  var signInNow = document.getElementById('signInNow');
  var registerNow = document.getElementById('registerNow');
  
  var uemail = document.getElementById('uemail');
  if (uemail) {
    var uemailLabel = document.getElementById('uemailLabel');
    if(uemail.value != '') {
      uemailLabel.style.display = 'none';
    }
    else{
      uemail.onfocus = function() {
              uemailLabel.style.display = 'none';        
      }        
      uemail.onblur = function() {
          if(uemail.value != ''){
              uemailLabel.style.display = 'none';        
          }
          else{
              uemailLabel.style.display = 'block';
          };
      }        
    };
    uemail.onclick = function() {
      uemailLabel.style.display = 'none';
      uemail.focus();
    }  
  }  
  
  var upass = document.getElementById('upass');
  if (upass) {
    var upassLabel = document.getElementById('upassLabel');
    if(upass.value != ''){
        upassLabel.style.display = 'none';
    }
    else{
        upass.onfocus = function() {
              upassLabel.style.display = 'none';        
        }        
        upass.onblur = function() {
          if(upass.value != ''){
              upassLabel.style.display = 'none';        
          }
          else{
              upassLabel.style.display = 'block';
          };
        }        
    };
    upass.onclick = function() {
        upassLabel.style.display = 'none';
        upass.focus();
    } 
  }



  var email = document.getElementById('email');
  var emailLabel = document.getElementById('emailLabel');
  if (email) {
    if(email.value != '') {
        emailLabel.style.display = 'none';
    }
    else{
        email.onfocus = function() {
                emailLabel.style.display = 'none';        
        }        
        email.onblur = function() {
            if(email.value != ''){
                emailLabel.style.display = 'none';        
            }
            else{
                emailLabel.style.display = 'block';
            };
        }        
    };
    email.onclick = function() {
        emailLabel.style.display = 'none';
        email.focus();
    }    
    
    jQuery('#login label').bind('mousemove', function() {
      if (jQuery(this).is('.error')) {
        jQuery(this).hide().prev().each(function() {this.focus(); });
      }
      return false;
    })
  }
  
  var pass = document.getElementById('pass');
  var passLabel = document.getElementById('passLabel');
  if (pass) {
    if(pass.value != ''){
        passLabel.style.display = 'none';
    }
    else{
        pass.onfocus = function() {
                passLabel.style.display = 'none';        
        }        
        pass.onblur = function() {
            if(pass.value != ''){
                passLabel.style.display = 'none';        
            }
            else{
                passLabel.style.display = 'block';
            };
        }        
    };
    pass.onclick = function() {
        passLabel.style.display = 'none';
        pass.focus();
    } 
  }

  jQuery('#uemail').add('#upass').bind('keyup', bindpass2).bind('keydown', function(event) {
    var key = event.charCode ? event.charCode : event.keyCode;
    if (key == 13) {
      jQuery('#registerNow').trigger('click');
      this.blur();
    }
  });

  jQuery('#registerNow').bind('click', function() {
    if (!jQuery(this).is('.disable')) {
      al_sack.setVar("log", jQuery('#uemail').attr('value'));
      al_sack.setVar("pwd", jQuery('#upass').attr('value'));
      
//      var reg = /^.*@/;
//      var arr = reg.exec(jQuery('#uemail').attr('value'));
//      var n = arr[0];
//      var name = n.substring(0, n.length - 1);
//      al_sack.setVar("username", name);
      al_sack.setVar("username", jQuery('#uemail').attr('value'));
      
      al_sack.requestFile = "/wp-content/plugins/ajax-login/register.php";
      al_sack.method = "POST";
      al_sack.onError = al_ajaxError;
      al_sack.onCompletion = al_registerHandleResponse;
      al_sack.runAJAX();
      al_status = 1;

    }
    return false;
  });
  
  jQuery('#email').add('#pass').bind('keyup', function() {
    if (document.getElementById('pass').value && /^[^@]+@[^@]+$/.test(jQuery('#email').attr('value')) && /^.+$/.test(jQuery('#pass').attr('value'))) {
      jQuery('#signInNow').removeClass('disable');
    } else {
      jQuery('#signInNow').addClass('disable');
    }
  }).bind('keydown', function(event) {
    var key = event.charCode ? event.charCode : event.keyCode;
    if (key==13) {
      jQuery('#signInNow').trigger('click');
      this.blur();
    }
  });

  jQuery('#signInNow').bind('click', function() {
    if (!jQuery(this).is('.disable')) {
      al_sack.setVar("log", jQuery('#email').attr('value'));
      al_sack.setVar("pwd", jQuery('#pass').attr('value'));
      al_sack.requestFile =  "/wp-content/plugins/ajax-login/login.php";
      al_sack.method = "POST";
      al_sack.onError = al_ajaxError;
      al_sack.onCompletion = al_loginHandleResponse;
      al_sack.runAJAX();
      al_status = 1;
    }
    return false;
  });
  
  jQuery('#forgetLink').bind('click', function() {
    if (!jQuery(this).is('.disabled')) {
      al_sack.setVar("email", jQuery('#email').attr('value'));
      al_sack.requestFile =  "/wp-content/plugins/ajax-login/lostpassword.php";
      al_sack.method = "POST";
      al_sack.onError = al_ajaxError;
      al_sack.onCompletion = al_forgetHandleResponse;
      al_sack.runAJAX();
      al_status = 1;
    }
    return false;
  });
}

function logout_functions() {
  if (jQuery('#signOut').length == 0) return;
  jQuery('#signOut').bind('click', function() {
    jQuery('div.account').html(login_load).load('/logout.php', function() {
      login_functions(); 
      //if (jQuery('#forum').length > 0) jQuery('#forum').addClass('disable').attr({href:'#'});
      if (jQuery('#comment-div').length > 0) jQuery('#comment-div').load('/comments');
      new Control.Tabs('tabs');
    });
    return false;
  })
}

function al_profileHandleResponse() {
  //jQuery('#invis').text(al_sack.response);
  var s = al_sack.response.split("|");
    if (s[0] == 3) {
      closeModal();
      //jQuery('#l_avatar').attr({src:'/avatars/loading.gif'}); 
      jQuery('div.account').load('/login', function() { setModal(); logout_functions(); jQuery('#l_avatar').attr({src:jQuery('#l_avatar').attr('src') + '?nocashe='+(new Date().getTime() / 1000) }); });
    } else if (s[0] == 2) {
            jQuery('#ppassLabel').html(s[1]).show().addClass('error');
    } else if (s[0] == 1) {
            jQuery('#pemailLabel').html(s[1]).show().addClass('error');
    }
}

function al_forgetHandleResponse() {
  var s = al_sack.response.split("|");
    if (s[0] == 3) {
            alert(s[1]);
    } else if (s[0] == 2) {
      alert(s[1]);
    } else if (s[0] == 1) {
            jQuery('#emailLabel').html(s[1]).show().addClass('error');
    }
}

function al_loginHandleResponse() {
  var s = al_sack.response.split("|");
  if (s[0] == 3) {
    //if (jQuery('#forum').length > 0) jQuery('#forum').attr({href:'/forum/'}).removeClass('disable');
    if (jQuery('#comment-div').length > 0) jQuery('#comment-div').load('/comments');
    jQuery('div.account').html(login_load).load('/login', function() { setModal(); logout_functions(); });
  } else if (s[0] == 2) {
    jQuery('#passLabel').html(s[1]).show().addClass('error');
  } else if (s[0] == 1) {
    jQuery('#emailLabel').html(s[1]).show().addClass('error');
  }
}

function al_registerHandleResponse() {
  var s = al_sack.response.split('|');
  if (s[0] == 3) {
    jQuery('div.account').html(login_load);
    al_sack.setVar("log", jQuery('#email').attr('value'));
    al_sack.setVar("pwd", jQuery('#pass').attr('value'));
    al_sack.requestFile =  "/wp-content/plugins/ajax-login/login.php";
    al_sack.method = "POST";
    al_sack.onError = al_ajaxError;
    al_sack.onCompletion = al_loginHandleResponse;
    al_sack.runAJAX();
    al_status = 1;
  } else if (s[0] == 2) {
    jQuery('#upassLabel').html(s[1]).show().addClass('error');
  } else if (s[0] == 1) {
    jQuery('#uemailLabel').html(s[1]).show().addClass('error');
  }
  jQuery(this).html('');
}

function al_ajaxError() {
  alert("Извините, произошла ошибка при запросе данных с сервара.\nПопробуйте позже, пожалуйста.\nЕсли ошибка будет повтарятся, пожалуйста обращайтесь к администрации сайта.");

  alert(al_sack.responseStatus[0] + ':\n' + al_sack.response);
  al_sack = new sack();
}

jQuery(document).bind('ready', login_functions).bind('ready', logout_functions).bind('ready', setModal);