var curSlide;
$(function(){
	if ($.browser.msie && $.browser.version < 8) $("#footer").append('<div><br /><center><strong>* FOR BEST RESULTS, PLEASE UPDATE YOUR BROWSER! *</strong></center></div>');
	$('#wrapper, #simple-wrapper').css('min-height', $(window).height());
	if (zend.showLogin=="true") showLoginScreen();
	$("table.admin-table").each(function (){ makeInteractiveTable(this, false); });
	$(".countdown").each(function (){ countDownObject(this, parseInt($(this).text())); });
	$("form").each(function (){ validateForm(this); });
	$('.techbrief').each(function (){ targetedAddThis(this); });
	$('.js-autoupdate').change(function (){$(this).parents('form:first').submit();}).children().click(function (){$(this).parents('form:first').submit();});
	$('#search-form form').submit(function (){
		if ($('#q').val().replace(/\W/gi, '').length<=0){
			alert('Please type at least one keyword consisting of letters and numbers.');
			return false;
		}
	});
	$('#q').each(function (){autoComplete(this);});
	$('.back-to-results').click(function (){  history.go(-1); return false;});
	$('#player').each(function (){
		$(this).empty();
		var pOptions = fpMakeConfig(zend.flowplayerOptions, this);
		if (pOptions!=false) this.f = $f(this, zend.baseUrl+'/js/swf/flowplayer.commercial-3.2.3.swf', pOptions); //flowplayer-3.2.3.swf
	});
	$('.tabs').tabs("div.panes > div", {tabs:'li'});
	$('#rate-it').each(function (){ makeRatingBox(this); });	
	
	$('form.ajax').each(function (){ makeAjaxForm(this); });
	if (typeof(zend.alert)=='string') alert(zend.alert);
	$(document).ajaxError(function(e, xhr, settings, exception){ alert('Unable to submit this form. There was an error in the page.\nError: '+exception+'\nServer Status: '+xhr.status + ' '+xhr.statusText); });
})

function makeAjaxForm(target){
	$(target).submit(function (evt){
		if ($(this).find('ul.errors li:visible:not(.correct)').length>0){return false;}							   
		var that = this;		
		setTimeout(function (){
			var action = $(that).attr('action');
			if (action=="") action = zend.ajaxPost;
			var postvars = $(that).serialize();
			$(that).find('input[type=submit]').attr('disabled', 'disabled').after('<span class="ajax-load"></span>');
			$.post(action, postvars, function (strresponse){
				$(that).find('input[type=submit]').attr('disabled', '');
				$(that).find('span.ajax-load').remove();
				try{
					var jsonresp = $.parseJSON(strresponse);
				}catch(e){
					if (typeof(console)!='undefined') console.log(e);
				}
				if (typeof(jsonresp)!='object' || jsonresp==null){alert('ERROR: '+jsonresp); return;}
				if (jsonresp.captcha) $(jsonresp.captcha.id).val(jsonresp.captcha.code).siblings("img").attr("src", jsonresp.captcha.img);
				if (jsonresp.callback){ callback = eval(jsonresp.callback); callback(); }
				if (jsonresp.alert) alert(jsonresp.alert);
				if (jsonresp.formHtml) $(that).html(jsonresp.formHtml);
				if (jsonresp.status=="success") target.reset();
				if (jsonresp.showClose) $(that).append('<div><br />&nbsp;<input type="button" name="close" id="close" value="Close Window" onclick="window.close();"></div>');
			});
		}, 1);			
		return false;
	});
}

