/* -----------------24/01/2011 3:09PM----------------
ROBBIE
 --------------------------------------------------*/

jQuery().ready( function() {
   if ( soap_LocalTimer > 0 && soap_LocalCall.length > 0) {
     setTimeout('LocalPing()', soap_LocalTimer * 60 * 10000);
   }
   setTimeout('RemotePing()', GetTimerLeftCookie(soap_PingTimerTag + '_remoteping'));
});  // jQuery().ready()


function LocalPing() {
 // Pings the local server for details with which to update the header
   if ( soap_LocalTimer > 0 && soap_LocalCall.length > 0) {
    jQuery.ajax({
      url: soap_LocalURL + soap_LocalCall,
      data: 'c=' + (Math.random() * 100000),
      dataType: 'json',
      cache: false,
      success: function(data) {
        if ( data.loggedin != soap_LoggedIn ) {
          insertParam('lcheck', '1')
          return;
        }
        // Update header if required
  //      jQuery("#TimeNowLocal").html('Time Local Checked: ' + data.time);
        setTimeout('LocalPing()', soap_LocalTimer * 60 * 10000);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        if ( typeof(console) != 'undefined' ) {
           console.log('Failed to communicate locally ' + textStatus);
        }
//        alert("ERROR: " + textStatus + "\n" + errorThrown);
        setTimeout('LocalPing()', soap_LocalTimer * 60 * 10000);
      }
    });
  //  SetTimerCookie(soap_PingTimerTag + 'localping');
  }
}  // LocalPing()

var soap_AccFader = false;

function ShowAccolades() {
  soap_ShowMessages = 1;
}
function StopAccolades() {
  soap_ShowMessages = 0;
}


