// Import Prototypes.
var URLLoader = ECTYPE.net.URLLoader;
var URLRequest = ECTYPE.net.URLRequest;
var URLVariables = ECTYPE.net.URLVariables;
var HTMLElement = ECTYPE.display.HTMLElement;
var HTMLDivElement = ECTYPE.display.HTMLDivElement;
var HTMLImageElement = ECTYPE.display.HTMLImageElement;
var HTMLAnchorElement = ECTYPE.display.HTMLAnchorElement;
var HTMLBRElement = ECTYPE.display.HTMLBRElement;
var ToolTip = EXANIMO.containers.ToolTip;




var playInterval;
var lastTarget;
var popup;
var tail;
var slots = [0,1,2,3,4,5,6,7,8,9,10,11,2,5,7,11,5,7,7];
var watchLinks = [];
var currentComedian;
var isTallied = {};





/**
 *
 * Works like getElementsByTagName.. but with class names.
 *
 */
function getElementsByClassName(node, classname)
{
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName('*');
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}




/**
 *
 * Adds the rollover state to the vote button.
 *
 */    
function setupPopup()
{
    // Setup popup close button.
    popup = document.getElementById('popup');
    var closeButton = new HTMLElement(popup.getElementsByTagName('a')[0]);
    closeButton.addEventListener(
        'click',
        function(e)
        {
            clearInterval(playInterval);
            document.getElementById('video').innerHTML = '';
            document.getElementById('popup-content').style.display = 'block';
            document.getElementById('popup-form').style.display = 'none';
            popup.style.display = 'none';
//            document.getElementById('countdown').style.visibility = 'visible';
            document.getElementById('votesSince').style.visibility = 'visible';
            e.preventDefault();
        }
    );

    // Create the popup tail.
    tail = document.createElement('div');
    popup.appendChild(tail);

    // Cache the popup backgrounds so they load immediately.
    var a = [];
    a[0] = new HTMLImageElement();
    a[0].src = './images/bracket/backgrounds/popup.png';
    a[1] = new HTMLImageElement();
    a[1].src = './images/bracket/backgrounds/tailLeft.png';
    a[2] = new HTMLImageElement();
    a[2].src = './images/bracket/backgrounds/tailDown.png';
    a[3] = new HTMLImageElement();
    a[3].src = './images/bracket/backgrounds/tailRight.png';
}




/**
 *
 *
 *
 */   
function setupToolTips()
{
    var path = './images/bracket/rollOvers/';
    var ttTargets = getElementsByClassName(document, 'comedian');
    for (var i = 0; i < ttTargets.length; i++)
    {
        var target = ttTargets[i];
        var div = target.getElementsByTagName('div')[0];   
        var hasWatchLink = getElementsByClassName(target, 'watchLink').length ? true : false;

        if (hasWatchLink && (typeof target.hasToolTip != 'boolean'))
        {
            target.hasToolTip = true;
            var comedianID = slots[i] == null ? i : slots[i];
            target = target.getElementsByTagName('a')[0];
            var src = path + comedianID + '.png';
            var img = new HTMLImageElement();
            img.target = target;
            img.addEventListener(
                'complete',
                function(e)
                {
                    var tt = new ToolTip(e.currentTarget, e.currentTarget.target);
                    tt.xOffset = -98;
                    tt.yOffset = -155;
                    tt.style.zIndex = 999;
                }
            );
            img.src = src;
        }
    }
    
    var winner = new HTMLElement(document.getElementById('winner'));
    if (typeof winner.hasToolTip != 'boolean')
    {
        winner.hasToolTip = true;
        var comedianID = 7;
        var src = path + comedianID + '.png';
        var img = new HTMLImageElement();
        img.target = winner;
        img.addEventListener(
            'complete',
            function(e)
            {
                var tt = new ToolTip(e.currentTarget, e.currentTarget.target);
                tt.xOffset = -98;
                tt.yOffset = -155;
                tt.style.zIndex = 999;
            }
        );
        img.src = src;
        
        winner.addEventListener(
            'click',
            function(e)
            {
                positionPopup(watchLinks[17]);
                watch(17);
            }
        );
        
        winner.style.cursor = 'pointer';
    }

}




