// The number of milliseconds between keystrokes to wait before performing a quick search.
//
// This should be tuned to maximize speed and usability without overloading the server with
// unnecessary searches
var QUICKSEARCH_KEY_TIMEOUT = 500;

//Set and uset waiting status
wait = function(item){
  document.body.style.cursor = 'wait';
};
endWait = function(item){
  document.body.style.cursor = 'default';
};

//Get current cursor position
getX = function(e) {
  if ( document.captureEvents ) {
    return e.pageX;
  } else if ( window.event.clientX ) {
    return window.event.clientX+document.documentElement.scrollLeft;
  }
  return 0;
};
getY = function(e) {
  if ( document.captureEvents ) {
    return e.pageY;
  } else if ( window.event.clientY ) {
    return window.event.clientY+document.documentElement.scrollTop;
  }
  return 0;
};

getTop = function(o,res){
  var nTop = null;
  if(o!=null){
    if(res==null){
      do{
      nTop += o.offsetTop;
      o = o.offsetParent;
      } while(o)
    }else{
      nTop = o.offsetTop;
    }
  }
  return nTop;
};
getLeft = function(o,res){
  var nLeft = null;
  if(o!=null){
    if(res==null){
      do{
      nLeft += o.offsetLeft;
      o = o.offsetParent;
      } while(o)
    }else{
      nLeft = o.offsetLeft;
    }
  }
  return nLeft;
};
function inRegion(x,y,el) {
  var result = false;
  try{
    result = (x > el.getLeft())&&(x<el.getLeft()+el.getSize()['x'])&&(y >el.getTop())&&(y <el.getTop()+el.getSize()['y']);
  } catch(e){}
  return result;
}

//Can see value
canSee = function(){
  if(navigator.appName.indexOf("Microsoft") > -1){
    return 'block';
  } else {
    return 'table-row';
  }
};
canSee_ = function(){
  return 'block';
};

//Disable
disableItems = function(items, disable){
  var val = disable?"disabled":"";
  items.each(function(item) {
    $(item).disabled = val;
  });
};

//Check submit key press
getKeyNum = function(e){
  var keynum=0;
  if(window.event){
    keynum = e.keyCode;
  } else if(e.which){
    keynum = e.which;
  }
  return keynum;
};
checkSubmit = function(e,func){
  var keynum = getKeyNum(e);
  if(keynum==13){
    setTimeout(func,1);
    e = new Event(e).stop();
  }
};

// Do nothing - handy when you need to supply a function but you don't want to actually do anything
function pass() {
  return false;
}

function updateBookCount() {
//  try{
    updateBookshelfCount();
  //}catch(e){}
}

