/**
 * Override function from ajax.js
 *
 * NOTE: Overridden from ajax.js
 */
function AjaxRequest(url, args) {
    url += "&skin=purple&_t=" + new Date()+"&rand="+(Math.random()*5);
    return new Ajax.Request(url, args);
}

////////////////////////////////////////////////////////////////////////
// Check if the user is remembered. This invocation
// is kept in the inline javascript rather on page load, as we dont want to render
// the page if the user is authorized.
// Check if we know the user, rememberMe ticket
var isAuthorized = readCookie('usersession'); // to get the user session
var rememberMe = readCookie('ticket');        // to check if the user had clicked on the remember me checkbox, logout will be immune to window close event.
// check for 'ticket' and 'usersession' token, and index page(s)
if(rememberMe != null && rememberMe != 'invalid' && 
    (isAuthorized == null || isAuthorized == 'transient' || isAuthorized == 'valid')) {
    // for some reason request.getSession() does not return the
    // session instance at the first invocation, which it should
    // as an hack, invoke remember me twice, one after the other
    // currently setting the time interval to 500ms
    isUserRemembered();
    // send another isUserRemembered request after 500ms
    // this is required if its a new browser genotrope
    // session
    setTimeout('isUserRemembered()',500);
}

/**
 * Sends request to check if the user is a valid user
 */
function isUserRemembered() {
    // Setup the URL
    var url = 'loginBanner.do?isUserRemembered=check&domain=genotrope';

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // check for 'Login / Register' string
            if(transport.responseText.indexOf('Login / Register') != -1
                || trim(transport.responseText) == '') {
                // User is not authorized
                // alert("not authorized response......>"+transport.responseText+"<.....>"+transport.responseText.indexOf('Login / Register')+"<......");
            }
            else {
                // Authorized user
                //alert("loading home page.....>"+transport.responseText+"<......>"+transport.responseText.indexOf('Login / Register'));
                // is window reload required..?
                // it goes into an endless loop
                //window.location.reload();
            }
        },
        onFailure: function() {
            // Silent failure
        }
    });
}
////////////////////////////////////////////////////////////////////////

/**
 * Submit a login request.
 */
function authenticateUser() {
    var url = "login.do?submit=submit";
    url += "&username=" + document.getElementById("username").value;
    url += "&password=" + document.getElementById("password").value;
    // differentiator between the old and new site
    url += "&domain=genotrope";
    // Update the remember me to valid value
    url += "&rememberMe="+document.getElementById("rememberMe").checked;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if ("close" == transport.responseText) {
                // set cookie for normal user
                createCookie('usertype','standard',1);
                // forward to the home page
                navigatePage('HOME_PAGE');
            }
            else if ("closeManager" == transport.responseText) {
                //alert('You are a Hiring Manager !');
                // set cookie for Hiring Manager
                createCookie('usertype','manager',1);
                // forward to the home page
                navigatePage('HOME_PAGE');
            }
            else if("closeAdmin" == transport.responseText) {
                // set cookie for admin user
                createCookie('usertype','admin',1);
                // forward to the home page
                navigatePage('HOME_PAGE');
            }
            else if("suspended" == transport.responseText) {
                var el = document.getElementById('message');
                if (el) {
                    el.innerHTML = "<label class='errorsmalltext' valign='top'>Account has been temporarily suspended. Please contact administrator.</label>";
                    focus('username');
                }
            }
            else {
                var el = document.getElementById('message');

                if (el) {
                    el.innerHTML = "<label class='errorsmalltext' valign='top'>Email and password do not match.</label>&nbsp;&nbsp;<a onClick='resetPassword();' class='underlined'>Reset</a><label class='errorsmalltext'> your password.</label>";
                    focus('username');
                }
            }
        },
        onFailure: function() {
            alert("Can't login... try again later");
        }
    });
    return false;
}

/**
 * Logout
 */
function signOutUser() {
    // Setup the URL
    var url = 'logout.do?_d=d';
    // as cookie takes some time to be deleted, put invalid entry
    createCookie('usertype','invalid',1);

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // erase the usertype cookie
            eraseCookie('usertype');
            navigatePage('HOME_PAGE');
        },
        onFailure: function(transport) {
            // IE does not handle the NO Content response
            // properly, NO response of an ajax request is taken
            // as a failure with status set to 1223, instead of 204
            // & readyStateChange set to 4
            if(transport.status == 1223) {
                // erase the usertype cookie
                eraseCookie('usertype');
                // redirect to index page
                navigatePage('HOME_PAGE');
            }
            else {
                alert('Unable to logout... please try again later.')
            }
        }
    });
}

/**
 * Makes a 'SYNCHRONOUS' server request to test if the user is authenticated
 * and set appropriate cookie for the unauthenticated user
 */
function isUserAuthenticated() {
    var authorized = false;
    var url = 'loginBanner.do?_d=d&domain=genotrope';
    // synchronized server request
    var ajaxRequest = new AjaxRequest(url, {
        method:'get',
        asynchronous: false
    });
    // get response
    var response = trim(ajaxRequest.transport.responseText);
    if(response.indexOf('Login / Register') != -1 || trim(response) == '') {
        // check for a valid ticket
        var ticket = readCookie('ticket');
        if(ticket != null && ticket != '' && ticket != 'invalid') {
            // we've a valid ticket, so try once more
            // synchronized server request
            var ajaxRequest = new AjaxRequest(url, {
                method:'get',
                asynchronous: false
            });
            // get response
            var response = trim(ajaxRequest.transport.responseText);
            if(response.indexOf('Login / Register') != -1 || trim(response) == '') {
                // found 'Login / Register'. So the user is not unauthorized.
                // as cookie takes some time to be deleted, put invalid entry
                createCookie('usertype','invalid',1);
                // go to home page, only for the pages
                // that mandate user authentication
                if(getPageToken() == 'PROFILE_LIST' || getPageToken() == 'TALENT_TARGET' ||
                    getPageToken() == 'HIT_LIST' || getPageToken() == 'COMP_GRAPH') {
                    navigatePage('HOME_PAGE');
                }
            }
            else {
                // the user is authorized.
                authorized = true;
            }
        }
        else {
            // found 'Login / Register'. So the user is not unauthorized.
            // as cookie takes some time to be deleted, put invalid entry
            createCookie('usertype','invalid',1);
            // go to home page, only for the pages
            // that mandate user authentication
            if(getPageToken() == 'PROFILE_LIST' || getPageToken() == 'TALENT_TARGET' ||
                getPageToken() == 'HIT_LIST' || getPageToken() == 'COMP_GRAPH') {
                navigatePage('HOME_PAGE');
            }
        }
    }
    else {
        // the user is authorized.
        authorized = true;
    }

    return authorized;
}

/**
 * Makes a server request to render login banner for
 * authenticated users. If the user has selected to
 * be rememebered, a keep alive request will also
 * happen every 'n' seconds, 'n' being session time.
 * Any failure will lead to redirection to home page.
 */
function getLoginBanner() {
    var el = document.getElementById('LOGIN');
    if(el) {
        var url = 'loginBanner.do?_d=d&domain=genotrope';
        new AjaxRequest(url, {
            method:'get',
            onSuccess:function(transport) {
                if(transport.responseText.indexOf('Login / Register') != -1
                    || trim(transport.responseText) == '') {
                    // error condition
                    // do nothing
                }
                else {
                    // so render authorized header
                    el.innerHTML = trim(transport.responseText) + "&nbsp;!";
                    // check for remember me
                    var ticket = readCookie('ticket');
                    if(ticket != null && ticket != '' && ticket != 'invalid') {
                        // cookie found, schedule a request before session time out
                        setTimeout('keepAliveRequest()', sessionTimeout);
                    }
                }
            },
            onFailure: function(transport) {
                // as cookie takes some time to be deleted, put invalid entry
                createCookie('usertype','invalid',1);
                // Server side error. Redirect to index page
                navigatePage('HOME_PAGE');
            }
        });
    }
}

/**
 * Function to make a server side request to keep
 * the user session alive, if the user has checked
 * 'remember me' option while login.
 */
function keepAliveRequest() {
    var url = 'loginBanner.do?_d=d&domain=genotrope';
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // do nothing
        },
        onFailure: function(transport) {
            // do nothing
        }
    });
    // start all over again
    setTimeout('keepAliveRequest()', sessionTimeout);
}

/**
 * Set current company in session
 */
