//----------------------------------------------------------
// Copyright (C) iPOV inc. All rights reserved.
//----------------------------------------------------------
//

/* Assumes the existence of a configuration object containing a list of options. */
//userOptions from playlist-options.js
//params from playlist-options.js

dojo.require("dojo.dnd.Source");
dojo.require("dijit.form.Button");
dojo.require("dijit.Tooltip");

var playlistConfig = { };

var optionContainer = null;
var maxOptionWidth = 0;
var maxOptionHeight = 0;

var toolTips = {}
var optionRecycled = {}

function playlist_init() {
	var genPlaylistButton = new dijit.form.Button({label: "Generate Playlist"}, 'generatePlaylist');
	dojo.connect(genPlaylistButton, 'onClick', generatePlaylist);

	// replace the avatar string to make it more human readable
	dojo.dnd.Avatar.prototype._generateText = function(){
		return (this.manager.copy ? "copy" : "mov") +
			"ing " + this.manager.nodes.length + " item" +
			(this.manager.nodes.length != 1 ? "s" : "");
	};

	//create the recycle bin
	var recycleBin = new dojo.dnd.Source('pasture', {horizontal: true, accept: ['v_thumbnail']});
	dojo.connect(recycleBin, 'onDndDrop', setupPlaylistConfig);
	recycleBin.creator = recycle_creator;

}

// The main thumbnail container creator
var main_creator = function(item, hint){
	var type = [];
	type.push('v_thumbnail');
	var node;
	if(hint == "avatar"){
		node = dojo.doc.createElement("div");
		node.innerHTML = '<img width="80px" height="60px" style="display: block; margin: 0 auto;" src="' + assetURL + '/' + item.thumbnail + '"/>';
		node.style.width = '100px';
		node.style.height = '75px';
	}else{
		var thumbnailContainer = document.createElement('div');
		thumbnailContainer.id = item.itemId;
		thumbnailContainer.className = 'thumbnailContainer';
		thumbnailContainer.style.width = item.thumbWidth + 'px';
		var newThumbnail = document.createElement('div');
		newThumbnail.id = item.itemId + '_flashContent';
		//newThumbnail.innerHTML = 'Flash Content here';
		newThumbnail.innerHTML = '<img src="' + assetURL + '/' + item.thumbnail + '"/>'; //just using image for now
		thumbnailContainer.appendChild(newThumbnail);

		var dragBar = createDragBar(item.itemId + '_dragBar');

		node = dojo.doc.createElement("div");
		node.appendChild(thumbnailContainer);
		node.appendChild(dragBar);

		/* Create the properties popup */
		var propsPopup = document.createElement('div');
		propsPopup.innerHTML = '<div><span class="vid-prop">Title:</span> ' + item.description + "</div>" +
			'<div><span class="vid-prop">Type:</span> ' + item_type_to_string(item) + "</div>" +
			'<div><span class="vid-prop">Resolution:</span> ' + item.width + "x" + item.height + "</div>" +
			'<div><span class="vid-prop">Duration:</span> ' + get_item_duration(item) + "</div>";
		propsPopup.id = item.itemId + '_propsPopup';
		node.appendChild(propsPopup);

		if(toolTips[item.itemId] != null) {
			toolTips[item.itemId].destroy();
		}
		var addTip = function() { toolTips[item.itemId] = new dijit.Tooltip({connectId:[item.itemId]}, propsPopup); };
		setTimeout(addTip, 50);

		optionRecycled[item.itemId] = {recycled: false};

		item.start = 0;
		item.end = item.maxEnd;

		var dual_slider = createYUISlider(item, { bgId: dragBar.id, maxId: dragBar.id + '_maxthumb', minId: dragBar.id + '_minthumb',
				highlight: dragBar.id + '_highlight', report: dragBar.id + '_report'}, 140, 6);
	}
	node.id = dojo.dnd.getUniqueId();
	return {node: node, data: item, type: type};
};