//Cookie functions
function createCookie(name,value,minutes) {
  var expires = "";
  if (minutes) {
    var date = new Date();
    date.setTime(date.getTime()+(minutes*60*1000));
    expires = "; expires="+date.toGMTString();
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {
      c = c.substring(1,c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

//Load JS file
function loadJS(filename,id) {
    try{
    return $(filename).id;
  }catch(e){
     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.id = id;
     script.type = 'text/javascript';
     script.src = filename;
     head.appendChild(script);
  }
  return id;
}

String.prototype.trim = function() {
  var a = this.replace(/^\s+/, '');
  return a.replace(/\s+$/, '');
};

function trim (str) {
	return str.replace(/^\s+|\s+$/g, '');
}

//Users list functions
getLastUn = function(str,rep){
  if(rep==null) {
    rep = true;
  }
  var un = '';
  do{
    var pos1 = str.lastIndexOf(",");
    var pos2 = str.lastIndexOf(";");
    var pos = (pos1>pos2)?pos1:pos2;
    un = str.substring(pos+1).trim();
    str = str.substring(0,pos);
  }while(rep && str.length>0 && un=="");
  return un;
};

replaceLastUn = function(str,new_un,rep){
  if(rep==null) {
    rep = true;
  }
  var un = '';
  do{
    var pos1 = str.lastIndexOf(",");
    var pos2 = str.lastIndexOf(";");
    var pos = (pos1>pos2)?pos1:pos2;
    un = str.substring(pos+1).trim();
    str = str.substring(0,pos);
  }while(rep && str.length>0 && un=="");
  if(str!='') {
    str = str + "; " + new_un;
  } else {
    str = new_un;
  }
  return str;
};

normalizeUnList = function(str){
  var un_list = '';
  do{
    var pos1 = str.lastIndexOf(",");
    var pos2 = str.lastIndexOf(";");
    var pos = (pos1>pos2)?pos1:pos2;
    var un = str.substring(pos+1).trim();
    if(un!='') {
      un_list = un+"; "+un_list;
    }
    str = str.substring(0,pos);
  }while(str.length>0);
  str = un_list;
  return un_list;
};

function choosePage(id, number){
  try {
    $(id+'_page_number').value = number;
    return true;
  } catch (e) {
    return false;
  }
}

// Declaring variables used elsewhere (this isn't good)
var sb_timeout_id = 0,
    sb_elem,
    sb_params,
    sb_event = {},
    timeoutFunction;

// Auto-complete suggestion fields
function suggestBooks(elem, params, event, action) {
  sb_elem = elem;
  sb_params = params;
  // Clone event
  for (prop in event) {
    sb_event[prop] = event[prop];
  }
  // Clear timeout
  if (sb_timeout_id != 0) {
    clearTimeout(sb_timeout_id);
  }
  // Function for timeout
  timeoutFunction = function() {
    // Default action in case one hasn't been specified in the view/elsewhere
    if (!action) {
      action = 'suggestRecommendBooks';
    }
    ajax_list_externalFile = LIVING_SITE_URL + '/books/' + action +'/'+ new Date().getTime();
    ajax_showOptions(sb_elem, sb_params, sb_event);
  };
  // Set the timeout
  sb_timeout_id = setTimeout("timeoutFunction()", QUICKSEARCH_KEY_TIMEOUT);
}

// Alias the above function for its use elsewhere
function requestBookSuggestion (elem, params, event, action) {
  return suggestBooks(elem, params, event, action);
}

function suggestAuthorBooks (elem, params, event, action) {
  if (!action) {
    action = 'suggestBookshelfAuthorBooks';
  }
  return suggestBooks(elem, params, event, action);
}

function removeThisFriend(friendRecordId, confirmNotice)
{
  if (!confirmNotice) {
    confirmNotice = HOME_REMOVE_FRIEND_CONF;
  }

  if(confirm(confirmNotice))
  {
    urlGet = LIVING_SITE_URL + "/friends/delete/" + friendRecordId;
      new Request({
        url: urlGet,
        method: 'get',
        onComplete: function(data){
          chooseTab('friend');
        }
      }).send();
  }
}

function removeFriendById(friendId) {
  if(confirm(HOME_REMOVE_FRIEND_CONF)) {
    url = LIVING_SITE_URL + "/friends/deleteByFriendId/" + friendId + '/' + $time();
    new Request({
      url: url,
      method: 'get',
      onComplete: function(){
        openPendingList(true);
      }
    }).send();
  }
}

function confirmAddFriend(friendId, friendUsername)
{
  if (confirm(HOME_ADD_FRIEND_PREFIX + friendUsername + HOME_ADD_FRIEND_SUFFIX)) {
    addFriend(0, friendUsername, friendId);
  } else {
    try {
      uncheck_img_checkbox($('fr_' + friendId));
    } catch (ex) {}
  }
}
function addFriend(myId, friendUsername, friendId)
{
  var url = LIVING_SITE_URL+'/friends/addFriend/0/' + friendUsername + '/' + $time();
  new Request({
    url: url,
    method:'get',
    onSuccess: function(){
      var response = this.response["text"] || "no response text";
      if(response != '1') {
        try {
          toggle_img_checkbox($('fr_' + friendId));
        } catch (ex) {}
        alert(response);
      }
      else {
        $('fr_' + friendId).title = HOME_REMOVE_FRIEND_TITLE;
        alert(HOME_FRIEND_INVITED);
      }
    }
  }).send();
}

function removeFriend(friendRecordId, friendId)
{
  if(confirm(HOME_REMOVE_FRIEND_CONF)) {
      new Request({
        url: LIVING_SITE_URL + "/friends/delete/" + friendRecordId + '/' + $time(),
        method: 'get',
        onComplete: function(data){
          $('fr_' + friendId).title = HOME_ADD_FRIEND_TITLE;
          alert(HOME_REMOVED_FRIEND);
        }
      }).send();
  } else {
    try {
      check_img_checkbox($('fr_' + friendId));
    } catch (ex) {}
  }
}

var ie = (document.all) ? true : false;
function hideID(objID){
  var element = (ie) ? document.all(objID) : document.getElementById(objID);
  element.style.display="none";
}
function showID(objID){
  var element = (ie) ? document.all(objID) : document.getElementById(objID);
  element.style.display="block";
}

function getUploadFile() {
  document.frmUploadAvatar.submit();
}

function doLogin() {
  $('do_login_form').set('send', {
    onSuccess: function(data) {
      endWait();
      if(data == 1) {
        //Redirect to homepage
        window.location.replace('/');
        return true;
      } else {
        alert(data);
        return false;
      }
    }
  }).send();
  wait();
}

/*************LISTS*************/
isDisabled=function(it){
  var val = false;
  try{
    if($("_D"+it.id) && $("_D"+it.id).value==true) {
      val = true;
    }
  }catch(e){}
  return val;
};
disableItem=function(it){
  try{
    $("_D"+it.id).value = true;
  }catch(e){}
};
enableItem=function(it){
  try{
    $("_D"+it.id).value = false;
  }catch(e){}
};
disableItems = function(items){
  for(var i in items){
    if(typeof items[i] == 'object') {
      disableItem(items[i]);
    }
  }
};
enableItems = function(items){
  for(var i in items){
    if(typeof items[i] == 'object') {
      enableItem(items[i]);
    }
  }
};
imgChecked=function(it){
  if((typeof it) != 'object' || !it) {
    return false;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  return it.src.indexOf("_active")>=0;
};

getICValue=function(it){
  if((typeof it) != 'object' || !it) {
    return false;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  return $('_'+it.id).value;
};

toggle_img_checkbox=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_active")>=0){
    it.src = src.replace("_active","_inactive");
    if($("_L"+it.id)) {
      $("_L"+it.id).setStyle("font-weight","normal");
    }
  } else if(src.indexOf("_inactive")>=0){
    it.src = src.replace("_inactive","_active");
    if($("_L"+it.id)) {
      $("_L"+it.id).setStyle("font-weight","bold");
    }
  }
};

imgABChecked=function(it){
  if((typeof it) != 'object' || !it) {
    return false;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  var cimg = $("_CI"+it.id).value;
  return it.src.indexOf(cimg)>=0;
};
toggle_img_ab_checkbox=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  var cimg = $("_CI"+it.id).value;
  var uimg = $("_UI"+it.id).value;
  if(src.indexOf(cimg)>=0){
    it.src = src.replace(cimg,uimg);
    it.title = INFO_ADD_TO_BOOKSHELF;
    if($("_L"+it.id)) {
      $("_L"+it.id).setStyle("font-weight","normal");
      var ulb = $("_UL"+it.id).value;
      $("_L"+it.id).set('text', ulb);
    }
  } else if(src.indexOf(uimg)>=0){
    it.src = src.replace(uimg,cimg);
    it.title = INFO_REMOVE_FROM_BOOKSHELF;
    if($("_L"+it.id)){
      $("_L"+it.id).setStyle("font-weight","bold");
      var clb = $("_CL"+it.id).value;
      $("_L"+it.id).set('text', clb);
    }
  }
};
check_img_checkbox=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_inactive")>=0){
    it.src = src.replace("_inactive","_active");
    if($("_L"+it.id)) {
      $("_L"+it.id).setStyle("font-weight","bold");
    }
  }
};

uncheck_img_checkbox=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_active")>=0){
    it.src = src.replace("_active","_inactive");
    if($("_L"+it.id)) {
      $("_L"+it.id).setStyle("font-weight","normal");
    }
  }
};
//Highlight it
hlight=function(it) {
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_off")>=0){
    if($("_B"+it.id)) {
      $("_B"+it.id).style.background="";
    }
    it.src = src.replace("_off","_on");
  }
};
unhlight=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_on")>=0){
    if($("_B"+it.id)) {
      $("_B"+it.id).style.background=$("_B"+it.id).getParent().style.background;
    }
    it.src = src.replace("_on","_off");
  }
};
cbdown=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_inactive")>=0){
    it.src = src.replace("_inactive","_active");
  }
};
cbup=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  if((it.id.indexOf("_L")>-1) || (it.id.indexOf("_B")>-1)) {
    it = $(it.id.substr(2));
  }
  if(isDisabled(it)) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_active")>=0){
    it.src = src.replace("_active","_inactive");
  }
};

btdown=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_on")>=0){
    it.src = src.replace("_on","_active");
  }
};
btup=function(it){
  if((typeof it) != 'object' || !it) {
    return;
  }
  var src = it.src;
  if(src.indexOf("_active")>=0){
    it.src = src.replace("_active","_on");
  }
};