function RemotePing(lRepeat) {
//  return;
 // Pings the remote server for details with which to update the header
  jQuery.ajax({
    url: soap_RemoteURL + '?action=ping2&from='+soap_PingTimerTag+'&jsoncallback=?',
    data: 'c=' + (Math.random() * 100000),
    dataType: 'jsonp',
    cache: false,
    success: function(data, status, request) {
      try {
        var cookies = request.getResponseHeader("set-cookie");
        if (cookies) {
          cookie_arr = cookies.split("\n");
          for(i=0; i<cookie_arr.length; i++) {
//            alert("SET COOKIE\n" + document.cookie + "=" + cookie_arr[i]);
            document.cookie = cookie_arr[i];
          }
        }
      } catch(err) {
      }


//alert(data.loggedin + " " +  soap_LoggedIn);
      if ( data.loggedin != soap_LoggedIn ) {
        insertParam('lcheck', '1')
        return;
      }

      // Process accolades
      if ( data.accolade && data.accolade.length > 0 && soap_ShowMessages==1) {

        // Create the div if needed
        if ( jQuery('#accolade').length == 0 ) {
            if ( soap_AccFader ) {
              clearTimeout(soap_AccFader);
              soap_AccFader =false;
            }

//            $(data.accolade).hide().prependTo('body').absCenter().fadeIn('slow');
            if ( $(data.accolade).hasClass('abscenter') ) {
              $(data.accolade).prependTo('body').absCenter();
            } else {
              $(data.accolade).prependTo('body');
              setTimeout(function() {
                jQuery('#accolade').fadeOut('slow', function() {$(this).hide().empty().remove(); } );
                jQuery.getJSON(soap_RemoteURL, 'action=AccoladeShown&c='+(Math.random() * 100000)+'&accolade_del=' + data.accolade_del + '&jsoncallback=?', function() { setTimeout(function(){RemotePing(false)}, 500); }  );
                }, 500000);
            }
            TagExternalLinks();


//            $('body').prepend(data.accolade);
            // Hide (just in case), add the HTML and show
//            jQuery('#accolade').absCenter();


            jQuery('#accolade a.closepop').click( function() {
                if (soap_AccFader) {
                  clearTimeout(soap_AccFader);
                  soap_AccFader = false;
                }
                jQuery('#accolade').fadeOut('fast').hide().empty().remove();
                jQuery.getJSON(soap_RemoteURL, 'action=AccoladeShown&c='+(Math.random() * 100000)+'&accolade_del=' + data.accolade_del + '&jsoncallback=?', function() { setTimeout(function(){RemotePing(false)}, 500); }  );
                return false;
            });
            jQuery('#accolade a.TweetAccolade').click( function() {
                 MyWin = window.open($(this).attr('href'), 'ResistanceTwitter', "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1");
                 if (MyWin) {
                   MyWin.focus();
                 }
                 SoapTweeted();
                 return false;
            });
            jQuery('#accolade a.PostAccolade').click( function() {
//                  alert(data.accolade_name + ' ' + data.accolade_points + ' ' + data.accolade_ref)
                  FBPostAccolade(data.accolade_name, data.accolade_points, data.accolade_ref)
                  return false;
            });
        }
      } else if ( data.unlock && data.unlock.length > 0 && soap_ShowMessages==1) {

        // Create the div if needed
        if ( jQuery('#accolade').length == 0 ) {
            if ( soap_AccFader ) {
              clearTimeout(soap_AccFader);
              soap_AccFader =false;
            }

//            $(data.accolade).hide().prependTo('body').absCenter().fadeIn('slow');
            if ( $(data.unlock).hasClass('abscenter') ) {
              $(data.unlock).prependTo('body').absCenter();
            } else {
              $(data.unlock).prependTo('body');
              setTimeout(function() {
                jQuery('#accolade').fadeOut('slow', function() {$(this).hide().empty().remove(); } );
                jQuery.getJSON(soap_RemoteURL, 'action=UnlockShown&c='+(Math.random() * 100000)+'&unlock_del=' + data.unlock_del + '&jsoncallback=?', function() { setTimeout(function(){RemotePing(false)}, 500); }  );
                }, 500000);
            }
            TagExternalLinks();

//            $('body').prepend(data.accolade);
            // Hide (just in case), add the HTML and show
//            jQuery('#accolade').absCenter();

            jQuery('#accolade a.closepop').click( function() {
                if (soap_AccFader) {
                  clearTimeout(soap_AccFader);
                  soap_AccFader = false;
                }
                jQuery('#accolade').fadeOut('fast').hide().empty().remove();
                jQuery.getJSON(soap_RemoteURL, 'action=UnlockShown&c='+(Math.random() * 100000)+'&unlock_del=' + data.unlock_del + '&jsoncallback=?', function() { setTimeout(function(){RemotePing(false)}, 500); }  );
                return false;
            });
        }
      } else if ( data.level && data.level.length > 0) {
        if ( soap_PingTimerTag == 'global' ) {
            // Do nothing, handled by Flash.
        } else if ( jQuery('#accolade').length == 0 ) {
            if (soap_AccFader) {
              clearTimeout(soap_AccFader);
              soap_AccFader = false;
            }
            $(data.level).hide().prependTo('body').absCenter().fadeIn('slow');
            setTimeout(function() {
                jQuery('#accolade').fadeOut('slow', function() {$(this).hide().empty().remove(); } );
              jQuery.getJSON(soap_RemoteURL, 'action=LevelShown&c='+(Math.random() * 100000)+'&jsoncallback=?', function() { setTimeout(function(){RemotePing(false)}, 500); }  );
              }, 500000);

            jQuery('#accolade a.closepop').click( function() {
                if (soap_AccFader) {
                  clearTimeout(soap_AccFader);
                  soap_AccFader = false;
                }
                jQuery('#accolade').fadeOut('fast').hide().empty().remove();
                jQuery.getJSON(soap_RemoteURL + '?action=LevelShown&c='+(Math.random() * 100000)+'&jsoncallback=?' );
                return false;
            });
            jQuery('#accolade a.TweetLevel').click( function() {
                 MyWin = window.open($(this).attr('href'), 'ResistanceTwitter', "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1");
                 if (MyWin) {
                   MyWin.focus();
                 }
                 SoapTweeted();
                 return false;
            });
            jQuery('#accolade a.PostLevel').click( function() {
                  FBPostLevel(data.level_id)
                  return false;
            });
        }
      } else {
        // Hide any accolades that may be shown (just in case cleared in another window)
        jQuery('#accolade').fadeOut('fast').hide().empty().remove();
      }
      SetTimerCookie(soap_PingTimerTag + 'remoteping');
      if (lRepeat == null){
       lRepeat = 1;
      }
      if ( lRepeat ) {
        setTimeout('RemotePing()', soap_PingTimer);
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      if ( typeof(console) != 'undefined' ) {
         console.log('Failed to communicate with server ' + textStatus);
      }
//      alert("ERROR: " + textStatus + "\n" + errorThrown);
      SetTimerCookie(soap_PingTimerTag + 'remoteping');
      if (lRepeat == null){
       lRepeat = 1;
      }
      if ( lRepeat ) {
        setTimeout('RemotePing()', soap_PingTimer);
      }
    }
  });
}  // RemotePing()

/* Borrowed from the web */
function insertParam(key, value) {
    key = escape(key);
    value = escape(value);
    var ss = document.location.search.substr(1)
    if (ss.length==0) {
      document.location.search = key + "=" + value;
    } else {
      var kvp = ss.split('&');
      var i = kvp.length;
      var x;
      while (i--) {
        x = kvp[i].split('=');
        if (x[0] == key) {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
      }
      if (i < 0) {
        kvp[kvp.length] = [key, value].join('=');
      }
      document.location.search = kvp.join('&');
    }
}


function FBPostAccolade(accolade_name, accolade_points, accolade_ref) {
  var caption = LangTXT['fb_acc_title'];
  caption = caption.replace(/{points}/i, accolade_points);
  caption = caption.replace(/{name}/i, accolade_name);
  var description = LangTXT['fb_acc_desc'];
//  '{*actor*} has just scored the ' + accolade_name + ' accolade for ' + accolade_points + ' points!';

  if ( accolade_ref ) {
    var picture = soap_RemoteURL + 'images/accolades/acc_' + accolade_ref + '.png';
  } else {
    var picture = soap_RemoteURL + 'images/accolades/default.jpg';
  }
  FBPostItem(caption, description, picture);
}

function FBPostLevel(level_id) {
  var caption = '{*actor*} has reached a new level ' + level_id;
  var description = "Don't get left behind, Join the War today!";
  var picture = soap_RemoteURL + 'images/R3_FB_130x130.jpg';
//  if ( level_id ) {
//    var picture = soap_RemoteURL + 'images/levels/' + level_id + '.png';
//  } else {
//    var picture = soap_RemoteURL + 'images/levels/default.jpg';
//    var picture = soap_RemoteURL + 'images/levels/default.jpg';
//  }
  FBPostItem(caption, description, picture);
}


function FBPostItem(caption, description, picture) {
  if ( soap_PingTimerTag == 'global' ) {
    var link = soap_LocalURL;
    var name = 'Global Resistance';
  } else {
    var link = soap_RemoteURL;
    var name = 'Resistance 3';
  }

  FB.ui(
    {
      method: 'stream.publish',
      display: 'popup',
      message: "Resistance 3",
      attachment: {
        name: name,
        caption: caption,
        description: description,
        href: link ,
        media: [{
          type: 'image',
          src: picture,
          href: link
        }]
      },
      action_links: [
        { text: 'Resistance 3', href: link }
      ]
    },
    function(response) {
      if (response && response.post_id) {
        jQuery.ajax({
          url: soap_RemoteURL + '?action=FacebookPosted',
          data: 'c=' + (Math.random() * 100000),
          dataType: 'XML',
          cache: false,
          success: function(data, status, request) {}
          });
        }
    }
  );
}

function Soap_Liked() {
  jQuery.ajax({
    url: soap_RemoteURL + '?action=FacebookLiked',
    data: 'c=' + (Math.random() * 100000),
    dataType: 'XML',
    cache: false,
    success: function(data, status, request) {}
    });
}


// This sets a cookie with teh current timestamp, to last 1 day
function SetTimerCookie(name) {
  var date = new Date();
  var timeNow = date.getTime();
  date.setTime(date.getTime()+(60*60*1000));
  var expires = "; expires="+date.toGMTString();
  document.cookie = name+"="+timeNow+expires+"; path=/";
}

function GetTimerLeftCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  var retval = 100;
  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) {
      // We have the index, now work out the difference.
      StartTime = parseInt(c.substring(nameEQ.length,c.length));
      var date = new Date();
      var timeNow = date.getTime();
      var TimePassed = timeNow - StartTime;
      retval = Math.max(100, soap_PingTimer - TimePassed);
    }
  }
  return retval;
}

