// JavaScript Document
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;
}

/**
 * Make an ajax call to store feedback result and thank client
 */
function storeBudgetFeedbackAndThank(projectId , score, budget_comment, proposed_budget, proposed_result ){
    var url = '/projects.php';
    var data = {
        'act'   : 'storeFeedback',
        'projectId' : projectId,
        'score' : score,
        'budget_comment' : budget_comment,
        'proposed_budget' : proposed_budget,
        'proposed_result' : proposed_result
    };
    $.post(url, data, storeBudgetFeedbackAndThankResponse);
};

/**
 * The response of the store feedback budget request call
 */
storeBudgetFeedbackAndThankResponse = function(response)
{
    response = $.evalJSON(response);

    // Feedback Budget has been stored successfully
    if (response.status == 1)
    {
        $('#budgetFeedbackDialog').fadeOut('slow',
        function()
        {
            $('#budgetFeedbackDialog').empty().append($('#thankBudgetFeedback').clone()).fadeIn('slow');
            setTimeout(function()
            {
                $('#budgetFeedbackDialog').dialog("close");
            },4000);

            $('#budgetFeedbackHeader').empty();
        });
    } else if (response.status == 2){ //user had two browsers open and clicked the button
            $('#budgetFeedbackDialog').empty().append($('#alreadyGivenBudgetFeedback').clone(true)).dialog("open");
            $('.openBudgetFeedbackDialog').hide();
    } else //feedback budget not stored so output error
    {
            $('#budgetFeedbackDialog').empty().append($('#errorBudgetFeedbackMsg').clone()).fadeIn('slow');
    }
}

