var mySlideControl

var SlideControl = new Class({
	Implements: [Events, Options],
	
	options: {
		slideSelector: 		'.popupSlide',
		navigateSelector: 	'.navigator',
		trackSelector:		'.trackMe',
		externalSelector:	'.external',
		startSlide: 		0		
	},
	
	current: null,
	
	slides: null,
	
	initialize: function(opts) {
		this.setOptions(opts)
		
		this.hasTracked = false
		this.setTracking().setNavigation().setExternal()
						
		var slides = $$(this.options.slideSelector)		
		this.slides = new Array()
		slides.each(function(slide, i) {
			this.slides.push(new Slide(slide, i, this))
		},this)
		
		this.setSlideActivation()
		
		return this
	},
	
	setSlideActivation: $empty,
	
	showSlide: function(index, playId) {
		if ($chk(this.current) && this.current == index) return this
		this.trackSlide(index)
		this.fireEvent('onShowSlide', [index, playId])
		if ($chk(this.current)) this.fireEvent('onHideSlide', [this.current])
		this.current = index
		
		return this
	},
	
	trackSlide: function(index) {
		if (!this.hasTracked) return this.hasTracked = true

		var trackdata = 
		[
			{dcsuri:'/overlay/Default.aspx'}, //landing page
			null, //videos page		{dcsuri:'/overlay/player.aspx'}
			null //game page		{dcsuri:'/overlay/game.aspx'}
		]
				
		var template 	= "['DCS.dcssip', '{dcspath}', 'DCS.dcsuri', '{dcsuri}']"
		var context 	= trackdata[index]
		
		if (context) {
			var defaults	= new Hash({dcspath: 'www.ambiencr.com', dcsuri: ''})
			
			defaults.extend(context)
			
			var arr = JSON.decode(template.substitute(defaults))
			try {
			    dcsMultiTrack.apply(this, arr)
			} catch(e) {}
							
		}
		
	},
	
	setTracking: function() {
		// initializes all of the links that are being tracked
		
		var tracks = $$(this.options.trackSelector)
		tracks.each(function(el, i) {
			var json = JSON.decode(el.get('rel'))
			el.setTracking(json.track)
			
			el.addEvent('click', function(e) {
				e.stop()
				this.callTracking()
			})
						
			delete json.track
			el.set('rel', JSON.encode(json))

			var cl = /\.(.*)/										
			el.removeClass(this.options.trackSelector.match(cl)[1])
		}, this)
		
		return this
	},
	
	setNavigation: function() {
		// initializes all of the links that navigate between slides
		var navs = $$(this.options.navigateSelector)
		navs.each(function(el, i) {
			var json 	= JSON.decode(el.get('rel'))
			var navid 	= ($chk(json.navigate.to)) ? json.navigate.to : null
			var playid	= ($chk(json.navigate.playId)) ? json.navigate.playId : null
			el.addEvent('click', function(e) {
				e.stop()
				this.showSlide(navid, playid)				
			}.bind(this))
			
			delete json.navigate
			el.set('rel', JSON.encode(json))
			
			var cl = /\.(.*)/	
			el.removeClass(this.options.navigateSelector.match(cl)[1])
		}, this)
				
		return this
	},
	setExternal: function() {
		// initializes all of the external links so that clicking them will actually target the parent
		
		var exits = $$(this.options.externalSelector)
		exits.each(function(el, i) {
			var href = el.get('href')
			el.set('href', 'javascript:void(0);')
			
			el.addEvent('click', function(e) {
				e.stop()
				try {window.parent.location = href} catch(e) {}
			})
						

			var cl = /\.(.*)/										
			el.removeClass(this.options.externalSelector.match(cl)[1])
		}, this)
		
		return this		
	}
})

var Slide = new Class({
	Implements: [Events, Options],
	
	options: {},
	
	activate: $empty,
	
	deactivate: $empty,
	
	placeFlash: $empty,
	
	fx: null,
	
	initialize: function(slide, index, controller) {		
		this.slide 	= slide
		this.num 	= index
		this.controller = controller
		
		this.isActive = false, this.hasActivated = false, this.playing = null
		
		this.fx = new Fx.Tween(this.slide, {
			property: 'opacity',
			duration: 750,
			link: 'cancel'
		}).set(0)
		this.toggleListeners(true)
	},
	
	toggleListeners: function(state) {
		var fn = (state) ? 'addEvent' : 'removeEvenet'
		this.controller[fn]('showSlide', function(index, playId){this.show(index, playId)}.bind(this))
		this.controller[fn]('hideSlide', function(index){this.hide(index)}.bind(this))
	},
	
	show: function(index, playId) {
		if (index != this.num) return
		this.slide.show()
		//if ($chk(playId)) this.playing = playId
		this.fx.start(1).chain(function(){			
			this.activate(playId)			
			this.isActive = true, this.hasActivated = true
		}.bind(this))
	},
	
	hide: function(index) {
		if (index != this.num) return
		this.fx.start(0).chain(function(){
			this.deactivate()
			this.isActive = false
		}.bind(this))	
	}
})

