/*
Script: OnDemand.js
	Contains <OnDemand>

Author:
	Alan Roemen

Class: OnDemand
	A simple javascript lightbox
	Supports flash video (swf) and images(gif,jpg,png)

Options:
	baseURL: Base directory for script. Default: false
	cssFile: Name of css file. Set to location of CSS file or true to use default and false to use none. Default: true,
	scriptName: Name of javascript file. Default: 'slidingtabs'
	className: CSS class name for script. Set to false for no CSS. Default: 'SlidingTabs'
	lightboxRel: Default value for REL attribute. Default: 'lightbox'
	initialWidth: Initial width of container. Default: '10px'
	initialHeight: Initial height of container. Default: '10px'
	movieWidth: Set width of flash videos. Default: 800
	movieHeight: Set height of flash videos. Default: 618
	screenMin: Minimum size allowed for screen. Set false to disable. Default: { x: '850', y: '650' }
	showEffect: options for effect used to animate the sliding, see Fx.Base in mootools docs. Default: duration: 300 // half a second
	hideEffect: options for effect used to animate the sliding, see Fx.Base in mootools docs. Default: duration: 300 // half a second
	showClose: Shows the close button for the container. Default: true
	backgroundClose: Close container when background is clicked. Default: false
	overlay: Display background overlay. Default: true
*/

