// Personal Webpage Engine
// Copyright(c) 2008 Mihail Kochanov
// You can contact me at StilgarAD@yahoo.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
//
// Personal Web Page Engine
//
//------------------------------------------------------------------------------

using System;
using System.Web.UI;

/// <summary>
/// Summary description for InvisibleCaptcha
/// </summary>
public static class InvisibleCaptcha
{
    public static void InititializeCaptcha(System.Web.UI.Page page, StateBag viewState)
    {
        if (viewState["captchavalue"] == null)
        {
            viewState["captchavalue"] = Guid.NewGuid().ToString();
        }


        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendLine("function SetCaptcha(){");
        sb.AppendLine("var form = document.getElementById('" + page.Form.ClientID + "');");
        sb.AppendLine("var el = document.createElement('input');");
        sb.AppendLine("el.type = 'hidden';");
        sb.AppendLine("el.name = 'captcha';");
        sb.AppendLine("el.value = '" + viewState["captchavalue"] + "';");
        sb.AppendLine("form.appendChild(el);}");

        page.ClientScript.RegisterClientScriptBlock(page.GetType(), "captchascript", sb.ToString(), true);
        page.ClientScript.RegisterOnSubmitStatement(page.GetType(), "captchayo", "SetCaptcha()");

    }

    /// <summary> 
    /// Gets whether or not the user is human 
    /// </summary> 
    public static bool IsCaptchaValid(System.Web.UI.Page page, StateBag viewState, bool raiseError)
    {
        bool result = false;

        if (viewState["captchavalue"] != null
            && page.Request.Form["captcha"] != null
            && page.Request.Form["captcha"].Length >= 36)
        {
            //substring first 36 characters to avoid duplicating Guid. Guid's string length is 36
            result = page.Request.Form["captcha"].Substring(0,36) == viewState["captchavalue"].ToString();
        }

        if (!result && raiseError)
        {
            page.Session[Constants.Session.ErrorMessage] = Constants.Error.ValidationFailed;
            page.Server.Transfer("~/Error.aspx");
        }

        return result;
    }


}