function setCurrentCompany(guid) {
    var url = "simpleValue.do?name=currentCompanyGuid&value=" + guid;

    // Make the request.
    new AjaxRequest(url, {
        method: 'get',
        onSuccess: function(transport) {
            loadCompany2(null, guid, false);
            // render generate button
            renderGenerateButton(guid);
        },
        onFailure: function() {
            // silent failure.
        }
    });
}

/**
 * Load the company details for which user has license
 */
function loadLicensedCompany() {
    // prepare url
    var url = "license.do?_d=d&action=licensedCompany";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(transport.responseText != null && trim(transport.responseText) != "") {
                // load company profile
                loadCompany2(null, trim(transport.responseText), false);
                // load hiring target companies
                loadWatchList();
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Method to render client companies
 */
function loadClientCompanies() {
    var el = getElementAndWait('clientCompanies');
    if (el) {
        // prepare url
        var url = "clientcompanies.do?_d=d";

        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                el.innerHTML = transport.responseText;
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
}

/**
 * Load the list of recent postings
 */
function loadRecentPostings() {
    // prepare url
    var url = "posting.do?_d=d&recent=true";

    var el = getElementAndWait('recentPostingContainer');
    if(el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "") {
                    el.innerHTML = trim(transport.responseText);
                }
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
}

/**
 * Get similar postings, postings similar
 * to the category of the posting id specified.
 */
function loadSimilarPostings(postingId) {
    var similarPostings = getElementAndWait('similarPostings');
    if(similarPostings) {
        if(postingId) {
            // request to fetch similar postings
            // prepare url
            var url = "posting.do?_d=d&action=similarPostings&guid="+postingId;
            // Make the request
            new AjaxRequest(url, {
                method:'get',
                onSuccess: function(transport) {
                    if(transport.responseText != null && trim(transport.responseText) != "" && trim(transport.responseText) != '{[]}') {
                        similarPostings.innerHTML = getPostingHTML(eval(transport.responseText), true);
                    }
                    else {
                        similarPostings.innerHTML = "&nbsp;";
                    }
                },
                onFailure: function() {
                    // silent failure
                    similarPostings.innerHTML = "&nbsp;";
                }
            });
        }
        else {
          // this should never happen !!
          similarPostings.innerHTML = "&nbsp;";
        }
    }
}

/**
 * Get additional postings, postings that
 * belong to the sponsoring companies
 */
function loadSponsoredPostings() {
    var sponsoredPostings = getElementAndWait('sponsoredPostings');
    if(sponsoredPostings) {
        // request to fetch similar postings
        // prepare url
        var url = "posting.do?_d=d&action=sponsoredPostings";
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "" && trim(transport.responseText) != '{[]}') {
                    sponsoredPostings.innerHTML = getPostingHTML(eval(transport.responseText), true);
                }
                else {
                    sponsoredPostings.innerHTML = "&nbsp;";
                }
            },
            onFailure: function() {
                // silent failure
                sponsoredPostings.innerHTML = "&nbsp;";
            }
        });
    }
}

/**
 * Load the list of postings for the company
 * guid in session
 */
function loadCompanyPostings() {
    // prepare url
    var url = "posting.do?_d=d";

    var el = getElementAndWait('JOB_POSTINGS');
    if(el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "") {
                    el.innerHTML = trim(transport.responseText);
                }
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
}

/**
 * Load the list of postings for a given company
 * and render all except the one whose guid is specified
 */
function loadOtherPostingsForCompany(companyGuid, postingGuid) {
    var message = "<br /><br /> <center class='smallnormaltext'>No more postings for the company</center>";
    // prepare url
    var url = "posting.do?_d=d&format=JSON&companyGuid="+companyGuid+"&postingGuid="+postingGuid;
    var el = getElementAndWait('otherPostings');
    if(el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "" && trim(transport.responseText) != '{[]}') {
                    el.innerHTML = getPostingHTML(eval(transport.responseText), false);
                }
                else {
                    el.innerHTML = message;
                }
            },
            onFailure: function() {
                // silent failure
                el.innerHTML = message;
            }
        });
    }
}

/**
 * Load top scorers
 */
function loadTopScorers() {
    // prepare url
    var url = "loginBanner.do?topScorers=_d";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            renderCredits(transport.responseText);
        },
        onFailure: function(transport) {
            // silent failure
        }
    });
}

/**
 * Check if help is to be shown on page specified
 */
function loadGettingStarted(helpDialog) {
    // Setup the URL
    var url = 'loginBanner.do?helpDialog='+helpDialog;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // check for value
            if(transport.responseText.indexOf('true') > -1) {
                // show help
                renderGettingStarted();
            }
            else {
                // do nothing
            }
        },
        onFailure: function(transport) {
            // silent failure
        }
    });
}

/**
 * Method to load home page components
 */
function loadHomePage() {
    var newCompanies = getElementAndWait('NEW_COMPANIES');
    var articlesAndCareers = getElementAndWait('ARTICLES_AND_CAREERS');

    // prepare url to get articles and postings
    var url = "homePage.do?_d=d";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var homePageContent = trim(transport.responseText);
            if(homePageContent != '') {
                var homePageArray = homePageContent.split("[,,,...,,,]");
                if(isManager() || isAdministrator()) {
                    var companyJSON = eval(homePageArray[1]);
                    if(newCompanies) {
                        newCompanies.innerHTML = getCompanyHTML(companyJSON);
                    }
                }
                else {
                    var postingJSON = eval(homePageArray[3]);
                    if(newCompanies) {
                        newCompanies.innerHTML = getPostingHTML(postingJSON, true);
                    }
                }
                // for all users
                var citationsJSON = eval(homePageArray[2])
                if(articlesAndCareers) {
                    articlesAndCareers.innerHTML = getCitationsHTML(citationsJSON);
                }
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Get posting details
 */
function loadPostingDetails(guid) {
    var postingDetails = getElementAndWait('postingDetails');
    if(postingDetails) {
        // request to fetch postings
        // prepare url
        var url = "posting.do?_d=d&action=postingDetails&guid="+guid;
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "" && trim(transport.responseText) != 'empty') {
                    var postingDetailsJSON = eval(trim(transport.responseText));
                    displayPostingDetails(postingDetailsJSON);
                    // load other postings for the company
                    loadOtherPostingsForCompany(postingDetailsJSON[0].companyGuid, postingDetailsJSON[0].postingGuid);
                }
                else {
                    postingDetails.innerHTML = "&nbsp;";
                }
            },
            onFailure: function() {
                // silent failure
                postingDetails.innerHTML = "&nbsp;";
            }
        });
    }
}

/**
 * Load a company into the company panel
 */