//More button
toggleMore = function(e) {
  var target = e.target || e.srcElement;
  var book_id = target.id.substr(2);
  var src = target.src;
  if (isMoreStatus(target) && $("M"+book_id)) {
    $("M"+book_id).style.display = canSee();
  } else {
    $("M"+book_id).style.display = "none";
  }
};
toggleMoreLess = function(it){
  var more_image = $("_more"+it.id).value;
  var less_image = $("_less"+it.id).value;

  var src = it.src;
  if(src.indexOf(more_image)>=0){
    it.src = src.replace(more_image,less_image);
  } else if(src.indexOf(less_image)>=0){
    it.src = src.replace(less_image,more_image);
  }

};
chooseMore = function(it){
  var more_image = $("_more"+it.id).value;
  var less_image = $("_less"+it.id).value;

  var src = it.src;
  if(src.indexOf(less_image)>=0){
    it.src = src.replace(less_image,more_image);
  }
};
chooseLess = function(it){
  var more_image = $("_more"+it.id).value;
  var less_image = $("_less"+it.id).value;

  var src = it.src;
  if(src.indexOf(more_image)>=0){
    it.src = src.replace(more_image,less_image);
  }
};
isMoreStatus = function(it){
  if((typeof it) != 'object' || !it) {
    return false;
  }
  var src = it.src;
  var less_image = $("_less"+it.id).value;
  if(it.src.indexOf(less_image)>=0) {
    return "less";
  }
  return false;
};

//Text Input Box
clearIBDefaultValue=function(el,default_value){
  if(el.value == default_value){
    el.value = "";
  }
  else {
    el.select();
  }
};
setIBDefaultValue=function(el,default_value){
  if(el.value == ""){
    el.value = default_value;
  }
};

setIBResetDefaultValue=function(el,default_value){
  el.value = default_value;
};

getIBDefaultValue=function(id){
  var val=null;
  try{
    val = $("dv_"+id).value;
  }catch(e){}
  return val;
};
getIBValue=function(id){
  var val = null;
  var default_val = null;
  try{
    if($(id)){
      val = $(id).value;
      default_val = $("dv_"+id).value; 
    }
  }catch(e){}
  if(val == default_val) {
    val = '';
  }
  return val;
};

//Popup menu
showPopupMenu=function(e,button,mn){
  mn.setStyle('left',getLeft(button));
  mn.setStyle('top',getTop(button)+22);
  mn.set('opacity', 1);
  e = new Event(e).stop();
};
hidePopupMenu=function(e,button,mn){
  cbup(button);
  try{
    mn.set('opacity', 0);
  }catch(e){}
  //e = new Event(e).stop();
};
getMenu=function(button){
  return $("_"+button.id);
};

//Popup menu
showPopupWindow=function(e,button,mn){
  mn.setStyle('left',button.getLeft());
  mn.setStyle('top',button.getTop()+22);
  mn.set('opacity', 1);
  e = new Event(e).stop();
};
hidePopupWindow=function(e,button,mn){
  cbup(button);
  try{
    mn.set('opacity', 0);
  }catch(e){}
  //e = new Event(e).stop();
};

//Page navigation
getPNvalues=function(id){
  var pn = 1;
  var ipp = 0;
  try{
    pn = $(id+"_page_number").value;
  }catch(e){}
  try{
    ipp = $(id+"_item_per_page").value;
  }catch(e){}
  if(pn=='undefined') {
    pn = 1;
  }
  if(ipp == 'undefined') {
    ipp = 0;
  }
  return {page_number:pn, items_per_page:ipp};
};

//Sort
getSortValues=function(id){
  var st = '';
  var sd = 'ASC';
  try{
    st = $(id+"_sort_type").value;
  }catch(e){}
  try{
    sd = $(id+"_sort_dir").value;
  }catch(e){}
  if(st == 'undefined') {
    st = '';
  }
  if(sd == 'undefined') {
    sd = 'ASC';
  }

  return {sort_type:st, sort_dir:sd};
};

setSortValues = function(id,sort_status){
  $(id+"_sort_type").value = sort_status.sort_type;
  $(id+"_sort_dir").value = sort_status.sort_dir;
};

var mn_ft = 1;
do_search = function(){
  if ($('mn_search').value.length < 2){
    show_alert(MENU_MINIMUM_CHARACTERS_NUMBER);
    return false;
  }
  return true;
};

reset_form = function(){
  document.search_form.mn_search.value = '';
  return true;
};

submit_search_form = function(){
  if(do_search()) {
    $('search_form').submit();
  }
};
show_alert = function(str){
  var size = $('mn_search').getSize();
  $('alert').setStyle('left', $('mn_search').getLeft());
  $('alert').setStyle('top', $('mn_search').getTop()+size.y);
  $('alert_content').set('html', str);
  $('alert').set('opacity', 1);
};
hide_alert = function(){
  $('alert').set('opacity', 0);
  $('mn_search').focus();
};

set_type = function(type){
  set_type_only(type);
  $('mn_search').focus();

};

set_type_only = function(type){
  var old_id = $('search_type').value;
  if($("i"+old_id)) {
    $("i"+old_id).className = '';
  }
  $('search_type').value = type;
  searchType = $("i"+type).get('text') || $("i"+type).textContent;
  $('mn_search_type').set('text', searchType);
  if($("i"+type)) {
    $("i"+type).className = 'selected';
  }
  mn_ft = 0;
};


sb_clear = function(el){
  var id = $('search_type').value;
  clearIBDefaultValue(el,$(id).get('text'));
};

sb_set = function(el){
  var id = $('search_type').value;
  setIBDefaultValue(el,$("i"+id).get('text'));
};

search_tag = function(tag,type){
  if(type==null) {
    type = 'tag';
  }
  $('search_type').value = 'subject';
  $('selected_tab').value = 'subject_'+type;
  $('mn_search').value = tag;
  if(do_search) {
    $('search_form').submit();
  }
};

var loginAttempts = 0;
function submitLogin() {
  new Request({
    url: '/users/login',
    method: 'post',
    data: {username:$('UserUsername').value, password:$('UserPassword').value},
    evalScripts: true,
    onComplete: function(data){
      if (data == 1) {
        window.location = "/";
      }
      else {
        loginAttempts++;
        if(loginAttempts > 2)
        {
          window.location.replace('/users/forgotPassword');
        }
        else
        {
          data += "<p>Number of attempts: "+loginAttempts+"</p>";
          document.getElementById('errLoginContainer').innerHTML = data;
          document.getElementById('UserPassword').value = "";
        }
      }
    }
  }).send();
}

function getValueFromCheckBox(chkId) {
  if(document.getElementById(chkId).getAttribute('src').indexOf('inactive') > 0) {
    return "0";
  } else {
    return "1";
  }
}

