﻿Websajt.Form.Validation = null;



Websajt.Form.GlobalActions = function() {

    /*
    ---------------------------------------------
    Prevents auto submit with "enter".
    ---------------------------------------------
    */
    $(document).keypress(function(e) {
        try {
            if (e.which == 13 && !$(e.target).is("textarea")) {
                e.returnValue = false;
                e.cancel = true;
                e.preventDefault();
                e.stopPropagation();
            }
        }
        catch (exp) { }
    });

    $(".validator-message-top").each(function() {
        var strMessage = $(this).html();
        $(this).hide();
        var strID = $('div', this).attr("id");
        $('div', this).change(function() { alert("CHANGE") })
        var ErrorBubble = new Websajt.Utils.BubbleDotNet('Något var inte korrekt ifyllt', strMessage, strID, -100, 80, 1000, "");
        ErrorBubble.Init();
    });

    /*
    ---------------------------------------------
    Watermark on all input forms that have rel
    "watermark"
    ---------------------------------------------
    */
    $('input.watermark').focus(function() {
        if ($(this).val() == this.defaultValue)
            $(this).val('');
        else if ($(this).val() == '')
            $(this).val(this.defaultValue);
    });

    $('input.watermark').blur(function() {
        if ($(this).val() == this.defaultValue)
            $(this).val('');
        else if ($(this).val() == '')
            $(this).val(this.defaultValue);
    });

    // XFORMS Manipulering
    $("#ContainerContentRightContent table tr td input:text").addClass("textbox");
    $("#ContainerContentRightContent table tr td input:submit").addClass("submit-xform-button");
    $("#ContainerContentRightContent table tr td input:checkbox + label").addClass("checkbox");
    $("#ContainerContentRightContent table tr td input:radio + label").addClass("radio");
    var objTD = $("#ContainerContentRightContent table tr td span.xformvalidator").parent();
    $("input:text", objTD).addClass("xform-error");
    $("#ContainerContentRightContent table tr td span.xformvalidator").html("");

    $('input.submit-button').each(function() {
        $(this).hide();
        var strText = $(this).attr("value");
        var strID = $(this).attr("id");

        $(this).after('<a href="javascript:Websajt.Form.DoSubmit(\'' + strID + '\')" id="lnk' + strID + '" class="submit-button"><span>' + strText + '</span></a>');

        $('#lnk' + strID).hover(function() {
            $(this).addClass("submit-button-hover");
            $(this + " span").addClass("submit-button-hover");
        },
		function() {
		    $(this).removeClass("submit-button-hover");
		    $(this + " span").removeClass("submit-button-hover");
		})
    });

    $('input.search-button').each(function() {
        $(this).hide();
        var strText = $(this).attr("value");
        var strID = $(this).attr("id");

        $(this).before('<a href="javascript:Websajt.Form.DoSubmit(\'' + strID + '\')" id="lnk' + strID + '" class="float-left search-button"><span>' + strText + '</span></a>');

        $('#lnk' + strID).hover(function() {
            $(this).addClass("search-button-hover");
            $(this + " span").addClass("search-button-hover");
        },
		function() {
		    $(this).removeClass("search-button-hover");
		    $(this + " span").removeClass("search-button-hover");
		})
    });

    $('#ContainerContentRightContent input.submit-xform-button').each(function() {
        $(this).hide();
        var strText = $(this).attr("value");
        var strID = $(this).attr("name").replace(/\$/g, "_");
        var strName = $(this).attr("name");
        if ($(this).hasClass('login-button')) {
            $(this).click(function() { $('#LoginInProgress').removeClass('hide'); $('lnk' + strID ).attr('onclick', 'return false;'); });
        }
        $(this).after('<a href="javascript:Websajt.Form.DoXformSubmit(\'' + strName + '\')" id="lnk' + strID + '" class="submit-button"><span>' + strText + '</span></a>');

        $('#lnk' + strID).hover(function() {
            $(this).addClass("submit-button-hover");
            $(this + " span").addClass("submit-button-hover");
        },
		function() {
		    $(this).removeClass("submit-button-hover");
		    $(this + " span").removeClass("submit-button-hover");
		})
    });


    /*
    ---------------------------------------------
    Adds a class name on all types of input boxes
    when the user have that field focused.
    ---------------------------------------------
    */
    $('input[type=text],input[type=password],textarea').focus(function() {
        $(this).addClass("focus");
    });

    $('input[type=text],input[type=password],textarea').blur(function() {
        $(this).removeClass("focus");
    });

}

//type=contactMe?name=&phone=&message=
Websajt.Form.ContactMe = function () {
    var ErrorContainer = $("#ContactErrorContainer")
    var validContactForm = true;
    $("#ContactForm input.required").each(function () {
        //Remove spaces and - from phonenumber
        var phoneNumber = $(this).val();
        phoneNumber = phoneNumber.replace(/-/g, '');
        phoneNumber = phoneNumber.replace(/ /g, '')

        //ContactName
        if ($(this).val() == "") {
            ErrorContainer.show();
            $(this).addClass("error");
            $("#" + $(this).attr('id') + "Error").show();
            validContactForm = false;
        }
        //Validating Phonenumber
        else if ($(this).attr("id") == "ContactPhone" && isNaN(parseInt(phoneNumber * 1))) {
            ErrorContainer.show();
            $(this).addClass("error");
            $("#" + $(this).attr('id') + "Error").show();
            validContactForm = false;
        }
        else {
            $(this).removeClass("error");
            $("#" + $(this).attr('id') + "Error").hide();
        }
    });
    setTimeout(function () {
        if (validContactForm) {
            $("#ContactForm").hide();
            $("#ContactErrorContainer").hide();
            $.ajax({
                type: "POST",
                url: contactAjaxUrl,
                data: "type=contactMe&name=" + $('#ContactName').val() + "&phone=" + $('#ContactPhone').val() + "&message=" + $('#ContactMessage').val(),
                success: function (data) { }
            });
        }
    }, 300);
};

Websajt.Form.DoSubmit = function(strID) {
	var ErrorContainer = $("#" + strID + "ErrorContainer")
	Websajt.Form.Validation = $("form").validate({
		errorContainer: ErrorContainer,
		errorLabelContainer: $("ul", ErrorContainer),
		wrapper: 'li',
		meta: "validate"
	});
	if ($("form").valid()) {
		$("#" + strID).click();
	}
}

Websajt.Form.DoXformSubmit = function (strName) {
    $("input[name='" + strName + "']").click();
}

Websajt.Form.ValidateValue = function(strValue, strMatchPattern) {
	/************************************************
	DESCRIPTION: Validates that a string a matches
	a valid regular expression value.
    
	PARAMETERS:
	strValue - String to be tested for validity
	strMatchPattern - String containing a valid
	regular expression match pattern.
      
	RETURNS:
	True if valid, otherwise false.
	*************************************************/
	var objRegExp = new RegExp(strMatchPattern);

	//check if string matches pattern
	return objRegExp.test(strValue);
}

Websajt.Form.ValidateEmail = function (email) {
    var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    if (!emailReg.test(email) || email == "") {
        return false;
    }

    return true;
}

