/*Make an AJAX call to fetch the HTML for the specified RSS feed and
 pass the HTML string to the provided rssHandlerFunction.

 @param rssUrl             url of the rss feed to fetch
 @param rssTitle           title to be used for the rss feed in the resulting HTML
 @param pageId             Page this function is being called from
 @param pageModuleId       Page Module this function is being called from
 @param moduleName         name of the JAZD page module in which the HTML is to be
 displayed
 @param contentSetId       the RSS ContentSet being displayed
 @param contentSetTypeId   the type of RSS ContentSet being displayed
 @param template           name of the .ftl template to be used to render HTML from
 the rss feed data
 @param page               page index to be requested in the paged list of RSS entries
 @param pageSize           number of rss items to be included per page in the HTML
 @param link_target        value for rss item anchor 'target' attributes
 @param link_context       'external' to render rss item anchors urls as provided in
 the feed, 'internal' to render them inside of the
 template.htm iframe
 @param previewMode        0 = false, 1 = true
 @param rssHandlerFunction reference to Javascript function to be called to
 handle the resulting HTML text
 @param categoryPath       the current directory category path if any
 */
function getRssFeed(feedObject) {
    new Ajax.Request(global_server_root + '/rss.htm',
    {
        method:'get',
        parameters: {
            feed: feedObject.rssUrl,
            feedName: feedObject.rssTitle,
            pageId: feedObject.pageIdentifier,
            pageModuleId: feedObject.moduleId,
            moduleName: feedObject.module,
            contentSetId: feedObject.contentSetIdentifier,
            contentSetTypeId: feedObject.contentSetTypeIdentifier,
            template: feedObject.ftlName,
            page: feedObject.pageNo,
            page_size: feedObject.pageSizeLimit,
            linkTarget: feedObject.link_target,
            linkContext: feedObject.link_context,
            previewMode: feedObject.preview,
            categoryPath: feedObject.categoryPath
        },
        onSuccess: function(response) {
            /* for some reason response text is not empty, hence checking it for length.
             * Tried trimming the string, but it left the call in unterminated loop */
            if (response.responseText.length > 2) {
                triPagerRssHandler(feedObject.module, response.responseText);
                successHandler();
            } else {
                /* if there is no responsetext(no feed content), it means the ajax call
                returned an exception(IO Exception, FeedException, FetcherException, etc..).
                so call the failureHandler in module_features_html.ftl to show partner rss. */
                failureHandler(true, feedObject.contentSetTypeIdentifier);
            }
        },
        onFailure: function() {
        }
    });
}

/*
 getRssFeed callback function for module_features_html.ftl. Displays
 RSS HTML in the div having the provided moduleName.

 @param moduleName name of the JAZD page module in which the HTML is to be
 displayed
 @param rssString  the HTML returned for the rss feed by the server
 */
function triPagerRssHandler(moduleName, rssString) {
    // Update the content HTML
    var moduleDiv = document.getElementById(moduleName);
    moduleDiv.innerHTML = rssString;

    // Find how many pages of data were returned
    var i = 1;
    for (; ; i++) {
        if (document.getElementById(moduleName + '_' + i) == null) {
            break;
        }
    }

    // Update the pager HTML
    if (i > 1) {
        $(moduleName + '_pager').innerHTML = tripager_html(moduleName, i - 1);
    }
}


/*
 Log user clicks on a url of interest.

 @param pageId PG_PAGE_TBL.PAGE_ID of the referring page
 @param pageModuleId PG_PAGE_MODULE_ID of the referring page's module that contained the clicked url
 @param clickTypeId REF_CLICK_TYPE_TBL.CLICK_TYPE_ID
 @param impressionTypeId REF_IMPRESSION_TYPE_TBL.IMPRESSION_TYPE_ID - the type of object clicked on
 @param objectId database identifier of the object clicked on
 @param referringUrl the url which referred
 @param categoryPath the category context path
 @param targetUrl the url clicked on
 @param referringUrl the url which referred
 */