var recycle_creator = function(item, hint){
	var type = [];
	type.push('v_thumbnail');
	var node;
	if(hint == "avatar"){
		node = dojo.doc.createElement("div");
		node.innerHTML = '<img width="80px" height="60px" style="display: block; margin: 0 auto;" src="' + assetURL + '/' + item.thumbnail + '"/>';
		node.style.width = '100px';
		node.style.height = '75px';
	}else{
		var recycledContainer = document.createElement('div');
		recycledContainer.id = item.itemId;
		recycledContainer.className = 'recycledContainer';
		var newThumbnail = document.createElement('div');
		newThumbnail.id = item.itemId + '_flashContent';
		//newThumbnail.innerHTML = 'Flash Content here';
		newThumbnail.innerHTML = '<img src="' + assetURL + '/' + item.thumbnailSmall + '"/>'; //just using image for now
		newThumbnail.style.width = '44px';
		newThumbnail.style.height = '44px';
		recycledContainer.appendChild(newThumbnail);

		node = dojo.doc.createElement("div");
		node.appendChild(recycledContainer);

		/* Create the properties popup */
		var propsPopup = document.createElement('div');
		propsPopup.innerHTML = '<div><span class="vid-prop">Title:</span> ' + item.description + "</div>" +
			'<div><span class="vid-prop">Type:</span> ' + item_type_to_string(item) + "</div>" +
			'<div><span class="vid-prop">Resolution:</span> ' + item.width + "x" + item.height + "</div>" +
			'<div><span class="vid-prop">Duration:</span> ' + get_item_duration(item) + "</div>";
		propsPopup.id = recycledContainer.id + '_propsPopup';

		if(toolTips[item.itemId] != null) {
			toolTips[item.itemId].destroy();
		}
		var addTip = function() { toolTips[item.itemId] = new dijit.Tooltip({connectId:[item.itemId]}, propsPopup); };
		setTimeout(addTip, 50);

		optionRecycled[item.itemId].recycled = true;



	}
	node.id = dojo.dnd.getUniqueId();
	return {node: node, data: item, type: type};
};


//helper to produce readable string
function item_type_to_string(item) {
	if(item == null) {
		return null;
	}
	if(item.variant != null) {
		if(item.variant == "mp4") {
			return ".h264 Video";
		}
		if(item.variant == "flv") {
			return "FLV Video";
		}
	}
	if(item.version == "9") {
		return "SWF - AVM2";
	}
	return "SWF - AVM1";

}

//helper to produce readable string
function get_item_duration(item) {
	if(item == null) {
		return 0;
	}
	if(item.variant == "mp4" || item.variant == "flv") {
		return item.maxEnd/1000.0;
	}
	if(item.version != null) {
		return item.maxEnd/item.fps;
	}
	return 0;

}

function populateOptions() {
	maxOptionWidth = 0;
	maxOptionHeight = 0;

	var maxThumbWidth = 0;

	optionContainer = new dojo.dnd.Source('optionsContainer', {accept: ["v_thumbnail"]});
	optionContainer.creator = main_creator;
	dojo.connect(optionContainer, 'onDndDrop', setupPlaylistConfig);


	for(var id in userOptions) {
		userOptions[id].itemId = id;
		optionContainer.insertNodes(false, [userOptions[id]]);


		var flashvars = {
			flv: userOptions[id].vthumb,
			thumbnail: userOptions[id].thumbnail,
			thumbHeight: userOptions[id].thumbHeight,
			width: userOptions[id].thumbWidth,
			height: (userOptions[id].thumbHeight + 10)
		};
		var flashId = id + '_flashContent';
		var attributes = {
			name: flashId,
			id: flashId
		};

		//swfobject.embedSWF('mysite/ipov_miniplayer.swf', flashId, flashvars.width, flashvars.height, '9.0.0', 'mysite/expressIntall.swf', flashvars, params, attributes);

		maxOptionWidth = Math.max(maxOptionWidth, userOptions[id].width);
		maxOptionHeight = Math.max(maxOptionHeight, userOptions[id].height);
		maxThumbWidth = Math.max(maxThumbWidth, userOptions[id].thumbWidth);
	}

	//document.getElementById('optionsContainer').style.width = (maxThumbWidth + 80) + 'px';
	setupPlaylistConfig();
}