function loadCompany2(name, guid, edit) {
    if (!guid) {
        // Updated to include date in the request for IE not to cache the request
        var url = "simpleValue.do?name=currentCompanyGuid";

        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                var guid = transport.responseText;
                if (guid) {
                    // if found
                    loadCompany2(null, guid, edit);
                }
                else {
                    // to be on safer side, clear all div
                    $('COMPANY_INFO').innerHTML = '';
                    $('COMPANY_MAP').innerHTML = '';
                    $('COMPANY_LINKS').innerHTML = '';
                    $('COMPANY_MAP2').innerHTML = '';
                    $('DELETE_BUTTON').innerHTML = '';
                }
            },
            onFailure: function() {
                // silent failure.
            }
        });
        return;
    }

    if (!name) {
        // Updated to include date in the request for IE not to cache the request
        var url = "simpleValue.do?name=currentCompanyName";

        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                var name = transport.responseText;
                if (name) {
                    loadCompany2(name, guid, edit);
                }
            },
            onFailure: function() {
                // silent failure.
            }
        });
        return;
    }

    // Clear the content.
    var el = document.getElementById('COMPANY_INFO');
    if (el) {
        el.innerHTML = '';
    }

    currentCompanyGuid = guid;
    var url = "viewCompany.do?guid="+guid;

    var el = document.getElementById('COMPANIES');
    if (el) {
        el.innerHTML = name;
    }

    if (edit) {
        url += "&edit=true";
    }

    var el = getElementAndWait('COMPANY_INFO');
    if (el) {
        // confirm the visibility of the div
        el.style.visibility = 'visible';
        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                var el = document.getElementById('COMPANY_INFO');
                if (el) {
                    // get the name token
                    var tokenToReplace = /Name:/g;
                    // Set the contents of the company panel
                    /// with the linked in span.
                    el.innerHTML = transport.responseText.replace(
                        tokenToReplace, "Name:&nbsp;<span id='li' name='li' style='cursor:pointer;' title='Look for company in LinkedIn'></span>");
                    //////////////////////////////////////////////
                    // hack to avoid rendering company address
                    // link in company profile, till we get solution
                    if(getPageToken().indexOf("COMPANY_PROFILE") > -1) {
                        var mapLink = document.getElementById("mapLink");
                        if(mapLink) {
                            var companyAddress = mapLink.innerHTML;
                            var parent = mapLink.parentNode;
                            parent.innerHTML = companyAddress;
                        }
                    }
                    // hack to render tell a friend link
                    if(getPageToken().indexOf("COMPANY_PROFILE") == -1) {
                        var tellAFriend = document.getElementById("TELL_A_FRIEND");
                        // for standard users
                        if(tellAFriend && isAuthorized()) {
                            tellAFriend.innerHTML = "<div id='mailButton' onmouseover='displayHint(\"tellFriend\")' onmouseout='displayHint(\"0\");' title='Tell a Friend' onclick='showFriendForm(\""+guid+"\", \""+name+"\");' />";
                        }
                    }
                    //////////////////////////////////////////////
                    // redner official url
                    renderOfficialURL();
                    // redner watch button
                    var watchButton = document.getElementById('WATCH_BUTTON');
                    if(watchButton) {
                        // Render Watch Button
                        watchUrl = "watch.do?isWatched=" + guid;

                        // Make the request
                        new AjaxRequest(watchUrl, {
                            method:'get',
                            onSuccess: function(transport) {
                                // check for response to render buttons
                                if(transport.responseText.indexOf('n/a') > -1) {
                                    // nothing to be rendered
                                }
                                else {
                                    if(transport.responseText.indexOf('true') > -1) {
                                        // already watched. render unwatch link
                                        renderWatchButton(guid, true);
                                    }
                                    else {
                                        // Not being watched. render watch link
                                        renderWatchButton(guid, false);
                                    }
                                }
                            },
                            onFailure: function() {
                                // silent failure
                            }
                        });
                    }
                    // display span from linked in
                    var li = document.getElementById('li');
                    if(li) {
                        if(edit){
                            li.innerHTML = '';
                        }
                        else if(li.innerHTML == ''){
                            // make span visible
                            li.style.visibility = 'visible';
                            var unescapedName = unescape(name).replace(/(\+)+/g, " ");
                            if(unescapedName.indexOf('(') > -1){
                                unescapedName = trim(unescapedName.substr(0, unescapedName.indexOf('(')));
                            }
                            try {
                                // call to create popup
                                new LinkedIn.CompanyInsiderPopup("li",unescapedName);
                            }
                            catch (err) {
                                // may be the site is not up
                                // hide the linked in span
                                li.style.visibility = 'hidden';
                            }
                        }
                    }
                    // change proforma buttons to image buttons
                    var buttons = document.getElementsByTagName('button');
                    for(var i=0;i<buttons.length;i++){
                        if(buttons[i].innerHTML.indexOf('Edit') != -1) {
                            // Edit button
                            buttons[i].innerHTML = "<img src='chameleon/purpleskin/icons/edit.gif' />";
                            buttons[i].title = "Edit Company";
                            buttons[i].className = 'proforma-image-button';
                        }
                    }
                }
            },
            onFailure: function() {
                // silent failure.
            }
        });
    }

    if (!edit) {
        // load company map
        loadCompanyMap();

        var el = document.getElementById('COMPANY_MAP2');
        // confirm the visibility of the div
        el.style.visibility = 'visible';
        if (el) {
            el.innerHTML =
                "<table width='100%' cellspacing='0' cellpadding='1' border='0'><tr>" +
                "<td style='text-align: left; vertical-align: top' width='50%'><div id='companyPanel_aux_parents'/></td>" +
                "<td style='text-align: left; vertical-align: top' width='50%'><div id='companyPanel_aux_children'/></td>" +
                "</tr></table>";
        }

        var el = getElementAndWait('companyPanel_aux_children');
        if (el) {
            var url = "getCompanyChildren.do?guid="+guid;

            // Make the request.
            new AjaxRequest(url, {
                method: 'get',
                onSuccess: function(transport) {
                    // Set the contents of the company aux child panel.
                    var el = document.getElementById('companyPanel_aux_children');
                    el.innerHTML = transport.responseText;
                },
                onFailure: function() {
                    // silent failure.
                }
            });
        }

        var el = getElementAndWait('companyPanel_aux_parents');
        if (el) {
            var url = "getCompanyParents.do?guid="+guid;

            // Make the request.
            new AjaxRequest(url, {
                method: 'get',
                onSuccess: function(transport) {
                    // Set the contents of the company aux paents panel.
                    var el = document.getElementById('companyPanel_aux_parents');
                    el.innerHTML = transport.responseText;
                },
                onFailure: function() {
                    // silent failure.
                }
            });
        }

        var url = "companyLinks.do?guid="+guid;

        var el = getElementAndWait('COMPANY_LINKS');
        // confirm the visibility of the div
        el.style.visibility = 'visible';
        if (el) {
            // Make the request.
            new AjaxRequest(url, {
                method: 'get',
                onSuccess: function(transport) {
                    var el = document.getElementById('COMPANY_LINKS');
                    el.innerHTML = transport.responseText;
                },
                onFailure: function() {
                    // silent failure.
                }
            });
        }

        var url = "getCompanyLocations.do?guid="+guid;

        var el = getElementAndWait('COMPANY_LOCATIONS');
        if (el) {
            // Make the request.
            new AjaxRequest(url, {
                method: 'get',
                onSuccess: function(transport) {
                    var el = document.getElementById('COMPANY_LOCATIONS');
                    el.innerHTML = transport.responseText;
                },
                onFailure: function() {
                    // silent failure.
                }
            });
        }
        // set document title
        if(trim(name) != '')
            document.title = name;

        // load postings for the company
        loadCompanyPostings();
    }
    return false;
}

/**
 * Submit a proforma form.
 */
function submitCompany(id, correlationIdentifier) {
    // check for blank company name
    var guid = "";
    var search = window.location.search+"";
    if(search != null && trim(search) != '' && (search.indexOf("guid=") != -1)) {
        // get guid
        guid = trim(search.split("=")[1]);
    }
    if(guid != "") {
        var companyName = document.getElementById(guid + "_name");
        if(companyName && trim(companyName.value) != "") {
            var el = document.getElementById('postalCodeError');
            if(el) {
                el.innerHTML = "&nbsp;";
                el.style.visibility = 'hidden';
            }
        }
        else {
            var el = document.getElementById('postalCodeError');
            if(el) {
                el.innerHTML = "Company name cannot be blank."
                el.style.visibility = 'visible';
                el.style.display = 'block';
            }
            return;
        }
    }
    // Setup the URL
    var url = "proformaCrud.do?correlationIdentifier=" + correlationIdentifier + "&" + Form.serialize($(id));

    // Make the request.
    new AjaxRequest(url, {
        method: 'get',
        onSuccess: function(transport) {
            loadCompany2(null,null,false);
            updateCredits = true;
        },
        onFailure: function(transport) {
            // IE does not handle the NO Content response
            // properly, NO response of an ajax request is taken
            // as a failure with status set to 1223, instead of 204
            // & readyStateChange set to 4
            if(transport.status == 1223) {
                loadCompany2(null,null,false);
                updateCredits = true;
            }
            else
            {
                alert('Unable to update record, try again later.')
            }

        }
    });
}

function editCompany(id) {
    loadCompany2(null,null,true);
}

/*
 * Cancel a proforma form.
 */
function cancelCompany(id) {
    loadCompany2(null,null,false);
}

/**
 * Deletes company
 */
function deleteCompany(guid) {
    // prepare url
    var url = "proformaCrud.do?delete=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // show appropriate message to user
            // clear all div
            $('COMPANY_INFO').innerHTML = '';
            $('COMPANY_MAP').innerHTML = '';
            $('COMPANY_LINKS').innerHTML = '';
            $('COMPANY_MAP2').innerHTML = '';
            $('COMPANIES').innerHTML = '';
            $('JOB_POSTINGS').innerHTML = '';
            document.title = "";
        },
        onFailure: function(transport) {
            alert('Unable to update record, try again later.');
        }
    });
}

/**
 * Load company graph
 * This method is for the older version of the graph
 * which doesn't accepts any parameters
 */
