﻿// timer thread for displaying ajax messages
//var ajaxTimerId;

/**
* The page which calls this function should have a div element that has the id "contentLodaing" which shall be used
* by this function to inform the user of the progress of the bookmark saving process.
*               
*
*@a                   :hyper link element that contains the href value for the ajax call for bookmarking
*@newcat              :string/text for new category name, pass NULL or undefined if you are not creating a new category
*@bookmarkCategoryId  :the ID of the category/folder from the select option drop down list, not the "name" of the folder,
*                      pass an empty string i.e. "" if the bookmark is not being added to a currently existing folder/category
**/
function submitBookmark(a, newcat, bookmarkCategoryId, contentLoadingDiv, addToMyHomepage) {
    saveBookmark(a, newcat, bookmarkCategoryId, null, null, null, null, contentLoadingDiv, addToMyHomepage);
    return false;
}

/**
 * saves the best match with the provided detailds
 */
function saveBestMatch(aObj, newcat, selectCategoryId, bookmarkTitle, bookmarkDescription, contentLoadingDiv) {   
    saveBookmark(aObj, newcat, selectCategoryId, null, bookmarkTitle, bookmarkDescription, null, contentLoadingDiv);
    return false;
}

/**
* saves a bookmark
*
*@a                    :hyper link element that contains the href value for the ajax call
*                       for bookmarking
*@newcat               :string/text for new category name, pass NULL or undefined 
*                       if you are not creating a new category
*@bookmarkCategoryId   :the ID of the category/folder from the select option drop down list,
*                       not the "name" of the folder but it's id from the db,
*                       pass an empty string i.e. "" if the bookmark is not being added to a 
*                       currently existing folder/category, i.e.
*                       a new folder is being created.
*@bookmarkName         :in cases where the bookmark is being given to the bookmark before 
*                       it is saved, this is the case for when there is a best match
*@bookmarkTitle        :this value should exist as part of the href value of the anchor tag, 
*                       however in cases where it doesn't exist or the user wants to assign
*                       the title this parameter should be populated.
*@bookmarkDescription  :the bookmark description to be saved for the bookmark.
*                       This paramter can be null as the bookmark description
*                       should exist in the href attribute of the add bookmark
*@bookmarkType         :this entry should exist in the add bookmark link href 
*                       however it is possible to change this. Leave it as null to take 
*                       the default from the anchor tag href attribute.
*@contentLoadingDiv    :if a div object is passed to this function then it will be used for 
*                       informing the user of the progress of bookmarking.
*                       it can be left as null, in which case
*                       no messages will be displayed to the user.
*@addToMyHomepage      :true or false. Determines whether the newly saved item will be
*                       added to the user's homepage
**/
function saveBookmark(a, newcat, bookmarkCategoryId, bookmarkName, bookmarkTitle, bookmarkDescription, bookmarkType, contentLoadingDiv, addToMyHomepage) {

    //clearInterval(ajaxTimerId);
    if (document.getElementById("contentLoading")) {
        document.getElementById("contentLoading").style.backgroundColor = '';
        document.getElementById("contentLoading").innerHTML = strGlobalLoading + getCloserLink();
        document.getElementById("contentLoading").style.visibility = 'visible';
        document.getElementById("contentLoading").style.display = '';
    }
    if (contentLoadingDiv) {
        //contentLoadingDiv.style.backgroundColor = '#ffffe1';
        contentLoadingDiv.innerHTML = strGlobalLoading;  //+ getCloserLink();
        contentLoadingDiv.style.visibility = 'visible';
        //contentLoadingDiv.style.display = '';
    }
    
    var bookmarkCategory = document.getElementById(bookmarkCategoryId);
    if (bookmarkCategory) {
        var cat = bookmarkCategory.options[bookmarkCategory.selectedIndex].value;
    }

    if(bookmarkName && bookmarkTitle && bookmarkDescription && bookmarkType) {
        
        bookmarkDescription = encodeIllegalChars(bookmarkDescription);
        bookmarkTitle = encodeIllegalChars(bookmarkTitle);
        bookmarkName = encodeIllegalChars(bookmarkName);
        bookmarkType = encodeIllegalChars(bookmarkType);        
        cat = encodeIllegalChars(cat);
        newcat = encodeIllegalChars(newcat);
        
        //used for edit bookmark
        jQuery.get(a.href, { 'f': (newcat ? newcat : ''), 
                             'fid': cat,
                             'n':bookmarkName,
                             't':bookmarkTitle,
                             'd':bookmarkDescription,
                             'bt':bookmarkType,
                             r: Math.floor(Math.random() * 999999) },
                             ajaxInform);
     }
     //used for best match bookmarking
     else if (bookmarkTitle && (bookmarkDescription != null)) {
    bookmarkDescription = encodeIllegalChars(bookmarkDescription);
    bookmarkTitle = encodeIllegalChars(bookmarkTitle);
    cat = encodeIllegalChars(cat);
    newcat = encodeIllegalChars(newcat);
        // used for best match
        jQuery.get(a.href, { 'f': (newcat ? newcat : ''), 
                             'fid': cat,
                             't':bookmarkTitle,
                             'd':bookmarkDescription,
                             r: Math.floor(Math.random() * 999999) },
                             function(data) { ajaxInform(data, contentLoadingDiv); });
    }
    else {
        //used for adding bookmarks from search results

        // hides all add bookmark buttons because .net engine seems to cut off
        // the process of adding a new bookmark when another request comes in
        //TODO: FIXME: fix this on the server side
        //$(".jsAddBookmark").each(function() { this.style.display = 'none'; });
        $(".jsAddBookmark").each(function() { this.style.visibility = 'hidden'; });

        //cat = encodeIllegalChars(cat);
        //newcat = encodeIllegalChars(newcat);

        jQuery.get(a.href, { 'f': (newcat ? newcat : '')
                            , 'fid': cat
                            , 'h': (addToMyHomepage) ? '1' : '0'
                            , r: Math.floor(Math.random() * 999999) },
            function(data) { ajaxInform(data, contentLoadingDiv); });
    }
    return false;
}

