bebo.ui.platform = {};
bebo.lightspeed = {};
bebo.lightspeed.Request = {};

bebo.ui.platform.showAll = function(){
  for(var i=0; i < arguments.length; i++){
     show(arguments[i]);
  }
  return false;
};
var showAll = bebo.ui.platform.showAll;

bebo.ui.platform.hideAll = function(){
    for(var i=0; i < arguments.length; i++){
       hide(arguments[i]);
    }
    return false;
};
var hideAll = bebo.ui.platform.hideAll;

bebo.ui.platform.toggleAll = function() {
  for(var i=0; i < arguments.length; i++){
       toggle(arguments[i]);
    }
    return false;
};
var toggleAll = bebo.ui.platform.toggleAll;

bebo.ui.platform.toggleSub = function(submenu) {
   toggleSub2(submenu,'+','-');
};
var toggleSub = bebo.ui.platform.toggleSub; 

bebo.ui.platform.toggleSub2 = function(submenu,show,hide) {
   var subEl = $(submenu);
   var visible = !(subEl.getStyle('display') == 'none'); 
   subEl.setStyle('display', visible?'none':'block');
   $('toggle'+ submenu).set('html', visible?hide:show);
};
var toggleSub2 = bebo.ui.platform.toggleSub2;

bebo.ui.platform.disableAll = function(){
  $$(arguments).each(function(e){e.disabled = true;});
};
var disableAll = bebo.ui.platform.disableAll;

bebo.ui.platform.enableAll = function(){
  $$(arguments).each(function(e){e.disabled = false;});
};
var enableAll = bebo.ui.platform.enableAll;

bebo.ui.platform.toggleEnabledAll = function() {
  $$(arguments).each(function(e){e.disabled = !e.disabled;});
};

function toggleEnabledAll(){
	for(var i=0; i < arguments.length; i++){
		var arg = $(arguments[i]);
		arg.disabled = !arg.disabled;
	}
}
/* lightspeed helpers */

/*this is a better way:
 * new bebo.lightspeed.Request.Partial({
 *      'controller': 'mycontroller',
 *      'action': 'get_html', 
 *      'onComplete': function(){alert('done');})
 * }).send();"
 */
bebo.lightspeed.Request.Partial = new Class({
   Extends: Request.HTML,
   initialize: function(options) {
      options.url = "/c/" + options.controller + "/" + options.action;
      this.parent(options);
   }
});

bebo.lightspeed.linkRemote = function(controller, action, replaceId) {
   tmp = new Request.HTML({
      'url':"/c/" + controller + "/" + action,
      method: 'get',
      update: $(replaceId)
   }).send();
};
var linkRemote = bebo.lightspeed.linkRemote;

//deprecated: use bebo.lightspeed.Request.Partial'
bebo.lightspeed.linkRemoteWithCallback = function(controller, action, callback) {
   tmp = new Request.HTML("/c/" + controller + "/" + action, {method: 'get',onComplete:callback}).send();
};
var linkRemoteWithCallback = bebo.lightspeed.linkRemoteWithCallback;

bebo.lightspeed.submitRemote = function(form,options){
    if ( MooTools.version == "1.11") {
        $(form).send(options);
    } else {
        options.url = form.action;
        var req = new Request.HTML(options).post($(form));
    }
};
var submitRemote = bebo.lightspeed.submitRemote;

/* end lightspeed helpers */

function autoCompleteSelected(element,tokens){
    var name = element.id.substring("selectorfor".length + 1);
    var input = document.getElementById(name);
    input.value = eval("name_to_ids_" + input.id + "['" + element.value + "']"); 
}

function prefillWithDefault(id,defaultValue){
    var elem = $(id);
    elem.addEvent('focus',function(){if(this.value == defaultValue){this.value = '';}});
    elem.addEvent('blur',function(){if(this.value == ''){this.value = defaultValue;}});
}

