/*
 * Implements the actions for selection a video for the greeting
 * card like the video player and the quick capture.
 *
 * Adoption of Ian Mendiola overlay.js implementation.
 *
 * @author Anja Hauth (ahauth@google.com)
 */

/*
 * Dummy pixel path
 */

var _PIXEL = 'http://s.ytimg.com/yt/img/pixel-vfl73.gif'
/*
 * Overlay background image path
 */

var _OVERLAY_BG_IMG = 'http://s.ytimg.com/yt/img/white-1x1-vfl52732.png';

/*
 * Modal box dark border image path
 */
var _BORDER_BG_IMG = 'http://s.ytimg.com/yt/img/overlay-border-1x1-vfl52732.png';

/*
 * hide div only used in IE6 version
 */
var __hidediv = null;

/*
 * div to be displayed when video player is activated
 */
var _playerBox = null;
var _playerViewport = null;

/*
 * div to be displayed when quick capture is activated
 */
var _captureBox = null;
var _captureViewport = null;

/*
 * div that gives overlay effect
 */
var _overlay = null;

/*
 * CSS prefix to be used 
 * for all overlay style classes
 */

var _CSS_PREFIX = 'yt-overlay-';

/*
 * Sets the extra width
 * for the modal box
 */
var _MODAL_EXTRA_WIDTH = 22;
/*
 * max size of youtube page
 */
var _maxPageWidth = 855;

/*
 * target box height
 */
var _boxHeight = 0;

/*
 * target box width
 */
var _boxWidth = 0;

/*
 * close string
 */
var _closeText = null;

/*
 * global width and height of window
 */

var _winW, _winH = 0;

/*
* global width and height of document
*/

var _docW, _docH = 0;
/*
 * id of video to be displayed
 */

var _videoId = null;

// Browser detection 
{
	var userAgent = navigator.userAgent.toLowerCase();
	_isOpera = userAgent.indexOf('opera') != -1;
	_isMSIE = userAgent.indexOf('msie') != -1 && !_isOpera;
	_isMSIE6 = userAgent.indexOf('msie 6') != -1 && !_isOpera;
	_isWebkit = userAgent.indexOf('webkit') != -1;
}

function install(boxWidth, boxHeight, closeText, selectText, selectFunction, optMultiplier) {
	optMultiplier = optMultiplier || 1;
	_boxHeight = boxHeight * optMultiplier;
	_boxWidth = boxWidth * optMultiplier;
	_closeText = closeText;
	_selectText = selectText || "";
	_selectFunction = selectFunction || null;
	_playerBox = document.createElement('div');
	_playerViewport = document.createElement('div');
	initBox(_playerBox, _playerViewport, 'player-viewport', _selectFunction);
	_captureBox = document.createElement('div');
	_captureViewport = document.createElement('div');
	initBox(_captureBox, _captureViewport, 'capture-viewport', null);

	initOverlay();

	// hide target box on install
	hide();

	// assign listener to target box to prevent it
	// from hiding the overlay when clicked
	
	if(!_isMSIE) {
		// attach listener to reposition box when window has
		// been resized
		window.addEventListener('resize',positionModalBoxes, false);
	} else {
		window.onresize = positionModalBoxes;
	}
	
	// initialize CSS styles
	initStyles();
}

/*
 * create overlay dialog box
 */
function initOverlay() {
	_overlay = document.createElement('div');
	_overlay.id = _CSS_PREFIX + 'a';

	// add iframe for ie6 SELECT hack
	// and create additional div for hiding
	if(_isMSIE6) {
		iframe = document.createElement('iframe');
		_overlay.appendChild(iframe);
	
		__hidediv = document.createElement('div');
		__hidediv.id = _CSS_PREFIX + 'b';
		document.body.appendChild(__hidediv);
	}
	
	document.body.appendChild(_overlay);
}