//
//
// Event handlers for the links and icons.
//
//

function watchLinkClickHandler(e)
{
    positionPopup(e.currentTarget);
    watch(e.currentTarget.num);
    e.preventDefault();
}

function windowResizeHandler()
{
    if (lastTarget)
    {
        positionPopup(lastTarget);
    }
}

function watchIconClickHandler(e)
{
    positionPopup(watchLinks[e.currentTarget.num]);
    watch(e.currentTarget.num);
    e.preventDefault();
}




/**
 *
 *
 *
 */   
function setupLinks()
{
    var comedianBlocks = getElementsByClassName(document, 'comedian');

    for (var i = 0; i < comedianBlocks.length; i++)
    {
        var comedianBlock = comedianBlocks[i];
        var a = getElementsByClassName(comedianBlock, 'watchIcon');
        var icon = a.length ? new HTMLElement(a[0]) : null;
        var link = a.length ? new HTMLElement(getElementsByClassName(comedianBlock, 'watchLink')[0]) : null;
        watchLinks[i] = link;

        if (icon && link)
        {
            icon.num = i;
            link.num = i;
            icon.addEventListener('click', watchIconClickHandler);
            link.addEventListener('click', watchLinkClickHandler);
        }
    }

    //
    //
    //
    window.addEventListener('resize', windowResizeHandler);
    
}




/**
 *
 * Play a video in the video popup.
 * 
 *     @param src
 *         the source of the video   
 *
 */   
function playVideo(src)
{
	//src = '/videos/hosts/bobbyMiyamoto.smil.xml';
    var swfObject = document.getElementById('myComediansVideoPlayerSWF');
    if (typeof swfObject.playVideo == 'function')
    {
        swfObject.playVideo(src);
        clearInterval(playInterval);
    }
}




function initPopup(slotID)
{
}




/**
 *
 * Positions the video player popup relative to a specific element.
 * 
 *     @target
 *         the element to which the popup should point     
 *     
 */              
function positionPopup(target)
{
    initPopup(target.num);

    lastTarget = target;
    popup.style.display = 'block';
    var num = target.num;
    var offset = target.getOffset();
    var left = offset.x;
    var top =  offset.y;

    switch (num)
    {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            left += 120;
            top -= 140;
            tail.id = 'tailLeft';
            break;
        case 12:
        case 13:
            left += 150;
            top -= 155;
            tail.id = 'tailLeft';
            break;
        case 14:
        case 15:
            left -= 705;
            top -= 155;
            tail.id = 'tailRight';
            break;
        case 16:
        case 17:
            left -= 225;
            top -= 405;
            tail.id = 'tailDown';
            break;
        default:
            left -= 682;
            top -= 145;
            tail.id = 'tailRight';
            break;
    }
        
    popup.style.left = left + 'px';
    popup.style.top = top + 'px';
        
}




/**
 *
 * Watch a video.
 * 
 *     @param id
 *         the slot number of the video to play.               
 *
 */                   
