/*****************************************************
** MANHUNT List JavaScript Library
** Author: Zachary Segal
** Version: 1.0
** Date: Jan. 31, 2008
** copyright MANHUNT 2008
*****************************************************/

function listResize(offset, obj1, obj2) {

    if (jQuery.browser.opera == true) {
      var height = window.innerHeight - offset;
    }
    else {
      var height = jQuery(window).height() - offset;
    }
    
    if (height < 150) {
        height = 150;
    }

    jQuery(obj1).height(height);
    //jQuery(obj2).height(height+35);
}

function buddyRowHover(obj, highlight) {
    
    if (highlight == true) {
        jQuery(obj).css('backgroundColor','#000000');
        jQuery(obj).find('a').addClass('buddyLink');
    }
    else {
        jQuery(obj).css('backgroundColor','#191919');
        jQuery(obj).find('a').removeClass('buddyLink');
    }
}

//===========================================================
//===========================================================
/**  BUDDY METHODS  **/

/**
* Add or edit a member on the user's buddy list
* 
* @param string url Url of the symfony action called with AJAX
* @return boolean Always returns false to stop the form submission
*/
function ajaxAddBuddy() {
    
    // get values from  hidden form elements
    var userId = jQuery('#buddyUid').val()//obj.buddyUid.value;
    var note = jQuery('#buddyNote').val()//obj.buddyNote.value;
    var imageId = jQuery('.selectedBuddyImage').attr('photoid')//obj.buddyImgID.value;
    
    /*
    if (imageId == undefined) {
        imageId = 0;
    }
    */

    var saveChanges = 1;
    
    url = url_for('list/modalAddBuddy');
    jQuery.post(url, {buddyUid:userId, buddyImgID:imageId, buddyNote:note, commit:saveChanges}, function(data) {
        // evaluate the returned string from PHP into a JSON object
        try {
           var jsonData = jQuery.parseJSON(data);
        }
        catch (e) {
            return false;
        }

        // detect from which page the user added or edited a buddy
        if (jQuery('.buddyListView').css('display') == 'block') {
            // update the preferred image
            getPhotoUrl = url_for('photo/ajaxGetPhoto');
            jQuery.get(getPhotoUrl, {profileId:userId, photoId:jsonData.buddyImageId, photoSize:'small'}, function(data) {
                try {
                    imageData =  jQuery.parseJSON(data);
                }
                catch (e) {
                    alert(mhDictionary.site.ajaxError);
                    return false;
                }

                jQuery('#buddy' + userId + ' a').css('background-image',"url('" + imageData.url + "')");

            });
            
            // update the notes in the page so they are seen immediately
            var shortNote = note.substr(0,50);
            jQuery("#buddyNotesGrid"+userId).html(shortNote);
            jQuery("#buddyNotesList"+userId).html(note);

         //   jQuery('#'+jsonData.buddyUid).find('.buddyPhoto').children('img').attr('alt',jsonData.buddyImageId);
         //   jQuery('#'+jsonData.buddyUid).find('.buddyPhoto').children('img').attr('src',jsonData.buddyImage);
            
            // update online buddies count in top nav
            var string = mhDictionary.list.topnav.replace('%ONLINE%',jsonData.onlineCount);
            //jQuery('#onlineBuddies').html(string);

            buddyCountClass = (jsonData.onlineCount > 0 && jsonData.onlineCount < 100) ? 'small-green-badge' : 'big-green-badge';
            jQuery('#buddy-count').attr('class', buddyCountClass);
            jQuery("#buddy-count").html(""); //Needed for Firefox 3.6
            jQuery('#buddy-count').append(jsonData.onlineCount);
            jQuery('#buddy-count').show();


        }
        else {
            // swap add buddy button with edit buddy button
            jQuery('#buddyButton'+userId).html(mhDictionary.list.editBuddyButtonLabel);
            //jQuery('#buddyButton'+userId).corner('5px');
            
            jQuery('#buddyIconPix'+userId).addClass('buddyStar'); //css('backgroundImage','url(' + assetDirectory + 'images/ui/buddy_star.png)');
            
            var string = mhDictionary.list.topnav.replace('%ONLINE%',jsonData.onlineCount);
            // update online buddies count in top nav
            try {
                //window.opener.jQuery('#onlineBuddies').html(string);
                if (window.opener.location.pathname != url_for('multichat')) window.opener.location.reload();
            }
            catch(e) {
                //jQuery('#onlineBuddies').html(string);

                buddyCountClass = (jsonData.onlineCount > 0 && jsonData.onlineCount < 100) ? 'small-green-badge' : 'big-green-badge';
                jQuery('#buddy-count').attr('class', buddyCountClass);
                jQuery("#buddy-count").html(""); //Needed for Firefox 3.6
                jQuery('#buddy-count').append(jsonData.onlineCount);
                jQuery('#buddy-count').show();

            }
        }

        // close the modal window
        modalClose();

        // need to reload the page if editing notes
        var greetingString = new String(document.getElementById("greeting").innerHTML);
        var editing = (greetingString.indexOf("Edit") != -1) ? true : false;
        var buddyListPage = jQuery("#buddyGrid").length == 1 ? true : false;
        
        if(editing && buddyListPage) {
            //alert(greetingString);
            var t = setTimeout("location.reload()",500);
        }
        
        
    });
    
    return false;
}


