var deleteproformacomment = true;
var skipCheck = false;
var inputHasFocus = false;

var jqueryEnabled = true;

var addEvidenceWindow;

if (typeof jQuery != 'function') {
    jqueryEnabled = false;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
/*
$(':input').change(function() {
    if (!isDirty) {
        isDirty = true;
    }
});

$('a').click(function() {
    return CheckWindowClose();
});


jQuery(window).unload(function(e) {
    return CheckWindowClose();
});


$(window).bind("beforeunload", function(e) {
    e.returnValue = "Are you sure? You haven\'t saved your changes. Click OK to leave or Cancel to go back and save your changes."; 
});
*/

function closeIt() {
    if (typeof ajaxDeleteProformaComment == 'function') {
        if (!skipCheck) {
            ajaxDeleteProformaComment();
        }
    } else {
        if (CheckWindowClose() && !skipCheck && (!addEvidenceWindow || addEvidenceWindow.closed)) {
            return 'You haven\'t saved your changes! Navigating away will lose any changes you have made.';
        }
    }
}

window.onbeforeunload = closeIt;

function rebindBeforeUpload() {

    window.onbeforeunload = closeIt;

}

function CheckWindowClose() {
    var elements = $(".changed");
    
    if(elements != null) {
    
        if (elements.length > 0) {
            return true;
        }
    }

    if (inputHasFocus) {
        return true;
    }    
    
    return false;
}

if (jqueryEnabled) {
    $(document).ready(function() {

        var input = $('input');
        var textarea = $('textarea');

        if (input != null) {
            $('input').focus(function() {
                inputHasFocus = true;
            });
        }

        if (textarea != null) {
            $('textarea').focus(function() {
                inputHasFocus = true;
            });
        }
    });
}

if (jqueryEnabled) {
    $(function() {

        var form = $('form');

        if (form != null) {
            $("form").dirty_form();
        }
    });
}

function ChangeBranchType(radiobutton) {
    var selectedvalue = $('input[name=' + radiobutton.name + ']:checked').val()
    if (selectedvalue) {
        $('.' + selectedvalue).show();

        if (selectedvalue == "branchtwo") {
            $('.' + "branchone").hide();
        } else {
            $('.' + "branchtwo").hide();
        }
    }
}

function FillBoxFromSelectList(boxid, selectList) {

    var value = selectList.options[selectList.selectedIndex].value;
    if (value != "None") {
        value = value.replace(new RegExp("\\[br\\]", "g"), "\n");
    }

    var box = $('#' + boxid);

    if (value == "None") {
        value = "";
    }
    box.val(value);
}

function validateInputs(redirectlocation, nopostback){
    
    IsNumeric(true);
    
    var title = document.getElementById("title");
    var description = document.getElementById("description");
    var doform = true;
    
    if(redirectlocation == undefined || null == redirectlocation || redirectlocation == "" )
        doform = false;
    
    if(title != null && description != null){
        if(title.value == "" && description.value == ""){
            alert("A title or description is needed for this form");
            doform = false;
            return false;
        }else{

            if(title.value.trim() == "" && description.value.trim() == ""){
                alert("A title or description is needed for this form");
                doform = false;
                return false;
            }
        }
    }
    
    stripHTML(document.getElementsByTagName("input"));
    stripHTML(elementsInputs = document.getElementsByTagName("textarea"));

    //This method is also called from the builder scripts where prototype eats $ and breaks CheckForRequired
    if (typeof Prototype == 'undefined') {
        if (!CheckForRequired()) {
            return false;
        }
    }

    if (doform == true) {
        skipCheck = true;
        
        var theForm = document.getElementById("mainproformaform");
        if (!theForm) {
            theForm = document.forms[0];
        }
    
        deleteproformacomment = false;
        if(nopostback != undefined && null != nopostback && nopostback == true){   
        }else{
            if(noPostBack != undefined && null != noPostBack && noPostBack){
                noPostBack(redirectlocation);
            }
        }
        var forms = document.getElementsByTagName("form");   
        if(doform == true){
            theForm.enctype = "multipart/form-data";
            theForm.action = redirectlocation;
            theForm.submit(); 
        }
    } else {
        skipCheck = true;
        return true;
    }
    
    skipCheck = true;
}

function stripHTML(elements){
    var re= /<\S[^><]*>/g;
    for (i=0; i<elements.length; i++){
        if(null != elements[i].type){
            if("file" != elements[i].type){
                elements[i].value=elements[i].value.replace(re, "");
            }
        }else{
            elements[i].value=elements[i].value.replace(re, "");
        }
    }
}

function IsNumeric(hideAlert) {
   return IsNumericInField("hours", "hours", hideAlert);}

function IsNumericInField(fieldName, niceName, hideAlert) {
    if (document.getElementById(fieldName) == null || document.getElementById(fieldName) == "undefined") {
        return
    }
    var sText = document.getElementById(fieldName).value;

    if (sText == "") {
        sText = "0";
        document.getElementById(fieldName).value = "0";
    }

    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }

    if (!IsNumber) {
        document.getElementById(fieldName).value = "";
        if ((hideAlert == null || hideAlert == "undefined" || hideAlert == false))
            alert("The " + niceName + " you entered is not valid!\n Only whole numbers may be used");

        document.getElementById(fieldName).value = "0";
        return false;
    }
    return true;
}