function loadCompanyMap() {
    var companyMap = document.getElementById('COMPANY_MAP');
    if (companyMap) {
        companyMap.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+
              'id="Graph" name="Graph" width="100%" height="100%"'+
              'codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">'+
              '  <param name="movie" value="swf/Graph.swf" />'+
              '  <param name="quality" value="high" />'+
              '  <param name="bgcolor" value="#f4f3f8" />'+
              '  <param name="allowScriptAccess" value="sameDomain" />'+
              '  <embed src="swf/Graph.swf" quality="high" bgcolor="#f4f3f8"'+
              '    width="100%" height="100%" name="Graph" id="Graph" align="middle"'+
              '    play="true" loop="false" quality="high" allowScriptAccess="sameDomain"'+
              '    type="application/x-shockwave-flash"'+
              '    pluginspage="http://www.adobe.com/go/getflashplayer">'+
              '  </embed>'+
              '</object>';
        // by pass activation process for IE
        if(isIE()) {
          fls = document.getElementsByTagName("object");
          for (var a = 0; a < fls.length; a++){
            fls[a].outerHTML = fls[a].outerHTML;
          }
        }
    }
}

/**
 * Load company graph
 * This is the newer version of the graph
 * which supports parameters to be passed
 * to render extra information
 */
function loadCompanyGraph2(companyId, divId, panellayout, clickable) {
    var companyMap = document.getElementById(divId);
    var clickfunction = '';
    if(clickable){
        clickfunction = '&click=navigateCompanyDetailsFromPostingDetails';
    }
    var flashvars = "".concat("companyId=", encodeURIComponent(companyId), "&legend=false", panellayout, clickfunction);
    if(companyMap) {
        companyMap.innerHTML = ''+
          '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+
          'id="Graph" name="Graph" width="100%" height="100%"'+
          'codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">'+
          '  <param name="movie" value="swf/tzWidget.swf" />'+
          '  <param name="quality" value="high" />'+
          '  <param name="bgcolor" value="#ffffff" />'+
          '  <param name="BorderStyle" value="1" />'+
          '  <param name="allowScriptAccess" value="always" />'+
          '  <param name="FlashVars" value="'+flashvars+'" />'+
          '  <embed src="swf/tzWidget.swf" quality="high" bgcolor="#ffffff"'+
          '    width="100%" height="100%" name="Graph" id="Graph" align="middle"'+
          '    play="true" loop="false" quality="high" border="0px" allowScriptAccess="always" FlashVars="'+flashvars+'"'+
          '    type="application/x-shockwave-flash"'+
          '    pluginspage="http://www.adobe.com/go/getflashplayer">'+
          '  </embed>'+
          '</object>' ;
    }
}

/**
 * Adds google map script dynamically to the document
 */
function loadGoogleMapScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    //script.src = "http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAqxoR6Hde6AWkNAKrw2sJIxSavlUjNwZHdmHAFhZcJf_Du39LNBSTGK_aZX9-noc1YXqqrAGCPAvnug&async=2";
    script.src = "http://maps.google.com/maps?file=api&v=2.s&key=ABQIAAAAqxoR6Hde6AWkNAKrw2sJIxR7XLAlVtCrrGCqv2QNySCAj8zB8hSHT4bEnerbegZWbf13TlyMtDlrMg&async=2";
    document.body.appendChild(script);
    mapScriptTagId = "YScriptId1";
    // hook for unload event
    window.onunload = function() {
        GUnload();
    }
}

/**
 * Fetces company brief from server and renders the same
 */
function loadCompanyOverview(companyGuid) {
    if(companyGuid) {
        var companyOverview = getElementAndWait('companyOverview');
        if(companyOverview) {
            var url = "viewCompany.do?guid="+companyGuid+"&isJSON=true";
            // Make the request
            new AjaxRequest(url, {
                method:'get',
                onSuccess: function(transport) {
                    if(transport.responseText != null && trim(transport.responseText) != "" && trim(transport.responseText) != 'empty') {
                        companyOverviewJSON = eval(trim(transport.responseText));
                        renderCompanySidePanel(companyOverviewJSON[0].companyGuid,
                            companyOverviewJSON[0].comanyName, companyOverviewJSON[0].companyIndustry,
                            companyOverviewJSON[0].companyStatus, companyOverviewJSON[0].companyAddress, 
                            companyOverviewJSON[0].companyComments, companyOverviewJSON[0].companyPrimaryURL, "");
                    }
                    else {
                        companyOverview.innerHTML = "&nbsp;";
                    }
                },
                onFailure: function() {
                    // silent failure
                    companyOverview.innerHTML = "&nbsp;";
                }
            });
        }
    }
}

/**
 * Load paginated list
 */
function loadPagedList(url) {
    var el = null;
    // if found, show loading image only for bottom div
    if(document.getElementById('LOADING_HIT_LIST') != null) {
        getElementAndWait('LOADING_HIT_LIST');
        el = document.getElementById('HIT_LIST');
    }
    else {
        el = getElementAndWait('HIT_LIST');
    }

    if (el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                var el = document.getElementById('HIT_LIST');
                if (el) {
                    el.innerHTML = transport.responseText;
                    var pagecount = document.getElementById('pageCount').value;
                    var pageNumber = document.getElementById('pageNumber').value;
                    pager = new PagerControl({
                        startPage:pageNumber,
                        pageCount: pagecount,
                        pagesToShow: 7,
                        unselectedCssClass: "spanPagerControlUnselected",
                        selectedCssClass: "spanPagerControlSelected",
                        hellipCssClass: "hellip",
                        previousPageLabel: "Previous",
                        nextPageLabel: "Next",
                        alwaysShowFirst: true,
                        alwaysShowLast: true,
                        varName: "pager",
                        targetDiv: "divPager",
                        pagedCallback: renderPageData
                    });
                }
            },
            onFailure: function() {
                document.getElementById('HIT_LIST').innerHTML =
                "<i>Error while fetching your hit list. Please try after some time or contact <a class='underlined' href='mailto:support@talentGraphz.com?subject=Hit List Error' title='mailto:support@talentGraphz.com?subject=Hit List Error'>administrator</a>.</i>";
            }
        });
    }
}

/**
 * Paged callback
 * Sends an XMLHttpRequest off to display the new page's contents in the
 * HTML document.
 */
function renderPageData(page) {
    // Setup the URL
    var url = 'hitList.do';
    url += '?_d=d&page='+page;
    var viewLink = document.getElementById('viewLink');
    if(viewLink != null)
        url += '&viewLink='+viewLink.value;

    // show loading image only for bottom div
    var el = getElementAndWait('LOADING_HIT_LIST');
    el = document.getElementById('HIT_LIST');
    if (el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                var el = document.getElementById('HIT_LIST');
                if (el) {
                    el.innerHTML = transport.responseText;
                }
            },
            onFailure: function() {
                document.getElementById('HIT_LIST').innerHTML =
                "<i>Error while fetching your hit list. Please try after some time or contact <a class='underlined' href='mailto:support@talentGraphz.com?subject=Hit List Error' title='mailto:support@talentGraphz.com?subject=Hit List Error'>administrator</a>.</i>";
            }
        });
    }
}

/**
 * Load contents for VC Directory page
 */
function loadVCDirectory() {
    /* load vc companies */
    // prepare url to load vc companies
    var url = "ventureCapitalists.do?type=standard&_d=d";
    var vcdirectory = document.getElementById('VC_BOSTON_LIST');
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // hack : convert all 'company.do' to 'CompanyDetails.html'
            // once the view class is rewritten, this hack will
            // not be required.
            var tokenToReplace = /company.do/gim;
            vcdirectory.innerHTML = transport.responseText.replace(
                tokenToReplace, pagelinks['RESEARCH_COMPANIES']);
        },
        onFailure: function() {
            // silent failure
        }
    });

    var url = "ventureCapitalists.do?type=angel&_d=d";
    var angelfunding = document.getElementById('ANGEL_FUNDING_LIST');
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // hack : convert all 'company.do' to 'CompanyDetails.html'
            // once the view class is rewritten, this hack will
            // not be required.
            var tokenToReplace = /company.do/gim;
            angelfunding.innerHTML = transport.responseText.replace(
                tokenToReplace, pagelinks['RESEARCH_COMPANIES']);
        },
        onFailure: function() {
            // silent failure
        }
    });

    /* load sponsors client companies */
    // prepare url for client companies
    var url = "clientcompanies.do?_d=d&type=sponsors";
    var clientCompanies = getElementAndWait('clientCompanies');

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            clientCompanies.innerHTML = transport.responseText;
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Show users profile.
 *
 * NOTE: Overridden from ajax.js
 */
