
var providers        = new Object();
var contacts         = new Object();
contacts.mail        = new ContactType("mail", "email");
contacts.nwrk        = new ContactType("nwrk", "social_network");
contacts.size        = 0;
contacts.oldHeight   = 0;

var rafIsActive      = false;
var rafRequestedType = false;
var personalMsgValid = true;
var personalMsg      = "";
var str_raf_myname   = "";

function ContactType(name,fullname) {
  this.name = name;
  this.fullname = fullname;
  this.list = new Object();
  this.size = 0;
  this.oldHeight = 0;
  this.checked = 0;
}

function Contact(provider, name, contact, status, userId) {
  this.provider = provider;
  this.name     = name;
  this.contact  = contact;
  
  if (typeof status != "undefined")
    this.status = status;
  else
    this.status = false;
    
  if (typeof userId != "undefined")
    this.userId   = userId;
  else
    this.userId   = 0;
}

function Provider(type, name, uid, pwd) {
  this.type = type;
  this.name = name;
  this.uid  = uid;
  this.pwd  = pwd;
}

function getTypeName(type) {
  if (contacts[type] == undefined)
    for (var t in contacts)
      if (type == contacts[t].fullname)
        type = contacts[t].name;
  if (contacts[type] == undefined)
    return false;
  else 
    return type;
}

function verifyContact(type, contact) {
  if (type == "mail") {
    var pattern = /^([a-zA-Z0-9_\-]+)((\.{1,1}[a-zA-Z0-9_\-]+)*|([a-zA-Z0-9_\-]*))@(([a-zA-Z0-9]+(\-*[a-zA-Z0-9]+)*\.)+)([a-zA-Z]{2,4})$/;
    return pattern.test(contact);
  }
  return true;
}

function addContact(type, provider, name, contact, status, userId) {
  type = getTypeName(type);
  if (name == "<"+ str_raf_fullname +">")
    name = "";
  if (typeof contacts[type] != "undefined") {
    if (!contacts[type])
      contacts[type] = ContactType(type);
    if (typeof contacts[type].list[contact] != "undefined" && contacts[type].list[contact].status === true)
      return false;
    if (verifyContact(type,contact)) {     // New/update
      contacts[type].list[contact] = new Contact(provider, name, contact, status, userId);
    }
    else {
      alert(str_raf_could_not_add+" "+name+" ("+contact+"). "+str_raf_contact_not_verified);
      return false;
    }
  }
  else
    return false;
  return true;
}

function removeAllContacts(type, status) {
  for (var c in contacts[type].list) {
    if (contacts[type].list[c].status === status) {
      removeContact(type,c,status);
      delete contacts[type].list[c];
    }
  }
}

function removeContact(type, contact, status) {
  if (contacts[type].list[contact] && contacts[type].list[contact].status === status) {
    contacts[type].list[contact].status = false;

    showContacts("all", true, "raf_contact");
    showContacts(type, false, "raf_"+type);

    if (status === true) {
      if (contacts.size <= 5 && document.getElementById('raf_contact'))
        contacts.oldHeight = document.getElementById('raf_contact').offsetHeight;
      if (contacts.size == 0)
        document.getElementById('raf_listframe').style.display = "none";
    }
    else {
      if (contacts[type].size <= 5 && document.getElementById('raf_'+type))
        contacts[type].oldHeight = document.getElementById('raf_'+type).offsetHeight;
    }

    rafButtonControl(false);
  }
}


function showContacts(type, status, outid) {
  if ( !document.getElementById(outid) )
    return false;

  if (status === true) {
    contacts.size = 0;
    contacts.oldHeight = 0;
  }
  else {
    contacts[type].size = 0;
    contacts[type].oldHeight = 0;
  }

  var out = "<table id='contacts_table_"+outid+"' border=0 cellspacing=0 cellpading=0 width=100%>";
  if (type == "all") {
    for (var t in contacts) {
      if (typeof status == "object") {
        for (var s=0 ; s<status.length ; s++) {
          out += getShowContacts(t, status[s]);
        }
      }
      else
        out += getShowContacts(t, status);
    }
  }
  else {
    if (typeof status == "object") {
      for (var s=0 ; s<status.length ; s++) {
        out += getShowContacts(type, status[s]);
      }
    }
    else {
      out += getShowContacts(type, status);
    }
  }
  out += "</table>";

  layer_write(outid, out);

  if (status === true && contacts.size > 0) {
    if (document.getElementById('raf_listframe').style.display == 'none') {
      document.getElementById('raf_listframe').style.display = 'block';
    }

    if (document.getElementById('raf_contact').offsetHeight <=  document.getElementById('contacts_table_'+outid).clientHeight)
      document.getElementById('raf_contact').style.height = document.getElementById('contacts_table_'+outid).clientHeight;
    if (contacts.size > 5)
      document.getElementById('raf_contact').style.height = (19 * 5) + 2;

  }
  else if (status !== true && contacts[type].size > 0) {
    if (document.getElementById('raf_'+type).offsetHeight <=  document.getElementById('contacts_table_'+outid).clientHeight)
      document.getElementById('raf_'+type).style.height = document.getElementById('contacts_table_'+outid).clientHeight;
    if (contacts[type].size > 5) {
      document.getElementById('raf_'+type).style.height = (22 * 5) + 2;
    }

  }

  return true;
}


