/**
 * Creates and displays the content for the submit resume popup
 * from the posting details page
 */
function showPostingSubmitResumeForm(postingGuid, jobTitle, jobCategory, companyGuid, companyName, modifiedDate) {
    trackRequest("POSTING_RESUME_CLICKED");
    var popupPanel = document.getElementById('popupPanel');
    if(popupPanel) {
        // title
        var popupPanelTitle = document.getElementById('popupPanelTitle');
        popupPanelTitle.innerHTML = jobTitle;
        popupPanelTitle.className = "boldtext";
        // close button
        preparePopupCloseButton();
        // body
        var el = document.getElementById('popupPanelBody');
        if (el) {
            el.innerHTML = prepareApplyForPostHTML(postingGuid, jobTitle, jobCategory, companyGuid, companyName, modifiedDate);
        }
        // set overlay, to avoid any other user interaction
        overlay(true);
        // display popup panel
        popupPanel.className = 'submitresumePanel';
        // set focus to all the controls to fire onblur event
        // last should be the first name
        focus('lastname');
        focus('emailid');
        focus('coveringNote');
        focus('firstname');
        // if user authorized, get brief profile
        if(isAuthorized()) {
            // Get the logged in user details
            var url = "userAdmin.do?action=currentUser";
            // Make the request
            new AjaxRequest(url, {
                method:'get',
                onSuccess: function(transport) {
                    if(trim(transport.responseText) != '') {
                        var userData = eval(trim(transport.responseText));
                        // for an authorised user mail id cannot be blank
                        if(userData[0].emailid != "") {
                            var el = document.getElementById('emailid');
                            if (el) {
                                el.value = userData[0].emailid;
                                // make the field read only
                                el.readOnly=true;
                            }

                            el = document.getElementById('firstname');
                            if (el) {
                                if(userData[0].firstname != null && trim(userData[0].firstname) != 'null')
                                    el.value = userData[0].firstname;
                            }

                            el = document.getElementById('lastname');
                            if (el) {
                                if(userData[0].lastname != null && trim(userData[0].lastname) != 'null')
                                    el.value = userData[0].lastname;
                            }
                            // if user first name or last name is null in system,
                            // set a flag to save these, once user submits for resume
                            if(userData[0].firstname == '' || userData[0].lastname == '') {
                                var saveUserDetails = document.getElementById('saveUserDetails');
                                if(saveUserDetails) {
                                    saveUserDetails.value = 'true';
                                }
                            }
                        }
                        // set focus to all the controls to fire onblur event
                        // last should be the first name
                        focus('lastname');
                        focus('emailid');
                        focus('coveringNote');
                        focus('firstname');
                    }
                },
                onFailure: function() {
                }
            });
        }
    }
}

/**
 * Returns inner html for submiting resume for the selected posting
 */