function fpMakeConfig(clipOptions, player){	
	var curcuepoint = -1;
	var playlist = null;
	var playlisthtml = "";
	var slideImageName = 'Slide#.gif';
	var slides = [];
	var instreamClips = [];
	
	if (typeof(clipOptions)!='object'){ $(player).addClass('error'); return false; }
	
	for (s in clipOptions.slides){
		if (!isNaN(clipOptions.slides[s])) clipOptions.slides[s] = {'position':+clipOptions.slides[s]};
		if (typeof(clipOptions.slides[s].type)=='undefined') clipOptions.slides[s].type = 'gif';
		if (typeof(clipOptions.slides[s].url)=='undefined') clipOptions.slides[s].url = clipOptions.assetsUrl+'Slide'+(parseInt(s)+1)+'.'+clipOptions.slides[s].type;
	}
	clipOptions.slides.sort(function (a, b){
		if (a.url) chk_a = a.position;
		else chk_a = a;
		if (b.url) chk_b = b.position;
		else chk_b = b;
		return chk_a-chk_b;
	});	
	
	for(var i in clipOptions.slides){
		i = parseInt(i);
		if (i<clipOptions.slides.length){
			if ((i % 4)==0) playlisthtml += (i>0?"</div>\n":'')+"<div>\n";
			pltime = null;
			plthumb = null;
			pltitle = null;
			switch(clipOptions.slides[i].type){
				case 'video':
					if (!clipOptions.slides[i].url.match(/http\:\/\//i)) clipOptions.slides[i].url = clipOptions.assetsUrl + clipOptions.slides[i].url;
					var temp = clipOptions.slides[i];
					var temp2 = clipOptions.slides[i];
					temp.position = Math.round(temp.position);
					delete temp.type;
					instreamClips.push($.extend({autoPlay:true}, temp));
					pltime = clipOptions.slides[i].position;
					plthumb = clipOptions.assetsUrl+'thumb'+(parseInt(i)+1)+'.jpg';
					pltitle = 'Video '+(parseInt(i)+1);
					temp2.url = plthumb;
					slides.push(temp2);
					break;
				case 'swf':
					pltime = clipOptions.slides[i].position;
					plthumb = clipOptions.assetsUrl+'thumb'+(parseInt(i)+1)+'.jpg';
					pltitle = 'Slide '+(parseInt(i)+1);
					slides.push(clipOptions.slides[i]);
					break;
				default:
					pltime = clipOptions.slides[i].position;
					plthumb = clipOptions.slides[i].url;
					pltitle = 'Slide '+(parseInt(i)+1);
					slides.push(clipOptions.slides[i]);
			}
			playlisthtml += '<a href="#" '+(parseInt(i)==0?' class="selected"':'')+' onclick="seekVideo('+pltime+'); return false;" title="'+pltitle+'" ><img src="'+plthumb+'" width="97" /><span>'+pltitle+'</span></a>'+"\n";
		}
	}	
	playlisthtml += "</div>\n";
	totalSlides = clipOptions.slides.length-1;
	$(player).after('<div class="playlist" style="display:none;"><div class="browse prev">Previous</div><div class="playlist-content"><div class="slides" style="height:'+(83*totalSlides)+'px">'+playlisthtml+'</div></div><div class="browse next">Next</div></div>');
	$(player).siblings('.playlist').each(function (){
		playlist = $(this).find('.playlist-content').scrollable({vertical:true}).data("scrollable");

	});
	
	var	options ={
			//debug:true,
			//log: { level: 'info', filter: 'org.flowplayer.slideshow.*'},			
			clip:{
				autoPlay: clipOptions.autoPlay,
				autoBuffering: true,
				url: clipOptions.assetsUrl+'audio.flv',
				playlist:instreamClips
			},
			plugins: {
				slideshow: {
					url: 'flowplayer.slideshow-3.2.0.swf',
					slides: slides,
					totalDuration: clipOptions.duration
				},
				viral: {
					url: 'flowplayer.viralvideos-3.2.2.swf',
					icons: {overColor: 'rgba(72,106,114,0.5)'},
					email:{
							script:zend.baseUrl+'/mailer',
							tokenUrl:zend.baseUrl+'/mailer/token',
							texts: { template: '{0}\n\n[D'+zend.tbid+']\n\n eeTECHbrief Link: <a href="'+location.href+'">'+location.href+'</a>' }
					},
					embed: !clipOptions.locked,
					share:{
						description: 'eeTECHbrief Video Presentation',
						myspace:false,
						livespaces:false,
						orkut:false,
						stubmbleupon:false,
						bebo:false						
					}
				},
				controls:  {
					url: 'flowplayer.eecontrols-3.2.0.swf',
					playlist:true,
					backgroundColor: '#486A72',
					backgroundGradient: 'none',
					height:30,
					progressColor: '#6d9e6b',
					bufferColor: '#333333',
					autoHide: true,
					trackLink: zend.baseUrl+'/track/view?tb='+zend.tbid,
					tooltips:{
						buttons: true
					},
					depth:100
				}
			},	
			key: '#$e492341540f1bf863aa',
			/*logo: {	
				url: zend.baseUrl+'/images/logo.png',
				opacity:0
			},*/			
			canvas: {
				backgroundColor: '#486A72',
				backgroundGradient: [0.3, 0]
			},
			onLoad: function (){
				$(player).siblings('.playlist').fadeIn('normal');
			},
			onCuepoint: function (event, cuepoint){
				slideIndex = parseInt(cuepoint.parameters.index);
				if (curcuepoint != slideIndex){
					playlist.seekTo(Math.floor(slideIndex/4));
					$(player).siblings('.playlist').find('a.selected').removeClass('selected');
					$(player).siblings('.playlist').find('a:eq('+slideIndex+')').addClass('selected');
					curcuepoint = slideIndex;					
				}
			},
			onError: function (errorCode, errorMessage){
				setTimeout(function (){
					$(player).addClass('error').html('');
					$(player).siblings('.playlist').empty();
				}, 100);
				
			}
	};
	return options;
}

function showLoginScreen(){
	var html ='<p>Enter your email address and password to continue.</p><div class="form-errors"><ul></ul></div><form action="'+zend.baseUrl+'/login?ret='+location.href+'" class="js-validate login-form" method="post" enctype="application/x-www-form-urlencoded" id="AutoForm"><dl class="zend_form"><dt id="email-label"><label class="required" for="email">Email Address*</label></dt><dd id="email-element"><input type="text" class="email" value="" id="email" name="email"></dd><dt id="password-label"><label class="required" for="password">Password*</label></dt><dd id="password-element"><input type="password" class="passwordfield" value="" id="password" name="password"></dd><dd class="keepsignedin-element"><span><input type="hidden" value="0" name="keepsignedin"><input type="checkbox" class="checkbox" value="1" id="keepsignedin" name="keepsignedin"></span> <span id="keepsignedin-label"><label class="optional" for="keepsignedin">Keep me signed in until I log out.</label></span></dd><dd class="submit-element"><input type="submit" class="button" value="Login" id="submit" name="submit"></dd></dl></form><p><a href="'+zend.baseUrl+'/login/recover">Forgot your password?</a></p><p>Don\'t have an account? <a href="'+zend.baseUrl+'/register">Click here</a> to register.</p>';
	showWindow('Registered Users Only', html, 420, 350);
}

function showWindow(title, html, width, height){
	if ($('#screenoverlay').length<=0) $('body').append('<div id="screenoverlay" style="height:'+$(document).height()+'px; width:'+$(document).width()+'px;"></div>');
	var top = $(window).height()/2 - height/2;
	var baseUrl = zend.baseUrl;
	if ($('#overlay-login-form').length<=0) $('body').append('<div id="overlay-login-form" style="top:'+top+'px;" ><h4></h4><div class="overlay-content"></div></div>');
	$('#overlay-login-form').children('h4').html(title);
	$('#overlay-login-form').children('.overlay-content').html(html);
	$('#overlay-login-form').css('height', height+'px');
	$('#overlay-login-form').css('width', width+'px');
	$('#overlay-login-form').css('margin-left', -(width/2)+'px');
}

function hideWindow(){
	$('#screenoverlay').remove();
	$('#overlay-login-form').remove();
}


function seekVideo(time){
	var clip = $("#player")[0].f.getClip();
	if (!clip.isInStream){
		$("#player")[0].f.seek(time);
		if (!$("#player")[0].f.isPlaying()) $("#player")[0].f.resume();
	}else{
		$("#player")[0].f.seek(clip.duration);
		if (!$("#player")[0].f.isPlaying()) $("#player")[0].f.resume();
	}
}

function autoComplete(target){	
	$(target).autocomplete({
		lookup: zend.autocomplete,
		onSelect: function (){
			$(target).parents('form:first').submit();
		}
	});
}

function targetedAddThis(contaner){
	url = $(contaner).find('.right-box').find('.light-button').attr('href');
	title = $(contaner).find('.right-box').find('h2').text();
	descr = $(contaner).find('.right-box').find('p').html();
	$(contaner).find('.addthis_toolbox a')
			   .attr('addthis:url', zend.baseUrl+url)
			   .attr('addthis:title', title+' @ eeTECHbrief')
			   .attr('addthis:description', descr);
}

function countDownObject(target, timer){
	$(target).html(timer);
	if (isNaN(timer) || timer<=0) return;
	setTimeout(function (){
		countDownObject(target, --timer);
	},1000);
}

function makeRatingBox(target){
	var rated = false;
	var star = 0;
	var rateCont = $(target).find('.rating');
	var rateDiv = $(target).find('.rate');
	var ratedDiv = $(target).find('.rated');
	var temp = $(ratedDiv).text(); temp = temp.match(/(\d+\.?\d*)/gi);
	var curRating = parseFloat(temp[0]);
	var totRatings = parseFloat(temp[2]);
	
	if(rateDiv.length==0) rated = true;
	
	$(target).find('.rating').mousemove(function (event){
		pos = $(this).offset();
		mouseX = (event.pageX - pos.left+0.25);
		star = Math.ceil(mouseX/20)*20;
		$(rateDiv).css('width', star +'px');
	}).mouseleave(function (event){
		$(rateDiv).css('width', '0px');
	}).mouseup(function (event){
		var myRating = star/20;
		$.post(zend.ajaxPost, 'action=rate&rate='+myRating, function (response){
			var rating = $.parseJSON(response);
			if (rating.rating>0){
				$(ratedDiv).css('width', (rating.rating*20)+'px');
				$(ratedDiv).html('Rating: '+rating.rating+'/5 out of '+rating.totalRatings+' ratings.');
				$(rateCont).attr('title', 'Rating: '+rating.rating+'/5 out of '+rating.totalRatings+' ratings.');
				$(rateDiv).css('width', '0px');
			}else{
				if (rating.rating==-1){
					alert("You have to be logged in to be able to rate this eeTECHbrief.");
				}else{
					alert("You must confirm your email address to be able to rate this eeTECHbrief.");
				}
			}
		});		
		rated = true;
	});
}

function validateForm(form){
	if ($(form).hasClass('js-validate') || $(form).hasClass('js-simple-validate')){
		var isSimpleForm = $(form).hasClass('js-simple-validate');
		$(form).find("input, select, textarea").each(function (){
			ss_validate = $(form).hasClass('validate');
			id = $(this).attr('id');
			label = $('#'+id+'-label').text();
			req = (label.indexOf('*')>=0?true:false);
			if (label){
				if (req){
					if ($(this).parent().find('ul.errors').length<=0) $(this).after('<ul class="errors"></ul>');
					var errorMessage = 'Please enter a '+label.replace('*','').toLowerCase();
					if ($(this).parent().find('ul.errors li').length<=0) $(this).parent().find('ul.errors').append('<li class="default" title="'+errorMessage+'">'+(isSimpleForm?'':errorMessage)+'</li>');
					$(this).parent().find('ul.errors').append('<li class="message">Required.</li>');
					$(this).parent().find('ul.errors').append('<li class="correct">Ok.</li>');
				}
				$(this).parent().find('ul.errors').find('li').each(function (){ if ($(this).text().length>0) $(this).attr('title',$(this).text()); });
			}

			validateField = function (){
				name = $(this).attr('id');
				css_class = $(this).attr('class');
				type = $(this).attr('type').toLowerCase();
				value = (type!='select-one'?$(this).val():$(this).find('option:selected').attr('value'));
				confirms = (name.match(/_confirm$/gi)?name.replace(/_confirm$/gi, ''):false);
				has_error = false;
				is_blank = false;
				
				$(this).parent().find('ul.errors').find('li').css('display', 'none');
				$(this).parent().find('ul.errors').find('li.message').css('display','inline-block');
				
				if (ss_validate && $(this).parent().find('ul.errors').find('li:not(.message):not(.correct):not(.default)').length>0) has_error = true;
				
				if (css_class.match(/\balphaspace\b/gi) && !value.match(/^[A-Z_\s]+$/gi)) has_error = true;
				if (css_class.match(/\balpha\b/gi) && !value.match(/^[A-Z_]+$/gi)) has_error = true;
				if (css_class.match(/\bdigits\b/gi) && !value.match(/^\d+$/gi)) has_error = true;
				if (css_class.match(/\bemail\b/gi) && !value.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/gi)) has_error = true;
				if (type=='select-one' && value=='') has_error = true;
				if (type=='password' && !value.match(/^.{4,10}$/gi)) has_error = true;
				if (type=='password' && $('#'+name+'_confirm').length>0){
					if ($('#'+name+'_confirm').val()!='') $('#'+name+'_confirm').change();
				}
				if (confirms){
					if ($('#'+confirms).val()!=value) has_error = true;
				}
				
				if (value=='') is_blank = true;
				
				if (has_error && !is_blank){
					$(this).parent().find('ul.errors').find('li').css('display','inline-block');
					$(this).parent().find('ul.errors').find('li.correct').css('display','none');
					$(this).parent().find('ul.errors').find('li.message').css('display','none');
				}else if(!is_blank){
					$(this).parent().find('ul.errors').find('li.correct').css('display','inline-block');
					$(this).parent().find('ul.errors').find('li.message').css('display','none');
				}
				
				
			}
			if (req) $(this).change(validateField).focusout(validateField).change();
		});
		$(form).submit(function (){
			$(form).find("input, select, textarea").change();
			if ($(this).find('ul.errors li:visible:not(.correct)').length>0){
				alert('Please fill out all the required fields!');
				return false;
			}
		});
	}
}

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function clean(text){
	var ret = text;
	ret = ret.replace(/(\')/i, '');
	return ret;
}

function checkCookie(){
	username=getCookie('username');
	if (username!=null && username!=""){
		alert('Welcome again '+username+'!');
	}else{
		username=prompt('Please enter your name:',"");
		if (username!=null && username!=""){
			setCookie('username',username,365);
		}
	}
}
