﻿var MPRootURL = "";
var MPPagingItemsPerPage = 0; 
var MPPagingTotalPages = 0; 
var MPPagingIndex = 1;
var MPPagingActive = false;
var arrForms = new Array();
var MPMonthsAbbreviated = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var MPMonthsFull = new Array("January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

function MPSetCookie(name, value, expires, path, domain, secure) 
{
    //path = (path) ? path : "";
    //domain = (domain) ? domain : "/";
    try
    {    
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );

        /*
        if the expires variable is set, make the correct 
        expires time, the current script below will set 
        it for x number of days, to make it for hours, 
        delete * 24, for minutes, delete * 60 * 24
        */
        if ( expires )
        {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
                            ( ( expires ) ? ";expires=" + expires_date.toUTCString() : "" ) + 
                            ( ( path ) ? ";path=" + path : "" ) + 
                            ( ( domain ) ? ";domain=" + domain : "" ) +
                            ( ( secure ) ? ";secure" : "" );

    }
    catch (err)
    {
        //alert("Error setting cookie: " + err.description);
    }
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function MPGetCookie( check_name ) {
    
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
	
	
}	

function MPDeleteCookie( name, path, domain ) {
    if (MPGetCookie(name))
        document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function MPGotoPreviousPage()
{
    if (MPPagingActive && MPPagingIndex > 1)
        MPGotoPage(MPPagingIndex - 1);
}

function MPGotoNextPage()
{
    if (MPPagingActive && MPPagingIndex < MPPagingTotalPages)
        MPGotoPage(MPPagingIndex + 1);
}

function MPGotoPage(pageNumber)
{
    if (MPPagingActive && pageNumber >= 1 && pageNumber <= MPPagingTotalPages)
    {
        var pattern = new RegExp("/pg/\\d+$");
        var url = window.location.href;
        url = url.replace(pattern, "");
        window.location.href = url + "/pg/" + pageNumber;
    }
}



function MPGlobalSearch(strSearchPhrase, searchType)
{
    if (!searchType)
        window.location = MPRootURL + "search/global?s=" + strSearchPhrase;
    else
        window.location = MPRootURL + "search/" + searchType + "?s=" + strSearchPhrase;
}


 function MPSendContactListEntryForm(id,rootURL,remoteHost)
{
    var strError = "";
    if (document.getElementById("FormFieldInputName").value == "")
        strError += "   Name\n";
    if (!IsValidEmail(document.getElementById("FormFieldInputEmailAddress").value))
        strError += "   Valid Email Address\n";
    if (document.getElementById("FormFieldInputComments").value == "")
        strError += "   Comments\n";
    
    if (strError == "")
    {
        Render.SendForm(
                id,
                rootURL,
                remoteHost,
                document.getElementById("FormFieldInputName").value,
                document.getElementById("FormFieldInputEmailAddress").value,
                document.getElementById("FormFieldInputPhone").value,
                document.getElementById("FormFieldInputComments").value, MPSendContactListEntryForm_callback);
    }
    else
        alert("Please provide the following information:\n\n" + strError);
}

function MPSendContactListEntryForm_callback(objResponse)
{
    $("#ContactForm").html("<div id=\"ContactFormThankYou\">Thank you. Your form was submitted successfully.</div>");
}

var mpFormSubmitPressed = false;
var mpFormKeyPressTimeoutID = null;
var mpFormValidationID = "";

function MPFormKeyUp(strFormID) 
{
    try
    {
        if (mpFormSubmitPressed)
        {
            mpFormValidationID = strFormID
            window.clearTimeout(mpFormKeyPressTimeoutID);
            mpFormKeyPressTimeoutID = window.setTimeout(MPFormValidation, 500);
        }
    }
    catch (ex) { }
}


function MPFormValidation(strFormID) 
{
    mpFormSubmitPressed = true;

    if (!strFormID)
        strFormID = mpFormValidationID;
    
    var strErrorHTML = "";

    $.each(arrForms, function(i, objForm) {
        if (objForm.settings !== undefined)
        {
            if (objForm.settings[0].guid === strFormID) 
            {
                $.each(objForm.settings[0], function(j, objSetting) {
                    try 
                    {
                        var blnIsValid = true;
                        var objFormField = objForm.fields[j];
                        var inputFormField = $("#" + objFormField.id);

                        switch (objFormField.type) 
                        {
                            case "RadioMultiple":
                            case "CheckBoxMultiple":
                                var intChecked = $("[id='" + objFormField.id + "']:checked").length;
                            
                                if (objFormField.required === true) 
                                {
                                    var intCheckedMin = 1;
                                    var intCheckedMax = -1;

                                    if (intChecked < intCheckedMin && intCheckedMin != -1) 
                                    {
                                        strErrorHTML = strErrorHTML.concat("You must check at least " + intCheckedMin + " box" + ((intCheckedMin > 1) ? "es" : "") + " from " + objFormField.name + ".<br />");
                                        blnIsValid = false;
                                    }
                                    else if (intCheckedMax < intChecked && intCheckedMax != -1) 
                                    {
                                        strErrorHTML = strErrorHTML.concat("You can only check at most " + intCheckedMax + " box" + ((intCheckedMax > 1) ? "es" : "") + " from " + objFormField.name + ".<br />");
                                        blnIsValid = false;
                                    }
                                }
                                break;
                            case "Select":
                            case "SelectMultiple":
                            case "CheckBox":
                            case "Text":
                            case "TextArea":
                            case "Password":
                            case "File":
                                if (objFormField.required) 
                                {
                                    switch (objFormField.type) 
                                    {
                                        case "Select":
                                        case "Text":
                                        case "TextArea":
                                        case "Password":
                                        case "File":
                                            if (inputFormField.val().length === 0) 
                                            {
                                                switch (objFormField.type) 
                                                {
                                                    case "Select":
                                                        strErrorHTML = strErrorHTML.concat("You must select an option for " + objFormField.name + ".<br />");
                                                        break;
                                                    case "Text":
                                                    case "TextArea":
                                                        strErrorHTML = strErrorHTML.concat("You must enter data for " + objFormField.name + ".<br />");
                                                        break;
                                                    case "Password":
                                                        strErrorHTML = strErrorHTML.concat("You must enter a password for " + objFormField.name + ".<br />");
                                                        break;
                                                    case "File":
                                                        strErrorHTML = strErrorHTML.concat("You must select a file for " + objFormField.name + ".<br />");
                                                        break;
                                                }

                                                blnIsValid = false;
                                            }
                                            break;
                                        case "SelectMultiple":
                                            var intSelected = $("option:selected", inputFormField).length;
                                            var intSelectedMin = 1;
                                            var intSelectedMax = -1;

                                            if (intSelected < intSelectedMin && intSelectedMin != -1) 
                                            {
                                                strErrorHTML = strErrorHTML.concat("You must select at least " + intSelectedMin + " item" + ((intSelectedMin > 1) ? "s" : "") + " from " + objFormField.name + ".<br />");
                                                blnIsValid = false;
                                            }
                                            else if (intSelectedMax < intSelected && intSelectedMax != -1) 
                                            {
                                                strErrorHTML = strErrorHTML.concat("You can only select at most " + intSelectedMax + " item" + ((intSelectedMax > 1) ? "s" : "") + " from " + objFormField.name + ".<br />");
                                                blnIsValid = false;
                                            }
                                            break;
                                        case "CheckBox":
                                            if (inputFormField.prop("checked")) 
                                            {
                                                strErrorHTML = strErrorHTML.concat("You must check the " + objFormField.name + " box before submitting this form.<br />");
                                                blnIsValid = false;
                                            }
                                            break;
                                    }
                                }
                                if (objFormField.validate !== "None" && objFormField.validationRegEx !== "" && blnIsValid === true && inputFormField.val().length > 0) 
                                {
                                    var regex = new RegExp(objFormField.validationRegEx, 'ig');
                                    if (regex.test(inputFormField.val())) 
                                    {
                                        switch (objFormField.validate) 
                                        {
                                            case "Phone1":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not a valid US phone number.<br />");
                                                break;
                                            case "Phone2":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not a valid international phone number.<br />");
                                                break;
                                            case "PostalCode":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not a valid posal code.<br />");
                                                break;
                                            case "EmailAddress":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not a valid e-mail address.<br />");
                                                break;
                                            case "Website":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not a valid url address.<br />");
                                                break;
                                            case "Custom":
                                                strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is not in the correct format.<br />");
                                                break;
                                        }

                                        blnIsValid = false;
                                    }
                                }
                                if (objFormField.length > 0) 
                                {
                                    if (objFormField.length < inputFormField.val().length) 
                                    {
                                        strErrorHTML = strErrorHTML.concat("The " + objFormField.name + " is too long. Must be " + objFormField.length + " characters or less.<br />");
                                        blnIsValid = false;
                                    }
                                }
                                break;
                        }

                        if (blnIsValid === false)
                        {
                            //alert(objFormField.id);
                            //alert(strClass);
                            //$('.mp-form-field-input:has([id="' + objFormField.id + '"])').addClass(strClass);
                            //$('.mp-form-field-group-item-input:has([id="' + objFormField.id + '"])').addClass(strClass);
                            inputFormField.addClass("mp-form-field-validation-error");
                        }
                        else
                            inputFormField.removeClass("mp-form-field-validation-error");
                    }
                    catch (ex) { alert(ex); }
                });
            }
        }
    });

    if (strErrorHTML !== "") 
    {
        strErrorHTML = "<div class=\"mp-form-error-message-title\">Please correct the following before continuing:</div><div class=\"mp-form-error-message-body\">" + strErrorHTML + "</div>";
        $("#" + strFormID + " .mp-form-error-message").html(strErrorHTML).css("display", "block");

        $("body").animate({scrollTop: $("#" + strFormID + " .mp-form-error-message").offset().top + "px"}, 1);
        if ($("#imgCaptcha_"+strFormID).length > 0)
        {
            if (CheckCaptcha($("#inputCaptcha_"+strFormID).val()) !== "")
            {
                $("#imgCaptcha_"+strFormID).attr("src", $("#inputCaptchaURL_"+strFormID).val().replace("%%DATE-TICKS%%", new Date().getTime()));
                $("#inputCaptcha_"+strFormID).val("");
            }
        }
        mpFormSubmitPressed = false;
        return false;
    }
    else
    {
        if ($("#imgCaptcha_"+strFormID).length > 0)
            strErrorHTML = CheckCaptcha($("#inputCaptcha_"+strFormID).val());

        if (strErrorHTML !== "") 
        {
            strErrorHTML = "<div class=\"mp-form-error-message-title\">Errors</div><div class=\"mp-form-error-message-body\">" + strErrorHTML + "</div>";
            $("#" + strFormID + " .mp-form-error-message").html(strErrorHTML).css("display", "block");
            $("body").animate({scrollTop: $("#" + strFormID + " .mp-form-error-message").offset().top + "px"}, 1);
            if ($("#imgCaptcha_"+strFormID).length > 0)
            {
                $("#imgCaptcha_"+strFormID).attr("src", $("#inputCaptchaURL_"+strFormID).val().replace("%%DATE-TICKS%%", new Date().getTime()));
                $("#inputCaptcha_"+strFormID).val("");
            }
            mpFormSubmitPressed = false;
            return false;
        }
        $("#" + strFormID + " .mp-form-error-message").html("").css("display", "none");
        return true;
    }
}

function CheckCaptcha(strCaptcha)
{
    var strErrorHTML = "";

    try
    {
        $.ajax({
            type: "POST",
            url: "/ajax/BasePage.aspx/MatchCaptcha",
            contentType: "application/json; charset=utf-8",
            data: "{\"strCaptcha\":\""+strCaptcha+"\"}",
            dataType: "json",
            async: false,
            success: function(result){ strErrorHTML = result.d; },
            error: AjaxFailed
        });
    }
    catch (ex)
    {
        return ex.Message;
    }

    return strErrorHTML;
}

function IsValidEmail(strValue)
{
    var objRegExp = /^([\!#\$%&'\*\+/\=?\^`\{\|\}~a-zA-Z0-9_-]+[\.]?)+[\!#\$%&'\*\+/\=?\^`\{\|\}~a-zA-Z0-9_-]+@{1}((([0-9A-Za-z_-]+)([\.]{1}[0-9A-Za-z_-]+)*\.{1}([A-Za-z]){1,6})|(([0-9]{1,3}[\.]{1}){3}([0-9]{1,3}){1}))$/i;
    return objRegExp.test(strValue);
}

function MPQueryString(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function _mpPing()
{
    try 
    {
        if (MPVisitorGUID == "") 
            MPVisitorGUID = MPGetCookie("MPVisitorGUID"); 
        if (MPVisitorSessionGUID == "") 
            MPVisitorSessionGUID = MPGetCookie("MPVisitorSessionGUID"); 
        $.ajax({
            type: "POST",
            url: "/ajax/BasePage.aspx/PingTrack",
            contentType: "application/json; charset=utf-8",
            data: "{\"strVisitorSessionGUID\":\""+MPVisitorSessionGUID+"\", \"strVisitorGUID\":\""+MPVisitorGUID+"\"}",
            dataType: "json",
            success: _mpPing_callback,
            error: AjaxFailed
        });
    } 
    catch (ex) { }
}

function AjaxFailed(result){ try{  }catch(ex){  }}

function _mpPing_callback(rsp) { window.setTimeout(_mpPing, 10000); }
