﻿/**************************************************************
* toolTipLogicAndText
* utility function to localise all logic and text strings for ToolTip actions in one place 
*(Makes for easier updating)
* call as e.g. var actionLogic = new toolTipLogicAndText(myAction);
* exposes the following properties
* .validAction             - t/f
* .onSuccess               - success handling function
* .alternativeFunction     - handle action via alternative js function.
* .confirmDataOpMessage    - Message to request confirmation before doing action
* .targetText              - name of area changed by action, e.g. 'My Most Stylish'
******************************************************************/
        
function toolTipLogicAndText(tipAction, entityID, entityType){
this.validAction = true;
    switch(tipAction){
        case "SaveToStylefile":
            this.feedbackText = "My Stylefile";
            this.directionPhrase = "added to";
            break;                 
        case "BookmarkStylefile":        
            this.feedbackText = "My Favorite Stylefiles";
            this.directionPhrase = "added to";
            break;       
        case "BookmarkPerson":
            this.feedbackText = "My Most Stylish";
            this.directionPhrase = "added to";
            break;
        case "UnbookmarkPerson":            
            this.onSuccess = function(){removePageditemFromBetterTable(entityID)}
            this.feedbackText = "My Most Stylish";
            this.directionPhrase = "removed from";
            break;
        case "UnbookmarkStylefile":
            this.onSuccess = function(){removePageditemFromBetterTable(entityID)}
            this.feedbackText = "My Favorite Stylefiles";
            this.directionPhrase = "removed from";
            break;
        case "RemoveFromStylefile":

            if (window.location.href.indexOf('vm=1')>0){
                //in the OSOME view of an item - need to redirect back to OSOME_SF
                this.onSuccess = function(){redirectClient('/OSOME/OSOME_Stylefile.publisha')}
            }else{
                this.onSuccess = function(){removePageditemFromBetterTable(entityID)}
            }
            this.confirmDataOpMessage = "Are you sure you want to remove this item from your Stylefile?",            
            this.feedbackText = "My Stylefile";
            this.directionPhrase = "removed from";
            break;                    
        case "RemoveFromHighstreet":
            if (window.location.href.indexOf('vm=1')>0){
                //in the OSOME view of an item - need to redirect back to OSOME_SF
                this.onSuccess = function(){redirectClient('/OSOME/OSOME_Highstreet.publisha')}
            }else{
                this.onSuccess = function(){removePageditemFromBetterTable(entityID)}
            }
            this.confirmDataOpMessage = "Are you sure you want to remove this store from your Highstreet?",            
            this.feedbackText = "My Highstreet";
            this.directionPhrase = "removed from";
            break;          
        case "UnBookmarkHighstreet":     
            this.feedbackText = "My Favorite Highstreets";  
            this.directionPhrase = "removed from";
            break;
        case "SendMessage":            
            this.alternativeFunction = function(){requestSendToFriendForm(entityType, entityID)};            
            break;
        case "RemoveFromFriends":
            this.confirmDataOpMessage = "Are you sure you want to remove this person as one of your OSOYOU Friends?",            
            this.onSuccess = function(){ removePageditemFromBetterTable(entityID);};
            this.feedbackText = "My Friends";  
            this.directionPhrase = "removed from";
            break; 
        case "SendFriendshipRequest":
            // Send friend request message to a user, but first let them confirm this action.       
            this.confirmDataOpMessage = "Send a Friendship request message to this person?";     
            this.feedbackText = "";
            this.directionPhrase = "was sent a Friendship invitation.";
            break;     
        case "BookmarkGroup":       
            this.feedbackText = "My Groups"; 
            this.directionPhrase = "added to";
            break;         
        case "RemoveFromGroups":
            this.confirmDataOpMessage = "Are you sure you want to remove this group from your OSOYOU Groups?";
            this.onSuccess = function(){removePageditemFromBetterTable(entityID)};
            this.feedbackText = "My Groups"; 
            this.directionPhrase = "removed from";
            break;      
        case "SendPrivateGroupInvite":
            // Send message to friends, or send Private Group Invite message
            this.alternativeFunction = function(){requestSendToFriendForm(entityType, entityID)};            
            this.feedbackText = "My Groups"; 
            this.directionPhrase = "invited to";
            break; 
        case "SendPrivateListInvite":
            // Send message to friends, or send Private List Invite message
            this.alternativeFunction = function(){requestSendToFriendForm(entityType, entityID)};            
            this.feedbackText = "My Lists"; 
            this.directionPhrase = "invited to";
            break; 
        case "SaveToHighstreet":            
            this.feedbackText = "My Highstreet"; 
            //this.alternativeFunction = function(){alert('Save to Highstreet tooltip action not implemented yet')};            
            this.directionPhrase = "added to";
            break; 
        case "BookmarkHighstreet":            
            this.feedbackText = "My Favorite Highstreets";             
            this.directionPhrase = "added to";
            break; 
        case "AddToList":
            this.alternativeFunction = function(){requestAddToListForm(entityType, entityID)};            
            break;
        case "BookmarkList":            
            this.feedbackText = "My Lists";             
            this.directionPhrase = "added to";
            break; 
        case "UnbookmarkList":            
            this.confirmDataOpMessage = "Are you sure you want to remove this list from Your Lists?",            
            this.feedbackText = "My Lists";  
            this.onSuccess = function(){removePageditemFromBetterTable(entityID)};           
            this.directionPhrase = "removed from";
            break; 
        default:
            this.alternativeFunction = function(){alert ("Unknown tool tip action - " + tipAction)};
            this.validAction = false;
            break;    
     }
}