/**
* TODO: test for more characters and the consequence they might have on application functionality.
* This function is supposed to get rid of any characters that cause a problem, however
* we don't want to url encode everything, so we will not use escape(), encodeURI, encodeURIComponent
* functions in javascript.
*
**/
function encodeIllegalChars(dodgyText) {
    if (dodgyText) {
        dodgyText = dodgyText.replace(/&/, '%26');
        return dodgyText; //not dodgy anymore
    }
    return dodgyText;
}


/**
 *
 * ajax callback function
 *
 */
function ajaxInform(data, contentLoadingDiv) {
    var ajaxMsgContainer = document.getElementById("contentLoading");

    if (data.indexOf("<mhp>login</mhp>") > -1 ) {
        if (confirm(strGlobalYouAreLoggedOut)) {
            loginRequired(); //redirects user to the login page.
        }
    }
    else if (data.indexOf("<mhp>1</mhp>") > -1) {
        if (ajaxMsgContainer) {
            ajaxMsgContainer.innerHTML = '<span>' + strGlobalSavedSuccessfully + '</span>'+ getCloserLink();
            showAjaxMessage(ajaxMsgContainer, 5000);
        }
        if (contentLoadingDiv) {
            contentLoadingDiv.innerHTML = '<span>' + strGlobalSavedSuccessfully + '</span>'; // + getCloserLink();            
            showAjaxMessage2(contentLoadingDiv.id, 5000);
        }
    }
    else if (data.indexOf("<mhp>0</mhp>") > -1) {
        if (ajaxMsgContainer) {
            document.getElementById("contentLoading").innerHTML = strGlobalSaveFailed + getCloserLink();
            showAjaxMessage(ajaxMsgContainer, 10000);
        }
        if (contentLoadingDiv) {
            contentLoadingDiv.innerHTML = strGlobalSaveFailed;  //+ getCloserLink();
            showAjaxMessage2(contentLoadingDiv.id, 10000);
        }
    }
    else {
        //document.getElementById("contentLoading").innerHTML = "Error: Savinging bookmark failed. (" + data + ")" + closeLink;
        if (ajaxMsgContainer) {
            document.getElementById("contentLoading").innerHTML = strGlobalSavingBookmarkFailed + getCloserLink();
            showAjaxMessage(ajaxMsgContainer, 60000);
        }
        if (contentLoadingDiv) {
            contentLoadingDiv.innerHTML = strGlobalSavingBookmarkFailed;  //+ getCloserLink();
            showAjaxMessage2(contentLoadingDiv.id, 60000);
        }
    }
    
    // makes add bookmark buttons re-appear after a bookmarking process has finished.
    //$(".jsAddBookmark").each(function() { this.style.display = ''; });
    $(".jsAddBookmark").each(function() { this.style.visibility = 'visible'; });
    
    return false;
}