function SoapTweeted() {
   jQuery.ajax({
     url: soap_RemoteURL + '?action=Tweeted',
     data: 'c=' + (Math.random() * 100000),
     dataType: 'HTML',
     cache: false,
     success: function(data, status, request) { }
   });
}  // SoapTweeted() {

function Soap_FacebookLogin() {
  if ( typeof(FB) != 'undefined' ) {
    FB.login(Soap_FBReturnStatus, {scope:'email,publish_stream,offline_access'});
  }
}  // Soap_FacebookLogin
function Soap_FBReturnStatus() {
  if ( typeof(FB) != 'undefined' ) {
    FB.getLoginStatus(function(response) {
       if (response.authResponse) {
         // Get the "stem" of the current URL
         var BaseURL = document.location.protocol + '//' + document.location.hostname + location.pathname;
         // Create the "final return to" target
         var CurrURL = window.location.href;
//         var EncCurrURL = escape(CurrURL).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
         var EncCurrURL = encode64(CurrURL);
         // Redirect to login screen
         document.location.href = soap_RemoteURL + '?action=FaceBook&FBCheck=1&PostLogin=' + EncCurrURL;
//alert(soap_RemoteURL + '?action=FaceBook&PostLogin=' + EncCurrURL);
         return false;
       }
     });
   }
}  // ReturnStatus