function prepareApplyForPostHTML(postingGuid, jobTitle, jobCategory, companyGuid, companyName, modifiedDate) {
    // The innerHTML should come thru ajax request
    var postingText = "";
    postingText += ("<form method='post' enctype='multipart/form-data' id='uploadFormId' name='uploadFormId' target='uploadFrame' action='upload.do' style='margin:0px'>");
    postingText += ("<input type='hidden' name='postingGuid' id='postingid' value='" + postingGuid + "' />");
    postingText += ("<input type='hidden' name='companyGuid' id='companyGuid' value='" + companyGuid + "' />");
    postingText += ("<input type='hidden' name='requestpage' value='HIT_LIST' />");
    postingText += ("<input type='hidden' name='saveUserDetails' id='saveUserDetails' value='false' />");
    var el = document.getElementById('viewLink');
    if(el) {
        postingText += ("<input type='hidden' name='viewLink' id='viewLink' value='"+el.value+"' />");
    }
    else {
        // @TODO : need to revisit
        // forcing view link to POSTING_LIST. This will happen whenever
        // resume is posted from 'Companies' page. Once we've a different
        // page for postings, this should be removed
        postingText += ("<input type='hidden' name='viewLink' id='viewLink' value='POSTING_LIST' />");
    }
    postingText += ("<table class='smallnormaltext' width='100%'>\n");

    postingText += ("<tr>");
    postingText += ("<td colspan ='2'>at <a class='companyName' onclick='navigateCompanyDetailsPage(\""+companyGuid+"\");'>"+companyName+"</a>");
    postingText += ("</td>");
    postingText += ("</tr>\n");

    if(modifiedDate != null && trim(modifiedDate) != '') {
      postingText += ("<tr>");
      postingText += ("<td colspan ='2' align='right'> Last modified on : <b>" + modifiedDate + "</b>");
      postingText += ("</td>");
      postingText += ("</tr>\n");
    }

    postingText += ("<tr><td colspan='2'><div style='visibility:hidden;' id='errormessage'><span class='errorsmalltext'>&nbsp;</span></div></td></tr>\n");
    postingText += ("<tr><td colspan='2'><hr class='ruler' width='485px' /></td></tr>\n");

    postingText += ("<tr>");
    postingText += ("<td class='smalltext' width='23%'>First Name:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><input tabindex='11' type='text' class='textbox' style='width:350px;' autocomplete='off' name='firstname' id='firstname' value='' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)' /></td>");
    postingText += ("</tr>\n");

    postingText += ("<tr>");
    postingText += ("<td class='smalltext'>Last Name:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><input tabindex='12' type='text' class='textbox' style='width:350px;' autocomplete='off' name='lastname' id='lastname' value='' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)' /></td>");
    postingText += ("</tr>\n");

    postingText += ("<tr>");
    postingText += ("<td class='smalltext'>Email Id:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><input tabindex='13' type='text' class='textbox' style='width:350px;' autocomplete='off' name='emailid' id='emailid' value='' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)' /></td>");
    postingText += ("</tr>\n");

    postingText += ("<tr>");
    postingText += ("<td class='smalltext' valign='top'>Cover Letter:</td>");
    postingText += ("<td><textarea tabindex='14' class='textarea' style='width:350px;' autocomplete='off' name='coveringNote' id='coveringNote' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)' rows='6'></textarea></td>");
    postingText += ("</tr>\n");

    postingText += ("<tr>");
    postingText += ("<td class='smalltext'>Resume:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><input tabindex='15' class='textbox' size='53' style='width:350px;' type='file' name='file' id='userresume'/></td>");
    postingText += ("</tr>\n");

    /*
    if(!isAuthorized()) {
        postingText += ("<td colspan='2'><img src='imagesEx/spacer.gif' height='2px' width='2px'></td>");
        postingText += ("<tr>");
        postingText += ("<td colspan='2'>");
        postingText += ("Check <input style='position:relative;top:2px;left:-1px' type='checkbox' id='toregister' name='toregister' value='toregister' /> to register @ TalentGraphz. Registered users are able to save work history, utilize the Affinity Job Search, add/edit companies in database and receive an RSS feed of relevant company info.");
        postingText += ("</td></tr>\n");
    }
    */

    postingText += ("<tr>");
    postingText += ("<td colspan='2'><hr/></td>");
    postingText += ("</tr>\n");
    postingText += ("<tr>");

    postingText += ("<td colspan='2' align='right'>");
    postingText += ("<input type='button' class='proformaButton' title='Submit Resume' value='Submit Resume' onclick='submitForPosting();' />&nbsp;&nbsp;");
    postingText += ("<input type='button' class='proformaButton' title='Cancel' value='Cancel' onclick='cancelPostingSubmitResume();' />");
    postingText += ("</td></tr>\n");
    postingText += ("</table>");
    postingText += ("</form>");

    return postingText;
}

/**
 * Submit resume for posting
 */
