/*
 * Copyright (c) 2008, VHI Inc. All rights reserved.
 */

/*

Work items:
  o Build underlay at zIndex - 1 to obscure background and intercept clicks.
  o Add close button

*/

VHI.namespace("player");

(function () {
    VHI.player.Ad = {
        get_image_url: function(zoneId, uniqueId) {
            //    return 'http://localhost:82/www/delivery/avw.php?zoneid=' + zoneId + '&n=' + uniqueId;
            return 'banners/vog_banner_classmates.gif';
        },
        get_click_url: function(uniqueId) {
            //    return 'http://localhost:82/www/delivery/ck.php?n=' + uniqueId;
            return 'test.html';
        }
    };
})();

var g_previousFlavor = '';

/* This routine is like showanimation, but it simplifies the calling syntax */
function showanimationset(path, prefix, suffix, list, title, image, link, target) {
    if (!VHI.util.lang.isArray(list) || !VHI.util.lang.isArray(list[0])) {
        return;
    }
    
    var pathArray = [];
    for (var i = 0; i < list.length; i++) {
        // Array elements may be 3 or 4 elements long:
        // [['m', 'a', 'y', 3], -- weight explicit: 3
        //  ['f', 'b', 'y']],   -- weight implicit: 1
        var weight = 1;
        if (list[i].length == 4)
        {
            weight = parseInt(list[i].pop(), 10);
        }
        
        //var fullPath = path + '/' + prefix + '_' + list[i].join('_') + '_' + suffix + '_' + '.swf';
        var fullPath=path + '/' + [prefix, list[i].join('_'), suffix].join('_') + '.swf';
        for (var w = 0; w < Math.min(weight, 100); w++) { // 100 is a safety check
            pathArray.push(fullPath);
        }
    }
    showanimation(pathArray, title, image, link, target);
}

/**
 * This routine will display a popup containing an animation embedded in
 * an Adobe Flash player object. The popup is displayed within a layer.
 *
 * This is currently the only public function in the VHI animation player
 * library. It is public so that it is easily callable from a vendor web page.
 */
