featureNav = {
	images: new Array(),
	copy: new Array(),
	keys: new Array(),
	active: false,
	suspend: false,
	player: null, // This is initialized by the "playerReady" function below
	init: function() {
		$('ul.main-nav2').hoverIntent(
			function(e) {},
			function(e) {
				if(featureNav.suspend == true) return false;
				$('.copy').removeClass('front').fadeOut();
				$('.mask').fadeOut('normal');
			}
		);
		$('ul.main-nav2').superfish({ 
	        delay:       200, 
	        speed:       'fast'
	    });		
		$("#tree").treeview({
			persist: "",
			collapsed: true
		});
		this.keys = new Array('ro1','ro2','ro3','ro4');
		for ( var i in this.keys ) {
			featureNav.images[i] = $('#' + this.keys[i] + '-img .mask');
			nav = $('#' + this.keys[i]);
			nav.hoverIntent(
				function(e) {
					if(featureNav.suspend == true) return false;
					key = e.target.id;
					featureNav.active = $('#' + key + '-img .mask');
					featureNav.active.slideUp('normal');
					copy = $('#' + key + '-copy');
					copy.addClass('front');
					copy.fadeIn('normal',function() {
						if (jQuery.browser.msie) this.style.removeAttribute('filter');
					});
					jQuery.each(featureNav.images, function(i,el) {
						thisId = $(this).attr('id');
						if(thisId != featureNav.active.attr('id')) {
							if ($.browser.msie) {
								this.show(); // IE has some flickering issues with fading in
							} else {
								this.fadeIn('fast');
							}
							
							key = featureNav.keys[i];
							$('#' + key + '-copy').hide();
						}
				    });
				},
				function(e) {
					return false;
				}
			);
		}
		$('.homeVideoPopup').toggle(
			function() {
				$('#homePageVideo, .mask').fadeIn();
				
//				if(featureNav.player) {
//				 	featureNav.player.sendEvent('PLAY','false');
//				}
		
				featureNav.suspend = true;
				$(document).bind('click',function() {
					$('.homeVideoPopup').click();
				});
				$(document).keyup(function(event) {
					if (event.keyCode == 27) {
						$('.homeVideoPopup').click();
					}
				});
				
				return false;
			},
			function() {

				$('#homePageVideo, .mask').hide();
				featureNav.suspend = false;
				featureNav.player.sendEvent('PLAY','false');
				$(document).unbind('click');
				$(document).unbind('keyup');
				return false;
			}
		);
	}
}

// Called by jwplayer object
function playerReady(thePlayer) {
	featureNav.player = document.getElementById(thePlayer.id);
	featureNav.player.sendEvent('PLAY','false');
}

var ticker = {
	timer:false, i:0, ct:0, t:3000,
	init : function(interval) {
		// initialize
		$('#news-ticker li:not(:first)').hide();
		ticker.start();
		ticker.ct = $('#news-ticker li').size();
		ticker.t = interval;
		// bind controls
		$('a.backward').click(function() {
			ticker.tick(-1).stop();
		});
		$('a.forward').click(function(){
			ticker.tick().stop();
		});
		
		// bind auto stop/start
		$('.news').hover(
			function() {
				ticker.stop();
			},
			function() {
				ticker.start();
			}
		);
	},
	stop : function() {
		clearTimeout(ticker.timer);
	},
	start : function() {
		ticker.stop();
		ticker.timer = setTimeout('ticker.tick()', ticker.t);
	},
	tick : function(steps) {
		ticker.stop();
		if(!steps) steps = 1;

		// hide current
		$('#news-ticker li:eq(' + ticker.i + ')').hide();

		// Increment the index
		ticker.i = (ticker.i + ticker.ct + steps) % ticker.ct;
		
		// Show the next one
		if($.browser.msie && $.browser.version == '6.0') { 
			$('#news-ticker li:eq(' + ticker.i + ')').animate({height:'show', width:'show'}, 500);
		} else {
			$('#news-ticker li:eq(' + ticker.i + ')').fadeIn(500);
		}
		ticker.start();
		return ticker;
	}
}

