﻿//This function creates a textbox element with the given attributes
//Classes can have multiple classes in an array
//Validations can have multiple validations in an array
//Validation messages can have multiple validations in an array. It is necessar to match the 
// index of the validation message with the index of the validations.
function CreateElement(ClientId, Container, ID, Name, Classes, EntityType, EntityName, Value, ValidationMessages) {
    //  debugger;
    var element = document.createElement("input");
    $(Container).append(element);

    var validations = '';
    element.type = "text";
    element.setAttribute("id", ClientId + "_" + ID);
    if (Name != "")
        element.setAttribute("name", ClientId + "$" + Name);

    //Add Classes
    if (Classes instanceof Array) {
        $(Classes).each(function() {
            $(element).addClass(this);
        })
    }
    else
        $(element).addClass(Classes);

    //Assign water mark and validations from the type object
    if (EntityType != null) {

        if (EntityType.Validations != '')
            validations = EntityType.Validations;

        if (!IsEmpty(EntityType.Required) && EntityType.Required.toString().toLowerCase() == 'true')
            validations = validations + ' required';
        if (ValidationMessages != undefined && ValidationMessages != "") {
            ValidationMessages = ValidationMessages + ",";
        }
        ValidationMessages = ValidationMessages + "required: '" + EntityName + " is required.'";
    }

    SetValidationsForElement(element, validations, ValidationMessages);


    if (Value != undefined)
        $(element).val(Value);

    //add watermarks    
    if (EntityType != null) {
        if (EntityType.Watermark != "")
            $(Container).children('[id=' + element.getAttribute("id") + ']').attr('watermark', EntityType.Watermark);
    }
    //Add watermark events
    element.onfocus = function() { Focus($(element).attr("id")); }
    element.onblur = function() { Blur($(element).attr("id")); }
}

function SetValidationsForElement(element, Validations, ValidationMessages) {
    if (Validations instanceof Array) {
        var cntr = 0;
        $(Validations).each(function() {
            if (this.toString().indexOf(":") > -1) {
                var parts = this.toString().split(':');
                if (parts.length > 1) {
                    $(element).attr(parts[0], parts[1]);
                }
            }
            else
                $(element).addClass(this);
        });
    }
    else {
        if (Validations != '')
            $(element).addClass(Validations);
    }
    if (ValidationMessages != "")
        $(element).addClass("{validate:{messages:{" + ValidationMessages + "}}}");
}


function BlankRowForTypeExists(divMain, objData, Type, AttachDataFunction) {
    var result = false;
    divMain.children("div").each(function() {
        //debugger;
        if ($(this).children().size() > 0) {
            var lblType = $(this).children()[0];
            if ($(lblType).attr("EntryId") == undefined ||
                        parseInt($(lblType).attr("EntryId")) == 0 ||
                        parseInt($(lblType).attr("EntryId")) == NaN)
                if ($(lblType).text() == Type) {

                result = true;
                if (typeof AttachDataFunction == 'function')
                    AttachDataFunction.call(this, $(this), objData);
            }

        }

    });
    return result;
}


function CreateRemoveLink(Container, ID, ParentDivId) {
    /// <summary>Use this method to create a remove link object.</summary>
    /// <param name="Container">An object which will contain the remove link</param>
    /// <param name="ParentDivId" >ID to identify the parent container which will contain Container object</param>
    /// <returns >Nothing</returns>
    var lnk = document.createElement('a');
    lnk.innerHTML = '&nbsp;&nbsp;&nbsp;';
    lnk.id = ID;
    lnk.href = "#";
    lnk.alt = "Remove";
    lnk.className = 'imgRemove';
    $(lnk).attr("alt", "Remove");
    lnk.onclick = function RemoveEntry() {
        var mainDiv;
        if (ParentDivId == undefined || ParentDivId == "")
            mainDiv = Container.parentNode;
        else
            mainDiv = document.getElementById(ParentDivId);
        if (mainDiv != undefined)
            mainDiv.removeChild(this.parentNode);

        //        if (CallBackFunction instanceof Function)
        //            CallBackFunction.call(this, arguments);
    }


    Container.appendChild(lnk);
}

function ReloadTypes(ddl, CheckFunction) {
    var $options = $('option', ddl);
    var removeTypes = new Array();
    $options.each(function() {
        if (CheckFunction.call($(this).text())) {
            removeTypes[removeTypes.length] = $(this).text();
        }
    })
    for (i = 0; i < removeTypes.length; i++) {
        $options.filter("[text='" + removeTypes[i] + "']").remove();
    }
}

function HookSendDataEvent(EventIds, SendDataFunction, ClientId, DataObject) {

    $("form").submit(function() { SendDataFunction.call(this, ClientId, DataObject); });
    var strObjIds = EventIds;
    //alert(strObjIds);
    if (strObjIds != "") {
        var PopulateDataObjectIds = JSON.parse(strObjIds);
        if (PopulateDataObjectIds.length > 0) {
            for (i = 0; i < PopulateDataObjectIds.length; i++) {
                var currId = PopulateDataObjectIds[i];
                $("#" + currId).bind("click", '', function() { SendDataFunction.call(this, ClientId, DataObject); });
            }
        }
    }
}