/**
*
* Shows the ajax message at the top of the search page(bookmark-find-new)
* TODO: remove this function as it is no longer used
**/
function showAjaxMessage(ajaxMsgContainer, delayMilliSeconds) {
    document.getElementById("contentLoading").style.visibility = 'visible';
    //ajaxTimerId = setTimeout("document.getElementById('contentLoading').style.visibility='hidden';", delayMilliSeconds);
    return false;
}

/**
 *
 * Shows the ajax message next to the add bookmark button on the search page(bookmark-find-new)
 *
**/
function showAjaxMessage2(contentLoadingDivId, delayMilliSeconds) {
    document.getElementById(contentLoadingDivId).style.visibility = 'visible';
    //document.getElementById(contentLoadingDivId).style.display = '';
    return false;
}


/**
 * returns a string which says "close this" or something similar
**/
function getCloserLink(){
return strGlobalCloseMessage;
}

// If the control "field" has the given matchText, it will be changed to the swap text and its color changed to sTextColor
// use as follows
//  onfocus="swapInputText(this,'enter your email','','#0000');"
//  onblur = "swapInputText(this,'','enter your email','#999');"
// to have a text box with default text that clear when clicked and rests if left blank
function swapInputText(field,matchText, swapText,sTextColor ) {
if (field.value == matchText) {
field.value = swapText;
field.style.color = sTextColor;
}
}

/** 
* this is a utility functions,
* to deal with the differences in xml processing of the browsers
* returns the next sibling of "thisElement" parameter which is of type "siblingTag"
* @siblingTag  refers to the name of the html tag e.g. input, a, div,...
**/
function getNextSibling(thisElement, siblingTag) {
    var el = thisElement.nextSibling;
    while (el && el.nodeName != siblingTag && el.nodeName != siblingTag.toUpperCase()) {
        el = el.nextSibling;
    }
    return el;
}



/**
* Sends an ajax request to the server to set the state of a message/info box,
* i.e. whether the info boxes at the top of the screen should be minimized/close/shown
*
* @name    this is the name of the message box div
* @value   this is the state of the message box - show/close/minimize
* @trigger the element being clicked on. i.e. the anchor tag
**/
function setMessageState(name, value, trigger) {
    
    if (value == 'close') {
        document.getElementById(name).style.display = 'none';
        jQuery.get("ajax-user-preference.aspx", { 'n': name, 'v': value, r: Math.floor(Math.random() * 999999) });
    }
    if (value == 'minimize') {
        if (document.getElementById(name).style.height == '14px') {
            document.getElementById(name).style.height = '';
            trigger.getElementsByTagName('img')[0].src = '../images/icons/minus.png';
            jQuery.get("ajax-user-preference.aspx", { 'n': name, 'v': "show", r: Math.floor(Math.random() * 999999) });
        }
        else {
            document.getElementById(name).style.height = '14px';
            trigger.getElementsByTagName('img')[0].src = '../images/icons/plus.png';
            jQuery.get("ajax-user-preference.aspx", { 'n': name, 'v': value, r: Math.floor(Math.random() * 999999) });
        }
        // TODO: use bg img for the hyperlink instead of child img element
        // TODO: use jQuery to: slide collapse the div for better animation effect or use something similar to the accordion
    }
}