// Sets element specific tracking calls by parsing "rel" attributes
Element.implement({
	setTracking: function(context) {
		if (this.retrieve('tracking')) return this
		return this.store('tracking', context)
	},
	
	callTracking: function(template) {
		//this is the template for tracking:
		//the 'defaults' are the default values which get extended (overwritten)
		//by the context, which are the element specific tracking values	
		var template 	= "['DCS.dcssip', '{dcspath}', 'DCS.dcsuri', '{dcsuri}']"
		var context 	= this.retrieve('tracking') || {}
		var defaults		= new Hash({dcspath: 'www.ambiencr.com', dcsuri: ''})
		
		defaults.extend(context)
		
		var arr = JSON.decode(template.substitute(defaults))
		try {
		    dcsMultiTrack.apply(this, arr)
		} catch(e) {}				
		//dcsMultiTrack(arr[0], arr[1], arr[2], arr[3])
		//dcsMultiTrack('DCS.dcssip', '/', 'DCS.dcsuri', 'someuri')
		
		return this
	},
	setImg: function(src) {
		var img = this.getElement('img')
		img.set('src', src)
		return this
	}
})

// Sets specific "activation" and "deactivation" functions for specific slides
SlideControl.implement({
	setSlideActivation: function() {
		// video player slide activation

		$extend(this.slides[1], {
			activate: function(playId) {
				
				this.shareBtns = {
					share:$('sendShare'),
					close:$('sendClose'),
					send:$('sendSubmit')					
				}
				
				this.toggleSendForm(true)
				
				if (!this.hasActivated) this.toggleControls()
				
				var wrap = $('playerWrapper')
				wrap.empty().adopt(new Element('div', {'id':'spotPlayer'}))
				
				this.placeFlash('spotPlayer', playId)				
				if ($chk(playId)) this.playItem(playId)	
							
				return this														
			},
			
			deactivate: function() {
				var wrap = $('playerWrapper').empty()				
				this.vidTitles.each(function(value, key) {
					value.hide()
				})
				this.toggleSendForm()
				this.closeShare()
				this.shareBtns = null
			},
			
			toggleControls: function() {
				var vidTitles 	= this.slide.getElements('.vidTitle')
				var obj 		= {}
				vidTitles.each(function(title, i){
					var id = title.get('rel')
					obj['title_'+id] = title
				}, this)
				this.vidTitles = $H(obj)
				
				var vidBtns 	= this.slide.getElements('.btn')
				var vidobj		= {}						
				vidBtns.each(function(el, i) {
					var json 	= JSON.decode(el.get('rel'))
					var playid	= ($chk(json.playId)) ? json.playId : null
					
					var src		= el.getElement('img').get('src')

					var exp		= /^(.*)(\.(jpg|gif|png))$/
					var arr		= src.match(exp)
					
					el.store('playid', playid)
					el.store('title', this.vidTitles['title_'+playid])
					el.store('offstate', src)
					el.store('onstate', arr[1]+'_on'+arr[2])
					
					el.addEvent('click', function(e) {
						e.stop()
						this.playItem(playid)						
					}.bind(this))
					
					vidobj['btn_'+playid] = el
					
					delete json.playId
					el.set('rel', JSON.encode(json))
					
					var cl = /\.(.*)/	
					el.removeClass(".btn".match(cl)[1])					
				}, this)
				this.vidBtns = $H(vidobj)
				
				this.hasActivated = true
				return this
			},			
			
			playItem: function(playid) {
				if ($chk(this.playing)) {
					var playing = this.vidBtns['btn_'+this.playing]
					if (playing.retrieve('playid') == playid) return
					
					playing.retrieve('title').hide()
					playing.setImg(playing.retrieve('offstate'))
				}

				var btn = this.vidBtns['btn_'+playid]				
				btn.retrieve('title').show()
				btn.setImg(btn.retrieve('onstate'))	
							
				try {loadVideoById(playid)} catch(e) {}
				this.playing = playid				
			},
					
			toggleSendForm: function(state) {
				 var fn = (state) ? 'addEvent' : 'removeEvent'
				 this.shareBtns.share[fn]('click', this.showShare.bind(this))
				 this.shareBtns.close[fn]('click', this.closeShare.bind(this))
				 this.shareBtns.send[fn]('click', this.sendShare.bind(this))
				 
			},			
			
			showShare: function(e) {
				if ($type(e) == 'event') e.stop()
				this.clearForm()
				$('sendToForm').show()
			},
			
			closeShare: function(e) {
				if ($type(e) == 'event') e.stop()
				$('sendToForm').hide()
				this.clearForm()
			},
			
			showConfirm: function() {
				$('sendToFriend').hide()
				$('sendConfirm').show()
			},
			
			sendShare: function(e) {
				if ($type(e) == 'event') e.stop()
				var formid = $('sendToFriend')
				
				var inputs = formid.getElements('input')
				var obj = {}
				inputs.each(function(item, i) {
					var key = item.get('name')
					var val = item.get('value')
					obj[key] = val
				})
				var exp 	= /(^.*)(\?.*)$/
				var href	= window.parent.location.href
				var match	= href.match(exp)
				obj.mylocation = (match) ? match[1] : href					
				
				var myrequest = new Request({
					url:window.root+'overlay/SendToFriend.aspx',
					headers: obj					
				})
				myrequest.addEvents({
					'onRequest': function() {
						//this.closeShare()
						this.showConfirm()
					}.bind(this),
					'onSuccess': function() {
						//this.closeShare()
						this.showConfirm()
					}.bind(this),	
					'onFailure': function() {
						this.closeShare()
						this.clearForm()
					}.bind(this)											
				})
				if (this.formValidates(formid)) myrequest.send()							
			},
			
			formValidates: function(el) {
				this.resetForm(el)
				var isValid 	= true
				var inputs 		= el.getElements('input')
				var fails		= new Array()
				
				var validEmail	= function(element) {return (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i).test(element.get('value'))}
				var validField	= function(element) {return ((element.get('value') == null) || (element.get('value').length == 0));}
				inputs.each(function(input, i) {
					var type 	= input.get('class')
					if (type == 'validate-email') {
						if (!validEmail(input)) {
							isValid = false
							fails.push(input)
							input.setStyle('backgroundColor', '#e1626b')
						}
						//isValid = (!validEmail(input)) ? false : isValid						
					}
					if (type == 'required') {
						if (validField(input)) {
							isValid = false
							fails.push(input)
							input.setStyle('backgroundColor', '#e1626b')
						}
						//isValid = (validField(input)) ? false : isValid						
					}					
				}, this)

				return isValid
			},
			
			resetForm: function(el) {
				if ($type(el) != 'element') el = $('sendToFriend')
				var inputs = $$('#sendToFriend input', '#sendToFriend textarea')//el.getElements('input','textarea')
				inputs.each(function(input, i) {
					input.setStyle('backgroundColor', '')
				})			
				
			},
			
			clearForm: function(el) {
				if ($type(el) != 'element') el = $('sendToFriend')
				var inputs = $$('#sendToFriend input', '#sendToFriend textarea')//el.getElements('input','textarea')
				inputs.each(function(input, i) {
					input.value = ''
					input.setStyle('backgroundColor', '')
				})
				$('sendToFriend').show()
				$('sendConfirm').hide()					
			},
			
			placeFlash: function(where, which) {
				var mypage = $A((window.location.href).split('/')).getLast()

				var flashvars = {
					xmlConfigUrl: "xml/videoOverlayPlayerConfig.xml",
					pageUrl: mypage,
					autoStart: true
				};
				flashvars.autoStartId = which
				
				var params = {
					menu: "true",
					wmode: "opaque",
					bgcolor: "#000000",
					base: window.root+"docs/swf",
					swliveconnect: "true",
					allowscriptaccess: "always",
					allowfullscreen: "true"
				};
				var attributes = {
					id: "videoSection",
					name: "videoSection"
				};
				swfobject.embedSWF(window.root+"docs/swf/videoSection.swf", where, "400", "321", "9.0.0", window.root+"docs/swf/expressInstall.swf", flashvars, params, attributes);
				//SWFFormFix("videoSection");			
				SWFFormFixAuto();
			}
		})
		
		// rooster game slide activation
		$extend(this.slides[2], {
			activate: function() {
				var wrap = $('roosterGameWrap')
				wrap.empty().adopt(new Element('div', {'class':'roosterGameWrapper'}).adopt(new Element('div', {'id':'roosterPlayer', 'class':'roosterPlayer'})))
				
				this.placeFlash('roosterPlayer')
				return this			
			},
			
			deactivate: function() {
				var wrap = $('roosterGameWrap').empty()
				var gameCTA = $('gameCTA')
				gameCTA.setStyle('display','none')
			},
			
			placeFlash: function(where) {
				var flashvars = {};
				var params = {
					wmode: 'transparent',
					scale: 'exactfit',
					menu: false,
					quality: 'high',
					allowScriptAccess: 'always',
					base: window.root+'docs/swf'
				};
				var attributes = {id:'roosterGame',name:'roosterGame'};
				swfobject.embedSWF(window.root+"docs/swf/Preloader.swf", where, "898", "455", "9.0.0", window.root+"docs/swf/expressInstall.swf", flashvars, params, attributes);					
			}
		})		
		
		
	}
})


//movie player functions
function thisMovie(movieName) {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return window[movieName];
	 } else {
		 return document[movieName];
	 }
}
function playVideo() {
	thisMovie("videoSection").playVideo();
}
function resumeVideo() {
	thisMovie("videoSection").resumeVideo();
}
function pauseVideo() {
	thisMovie("videoSection").pauseVideo();
}
function stopVideo() {
	thisMovie("videoSection").stopVideo();
}
function seekVideo(offset) {
	thisMovie("videoSection").seekVideo(offset);
}
function setVideoVolume(level) {
	thisMovie("videoSection").setVideoVolume(level);
}
function fullScreenVideo() {
	thisMovie("videoSection").fullScreenVideo();
}
function loadVideoById(id) {
	thisMovie("videoSection").loadVideoById(id);
}
function loadVideoPlayList(stringArray) {
	thisMovie("videoSection").loadVideoPlayList(stringArray);
}