var selectedCurrency;
/* avoid the multiple submission */
function fireTracker(page, id)
{
    // initialise the check array to avoid tracking events resubmission
    if(typeof(checkResubmission) == 'undefined')
        checkResubmission = [];

    // call the event only if google analytics has been included in the page
    if(!checkResubmission[id] && typeof(pageTracker) != 'undefined') {
        checkResubmission[id] = 1;
        pageTracker._trackPageview("/" + page + "/" + id);
    }
}
function logData(fieldname,value,isValue){
if(doLog == 'Y'){
  var jobId = $('#logJobId').val();
  if(jobId == ''){
    jobId='&user='+$('#logUserId').val();
  }

  if (isValue != 'Y') {
      //This is the case when function is called on 'Job Description' onFocus in Posting form.
      var val = $('#'+value).val();
  } else {
      var val = value;
  }

  time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

  $.ajax({
         url: "ajax/logJobdata.php",
         data: "r="+time+"&id="+jobId+"&field="+fieldname+"&data="+val,
         success: function(data) {if(data != '')$('#logJobId').val(data);}
       });
  }
}
function logMultipleData(value){
if(doLog == 'Y'){
  var jobId = $('#logJobId').val();

  time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

  $.ajax({
         url: "ajax/logJobdata.php",
         data: "r="+time+"&type=multiple&id="+jobId+"&"+value
       });
  }
}
var uploadCount = 0;
var uploadMax = 3;

// Extend email validation method so that it ignores whitespace
jQuery.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
    return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
}, "Please enter a valid email");

// JQuery Modal Dialog Box transfered in a seperate function
// to make it easier accessible - also called from checkAdFrm
// if user's session has expired.
// This function will open the login dialog
function openDialogClick(){
    // reset form state and open
    $('#noAuth-register').hide();
    $('#noAuth-login').show();
    $('#noAuth-register .validationError').html('');
    $('#noAuth-login .validationError').html('');
    $("#dialog").dialog("open");

    logData('page3_continue_clicked','Y','Y');
    logData('registered_user','Y','Y');
}


