<?xml version="1.0"?>
<!--
 -
 -  $Id$
 -
 -  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 -  project.
 -
 -  Copyright (C) 1998-2018 OpenLink Software
 -
 -  This project is free software; you can redistribute it and/or modify it
 -  under the terms of the GNU General Public License as published by the
 -  Free Software Foundation; only version 2 of the License, dated June 1991.
 -
 -  This program is distributed in the hope that it will be useful, but
 -  WITHOUT ANY WARRANTY; without even the implied warranty of
 -  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 -  General Public License for more details.
 -
 -  You should have received a copy of the GNU General Public License along
 -  with this program; if not, write to the Free Software Foundation, Inc.,
 -  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 -
-->
<v:page name="fb-user-home"
        xmlns:vm="http://www.openlinksw.com/vspx/ods/"
        xmlns:v="http://www.openlinksw.com/vspx/"
        style="index.xsl"
        fast-render="1"
        doctype="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <vm:page>
    <vm:header>
      <vm:title>
        <v:label value="--'Facebook integration to ODS'" render-only="1"/>
      </vm:title>
    </vm:header>
    <vm:pagewrapper>
      <vm:navigation-new on="site"/>
      <vm:subnavigation-new on="site"/>
      <v:variable name="_fb" type="DB.DBA.Facebook"/>
      <v:variable name="_fb_isset" type="integer"/>
      <v:variable name="_fb_usernotcorrespond" type="integer"/>
      <v:variable name="_sync" type="integer"/>
      <v:variable name="_ods_login_params" type="varchar"/>
      <v:variable name="_ods_u_name" type="varchar"/>
      <v:variable name="_fb_u_name" type="varchar"/>
      <v:variable name="_dhtml" type="any" />
      <v:variable name="syncdata_arr" type="any" />
      <vm:body>
        <v:before-data-bind>
        <![CDATA[
          declare i integer;
          declare _user_name varchar;
          declare _user_id integer;
          declare contatcst_import_res any;
          declare _http_query_str varchar;

          _http_query_str:=http_request_get ('QUERY_STRING');
          if (locate('auth_token',_http_query_str)>0)
          {
            declare _start,_end integer;
            _start:=locate('&auth_token',_http_query_str);
            _end:=locate('&',_http_query_str,_start+1);
            if(_start>0)
            {
              if(_end>0)
                 _http_query_str:=subseq(_http_query_str,0,_start-1)||subseq(_http_query_str,_end-1);
              else
                 _http_query_str:=subseq(_http_query_str,0,_start-1);

            }

            _http_query_str:=replace(_http_query_str,'auth_token','false_auth_token');
          }
          if(_http_query_str is not null and length(_http_query_str)>0)
          {
            declare _qstr_pos integer;
            _qstr_pos:=position ('_http_query_str', params);
            if(_qstr_pos>0)
            {
               params := vector_concat (subseq (params, 0, _qstr_pos-1),
                                         vector('_http_query_str', _http_query_str), subseq (params, _qstr_pos));
            } else {
               params:=vector_concat(params, vector('_http_query_str',_http_query_str));
          }
          }
          self._ods_login_params:='';
          if(length(self.sid)>0)
            self._ods_login_params:='sid='||self.sid||'&realm='||coalesce(self.realm,'wa');

            declare exit handler for not found
            {
          _user_name:=null;
          _user_id:=null;
          };
              select VS_UID,U_ID into _user_name,_user_id from DB.DBA.VSPX_SESSION, DB.DBA.SYS_USERS where VS_UID=U_NAME and VS_SID=self.sid;
          self._ods_u_name:=_user_name;

          declare _ods_fb_id,_fb_user_assocexist integer;
          declare _cfb_id integer;
          declare _cfb_session varchar;
          declare _fb_user integer;
          declare fb_dba_options any;

            _ods_fb_id := (select WAUI_FACEBOOK_ID from DB.DBA.WA_USER_INFO where WAUI_U_ID = _user_id);
            if (_get_ods_fb_settings(fb_dba_options)) --fb_dba_options is array of type (facebook_api_key,facebook_api_secret)
          {
             self._fb_isset:=1;
             self._fb:= new Facebook(fb_dba_options[0], fb_dba_options[1], params,lines);
            _cfb_id :=  cast (self._fb._user as integer);
            _cfb_session :=  self._fb.api_client.session_key;
            if (_cfb_id > 0 and _cfb_session <> '')
            {
              self._fb.set_user(_cfb_id,_cfb_session,now());
              _fb_user  := _cfb_id;
          }
          } else {
             self._fb_isset:=0;
          }

          self._dhtml:=vector();
          self.syncdata_arr:=vector();

          declare _html,_src,_fb_user_fullname varchar;

            _fb_user_fullname := '';
          if(self._fb_isset)
          {
            _fb_user_assocexist:=0;
            if(_fb_user is not null and _fb_user>0
               and
               exists (select 1 from DB.DBA.WA_USER_INFO where WAUI_FACEBOOK_ID=_fb_user)
              )
            {
               _fb_user_assocexist:=1;
            }
            self._fb_usernotcorrespond:=0;
            if((_ods_fb_id is not null
                 and _ods_fb_id>0
                 and _fb_user>0
                 and _ods_fb_id<>_fb_user
               )
               or
               ( (_ods_fb_id is null or _ods_fb_id=0)
                 and _fb_user>0
                 and _fb_user_assocexist=1
               )
              )
            {
              self._fb_usernotcorrespond:=1;
            }

            declare _assoc_action varchar;

            _assoc_action:=get_keyword('assoc', params,null);

            if(_assoc_action is not null)
            {

               if (_fb_user<>0 and _user_name is not null)
               {
                 if(_assoc_action='assoc')
                  {
                    update DB.DBA.WA_USER_INFO set WAUI_FACEBOOK_ID=_fb_user where WAUI_U_ID=_user_id;
                  }
                  else if (_assoc_action = 'unassoc')
                  {
                    update DB.DBA.WA_USER_INFO set WAUI_FACEBOOK_ID=null where WAUI_U_ID=_user_id;
               }
            }
              }

            -- ODS autologin for ODS use that has signed in to FB but not to ODS and he has connected his ods user to facebook user
            if(_fb_user<>0 and _user_name is null)
            {
                declare exit handler for not found
                {
                _user_name := null;
                _user_id := null;
              };
              select WAUI_U_ID,U_NAME into _user_id,_user_name from DB.DBA.WA_USER_INFO, DB.DBA.SYS_USERS where WAUI_U_ID=U_ID and WAUI_FACEBOOK_ID=_fb_user;
              if( _user_id is not null)
              {
                 declare _sid varchar;

                _sid :=  md5 (concat (datestring (now ()), http_client_ip (), http_path ()));
                 insert into DB.DBA.VSPX_SESSION (VS_REALM, VS_SID, VS_UID, VS_STATE, VS_EXPIRY)
                  values ('wa', _sid, _user_name, serialize (vector ('vspx_user', _user_name)), now());
                 http_request_status ('HTTP/1.1 302 Found');
                 http_header (sprintf('Location: %sfb_front.vspx?sid=%s&realm=wa\r\n', self.odsbar_ods_gpath, _sid));
                 return;
              }
            }

            declare _are_assoc int;

            _are_assoc := 0;
            if(exists (select 1 from DB.DBA.WA_USER_INFO where  WAUI_U_ID=_user_id and WAUI_FACEBOOK_ID=_fb_user))
               _are_assoc:=1;

            if(_fb_user<>0)
            {
              declare _res any;


              _res:=self._fb.api_client.users_getInfo(cast(_fb_user as varchar),'name,pic,affiliations,activities,interests,work_history');

              if(_res is not null)
              {
                _src:=cast(xpath_eval('/users_getInfo_response/user/pic',_res) as varchar);

                declare networks any;
                declare networks_str varchar;
                networks_str:='';

                networks:=xpath_eval('//users_getInfo_response/user/affiliations/affiliation',_res,0);

                if(isarray(networks))
                {
                  networks_str:='';
                  for (I := 0; i < length (networks); I := I + 1)
                  {
                   if(i<(length(networks)-1))
                      networks_str:=networks_str||cast(xpath_eval('string(name)',networks[i]) as varchar)||',';
                   else
                      networks_str:=networks_str||cast(xpath_eval('string(name)',networks[i]) as varchar);
                  }
                }
                if(length(networks_str)=0)
                   networks_str:='&nbsp';

                if(length(_src)=0)
                   _src:=self.odsbar_ods_gpath ||'images/t_default.jpg';

                _html:='<table style=padding:0px;spacing:0px><tr>'||
                       '<td style="width:160px; text-align:center;text-size:9pt;vertical-align: top;"><img src="'||_src||'">'||
                           '<h3>'||cast(xpath_eval('/users_getInfo_response/user/name',_res) as varchar);
                  if (DB.DBA.WA_USER_APP_ENABLE (_user_id))
                  _html := _html ||
                           ' <img id="rdf_'||cast(self._fb._user as varchar)||'"src="./images/oat/RDF_rdf.png"/>';
                  _html := _html ||
                           '</h3><br/></td>'||
                       '<td valign="top"><table ><tr>'||
                       '<tr><td style="width:80px;font-weight: bold;padding-right: 5px">Personal Info</td><td></td></tr>'||
                       '<tr><td style="width:80px;padding-right: 5px;color: #808080">Activities:</td><td>'||cast(xpath_eval('string(/users_getInfo_response/user/activities)',_res) as varchar)||'</td>'||
                       '<tr><td style="width:80px;padding-right: 5px;color: #808080">Interests:</td><td>'||cast(xpath_eval('string(/users_getInfo_response/user/interests)',_res) as varchar)||'</td></tr>'||
                       '<tr><td style="width:80px;padding-right: 5px;color: #808080">Networks:</td><td>'||networks_str||'</td></tr>'||
                       '<tr><td style="width:80px;font-weight: bold;padding: 15px 5px 0px 0px">Work info</td><td></td></tr>'||
                       '<tr><td style="width:80px;padding-right: 5px;color: #808080">Employer:</td><td>'||cast(xpath_eval('string(/users_getInfo_response/user/work_history/work_info[1]/company_name)',_res) as varchar)||'</td></tr>'||
                       '<tr><td style="width:80px;padding-right: 5px;color: #808080">Position:</td><td>'||cast(xpath_eval('string(/users_getInfo_response/user/work_history/work_info[1]/position)',_res) as varchar)||'</td></tr>'||
                       '</tr></table></td>'||
                       '</tr></table>';
                _fb_user_fullname:=cast(xpath_eval('/users_getInfo_response/user/name',_res) as varchar);
                self._fb_u_name:=_fb_user_fullname;
              } else {
                _html:='Hello, user:'||cast(_fb_user as varchar)||'<br/>';
              }

              self._dhtml:=vector_concat(self._dhtml,vector('user',_html));

              _res:=self._fb.api_client.friends_get();
              if(isarray(_res) and length(_res)>0)
              {
                declare ff_ids varchar;
                ff_ids:='';
                _html:='';
                for (I := 0; i < length (_res); I := I + 1)
                {
                 if(i<(length(_res)-1))
                    ff_ids:=ff_ids||_res[i]||',';
                 else
                    ff_ids:=ff_ids||_res[i];
                }
                self._dhtml:=vector_concat(self._dhtml,vector('fbf_jsarrstr',ff_ids));
                _res:=self._fb.api_client.users_getInfo(ff_ids,'name,pic_small');
                 if(_res is not null)
                 {
                 _html:='<div class="doc">';
                  _res:=xpath_eval('/users_getInfo_response/user',_res,0);
                    if (length (_res))
                  {
                      foreach (any _resData in _res) do
                    {
                        _src := xpath_eval ('string (pic_small)', _resData);
                      if(length(_src)=0)
                        _src:=self.odsbar_ods_gpath ||'images/t_default.jpg';

                        _html := _html ||
                                 '<div style="float:left;width:160px;padding:5px;border-right:1px dotted #888888;text-align:center">' ||
                                      '<img src="'||_src||'" >'||
                                      '<br/>'||
                                 '<a href="http://www.facebook.com/profile.php?id=' || xpath_eval ('string(uid)',_resData) || '" target="_blank">' || serialize_to_UTF8_xml (xpath_eval('string(name)',_resData)) || '</a> ';
                        if (DB.DBA.WA_USER_APP_ENABLE (_user_id))
                        _html := _html ||
                                 '<img id="rdf_'||xpath_eval('string(uid)',_resData)||'"src="./images/oat/RDF_rdf.png"/>';
                        _html := _html || '</div>';
                    }
                  }
                  _html:=_html||'</div>';
                 }
              } else {
                _html:='You have no Facebook friends.';
              }
              self._dhtml:=vector_concat(self._dhtml,vector('friends',_html));
              if(get_keyword('import', params,'')='create_import')
              {
                  DB.DBA.ODS_CREATE_NEW_APP_INST ('AddressBook', _user_name||'''s AddressBook', _user_name);
                 sync_fbf_odsab(self._fb,_user_id,_fb_user);
              }
              if(get_keyword('import', params,'')='import')
                 sync_fbf_odsab(self._fb,_user_id,_fb_user);

              self._sync:=0;
              if(get_keyword('import', params,'')='update')
              {
                 declare syncdata_jsarrstr varchar;

                  self._sync := 1;
                  syncdata_jsarrstr := get_syncdata_arr(self._fb,_user_id, 1);
                 if(length(syncdata_jsarrstr))
                  self._dhtml:=vector_concat(self._dhtml,vector('syncdata_jsarrstr',syncdata_jsarrstr));
              }
              else if (get_keyword('import', params,'')='updateadvanced')
              {
                 declare syncdata_jsarrstr varchar;

                  self._sync := 2;
                 syncdata_jsarrstr:=get_syncdata_arr(self._fb,_user_id);
                 if(length(syncdata_jsarrstr))
                  self._dhtml:=vector_concat(self._dhtml,vector('syncdata_jsarrstr',syncdata_jsarrstr));
              }
              contatcst_import_res:=sync_fbf_odsab(self._fb,_user_id,_fb_user,0,1);
              self.syncdata_arr:=vector_concat(vector(_fb_user),contatcst_import_res);
            }
            _html:='';

            if(_user_id is null or _fb_user is null or _fb_user=0)
            {
               if(_user_id is not null)
                  _html:=_html||'You are logged as ODS user: '||_user_name||'.';
               else
                  _html:=_html||'You are not logged as ODS user!';

               if(_fb_user<>0)
                  _html:=_html||'<br/><br/>You are logged as Facebook user: '||_fb_user_fullname||'.';

               _html:=_html||'<br/>';
            }
            if(_user_id is not null and _fb_user>0 and _are_assoc=0)
            {
                _html := _html||'<br/>'||_user_name||' and '||_fb_user_fullname||' are not logically connected in ODS.<br /> <a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?assoc=assoc',self._ods_login_params)||'">Do you want to connect them?</a>';
            }
            else if (_user_id is not null and _fb_user<>0 and _are_assoc=1)
            {
                _html := _html||'<br/>'||_user_name||' and '||_fb_user_fullname||' are logically connected in ODS.<br /><a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?assoc=unassoc',self._ods_login_params)||'">Disconnect?</a>';
            }
            else if(_user_id is not null and _fb_user=0)
            {
               _html:=_html||'';
            }
            else if(_user_id is null and _fb_user<>0)
            {
               _html:=_html||'<br/><a href="'||self.odsbar_ods_gpath ||'register.vspx?reguid='||lcase(replace(_fb_user_fullname,' ',''))||'&fb_id='||cast(_fb_user as varchar)||'&URL='||self.odsbar_ods_gpath ||'fb_front.vspx">Create ODS user and connect it to:'||_fb_user_fullname||'</a>';
            }
            if(_are_assoc=1)
            {
              declare dataspace_url varchar;
              dataspace_url:=sprintf('/dataspace/%U/addressbook',_user_name);
              if(isarray(contatcst_import_res))
                 dataspace_url:=sprintf('%s/%U',dataspace_url,(select WAI_NAME from DB.DBA.WA_INSTANCE where WAI_ID=contatcst_import_res[4]));

              if(isarray(contatcst_import_res) and contatcst_import_res[0]=-1 and wa_check_package ('addressbook') and _user_id is not null)
                 _html:=_html||'<br/><br/><a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=create_import',self._ods_login_params)||'">Create ODS addressbook and import Facebook contacts.</a>';


              if(isarray(contatcst_import_res) and contatcst_import_res[0]=1 and contatcst_import_res[3]=0)
                 _html:=_html||'<br/><br/>You have no Facebook contacts that may be imported to ODS AddressBook.';

              if(isarray(contatcst_import_res) and contatcst_import_res[0]=0 and contatcst_import_res[1]>0)
                _html:=_html||'<br/><br/>You have '||cast(contatcst_import_res[1] as varchar)||' Facebook contact'||(case when contatcst_import_res[1]>1 then 's' else '' end)||
                                ' that may be imported to your <a href="'||wa_expand_url(dataspace_url,self._ods_login_params)||'">ODS AddressBook</a> application.<br /><a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=import',self._ods_login_params)||'">Import</a>';

              if(isarray(contatcst_import_res) and contatcst_import_res[0]=0 and contatcst_import_res[2]>0)
                _html:=_html||'<br/><br/>You have '||cast(contatcst_import_res[2] as varchar)||' Facebook contact'||(case when contatcst_import_res[2]>1 then 's' else '' end)||
                                ' that may be updated in your <a href="'||wa_expand_url(dataspace_url,self._ods_login_params)||'">ODS AddressBook</a> application.<br /><a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=update',self._ods_login_params)||'">Synchronize</a>';

              if(isarray(contatcst_import_res) and contatcst_import_res[0]=1 and contatcst_import_res[2]>0)
                _html:=_html||'<br/><br/>You have '||cast(contatcst_import_res[2] as varchar)||' Facebook contact'||(case when contatcst_import_res[2]>1 then 's' else '' end)||
                                ' that may be updated in your <a href="'||wa_expand_url(dataspace_url,self._ods_login_params)||'">ODS AddressBook</a> application.<br /><a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=update',self._ods_login_params)||'">Synchronize</a>';
            }
            self._dhtml:=vector_concat(self._dhtml,vector('ods_user',_html));

            declare validate_by_fields any;

              _html := 'var validateObj={};';
            validate_by_fields := coalesce ((select deserialize (LV_FIELDS) from LDAP..LDAP_VALIDATION where LV_USER_ID = _user_id), vector());
            if(validate_by_fields is not null and length(validate_by_fields)>0)
            {
                declare i integer;
               for (i := 0; i < length (validate_by_fields); i := i + 2)
                   _html:=sprintf('%s\nvalidateObj[''%s'']=%s ;',_html,validate_by_fields[i],coalesce(validate_by_fields[i+1],0));
            }
            self._dhtml:=vector_concat(self._dhtml,vector('validation_obj',_html));
         }
        ]]>
        </v:before-data-bind>
        <?vsp
          if (self._fb_isset)
          {
            http(         '<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>');
            http(sprintf ('<fb:login-button autologoutlink="true" onlogin1="window.location=\'/ods/fb_front.vspx?sid=%s&ream=%s\'"></fb:login-button>', self.sid, self.realm));
            http(sprintf ('<script type="text/javascript">FB.init("%s", "fb_dummy.vsp", {"reloadIfSessionStateChanged":true});</script>', self._fb.api_key));
          }
        ?>
<script type="text/javascript">
<![CDATA[
function dd(txt){
  if (typeof console == 'object')
    console.debug(txt);
  }

 var cssDockNode = document.createElement('link');
 cssDockNode.type = 'text/css';
 cssDockNode.rel = 'stylesheet';
 cssDockNode.href = '<?V self.odsbar_ods_gpath ?>dock.css';
 document.getElementsByTagName("head")[0].appendChild(cssDockNode);

 var docColumnMinSize=235;
 var usableViewRatio=.94;

 var ajaxSuccCallCount=0;
ODSInitArray.push(fbInitPrepare);

function fbInitPrepare()
{
  ods_bar_state_set('min');
  OAT.Preferences.imagePath='./images/oat/';
  if(typeof(fbInit)!='undefined')
                OAT.Loader.load(["dock","animation","ajax","xml","combobutton","mswin","window","anchor","sparql"], function(){setTimeout(fbInit,80)});
}

var colors = ["#99c","#cc9","#c8c","#9c9"];
var dock = false;
var counter = 0;
var urls = {};

function dockAdd(win_title,custom_colsize)
{

	var container = OAT.Dom.create("div");
  container.setAttribute('id','dockwin_'+counter+'container');

	var bodyDiv = OAT.Dom.create("div");
  bodyDiv.setAttribute('id','dockwin_'+counter+'_body');
	var subDiv = OAT.Dom.create("div");
	subDiv.style.position='absolute';
	subDiv.style.bottom='15px';
  subDiv.setAttribute('id','dockwin_'+counter+'_sub');

	var color = colors[counter % colors.length];

	var win = dock.addObject(counter % dock.columns.length,container,{color:color,title:win_title,titleColor:"#000"});
  win.id='dockwin_'+counter;
  win.div.id='dockwin_'+counter;

  var col_px = Math.floor(OAT.Dom.getViewport()[0]*usableViewRatio/dock.columns.length);
  if (col_px<docColumnMinSize)
    col_px=docColumnMinSize;

  if(typeof(custom_colsize)!='undefined' && custom_colsize>10)
     dock.columns[counter % dock.columns.length].style.width=custom_colsize+'px';
  else
     dock.columns[counter % dock.columns.length].style.width=col_px+'px';

	OAT.Dom.append([container,bodyDiv,subDiv]);

	counter++;

  return win;
}

function ajaxUpdate(abID,odsCID,fbCID,dockObj,mappingStr)
{
  var data='sid=<?Vself.sid?>&'+
  	       'realm=<?Vself.realm?>&'+
  	       'instid='+abID+'&'+
  	       'fb_userid=<?V(case when self._fb is not null then self._fb._user else '' end)?>&'+
  	       'fb_session=<?V(case when self._fb is not null then self._fb.api_client.session_key else '' end)?>&'+
  	       'fb_cid='+fbCID+'&'+
  	       'ods_cid='+odsCID;
 if(mappingStr.length>0)
    data=data+'&usemapping=1&'+'mapping='+mappingStr;

  var options = {
  	auth:OAT.AJAX.AUTH_BASIC,
  	onerror:function(request) { dd(request.getStatus()); }
  }
  var callback = function(xmlString) {
                                       var xmlDoc = OAT.Xml.createXmlDoc(xmlString);
                                       var res_code_xml = OAT.Xml.xpath(xmlDoc, '//res_code', {});
                                       if(res_code_xml.length)
                                          var res_code = OAT.Xml.textValue(res_code_xml[0]);

                                       if(res_code==0)
                                       {
                                          var i=5;
                                          setInterval(function(){
                                                                 if(i>0)
                                                                    $(dockObj.id+'_body').innerHTML='Synchronization successful. Autoclose in '+i+' seconds';
                                                                  else
                                                                    dockObj.dock.removeObject(dockObj);
                                                                  i--;
                                                                }, 1000);

               } else {
                                        var err_msg_xml  = OAT.Xml.xpath(xmlDoc, '//err_msg', {});
                                        var err_msg='';
                                        if(err_msg_xml.length)
                                           err_msg = OAT.Xml.textValue(err_msg_xml[0]);
                                        $(dockObj.id+'_body').innerHTML='Synchronization unsuccessful due to:'+err_msg
                                       }
             }

  OAT.AJAX.POST("facebook_helper.vsp", data, callback, options);
}


function ajaxUpdateAdvanced(abID,odsCID,fbCID,dockObj,mappingStr,validationStr,totalCount,pbUnit)
{
  var data='sid=<?Vself.sid?>&'+
  	       'realm=<?Vself.realm?>&'+
  	       'instid='+abID+'&'+
  	       'fb_userid=<?V(case when self._fb is not null then self._fb._user else '' end)?>&'+
  	       'fb_session=<?V(case when self._fb is not null then self._fb.api_client.session_key else '' end)?>&'+
  	       'fb_cid='+fbCID+'&'+
  	       'ods_cid='+odsCID+'&'+
  	       'usemapping=1&'+
  	       'mapping='+mappingStr+'&'+
  	       'usevalidation=1&'+
  	       'validation='+validationStr;
  	       ;

  var options = {
  	auth:OAT.AJAX.AUTH_BASIC,
  	onerror:function(request) { dd(request.getStatus()); }
  }
  var callback = function(xmlString) {
                                       var xmlDoc = OAT.Xml.createXmlDoc(xmlString);
                                       var res_code_xml = OAT.Xml.xpath(xmlDoc, '//res_code', {});
                                       if(res_code_xml.length)
                                          var res_code = OAT.Xml.textValue(res_code_xml[0]);

                                       if(res_code==0)
                                       {
                                         ajaxSuccCallCount=ajaxSuccCallCount+1;
                                         if(ajaxSuccCallCount==totalCount)
                                         {
                                           $(dockObj.id+'_progress').style.width=OAT.Dom.getWH($(dockObj.id+'_bar'))[0]+'px';
                                           $(dockObj.id+'_counterdiv').innerHTML=totalCount+' of '+totalCount+' contacts synchronized';
                  } else {
                                           $(dockObj.id+'_progress').style.width=OAT.Dom.getWH($(dockObj.id+'_progress'))[0]+pbUnit+'px';
                                           $(dockObj.id+'_counterdiv').innerHTML=ajaxSuccCallCount+' of '+totalCount+' contacts synchronized';
                                         }
                } else {
                                        var err_msg_xml  = OAT.Xml.xpath(xmlDoc, '//err_msg', {});
                                        var err_msg='';
                                        if(err_msg_xml.length)
                                           err_msg = OAT.Xml.textValue(err_msg_xml[0]);
                                        $(dockObj.id+'_body').innerHTML='Synchronization unsuccessful due to:'+err_msg
                                       }
              }
  OAT.AJAX.POST("facebook_helper.vsp", data, callback, options);
}

function derefFBP(fbCID)
{
  var data='helpertact=deref&'+
           'sid=<?Vself.sid?>&'+
  	       'realm=<?Vself.realm?>&'+
  	       'fb_userid=<?V(case when self._fb is not null then self._fb._user else '' end)?>&'+
  	       'fb_session=<?V(case when self._fb is not null then self._fb.api_client.session_key else '' end)?>&'+
  	       'fb_cid='+fbCID;

  var options = {
  	auth:OAT.AJAX.AUTH_BASIC,
  	onerror:function(request) { dd(request.getStatus()); }
  }
  var callback = function(xmlString) {
                                       var xmlDoc = OAT.Xml.createXmlDoc(xmlString);
                                       var res_code_xml = OAT.Xml.xpath(xmlDoc, '//res_code', {});
                                       if(res_code_xml.length)
                                          var res_code = OAT.Xml.textValue(res_code_xml[0]);

                                       if(res_code==1)
                                       {


                                          var resCallback = function(_xmlTxt) {
                                              _xmlTxt=_xmlTxt.substring(_xmlTxt.indexOf('<results '),_xmlTxt.length);
                                              _xmlTxt=_xmlTxt.substring(0,_xmlTxt.indexOf('</sparql>'));

                                              _xml=OAT.Xml.createXmlDoc(_xmlTxt);

                                              var nsObj = {};

                                        		  var resultArrayS = OAT.Xml.xpath(_xml, '//result/binding[@name="s"]/node()/text()', nsObj);
                                        		  var resultArrayP = OAT.Xml.xpath(_xml, '//result/binding[@name="p"]/node()/text()', nsObj);
                                        		  var resultArrayO = OAT.Xml.xpath(_xml, '//result/binding[@name="o"]/node()/text()', nsObj);

                                              var _t=OAT.Dom.create("table",{borderCollapse: 'collapse',margin:'0px',padding:'0px'});
                                              var _tb=OAT.Dom.create("tbody");
                                              var _tr=OAT.Dom.create("tr");
                                            var _td1=OAT.Dom.create("td",{background: '#EBEADB',border:'1px solid #CCC',fontWeight:'bold'});
                                                  _td1.innerHTML='s';
                                              var _td2=OAT.Dom.create("td",{background: '#EBEADB',border:'1px solid #CCC',fontWeight:'bold'});
                                                  _td2.innerHTML='p';
                                              var _td3=OAT.Dom.create("td",{background: '#EBEADB',border:'1px solid #CCC',fontWeight:'bold'});
                                                  _td3.innerHTML='o';

                                              OAT.Dom.append([_t,_tb],[_tb,_tr],[_tr,_td1,_td2,_td3]);

                                              for(var i=0;i<resultArrayS.length;i++)
                                              {
                                                if(OAT.Xml.textValue(resultArrayO[i]).indexOf('nodeID')==-1)
                                                {
                                                  var _bgc='#F0F0FF';
                                                  if(i%2)_bgc='#F8F8FF';
                                                  var _tr=OAT.Dom.create("tr");
                                                  var _td1=OAT.Dom.create("td",{border:'1px solid',background: _bgc});
                                                  var _td2=OAT.Dom.create("td",{border:'1px solid',background: _bgc});
                                                  var _td3=OAT.Dom.create("td",{border:'1px solid',background: _bgc});


                                                  OAT.Dom.append([_tb,_tr],[_tr,_td1,_td2,_td3],
                                                                 [_td1,constructElm(OAT.Xml.textValue(resultArrayS[i]))],
                                                                 [_td2,constructElm(OAT.Xml.textValue(resultArrayP[i]))],
                                                                 [_td3,constructElm(OAT.Xml.textValue(resultArrayO[i]))]
                                                                )
                                                }
                                              }

                                          var rdfDiv=OAT.Dom.create('div');
                                          rdfDiv.id='resdiv_'+fbCID;

                                          OAT.Dom.append([rdfDiv,_t]);

                                          var optObj = {
                                          	href: '/sparql/',
                                           	title:"RDF",
                                          	content:rdfDiv,
                                          	width:400,
                                          	height:300,
                                          	result_control:false,
                                          	activation:"hover"
                                          };
                                          var rdfObj=$('rdf_'+fbCID);
                                          if(rdfObj)
                                          {
                                            rdfObj.style.cursor='pointer';
                                            OAT.Anchor.assign(rdfObj,optObj);
                                          }

                                          }
                                          function simpleUri(uri)
                                          {
                                  					var idx = Math.max(uri.lastIndexOf("/"),uri.lastIndexOf("#"),uri.lastIndexOf(":"));
                                  					var simple = uri.substring(idx+1);
                                  					if (simple == "this") {
                                  						var idx1 = Math.max(value.lastIndexOf("/"));
                                  						var idx2 = Math.max(value.lastIndexOf("#"));
                                  						var simple = uri.substring(idx1+1,idx2);
                                  					}

                                  					return simple;
                                          }

                                          function constructElm(txt)
                                          {
                                            var simple=simpleUri(txt);
                    if (txt.indexOf('http') == 0) {
                                              var _a=OAT.Dom.create("a");
                                              _a.href=txt;
                                              _a.innerHTML=simple;
                                              _a.target='_blank';
                                              return _a;
                    }
                                              return OAT.Dom.text(simple);
                                          }

                                          function buildRequest (opts) {
                                          		var paramsObj = {};
                                          		paramsObj["query"] = opts.query;
                                          		paramsObj["format"] = opts.format?opts.format:"application/rdf+xml";
                                          		if (opts.defaultGraph && !opts.query.match(/from *</i)) { paramsObj["default-graph-uri"] = opts.defaultGraph; }
                                          		if (opts.limit) { paramsObj["maxrows"] = opts.limit; }
                                          		if (opts.sponge && self.options.virtuoso) { paramsObj["should-sponge"] = opts.sponge; }

                                          		var arr = [];
                                          		for (var p in paramsObj) {
                                          			arr.push(p+"="+encodeURIComponent(paramsObj[p]));
                                          		}
                                          		for (var i=0;i<opts.namedGraphs.length;i++) {
                                          			arr.push("named-graph-uri="+encodeURIComponent(opts.namedGraphs[i]));
                                          		}
                                          		return arr.join("&");
                                          	}
                                          var optObj={query:"SELECT ?s, ?p, ?o from <http://www.facebook.com/profile.php?id="+fbCID+"> where { ?s ?p ?o }",
                                                      format:"xml" ,
                                                      namedGraphs:false
                                                 };
                                          var _endpoint='/sparql/';
                                          var _request=buildRequest(optObj);
                                      		OAT.AJAX.POST(_endpoint,_request,resCallback,{type:OAT.AJAX.TYPE_TEXT});
                } else {
                                        var err_msg_xml  = OAT.Xml.xpath(xmlDoc, '//err_msg', {});
                                        var err_msg='';
                                        if(err_msg_xml.length)
                                           err_msg = OAT.Xml.textValue(err_msg_xml[0]);
                                        $(dockObj.id+'_body').innerHTML='Synchronization unsuccessful due to:'+err_msg
                                       }
              }
  OAT.AJAX.POST("facebook_helper.vsp", data, callback, options);
}

function genAbFieldsCb(cbId,defSelection)
{
  var _tr=OAT.Dom.create("tr");
  var _td1=OAT.Dom.create("td",{textAlign:'right'});
  var _label=OAT.Dom.create("label",{fontWeight:'bold',fontSize:'12px'});
  _label.innerHTML=cbId;
  _label.forHTML=cbId;
  var _td2=OAT.Dom.create("td",{textAlign:'left'});

  var cb = OAT.Dom.create("select");
  cb.id = cbId;
  OAT.Dom.option('--','skip',cb);
  OAT.Dom.option('Name','P_NAME',cb);
  OAT.Dom.option('Title','P_TITLE',cb);
  OAT.Dom.option('First Name','P_FIRST_NAME',cb);
  OAT.Dom.option('Middle Name','P_MIDDLE_NAME',cb);
  OAT.Dom.option('Last Name','P_LAST_NAME',cb);
  OAT.Dom.option('Full Name','P_FULL_NAME',cb);
  OAT.Dom.option('Gender','P_GENDER',cb);
  OAT.Dom.option('Birthday','P_BIRTHDAY',cb);
  OAT.Dom.option('Contact - Mail','P_MAIL',cb);
  OAT.Dom.option('Contact - Web address','P_WEB',cb);
  OAT.Dom.option('Contact - Icq','P_ICQ',cb);
  OAT.Dom.option('Contact - Skype ID','P_SKYPE',cb);
  OAT.Dom.option('Contact - AIM Name','P_AIM',cb);
  OAT.Dom.option('Contact - Yahoo! ID','P_YAHOO',cb);
  OAT.Dom.option('Contact - MSN Messenger','P_MSN',cb);
  OAT.Dom.option('Home - Country','P_H_COUNTRY',cb);
  OAT.Dom.option('Home - City','P_H_CITY',cb);
  OAT.Dom.option('Home - State/Province','P_H_STATE',cb);
  OAT.Dom.option('Home - Zip/Postal Code','P_H_CODE',cb);
  OAT.Dom.option('Home - Address1','P_H_ADDRESS1',cb);
  OAT.Dom.option('Home - Address2','P_H_ADDRESS2',cb);
  OAT.Dom.option('Home - Time Zone','P_H_TZONE',cb);
  OAT.Dom.option('Home - Latitude','P_H_LAT',cb);
  OAT.Dom.option('Home - Longitude','P_H_LNG',cb);
  OAT.Dom.option('Home - Phone','P_H_PHONE',cb);
  OAT.Dom.option('Home - Mobile','P_H_MOBILE',cb);
  OAT.Dom.option('Home - Fax','P_H_FAX',cb);
  OAT.Dom.option('Home - Mail','P_H_MAIL',cb);
  OAT.Dom.option('Home - Web address','P_H_WEB',cb);
  OAT.Dom.option('Business - Country','P_B_COUNTRY',cb);
  OAT.Dom.option('Business - City','P_B_CITY',cb);
  OAT.Dom.option('Business - State/Province','P_B_STATE',cb);
  OAT.Dom.option('Business - Zip/Postal Code','P_B_CODE',cb);
  OAT.Dom.option('Business - Address1','P_B_ADDRESS1',cb);
  OAT.Dom.option('Business - Address2','P_B_ADDRESS2',cb);
  OAT.Dom.option('Business - Time Zone','P_B_TZONE',cb);
  OAT.Dom.option('Business - Latitude','P_B_LAT',cb);
  OAT.Dom.option('Business - Longitude','P_B_LNG',cb);
  OAT.Dom.option('Business - Phone','P_B_PHONE',cb);
  OAT.Dom.option('Business - Mobile','P_B_MOBILE',cb);
  OAT.Dom.option('Business - Fax','P_B_FAX',cb);
  OAT.Dom.option('Business - Industry','P_B_INDUSTRY',cb);
  OAT.Dom.option('Business - Organization','P_B_ORGANIZATION',cb);
  OAT.Dom.option('Business - Department','P_B_DEPARTMENT',cb);
  OAT.Dom.option('Business - Job Title','P_B_JOB',cb);
  OAT.Dom.option('Business - Mail','P_B_MAIL',cb);
  OAT.Dom.option('Business - Web address','P_B_WEB',cb);

  cb.value=defSelection;

  OAT.Dom.append([_tr,_td1],[_td1,_label],[_tr,_td2],[_td2,cb])
              return _tr;
}

function getCustomMapping(mappingDockId)
{
  var resStr='';
  var mappingDock=$(mappingDockId);
  if($(mappingDock.id+'_body')!=false)
     mappingDock=$(mappingDock.id+'_body');

  var _selectArr=mappingDock.getElementsByTagName("select")

  for (var i=0;i<_selectArr.length;i++)
  {
   if(_selectArr[i].id!='')
   {
      if(resStr.length==0)
        resStr=_selectArr[i].id+','+_selectArr[i].value;
      else
        resStr=resStr+';'+_selectArr[i].id+','+_selectArr[i].value;

   }
  }

 return resStr;

}

function getCustomValidation(validationDockId)
{
  var resStr='';
  var validationDock=$(validationDockId);
  if($(validationDock.id+'_body')!=false)
     validationDock=$(validationDock.id+'_body');

  var inputCtrls=validationDock.getElementsByTagName('input');
  for (var i=0;i<inputCtrls.length;i++)
  {
      if(inputCtrls[i].type=='checkbox')
      {
        if(resStr.length==0)
           resStr=inputCtrls[i].value+','+(inputCtrls[i].checked ? 1 : 0);
        else
           resStr=resStr+';'+inputCtrls[i].value+','+(inputCtrls[i].checked ? 1 : 0);
      }

  }
 return resStr;

}

function inverseSelected(parentDiv)
{
  if(typeof(parentDiv)=='undefined') return;

  var inputCtrls=parentDiv.getElementsByTagName('input');

  for(var i=0; i<inputCtrls.length;i++)
  {
    if(inputCtrls[i].type=='checkbox')
       inputCtrls[i].checked= inputCtrls[i].checked ? false : true;
  }
}

]]>
</script>

<v:template type='simple' enabled='--case when self._fb_isset=1 and self._fb_usernotcorrespond=0  and self._sync=0 then 1 else 0 end'>
<script type="text/javascript">
<![CDATA[

var fbfStr=false;
function fbInit()
{

 dock = new OAT.Dock('fbDock',3);

 var user_win=dockAdd('Facebook User Info');
 var friends_win=dockAdd('User Facebook Friends Info');
 var ods_win=dockAdd('ODS User Info');

 $(user_win.id+'_body').innerHTML='<?vsp http(get_keyword('user',self._dhtml,'')); ?>';
 $(user_win.id+'_sub').innerHTML='<a style="text-decoration: none;padding-left:5px" href="http://www.facebook.com/profile.php?id=<?Vself._fb._user?>" target="_blank">View more...</a>';
 $(friends_win.id+'_body').innerHTML='<?vsp http(get_keyword('friends',self._dhtml,'')); ?>';
 $(ods_win.id+'_body').innerHTML='<?vsp http(get_keyword('ods_user',self._dhtml,'')); ?>';

 derefFBP(<?Vself._fb._user?>);

fbfStr='<?vsp http(get_keyword('fbf_jsarrstr',self._dhtml,'')); ?>';

 var fbfArr=fbfStr.split(',');
 for(var i=0;i<fbfArr.length;i++)
   derefFBP(fbfArr[i]);
}
    ]]>
</script>
<div id="fbDock"></div>
</v:template>

<v:template type='simple' enabled='--(case when self._fb_isset and self._sync=1 then 1 else 0 end)'>
<script type="text/javascript">
<![CDATA[
var totalSyncCount=<?Vself.syncdata_arr[3]?>;
var _syncContactsArr= <?vsp http(get_keyword('syncdata_jsarrstr',self._dhtml,'')); ?> ;
var win_mapping=false

<?vsp http(get_keyword('validation_obj',self._dhtml,'')); ?>

function fbInit()
{
 dock = new OAT.Dock('fbDock',2);

 var win_info=dockAdd('Action');

 win_mapping=dockAdd('Set default mapping',460);
 createMappingDock(win_mapping);

 win_mapping.state=0;
 win_mapping.actualizeState();

 OAT.Dom.unlink(win_mapping.close.firstChild);

 $(win_info.id+'_body').innerHTML='<?vsp http('<a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx',self._ods_login_params)||'">Back to ODS - Facebook</a> | '); ?>' +
                                  '<?vsp http('<a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=updateadvanced',self._ods_login_params)||'">Show all contacts to synchronize</a>'); ?> | ' +
                                   '<a href="javascript:void(0)" onclick="win_mapping.state=1;win_mapping.actualizeState();">Set default mapping</a>';
 var win_syncstatus=dockAdd('Synchronize status',OAT.Dom.getViewport()[0]*usableViewRatio-460);
 win_syncstatus.mappingDockId=win_mapping.id;
 createSyncstatusDock(win_syncstatus);

 win_validation=dockAdd('Set default validation',460);
 createValidationDock(win_validation);

 win_syncstatus.validationId=win_validation.id;
 OAT.Dom.unlink(win_validation.close.firstChild);
 win_validation.state=0;
 win_validation.actualizeState();


}

function createSyncstatusDock(dockWinObj)
{
  var _parent_div=$(dockWinObj.id+'_body')
  _parent_div.style.textAlign='center';
  var _syncBtn=OAT.Dom.create('input',{width:'120px',margin:'5px'});
  _syncBtn.type='button';
  _syncBtn.value='Synchronize All';
  _syncBtn.id=dockWinObj.id+'_syncallbtn';
  OAT.Event.attach(_syncBtn,"click",function(){UpdateAll(<?Vself.syncdata_arr[5]?>,dockWinObj);});

  var _progressBar=OAT.Dom.create('div',{height:'20px',width:'0px',padding:'0px',backgroundColor : "#0F0"});
  _progressBar.id=dockWinObj.id+'_progress';
  var _bar=OAT.Dom.create('div',{height:'20px',width:'200px',padding:'0px',border:'1px solid',textAlign:'left',margin:'0 auto'});
  _bar.id=dockWinObj.id+'_bar';

  OAT.Dom.append([_bar,_progressBar]);

  var _counterTxtDiv =OAT.Dom.create('div',{padding:'10px 0px'});
  _counterTxtDiv.id=dockWinObj.id+'_counterdiv';
  _counterTxtDiv.innerHTML='0 of '+totalSyncCount+' contacts synchronized';

  OAT.Dom.append([_parent_div, _syncBtn, _bar,_counterTxtDiv]);


}
function createMappingDock(dockWinObj)
{
  var _parent_div=$(dockWinObj.id+'_body')
  _parent_div.style.textAlign='center';
  _parent_div.style.width='100%';
  var _table=OAT.Dom.create("table");
  _table.style.width='100%';
  var _tbody = OAT.Dom.create("tbody");

  var _tr=OAT.Dom.create("tr");
  var _th1=OAT.Dom.create("td",{textAlign:'right',fontWeight:'bold',fontSize:'12px'});
  _th1.innerHTML='Facebook Contact Property';
  var _th2=OAT.Dom.create("td",{fontSize:'12px'});
  _th2.innerHTML='ODS Contact Property';

  OAT.Dom.append([_tbody,_tr],[_tr, _th1,_th2]);

  var _close=OAT.Dom.create("input",{width:'60px'});
  _close.type='button';
  _close.value="Set";
  OAT.Event.attach(_close,"click",function(){win_mapping.state=0;win_mapping.actualizeState();});



  OAT.Dom.append([_tbody, genAbFieldsCb('name','P_FULL_NAME'),
                          genAbFieldsCb('first_name','P_FIRST_NAME'),
                          genAbFieldsCb('last_name','P_LAST_NAME'),
                          genAbFieldsCb('sex','P_GENDER'),
                          genAbFieldsCb('birthday','P_BIRTHDAY'),
                          genAbFieldsCb('hometown_location/city','P_H_CITY'),
                          genAbFieldsCb('hometown_location/state','P_H_STATE'),
                          genAbFieldsCb('hometown_location/country','P_H_COUNTRY'),
                          genAbFieldsCb('hometown_location/zip','P_H_CODE'),
                          genAbFieldsCb('work_info/location/city','P_B_CITY'),
                          genAbFieldsCb('work_info/location/state','P_B_STATE'),
                          genAbFieldsCb('work_info/location/country','P_B_COUNTRY'),
                          genAbFieldsCb('work_info/company_name','P_B_ORGANIZATION'),
                          genAbFieldsCb('work_info/position','P_B_JOB'),
                          genAbFieldsCb('current_location/city','skip'),
                          genAbFieldsCb('current_location/state','skip'),
                          genAbFieldsCb('current_location/country','skip'),
                          genAbFieldsCb('current_location/zip','skip'),
                          genAbFieldsCb('timezone','skip')
                 ]);

  OAT.Dom.append([_table,_tbody]);

  OAT.Dom.append([_parent_div,_table,_close]);

}
function createValidationDock(dockWinObj)
{
  var _parent_div=$(dockWinObj.id+'_body')
  _parent_div.style.textAlign='center';
  _parent_div.style.width='100%';


 var _table=$('validationFieldsTbl');

var inputCtrls=_table.getElementsByTagName('input');
for (var i=0;i<inputCtrls.length;i++)
{
    if(inputCtrls[i].type=='checkbox')
    {
        if(typeof(validateObj[inputCtrls[i].value])!='undefined' && validateObj[inputCtrls[i].value]==1)
           inputCtrls[i].checked=true;
        else
           inputCtrls[i].checked=false;
    }

}

  var toggleSelect=OAT.Dom.create('div');
  var toggleSelectCB=OAT.Dom.create('input');
  toggleSelectCB.type='checkbox';
  OAT.Event.attach(toggleSelectCB,"click",function(){inverseSelected($('validationFieldsTbl'));});

  OAT.Dom.append([toggleSelect,toggleSelectCB,OAT.Dom.text(' Toggle select')]);


  var _close=OAT.Dom.create("input",{width:'60px'});
  _close.type='button';
  _close.value="Set";
  OAT.Event.attach(_close,"click",function(){win_validation.state=0;win_validation.actualizeState();});


  OAT.Dom.append([_parent_div,toggleSelect,_table,_close]);
  OAT.Dom.show(_table);


}

function UpdateAll(abID,dockObj)
{
  $(dockObj.id+'_progress').style.width=0+'px';
  ajaxSuccCallCount=0;
  var totalCount=<?Vself.syncdata_arr[3]?>;
  var _pbUnit=Math.floor(OAT.Dom.getWH($(dockObj.id+'_bar'))[0]/totalCount);


  var mappingStr='';
  mappingStr=getCustomMapping(dockObj.mappingDockId);
  var validationStr='';
  validationStr=getCustomValidation(dockObj.validationId);


  for(var i=0;i<totalCount;i++)
      ajaxUpdateAdvanced(abID,_syncContactsArr[i].ods_cid,_syncContactsArr[i].fb_id,dockObj,mappingStr,validationStr,totalCount,_pbUnit);

}


]]>
</script>
<div id="fbDock"></div>
</v:template>

<v:template type='simple' enabled='--(case when self._fb_isset and self._sync=2 then 1 else 0 end)'>

<script type="text/javascript">
<![CDATA[


var _syncContactsArr= <?vsp http(get_keyword('syncdata_jsarrstr',self._dhtml,'')); ?> ;

var mappingWin=false;

function fbInit()
{

 var colnum=Math.floor(OAT.Dom.getViewport()[0]*usableViewRatio/docColumnMinSize);
 dock = new OAT.Dock('fbDock',colnum);

 var win_info=dockAdd('Action');
 $(win_info.id+'_body').innerHTML='<?vsp http('<a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx',self._ods_login_params)||'">Back to ODS - Facebook</a> <br/>'); ?>'+
                                  '<?vsp http('<a href="'||self.odsbar_ods_gpath ||wa_expand_url('fb_front.vspx?import=update',self._ods_login_params)||'">Back to Synchronize</a> <br/><br/>'); ?>'+
                                  '<a href="javascript:void(0)" onclick="OAT.Dom.show($(\'mappingDiv\'));">Set Default Mapping</a>';

 var mappingWin=new OAT.Window({resize:0,min:0,max:0,close:1,move:1,x:130,y:70,width:460,height:575,title:'Set Default Mapping',imagePath:'./images/oat/'}, OAT.WindowData.TYPE_AUTO); //imagePath:'/samples/wa/oat/images/'

 mappingWin.div.style.zIndex = 1001;
 mappingWin.div.id = "mappingDiv";
 mappingWin.onclose=function(){OAT.Dom.hide(this.div);};
 mappingWin.content.style.zIndex = 1002;
 mappingWin.content.style.textAlign='center';
 mappingWin.content.id= "mappingDivContent";


  var _table=OAT.Dom.create("table");
  _table.style.width='100%';
   var _tbody = OAT.Dom.create("tbody");

  var _tr=OAT.Dom.create("tr");
  var _th1=OAT.Dom.create("td",{textAlign:'right',fontWeight:'bold',fontSize:'12px'});
  _th1.innerHTML='Facebook Contact Property';
  var _th2=OAT.Dom.create("td",{fontSize:'12px'});
  _th2.innerHTML='ODS Contact Property';

  OAT.Dom.append([_tbody,_tr],[_tr, _th1,_th2]);
  OAT.Dom.append([_tbody, genAbFieldsCb('name','P_FULL_NAME'),
                          genAbFieldsCb('first_name','P_FIRST_NAME'),
                          genAbFieldsCb('last_name','P_LAST_NAME'),
                          genAbFieldsCb('sex','P_GENDER'),
                          genAbFieldsCb('birthday','P_BIRTHDAY'),
                          genAbFieldsCb('hometown_location/city','P_H_CITY'),
                          genAbFieldsCb('hometown_location/state','P_H_STATE'),
                          genAbFieldsCb('hometown_location/country','P_H_COUNTRY'),
                          genAbFieldsCb('hometown_location/zip','P_H_CODE'),
                          genAbFieldsCb('work_info/location/city','P_B_CITY'),
                          genAbFieldsCb('work_info/location/state','P_B_STATE'),
                          genAbFieldsCb('work_info/location/country','P_B_COUNTRY'),
                          genAbFieldsCb('work_info/company_name','P_B_ORGANIZATION'),
                          genAbFieldsCb('work_info/position','P_B_JOB'),
                          genAbFieldsCb('current_location/city','skip'),
                          genAbFieldsCb('current_location/state','skip'),
                          genAbFieldsCb('current_location/country','skip'),
                          genAbFieldsCb('current_location/zip','skip'),
                          genAbFieldsCb('timezone','skip')
                 ]);

  OAT.Dom.append([_table,_tbody]);

  var _close=OAT.Dom.create("input",{width:'60px'});
  _close.type='button';
  _close.value="Set";
  OAT.Event.attach(_close,"click",function(){OAT.Dom.hide($('mappingDiv'));});

  OAT.Dom.append([mappingWin.content,_table,_close]);

 $('fbDock').appendChild(mappingWin.div);

 OAT.Dom.hide(mappingWin.div);

 var manualMappingWin=new OAT.Window({resize:0,min:0,max:0,close:1,move:1,x:130,y:70,width:460,height:575,title:'Set Manual Mapping',imagePath:'./images/oat/'}, OAT.WindowData.TYPE_AUTO); //imagePath:'./images/oat/'

 manualMappingWin.div.style.zIndex = 1003;
 manualMappingWin.div.id = "manualMappingDiv";
 manualMappingWin.onclose=function(){OAT.Dom.hide(this.div);};
 manualMappingWin.content.style.zIndex = 1004;
 manualMappingWin.content.style.textAlign='center';
 manualMappingWin.content.id= "manualMappingDivContent";

  var _table=OAT.Dom.create("table");
  _table.style.width='100%';
  var _tbody = OAT.Dom.create("tbody");


  var _tr=OAT.Dom.create("tr");
  var _th1=OAT.Dom.create("td",{textAlign:'right',fontWeight:'bold',fontSize:'12px'});
  _th1.innerHTML='Facebook Contact Property';
  var _th2=OAT.Dom.create("td",{fontSize:'12px'});
  _th2.innerHTML='ODS Contact Property';

  OAT.Dom.append([_tbody,_tr],[_tr, _th1,_th2]);

  OAT.Dom.append([_tbody, genAbFieldsCb('name','P_FULL_NAME'),
                          genAbFieldsCb('first_name','P_FIRST_NAME'),
                          genAbFieldsCb('last_name','P_LAST_NAME'),
                          genAbFieldsCb('sex','P_GENDER'),
                          genAbFieldsCb('birthday','P_BIRTHDAY'),
                          genAbFieldsCb('hometown_location/city','P_H_CITY'),
                          genAbFieldsCb('hometown_location/state','P_H_STATE'),
                          genAbFieldsCb('hometown_location/country','P_H_COUNTRY'),
                          genAbFieldsCb('hometown_location/zip','P_H_CODE'),
                          genAbFieldsCb('work_info/location/city','P_B_CITY'),
                          genAbFieldsCb('work_info/location/state','P_B_STATE'),
                          genAbFieldsCb('work_info/location/country','P_B_COUNTRY'),
                          genAbFieldsCb('work_info/company_name','P_B_ORGANIZATION'),
                          genAbFieldsCb('work_info/position','P_B_JOB'),
                          genAbFieldsCb('current_location/city','skip'),
                          genAbFieldsCb('current_location/state','skip'),
                          genAbFieldsCb('current_location/country','skip'),
                          genAbFieldsCb('current_location/zip','skip'),
                          genAbFieldsCb('timezone','skip')
                 ]);

  OAT.Dom.append([_table,_tbody]);

  var _close=OAT.Dom.create("input",{width:'60px'});
  _close.type='button';
  _close.value="Ok";
  _close.c_ods_cid=0;
  _close.id='manualMappingOK';
  OAT.Event.attach(_close,"click",function(e){
    OAT.Dom.hide($('manualMappingDiv'));
                                           if(OAT.Browser.isIE)
                                              var _elm=e.srcElement;
                                           else
                                              var _elm=this;
                                           ajaxUpdate(_elm.odsab_instid,parseInt(_elm.c_ods_cid),_elm.fb_id,_elm.dock_obj,getCustomMapping('manualMappingDivContent'));
                                         });

  OAT.Dom.append([manualMappingWin.content ,_table,_close]);
 $('fbDock').appendChild(manualMappingWin.div);
 OAT.Dom.hide(manualMappingWin.div);

 for (var i=0;i<_syncContactsArr.length;i++)
   createImportObjDock(_syncContactsArr[i]);
 }

function createImportObjDock(_syncData)
{
   var _dock_obj=dockAdd('Facebook contact <a href="'+_syncData.fb_href+'" target="_blank">'+_syncData._name+'</a>');

   var _parent_div=$(_dock_obj.id+'_body')

  _parent_div.appendChild(OAT.Dom.text('ODS contacts:'));

  _parent_div.appendChild(OAT.Dom.create("br"));

  var d_ods_cid=0;
  for(var ii=0;ii < _syncData.ods_contacts.length;ii++)
  {
          var _radio = OAT.Dom.create("input", {type: "radio", id: _dock_obj.id+'_syncgrp'});
   _radio.value=_syncData.ods_contacts[ii].ods_cid;
          OAT.Dom.append([_parent_div,_radio]);
    OAT.Event.attach(_radio,"click",function(e){
      if (OAT.Browser.isIE)
                                                var _objval=e.srcElement.value;
                                             else
                                                var _objval=this.value;

                                             $(_dock_obj.id+'_body').c_ods_cid=_objval;
                                            });

   if(ii==0)
   {
    _radio.checked=true;
    d_ods_cid=_syncData.ods_contacts[ii].ods_cid;
   }

   $(_dock_obj.id+'_body').c_ods_cid=d_ods_cid;


   var _ods_link=OAT.Dom.create('a');
   _ods_link.href=_syncData.ods_contacts[ii].ods_href;
   _ods_link.target='_blank';
   _ods_link.appendChild(OAT.Dom.text(_syncData.ods_contacts[ii].ods_name));

   _parent_div.appendChild(_ods_link);

   _parent_div.appendChild(OAT.Dom.create("br"));

  }




  var _table=OAT.Dom.create("table",{textAlign:'left',padding:'5px',margin: '5px 0px'});
  var _tbody=OAT.Dom.create("tbody");
  var _tr=OAT.Dom.create('tr');
  var _td1=OAT.Dom.create('td',{textAlign:'right'});
  _td1.innerHTML='Mapping ';
  var _td2=OAT.Dom.create('td');

  var _cbutton = new OAT.ComboButton();
  _cbutton.addOption(""," Default ",function(){
                                               ajaxUpdate(_syncData.odsab_instid,parseInt($(_dock_obj.id+'_body').c_ods_cid),_syncData.fb_id,_dock_obj,getCustomMapping('mappingDivContent'));
                                              })
      	_cbutton.addOption(""," Manual ",function(){
      	  $('manualMappingOK').odsab_instid=_syncData.odsab_instid;
                                               $('manualMappingOK').c_ods_cid=parseInt($(_dock_obj.id+'_body').c_ods_cid);
                                               $('manualMappingOK').fb_id=_syncData.fb_id;
                                               $('manualMappingOK').dock_obj=_dock_obj;
                                               OAT.Dom.show($('manualMappingDiv'));
                                             })
  _td2.appendChild(_cbutton.div);

  OAT.Dom.append([_table,_tbody],[_tbody,_tr],[_tr,_td1,_td2])
  OAT.Dom.append([_parent_div,_table,OAT.Dom.create('br')]);
}
]]>
</script>
<div id="fbDock"></div>

</v:template>

<v:template type='simple' enabled='--(1-self._fb_isset)'>
<div style="padding:10px;">ODS is not set up to use Facebook. Please contact ODS administrator.</div>
</v:template>

<v:template type='simple' enabled='--self._fb_usernotcorrespond'>
 <?vsp
   http_get ('http://www.facebook.com/logout.php',null, 'POST', 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)', 'confirm=1'); --,'127.0.0.1:8888'
 ?>

 <div style="padding:10px;">The current ODS Dataspace already has an ODS user, which is connected with the Facebook user <?Vself._fb_u_name?>.<br/> Please <a href="<?Vself._fb.get_login_url(self._fb.current_url(), self._fb.in_frame(),1)?>">login </a> as different Facebook user, or register a new one in order to connect it with the ODS user <?Vself._ods_u_name?>.</div>

</v:template>

<table cellspacing="0" style="display:none;" id="validationFieldsTbl">
  <tbody>
  <tr><td width="1%"><input type="checkbox" value="P_NAME"/></td>
    <td>       Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_TITLE"/></td>
    <td>      Title    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_FIRST_NAME"/></td>
    <td>      First Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_MIDDLE_NAME"/></td>
    <td>      Middle Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_LAST_NAME"/></td>
    <td>      Last Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_FULL_NAME"/></td>
    <td>      Full Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_GENDER"/></td>
    <td>      Gender    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_BIRTHDAY"/></td>
    <td>      Birthday    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_MAIL"/></td>
    <td>      Contact - Mail    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_WEB"/></td>
    <td>      Contact - Web address    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_ICQ"/></td>
    <td>      Contact - Icq    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_SKYPE"/></td>
    <td>      Contact - Skype ID    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_AIM"/></td>
    <td>      Contact - AIM Name    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_YAHOO"/></td>
    <td>      Contact - Yahoo! ID    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_MSN"/></td>
    <td>      Contact - MSN Messenger    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_COUNTRY"/></td>
    <td>      Home - Country    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_CITY"/></td>
    <td>      Home - City    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_STATE"/></td>
    <td>      Home - State/Province    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_CODE"/></td>
    <td>      Home - Zip/Postal Code    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_ADDRESS1"/></td>
    <td>      Home - Address1    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_ADDRESS2"/></td>
    <td>      Home - Address2    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_TZONE"/></td>
    <td>      Home - Time Zone    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_LAT"/></td>
    <td>      Home - Latitude    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_LNG"/></td>
    <td>      Home - Longitude    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_PHONE"/></td>
    <td>      Home - Phone    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_MOBILE"/></td>
    <td>      Home - Mobile    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_FAX"/></td>
    <td>      Home - Fax    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_MAIL"/></td>
    <td>      Home - Mail    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_H_WEB"/></td>
    <td>      Home - Web address    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_COUNTRY"/></td>
    <td>      Business - Country    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_CITY"/></td>
    <td>      Business - City    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_STATE"/></td>
    <td>      Business - State/Province    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_CODE"/></td>
    <td>      Business - Zip/Postal Code    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_ADDRESS1"/></td>
    <td>      Business - Address1    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_ADDRESS2"/></td>
    <td>      Business - Address2    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_TZONE"/></td>
    <td>      Business - Time Zone    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_LAT"/></td>
    <td>      Business - Latitude    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_LNG"/></td>
    <td>      Business - Longitude    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_PHONE"/></td>
    <td>      Business - Phone    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_MOBILE"/></td>
    <td>      Business - Mobile    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_FAX"/></td>
    <td>      Business - Fax    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_INDUSTRY"/></td>
    <td>      Business - Industry    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_ORGANIZATION"/></td>
    <td>      Business - Organization    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_DEPARTMENT"/></td>
    <td>      Business - Department    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_JOB"/></td>
    <td>      Business - Job Title    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_MAIL"/></td>
    <td>      Business - Mail    </td>
  </tr>
  <tr><td width="1%"><input type="checkbox" value="P_B_WEB"/></td>
    <td>      Business - Web address    </td>
  </tr>
  </tbody>
</table>

      </vm:body>
    </vm:pagewrapper>
  </vm:page>
</v:page>