function multiCompleteSelect(element,tokens){
    var parent = $(element.parentNode); // apply moo prototypes
    var inputName = element.id.substring("selectorfor".length + 1);
    var input = $(element);
    
    // when we add one of these guys, 
    if (!$(inputName + input.value)){
        var span = new Element("span",{'class':'added-username','id' : inputName + input.value});
        var hidden = new Element("input", {
           'type': 'hidden',
           'value': eval("name_to_ids_" + inputName)[input.value],
           'name' : 'ids[]'
        }); 
        var anchor = new Element('a',{
           'events' : {
              // this happens when someone clicks on the remove links
              'click': function() {
                 var toKill = $(this.parentNode);
                 var fx = toKill.get('tween', {property: 'opacity', duration:300, transition: Fx.Transitions.Quart.easeOut});
                 fx.addEvent('complete', function() {toKill.destroy();});
                 fx.start(1,0);
              }
           },
           'href':'javascript:void(0);',
           'class':'remove'
        }).adopt(new Element('img', { 'border':'0','src':'/img/Remove.png'}));
        
        span.set('html', element.value);
        span.adopt(hidden);
        span.adopt(anchor);
        span.inject(input, 'before');
        input.value = '';
    }
}

function initAjaxAutocomplete(id,tokens,onSelectCallback){
    var selector = $$('#' + id);
    if ( selector != null){
        selector.addEvent('focus',function() {
            var selectorName = id.substring("selectorfor-".length);
            var namesToIds = eval('name_to_ids_' + selectorName);
            
            if (namesToIds == null){
               var throb = function(){
                  $(selectorName + "-throbber").setStyle('display','inline');
               };
               var complete = function(json) {
                  eval('name_to_ids_' + selectorName + "= json.nameToIds");
                  initAutocomplete(id,json.list, onSelectCallback);
                  $(selectorName + "-throbber").setStyle('display','none');
               };
               tmp = new Request.JSON({
                     url: '/ajax/friend-data',
                     method: 'get',
                     onRequest: throb,
                     onSuccess: complete
                  }).send();
            }
        });
    }
}

function initAutocomplete(id,tokens,onSelectCallback){
    onSelectCallback = onSelectCallback|| autoCompleteSelected;
    
    var el = $$('#' + id);
    
    var completer = new Autocompleter.Local(el[0], tokens, {
        'delay': 100,
        'maxChoices':500,
        'filterTokens': function() {
            var regex = new RegExp('^' + this.queryValue.escapeRegExp(), 'i');
            return this.tokens.filter(function(token){
                return (regex.test(token[0]) || regex.test(token[1]));
            });
        },
        'injectChoice': function(choice) {
            var name = (choice[0].length > 20)? choice[0].substring(0,10) + "..." : choice[0];
            var un  = null;
            if ( choice.length > 1){
                un = (choice[1].length > 20)? choice[1].substring(0,10) + "..." : choice[1];
            }
            var el = new Element('li');
            
            if(MooTools.version == '1.11') {
               el.setHTML(this.markQueryValue(name));
            } else {
               el.set('html', this.markQueryValue(name));
            }
            
            if ( un != null) {
               var newEle = new Element('span', {'class': 'username'});
               if(MooTools.version == '1.11') {
                  newEle.setHTML('&lt;' + this.markQueryValue(un) + '&gt;');
             } else {
                newEle.set('html', '&lt;' + this.markQueryValue(un) + '&gt;');
             }
               el.adopt(newEle);
            }
            el.inputValue = choice[0];
            this.addChoiceEvents(el).injectInside(this.choices);
        },
        'onHide' : onSelectCallback
    });
}



/* multi friend selector stuff */


function toggleFriend(link,memberId){
    var elem = $(link);
    if (elem.getParent().hasClass('added')){
        removeFriend(elem,memberId);
    } else {
        addFriend(elem,memberId);
    }
    var addedFriendsLink = $E("a","added-friends");
    addedFriendsLink.set('html', addedFriendsLink.getProperty('title') + ' (' + numAdded + '/' + max + ')');
}

function clearFriends(form){
    var inputs = $$('.friend-id');
    for(var i = 0 ; i < inputs.length; i++){
        inputs[i].dispose();
    }
    return false;
}

function removeFriend(link,memberId){
    $E('#friend-element-' + memberId).toggleClass('added');
    $E('#toggler-' + memberId).toggleClass('added');
    $E('#input-' + memberId).dispose();
    var removed = $E('#toggler-' + memberId);
    $E('#not-added').adopt(removed);
    numAdded--;
}