function watch(slotID)
{
    var id = slots[slotID] == null ? slotID : slots[slotID];
    currentComedian = id;
    slotID = parseInt(slotID);

    // If the popup is over the countdown, hide the countdown (just in case
    // browser doesn't support transparent wmode.
    switch(slotID)
    {
        case 0:
        case 1:
        case 2:
        case 12:
        case 16:
        case 17:
        case 14:
        case 6:
        case 7:
        case 8:
//            document.getElementById('countdown').style.visibility = 'hidden';
            document.getElementById('votesSince').style.visibility = 'hidden';
            break;
    
    }

    // Load the video.
    var myComediansVideoPlayer = new SWFObject("./flash/comediansVideoPlayer-bracket.swf", "myComediansVideoPlayerSWF", "320", "256", "8", "#f2ebcc");
    //myComediansVideoPlayer.addParam('wmode', 'opaque');
    myComediansVideoPlayer.write('video');

    clearInterval(playInterval);

    // Poll until callback has been added to SWF.
    playInterval = setInterval(
        function()
        {
            playVideo('./videos/comedians/' + id + '.smil.xml');
        },
        500
    );

    //
    // Play the loading animation while the bio loads.
    //

    var content = getElementsByClassName(popup, 'content')[0];
    content.innerHTML = 'Loading';
    var count = 0;
    var loadingInterval = setInterval(
        function()
        {
            var s = 'Loading';
            for (var i = 0; i < count; i++)
            {
                s += '.';
            }
            content.innerHTML = s;
            count = (count + 1) % 4;
        },
        700
    );
        
    // Load the bio.
        
    var loader = new URLLoader();
    loader.addEventListener(
        'complete',
        function(e)
        {
            clearInterval(loadingInterval);
            content.innerHTML = e.currentTarget.data;
            
var h2 = getElementsByClassName(popup, 'comedianName')[0];
h2.innerHTML = 'Comedian ' + id;
h2.style.backgroundImage = 'url(./images/bracket/headings/names/' + id + '.gif)';
        }
    );
    //var request = new URLRequest('./includes/getSlotInfo.php');
    var request = new URLRequest('./includes/getComedianInfo.php');
    var variables = new URLVariables();
    variables.id = id;
    request.data = variables;
    loader.load(request);
    
    // Load the correct heading.
    /*
    var h2 = getElementsByClassName(popup, 'comedianName')[0];
    h2.innerHTML = 'Comedian ' + id;
    h2.style.backgroundImage = 'url(./images/bracket/headings/names/' + id + '.gif)';
    */
    var downloadItLink = document.getElementById('downloadItLink');
    downloadItLink.href = './videos/comedians/' + id + '/' + id + '.mov.zip';
}






/**
 *
 *
 *
 */   
function setupForwardToAFriend()
{
    var popupContent = document.getElementById('popup-content');
    var popupForm = document.getElementById('popup-form');
    var forwardVideoLink = new HTMLElement(document.getElementById('forwardVideoLink'));
    forwardVideoLink.addEventListener(
        'click',
        function(e)
        {
            popupForm.style.display = 'block';
            popupContent.style.display = 'none';
            e.preventDefault();
        }
    );
    
    var textarea = new HTMLElement(document.getElementById('popup-message'));
    textarea.style.color = textarea.value == 'Message' ? '#ccc' : '#000';
    function blurHandler()
    {
        if (textarea.value == '')
        {
            textarea.style.color = '#ccc';
            textarea.value = 'Message';
        }
    }
    function focusHandler()
    {
        if (textarea.value == 'Message')
        {
            textarea.style.color = '#000';
            textarea.value = '';
        }    
    }
    textarea.addEventListener('blur', blurHandler);
    textarea.addEventListener('focus', focusHandler);
    
    var submitButton = new HTMLElement(document.getElementById('forwardVideoSubmit'));
    function submitClickHandler(e)
    {
        var loader = new URLLoader();
        var request = new URLRequest('./includes/forwardVideo.php');
        var variables = new URLVariables();
        
        var yourEmail = document.getElementById('popup-yourEmail');
        var friendsEmail = document.getElementById('popup-friendsEmail');
        var message = document.getElementById('popup-message');

        e.preventDefault();
        
        if (!checkMail(yourEmail.value))
        {
            alert('Sorry, the email you provided is invalid.');
        }
        else if (!checkMail(friendsEmail.value))
        {
            alert('Please provide us with a valid email address for your friend.');
        }
        else
        {
            variables.yourEmail = yourEmail.value;
            variables.friendsEmail = friendsEmail.value;
            variables.message = message.value == 'Message' ? '' : message.value;
            variables.comedian = currentComedian;
            request.data = variables;
            request.method = 'POST';
            loader.load(request);
    
            yourEmail.value = '';
            friendsEmail.value = '';
            message.value = '';
            blurHandler();
    
            document.getElementById('popup-content').style.display = 'block';
            document.getElementById('popup-form').style.display = 'none';
        }
    }
    submitButton.addEventListener('click', submitClickHandler);

}