function submitForPosting() {
    var postingGuid = document.getElementById('postingGuid');
    var companyGuid = document.getElementById('companyGuid');
    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var emailid = document.getElementById('emailid');
    var coveringNote = document.getElementById('coveringNote');
    var userresume = document.getElementById('userresume');
    // validation
    if(firstname == null || trim(firstname.value) == '' || trim(firstname.value) == hintMessages[firstname.name]) {
        showError("Please provide a valid first name.");
        return;
    }
    else if(lastname == null || trim(lastname.value) == '' || trim(lastname.value) == hintMessages[lastname.name]) {
        showError("Please provide a valid last name.");
        return;
    }
    else if(emailid == null || trim(emailid.value) == '' || !checkEmail(emailid.value) || trim(emailid.value) == hintMessages[emailid.name]) {
        showError("Please provide a valid email id.");
        return;
    }
    else if(userresume == null || trim(userresume.value) == '') {
        showError("Please specify a valid resume to upload.");
        return;
    }
    else {
        trackRequest("POSTING_RESUME_SUBMITTED");
        if(coveringNote != null && (trim(coveringNote.value) == '' || trim(coveringNote.value) == hintMessages[coveringNote.name])) {
            coveringNote.value = "";
        }
        // Get the form handle
        var form = document.getElementById('uploadFormId');
        if(form)
        {
            // upload resume
            form.submit();
        }
        // display processing gif
        // and disable user controls
        var processingImage = document.getElementById('errormessage');
        if(processingImage) {
            processingImage.style.visibility = 'visible';
            // Browser differences again :
            // the overlay div for the pop up, with
            // an 'absolute' style and top and left defined
            // as 0 is required from IE, Chrome and Safari.
            // Where as for Firefox, the actual top & left of
            // the pop up panel is required. The hardcoding
            // for the browser check should be changed
            // with proper solution.
            var addOffset = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)?true:false;
            processingImage.innerHTML = "<span class='errorsmalltext' height='17px'><center>&nbsp;<span style='position:absolute'><img src='imagesEx/green_rot.gif'/></span></center><div id='veilpopup' style='position:absolute;top:"+(addOffset?"200px":"0px")+";left:"+(addOffset?"375px":"0px")+";width:500px;height:360px;z-index:6;opacity:0.01;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=1);background-color:#fffffe'>&nbsp;</div></span>";
        }
        // set time out for the upload response
        uploadTimer = setTimeout('uploadCompleted', 20000);
        // check for authenticated user and flag to set details
        if(isAuthorized()) {
            var saveUserDetails = document.getElementById('saveUserDetails');
            if(saveUserDetails && saveUserDetails.value == 'true') {
                // Get the logged in user details
                var url = "userAdmin.do?action=setCurrentUserDetails";
                url += "&firstname="+firstname.value;
                url += "&lastname="+lastname.value;
                // Make the request
                new AjaxRequest(url, {
                    method:'get',
                    onSuccess: function(transport) {
                        // do nothing
                    },
                    onFailure: function() {
                        // silent failure
                    }
                });
            }
        }
    }
}

// global upload timer variable
var uploadTimer = 0;

/**
 * timer call back for an upload thread
 */
function uploadCompleted(error) {
    // check if the timer is still running
    if(uploadTimer != 0) {
        // stop timer
        clearTimeout(uploadTimer);
        uploadTimer = 0;
    }
    // check for any error
    if(error) {
        // display error
        showError(error);
        // no further execution
        return;
    }
    var toregister = document.getElementById('toregister');
    var showRegistration = false;
    if(toregister && toregister.checked) {
        showRegistration = true;
    }
    var emailidValue ='';
    var emailid = document.getElementById('emailid');
    if(emailid) {
        emailidValue = emailid.value;
    }
    // body
    var el = document.getElementById('popupPanelBody');
    if (el) {
        el.innerHTML = "<hr class='ruler' width='490px' /><br /><center>Your resume was uploaded successfully for the posting.</center><br /><br />";
        if(!isAuthorized()) {
            el.innerHTML += "<hr class='ruler' />" +
                "<table class='boldtext'><tr><td align='center'>" +
                "You don't have to register, <br /> but when you do, here is what you get. <br/><br/><br/>" +
                "We create your professional graph of the companies you're connected to through your employment history <br /><br /><br />" +
                "Better-fit matching to companies and jobs based on commonality of professional graph <br /><br /><br />" +
                "Highly customizable Opt-in weekly jobs email. <br /><br /><br />" +
                "LinkedIn integration to help you discover contacts at companies of interest <br /><br /><br />" +
                "<span class='veryverybigbluetext'>It's Free So</span>&nbsp;&nbsp;<span onclick='javascript:showRegistrationForm(\"REGISTRATION_CLICKED_4\");'><img style='position:relative;top:15px;cursor:pointer;' src='./imagesEx/signup2.png'/></span>&nbsp;&nbsp;<span class='veryverybigbluetext'>Now</span><br /><br />" +
                "It only takes a minute" +
                "</td></tr></table>";
        }
    }
    // hide pop up panel
    //hidePopupPanel();
    /*
    // if user opts for registration
    if(showRegistration) {
        // show registration form
        showRegistrationForm();
        // populate email
        var email = document.getElementById('email');
        if(email) {
            email.value = emailidValue;
        }
        // populate confirm email
        var confirm = document.getElementById('confirm');
        if(confirm) {
            confirm.value = emailidValue;
        }
        // check accept terms
        var acceptterms = document.getElementById('acceptterms');
        if(acceptterms) {
            acceptterms.checked = true;
        }
    }
    */
}