function logClick(pageId,
                  pageModuleId,
                  clickTypeId,
                  impressionTypeId,
                  objectId,
                  categoryPath,
                  targetUrl,
                  referringUrl) {
    new Ajax.Request(global_server_root + '/lg/logClick.htm',
    {
        method:'put',
        parameters: {
            pageId: pageId,
            pageModuleId: pageModuleId,
            clickTypeId: clickTypeId,
            impressionTypeId: impressionTypeId,
            objectId: objectId,
            categoryPath: categoryPath,
            targetUrl: targetUrl,
            referringUrl: referringUrl
        },
        onFailure: function() {
            alert('Something went wrong... (Log Click)');
        }
    });
}

/*
 Create a LEAD_TBL record in the database.

 @param pageId PG_PAGE_TBL.PAGE_ID of the referring page
 @param pageModuleId PG_PAGE_MODULE_ID of the referring page's module that contained the clicked url
 @param leadTypeId REF_LEAD_TYPE_TBL.LEAD_TYPE_ID
 @param objectId database identifier of the object clicked on
 @param tableId REF_TABLE_TBL.TABLE_ID - identifier of the database table in which objectId is stored
 @param targetUrl the url clicked on
 @param referringUrl the url which referred
 */

function logLead(pageId,
                 pageModuleId,
                 leadTypeId,
                 objectId,
                 tableId,
                 targetUrl,
                 referringUrl) {
    new Ajax.Request(global_server_root + '/lg/logLead.htm',
    {
        method:'put',
        parameters: {
            pageId: pageId,
            pageModuleId: pageModuleId,
            leadTypeId: leadTypeId,
            objectId: objectId,
            tableId: tableId,
            targetUrl: targetUrl,
            referringUrl: referringUrl
        },
        onFailure: function() {
            alert('Something went wrong... (Log Lead)');
        }
    });
}

/*
 Create an entry in jazd-module-impressions.log recording a list
 of items that were viewed by a User in a page module.

 @param pageId PG_PAGE_TBL.PAGE_ID of the page containing impression objects
 @param pageModuleId PG_PAGE_MODULE_ID of the page module containing impression
 @param pageViewId universally unique identifier of the current page view event
 @param impressionTypeId the ImpressionType of the Impression Object identifiers
 @param objectIds comma separated String containing database identifiers of the Objects
 for which impressions are to be recorded
 */
function logImpressions(pageId,
                        pageModuleId,
                        pageViewId,
                        impressionTypeId,
                        objectIds) {
    new Ajax.Request(global_server_root + '/lg/logModuleImpressions.htm',
    {
        method:'put',
        parameters: {
            pageId: pageId,
            pageModuleId: pageModuleId,
            pageViewId: pageViewId,
            impressionTypeId: impressionTypeId,
            objectIds: objectIds
        },
        onFailure: function() {
            alert('Something went wrong... (Log Impressions)');
        }
    });
}

// function to validate whether search parameter is entered to perform search
function validateSearch(searchElement) {
    if (searchElement.value.replace(/^\s*/, "").replace(/\s*$/, "") == '') {
        alert("Please enter a value in the search field to continue.");
        return false;
    }
    return true;
}

var forgotEnabled, loginControllerUrl;
var loginForm;

$(document).ready(function() {
    loginForm = $('#login_form')[0];

    $('#loginButton').click(function() {
        doLogin();
    });
    $('#forgotButton').click(function() {
        doLogin();
    });

    $("#login_form").submit(function() {
        doLogin();
        return false;
    });

    $('#loginButton').blur(function() {
        $(loginForm['email']).focus();
    });

    $(loginForm['email']).keypress(function(e) {
        handleLoginEnterKey(e);
    });
    $(loginForm['password']).keypress(function(e) {
        handleLoginEnterKey(e);
    });

    //Fix for Empty RSS feeds. If Rss feed doesn't contain content it will be hided.
    //TODO The RSS HTML modules should be refactored to avoid paste/copy.  
    $("div:contains('No Rss Feeds available')").parent("td").parent("tr").parent("tbody").parent("table").parent("td").parent("tr").hide();
});