function submitUpdateProfile() {
  setValueForPermission();
  document.getElementById('agree_id').value = getValueFromCheckBox('chkAgreeCondition');

  $('frmRegisterAccount').set('send', {
    onSuccess:function(data) {
      endWait();
      var imgCaptchaMenu;
      if(data == 1) {
        //Redirect to homepage
        window.location.replace('/');
      } else if(data == 0) {
        document.getElementById('captchaValue').value = '';
        imgCaptchaMenu = document.getElementById('captchaMenu');
        imgCaptchaMenu.src = "/users/captcha_image?id=" + Math.random();
        document.getElementById('errMenuContainer').innerHTML = "There's an error when saving data. Please try again or contact administrator";
      } else {
        document.getElementById('captchaValue').value = '';
        imgCaptchaMenu = document.getElementById('captchaMenu');
        imgCaptchaMenu.src = "/users/captcha_image?id=" + Math.random();
        document.getElementById('errMenuContainer').innerHTML = data;
      }
    }
  }).send();
  wait();
}
function setValueForPermission()
{
  document.getElementById('fullname_permission_id').value = getValueFromCheckBox('chkFullname_P') + getValueFromCheckBox('chkFullname_R') +getValueFromCheckBox('chkFullname_F');

  document.getElementById('email_permission_id').value = getValueFromCheckBox('chkEmail_P') + getValueFromCheckBox('chkEmail_R') +getValueFromCheckBox('chkEmail_F');

  document.getElementById('dob_permission_id').value = getValueFromCheckBox('chkDOB_P') + getValueFromCheckBox('chkDOB_R') +getValueFromCheckBox('chkDOB_F');

  document.getElementById('gender_permission_id').value = getValueFromCheckBox('chkGender_P') + getValueFromCheckBox('chkGender_R') +getValueFromCheckBox('chkGender_F');

//  document.getElementById('country_permission_id').value = getValueFromCheckBox('chkCountry_P') + getValueFromCheckBox('chkCountry_R') +getValueFromCheckBox('chkCountry_F');
//
//  document.getElementById('state_permission_id').value = getValueFromCheckBox('chkState_P') + getValueFromCheckBox('chkState_R') +getValueFromCheckBox('chkState_F');

  document.getElementById('city_permission_id').value = getValueFromCheckBox('chkCity_P') + getValueFromCheckBox('chkCity_R') +getValueFromCheckBox('chkCity_F');

}

function createRadioFuntion(chkPermission)
{

  strCommandName = chkPermission.id.split('_')[0];
  strKind =  chkPermission.id.split('_')[1];

  var otherKind1 = "";
  var otherKind2 = "";

  if(strKind == "P")
  {
    otherKind1 = "R";
    otherKind2 = "F";
  }
  if(strKind == "R")
  {
    otherKind1 = "P";
    otherKind2 = "F";
  }
  if(strKind == "F")
  {
    otherKind1 = "P";
    otherKind2 = "R";
  }
  if(getValueFromCheckBox(chkPermission.id) == '0')
  {
    chkPermission.src = LIVING_SITE_URL + '/img/checkbox_active_off.png';
  }
  else
  {
    document.getElementById(strCommandName + "_" + otherKind1).src = LIVING_SITE_URL + '/img/checkbox_inactive_off.png';
    document.getElementById(strCommandName + "_" + otherKind2).src = LIVING_SITE_URL + '/img/checkbox_inactive_off.png';
  }

}

function changeStateMenu(cboCountry) {
  document.getElementById('txtMenuCity').value="";
  var url = LIVING_SITE_URL + "/countries/getStateByCountry/" + cboCountry.value;
  new Request({
    url: url,
    method: 'get',
    evalScripts: true,
    onComplete: function(){
      $('stateMenuContainer').set('html', this.response["text"]);
    }
  }).send();
}

sendRecommend=function(e){
  var book_id = $("book_id").get('value');
  var username = ($("rec_book").get('value')).toLowerCase();
  if(username.trim()=='' || username == $('rec_book').defaultValue.toLowerCase()){
    alert(BOOK_INVALID_EMAIL_USERNAME);
    return;
  }

    var val_email = new RegExp('^([A-Za-z0-9][A-Za-z0-9_\\-\\.\\+]*)@([A-Za-z0-9][A-Za-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[A-Za-z]{2,4}))$');
  var val_username = new RegExp('^[A-Za-z0-9][A-Za-z0-9_\\-\\.\\+ ]*$');

  if(!val_email.test(username)&&!val_username.test(username)){
    alert(BOOK_INVALID_EMAIL_USERNAME);
    return;
  }
  username = escape(username);
  e = new Event(e).stop();
  var url = LIVING_SITE_URL+"/books/recommend/"+book_id+"/"+username+"/"+ new Date().getTime();
  new Request({
    url: url,
    method: 'get',
    onComplete: function(){
      if (this.response["text"].substr(0,1)=="1"){
        alert(SUCCESS);
        $("rec_book").value = '';
        $("rec_book").focus();
      } else if (this.response["text"]=="2") {
        window.location.replace(LIVING_SITE_URL + "/users/registerUser/");
      } else {
        alert(this.response["text"]);
      }
    }
  }).send();
};

var currentlyReadingID = 0;

function loadCurrentlyReading() {
  new Request({
    url: LIVING_SITE_URL + "/users/getCurrentReadingIdTitleAuthor/"+ new Date().getTime(),
    method: 'get',
    onComplete: function(data) {
      rs = eval('('+data+')');
      if (rs['id']) {
        $('SearchSuggestBook').value = rs['title']+' - '+rs['authors'];
        currentlyReadingID = rs['id'];
        loadSimilar();
      } else {
        currentlyReadingID = 0;
      }
      loadVrgData();
      loadLikeMinded();
    }
  }).send();
}

function updateCurrentlyReading() {
  currentlyReadingID = $('SearchSuggestBook_hidden').value;
  if(!currentlyReadingID || currentlyReadingID == 0)
  {
    alert(HOME_ENTER_BOOK_TITLE_AND_CHOOSE);
    return;
  }
  
  if ($('frmSendCurRead')) {
    data = {
      fb: $('frmSendCurRead').fb.src.test(/_active_/),
      twitter: $('frmSendCurRead').twitter.src.test(/_active_/)
    };
  } else {
    data = null;
  }
  
  new Request({
    url: LIVING_SITE_URL + "/users/updateCurrentReadingBook/" + currentlyReadingID + "/yes/" + $time(),
    method: 'post',
    data: data,
    onComplete: function() {
      switch (this.response.text) {
        case '2':
          window.location.replace(LIVING_SITE_URL + "/users/registerUser/");
          break;
        case '3': // chosen book is same as existing currently reading
          $('change_read_content').style.display = 'none';
          break;
        default:
          document.getElementById('cur_read_mod').innerHTML = this.response.text;
          break;
      }
    }
  }).send();
}

function openTwitterLogin(bookId) {
  $('twitter_auth').setStyle('display', 'none');
  eval("twitter_login = window.open('/users/tweet_current_reading/" + bookId + "/" + $time() + "', 'twitter_login', 'toolbar=0,scrollbars=0,location=1,statusbar=0,menubar=0,resizable=1,width=800,height=500');");
}