/**
* Remove a member from the user's buddy list
* 
* @param string url Url of the symfony action called with AJAX
* @param int uid User id of the member to remove from buddy list
* @param object obj The dom element used to call this method
*/
function ajaxRemoveBuddy(uid, obj, name) {
    //var buddyName = jQuery(obj).parent().siblings('a').html();
    var c = confirm(mhDictionary.list.confirmDelete.replace('%NAME%', name));
    if (c == false) {
        return false;
    }
    
    var url = url_for('list/ajaxDeleteBuddy');
    jQuery.post(url, {buddy:uid}, function(data) {
        try {
            var jsonData =  jQuery.parseJSON(data);
            //alert("count: "+jsonData.onlineCount);
        }
        catch (e) {
            alert(mhDictionary.site.ajaxError);
            return false;
        }
        
        // alert user that an error occured (shouldn't happen)
        if (jsonData.success == "false") {
            alert(mhDictionary.list.notOnListError);
            return false;
        }
        
        //var string = mhDictionary.list.topnav.replace('%ONLINE%', jsonData.onlineCount);
        //alert("onlineCount: " + string);

        //jQuery('#onlineBuddies').html(string);
        
        // animate the removal of a buddy from your buddy list
        //var row = jQuery(obj).parent().parent().parent();
        //var item = jQuery(obj).parent().parent();
        
        //jQuery(item).remove();
        location.reload();
        
        /*
        jQuery(row).animate({opacity:0}, 'fast', function() 
        {
            jQuery(this).animate({height:0}, 'slow', function() 
            {
                
                if (jQuery(this).siblings('td').length < 1) {
                    var emptyMessage = document.createElement('p');
                    jQuery(emptyMessage).addClass('emptyList');
                    jQuery(emptyMessage).css('display','none');
                    
                    var text = mhDictionary.list.emptyBuddyList;
                    if (jQuery('a.selectedBuddyTab:contains("Online")').length == 1) 
                    {
                        text = mhDictionary.list.emptyOnlineBuddyList;
                    }
                    jQuery(emptyMessage).html(text);
                    
                    jQuery(this).before(emptyMessage);
                    jQuery('.emptyList').fadeIn("fast");
                }
                
                jQuery(this).remove();
                
            });
        });
        */
    });

}

function selectBuddyPhoto(obj) {
    jQuery('.photoIcon').removeClass('selectedBuddyImage');
    jQuery(obj).addClass('selectedBuddyImage');
}

//===========================================================
//===========================================================
/**  BLOCK METHODS  **/ 

/**
* Add a member to the user's block list
* 
* @param string url Url of the symfony action called with AJAX
* @return boolean Always returns false to stop the form submission
*/
function ajaxAddBlock() {

    // get values from hidden form elements
    var userId = jQuery('#blockUid').val();
    var note = jQuery('#blockNote').val();
    var saveChanges = 1;
    
    var url = url_for('list/modalAddBlock');
    jQuery.post(url, {blockUid:userId, blockNote:note, commit:saveChanges}, function(data) {
        try {
            var jsonData =  jQuery.parseJSON(data);
        }
        catch (e) {
            alert(mhDictionary.site.ajaxError);
            return false;
        }

        if(window.opener) {            
            if (window.opener.location.pathname != url_for('multichat')) window.opener.location.reload();
            //alert("url: " + window.opener.location.href);
        }
        
        handleCallBackAddBlock(jsonData);
    });

    return false;
}