function handleLoginEnterKey(e) {
    if (e.which == 13) {
        doLogin();
    }
}

function commonLoginInit(leadGen, forgot) {
    clearAll();
    forgotEnabled = false;
    if (leadGen) {
        $('#popup_login_title').show();
    } else {
        if (forgot) {
            $('#popup_login_title').text('Forgot Password');
        } else {
            $('#popup_login_title').text('Login');
        }
        $('#popup_login_title').show();
    }
    $('#login_form').find('#login_only').show();
    $('#login_form').find('#forgot_only').hide();
    loginControllerUrl = global_server_root + '/user/login.htm';

    setTimeout("$(loginForm['email']).focus()", 250);
}

function displayLogin() {
    commonLoginInit(false, false);
}

function forgotPasswordSetup() {
    clearLoginErrors();
    commonLoginInit(false, true);
    $('#login_form').find('#forgot_only').show();
    $('#login_form').find('#login_only').hide();
    loginControllerUrl = global_server_root + '/user/forgotPassword.htm';
    forgotEnabled = true;
}

function popupLoginHide() {
    $('#popup_login').popup().data('popup').close();
}

function doLogin() {
    clearLoginErrors();

    $('#login_form').attr('href', window.location.href);

    $.ajax({
        url: loginControllerUrl,
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: $('#login_form').serialize() + '&href=' + window.location.href,
        success: function(data) {
            if (data.result == "success") {
                if (!forgotEnabled) {
                    window.location = global_reload_url;
                } else {
                    alert('Password has been reset.  A new password has been emailed to you');
                }
                popupLoginHide();
            } else if (data.result == "error") {
                var error = data.error;
                if (error.field != "") {
                    $('div#lgn_' + error.field + 'Error').text(error.message);
                } else {
                    $('div#loginErrorMessage').text(error.message);
                    $('div#loginError').show();
                }
            } else if (data.result == "validation") {
                if (!forgotEnabled) {
                    if (data.validation['cookies']) {
                        $('div#lgn_caption').text(data.validation['cookies']);
                    } else {
                        $('div#lgn_caption').text("Please enter a valid email address and your password to continue.");
                    }
                } else {
                    if (data.validation['cookies']) {
                        $('div#lgn_caption').text(data.validation['cookies']);
                    } else {
                        $('div#lgn_caption').text("Please enter a valid email address to continue.");
                    }
                }
            } else {
                alert('Something went wrong... (doLogin)');
            }
        },
        failure: function() {
            alert('Something went wrong... (doLogin)');
        }
    });
}

function clearAll() {
    clearLoginErrors();
    clearEmail();
}

function clearLoginErrors() {
    $('div#popup_login').find('div.validation-error').text('');
    $('div#loginError').hide();
}

function clearEmail() {
    var email = $('div#popup_login').find(':input=email');
    email.val('');
}

<!-- Login and registration popup jquery scripts. -->
var loginPopup, regPopup;
$('document').ready(function() {
    loginPopup = $('#popup_login').popup({
        width: '200px',
        height: ''
    });
    $('#link_login').click(function() {
        loginPopup.removeClass('hiddenDiv');
        displayLogin();
        loginPopup.data('popup').open();
        return false;
    });
    $('#leadgen_login_link').click(function() {
        loginPopup.removeClass('hiddenDiv');
        displayLogin();
        loginPopup.data('popup').open();
        return false;
    });

    $('.popup').css('z-index', '205');
    $($('#popup_login').parents()[5]).css('z-index', '300');
});

/* Gets the height of 'td'(table cell) - Function to make column heights in Supplier detail and product
 detail page for Categories on left and Detailed supplier/product description on center as equal.
 All it does is Calculate the height of the Center table cell and assign it as the height for the left table cell (Categories on left).
 (62 is subtracted from the contenHeight to make it equal in heights)
 This function is invoked when supplier and product detail page loads (<body onload="getTDHeight();") */
function getTDHeight() {
    var contentHeight = document.getElementById('content').offsetHeight;
    document.getElementById('categories_left').style.height = contentHeight - 62 + 'px';
}