/* Minification failed. Returning unminified contents.
(138,13-14): run-time warning JS1004: Expected ';': q
 */
//params is an object with the format:
//.id: string of the format CS12345[,CS67890[,...]], which is a list of CMS ids formatted for request from Solr
//.container: the id of the containing element to append to
function dynamicCmsItem(params) {
    $.get('/Records/DynamicCmsItem', { id: params.id }, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var relatedBox = document.createElement('div');
            var relatedTitle = document.createElement('h1');
            var relatedLink = document.createElement('a');
            var relatedBody = document.createElement('p');

            relatedBox.setAttribute('class', 'related-record');

            relatedLink.setAttribute('href', '/Records/Article/' + this.Id);
            relatedLink.innerHTML = this.Title;
            relatedTitle.appendChild(relatedLink);

            relatedBody.innerHTML = this.MetaDescription;
        
            relatedBox.appendChild(relatedTitle);
            relatedBox.appendChild(relatedBody);

            container.append(relatedBox);
        });
    });
}

//params is an object with the format:
//.id: string of the format CS12345[,CS67890[,...]], which is a list of CMS ids formatted for request from Solr
//.container: the id of the containing element to append to
//.linksonly: if true, only returns the title as a link
function dynamicCmsList(params) {
    $.get('/Records/DynamicCmsItem', { id: params.id }, function (data) {
        var container = $(params.container);
        /*var linksonly = false;

        if (params.hasOwnProperty('linksonly') && params.linksonly)*/

        $(data).each(function () {
            var listItem = document.createElement('li');
            var listLink = document.createElement('a');
            var listBody = document.createElement('p');

            listLink.setAttribute('href', '/Records/Article/' + this.Id);
            listLink.innerHTML = this.Title;
            listItem.appendChild(listLink);

            if (params.linksonly != 'true') {
                listBody.innerHTML = this.MetaDescription;
                listItem.appendChild(listBody);
            }

            container.append(listItem);
        });
    });
}

//params is an object with the format:
//.id: a Solr query to search for
//.rows: the number of records to return
//.container: the id of the containing element to append to
function dynamicArticles(params) {
    $.get('/Records/DynamicItems', { id: params.id, rows: params.rows }, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var relatedBox = document.createElement('div');
            var relatedTitle = document.createElement('h1');
            var relatedLink = document.createElement('a');
            var relatedSub = document.createElement('p');
            var relatedBody = document.createElement('p');

            //added to display images for press books
            if (this.PrimaryImage) {
                var imageLink = document.createElement('a');
                var imageBody = document.createElement('img');

                imageLink.setAttribute('href', this.Links);
                imageBody.setAttribute('src', this.PrimaryImage);
                imageLink.appendChild(imageBody);
                relatedBox.appendChild(imageLink);
            }

            relatedBox.setAttribute('class', 'related-record');

            relatedLink.setAttribute('href', '/Records/Article/' + this.Id);
            relatedLink.innerHTML = this.Title || '';
            relatedTitle.appendChild(relatedLink);

            

            relatedSub.innerHTML = this.SubTitle || '';

            relatedBody.innerHTML = this.MetaDescription || '';

            relatedBox.appendChild(relatedTitle);
            relatedBox.appendChild(relatedSub);
            relatedBox.appendChild(relatedBody);

            container.append(relatedBox);
        });
    });
}

//params is an object with the format:
//.id: a Solr query to search for
//.rows: the number of records to return
//.sortAscending: sort ascending instead of descending
//.container: the id of the containing element to append to
function dynamicListItems(params) {
    $.get('/Records/DynamicItems', { id: params.id, rows: params.rows, sortAscending: params.sortAscending == "true" }, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var listItem = document.createElement('li');
            var listLink = document.createElement('a');
            var listBody = document.createElement('p');

            listLink.setAttribute('href', '/Records/Article/' + this.Id);
            listLink.innerHTML = this.Title || '';

            listBody.innerHTML = this.MetaDescription || '';

            listItem.appendChild(listLink);
            listItem.appendChild(listBody);

            container.append(listItem);
        });
    });
}

