$(function(jQuery){
	var embed_swf,gartner_video,movie_player,spawn_window,tcse_only_row,thumbnail_after,video_re;
	jQuery.fn.tagName=function(){
		var tag_names;
		if(1===this.length){
			return this[0].tagName.toLowerCase();
		}else{
			tag_names=[];
			this.each(function(iteration,item){
				tag_names[iteration]=item.tagName.toLowerCase();
			});
			return tag_names;
		}
	};
	$('.Transparent').ifixpng();//TODO: This should only be called when needed.
	embed_swf=function(video,id,autoplay,callback,width,height){
		autoplay=(true===autoplay)?'1':'0';
		if ('undefined'===typeof width) {
			width=424;
		}
		if ('undefined'===typeof height) {
			height=322;
}
		swfobject.embedSWF(
			'http://www.youtube.com/v/'+video+'&hl=en&fs=1&rel=0&showinfo=0&autoplay='+autoplay,
			id,
			width,
			height,
			'8.0.0',
			'flash/expressInstall.swf',
			{},{},{},
			callback);
	};
	spawn_window=function(url){
		var child;
		child=window.open(url);
		return 'object'!==typeof child;
	};
	//Lightbox-esque movie player
	movie_player=function(){
		var animator,body,cache,doc,html,vanish;
		animator=function(scroll_top){
			if(-1===scroll_top){
				scroll_top=animator.scroll_top;
			}
			if(false===animator.running){
				animator.running=true;
				cache.player_wrapper.animate({top:scroll_top},250,'linear',function(){
					animator.running=false;
				});
			}else{
				animator.scroll_top=scroll_top;
				if(null!==animator.timeout){
					clearTimeout(animator.timeout);
				}
				animator.timeout=setTimeout(function(){animator(-1);},250);
			}
		};
		vanish=function(e){
			$('#MoviePlayer').remove();
			cache.player_wrapper.hide();
			cache.dimmer.hide(500);
		};
		movie_player.vanish=vanish;
		animator.running=false;
		animator.timeout=null;
		movie_player.animator=animator;
		body=$(document.body);
		cache=movie_player.storage;
		doc=$(document);
		html=$(document.documentElement);
		if(null===cache){
			cache={};
			movie_player.storage=cache;
			cache.dimmer=$(
				document.createElement('div')
			).attr('id','Dimmer')
			.hide().height(doc.height())
			.width(doc.width()).click(vanish);
			cache.player_wrapper=$(document.createElement('div'))
			.attr('id','PlayerWrapper')
			.append($(document.createElement('h4')).click(vanish)
			).hide();
			body.append(cache.dimmer)
			.append(cache.player_wrapper);
			$(window).scroll(function(e){
				animator(html.attr('scrollTop'));
			});
		}
		cache.dimmer.fadeTo(0,0);
		cache.dimmer.show();
		cache.dimmer.fadeTo(500,0.75);
		cache.player_wrapper.append($(document.createElement('div')).attr('id','MoviePlayer'));
		cache.player_wrapper.show();
	};
	movie_player.storage=null;
	//Updates the 'Screenshot x of y' label that accompanies cycling thumbnails
	thumbnail_after=function(	currSlideElement,
								nextSlideElement,
								options,
								forwardFlag){
		var container,list,slide;
		slide=$(this);
		list=$(slide.parent());
		container=$(list.parent());
		$('.Counter span',container).text(String((1+slide.prevAll().length)));
	};

	//Search
	$('#SearchForm input').focus(function(e){
		var input;
		input=$(this);
		if('Search'===$.trim(input.val())){
			input.val('');
		}
	}).blur(function(e){
		var input;
		input=$(this);
		if(''===$.trim(input.val())){
			input.val(input.attr('defaultValue'));
		}
	});

	//Flash animation
	if('undefined'!==typeof swfobject){
		video_re=/http:\/\/www\.youtube\.com\/watch\?v=([^$]+)$/;
		//...on the home page.
		if(1===$('#Home').length){
			swfobject.embedSWF(
				'flash/solutions.swf',
				'Frozen',
				'960',
				'300',
				'6.0.0',
				'flash/expressInstall.swf',
				{protocol:document.location.protocol,hostname:document.location.hostname,pathname:document.location.pathname});
		//...and on the web-based training page.
		}
		if(1===$('#Lessons').length){
			swfobject.embedSWF(
				'lessons/'+$('#swf').val(),
				'Lesson',
				$('#width').val(),
				$('#height').val(),
				'7.0.0',
				'../flash/expressInstall.swf');
		}
		//...and on every page that has a link to a you tube video
		if(0!==$('a.YouTube,a.InlineYouTube').length){
			$('a.YouTube,a.InlineYouTube').each(function(iteration,item){
				var anchor,match;
				anchor=$(item);
				match=video_re.exec(anchor.attr('href'));
				if(null!==match){
					anchor.click(function(e){
						movie_player();
						embed_swf(video_re.exec($(this).attr('href'))[1],'MoviePlayer',true,function(e){
							if(true===e.success){
								movie_player.animator($(document.documentElement).attr('scrollTop'));
							}else{
								movie_player.vanish();
							}
						},424,322);
						$('#PlayerWrapper h4').text($('img',this).attr('alt')||$(this).attr('title'));
						return false;
					});
				}
			});
		}
		//..and on the about-the-company page
		if(1===$('#AboutTheCompany').length){
			$.each(['ShortTufinOverview','TufinOpenPlatformOverview'],function(iteration,item){
				var video;
				video=video_re.exec($('#'+item).attr('href'));
				embed_swf(video[1],item,false,null);
			});
		}
	}
	//flowplayer videos
	if('undefined'!==typeof flowplayer){
		var play;
		if($("#GartnerVideo").length>0){
			play=$('#GartnerVideo');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
						{url:'../downloads/tufin_gartner_video.flv'}
				});
		}
		if ($("#player").length>0) {
			play=$('#player');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/output.flv'}
				});
		}
		if ($("#pan-player").length>0) {
			play=$('#pan-player');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/pan_webinar.flv'}
				});
		}
 		if ($("#michael-hamelin-fom").length>0) {
			play=$('#michael-hamelin-fom');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/michael_hamelin_firewall_operations_management.flv'}
				});
		}
		if ($("#michael-hamelin-auditing").length>0){
 			play=$('#michael-hamelin-auditing');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/michael_hamelin_auditing_risk_compliance.flv'}
				});
		}
 		if ($("#security-change-automation").length>0){
 			play=$('#security-change-automation');
			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/security_change_automation.flv'}
				});   	
		}
 		if ($("#apg-video").length>0) {   	
 			play=$('#apg-video');
 			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/apg.flv'}
				});
		}
  		if ($("#tss6-webinar-and-demo").length>0) {   	
 			play=$('#tss6-webinar-and-demo');
 			play.flowplayer('../flash/flowplayer-3.1.5.swf',
				{clip:
					{url:'../downloads/tss6-webinar-and-demo.flv'}
				});
		}
		if (play) {
			play.height(450);
			play.width(719);
		}
	}
	//Cycle plugin, allows logos and testimonials to fade.
	//Also enables thumbnails cycling.
	if('function'===typeof $.fn.cycle){
		$.each({'#Logos':undefined,
				'#Testimonials':{speed:8000,pause:true},
				'.Thumbnails':{fx:'scrollHorz',
								prev:'.Previous',
								next:'.Next',
								after:thumbnail_after,
								pause:true
								}
				},function(selector,argument){
			var elements;
			elements=$(selector);
			if(0!==elements.length){
				elements.cycle(argument);
			}
		});
		$('.Thumbnails').siblings(
			'.Next,.Previous').removeClass(
			'NotDisplayed');
	}
	//Makes selected anchors open in a new window.
	$('a.Blank').click(function(e){
		return spawn_window(e.currentTarget.href);
	});

	//How to Buy
	$('#HowToBuy select.#Country').change(function(e){//Automatic form submission
		var country,pathname,protocol,query;
		protocol=document.location.protocol;
		pathname=document.location.host+document.location.pathname;
		country=$(this);
		query=country.attr('name')+'='+window.encodeURIComponent(country.val());
		document.location.assign(protocol+'//'+pathname+'?'+query);
	}).data('initial_run',false);

	$('#HowToBuy select.#Region').change(function(e){//Country list filteration
		var countries,country,hidden,region;
		region=$(e.target).val();
		country=$('#Country');
		hidden=country.data('hidden');
		if('undefined'!==typeof hidden){
			country.append(hidden);
		}
		countries=$('option[class!="'+region+'"]:not(#PleaseSelect)',country);
		country.data('hidden',countries.remove());
		if(false===country.data('initial_run')){
			country.selectedIndex=0;
			country.data('initial_run',true);
		}
	}).change();

	//Makes partner anchors open in a new window.
	$('#HowToBuy .ResourcesBoxSibling ul a[href^=http]').click(function(e){
		return spawn_window(e.currentTarget.href);
	});

	//TCSE Training Registration
	tcse_only_row=function(){
		if((1===$('#TCSE #ContactAttending:checked').length)||(1===$('#TCSE tbody tr').length)){
			$('#TCSE tbody tr:first').addClass('OnlyRow');
		}else{
			$('#TCSE tbody tr:first').removeClass('OnlyRow');
		}
	};
	$('#TCSE #Add').click(function(e){
		var attribute_name,attribute_value,attribute_names,attribute_names_length,digits,element,elements,elements_length,expression,i,j,new_row;
		attribute_names=['id','name','for'];
		attribute_names_length=attribute_names.length;
		new_row=$('tr:last').clone().removeClass('OnlyRow');
		elements=$('input,label,select',new_row);
		elements_length=elements.length;
		expression=/[^0-9]+([0-9]+)/;
		for(i=0;i<elements_length;++i){
			element=$(elements[i]);
			for(j=0;j<attribute_names_length;++j){
				attribute_name=attribute_names[j];
				attribute_value=element.attr(attribute_name);
				if('undefined'===typeof attribute_value){
					continue;
				}
				if(true!==expression.test(attribute_value)){
					continue;
				}
				digits=expression.exec(attribute_value)[1];
				element.attr(attribute_name,attribute_value.replace(digits,Number(digits)+1));
			}
			if('undefined'!==typeof element.attr('value')){
				element.attr('value','');
			}
			element.attr('readonly','').removeClass('Disabled');
		}
		$('tbody').append(new_row);
		tcse_only_row();
	});
	$('#TCSE .Remove').live('click',function(e){
		if(true===window.confirm('Remove this attendee?')){
			$($(this).parents('tr')).remove();
			tcse_only_row();
		}
	});
	$('#TCSE #ContactFullName,#TCSE #ContactEmailAddress').bind('keyup keydown change',function(e){
		var input;
		if(1!==$('#TCSE #ContactAttending:checked').length){
			return;
		}
		input=$(this);
		$('#'+input.attr('id').replace('Contact','')+'0').val(input.val());
	});
	$('#TCSE #ContactAttending').bind('change click',function(e){
		var checkbox,inputs;
		checkbox=$(this);
		inputs=$('#TCSE tr:first-child input[type="text"]');
		if(true===checkbox.attr('checked')){
			inputs.attr('readonly','readonly').addClass('Disabled');
			$('#TCSE #ContactFullName,#TCSE #ContactEmailAddress').change();
		}else{
			inputs.attr('readonly','').removeClass('Disabled');
			inputs.val('');
		}
		tcse_only_row();
	});

	//Update password form validation
	$('#UpdatePassword form').submit(function(e){
		if($('#NewPassword').val()!==$('#PasswordAgain').val()){
			$('#PasswordMismatchNotification').show();
			return false;
		}
		if(6>$('#NewPassword').val().length){
			$('#ShortPasswordNotification').show();
			return false;
		}
		return true;
	});

	//Generic forms