/**
 * Cancel submit resume
 */
function cancelPostingSubmitResume() {
    trackRequest("POSTING_RESUME_CANCELLED");
    hidePopupPanel();
}

/**
 * Updates the status of the posting
 */
function updateStatus(guid, status) {
    // Deactivated postings should not be seen
    // Ref : Mail - TZ Minutes of meeting June 02,2011
    // Changes - 6/24/2011 7:13 AM
    if(status=='inactive') {
        if(!confirm("Deleted postings cannot be recovered. Do you wish to continue?")) {
            // not to be deleted
            return;
        }
    }
    // prepare url
    var url = "posting.do?_d=d&action=updateStatus&guid="+guid+"&status="+status;

    var el = document.getElementById('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
            }
        });
    }
}

/**
 * Displays posting panel
 */
function showPostingPanel() {
    var popupPanel = document.getElementById('popupPanel');
    if(popupPanel) {
        // title
        var popupPanelTitle = document.getElementById('popupPanelTitle');
        popupPanelTitle.innerHTML = "Manage Posting";
        popupPanelTitle.className = "boldtext";
        // close button
        preparePopupCloseButton();
        // set overlay, to avoid any other user interaction
        overlay(true);
        // display popup panel
        popupPanel.className = 'postingPanel';
        // hide graph
        hideGraph();
        focus('jobTitle');
        focus('jobCategory');
        InitQueryCode('jobCategory', 'title.do?_d=d&categoryPattern=');
        document.getElementById('jobCategory').onblur=function(){
            // method from autocomplete.js
            // @TODO should think of another solution
            showDiv(false);
            // display message if required.
            toggleHintMessage(document.getElementById('jobCategory'), true);
        }
    }
}

/**
 * Display blank form for new posting
 */
function addPosting(companyid) {
    // set body text
    var el = document.getElementById('popupPanelBody');
    if (el) {
        el.innerHTML = preparePostingHTML('',companyid, '', '', '', '', 'true', null);
        // set up rich text editor for posting details
        setUpYUIPostingEditor();
    }
    showPostingPanel();
}

/**
 * Display posting details
 */
function getPosting(postingid, companyid, jobTitle, jobCategory, skill, responsibility, active, modifiedDate) {
    // set body text
    var el = document.getElementById('popupPanelBody');
    if (el) {
        //skill = skill.replace(/<br \/>/g, "\r\n");
        //responsibility = responsibility.replace(/<br \/>/g, "\r\n");
        var skillObject = document.getElementById(postingid+"_skill");
        if(skillObject) {
            skill = skillObject.innerHTML;
        }
        var responsibilityObject = document.getElementById(postingid+"_responsibility");
        if(responsibilityObject) {
            responsibility = responsibilityObject.innerHTML;
        }
        el.innerHTML = preparePostingHTML(postingid, companyid, jobTitle, jobCategory, skill, responsibility, active, modifiedDate);
        // set up rich text editor for posting details
        setUpYUIPostingEditor();
    }
    showPostingPanel();
}

/**
 * Add/Update posting
 */