$(document).ready(function() {

    $('#yp_name').click(function(){
                changeClass(this);
    });
    $('#category').change(function(){
           getSubCategory($(this).val());
           checkDataFilled();// check for data filled.
     });

    $('#comment').val('Enter your requirements here, taking care to be as specific as possible');
    $('#comment').css({color:'#5D5D5D'});

    $('#comment').focus(function(){
     var str = $(this).val();
        if (str.substring(0,28) == 'Enter your requirements here')
        {

            $(this).val('');
            $(this).css({color:'#000'});
        }
      $('#postContainerRight').hide();//check_desc();
      $('#postHelpRight').css('padding-top','185px');
      $('#postHelpRight').show();
      $('#helpContent').html('<span class="helpHead">Job Description</span><p>Secure best talent and attract more Bids by providing a detailed Job Description. E.g. </p><ul class="helpList"> <li>If it\'s a sales Job, give details of your product, what makes it so sellable, give realistic sales targets and why you think they are achievable.</li><li>If it\'s a translation / writing Job specify the number of words, tone and purpose.</li><li>If it\'s a technical Job attach a technical spec if possible or a functional requirements list. </li><li>If it\'s a design Job try to show similar designs you like, detailing the \'look and feel\' and the formats you need the end design in. </li></ul>');
      });
    $('#comment').blur(function(){$('#postHelpRight').hide();$('#postContainerRight').show();});
    $('#comment').keyup(function(){checkDataFilled();check_desc();});
    $('#yp_name').keyup(function(){checkDataFilled();});

  //  $('#txtAreaComStr').val('e.g. 20% commission up to 100 sales/month');
  //  $('#txtAreaComStr').css({color:'#5D5D5D'});
    $('#txtAreaComStr').focus(function(){
     var str = $(this).val();
         if (str.substring(0,41) == 'e.g. 20% commission up to 100 sales/month')
        {
            $(this).val('');
            $(this).css({color:'#000'});
        }
     });

    $('#hourlyJobRd').click(function(){
        //logdata
        logData('jobtype','H','Y');

        //Hiding Help Widget of Commission Job
        $('#postHelpRight').hide();

        //Hiding Forms for the other 2 Job types
        $('#fixedJob').hide();
        // $('#commissionJob').hide();

        //Showing Hourly Job Selectors
        $('#hourlyJob').show();
        $('#hourly_budget_min').focus();
    });
    $('#fixedJobRd').click(function(){
        //logdata
        logData('jobtype','F','Y');

        //Hiding Help Widget of Commission Job
        $('#postHelpRight').hide();

        //Hiding Forms for the other 2 job types
        // $('#commissionJob').hide();
        $('#hourlyJob').hide();

        //Showing Fixed Job Budget Selectors & focusing on first input.
        $('#fixedJob').show();
        $('#fixed_budget_min').focus();
    });
    $('#commissionJobRd').click(function(){
        //logdata
        logData('jobtype','B','Y');

        $('#fixedJob').hide();
        $('#hourlyJob').hide();
        $('#commissionJob').show();
        $('#postHelpRight').css('padding-top','0px');
        $('#postHelpRight').show();
        $('#helpContent').html('<span class="helpHead">Base + Result fee</span><p>Choose this option if you want to reward the Freelancer for their time plus results achieved (e.g. sales achieved or leads generated).</p><p><strong>To attract good talent we recommend that you</strong></p><ol class="helpListBudget"><li>Offer a Base Fee to incentivise top talent to commit time to your Job.</li><li>Set realistic targets that are believable and achievable.</li><li>Make sure the target earnings are competitive.</li><li>Describe your proposition in detail (click back to amend).</li></ol>');
   });

    $('#targetType').change(function(){
        if($(this).val() == 'Other'){
            $('#txtOtherValue').show();
        }
        else{
            $('#txtOtherValue').hide();
        }
    });
    $('#chkWhobid').change(function(){
        if($(this).val() == 'I'){
            $('#countryList').hide();
            $('#whereBid').val('ALL');
        }
        else
        {
            $('#countryList').show();
        }
    });

    $('#hideJobLoc').click(function(){
        $('#jobLocation').hide();
    });

    $('#showJobLoc').click(function(){
        $('#jobLocation').show();
    });

    $("#privacySelect").change(function(){
        $("#" + this.value + 'msg').show().siblings().hide();
    });

    $('#feature_duration').change(function(){
        if($(this).val()=='3'){
            $('#feaprice').html(postingform_data.fprice[0]);
        }
        else if($(this).val()=='7'){
            $('#feaprice').html(postingform_data.fprice[1]);
        }
        else if($(this).val()=='30'){
            $('#feaprice').html(postingform_data.fprice[2]);
        }
    });

    /* change the commitment time phrase based on the budget time choosen */
    $('select[name=hourly_budget_time]').bind('click change', function(){
        var value = ($(this).val() == 'Per Hour') ? 'Hours' : 'Days';
        $('#commitment_time_show').html(value + ' Per Week');
        $('input[name=commitment_time]').val(value);
        logData('budget_range_type','hourly_budget_time');
    });
    $('input[name=week_commitment], input[name=commitment_num]').bind('click', function(){
        if($('#hour_budget_range').is(':checked')) {
          $('input[name=hourly_budget_time],select[name=hourly_budget_time]').trigger('click');
        }
    });
    /* reset the commitment time to hours */
    $('#hour_budget_ID').bind('click change', function(){
        $('#commitment_time').html('Hours Per Week');
    });
    /* recall the commitment_time change */
    $('#hour_budget_range').bind('click change', function(){
        $('select[name=hourly_budget_time]').click();
    });
    $('#txtBaseFee,#baseFeeType').focus(function(){$('#postHelpRight').css('padding-top','85px');
                                    $('#postHelpRight').show();
                                                               $('#helpContent').html('<span class="helpHead">Base Fee</span><p>We <strong>highly recommend </strong>you include a Base Fee as this is a very competitive category and the best talent will tend to not work for a % of sales only.</p>A good way to go is to include a modest day rate/weekly pay for the Freelancer and then a more aggressive result-based fee structure below.');
                                                               });
   // $('#txtBaseFee').blur(function(){$('#postHelpRight').hide();});

    $('#txtTime,#timeCommitmentType').focus(function(){$('#postHelpRight').css('padding-top','165px');
                                    $('#postHelpRight').show();
                                                               $('#helpContent').html('<span class="helpHead">Time commitment needed from Freelancer</span><p>Is there a minimum amount of hours you want the Freelancer to commit to on this Job?</p>This is important if you have a Base Fee - make sure that the Freelancer has that amount of time free in their calendar.');
                                                               });
   // $('#txtTime').blur(function(){$('#postHelpRight').hide();});

    $('#txtTarget,#targetType,#oteType').focus(function(){$('#postHelpRight').css('padding-top','265px');
                                    $('#postHelpRight').show();
                                                               $('#helpContent').html('<span class="helpHead">Please state <u>realistic</u> targets for Freelancers to achieve</span><p>For example: weekly sales or number of calls or leads to be generated within a specified time period.</p> It is <strong>very important</strong> to set realistic, believable targets to attract good talent. Jobs with unrealistic targets will tend to be ignored.');
                                                               });
   // $('#txtTarget').blur(function(){$('#postHelpRight').hide();});

    $('#txtAreaComStr').focus(function(){
        var targetTypeDisp = 'targets met';
        if ($('#targetType').val() != '') {
            if ($('#targetType').val() != 'Other') {
                str =  $('#targetType').val();
                targetTypeDisp = str.substring(0, str.length-1);
            } else if($('#txtOtherValue').val() !='') {
                targetTypeDisp = escape($('#txtOtherValue').val());
            }
        }

        $('#postHelpRight').css('padding-top','435px');
        $('#postHelpRight').show();
        //$('#helpContent').html('<span class="helpHead">What are you offering the Freelancer per '+targetTypeDisp+'?</span><p> This could be a flat fee per call, lead or unit sold, or a % commission fee on sales they achieve.</p> <p><strong>Unrealistic targets will tend to get no bids - so make sure you enter achievable targets.</strong></p><p>If you have set a low Base Fee we recommend you set a more aggressive  Results Fee to incentivise good Freelancers to bid for your Job. </p>For  e.g. it is not uncommon when selling rolling contracts (e.g. advertising  contracts) to offer the first one or two month\'s sales to the  Freelancer.');
        $('#helpContent').html('<span class="helpHead">Bonus structure</span><p>In addition to offering a base fee, a bonus scheme/structure is a great  way of incentivising Freelancers and attracting top talent for your Job.</p><p>Bonus schemes typically reward Freelancers that exceed their targets  more generously by offering a higher results fee if the targets are  outperformed.</p><p>For example: it is not unusual to offer a bonus structure that offers a  higher % reward to the Freelancer for each sale made over and above the  target set for the week or month.</p><p>Alternatively, the bonus could be a  flat amount that is paid to the Freelancer once an agreed volume of  sales is reached.</p><strong>Unrealistic targets will tend to get no bids so make sure you enter achievable targets and a realistic bonus scheme. </strong>');
    });
    $('#txtAreaComStr').blur(function(){$('#postHelpRight').hide();});

    $('#txtOte').focus(function(){$('#postHelpRight').css('padding-top','360px');
    $('#postHelpRight').show();
    $('#helpContent').html('<span class="helpHead">Result Fee: What will the Freelancer earn if they meet their targets?</span><br>' +
        '<br>This is calculated on the basis of: Results Fee = targets x result fee per target<br>' +
        '<br>Example 1<br>' + selectedCurrency + '5000 monthly sales x 50% commission = ' + selectedCurrency + '2500 per month Result Fee<br>' +
        '<br>Example 2<br>100 leads per month @ ' + selectedCurrency + '10 per lead = ' + selectedCurrency + '1000 per month Result Fee.');});
    $('#txtOte').blur(function(){$('#postHelpRight').hide();});

    $('#txtBaseFee').keyup(function(){updatebasefee();});
    $('#baseFeeType').change(function(){updatebasefee();});
    $('#txtTime').keyup(function(){updatebasefee();});
    $('#timeCommitmentType').change(function(){var value = $('#timeCommitmentType').val();
                                            if($('#oteType').val() == '')
                                             $('#oteType').val(value);
                                             updatebasefee();});
    $('#txtTarget').keyup(function(){updateResultFee();});
    $('#targetType').change(function(){updateResultFee();});
    $('#txtOtherValue').keyup(function(){updateResultFee();});
    $('#oteType').change(function(){updateResultFee();});
    $('#txtOte').keyup(function(){var oteFee = parseFloat($('#txtOte').val()).toFixed(2);
                                if(isNaN(oteFee))oteFee='0.00';
                                      $('#resultFeeDiv').html(oteFee);
                                      updateOTE();
                                    });

    // Project Posting Guidlines Modal Box Start
    $('.openGuidlinesDialog').click(function(){$("#guidlinesDialog").dialog("open");return false;});
    $("#guidlinesDialog").dialog({
        modal: true,
        autoOpen: false,
        width: 750,
        height: 500,
        overlay: {
            opacity: 0.5,
            background: "black"
        },
        buttons: {
            Close: function() {
                $(this).dialog('close');
            }
        }

    });

    // JQuery Modal Dialog Box
    $('.openDialog').click(function() {
        openDialogClick();
        return false;
    });

    //$('.closeDialog').click(function(){$("#dialog").dialog("close");return false;});

    $("#dialogRegisterNow").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        width: 660,
        position: ["center",10],
        overlay: {
            opacity: 0.5,
            background: "black"
        }
    });

    $("#dialogRegisterNow .dialogBack").click(function(e){
        $("#dialogRegisterNow").dialog("close");
        $('#noAuth-register').hide();
        $('#noAuth-login').show();
        $('#dialog').dialog("open");
        e.preventDefault();
    });

    $("#dialogRegisterNow .dialogOk").click(function(e){
        $("#dialogRegisterNow").dialog("close");
        e.preventDefault();
    });

    $("#dialogRegisterNow .dialogRegister").click(function(e){
        $("#dialogRegisterNow").dialog("close");
        $('#dialog').dialog("open");
        $('#noAuth-register').show();
        $('#noAuth-login').hide();
        e.preventDefault();
    });

    $("#dialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        width: 660,
        position: ["center",10],
        overlay: {
            opacity: 0.5,
            background: "black"
        },
        close: function() {
            $('#dialogRegisterNow').dialog("open");
        }
    });

    // JQuery Click handlers to blank out password of other tab in form (otherwise form may not submit due to invaid email)
    $('#optR').click(
        function(){
            $('#txtEmail').val('');
        }
    );
    $('#optL').click(
        function(){
            $('#txtRemail').val('');
            $('#txtCemail').val('');
            $('#txtPassword').val('');
            $('#txtCpassword').val('');
        }
    );

    // Use JQuery.validator to validate login/registration popup form
    $("#f2").validate({
        rules: {
            // Existing member login form
            txtEmail: {
                required: function() {return $('#optL').is(':checked');},
                email: true
            },
            txtPwd: {required: function() {return $('#optL').is(':checked');}},

            // New member registration form
            txtFname: {required: function() {return $('#optR').is(':checked');}},
            txtPhone: {required: function() {return $('#optR').is(':checked');}},
            txtLname: {required: function() {return $('#optR').is(':checked');}},
            postcode: {required: function() {return $('#optR').is(':checked');}},
            txtRemail: {
                required: function() {return $('#optR').is(':checked');},
                emailButAllowTrailingWhitespace: true
            },
            txtPassword: {required: function() {return $('#optR').is(':checked');}},
            txtCemail: {
                required: function() {return $('#optR').is(':checked');},
                equalTo: "#txtRemail"
            },
            txtCpassword: {
                required: function() {return $('#optR').is(':checked');},
                equalTo: "#txtPassword"
            },
            selIndustry: {required: function() {return $('#optR').is(':checked');}},
            txtIndustry: {required: function() {return ($('#optR').is(':checked') && $('#selIndustry').val() == 35);}},
            selReference: {required: function() {return $('#optR').is(':checked');}},
            agency: {required: function() {return $('#optR').is(':checked');}},
            employees: {required: function() {return $('#optR').is(':checked');}},
            txtOthers: {required: function() {return ($('#optR').is(':checked') && $('#selReference').val() == 4);}},
            chk_terms: {required: function() {return $('#optR').is(':checked');}}
        },
        errorPlacement: function(error, element) {
             if (element.attr("name") == "txtEmail")
               error.insertAfter("#emailError");
             else if (element.attr("name") == "txtPwd")
               error.insertAfter("#pwdError");
             else if (element.attr("name") == "txtFname")
               error.insertAfter("#txtFnameError");
             else if (element.attr("name") == "txtPhone")
               error.insertAfter("#txtPhoneError");
             else if (element.attr("name") == "txtLname")
               error.insertAfter("#txtLnameError");
             else if (element.attr("name") == "postcode")
               error.insertAfter("#postcodeError");
             else if (element.attr("name") == "txtRemail")
               error.insertAfter("#txtRemailError");
             else if (element.attr("name") == "txtPassword")
               error.insertAfter("#txtPasswordError");
             else if (element.attr("name") == "txtCemail")
               error.insertAfter("#txtCemailError");
             else if (element.attr("name") == "txtCemail")
               error.insertAfter("#txtCemailError");
             else if (element.attr("name") == "txtCpassword")
               error.insertAfter("#txtCpasswordError");
             else if (element.attr("name") == "selIndustry")
               error.insertAfter("#selIndustryError");
             else if (element.attr("name") == "txtIndustry")
                   error.insertAfter("#txtIndustryError");
             else if (element.attr("name") == "agency")
                   error.insertAfter("#agencyError");
             else if (element.attr("name") == "employees")
                   error.insertAfter("#employeesError");
             else if (element.attr("name") == "selReference")
               error.insertAfter("#selReferenceError");
             else if (element.attr("name") == "txtOthers")
                   error.insertAfter("#txtOthersError");
             else if (element.attr("name") == "chk_terms")
               error.insertAfter("#chk_termsError");
             else
               error.insertAfter(element);
        }
    });

    // Define dialog box to show when uploading a file
    $("#loadingDialog").dialog({
        modal: true,
        autoOpen: false,
        width: 350,
        overlay: {
            opacity: 1.5,
            background: "black"
        },
        closeOnEscape: false,
        // Hide close controls
        open: function(event, ui) {$(".ui-dialog-titlebar-close").hide();}
    });

    // Define dialog box to show file uploading Error message
    $("#confirmDialog").dialog({
        modal: true,
        autoOpen: false,
        width: 450,
        overlay: {
            opacity: 1.5,
            background: "black"
        },
        buttons: {
            OK: function() {
                $(this).dialog('close');
            }
        }
    });

    new Ajax_upload('#aJaxUpload', {
        action : 'ajax/ajaxFileUpload.php',
        name: 'uploadFile',
        data: {uploadType : 'JobFileAttachment'},
        // Fired when user selects file
        onSubmit: function(file, extension) {
            if (uploadCount >= uploadMax) {
                alert('You can not attach more than '+uploadMax+' files.')

                return false; // cancel upload
            }
            var unAllowedFileTypes = new Array('ade','adp','bas','bat','chm','cmd','com','cpl','crt','eml','exe','hlp','hta','inf','ins','isp','js','jse','lnk','mdb','mde','msc','msi','msp','mst','pcd','php','pif','reg','scr','sct','shs','url','vbs','vbe','wsf','wsh','wsc');
            if (jQuery.inArray(extension.toString(), unAllowedFileTypes ) >= 0) {
                // This file extension is not allowed
                $('#fileUploadDiv .text').html(extension + ' files are not currently supported.<br>Please email us at <img src="images\/info_email.JPG" align="absmiddle" /> for support.');

                return false; // cancel upload
            }
            // Show loading dialog box
            $("#loadingDialog").dialog('open');
        },
        // Fired when server returns something
        onComplete : function(file, response){

            var resMsg = response.split(":");

            if (resMsg[0] == "success") {
                uploadCount++;

                // Strip off sub-directory and file timestamp when displaying to user (e.g. dirname/100422125450_)
                var fileNameToDisplay = resMsg[2];

                $('<li></li>').appendTo($('#fileUploadDiv .files')).html('<font color="green">Uploaded</font> ' + fileNameToDisplay + " <img src=\"images/icons/delete_attach.png\" onclick=\"javascript:removeFile("+uploadCount+")\" />");
                $('#fileUploadDiv .text').html('<p>Uploaded files:</p>');

                if (uploadMax-uploadCount == 1) {
                    $('#fileUploadDiv .text2').html('(' + (uploadMax-uploadCount) + ' more file can be uploaded)');
                } else {
                    // Plural version
                    $('#fileUploadDiv .text2').html('(' + (uploadMax-uploadCount) + ' more files can be uploaded)');
                }

                // Save this file name and location in a hidden form field.
                document.f1["ProjectFile"+uploadCount].value = resMsg[1];
                logData('attachment'+uploadCount,'ProjectFile'+uploadCount);

                // Display Attachment on page
                $('#fileUploadDiv .text').text('Attachment: ' + fileNameToDisplay);

                // Hide loading dialog box
                $("#loadingDialog").dialog('close');
            } else {
                $("#loadingDialog").dialog('close');
                // Display file upload error
                $("#confirmDialog").html(response);
                $("#confirmDialog").dialog('open');
            }
        }
    });

    // Reload form values
    var reloadForm = $(location).attr('href').lastIndexOf('reloadForm') > 0;
    var postForm = $(location).attr('href').lastIndexOf('postForm') > 0;
    if(reloadForm || postForm) {
        jQuery.ajax({
            'type': 'GET',
            'cache': false,
            'url': '/ajax/post_req1_session.php',
            'dataType': 'json',
            'success': function(data) {
                for (var key in data) {

                    var value = data[key];
                    var found = false;

                    // look for input and text fields
                    $('#postProjectForm input[name=' + key + ']')
                            .add('#postProjectForm textarea[name=' + key + ']')
                            .each(function(){
                        var elem = $(this);
                        var type = elem.attr('type');
                        if(type == 'radio') {
                            if(elem.attr('value') == value) {
                                elem.attr('checked', 'checked');
                            } else {
                                elem.attr('checked', '');
                            }
                            found = true;
                        } else if(type == 'text' ||
                                  type == 'textarea' ||
                                  type == 'hidden') {
                            elem.val(value);
                            found = true;
                        } else {
                            alert('unhandled type: ' + type);
                        }
                    });

                    if(!found) {
                        $('#postProjectForm select[name=' + key + '] option').each(function(){
                            var elem = $(this);
                            if(elem.attr('value') == value) {
                                elem.attr('selected', 'selected');
                            } else {
                                elem.attr('selected', '');
                            }
                            found = true;
                        });
                    }
                }

                getSubCategory(
                    $('#category').val(),
                    function() {
                        $('#rad option[value=' + data.rad + ']').attr('selected', 'selected');
                        // now decide whether to post or check
                        if(postForm && postingform_data.loggedin) {
                            checkAdFrm(document.f1);
                        } else {
                            $('#postContainerRight').hide();
                            checkFrmPage2();
                        }
                    }
                );
            }
        });
    }

    // At each step of the process we should post to a form so we can restore values more easily later
    $('.openDialog,.postContinue a').click(function() {
        jQuery.ajax({
            'type': 'POST',
            'cache': false,
            'url': '/ajax/post_req1_session.php',
            'data': $('#postProjectForm').serialize(),
            'dataType': 'json'
        });
    });

    // warning message should not come for social buttons
    $('.social-buttons,.signup-icons a').click(function() {
        checkExit = false;
    });

    var changeCurrency = function() {
        // this is a global var defined at the top!
        selectedCurrency = $('#projectCurrency').find(':selected').attr('data-symbol');
        $('.currencyPlaceholder').html(selectedCurrency);
    };

    $('#projectCurrency').change(function(){
        changeCurrency();
    });
    changeCurrency();
    /* Handling the new "Choose Budget" widget/popup */
    $(".choose-budget a").live('click',function(e){
        e.preventDefault();
        var subcid = $("#rad").val();
        var type = $("input[type=radio]:checked").val();
        var currency = $('#projectCurrency').find(':selected').val();
        var data = "type="+type+"&subcid="+subcid+'&currency='+currency;
        $("#budget-chooser-modal").dialog("open");
        $("#budget-chooser-modal input[type=text]").blur();
        $("#budget-chooser-modal input[type=text]").val($("#budget-chooser-modal input[type=text]").attr('placeholder'));
        getAwardedJobs(data);
    });

    /*Search through the pagination buttons*/
    $("#budget-chooser-modal .pagination a").live('click',function(){
        var key='';
        var subcid = $("#rad").val();
        var type = $("input[type=radio]:checked").val();
        var page = $(this).attr('page');
        var currency = $('#projectCurrency').find(':selected').val();
        if ($("#budget-chooser-modal input[type=text]").val() != $("#budget-chooser-modal input[type=text]").attr('placeholder'))
            key = $("#budget-chooser-modal input[type=text]").val();
        var data = "type="+type+"&subcid="+subcid+"&page="+page+"&key="+key+'&currency='+currency;
        getAwardedJobs(data);
    });
    /* Trigger search through the search button */
    $("#budget-chooser-modal input[type=button]").live('click',function(){
        var key='';
        var subcid = $("#rad").val();
        var type = $("input[type=radio]:checked").val();
        var currency = $('#projectCurrency').find(':selected').val();
        if ($("#budget-chooser-modal input[type=text]").val() != $("#budget-chooser-modal input[type=text]").attr('placeholder'))
            key = $("#budget-chooser-modal input[type=text]").val();
        var data = "type="+type+"&subcid="+subcid+"&page=1&key="+key+"&currency="+currency;
        getAwardedJobs(data);
    });
    /* Trigger search on enter */
    $("#budget-chooser-modal input[type=text]").keypress(function(e){
        if ( e.which == 13 ) {
            var key='';
            var subcid = $("#rad").val();
            var type = $("input[type=radio]:checked").val();
            var currency = $('#projectCurrency').find(':selected').val();
            if ($("#budget-chooser-modal input[type=text]").val() != $("#budget-chooser-modal input[type=text]").attr('placeholder'))
                key = $("#budget-chooser-modal input[type=text]").val();
            var data = "type="+type+"&subcid="+subcid+"&page=1&key="+key+"&currency="+currency;
            getAwardedJobs(data);
       }
    });

    /* Definition of The modal */
    $("#budget-chooser-modal").dialog({
            modal: true,
            autoOpen: false,
            minHeight: 400,
            width: 400,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            open: function(event, ui) {$(".ui-dialog-titlebar-close").show();}
     });

     /* Fetch Search Results */
     getAwardedJobs = function(data){
        $("#budget-chooser-modal .pagination").html('');
        $("#budget-chooser-modal .jobs-container").html('');
        $("#budget-chooser-modal .loader").removeClass('hidden');

        $.ajax({
            url: 'ajax/getAwardedJobs.php',
            type: 'post',
            data: data,
            dataType:'html',
            success: function(r){
                if(r){
                    $("#budget-chooser-modal .loader").addClass('hidden');
                    $("#budget-chooser-modal .jobs-container").html(r);
                    $("#budget-chooser-modal .pagination").html($("#budget-chooser-modal .jobs-container .apagination").html());
                    $("#budget-chooser-modal .jobs-container .apagination").remove();
                }
            }
        });
     }

     /* Cross Browser Placeholder Attribute*/
    $("'[placeholder]'").focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == "" || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
});