function addFriend(link,memberId){
    if ( numAdded < max ){
        $E('#friend-element-' + memberId).toggleClass('added');
        $E('#toggler-' + memberId).toggleClass('added');
        numAdded++;
        var added = $E('#toggler-' + memberId);
        added.dispose();
        
        $('already-added').adopt(added);
        link.adopt(new Element('input',{
           'type' : 'hidden', 
           'name' :"ids[]", 
           'class' : 'friend-id',
           'value' : memberId, 
           'id' : "input-" + memberId
         }));
    }
}

function selectTopFriends(selectorId){
    var top = $$('#'+selectorId+" a.top").each(function(element,idx){
        var memberId = $(element).getParent().id.substring("friend-element-".length);
        toggleFriend(element,memberId);
    });
}

function select(element,containerId,toEnable,toDisable){
    $E('.current',containerId).toggleClass('current');   
    $(element).getParent().toggleClass('current');
    if($(toEnable)){
    	$(toEnable).setStyle('display','');
    }
    for(var i=0; i < toDisable.length; i++){
    	if ($(toDisable[i])){
    		$(toDisable[i]).setStyle('display','none');
    	}
    }

}

/* effects */
function fadeIn(element, duration){
   var fx = new Fx.Tween(element, {property: 'opacity', 
	                               duration: duration,
	                               onStart: function(){ element.setStyle('display','');}
   								   });
   fx.start(0,1);   
}

function fadeOut(element, duration){
	var fx = new Fx.Tween(element, {
			property: 'opacity',
			duration: duration,
			onComplete: function(){ element.setStyle('display','none');}
	});
   fx.start(1,0);   
}

/* rating tag stuff */
function enhanceAppRatingTags() {
   $$(".app-rating").each(function(element){
      element.rating = element.getAttribute("rating");
      element.formToken = element.getAttribute("FormToken");
      element.originalRating = element.rating;
      setRatingImage(element, element.getAttribute("friend") == "Y", element.rating);
      //alert("appId=" + element.appId);
      if (element.getAttribute("appId") != null) {
         element.appId = element.getAttribute("appId");
         element.addEvents({
            "mouseleave": function(event) {
               element.rating = element.savingRating == null ? element.originalRating : element.savingRating;
               setRatingImage(element, false, element.rating);
            },
            "mousemove": function(event) {
               var star = calculateStar(new Event(event));
               setRatingImage(element, true, star);
            },
            "click": function(event) {
               var star = calculateStar(new Event(event));
               tmp = new Request.JSON({
                  url:"/c/apps/save_rating?AppId=" + element.appId + "&NewRatingNum=" + star + "&FormToken=" + element.formToken,
                  onComplete: function(response) {
                     if(response.data.result=="Saved") {
                        element.originalRating = element.rating = star;
                        openReviewLightBox("review"+element.appId);
                     } else {
                        element.rating = element.originalRating;
                     }
                     element.savingRating = null;
                     setRatingImage(element, false, star);
                  } 
               }).send();
               element.savingRating = element.rating = star;
               setRatingImage(element, true, star);
            }
         });
      }
   }); 
}
                                                   
function calculateStar(event) {
   var target = $(event.target);
   return Math.ceil((event.client.x - target.getLeft())/(target.getCoordinates().width/5));
}

function setRatingImage(imgElement, friend, rating) {
   var stars = rating === undefined ? 0 : Math.round(rating);
   imgElement.set("src", "/img/" + (friend ? "Orange" : "Red") + "Stars" + stars + ".png");
}
/* end rating tag stuff */

/* app icon zoom stuff */
function enhanceMyApplications() {
   var div = $("my-applications");
   var drawer = div.getElement(".drawer");
   var slide = new Fx.Slide(drawer);
   slide.hide();
   var toggle = div.getElement("a.toggle");
   toggle.addEvent("click", function(event) {
      if (div.hasClass("expand")) {
         with (new Event(event)) {
            div.removeClass("expand");
            slide.slideOut();
            stop();
         }
      } else {
         with (new Event(event)) {
            div.addClass("expand");
            slide.hide();
            slide.slideIn();
            stop();
         }
      }
   });
}
/* end app icon zoom stuff */