function savePosting() {
    // validation
    var jobTitle = document.getElementById('jobTitle');
    var jobCategory = document.getElementById('jobCategory');
    var skill = document.getElementById('skill');
    var responsibility = document.getElementById('responsibility');
    var postingdetails = document.getElementById('postingDescription');
    var guid = document.getElementById('postingid');
    var companyid = document.getElementById('companyGuid');
    if(jobCategory == null || trim(jobCategory.value) == '' || trim(jobCategory.value) == hintMessages[jobCategory.name]) {
        showError("Please provide a valid posting category.");
        return;
    }
    else if(jobTitle == null || trim(jobTitle.value) == '' || trim(jobTitle.value) == hintMessages[jobTitle.name]) {
        showError("Please provide a valid posting title.");
        return;
    }
    else if(postingdetails == null || trim(postingdetails.value) == '' || trim(postingdetails.value) == hintMessages[postingdetails.name]) {
        showError("Please provide with posting details.");
        return;
    }
    else {
        // server side request
        // prepare url
        var url = "savePosting.do?_d=d&";
        var params = "action=savePosting";
        params += "&guid="+guid.value;
        params += "&companyid="+companyid.value;
        params += "&jobTitle="+encodeURIComponent(jobTitle.value);
        params += "&jobCategory="+jobCategory.value;
        //var escapedSkill = escapeNewLine(skill.value, '<br />');
        var escapedResponsibility = escapeNewLine(postingdetails.value, '<br />');
        params += "&skill="+EMPTY_SKILLS;//+removeSpecialCharacters(escapedSkill);
        params += "&responsibility="+encodeURIComponent(escapedResponsibility);
        // processing indicator
        var processingImage = document.getElementById('errormessage');
        if(processingImage) {
            processingImage.style.visibility = 'visible';
            processingImage.innerHTML = "<span class='errorsmalltext'><center>&nbsp;<span style='position:absolute'><img src='imagesEx/green_rot.gif'/></span></center></span>";
        }
        // Make the request
        new AjaxRequest(url, {
            method:'post',
            encoding:'UTF-8',
            requestHeaders: ["Accept-Language","en-us,en;","Accept-Charset","ISO-8859-1,UTF-8;"],
            parameters: params,
            onSuccess: function(transport) {
                if(transport.responseText != null && trim(transport.responseText) != "") {
                    var returnString = trim(transport.responseText)
                    if(returnString.indexOf("error:") > -1) {
                        showError(returnString.split(":")[1]);
                        return;
                    }
                    else if(returnString.indexOf("success:") > -1) {
                        // hide panel
                        hidePopupPanel();
                        // load all postings of the company
                        loadCompanyPostings();
                    }
                    else {
                        // hide panel
                        hidePopupPanel();
                        var el = document.getElementById('JOB_POSTINGS');
                        el.innerHTML = returnString;
                    }
                }
            },
            onFailure: function() {
                // hide panel
                hidePopupPanel();
                // silent failure
            }
        });
    }
}

/**
 * Returns the inner html for the posting popup panel
 */