function setupPlaylistConfig() {
	if(optionContainer == null) {
		return;
	}
	playlistConfig = {};
	playlistConfig.assetURL = assetURL;
        playlistConfig.autoplay = "true";
	playlistConfig.ui = { style: "grey", buttonHoverColor: "0xcc0000" };
	playlistConfig.vitems = [ ];
	var items = optionContainer.getAllNodes();

	for(var i=0; i < items.length; i++) {
		var option = userOptions[items[i].firstChild.id];
		if(option == null) {
			break;
		}
		if(!optionRecycled[option.itemId].recycled) {
			playlistConfig.vitems.push(option);
		}
	}
}

function createDragBar(id) {

	var dragBar = dojo.doc.createElement('div');
	dragBar.id = id;
	dragBar.className = 'sliderbg';


	var highlightBar = dojo.doc.createElement('span');
	highlightBar.id = dragBar.id + '_highlight';
	dragBar.appendChild(highlightBar);

	var minThumb = dojo.doc.createElement('div');
	minThumb.className = 'minthumb';
	minThumb.id = dragBar.id + '_minthumb';
	var maxThumb = dojo.doc.createElement('div');
	maxThumb.className = 'maxthumb';
	maxThumb.id = dragBar.id + '_maxthumb';

	minImg = dojo.doc.createElement('img');
	minImg.src = 'mysite/images/player_demo/l-thumb-round.gif';
	minImg.setAttribute('width', '16');
	minImg.setAttribute('height', '20');
	maxImg = dojo.doc.createElement('img');
	maxImg.src = 'mysite/images/player_demo/r-thumb-round.gif';
	minImg.setAttribute('width', '16');
	minImg.setAttribute('height', '20');

	minThumb.appendChild(minImg);
	maxThumb.appendChild(maxImg);

	dragBar.appendChild(minThumb);
	dragBar.appendChild(maxThumb);

	return dragBar;
}

function createYUISlider(item, idObj, range, tickSize) {
	var Dom = YAHOO.util.Dom;

	var reportSpan = Dom.get(idObj.report);

        // Create the DualSlider
        var slider = YAHOO.widget.Slider.getHorizDualSlider(idObj.bgId,
            idObj.minId, idObj.maxId,
            range, tickSize);

    	slider._highlightId = idObj.highlight;

        // Decorate the DualSlider instance with some new properties and
        // methods to maintain the highlight element
        YAHOO.lang.augmentObject(slider, {
            updateHighlight : function () {
		var delta = this.maxVal - this.minVal;

                if (this.activeSlider === this.minSlider) {
                	// If the min thumb moved, move the highlight's left edge
			YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get(this._highlightId),'left', (this.minVal + tickSize) + 'px');
                }
                // Adjust the width of the highlight to match inner boundary
		YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get(this._highlightId),'width', Math.max(delta - tickSize,0) + 'px');

		this.updatePlaylist();
            },

	    updatePlaylist: function () {
		    item.start = Math.round(this.minVal/range * item.maxEnd);
		    item.end = Math.round(this.maxVal/range * item.maxEnd);
	    }

        },true);

        // Attach the highlight method to the slider's change event
        slider.subscribe('change',slider.updateHighlight,slider,true);

        // Create an event callback to update some display fields
        var report = function () {
            reportSpan.innerHTML = slider.minVal + ' - ' + slider.maxVal;
        };

        // Subscribe to the slider's change event to report the status.
        slider.subscribe('change',report);
	return slider;
}


function generatePlaylist() {
	clearCurrentPlaylist();
	var currentPlaylist = document.getElementById('currentPlaylist');
	currentPlaylist.style.width = maxOptionWidth;
	//alert( dojo.toJson(playlistConfig) );
	var flashvars = { 'proxyURL': '/mysite/avm1Proxy.swf', 'JSON': escape(dojo.toJson(playlistConfig)) };
	flashvars.toJSONString = null;
	var attributes = { id: 'CoSolventPlayer', name: 'CoSolventPlayer' };

	swfobject.embedSWF('mysite/cosolvent-player.swf', 'flashcontent', maxOptionWidth, maxOptionHeight + 24, '9.0.0', 'mysite/expressIntall.swf', flashvars, params, attributes);
}

function clearCurrentPlaylist() {
	var currentPlaylist = document.getElementById('currentPlaylist');
	currentPlaylist.innerHTML = '<div id="flashcontent">' + "\n" + '</div>';
}

