﻿/// <reference path="jquery-1.4.1.js" />
/// <reference path="jquery.validate.min.js" />
/// <reference path="jquery.maskedinput-1.2.2.min.js" />
/// <reference path="additional-methods.js" />

var ContactInfo = {
    ContactName: '',
    EmailAddress: '',
    PhoneNumber: '',
    Comment: '',
    CaptchaNew: '',
    CaptchaOld: ''
};

var ContactServiceURL = "wcf/Email.svc/";
var ContactServiceProxy = new serviceProxy(ContactServiceURL);
var AJAXError = $('#AJAXError');

$(document).ready(function() {
    $('#AJAXError').hide();

    $('#website').addClass('contact');

    $('#name').focus();
    
    $("input.PhoneMask").mask("(999) 999-9999");
    $("input.ZipCodeMask").mask("99999");

    // http: //www.javascriptkit.com/script/script2/enforceform.shtml
    setformfieldsize($('#Comment'), 1500, 'charsRemain')    
    
    $('.error').hide();

    $("#map").googleMap({
        zoomLevel: 12,
        center: '97 ROUTE 416, CAMPBELL HALL, NY 10916'
    }).load();

    $('#reset').click(function() {
        $(":input").not(":button, :submit, :reset, :hidden").each(function() {
            this.value = this.defaultValue;
        });
    });

    //http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/
    $("form input").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return true;
        }
    });

    $("#ContactForm").validate({ submitHandler: function(form) { StoreNewContact(); } });

    var ajaxLog = $("#ajaxLog");

//    $("#AJAXError").ajaxError(function(event, request, settings) {
//        $(this).append("Error requesting page " + (settings.url) ? settings.url : '' + "<br/>http Status Code: " +
//            (request.status) ? request.status : '' + "<br/>http Status: " + (request.statusText) ? request.statusText : '');
//    });
    
//    ajaxLog.ajaxStart(function(evt, request, settings) {
//        var dt = new Date();
//        $(this).append("<br/><hr/>Starting request...  " + dt.toLocaleString());
//    });

//    ajaxLog.ajaxComplete(function() {
//        var dt = new Date();
//        $(this).append('<br/>Triggered ajaxComplete handler.' + dt.toLocaleString());
//    });

//    ajaxLog.ajaxSuccess(function() {
//        var dt = new Date();
//        $(this).append('<br/>Triggered ajaxSuccess handler.' + dt.toLocaleString());
//    });

});

// --
function ClearForm() {
    $("#ContactName").attr("value", "");
    $("#Email").attr("value", "");
    $("#Phone").attr("value", "");
    $("#Comment").attr("value", "");
    $("#txtCode").attr("value", "");
    $('#charsRemain').text('');
}
// ---
// STORE NEW CONTRACT REQUEST METHODS
function processCompletedContactStore(response) {
    if (!response) {
        showErrorMsg('Your request was NOT received.  Please contact an administrator or try again.');
        return;
    }

    ClearForm();
    
    $('#ContactRequest').empty().html("<div id='ContactResponse'><p>Your request has been received.  You will receive a response shortly.</p></div>");
    $.unblockUI();

}
// ---
function buildNewContactRequest() {

    var request = { ContactInfo: ContactInfo };

    request.ContactInfo.ContactName = $("#ContactName").val();
    request.ContactInfo.EmailAddress = $("#Email").val();
    request.ContactInfo.PhoneNumber = $("#Phone").val();
    request.ContactInfo.Comment = $("#Comment").val();
    request.ContactInfo.CaptchaNew = $("#txtCode").val();
    request.ContactInfo.CaptchaOld = $(".txtCaptcha").val();
    return request;
}

function StoreNewContact() {

    var ContactRequest = $('#ContactRequest');

    wjBlockUI();
    var request = buildNewContactRequest();
    ContactRequest.empty();

    ContactServiceProxy.invoke({ serviceMethod: "PostNewContact",
        data: { request: request },
        callback: function(response) {
            processCompletedContactStore(response);
        },
        error: function(xhr, errorMsg, thrown) {
            postErrorAndUnBlockUI(xhr, errorMsg, thrown);
        }
    });

    return false;

}
//Error Handling
function postErrorAndUnBlockUI(xhr, errorMsg, thrown) {
    $.unblockUI();
    OnPageError(xhr, errorMsg, thrown);
}

function showErrorMsg(Msg) {

    if (!AJAXError || AJAXError.length === 0) {//If the error element was added after $.Ready we need to regrab it.
        AJAXError = $("#AJAXError");
    }

    AJAXError.show();
    AJAXError.insertStatusMessage({ statusMessage: Msg });
}