/*	$('.Generic select.State,.Generic select.Country').change(function(e){ - commented out because now we have state and country auto detection. before Dec 2010 we had only country detection
		var new_country,selected_option,selected_value,target;
		target=$(e.target);
		selected_option=$(':selected',target);
		selected_value=selected_option.val();
		state=$('.State');
		country=$('.Country');
		switch(selected_value){
			case 'USA':
			case 'Canada':
				state.attr('selected','selected');
				break;
			case '':
				if('Outside US or Canada'!==selected_option.text()){
					state.attr('selectedIndex',0);
				}
				country.attr('selectedIndex',0);
				break;
			default:
				if(selected_option.hasClass('USA')||selected_option.hasClass('Canada')){
					new_country=$('option[value="'+selected_option.attr('class')+'"]',country);
					new_country.attr('selected','selected');
				}else{
					state.attr('selected','selected');
				}
				break;
		}
 	});*/
//	$('.Generic select.Country').change();
	$('.Generic,#Winter2009Survey').submit(function(e){
		var email_re,email_validator,form,i,expression_and_validator,expressions_and_validators,mandatory_radio_validator,mandatory_validator,maximum_length_validator,validate_and_notify,numeric_validator,valid,validation_error_messages;
		// Taken from jQuery validation plug-in v1.2.1 where it was contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		email_re=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
		form=$(this);
		email_validator=function(element){
			var empty,result,valid,value;
			value=element.val();
			empty=''===$.trim(value);
			if(true!==empty){
				valid=true===email_re.test(value);
			}else{
				valid=true;
			}
			result=empty||valid;
			return result;
		};
		mandatory_radio_validator=function(name){
			var i,notified,radios,valid;
			radios=$('[name='+name+']');
			notified=radios.data('notified');
			valid=true;
			if(false===notified){
				valid=false;
				for(i=0;i<radios.length;++i){
					valid=(valid||(true===$(radios[i]).attr('checked')));
				}
				notified=radios.data('notified',false===valid);
			}
			return valid;
		};
		full_name_validator=function(element){
			var count,i,parts,parts_length;
			parts=element.val().split(' ');
			parts_length=parts.length;
			count=0;
			for(i=0;i<parts_length;++i){
				if(''!==$.trim(parts[i])){
					count=count+1;
					if(2===count){
						return true;
					}
				}
			}
			return false;
		};
		mandatory_validator=function(element){
			switch(element.attr('type')){
				case 'checkbox':
					return true===element.attr('checked');
				case 'radio':
					return mandatory_radio_validator(element.attr('name'));
				default:
					return ''!==$.trim(element.val());
			}
		};
		maximum_length_validator=function(element,substitutions){
			var classes,maximum_length,name;
			maximum_length=element.attr('maxlength');
			if($(document.createElement(element.tagName())).attr('maxlength')===maximum_length){
				classes=$.trim(element.attr('class')).split(' ');
				if(0<classes.length){
					name=classes[0];
					maximum_length=parseInt(name.substr(13),10);
				}
			}
			if(true===isNaN(maximum_length)){
				return true;
			}
			substitutions.push('%d');
			substitutions.push(maximum_length);
			return element.val().length<=maximum_length;
		}
		numeric_validator=function(element){
			var value;
			value=$.trim(element.val());
			return ('NaN'!==value)&&((String(Number(value))==value)||(''===value));
		};
		expressions_and_validators=[
			{expression:'.Mandatory',validator:mandatory_validator,message:'Please fill in the %s field.'},
			{expression:'.FullName',validator:full_name_validator,message:'Please enter both first and last name in the %s field.'},
			{expression:'.EmailAddress',validator:email_validator,message:'Please enter a valid email address in the %s field.'},
			{expression:'.Numeric',validator:numeric_validator,message:'Please enter a number in the %s field.'},
			{expression:'[class^=MaximumLength],[maxlength]',validator:maximum_length_validator,message:'Please limit the number of characters in the %s field to %d.'}
		];
		valid=true;
		validation_error_messages=[];
		for(i=0;i<expressions_and_validators.length;++i){
			$(expressions_and_validators[i].expression,form).data('notified',false);
		}
		validate_and_notify=function(iteration,item){
			var alternative,element,notification,label_text,substitutions,validation_error_message;
			element=$(item);
			notification=$('label.For'+element.attr('name')+' .Notification,label[for="'+element.attr('id')+'"] .Notification').eq(0);
			if(false===element.data('notified')){
				substitutions=[];
				if(true!==expression_and_validator.validator(element,substitutions)){
					valid=false;
					alternative=element.attr('title')||notification.attr('title');
					if(('string'===typeof alternative)&&(0<$.trim(alternative).length)){
						validation_error_message=alternative;
					}else{
						label_text=$(notification.parent()).text();
						validation_error_message=expression_and_validator.message.replace('%s',label_text.substring(0,label_text.length-2));
						if(0!==substitutions.length){
							validation_error_message=validation_error_message.replace(substitutions[0],substitutions
[1]);
						}
					}
					validation_error_messages.push(validation_error_message);
					notification.removeClass('NotDisplayed');
					element.data('notified',true);
				}
				else{
					notification.addClass('NotDisplayed');
				}
			}
		};
		for(i=0;i<expressions_and_validators.length;++i){
			expression_and_validator=expressions_and_validators[i];
			$(expression_and_validator.expression,form).each(validate_and_notify);
		}
		if(true!==valid){
			alert(validation_error_messages.join('\n'));
		}
		return valid;
	});

	if ($('a.lightbox').length > 0){
		$('a.lightbox').lightBox({fixedNavigation:true});
	}

	//Call-To-Action buttons on the homepage

	var unhovered=$(".unhovered");
	var hovered=$(".hovered");
	unhovered.hover(function() {
		var me,src; 
		me=$('img',this)
		src = me.attr("src");
		src = src.substr(0,src.indexOf('.png'));
		src = src + '_hovered.png';
		$("div:has(>a>img[src$="+src+"])").fadeIn(100);
	}
	);
	$("div.hovered").mouseleave(function() {
		if ($(this).css('display')=='block') {
				$(this).fadeOut(100);
		}
	});

	$("select.Country").change(function (e) {
   		var div = $("div.state");
		if ("USA" === $("select.Country").val() || "Canada"=== $("select.Country").val()) {
			div.show()
			div.children("div:first").children("#State").addClass("Mandatory");
		}else{
			div.hide();
		}
	}).change();

	$("div#demo").children("a:first").children("img:first").click(function() {
	    imageId = $(this).attr('id');
		_gaq.push(['_trackEvent', 'Demos/Webinars', 'click', imageId]);
	});

 	$("div#whitePaper").children("a:first").children("img:first").click(function() {
	    imageId = $(this).attr('id');
		_gaq.push(['_trackEvent', 'White Papers', 'click', imageId]);
	});
  	$("div#eval").children("a:first").children("img:first").click(function() {
	    _gaq.push(['_trackEvent', 'Free Evaluation', 'click']);
	});
	$(document).ready( function() { 
		$('input[type="submit"].submitSurvey').bind("click",submitSurveyClick)
	});	
	function submitSurveyClick() {
		var validation_errors = new Array();
		var canSubmit = 1;
		var divs = $('div.Validate');
		divs.each(
			function(index) {
				if ($(this).children(':checked').size() !== 1) {
					var question = $(this).attr("id");
					question = question.split('_');
					question = question.join(" ");
					validation_errors.push('Please answer the following question: ' + question +"\n");
					canSubmit = 0;
					$("form.surveyForm").one("submit",function() {
						return false;
					});

				}
		   /* 	else {
 					
				}*/
		})
		if (validation_errors.length>0) {
			var validationNotifications = validation_errors.join("\n");
			alert(validationNotifications);
		}
		if (canSubmit === 1) {
			$("form.surveyForm").submit(function() {
				return true;
			});   			 
		}
/*		if (divs:not(:has(:radio:checked))')) {
			validation_errors.push($(this).attr('id'));
			alert(validation_errors);
		}*/
	}
});