function initBox(box, viewport, viewportId, selectFunction) {
	box.className = _CSS_PREFIX + 'modal-box';

	viewport.id = _CSS_PREFIX + viewportId;
	viewport.className = _CSS_PREFIX + 'modal-viewport';
	box.appendChild(viewport);

	var bar = document.createElement('div');
	bar.className = "search-wrapper";
	bar.id = "yt-overlay-modal-bar"
	box.appendChild(bar);

	var centeredContent = document.createElement('div');
	centeredContent.id = 'centered-content';
	bar.appendChild(centeredContent);
	
	var centeredDiv1 = document.createElement('div');
	centeredDiv1.id = "centered-div1";
	centeredContent.appendChild(centeredDiv1);
	
	var centeredDiv2 = document.createElement('div');
	centeredDiv2.id = "centered-div2";
	centeredDiv1.appendChild(centeredDiv2);
	
	var centeredDiv3 = document.createElement('div');
	centeredDiv3.id = "centered-div3";
	centeredDiv2.appendChild(centeredDiv3);
	
	if (selectFunction != null) {
		appendSendButton(centeredDiv3, _selectText, function() {_selectFunction(_videoId);});
	}
	appendCloseButton(centeredDiv3, _closeText, function() {hide();});
	
	// used to make sure clicking on the 
	// modal box does not hide it
	if(!_isMSIE) {
		box.addEventListener('mousedown', function(e){e.stopPropagation()}, false);
	}
	else if(_isMSIE) {
		box.attachEvent('mousedown', function(e){e.stopPropagation()});
	}
	document.body.appendChild(box);
}

/*
 * Initialize CSS Style rules
 */
function initStyles() {
	var headElement = document.getElementsByTagName('head')[0];
	
	// create a style element to hold our styles
	var styleElement = document.createElement('style');

	// check that hte browser supporrts styleSheet object property
	// if so insert a style element tot he DOM and get a reference
	if(document.styleSheets) {
		headElement.appendChild(styleElement)
		var sheet = styleElement.sheet ? styleElement.sheet : styleElement.styleSheet;
	}

	if(!sheet) {
		textNode = document.createTextNode('');
		styleElement.appendChild(textNode);
	}

	var addCSSRule = function(name, style) {
		var rule = name + ' { ' + style + ' }';
		if(sheet) {
			if (sheet.insertRule) 
				sheet.insertRule(rule, sheet.cssRules.length);
			else if(sheet.addRule)
				sheet.addRule(name, style);
		} else {
			textNode.data += rule + '\n';
		}
	}

	// IE6 specific CSS Rule to fix .png
	var overlayCondCSS = '';
	var borderCondCSS = '';
	if(!_isMSIE6) {
		overlayCondCSS = 'background-image:url("' + _OVERLAY_BG_IMG + '");';
	}
	else {
		overlayCondCSS =	alphaImageLoader(_OVERLAY_BG_IMG);
	}

	borderCondCSS = 'background-image:url("' + _BORDER_BG_IMG + '");';
	// styles the overlay screen 
	addCSSRule('#' + _CSS_PREFIX + 'a', 
						 'width:100%;' + 
						 'position:absolute; left:0; top:0;' +
						 overlayCondCSS);
	// styles the wrapping box
	extraWidth = _boxWidth + _MODAL_EXTRA_WIDTH;
	addCSSRule('.' + _CSS_PREFIX + 'modal-box',
						borderCondCSS + 'border:solid 1px #999;' +
						'padding:5px; left:0; top:0; z-index:2500;' + 
						'width:' + extraWidth + 'px; overflow:hidden;' +
						'zoom:1;' + 'text-align: center;');


	// css for internet explorer 6 SELECT bug
	if(_isMSIE6) {
		// style for dummy div to hide
		addCSSRule('#' + _CSS_PREFIX + 'b',
							'position:absolute;z-index:1000;top:0;left:0;');

		// style for iframe
		addCSSRule('#' + _CSS_PREFIX + 'a iframe', 
							'display:none;display:block;position:absolute;top:0;' +
							'left:0;z-index=-1;filter:mask();width:3000px;height:3000px;');
		addCSSRule('.' + _CSS_PREFIX + 'modal-box', 
				'position:absolute;');
	} else {
		addCSSRule('.' + _CSS_PREFIX + 'modal-box', 
				'position:fixed;');
		
	}
	
	// styles the view port
	addCSSRule('.' + _CSS_PREFIX + 'modal-viewport',
						'background-color:#fff; height:' + _boxHeight +
						'px; width:' + _boxWidth + 'px; border:solid 1px #ccc;' +
						'margin:5px; padding:5px;text-align:center;' +
						'zoom:1');
		
	// styles close link
	addCSSRule('#' + _CSS_PREFIX + 'close-link',
						'display: inline;' +
							'margin-bottom: 5px;' +
							'margin-left: 5px;' +
							'float: left;' +
							'zoom:1;');

	// styles select link
	addCSSRule('#' + _CSS_PREFIX + 'select-link',
						'white-space: nowrap;' +
							'display: block;' +
							'margin-bottom: 5px;' +
							'margin-left: 6px;' +
							'float: left;' +
							'zoom:1');
	
	// styles search-left-cap
	addCSSRule('.' + 'search-left-cap',
							'background: transparent url(/img/greeting/search-button-leftcap.gif) no-repeat scroll' +
							'float: left;' +
							'zoom:1');

	// styles "buttons" in player
	addCSSRule('#yt-overlay-modal-bar',
			'float: left;' +
			'width: 100%;' +
			'text-align: center;');
	addCSSRule('#centered-content',
			'display: block' +
			'text-align: center;');
	addCSSRule('#centered-div1',
			'width: 100%;' +
			'float: left;');
	addCSSRule('#centered-div2',
			'left: 50%;' +
			'position: relative;' +
			'float: left;');
	addCSSRule('#centered-div3',
			'right: 50%;' +
			'position: relative;' +
			'float: left;' +
			'text-align: left;');
}

