/****
	Details popup
	by Peter Fingler
****/

// Constants
var kTargetPadding = 5;
var kCardBoxWidth = 240;
var kEnableCache = true;
var cardTimer = 0;

// Cache results here
var cardCache = {}

function cardShow(subject, target, action /* optional */, params /*optional*/) 
{
    if ( !$('cardbox') || 
         target != $('cardbox').target || 
         $('cardbox').style.display != 'block' )
    {
        var cardBox = buildCard(target);
        if ( cardBox.loader )
        {
            // Cancel loading the other card
            cardBox.loader.cancel();
            cardBox.loader = null;
        }

        cardBox.innerHTML = '';

        // Element must be visible to get position
        showElement(cardBox);
        positionCard(cardBox);

        if (action == 'wallpaper') {
            if(!params) params = {page: "1", max: "9"};
            cardurl = '/mozes_widget/wallpaper_select?keyword_id='+subject+'&page='+params.page+'&max='+params.max;
        } else if (action == 'ringtone') {
            if(!params) params = {page: "1", max: "2"};
            cardurl = '/mozes_widget/ringtone_select?keyword_id='+subject+'&page='+params.page+'&max='+params.max;
        }
        else if (action == 'photos') cardurl = '/mozes_card_images.php?photos';
        else if (action == 'share') cardurl = '/mozes_card_share.php';
        else if (action == 'feedback') cardurl = '/mozes_feedback.php';
        else cardurl = '/mozes_widget/card/?keyword=' + subject;

        connect(document, 'onmousemove', cardMove);
        cardTimer = setTimeout(function () { loadCard(cardurl, cardBox); }, 1000);
//        loadCard(cardurl, cardBox);
    }
}

function positionCard(cardBox)
{
    var cardRect   = elementRect(cardBox);
    var targetRect = elementRect(cardBox.target);
    var viewport   = getViewportRect();

    // Reset position to match targets
    cardRect.x = targetRect.x;
    cardRect.y = targetRect.y;
    
    // Place the card to the right of the target
    cardRect.setLeft(cardRect.x + targetRect.w + kTargetPadding);
    // Move the card to be centered vertically
    cardRect.setTop(cardRect.y - (cardRect.h / 2) + (targetRect.h / 2));

    // Check that the card is within bounds of window
    // Priority is lowest to highest
    if ( cardRect.right() > viewport.right() ) 
        cardRect.setRight(targetRect.left() - kTargetPadding);

    if ( cardRect.left() < viewport.left() ) 
        cardRect.setLeft(targetRect.right() + kTargetPadding);

    if ( cardRect.bottom() > viewport.bottom() ) 
        cardRect.setBottom(viewport.bottom() - kTargetPadding);

    if ( cardRect.top() < viewport.top() ) 
        cardRect.setTop(viewport.top() + kTargetPadding);

    setElementPosition(cardBox, cardRect);
}

function hideCard()
{
    var cardBox = $('cardbox');
    if ( cardBox )
    {
        // Remove mouse events
        disconnectAll(document, 'onmousemove');
        hideElement(cardBox);
    }
    

    if (navigator.appVersion.match('MSIE 6') == 'MSIE 6') {
      selects = document.getElementsByTagName("select"); 
      for (i=0; i<selects.length; i++) {
        selects[i].style.visibility="visible";
      }
    }

}

function cardMove(e) 
{
    var cardBox = $('cardbox');
	if ( cardBox && e.mouse && cardBox.style.display == 'block' )
    {
		// Check to see if the mouse is outside of the card or target
        var cardRect = elementRect(cardBox).union(elementRect(cardBox.target));
        //log(cardRect);
        //log(e.mouse().page);
        if ( !cardRect.isPointInside(e.mouse().page.x, e.mouse().page.y) )
        {
            hideCard();
            if(cardTimer) {
                clearTimeout(cardTimer);
                cardTimer = 0;
            }
	    }
	}
}

function buildCard(target) 
{
	if ( !$('cardbox') ) 
    {
        // Uses Mochikit DOM to create the element
		var cardBox = DIV({ 'id' : 'cardbox'});
		cardBox.style.position = 'absolute';
		cardBox.style.width = kCardBoxWidth + 'px';
		cardBox.style.zIndex = '99';
        cardBox.loader = null;
        cardBox.onmouseout = null;
        appendChildNodes(document.body, cardBox);
    }

    $('cardbox').target = target;
    return $('cardbox');
}

function loadCard(url, target) 
{
    if ( kEnableCache && cardCache[url] )
    {
        // Load from Cache
        loadCardDone(cardCache[url], url, target);
    }
    else
    {
        var d = doSimpleXMLHttpRequest(url);
        target.loader = d;

        // This will only call loadCardDone on a valid response so we don't have to check
        // for valid responses in loadCardDone
        d.addCallback(function(req) { cardCache[url] = req; loadCardDone(req, url, target); });
    }
}

// Called on a successful card load
function loadCardDone(req, url, cardBox) 
{
    // log and logDebug messages will only show up in consoles like Firebug for Firefox.
    // This makes it great for debugging without pestering the user
    if (navigator.appVersion.match('MSIE 6') == 'MSIE 6') {
      selects = document.getElementsByTagName("select"); 
      for (i=0; i<selects.length; i++) {
        selects[i].style.visibility="hidden";
      }
    }

    logDebug('loadCardDone ', req.status, ': ', url);
    cardBox.innerHTML = req.responseText;
    positionCard(cardBox);    
}
