// JavaScript Document
function changeAvatar(user_name) {
  //var url = RESOURCE_HOST+"/avatar/upload/user?referInfo="+encodeURIComponent(BOOKMARK_HOST+"/user_mana2/upload_avatar_result");
  var url = RESOURCE_HOST+"/avatar/upload/user?id="+user_name+"&referInfo="+encodeURIComponent(BOOKMARK_HOST+"/user_mana2/upload_avatar_result");
  var w = window.open(url, null, "width=380,height=200,left=0,top=0,status=no,resizable=no");
}

function deleteAvatar() {
	  try{ 
	  var url = '/user_mana2/delete_avatar';
	  new Ajax.Request(url, 
					   {asynchronous:true, 
						evalScripts:true, 
						onLoading:function(request){deleteAvatarLoading(request);}, 
						onComplete:function(request){deleteAvatarComplete(request);}
					   }); 
	  return false;
  }catch(e) {
	  return false;
  }	
}

function deleteAvatarLoading(request) {
   showCentralNoticer(WORD_3);
}

function deleteAvatarComplete(request) {
  if(request.status=="200") {
	  refreshAvatarAfterDelete();
	  updateCentralNoticer(ALE_13);
	  hideCentralNoticer(1);
  }else {
	  updateCentralNoticer(EXC_2);
	  hideCentralNoticer(5);  
  }
}
function refreshAvatar(avatar_url) {
  var avatar = $("avatar");
  avatar.src = avatar_url+"?"+new Date();
}

function renderGDisplay() {
	 $("dRealName").innerHTML = $F("realName");
	 $("dEmail").innerHTML = $F("email");
	 $("dSignature").innerHTML = $F("signature");
}

function refreshAvatarAfterUpload(file_uri) {
  refreshAvatar(file_uri);  
  
}
function refreshAvatarAfterDelete(){
  var file_uri = user_avatar_uri(USER_DEF_AVATAR, "96");
  refreshAvatar(file_uri);
}

function user_avatar_uri(fileName, size) {
  var uri = USER_AVATAR_URI+"/"+fileName+"_"+size+".jpg";
  return uri;
}

function changeCountry() {
  var country = $("countrySelector");
  if(country.value!="US" && country.value!="CN" && country.value!="JP") {
    $("regionInput").style.display = "";
    $("regionSelector").style.display = "none";    
  }else {
    loadRegionCode(country.value);
  }
  $("regionInput").value = "";
}
function loadRegionCode(countryCode) {
          var url = "/profile_mana/load_region_code?c_code="+countryCode;
          loadRegionCodeLoading();
	  new Ajax.Request(url, 
			  {asynchronous:true, 
			  evalScripts:false,
                          requestHeaders: {Accept: 'application/json'},
			  onComplete:function(request){loadRegionCodeComplete(request);}
			  }); 
	  return false;
}
function loadRegionCodeLoading() {
  $("regionSelector").style.display = "none";
  $("regionInput").style.display = "none";
  loading("regionLoader");
}
function loadRegionCodeComplete(request) {
  if(request.status=="200") {
    loadComplete("regionLoader");
    $("regionSelector").style.display = "";
    var regionCode = eval(request.responseText);
    //console.log(regionCode);
    makeRegionCode(regionCode);
  }else{
  }
}
function makeRegionCode(regionCode) {
    $("regionSelector").options.length = 0;
    for(var i=0; i<regionCode.length; i++) {
      var option = document.createElement("option");
      option.value = regionCode[i][0];
      option.innerHTML = regionCode[i][1];
      $("regionSelector").appendChild(option);
    }
}
function changeRegion() {
  $("regionInput").value = $F("regionSelector");
}

function saveProfileBefore() {
  if (!isValidEmail("email")) return false;
  if (!isValidRealname()) return false;
  return true;
}