function Soap_FacebookLogout() {
  try {
    FB.getLoginStatus(function(response) {
       if (response.authResponse) {
         FB.logout(Soap_LogMeOut);
       } else {
         Soap_LogMeOut();
       }
    });
  } catch(err) {
    Soap_LogMeOut();
  }
}

function Soap_LogMeOut() {
  if ( soap_LoggedIn > 0 ) {
    document.location.href = soap_RemoteURL + '?action=quicklogout';
  } else {
    document.location.href = soap_LocalURL + '?action=quicklogout';
  }
}

function Soap_PSNLogin() {
  // Get the "stem" of the current URL
//  if (confirm('IMPORTANT! If you have an account already, to connect your existing account to PSN you must first log in with your existing account. Go to "Edit Profile" to link to PSN. If you are not logged in you will create a new account, and this is NOT reversable.')) {
    return Soap_PSNLoginSub();
//  }
}

function Soap_PSNLoginSub() {
    var BaseURL = document.location.protocol + '//' + document.location.hostname + location.pathname;

    // Create the "final return to" target
    var CurrURL = window.location.href;
  //  var EncCurrURL = escape(CurrURL).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
    var EncCurrURL = encode64(CurrURL);

    // Redirect to login screen
    document.location.href = soap_RemoteURL + '?action=PSN&PostLogin=' + EncCurrURL;
    return false;
}


jQuery().ready( function() {
  jQuery('a.fblogin').click( function() {
    Soap_FacebookLogin();
    return false;
  });
  jQuery('a.fblogout').click( function() {
    if ( typeof(FB) != 'undefined' ) {
      Soap_FacebookLogout();
    } else {
      Soap_LogMeOut();
    }
    return false;
  });
  jQuery('a.PSNLogin').click( function() {
    Soap_PSNLogin();
    return false;
  });
  jQuery('a.PSNLoginSub').click( function() {
    Soap_PSNLoginSub();
    return false;
  });
  TagExternalLinks();
});


  // Add actions for the links that are external

function TagExternalLinks() {
    jQuery("a.external").each( function() {
      var href= jQuery(this).attr("href");
      var rel = jQuery(this).attr("rel");
      if (rel.substring(0,8) == 'external') {
        var aSize = rel.split(';');
        jQuery(this).click( function() {
          var onclick = jQuery(this).attr("onclick");
          if ( onclick == null ) {
            onclick = '';
          }
          if (aSize[1]) {
  /*          _gaq.push(['_trackEvent', aSize[1], 'clicked']);  */
            _gaq.push(['_trackPageview', aSize[1]]);
          }
          if (onclick.length > 0) {
            eval(onclick);
          } else if (aSize[2] == 'small') {
            window.open(href,'','width=600,height=800,resizable=yes,scrollbars=yes');
            return false;
          } else {
            window.open(href);
            return false;
          }
        });
      }
    });
}

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3 = "";
   var enc1, enc2, enc3, enc4 = "";
   var i = 0;

   var keyStr = "ABCDEFGHIJKLMNOP" +
             "QRSTUVWXYZabcdef" +
             "ghijklmnopqrstuv" +
             "wxyz0123456789+/" +
             "=";


   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output +
         keyStr.charAt(enc1) +
         keyStr.charAt(enc2) +
         keyStr.charAt(enc3) +
         keyStr.charAt(enc4);
      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";
   } while (i < input.length);

   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3 = "";
   var enc1, enc2, enc3, enc4 = "";
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   var base64test = /[^A-Za-z0-9\+\/\=]/g;
   if (base64test.exec(input)) {
      alert("There were invalid base64 characters in the input text.\n" +
            "Valid base64 characters are A-Z, a-z, 0-9, ?+?, ?/?, and ?=?\n" +
            "Expect errors in decoding.");
   }
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }

      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";

   } while (i < input.length);

   return output;
}