function trackChecked(obj) {
  var type = obj.id.substr(0, obj.id.indexOf("&") );
  if (contacts[type].list[obj.value].status === false) {
    if (obj.checked == true)
      contacts[type].checked++;
    else if (contacts[type].checked > 0)
      contacts[type].checked--;
  }
}


function getShowContacts(type, status) {
  out_tmp = "";
  for (var i in contacts[type].list) {
    if (contacts[type].list[i].status === status) {
      out_tmp += "<tr>";

      if (status === true) {
        var css = ((contacts.size % 2) == 1) ? "" : "class=raf_listsecondary";
          out_tmp += "<td width=177 "+ css +"><div id='"+ type +"_name&"+ i +"' style='height:17px;overflow:hidden;'>"+contacts[type].list[i].name +"</div></td>";
        if (type == 'nwrk')
          out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:189px;overflow:hidden;'>"+contacts[type].list[i].provider +"</div></td>";
        else
          out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:189px;overflow:hidden;'>"+contacts[type].list[i].contact +"</div></td>";
        out_tmp += "<td width=13 align=right "+ css +"><img src='img/raf/trashcan.gif' onClick=\"removeContact('"+ type +"', '"+ i +"', true)\" width=12 height=13 style='cursor:pointer;'></td>";

        contacts.size++;
        if (contacts.size <= 5) {
          contacts.oldHeight = document.getElementById('raf_contact').offsetHeight;
        }

      }
      else {
        var css = ((contacts[type].size % 2) == 1) ? "" : "class=raf_listsecondary";
        if (status === false) {
          contacts[type].size++;
          out_tmp += "<td width=22 "+ css +"><input type=checkbox onClick='trackChecked(this);' class=checkbox id='"+ type +"&"+ i +"' name='"+ type +"&"+ i +"' value='"+ i +"'></td>";
          out_tmp += "<td width=178 "+ css +"><div id='"+ type +"_name&"+ i +"' style='width:178px;overflow:hidden;'>"+contacts[type].list[i].name +"</div></td>";
          if (type == 'nwrk')
            out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:175px;overflow:hidden;'>"+contacts[type].list[i].provider +"</div></td>";
          else
            out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:175px;overflow:hidden;'>"+contacts[type].list[i].contact +"</div></td>";
        }
        else if (status == 'invited') {
          contacts[type].size++;
          out_tmp += "<td width=22 "+ css +"><input type=checkbox class=checkbox disabled></td>";
          out_tmp += "<td width=178 "+ css +"><div id='"+ type +"_name&"+ i +"' style='height:20px;width:178px;overflow:hidden;'>"+contacts[type].list[i].name +"</div></td>";
          out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:175px;overflow:hidden;'>"+str_raf_already_invited+"</div></td>";
        }
        else if (status == 'joined') {
          contacts[type].size++;
          out_tmp += "<td width=22 "+ css +"><input type=checkbox class=checkbox disabled></td>";
          out_tmp += "<td width=178 "+ css +"><div id='"+ type +"_name&"+ i +"' style='height:20px;width:178px;overflow:hidden;'>"+contacts[type].list[i].name +"</div></td>";
          out_tmp += "<td "+ css +"><div id='"+ type +"_contact&"+ i +"' style='width:175px;overflow:hidden;'>"+str_raf_already_member+" <a href=\"javascript:rafAjaxAddFriend("+ contacts[type].list[i].userId +", '"+ type +"_contact&"+ i +"');\">"+str_raf_add_friend+"</a></div></td>";
        }

        if (contacts[type].size <= 5) {
          contacts[type].oldHeight = document.getElementById('raf_'+type).offsetHeight;
        }
      }
      
      out_tmp += "</tr>";
    }
  }
  return out_tmp;
}

