﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

jQuery.fn.bestvalidate = function (settings) {
    allRules = {
        "required": {
            "regex": "none",
            "alertText": "* Bu alan zorunludur",
            "alertTextCheckboxMultiple": "* Bir secim yapiniz",
            "alertTextCheckboxe": "* Bu alan zorunludur"
        },


        "length": {
            "regex": "none",
            "alertText": "* Girilen metin en az ",
            "alertText2": " ve ",
            "alertText3": " karakter arasinda olmalidir"
        },
        "AdSoyad": {
            "regex": "/^[a-zA-Z]|\s|[a-zA-Z]+/",
            "alertText": "* Lütfen ad soyadın tamamını yazınız"
        },

        "minCheckbox": {
            "regex": "none",
            "alertText": "* Isaretleme siniri asildi"
        },
        "confirm": {
            "regex": "none",
            "alertText": "* Alanlar esit degil"
        },
        "telephone": {
            "regex": "/^[0-9\-\(\)\ ]{0,11}$/",
            "alertText": "* Gecersiz telefon numarasi"
        },
        "kimlikno": {
            "regex": "/^[0-9\ ]{0,11}$/",
            "alertText": "* T.C. No 11 haneli rakam olmalı"
        },
        "email": {
            "regex": "/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]$/",
            "alertText": "* Gecersiz mail adresi"
        },
        "date": {
            "regex": "/^(([0-9])|([0-2][0-9])|(3[0-1]))\.(([1-9])|(0[1-9])|(1[0-2]))\.(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$/",
            "alertText": "* Gecersiz tarih"
        },
        "onlyNumber": {
            "regex": "/^[0-9\ ]{0,11}$/",
            "alertText": "* Sadece rakam giriniz"
        },
        "noSpecialCaracters": {
            "regex": "/^[0-9a-zA-Z]+$/",
            "alertText": "* Ozel karakter giremezsiniz"
        },
        "creditCard": {
            "regex": "/^4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}$/",
            "alertText": "Kart numarasını yanlış girdiniz."
        },
        "creditCardExpiration": {
            "regex": "/^((0[1-9])|(1[0-2]))[\/\.\-]*((0[8-9])|(1[1-9]))$/",
            "alertText": "Son kullanma tarihini yanlış girdiniz."
        },
        "ccv": {
            "regex": "/^([0-9]{3,4})$/",
            "alertText": "Güvenlik kodunu yanlış girdiniz."
        },
        "onlyLetter": {
            "regex": "/^[a-zA-Z\ \']+$/",
            "alertText": "* Sadece harf girebilirsiniz"
        }
    };

    settings = jQuery.extend({
        allrules: allRules
    }, settings);

    var isError = false;

  
    $("form").submit(function () {
        $("[class^=validate]").each(function () {
            loadValidation(this)
        });

        if ($("[class^=formErrorContent]").size() > 0) {



            window.top.$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $(".formError:first").offset().top - 15 }, 600)


            return false;


        }

    });

    $(".validate").click(function () {
        $("[class^=Mvalidate]").each(function () {
            loadValidation(this)
        });

        if ($("[class^=formErrorContent]").size() > 0) {



            window.top.$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $(".formError:first").offset().top - 15 }, 600)


            return false;


        }

    });
    this.each(function () {
        var $this = $(this);
        if ($this.attr("type") == "checkbox")
            $this.click(function (obj) { loadValidation(this) })
        else
            $this.blur(function (obj) { loadValidation(this) })
    });

    //$(this).not("[type=checkbox]").blur(function(obj) { loadValidation(this) })
    //$(this + "[type=checkbox]").click(function(obj) { loadValidation(this) })

    function ShowMessage(obj, promptText) {
        var objId = $(obj).attr("id");
        $("body").append('<div id="frmErr_' + objId + '" class="formError ' + objId + '"><div class="formErrorArrow"><div class="line5"></div><div class="line4"></div><div class="line3"></div><div class="line2"></div><div class="line1"></div></div><div class="formErrorContent">' + promptText + '</div></div>');
        var $div = $("#frmErr_" + objId);
        $div.css({
            top: $(obj).offset().top - $div.height() - 5,
            left: $(obj).offset().left + $(obj).width() - 15,
            opacity: 0
        })
        $div.fadeTo("fast", 0.25);
        isError = false;
    };

    function UpdateMessage(obj, promptText) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
        var objId = $(obj).attr("id");
        var $div = $("#frmErr_" + objId);
        $div.find(".formErrorContent").html(promptText);
        $div.animate({
            top: $(obj).offset().top - $div.height() - 5
        });
        isError = false;

    }

    function loadValidation(obj) {
        rulesParsing = $(obj).attr('class');
        rulesRegExp = /\[(.*)\]/;
        getRules = rulesRegExp.exec(rulesParsing);
        str = getRules[1]
        pattern = /\W+/;
        result = str.split(pattern);
        validateCall(obj, result)
    };

    function validateCall(obj, rules) {
        var promptText = ""
        var objId = $(obj).attr("id");
        var $div = $("#frmErr_" + objId);
        objType = $(obj).attr("type");

        for (i = 0; i < rules.length; i++) {

            switch (rules[i]) {
                case "optional":
                    if (!$(obj).val()) {
                        closePrompt(obj);
                    }
                    break;
                case "required":
                    _required(obj, rules);
                    break;
                case "custom":
                    _customRegex(obj, rules, i);
                    break;
                case "length":
                    _length(obj, rules, i);
                    break;
                case "minCheckbox":
                    _minCheckbox(obj, rules, i);
                    break;
                case "confirm":
                    _confirm(obj, rules, i);
                    break;
                default: ;
            };
        };

        if (isError) {

            if ($("input[id=" + objId + "]").size() > 1 && objType == "radio") {
                obj = $("input[id=" + objId + "]:first")
            }
            ($div.size() == 0) ? ShowMessage(obj, promptText) : UpdateMessage(obj, promptText)
        } else {
            closePrompt(obj)
        }


        function _required(obj, rules) {
            objType = $(obj).attr("type")

            if (objType == "text" || objType == "password" || objType == "textarea") {

                if (!$(obj).val()) {
                    isError = true
                    promptText += settings.allrules[rules[i]].alertText + "<br />"
                }
            }
            if (objType == "radio" || objType == "checkbox") {
                objName = $(obj).attr("id")

                if ($("input[id=" + objName + "]:checked").size() == 0) {
                    isError = true
                    if ($("input[id=" + objName + "]").size() == 1) {
                        promptText += settings.allrules[rules[i]].alertTextCheckboxe + "<br />"
                    } else {
                        promptText += settings.allrules[rules[i]].alertTextCheckboxMultiple + "<br />"
                    }
                }
            }
            if (objType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you
                objName = $(obj).attr("id");

                if (!$("select[id=" + objName + "]").val()) {
                    isError = true;
                    promptText += settings.allrules[rules[i]].alertText + "<br />";
                }
            }
            if (objType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you
                objName = $(obj).attr("id");

                if (!$("#" + objName).val()) {
                    isError = true;
                    promptText += settings.allrules[rules[i]].alertText + "<br />";
                }
            }
        }
        function _customRegex(obj, rules, position) {
            customRule = rules[position + 1]
            pattern = eval(settings.allrules[customRule].regex)

            if (!pattern.test($(obj).attr('value'))) {
                isError = true
                promptText += settings.allrules[customRule].alertText + "<br />"
            }
        }
        function _confirm(obj, rules, position) {
            confirmField = rules[position + 1]

            if ($(obj).attr('value') != $("#" + confirmField).attr('value')) {
                isError = true
                promptText += settings.allrules["confirm"].alertText + "<br />"
            }
        }
        function _length(obj, rules, position) {

            startLength = eval(rules[position + 1])
            endLength = eval(rules[position + 2])
            feildLength = $(obj).attr('value').length

            if (feildLength < startLength || feildLength > endLength) {
                isError = true
                promptText += settings.allrules["length"].alertText + startLength + settings.allrules["length"].alertText2 + endLength + settings.allrules["length"].alertText3 + "<br />"
            }
        }
        function _minCheckbox(obj, rules, position) {    // VALIDATE CHECKBOX NUMBER

            nbCheck = eval(rules[position + 1])
            groupname = $(obj).attr("id")
            groupSize = $("input[name=" + groupname + "]:checked").size()

            if (groupSize > nbCheck) {
                isError = true
                promptText += settings.allrules["minCheckbox"].alertText + "<br />"
            }
        }
        return isError;
    };

    function closePrompt(obj) {
        var $div = $("#frmErr_" + $(obj).attr("id"));
        if ($div.size() > 0) {
            $div.fadeTo("fast", 0, function () {
                $div.remove()
            });
        }
    };

    function debug(msg) {
        if (window.console && window.console.log)
            window.console.log(msg);
    };

};

