﻿function Fly(sourceId, targetId, callback) {
    sourceElem = $('#' + sourceId + ' img'); //document.getElementById(sourceId);
    targetElem = document.getElementById(targetId);
    sourcePos = getElementPosition(sourceElem.get(0));
    targetPos = getElementPosition(targetElem);

    flyer = sourceElem.clone().get(0);
    flyer.id = 'flyer';
    flyer.style.position = 'absolute';
    flyer.style.left = sourcePos.left + 'px';
    flyer.style.top = sourcePos.top + 'px';
    
    // Please don't ask me why this has to be done twice but without it doesn't work on my IE
    document.getElementById('leftContent').appendChild(flyer);
    document.getElementById('leftContent').appendChild(flyer);

    flying = true;
    $(flyer).animate({ left: targetPos.left, top: targetPos.top, opacity: 0.2 }, 'slow', 'swing', function() {
        flyer.parentNode.removeChild(flyer);
        flying = false;
        callback();
    });
}

function getElementPosition(elem) {
    var offsetTrail = elem;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return { left: offsetLeft, top: offsetTop };
}