function loadProfile(edit) {
    // Setup the URL
    var url = 'profile.do?_d=d';

    if (edit) {
        url += "&edit=true";
    }

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            document.getElementById('PROFILE').innerHTML = transport.responseText;
        },
        onFailure: function() {
            document.getElementById('PROFILE').innerHTML =
                "<i>Error while fetching your profile. Please try after some time or contact <a class='underlined' href='mailto:support@talentGraphz.com?subject=My Profile Error' title='mailto:support@talentGraphz.com?subject=My Profile Error'>administrator</a>.</i>";
        }
    });

    // load watch list
    loadWatchList();

    // load engagement list
    loadEngagementList();
}

/**
 * Method to render watch list
 *
 * NOTE: Overridden from ajax.js
 */
function loadWatchList() {
    var watchList = document.getElementById('WATCH_LIST');
    if(watchList) {
        // Setup the URL
        var url = 'watch.do?_d=d';

        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                watchList.innerHTML = transport.responseText;
                renderWatchMessage();
            },
            onFailure: function() {
            }
        });
    }
}

/**
 * Method to render engagements/hiring targets
 *
 * NOTE: Overridden from ajax.js
 */
function loadEngagementList() {
    var engagements = document.getElementById('ENGAGEMENT_LIST');
    if (engagements) {
        // Setup the URL
        var url = 'engage.do?_d=d';

        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                engagements.innerHTML = transport.responseText;
                renderEngagementMessage();
            },
            onFailure: function() {
            }
        });
    }
}

var selectFor = null;

/**
 * Surrogate function for 'associateCompanies'
 * just to make it sure, old function is not being called
 *
 * NOTE: Overridden from ajax.js
 */
function associateCompaniesWithDates(name, guid, startDate, endDate) {
    // NOTE : discard startDate and endDate, as these are not being used
    associateCompanies(name, guid)
}

/**
 * Single method to associate companies
 * as parent, child, watches and engaagements
 *
 * NOTE: Overridden from ajax.js
 */
function associateCompanies(name, guid) {
    hidePopupPanel();
    if (selectFor == "CHILD") {
        addChild(guid, currentCompanyGuid);
    }
    else if (selectFor == "PARENT") {
        addParent(currentCompanyGuid, guid);
    }
    else if (selectFor == "WATCHING") {
        watchCompany(guid);
    }
    else if (selectFor == "ENGAGEMENT") {
        engageCompany(guid);
    }
}

/**
 * Add company in child list
 *
 * NOTE: Overridden from ajax.js
 */
function addChild(childCompanyGuid, parentCompanyGuid) {
    var el = document.getElementById('companyPanel_aux_children');
    if (el) {
        url = "childCompany.do?childGuid=" + childCompanyGuid;
        url += "&parentGuid=" + parentCompanyGuid;

        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                el.innerHTML = transport.responseText;
                // set credits flag
                updateCredits = true;
                // refresh graph
                loadCompanyMap();
            },
            onFailure: function() {
                // silent failure.
            }
        });
    }
}

/**
 * Add company in parent list
 *
 * NOTE: Overridden from ajax.js
 */
function addParent(childCompanyGuid, parentCompanyGuid) {
    var el = document.getElementById('companyPanel_aux_parents');
    if (el) {
        url = "parentCompany.do?childGuid=" + childCompanyGuid;
        url += "&parentGuid=" + parentCompanyGuid;

        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                el.innerHTML = transport.responseText;
                // set credits flag
                updateCredits = true;
                // refresh graph
                loadCompanyMap();
            },
            onFailure: function() {
                // silent failure.
            }
        });
    }
}

/**
 * Drop child company
 *
 * NOTE: Overridden from ajax.js
 */
function dropChild(guid) {
    var url = "childCompany.do?remove=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('companyPanel_aux_children');
            if (el) {
                el.innerHTML = transport.responseText;
                // refresh graph
                loadCompanyMap();
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Drop parent company
 *
 * NOTE: Overridden from ajax.js
 */
function dropParent(guid) {
    var url = "parentCompany.do?remove=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('companyPanel_aux_parents');
            if (el) {
                el.innerHTML = transport.responseText;
                // refresh graph
                loadCompanyMap();
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Add company in watch list
 *
 * NOTE: Overridden from ajax.js
 */
function watchCompany(guid) {
    var url = "watch.do?add=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('WATCH_LIST');

            if (el) {
                el.innerHTML = transport.responseText;
            }
            // render watch button
            renderWatchButton(guid, true);
        },
        onFailure: function() {
        }
    });
}

/**
 * Drop watching company
 *
 * NOTE: Overridden from ajax.js
 */
function dropWatchingCompany(guid) {
    var url = "watch.do?remove=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('WATCH_LIST');

            if (el) {
                el.innerHTML = transport.responseText;
                renderWatchMessage();
            }
            // render watch button
            renderWatchButton(guid, false);
        },
        onFailure: function() {
        }
    });
}

/**
 * Add company in enagagement list
 *
 * NOTE: Overridden from ajax.js
 */
function engageCompany(guid) {
    var url = "engage.do?add=" + guid;

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('ENGAGEMENT_LIST');
            if (el) {
                el.innerHTML = transport.responseText;
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Proposes a new company to the system
 * renders the company page.
 *
 * NOTE: Overridden from ajax.js
 */
function proposeNewCompany(proposedCompany, renderCompanyPage) {
    hidePopupPanel();
    // prepare url
    var url = "viewCompany.do?proposed="+unescape(proposedCompany);

    // Make the request.
    new AjaxRequest(url, {
        method: 'get',
        onSuccess: function(transport) {
            // render company page
            navigateCompanyDetailsPage(trim(transport.responseText));
        },
        onFailure: function(transport) {
            alert('Unable to update record, try again later.');
        }
    });
}

/**
 * Function to add update citation link
 */
function saveCompanyLink() {
    var value;
    var url = "companyLinks.do";

    var el = document.getElementById('url');
    if (el) {
        value = el.value;
        url+="?url=" + value.replace(/&/g, "%26").replace(/ /g, "%20");
    }
    el = document.getElementById('title');
    if (el) {
        value = el.value;
        url+="&title=" + value.replace(/&/g, "%26").replace(/ /g, "%20");
    }
    el = document.getElementById('headline');
    if (el) {
        value = el.value;
        url+="&description=" + value.replace(/&/g, "%26").replace(/ /g, "%20");
    }
    el = document.getElementById('linkguid');
    if (el) {
        value = el.value;
        if(trim(value).length > 0){
            url+="&edit=" + value;
        }
    }

    var el = document.getElementById('COMPANY_LINKS');
    if (el) {
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                var el = document.getElementById('COMPANY_LINKS');
                if (el) {
                    el.innerHTML = transport.responseText;
                }
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
    // hide panel
    hidePopupPanel();
}

/**
 * Drops company link
 *
 * NOTE: Overridden from ajax.js
 */
function dropCompanyLink(guid) {
    var el = document.getElementById('COMPANY_LINKS');

    if (el) {
        var url = "companyLinks.do?remove=" + guid;

        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                var el = document.getElementById('COMPANY_LINKS');

                if (el) {
                    el.innerHTML = transport.responseText;
                }
            },
            onFailure: function() {
            }
        });
    }
}

// variable to store search request id
var searchRequestId = 0;

/**
 * Set a timer to make a search request after
 * 0.2 seconds. If already a request has been
 * set but not fired, cancel that request and
 * make a new request
 */
function initiateSearchRequest() {
    // check if already a request is initiated
    if(searchRequestId != 0) {
        // cancel request
        clearTimeout(searchRequestId);
    }
    // set new request
    searchRequestId = setTimeout("searchRequest(null)", 200);
    // return true, to bubble up events
    return true;
}

/**
 * Makes a search request and updates
 * corresponding elements
 */