function addStar(field)
{
    if (!field.isError)
    {
        var star = new HTMLImageElement();
        star.src = './images/bracket/errorStar.gif';
        star.className = 'errorStar';
        star.alt = 'This field\'s value is invalid!';
        field.parentNode.insertBefore(star, field.nextSibling);
        field.isError = true;
        
        getElementsByClassName(field.parentNode, 'errorMessage')[0].style.display = 'block';
    }
}

function removeStar(field)
{
    if (field.isError)
    {
        var tmp = field;
        while (tmp = tmp.nextSibling)
        {
            if (tmp.className == 'errorStar')
            {
                tmp.parentNode.removeChild(tmp);
                break;
            }
        }
        field.isError = false;
    }
}


/**
 *
 *
 *
 */   
function setupBigForwardToAFriend()
{
    var textarea = new HTMLElement(document.getElementById('message'));
    textarea.style.color = textarea.value == 'Message' ? '#ccc' : '#000';
    function blurHandler()
    {
        if (textarea.value == '')
        {
            textarea.style.color = '#ccc';
            textarea.value = 'Message';
        }
    }
    function focusHandler()
    {
        if (textarea.value == 'Message')
        {
            textarea.style.color = '#000';
            textarea.value = '';
        }    
    }
    textarea.addEventListener('blur', blurHandler);
    textarea.addEventListener('focus', focusHandler);
    
    var submitButton = new HTMLElement(document.getElementById('f2afSubmit'));
    function submitClickHandler(e)
    {
        e.preventDefault();

        var loader = new URLLoader();
        var request = new URLRequest('./includes/sendToAFriend.php');
        var variables = new URLVariables();
        
        var yourName = document.getElementById('yourName');
        var yourEmail = document.getElementById('yourEmail');
        var friendsName = document.getElementById('friendsName');
        var friendsEmail = document.getElementById('friendsEmail');
        var message = document.getElementById('message');
        var isError = false;

        if (!checkMail(yourEmail.value))
        {
            addStar(yourEmail);
            isError = true;
        }
        else
        {
            removeStar(yourEmail);
        }

        if (!checkMail(friendsEmail.value))
        {
            addStar(friendsEmail);
            isError = true;
        }
        else
        {
            removeStar(friendsEmail);
        }
        
        if (!isError)
        {
            variables.yourName = yourName.value;
            variables.yourEmail = yourEmail.value;
            variables.friendsName = friendsName.value;
            variables.friendsEmail = friendsEmail.value;
            variables.message = message.value == 'Message' ? '' : message.value;
            
            request.data = variables;
            request.method = 'POST';
            loader.load(request);
            
            yourName.value = '';
            yourEmail.value = '';
            friendsName.value = '';
            friendsEmail.value = '';
            message.value = '';
            blurHandler();
            
            alert('Your email has been sent!');
        }
    }
    submitButton.addEventListener('click', submitClickHandler);

}




/**
 *
 *
 *
 */   
function showRecommendedVideo()
{
    if (window.location.toString().indexOf('comedian=') != -1)
    {
        var comedian = window.location.toString().split('comedian=').pop().split('#')[0].split('&')[0];
        positionPopup(watchLinks[comedian]);
        watch(comedian);
    }
}



  
window.addEventListener('load', setupPopup);
window.addEventListener('load', setupToolTips);
window.addEventListener('load', setupLinks);
window.addEventListener('load', setupForwardToAFriend);
window.addEventListener('load', setupBigForwardToAFriend);
window.addEventListener('load', showRecommendedVideo);
