﻿/// <reference path="jquery-1.6.2.min.js" />
/// <reference path="jquery.validate.min.js" />

$(document).ready(function () {


    $(function () {
        $("div.form-item .date").datepicker();
    });

    $('div.form-item input[type=text]').keyup(function (e) {
        ItemValidate(this);
    });
    $('div.form-item input[type=text]').change(function (e) {
        ItemValidate(this);
        var $this = $(this);
        var value = $.trim($this.val());
        if ($this.attr('default') && value != $this.attr('default')) {
            $this.addClass('form-value');
        } else if (value == "" || value == $this.attr('default')) {
            $this.removeClass('form-value');
        }
        $this.addClass('form-value');
    });
    $('div.form-item > select').change(function (e) {
        ItemValidate(this);
    });
    /*
    $('input[type=text]').focus(function (e) {
        var $this = $(this);
        var value = $.trim($this.val());
        if ($this.attr('default') && value == $this.attr('default')) {
            $this.val("");
        }
        $this.addClass('form-value');
    });
    $('input[type=text]').blur(function (e) {
        var $this = $(this);
        var value = $.trim($this.val());
        if (value == "") {
            $this.val($this.attr('default'));
            $this.removeClass('form-value');
        }
    });
    */
    $('textarea').focus(function (e) {
        var $this = $(this);
        var value = $.trim($this.val());
        if ($this.attr('default') && value == $this.attr('default')) {
            $this.val("");
        }
        $this.addClass('form-value');
    });
    $('textarea').blur(function (e) {
        var $this = $(this);
        //var value = $.trim($this.text());
        var value = $.trim($this.val());
        if (value == "") {
            //$this.text($this.attr('default'));
            $this.val($this.attr('default'));
            $this.removeClass('form-value');
        }
    });

    $('.front-form-submif').bind('click', function (e) {
        return btnFormSubmit_click(this, e);
    });

});


function ValidateForm(sender) {
    var hasError = false;
    var res = "";
//    $(sender).validate();

    sender.find(':input').not(':input[type=button], :input[type=radio]').each(function () {
        var $this = $(this);
        var value = ($this.attr('type') == "checkbox") ? ($this.attr('checked') == true).toString() : $.trim($this.val());
        if (res)
            res += "|||";
        res += $this.attr('name') + ":::";

        hasError = ItemValidate(this) || hasError;
        
//        if ($this.hasClass('required')) {
//            if ((value == '' || value == $this.attr('default'))) {
//                hasError = true;
//                $this.addClass('required-error');
//            } else if ($this.attr('type') == "text" && $this.hasClass('email') && !isValidEmail(value)) {
//                hasError = true;
//                $this.addClass('required-error');
//            } else if ($this.attr('type') == "text" && $this.hasClass('phone') && !isValidPhone(value)) {
//                hasError = true;
//                $this.addClass('required-error');
//            } else if ($this.attr('type') == "text" && $this.hasClass('date') && !isValidDate(value)) {
//                hasError = true;
//                $this.addClass('required-error');
//            } else if ($this.attr('type') == "text" && $this.hasClass('card') && !isValidCreditCard(value)) {
//                hasError = true;
//                $this.addClass('required-error');

//            }
//            else {
//                $this.removeClass('required-error');
//                if (value != '' && value != $this.attr('default'))
//                    res += value;
//            }
//        }
//        else {
//            $this.removeClass('required-error');
//            if (value != '' && value != $this.attr('default'))
//                res += value;
//        }

    });
    
    if (hasError)
        res = "-1";
    return res;
}

function ItemValidate(sender) {
    var hasError = true;
    var $this = $(sender);
    if ($this.hasClass('required')) {
        var value = ($this.attr('type') == "checkbox") ? ($this.attr('checked') == true).toString() : $.trim($this.val());
        if ((value == '' || value == $this.attr('default'))) {
            $this.addClass('required-error');
        } else if ($this.attr('type') == "text" && $this.hasClass('email') && !isValidEmail(value)) {
            $this.addClass('required-error');
        } else if ($this.attr('type') == "text" && $this.hasClass('phone') && !isValidPhone(value)) {
            $this.addClass('required-error');
        } else if ($this.attr('type') == "text" && $this.hasClass('date') && !isValidDate(value)) {
            $this.addClass('required-error');
        } else if ($this.attr('type') == "text" && $this.hasClass('card') && !isValidCreditCard(value)) {
            $this.addClass('required-error');
        }
        else {
            $this.removeClass('required-error');
            hasError = false;
        }
    } else {
        $this.removeClass('required-error');
        hasError = false;
    }
    if (hasError) {
        if ($this.parent().find(".val:first").length == 0) {

            $this.parent().append("<div class=\"val-wrap\"><div class=\"val\">" + $this.attr("default") + "</div></div>"); // required
            //var vw = $this.parent().find(".val-wrap");
            var v1 = $this.parent().find(".val");
            if ($this.is("select")) {
                v1.css("right", "-" + ($this.width() - 28).toString() + "px");
            } else {
                v1.css("right", "-" + ($this.width()-3).toString() + "px");//.parent()
            }
            v1.css("top", "-" + ($this.height() + 7).toString() + "px");
            v1.click(function () {
                $(this).parent().prev().focus();
            });
        }
    } else {
        $this.parent().find(".val-wrap:first").remove();
    }
    return hasError;
}
function isValidEmail(value) {
    //var pattern = new RegExp('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i');
    ///^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);

    //return pattern.test(email);
}
function isValidPhone(value) {
    //var pattern = new RegExp('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x');
    //var res = /^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$/.test(value);
    //return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
    //var res = /^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(value);
    var res = /^(?:\+?[0-9]{1}[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(value);
    return res;
}
function isValidDate(value) {
    //var pattern = new RegExp('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x');
    return !/Invalid|NaN/.test(new Date(value));
}
function isValidCreditCard(value) {
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (var n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
}

function btnFormSubmit_click(sender, e) {
    var $this = $(sender);
    //var formID = $this.closest('form').find('#elementID').val('formid');
    //$('#summary-' + formID).html("")
    var form = $this.closest('form');
    var formID = form.find('input[name=elementID]').val();
    form.find('.form-summary').html('');
    var res = ValidateForm(form);
    if (res == "-1") {
        return false;
    }

    $(':not(#recaptcha-' + formID + ').captcha:not(.empty)').each(function () {
        $(this).addClass('empty');
    });

    if ($('#recaptcha-' + formID).hasClass('empty')) {
        Recaptcha.create("6LdR2MMSAAAAAIc95SPVJuJFceKbC263XMMGtC-y",
                    "recaptcha-" + formID,
                    {
                        theme: "white",
                        lang: "en",
                        callback: Recaptcha.focus_response_field
                    }
                );
        $('#recaptcha-' + formID).removeClass('empty')
        return false;
    }

    var postUrl = form.attr('action') == '#' ? '/MyAdmin/FormData/_PostForm' : form.attr('action');

    $.post(postUrl, form.serialize(), function (data) {
        if (data == "1") {
//            $('#frmFormContent-' + formID).hide('fade', {}, 300, function () {
//                $('#frmFormMessage-' + formID).show('fade', {}, 300);
//            });
            form.hide('fade', {}, 300, function () {
                form.next(':first').show('fade', {}, 300);
            });
        } else {
            //$('#summary-' + formID).html(data);
            form.find('.form-summary').html(data);
            Recaptcha.reload();
        }
    });

    return false;

}


		