function show(component, box, viewport) {
	// request servlet
	setVisibility(_overlay, true);
	
	component.write(viewport.id);

	positionModalBox(box);
	setVisibility(box, true);
	if (_isMSIE6) {
		window.onscroll = positionModalBoxes;
	}
}

function hide() {
	setVisibility(_overlay, false);
	setVisibility(_playerBox, false);
	setVisibility(_captureBox, false);
	// clear viewport
	_playerViewport.innerHTML = '';
	_captureViewport.innerHTML = '';
	if (_isMSIE6) {
		window.onscroll = null;
	}
}

function positionModalBoxes() {
	positionModalBox(_playerBox);
	positionModalBox(_captureBox);
}

function positionModalBox(modalBox) {

	// get the view port dimensions
	if(!_isMSIE) {
		_winW = window.innerWidth;
		_winH = window.innerHeight;
		_docW = document.documentElement.scrollWidth;
		_docH = document.documentElement.scrollHeight;
	} else if(_isMSIE) {
		_winW = document.documentElement.clientWidth;
		_winH = document.documentElement.clientHeight;
		_docW = document.documentElement.scrollWidth;
		_docH = document.documentElement.scrollHeight;
	}
	var offset = 0;
	if(_isMSIE6) {
		__hidediv.style.width = _winW + 'px';
		__hidediv.style.height= _winH + 'px';
		offset = document.documentElement.scrollTop;
	}

	//reposition height of overlay
	_overlay.style.height = _docH + 'px';

	modalBox.style.left = (_winW/2 - modalBox.offsetWidth/2) + "px";
	modalBox.style.top = (offset + _winH/2 - modalBox.offsetHeight/2) + "px";
}

function setVisibility(target, visible) {
	target.style.visibility = visible ? 'visible' : 'hidden';
}

function appendSendButton(elem, text, action) {
	var link = document.createElement('a');
	link.id = "yt-overlay-select-link";
	link.className = 'yt-button yt-button-primary';
	// needed for Safari and Chrome
	link.style.display = 'inline';

	var span_text = document.createElement('span');
	span_text.appendChild(document.createTextNode(text));
	link.appendChild(span_text);
	link.onclick = action;

	elem.appendChild(link);
}

function appendCloseButton(elem, text, action) {
	var link = document.createElement('a');
	link.id = "yt-overlay-close-link";
	link.className = 'yt-button yt-button-primary';
	
	var span_text = document.createElement('span');
	span_text.appendChild(document.createTextNode(text));
	link.appendChild(span_text);
	
	link.onclick = action;
	
	elem.appendChild(link);
}

function alphaImageLoader(src) {
	return "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale');";
}

function sendPlayerRequest(videoId, embedUrl) {
	_videoId = videoId;

	var fo = new SWFObject(embedUrl, "movie_player-"+ videoId, _boxWidth, _boxHeight, "7", "#CCCCCC");
	fo.addVariable("use_get_video_info", "1");
	fo.addVariable("rel", "0");
	fo.addVariable("autoplay", "1");
	show(fo, _playerBox, _playerViewport);
}

function sendQuickCaptureRequest(vidcapData) {
	var fo = new SWFObject("/vidcap", "vidcap_player", _boxWidth, _boxHeight, "7", "#CCCCCC");
	fo.addParam("flashvars", vidcapData);
	show(fo, _captureBox, _captureViewport);
}

/**
 * Application context. Public methods will be added
 * to yt.overlay. Everything else is private.
 */
yt = {
	kEI: "{{EVENT_ID:j}}"
};
yt['overlay'] = {
	'install' : install,
	'getPlayer' : sendPlayerRequest,
	'getCapture' : sendQuickCaptureRequest,
	'hide' :hide
};