function loadLikeMinded(){
  var url = LIVING_SITE_URL+"/recommendations/like_minded/"+ currentlyReadingID +"/"+ new Date().getTime();
  new Request({
    url: url,
    method: 'get',
    evalScripts: true,
    onComplete: function(){
      $('likeMindedContent').innerHTML = this.response["text"];

    }
  }).send();
}

/*---Newsletter paging BEGIN --*/
getFriendValues = function(){

  var id = 'friend';
  try{
    $('tab_id').value;
  }catch(e){}

  var page = getPNvalues(id);
  var sort_status = getSortValues(id);


  return {sort_type:sort_status.sort_type, sort_dir:sort_status.sort_dir, items_per_page:page.items_per_page, page_num:page.page_number};
};

loadFriendList = function(requestPage){
  var url = LIVING_SITE_URL + "/users/"+requestPage+"/"+ new Date().getTime();
  var data = getFriendValues();
  new Request({
    url: url,
    method: 'post',
    data: data,
    evalScripts: true,
    onComplete: function(){
      $('tab_content').set('html', this.response["text"]);
      endWait();
    }
  }).send();
  wait();
};

sortFriend = function(sort_type, requestPage){
  if ($('friend_sort_type').value == sort_type){
    if($('friend_sort_dir').value == "ASC") {
      $('friend_sort_dir').value = "DESC";
    } else {
      $('friend_sort_dir').value = "ASC";
    }
  } else {
    $('friend_sort_type').value = sort_type;
  }
  loadFriendList(requestPage);
};
/*-- Newsletter paging END --*/

//Paging for pendingList


sortPendingFriend = function(sort_type){
  if ($('friend_sort_type').value == sort_type){
    if($('friend_sort_dir').value == "ASC") {
      $('friend_sort_dir').value = "DESC";
    } else {
      $('friend_sort_dir').value = "ASC";
    }
  } else {
    $('friend_sort_type').value = sort_type;
  }
  openPendingList();
};

function openPendingList(outgoing) {
  var url;
  if (outgoing) {
    url = LIVING_SITE_URL + "/users/getPendingFriend/1/"+ new Date().getTime();
  } else {
    url = LIVING_SITE_URL + "/users/getPendingFriend/0/"+ new Date().getTime();
  }

  var data = getFriendValues();
  new Request({
    url: url,
    method: 'post',
    data: data,
    evalScripts: true,
    onComplete: function(){
      $('tab_content').set('html', this.response["text"]);
      endWait();
    }
  }).send();
  wait();
}

function addFriendRequest(myId, inputValue)
{
  var friendsSuggestion = $('FriendsSuggestion');
  if (!inputValue) {inputValue = friendsSuggestion.value;}
  if(inputValue == "" || inputValue == friendsSuggestion.defaultValue)
  {
    alert("Please input username or email"); return;
  }
  else
  {
    new Request({
      url: '/friends/addFriend/'+ myId + '/' + inputValue,
      method: 'get',
      onComplete: function(){
        pendingStr = $('lnkPendingNumber');
        if (this.response.text != '1') {
          alert(this.response.text);
        } else if (pendingStr) {
          var re = /\d+/;
          var count = parseInt(re.exec(pendingStr.innerHTML), 10) + 1;
          pendingStr.innerHTML = pendingStr.innerHTML.replace(/\d+/, count);
        }
        if (friendsSuggestion) {
          friendsSuggestion.value = "";
          friendsSuggestion.focus();
        }
      }
    }).send();
  }
}

updateFriendStatus = function(id, request_status){
  var data = {status:request_status,id:id};
  var url = LIVING_SITE_URL+"/messages/change_friend_status/" + new Date().getTime();
  new Request({
    url: url,
    method: "post",
    data:data,
    evalScripts: true,
    onComplete: function(){
      if(this.response["text"] != 1) {
        alert(this.response["text"]);
      } else {
        if (request_status == 'ignored') {
          alert(MSG_REQ_IGNORED);
        } else {
          alert(MSG_SENT);
        }
        window.location.reload();
      }
    }
  }).send();
};

change_vrg_member_status = function(id, active_status) {
  new Request({
    url: LIVING_SITE_URL+"/messages/change_vrg_member_status/" + new Date().getTime(),
    method: "post",
    data:{status:active_status,id:id},
    onComplete: function(){
      if(this.response["text"] != 1) {
        alert(this.response["text"]);
      } else {
        alert(MSG_UPDATE_SCF);
        loadMsMenu('',1);
      }
    }
  }).send();
};

loadingIndicator = function(target) {
	while($(target).childNodes[0]) {
		$(target).removeChild($(target).childNodes[0]);
	}
	var div = document.createElement('div');
	div.className = 'spinnerWrapper';
	var img = document.createElement('img');
	img.src='/img/loading.gif';
	img.className = 'loading';
	div.appendChild(img);
	$(target).appendChild(div);

};

var htmlConversions = new Hash({
  '&amp;': '&',
  '&quot;': '"',
  '&#039;': "'",
  '&lt;': '<',
  '&gt;': '>'
});
function htmlSpecialCharsDecode(str) {
  return str.replace(/&[^;]+;/g, function(match) {
    m = htmlConversions.get(match);
    if (m) {
      return m;
    }
    return match;
  });
}

/* Ratings */
var RATING_STAR_HEIGHT = 16;
var RATING_STAR_WIDTH = 15;
var RATING_USER_STAR_OFFSET = 176; // the y coord of the start of the user rating stars

function ratingsMousemove(el, ev) {
  var scroll = RATING_USER_STAR_OFFSET + ratingsGetRating(el, ev) * RATING_STAR_HEIGHT * 2; // how far down the background image needs to be scrolled
  $(el).setStyle("background-position", '0 -' + scroll + 'px');
}

function ratingsMouseout(el) {
  ratingsReset(el.parentNode);
}

function ratingsOnclick(el, ev) {
  ratingsSubmit(el.parentNode, ratingsGetRating(el, ev), ratingsGetBookId(el.parentNode));
}

function ratingsGetRating(el, ev) {
  var left = getX(ev) - getLeft(el); // how far the mouse is into the stars
  return Math.ceil(left / (RATING_STAR_WIDTH/2)) / 2;
}

function ratingsReset(ratingsBox) {
  ratingsShow(ratingsBox, ratingsGet(ratingsBox, 'rating'));
}

function ratingsShow(ratingsBox, rating) {
  var stars = $(ratingsBox.id).getElement('.stars');
  var scroll = ratingsGetOffset(ratingsBox) + rating * RATING_STAR_HEIGHT * 2;
  stars.setStyle('background-position', '0 -' + scroll + 'px');
  if (rating > 0) {
    try {
      $(ratingsBox.id).getElement('img').setStyle('visibility', '');
    } catch (e) {}
  }
}

function ratingsGet(ratingsBox, field) {
  return $(ratingsBox.id).getElement('input.'+field).value;
}

function ratingsSet(ratingsBox, field, val) {
  $(ratingsBox.id).getElement('input.'+field).value = val;
}