function startRAF() {
  lightboxInit();
  rafIsActive = true;
  showContent(["","closebutton","notitle"], "<table width=435><tr><td align=center><img src=\"img/ajax_loader.gif\" alt=\"Loading\" width=\"16\" height=\"16\"></td></tr></table>");
  rafGetTemplates("start");
}

function endRAF() {
  removeAllContacts("mail",true);
  removeAllContacts("nwrk",true);
  rafIsActive = false;
}

function rafAjaxResponse(readyState, response, responseParameter) {
  if (readyState == 4 && rafIsActive) {
    eval(response);
    if (typeof rafTemplates == "object") {
      raf_str_contactsdiv = "contactsdiv";
      raf_str_messagediv = "messagediv";
      rafTitle        = doTheReplace(rafTemplates["raftitle"]);
      rafMailBody     = doTheReplace(rafTemplates["rafmailbody"]);
      rafNwrkBody     = doTheReplace(rafTemplates["rafnwrkbody"]);
      rafMailWin      = doTheReplace(rafTemplates["rafmailwindow"]);
      rafNwrkWin      = doTheReplace(rafTemplates["rafnwrkwindow"]);
      rafMailGet      = doTheReplace(rafTemplates["rafmailget"]);
      rafMailList     = doTheReplace(rafTemplates["rafmaillist"]);
      rafNwrkGet      = doTheReplace(rafTemplates["rafnwrkget"]);
      rafNwrkList     = doTheReplace(rafTemplates["rafnwrklist"]);
      rafBody         = doTheReplace(rafTemplates["rafbody"]);
      rafTitlePreview = doTheReplace(rafTemplates["raftitlepreview"]);
      rafBodyPreview  = doTheReplace(rafTemplates["rafbodypreview"]);
      rafBodyEnd      = doTheReplace(rafTemplates["rafbodyend"]);
      rafDefMsg      = doTheReplace(rafTemplates["rafdefmsg"]);
      showContentMain();
    }
    else {
      alert(str_raf_error_retr_form);
    }
  }
}

function rafAjaxResponseContacts(readyState, response, responseParameter) {
  if (readyState == 4 && rafIsActive) {
    if (document.getElementById("ajax_loader_"+rafRequestedType))
      document.getElementById("ajax_loader_"+rafRequestedType).style.display = 'none';
    if(response == -1) { // error
      alert(str_raf_login_failed);
    }
    else {
      eval(response);
      if (rafRequestedType != false)
        showContentList(rafRequestedType);
    }
    rafButtonControl(false);
    rafRequestedType = false;
  }
}

function rafAjaxResponseSubmit(readyState, response, responseParameter) {
  if (readyState == 4 && rafIsActive) {
    showContentEnd();
    rafButtonControl(false);
  }
}

function showContent(title, body, closeaction) {
  if (rafIsActive) {
    lightboxShow(450, [title, "lefttitle"], body, "", "", "", "", "endRAF();" );
    lightboxSetPosY(90);
  }
}

function rafButtonControl(busy) {
  if (busy == true) {
    disableButton("rafSendBtn");
    disableButton("rafReturnBtn");
    disableButton("rafPreviewBtn");
    disableButton("rafContactBtn");
    disableButton("rafMailBtn");
    disableButton("rafNwrkBtn");
    disableButton("rafGetMailBtn");
    disableButton("rafGetNwrkBtn");
    disableButton("rafBackMailBtn");
    disableButton("rafBackNwrkBtn");
  }
  else if (busy == false) {
    if (personalMsgValid)
      reenableButton("rafSendBtn");
    else
      disableButton("rafSendBtn");
    reenableButton("rafReturnBtn");
    reenableButton("rafPreviewBtn");
    reenableButton("rafContactBtn");
    reenableButton("rafMailBtn");
    reenableButton("rafNwrkBtn");
    reenableButton("rafGetMailBtn");
    reenableButton("rafGetNwrkBtn");
    reenableButton("rafBackMailBtn");
    reenableButton("rafBackNwrkBtn");
  }
}
  
