var MSG =
{
      DATA_LOAD_FAILURE : "Ошибка загрузки данных",
      INPUT_ACTIVE_EMAIL : "Введите существующий адрес",
      PASSWORD_SHOULD_BE_LONGER : "Пароль должен быть длинее 6 символов",
      PASSWORD_NOT_SIMILAR : "Пароли не совпадают",
	  AVATAR_UPLOAD_START: "Пожалуйста ждите...",
	  AVATAR_UPLOAD_SUCCESS: "Ваш аватар успешно загружен"      
};

var Profile =
{    
     
     init : function()
     {        
         //$.getJSON("http://www.zigzagz.net/testAuth/auth/get-user-profile?callback=?",
          zwsGetJSON("get-user-profile",
             {
             },
             function(o){
                 if (o.status == 401){
                      parent.location = "http://www.zigzagz.net/login.html?continueUrl=" + encodeURIComponent(parent.location + "");
                 } else if (o.ok){
                             for (i in o){
                                 if (i == "ok") continue;
                                 	$("#" + i).val(o[i]);
                             }
                                 } else {
                                          Profile.message("DATA_LOAD_FAILURE");
                                        }
                        }, "testAuth/auth/");
          //$.getJSON("http://www.zigzagz.net/testAuth/auth/get-user-credentials?callback=?",
           zwsGetJSON("get-user-credentials",
             {

             },
             function(o){
                 if (o.status == 401){
                     parent.location = "http://www.zigzagz.net/login.html?continueUrl=" + encodeURIComponent(parent.location + "");
                 } else if (o.ok){
                               for (i in o){
                                 if (i == "ok") continue;
                                 $("#" + i).val(o[i]);
                               }
                               } else {
                                         Profile.message("DATA_LOAD_FAILURE");
                                      }
                       },"testAuth/auth/");
		var serverAddress = "http://www.zigzagz.net/PhotoBook/";					   
		//$.getJSON(serverAddress + "GetUserAvatar?callback=?",
                zwsGetJSON("GetUserAvatar",
                          {},function(data){
			if(data.status=="200")
				$("#avatarImage").css("background-image","url("+data.url+")");
		}); 
					   
		$("#btnSubmit").click(function(){
			Profile.uploadAvatar();
		});
                
                
        
     },
	 
	 uploadAvatar: function()
		{   			
		    if(!$("#fileUploadForm input[name='file']").attr("value"))
		        return;
                  
                  
                  var filePath = $("#fileUploadForm input[name='file']").attr("value");
			var i = filePath.lastIndexOf(".");            
            if(i>0 && MIMEType(filePath.substr(i+1))==false){
                alert("Запрещенный тип файла!\nРазрешены файлы только формата jpeg и gif");	                
                return false;
            }
            
			$("#uploadComplete").addClass("hide");
			$("#waitMessage").removeClass("hide");			
		    
		    var redirect = "http://www.zigzagz.net/messageDispatcher.html";
		    var callback = "uploadAvatarComplete";
		    var serverAddress = "http://www.zigzagz.net/PhotoBook/";
                    
		    loadingBox(2);
                    
		    zwsGetJSON("AvatarUploadSignerServlet",
                                          {redirect: redirect, callback:callback},function(dt){
		           if(dt.status=="200"){          						                    
						$("#fileUploadForm input[name='policy']").attr("value",dt.policy);
						$("#fileUploadForm input[name='signature']").attr("value",dt.signature);
						$("#fileUploadForm input[name='acl']").attr("value",dt.acl);
						$("#fileUploadForm input[name='key']").attr("value",dt.key);
						$("#fileUploadForm input[name='success_action_redirect']").attr("value",dt.success_action_redirect);
						$("#fileUploadForm input[name='file']").removeAttr("disabled");
						
						var filePath = $("#fileUploadForm input[name='file']").attr("value");
				        var i = filePath.lastIndexOf(".");        
				        if(i>0){            
				            $("#fileUploadForm input[name='Content-Type']").attr("value", MIMEType(filePath.substr(i+1)));
				        }
						//alert($("#fileUploadForm",div).html());
//						var opt = {
//							success: uploadComplete
//						};
						$("#fileUploadForm").ajaxSubmit();
		           }
		           else{
		                alert("error");
		           }
		    });
		},
     
     message : function(msg)
     {          
           $("#statusMessage").html(MSG[msg]);
     },
     
     submit : function() {
      		 
			 if ( !zValidate.checkForValid("profileFormF") ) { return false; }
             loadingBox(1);
             return true;
            
            },
     
      submitAccount : function()
      {
          
           
           var oldPassword = $("input#oldPassword").val();
           var userPassword = $("input#userPassword").val();
           var userPassword2 = $("input#userPassword2").val();
           
           if ( !zValidate.checkForValid("registerFormPassword") ) { return false; }

           
           
           loadingBox(4);
           //$.getJSON("http://www.zigzagz.net/testAuth/auth/want-edit-credentials?callback=?",
           zwsGetJSON("want-edit-credentials",
           {
 
                postData : Base64.encode(
                                         JSON.stringify(
                                                        {
                                                             responseHtmlUrl:"http://www.zigzagz.net/postSupport_iframe.html",
                                                             workerUrl: "http://www.zigzagz.net",
                                                             successRegistrationUrl: "http://www.zigzagz.net/success-credentials-update.html"
                                                        }
                                                        )
                                         )
                
           },
           function(dt) {
                PreregistrationResponse(dt);
                         },"testAuth/auth/"
                         
                         );
      
           return false;

     },
     submitEmail : function()
      {
          
           
           var email = $("#email").val();
           var password = $("#userPasswordForEmail").val();
           
           if ( !zValidate.checkForValid("registerFormEmail") ) { return false; }

           loadingBox(3);
           zwsGetJSON("want-edit-email",
           {
 
                postData : Base64.encode(
                                         JSON.stringify(
                                                        {
                                                             responseHtmlUrl:"http://www.zigzagz.net/postSupport_iframe.html",
                                                             workerUrl: "http://www.zigzagz.net",
                                                             successRegistrationUrl: "http://www.zigzagz.net/success-credentials-update.html"
                                                        }
                                                        )
                                         )
                
           },
           function(dt) {
                PreEmailChangeResponse(dt);
                         },"testAuth/auth/");
      
           return false;

     },
     submitProfile : function()
     {
          
          
     }     
     
    
};

	  
$(document).ready(function(){
	Profile.init();
});