function ratingsGetOffset(ratingsBox) {
  return parseInt($(ratingsBox.id).getElement('input.bg-offset').value, 10);
}

function ratingsGetBookId(ratingsBox) {
  return $(ratingsBox.id).getElement('input.book-id').value;
}

function ratingsSubmit(ratingsBox, rating, bookId) {
  var url = LIVING_SITE_URL+"/books/rate/"+bookId+"/"+rating+"/"+ $time();
  new Request({
    url: url,
    method: 'get',
    onComplete: function(){
      if (this.response.text == '2') {
        window.location.replace(LIVING_SITE_URL + "/users/registerUser/");
      } else if (this.response.text != "0" && this.response.text != "1" ) {
        alert(this.response.text);
      } else {
        ratingsSet(ratingsBox, 'bg-offset', RATING_USER_STAR_OFFSET);
        ratingsSet(ratingsBox, 'rating', rating);
        ratingsShow(ratingsBox, rating);
        if(this.response.text == '1') {
          var addToBs = $('add_bs'+bookId);
          if (addToBs && !imgABChecked(addToBs)) {
            toggle_img_ab_checkbox(addToBs);
          }
          check_img_checkbox($('hri'+bookId));
          updateBookCount();
        }
      }
      endWait();
    }
  }).send();
  wait();
}

function ratingsSubmitAutorate(elem, event) {
  var value = ratingsGetRating(elem, event);
  var url = LIVING_SITE_URL + "/users/updateRateOption/" + value + "/" + $time();
  new Request({
    url: url,
    method: 'get',
    onComplete: function(){
      var ratingsBox = elem.parentNode;
      ratingsSet(ratingsBox, 'bg-offset', RATING_USER_STAR_OFFSET);
      ratingsSet(ratingsBox, 'rating', value);
      ratingsShow(ratingsBox, value);
    }
  }).send();
}

function removeRating(bookId, el) {
  var url = LIVING_SITE_URL+'/books/removerating/'+bookId+'/'+$time();
  new Request({
    url: url,
    method: 'get',
    onComplete: function(){
      var result = this.response["text"];
      if (result != "0" && result != "1" ) {
        alert(result);
      } else {
        el.style.visibility = 'hidden';
        ratingsSet(el.parentNode, 'rating', '0');
        ratingsShow(el.parentNode, '0');
      }
      endWait();
    }
  }).send();
  wait();
}

removeGroupMemberByUserId = function(vrg_id,member_id, myself){
  var confirm_string = REMOVE_MEMBER_CONFIRM;
  if (myself == true) {
    confirm_string = REMOVE_ME_CONFIRM;
  }

  if (confirm(confirm_string)) {
    var url = LIVING_SITE_URL+"/reading_groups/removeMemberByUserId/"+vrg_id+"/"+member_id+"/"+ new Date().getTime();
    new Request({
      url: url,
      method: 'get',
      onComplete: function(data) {
        endWait();
        if(data == "1") {
          var el = document.getElementById('result_'+member_id);
          el.dispose(0);
        } else {
          alert(CANNOT_REMOVE_MEMBER);
        }
      }
    }).send();
    wait();
  }
};

function joinReadingGroup(vrg_id)
{
  if(confirm(CONFIRM_JOIN_MEMBER))
  {
  var url = LIVING_SITE_URL + '/reading_groups/joinMember/'+vrg_id;
    new Request({
      url: url,
      method: 'get',
      onComplete: function(data){
        if(data == 1)
        {
          window.location.reload();
        }
        else
        {
          alert(data);
        }
      }
    }).send();
  }
}


// status icons
saveInfo = function(el,type) {
  if(isDisabled(el)) {
    return;
  }
  if (el.className != "loan") {
    var value = imgChecked(el)?1:0;
    var book_id = getICValue(el);
    var url = LIVING_SITE_URL+"/books/saveinfo/" + type + "/" + book_id + "/" + value+"/"+ new Date().getTime();
    new Request({
      url: url,
      method: 'get',
      onComplete: function(){
        var result = this.response["text"];
        if (result=="2") {
          window.location.replace(LIVING_SITE_URL + "/users/registerUser/");
        } else if (result!="0" && result!="1") {
          alert(result);
          if(value) {
            uncheck_img_checkbox(el);
          }
          else {
            check_img_checkbox(el);
          }
        } else {
          if((result=="1") && $('add_bs'+book_id) && !imgABChecked($('add_bs'+book_id))) {
            toggle_img_ab_checkbox($('add_bs'+book_id));
            updateBookCount();
          } else if(type=='not_interested') {
            var checkboxes = new Array($('own'+book_id), $('hri'+book_id), $('wlt'+book_id));
            if(value) {
              uncheck_img_checkbox($('own'+book_id));
              uncheck_img_checkbox($('hri'+book_id));
              uncheck_img_checkbox($('wlt'+book_id));
              disableItems(checkboxes);
            } else {
              enableItems(checkboxes);
            }
            updateBookCount();
          }
          afterSaveInfo(el, type);
        }
        endWait();
      }
    }).send();
    wait();
  }
};

afterSaveInfo = function(el, type){};

setBookShelf = function(e,other) {
  var target = e.target || e.srcElement;
  var book_id = getICValue(target);
  var url;
  if (other) {
    url = LIVING_SITE_URL+"/bookshelves/addtobookshelf_ajax/"+book_id+"/"+ new Date().getTime();
  } else {
    if (imgABChecked(target)) {
      toggle_img_ab_checkbox(target);
      url = LIVING_SITE_URL+"/bookshelves/addtobookshelf_ajax/"+book_id+"/"+ new Date().getTime();
    } else {
      toggle_img_ab_checkbox(target);
      url = LIVING_SITE_URL+"/bookshelves/removefrombookshelf_ajax/"+book_id+"/"+ new Date().getTime();
    }
  }
  new Request({
    url: url,
    method: 'get',
    onComplete: function(){
      var result = this.response["text"];
      if (result=="1") {
        if(other) {
          return;
        }
        updateBookshelfCount();
        toggle_img_ab_checkbox(target);
        afterSetBookShelf(target, other);
      } else if (result=="2") {
        window.location.replace(LIVING_SITE_URL + "/users/registerUser/");
      }
      else {
        alert(result);
      }
    }
  }).send();
};

afterSetBookShelf = function(target, other){};

function isValidEmail(email) {
    var re = new RegExp('^([A-Za-z0-9][A-Za-z0-9_\\-\\.\\+]*)@([A-Za-z0-9][A-Za-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[A-Za-z]{2,4}))$');
    return re.test(email);
}

