﻿/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" />

$(document).ready(function ()
{
    var self = this;
    $('#contact').click(function ()
    {
        show();
    });

    $('#send').click(sendEmail);
});


function sendEmail()
{
    $('.required span').hide();

    var name = $('#name').val();
    var email = $('#email').val();
    var message = $('#message').val();

    var hasErrors = false;
    if ($.trim(name).length == 0)
    {
        hasErrors = true;
        $('#nameRequired span').show();
    }

    if ($.trim(email).length == 0)
    {
        hasErrors = true;
        $('#emailRequired span').show();
    }
    else
    {
        if (!isEmailValid($.trim(email)))
        {
            hasErrors = true;
            $('#emailRequired span').show();
            alert('this is not an vaild email address!');
        }
    }
    if ($.trim(message).length == 0)
    {
        hasErrors = true;
        $('#messageRequired span').show();
    }


    if (!hasErrors)
    {
        $('#send, #cancel').hide();
        callWebservice('/MailService.asmx/SendMail', "{Name:'" + name + "', Email:'" + email + "', Message:'" + message + "'}", onSuccess);
    }
    
}

function callWebservice(method, data, onSuccess)
{

    $.ajax({
        type: "POST",
        url: method,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: onSuccess,
        error: function (request, status, error)
        {
            alert($.parseJSON(request.responseText).Message);
            $('#send, #cancel').show();
        }
    });


}

function onSuccess(result)
{
    alert("Your mail was sent.");
    $('#send, #cancel').show();
    hide();
}

function show()
{
    $('#name,#email,#message').val('');
    $('.required span').hide();
    $('#overlay, #dialog').show();
}

function hide()
{
    $('#overlay, #dialog').hide();
}

function isEmailValid(expr)
{
    return expr.match(/^[0-9a-zA-Z]([-_.]{0,1}[\w])*([0-9a-zA-Z]){0,1}@(([0-9a-zA-Z])+[-.]{0,1})*[0-9a-zA-Z]\.([a-zA-Z]{2}||aero||arpa||biz||cat||coop||com||edu||gov||info||int||jobs||mil||mobi||museum||name||net||org||pro||tel||travel)$/);
}
