﻿



$(document).ready(function() {

    var objURL = new Object();

    window.location.search.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function(a, b, c, d) {
            if (b != "form") {
                $("#" + b).val(escape(d));
            }
        }
    );


    $("#form1").validate({
        errorPlacement: function(error, element) {

            if (element.hasClass("labelLeft")) {
                error.css("position", "absolute")
                error.appendTo(element.parent());
            }
            else if (element.is(":radio")) {
                element2 = $("[for=" + element.attr("name") + "]")

                if (element2.length > 0) {
                    error.appendTo(element2.parent());
                }
                else {

                    error.appendTo(element.parent());

                }

            }
            else {
                error.css("float", "left")
                error.appendTo(element.parent());
            }

        }
    })

    //-- Simple Repeater --//

    $(".simpleRepeaterAdd").click(function() {
        var maxInstances = $(this).parent().attr("am-maxInstances");
        var minInstances = $(this).parent().attr("am-minInstances");
        var currentInstances = $(this).parent().attr("am-currentInstances");
        // var direction = $(this).parent().attr("am:direction");   
        if (currentInstances + 1 <= maxInstances) {
            $(this).siblings(".content:first").clone(true).insertAfter($(this).siblings(".content:last")).hide().slideDown();
            currentInstances++;

            clearForm($(this).siblings(".content:last"))
            fixClonedElements($(this).siblings(".content:last"), currentInstances - 1)

            $(this).parent().attr("am-currentInstances", currentInstances);



            if (currentInstances >= maxInstances) {
                $(this).addClass("buttonDisabled");
                $(this).removeClass("button")
            }
            if (currentInstances > minInstances) {
                $(this).siblings(".simpleRepeaterRemove").removeClass("buttonDisabled");
                $(this).siblings(".simpleRepeaterRemove").addClass("button");
            }
        }
    });

    $(".simpleRepeaterRemove").click(function() {

        var maxInstances = $(this).parent().attr("am-maxInstances");
        var minInstances = $(this).parent().attr("am-minInstances");
        var currentInstances = $(this).parent().attr("am-currentInstances");
        //var direction = $(this).parent().attr("am:direction"); 

        if (currentInstances - 1 >= minInstances) {
            $(this).siblings(".content:last").slideUp("fast", function() { $(this).remove() });
            currentInstances--;
            $(this).parent().attr("am-currentInstances", currentInstances);
            if (currentInstances <= minInstances) {
                $(this).addClass("buttonDisabled");
                $(this).removeClass("button")
            }
            if (currentInstances < maxInstances) {
                $(this).siblings(".simpleRepeaterAdd").removeClass("buttonDisabled");
                $(this).siblings(".simpleRepeaterAdd").addClass("button");
            }
        }
    });



    $("input[type=text]").change(function() {
        $(this).val($(this).val().toUpperCase());
        $("#form1").validate().element($(this));
        $(this).filter(".currency").each(function() {

            var numericValue = $(this).val()
            if (numericValue > 0) {
                numericValue = numericValue.toString().replace(",", '');


                var tempValue = parseInt((Math.abs(numericValue) + .005) * 100);
                var cents = tempValue % 100;
                var dollars = Math.floor(tempValue / 100).toString();
                if (cents < 10) {
                    cents = "0" + cents;
                }
                for (var i = 0; i < Math.floor((dollars.length - (1 + i)) / 3); i++) {
                    dollars = dollars.substring(0, dollars.length - (4 * i + 3)) + ',' + dollars.substring(dollars.length - (4 * i + 3));
                }
                if (!isNaN(parseInt(dollars))) {
                    $(this).val(dollars + '.' + cents);
                }
            }
        });

    });
    $("input").mouseover(function() {

        var elem = $(this).siblings().andSelf().filter(".error");
        if (elem.length > 0 && elem.css("display") != "none") {
            var errorMsg = elem.attr("error")

            JT_show(errorMsg, this.id, $(this).siblings("label").text())

            $(this).mouseout(function() {
                $('#JT').remove()
            });
        }
    });


    //--Date Picker--//
    //  $('.date-pick').datePicker().filter(".today").val(new Date().asString()).trigger('change')
    $.datepicker.setDefaults({ showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true, dateFormat: 'dd/mm/yy', yearRange: '-99:+99' });
    var d = new Date();
    $('.today').val(LZ(d.getDate()) + "/" + LZ(d.getMonth() + 1) + "/" + d.getFullYear());
    $('.date-pick').each(function() {
        $(this).attachDatepicker({ defaultDate: $(this).val() });
    });


    $("[autofillname]").add("[autofillsources]").change(function() {

        var sourceName = $(this).attr("autofillname");
        var alt = false;
        if (sourceName == null || sourceName == undefined) {
            alt = true;
            sourceName = $(this).attr("name");
        }

        $("[autofillsources=" + sourceName + "]").each(function() {

            var resultField = $(this);

            var fillType = resultField.attr("autofill");


            switch (fillType) {
                case "sum":
                    resultField.val(0);

                    $("[autofillname=" + sourceName + "]").each(function() {
                        if (!isNaN(parseFloat($(this).val()))) {
                            resultField.val(parseFloat(resultField.val().replace(/,/g, "")) + parseFloat($(this).val().replace(/,/g, "")))
                        }
                    });
                    resultField.trigger('change');
                    break;
                case "copy":
                    resultField.val("");
                    if (alt) {
                        $("[name=" + sourceName + "]:first").each(function() {
                            resultField.val($(this).val())

                        });
                    } else {
                        $("[autofillname=" + sourceName + "]:first").each(function() {
                            resultField.val($(this).val())

                        });
                    }
                    resultField.trigger('change');
                    break;
                case "combine":
                    resultField.val("");
                    $("[autofillname=" + sourceName + "]").each(function() {
                        resultField.val(resultField.val() + $(this).val())

                    });

                    resultField.trigger('change');
                    break;
                case "combinewithspace":
                    resultField.val("");
                    resultField.html("")
                    $("[autofillname=" + sourceName + "]").each(function() {
                        if (resultField.val().length == 0) {
                            resultField.val($(this).val());
                        }
                        else {
                            resultField.val(resultField.val() + " " + $(this).val());
                        }

                        if (resultField.html().length == 0) {
                            try {
                                resultField.html($(this).val());
                            } catch (err) { }
                        }
                        else {
                            resultField.html(resultField.html() + " " + $(this).val());
                        }
                    });

                    resultField.trigger('change');
                    break;
            }
        });
    });

    $("[autofillsources]").focus(function() {
        var fillType = $(this).attr("autofill");
        if (fillType == "sum") {
            $(this).blur()
        }
    });

    $("[trigger]").each(function() {

        var trigger = $(this).attr("trigger");


        $(this).bind(trigger, function() {
            manageEvent($(this))//.attr("targetelement") ,$(this).val() ,$(this).attr("testvalue") ,$(this).attr("testoperator") ,$(this).attr("failureaction")  ,$(this).attr("successaction") )
        });

        //run events now (this is to hide elements that need to be hidden etc)
        manageEvent($(this))//.attr("targetelement") ,$(this).val() ,$(this).attr("testvalue") ,$(this).attr("testoperator") ,$(this).attr("failureaction")  ,$(this).attr("successaction") )
    });

    $("label").each(function() {
        var targetField = $("#" + $(this).attr("for"))


        //check if textfield is required AND parent div is not "joined"
        if (!targetField.is(":radio") && targetField.hasClass("required") && targetField.parent().attr("joined") == undefined) {
            if ($(this).hasClass("labelLeft")) {
                $(this).addClass("requiredLabelLeft");
            }
            else {
                $(this).addClass("requiredLabel");
            }
        }
        else if (targetField.is(":radio") && targetField.hasClass("required")) {
            //for radio buttons, we need to an inverse lookup to be sure that there is not a grouplabel associated with this
            targetLabel = $("[for=" + targetField.attr("name") + "]")
            if ((targetLabel.length > 0 && !targetLabel.is("label")) || targetLabel.length == 0) {
                $(this).addClass("requiredLabel");
            }


        }
        else if (targetField.length == 0) {
            //this label has no id element attached, check if there is a radio button with this name instead
            targetField = $("[name=" + $(this).attr("for") + "]")
            if (targetField.is(":radio") && targetField.hasClass("required") && targetField.parent().attr("joined") == undefined) {
                $(this).addClass("requiredLabel");

            }
        }

    });

//    $("[joined]").each(function() {

//        var target = $("#" + $(this).attr("joined"))

//        $(target).siblings(".labelTop").css("display", "block");
//        $(this).children(".labelTop").css("display", "block");

//        var targetContainerWidth = target.parent().outerWidth();
//        var targetWidth = target.outerWidth();
//        var calculatedMargin = (targetWidth - targetContainerWidth);
//        $(this).css("margin-left", calculatedMargin + "px");


//    });
    //


});
            