$().ready(function()
{

    $('.openOTEDialog').click(function(){$("#oteDialog").dialog("open");return false;});
            $("#oteDialog").dialog({
                modal: true,
                autoOpen: false,
                width: "590px",
                overlay: {
                    opacity: 1.5,
                    background: "black"
                },
                buttons: {
                    Close: function() {
                        $(this).dialog('close');
                    }
                }
            });

    //budget feedback dialog box
    $("#budgetFeedbackDialog").dialog({
            modal: true,
            autoOpen: false,
            width: "450px",
            position: ['center',100],
            overlay: {
                opacity: 1.5,
                background: "black"
         },
         buttons: {
         }
    });

    // ---- budget feedback events -----
    //when the "Give feedback to the budget" link is clicked
    $('.openBudgetFeedbackDialog').click(
    function() {
        $('.giveBudgetFeedbackForm .negativeBudgetFeedbackForm').addClass('hide');
        $('.giveBudgetFeedbackForm .anonymousBudgetFeedbackLabel').addClass('hide');
        $('#budgetFeedbackDialog').empty().append($('.giveBudgetFeedbackForm').clone(true)).dialog("open");return false;
    });

    $('.feedbackOptValue1' ).click(function(){
         $('.giveBudgetFeedbackForm .negativeBudgetFeedbackForm').addClass('hide');
         $('.giveBudgetFeedbackForm .anonymousBudgetFeedbackLabel').addClass('hide');
    });
    $('.feedbackOptValue0' ).click(function(){
         $('.giveBudgetFeedbackForm .negativeBudgetFeedbackForm').removeClass('hide');
         $('.giveBudgetFeedbackForm .anonymousBudgetFeedbackLabel').removeClass('hide');
    });

    //when the submit button is clicked in the give budget feedback dialog
    $('.giveBudgetFeedbackForm input[type=button]').click(
        function()
        {
            var selection = $('input[name=feedbackOptValue]:checked', 'form[name=budgetFeedbackForm]' ).val();
            var orig_comment = 'Clients often do not know what the right Budget is. Help them understand by explaining:\nWhy the Budget is unrealistic?\nWhat amount of work needs to be done?\nWhat resources are needed to do a proper Job?';
            var proposed_budget = checkBudgetFeedbackNumericValues(selection, 'proposed_budget');
            var proposed_base = checkBudgetFeedbackNumericValues(selection, 'proposed_base');
            var proposed_result = checkBudgetFeedbackNumericValues(selection, 'proposed_result');
            var budget_comment = $('#budgetFeedbackDialog .budget_comment').val();
            var hasErrors = false;

            if (selection != 0 && selection != 1){ //if user did not choose anything
                showErrorMessage( 'feedbackOptValue' );
                hasErrors = true;
            } else if(selection == 0) {
                if (proposed_budget == '1'){ //if user choose unrealistic and didn't fill budget
                    showErrorMessage( 'proposed_budget', 'Please enter a realistic budget.' );
                    hasErrors = true;
                }else if (proposed_budget == '2'){ //if user choose unrealistic and budget is not a decimal
                    showErrorMessage( 'proposed_budget', 'Budget entered should be a number.' );
                    hasErrors = true;
                }
                if (proposed_base == '1'){ //if user choose unrealistic and didn't fill budget
                    showErrorMessage( 'proposed_base', 'Please enter a realistic base fee.' );
                    hasErrors = true;
                }else if (proposed_base == '2'){ //if user choose unrealistic and budget is not a decimal
                    showErrorMessage( 'proposed_base', 'Base fee entered should be a number.' );
                    hasErrors = true;
                }
                if (proposed_result == '1'){ //if user choose unrealistic and didn't fill budget
                    showErrorMessage( 'proposed_result', 'Please enter a realistic result fee.' );
                    hasErrors = true;
                }else if (proposed_result == '2'){ //if user choose unrealistic and budget is not a decimal
                    showErrorMessage( 'proposed_result', 'Result fee entered should be a number.' );
                    hasErrors = true;
                }

//                var charLimit = 100;
                if (($('#budgetFeedbackDialog .budget_comment').val().length == 0) || ($('#budgetFeedbackDialog .budget_comment').val() == orig_comment)){ //if field is empty
                    showErrorMessage( 'budget_comment', 'Please enter a comment.' );
                    hasErrors = true;
                }else if ($.trim($('#budgetFeedbackDialog .budget_comment').val()).length == 0 ){
                    showErrorMessage( 'budget_comment', 'Please enter a comment.' );
                    hasErrors = true;
                    $('#budgetFeedbackDialog .budget_comment').val('');
//                }else if ($('#budgetFeedbackDialog .budget_comment').val().length > charLimit ){
//                    showErrorMessage( 'budget_comment', 'Comment must be less than '+charLimit+'.' );
//                    hasErrors = true;
                }
            }
            if (hasErrors == false){
                var proposed_budget = getBudgetFeedbackNumericValues('proposed_budget');
                var proposed_base = getBudgetFeedbackNumericValues('proposed_base');
                var proposed_result = getBudgetFeedbackNumericValues('proposed_result');

                $(this).attr('disabled', true);

                if( typeof proposed_result !== "undefined" ){
                    proposed_budget = proposed_base;
            }
                storeBudgetFeedbackAndThank($(this).next().val() , selection, budget_comment, proposed_budget, proposed_result );
        }
        }
    );

});
function getBudgetFeedbackNumericValues( label ){
    if ( typeof $('#budgetFeedbackDialog .'+label+'').val() ) {
        var value = $('#budgetFeedbackDialog .'+label+'').val();
    } else {
        var value = '';
    }
    return value;
}
function checkBudgetFeedbackNumericValues( selection, label ){
    var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;//Used to check if proposed_budget is decimal number
    var result = 0;//OK
    if ( typeof $('#budgetFeedbackDialog .'+label+'').val() !== "undefined" ) {
        var value = $('#budgetFeedbackDialog .'+label+'').val();

        if (selection == 0 && value == ''){ //if user choose unrealistic and didn't fill budget
            result = 1;//Empty
        }else if (selection == 0 && numberRegex.test(value) == false){ //if user choose unrealistic and budget is not a decimal
            result = 2;//Non numeric
        }
    }

    return result;
}
$().ready(function()
{
    // JQuery Modal Dialog Box
    $('.openDialog').click(function(){$("#dialog").dialog("open");return false;});
    $('.closeDialog').click(function(){$("#dialog").dialog("close");return false;});
    $("#dialog").dialog({
        modal: true,
        autoOpen: false,
        width: "590px",
        position: ["center",10],
        overlay: {
            opacity: 0.5,
            background: "black"
        }
    });

    // Define dialog box to show when uploading a file
    $("#loadingDialog").dialog({
        modal: true,
        autoOpen: false,
        width: "660px",
        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: "660px",
        overlay: {
            opacity: 1.5,
            background: "black"
        },
        buttons: {
            OK: function() {
                $(this).dialog('close');
            }
        }
    });

    new Ajax_upload('#aJaxUpload', {
        action : '/ajax/ajaxFileUpload.php',
        name: 'uploadFile',
        data: { uploadType : 'bidFileAttachment' },
        // Fired when user selects file
        onSubmit: function(file, extension) {

            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) {
                // 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"){
                $("#loadingDialog").dialog('close');

                // Save this file name and location in a hidden form field.
                document.Bidfrm["ProjectFile"].value = resMsg[1];

                var fileNameToDisplay = resMsg[2];
                var fileString = 'Attachment ' + fileNameToDisplay + " <a href=\"#\" onclick=\"javascript:return removeFile('"+fileNameToDisplay+"')\">remove</a>"
                $('#fileUploadDiv .text').html(fileString);
            } else {
                $("#loadingDialog").dialog('close');
                // Display file upload error
                $("#confirmDialog").html(response);
                $("#confirmDialog").dialog('open');
            }
        }
    });

    $("#biddersInfoPopup").dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 415,
        height: 310,
        position:['center', 70],
        buttons: {
           Close: function() {
               $(this).dialog('close');
           }
        },
        overlay: {
           opacity: 1.5,
           background: "black"
        },
        closeOnEscape: false
    });

    $('.viewAllBiddingActivity').click(function(e) {
        e.preventDefault();
        $("#biddersInfoPopup").dialog('open');
    });

});
// function to remove a file that has been uploaded
function removeFile(fileToRmove) {
  $.ajax({
         url: "/ajax/postProjectFileDelete.php?file="+fileToRmove,
         type: 'GET',
         success: function(){
        $('#fileUploadDiv .text').html('');
        }
      });
  return false;
}