function ClearMsgBox(item) {
    var msgBox = $("#messageBox");
    //debugger;
    if (msgBox != null) {
        if (item != null) {
            msgBox.find("[for^='" + item + "']").parent().remove();
            msgBox.find("[for^='" + item + "']").remove();
        }
        else {
            msgBox.children().remove();
        }
    }
}
function RemoveWatermark(obj) {
    ///<Summary>
    ///Removes the watermark from the input-text controls. If the obj is not passed removes watermark from 
    ///all the controls on the page
    ///</Summary>

    //            if (typeof (ClearMsgBox) == 'function') {
    //                ClearMsgBox();
    //            }
    var txtItems = Array();
    if (!obj)
        txtItems = $('input[type=text], textarea');
    else
        txtItems = obj;
    txtItems.each(function() {
        if ($(this).attr("watermark") != 'undefined')
            if ($(this).val() == $(this).attr("watermark")) {

            $(this).val('');
        }

    }
           )
}
function AddWatermark(obj) {
    ///<Summary>
    ///Adds the watermark to the input-text controls. If the obj is not passed adds watermark to 
    ///all the controls on the page
    ///</Summary>
    var txtItems;
    if (!obj)
        txtItems = $('input[type=text], textarea');
    else
        txtItems = obj;
    txtItems.each(function() {
        if ($(this).val() == '') {
            if ($(this).attr("watermark") != undefined) {
                $(this).val($(this).attr("watermark"));
                $(this).addClass("watermarkText");
                //$(this).removeClass("Adddress_textAddress");
            }
        }
    }
            )
}

function BeforeSubmit() {
   
    if (typeof (ClearMsgBox) == 'function') {
        ClearMsgBox();
    }
    if (typeof (RemoveWatermark) == 'function') {
        RemoveWatermark();
    }
  
    var res = $("form").validate().form();
    //AddWatermark();
    return res;
}


function Focus(objname) {
    ///<Summary>
    ///It is used to remove the water mark from the controls on the focus event
    ///</Summary>
    obj = document.getElementById(objname);
    if ($(obj).attr("watermark") != undefined) {
        if (obj.value == $(obj).attr("watermark")) {
            obj.value = "";
            //alert($(obj).attr("class"));
            //$(obj).addClass("Adddress_textAddress");
            $(obj).removeClass("watermarkText");
        }
    }
}
function Blur(objname) {
    ///<Summary>
    ///It is used to add the watermark to the controls on the focus event
    ///</Summary>
    obj = document.getElementById(objname);
    if (obj.value == "") {
        if ($(obj).attr("watermark") != undefined) {
            obj.value = $(obj).attr("watermark");
            $(obj).addClass("watermarkText");
            //  $(obj).removeClass("Adddress_textAddress");
        }
    }
    else {
        // $(obj).addClass("Adddress_textAddress");
        $(obj).removeClass("watermarkText");
    }
}


function IsEmpty(val) {
    ///<summary>Checks if the value is undefined or null or empty </summary>
    if (val == undefined || val == null || val == '')
        return true;
    else
        return false;
}


function CBoolean(val) {
    ///<summary>Converts string or number to boolean value </summary>
    if (!IsEmpty(val)) {
        switch (val.toString().toLowerCase()) {
            case '':
            case 'false':
            case '0':
            case 0:
                return false;
                break;
            case 'true':
            case '1':
            case 1:
                return true;
                break;
        }
    }
    return false;
}


function RemoveInvalidMessages(obj) {
    $(obj).find("input, textarea").each(function() {
        var forElement = $(this).attr("id");
        if ($("#" + forElement).length > 0) {
            $("#" + forElement).parent("").children(".Img_Error").remove();
            $("label[for='" + forElement + "']").parent().remove();
        }
        //.showErrors();
    });
}



/* Initializations
*/
var NewColumnWatermark = {
    "Title": "Column Name",
    "Value": "Column Value"
}


var ServiceMethods = {
    "KindMethod": "GetKinds",
    "ColumnCheckMethod": "CheckColumn"
}

var Multiplicity = {
    "Multiple": "Multiple",
    "One": "One"
}
var AddMode = {
    "Insert": { /*searches in database for the value and if not found inserts */
        "Name": "Insert",
        "Value": 1
    },
    "Select": {
        "Name": "Select",
        "Value": 3
    },
    "Search": {
        "Name": "Search",
        "Value": 4
    },
    "InsertInline": { /*Always inserts*/
        "Name": "Insert Inline",
        "Value": 8
    },
    "ValueSelect": {
        "Name": "Value Select",
        "Value": 3
    },
    "DetailedInfo": {
        "Name": "Insert With Detailed Info",
        "Value": 9
    }
}
function FormatValue(value, valueformat) {
    var result = value;
    switch (valueformat) {
        case "number":
        case "numberwithcomma":
            result = CommaFormatted(value);
            break;
        case "currency":
            result = CurrencyFormatted(value);
            break;
    }
    return result;
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}


function CommaFormatted(amount) {
    amount = amount.replace(/^0+/, '');
    amount += ''; x = amount.split('.');
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}