// function to remove a file that has been uploaded
function removeFile(fileToRmove) {
    var fileString = "";
    for (var i=1;i<=uploadCount;i++) {
        var elem = document.f1["ProjectFile"+i];

        if (i==fileToRmove) {
            // aJax call to actually delete file (directory is stripped off on server-side)
            $.get("ajax/postProjectFileDelete.php?file="+elem.value);

            // re-jig the javascript variables holding file names
            if (i==uploadCount) {
                // Last file so, we can blank it
                elem.value = "";
            } else {
                // Move the last file to the current position and blank the last file
                elem.value = document.f1["ProjectFile"+uploadCount].value
                document.f1["ProjectFile"+uploadCount].value = "";
            }
        }
        if (elem.value) {
            // Strip off sub-directory and file timestamp when displaying to user (e.g. dirname/100422125450_)
            var fileNameToDisplay = elem.value.replace(/^.*\/\d{12}\_/,"");
            fileString += '<li><font color="green">Uploaded</font> ' + fileNameToDisplay + " <img src=\"images/icons/delete_attach.png\" onclick=\"javascript:removeFile("+i+")\" /></li>"
        }
    }
    uploadCount--;

    $('#fileUploadDiv .files').html(fileString);
    if (uploadCount == 0) {
        $('#fileUploadDiv .text').html('');
    } else {
        $('#fileUploadDiv .text').html('<p>Uploaded files:</p>');
    }
    $('#fileUploadDiv .text2').html('(' + (uploadMax-uploadCount) + ' more files can be uploaded)');
}