function betterToolTipAction(entityType, tipAction, entityID, entityTitle){
    var action=null;
    
    //clear down any tooltip bubbles    
    hideToolTipBubble();
    
    //get the correct logic for this action
    var actionLogic = new toolTipLogicAndText(tipAction,entityID, entityType);
             
    //check logic rule              
    if (actionLogic.alternativeFunction){
        //call alternative code instead of performdataOp
        actionLogic.alternativeFunction();
    }else if (actionLogic.confirmDataOpMessage){

        //need to confirm before performing action        
        OSOYouYesNo("Confirm", 
                    actionLogic.confirmDataOpMessage,
                    function() {performRequiredDataOperations(entityID,entityType,entityTitle,tipAction,actionLogic.onSuccess);});
    }else{
        //do action with no confirmation
        performRequiredDataOperations(entityID,entityType,entityTitle,tipAction,actionLogic.onSuccess);
    }
    return false;    
}

// Send message to friend - form request and handler 
function requestSendToFriendForm(entityType, entityID){
    var theData = "EntityType=" + entityType + "&EntityID=" + entityID;
    var fParentID = '#contentcontainer';
    ajaxCall("friendmessageform", 
             theData,
             function(theResult){
                var resultString = theResult.result;                               
                if(theResult.result == "success"){
                    // Success
                    // Actually display the send message form
                    var theStatus = eval(theResult.data);
                    if(theStatus.status == "form"){
                        // Get the required JS files
                        $.getScript("/Media/js/InviteFriendsCheckboxes.js", 
                                    function(){
                                        $.getScript("/Media/js/forms_utils.js",
                                                    function(){
                                                        html = URLDecode(theStatus.data); 
                                                        var div = '<div id="ModalForm">' + html + '</div>';
                                                        inline_tb_show('width=375&TB_inlineId=OSODialog&inlineId=ModalForm&modal=true', div); 
                                                    });
                                    });
                    }
                }
                else if(theResult.result == "failure")
                {   
                    var failureObject = eval(theResult.data);
                    OSOYouAlert("OSOYOU Message", failureObject.message);                
                }
                return;               
             }
             ,fParentID); 
}
function handleSendToFriendForm(entityType, entityID){
    // Extract and validate form input
    var friends = $("input[@name=friends]:input:checked").serialize();
    var theComment = formatTextBoxValue("#txt_comment");
    if((theComment == null)||(theComment == "")){
        OSOYouAlert("OSOYOU Message", "Please provide a Message comment.");        
        return;
    }
    if((friends == null)||(friends == "")){
        OSOYouAlert("OSOYOU Message", "Please select what friends to send Message to.");        
        return;
    }
    var theData = "EntityType=" + entityType + "&EntityID=" + entityID + "&comment=" + theComment + "&messageTypeAsInt=" + formatTextBoxValue("#messageTypeAsInt") + "&" + friends;
    var fParentID = '#SMFormID';
    ajaxCall("friendmessageprocess", 
             theData,
             function(theResult){
                if(theResult.result == "success"){
                    tb_remove();
                    OSOYouAlert("OSOYOU Message", "Message sent to selected friends. Thanks for using OSOYOU!", null,null,null, 5000);
                }
                else if(theResult.result == "failure")
                {   
                    var failureObject = eval(theResult.data);
                    OSOYouAlert("OSOYOU Message", failureObject.message);                
                }
                return;               
             }
             ,fParentID); 
}