function showanimation(path, title, image, link, target) {
//    var background = "#FF6600"; // orange--for testing
    var background = "#ffffff";
    var embedId = "vhi_swfObject";
    var zIndex = 5;

    // If an array was passed, select randomly.
    if (VHI.util.lang.isArray(path)) {
        // If each element is itself an array, use weighted probabilities:
        // var examplePath = [['animation1.swf', 3], ['animation2.swf', 1]];
        if (VHI.util.lang.isArray(path[0])) {
            var totalWeight = 0;
            for (var i = 0; i < path.length; i++) {
                totalWeight += path[i][1];
            }
            var weightedPaths = [];
            for (var i = 0; i < path.length; i++) {
                for (var j = 0; j < path[i][1]; j++) {
                    weightedPaths.push(path[i][0]);
                }
            }
            
            var tries = 5;
            while (tries-- > 0) {
                var pathIndex = Math.floor(Math.random() * totalWeight);
                path = weightedPaths[pathIndex];

                var match = /_(\w_\w_\w)_/.exec(path);
                if (g_previousFlavor != match[1]) {
                    g_previousFlavor = match[1];
                    break;
                }
            }
        }
        else 
        {
            // Just select randomly from the array.
            var pathIndex = Math.floor(Math.random() * path.length);
            path = path[pathIndex];
        }
    }
    
    var video = path;
    var content;
    //	var container = document.createElement("div");
    
    //
    // Build the viewer container.
    //
    content = document.createElement("div");
    content.id = "vhi_videoContainer";

    content.style.backgroundColor = "white";
//	content.style.width = "10em";
//	content.style.height = "10em";
    content.style.border = "1px solid black";
    content.style.visibility = "visible";
    content.style.textAlign = "center";

    content.style.zIndex = zIndex;

    //
    // Mask panel
    //

    if (true) {
    mask = document.createElement("div");
    mask.id = "vhi_playerMask";

//	mask.style.border = "1px solid black";
//	mask.style.visibility = "visible";
    mask.style.backgroundColor = "black";
    
    // This is one of the few styles that are handled differently in
    // different browsers.
    VHI.util.Dom.setOpacity(mask, 0.25);

    mask.innerHTML = "&#160;";
    
    mask.style.width = VHI.util.Dom.getDocumentWidth() + "px";
    mask.style.height = VHI.util.Dom.getDocumentHeight() + "px";
    VHI.util.Dom.maximize(mask);

    mask.style.display = "block";
    mask.style.position = "absolute";
    mask.style.zIndex = zIndex - 1;
    
    document.body.insertBefore(mask, document.body.firstChild);
    //document.body.appendChild(mask);
//    container.appendChild(mask);
//    container.appendChild(content);
    }

    //
    // Header bar
    //
    
    var header = document.createElement("div");
    header.id = "vhi_header";

	var adContainer = document.createElement("div");
	adContainer.id = "vhi_adContainer";
    adContainer.style.clear = 'both';

    var videoContainer = document.createElement("div");
    videoContainer.id = embedId;
   
    var titleBar = document.createElement("div");

    if (false) {
        // Text-based title
        var titleText = document.createElement("span");
        titleText.style.textAlign = 'center';
        titleText.style.cssFloat = 'left';
        titleText.style.width = '89%';
        titleText.style.fontFamily = 'Arial, sans-serif';
        titleText.innerHTML = "&nbsp;";
        if (title) {
            titleText.innerHTML = title;
        }
        
        var closeClick = function(){
            document.body.removeChild(mask);
            document.body.removeChild(content);
        };
        
        var closeButton = document.createElement('input');
        closeButton.setAttribute('type', 'button');
        closeButton.setAttribute('value', 'X');
        closeButton.onclick = closeClick;

        var closeContainer = document.createElement("span");
        closeContainer.style.textAlign = 'right';
        closeContainer.style.cssFloat = 'right';
        closeContainer.style.width = '9%';
        closeContainer.appendChild(closeButton);
    
        titleBar.appendChild(titleText);
        titleBar.appendChild(closeContainer);
    }
    else {
        var titleImg = document.createElement('img');
        titleImg.setAttribute('src', 'images/titlebar.png');
        
        var closeClick = function(){
            document.body.removeChild(mask);
            document.body.removeChild(content);
        };
        
        var closeButton = document.createElement('img');
        closeButton.setAttribute('src', 'images/titleclose.png');
        closeButton.setAttribute('cursor', 'hand', 0);
        closeButton.onclick = closeClick;

        titleBar.appendChild(titleImg);
        titleBar.appendChild(closeButton);
    }
    
    header.appendChild(titleBar);
    content.appendChild(header);

    //
    // Advertisement
    //
    if (image !== undefined && image !='') {
        var adAnchor = document.createElement("a");
        var adImage = document.createElement("img");

        adAnchor.target = target;
///     adAnchor.href = VHI.player.Ad.get_click_url(unique);
        adAnchor.href = link;

        adImage.border = '0';
        adImage.alt = '';
///     adImage.src = VHI.player.Ad.get_image_url(zone, unique);
        adImage.src = image;

        adContainer.style.width = 640;
        adContainer.style.height = 100;

        if (link !== undefined && link != '') {
            adContainer.appendChild(adAnchor);
            adAnchor.appendChild(adImage);
        }
        else {
            adContainer.appendChild(adImage);
        }

///	    adContainer.innerHTML = sBannerHTML;
        content.appendChild(adContainer);
    }

    //
    // Provide a placeholder for those without the plugin installed.
    //
    
    var alternative = document.createElement("p");
    alternative.innerHTML = "<a href=\"http://www.adobe.com/go/getflashplayer\">Download Adobe&reg; Flash&trade; Player.</a>";

    videoContainer.appendChild(alternative);

    //
    // Build the viewer frame.
    //

    var viewer = new VHI.animation.Viewer(content);
    
 //   swf.write(videoContainer);

    content.appendChild(videoContainer);

    viewer.render(document.body);

    //
    // Build the SWF object/embed.
    //
    // NOTE: wmode:opaque seems to cause a problem on Mac Flash.
    //

    var flashvars = {};
    var params = {
//        bgcolor: background,
//        wmode: "opaque"
    };
    var attributes = {};
    
    var flashwidth = 640;
    var flashheight = 480;

    var framewidth = flashwidth;
    var frameheight = flashheight + 20; // SWF height + title bar image.

    if (image !== undefined && image != '') {
        frameheight = frameheight + 100;
    }
    
//	var swf = new SWFObject(video, embedId, 360, 280, "9", background);
//	swf.addParam("wmode", "opaque");
//	swf.addVariable("flashVarText", "this is passed in via FlashVars for example only"); // this line is optional, but this example uses the variable and displays this text inside the flash movie
    swfobject.embedSWF(video, embedId, flashwidth, flashheight, "9.0.0", null, 
                       flashvars, params, attributes);
    
    //
    // This is a bit of a hack.
    // We have to manually set the container width using the the player size.
    //
    var embed = document.getElementById(embedId);
    
    // Constrain width, but allow height to grow dynamically.
    // If we don't set the width, center doesn't work.
    content.style.width = framewidth + "px";

    // REVIEW: We have to specify a height because on FF3 the SWF embed doesn't
    // register its height by the time center is called below.
    content.style.height = frameheight + "px";

    if (false) {
        //
        // Set up the player buttons
        //
        
        var playClick = function(){
            embed.Play();
        };
        
        var pauseClick = function(){
            embed.StopPlay();
        }; 
        
        var rewindClick = function(){
            embed.Rewind();
        };
        
        var playButton = document.createElement('input');
        playButton.setAttribute('type', 'button');
        playButton.setAttribute('value', 'Play');
        playButton.onclick = playClick;
    //	$E.on(playButton, 'click', playClick, playButton);

        var pauseButton = document.createElement('input');
        pauseButton.setAttribute('type', 'button');
        pauseButton.setAttribute('value', 'Pause');
        pauseButton.onclick = pauseClick;
    //	$E.on(pauseButton, 'click', pauseClick, pauseButton);

        var rewindButton = document.createElement('input');
        rewindButton.setAttribute('type', 'button');
        rewindButton.setAttribute('value', 'Rewind');
        rewindButton.onclick = rewindClick;
    //	$E.on(rewindButton, 'click', rewindClick, rewindButton);
        
        content.appendChild(playButton);
        content.appendChild(pauseButton);
        content.appendChild(rewindButton);
    }

    viewer.center();
    //VHI.util.Dom.center(content);
    
    // REVIEW: I'm not sure why this gets reset when style.width, etc are set.
    // in center(). Reset it here as a workaround.
    content.style.position = "absolute";
}
