﻿// ensure we don't butt heads with other js
//jQuery.noConflict();

/*****************************************************
    AJAX functions require global vars
******************************************************
    - see Container.ascs/cs
    
    var itemName = '<%= ItemName %>';
    var sectionName = '<%= SectionName %>';
    var sitecoreItemUri = '<%= SitecoreItemUri %>';
    var userName = '<%= UserName %>';

******************************************************
*****************************************************/

// add an item to the journey kit
function AddToJourneyKit(journeyKitItemType) {
    
    if (journeyKitItemType == 'URL') {
        itemName = location.href + "$" + document.title; 
    }

    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkAdd",
        contentType: "application/json; charset=utf-8",
        data: "{'Item':'" + itemName + "', 'Section':'" + sectionName + "', 'JourneyKitItemType':'" + journeyKitItemType + "'}",
        dataType: "json",
        success: function () {
            UpdateSavedFilesDisplay("Add");
            UpdatePageControl(journeyKitItemType);
            UpdateJourneyKit();
            UpdateShareYourKit(1);
      
        },
        error: jkAjaxFailed
    });

    
}
function UpdateSavedFilesDisplay(action) {
    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/GetItemCount",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            jQuery("#savedfiles").text(msg.d);

            if (action == "Add") 
            {
                jQuery("#saveMessage").show("fast");
                jQuery("#saveMessage").delay(5000).fadeOut(3000);
            }
      },

        error: jkAjaxFailed
    });
}
// remove an item from the journey kit
function DeleteFromJourneyKit(delItem, journeyKitItemType, numRecords, tab) {

    var ok = confirm('Are you sure?');

    // must hardwire tab state
    sectionName = tab;
    
    if (ok) {
        jQuery.ajax({
            type: "POST",
            url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkDelete",
            contentType: "application/json; charset=utf-8",
            data: "{'Item' : '" + delItem + "', 'JourneyKitItemType':'" + journeyKitItemType + "'}",
            dataType: "json",
            success: function () {
                UpdateSavedFilesDisplay("Delete");
                UpdatePageControl(journeyKitItemType);
                UpdateJourneyKit();
                UpdateShareYourKit(numRecords);
            },
            error: jkAjaxFailed
        });
    }
}

function AttemptLogin(successURL) {
   
    userName = document.getElementById('loginUserName').value;
    pass = document.getElementById('loginPassword').value;
    
    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkLogin",
        contentType: "application/json; charset=utf-8",
        data: "{'u':'" + userName + "', 'p':'" + pass + "'}",
        dataType: "json",
        success: function (msg) { ValidateLogin(msg, userName, successURL) },
        error: jkAjaxFailed
    });
}

function EmailJourneyKit(uri, url) {
    e = document.getElementById('emailJourneyKitList').value;
    m = document.getElementById('emailJourneyKitMessage').value; 
    c = document.getElementById('emailJourneyKitCopyMe').checked;
    p = document.getElementById('FullJourneyKitProgressDiv');

    // turn on progress
    p.style.display = "block";
    
    // check each normal required field
    emailIsValid = true;
    errors = "";
    // reset
    jQuery("#error_messages").html(errors);
    errors += "<ul>";
    
    if (e == "") {
        errors += "<li>Email Address(s) is a required field.</li>";
        emailIsValid = false;
    }

    errors += "</ul>";

    // update error div we are not valid
    if (!emailIsValid) {
        jQuery("#error_messages").html(errors);
        // turn off progress
        p.style.display = "none";
        return;
    }

    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkEmailKit",
        contentType: "application/json; charset=utf-8",
        data: "{'e':'" + e + "', 'm':'" + m + "', 'c':'" + c + "', 'u':'" + userName + "', 'uri':'" + uri + "', 'url':'" + url + "'}",
        dataType: "json",
        success: function(msg) { ValidateEmailJourneyKit(msg) },
        error: jkAjaxFailed
    });
}

function ValidateEmailJourneyKit(msg, url) {
    try {
        if (msg.d == false) {
            // show error message
            jQuery("#error_messages").html("<ul><li>We're sorry! There was an error sending the emails.</li></ul>");            
        }
        else {
            onclick = "_gaq.push(['_trackEvent', 'Modals', 'Email My Password Confirmation Window', 'Email My Password Confirmation Window']);"
            document.getElementById('EmailJourneyKit_Confirmation').style.display = "block";
            document.getElementById('EmailJourneyKit_Form').style.display = "none";
        }
    }
    catch (Error) {
        //alert('ValidateEmailJourneyKit ' + Error);
    }

    // turn off progress
    p.style.display = "none";
}

function ForgotPassword(uri, url) {
    e = document.getElementById('forgotPasswordUserName').value;

    // check each normal required field
    emailIsValid = true;
    errors = "";
    // reset
    jQuery("#error_messages").html(errors);
    errors += "<ul>";
    
    if (e == "") {
        errors += "<li>This is a required field.</li>";
        emailIsValid = false;
    }
    else {
        var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        var matchArray = e.match(emailReg);
        if (matchArray == null) {
            errors += "<li>Your email address must be in the format email@email.com.</li>";
            emailIsValid = false;
        }
    }

    errors += "</ul>";

    // update error div we are not valid
    if (!emailIsValid) {
        jQuery("#error_messages").html(errors);
        return;
    }
    
    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkForgotPassword",
        contentType: "application/json; charset=utf-8",
        data: "{'e':'" + e + "', 'uri':'" + uri + "', 'url':'" + url + "'}",
        dataType: "json",
        success: function(msg) { ValidateForgotPassword(msg, url) },
        error: jkAjaxFailed
    });
}