var OnDemand = new Class({
	options: {
		baseURL: false,
		cssFile: true,
		scriptName: 'ondemand',
		className: 'OnDemand',
		lightboxRel: 'lightbox',
		initialWidth: '10px',
		initialHeight: '10px',
		movieWidth: 689,
		movieHeight: 510,
		screenMin: { x: '805', y: '605' },
		showEffect: {	duration: 300	},
		hideEffect: {	duration: 300	},
		showClose: true,
		backgroundClose: false,
		overlay: true,
		require_login: true
	},	

	initialize: function(links, options) {
		this.setOptions(options);
		links = links || this.options.lightboxRel;
		this.links = document.getElements('a[rel^='+links+']');
		
		//IE Problems
		if(window.ie6){
			this.options.showClose = false;
			this.options.backgroundClose = true;
			this.options.overlay = true;
		}
		
		// Get script base path
		if(!this.options.baseURL) {
			var elements = document.getElementsByTagName('script');
			for (var i=0; i<elements.length; i++) {
				if (elements[i].src && (elements[i].src.indexOf(this.options.scriptName+'.js') != -1)) {
					var src = elements[i].src;
					this.options.baseURL = src.substring(0, src.lastIndexOf('/'));
					break;
				}
			}
			// Get document base path
			this.documentBasePath = document.location.href;
			if (this.documentBasePath.indexOf('?') != -1)
				this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.indexOf('?'));
			this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.lastIndexOf('/'));
			if (this.options.baseURL.indexOf('://') == -1 && this.options.baseURL.charAt(0) != '/')
				this.options.baseURL = this.documentBasePath + "/" + this.options.baseURL;
		}
		
		// Adds Stylesheet
		if(this.options.cssFile === true) new Asset.css(this.options.baseURL + '/' + this.options.scriptName + '.css', {id: 'style'});
		else if(this.options.cssFile !== false) new Asset.css(this.options.cssFile, {id: 'style'});
		
		// Setup Links & Link Images
		this.images = new Array();
		this.links.each(function(el, i){
			el.options = false;
			if(el.rel.indexOf(',') != -1) this.getOptions(el);
			el.addClass(this.options.className);
			el.addEvent('click', function(e){
				e = new Event(e).stop();
				if(this.active) return;
				this.active = el;
				this.show();
			}.bindWithEvent(this));
		}.bind(this));
		
		// Check Logon
		if(!this.options.require_login){
			this.loggedon = true;
			return;
		}
		new Ajax(this.options.baseURL+'/logon_check.php', {
			method: 'get',
			onComplete: function(logon){ this.loggedon = eval(logon); }.bind(this)
		}).request();
	},

	getOptions: function(el){
		var obj = {};
		var options = el.rel.substring(el.rel.indexOf(',')+1);

		options = options.split(',');
		for(var i=0; i<options.length; i++){
			var temp = options[i].split(':');
			if(temp.length != 2) continue;
			obj[temp[0]] = temp[1];
		}
		var check='';for(var i in obj)check+=i+': '+obj[i]+'\n'; if(check=='') return;
		el.options = obj;
	},

	checkScreenSize: function(){
		if(!this.options.screenMin) return true;
		var size = window.getSize().size;
		var aSize = { x: window.screen.availWidth.toInt(), y: window.screen.availHeight.toInt() };
		var check = true;
		if(size.x < this.options.screenMin.x) check = false;
		if(size.y < this.options.screenMin.y) check = false;
		if(check) return true;
		
		if(aSize.x<this.options.screenMin.x || aSize.y<this.options.screenMin.y){
			alert('Error! Your browser does not support the needed size of '+this.options.screenMin.y+'x'+this.options.screenMin.x);
			return false;
		}
		
		window.moveTo(0,0);
		window.resizeTo(aSize.x,aSize.y);
		return true;
	},

	centerElement: function(el){
		var size = window.getSize().size;
		var elSize = el.getSize().size;
		var width = (size.x - elSize.x)/2;
		var height = (size.y - elSize.y)/2;
		el.setStyle('left',width.toInt());
		el.setStyle('top',height.toInt());
	},

	logon: function(){
		var pos = window.getSize().size;
		this.background = new Element('div', {
			'styles': {
				'background-color': '#000000',
				'opacity': '0.7',
				'position': 'fixed',
				'top': '0',
				'left': '0',
				'width': '100%',
				'height': '100%',
				'z-index': '60'
			}
		}).inject(document.body);
		this.loginBox = new Element('div', {
			'styles': {
				'position': 'fixed',
				'top': '200px',
				'left': pos.x/2-225,
				'width': '450px',
				'z-index': '61',
				'font': '11px Arial',
				'background': 'transparent url('+this.options.baseURL+'/box_bck.gif) repeat-x scroll center bottom',
				'border': '1px solid #ECECEC'
			}
		}).inject(document.body);
		var heading = new Element('div', {
			'styles': {
				'background': '#F9F9F9 none repeat scroll 0%',
				'border': '1px solid #FFFFFF',
				'height': '20px',
				'padding': '5px 10px 0 10px',
				'color': '#444444',
				'font-weight': 'bold'
			}
		}).injectInside(this.loginBox);
		new Element('div', {
			'styles': {
				'float': 'left'
			}
		}).setHTML('LOGIN REQUIRED').injectInside(heading);
		new Element('div', {
			'styles': {
				'color': '#f9f9f9',
				'background-color': '#444444',
				'padding': '0 3px',
				'float': 'right',
				'cursor': 'pointer'
			},
			'events': {
				'click': (function(e){
					e = new Event(e).stop();
					this.loginBox.remove();
					this.background.remove();
				}).bindWithEvent(this)
			}
		}).setHTML('X').injectInside(heading);
		new Element('div', {
			'class': 'box_contents',
			'styles': {
				'background-color': '#ffffff',
				'line-height': '18px',
				'padding': '20px'
			}
		}).setHTML('<p style="padding: 0">A login is required to access this feature of the website. If you already have an account, please log in now to gain access. If you do not already have an account, you can create a free account. Creating a free account only takes a few seconds and will save you time as you take advantage of all our site features. Once you are logged into aop.com, you will no longer need to enter your demographic information each time you desire to take advantage of a particular feature on aop.com. So <a href="/login.php">sign-in</a> or <a href="/account-new.php">create a free account today</a>!</p>').injectInside(this.loginBox);
		
		this.active = false;
	},

	show: function(){
		if(!this.loggedon) { this.logon(); return; }
		if(!this.checkScreenSize()) return;	
		
		//Create Element
		this.background = new Element('div', {
			'class': 'background',
			'styles': {
				'width': '100%',
				'height': '100%',
				'opacity': '0.7',
				'cursor': (this.options.backgroundClose?'pointer':'auto')
			},
			'events': {
				'click': (function(e){
					e = new Event(e).stop();
					if(this.options.backgroundClose) this.hide();
				}).bindWithEvent(this)
			}
		});
		this.container = new Element('div', {
			'class': this.options.className,
			'styles': {
				'width': this.options.initialWidth,
				'height': this.options.initialHeight,
				'overflow': 'hidden'
			}
		});
		this.close = false;
		
		this.width = false;
		this.height = false;
		if(this.active.options && this.active.options.width) this.width = this.active.options.width.toInt();
		if(this.active.options && this.active.options.height) this.height = this.active.options.height.toInt();
		this.createObject();
	},

	showContents: function(){
		if(this.options.overlay) this.background.inject(document.body);
		this.container.inject(document.body);
		this.centerElement(this.container);
		
		//Add resize event
		if(!window.ie6) {
			window.addEvent('resize', function(){
				if(!this.active) return;
				this.checkScreenSize();
				this.centerElement(this.container);
				if(this.options.showClose) this.showClose();
			}.bindWithEvent(this));
		}
		
		//IE6 fixed positioning & positioning hack
		if(window.ie6){
			new Ajax(this.options.baseURL+'/ie7-fixed.js', {
				method: 'get',
				evalScripts: true
			}).request();
		}
		
		// Show Effect
		var cords = this.container.getCoordinates();
		if(window.ie6) this.container.setStyles({'top': cords.top.toInt() - (this.height/2), 'left': cords.left.toInt() - (this.width/2)});
		this.fx = new Fx.Styles(this.container, this.options.showEffect);
		this.fx.start({
			'height': this.height,
			'top': cords.top.toInt() - (this.height/2)
		}).chain(function(){
			this.fx.start({
				'width': this.width,
				'left': cords.left.toInt() - (this.width/2)
			}).chain(function(){
				if(this.str != '') this.container.innerHTML = this.str;
				if(this.options.showClose) this.showClose();
			}.bind(this));
		}.bind(this));
	},

	showClose: function(){
		if(this.close) this.close.remove();
		var cords = this.container.getCoordinates();
		this.close = new Element('div', {
			'class': 'close',
			'styles': {
				'cursor': 'pointer',
				'position': 'fixed',
				'top': cords.top - 10,
				'left': cords.right - 20,
				'width': '32px',
				'height': '32px',
				'background': 'url('+this.options.baseURL+'/images/close.png) top right no-repeat'
			},
			'events': {
				'click': (function(e){
					e = new Event(e).stop();
					this.hide();
				}).bindWithEvent(this)
			}
		}).setHTML(this.options.closeText).inject(document.body);
	},

	hide: function(){
		this.container.empty();
		var cords = this.container.getCoordinates();
		var size = this.container.getSize().size;
		if(this.options.showClose) this.close.remove();
		// Hide Effects
		this.fx = new Fx.Styles(this.container, this.options.hideEffect);
		this.fx.start({
			'height': 10,
			'top': cords.top.toInt() + (size.y/2)
		}).chain(function(){
			this.fx.start({
				'width': 10,
				'left': cords.left.toInt() + (size.x/2)
			}).chain(function(){
				this.remove();
			}.bind(this));
		}.bind(this));
	},

	remove: function(){
		this.container.remove();
		if(this.options.overlay) this.background.remove();
		this.active = false;		
	},

	createObject: function(){
		this.extension = this.active.href.substring(this.active.href.lastIndexOf('.')+1);
		switch(this.extension){
			case 'swf': this.createEmbedObject('flashVideo'); break;
			case 'jpg': this.createImage(); break;
			case 'gif': this.createImage(); break;
			case 'png': this.createImage(); break;
			default: this.str = 'Error! Object Not Supported!';
		}
	},

	createImage: function(){
		var url = this.active.href;
		if(this.active.title) var alt = this.active.title;
		else var alt = '';
		this.str = '<img src="'+url+'" alt="'+alt+'" />';
		
		var img = new Asset.image(url, {
			'alt': alt,
			'onload': function(){
				if(!this.width) this.width = img.width;
				if(!this.height) this.height = img.height;
				this.showContents();
			}.bind(this)
		});
	},

	createEmbedObject: function(type){
		var url = this.active.href;
		if(!this.width) this.width = this.options.movieWidth;
		if(!this.height) this.height = this.options.movieHeight;
		
		if(type == 'flash')
			this.str='<iframe src ="'+url+'" height="'+this.height+'" width="'+this.width+' frameborder="0" scrolling="no"></iframe>';
		
		if(type == 'flashVideo'){
			this.str = '<object id="csSWF" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
				this.str += 'width="'+this.width+'" ';
				this.str += 'height="'+this.height+'" ';
				this.str += 'codebase="http://active.macromedia.com/flash7/cabs/ swflash.cab#version=9,0,28,0">';
				this.str += '<param name="allowFullScreen" value="true"/>';
  			this.str += '<param name="wmode" value="transparent">';
				this.str += '<param name="src" value="'+url+'"/>';
				this.str += '<param name="bgcolor" value="#1a1a1a"/>';
				this.str += '<param name="quality" value="best"/>';
				this.str += '<param name="allowScriptAccess" value="always"/>';
				this.str += '<param name="scale" value="showall"/>';
				this.str += '<param name="flashVars" value="autostart=false"/>';
				this.str += '<embed name="csSWF" src="'+url+'" allowFullScreen="true" wmode="transparent" ';
				this.str += 'width="'+this.width+'" ';
				this.str += 'height="'+this.height+'" ';
				this.str += 'bgcolor="#1a1a1a" quality="best" allowScriptAccess="always" scale="showall" flashVars="autostart=false" ';
				this.str += 'pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>';
			this.str += '</object>';
		}
		
		this.showContents();
	}
});

OnDemand.implement(new Options, new Events);