function preparePostingHTML(postingid, companyid, jobTitle, jobCategory, skill, responsibility, active, modifiedDate) {
    // The innerHTML should come thru ajax request
    var postingText = "";
    postingText += ("<form id='postingForm' name='postingForm' onsubmit='return false;' style='margin:0px'>");
    postingText += ("<input type='hidden' name='postingid' id='postingid' value='" + postingid + "' />");
    postingText += ("<input type='hidden' name='companyGuid' id='companyGuid' value='" + companyid + "' />");
    postingText += ("<table class='normaltext yui-skin-sam' width='100%' border='0' style='zoom:1'>\n");

    if(modifiedDate != null && trim(modifiedDate) != '') {
      postingText += ("<tr>");
      postingText += ("<td colspan ='2' align='right' class='smallnormaltext'> Last modified on : <b>" + modifiedDate + "</b>");
      postingText += ("</td>");
      postingText += ("</tr>\n");
    }
    postingText += ("<tr><td colspan='2'><div style='visibility:hidden;' id='errormessage'><span class='errorsmalltext'>&nbsp;</span></div></td></tr>\n");
    postingText += ("<tr><td colspan='2'><hr class='ruler' width='485px' /></td></tr>\n");

    postingText += ("<tr>");
    postingText += ("<td width='117px' class='smalltext'>Category:<label class='smallnormalredtext'>*</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>");
    postingText += ("<td><input tabindex='1' type='text' class='textbox' style='width:350px;' autocomplete='off' name='jobCategory' id='jobCategory' onfocus='toggleHintMessage(this, false)' value='"+jobCategory+"'  /></td>");
    postingText += ("</tr>\n");

    postingText += ("<tr>");
    postingText += ("<td width='117px' class='smalltext'>Title:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><input tabindex='2' type='text' class='textbox' style='width:350px;' name='jobTitle' id='jobTitle' value='"+jobTitle+"' onfocus='toggleHintMessage(this, false)' onblur='toggleHintMessage(this, true)' /></td>");
    postingText += ("</tr>\n");

    // skill + resposibility widget
    postingText += ("<tr>");
    postingText += ("<td colspan='2'>");
    postingText += ("<div id='refinedFields' style='visibility:hidden;display:none;'>");
    postingText += ("<table class='smallnormaltext' border='0' width='100%'>");
    postingText += ("<tr>");
    postingText += ("<td colspan='2' align='right'>");
    postingText += ("<a style='text-decoration:underline;' onclick=''>Switch to details view</a>");
    postingText += ("</td>");
    postingText += ("</tr>");
    postingText += ("<tr>");
    postingText += ("<td width='115px' class='smalltext' valign='top'>Skill:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><textarea tabindex='3' class='textarea' style='width:350px;' name='skill' id='skill' rows='6' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)'>"+skill+"</textarea></td>");
    postingText += ("</tr>");
    postingText += ("<tr>");
    postingText += ("<td class='smalltext' valign='top'>Responsibility:<label class='smallnormalredtext'>*</label></td>");
    postingText += ("<td><textarea tabindex='4' class='textarea' style='width:350px;' name='responsibility' id='responsibility' rows='6' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)'>"+responsibility+"</textarea></td>");
    postingText += ("</tr>");
    postingText += ("</table>");
    postingText += ("</div>");
    postingText += ("</td>");
    postingText += ("</tr>");

    // only details widget
    postingText += ("<tr>");
    postingText += ("<td colspan='2'>");
    postingText += ("<div id='detailedField' style='visibility:visible;display:block;position:relative;top:-4px'>");
    postingText += ("<table class='smallnormaltext' border='0' cellspacing='2' cellpadding='0' width='100%'>");
    postingText += ("<tr>");
    postingText += ("<td colspan='2'><textarea tabindex='5' class='textarea' style='width:470px;' name='postingDescription' id='postingDescription' rows='15' onblur='toggleHintMessage(this, true)' onfocus='toggleHintMessage(this, false)'>"+((trim(skill) == "" || trim(skill) == EMPTY_SKILLS)?responsibility:trim(responsibility)+"\r\n"+trim(skill))+"</textarea></td>");
    postingText += ("</tr>");
    postingText += ("</table>");
    postingText += ("</div>");
    postingText += ("</td>");
    postingText += ("</tr>");

    postingText += ("<tr>");
    postingText += ("<td colspan='2'><hr/></td>");
    postingText += ("</tr>\n");
    postingText += ("<tr>");
    postingText += ("<td colspan='2' align='right'>");
    // allow user to update only if posting is active
    if(active=='true')
        postingText += ("<input id='btnSavePosting' type='button' class='proformaButton' title='Save Posting' value='Save Posting' onclick='savePosting();' />&nbsp;&nbsp;");
    postingText += ("<input type='button' class='proformaButton' title='Cancel' value='Cancel' onclick='hidePopupPanel();' />");
    postingText += ("</td></tr>\n");
    postingText += ("</table>");
    postingText += ("</form>");

    return postingText;
}

/**
 * Setup rich text editor for
 * posting details
 */
