
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var fileManagerQuestion=null;
var changedDataCheck=false;
var allowedFileTypes="DOC,DOCX,PDF,ODT,BMP,GIF,JPG,JPEG,TIF,TIFF,WMF,PNG";

//---PLUG INS---s

//Creates image file upload buttons
(function($) {
    $.fn.styleFileInput = function() {
        return this.each(function() {
            $(this).wrap('<span class="file-input"></span>');
            $(this).after('<span class="btn"></span>');
        });
    };
})(jQuery);

$(document).ready(function() {

    //---SETUP---

    $("#jsNotEnabled").css("display","none");
    $("#jsEnabled").css("display","");

    $.ajaxSetup ({
        // Disable caching of AJAX responses
        cache: false
    });   

    //admin section TODO new start
    $('#qHeaderEditor').ckeditor({
        height : '100px'
    });
    $('#qTextEditor').ckeditor({
        height : '150px'
    });
    
    $('#qGuidanceEditor').ckeditor({
        toolbar : 'Basic',
        height : '150px',
        toolbar :
        [
        {
            name: 'basicstyles', 
            items : [ 'Bold','Italic','Underline' ]
        },
        {
            name: 'paragraph', 
            items : [ 'NumberedList','BulletedList' ]
        },
        {
            name: 'links', 
            items : [ 'Link','Unlink' ]
        }


        ]
    });  

    $(".moveQuestions").live('click',function(){
        swapSort=null;
        parameters=$(this).attr("id").split("_");
        //get next tr image id and split to get sort order to swap - need to determine sort order
        if(parameters[1]=='0')
            swapSort=$(this).parent().parent().next('tr').find('.moveQuestions').attr("id").split("_");
        else
            swapSort=$(this).parent().parent().prev('tr').find('.moveQuestions').attr("id").split("_");

        //param1 = clicked id, param2 = clicked sort order, param3 = next/prev id, param4=next/prev sort order
        $.ajax({
            type: "GET",
            url: "/ajax/moveQuestion.php",
            data: "param1="+ parameters[2] + "&param2=" + parameters[3] +"&param3=" + swapSort[2]+"&param4=" + swapSort[3],
            success: function(data)
            {
                if(data.trim()=="success")                                       
                    $('#questionAdmin').load('question_admin_index.php #questionAdmin');
            }
        });
    });
    
    $("#questionSupplierType").change(function(){
        $("#editQuestions").submit();
    });

    $("#saveHtmlQuestion, #saveUser").click(function(){
        $("#validateInputForm").submit();
    });
    //new end

    $('input[type=file]').styleFileInput();
    $( "#chaseExcludeDate" ).datepicker({
        dateFormat: 'dd/mm/yy'
    });
    $(".contactRowEdit").hide();
    $(".companyRowEdit").hide();

    //---VALIDATION ROUTINES---

    //Checks for errors in any given validation area and appends error messages to the parent element
    function ValidateInputs(validateArea)
    {
        var postcodeRegxp = /[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}/i;
        var emailRegxp = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
        var phoneRegxp = /^(\(?\+44\)?\s?(1|2|3|7|8)\d{3}|\(?(01|02|03|07|08)\d{3}\)?)\s?\d{3}\s?\d{3}|(\(?\+44\)?\s?(1|2|3|5|7|8)\d{2}|\(?(01|02|03|05|07|08)\d{2}\)?)\s?\d{3}\s?\d{4}|(\(?\+44\)?\s?(5|9)\d{2}|\(?(05|09)\d{2}\)?)\s?\d{3}\s?\d{3}$/;
        var inputError=false;
        var scrollTo=null;

        //remove any existing messages
        $(validateArea + ' .formErrorText').remove();

        //check if pass/fail options are selected
        if(($("#assessmentResult_fail:enabled").length>0) && ($("#assessmentResult_pass_fail [type='radio']:checked").length==0))
        {
            $("#assessmentResult_pass_fail").append("<span style='clear:both' class='formErrorText cntrlsFloatRight'>Error - Please set assessment result</span>");
            inputError=true;
        }

        if($("#assessmentResult_fail").attr('checked') && $("#failReasonTextArea").val()=="Please provide a reason why the assessment failed.")
        {
            $("#failReasonTextArea").parent().append("<span class='formErrorText'>Error - please provide a reason why the assessment failed</span>");
            inputError=true;
        }

        if($("#chaseExclude_Excluded").attr('checked') && $("#chaseExcludeDate").val()=="")
        {
            $("#chaseExcludeDate").parent().append("<span class='formErrorText'><br>Error - required field</span>");
            inputError=true;
        }

        $(".assessed:checked").each(function (){ //for every assessed item check that an answer has been selected

            if($(this).attr("id"))
            {
                qid=$(this).attr("id").split("_");
                if($("#assessed_" + qid[1] + " [type='radio']:checked").length==0)
                {
                    $("#assessed_" + qid[1] + " .assessed").parent().append("<span class='formErrorText'><br>Error - Please set the status to Pass/Fail/Further information required</span>");
                    inputError=true;
                    if(scrollTo==null)
                    {
                        scrollTo=qid[1];
                        window.location="assessor_ssip_questions.php#question" + scrollTo;
                    }
                }
            }
            else
            {
                if($(".subsetControls [type='radio']:checked").length==0)
                {
                    if($(".subsetControls [type='radio']").length==3)
                        $(".assessed").parent().append("<span class='formErrorText'><br>Error - Please set the status to Pass/Fail/Further information required</span>");
                    else
                        $(".assessed").parent().append("<span class='formErrorText'><br>Error - Please set the status to Pass/Fail</span>");

                    inputError=true;
                }
            }
        });

        $(validateArea + " #codeID").each(function() {
            if($(this).val().length!=3)
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - Invalid code (eg. 001)</span>");
                inputError=true;
            }
        });

        $(validateArea + " .requiredInput").each(function() {
            if($(this).val()=="" || $(this).find("option:selected").text()=="Please select...")
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - required field</span>");
                inputError=true;
            }
        });

        $(validateArea + ' .emailInput').each(function() {
            if (emailRegxp.test($(this).val()) != true && $(this).val()!="")
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - invalid email</span>");
                inputError=true;
            }
        });


        $(validateArea + ' .phoneInput').each(function() {
            if (phoneRegxp.test($(this).val()) != true && $(this).val()!="")
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - invalid number</span>");
                inputError=true;
            }
        });

        $(validateArea + ' .postcodeInput').each(function() {
            if (postcodeRegxp.test($(this).val()) != true && $(this).val()!="")
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - invalid post code</span>");
                inputError=true;
            }
        });

        $(validateArea + ' .passwordInput').each(function() {
            if ($(this).val().length<8 || $(this).val().length>25 )
            {
                $(this).parent().append("<span class='formErrorText'><br>Error - invalid password</span>");
                inputError=true;
            }
        });

        return inputError;
    }

    //---VISUAL ROUTINES---

    $("#title").change(function() {
        $("#readOnlyTitle").val($(this).find('option:selected').val());
    });

    $("#chaseExclude_Excluded").click(function(){
        $("#chaseExcludeDate").removeAttr('disabled');
    });

    $("#chaseExclude_NotExcluded").click(function(){
        $("#chaseExcludeDate").val("");
        $("#chaseExcludeDate").attr('disabled', 'disabled');
    });

    $("#assessmentResult_fail").click(function(){
        //$("#failReason").css("display","");
        $("#failReason").fadeIn("fast","linear");
    });

    $("#assessmentResult_pass").click(function(){
        //$("#failReason").css("display","none");
        $("#failReason").fadeOut("fast","linear");
        $("#failReasonTextArea").val("");
    });

    $(".radioButtonText").click(function(){
        //only check if not disabled
        if(!$(this).prev().attr('disabled'))
            $(this).prev().attr('checked','checked');
    });
    
    $(".checkBoxText").click(function(){
        //only check if not disabled
        if(!$(this).prev().attr('checked'))
            $(this).prev().attr('checked','checked');
        else
            $(this).prev().removeAttr('checked');
    });

    $("#radioButtonTextSummaryFail").click(function(){
        //only check if not disabled
        if(!$(this).prev().attr('disabled'))
        {
            $(this).prev().attr('checked','checked');
            //$("#failReason").css("display","");
            $("#failReason").fadeIn("fast","linear");
        }
    });

    $("#radioButtonTextSummaryPass").click(function(){
        //only check if not disabled
        if(!$(this).prev().attr('disabled'))
        {
            $(this).prev().attr('checked','checked');
            //$("#failReason").css("display","none");
            $("#failReason").fadeOut("fast","linear");
            $("#failReasonTextArea").val("");
        }
    });

    $(".assessed").click(function(){
        var obj;
        //check type of element and set obj varible to the correct element
        if($(this).is("span"))
        {
            $(this).prev().attr('checked') ? $(this).prev().removeAttr('checked') : $(this).prev().attr('checked','checked');
            obj=$(this).prev();
        }
        else
            obj=$(this);

        if(obj.attr("id"))
        {
            qid=obj.attr("id").split("_");
            if(!obj.attr('checked'))
            {
                $("#assessed_" + qid[1] + " [type='radio']").attr('disabled', 'disabled');
                $("#assessed_" + qid[1] + " [type='radio']").removeAttr('checked');
            }
            else
                $("#assessed_" + qid[1] + " [type='radio']").removeAttr('disabled');

        }
        else
        {
            if(!obj.attr('checked'))
            {
                $(".subsetControls [type='radio']").attr('disabled', 'disabled');
                $(".subsetControls [type='radio']").removeAttr('checked');
            }
            else
                $(".subsetControls [type='radio']").removeAttr('disabled');
        }
    });

    $(".displayNameInput").change(function() {
        if($(this).find("option:selected").text()!="Please select")
        {
            //set hidden value to id of lookup value
            $(this).parent().next().next().find(":input").val($(this).val());
            //combine original filename with select box value
            $(this).parent().next().html($(this).find("option:selected").text() + " (" + $(this).parent().prev().find(".fileLink").html() + ")");
        }
    });

    $('#maintainedFiles .codeLink').live('click',function(){
        $("#maintain_text .formErrorText").remove();
        $(".tableBody tr").removeClass('boldText');
        //highlight the row that was clicked by aplying the bold class to it
        $(this).parent().parent().addClass('boldText');
        $('#codeID').val($(this).html());
        //get filename id - stored in checkbox value
        $('#fileNameID').val($(this).parent().prev(".checkBox").find("[type='checkbox']").val());
        //get description of filename - stored in next td
        $('#descriptionID').val($(this).parent().next(".description").html());
    });

    $('.inputButton').live('mouseover', function() {
        //check if button is disabled - use background image to determine this (it will be grey if disabled)
        if($(this).css('background-image').indexOf('Grey')==-1)
            $(this).css("text-decoration","underline");
    });

    $('.inputButton').live('mouseout', function() {
        $(this).css("text-decoration","none");
    });

    $("#editCompany").click(function(){
        $(".companyRow").hide();
        $(".companyRowEdit").show();
    });

    $("#editContact").click(function(){
        $(".contactRow").hide();
        $(".contactRowEdit").show();
    });

    $(".expandComments").click(function(){
        commentArea=$(this).attr("rel");
        if($("#" + commentArea + " tr").length>0)
        {
            if ($(this).html().indexOf("+&nbsp;")!="-1")
            {
                //$("#" + commentArea).css('display','');
                $(this).html($(this).html().replace("+&nbsp;", "-&nbsp;"));
            }
            else
            {
                //$("#" + commentArea).css('display','none');
                $(this).html($(this).html().replace("-&nbsp;", "+&nbsp;"));
            }
            $("#" + commentArea).fadeToggle("fast","linear");
        }
    });

    //Any input with a class of inputChange applied to it will have a check that will set a
    //data changed flag. If any changes are made on the input and are not saved before the user
    //logs out a message will be triggered warning the user
    $(".inputChange").change(function() {
        changedDataCheck='true';
        if ($(this).attr('name') != 'commentTextArea_new') {
            $('#saveState').val('1');
        }
    });

    $(".showComment").live('click',function(){
        qid=$(this).attr("rel");
        if(document.getElementById("inputCommentRow-" + qid).style.display=="none")
        {
            $("#sym_" + qid).html("-&nbsp;Add comment");
        //$("#inputCommentRow-" + qid).css("display","");
        }
        else
        {
            $("#sym_" + qid).html("+&nbsp;Add comment");
        //$("#inputCommentRow-" + qid).css("display","none");

        }
        $("#inputCommentRow-" + qid).fadeToggle("fast","linear");

    });

    $('.textComments').focus(function(){
        if ($(this).val() =="Please note that any comments entered can be viewed by the Supplier, the Health and Safety assessor and Buyer users." || $(this).val() == "Please provide a reason why the assessment failed." )
        {
            $(this).val("");
            $("#commentTextArea_new").val("");
        }
    });

    //---SUBMIT ROUTINES---

    $('#validateInputForm').submit(function(){
        error=ValidateInputs("#validateInputForm");
        if(!error)
            return true;
        else
            return false;
    });


    $("#deleteConfirmOK").click(function(){
        $("#postDelete").val("1");
        $("#constructionline_summary").submit();
    });

    $("#loginButton").click(function(){
        $("#loginform").submit();
    });

    $("#supplierQuestionsNext, #workCategoriesNext").click(function(){
        if($(this).css('background-image').indexOf('Grey')==-1)
        {
            $('#pageDirection').val('next');
            $("#validateInputForm").submit();
        }
    });

    $("#supplierQuestionsPrev, #workCategoriesPrev").click(function(){
        if($(this).css('background-image').indexOf('Grey')==-1)
        {
            $('#pageDirection').val('prev');
            $("#validateInputForm").submit();
        }
    });

    $("#supplierQuestionHome, #workCategoriesHome").click(function(){
        if($(this).css('background-image').indexOf('Grey')==-1)
        {
            $('#pageDirection').val('home');
            $("#validateInputForm").submit();
        }
    });

    $(".supplierAssessment").click(function(){
        $("#selectedSupplier").val($(this).attr('rel'));
        $("#supplier_index").submit();
    });

    $("#addCLUser, #editCLUser, #passwordChangeButton, #supplierContactForm").click(function(){
        $("#validateInputForm").submit();
    });

    $('.file').change(function() {
        var filePath= $(this).val();
        var uploadMsg=$(this).attr("id")+"_status";
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toUpperCase();
        if(allowedFileTypes.indexOf(ext) != -1) //if extension of file in allowedFileTypes
        {
            $('#upState').val('true');
            $('#upNumber').val($(this).attr("id"));
            $('#validateInputForm').attr("target","target_iframe");
            $('#' + uploadMsg).append("<div class='uploadMessage'><img src='/images/file_upload.gif'>&nbsp;uploading file(s)</div>");

            $('#supplierQuestionsNext').removeClass('clButton');
            $('#supplierQuestionsNext').addClass('clGreyButton');

            $('#supplierQuestionsPrev').removeClass('clButton');
            $('#supplierQuestionsPrev').addClass('clGreyButton');

            $('#supplierQuestionHome').removeClass('clButton');
            $('#supplierQuestionHome').addClass('clGreyButton');

            $(".file").hide();
            $(".file-input .btn").css("background-image", "url('/images/Upload_disabled.png')");

            $('#validateInputForm').submit();
        }
        else
            alert("File type not permitted")
    });

    //---QUERYSTRING ROUTINES---

    $("#ssipConstructionlineSubmit").click(function()
    {
        $("#postSubmit").val("1");
        $("#constructionline_summary").submit();
    });

    $("#ssipAssessorSubmit").click(function()
    {
        $("#postSubmit").val("1");
        $("#validateInputForm").submit();
    });

    $("#ssipSave").click(function()
    {
        window.location='/logout.php?commitchanges=1';
    });

    $("#supplier_ssipSubmit" ).bind( "dialogbeforeclose", function() {
        window.location='/logout.php';
    });

    //On logout button check the changeDataCheck variable - show message if flag is true
    $("#logMeOut").click(function() {
        var input_box;

        if (changedDataCheck=='summarySubmit')
        {
            input_box=confirm("Assessment has not been saved/submitted. Please click on OK \nto confirm if you wish to do this or click on Cancel to \nreturn to the form");
            if (input_box==true)
                window.location="/logout.php";
        }
        else{
            if (changedDataCheck=='true')
            {
                input_box=confirm("Data entered will not be saved. Please click on OK \nto confirm if you wish to do this or click on Cancel to \nreturn to the form");
                if (input_box==true)
                    window.location="/logout.php";
            }
            else
                window.location="/logout.php";
        }
    });

    //---AJAX ROUTINES---
    
    $('#resetPassword').click(function(){
        if($(this).css('background-image').indexOf('Grey')==-1){
            $(".formErrorText").remove();
            $.ajax({
                type: "GET",
                url: "/ajax/sendEmail.php",
                success: function(data)
                {                    
                    if(data.trim()!="success")
                        $(".subsetControls").append('<div style="padding-left:10px;" class="formErrorText cntrlsFloatLeft">' + data + '</div>'); 
                    else
                    {
                        $("#passwordReset").dialog({
                            title: '&nbsp;',
                            width: 400,
                            resizable: false,
                            modal:true,
                            zIndex: 20
                        });
                    }
                }
            }); 
        
        }
    });
    
    $("#Users [type='checkbox']").live('click',function(){  
        var state=$(this).attr('checked')? 1 : 0;
        
        $.ajax({
            type: "GET",
            url: "/ajax/activateUser.php",
            data: "param1=" + $(this).val() + "&param2=" + state,
            success: function(data)
            {
                if(data.trim()!="Success")
                    $(".subsetControls").append('<div style="padding-right:10px;" class="formErrorText cntrlsFloatRight">' + data + '</div>');                       
            }
        });       
    });

    $(".updateSupplier").click(function()
    {
        answerId="answer_" + $(this).attr("rel");
        answerAddCommentId="answerAddComment_"+$(this).attr("rel");
        addUnderline="addCUnderline_"+ $(this).attr("rel");
        suppliercommentTextArea="supplierCommentTextArea_" + $(this).attr("rel");
        constructioncommentTextArea="constructionlineCommentTextArea_" + $(this).attr("rel");
        assessorcommentTextArea="assessorCommentTextArea_" + $(this).attr("rel");
        canUpload="canUpload_" + $(this).attr("rel");
        question="q" + $(this).attr("rel") + "_status";
        spcommentRow="supplierCommentTextArea_" + $(this).attr("rel");
        clcommentRow="constructionlineCommentTextArea_" + $(this).attr("rel");
        ascommentRow="assessorCommentTextArea_" + $(this).attr("rel");
        commentTextArea="commentTextArea_new_" + $(this).attr("rel");

        //use get elementbyid due to performance issues in IE
        document.getElementById(answerId + "_Y").disabled=false;
        document.getElementById(answerId + "_N").disabled=false;

        document.getElementById(commentTextArea).readOnly = false;
        $("#" + canUpload).css("visibility","visible");

        $('#' + answerAddCommentId).removeClass('clGreyButton');
        $('#' + answerAddCommentId).addClass('clButton');
        $('#' + answerAddCommentId).addClass('showComment');
        $('#' + addUnderline).addClass("inputButton");
        if(($('#pageState').val()==3)||($('#pageState').val()==7))
        {
            //remove all previous comments for that question
            $("#" + suppliercommentTextArea + " .commentStatus_1, #" + constructioncommentTextArea + " .commentStatus_1, #" + assessorcommentTextArea + " .commentStatus_1").remove();
            if ($('#' + spcommentRow + ' tr').length==0) //check each table length
                $('#' + suppliercommentTextArea).css("display","none");
            if ($('#' + clcommentRow + ' tr').length==0)
                $('#' + constructioncommentTextArea).css("display","none");
            if ($('#' + ascommentRow + ' tr').length==0)
                $('#' + assessorcommentTextArea).css("display","none");

            //mark comments as deleted in object
            $.ajax({
                type: "GET",
                url: "/ajax/removeComments.php",
                data: "param1=" + $(this).attr("rel")
            });
        }

        //Show delete icons
        $('#' + question + " .nodelFile").each(function() {
            $(this).addClass('delFile');
            $(this).removeClass('nodelFile');
        });
    });

    $(".saveAssignFileName").click(function(){
        var data= new Array();
        fileManagerQuestion = $(this).attr("rel");
        $("#assign_filename_"+ fileManagerQuestion + " .displayNameInput").each(function() {
            //for each selectbox in table check hidden value to see if any changes have been made
            if($(this).parent().next().next().find(":input").val())
            {
                atid=$(this).attr("id").split("_");
                //if changes have been made push id of lookup value, questionid,attachmentid and new file name into array
                record=new Array($(this).parent().next().next().find(":input").val(),fileManagerQuestion,atid[1],$(this).parent().next().html());
                data.push(record);
            }
        });
        if(data.length>0){ //if data to send
            $(".formErrorText").remove(); //remove any errors
            $.ajax({
                type: "POST",
                url: "/ajax/updateDisplayName.php",
                data: {
                    param1:  data
                },//pass in array of values - ajax will convert
                success: function(id)
                {
                    if(id.trim().indexOf("Error") == -1)
                    {
                        $("#assign_filename_"+ id.trim() +" input:hidden").each(function() {
                            $(this).val("");
                        });
                        $("#q" + id.trim()+ "_status").load('constructionline_ssip_questions.php #q' + id.trim() + '_status');
                        $("#assign_filename_"+ id.trim()).dialog("close");
                    }
                    else                    
                    {                         
                        values=id.split("-");
                        $("#assign_filename_"+ values[0].trim() + " .saveAssignFileName").parent().append('<div style="padding-right:10px;" class="formErrorText cntrlsFloatRight">' + values[1].trim() + '</div>');                                            
                    }

                }
            });
        }
        else
            $("#assign_filename_"+ fileManagerQuestion).dialog("close");
    });

    //Sort lookup values for maintain lookup screen
    $(".codeSortLink").click(function(){
        $("#sortDirection").attr("src",($("#sortDirection").attr("src") == "/images/arrow_sort_asc.png") ? "/images/arrow_sort_desc.png" : "/images/arrow_sort_asc.png");
        if($("#sortDirection").attr("src")=="/images/arrow_sort_asc.png")
            direction=1;
        else
            direction=2;
        $.getJSON('/ajax/sortFilenames.php',{
            param1:direction
        }, function(data) {
            if(!data.error)
            {
                $("#maintainedFiles tr").remove();
                $.each(data, function(index, array) {
                    //Dont show records that have been marked as deleted
                    if(!array['toBeDeleted']==1)
                    {
                        row="<tr valign='top' id='lookup_" + array['fileNameID'] + "'>"
                        + "<td class='nogrid checkBox'><input title='Check to mark for deletion' alt='Check to mark for deletion' type='checkbox' value='"+ array['fileNameID'] +"'></td>"
                        + "<td class='nogrid code'><a title='Modify filename' alt='Modify filename' class='codeLink' style='color:#0000E1;'>" + array['code'] +"</a></td>"
                        + "<td class='nogrid description'>"+ array['description'] + "</td>"
                        + "</tr>";
                        $("#maintainedFiles").append(row);
                    }
                });
                $("#descriptionID, #codeID").val("");
                $("#maintain_text .formErrorText").remove(); //remove any errors
                $("#maintain_text .maintainOverFlowDiv").scrollTop(0);
            }
        });
        
    });

    $( "#maintain_text" ).bind( "dialogbeforeclose", function() {
        //On add, update and delete set datachanged flag to true if close set back to false
        if(changedDataCheck=='true')
        {
            input_box=confirm("Changes has not been saved. Please click on OK \nto confirm if you wish to do this or click on Cancel to \nreturn to the form");
            if (input_box==true)
            {
                //Reset div to clear any changes made
                $.getJSON('/ajax/resetFileNames.php', function(data) {
                    if(!data.error)
                    {
                        $("#maintainedFiles tr").remove();
                        $.each(data, function(index, array) {
                            row="<tr valign='top' id='lookup_" + array['fileNameID'] + "'>"
                            + "<td class='nogrid checkBox'><input title='Check to mark for deletion' alt='Check to mark for deletion' type='checkbox' value='"+ array['fileNameID'] +"'></td>"
                            + "<td class='nogrid code'><a title='Modify filename' alt='Modify filename' class='codeLink' style='color:#0000E1;'>" + array['code'] +"</a></td>"
                            + "<td class='nogrid description'>"+ array['description'] + "</td>"
                            + "</tr>";
                            $("#maintainedFiles").append(row);
                        });
                        $("#descriptionID, #codeID").val("");
                        $("#maintain_text .formErrorText").remove(); //remove any errors
                        changedDataCheck='false';
                    }
                });
                return true;
            }
            else
                return false;
        }
        else
        {
            $("#descriptionID, #codeID").val("");
            $("#maintain_text .formErrorText").remove(); //remove any errors
            $("#maintainedFiles [type='checkbox']:checked").removeAttr('checked');
            return true;
        }
    });

    $('#maintainSave').click(function(){
        $(".formErrorText").remove(); //remove any errors
        $.ajax({
            type: "GET",
            url: "/ajax/saveFileNames.php",
            success: function(data)
            {
                if(data.trim()=="success")
                    $("#validateInputForm").submit();
                else                    
                    $("#maintainSave").parent().append("<span style='padding-right:10px;' class='formErrorText cntrlsFloatRight'>" + data + "</span>");
            //changedDataCheck will be reset on submit
            }
        });
    });
    
    $('#deleteLookupConfirmOK').click(function(){ 

        var data=new Array();
        $(".settings tr [type='checkbox']").each(function() {
            if($(this).attr('checked'))
                data.push($(this).val());
        });
                
        if(data.length>0){
            $.ajax({
                type: "POST",
                dataType:'json',
                url: "/ajax/delete"+ $(".section").find(".settings").attr("id") +".php",
                data: {
                    param1:  data
                },//pass in array of values - ajax will convert
                success: function(data)
                {                      
                    if(data.error)
                        $("#deleteLookups").parent().append('<div style="padding-right:10px;" class="formErrorText cntrlsFloatRight">' + data.error + '</div>');                        
                    else
                    {
                        $.each(data, function(index, item) {
                            $("#lk" + item).remove();
                        });
                    }
                    $("#deleteLookupConfirmation").dialog( "close" );
                    
                }
            })  
        }        
    });
    
    //use the same function for all lookups    
    $('#deleteLookups').click(function(){    
        $(".formErrorText").remove();
        if ($(".settings tr [type='checkbox']:checked").length>0)        
        {
            $("#deleteLookupConfirmation").dialog({
                title: '&nbsp;',
                width: 400,
                resizable: false,
                modal:true,
                zIndex: 20
            });
        }
        else
            $(this).parent().append('<div style="padding-right:10px;" class="formErrorText cntrlsFloatRight">Please select item(s) to delete.</div>');                    
    });

    $("#maintainDelete").click(function(){
        var data= new Array();
        var dataDeleted=false;

        //Remove any previously highlighted rows
        $(".tableBody tr").removeClass('boldText');
        $("#maintain_text .formErrorText").remove();
        $(".tableBody tr [type='checkbox']").each(function() {
            if($(this).attr('checked'))
                data.push($(this).val());
        });
        if(data.length>0)
        {
            $.ajax({
                type: "POST",
                dataType:'json',
                url: "/ajax/deleteFileNames.php",
                data: {
                    param1:  data
                },//pass in array of values - ajax will convert
                success: function(data)
                {
                    if(data.error)
                    {
                        $("#codeID").parent().append("<span class='formErrorText'><br>" + data.error + "</span>");
                    }
                    else
                    {
                        $.each(data, function(index, item) {
                            if(item!="error")
                            {
                                $("#maintainedFiles #lookup_" + item).remove();
                                dataDeleted=true;
                            }
                            else
                            {
                                if($("#codeID").parent().html().indexOf('formErrorText')==-1)
                                    $("#codeID").parent().append("<span class='formErrorText'><br>Error deleting some selected item(s). Code(s) in use.</span>");
                            }

                        });
                        if (dataDeleted==true)
                            changedDataCheck='true';
                    }
                }

            });
        }
        else
            $("#codeID").parent().append("<span class='formErrorText'><br>Please select item(s) to delete.</span>");
    });

    $("#maintainAdd").click(function(){
        var currentTime = new Date();

        //Remove any previously highlighted rows
        $(".tableBody tr").removeClass('boldText');
        error=ValidateInputs("#maintain_text");
        if(!error)
        {
            $.getJSON('/ajax/addFileNames.php',{
                param1:$('#codeID').val(),
                param2:$('#descriptionID').val(),
                param3:"ftmp_" + currentTime.getTime()
            }, function(data) {
                if(data.error)
                {
                    $("#codeID").parent().append("<span class='formErrorText'><br>" + data.error + "</span>");
                }
                else
                {
                    $("#maintainedFiles").append("<tr valign='top' id='lookup_" + data.fileNameID + "'><td class='nogrid checkBox'><input title='Check to mark for deletion' alt='Check to mark for deletion' type='checkbox' value='"+ data.fileNameID +"'></td><td class='nogrid code'><a title='Modify filename' alt='Modify filename' class='codeLink' style='color:#0000E1;'>"+data.code+"</a></td><td class='nogrid description'>"+data.description+"</td></tr>");
                    $("#descriptionID, #codeID").val("");
                    $("#maintain_text .maintainOverFlowDiv").scrollTop($("#maintain_text .maintainOverFlowDiv")[0].scrollHeight);
                    changedDataCheck='true';
                }

            });
        }
    });

    $("#maintainUpdate").click(function(){

        $("#maintain_text .formErrorText").remove();
        //If the user has selected a row to be updated (check for highlighted rows)
        if($("#maintain_text .boldText").length>0)
        {
            error=ValidateInputs("#maintain_text");
            if(!error)
            {
                $.getJSON('/ajax/updateFileNames.php',{
                    param1:$('#fileNameID').val(),
                    param2:$('#descriptionID').val(),
                    param3:$('#codeID').val()
                }, function(data) {
                    if(data.error)
                    {
                        $("#codeID").parent().append("<span class='formErrorText'><br>" + data.error + "</span>");
                    }
                    else
                    {
                        //Update code and description
                        $("#maintainedFiles #lookup_" + data.fileNameID + " .code").html('<a title="Modify filename" class="codeLink" style="color:#0000E1;">'+ data.code +'</a>');
                        $("#maintainedFiles #lookup_" + data.fileNameID + " .description").html(data.description);
                        changedDataCheck='true';
                    }
                });
            }
        }
        else
        {
            $("#codeID").parent().append("<span class='formErrorText'><br>Error - Please select an item to update.</span>");
        }
        $("#descriptionID, #codeID").val("");
        $(".tableBody tr").removeClass('boldText');
    });

    //Delete uploaded files - live as elements are generated at runtime
    $(".delFile").live('click',function() {
        //match numbers
        var id= /[0-9]+/;
        var dataString;
        var upload=$(this).parent();

        questionId=$(this).parent().parent().attr('id');
        var matchArray = id.exec(questionId);

        questionId=matchArray[0];
        //Get the href of the file and split it to get its filename
        filename=$(this).next().attr('href').split("?file=");
        if($(this).parent().attr("id"))
        {
            //Pass in filename, question id and attachement id
            attachmentId=$(this).parent().attr("id").split("_");
            dataString="param1=" + filename[1] + "&param2=" + questionId + "&param3=" + attachmentId[1];
        }
        else
            dataString="param1=" + filename[1] + "&param2=" + questionId;

        $.ajax({
            type: "GET",
            url: "/ajax/deleteAttachment.php",
            data: dataString,
            success: function(msg)
            {
                if(msg==1){
                    upload.remove();
                    changedDataCheck='true';
                }
                else
                    alert(msg);
            },
            error: function()
            {
                alert("Error removing file");
            }
        });

    });

    //contactaddress select box is changed
    $("#contactaddress").change(function(){
        $(".formErrorText").remove(); //remove any errors
        if($(this).val()=="1")
        {
            $.getJSON('/ajax/getSupplierAddress.php',{
                param1:$("#supplierId").val()
            }, function(data) {
                if(data.error)
                {                    
                    $("#contactaddress").parent().append("<span class='formErrorText'><br>"+ data.error + "</span>");
                }
                else
                {
                    $("#address1").val(data.address1);
                    $("#address2").val(data.address2);
                    $("#address3").val(data.address3);
                    $("#address4").val(data.address4);
                    $("#town").val(data.town);
                    $("#county").val(data.county);
                    $("#postcode").val(data.postcode);
                    $("#www").val(data.www);
                }

            /*
                //uses getElementById here due to speed issues in IE
                document.getElementById("address1").readOnly = true;
                document.getElementById("address2").readOnly = true;
                document.getElementById("address3").readOnly = true;
                document.getElementById("address4").readOnly = true;
                document.getElementById("town").readOnly = true;
                document.getElementById("county").readOnly = true;
                document.getElementById("postcode").readOnly = true;
                document.getElementById("www").readOnly = true;

                $("#address1, #address2, #address3, #address4, #town, #county, #postcode,#www").addClass('disabledInput');
                     */
            });
        }
        else if($(this).val()=="2")
        {
            $("#address1, #address2, #address3, #address4, #town, #county, #postcode,#www").val("");

        /*
            //speed issues in ie
            document.getElementById("address1").readOnly = false;
            document.getElementById("address2").readOnly = false;
            document.getElementById("address3").readOnly = false;
            document.getElementById("address4").readOnly = false;
            document.getElementById("town").readOnly = false;
            document.getElementById("county").readOnly = false;
            document.getElementById("postcode").readOnly = false;
            document.getElementById("www").readOnly = false;

            $("#address1, #address2, #address3, #address4, #town, #county, #postcode,#www").removeClass('disabledInput');
                 */
        }       
    });

    //primarycontact selectbox changed
    $("#primarycontact").change(function()
    {
        $(".formErrorText").remove(); //remove any errors
        if($(this).val()=="1")
        {
            //$(this).parent().append("<span id='primarycontactWait' class='waiting'><br>retrieving data...</span>");

            $.getJSON('/ajax/getPrimaryContact.php',{
                param1:$("#supplierId").val()
            }, function(data) {
                if(data.error)
                {                    
                    $("#primarycontact").parent().append("<span class='formErrorText'><br>"+ data.error + "</span>");
                }
                else
                {
                    $("#title").val(data.title);
                    $("#forename").val(data.forename);
                    $("#surname").val(data.surname);
                    $("#tel").val(data.telephone);
                    $("#email").val(data.email);
                }
            //$("#readOnlyTitle").val(data.title);
            /*
                document.getElementById("forename").readOnly = true;
                document.getElementById("surname").readOnly = true;
                document.getElementById("tel").readOnly = true;
                document.getElementById("email").readOnly = true;

                $("#title").css("display","none");
                $("#readOnlyTitle").css("display","");

                $("#forename,#surname,#tel,#email").addClass('disabledInput');
                     */
            });
        }
        else if($(this).val()=="2")
        {
            $("#title,#forename,#surname,#tel,#email").val("");
        /*
            document.getElementById("forename").readOnly = false;
            document.getElementById("surname").readOnly = false;
            document.getElementById("tel").readOnly = false;
            document.getElementById("email").readOnly = false;

            $("#title").css("display","");
            $("#readOnlyTitle").css("display","none");
            $("#forename,#surname,#tel,#email").removeClass('disabledInput');
                 */
        }

    });

    //---DIALOG ROUTINES---  

    $('#passwordResetOK').click(function(){
        $("#passwordReset").dialog( "close" );
        $('#resetPassword').removeClass('clButton');
        $('#resetPassword').addClass('clGreyButton');
    });    
    
    $('#deleteForm').click(function(){
        $("#deleteConfirmation").dialog({
            title: '&nbsp;',
            width: 400,
            resizable: false,
            modal:true,
            zIndex: 20
        });
    });
    
    //remove any confirmation boxes from the screen
    $('#deleteConfirmCancel, #deleteLookupConfirmCancel').click(function(){
        $("#deleteConfirmation, #deleteLookupConfirmation").dialog( "close" );
    });

    $('#maintainClose').click(function(){
        $("#maintain_text").dialog( "close" );
    });

    //show hide add
    $(".addEntry").click(function(){
        $("#assign_filename_" + fileManagerQuestion).dialog( "close" );
        $("#maintain_text").dialog({
            title: '&nbsp;',
            width: 1020,
            resizable: false,
            modal:true,
            zIndex: 20
        });
    });

    $("#printReport, #submitPrint").click(function()
    {
        if($("#printReport").attr("rel")=="SUPPLIER_COMPLETE" || $("#printReport").attr("rel")=="BUYER")
        {
            if ($('#printReportDialog').dialog('isOpen')!=true)
            {
                $("#printReportDialog").dialog({
                    title: '&nbsp;',
                    width: 500,
                    resizable: false,
                    modal:true,
                    zIndex: 20
                });
            }
        }
        else
        {
            //window.location="/templates/PDF/ssip_supplier_report.php?uploads=1&comments=1";
            window.open("/templates/PDF/ssip_supplier_report.php?uploads=1&comments=1");
        }
    });

    $("#generateReport").click(function(){
        download=false;
        queryString="?";

        $("#printReportDialog [type='checkbox']").each(function() {
            if($(this).attr('checked'))
                queryString=queryString+$(this).attr('name') +"=1&"
            if($(this).attr('checked') && $(this).attr('name')=='uploads')
                download=true;
        });
        if($("#printReportDialog [type='checkbox']").length==1)//if only one select box set comments to always on
            queryString=queryString+"comments=1&"

        if(download==true)
            window.location="/templates/PDF/ssip_supplier_report.php?uploads=1&comments=1";
        else
            window.open('/templates/PDF/ssip_supplier_report.php' + queryString.slice(0, -1));

        $("#printReportDialog").dialog( "close" );
    });

    $("#ssipSubmit").click(function()
    {
        $.getJSON('/ajax/supplierSubmit.php',{}, function(data) {
            if(data.error)
            {
                alert(data.error);
            }
            else
            {
                $("#supplier_ssipSubmit").dialog({
                    title: '&nbsp;',
                    width: 660,
                    resizable: false,
                    modal:true,
                    zIndex: 20
                });
            }
        });
    });

    $(".uploadDocuments").click(function()
    {
        fileManagerQuestion= $(this).attr("rel");
        $("#assign_filename_" + fileManagerQuestion).dialog({
            title: '&nbsp;',
            width: 1020,
            resizable: false,
            modal:true,
            zIndex: 20
        });

    });

    $("#ssipSubmit_close").click(function(){
        $("#supplier_ssipSubmit").dialog( "close" );
    });

});