function showContentMain() {

  if (objHide = document.getElementById('preview_overlay') )
    objHide.style.display = "none";

  showContent([rafTitle,"closebutton"], rafBody);
  // Show correct mail import content
  layer_write("maildiv",rafMailBody);
  if (document.getElementById("raf_mail_top"))
    layer_write("raf_mail_top",rafMailGet);
  // Show correct network import content
  layer_write("nwrkdiv",rafNwrkBody);
  if (document.getElementById("raf_nwrk_top"))
    layer_write("raf_nwrk_top",rafNwrkGet);

  rafButtonControl(false);
  divsShowOnly('raf_contacts', 'raf_contacts');
  divsShowOnly('raf_message', 'raf_message');
  showContacts("all", true, "raf_contact");

  if (str_raf_myname != "")
    document.getElementById("rafaMyName").value = str_raf_myname;

  if(personalMsg.length == 0)
    document.getElementById("raf_message_txt").value = rafDefMsg.replace(/<br>/g, "\n");
  else
    document.getElementById("raf_message_txt").value = personalMsg;
  checkPersonalMsg(500,'rafMsgCnt',str_raf_msg_cnt);
}

function showContentList(type) {
  type = getTypeName(type);
  if (type == "mail")
    layer_write("raf_mail_top",rafMailList);
  else if (type == "nwrk")
    layer_write("raf_nwrk_top",rafNwrkList);
  var status = new Array('joined', false, 'invited');
  showContacts(type, status, "raf_"+type);
  showContacts("all", true, "raf_contact");
}

function showContentPreview() {
  var cnt = 0;
  for (var type in contacts) {
    if (typeof contacts[type] == "object")
      cnt = cnt + contacts[type].checked;
  }
  if (cnt > 0) {
    alert(str_raf_error_active_selections);
    reenableButton("rafPreviewBtn");
    return;
  }

  for (var type in contacts)
    if (typeof contacts[type] == "object")
      contacts[type].checked = 0;

  personalMsg = document.getElementById("raf_message_txt").value;
  str_raf_myname  = document.getElementById("rafaMyName").value;

  var personalMsgTmp = personalMsgValidate();
  showContent([rafTitlePreview,"notitle"], doTheReplace(rafBodyPreview) );
  if (personalMsgTmp != "" && personalMsgTmp.length >= 4) {
    layer_write("personal_msg", ""+personalMsgTmp+"<br><br>/"+str_raf_myname);
  }
  var objHide = document.getElementById('preview_overlay');
  objHide.style.top = 0;
  objHide.style.left = 0;
  objHide.style.width = 600;
  objHide.style.height = document.getElementById('lightbox').offsetHeight - 50;
  objHide.style.display = "block";

  rafButtonControl(false);
}

function showContentEnd() {
  showContent(["","closebutton"], doTheReplace(rafBodyEnd) );
}

function backToGet(type) {
  setTimeout("__backToGet('"+type+"')", 100);
}

function __backToGet(type) {
  removeAllContacts(type, false);
  type = getTypeName(type);
  if (type == "mail") {
    contacts[type].checked = 0;
    if (rafMailBody != rafMailWin)
      rafMailBody = rafMailWin;
    layer_write("maildiv",rafMailBody);
    layer_write("raf_mail_top",rafMailGet);
    divsShowOnly('raf_import_mail', 'raf_import');
  }
  else if (type == "nwrk") {
    contacts[type].checked = 0;
    if (rafNwrkBody != rafNwrkWin)
      rafNwrkBody = rafNwrkWin;
    layer_write("nwrkdiv",rafNwrkBody);
    layer_write("raf_nwrk_top",rafNwrkGet);
    divsShowOnly('raf_import_nwrk', 'raf_import');
  }
  rafButtonControl(false);
}

function rafSelectAll(type, status) {
  var cboxs = document.getElementsByTagName("INPUT");

  var inputs = document.getElementsByTagName("INPUT");
  for(i = 0; i < inputs.length; i++) {
    input = inputs[i];
    str = input.id;
    if (input.type == "checkbox") {
      if (str.substr(0, type.length+1) == type+"&") {
        if (input.checked != status) {
          input.checked = status;
          trackChecked(input,true);
        }
        else
          input.checked = status;
      }
    }
  }

}

function rafAjaxAddFriend(userId, divId) {
  ajaxCall('ajax_com/raf.php', 'val=RAFAddFriend&sport='+ajaxSport+'&uid='+userId, 'writeLayer', divId);
}

function rafGetTemplates(templateId) {
  ajaxCall('ajax_com/raf.php','val=getRAFTemplate&sport='+ajaxSport+'&template='+templateId, 'rafAjaxResponse', '');
}