function searchRequest(pattern) {
    // check for pattern, if not found
    if(!pattern) {
        pattern = document.getElementById('searchField').value;
    }
    // do unescape, as we escaped it while calling
    pattern = unescape(pattern);
    // hide popup, if empty string
    if(trim(pattern) == '' || pattern.indexOf("Enter company") > -1) {
        hideCompanyList();
        return;
    }
    // change double quotes to single quotes, as company name,
    // with double quotes created problem while rendering graph.
    if(pattern.indexOf('"') > -1) {
        var singleQuotes = "'"
        pattern = pattern.replace(/\"/g, singleQuotes);
        document.getElementById('searchField').value = pattern;
    }

    // Build the url for the search.
    var url = "browseCompanies.do?pattern=" + pattern;
    // check for the element to identify this request is for registration
    var toRegister = document.getElementById('toRegister');
    if(toRegister) {
        url += "&toRegister=1";
    }

    // Shouldn't wait
    var el = document.getElementById('divCompanyList');
    if (el) {
        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                var html = "";
                if (pattern.length > 0) {
                    if ("empty" != transport.responseText && trim(transport.responseText) != "") {
                        html += transport.responseText + "<br/>";
                        // hack : convert all 'company.do' to 'CompanyDetails.html'
                        // once the view class is rewritten, this hack will
                        // not be required.
                        var tokenToReplace = /company.do/gim;
                        el.innerHTML = html.replace(
                            tokenToReplace, pagelinks['RESEARCH_COMPANIES']);
                        el = document.getElementById('divCompanyList');
                        el.style.visibility = 'visible';
                        document.onclick = hideCompanyList;
                    }
                    else {
                        el = document.getElementById('divCompanyList');
                        el.style.visibility = 'hidden';
                    }
                }
            },
            onFailure: function() {
                // silent failure.
            }
        });
    }

    // don't forget to clear the request id
    searchRequestId = 0;
}

/**
 * Key press handler for company search field
 */
function keyPressHandler(e) {
    var kC  = (window.event) ? event.keyCode : e.which;
    var esc = 27;
    var tab = 9;
    if(kC!=esc && kC!=tab){
        initiateSearchRequest();
    }
    else{
        // hide div
        var divCompanyList = document.getElementById('divCompanyList');
        if(divCompanyList){
            divCompanyList.style.visibility = 'hidden';
        }
    }
}

/**
 * Hide company list div
 */
function hideCompanyList() {
    document.onclick = null;
    // hide div
    var divCompanyList = document.getElementById('divCompanyList');
    if(divCompanyList){
        divCompanyList.style.visibility = 'hidden';
    }
}

/**
 * Adds company license
 */
function addLicense() {
    // prepare url
    var url = "license.do?_d=d&action=createLicense";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function() {
            var el = document.getElementById("licenseButton");
            if (el) {
                el.innerHTML = "<div id='removeLicenseButton' title='Remove License' onclick='removeLicense();' onmouseover='displayHint(\"removeLicense\")' onmouseout='displayHint(\"0\");'/>";
            }
            var el = document.getElementById("licenseUserButton");
            if (el) {
                el.innerHTML = "<div id='addLicensedUserButton' title='Add Licensed Users' onclick='viewLicenseUsers();' onmouseover='displayHint(\"addLicensedUser\")' onmouseout='displayHint(\"0\");' />";
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * removes company license
 */
function removeLicense() {
    // prepare url
    var url = "license.do?_d=d&action=removeLicense";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function() {
            var el = document.getElementById("licenseButton");
            if (el) {
                el.innerHTML = "<div id='addLicenseButton' title='Add License' onclick='addLicense();' onmouseover='displayHint(\"addLicense\")' onmouseout='displayHint(\"0\");' />";
            }
            var el = document.getElementById("licenseUserButton");
            if (el) {
                el.innerHTML = "";
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Get/add/remove licensed users
 */
function addUpdateLicensedUser(guid, toAdd) {
    var url = "license.do?action=addUser&guid=" + guid;
    if(!toAdd)
    {
        url = "license.do?action=removeUser&guid=" + guid;
    }
    // Check if its an initial request to load the licensed users for the company
    if(guid == -1)
    {
       // load the list of existing license for this company
       url = "license.do?_d=d";
    }
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            var el = document.getElementById('licensedUsersListPanel');
            if (el) {
                el.innerHTML = transport.responseText;
                // hack : convert all image paths from
                // old icons to new icons
                // once the view class is rewritten, this hack will
                // not be required.
                var tokenToReplace = /genotrope\/chameleon/gim;
                el.innerHTML = transport.responseText.replace(
                    tokenToReplace, "chameleon/purpleskin");
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Process a key stroke in the license input control.
 */
function licenseUserPickerKeyEvent(e) {
    var keynum;

    // If IE
    if(window.event) {
        keynum = e.keyCode
    }

    // Else if Netscape/Firefox/Opera
    else if(e.which) {
        keynum = e.which
    }

    if (keynum) {

        var element = document.getElementById("licenseUserPickerField");
        var pattern = new String(element.value);

        len = pattern.length;
        if (8 == keynum) {
            if (len > 0) {
                len--;
                pattern = pattern.substring(0, len);
            }
        }
        else {
            var keychar = String.fromCharCode(keynum);
            pattern += keychar;
        }

        var url = "license.do?action=list&pattern=" + pattern;

        // Make the request.
        new AjaxRequest(url, {
            method: 'get',
            onSuccess: function(transport) {
                // Set the contents of the search panel.
                document.getElementById('licenseUserPickerPanelContent').innerHTML = transport.responseText;
            },
            onFailure: function() {
                // silent failure.
            }
        });

        // update the element value.
        element.value = pattern;
    }

    return false;
}

/**
 *
 */
function loadAdminContent() {
    // Get the list of users currently
    var url = "userAdmin.do?action=count";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var countData = eval(trim(transport.responseText));
                var el = document.getElementById('userCountPanel');

                if (el) {
                    el.innerHTML = countData[0].userCount;
                }
                el = document.getElementById('companyCountPanel');

                if (el) {
                    el.innerHTML = countData[0].companyCount;
                }
            }
        },
        onFailure: function() {
        }
    });
    // update startup jobs
    getStartupJobs(true);
    // get notification control and status details
    getNotificationControl();
    // get notification mail subject and messages
    getNotificationMessages();
    // get posting deactivation process's status
    getPostingProcessStatus();
    // get feature message
    getFeatureMessage();
    // get mail debugging status
    getMailDebuggingStatus();
}

/**
 * Method to fetch number of start up jobs
 */
function getStartupJobs(isAdmin) {
    // prepare url to get number of start up jobs
    var url = "homePage.do?_d=d&getStartupJobs=startup";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(transport.responseText){
                if(isAdmin){
                    $('numberOfStartup').value = trim(transport.responseText);
                }
                else {
                    $('numberOfStartup').innerHTML = trim(transport.responseText);
                }
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Method to update number of start up jobs
 */
function updateStartJobs(){
    var numberOfStartup = document.getElementById('numberOfStartup').value;
    // check if it is numeric
    if(!isNumber(trim(numberOfStartup))) {
        alert("Please enter a valid number !")
        return;
    }
    // prepare url to update number of start up jobs
    var url = "homePage.do?_d=d&setStartupJobs="+trim(numberOfStartup);
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            // do nothing
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Gets the status whether the notification is to be sent
 * or not. If value 'true' for toggle is provided, url
 * is updated to toggle the flag as well.
 */
function getNotificationControl(toggle) {
    // Toggle Get and control
    var url = "userAdmin.do?action=getNotificationControl";
    if(toggle)
        url += "&toggle=true";
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var controlNotification = "";
                if(trim(transport.responseText) == 'yes') {
                    controlNotification = 'talentGraphz updates are enabled. Click <img src="chameleon/purpleskin/icons/rewind_alt.gif" title="Disable notifications" onClick="getNotificationControl(true);" style="position:relative;top:3px;cursor:pointer;" /> to stop sending notifications.';
                }
                else {
                    controlNotification = 'talentGraphz updates are disabled. Click <img src="chameleon/purpleskin/icons/fforward_alt.gif" title="Enable notifications" onClick="getNotificationControl(true);" style="position:relative;top:3px;cursor:pointer;" /> to start sending notifications.';
                }
                var el = document.getElementById('controlNotification');
                if (el) {
                    el.innerHTML = controlNotification;
                }
                // refresh status
                getNotificationStatus();
                // get period
                getNotificationPeriod();
            }
        },
        onFailure: function() {
        }
    });
}

var notificationRefeshCount = 0;
var notificationMaxRefreshCount = 60;

/**
 * Gets the status of the notification cycle status
 * currently being executed. If not, will get the details
 * of the previous cycle
 */
function getNotificationStatus() {
    // Get notification status
    var url = "userAdmin.do?action=getNotificationStatus";
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var notificationStatus = eval(trim(transport.responseText));
                var el = document.getElementById('notificationStatus');
                if (el) {
                    el.innerHTML = notificationStatus[0].message;
                }
                // check if the cycle is in progress
                if(trim(notificationStatus[0].cycleInProgress).toLowerCase() == 'true' &&
                    notificationRefeshCount < notificationMaxRefreshCount) {
                    // set a refresh cycle of 1 second
                    setTimeout('getNotificationStatus()',1000);
                    notificationRefeshCount++;
                }
                else {
                    notificationRefeshCount = 0;
                }
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Gets the notification period. If updatePeriod is true,
 * makes a server trip to update the period value
 */
function getNotificationPeriod(updatePeriod) {
    // Get notification status
    var url = "userAdmin.do?action=getPostingsFrom";
    if(updatePeriod) {
        var el = document.getElementById('postingsFrom');
        if(!isNumber(el.value)) {
            alert("Please enter a valid number !");
            return;
        }
        var period = parseInt(trim(el.value));
        if(period > 180) {
            alert("Please enter days less than 180.");
            return;
        }
        url += "&postingsFrom="+period;
    }
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var postingsFrom = document.getElementById('postingsFrom');
                postingsFrom = trim(transport.responseText);
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Returns notification mail messages and subject.
 * If update flag is set to true, the messages
 * from the UI controls will be saved in the
 * database
 */
function getNotificationMessages(update) {
    // Get notification mail messages
    var url = "userAdmin.do?action=notificationMessages";
    var mailSubject = document.getElementById('mailSubject');
    var mailHeader = document.getElementById('mailHeader');
    if(update) {
        url += "&update=true";
        if(mailSubject && trim(mailSubject.value) != "") {
            url += "&mailSubject=" + encodeURIComponent(trim(mailSubject.value));
        }
        else {
            alert("Mail subject is required, and cannot be empty !");
            return;
        }
        if(mailHeader) {
            url += "&mailHeader=" + encodeURIComponent(trim(mailHeader.value));
        }
    }

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var notificationMessages = eval(trim(transport.responseText));
                if (mailSubject) {
                    mailSubject.value = notificationMessages[0].mailSubject;
                }
                if(mailHeader) {
                    mailHeader.value = notificationMessages[0].mailHeader;
                }
            }
        },
        onFailure: function() {
            // silent failure
        }
    });
}

/**
 * Gets the status whether the posting process is enabled.
 * If value 'true' for toggle is provided, url
 * is updated to toggle the flag as well.
 */
function getPostingProcessStatus(toggle) {
    // Toggle Get and control
    var url = "userAdmin.do?action=postingProcessStatus";
    if(toggle)
        url += "&toggle=true";
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var postingProcessStatus = "";
                if(trim(transport.responseText) == 'yes') {
                    postingProcessStatus = 'Postings deactivation schedule is enabled. Click <img src="chameleon/purpleskin/icons/rewind_alt.gif" title="Disable posting deactivation" onClick="getPostingProcessStatus(true);" style="position:relative;top:3px;cursor:pointer;" /> to suspend the process.';
                }
                else {
                    postingProcessStatus = 'Postings deactivation schedule is disabled. Click <img src="chameleon/purpleskin/icons/fforward_alt.gif" title="Enable posting deactivation" onClick="getPostingProcessStatus(true);" style="position:relative;top:3px;cursor:pointer;" /> to restart the process.';
                }
                var el = document.getElementById('postingProcessStatus');
                if (el) {
                    el.innerHTML = postingProcessStatus;
                }
            }
            // get process details
            getPostingProcessDetails();
        },
        onFailure: function() {
        }
    });
}