sendReport=function(e){
  var book_id = $("book_id").get('value');
  var rep = $("rep_book").get('value');
  book_id = escape(book_id);
  rep = escape(rep);
  if(rep == "") {
    rep = "No content";
  }

  e = new Event(e).stop();
  new Request({
    url: LIVING_SITE_URL+"/books/sendReport/"+book_id+"/"+rep+"/"+ new Date().getTime(),
    method: 'get',
    onComplete: function(){
      if (this.response["text"].substr(0,1)=="1"){
        alert("Thanks for letting us know, we'll fix it as soon as possible.");
        $("rep_book").value = '';
        $("rep_book").focus();
      } else if (this.response["text"]=="2") {
        alert("Sorry, we couldn't send your report. You might be able to send feedback instead.");
      } else {
        alert(this.response["text"]);
      }
    }
  }).send();
};

function toggleFeedback() {
  var div = $('feedback_content');
  if (div.getStyle('display') == 'none') {
    div.setStyle('display', '');
    div.setStyle('z-index', '1');
  } else {
    div.setStyle('display', 'none');
  }
}

function blogWidgetPopup(bookId, shareDiv, x) {
  if (!bookId) {
    return;
  }
  if (x == undefined) {
    x = 0;
  }
  new Request({
    url: LIVING_SITE_URL+'/books/blogWidget/'+bookId, 
    method: 'get',
    onComplete: function(response) {
      blogWidgetRemove();
      var pos = $(shareDiv).getPosition();
      var blogCont = new Element('div', {
        id: 'blogcont',
        styles: {
          position: 'absolute',
          left: pos.x + x,
          top: pos.y
        }
      }).set('html', response);
      document.body.appendChild(blogCont);
      document.onblur = blogWidgetRemove;
      document.onclick = blogWidgetRemove;
    }
  }).send();
}

function blogWidgetRemove(e) {
  var div = $('blogcont');
  if (!div) {
    return;
  }
  if (e || event) {
    var target = e ? e.target : event.srcElement;
    if (div.hasChild(target)) { // do not remove if clicked within the div
      return;
    }
  }
  div.dispose();
}

function blogWidgetToggleCode() {
  var display = '';
  var blogcode = $('blogcode');
  var buttonImg = $(blogcode.parentNode).getElements('img')[1];
  if (blogcode.style.display != 'none') {
    display = 'none';
    buttonImg.src = buttonImg.src.replace(/_down_/, '_up_');
  } else {
    buttonImg.src = buttonImg.src.replace(/_up_/, '_down_');
  }
  blogcode.style.display = display;
}
var popupTipTimeout;
var POPUPTIP_DELAY = 3000;
function popupTip(content, ev, style) {
  removePopupTip();
  
  // Remove tip on mouseout
  var el = $(ev.target || ev.srcElement);
  el.addEvent('mouseout', function(event) {
    popupTipTimeout = setTimeout('removePopupTip()', POPUPTIP_DELAY);
  });
  
  switch(style) {
    case 'left':
      popclass = 'tleft';
      topY =  11;
      leftX = -21;
      break;
    default:
      popclass = 't';
      topY  = 10;
      leftX = -135;
      break;
  }
  var ul = new Element('ul', {
    id: 'popup-tip',
    'class': 'popup-tip',
    styles: {
      top: getY(ev) + topY,
      left: getX(ev) + leftX
    }
  });
  
  new Element('li', {
    'class': popclass
  }).inject(ul);
  
  var m = new Element('li', {
    'class': 'm'
  }).inject(ul);
  
  new Element('div').set('html', content).inject(m);
  
  new Element('li', {
    'class': 'b'
  }).inject(ul);
  
  document.body.appendChild(ul);
}

function removePopupTip() {
  try {
    $('popup-tip').dispose();
  } catch (e) {}
  clearTimeout(popupTipTimeout);
}

function recommendBookToFriend(){
  var book_id = getIBValue("RecommendBook_hidden");
  var username = getIBValue("RecommendUser").toLowerCase();
  username = username.replace(/^\s+|\s+$/g, '') ;
  if(book_id == '') {
    alert(HOME_ENTER_BOOK_TITLE_AND_CHOOSE);
  } else if(username == '') {
    alert(HOME_ENTER_USERNAME);
  } else {
    var val_email = new RegExp('^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[a-z]{2,4}))$');
    var val_username = new RegExp('^[a-z0-9][a-z0-9_\\-\\.\\+ ]*$');
    if(!val_email.test(username)&&!val_username.test(username)){
      alert(ERR_INVALID_EMAIL_USERNAME);
      return;
    }
    username = escape(username);
    new Request({
      url: LIVING_SITE_URL+"/books/recommend/"+book_id+"/"+username+"/"+ new Date().getTime(),
      method: 'get',
      onComplete: function(){
        if (this.response["text"].substr(0,1)=="1"){
          alert(SUCCESS);
          $("RecommendBook").value = HOME_TITLE;
          $("RecommendBook_hidden").value = '';
          $("RecommendUser").value = HOME_USERNAME_OR_EMAIL;
          $("RecommendBook").focus();
        } else {
          alert(this.response["text"]);
        }
      }
    }).send();
  }
}

function friendIconMouseOver(el) {
  var w = $(el).getSize().x;
  var bgPos = $(el).getStyle('background-position');
  $(el).setStyle('background-position', ' -' + w + 'px ' + bgPos.split(' ')[1]);
}

function friendIconMouseOut(el) {
  var bgPos = $(el).getStyle('background-position');
  $(el).setStyle('background-position', '0 ' + bgPos.split(' ')[1]); 
}

function friendIconAddFriend(el) {
  if (!confirm(HOME_ADD_FRIEND)) {
    return;
  }
  var friendId = friendIconGetFriendId(el);
  new Request({
    url: LIVING_SITE_URL+'/friends/addFriendById/0/' + friendId + '/1/' + friendIconHasMessage(el) + '/' + $time(),
    method:'get',
    onSuccess: function(response) {
      $('friend_status_'+friendId).set('html', response);
    },
    onFailure: function(response) {
      alert(response.responseText);
    }
  }).send();
}

function friendIconCancelPending(el) {
  if (!confirm(HOME_CANCEL_PENDING_FRIEND_CONF)) {
    return;
  }
  var friendId = friendIconGetFriendId(el);
  new Request({
    url: LIVING_SITE_URL+'/friends/cancelPending/' + friendId + '/' + friendIconHasMessage(el) + '/' + $time(),
    method:'get',
    onSuccess: function(response) {
      $('friend_status_'+friendId).set('html', response);
    },
    onFailure: function(response) {
      alert(response.responseText);
    }
  }).send();
}

function friendIconRemoveFriend(el) {
  if (!confirm(HOME_REMOVE_FRIEND_CONF)) {
    return;
  }
  var friendId = friendIconGetFriendId(el);
  new Request({
    url: LIVING_SITE_URL+'/friends/deleteByFriendId/' + friendId + '/' + friendIconHasMessage(el) + '/' + $time(),
    method:'get',
    onSuccess: function(response) {
      $('friend_status_'+friendId).set('html', response);
    },
    onFailure: function(response) {
      alert(response.responseText);
    }
  }).send();
}