var foundRequiredElements = new Array();

var panelFoundWithContent = false;

function CheckForRequired() {

    //Clean the array
    foundRequiredElements = new Array();

    //Process single line inputs
    var inputBoxContainers = $(".textinputfield.requiredfield:visible");
    if (inputBoxContainers != null) {
        inputBoxContainers.each(function() {

            $(this).find("input:text").each(function() {

                if ($(this).val() == '') {
                    foundRequiredElements.push($(this).parents("table"));
                }

            });

        });
    }
    
    //Process textareas

        var textAreaContainers = $(".textareafield.requiredfield:visible");
        if (textAreaContainers != null) {
            textAreaContainers.each(function() {
                $(this).find("textarea").each(function() {

                    if ($(this).val() == '') {
                        foundRequiredElements.push($(this).parents("table"));
                    }

                });
            });
        }
    
    //Process radio buttons and checkboxes

        var radioButtonContainers = $(".radiobuttons.requiredfield:visible");
        if (radioButtonContainers != null) {
            radioButtonContainers.each(function() {

                var radioCount = $(this).find("input:radio:checked").length;
                var checkCount = $(this).find("input:checkbox:checked").length;

                var selectCount = 0;

                var selectItem = $(this).find("select");

                if (selectItem.length > 0 && selectItem.val() != "None") {
                    selectCount = 1;
                }

                if (radioCount + checkCount + selectCount == 0) {
                    foundRequiredElements.push($(this).parents("table"));
                }
            });
        }
    //}
    
    //Process likert inputs
    
        var likertContainers = $(".likertinput.requiredfield:visible");
        if (likertContainers != null) {
            likertContainers.each(function() {
                var radioCount = $(this).find("input:radio:checked").length;

                if (radioCount == 0) {
                    foundRequiredElements.push($(this).prev("table"));
                }
            });
        }
    
    //Process panel inputs

        var panelAreaContainers = $(".panelinput.requiredfield:visible");
        if (panelAreaContainers != null) {
            panelAreaContainers.each(function() {
                var areas = $(this).find("textarea");

                panelFoundWithContent = false;

                areas.each(function() {

                    if ($(this).val() != '') {
                        panelFoundWithContent = true;
                    }

                });

                if (!panelFoundWithContent) {
                    foundRequiredElements.push($(this).parent());
                }

            });
        }

        if (foundRequiredElements.length > 0) {

            for (var index = 0; index < foundRequiredElements.length; index++) {

                var foundRequiredField = foundRequiredElements[index];

                if (!foundRequiredField.is(":hidden") && !foundRequiredField.parents().is(":hidden")) {
                    alert("A required field has not been filled in.");
                    $('html, body').animate({ scrollTop: foundRequiredField.position().top }, 'slow', 'swing', null);
                    return false;
                }

            }

        }

    return true;
}


function TickPrivacyOptions(main){
    var controlBox = $(main);
    $('.remainprivatecheckbox').attr('checked', controlBox.attr("checked"));
}