//params is an object with the format:
//.container: the id of the containing element to append to
function dynamicImages(params) {
    $.get('/Records/DynamicItems', { id: 'CATEGORIES:"Wisconsin Historical Images"', rows: params.rows }, function (data) {
        let quickHold = document.querySelector(params.container);
        quickHold.innerHTML = '';

        var container = $(params.container);

        $(data).each(function () {
            var relatedBox = document.createElement('div');
            var imageLink = document.createElement('a');
            var imageBody = document.createElement('img');
            var relatedTitle = document.createElement('h1');
            var relatedLink = document.createElement('a');
            var relatedBody = document.createElement('p');

            relatedBox.setAttribute('class', 'related-record');

            imageLink.setAttribute('href', '/Records/Image/' + this.Id);
            imageBody.setAttribute('src', this.ImageThumbFileLocation);
            imageLink.appendChild(imageBody);

            relatedLink.setAttribute('href', '/Records/Image/' + this.Id);
            relatedLink.innerHTML = this.Title;
            relatedTitle.appendChild(relatedLink);

            relatedBody.innerHTML = this.MetaDescription;

            relatedBox.appendChild(imageLink);
            relatedBox.appendChild(relatedTitle);
            relatedBox.appendChild(relatedBody);

            container.append(relatedBox);
        });
    });
}

function dynamicBooks(params) {
    $.get('/Records/DynamicItems', { id: params.id, rows: params.rows, sort: 'OTHER_ID'}, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var bookBox = document.createElement('div');
            var imageLink = document.createElement('a');
            var imageBody = document.createElement('img');
            var bookTitle = document.createElement('h2');
            var bookLink = document.createElement('a');
            var bookAuthor = document.createElement('p');

            bookBox.setAttribute('class', 'related-record');

            imageLink.setAttribute('href', '//' + this.Id);
            imageBody.setAttribute('src', '//' + this.PrimaryImage);
            imageLink.appendChild(imageBody);

            bookLink.setAttribute('href', '//' + this.Id);
            bookLink.innerHTML = this.Title;
            bookTitle.appendChild(bookLink);

            bookAuthor.innerHTML = this.Author;

            bookBox.appendChild(imageLink);
            bookBox.appendChild(bookTitle);
            bookBox.appendChild(bookAuthor);

            container.append(bookBox);
        });
    });
}

//params is an object with the format:
//.id: a Solr query to search for
//.rows: the number of records to return
//.sortAscending: sort ascending instead of descending
//.container: the id of the containing element to append to
function dynamicEvents(params) {
    $.get('/Records/DynamicItems', { id: params.id, rows: params.rows, sort: "StartDate", sortAscending: params.sortAscending == "true" }, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var listItem = document.createElement('li');
            var listLink = document.createElement('a');
            var listBody = document.createElement('p');

            listLink.setAttribute('href', '/Records/Event/' + this.Id);
            listLink.innerHTML = this.Title || '';

            //The dates require serious massaging. They come in from C#.NET as a string in the format /Date(n)/, where n is the number of milliseconds of the datetime since 
            //midnight of January 1, 1970. So we strip the non-milliseconds, convert it to a number, and then add 21600000 to put it into Central Standard Time, which is
            //good enough because we don't display the time. Then it's converted into a date, then a date string of a format like Mon Oct 06 2018. The substring removes
            //the day name and year number, and the replace turns two digit dates less than 10 into single digits, giving Oct 6 from the example. Then we can actually display them.
            var startPrint = new Date(Number(this.StartDate.replace('/Date(', '').replace(')/', ''))+21600000).toDateString().substring(4, 10).replace(/0(\d)/, function(match,p1){return p1;});
            var endPrint = new Date(Number(this.EndDate.replace('/Date(', '').replace(')/', ''))+21600000).toDateString().substring(4, 10).replace(/0(\d)/, function(match,p1){return p1;});

            if (startPrint == endPrint) {
                listBody.innerHTML = startPrint;
            }
            else {
                listBody.innerHTML = startPrint + ' - ' + endPrint;
            }

            listItem.appendChild(listLink);
            listItem.appendChild(listBody);

            container.append(listItem);
        });
    });
}
//params is an object with the format:
//.id: a Solr terms query to search for
//.rows: the number of records to return
//.sortAscending: sort ascending instead of descending
//.container: the id of the containing element to append to
function dynamicTermEvents(params) {
    $.get('/Records/DynamicTermItems', { terms: params.id, rows: params.rows, sort: "StartDate", sortAscending: params.sortAscending == "true" }, function (data) {
        var container = $(params.container);

        $(data).each(function () {
            var listItem = document.createElement('li');
            var listLink = document.createElement('a');
            var listBody = document.createElement('p');

            listLink.setAttribute('href', '/Records/Event/' + this.Id);
            listLink.innerHTML = this.Title || '';

            //The dates require serious massaging. They come in from C#.NET as a string in the format /Date(n)/, where n is the number of milliseconds of the datetime since 
            //midnight of January 1, 1970. So we strip the non-milliseconds, convert it to a number, and then add 21600000 to put it into Central Standard Time, which is
            //good enough because we don't display the time. Then it's converted into a date, then a date string of a format like Mon Oct 06 2018. The substring removes
            //the day name and year number, and the replace turns two digit dates less than 10 into single digits, giving Oct 6 from the example. Then we can actually display them.
            var startPrint = new Date(Number(this.StartDate.replace('/Date(', '').replace(')/', ''))+21600000).toDateString().substring(4, 10).replace(/0(\d)/, function(match,p1){return p1;});
            var endPrint = new Date(Number(this.EndDate.replace('/Date(', '').replace(')/', ''))+21600000).toDateString().substring(4, 10).replace(/0(\d)/, function(match,p1){return p1;});

            if (startPrint == endPrint) {
                listBody.innerHTML = startPrint;
            }
            else {
                listBody.innerHTML = startPrint + ' - ' + endPrint;
            }

            listItem.appendChild(listLink);
            listItem.appendChild(listBody);

            container.append(listItem);
        });
    });
}