function setUpYUIPostingEditor() {
    // check for yahoo library imported
    if(typeof(YAHOO) == 'undefined') {
        // seems to be library not included
        return;
    }
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

    var myConfig = {
        height: '150px',
        width: '470px',
        dompath: false,
        focusAtStart: false,
        removeLineBreaks: true,
        filterWord : true,
        css: YAHOO.widget.SimpleEditor.prototype._defaultCSS + "body { font-family:'Verdana';font-size:11px;}",
        toolbar: { 
            titlebar: '',
            grouplabels: false,
            collapse: false, 
            buttons: [
                { group: 'fontstyle', label: 'Font Name and Size',
                    buttons: [
                        { type: 'select', label: 'Verdana', value: 'fontname', disabled: true,
                            menu: [
                                { text: 'Arial', checked: true },
                                { text: 'Arial Black' },
                                { text: 'Comic Sans MS' },
                                { text: 'Courier New' },
                                { text: 'Lucida Console' },
                                { text: 'Tahoma' },
                                { text: 'Times New Roman' },
                                { text: 'Trebuchet MS' },
                                { text: 'Verdana' }
                            ]
                        },
                        { type: 'spin', label: '11', value: 'fontsize', range: [ 9, 75 ], disabled: true }
                    ]
                },
                { type: 'separator' },
                { group: 'textstyle', label: 'Font Style',
                    buttons: [
                        { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
                        { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
                        { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
                        /*{ type: 'push', label: 'Strike through', value: 'strikethrough' },*/
                        { type: 'separator' },
                        { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
                        { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
                        { type: 'separator' }
                    ]
                },
                { type: 'separator' },
                { group: 'indentlist', label: 'Indenting and Lists',
                    buttons: [
                        { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
                        { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
                    ]
                }
            ]
        }
    };

    // invalid tags to be removed. Also few tags whose body to be remain as is.
    var invalidTags = {"applet":"", "area":"", "base":"", "script":"", "cufontext" : "", "cufon" : "",
        "style" : "", "link" : "", "xml" : "" , "form" : "" , "iframe" : "",
        "html" : "" , "input" : "", "button" : "", "select" : "" , "title" : "",
        "blockquote":{ "keepContents":true }, "body":{ "keepContents":true }};

    var myEditor = new YAHOO.widget.SimpleEditor('postingDescription', myConfig);
    myEditor.invalidHTML = invalidTags;
    myEditor._defaultToolbar.buttonType = 'advanced';
    myEditor.render();
    //Inside an event handler after the Editor is rendered
    YAHOO.util.Event.on('btnSavePosting', 'mouseover', function() {
        // get html
        var html = myEditor.getEditorHTML();
        // filter unwanted data
        html = myEditor.filter_all_rgb(html);
        html = myEditor.filter_internals(html);
        html = myEditor.filter_invalid_lists(html);
        // set back
        myEditor.setEditorHTML(html);
        //Put the HTML back into the text area
        myEditor.saveHTML();
    });
}

/**
 * Replace new line with <br/>
 * textarea is reference to that object
 * replaceWith is string that will replace the encoded return
 */
function escapeNewLine(textarea,replaceWith){
    if(textarea.indexOf("\r\n") > -1) {
      // for some reason, IE works with this..
      textarea = textarea.replace(new RegExp("\r\n", "g"), "<br />");
    }
    else if(textarea.indexOf("\n") > -1) {
      // and Firefox, Safari and Chrome with this on Windows
      textarea = textarea.replace(new RegExp("\n", "g"), "<br />");
    }
    else if(textarea.indexOf("\r") > -1) {
      // not sure, when this will be the case
      textarea = textarea.replace(new RegExp("\r", "g"), "<br />");
    }
    return textarea;
}

/**
 * Returns the input string after removing
 * characters not friendly for a url
 */
function removeSpecialCharacters(inputString, replaceWith) {
    if(inputString != null && trim(inputString) != "") {
        if(inputString.indexOf("%") > -1) {
            inputString = inputString.replace(/%/g, (replaceWith?replaceWith:escape("%")));
        }
        if(inputString.indexOf("&") > -1) {
            inputString = inputString.replace(/&/g, (replaceWith?replaceWith:escape("&")));
        }
        if(inputString.indexOf("#") > -1) {
            inputString = inputString.replace(/#/g, (replaceWith?replaceWith:escape("#")));
        }
        if(inputString.indexOf("\\") > -1) {
            inputString = inputString.replace(/\\/g, (replaceWith?replaceWith:escape("\\")));
        }
        // '+' is never received in servlet. so this special symbol
        if(inputString.indexOf("+") > -1) {
            inputString = inputString.replace(/\+/g, (replaceWith?replaceWith:escape("plus_sign")));
        }
        // add any other special characters
        return inputString;
    }
    else {
        return "";
    }
}