/* app review stuff */
var reviewlightbox;
var reviewPostSubmit = function(event){
	event.preventDefault();
	event.target.send();
    if ($defined(reviewlightbox)){
    		reviewlightbox.close();
    }
};

function enhanceAppReviews() {
    $$(".app_review_form").each(
        function(element){
            element.addEvent("submit",reviewPostSubmit);
        });
}

function openReviewLightBox(id) {
   if ($defined(reviewlightbox)) {reviewlightbox.close();}
   reviewlightbox = new LightBox(id,{'valign':'top'});
   reviewlightbox.open();
   reviewlightbox.element.getElement('textarea').focus();
}

/* end app review stuff */

/* app tooltip stuff */
function enhanceAppLinks() {
   var container = $("top-rated-applications");
   container.responses = new Object();
   var memberId = container.getAttribute("memberId");
   //alert("memberId=" + memberId);
   var tooltip = $("app-tool-tip");
   var body = $(document.body);
   //alert(body.id); 
   tooltip.injectTop(body);
   $$(".app-link").each(function(element){
      element.addEvents({
         "mouseenter" : function(event) {
            var appId = element.getAttribute("appId");
            var data = topRatedApplicationsToolTipData[appId];
            setupTooltip(tooltip, data);
            showAppTooltip(tooltip, element);
         }, 
         "mouseleave" : function(event) {
            hideTooltip(tooltip);
         } 
      });
   });
   tooltip.addEvents({
      "mouseenter" : function(event) {
         if (tooltip.fx != undefined) {
            tooltip.fx.stop();
         }
         if (tooltip.getStyle("opacity") > 0.5) {
            tooltip.setStyle("opacity", "1");
         } else {
            tooltip.setStyle("opacity", "0");
         }
      }, 
      "mouseleave" : function(event) {
         hideTooltip(tooltip);
      } 
   });
}

function setupTooltip(tooltip, response) {
   tooltip.getElement("h1").setHTML(response.appName);
   setRatingImage(tooltip.getElement(".friends-rating"), true, response.friendRating);
   setRatingImage(tooltip.getElement(".bebo-rating"), false, response.beboRating);
   var label = tooltip.getElement("label#recently-added-label");
   var ul = tooltip.getElement("ul#recently-added");
   ul.empty();
   var recentlyAdded = response.recentlyAdded;
   if (recentlyAdded.length > 0) {
      label.setStyle("display", "block");      
      ul.setStyle("display", "block");      
      for(var i = 0; i < recentlyAdded.length; i+=1) {
         var one = recentlyAdded[i];
         var li = new Element("li");
         li.inject(ul);
         var a = new Element("a", {
            "href": "?MemberId=" + one.memberId,
            "text": one.displayName
         }).inject(li,'top');
      }
   } else {
      label.setStyle("display", "none");      
      ul.setStyle("display", "none");      
   }
}

function showAppTooltip(tooltip, element) {
   var c = element.getCoordinates();
   var left = (c.left + c.right) / 2 - 27;
   var correctedLeft = Math.min(left, window.getWidth() - 265);
   tooltip.set('styles', {
      "left": correctedLeft,
      "background-position": (left - correctedLeft - 247) + "px bottom",
      "bottom": window.getHeight() - element.getElement("img").getTop() - 7,
      "display": 'block',
      "opacity": 0
   });
   if ($defined(tooltip.fx)) {
      tooltip.fx.stop();
   }
   tooltip.fx = new Fx.Style(tooltip, 'opacity', {
      transition: Fx.Transitions.Cubic.easeIn, 
      duration: 300, 
      onComplete : function(event) {tooltip.fx=undefined;}
   }).start(1);
}

function hideTooltip(tooltip) {
   if (tooltip.fx != undefined) {
      tooltip.fx.stop();
   }
   tooltip.fx = new Fx.Style(tooltip, 'opacity', {
      transition: Fx.Transitions.Cubic.easeOut, duration: 800, 
      onComplete : function(event){
         tooltip.setStyle("display", "none"); 
         tooltip.fx=undefined;
      }
   }).start(0);
}
/* end app tooltip stuff */


/* drop down */
function closeDropDowns(id){
    $$('.drop-down-options').each(function(elem){elem.style.display = 'none';});
    $('content').removeEvent('click',closeDropDowns);
}
function dropDownSelected(id) {
    toggle(id);
    setTimeout("$('content').addEvent('click',closeDropDowns)",100);
}
/* end drop down  */