function friendIconGetFriendId(el) {
  if (el.nodeName == 'A') {
    return el.parentNode.previousSibling.id.split('_')[1];
  }
  return el.id.split('_')[1];
}

function friendIconHasMessage(el) {
  try {
    if (el.nodeName == 'A' || $(el).parentNode.getElement('.friend_message')) {
      return '1';
    }
  } catch (ex) {}
  return '0';
}

function getUrlParam (key) {
  url = location.href;
  url = url.split("?");

  var regex = new RegExp("[?&]"+key+"=([^&#]*)");
  var results = regex.exec(url);
  return (results == null ) ? "" : results[1];
}

function IsNumeric(sText) {
  var re = new RegExp(/^[0-9\.]+$/);
  return re.test(sText);
}

/* Don't use this, it will ultimately be removed - use $() */
function getElement(id) {
  return document.getElementById(id);
}
function createRadioFuntionFeedback(chkPermission) {
	strCommandName = chkPermission.id.split('_')[0];
	strKind =  chkPermission.id.split('_')[1];

	var otherKind1 = "";
	var otherKind2 = "";
	
	if(strKind == "1") {
		otherKind1 = "2";
		otherKind2 = "3";
 	}
 	if(strKind == "2") {
 		otherKind1 = "1";
 		otherKind2 = "3";
 	}
 	if(strKind == "3") {
 		otherKind1 = "1";
 		otherKind2 = "2";
 	}
	if($(chkPermission).getAttribute('src').indexOf('inactive') > 0) {
		chkPermission.src = LIVING_SITE_URL + '/img/checkbox_active_off.png';
	}
	document.getElementById('title_lead').value = strKind;
	document.getElementById(strCommandName + "_" + otherKind1).src = LIVING_SITE_URL + '/img/checkbox_inactive_off.png';
	document.getElementById(strCommandName + "_" + otherKind2).src = LIVING_SITE_URL + '/img/checkbox_inactive_off.png';
}

function doFeedback() {
	var title = document.getElementById('feedTitle').value;
	var content = $('feedContent').value;
	error = "";
	if(title == "") {
		error += "<p>* Please summarize the issue</p>";
	}
	if(content == "") {
		error += "<p>* Please give us some detail about the issue</p>";
	}
	if(error == "") {
		document.getElementById('frmSendFeed').submit()
  } else {
		document.getElementById('errorFeed').innerHTML = error;
  }
}

// Snap the window back into the viewport if moved out of it
function popupConstrain(el) {
  var minShow = 50; // the minimum width in px to show of the previewer
  var coords = el.getCoordinates();
  var newPos = {x: coords.left, y: coords.top};
  var winCoords = window.getCoordinates();
  var winScrollTop = window.getScrollTop();
  
  if (coords.left + minShow >= winCoords.width) { // over rhs
    newPos.x = winCoords.width - minShow;
  } else if (coords.left + coords.width - minShow < 0) { // over lhs
    newPos.x = minShow - coords.width;
  }
  if (coords.top < 0) { // over top
    newPos.y = 0;
  } else if (coords.top >= winCoords.height + winScrollTop - minShow) { // below bottom
    newPos.y = winCoords.height + winScrollTop - minShow;
  }
  
  if (newPos.x != coords.left || newPos.y != coords.top) {
    el.setPosition(newPos);
  }
}

var FOLLOWED_AUTHOR_CLOSE_BUTTON = '<a class="close" href="#" onclick="closeFollowedAuthorsPopup(); return false">Close</a>';
function showFollowedAuthorsPopup(el, offset) {
  var popup = $('followed_authors_popup');
  if (offset == undefined) {
    offset = {x: 0, y: 0};
  }
  var coords = $(el).getCoordinates();
  popup.setPosition({
    x: coords.left + coords.width + offset.x,
    y: coords.top + coords.height + offset.y
  });
  
  var container = popup.getElement('.c');
  var centre = popup.getElement('.m');
  
  new Drag(popup, {
    onComplete: popupConstrain
  });
  
  popup.setStyles({
    visibility: 'visible',
    zIndex: 1
  });
  container.empty();
  loadingIndicator(centre);
  new Request({
    url: '/users/authors/' + $time(),
    onComplete: function(response) {
      centre.set('html', ''); // clear loading indicator
      container.set('html', response + FOLLOWED_AUTHOR_CLOSE_BUTTON);
      resizeFollowedAuthorsPopup();
    }
  }).send();
}

function closeFollowedAuthorsPopup() {
  var popup = $('followed_authors_popup');
  popup.setStyle('visibility', 'hidden');
}

function resizeFollowedAuthorsPopup() {
  var popup = $('followed_authors_popup');
  if (!popup) {
    return;
  }
  var fx = new Fx.Morph(popup.getElement('.m'), {transition: Fx.Transitions.Sine.easeOut});
  fx.start({
    height: popup.getElement('.c').getSize().y - 45
  });
}

getAuthorValues = function() {
	var id = 'author';
	try{
		$('tab_id').value;
	}catch(e){}
	
	var page = getPNvalues(id);
	var sort_status = getSortValues(id);
  
	return {sort_type:sort_status.sort_type, sort_dir:sort_status.sort_dir, items_per_page:page.items_per_page, page_num:page.page_number};
};

loadAuthorList = function(requestPage) {
	var data = getAuthorValues();
	new Request({
    url: LIVING_SITE_URL + "/users/"+requestPage+"/"+ $time(),
		method: 'post',
		data: data,
		evalScripts: true,
		onComplete: function(response) {
			try {
        $('tab_content').set('html', response);
      } catch (ex) {
        document.getElement('#followed_authors_popup .c').set('html', response + FOLLOWED_AUTHOR_CLOSE_BUTTON);
        resizeFollowedAuthorsPopup();
      }
			endWait();
		}
	}).send();
	wait();
};

sortAuthorList = function(sort_type, requestPage){
	if ($('author_sort_type').value == sort_type){
		if($('author_sort_dir').value == "ASC")
			$('author_sort_dir').value = "DESC";
		else
			$('author_sort_dir').value = "ASC";
	} else {
		$('author_sort_type').value = sort_type;
	}
	loadAuthorList(requestPage);
};

function removeThisTrack(trackid) {
  if(confirm('Are you sure you want to remove this author from your Tracked Authors list?')) {
    new Request({
      url: LIVING_SITE_URL + "/users/removeTrackAuthor/" + trackid,
      method: 'get',
      onComplete: function(data){
        var tblTrack = document.getElementById('tblTrackAuthors');
        var rowDelete = document.getElementById('rowTrackAuthor_' + trackid);
        tblTrack.deleteRow(rowDelete.rowIndex);
        resizeFollowedAuthorsPopup();
      }
    }).send();
  }
}