function isValidEmail(ID) {
  try{
  var email = $(ID);
  var validator = new Validator();
  if(!validator.IsEmail(email.value)) {
    email.focus();
    flashNotice2(ALE_8, "noticer_email");
    return false;
  }else {
    if($("noticer_email") && $("noticer_email").innerHTML==ALE_8) {
      hideNotice2("noticer_email");
    }
    return true
  }
  }catch(e) {
    return false;
  }
}
function isValidRealname() {
    try { 
        var realName_f = $("first_name");
        var realName_l = $("last_name");
        if(realName_f.value.trim()=="") {
            flashNotice2(ALE_14, "noticer_real_name");
            realName_f.focus();
            return false;
        }
        if(realName_l.value.trim()=="") {
            flashNotice2(ALE_14, "noticer_real_name");
            realName_l.focus();
            return false;
        }
        hideNotice2("noticer_real_name");
        return true
    }catch(e) {
        return false;
    }
}

function selectAvatar(index) {
      var url = "/profile_mana/select_avatar?avatar_index="+index;
      showCentralNoticer(DIS_10);
	  new Ajax.Request(url, 
			  {asynchronous:true, 
			  evalScripts:false,
			  onComplete:function(request){
			     hideCentralNoticer();
			     var avatarElement = $("avatar");
			     avatarElement.src = avatarElement.src.replace(/user\/.*\.jpg/, "user/"+USER_DEF_AVATAR+"_"+index+"_96.jpg");
			  }
			  }); 
	  return false;
}