/**
 * Get the details of the posting process
 * If updatePeriod is true, makes a server trip to update the period value
 */
function getPostingProcessDetails(updatePeriod) {
    // Get notification status
    var url = "userAdmin.do?action=postingProcessDetails";
    if(updatePeriod) {
        var el = document.getElementById('postingActivePeriod');
        if(!isNumber(el.value)) {
            alert("Please enter a valid number !");
            return;
        }
        var period = parseInt(trim(el.value));
        if(period > 365) {
            alert("Please enter days less than 365.");
            return;
        }
        url += "&postingActivePeriod="+period;
    }
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var postingProcessDetails = eval(trim(transport.responseText));
                var el = document.getElementById('postingProcessDetails');
                if (el) {
                    el.innerHTML = postingProcessDetails[0].message;
                }
                el = document.getElementById('postingActivePeriod');
                if(el) {
                  el.value = postingProcessDetails[0].postingActivePeriod;
                }
            }
        },
        onFailure: function() {
        }
    });
}

/**
 * Returns new feature message.
 * If update flag is set to true, the message
 * from the UI controls will be saved in the
 * database
 */
function getFeatureMessage(update) {
    // Get feature messages
    var url = "userAdmin.do?action=featureMessage";
    var featureMessage = document.getElementById('featureMessage');
    if(update) {
        url += "&update=true";
        if(featureMessage) {
            url += "&featureMessage=" + encodeURIComponent(trim(featureMessage.value));
        }
    }

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            featureMessage.value = trim(transport.responseText);
        },
        onFailure: function() {
            // silent failure
        }
    });
    // get feature message status
    getFeatureMessageStatus();
}

/**
 * Returns, whether feature message is to be displayed.
 * Also, enables/disables feature message, as per the
 * input flag
 */
function getFeatureMessageStatus(toggle) {
    var enableFeatureMessageSpan = document.getElementById('enableFeatureMessageSpan');
    if(enableFeatureMessageSpan) {
        // Get whether the feature message is to be displayed
        var url = "userAdmin.do?action=getFeatureMessageStatus";
        // check if the state is to be toggled
        if(toggle) {
            url += "&toggle="+toggle;
        }
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(trim(transport.responseText) == 'yes') {
                    enableFeatureMessageSpan.innerHTML = '<div id="disableButton" title="Disable feature message" onClick="getFeatureMessageStatus(true);" />';
                }
                else {
                    enableFeatureMessageSpan.innerHTML = '<div id="enableButton" title="Enable feature message" onClick="getFeatureMessageStatus(true);" />';
                }
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
}

/**
 * Returns, whether mail debugging is enabled.
 * Also, enables/disables debugging, as per the
 * input flag
 */
function getMailDebuggingStatus(toggle) {
    var enableMailDebuggingSpan = document.getElementById('enableMailDebuggingSpan');
    if(enableMailDebuggingSpan) {
        // Get whether the mail debugging is to be enabled
        var url = "userAdmin.do?action=getMailDebugStatus";
        // check if the state is to be toggled
        if(toggle) {
            url += "&toggle="+toggle;
        }
        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                if(trim(transport.responseText) == 'yes') {
                    enableMailDebuggingSpan.innerHTML = 'Mail debugging enabled. Click button to disable it. <div>&nbsp;</div><div id="disableButton" title="Disable mail debugging" onClick="getMailDebuggingStatus(true);" />';
                }
                else {
                    enableMailDebuggingSpan.innerHTML = 'Mail debugging disabled. Click button to enable it. <div>&nbsp;</div><div id="enableButton" title="Enable mail debugging" onClick="getMailDebuggingStatus(true);" />';
                }
            },
            onFailure: function() {
                // silent failure
            }
        });
    }
}

/**
 * Function to add selected companies to talent targets
 */
function addTalentTargets() {
    //prepare url to check companies selected from various pages
    var url = "resume.do?submit=targets";
    var viewLink = document.getElementById('viewLink');
    if(viewLink != null)
        url += '&viewLink='+viewLink.value;
    // Make the request.
    new AjaxRequest(url, {
        method: 'get',
        onSuccess: function(transport) {
            // check if there is any company in the list
            if(trim(transport.responseText) == '') {
                var popupPanel = document.getElementById('popupPanel');
                if(popupPanel) {
                    // title
                    var popupPanelTitle = document.getElementById('popupPanelTitle');
                    popupPanelTitle.innerHTML = "Error";
                    // close button
                    preparePopupCloseButton();
                    // body
                    var popupPanelBody = document.getElementById('popupPanelBody');
                    popupPanelBody.innerHTML = "<hr class='ruler' width='490px' /><br><center>Please select at least one company to add to talent targets.</center><br>";
                    hideGraph();
                    // set overlay, to avoid any other user interaction
                    overlay(true);
                    // display popup panel
                    popupPanel.className = 'registrationPanel';
                }
            }
            else {
                //prepare url to add talent target
                var url = "talenttarget.do?action=add";
                var viewLink = document.getElementById('viewLink');
                if(viewLink != null)
                    url += '&viewLink='+viewLink.value;
                new AjaxRequest(url, {
                    method: 'get',
                    onSuccess: function(transport) {
                        // refresh page
                        refreshBrowseCompanies();
                    },
                    onFailure: function() {
                        // silent failure
                    }
                });
            }
        },
        onFailure: function() {
            alert('Unable to update record, try again later.')
        }
    });
}

