// com.tts.initial.html5.quiz.ddsource.autoform
define( ["jquery"], function( jq ) {

    "use strict";

    function OffsetService( context ){

        /*
         * Gets global offset for elements with absolute positioning.
         * The offset includes stage offset and ignores css zoom factor.
         */
        function getGlobalOffset( element ){

            var offset = getCssOffset( element ),
                groupOffset = getGroupOffset( element );

            if( groupOffset.left !== 0 || groupOffset.top !== 0 ){
                return addGroupOffset( element, offset, groupOffset );
        }

            return offset;
        }

        function getCssOffset( element ){

            var offset = {
                "left" : parseInt( jq(element).css( "left" ).replace("px",""), 10) || 0,
                "top": parseInt( jq(element).css( "top" ).replace("px",""), 10) || 0
            };

            return offset;
        }

        function addGroupOffset( element, offset, groupOffset ){
            return {
                left : offset.left + groupOffset.left,
                top : offset.top + groupOffset.top
            };
        }

        /*
         * This method based on the convention that no absolute element is placed in the chain of tts group elements
         * and all css positions set as px units
         */
        function getGroupOffset( element ) {

            var groupOffset = {
                    left: 0,
                    top: 0
                },
                jqElement = jq(element),
                parents = jqElement.parents(),
                parent,
                position;

            parents.each( function( index, element ){
                parent = jq(element);
                if( parent.hasClass("Group") || parent.hasClass("ttclassgroup") ){
                    position = getCssOffset( parent ); //parent.position();
                    groupOffset.left += position.left;
                    groupOffset.top += position.top;
                }
            });

            return groupOffset;
        }

        return {
            getGlobalOffset: getGlobalOffset
        };
    }

    return OffsetService;
});