function reportProject(project)
{
    window.open("/reporterror.php?project="+project, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=400,left = 262,top = 19');
}

function reportMessage(message)
{
    window.open("/reporterror.php?message="+message, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=400,left = 262,top = 19');
}

function replyMessage(message)
{
    window.open("/replymessage.php?id="+message, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=400,left = 262,top = 19');
}

function reportReviewedMessage()
{
 window.open("/reviewedmessage.php", null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=175,left = 262,top = 19');
}
function sendActiveMail(memid,val){
    window.open("/sendactivemail.php?id="+memid+"&type="+val, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300,left = 262,top = 19');
}
function clearStartJob()
{
  $("#startJobError").hide();
  $("#startJobTitle").css('color','black');
  $("#startJobInput").css('background-color','#FFFFFF');
  document.Bidfrm.delivery_code_id.className='';
}
function showDepHelp()
{
    document.Bidfrm.txtMinAmt.className='';
  //  $("#depositTip").attr('class','tooltip1');
  //  $("#depositTip").html('<div style="position: absolute;  top: 50%;"><div class="pointer">&nbsp;</div></div><p><img src="/images/icons/info.png" width="16" height="16" hspace="5" align="left" />We recommend a deposit equivalent to 50% of your Bid Amount.</p><p>Protects you against Client defaults and dispute resulting from your work.</p><p>Deposit is held in <a href="javascript:showEscrowHelp();">Escrow</a> and will be released and paid to you after Client authorises payment towards your first Invoice.</p>');
    document.Bidfrm.txtMinAmt.focus();
}
function showAmtHelp()
{
    document.Bidfrm.hourrate.className='';
  //  $("#amountTip").attr('class','tooltip1');
  //  $("#amountTip").html('<div style="position: absolute;  top: 50%;"><div class="pointer">&nbsp;</div></div><p><img src="/images/icons/info.png" width="16" height="16" hspace="5" align="left" />Over 90% of Bids are awarded to Freelancers with a Mid-Range or Highest Bid Amount.</p><p>The Bid Amount includes <a href="javascript:showVatHelp(\'whatIsVat\',400)">VAT</a> unless stated otherwise by you in your Bid Proposal.</p><p>PPH charges a <a href="/pro_faqs.php#128">4.5-10% service fee</a> after you receive payment for your Job from the Client.</p>');
    document.Bidfrm.hourrate.focus();
}
function clearbaseFee()
{
    document.Bidfrm.txtBaseFee.className='';
    //$("#BaseFeeTipNew1").attr('class','tooltip1');
  //  $("#BaseFeeTipNew1").html('<div style="position: absolute;  top: 50%;"><div class="pointer">&nbsp;</div></div><p><img src="/images/icons/info.png" width="16" height="16" hspace="5" align="left" />Clients will pay you a base fee regardless of whether you meet targets.</p><p>Includes VAT unless stated otherwise by you in your Bid Proposal.</p><p>PPH charges a <a href="#">4.5-10% service fee</a> after you receive payment for your Job from the Client.</p>');
    document.Bidfrm.txtBaseFee.focus();
}
function checkBaseFee()
{
       if(isNaN(document.Bidfrm.txtBaseFee.value)){
               $("#BaseFeeTipNew1").attr('class','errorTip');
               $("#BaseFeeTipNew1").html('<div style="position: absolute;  top: 50%;"><div class="errorpointer">&nbsp;</div></div><img src="/images/icons/exclamation.png" width="16" height="16" hspace="5" align="left" />Only numbers are allowed in the Base Fee Value field. Please make sure that you have not entered any other characters.');
               document.Bidfrm.txtBaseFee.focus();
               document.Bidfrm.txtBaseFee.className='postTxtError';
               return false;
       }
}
function showVatHelp(help, height)
{
  window.open("/showhelp.php?help="+help, null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height='+height+',left = 300,top = 50');
}
function showEscrowHelp()
{
  window.open("/showprojecthelp.php?help=escrowDeposit", null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=460,left = 262,top = 19');
}
function showHelp(help)
{
    if(help == 'minimumDeposit'){
        window.open("/showhelp.php?help="+help, null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=380,left = 300,top = 50');
    }else if(help == 'bidProposal'){
       //window.open("/showhelp.php?help="+help, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=380,left=260,top=50');
    //$("#descTip").attr('class','tooltip1');
    if(document.Bidfrm.projectType.value == 'fixed_price'){
    //  $("#descTip").html('<div style="position: absolute;  top: 50%;"><div class="pointer">&nbsp;</div></div><img src="/images/icons/info.png" width="16" height="16" hspace="5" align="left" /><strong>A good Bid is...</strong><p><strong>Realistic</strong> - A sensibly priced bid will be more credible than one with the lowest price. Over 90% of awarded Jobs go to a Mid-Range or Highest bidder. <a href="javascript:showHelp(\'bidProposal\');">Learn more</a></p><p> <strong>Detailed</strong> - A bid which details your approach, deliverables and timelines will instil confidence in the Client about your ability to deliver the Job.</p><p> <strong>Tailored</strong> - A bid customised to Job requirements is more likely to be accepted than a generic or templated bid.</p>');
    }
    else
    {
    //  $("#descTip").html('<div style="position: absolute;  top: 50%;"><div class="pointer">&nbsp;</div></div><img src="/images/icons/info.png" width="16" height="16" hspace="5" align="left" /><strong>A good Bid is...</strong><p><strong>Realistic</strong> - A sensibly priced bid will be more credible than one with the lowest price. To view data on Bids awarded, visit <a href="/pph_economy.php">PPH Economy</a></p><p> <strong>Detailed</strong> - A bid which details your approach, deliverables and timelines will instil confidence in the Client about your ability to deliver the Job.</p><p> <strong>Tailored</strong> - A bid customised to Job requirements is more likely to be accepted than a generic or templated bid.</p>');
    }
window.document.Bidfrm.pmb_comments.focus();
    }else if(help == 'serviceFee'){
        window.open("/showhelp.php?help="+help, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=350,height=200,left=260,top=50');
    } else if(help == 'BiddingMinimum'){
        window.open("/showhelp.php?help="+help, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=320,left=260,top=50');
    }
}


// Returns the value of the selected radio button or "" if no button is selected
function showPost(projID)
{
    window.open("/showterms.php?projID="+projID, null,'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300,left=260,top=50');
}

function showDetails()
{
    window.open("/showpriority.php?item=F", null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=450,height=300,left = 262,top = 19');
}

function showErrorMessage( label, message )
{
    if ( typeof message !== "undefined" && message) {
        $('#budgetFeedbackDialog .'+label+'Message').html( message );
    }
    $('#budgetFeedbackDialog .'+label+'Message').css( 'display', 'inline' );
}

function clearErrorMessage( label )
{
    $('#budgetFeedbackDialog .'+label+'Message').css( 'display', 'none' );
}

function clearDummyText()
{

    var str = document.Bidfrm.pmb_comments.value;
    if (str.substring(0,23) == 'Enter your detailed bid')
    {

        document.Bidfrm.pmb_comments.value = '';
        document.Bidfrm.pmb_comments.style.color='black';
    }
}
function processDummyBudgetText(orig_comment)
{
    var budget_comment = $('#budgetFeedbackDialog .budget_comment');
    var str = budget_comment.val();
    budget_comment.css('color', 'black');
}

function showBaseFee(){
    var frm = window.document.Bidfrm;
    var chkbasefeenew = getSelectedRadioValue(frm.rdAcceptedBaseFee);
    if(chkbasefeenew == 'baseFeeAccepted'){
        frm.txtBaseFee.disabled = true;
        frm.baseFeeType.disabled = true;
        $("#newBaseFeeError").hide();
        $("#newBaseFeeInput").css('background-color','#FFFFFF');
        frm.txtBaseFee.className='';
    }else if(chkbasefeenew == 'baseFeeNew') {
        frm.txtBaseFee.disabled = false;
        frm.baseFeeType.disabled = false;
    }

    var chkcomstrnew = getSelectedRadioValue(frm.rdAcceptedCommStr);
    if(chkcomstrnew == 'commStrAccepted'){
        frm.txtAreaComStr.disabled = true;
                                $("#newComStructError").hide();
                                $("#newComStructInput").css('background-color','#FFFFFF');
                                frm.txtAreaComStr.className='';
    }else if(chkcomstrnew == 'commStrNew') {
        frm.txtAreaComStr.disabled = false;
    }
}
function showResultFee(){
    var frm = window.document.Bidfrm;
    var chkresultfenew = getSelectedRadioValue(frm.rdAcceptedResultFee);
    if(chkresultfenew == 'resultFeeAccepted'){
        frm.txtResultFee.disabled = true;
        $("#newResultFeeError").hide();
        $("#newResultFeeInput").css('background-color','#FFFFFF');
        frm.txtResultFee.className='';
    }else if(chkresultfenew == 'resultFeeNew') {
        frm.txtResultFee.disabled = false;
    }
}

function assignCategory()
{
    document.catAssign.categoryAssign.value = 'Y';
    document.catAssign.submit();
}

function showClBoardHelp()
{
    document.getElementById('projectHelp').style.display = "block";
}
function closeHelp()
{
    document.getElementById('projectHelp').style.display = "none";
}

function showPPHHelp(help, height, bidId)
{
    var url = "/showhelp.php?help="+help;
    if(bidId > 0){
      url = "/showhelp.php?help="+help+"&bidId="+bidId;
    }
    window.open(url, null, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height='+height+',left = 300,top = 50');
}