//Warn user before they exit the form and loss all the data they have already entered
var checkExit = false;
window.onbeforeunload = function()
{
    if (checkExit) {
        return "Any Job details typed in would be lost.\nNeed Help? Call PeoplePerHour at +44 (0)20 7835 5950 Mon-Fri, 9am-6:30pm UK time";
    }
}
function updatebasefee(){
  var baseFeeTxt = '';
  var basefeeval=0;
  var basFeeRate=$('#txtTime').val();
  var rateVal =$('#txtBaseFee').val() ;
  var perRate = $('#baseFeeType').val();

  if($('#txtBaseFee').val() > 0 && $('#txtTime').val() > 0){
    if($('#baseFeeType').val() == 'Hour'){
      if($('#timeCommitmentType').val()=='Day'){
        if($('#oteType').val() == 'Day'){
          basefeeval = $('#txtBaseFee').val()*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Week'){
          basFeeRate = $('#txtTime').val()*5;
          basefeeval = $('#txtBaseFee').val()*$('#txtTime').val()*5;
        }
        else if($('#oteType').val() == 'Month'){
          basFeeRate = $('#txtTime').val()*20;
          basefeeval = $('#txtBaseFee').val()*basFeeRate;
        }
      }
      else if($('#timeCommitmentType').val()=='Week'){
        if($('#oteType').val() == 'Day'){
          basFeeRate = $('#txtTime').val()/5;
          basefeeval = ($('#txtBaseFee').val()/5)*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Week'){
          basefeeval = $('#txtBaseFee').val()*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Month'){
          basFeeRate = $('#txtTime').val()*4;
          basefeeval = $('#txtBaseFee').val()*$('#txtTime').val()*4;
        }
      }
      else if($('#timeCommitmentType').val()=='Month'){
        if($('#oteType').val() == 'Day'){
          basFeeRate = $('#txtTime').val()/20;
          basefeeval = ($('#txtBaseFee').val()/20)*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Week'){
          basFeeRate = $('#txtTime').val()/4;
          basefeeval = ($('#txtBaseFee').val()/4)*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Month'){
          basefeeval = $('#txtBaseFee').val()*$('#txtTime').val();
        }
      }
    }
    if($('#baseFeeType').val() == 'Day'){
      if($('#timeCommitmentType').val()=='Day'){
        rateVal = $('#txtBaseFee').val()/8;
        perRate = 'hour';
        if($('#oteType').val() == 'Day'){
          basefeeval = rateVal*$('#txtTime').val();
        }
        else if($('#oteType').val() == 'Week'){
          basFeeRate = $('#txtTime').val()*5;
          basefeeval = rateVal*basFeeRate;
        }
        else if($('#oteType').val() == 'Month'){
          basFeeRate = $('#txtTime').val()*20;
          basefeeval = rateVal*basFeeRate;
        }
      }
      if($('#timeCommitmentType').val()=='Week'){
        rateVal = $('#txtBaseFee').val()/8;
        perRate = 'hour';
        if($('#oteType').val() == 'Day'){
          basFeeRate = $('#txtTime').val()/5;
          basefeeval = rateVal*basFeeRate;
        }
        else if($('#oteType').val() == 'Week'){
          basFeeRate = $('#txtTime').val();
          basefeeval = rateVal*basFeeRate;
        }
        else if($('#oteType').val() == 'Month'){
          basFeeRate = ($('#txtTime').val()/5)*20;
          basefeeval = rateVal*basFeeRate;
        }
      }
      if($('#timeCommitmentType').val()=='Month'){
        rateVal = $('#txtBaseFee').val()/8;
        perRate = 'hour';
        if($('#oteType').val() == 'Day'){
          basFeeRate = $('#txtTime').val()/20;
          basefeeval = rateVal*basFeeRate;
        }
        else if($('#oteType').val() == 'Week'){
          basFeeRate = $('#txtTime').val()/4;
          basefeeval = rateVal*basFeeRate;
        }
        else if($('#oteType').val() == 'Month'){
          basFeeRate = $('#txtTime').val();
          basefeeval = rateVal*basFeeRate;
        }
      }
    }
  baseFeeTxt=' For '+basFeeRate+' Hours/'+$('#oteType').val()+' @ ' + selectedCurrency + rateVal + '/' + perRate;
  }
  document.f1.totalBaseFee.value = basefeeval;
  $('#showBaseFeeFinal').html(basefeeval.toFixed(2));
  logData('totalbasefee','totalBaseFee');

  if(baseFeeTxt==''){
  baseFeeTxt = '<span class="smRedTxt">To secure best talent we recommend that you specify a Base Fee.<br>&nbsp;</span>';
  if($('#txtTime').val() <1 || $('#timeCommitmentType').val() == '')
  baseFeeTxt = '<span class="smRedTxt">To secure best talent we recommend that you specify a Base Fee and Time Commitment needed.<br>&nbsp;</span>';

  $('#basFeeUnits').html('<span class="smRedTxt">(recommended)</span>');
  }
  else
  $('#basFeeUnits').html('(Per '+$('#oteType').val()+')');

  $('#showBaseFeeText').html(baseFeeTxt);
  updateOTE();
}
function updateResultFee(){
  var feeText = '';
  var targetFee = 0;
  var targetTypeDisp='target met';
  if($('#txtTarget').val()!= ''){
    targetFee=$('#txtTarget').val();
  }
  else
  targetFee=0;

  if(targetFee!=''){
    feeText = 'For '+targetFee;
  if($('#targetType').val() != ''){
    if($('#targetType').val() != 'Other')
    feeText+=' '+$('#targetType').val();
    else if($('#txtOtherValue').val() !='')
    feeText+=' '+escape($('#txtOtherValue').val());
  }

if($('#oteType').val() != ''){
    feeText+=' Per '+$('#oteType').val();
    $('#showResultFeeUnits').html(' (Per '+$('#oteType').val()+')');
  }
  }

  if($('#targetType').val() != ''){
    if($('#targetType').val() != 'Other'){
    str =  $('#targetType').val();
    targetTypeDisp = str.substring(0, str.length-1);
    }
    else if($('#txtOtherValue').val() !='')
    targetTypeDisp = escape($('#txtOtherValue').val());
  }

  $('#showResultFee').html(feeText);
  $('#showResultFeeFinal').html(feeText);
  $('#showTargetType').html(targetTypeDisp);
  updatebasefee();
  updateOTE();
}
function updateOTE(){
  var finalOTE=0;
  var oteVal=0;
  var oteTypeText='';
  if($('#txtOte').val() >0 ){
    oteVal = $('#txtOte').val();
  }
  else oteVal = 0;

  if($('#totalBaseFee').val() >0){
  finalOTE = parseFloat(oteVal)+parseFloat($('#totalBaseFee').val());
  finalOTE=finalOTE.toFixed(2);

  logData('ote',finalOTE,'Y');

  $('#basFeeUnits').html('(Per '+$('#oteType').val()+')');
    }
    else
    {finalOTE = parseFloat(oteVal).toFixed(2);
    if(isNaN(finalOTE))finalOTE='0.00';
    var errorTxt = 'To secure best talent we recommend that you specify a Base Fee.<br>&nbsp;';
      if($('#txtTime').val() <1 || $('#timeCommitmentType').val() == '')
      errorTxt = 'To secure best talent we recommend that you specify a Base Fee and Time Commitment needed.<br>&nbsp;';

      $('#showBaseFeeText').html('<span class="smRedTxt">'+errorTxt+'</span>');
      $('#basFeeUnits').html('<span class="smRedTxt">(recommended)</span>');
    }
  $('#oteFeeDiv').html(finalOTE);
  if($('#oteType').val() !='')
  oteTypeText='Per '+$('#oteType').val();
  else
  oteTypeText='';
  $('#oteFeeText').html(oteTypeText);
  if(oteTypeText!='')
  $('#showResultFeeUnits').html(' ('+oteTypeText+')');
}
function getSubCategory(str, callback){
    var list = document.getElementById('category');
    var listCount = list.options.length;

    for(var i = 0; i < listCount; i++) {
        var catId = list.options[i].value;
        if (catId != "") {
            $('#rad').val("");
            $('#showSubcat').hide();
        }
    }
    if (str > 0) {
        var subCatOptionsData = $('#rad'+str).html();
        $('#rad').html(subCatOptionsData);
        $('#showSubcat').show();
    }
}
function checkDataFilled()
{
    var titleText =  trim(document.getElementById("yp_name").value);
    var catText =  document.getElementById("category").value;
    var jobDescText =  trim(document.getElementById("comment").value);
    if(titleText != "" || catText != "" || jobDescText != "") {
        checkExit = true; // Now that the user has entered some data, warn them before exiting
    } else {
        checkExit = false; // Now that the user has not entered any data, dont warn them before exiting
    }
}
function check_desc()
{
    var lyr = 'descriptionCheck2';
    document.getElementById(lyr).style.display = 'block';
    var str = trim(document.f1.comment.value);

    if (str.substring(0,28) != 'Enter your requirements here')
    {
        if (str.length > 0) {
            if (str.length == 1)
                document.getElementById("numChars").innerHTML='1 Character - ';
            else
                document.getElementById("numChars").innerHTML= str.length+' Characters - ';
        } else {
            document.getElementById("numChars").innerHTML= '0 Characters - ';
        }

        helpText = "<a href=\"#\" onclick=\"javascript:return showHelp('Description');\" class=\"helplink\">help?</a>";

        if(str.length < 300){
        document.getElementById("descDetails").innerHTML='<strong>Short</strong> - possibly not enough information entered. '+helpText;
        document.getElementById("str_indicator1").style.width='25%';
        document.getElementById("str_indicator1").style.background='red';
        document.getElementById("str_indicator2").style.width='75%';
        }
        else if(str.length > 300 && str.length < 400){
        document.getElementById("descDetails").innerHTML='<strong>OK</strong> - could benefit from some more detail. '+helpText;
        document.getElementById("str_indicator1").style.width='50%';
        document.getElementById("str_indicator1").style.background='yellow';
        document.getElementById("str_indicator2").style.width='50%';
        }
        else if(str.length > 400 && str.length < 500){
        document.getElementById("descDetails").innerHTML='<strong>Good</strong> Detail - appears to be detailed. .'+helpText;
        document.getElementById("str_indicator1").style.width='75%';
        document.getElementById("str_indicator1").style.background='green';
        document.getElementById("str_indicator2").style.width='25%';
        }
        else if(str.length > 500){
        document.getElementById("descDetails").innerHTML='<strong>Excellent</strong> Detail - well done! '+helpText;
        document.getElementById("str_indicator1").style.width='100%';
        document.getElementById("str_indicator1").style.background='green';
        document.getElementById("str_indicator2").style.width='0%';
        }

    } else {
        document.getElementById("str_indicator1").style.background='white';
    }
}
// Removes leading whitespaces
function LTrim( value ) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {

    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) {
    return LTrim(RTrim(value));
}