function getRAFContacts(type) {
  rafButtonControl(true);
  var uid = document.getElementById("raf_get"+type+"uid").value.replace(/<.*>/g,"invalid");
  var pwd = document.getElementById("raf_get"+type+"pwd").value.replace(/<.*>/g,"invalid");
  rafContactsRequest(type,uid,pwd);
}

function rafContactsRequest(type,uid,pwd) {
  if (rafRequestedType == false)
    rafRequestedType = type;
  if (document.getElementById("raf_get"+type+"provider")) {
    var pid = document.getElementById("raf_get"+type+"provider").value;
    if (!providers[pid])
      providers[pid] = new Provider(type, pid, uid, pwd);
  }
  else
    var pid = contacts[type].fullname;

  if (document.getElementById("ajax_loader_"+type)) {
    document.getElementById("ajax_loader_"+type).style.display = 'block';
  }
  pwd = escape(pwd);
  ajaxCall('ajax_com/raf.php','val=getRAFContactsRequest&sport='+ajaxSport+'&type='+contacts[type].fullname+'&provider='+pid+'&uid='+uid+'&pwd='+pwd, 'rafAjaxResponseContacts', '');
}


function rafContactsSubmit() {
  var cnt = 0;
  for (var type in contacts) {
    if (typeof contacts[type] == "object")
      cnt = cnt + contacts[type].checked;
  }
  if (cnt > 0) {
    alert(str_raf_error_active_selections);
    reenableButton("rafSendBtn");
    return;
  }

  rafButtonControl(true);
  if(document.getElementById("rafaMyName"))
   str_raf_myname = document.getElementById("rafaMyName").value;
  if (str_raf_myname.indexOf("<") >= 0)
    str_raf_myname = "";
  if(document.getElementById("raf_message_txt"))
   personalMsg = document.getElementById("raf_message_txt").value;

  var personalMsgTmp = personalMsgValidate();
  var str_contacts = "";
  for (var type in contacts) {
    for (var c in contacts[type].list) {
      if (contacts[type].list[c].status === true) {
        if (str_contacts != "")
          str_contacts += "::";
        str_contacts += contacts[type].fullname +","+contacts[type].list[c].provider +","+ contacts[type].list[c].name +","+ contacts[type].list[c].contact;
      }
    }
  }
  var str_providers = "";
  for (var pid in providers) {
    if (str_providers != "")
      str_providers += "::";
    str_providers += providers[pid].name +","+ providers[pid].uid +","+ providers[pid].pwd ;
  }

  if (document.getElementById("ajax_loader_send"))
    document.getElementById("ajax_loader_send").style.display = 'block';

  ajaxCall('ajax_com/raf.php','val=submitRAFContacts&sport='+ajaxSport+'&myname='+str_raf_myname+'&providers='+str_providers+'&contacts='+escape(str_contacts)+'&message='+escape(personalMsg), 'rafAjaxResponseSubmit', '');
}


function personalMsgValidate() {
  personalMsg = personalMsg.replace(/<.*>/g,"").replace(/^[\s]+/,'').replace(/[\s]+$/,'');
  var personalMsgTmp = personalMsg.replace(/[\n]/g,"<br>");
  return personalMsgTmp.replace(/[\s]{2,}/g," ");
}

function addContactMail() {
  rafButtonControl(true);
  var addName = document.getElementById("raf_add_name").value;
  var addMail = document.getElementById("raf_add_mail").value;
  if ( addContact("mail", "email", addName, addMail, true) ) {
    document.getElementById("raf_add_name").value = "<"+ str_raf_fullname +">";
    document.getElementById("raf_add_mail").value = "<"+ str_raf_mail +">";
  }
  showContacts("all", true, "raf_contact");
  
  
  rafButtonControl(false);
}

function addContacts(type) {
  rafButtonControl(true);
  for (var i in contacts[type].list) {
    if (contacts[type].list[i].status === false) {
      cbox = document.getElementById(type+"&"+i);
      if (cbox.checked == true) {
        contacts[type].checked--;
        addContact(type, contacts[type].list[i].provider, contacts[type].list[i].name, contacts[type].list[i].contact, true);
      }
    }
  }
  showContentList(type);
  rafButtonControl(false);
}

function checkPersonalMsg(maxlength, outid, text) {
  if (document.getElementById("raf_message_txt")) {
    var obj = document.getElementById("raf_message_txt");
    personalMsgValid = showTextCnt(obj, maxlength, outid, text);
  }
  if (personalMsgValid)
    reenableButton("rafSendBtn");
  else
    disableButton("rafSendBtn");

}

