﻿$(function () {
    /** GENERAL **/
    $('input[type=text]:not(.epi-formLayout input)').each(function () { resetInputField($(this), $(this).attr('value')) });
    $('textarea:not(.epi-formLayout textarea)').each(function () { resetInputField($(this), $(this).attr('value')) });
    $('.masonry').masonry({
        itemSelector: '.containerMedium'
    });

    $('#ctl00_FullRegion_categoryList').selectmenu({ style: 'dropdown' });
    $('select.dropdown').selectmenu({ style: 'dropdown' });

    $('a.lightboxLink').fancybox({
        autoDimensions: false,
        type: 'inline',
        width: '620',
        height: '500',
        overlayColor: '#000',
        speedIn: 100,
        speedOut: 100
    });



    /*** DIN SAK ***/

    $('#mainWrap .expandable h2 a').click(function (e) {
        var grandParent = $(this).parent().parent();
        grandParent.toggleClass('expanded');
        grandParent.toggleClass('collapsed');
        grandParent.children('.data').toggle('medium');
        e.preventDefault();
    });

    $('#mainWrap .expandable .data ul ul').hide();
    $('#mainWrap .expandable .data ul > li').click(function () {
        $(this).children('ul').toggle(200);
        $(this).toggleClass('opened');
    });

    var infoTextCount = $('.infoTextRow').length;
    var textArea = $('#infoText');
    var infoTable = $('#infoTable');
    var dateField = $('#datepicker');
    $.datepicker.setDefaults($.datepicker.regional["no"]);
    dateField.datepicker({ dateFormat: 'dd.mm.yy' });

    $('#addInfoButton').live('click', function (e) {
        var dateString = $('#datepicker').val();
        content = cleanText(textArea.val());

        infoTable.append(
                      $('<tr class="infoTextRow">' +
                        '<td class="date">' + dateString + '</td>' +
                        '<td class="text">' + content + '</td>' +
                        '<td class="edit"><a href="#" class="editLink">Rediger</a> <a href="#" class="deleteLink">Slett</a>' +
                        '<input type="hidden" value=\'{ "Date": "' + dateString + '", "Content": "' + content + '"}\' name="infoText">' +
                        '<input type="hidden" value="' + infoTextCount + '" class="infoTextId">' +
                        '</td>' +
                        '</tr>')
                        );
        infoTextCount++;

        e.preventDefault();
        var caseName = $('#sakensNavn').val();
        aspnetForm.reset();
        $('#sakensNavn').val(caseName);
    });

    var currentInfoToEdit;
    var buttonArea = $('#buttonArea');
    $('.editLink').live('click', function (e) {
        var date = $(this).parent().parent().children('.date')[0].innerText;
        textArea.val($(this).parent().parent().children('.text')[0].innerText);
        dateField.val(date);

        currentInfoToEdit = $(this).siblings('.infoTextId').val();
        buttonArea.empty();
        buttonArea.append($('<input type="image" src="/Images/oppdaterButton.png" class="leggTilButton" id="updateInfoButton">'));
        e.preventDefault();
    });

    $('#updateInfoButton').live('click', function (e) {
        var content = cleanText(textArea.val());
        var rowToEdit = $('.infoTextId[value=' + currentInfoToEdit + ']').parent().parent();
        rowToEdit.children('.text').html(content);
        rowToEdit.children('.date').html(dateField.val());

        buttonArea.empty();
        buttonArea.append($('<input type="image" src="/Images/leggTilButton.png" class="leggTilButton" id="addInfoButton">'));
        e.preventDefault();

        var caseName = $('#sakensNavn').val();
        aspnetForm.reset();
        $('#sakensNavn').val(caseName);
    });

    $('.deleteLink').live('click', function (e) {
        if (confirm($('#deleteConfirmationText').val())) {
            var thisRow = $(this).parent().parent();
            ShowHideTableRow(thisRow, 400, false, function () {
                thisRow.remove();
            });

        }
        e.preventDefault();
    });

    $('#printButton').click(function() {
        window.print();
    }); 

    $('.bottomPanel .printButton').click(function (e) {
        e.preventDefault();

        var infoTextRows = $('.infoTextRow');
        var popup = window.open('', 'Utskrift', 'height=700, width=600, resizable=0');

        popup.document.write('<html><head><title>Din sak: Utskrift</title></head><body onload="self.print()">');
        popup.document.write('<input type="button" value="Print!" onclick="print()">');
        popup.document.write('<div style="font-family: georgia, serif">');
        popup.document.write('<h1>Din sak</h1>');
        popup.document.write('<table style="border-collapse: collapse; border: 1px solid black"><tr><th>Dato</th><th>Opplysning</th></tr>');
        for (var i = 0; i < infoTextRows.length; i++) {
            popup.document.write('<tr>');
            popup.document.write('<td style="border: 1px solid black; padding: 8px; margin: 0;">' + $(infoTextRows[i]).children('.date').text() + '</td>');
            popup.document.write('<td style="border: 1px solid black; padding: 8px; margin: 0;">' + $(infoTextRows[i]).children('.text').text() + '</td>');
            popup.document.write('</tr>');
        }
        popup.document.write('</table>');
        popup.document.write('</div>');
        popup.document.write('</body></html>');
        popup.document.close();
    });

    function cleanText(text) {
        text = text.replace('<', '&lt;');
        text = text.replace('>', '&gt;');
        text = text.replace('"', '&quot;');
        return text;
    }

    /* FINN ADVOKAT */
    $('.normalPrintButton').click(function (e) {
        e.preventDefault();
        window.print();
    });

    $('.advancedSearchButton').click(function () {
        $(this).toggleClass('advancedSearchButtonExpanded');
        $(this).toggleClass('advancedSearchButtonCollapsed');
        $('.advancedSearch').toggle(100);

        var hiddenAdvanced = $('#ctl00_FullRegion_uxSearchFields_hiddenAdvanced');
        if (hiddenAdvanced.val() == '0')
            hiddenAdvanced.val('1');
        else
            hiddenAdvanced.val('0');
    });

    if (typeof initializeGoogleMaps == 'function') {
        initializeGoogleMaps();

        // Sette inn mapmarkers
    }

    /* Treff i Finn advokat-boks */

    $('.container .treeView ul').hide();

    $('.container .treeView a:not(.treeView ul ul li a)').click(function (e) {
        $(this).parent().children('ul').toggle(200);
        $(this).toggleClass('expanded');

        e.preventDefault();
    });

    /* SPØR EN ADVOKAT */

    var questionTextArea = $('.questionForm #ctl00_FullRegion_txtQuestion');
    var categoryArea = $('.questionForm #ctl00_FullRegion_categoryList');
    var categoryLinkArea = $('.questionForm #ctl00_FullRegion_categoryList-button');
    var yourNameField = $('.questionForm #ctl00_FullRegion_txtName');
    var yourEmailField = $('.questionForm #ctl00_FullRegion_txtEmail');

    yourNameField.defaultValue = yourNameField.val();
    yourEmailField.defaultValue = yourEmailField.val();
    questionTextArea.defaultValue = questionTextArea.val();
    categoryArea.defaultValue = categoryArea.val();

    // Page 1
    $('#ctl00_FullRegion_completeStep1Button').click(function (e) {
        validateRequiredField(questionTextArea, questionTextArea.defaultValue, e);
        validateCategoryField(categoryArea, categoryArea.defaultValue, categoryLinkArea, e);
    });

    // Page 2
    $('#ctl00_FullRegion_completeStep2Button').click(function (e) {
        validateRequiredField(yourNameField, yourNameField.defaultValue, e);
        validateRequiredField(yourEmailField, yourEmailField.defaultValue, e);
        validateEmailField(yourEmailField, e);
    });

    /* RISIKOTEST */

    $('.riskTestAnswers input[type=radio]').change(function () {
        $('.riskTestHelpTexts p').hide();
        $('.nextButton').removeAttr('disabled');

        var answerId = $(this).attr('value');

        var yellowFlag = $('#yellowFlag' + answerId);
        var redFlag = $('#redFlag' + answerId);
        var infoText = $('#infoText' + answerId);
        if (yellowFlag != undefined)
            yellowFlag.show();
        if (redFlag != undefined)
            redFlag.show();
        if (infoText != undefined)
            infoText.show();
    });

    /* Utility */

    function validateEmailField(inputField, e) {
        var emailRegex = /^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/;
        if (emailRegex.test(inputField.val()) == false) {
            e.preventDefault();
            highlightInputField(inputField);
        }
    }

    function validateCategoryField(inputField, initialValue, anchorField, event) {
        if (inputField.val() == "" || inputField.val() == initialValue) {
            event.preventDefault();
            highlightInputField(anchorField);
        }
    }

    function validateRequiredField(inputField, initialValue, event) {
        if (inputField.val() == "" || inputField.val() == initialValue) {
            event.preventDefault();
            highlightInputField(inputField);
        }
    }

    function highlightInputField(inputField) {
        inputField.addClass('invalid').delay(1000).queue(function () {
            $(this).removeClass('invalid');
            $(this).dequeue();
        });
    }

    function resetInputField(inputField, initialValue) {
        if (inputField.attr('rel') == null || inputField.attr('rel') != 'noreset') {
            inputField.blur(function () {
                if (inputField.attr('value') == '') {
                    inputField.attr('value', initialValue);
                }
            });

            inputField.focus(function () {
                if (inputField.attr('value') == initialValue) {
                    inputField.attr('value', '');
                }
            });
        }
    }

    function ShowHideTableRow(rowSelector, speed, show, callback) {
        var childCellsSelector = $(rowSelector).children("td");
        var lastChild = childCellsSelector.length - 1;
        var lastCallback = null;

        childCellsSelector.each(function (i) {
            // Only execute the callback on the last element.
            if (lastChild == i)
                lastCallback = callback

            if (show) {
                $(this).fadeIn(speed, lastCallback)
            }
            else {
                $(this).fadeOut(speed, lastCallback)
            }
        });
    }
});