/*lightbox*/
var LightBox = new Class({
  initialize: function(element) {
    this.params = arguments[1];
    if (arguments[1] == null){
        this.params = {};
    }
    
    if ($type(element) == 'element') {
      this.element = element;
    } else {
      this.element = $(element);
    }
    //init element
    this.element.setStyle('z-index', '9999');
    this.element.setStyle('position', 'absolute');
    this.element.injectInside(document.body);

    //init background
    if (!$defined($('lightbox_bg'))) { 
      margin = 8;
      this.bg = new Element('div');
      this.bg.setStyle('id', 'lightbox_bg');
      this.bg.injectAfter(this.element);
      this.bg.setStyle('z-index', '9998');
      this.bg.setStyle('background-color', 'black');
      this.bg.setStyle('position', 'absolute');
    }
    this.close();
  }
});

LightBox.implement({
	setOnClose: function(evt){
		this.onclose = evt;
	}
});

LightBox.implement({
    open: function() {
      //display
      this.element.setStyle('display', 'block');
      this.element.setOpacity(1);
    
      //hide all ads
      $$('div.advertisement').each(function(ad, index) {
         ad.setOpacity(0);
      });
    
      var eleSize = {};
      
      if(MooTools.version == '1.11') {
         eleSize = this.element.getSize().size;
      } else { // version >= 1.2
         eleSize = this.element.getSize();
      }
      
      //center
      elementLeft = parseInt(window.getWidth()/2 - eleSize.x/2, 10);
      if (this.params.valign == 'top'){
          elementTop = 80;
      } else {
          elementTop = parseInt(window.getHeight()/2 - eleSize.y/2, 10);
          elementTop = elementTop<80? 80 : elementTop;
      }
      
      this.element.set('styles', {
         'left': elementLeft,
         'top': elementTop,
         'position': 'fixed',
         'visibility': 'visible'
      });
     
      this.bg.set('styles', {
        'display': 'block',
        'position': 'fixed',
        'top': elementTop - margin,
        'left': elementLeft - margin,
        'width': eleSize.x + margin * 2,
        'height': eleSize.y + margin * 2,
        'opacity': 0.4
      });
      
      //show and position close button
      this.visible = true;
    }
});

LightBox.implement({
  close: function() {
    this.bg.setOpacity(0);
    this.bg.setStyle('display', 'none');
    this.element.setOpacity(0);
    this.element.setStyle('display', 'none');
    this.visible = false;
    
    if(this.onclose){
    	this.onclose();
    }
    //show ads again
    $$('div.advertisement').each(function(ad, index) {
          ad.setOpacity(1);
       });

  }
});

LightBox.implement({
    destroy: function() {
        this.element.destroy();
    }
});

LightBox.implement({
  toggle: function() {
    if (!this.visible) {
      this.open();
    } else {
      this.close();
    }
  }
});
/* end lightbox */


/* photoselector */
//(to be used with sn:photo-selector tag)
var activePhotoSelector;