//for our direct-to-email feedback forms in CMS articles, we have emailForms.
//ONLY ONE FORM PER PAGE RIGHT NOW
//set your submit-replacing button to class "g-recaptcha", with data-sitekey to our public key, and data-callback to emailForms
function emailForms(token) {
    if ($('#form1').valid()) {
        var feedbackForm = $('#form1').serializeArray();
        $.ajax({
            url: '//www.wisconsinhistory.org/Home/Send',
            type: 'POST',
            dataType: 'json',
            data: { token: token, formVars: JSON.stringify(feedbackForm) },
            success: function (data) {
                /* For now: assuming you're sending to a staff address, that staff member will always receive their copy of the mail,
                 so just alert the user that the mail was sent and then redirect to the blank form */
                alert('Your data was successfully submitted!');
                location.href = location.href;

                /* If it looks like something's amiss, use the below code to suss it out */
                // if (data == 'email_success') {
                //     //location.href = '//www.wisconsinhistory.org/';
                //     $('#form1').empty();
                //     $('#form1').append('<fieldset><legend>Success!</legend><p>Thank you for your submission! The information you supplied has been sent to the appropriate staff member.</p></fieldset>');
                // }
                // else {
                //     alert(data);
                // }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('request failed : ' + textStatus + ' - ' + errorThrown);
            }
        });
    }
}

// For the email form on CS16787, the temporary Tax Credit Interest form
function emailTaxCredits(token) {
    $('#form1').validate();
    if ($('#form1').valid()) {
        var feedbackForm = $('#form1').serializeArray();
        $.ajax({
            url: '//www.wisconsinhistory.org/Home/Send',
            type: 'POST',
            dataType: 'json',
            data: { token: token, formVars: JSON.stringify(feedbackForm) },
            success: function (data) {
                $('#form1').empty();
                $('#form1').append('<fieldset><legend>Success!</legend><p>Your request was successfully submitted. Please allow staff X days to respond.</p></fieldset>');

                /* If it looks like something's amiss, use the below code to suss it out */
                // if (data == 'email_success') {
                //     //location.href = '//www.wisconsinhistory.org/';
                //     $('#form1').empty();
                //     $('#form1').append('<fieldset><legend>Success!</legend><p>Thank you for your submission! The information you supplied has been sent to the appropriate staff member.</p></fieldset>');
                // }
                // else {
                //     alert(data);
                // }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('request failed : ' + textStatus + ' - ' + errorThrown);
            }
        });
    }
    else {
        alert('There are missing form fields. Please fill out ALL fields before submitting.')
    }
};