function getString(_object)
{
    if (_object == undefined)
        return '';
    else if (_object == null)
        return '';
    else 
        return String(_object);
}

/*Array.prototype.indexOf = function(obj, start) { 
     for (var i = (start || 0), j = this.length; i < j; i++) { 
         if (this[i] === obj) { return i; } 
     } 
     return -1; 
} 
*/

function checkArray(_array, obj, start) {
    for (var i = (start || 0), j = _array.length; i < j; i++) {
        if (_array[i] === obj) { return i; }
    }
    return -1;
}


var citValidation = function () {
    this.ValidationSummeryIsVisible = false;
    this.Sender = null;
    this.ShowSummery = false;
    this.SummeryBox = null;
    this.SummeryText = '';
    this.IsValid = true;
    this.AllowBlankErrorTextInput = CIT.Labels.MustNotBeBlank;
    this.AllowBlankErrorOthers = CIT.Labels.MustBeSelected;
    this.UnknownError = 'unknown error';
    this.Items = null;
    this.ErrorItems = $("#gdfg");
    this.ErrorMessages = new Array();
    this.ErrorFields = new Array();

    this.MarkMandatoryFields = function (_position) {
        _this = this;

        if (this.Items == null)
            this.Items = $("*[validate='true']");

        this.Items.each(function (i) {

            var Item = $(this);
            var displayError = false;
            var errorText = '';

            if (Item.attr("allowBlank") == 'false') {


                if ((Item[0].type == 'text') && (Item[0].tagName == 'INPUT'))
                    _mandatoryText = '<span style="color:#CC0000;" title="' + _this.AllowBlankErrorTextInput + '"> * </span>';
                else
                    _mandatoryText = '<span style="color:#CC0000;" title="' + _this.AllowBlankErrorOthers + '"> * </span>';


                if (_position == 'before')
                    Item.before(_mandatoryText);
                else
                    Item.after(_mandatoryText);

            }
        })
    }

    this.ShowError = function (_item, _errortext) {
        //this.ErrorItems = this.ErrorItems.add(_item);

        var _friendly = getString(_item.attr('friendly'));
        if (_friendly != '')
            _errortext = _friendly + ': ' + _errortext;

        _errorElementId = getString(_item.attr('errorelement'));
        if (_errorElementId != '')
            $("#" + _errorElementId).show()[0].title = _errortext;

        _item.addClass("error")[0].title = _errortext;
        this.IsValid = false;

        //var idx = this.ErrorFields.indexOf(_item[0].id)
        var idx = checkArray(this.ErrorFields, _item[0].id);

        //Hvis feltet allerede findes, opdater fejlbesked
        if (idx > -1) {
            this.ErrorMessages[idx] = _errortext;
        }
        else {	//Ellers tilføj felt
            this.ErrorMessages.push(_errortext);
            this.ErrorFields.push(_item[0].id);
        }
    }

    this.HideError = function (_item) {
        //var idx = this.ErrorFields.indexOf(_item[0].id)
        var idx = checkArray(this.ErrorFields, _item[0].id);

        if (idx > -1) {
            this.ErrorFields.splice(idx, 1);
            this.ErrorMessages.splice(idx, 1);
        }
        _errorElementId = getString(_item.attr('errorelement'));
        if (_errorElementId != '')
            $("#" + _errorElementId).hide()[0].title = '';

        _item.removeClass("error")[0].title = '';
    }

    this.GenerateValidationSummery = function () {
        this.SummeryText = '';
        for (var i = 0; i < this.ErrorMessages.length; i++) {
            this.SummeryText += '<li>' + this.ErrorMessages[i] + '</li>';
        }
    }

    this.ShowValidationSummeryPopup = function () {
        _this = this;
        this.GenerateValidationSummery();
        if (this.SummeryBox == null)
            this.SummeryBox = $("#ValidationSummeryPopup");

        this.SummeryBox.find("#Container").html(this.SummeryText);

        this.SummeryBox.click(function () {
            _this.HideValidationSummeryPopup();
        });

        this.SummeryBox
            .fadeIn()
	        .css({
	            top: (this.Sender.position().top + 15) + "px",
	            left: (this.Sender.position().left + 15) + "px"
	        });

    }

    this.HideValidationSummeryPopup = function () {
        if (this.SummeryBox == null)
            this.SummeryBox = $("#ValidationSummeryPopup");

        this.ClearAllErrorElements();

        this.SummeryBox.find("#Container").html('');
        this.SummeryBox.fadeOut();
    }


    this.ShowValidationSummery = function () {
        //for (var i = 0; i < this.ErrorMessages.length; i++) { 
        //    this.SummeryText += '<li>' + this.ErrorMessages[i] + '</li>';
        //}
        this.GenerateValidationSummery();
        //alert(this.SummeryBox.length);
        if (this.SummeryBox == null)
            this.SummeryBox = $("#ValidationSummeryBox");
        //alert(this.SummeryBox);
        this.SummeryBox.find("#Container").html(this.SummeryText);
        //alert(this.SummeryText);
        this.SummeryBox.slideDown();
        this.ValidationSummeryIsVisible = true;

        //this.SummeryContainer.html(this.SummeryText).slideDown();
    }

    this.HideValidationSummery = function () {
        if (this.SummeryBox == null)
            this.SummeryBox = $("#ValidationSummeryBox");

        this.SummeryBox.find("#Container").html('');
        this.SummeryBox.slideUp();

        this.ValidationSummeryIsVisible = false;
    }

    this.ClearAllErrorElements = function () {
        _this = this;
        this.ErrorItems.each(function (i) {

            var Item = $(this);
            _this.HideError(Item);
        })
        this.ErrorItems.first().focus();
    }

    this.ValidateItem = function (Item) {

        var displayError = false;
        var errorText = '';

        //Allow blank check
        if ((Item.attr("allowBlank") == 'false') && (Item.val() == '')) {
            displayError = true;

            if ((Item[0].type == 'text') && (Item[0].tagName == 'INPUT'))
                errorText = _this.AllowBlankErrorTextInput;
            //alert();
            else
                errorText = _this.AllowBlankErrorOthers;
        }
        else {
            //Regular expression validation
            regError = false;
            _regularExpression = getString(Item.attr('regularexpression'));
            if (_regularExpression != '' && Item.val() != "") {
                myRegExp = new RegExp(_regularExpression)
                if (myRegExp.exec(Item.val()) == null) {
                    displayError = true;
                    regError = true;
                }
            }

            //Function validation
            _validationFunction = getString(Item.attr('validationfunction'));
            if ((!displayError) && (_validationFunction != '')) {
                var isFieldValid = false;
                //strFunc = new String(validationfunction);
                eval('isFieldValid = ' + _validationFunction + '(Item);');

                isFieldValid = new String(isFieldValid);
                if (isFieldValid == 'true') {
                }
                else if (isFieldValid == 'false') {
                    displayError = true;
                }
                else {
                    displayError = true;
                    errorText = isFieldValid;
                }
            }

            if (displayError) {
                if (errorText == '') {
                    if (getString(Item.attr('errordescriptionid')) != '')
                        eval('errorText = ' + getString(Item.attr('errordescriptionid')));
                    else if ((regError) && (getString(Item.attr('errordescription_reg') != '')))
                        errorText = getString(Item.attr('errordescription_reg'));
                    else if ((!regError) && (getString(Item.attr('errordescription_func') != '')))
                        errorText = getString(Item.attr('errordescription_func'));

                    if (errorText == '')
                        errorText = _this.UnknownError;
                }
            }

        }

        if (displayError)
            _this.ShowError(Item, errorText);
        else
            _this.HideError(Item);


    }

    this.Validate = function () {
        _this = this;

        //Clear 
        this.IsValid = true;
        this.ErrorItems = $("#gdfg");
        this.ErrorMessages = new Array();
        this.ErrorFields = new Array();


        if (this.Items == null)
            this.Items = $("*[validate='true']");


        this.Items.each(function (i) {
            //alert(this.id);
            if ($(this).attr('tempdontvalidate') != 'true')
                _this.ValidateItem($(this));


        });



        if (this.ShowSummery) {
            if (!this.IsValid)
                this.ShowValidationSummery();
            else
                this.HideValidationSummery();
        }
    }

}