function MIMEType(ext)
{
    ext = ext.toUpperCase();
    if(ext=="JPG" || ext=="JPEG")
        return "image/jpeg";
    else if(ext=="GIF")
        return "image/gif";
    else if(ext=="PNG")
        return "image/png";
    else
        return false;
}

function uploadAvatarComplete(data)
{	
	$("#avatarImage").css("background-image","url("+data.url+")");
        continueEditBlock(2);
        
}

function uploadComplete(resp, status, form)//iframeName, params)
{
    if(!form) 
        return;
    
    alert("upload success");

}

function loadingBox(fragment)
{
       $("#fragment-"+fragment+" form").hide();
       $("#fragment-"+fragment+" .continueBlock").removeClass("hide");
       $("#fragment-"+fragment+" .continueBlockMsg").html("<img src='/img/ajax-loader.gif'> <br /><div class='header3'>Пожалуйста, ждите...</div>");
       
}
function continueEditBlock(fragment)
{
      
       var msgEdit = { 1 : "<div class='header3'>Данные обновлены! <br /><br /><input type='button' onclick='editAgain(1);' value='Редактировать' /></div>" ,
                       3:  "<div class='header3'>Запрос отправлен, проверье ваш email.<br /><br /><input type='button' onclick='editAgain(3);' value='Редактировать' /></div>" ,
                       4 : "<div class='header3'>Пароль успешно изменён!<br /><br /><input type='button' onclick='editAgain(4);' value='Редактировать' /></div>",
                       2 : "<div class='header3'>Аватар успешно загружен! <br /><br /><input type='button' onclick='editAgain(2);' value='Редактировать' /></div>"
                       };
       
       $("#fragment-"+fragment+" .continueBlockMsg").html(msgEdit[fragment]);
}
function editAgain(fragment)
{
       $("#fragment-"+fragment+" .continueBlock").addClass("hide");
       $("#fragment-"+fragment+" form").show();
}
function PreregistrationResponse(dt)
{
      
      var oldPassword = $("input#oldPassword").val();
      var userPassword = $("input#userPassword").val();
      var userPassword2 = $("input#userPassword2").val();
      
      
      
      try{
            if (dt.status == 401){
                                         parent.location = "http://www.zigzagz.net/login.html?continueUrl=" + encodeURIComponent(parent.location + "");
                                                    } else if (dt.ok) {
                                                                  
                                                                  var iframe;

                                                                  if (window.frames["postFrame"])
                                                                       iframe = window.frames["postFrame"];
                                                                  else
                                                                       iframe = $("iframe")[0];
                                                                  
                                                                  iframe.formSubmit(dt.policy, {
                                                                                                
                                                                                                oldPassword: oldPassword,
                                                                                                userPassword: userPassword
                                                                                                });
                                                                       }
                               } catch (e){

                                              throw e;
                                          }
      
}
/** Смена Email'a **/
function PreEmailChangeResponse(dt)
{
      var email = $("#email").val();
      var password = $("#userPasswordForEmail").val();
      try{
            if (dt.status == 401){
                                         parent.location = "http://www.zigzagz.net/login.html?continueUrl=" + encodeURIComponent(parent.location + "");
                                                    } else if (dt.ok) {
                                                                  
                                                                  var iframe;

                                                                  if (window.frames["postFrame"])
                                                                       iframe = window.frames["postFrame"];
                                                                  else
                                                                       iframe = $("iframe")[0];
                                                                  
                                                                  iframe.formSubmit(dt.policy, {
                                                                                                newEmail: email,
                                                                                                password: password
                                                                                                });
                                                                       }
                               } catch (e){

                                              throw e;
                                          }
      
}


	 
function registrationResponse(dt)
{
 
      if ( dt.status == "success" )
      {
             if (dt.action == "email")    { continueEditBlock(3); }
             if (dt.action == "password") { continueEditBlock(4); }
      }else
      {
             
             if (dt.action == "email") {
                   
                   if (dt.fields.newEmail)
                   {     $("#fragment-3 .continueBlockMsg").html("<div class='header3'>Вы ввели неправильный пароль.<br /><br /><input type='button' onclick='editAgain(3);' value='Редактировать' /></div>");
                   }else{$("#fragment-3 .continueBlockMsg").html("<div class='header3'>Такой email уже используется в системе.<br /><br /><input type='button' onclick='editAgain(3);' value='Редактировать' /></div>");}
                  }
             if (dt.action == "password") {
                  $("#fragment-4 .continueBlockMsg").html("<div class='header3'>Вы ввели неправильный пароль.<br /><br /><input type='button' onclick='editAgain(4);' value='Редактировать' /></div>");
                  }
      }
}
function submitResult(dt)
{
      if (dt.ok)
      {
             continueEditBlock(1);
      }
}