$(function() {
	//Dropdown Menus
	$('.sub_menu_wrapper').hover(
		function() {
			$(this).addClass('active_hover');
			$('ul', this).stop(true, true).slideDown(100);
		},
		function() {
			$(this).removeClass('active_hover');
			$('ul', this).hide();
		}
	);

	//Modals
	var Modal = {
		init: function(modal_data)
		{
			var me = this;
			// All the videos currently in use and their YouTube hash
			this.videos = {
				 box_overview: 'IcjgqQTPFx4'
				,box_sync: 'W2UdBjGzyF4'
				,box_drag_and_drop: 'rkY7MGilQZY'
				,boxgoogle_apps: 'H_KnRwoKbJs'
				,box_salesforce: 'Gqbka1dtHOY'
				,box_preview: 'RNMBvZWL0Pw'
				,box_v5: 'WJdk2avSUWQ'
				,box_short_overview: '57CBljJ8gwE'
				,box_google_docs: 'uLHrJOiXue8'
				,box_touch_pad: 'd8siAK_IuoE'
				,box_ecm_intergration: '7Hk4Wp1RNlQ'
				,box_sync_overview: '0WPiALLABQ8'
				,box_ipad: 'cFFw-0qH1Hs'
				,box_ipad_continued: 'YzQZmzFZ1UM'
				,box_ipad_business: 'TqLlmNiDCpU'
				,box_choose_cloud: 's-AwAvQD_F0'
				,box_reinvent_sharing: 'oHam8glLuj4'
				,box_altitude: 's-ptXaRsE-8'
				,box_works_2011: '9BP9LMYRVJU'
				,platform_intro: 'Nd6E82FcgMQ'
				,platform_overview: 'I0EjSGg1nFM'
				,platform_api: '5AtPW4q3wqA'
				,cusomters_cardnial_capital: 'GE2WZv2mzLU'
				,cusomters_fuzebox: '0QJPsZt-_WA'
				,cusomters_fanminder: 'R-mQROC2t0Q'
				,cusomters_growthpoint: 'Eu3sjQn9nT0'
				,cusomters_speedfreaks: 'gmPDqx09plQ'
				,cusomters_dfj: '7ssquYK0Qg0'
				,cusomters_eveo: '7uT0XyEu3kg'
				,cusomters_clear_channel: '1cokyg9l3hA'
				,cusomters_six_flags: 'TBLhw90t_nw'
				,cusomters_pandora: '2ZrvuwLiVO4'
				,cusomters_yammer: 'bsMhjhjPnl4'
				,cusomters_balfour_beatty: 'z4SulkRlSPk'
				,cusomters_flir: 'DoJUFqqyu0s'
			};
			
			var modal_content = this.get_modal_content(modal_data);
			this.show(modal_content);
			this.hide();
		}
		/**
		 * Get modal content based on data-modal-type and data-type (video, form or html). 
		 */
		,get_modal_content: function(modal_data)
		{	
			var modal_type = modal_data.modalType;
			var modal_data_type = null;
			var identifier = null;
			var modal_content = null;
			switch (modal_type)
			{
				case 'video':
					modal_data_type = modal_data.video;
					identifier = this.videos[modal_data_type];
					var youtube_url = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.youtube.com/v/' + identifier + '&hl=en&fs=1&hd=1&autoplay=1';
					modal_content = ['<iframe id="" class="phl pvl mtl" src="' + youtube_url + '" style="width: 623px; height: 368px;" name="frameName" frameborder="0"></iframe>'].join('');
				break;
				case 'form':
					modal_data_type  = modal_data.form;
					identifier = '#' + modal_data_type + '_form';
					modal_content = $(identifier).html();
				break;
				case 'html':
					modal_data_type  = modal_data.html;
					identifier = '#' + modal_data_type + '_html';
					modal_content = $(identifier).html();
				break;
				default:
					identifier = this.videos['box_overview'];
					youtube_url = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.youtube.com/v/' + identifier + '&hl=en&fs=1&hd=1&autoplay=1';
					modal_content = ['<iframe id="" class="phl pvl mtl" src="' + youtube_url + '" style="width: 623px; height: 368px;" name="frameName" frameborder="0"></iframe>'].join('');
				break;
			}

			return modal_content;
		}
		,show: function(modal_content)
		{
			var html = [
				,'<div id="modal_wrapper" class="cntr_modal">'
				,'<div class="close sprite_16x16 sprite_16x16_grey_close"></div>'
				,'<div id="modal_content">' +  modal_content + '</div>'
				,'</div>'
				].join('');
			$(html).appendTo(document.body);
			// Get the width of the modals content.
			var modal_width = $('#modal_content').children().outerWidth();
			// Set the modal's width.
			$('#modal_wrapper').width(modal_width);
			// Position the modal in the center.
			this.set_center_position($('#modal_wrapper').get(0), 140);
			// Apply grey backdrop.  
			this.backdrop();	
		}
		,hide: function()
		{
			$('.close, #modal_backdrop').click(function()
			{
				$('#modal_backdrop').remove();	
				$('#modal_wrapper').remove();
			});
		}
		,set_center_position: function(obj, top)
		{
			var x,y;
			if (self.pageYOffset) // all except Explorer
			{
				x = self.pageXOffset;
				y = self.pageYOffset;
			}
			else if (document.documentElement && document.documentElement.scrollTop)
			// Explorer 6 Strict
			{
				x = document.documentElement.scrollLeft;
				y = document.documentElement.scrollTop;
			}
			else if (document.body) // all other Explorers
			{
				x = document.body.scrollLeft;
				y = document.body.scrollTop;
			}
			if ('undefined' == typeof(top)) top = 240;
			obj.style.top  = y + top + 'px';
			obj.style.left = document.body.clientWidth/2 - (obj.offsetWidth/2) + 'px';
		}
		,backdrop: function()
		{
			var height = Math.max($(window).height(), $(document).height());
			var width = Math.max($(window).width(), $(document).width());	
			$('<div id="modal_backdrop" class="modal_backdrop"></div>').css({'opacity':'.50','height': height, 'width':width}).appendTo('body');
		}
	};

	//Enable Modals
	$('body').delegate('[data-modal-type]', 'click', function(e)
	{
		e.preventDefault();
		Modal.init($(this).data());
		init_ajax_forms();
	});
	
	//Sidebar
	var Side_Menu = {
		// Properties and methods to be called when instantiated
	    init: function(side_menu)
	    {
	    	var me = this;
	
	    	// Store the side menu element
	    	this.j_side_menu_elm = j_side_menu_elm;
	
	    	// Define CSS selectors to be used  
	    	this.selectors = {
	    		current_menu: 'current_side_menu'
	    		,menu_items: 'side_menu_items'
	    		,toggle_arrow: 'toggle_arrow'
	    		,active_toggle_arrow: 'active_toggle_arrow'
	    		,menu_toggle: 'side_menu_toggle'
	    		,toggle_active: 'side_menu_active_toggle'
	    		,last_toggle: 'last_side_menu_header'
	    		,bottom_header: 'side_menu_header_bottom'
	    		,bottom_menu: 'side_menu_bottom'
	    	};
	
	    	// Store a new object of descendant menus 
	    	this.menu_items = this.j_side_menu_elm.find('.' + this.selectors.menu_items);
	
	    	// Store the heights of each menu item 
	    	this.menu_heights = this.get_menu_heights();
	
	    	// Attach event handler side menu element  
	    	this.j_side_menu_elm.bind('click', function(e)
	    	{
	    		// Determine if a toggle was clicked and expand menu accordingly 
	    		me.click_event(e);
	    	});
	    }
	
	    ,get_menu_heights: function()
	    {
	    	var me = this,
	    	menu_heights = {};
	    	this.menu_items.each(function(i)
	    	{
	    		var menu_id = me.selectors.menu_items + i;
	    		$(this).attr('id', menu_id);
	    		menu_heights[menu_id] = $(this).height();
	    	});
	
	    	return menu_heights;
	    }
	
	    ,expand_menu: function(j_toggle_elm) 
	    {
	    	var me = this
	    	,menu_toggle = j_toggle_elm.parent()
	    	,menu_id = menu_toggle.next().attr('id')
	    	,menu_height = this.menu_heights[menu_id]
	    	,j_menu_elm = $('#' + menu_id);
	
	
	    	if (menu_toggle.hasClass(this.selectors.bottom_header))
	    	{
	    		menu_toggle
	    			.removeClass(this.selectors.bottom_header)
	    			.addClass(this.selectors.last_toggle);
	    		j_menu_elm.addClass(this.selectors.bottom_menu);
	    	}
	    	else
	    	{
	    		$('.' + this.selectors.last_toggle).addClass(this.selectors.bottom_header);
	    	}
	
	    	menu_toggle
	    		.children('.' + this.selectors.toggle_arrow)
	    		.addClass('active_toggle_arrow');
	
	       	// To make sure showing and hiding has a smooth transition... 
	    	// The menu needs to animate to its correct height.
	    	j_menu_elm	
	    		.show()
	    		.css({'height':0})
	    		.animate({height: menu_height}, {duration: 400, complete: function()
	    		{
	    			$(this).addClass(me.selectors.current_menu);
	
	    		}});
	
	    	menu_toggle
	    		.siblings()
	    		.children('.' + this.selectors.toggle_arrow)
	    		.removeClass('active_toggle_arrow');
	
	    	j_menu_elm
	    		.siblings('.' + this.selectors.menu_items)
	    		.animate({height: 0, opacity: 'hide'},{duration: 400, complete: function()
	    		{
	    			$(this)
	    				.hide()
	    				.removeClass(me.selectors.current_menu);
	    		}});
	    }
	
	    /**
	     * Check the that the side menu header has a toggle selector and its sibling is not expanded.
	     */
	    ,click_event: function(e)
	    {
	    	var j_toggle_elm = $(e.target);
	    	if (!j_toggle_elm.parent().next('.' + this.selectors.menu_items).is(':visible') && j_toggle_elm.is('.' + this.selectors.menu_toggle))
	    	{
	    		this.expand_menu(j_toggle_elm);
	    	}
	
	    	return false; 
	    }
	};

	//Enable Sidebar
	var j_side_menu_elm = $('#side_menu_multiple');
	if (j_side_menu_elm.length)
	{
		var side_menu = Side_Menu.init(j_side_menu_elm);
	}
	
	//Twitter feed
	var url = 'http://search.twitter.com/search.json?callback=?&rpp=3&q=from:BoxHQ';

	$.getJSON(url, function(json) {
	    $.each(json.results, function(i, tweet) {
	    	var tweet = tweet.text;
	    	var expEmail = /([A-Z0-9\.\+\-_]+)@([A-Z0-9\.\-]+\.[A-Z]{2,4})/ig;
	    	var expLink = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	    	var expHandle = /@([A-Z0-9_]+)/ig;
	    	var expHashtag = /([^&])#([A-Z0-9_]+)/ig;
	    	
	    	tweet = tweet.replace(expEmail, '<a href="mailto:$1&#64;$2">$1&#64;$2</a>')
	    				 .replace(expLink, '<a href="$1">$1</a>')
	    				 .replace(expHandle, '<a href="http://twitter.com/$1">@$1</a>')
	    				 .replace(expHashtag, '$1<a href="http://twitter.com/search?q=%23$2">#$2</a>');
	    	
	    	$("#twitter_feed").append('<li class="pam">'+tweet+'</li>');
	    });
	});
	
	//Form show/hide value on focus/blur
	$('input[type="text"]').focus(function() {
		var defaultValue = $(this)[0].defaultValue;
		var formValue = $(this).val();
		if (formValue == defaultValue) {
			$(this).val('');
		}
	});
	$('input[type="text"]').blur(function() {
		var defaultValue = $(this)[0].defaultValue;
		var formValue = $(this).val();
		if (formValue == '') {
			$(this).val(defaultValue);
		}
	});
	
	//Search form disallow default search
	$('#search_button').click(function() {
		var defaultValue = $('#search')[0].defaultValue;
		var formValue = $('#search').val();
		if (formValue == defaultValue) {
			$('#search').val('').focus();
			return false;
		}
	});
	
	//Newsletter AJAX submit
	$('#newsletter_submit').click(function() {
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
 
        var emailaddress = $('#newsletter_email').val();
        if(!emailReg.test(emailaddress)) {
        	$('#newsletter_form .success').animate({ opacity: 'hide', height: 'hide' }, 'slow')
            $('#newsletter_form .error').html('Please enter a valid email.').fadeIn();
            $('#newsletter_email').focus();
            hasError = true;
        }
 
        if(hasError == true) { return false; }
        else { $('#newsletter_submit').attr('disabled', 'disabled'); }
		
		var dataString = $('#newsletter_form').serialize();  
 
		$.ajax({
			url: "/ajax/proxy.php?proxy_url=http://now.eloqua.com/e/f2.aspx",
			type: "POST",  
			data: dataString,
			success: function() {
				$('#newsletter_form .error').animate({ height: 'hide', opacity: 'hide' });
				$('#newsletter_form .success').html('Thank you for subscribing!').fadeIn('slow');
				$('#newsletter_submit').attr('disabled', 'disabled');
			}
		});
		return false;
	});
	
	init_ajax_forms();
});