var resources = {
	dialogCreated: false,
	autoClicked: false,
	autoClickId: false,

	init: function() {
		this.initModalLinks();
	},
	initModalLinks: function() {
		// Anchor hash used to simulate click
		resourceString = location.hash;
		autoClickId = resourceString.replace(/#resource\-([0-9]{1,6})/,'$1');
		if(autoClickId) {
			resources.autoClickId = autoClickId;
		}

		// Init resource links
		$('.resourceModalLink').each(function() {
			$(this).click(function(e) {
				resourceTypePrepend = '';
				if($(this).hasClass('resourceType_video')) {
					resourceTypePrepend = 'Video: ';
				} else if($(this).hasClass('resourceType_whitePaper')) {
					resourceTypePrepend = 'White Paper: ';
				} else if($(this).hasClass('resourceType_productInformation')) {
				 	resourceTypePrepend = 'Product Information: ';
				} else if($(this).hasClass('resourceType_caseStudy')) {
					resourceTypePrepend = 'Case Study: ';
				}
				pseudoUrl = '/clicked-link/resources/' + resourceTypePrepend + $(this).attr('title');
				pageTracker._trackPageview(pseudoUrl);
				rUid = $(this).attr('rel');
				resources.initModal(rUid,'resource');
				return false;
			});
			// If the autoClickId is the same as the link we're rendering, then click it
			rUid = $(this).attr('rel');
			if(!resources.autoClicked && resources.autoClickId == rUid) {
				resources.autoClicked = true;
				$(this).click();
			}
		});
		
		// Init campaign links
		$('.campaignModalLink').each(function() {
			$(this).click(function(e) {
				rUid = $(this).attr('rel');
				resources.initModal(rUid,'campaign');
				return false;
			});
		});
	},
	submitForm: function() {
		var requiredFields = ['fFirstName','fLastName','fEmail','fPhone','fCompany'];
		valid = true;
		$.each(requiredFields,function() {
			var el = $('#'+this);
			if(el.length) { // If the field isn't present in the form, then don't validate it.
				if(el.val().length < 1) {
					valid = false;
					el.addClass('ui-state-error');
				} else {
					el.removeClass('ui-state-error');
				}
			}
		});
	
		errorContainer = $('#registrationError');
		if(valid == false) {
			if(errorContainer.is(':hidden')) errorContainer.fadeIn();
		} else {
			this.processForm();
		}
		
	},
	updateErrorMessage: function(msg) {
		errorContainer = $('#registrationError');
		if(errorContainer.is(':hidden')) errorContainer.fadeIn();
		errorContainer.html(msg);
	},
	processForm: function() {
		qArgs = $('#registrationForm').serialize();
		resources.getData(qArgs)
	},
	initVideo: function(data) {
		// 512x228
		var flashvars = {
			file: data.flv,
			autostart: true
		}
		ui.modal.dialog('option','height',430);
		ui.modal.dialog('option','width',550);
		ui.modal.dialog('option','position','center');

		var params = {
			allowfullscreen:"true"
		};
		var attributes = {
		};
		swfobject.embedSWF("fileadmin/templates/swf/contrib/longtail/player-licensed.swf", "playerContainer", "512", "312", "9.0.0",'', flashvars, params, attributes);
		
	},
	getData: function(queryArgs) {
		url = '/?type=238&handler=tx_voxwareresource_pi1';

		var async = false; // Calls that are asynchronous trigger pop up blockers in IE and FF
		
		$.ajax({
			url: url,
			async:  async,
			data: queryArgs,
			dataType: 'json',
			beforeSend: function() {
			},
			error: function(data,textStatus) {
				resources.getDataResults = data;
				resources.updateErrorMessage('Our registration system is experiencing technical difficulties. Please wait and try again in a few minutes.');
			},
			success: function(data,textStatus) {
				success = true;
				resources.getDataResults = data;
			},
			complete: function(data,textStatus) {
				resources.control(resources.getDataResults);
			}
		});

	},
	refreshDialog: function() {
		ui.modalHeight = $('#checkHeight').height() + 20;
		ui.modal.dialog('option','position','center');
		$('#dialog .closeDialog').each(function() {
			$(this).click(function() {
				ui.modal.dialog('close');
			})
		})

		// setup form submit event
		form = ui.modal.find('form');
		form.submit(function() {
			resources.submitForm();
			return false;
		})
	},
	doDownload: function(filepath) {
		window.open('/' + filepath,'Download');  
	},
	createDialog: function() {
		resources.dialogCreated = true;
		ui.modal.empty();
		ui.modal.dialog({
			title: 'Registration Required',
			width: 330,
			modal: true,
			autoOpen: false,
			resizable: false,
			close: function(event, ui) {
				window.ui.modal.dialog('destroy');
			},
			open: function(event, ui) {
			}
		});	
	},
	updateAndShowDialog: function(data) {
		ui.modal.html(data.view);
		if(data.title) ui.modal.dialog('option','title', data.title);
		if(data.type == 'video') {
			resources.initVideo(data);
		} else {
			resources.refreshDialog();
		}
		ui.modal.dialog('open');
	},
	control: function(data) {
//		console.log(data.success);
		if(data.success == true) {
			if(typeof(data.resource) !== 'undefined' && data.resource.data.file_path_combined && data.type != 'video') { 
				resources.doDownload(data.resource.data.file_path_combined);
				if(resources.dialogCreated = true) ui.modal.dialog('close');
			} else {
				resources.createDialog();
				resources.updateAndShowDialog(data);
			}
		} else {
			resources.updateErrorMessage(data.message);
		}
	},
	initModal: function(rUid,type) {
		if(type == 'resource') {
			qArgs = {
				'tx_voxwareresource_pi1[action]':'JSONDownload',
				'tx_voxwareresource_pi1[resourceId]':rUid,
				'tx_voxwareresource_pi1[autoClickId]':resources.autoClickId
			};
		} else if(type == 'campaign') {
			qArgs = {
				'tx_voxwareresource_pi1[action]':'JSONCampaignRegister',
				'tx_voxwareresource_pi1[campaignId]':rUid
			};
		}
		resources.rUid = rUid;
		resources.getData(qArgs);
	}
}

var ui = {
	init: function() {
		this.modal = $('#dialog');
	}
}

var textFields = {

	init : function() {
			
		$('label.text-hint').each(function() {
					var i = $(this).siblings();
					var l = $(this).text();
					i.attr('value', l);
					i.focus(function() {
						if(i.attr('value') == l) {
							i.attr('value', '');
						}
					}).blur(function() {
						if(i.attr('value') == '') {
							i.attr('value', l);
						}
					});
		});
	}
}

var voxware = {
	init: function() {
		featureNav.init();
		ticker.init(3500);
		ui.init();
		resources.init();
		textFields.init();
		
	}
}

$(document).ready(function() {
	voxware.init();
});