// Add entity to list - form request and handler 
function requestAddToListForm(entityType, entityID){
    var theData = "EntityType=" + entityType + "&EntityID=" + entityID;
    var fParentID = '#contentcontainer';
    ajaxCall("addtolistform", 
             theData,
             function(theResult){
                var resultString = theResult.result;                               
                if(theResult.result == "success"){
                    // Success
                    // Actually display the send message form
                    var theStatus = eval(theResult.data);
                    if(theStatus.status == "form"){
                        // Get the required JS files
                        $.getScript("/Media/js/forms_utils.js",
                                    function(){
                                        html = URLDecode(theStatus.data); 
                                        var div = '<div id="ModalForm">' + html + '</div>';
                                        inline_tb_show('width=380&height=460&TB_inlineId=OSODialog&inlineId=ModalForm&modal=true', div); 
                                    });
                    }
                }
                else if(theResult.result == "failure")
                {   
                    var failureObject = eval(theResult.data);
                    OSOYouAlert("OSOYOU Message", failureObject.message);                
                }
                return;               
             }
             ,fParentID); 
}
function handleAddToListForm(entityID){
    // Extract and validate form input
    var myLists = $("input[@name=myLists]:input:checked").serialize();
    var viewedLists = $("input[@name=recentlyViewedLists]:input:checked").serialize();
    var theComment = formatTextBoxValue("#txt_comments");
    var theTags = formatTextBoxValue("#txt_tags");
    if(((myLists == null)||(myLists == ""))&&((viewedLists == null)||(viewedLists == ""))){
        OSOYouAlert("OSOYOU Message", "Please select at least one List to add the Item to.");        
        return;
    }
    var theData = "EntityID=" + entityID + "&comment=" + theComment + "&" + myLists + "&" + viewedLists + "&tags=" + theTags;
    var fParentID = '#AddToLID';
    ajaxCall("addtolistprocess", 
             theData,
             function(theResult){
                if(theResult.result == "success"){
                    tb_remove();
                    OSOYouAlert("OSOYOU Message", "Item added to selected Lists. Thanks for using OSOYOU!", null,null,null, 5000);
                }
                else if(theResult.result == "failure")
                {   
                    var failureObject = eval(theResult.data);
                    OSOYouAlert("OSOYOU Message", failureObject.message);                
                }
                return;               
             }
             ,fParentID); 
}

function removePageditem(entityID){        
    var itemCount = $("osomepageitemcount").html();
    $("img.galleryimage[@assetid="+entityID+"]").parents("td").remove();
    rebuildTable();
    //HACK - set any item count to one less
    deincrementPagedItemCount();
    //try to stop any paging from being cached.
    doNotCachePaging();
}
function removePageditemFromBetterTable(entityID){        
    var itemCount = $("osomepageitemcount").html();
    $("img.galleryimage[@assetid="+entityID+"]").parents("td:eq(0)").remove();
    rebuildBetterTable();
    //HACK - set any item count to one less
    deincrementPagedItemCount();
    //try to stop any paging from being cached.
    doNotCachePaging();
}

//uses Jquery to deincrement item count without DB roundtrip.
//NB: Only works on OSOME pages with itemcount in specific format
function deincrementPagedItemCount(){
   // GR - Now uses the span ID method
   var itemCount = $("#itemcount").text();
   if(itemCount){
        itemCount--;
        $("#itemcount").text(itemCount);
   }
}


function doNotCachePaging(){
    var pagingLinks = $(".PageLinkActive/a,.PageLinksNext/a,.pageLinksPrev/a");
    if(pagingLinks && pagingLinks.length > 0 ){
        pagingLinks.each(function (i) { $(this).attr("href", $(this).attr("href").replace("rf=f&",""))});
    }
}

function rebuildTable(){
    var table =$(".PagingContainer//table");    
    var cells = table.find("td");
    table.empty();
    var x=0;
    
    for (var i=0;i<cells.length;i++){
        if (i%2==0 && i==(cells.length-1)){
            table.append("<tr><td>"+$(cells[i]).html()+"</td><td>&nbsp;</td></tr>");
        }
        if (i%2==1){
            table.append("<tr><td>"+$(cells[i-1]).html()+"</td><td>"+$(cells[i]).html()+"</td></tr>");
        }
    }
}