function changeMonth(month){     
    var month = $("month").value 
    var old_day = $("day").value
    if(month == 0) return;
    var day_max_index = 31;
    switch(month){        
        case "1":
        case "3":
        case "5":
        case "7":
        case "8":
        case "10":
        case "12":
            day_max_index = 31
            break;
        case "2":
            day_max_index = 28
            break;
        case "4":
        case "6":
        case "9":
        case "11":
            day_max_index = 30
            break;            
    }
    $("day").innerHTML = "";
    var option = document.createElement("option")
    option.value = 0;
    option.innerHTML = "Day:";
    $("day").appendChild(option);
    for(var i = 1;i <= day_max_index;i++){
        var option = document.createElement("option")
        option.value = i;
        option.innerHTML = i;
        $("day").appendChild(option);
    } 
    $("day").value = old_day;
}
function set_privacy(elem_id){
    $(elem_id).style.display = "none";
    var select_id = elem_id.replace("show_","set_");
    $(select_id).style.display = "";
    $(elem_id.replace("show_","cancel_")).style.display = "";
}
function save_privacy(elem_id){
	//only for IE6
	if($(elem_id).style.display == "none")return;
	//
    var privacy_value = $(elem_id).value;
    var id = elem_id.replace("set_privacy_","")
    var params =id + ":"+ privacy_value;
    showCentralNoticer("update privacy of " + id);
    new Ajax.Request(save_privacy_url,{method:'post',
                              parameters:{value:params},
			      onSuccess:function(transport){
                                  hideCentralNoticer();
                                  $(elem_id.replace("set_","show_")).style.display = "";
                                  $(elem_id).style.display = "none";
                                  $(elem_id.replace("set_","cancel_")).style.display = "none";
                                  if(id == "birthday"){
                                      $(elem_id.replace("set_","show_")).innerHTML = PRIVACY_BIRTHDAY_CODE[transport.responseText];
                                  }
                                  else if(id == "wall_read"){
                                    wall_privacy = parseInt(transport.responseText);  
                                    read_privacy = wall_privacy%10;
                                    $(elem_id.replace("set_","show_")).innerHTML = PRIVACY_WALL_CODE[read_privacy];
                                    write_privacy = parseInt(wall_privacy/10) * 10;
                                    $("show_privacy_wall_write").innerHTML = PRIVACY_WALL_CODE[write_privacy];
                                    set_wall_write_option(read_privacy);
                                  }
                                  else if(id == "wall_write"){
                                    $(elem_id.replace("set_","show_")).innerHTML = PRIVACY_WALL_CODE[transport.responseText];
                                  }  
                                  else{
                                    $(elem_id.replace("set_","show_")).innerHTML = PRIVACY_CODE[transport.responseText];
                                  }
                              }                                
                          }
		    )
}
function cancel_change_privacy(elem_id){
    $(elem_id).style.display = "none";
    $(elem_id.replace("set_","cancel_")).style.display = "none";
    $(elem_id.replace("set_","show_")).style.display = "";    
}
function save_check_box_privacy(elem_id){
    var privacy_value = 1;
    if($(elem_id).checked)
        privacy_value = 0;
    var params =elem_id + ":"+ privacy_value;
    showCentralNoticer("update privacy of " + elem_id);
    new Ajax.Request(save_privacy_url,{method:'post',
                              parameters:{value:params},
			      onSuccess:function(transport){
                                  hideCentralNoticer();
                              }                                
                          }
		    )
}
function set_wall_write_option(read_privacy){
    $("set_privacy_wall_write").innerHTML = "";
    for(var i=1;i <= read_privacy && i<4;i++){        
        insert_html = "<option value='"+i*10+"'>"+PRIVACY_WALL_CODE[i*10]+"</option>";
        new Insertion.Bottom("set_privacy_wall_write",insert_html);
    }
}
//----------shout box----------------
function post_new_msg(){
        msg_body = $("msg_input").value;
        if(msg_body.empty()){
            $("post_noticer").style.display = "";
            return false;
        }else{
            $("post_noticer").style.display = "none";
        }          
        url = "/profile_mana/post_message";
        showCentralNoticer("Post Message");
        new Ajax.Request(url,{method:'post',
                               parameters:{to:owner_id,
                                           msg:msg_body},
                                           onSuccess:function(transport){
                                                result = eval("(" + transport.responseText + ")");                                               
                                                try{
                                                msg = result["msg"];
                                                if(result["is_owner"] == 1){
                                                    insert_html = "<li id='msg_"+msg["p_id"]+"'><a href='/profile/"+msg["poster_u_name"]+"' title='See "+msg["poster_real_name"]+"'s profile' class='avatarLink_48'>"+ 
                                                              "<span class='avatarFrame'><img src='"+RESOURCE_HOST+"/images/avatar/user/"+msg["poster_u_name"]+"_48.jpg' class='avatarImg'/></span>"+ 
                                                              "<span id='status_"+msg["p_id"]+"' title='"+msg["poster_u_name"]+"' class='dUserName'>"+msg["poster_real_name"]+
                                                              "</span></a><a class='delete' href='javascript:void(0)' onclick='delete_post("+msg["p_id"]+")'><span>Delete</span></a>"+
                                                              "<h3><a href='/profile/"+msg["poster_u_name"]+"' title='See "+msg["poster_real_name"]+"'s profile'>"+msg["poster_real_name"]+"</a><span class='hint'>wrote on "+msg["created_at"]+"</span></h3>"+
                                                              "<blockquote>"+msg["body"]+"</blockquote>"+
                                                             "<div class='opt'><a class='linkOpt' href='/profile/"+msg["poster_u_name"]+"/shout_box'>[ Write on "+msg["poster_real_name"]+"'s Shout Box ]</a><a class='linkOpt' href='javascript:void(0)' onclick='delete_post("+msg["p_id"]+")'>[ Delete ]</a> </div>"+
                                                              "</li>";                                                       
                                                  }else{
                                                         insert_html = "<li id='msg_"+msg["p_id"]+"'><a href='/profile/"+msg["poster_u_name"]+"' title='See "+msg["poster_real_name"]+"'s profile' class='avatarLink_48'>"+ 
                                                              "<span class='avatarFrame'><img src='"+RESOURCE_HOST+"/images/avatar/user/"+msg["poster_u_name"]+"_48.jpg' class='avatarImg'/></span>"+ 
                                                              "<span id='status_"+msg["p_id"]+"' title='"+msg["poster_u_name"]+"' class='dUserName'>"+msg["poster_real_name"]+
                                                              "</span></a><a class='delete' href='javascript:void(0)' onclick='delete_post("+msg["p_id"]+")'><span>Delete</span></a>"+
                                                              "<h3><a href='/profile/"+msg["poster_u_name"]+"' title='See "+msg["poster_real_name"]+"'s profile'>"+msg["poster_real_name"]+"</a><span class='hint'>wrote on "+msg["created_at"]+"</span></h3>"+
                                                              "<blockquote>"+msg["body"]+"</blockquote>"+
                                                             "<div class='opt'><a class='linkOpt' href='/profile/"+msg["poster_u_name"]+"/shout_box'>[ Write on "+msg["poster_real_name"]+"'s Shout Box ]</a>"+
                                                              "</li>";
                                                  
                                                    }
                                                  new Insertion.Top("msgList",insert_html);     
                                                  $("msg_input").value = "";
                                                  markOneUserStatus("status_"+msg["p_id"])
                                                  hideCentralNoticer();
                                                  }catch(e){
                                                  hideCentralNoticer();
                                              }
                                           }                                           
                                           })
    }