var PhotoSelector = new Class({
  initialize: function(id, member_id, select, deselect, url, size) {
    this.id = id; //id of photo_selector div
    this.member_id = member_id;
    this.select_callback = select;
    this.deselect_callback = deselect;
    //this.remote_url = '/c/photo_selector/'
    this.base_url = url;//'/c/photo_selector/'; // //
    this.size = size;
    //make div a lightbox
    this.lightbox = new LightBox('selector' + this.id, {'valign':'top'});
    this.content = $('content' + this.id);
    this.tip = $('tip' + this.id);
    this.add_link = $('add' + this.id);
    this.remove_link = $('remove' + this.id);
    this.photo = $('photo' + this.id);
    this.active = false;
  },

  loading: function() {
    this.content.set('html', '<img src="/img/throbber_default.gif" /> Loading...');
  },
  
  open: function() {
    if (!activePhotoSelector) {
      activePhotoSelector = this;
      this.lightbox.open();
      this.active = true;
      this.render();
    }
  },
  
  render: function() {
    this.loading();
    this.tip.innerHTML = 'First, pick an album to open:';
    //show albums
    url = this.base_url + 'show_albums?MemberId=' + this.member_id + '&no_layout=1';
    tmp = new Request.HTML({
       'url': url,
       'update': activePhotoSelector.content
    }).send();
  },
  
  select_album: function(album_id) {
    this.album_id = album_id;
    this.loading();
    this.tip.set('html', 'Now select a photo to use (<a href="javascript:activePhotoSelector.render();">back</a>)');
    //show photos
    url = this.base_url + 'show_photos?MemberId=' + this.member_id + '&AlbumId=' + this.album_id + '&Size=' + this.size + '&no_layout=1';
    tmp = new Request.HTML({'url': url, 'update': activePhotoSelector.content}).send();
  },

  select_photo: function(photo_id, file_url) {
    this.photo_id = photo_id;
    //swap the add/remove
    this.add_link.setStyle('display', 'none');
    this.remove_link.setStyle('display', 'inline');
    //insert the image
    this.photo.set('html', '<img src="' + file_url + '"/>');
    //call the callback
    eval (this.select_callback + '(photo_id, file_url);');
    this.close();
  },

  deselect_photo: function() {
    this.photo_id = null;
    //swap the add/remove
    this.remove_link.setStyle('display', 'none');
    this.add_link.setStyle('display', 'inline');
    //remove image
    this.photo.set('html', '');
    eval (this.deselect_callback + '();'); //jesh: i dont understand this...
    this.close();
  },

  close: function() {
    activePhotoSelector = null;
    this.active = false;
    this.lightbox.close();
  }
});

//default photoselect callback
function wee(photo_id, file_url) {
  alert('selected photo: ' + photo_id);
}
/* end photoselector */

/* dialog */
function showDialog(id){
   closeDialog();
   var orig = $(id + "-orig");
   // cloning protects agains mock ajax permanently messing with 
   // the original contents of the box.
   var cloned = orig.cloneNode(true);
   var form = $E('form',cloned);
   if ( form != null) {
      form.setAttribute('id',form.getAttribute('id').substring(0,form.id.length - "-orig".length));
   }
   cloned.id = id;
   cloned.inject(orig, 'after');
   window.dialogBox = new LightBox(cloned,{'valign':'top'});
   window.dialogBox.open();
}

function submitDialog(formId){
   var form = $(formId);
   //IE does not find the element to submit (a cloned form) in the
   //previous line, the hack below fixes that problem
   if (form.id=="") { //damn IE!
      var formArray = document.getElementsByTagName('form');
      for (i=0; i<formArray.length; i++) {
         if (formArray[i].id==formId) {
            form = formArray[i];
            break;
         }
      }
   }
   form.submit();
}

function closeDialog(){
   if ( window.dialogBox != null) {
      window.dialogBox.close();
      window.dialogBox.destroy();
      window.dialogBox = null;
   }
}

/* app tracking */
function initFocusTracker(appId) {
   var timeout = 30000;
   var heartbeat = window.setInterval('heartbeat(\''+appId+'\')', timeout);
   
   var intervalSet = true;

   $(window).addEvents({
      'windowentered': function() {
         canvasFocus(appId); 
         if (!intervalSet) {
            heartbeat = window.setInterval('heartbeat(\''+appId+'\')', timeout); 
            intervalSet = true;
         }
      },
      'windowleft': function() {
         canvasBlur(appId);
         window.clearInterval(heartbeat);
         intervalSet = false;
      },
      'unload': function(){
         canvasBlur(appId);
      },
      'domready' : function(){
         canvasFocus(appId);
      }
   });
   
}

function canvasBlur(appId) {
   tmp = new Request.JSON({url: "/c/track/canvas_blur?AppId="+appId, method: 'get'}).send();
}

function canvasFocus(appId) {
   tmp = new Request.JSON(
		   {url: "/c/track/canvas_focus?AppId="+appId, method: 'get'}).send();
}

function heartbeat(appId) {
   tmp = new Request.JSON({
	   url: "/c/track/canvas_heartbeat?AppId="+appId, 
	   method: 'get',
	   onComplete: function(responseJSON, responseText){
		   if (responseJSON != null){
		   	handleLuvAdded(responseJSON.data);
		   }
   	   }
   }).send();
}