function stripCharsInBag (s, bag)
{
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
// Control which page of the form we are viewing. The visibility of the rest is set to zero.
var currentLayer = 'jobPage1';
function showLayer(lyr) {
   document.getElementById(currentLayer).style.display = 'none';
   document.getElementById(lyr).style.display = 'block';
   currentLayer = lyr;

   // Set the focus back to the top of the page
   document.getElementById('focusPoint').focus();
}
function isFloat (s)
{
    var reFloat = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;

    return reFloat.test(s);
}
function isInteger (s)
{
    var reInteger = /^\d+$/;
    return reInteger.test(s);
}

function changeClass(inputVal){
    if(inputVal.className == 'postTxtError'){
        inputVal.className = '';
    }
}

function checkFrmPage1()
{
    var frm = window.document.f1;
    generalJTerror = "Job Titles generally contain at least a few words.\nPlease enter a suitable Job Title.";

    // Validate Project title
    if( stripCharsInBag (frm.yp_name.value, " ") == "" )
    {
        alert(generalJTerror);
        $("#yp_name").focus();
        frm.yp_name.className='postTxtError';
        return false;
    }
    jobTitle = frm.yp_name.value.split(' ').join('');

    //check if only numerics and output related message
    var pattern=new RegExp("[^0-9]+", "g");
    var onlynumerics=pattern.test(jobTitle);
    if (!onlynumerics){
        alert(generalJTerror);
        frm.yp_name.focus();
        return false;
    }

    // Validate Project title isn't all in Uppercase - looks bad and screws up text width.
    if(frm.yp_name.value == frm.yp_name.value.toUpperCase())
    {

        var pattern=new RegExp("[a-zA-Z]");
        var onlyspecialchars=pattern.test(jobTitle);
    if (!onlyspecialchars){
          alert(generalJTerror);
        frm.yp_name.focus();
        return false;
    }

        // Convert title to sentance case
        frm.yp_name.value = frm.yp_name.value.toLowerCase().replace(/(^\s*\w|[\.\!\?]\s*\w)/g,function(c){return c.toUpperCase()});

        alert("The Job Title has been converted from uppercase.");
        frm.yp_name.focus();
        return false;
    }

    // Validate Project Category
    if(frm.category.value == '')
    {
        alert("Please select the Category");
        frm.category.className='postTxtError';
        frm.category.focus();
        return false;
    }
    var rad = document.getElementById("rad");
    // Validate Project subcategory
    if(rad.value == '')
    {
        alert("Please select the Subcategory for the Job");
        rad.className='postTxtError';
        rad.focus();
        return false;
    }
    // Validate Project Description
    if( stripCharsInBag (frm.comment.value, " ") == "" || frm.comment.value.substring(0,28) == 'Enter your requirements here')
    {
        alert("Please enter the Job Description ");
        frm.comment.className='postTxtError';
        frm.comment.focus();
        return false;
    }

    // Page 1 seems valid, we should show page 2
    var lyr = 'descriptionCheck2';
   document.getElementById(lyr).style.display = 'none';

    showPage2();
    return false; // i.e. don't follow link
}
function optFor(oName,oVal)
{
     var inputName = document.getElementById(oName);
        inputName.checked=true;
        inputName.click();
}
function widget()
{
     $('#postSearchProjectRight').hide();
     return false;
}
/*function showBaseFee()
{
    var frm = document.f1;
    var chkbasefeevalue = getSelectedRadioValue(frm.rdBaseFee);
    if(chkbasefeevalue == 'baseFeeNego' || chkbasefeevalue == 'baseFeeNone'){
        frm.txtBaseFee.disabled = true;
        frm.baseFeeType.disabled = true;
    }else {
        frm.txtBaseFee.disabled = false;
        frm.baseFeeType.disabled = false;
    }
}
function showTargetRate()
{
    document.getElementById("target_rate").innerHTML = '';
   if(document.f1.oteType.value != ''){
    document.getElementById("target_rate").innerHTML = " Per "+document.f1.oteType.value;
   }
}*/
// Validate the user has entered correct details on page 2 of the form. If so, show page 3
function showPage1()
{
   logData('page2_bak_page1','1','Y');
   $('#needTxt').html('Need a Freelancer?');
    $('#middleTxt').html('Describe your Job below and we will help you find a great Freelancer!');
    $('#lastTxt').show();
    $('#postContainerRight').show();
    $('#postHelpRight').hide();
    showLayer('jobPage1');

    return false;
}

function showPage2(){
  $('#noPage3Container').show();
  var str='';
  //log data for 1st page
  str += "title=" + encodeURIComponent($('#yp_name').val()) + "&";
  str += "category=" + escape($('#category').val()) + "&";
  str += "subcategory=" + escape($('#rad').val()) + "&";
  str += "description=" + encodeURIComponent($('#comment').val()) + "&";
  if($('#ProjectFile1').val() != '')
  str += "attachment1=" + escape($('#ProjectFile1').val()) + "&";
  if($('#ProjectFile2').val() != '')
  str += "attachment2=" + escape($('#ProjectFile2').val()) + "&";
  if($('#ProjectFile3').val() != '')
  str += "attachment3=" + escape($('#ProjectFile3').val()) + "&";

  str += "page1=Y";
  logMultipleData(str);
  //
    $('#proOne').attr("class","current");
    $('#proOne > img').attr('src','images/num1_blue.png');
    $('#proTwo').attr("class","");
    $('#proTwo > img').attr('src','images/num2_gray.png');
    $('#needTxt').html('Just a few more details on your Job...');
    $('#middleTxt').html('Tell us about the type of Job and your budget');
    $('#lastTxt').hide();
    $('#postContainerRight').hide();
    showLayer('jobPage2');
    $('#page2titlebar').show();

    /* analytics: analyze the drop in the posting form */
    fireTracker('post_req1', 'Post_a_Job_2');

    return false;
}

function showPage3(){
  var str='';
  //log data for 1st page
  var btn1 = getSelectedRadioValue(document.f1.rdProjectType);
  if(btn1 == 'fixed_price'){
  str += "budget_range_max=" + encodeURIComponent($('#fixed_budget_max').val()) + "&";
  }
  else if(btn1 == 'hourly'){
  str += "budget_range_min=" + encodeURIComponent($('#hourly_budget_min').val()) + "&";
  str += "budget_range_max=" + encodeURIComponent($('#hourly_budget_max').val()) + "&";
  str += "budget_range_type=" + encodeURIComponent($('#hourly_budget_time').val()) + "&";

  var contract = 'N';
  var btn2 = getSelectedRadioValue(document.f1.con_dur);
  if(btn2 != '')
  contract = btn2;

  str += "contract_duration=" + contract + "&";

  str += "contract_num=" + encodeURIComponent($('#contract_num').val()) + "&";
  str += "contract_time=" + encodeURIComponent($('#contract_time').val()) + "&";

  var weekly = 'O';
  var btn3 = getSelectedRadioValue(document.f1.week_commitment);
  if(btn3 != '')
  weekly = btn3;

  str += "week_commitment=" + weekly + "&";

  str += "commitment_num=" + encodeURIComponent($('#commitment_num').val()) + "&";
  str += "commitment_time=" + encodeURIComponent($('#commitment_time').val()) + "&";
  }
  else if(btn1 == 'commission'){
  str += "base_fee=" + encodeURIComponent($('#txtBaseFee').val()) + "&";
  str += "base_fee_type=" + encodeURIComponent($('#baseFeeType').val()) + "&";
  str += "time_commitment=" + encodeURIComponent($('#txtTime').val()) + "&";
  str += "time_commitment_type=" + encodeURIComponent($('#timeCommitmentType').val()) + "&";
   str += "target_fee=" + encodeURIComponent($('#txtTarget').val()) + "&";
  str += "target_type=" + encodeURIComponent($('#targetType').val()) + "&";
  str += "target_time=" + encodeURIComponent($('#oteType').val()) + "&";
  str += "totalbasefee=" + encodeURIComponent($('#totalBaseFee').val()) + "&";
  str += "resultfee=" + encodeURIComponent($('#txtOte').val()) + "&";
    var oteVal = $('#totalbasefee').val()+$('#txtOte').val();
  str += "ote=" + oteVal + "&";
  str += "ote_type=" + encodeURIComponent($('#oteType').val()) + "&";
  str += "commission_structure=" + encodeURIComponent($('#txtAreaComStr').val()) + "&";
  }

  str += "est_job_starts=" + escape($('#start_date').val()) + "&";
  str += "bidding_ends=" + escape($('#rfp_duration').val()) + "&";
  str += "who_can_bid=" + escape($('#chkWhobid').val()) + "&";
  str += "where_can_bid=" + escape($('#whereBid').val()) + "&";

  var btn = getSelectedRadioValue(document.f1.loc);
  if(btn == 'Y')
  var loc = 'Remote';
  else
  var loc = document.f1.txtProjLoc.value;

  str += "job_location=" + loc + "&";
  str += "job_postcode=" + encodeURIComponent($('#txtPostcode').val()) + "&";
  //str += "private=" + escape($('#privacySelect').val()) + "&";
  str += "promo_code=" + encodeURIComponent($('#promo_code').val()) + "&";
  /*if(document.f1.chk2.checked == true){
  str += "urgent=" + escape($('#chk1').val()) + "&";
  }
  if(document.f1.chk2.checked == true){
  str += "featured=" + escape($('#chk2').val()) + "&";
  str += "featured_days=" + escape($('#feature_duration').val()) + "&";
  }*/

  str += "page2=Y&";
  logMultipleData(str);
    $('#proOne').attr("class","");
    $('#proOne > img').attr('src','images/num1_gray.png');
    $('#proTwo').attr("class","current");
    $('#proTwo > img').attr('src','images/num2_blue.png');
    $('#needTxt').html('You\'re almost there!');
    $('#middleTxt').html('This is how your Job listing will look like on the site');
    $('#lastTxt').hide();
    $('#postHelpRight').hide();
    // Because the form has changed, generate the form preview
    generateProjectPreview();
    showLayer('jobPage3');
    $('#noPage3Container').hide();
    /* analytics: analyze the drop in the posting form */
    fireTracker('post_req1', 'Post_a_Job_3');
}
function html_entity_decode(str)
{
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}
function checkFrmPage2()
{
    var frm = window.document.f1;
    var currency = html_entity_decode(selectedCurrency);

    // Validate Project type: Hourly, Fixed or commision
    var btn = getSelectedRadioValue(frm.rdProjectType);
    if (btn == "")
    {
     alert('Please select How would you like to be quoted?');
     return false;
    }
    // Validate project range
    if(btn=='fixed_price')
    {
       if(frm.fixed_budget_min.value == '' && frm.fixed_budget_max.value > 0){
           alert("Please Enter The Minimum Budget Range Value");
           frm.fixed_budget_min.className='postTxtError';
           frm.fixed_budget_min.focus();
           return false;
       }else if(isNaN(frm.fixed_budget_min.value)){
           alert("Only numbers are allowed in the Minimum Budget Range Value field.\nPlease make sure that you have not entered any other characters");
           frm.fixed_budget_min.className='postTxtError';
           frm.fixed_budget_min.focus();
           return false;
       }else if(frm.fixed_budget_min.value < 40 && frm.fixed_budget_min.value != ''){
           alert("To maintain a fair price for skill, time and effort put in by our Freelancers,\nPPH does not allow minimum Budget Range to be less than "+currency+"40 for Fixed Price Jobs.");
           frm.fixed_budget_min.className='postTxtError';
           frm.fixed_budget_min.focus();
           return false;
       }

      if(frm.fixed_budget_max.value == '' && frm.fixed_budget_min.value > 0){
           alert("Please Enter The Maximum Budget Range Value");
           frm.fixed_budget_max.className='postTxtError';
           frm.fixed_budget_max.focus();
           return false;
       }else if(isNaN(frm.fixed_budget_max.value)){
           alert("Only numbers are allowed in the Maximum Budget Range Value field.\nPlease make sure that you have not entered any other characters");
           frm.fixed_budget_max.className='postTxtError';
           frm.fixed_budget_max.focus();
           return false;
       }else if(parseFloat(frm.fixed_budget_max.value) <= parseFloat(frm.fixed_budget_min.value)){
           alert("Maximum Budget Range Value can't be less than Minimum Budget Range Value.");
           frm.fixed_budget_max.className='postTxtError';
           frm.fixed_budget_max.focus();
           return false;
       }
    }
    //Validate hourly project fields
    if(btn == 'hourly')
    {
       if(frm.hourly_budget_min.value == '' && frm.hourly_budget_max.value > 0){
           alert("Please Enter The Minimum Budget Range Value");
           frm.hourly_budget_min.className='postTxtError';
           frm.hourly_budget_min.focus();
           return false;
       }else if(isNaN(frm.hourly_budget_min.value)){
           alert("Only numbers are allowed in the Minimum Budget Range Value field.\nPlease make sure that you have not entered any other characters");
           frm.hourly_budget_min.className='postTxtError';
           frm.hourly_budget_min.focus();
           return false;
       }else {
           if(frm.hourly_budget_time.value == 'Per Hour'){
               if(frm.hourly_budget_min.value < 4 && frm.hourly_budget_min.value!=''){
                   alert("To maintain a fair price for skill, time and effort put in by our Freelancers,\nPPH does not allow minimum Budget Range to be less than "+currency+"4 per hour for Hourly Jobs.");
                   frm.hourly_budget_min.className='postTxtError';
                   frm.hourly_budget_min.focus();
                   return false;
               }
           }else if(frm.hourly_budget_time.value == 'Per Day'){
               if(frm.hourly_budget_min.value < 32 && frm.hourly_budget_min.value!=''){
                   alert("To maintain a fair price for skill, time and effort put in by our Freelancers,\nPPH does not allow minimum Budget Range to be less than "+currency+"32 per day for Hourly Jobs.");
                   frm.hourly_budget_min.className='postTxtError';
                   frm.hourly_budget_min.focus();
                   return false;
               }
           }
       }

      if(frm.hourly_budget_max.value == '' && frm.hourly_budget_min.value > 0){
           alert("Please Enter The Maximum Budget Range Value");
           frm.hourly_budget_max.className='postTxtError';
           frm.hourly_budget_max.focus();
           return false;
       }else if(isNaN(frm.hourly_budget_max.value)){
           alert("Only numbers are allowed in the Maximum Budget Range Value field.\nPlease make sure that you have not entered any other characters");
           frm.hourly_budget_max.className='postTxtError';
           frm.hourly_budget_max.focus();
           return false;
       }else if(parseFloat(frm.hourly_budget_max.value) <= parseFloat(frm.hourly_budget_min.value)){
           alert("Maximum Budget Range Value can't be less than Minimum Budget Range Value.");
           frm.hourly_budget_max.className='postTxtError';
           frm.hourly_budget_max.focus();
           return false;
       }

        var btn1 = getSelectedRadioValue(frm.con_dur);
         if(btn1 == ""){
             alert('Please select Contract Duration for your Job');
             return false;
         }
         else if(btn1 == 'L'){
            if(frm.contract_num.value == ''){
                alert("Please Enter The Contract Duration Value");
                frm.contract_num.className='postTxtError';
                frm.contract_num.focus();
                return false;
            }else if(isNaN(frm.contract_num.value)){
                alert("Only numbers are allowed in the Contract Duration Value field.\n Please make sure that you have not entered any other characters");
                frm.contract_num.className='postTxtError';
                frm.contract_num.focus();
                return false;
           }else if(frm.contract_num.value == 0){
                alert("You have entered Zero (0) in the Contract Duration field.\nPlease select 'On Going' radio button option if you prefer an ongoing Job.");
                frm.contract_num.className='postTxtError';
                frm.contract_num.focus();
                return false;
           }else if(frm.contract_num.value < 0){
                alert("Only positive numbers are allowed in the Contract Duration Value field.\n Please make sure that you have not entered a negative value");
                frm.contract_num.className='postTxtError';
                frm.contract_num.focus();
                return false;
           }
         }

         var btn2 = getSelectedRadioValue(frm.week_commitment);
         if(btn2 == ""){
             alert('Please select if Weekly Commitment is needed for your Job');
             return false;
         }
         else if(btn2 == 'Y'){
            if(frm.commitment_num.value == ''){
                alert("Please Enter The Weekly Commitment Value");
                frm.commitment_num.className='postTxtError';
                frm.commitment_num.focus();
                return false;
            }else if(isNaN(frm.commitment_num.value)){
                alert("Only numbers are allowed in the Weekly Commitment Value field.\n Please make sure that you have not entered any other characters");
                frm.commitment_num.className='postTxtError';
                frm.commitment_num.focus();
                return false;
           }else if(frm.commitment_num.value == 0){
                alert("You have entered Zero (0) in the Weekly Commitment field.\nPlease select 'Not Sure' radio button option if Weekly Commitment is not needed for your Job.");
                frm.commitment_num.className='postTxtError';
                frm.commitment_num.focus();
                return false;
           }else if(frm.commitment_num.value < 0){
                alert("Only positive numbers are allowed in the Weekly Commitment field.\nPlease make sure that you have not entered a negative value.");
                frm.commitment_num.className='postTxtError';
                frm.commitment_num.focus();
                return false;
           }
         }
    }

   // Validate commissioned project fields.
    if(btn == 'commission')
    {
      if(frm.txtTime.value > 0){
        //Valdidate base fee only when time commitment is entered
        if(frm.txtBaseFee.value == '')
        {
          if(frm.timeCommitmentType.value !='')
          alert('You have specified a time commitment of '+frm.txtTime.value+' hours Per '+frm.timeCommitmentType.value+'. \n Please specify a Base Fee which the Freelancer can expect to earn hourly or daily for their time committed');
          else
          alert('Please specify Base Fee');
          frm.txtBaseFee.className='';
          frm.txtBaseFee.focus();
          return false;
        }
      }

      if(frm.txtBaseFee.value != ''){
          if(isNaN(frm.txtBaseFee.value)){
            alert("Only numbers are allowed in the Base Fee field.\nPlease make sure that you have not entered any other characters");
            frm.txtBaseFee.className='postTxtError';
            frm.txtBaseFee.focus();
            return false;
         }
         else {
           if(frm.txtBaseFee.value < 4 && frm.baseFeeType.value == 'Hour')
           {
            alert("To maintain a fair price for skill, time and effort put in by our Freelancers,\nPPH does not allow Base Fee to be less than "+currency+"4 per hour");
            frm.txtBaseFee.className='postTxtError';
            frm.txtBaseFee.focus();
            return false;
           }
           if(frm.txtBaseFee.value < 32 && frm.baseFeeType.value == 'Day')
           {
            alert("To maintain a fair price for skill, time and effort put in by our Freelancers,\nPPH does not allow Base Fee to be less than "+currency+"32 per day");
            frm.txtBaseFee.className='postTxtError';
            frm.txtBaseFee.focus();
            return false;
           }
         }
         if(frm.baseFeeType.value == ''){
            alert("Please Select Base Fee Type");
            frm.baseFeeType.className='postTxtError';
            frm.baseFeeType.focus();
            return false;
         }
      }
         //Validate Desired Time Commitment
        if(frm.txtBaseFee.value > 0){
          if(frm.txtTime.value == '')
          {
            alert('Please specify, Time Commitment needed from Freelancer');
            frm.txtTime.className='';
            frm.txtTime.focus();
            return false;
          }
        }
         if(frm.txtTime.value != ''){
            if(isNaN(frm.txtTime.value)){
                alert("Only numbers are allowed in the Time Commitment field.\nPlease make sure that you have not entered any other characters");
                frm.txtTime.className='postTxtError';
                frm.txtTime.focus();
                return false;
           }else if(frm.txtTime.value < 0){
                alert("Only positive numbers are allowed in the Time Commitment field.\nPlease make sure that you have not entered a negative value");
                frm.txtTime.className='postTxtError';
                frm.txtTime.focus();
                return false;
           }
           if(frm.timeCommitmentType.value == ''){
                alert("Please Select Time Commitment Type");
               frm.timeCommitmentType.className='postTxtError';
               frm.timeCommitmentType.focus();
                return false;
           }
        }

        //Validate Target
        if(frm.txtTarget.value == ''){
            alert("Please specify, what targets you want the Freelancer to achieve");
            frm.txtTarget.className='postTxtError';
            frm.txtTarget.focus();
            return false;
        }/*else if(isNaN(frm.txtTarget.value)){
            alert("Only numbers are allowed in the Target field. Please make sure that you have not entered any other characters");
             frm.txtTarget.className='postTxtError';frm.txtTarget.focus();
            return false;
        }*/else if(frm.txtTarget.value == 0){
                alert("You have entered Zero (0) in the Target field.\n\n Zero is not allowed in this field.\nPlease enter new Target Value.");
                 frm.txtTarget.className='postTxtError';frm.txtTarget.focus();
                return false;
        }else if(frm.txtTarget.value < 0){
                alert("You have entered a negative number in the Target field.\nA negative number is not allowed in this field. Please enter new Target Value.");
                 frm.txtTarget.className='postTxtError';frm.txtTarget.focus();
                return false;
        }
        if(frm.targetType.value == ''){
            alert("Please Select Target Type");
             frm.targetType.className='postTxtError';
             frm.targetType.focus();
            return false;
        } else if(frm.targetType.value == 'Other'){
            if(frm.txtOtherValue.value == ''){
                alert("Please Enter Other Target Type");
                 frm.txtOtherValue.className='postTxtError';
                 frm.txtOtherValue.focus();
                return false;
            }
        }
        if(frm.oteType.value == ''){
            alert("Please Select Target Period");
             frm.oteType.className='postTxtError';
             frm.oteType.focus();
            return false;
        }

        //Validate OTE
        if(frm.txtOte.value == ''){
            alert("Please Enter Result Fee");
            frm.txtOte.className='postTxtError';
            frm.txtOte.focus();
            return false;
        }else if(isNaN(frm.txtOte.value)){
            alert("Only numbers are allowed in the Result Fee field.\nPlease make sure that you have not entered any other characters");
             frm.txtOte.className='postTxtError';
             frm.txtOte.focus();
            return false;
        }else if(frm.txtOte.value == 0){
                alert("You have entered Zero (0) in the Result Fee field.\n Zero is not allowed in this field. Please enter new OTE Value.");
                 frm.txtOte.className='postTxtError';
                 frm.txtOte.focus();
                return false;
        }else if(frm.txtOte.value < 0){
            alert("Only positive numbers are allowed in the Result Fee field.\nPlease make sure that you have not entered a negative value");
             frm.txtOte.className='postTxtError';
             frm.txtOte.focus();
            return false;
        }
    }

    // Validate project start date
    if( stripCharsInBag (frm.start_date.value, " ") == "" )
    {
        alert("Please select the Start Date ");
        frm.start_date.focus();
        return false;
    }

    // Validate Job Location
    var btn1 = getSelectedRadioValue(frm.loc);
    if (btn1 == "")
    {
     alert('Please select working remotely or not?');
     return false;
    }
    if (btn1 == 'N')
    {
                if( stripCharsInBag (frm.txtProjLoc.value, " ") == "" )
                {
                        alert("Please enter the Job Location ");
                     frm.txtProjLoc.className='postTxtError';
                     frm.txtProjLoc.focus();
                        return false;
                }
        if( stripCharsInBag (frm.txtPostcode.value, " ") == "" )
        {
            alert("Please enter the Post Code");
            frm.txtPostcode.className='postTxtError';
            frm.txtPostcode.focus();
            return false;
        }
    }

     $(".continueButtonMsg").text(" ");
     document.getElementById("projExists").innerHTML=' ';

    showPage3();
    return false; // i.e. dont follow link
}
// Convert characters to HTML entities
function pph_htmlentities(textToChange)
{
    return textToChange.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
}

// output date format: 01/12/2008 11:11 pm
function currentDateFormatted(monthOffset){
    var now = new Date();

    var days = now.getDate();
    var month = now.getMonth() + monthOffset;
    var years = now.getFullYear();

    var hours = now.getHours()
    var minutes = now.getMinutes()
    var suffix = "am";

    if (days < 10) { days = "0" + days; }
    if (month < 10) { month = "0" + month; }
    if (minutes < 10) { minutes = "0" + minutes; }

    if (hours == 0) {
        hours = 12;
    }else if (hours < 10) {
        hours = "0" + hours;
    }else if (hours >= 12) {
        suffix = "pm";
        hours = "0" + (hours - 12);
    }

    return days + "/" + month + "/" + years + " " + hours + ":" + minutes + " " + suffix;
}

// Generate the project preview data
function generateProjectPreview()
{
    var tTime = 1;
    var btn = getSelectedRadioValue(document.f1.loc);
  if(btn == 'Y')
  var loc = 'Remote';
  else
  var loc = document.f1.txtProjLoc.value;
    // Preview for Job details:
    var previewProjCat = document.f1.category[document.f1.category.selectedIndex].innerHTML;
    var subCatObj = document.getElementById("rad");
    var subCatSelIndex = subCatObj.selectedIndex;
    var previewSubCat  = subCatObj[subCatSelIndex].innerHTML;

    var limitedLocationIcon ="";
    if ($('#whereBid').val() != "ALL"){
        limitedLocationIcon = "<img src='images/icons/limitedLocation.png' border=0 />";
    }

    previewTxt  =  "<div class='mmbgdiv'>";
    previewTxt  += "<div class='mmbgdivtop-m'>";
    previewTxt  += "<div align='right' style='float:right; width:75%; position:relative; right: 20px; top: 6px;' ><img src='images/jobPreview_shareThisJob.png' /></div>";
    previewTxt  += "<h2 class='mmabove'>Job Details</h2></div>";
    previewTxt  += "<div class='mmbgdivbot mmabove'>";
    previewTxt  += "<div style='width:390px; float:left;'>";
    previewTxt  += "<strong>Category: </strong> " + previewProjCat + " > " + previewSubCat + "<br />";
    previewTxt  += "<strong>ID: </strong> 12345<br />";
    previewTxt  += "<strong>Title: </strong> " + pph_htmlentities(document.f1.yp_name.value) + "<br />";
    previewTxt  += "<strong>Location:</strong> " + loc + "<br />";
    if (document.f1.txtPostcode.value) previewTxt  += "<strong>Post Code:</strong> " + pph_htmlentities(document.f1.txtPostcode.value) + "<br />";
    //TODO: display priority logo? (if commissioned project?)
    previewTxt  += "</div>";
    previewTxt  += "<div style='width:75px; float:left;' align='center'>";
    previewTxt  += limitedLocationIcon;
    previewTxt  += "</div>";
    previewTxt  += "</div></div>";

    // Preview for Job description:
    previewTxt  += "<div class='mmbgdiv'>";
    previewTxt  += "<div class='mmbgdivtop'>";
    previewTxt  += "<div class='mmbgdivtop-m'>";
    previewTxt  += "<div class='jobdescr-title'><h2 class='mmabove'>Job Description</h2></div>";
    previewTxt  += "<div class='reportjob-link' align='right'>";
    previewTxt  += "<img src='images/jobPreview_reportThisJob.png' />";
    previewTxt  += "</div></div></div>";
    previewTxt  += "<div class='mmbgdivbot mmabove'>";
    previewTxt  += pph_htmlentities(document.f1.comment.value).replace(/\n/g,'<br>');
    previewTxt  += "</div></div>";

    // Preview for Job budget:

    var budgetType = getSelectedRadioValue(document.f1.rdProjectType);
    if (budgetType == "commission")
    {
        var baseFeeType='';
        var baseFee = 'Not specified';
        var finalOTE='';
        if(document.f1.txtBaseFee.value > 0){
          var baseFee = selectedCurrency + document.f1.txtBaseFee.value+" "+document.f1.baseFeeType[document.f1.baseFeeType.selectedIndex].innerHTML;
        }
        var ote = selectedCurrency + document.f1.txtOte.value+" "+document.f1.oteType[document.f1.oteType.selectedIndex].innerHTML;
        if(document.f1.targetType.value == 'Other'){
            var target = document.f1.txtTarget.value+" "+escape(document.f1.txtOtherValue.value)+" "+document.f1.oteType[document.f1.oteType.selectedIndex].innerHTML;
        }else{
            var target = document.f1.txtTarget.value+" "+document.f1.targetType[document.f1.targetType.selectedIndex].innerHTML+" "+document.f1.oteType[document.f1.oteType.selectedIndex].innerHTML;
        }
        var commissionStructure = escape(document.f1.txtAreaComStr.value);
if(commissionStructure == 'e.g. 20% commission up to 100 sales/month' || commissionStructure == '')
        commissionStructure = 'Not Specified';
        var timeCommitment = '';
        if(document.f1.txtTime.value != '' && document.f1.txtTime.value != '0'){
            var timeCommitment = document.f1.txtTime.value+" Hours "+document.f1.timeCommitmentType[document.f1.timeCommitmentType.selectedIndex].innerHTML;
        }else{
            var timeCommitment = 'Not Specified';
        }
    finalOTE = selectedCurrency;
        finalOTE += (parseFloat($('#txtOte').val())+parseFloat($('#totalBaseFee').val())).toFixed(0);
  finalOTE+=' Per '+$('#oteType').val();
    }
    previewTxt  += "<div class='mmbgdiv'>";
    previewTxt  += "<div class='mmbgdivtop-m'>";
    previewTxt  += "<h2 class='mmabove'>Job Budget</h2></div>";
    previewTxt  += "<div class='mmbgdivbot mmabove'>";

    var realisticBudget = "<img src='images/jobPreview_realisticBudget.png' />";
    if (baseFee == 'Not specified'){
        realisticBudget ="";
    }

    if (budgetType == "hourly")
        previewTxt  += "<strong>Job Type: </strong> Hourly Job<br />";
    else if (budgetType == "fixed_price")
        previewTxt  += "<strong>Job Type: </strong> Fixed Price Job<br />";
    else
        previewTxt  += "<strong>Job Type: </strong> Base + Result Fee<br />";

    if ( budgetType == "fixed_price") {
        var fixedBudgetRange = 'Not specified';

        if(document.f1.fixed_budget_min.value !='' && document.f1.fixed_budget_max.value !=''){
           fixedBudgetRange = selectedCurrency + document.f1.fixed_budget_min.value + "-" + selectedCurrency + document.f1.fixed_budget_max.value;
           var amounts = [document.f1.fixed_budget_min.value,document.f1.fixed_budget_max.value];
        }
        if (fixedBudgetRange == 'Not specified'){
            realisticBudget ="";
        }

        previewTxt  += "<div><div style='min-width:140px; float:left;'><strong>Budget Range: </strong> " + fixedBudgetRange + "</div><div id='realistic' style='margin-left:40px'><div id='appro' style='float:left;'></div><div style='float:left; padding:4px 0px 0px 10px;'>" + realisticBudget + "</div></div></div><br />";
        previewTxt  += "<strong>Budget type: </strong>Fixed Fee<br />";
    } else if(budgetType == "hourly"){
        var contractDuration = 'OnGoing';
        if(getSelectedRadioValue(document.f1.con_dur)=='L'){
            contractDuration=document.f1.contract_num.value + " " + document.f1.contract_time.value;
        }
        var WeeklyCommit = 'Not Sure';
        if(getSelectedRadioValue(document.f1.week_commitment) == 'Y'){
            WeeklyCommit = document.f1.commitment_num.value + " " + document.f1.commitment_time.value +" Per Week";
        }

      var hourlyBudgetRange = 'Not specified';

      var budgetTime = document.f1.hourly_budget_time[document.f1.hourly_budget_time.selectedIndex].innerHTML;
      if(document.f1.hourly_budget_min.value != '' && document.f1.hourly_budget_max.value != ''){
           hourlyBudgetRange = selectedCurrency + document.f1.hourly_budget_min.value + "-" + selectedCurrency + document.f1.hourly_budget_max.value + " " + budgetTime;
           var amounts = [document.f1.hourly_budget_min.value,document.f1.hourly_budget_max.value];
      }
      if (hourlyBudgetRange == 'Not specified'){
            realisticBudget ="";
      }

      previewTxt  += "<strong>Contract duration: </strong> " + contractDuration + "<br />";
      previewTxt  += "<strong>Weekly commitment needed: </strong> " + WeeklyCommit + "<br />";
      previewTxt  += "<div><div style='min-width:140px; float:left;'><strong>Budget Range: </strong> " + hourlyBudgetRange + "</div><div style='float:left; padding:4px 0px 0px 10px;'>" + realisticBudget + "</div><div id='realistic' style='margin-left:40px'><div id='appro' style='float:left;'></div></div></div><br />";

    } else if (budgetType == "commission") {
        var tTime = document.f1.txtTime.value;
        var amounts = [document.f1.txtBaseFee.value,document.f1.txtOte.value];

        previewTxt  += "<div><div style='min-width:140px; float:left;'><strong>Budget Range: </strong> " + baseFee + "</div><div id='realistic' style='margin-left:40px'><span id='appro1' style='float:left; margin-left: 3px;'></span><div style='float:left; padding:4px 0px 0px 10px;'>" + realisticBudget + "</div></div></div><br />";
        previewTxt  += "<strong>Result Fee: </strong> " + ote + "<span id='appro2'></span><br />";
        previewTxt  += "<strong>OTE: </strong> " + finalOTE + " <img width='16px' height='16px' border='0' src='images/help_1.png'>" + "<span id='appro3'></span><br />";
        previewTxt  += "<strong>Target: </strong> " + target + "<br />";
        previewTxt  += "<strong>Bonus Structure: </strong> " + commissionStructure + "<br />";
        previewTxt  += "<strong>Desired Time Commitment: </strong> " + timeCommitment + "<br />";
    }

    previewTxt  += "</div></div>";

    // Preview for Job Additional Information:
    var previewStartDate = document.f1.start_date[document.f1.start_date.selectedIndex].innerHTML;
    var previewAttachedFiles = "none";
    if (document.f1.ProjectFile1.value)
        previewAttachedFiles = '<br />' + document.f1.ProjectFile1.value.replace(/^.*\/\d{12}\_/,"");
    if (document.f1.ProjectFile2.value)
        previewAttachedFiles += '<br />' + document.f1.ProjectFile2.value.replace(/^.*\/\d{12}\_/,"");
    if (document.f1.ProjectFile3.value)
        previewAttachedFiles += '<br />' + document.f1.ProjectFile3.value.replace(/^.*\/\d{12}\_/,"");

    var previewEndTime = '29d, 23h (ends:'+currentDateFormatted(2)+')';

    previewTxt  += "<div class='mmbgdiv'>";
    previewTxt  += "<div class='mmbgdivtop-m'>";
    previewTxt  += "<h2 class='mmabove'>Additional Information</h2></div>";
    previewTxt  += "<div class='mmbgdivbot mmabove'>";
    previewTxt  += "<strong>Approx Start Date after bid is selected:</strong> " + previewStartDate + "<br />";
    previewTxt  += "<strong>Attached files:</strong> "+previewAttachedFiles+"<br />";
    previewTxt  += "<strong>Bidding ends:</strong> "+previewEndTime+"<br />";
    previewTxt  += "<strong>Job posted:</strong> "+currentDateFormatted(1)+"<br />";
    previewTxt  += "</div></div>";

    previewTxt  += "<div class='mmbgdiv'>";
    previewTxt  += "<div class='mmbgdivtop-m'>";
    previewTxt  += "<h2 class='mmabove'>Bidding activity on this Job</h2></div>";
    previewTxt  += "<div class='mmbgdivbot mmabove'>";
    previewTxt  += "<strong>Bids:</strong> 0<br />";
    previewTxt  += "<strong>Who has Bid:</strong> No one has bid on this job yet<br />";
    previewTxt  += "</div></div>";

    document.getElementById('projectPreviewDiv').innerHTML = previewTxt;

    var perType = [
        $('#hourly_budget_time').val(),
        $('#baseFeeType').val(),
        $('#oteType').val()
    ];
    var parameters = {
      "currency" : $('#projectCurrency').val(),
      "budgetType" : budgetType,
      "amounts[]": amounts,
      "per" : perType,
      "comTime" : tTime
    };

    $.post(
      "../ajax/showApprox.php",
      parameters,
      function(msg) {
          if (msg !=""){
              var res = $.parseJSON(msg);
              if (res[0] !="commission"){
                  $("#realistic").addClass('clear');
                  $("#appro").html(res[1]);
              }else{
                  if(res[1]!=0)
                      $("#appro1").html(res[1]);
                  $("#appro2").html(res[2]);
                  $("#appro3").html(res[3]);
}
          }
          $(".previewPat").height($(".mleftbordiv-m").height());
      }
    );
}
function getXmlHttpRequestObject()
{
    if (window.XMLHttpRequest)
    {
        // Mozilla, Safari
        return new XMLHttpRequest();
    } else if(window.ActiveXObject)
    {
        //IE
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else
    {
        alert("Sorry, your browser does not support AJAX, which is required for this application.\nConsider upgrading your browser, or using another one such as Firefox");
    }
}

function handleAJAXPost(receiveReq)
{
    // When readyState 4 the response is complete and we can get our data.
     if (receiveReq.readyState == 4) {

        var xmldoc = receiveReq.responseText;

        if (receiveReq.status == 200)
        {
            // un-block continue button
            postedAlready = false;

            if(trim(xmldoc) == 'pwdMatch')
            {
                $(".continueButtonMsg").text("Please edit password and try again...");
                document.getElementById("emailError").innerHTML='';
                document.getElementById("pwdError").innerHTML='Incorrect password';
            }
            else if(trim(xmldoc) == "pwdBad")
            {
                $(".continueButtonMsg").text("Please edit password and try again...");
                document.getElementById("emailError").innerHTML='';
                document.getElementById("txtPasswordError").innerHTML='The password must be at least 6 characters long';
            }
            else if(trim(xmldoc) == "noEmail")
            {
                $(".continueButtonMsg").text("Please edit email and try again...");
                document.getElementById("pwdError").innerHTML='';
                document.getElementById("emailError").innerHTML="Email not found - please check and enter again";
            }
            else if(trim(xmldoc) == "emailExists")
            {
                $(".continueButtonMsg").text("Please edit email try again...");
                document.getElementById("emailExist").innerHTML='An account with this email already exists';
            }
            else if(trim(xmldoc) == 'ntBuyer')
            {
                $(".continueButtonMsg").text("Please enter buyer details and try again...");
                document.getElementById("emailError").innerHTML='';
                document.getElementById("pwdError").innerHTML='';
                document.getElementById("notBuyer").innerHTML='Sorry, only Clients can Post Jobs, please register as a Client';
             }
             else if(trim(xmldoc) == "usrNtActive")
            {
                $(".continueButtonMsg").text('');
                document.getElementById("notBuyer").innerHTML='<span class="sttext"><br>Your account has been deactivated. If you feel this deactivation is in error, please contact customer support as soon as possible.</span>';
            }
            else if(trim(xmldoc) == "exists")
            {
                $(".continueButtonMsg").text("Please edit Job and try again...");
                document.getElementById("projExists").innerHTML='<span class="sttext"><br>The Job details are exact duplicate of the existing Job,<br>if you want to repost the same Job you can repost it from your posted Jobs list.</span>';
            }
            else
            {
                logData('popup_submitted','Y','Y');
                logData('job_posted',xmldoc,'Y');
                // Turn off exit check
                checkExit = false;
                document.location.href = 'posting_method.php?project='+xmldoc;
            }
        } else {
            alert('There was a problem retrieving the XML data: ' + receiveReq.responseText);
        }
    }
}

// This function validates the form in JS, then builds a string containing POST variables and submits it via AJAX to postProjectDBInsert.php
// When postProjectDBInsert.php replies handleAJAXPost() is called and the next page is activated.
postedAlready = false;
function checkAdFrm(f)
{
    $.ajax({
        url: 'ajax/isUserLogged.php',
        type: 'POST',
        success: function(data){
            if(data=='y'){
    // Gather form variables into a sting to POST to PHP script
    var str = getFormValues(f,"");

    //Log the data
    logData('page3_continue_clicked','Y','Y');

    if(postingform_data.loggedin == false)
    {
        // The user was not logged in when posting project

        // Blank out previous errors
        document.getElementById('emailExist').innerHTML= '';
        document.getElementById('emailError').innerHTML= '';
        document.getElementById('pwdError').innerHTML  = '';
        //echo "document.getElementById('notBuyer').innerHTML  = '';";

        // Note: Using jquery validator plugin - prevent AJAX call below (if does not validate)
        if (!$("#f2").valid()) return false;

        // The login/registrations details are validated, Sent them append them to the POST string
        else str += "&" +getFormValues(document.f2,"");
    }

    if (postedAlready)
    {
        // user has clicked continue button twice, ignore this click.
        $(".continueButtonMsg").text("Please wait...");
    }
    else
    {
        // un-activate continue button to prevent user clicking it twice
        postedAlready = true;
        $(".continueButtonMsg").text("LOADING...");

        // Do server side checks and DB insert via AJAX call to PHP script

        var receiveReq = getXmlHttpRequestObject();
        if (!receiveReq) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
        }
        receiveReq.open("POST", "ajax/postProjectDBInsert.php", true);

        // Allow the server to pick up POST data
        receiveReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
        receiveReq.onreadystatechange = function() {handleAJAXPost(receiveReq);};
        receiveReq.send(str);
    }
            }else{
                openDialogClick();
            }
        }
    });

    // Important: We don't want the form to submit (because we want to redirect in our own way) - so return false
    return false;
}

function getFormValues(fobj,valFunc)
{
   var str = "";
   var valueArr = null;
   var val = "";
   var cmd = "";
   for(var i = 0;i < fobj.elements.length;i++)
   {
        switch(fobj.elements[i].type)
        {
           case "textarea":
           case "text":
                if(valFunc)
                {
                    //use single quotes for argument so that the value of
                    //fobj.elements[i].value is treated as a string not a literal
                    cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
                    val = eval(cmd);
                }
                // Use encodeURIComponent so we can pass "+" chars.
                str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&";
                 break;
           case "select-one":
           case "hidden":
           case "password":
                if(valFunc)
                {
                    //use single quotes for argument so that the value of
                    //fobj.elements[i].value is treated as a string not a literal
                    cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
                    val = eval(cmd);
                }
                str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
                 break;
           case "checkbox":
           case "radio":
                if(valFunc)
                {
                    //use single quotes for argument so that the value of
                    //fobj.elements[i].value is treated as a string not a literal
                    cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
                    val = eval(cmd);
                }
                if(fobj.elements[i].checked){
                    str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
                }
                break;
        }
   }
   str = str.substr(0,(str.length - 1));
   return str;
}

// The radio buttons asking if the user is already registered need to toggle the visiblity of the login/registration box
function checkSelect(val)
{
    var showTag = "";
    var hideTag = "";
    var logValue = '';

    if(val == 'L')
    {
        showTag = 'divLogin';
        hideTag = 'divRegister';
        logValue = 'Y';
    }
    else if(val == 'R')
    {
        showTag = 'divRegister';
        hideTag = 'divLogin';
        logValue = 'N';
    }

    var theElement1 = document.getElementById(hideTag);
    theElement1.style.display = 'none';

    var theElement2 = document.getElementById(showTag);
    theElement2.style.display = 'block';

    //log data
    logData('registered_user',logValue,'Y');
}

function showHelp(help)
{
  if(help == 'CommissionStructure'){
    var targetTypeDisp = 'target met';
    if($('#targetType').val() != ''){
    if($('#targetType').val() != 'Other'){
    str =  $('#targetType').val();
    targetTypeDisp = str.substring(0, str.length-1);
    }
    else if($('#txtOtherValue').val() !='')
    targetTypeDisp = escape($('#txtOtherValue').val());
  }
  help+='&ttype='+targetTypeDisp;
  }
  if($('#projectCurrency').length && $('#projectCurrency').val().length == 3){
      help += '&currency=' + $('#projectCurrency').val();
  }
    window.open("showjobhelp.php?help="+help, null, 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=500,left = 262,top = 19');
    return false;
}
// Show/Hide registration form elements
function showSelect(tag,val,field)
{
    var frm = document.f2[field].value;
    var theElement = document.getElementById( tag );

    if(frm == val)
        theElement.style.display = 'block';
    else
        theElement.style.display = 'none';
}
// Moved Here From showjobs.js which will be deleted
function getSelectedRadioValue(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {cnt = i; i = -1;}
    }
    if (cnt > -1) return btn[cnt].value;
    else return "";
}