/**
 * Check if there is any message to be rendered
 * in new feature dialog and renders the same
 */
function loadNewFeatureDialog(showFeature) {
    var DEFAULT_MESSAGE = "NO_MESSAGE";
    // default message
    var newFeatureMessage = DEFAULT_MESSAGE;

    // check if the user has turned off dialog
    var url = "loginBanner.do?newFeatureDialog=checkAndShowFeature";
    if(showFeature) {
        url += "&showFeature=yes";
    }
    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                if(trim(transport.responseText).toUpperCase() == "HIDE_MESSAGE") {
                    // do nothing
                    // 3/8/2010 7:02 AM
                    /*
                    // get handle to help cell
                    var helpCell = document.getElementById("helpCell");
                    if(helpCell) {
                        // add new feature icon
                        helpCell.innerHTML = "<img id='newFeatureImg' alt='*' height='16px' width='16px' src='chameleon/icons/new.gif' style='cursor:pointer;position:relative;top:-1px' title='View Message' onclick='loadNewFeatureDialog(true);this.style.visibility=\"hidden\";'> " + helpCell.innerHTML;
                        // add blink
                        //fade("newFeatureImg", false);
                    }
                    */
                }
                else if(trim(transport.responseText).toUpperCase() != DEFAULT_MESSAGE) {
                    // add overlay
                    //overlay(true);
                    // add tool tip
                    Tip("<div class='smallnormaltext'><div style='float:right' id='cancelButton' onclick='hideNewFeatureDialog();'>&nbsp;</div><br/>"+trim(transport.responseText)+"<br /><br />"+(isAuthorized()?"<input type='checkbox' id='neverShowFeature' name='neverShowFeature'>Do not show me this message again<br /><br />":"")+"<a onclick='hideNewFeatureDialog();'>Close</a></div>", TEXTALIGN, "center", STICKY, true, SHADOW, true, FADEIN, 1000, FADEOUT, 1000, PADDING, 5, BGCOLOR, "#ffffff", BORDERWIDTH, 1, BORDERCOLOR, "#2a234f", DURATION, 20000, EXCLUSIVE, true, OPACITY, 90, WIDTH, 325, CENTERWINDOW, true, CENTERALWAYS, true);
                }
            }
        },
        onFailure: function(transport) {
            // silent failure
        }
    });
}

/**
 * Hides the new feature dialog, and makes
 * server trip to remember the user preference
 */
function hideNewFeatureDialog() {
    // get user preference for 'never show feature'
    var neverShowFeature = document.getElementById('neverShowFeature');
    var neverShowFeatureChecked = (neverShowFeature && neverShowFeature.checked?true:false);
    // hide tool tip
    tt_Hide();
    // remove overlay
    overlay(false);
    /*
    // do nothing
    // 3/8/2010 7:02 AM
    // display new feature icon
    var newFeatureImg = document.getElementById('newFeatureImg');
    if(newFeatureImg) {
        newFeatureImg.style.visibility = 'visible';
    }
    */
    // remember user reference
    if(neverShowFeatureChecked && isAuthorized()) {
        // check if the user has turned off dialog
        var url = "loginBanner.do?newFeatureDialog=hideFeature";

        // Make the request
        new AjaxRequest(url, {
            method:'get',
            onSuccess: function(transport) {
                // do nothing
            },
            onFailure: function(transport) {
                // do nothing
            }
        });
    }
}

var incompleteItemMessages = new Array();
incompleteItemMessages["title"] = "Edit profile > Update your job category ";
incompleteItemMessages["zipcode"] = "Edit profile > Update your zipcode ";
incompleteItemMessages["industry"] = "Edit profile > Update Job Notification Preferences Industry ";
incompleteItemMessages["status"] = "Edit profile > Update Job Notification Preferences Status ";
incompleteItemMessages["engagement"] = "Edit profile >Add engagement(s) ";

/**
 * Get profile completeness
 */
function loadProfileCompleteness() {
    var el = document.getElementById('infoMessage');
    if(!el)
        return;

    // prepare url
    var url = "profile.do?action=profileCompleteness";

    // Make the request
    new AjaxRequest(url, {
        method:'get',
        onSuccess: function(transport) {
            if(trim(transport.responseText) != '') {
                var profileCompletenessStatus = eval(trim(transport.responseText));
                var profileCompletenessPercent = profileCompletenessStatus[0].profileCompleteness;
                var incompleteItemString = profileCompletenessStatus[0].incompleteItems;
                // 'padding' works for all the browsers, but IE.
                // For IE, have set the 'height', which surprisingly
                // doesn't works in other browsers.
                var completenessMessage = '<img src="imagesEx/spacer.gif" width="90px" height="1px" />'+
                    ' <span id="labelInfoMessage" ' +
                    ' onMouseover="this.setAttribute(\'over\',\'true\');" onMouseout="this.setAttribute(\'over\',\'false\');">' +
                    ' &nbsp;&nbsp;Your <a href="UserProfile.html" title="Update your profile to get relevant updates">profile</a> is ' +
                    profileCompletenessPercent + '% complete.&nbsp;';
                if (profileCompletenessPercent != '100' && trim(incompleteItemString) != '') {
                    var incompleteItems = incompleteItemString.split(",");
                    var nameValue;
                    var tempMessage = '<table class=\\\'smallnormaltext\\\' width=\\\'200px\\\' style=\\\'padding:0;spacing:0;border:0;\\\'>';
                    for(var j=0;j<incompleteItems.length;j++) {
                        nameValue = incompleteItems[j].split(":");
                        if(nameValue != null && nameValue.length == 2)
                            tempMessage += '<tr class=\\\'smallnormaltext\\\'><td>'+incompleteItemMessages[nameValue[0]] + "</td><td width=\\\'20%\\\' align=\\\'right\\\' valign=\\\'top\\\'>+" + nameValue[1] + "%</td></tr>";
                    }
                    tempMessage += '</table>';
                    completenessMessage += '<a href="UserProfile.html" onmouseout="UnTip();" onmouseover="Tip(\''+tempMessage+'\', BGCOLOR, \'#ffffff\', BORDERCOLOR, \'#5b5a79\', SHADOW, true, TITLE, \'Completeness Tips\', TITLEFONTSIZE, \'9pt\', WIDTH, 200, OFFSETX, 7, FADEIN, 500, FADEOUT, 500, FOLLOWMOUSE, false)">Add.</a>';
                }
                else {
                    completenessMessage = '<img src="imagesEx/spacer.gif" width="20px" height="1px" />' + completenessMessage;
                }
                completenessMessage += '&nbsp;</span>';
                el.innerHTML = completenessMessage;
                var labelInfoMessage = document.getElementById('labelInfoMessage');
                // default mouse is not over the message
                labelInfoMessage.setAttribute("over", "false");
                // and zero seconds have elapsed
                labelInfoMessage.setAttribute("duration", "0");
                // start timer to hide after some time
                setTimeout('refreshProfileCompleteness()', 1000);
            }
        },
        onFailure: function(transport) {
            // silent failure
        }
    });
}

/**
 * Refreshes the message and clears after some duration
 */
function refreshProfileCompleteness() {
    var labelInfoMessage = document.getElementById('labelInfoMessage');
    if(labelInfoMessage != null) {
        var over = trim(labelInfoMessage.getAttribute("over"));
        var duration = trim(labelInfoMessage.getAttribute("duration"));
        // check if mouse is over the message
        if(over == 'true') {
            // just repeat !
            setTimeout('refreshProfileCompleteness(true)', 1000);
        }
        else if(over == 'false') {
            // mouse is not over, get the duration elapsed
            if(isNumber(duration) && parseInt(duration) > 10) {
                // duration over, clear message
                var el = document.getElementById('infoMessage');
                el.innerHTML = '';
            }
            else {
                // increment duration
                labelInfoMessage.setAttribute("duration", ""+(parseInt(duration)+1));
                // repeat cycle
                setTimeout('refreshProfileCompleteness(true)', 1000);
            }
        }
        //if(window.console)
        //    console.log("labelInfoMessage.duration:"+duration+";labelInfoMessage.over:"+over);
    }
}