function recordNotificationClick(appIdNotif,sourceCd,sourceId,hasNotifApp,appUsernameLink) {
   tmp = new Request({url: "/c/app_request/record_notification_click?AppIdNotif="+appIdNotif+"&SourceCd="+sourceCd+"&SourceId="+sourceId+"&AppUsernameLink="+appUsernameLink+"&HasNotifApp="+hasNotifApp, method: 'get', async:false}).send();
}

function recordInvitationClick(appIdInvite,sourceCd,sourceId,hasInviteApp,appUsernameLink) {
   tmp = new Request({
      url: "/c/app_request/record_invitation_click?AppIdInvite="+appIdInvite+"&SourceCd="+sourceCd+"&SourceId="+sourceId+"&AppUsernameLink="+appUsernameLink+"&HasInviteApp="+hasInviteApp, 
      method: 'get', 
      async:false
   }).send();
}

function trackAppSourceInstall(appId,sourceCd,sourceId) {
   if (window.Ajax) {   
      tmp = new Ajax("/c/app_request/track_app_source_install?AppId="+appId+"&SourceCd=" + sourceCd+"&SourceId="+sourceId, {method: 'get',async:false}).request();
   } else {
      tmp = new Request({method:'get', async:false, url: '/c/app_request/track_app_source_install'}).send("AppId="+appId+"&SourceCd="+sourceCd+"&SourceId="+sourceId).send();  
   }
}

function recordNotificationView() {
   tmp = new Request({url:"/c/app_request/record_notification_view", method: 'get'}).send();
}

function recordInvitationView() {
   tmp = new Request({url:"/c/app_request/record_invitation_view", method: 'get'}).send();
}

function trackAppCanvasView(appId,sourceCd) {
   if (window.Ajax) {
      tmp = new Ajax("/c/app_request/track_app_canvas_view?AppId="+appId+"&SourceCd="+sourceCd, {method: 'get'}).request();
   } else {
      tmp = new Request({method:'get', url: '/c/app_request/track_app_canvas_view'}).send("AppId="+appId+"&SourceCd="+sourceCd).send();
   }
}

function trackAppByUsername(appUsername,sourceCd,sourceId) {
   if (window.Ajax) {
      tmp = new Ajax("/c/app_request/track_app_by_username?AppUsername="+appUsername+"&SourceCd="+sourceCd+"&SourceId="+sourceId, {method: 'get',async:false}).request();
   } else {
      tmp = new Request({method:'get', async:false, url: '/c/app_request/track_app_by_username'}).send("AppUsername="+appUsername+"&SourceCd="+sourceCd+"&SourceId="+sourceId);
   }
}
/* app tracking */

/* App Notifications in Bebo Web Messenger */
function getNewAppNotifications() {
	tmp = new Request.JSON( {
		url :'/c/app_request/get_new_app_notifications',
		method :'get',
		async :false,
		onComplete : function(json, text) {
		}
	}).send();
}

window.activeHelp = null;

var HelpBubble = new Class({
	initialize: function(uid, anchor){
		this.bubble = $(uid);
		this.showing = false;
		this.uid = uid;
		this.anchor = anchor;
	},

	showBubble: function(event){
		this.bubble.setStyles({
			top: 15,
			left: -36,
			display: "block"
		});
		this.showing = true;
	},
	
	hideBubble: function(){
		this.bubble.setStyle("display","none");
		this.showing = false;
	},
	
	toggleBubble: function(event){
		if ( window.activeHelp != this){
			this.closeOpenBubble();
			window.activeHelp = this;
		}
		
		if (this.showing){
			this.hideBubble();
		} else {
			this.showBubble(event);
		}
	},
	closeOpenBubble: function(){
		if ( window.activeHelp != null && window.activeHelp.showing){
			window.activeHelp.hideBubble();
			window.activeHelp = null;
		}
	},
	bindTo: function(anchor){
		this.anchor = $(anchor);
		this.anchor.addEvent("click",this.toggleBubble.bind(this));
		this.bubble.addEvent("click", this.hideBubble.bind(this));
	}	
   
});

/* luv Rewards */
function handleLuvAdded(luvData){
	var elem = new Element("div");
	elem.set("html", luvData.partial);
	bebo.ui.Growl.notify(elem,{delay: 10000});
}