/**
* Handle the different cases where ajaxAddBlock is called
* 
* @param object data JSON object containing the added block's id and notes 
*/
function handleCallBackAddBlock(data) {
    
    // get the full url path of the current page
    var urlPath = window.location.pathname;
    
    
    // see if the parent window is a search page 
    // and attempt to switch the block button their.
    try {
          if (window.opener.location.pathname.match('search')) {
              var row = window.opener.jQuery('#profile'+data.uid);
              if (row.css('display') == 'block') {
                  jQuery(row).children('.panelBody').remove();
                  jQuery(row).children('.panelHeader').html(mhDictionary.list.blockedUser);
                  jQuery(row).children('.panelHeader').css('marginBottom','10px');
             }
            else {
                //alert('parent window doesnt contain matching button');
            }
          }
          else {
              //alert('parent window not search');
          }
    }
    catch(e) {
        //alert('no parent window');
    }
    
    // detect from which page the user added the block
    if (urlPath.toLowerCase().match('block')) {
        // update the note of the block in the block list 
        jQuery("#buddyNotesGrid"+data.uid).html(data.blockNote);
        jQuery("#buddyNotesList"+data.uid).html(data.blockNote);
        jQuery('#block'+data.uid).find('.buddyNotes').html(data.blockNote);
    }
    else if (urlPath.match('profile')) {
        // close the profile view after block is added
        window.close();
    }
    else if (urlPath.match('mail')) {
        // load appropriate mailbox after block is added from mail message
        var environment = data.env
        if (environment != 'prod') {
            environment = '/frontend_' + environment + '.php';
        }
        else {
            environment = "";
        }
        var folder = urlPath.match(/\/folder\/([^\/]*)\//);
        var url = environment + '/mail/viewFolder/folder/'+folder[1];
        window.location.assign(url);
    }
    else if (urlPath.match('search')) {
        // animate the removal of member from their block list
        var row = jQuery('#profile'+data.uid);
        jQuery(row).children('.panelBody').slideUp('fast', function() {
            jQuery(this).remove();
        });
        
        jQuery(row).children('.panelHeader').html(mhDictionary.list.blockedUser);
        jQuery(row).children('.panelHeader').css('marginBottom','10px');
    }
    else {
        alert(mhDictionary.site.generalError);
    }
    
    
    // close the modal window if page wasn't refreshed or reloaded
    modalClose();
}


/**
* Remove a member from the user's block list
* 
* @param string url Url of the symfony action called with AJAX
* @param int uid User id of the member to remove from block list
* @param object obj The dom element used to call this method
*/
function ajaxRemoveBlock(uid, obj) {
    var name = jQuery(obj).parent().siblings('a').html();
    var c = confirm(mhDictionary.list.confirmUnblock.replace('%NAME%', name));
    if (c == false) {
        return false;
    }
    
    var url = url_for('list/ajaxDeleteBlock');
    jQuery.post(url, {block:uid}, function(data) {
        handleCallBackRemoveBlock(data, obj, uid)
    });
}


/**
* Handle the different cases where ajaxRemoveBlock is called
* 
* @param string data Pass/fail string returned from ajax request
* @param object obj The dom element used to call this method
*/
function handleCallBackRemoveBlock(data, obj, uid) {
    
    // alert user that an error occured (shouldn't happen)
    if (data == "error") {
        alert(mhDictionary.list.notOnListError);
        return false;
    }
    
    
    // see if the parent window is a search page 
    // and attempt to switch the block button their.
    try {
           if (window.opener.location.pathname.match('search')) {
           
            var button = window.opener.jQuery('#blockButton'+uid);
            if (button.css('display') == 'block') {
                button.html('block');
                 //button.corner('5px');
                 button.unbind();
                 button.bind('click', function() {
                     window.opener.modalOpen('list/modalAddBlock',{block:uid});
                });
            }
            else {
                //alert('parent window doesnt contain matching button');
            }
           }
           else {
               //alert('parent window not search');
           }
    }
    catch(e) {
        //alert('no parent window');
    }
    
    
    // detech which way the user used to remove member block
    if (obj.id == "blockButton") {
        // refresh profile view after block is removed
        location.reload();
    }
    else if (obj.id == "blockButton"+uid) {
        jQuery(obj).html('block');
        //jQuery(obj).corner('5px');
        jQuery(obj).unbind();
        jQuery(obj).bind('click', function() {
            modalOpen('list/modalAddBlock',{block:uid});
           });
    }
    else {
        // animate the removal of member from their block list
        var listItem = "#block" + uid;
        var row = jQuery(listItem);
        jQuery(row).animate({opacity:0}, 'fast', function() {
            jQuery(this).animate({height:0}, 'slow', function() {
                if (jQuery(this).siblings('div').length < 1) {
                    var emptyMessage = document.createElement('p');
                    jQuery(emptyMessage).addClass('emptyList');
                    jQuery(emptyMessage).css('display','none');
                    jQuery(emptyMessage).html(mhDictionary.list.emptyBlockList);
                    
                    jQuery(this).before(emptyMessage);
                    jQuery('.emptyList').fadeIn("fast");
                }
                
                jQuery(this).remove();
            });
        });

        var gridItem = "#buddyListGrid" + uid;
        var cell = jQuery(gridItem);
        jQuery(cell).stop(true);
        jQuery(cell).unbind();
        jQuery(cell).animate({opacity:0}, 'fast', function() {
            jQuery(this).animate({width:0}, 'slow', function() {
                if (jQuery(this).siblings('div').length < 1) {
                    var emptyMessage = document.createElement('p');
                    jQuery(emptyMessage).addClass('emptyList');
                    jQuery(emptyMessage).css('display','none');
                    jQuery(emptyMessage).html(mhDictionary.list.emptyBlockList);
                    
                    jQuery(this).before(emptyMessage);
                    jQuery('.emptyList').fadeIn("fast");
                }
                
                jQuery(this).remove();
            });
        });
    }
    
}


//===========================================================
//===========================================================
/**  UNLOCK METHODS  **/

/**
* Toggle a member's presence on the user's unlock list
* 
* @param string url    Url of the symfony action called with AJAX
* @param int id        User id of the member to add/remove from unlock list
* @param string name   Name of the member to add/remove from unlock list
* @param object obj    The dom element used to call this method
*/
function ajaxToggleUnlock(action, id, name, obj, whichList) {
    
    if (action == 'unlock') {
        url = url_for('list/ajaxAddUnlock');
    }
    else if (action == 'lock') {
        url = url_for('list/ajaxDeleteUnlock');
    }
    else {
        alert('action value is invalid')
        return false;
    }
    
    jQuery.post(url, {uid:id, name:name}, function(data) {
        // alert user that an error occured (shouldn't happen)
        if (data == "error") {
            alert(mhDictionary.site.generalError);
            return false;
        }
        
        var sNoUserError = "NOUSER:";
        if (data.indexOf(sNoUserError) != -1) {
            // No user was found (probably due to one of the two being on the 
            //  other's block list
            // The error message displayed here has already been localized
            modalOpenContent(data.substring(sNoUserError.length, data.length));

            return false;
        }
        
        // show the confirmation modal
        modalOpen('list/modalUnlock',{unlock:action, name:name})
        
        // toggle the lock/unlock button's functionality 
        jQuery(obj).unbind();
        if (url.match('Delete') == null) {
            var unlockStr = mhDictionary.list.unlockButtonLabel;
            var newLabel = jQuery(obj).html().replace(unlockStr, mhDictionary.list.lockButtonLabel);
            jQuery(obj).html(newLabel);
            bindToggleUnlockAction('lock',id,name,obj,whichList);
        }
        else {
            var lockStr = mhDictionary.list.lockButtonLabel;
            var newLabel = jQuery(obj).html().replace(lockStr, mhDictionary.list.unlockButtonLabel);
            jQuery(obj).html(newLabel);
            bindToggleUnlockAction('unlock',id,name,obj,whichList);
        }
        
        // toggle the lock/unlock button's functionality on the other view (grid/list)
        /*
        var otherButton = "unlockButton"+id;
        if(whichList == "grid") { otherButton = "unlockButtonGrid"+id; }
        jQuery(otherButton).unbind();
        if (url.match('Delete') == null) {
            var unlockStr2 = mhDictionary.list.unlockButtonLabel;
            var newLabel2 = jQuery(otherButton).html().replace(unlockStr2, mhDictionary.list.lockButtonLabel);
            jQuery(otherButton).html(newLabel2);
            bindToggleUnlockAction('lock',id,name,otherButton,whichList);
        }
        else {
            var lockStr2 = mhDictionary.list.lockButtonLabel;
            var newLabel2 = jQuery(otherButton).html().replace(lockStr2, mhDictionary.list.unlockButtonLabel);
            jQuery(otherButton).html(newLabel2);
            bindToggleUnlockAction('unlock',id,name,otherButton,whichList);
        }
        */
        
    });
}

function bindToggleUnlockAction(action, id, name, obj, whichList) {
    jQuery(obj).bind('click', function() {
        ajaxToggleUnlock(action,id,name,obj,whichList);
    });
}


/**
* Remove a member from the user's unlock list
* 
* @param string url Url of the symfony action called with AJAX
* @param int id User id of the member to remove from unlock list
* @param object obj The dom element used to call this method
*/
function ajaxRemoveUnlock(id, obj) {
    
    var url = url_for('list/AjaxDeleteUnlock');
    jQuery.post(url, {uid:id}, function(data) {
        // alert user that an error occured (shouldn't happen)
        if (data == mhDictionary.list.notOnListError) {
            alert('this ');
            return false;
        }
        
        // animate the removal of the member from user's unlock list
        var row = jQuery(obj).parent().parent();
        jQuery(row).animate({opacity:0}, 'fast', function() {
            jQuery(this).animate({height:0, padding:0}, 'slow', function() {
                if (jQuery(this).siblings('div').length < 1) {
                    var emptyMessage = document.createElement('p');
                    jQuery(emptyMessage).addClass('emptyList');
                    jQuery(emptyMessage).css('display','none');
                    jQuery(emptyMessage).html(mhDictionary.list.emptyUnlockList);
                    
                    jQuery(this).before(emptyMessage);
                    jQuery('.emptyList').fadeIn("fast");
                }
                
                jQuery(this).remove();
            });
        });
        
        // swap pajama stripping of rows after the removed row
        jQuery(row).nextAll().each(function() {
            jQuery(this).toggleClass('trackStripeDark').toggleClass('trackStripeLight');
        });
        
    });
}

function changeTrackPreference(obj) {
    if (obj.id == 'noTrack') {
        var track = 0;
    }
    else {
        var track = 1;
    }
    
    jQuery("input[type=radio]").attr('disabled','disabled');
    jQuery(".trackControls span").fadeOut('fast', function() {
        jQuery(".trackControls strong").fadeIn('fast');
    });
    
    
    var url = url_for('list/ajaxSetTrackable');
    jQuery.post(url, {'track':track}, function(data) {
        jQuery('.trackControls span').animate({marginLeft:0}, 2000, function() {
            jQuery('input[type=radio]').attr('disabled',false);
            jQuery('.trackControls strong').fadeOut('fast', function() {
                jQuery(".trackControls span").fadeIn('fast');
            });
        });
    });
}




//===========================================================
//===========================================================

var buddyImage = [];
 
function loadBuddyImage(rowName,imageUrl,profileUrl) {
    jQuery(rowName + ' .buddyPhoto').css('backgroundImage','url(' + assetDirectory + 'images/ui/ajax_loader.gif)');
    
    buddyImage[rowName] = new Image();
    buddyImage[rowName].onload = function() {
        calcBuddyImage(rowName,buddyImage[rowName],profileUrl);
    }
    buddyImage[rowName].src = imageUrl;
}


function calcBuddyImage(rowName,img,profileUrl) {
    var imgWidth = img.width / 2;
    var imgHeight = img.height / 2;
    
    var imgTag = document.createElement('img');
    imgTag.setAttribute('src',img.src);
    imgTag.setAttribute('alt','');
    imgTag.setAttribute('width',imgWidth);
    imgTag.setAttribute('height',imgHeight);
    
    containerSize = 50;
    
    var leftOffset = Math.floor((containerSize - imgWidth) / 2);
    var topOffset = Math.floor((containerSize - imgHeight) / 2);
    imgTag.style.top = topOffset+'px';
    imgTag.style.left = leftOffset+'px';
    
    if (profileUrl) {
      imgTag.onclick = function() {
        setWindow(profileUrl,'profile');
      }
    }
    
    jQuery(rowName+' .buddyPhoto').append(imgTag);
    jQuery(rowName + ' .buddyPhoto').css('backgroundImage','none');
}

//===========================================================
//===========================================================
// function to save client-side user preferences

function ajaxSavePreference(userID, preference, value) {
    //alert("userID: " + userID + "\npreference: " + preference + "\nvalue: " + value);
    
    var url = url_for('list/AjaxSavePreference');
    jQuery.post(url, {uid:userID, preference:preference, value:value});
}