function init_ajax_forms()
{
	var j_forms = $('.ajax_form');
	
	// set to true when submit to server is pending to prevent user from spam clicking
	var submit_pending = false;

	// perform visual validation on focus and blur
	j_forms.delegate('input, textarea, select', 'focus', function()
	{
		$(this).removeClass('error');
	});
	j_forms.delegate('input, textarea, select', 'blur', function()
	{
		validate_field($(this));
	});

	// validate and submit the form on click
	j_forms.delegate('.submit_button', 'click', function()
	{
		var j_form  = $(this).parents('.ajax_form');
		var j_form_fields = j_form.find('input, textarea, select').not(':hidden');

		j_form_fields.each(function()
		{
			validate_field($(this));
		});

		// do not submit if any fields have error or if a submit is already pending and not completed
		if (!submit_pending && !j_form.find('.error').length)
		{
			submit_pending = true;

			//serialize and post to the server
			var form_data = j_form.serialize();
			$.post('/box/wordpress/ajax/proxy.php?proxy_url=http://now.eloqua.com/e/f2.aspx', form_data, function()
			{
				j_form.find('.submit_success').fadeIn().focus();
				j_form_fields.val('');
				submit_pending = false;
			});
		}

		return false;
	});
}

// validate a passed form field - set an error class if an issue is found
function validate_field(j_field)
{
	var val = j_field.val();
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
	if (!val)
	{
		j_field.addClass('error');
	}
	else if(j_field.hasClass('email') && !emailReg.test(val))
	{
		j_field.addClass('error');
	}
}