function rebuildBetterTable(){
    var table = $(".PagingContainer//table");    
    var cells = table.find("td.borderbottom");
    var rightBorderCells = table.find("td.borderright");
    var rightBorderClass = '';
    if(rightBorderCells && (rightBorderCells.length > 0)){
        rightBorderClass = 'borderright';
    }
    table.empty();
    for (var i=0;i<cells.length;i++){
        if (i%2==0 && i==(cells.length-1)){
            table.append('<tr><td class="borderbottom">'+$(cells[i]).html()+'</td><td class="' + rightBorderClass + '"><img src="/media/images/system/spacer.gif" alt="" /></td></tr>');
        }
        if (i%2==1){
            table.append('<tr><td class="borderbottom">'+$(cells[i-1]).html()+'</td><td class="' + rightBorderClass + '"><img src="/media/images/system/spacer.gif" alt="" /></td><td class="borderbottom">'+$(cells[i]).html()+'</td></tr>');
        }
    }
}

// show bubble in the appropriate place for this icon.
// the tooltip bubble div container has id="bubbleContainer", and the text div has id="bubbleText" inside this.
// the pointy bit div has id="bubblePointyBit", which is ALWAYS 24px down from bubbleContainer.
// We need to get the position from the top of the DOM, not the containing parent cos the single bubble is written into the DOM at the very top.
// We will also change the images for the left & right bubble ends & the pointy bit depending on colour scheme requirements.

// We need access to the images in order to change them per colour scheme. Their IDs are:
// bubblePointyImage
// bubbleLeftImage
// bubbleRightImage
// Also we need to set the CSS for the text part: 
// bubbleText
function showToolTipBubble(objTip, action, bubbleText, pointyOffset, bubbleLeftImage, bubbleRightImage, bubblePointyImage, bubbleTextCSS) {

//alert( [objTip, action, bubbleText, pointyOffset, bubbleLeftImage, bubbleRightImage, bubblePointyImage, bubbleTextCSS]);
    $("#bubblePointyImage").attr("src", bubblePointyImage);
    $("#bubbleLeftImage").attr("src", bubbleLeftImage);
    $("#bubbleRightImage").attr("src", bubbleRightImage);
    $("#bubbleText").attr( 'class', bubbleTextCSS);

    var posX = findPosXToTop(objTip);
    var posY = findPosYToTop(objTip);
    var bubbleDiv = $("div[@id=bubbleContainer]");
    var bubbleTextDiv = $("div[@id=bubbleText]");
    var bubblePointy = $("div[@id=bubblePointyBit]");
    bubbleDiv.show(); // need to show this here - if not it gets set to width=1047!!
    bubbleTextDiv.text(bubbleText);
    var bubbleWidth = $(bubbleDiv).width();
    if( pointyOffset == -1 ) { // centralise the pointy thing

        pointyOffset = (bubbleWidth / 2) - 4;
    }

    // adjust the x & y co-ordinates to get the x & y for positioning the bubble
    var xTip = posX - pointyOffset + 5;
    var yTip = posY - 28;

    bubbleDiv.css({left:xTip, top:yTip});
    bubblePointy.css({left: xTip + pointyOffset, top:yTip + 24});
    bubblePointy.show();
}

// simply hide the tip
function hideToolTipBubble() {    
    var bubbleDiv = $("div[@id=bubbleContainer]");
    var bubblePointy = $("div[@id=bubblePointyBit]");
    bubbleDiv.hide();
    bubblePointy.hide();
}

// Report a object
function reportObject(entityType, entityID, blockingObject) {
    // Extract and validate form input
    var theData = "type=" + entityType + "&id=" + entityID;
    var fParentID = blockingObject;
    ajaxCall("reportobject", 
             theData,
             function(theResult){
                if(theResult.result == "success"){
                    tb_remove();
                    OSOYouAlert("OSOYOU Message", "The content was reported to our Team. Thanks for using OSOYOU!", null,null,null, 5000);
                }
                else if(theResult.result == "failure")
                {   
                    OSOYouAlert("OSOYOU Message", "An error occurred reporting the content. Please try again.");                
                }
                return;               
             }
             ,fParentID);  
}