function delete_post(p_id){
    if(!confirm(ALE_38)) return;
    self.location = "/profile_mana/delete_message?owner_id="+owner_id+"&post_id="+p_id+"&refer_info="+refer_info;
}    
function markOneUserStatus(id) {
    var usernameEls = [$(id)];
    var usernames = [];
    usernameEls.each(function(u) {
        Try.these(
            function() {usernames.push(u.name.toLowerCase());},
            function() {usernames.push(u.title.toLowerCase());}
        );
    });
    var url="/user_mana2/check_user_status";
    var params = "json_infos="+usernames.toJSON();
    new Ajax.Request(url, 
		       {asynchronous:true, 
			    evalScripts:false,
			    method:'get', 
			    onComplete:function(request){checkUserStatusCompleted(request, usernameEls)},
			    parameters:params
			    }); 
    //console.log(userNames);
}    
//-----------------------------------
//--------------edit other profile--------------------------------------------
function save_other_profile(name){
    value = $(name + "_input").value;
    validator = new Validator();
    if(value.empty() || !validator.IsUrl2(value)){
        $(name+"_noticer").style.display = "";
        return false;
    }else{
        $(name+"_noticer").style.display = "none";
    }
         
    showCentralNoticer("save "+name+" link");
    url = "/profile_mana/other_profile"
    new Ajax.Request(url,{method:'post',
                               parameters:{key:name,
                                           value:value},
                                           onSuccess:function(transport){
                                               result = eval("(" + transport.responseText + ")");
                                               $(name+"_show").innerHTML = result["url"];
                                               $(name+"_show").style.display = "";
                                               $(name+"_show").href = value;
                                               $(name + "_input").style.display = "none";
                                               $(name + "_cancel").style.display = "none";
                                               $(name + "_save").style.display = "none";
                                               $(name + "_edit").style.display = "";
                                               $(name+"_delete").style.display = "";
                                                hideCentralNoticer();
                                              }
                                           }                                           
                                           )
    
}
function cancel_other_profile(name){
        $(name+"_show").style.display = "";
        $(name + "_input").style.display = "none";
        $(name + "_cancel").style.display = "none";
        $(name + "_save").style.display = "none";
        $(name + "_edit").style.display = "";
        $(name+"_delete").style.display = "";
}
function edit_other_profile(name){
        $(name+"_show").style.display = "none";
        $(name + "_input").style.display = "";
        $(name + "_input").value = $(name+"_show").innerHTML;
        $(name + "_cancel").style.display = "";
        $(name + "_save").style.display = "";
        $(name + "_edit").style.display = "none";       
}
function delete_other_profile(name){
     if(!confirm(ALE_41)) return;
    showCentralNoticer("delete "+name+" link");
    url = "/profile_mana/other_profile"
    new Ajax.Request(url,{method:'post',
                               parameters:{key:name,
                                           value:""},
                                           onSuccess:function(transport){
                                               $(name+"_show").style.display="none";
                                               $(name+"_show").innerHTML = "";                                                                                              
                                               $(name+"_show").href = "javascript:void(0)";
                                               $(name + "_input").style.display = "";
                                               $(name + "_input").value = "";
                                               $(name + "_save").style.display = "";
                                               $(name + "_edit").style.display = "none";
                                               $(name + "_delete").style.display = "none";
                                               $(name + "_cancel").style.display = "none";
                                                hideCentralNoticer();
                                              }
                                           }                                           
                                           )
    
}
//--------------end edit other profile----------------------------------------