function ValidateForgotPassword(msg, url) {
    try {        
        if (msg.d == false) {
            // show error message
            jQuery("#error_messages").html("<ul><li>We're sorry! We do not have an account with that email address. Try a different email address, or <a href='" + url + "/Sign-Up.aspx'>sign up.</a></li></ul>");
        }
        else {
            document.getElementById('ForgotPassword_Confirmation').style.display = "block";
            document.getElementById('ForgotPassword_Form').style.display = "none";
        }
    }
    catch (Error) {
        //alert(Error);
    }
}

function jkAjaxFailed(result) {
    //alert("ERROR: " + result.status + ' ' + result.statusText);
}

function ValidateLogin(msg, userName, successURL) {
   
    try
    {
        if (msg.d == false) {
            // show error message
            jQuery("#error_messages2").html("<ul><li>Email Address and Password do not match. Try again.</li></ul>");            
        }
        else {        
            // force the postback with email and remember me as "__EVENTARGUMENT"
            var eventArgs = "__haCustomEVENTARGUMENT:";
            if (document.getElementById('rememberMe').checked == true)
                eventArgs = eventArgs + userName + ":true:";
            else
                eventArgs = eventArgs + userName + ":false:";

            eventArgs = eventArgs + successURL;
            // fire postback

            __doPostBack('__Page', eventArgs);
        
        }
    }
    catch (Error) {
        //alert(Error);
    }
}

function UpdatePageControl(journeyKitItemType) {
    // repopulate journey kit control
    jQuery.get("/layouts/HearingAid/JourneyKit/Ajax/PageControlWrapper.aspx?Item=" + itemName + "&SectionName=" + sectionName + "&UserName=" + userName + "&JourneyKitItemType=" + journeyKitItemType, function(response) {
        // could have up to 4 per page. built in try catch in jquery
        jQuery("#PageControlDiv\\.entry\\[1\\]").html(CleanResponse(response));
        jQuery("#PageControlDiv\\.entry\\[2\\]").html(CleanResponse(response));
        jQuery("#PageControlDiv\\.entry\\[3\\]").html(CleanResponse(response));
        jQuery("#PageControlDiv\\.entry\\[4\\]").html(CleanResponse(response));
    });
}
function UpdateJourneyKit() {
    // repopulate journey kit control
    jQuery.get("/layouts/HearingAid/JourneyKit/Ajax/ItemListWrapper.aspx?SectionName=" + sectionName + "&SitecoreItemUri=" + sitecoreItemUri, function(response) {
        jQuery("#ItemListDiv").html(CleanResponse(response));
    });
}

function SwitchTab(tab, itemURI) {
    // repopulate journey kit control
    jQuery.get("/layouts/HearingAid/JourneyKit/Ajax/ItemListWrapper.aspx?SectionName=" + tab + "&SitecoreItemUri=" + itemURI, function(response) {
        jQuery("#ItemListDiv").html(CleanResponse(response));
    });
}

function UpdateShareYourKit(numRecords) {
//    // repopulate journey kit control
//    jQuery.get("/layouts/HearingAid/JourneyKit/Ajax/ShareYourKitWrapper.aspx?UserName=" + userName, function(response) {
//        jQuery("#ShareJourneyKitDiv").html(CleanResponse(response));
    //    });


    if (numRecords > 0) {
        document.getElementById('JourneyKitEmpty').style.display = "none";
        document.getElementById('JourneyKitFull').style.display = "block";
    }
    else {
        document.getElementById('JourneyKitEmpty').style.display = "block";
        document.getElementById('JourneyKitFull').style.display = "none";
    }
}

function CleanResponse(response) {
    // purpose: return all HTML between developer defined start/end tags. removes __VIEWSTATE, FORM and other unwanted HTML
    try {
        startAJAX = response.search("<!-- start AJAX -->");
        endAJAX = response.search("<!-- end AJAX -->");

        // we found a custom ajax response!
        if (startAJAX != -1 && endAJAX != -1) {
            // lets get everything between the markers
            response = response.substring(startAJAX, endAJAX + 17);
        }
    }
    catch (Error) { }

    return response;
}

function CheckEmail(email) {
    jQuery.ajax({
        type: "POST",
        url: "/layouts/hearingaid/JourneyKit/Ajax/AjaxEngine.aspx/jkCheckEmail",
        contentType: "application/json; charset=utf-8",
        data: "{'email':'" + email + "'}",
        dataType: "json",
        beforeSend: function() { jQuery("#EmailInfoSpan").html("<img src=\"~/media/HearingAid/Images/validation_progress.ashx\" width=\"21\" height=\"21\" alt=\"\" class=\"validation\" />"); },
        success: function(msg) { ceSuccess(msg); },
        error: ceAjaxFailed
    });
}

function ceSuccess(msg) {
    if (msg.d == true) {
        jQuery("#EmailInfoSpan").html("<img src=\"~/media/HearingAid/Images/validation_error.ashx\" width=\"21\" height=\"21\" alt=\"\" class=\"validation\" />");
    }
    else {
        jQuery("#EmailInfoSpan").html("<img src=\"~/media/HearingAid/Images/validation_success.ashx\" width=\"21\" height=\"21\" alt=\"\" class=\"validation\" />");
    }
}

function ceAjaxFailed(result) {
    //alert("ERROR: " + result.status + ' ' + result.statusText);
}