function OnPageError(xhr, errorMsg, thrown) {

    if (typeof xhr == "string") {
        showErrorMsg(xhr);
        return;
    }
    else if (typeof (xhr.responseText) == "string" && xhr.responseText != "") {
        var err = JSON.parse(xhr.responseText);

        switch (err.ExceptionType) {

            case 'System.Exception':
                showErrorMsg(err.Message);
                return;
            default:
                showErrorMsg(xhr.responseText);
                return;
        }
    } else {
        showErrorMsg("Unknown error occurred in callback.");
    }

}


$.fn.insertStatusMessage = function(options) {

    // HIDE DEBUG DETAILS
    AJAXError.hide();
    
    if (this.length === 0) { return };

    // Default settings
    var settings = {
        msgElement: "<div class='{1}'>{0}</div>",
        statusMessage: "[Status Message]",
        msgClass: 'Confirm-Message-Area',
        insertAfter: true,
        timeOutTime: 9000,
        fadeOutTime: 9000
    };
    if (options) {
        $.extend(settings, options);
    }
    var strMsg = settings.msgElement.replace("{0}",settings.statusMessage).replace("{1}", settings.msgClass);    
    
    if (settings.insertAfter) {
        $(this).after(strMsg);
    } else {
        $(this).html(strMsg);
    }

    var msgClassSelector = "." + settings.msgClass;

    if ($(msgClassSelector).length > 0) {

        if (settings.timeOutTime > 0) {
            var t = setTimeout(
            function() {
                if (settings.fadeOutTime > 0) {
                    $(msgClassSelector).fadeOut(settings.fadeOutTime);
                } else {
                    $(msgClassSelector).hide();
                }
            }, settings.timeOutTime);
        } else {
            if (settings.fadeOutTime > 0) {
                $(msgClassSelector).fadeOut(settings.fadeOutTime);
            }
        }
    }
};

/*****
Data Templates
http://weblogs.asp.net/dwahlin/archive/2009/04/17/minimize-code-by-using-jquery-and-data-templates.aspx
http://www.west-wind.com/Weblog/posts/509108.aspx
http://ejohn.org/blog/javascript-micro-templating/
*****/

$.fn.parseTemplate = function(data) {
    var str = (this).html();
    var _tmplCache = {}
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //    alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return $.trim(func(data));
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
}

// *** Generic Service Proxy class that can be used to 
// *** call JSON Services generically using jQuery
// *** Depends on JSON2 modified for MS Ajax usage
function serviceProxy(wjOrderServiceURL) {
    var _I = this;
    this.ServiceURL = wjOrderServiceURL;

    // *** Call a wrapped object
    this.invoke = function(options) {

        // Default settings
        var settings = {
            serviceMethod: '',
            data: null,
            callback: null,
            error: null,
            type: "POST",
            processData: false,
            contentType: "application/json",
            timeout: 120000, //Not Preferable, but needed for now.
            dataType: "text",
            bare: false
        };

        if (options) {
            $.extend(settings, options);
        }

        // *** Convert input data into JSON - REQUIRES Json2.js
        var json = JSON.stringify(settings.data);

        // *** The service endpoint URL
        var url = _I.ServiceURL + settings.serviceMethod;

        $.ajax({
            url: url,
            data: json,
            type: settings.type,
            processData: settings.processData,
            contentType: settings.contentType,
            timeout: settings.timeout,
            error: settings.error,
            dataType: settings.dataType,
            success:
                    function(res) {
                        if (!settings.callback) { return; }

                        // *** Use json library so we can fix up MS AJAX dates
                        var result = JSON.parse(res);

                        if (result.ExceptionDetail) {
                            OnPageError(result.Message);
                            return;
                        }

                        // *** Bare message IS result
                        if (settings.bare)
                        { settings.callback(result); return; }

                        //http://encosia.com/2009/07/21/simplify-calling-asp-net-ajax-services-from-jquery/
                        if (result.hasOwnProperty('d'))
                        { return settings.callback(result.d); }
                        else
                        { return result; }


                        // *** Wrapped message contains top level object node
                        // *** strip it off
                        //                        for (var property in result) {
                        //                            settings.callback(result[property]);
                        //                            break;
                        //                        }
                    }
        });
    };
}

function wjBlockUI(msg) {

    var defaultMsg = '<img src="../images/activity.gif" />';

    if (null !== msg) {
        defaultMsg = msg
    }

    $.blockUI({ overlayCSS: { backgroundColor: '#aaa' }, message: defaultMsg });
}
