/*global
PF: false,
document: false,
window: false,
$: false
 */

/*
 * Teisės akto peržiūros puslapyje:
 */
$(document).ready(function () {
    'use strict';
    var init = false, viewWasConstrainedByPartId = false, iframe = $('iframe');

    if (typeof mLegalActFrame === 'undefined' || iframe.size() === 0) {
        return;
    }

    // when switching between constraint and scroll to mode, try to
    // keep the scrollbar in the same position
    function filterStatusButtonStateChanged(button) {
        var frame = $('iframe'), pos;
        if (viewWasConstrainedByPartId) {
            pos = mLegalActFrame.findFramesScrollPos(frame);
            mLegalActFrame.showHiddenFromView(frame);
            pos += mLegalActFrame.findPartIdPos(frame, viewWasConstrainedByPartId);
            mLegalActFrame.scrollTo(frame, pos);
            viewWasConstrainedByPartId = false;
        }
    }

    /*
     * Jei "Dokumento dalys" mytukas yra būsenoje "Rodyti tik", tai perimame
     * spausdinimo mygtuko paspaudimą (ir įvykio neleidžiame apdoroti PF)
     */
    function onPrintButton(evt) {
        var button = $('.js-print-button');
        if (viewWasConstrainedByPartId) {
            window.open(button.attr('href') + '&constraintToPartIds=' + viewWasConstrainedByPartId, '_blank');
            evt.stopPropagation();
            evt.preventDefault();
        }
    }

    /*
     * mLegalActFrame yra inicializuojamas legalActFrame.js.
     * Pasplepia mygtuką "Padaryti matomą", jei teisės aktas neturi id="part..." fragmentų.
     */
    mLegalActFrame.waitForFrameToLoad(iframe, function (frameContents) {
        mLegalActFrame.targetLinksToParent(frameContents);
        if (frameContents.find('[id^=part_]').size() === 0) {
            $('.js-legalActStructureFilterStateButton-container').hide();
        } else{
        	if (window.location.hash) {
	        	var frame = $('iframe');
	        	var partId = window.location.hash.substring(1);
	        	mLegalActFrame.scrollToPartId(frame, partId, 100);
	        }
        }
    });

    /*
     * Ką daryti paspaudus mygtuką "Padaryti matomą".
     */
    $('.strLink').on('click', function (evt) {
        evt.preventDefault();
        var frame = $('iframe'), partId = $(this).data('partid'), filterStatusButton = PF('legalActStructureFilterStateButton');

        if (!init) {
            init = true;
            filterStatusButton.inputs[0].onchange = function() {filterStatusButtonStateChanged(filterStatusButton);};
            filterStatusButton.inputs[1].onchange = function() {filterStatusButtonStateChanged(filterStatusButton);};
            $('.js-print-button').on('click', onPrintButton);
        }

        if (filterStatusButton.inputs[1].checked) {
            window.location.hash = partId;
            mLegalActFrame.viewOnly(frame, partId);
            viewWasConstrainedByPartId = partId;
        } else {
            window.location.hash = partId;
            mLegalActFrame.scrollToPartId(frame, partId, 100);
        }
    });

    /*
     * ???
     */
    $('.westHeader').parent().css({'border': '1px solid #dddddd', 'background': '#ffffff', 'color': '#333333'});
});

/*
 * name: PF widget var (laukiame, kol šitas widget bus pakrautas/inicializuotas PF)
 * fn: kokią funkciją iškviesti, kai widget [name] užsikraus.
 * Kviečiame be parametro cnt.
 */
function waitForWidget(name, fn, cnt) {
    'use strict';
    cnt = cnt || 1;
    if (cnt < 30) {
        if (PF && PF(name)) {
            fn(PF(name));
        } else {
            window.setTimeout(function () {
                waitForWidget(name, fn, cnt + 1);
            }, Math.min(cnt * 100, 2000));
        }
    }
}

/*
 * Panel header paruošimas vertikaliam parodymui (vertikaliai parodo mainLayout.css (rotate)).
 */
$(document).ready(function () {
    'use strict';

    function lazyLoadTitleIfContainerExists(widget, titleContainer, position) {
        var title, resizer, resizerTitle, type;

        if (!titleContainer.size()) {
            return;
        }

        title = titleContainer.text();
        resizer = $('.ui-layout-resizer-' + position);
        resizerTitle = resizer.find('.custom-layout-resizer-title');

        if (titleContainer.hasClass('js-custom-layout-tb-header')) {
            type = 'tb';
        } else if (titleContainer.hasClass('js-custom-layout-bt-header')) {
            type = 'bt';
        } else {
            type = 'lr';
        }

        if (!type || resizerTitle.size() !== 0) {
            return;
        }

        resizer.addClass('custom-layout-resizer');
//        resizer.on('click', function () {
//            if (resizer.hasClass('ui-layout-resizer-open')) {
//                widget.open('center_' + position);
//            }
//        });
        resizerTitle = $('<div />').
            addClass('custom-layout-resizer-title').
            addClass('custom-layout-resizer-title-' + type).
            text(title);
        resizerTitle.appendTo(resizer);
    }

    (function () {
        var west = $('.westHeader'), east = $('.eastHeader'), north = $('.northHeader');
        waitForWidget('fpLayoutWidget', function (widget) {
            lazyLoadTitleIfContainerExists(widget, west, 'west');
            lazyLoadTitleIfContainerExists(widget, east, 'east');
            lazyLoadTitleIfContainerExists(widget, north, 'north');
        });
    }());
//        var oldClose = widget.close;
//        widget.close = function (pane) {
//            var position, titleContainer;
//
//            oldClose.apply(this, [pane]);
//
//            titleContainer = $('[data-combinedposition=' + pane + '] .ui-widget-header');
//            position = pane.split('_');
//            position = position[position.length - 1];
//
//            lazyLoadTitle(titleContainer, position);
//        };
//    });

});
