// onload
$(function() {
	// capture campaign id's across site for use in form submissions
	var cid = $.url.param('Campaign_ID')

	if(cid != '') {
		// set cookie
		$.cookie('cid', cid, {
			expires: 30,
			path: '/'
		});
	}

	addFooterToggle();
	addUniformStyles();
	addFormEventsAndValidation();

	$('.opener').each(function() {
		var opener = $(this);
		var container = opener.parent('div');

		var content = $(this).siblings('.power-content');
		var height = content.height();
		container.toggleClass('collapsed expanded');
		content.css({
			height: 0
		});

		opener.click(function () {
			var h = container.hasClass('collapsed') ? height : 0;
			content.animate({
					height: h
				},
				'slow',
				function() {
					container.toggleClass('collapsed expanded');
				}
			);
			return false;
		});
	});

	// set current lang on site selector
	var classes = $(document.body).attr('class').split(' ');
	var select = $('#country-select');
	for (var i = 0; i < classes.length; i++) {
		var options = select.find('.' + classes[i]);
		if (options.length) {
			options.attr('selected', true);
			$('#footer-site-picker').find('.' + classes[i]).remove();
			break;
		}
	}

	// add reloads to site pickers
	var select = new PseudoSelect($('#country-select select'));
	select.change(function () {
		var site = $(this).data('value');
		if (site != '') {
			document.location.href = site;
		}
	});

	$('#footer-site-picker select').change( function() {
		site = $(this).find('option:selected').val();
		if(site != '') {
			document.location.href = site;
		}
	});

	$('#sidenav .subnav').submenu();

	$('a[rel=lightbox]').fancybox({
		overlayColor: '#483030',
		overlayOpacity: '0.8'
	});
});

$.fn.submenu = function () {
	var init = function (submenu) {
		var $submenu = $(submenu);
		var $parent = $submenu.parent()
		var $toggler = $submenu.siblings('a');
		var active = ($submenu.find('li.on').length > 0 || $submenu.parent().hasClass('on'));

		if (active) {
			$parent.addClass('expanded');
			return;
		}

		$parent.addClass('collapsed');

		// hide it
		var speed = 400;
		var height = $submenu.height();
		$submenu.css({
			height: 0,
			overflow: 'hidden'
		});

		$toggler.hover(function () {
			$parent.toggleClass('expanded collapsed');
			$submenu.animate({
					'height': height
				},
				speed
			);
		});
	}

	var $elements = $(this);
	for (var i = 0; i < $elements.length; i++) {
		init($elements[i]);
	}
}


function addFooterToggle() {
	if ($.cookie('footer-cookie')) {
		// closed
		$('#footer div.collapsable').css('display', 'none');
		$('#footer-toggle').toggleClass('min max');
	}

	$('#footer-toggle').click( function() {
		var $anchor = $(this);
		$('#footer div.collapsable').toggle('slow', function() {
			// switch class and text for anchor
			$anchor.toggleClass('min max');

			var hidden = $(this).is(':hidden') ? 1 : 0;
			var text = hidden ? maxFooterText : minFooterText;
			$anchor.text(text);
			if (hidden) {
				$.cookie('footer-cookie', 1, {
					expires: 30,
					path: '/'
				})
			}
			else {
				$.cookie('footer-cookie', 1, {
					expires: -1,
					path: '/'
				});
			}
		});
		footerScrollBottom();
		return false;
	});
}

function footerScrollBottom() {
	// scroll to bottom
	if ($('#footer-toggle').hasClass('max')) {
		var height = $(document).height();
		window.scrollTo(0, height);
		setTimeout('footerScrollBottom()', 10);
	}
}

function addUniformStyles() {
	$('#footer-site-picker select').uniform();
	$('#contactform select').uniform();
	$('#resourceform select').uniform();
	$('#eventform select').uniform();

}

// see http://docs.jquery.com/Plugins/Validation
function addFormEventsAndValidation() {
	/**
	 * Contact Pages
	**/
	// move action from hidden field to form param
	$theForm = $('#contactform');
	$theForm.attr('action', $theForm.find('input[name=url]').val());

	// capture campaign id
	var cid = $.cookie('cid');

	// add campaign id from cookie if it exists
	if(cid) {
		$theForm.find('input[name=Campaign_ID]').val(cid);
	}

	// add validation
	$theForm.validate({
		errorPlacement: function() {
			// override default so errors aren't shown on labels. Still add error class
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				$(this).find("div.form-errors").html(formValidationMessage).show();
			} else {
				$(this).find("div.form-errors").hide();
			}
		}
	});

	/**
	 * Newsletter form in page footer
	**/
	$theForm = $('#newsletterform');

	// add campaign id from cookie if it exists
	if(cid) {
		$theForm.find('input[name=Campaign_ID]').val(cid);
	}

	$theForm.find('input[type=submit]').ajaxStart(function() {
		$(this).val(formSendingMessage);
	});

	$theForm.find('input[type=submit]').ajaxComplete(function() {
   		$(this).val(formSuccessMessage);
	});

	// add validation
	$theForm.validate({
		showErrors: function(errorMap, errorList) {
			// override default so errors aren;t shoen on labels
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				$(this).find("div.form-errors").html(formValidationMessage).show();
			} else {
				$(this).find("div.form-errors").hide();
			}
		},
		submitHandler: function(form) {
			var $form = $(form);
			var url = $form.find('input[name=url]').val();
			var data =  $form.serialize();

			$.ajax({
				type: 'GET',
				url: url,
				data: data
			});

			// clear form
			$(':input',$form)
			 .not(':button, :submit, :reset, :hidden')
			 .val('')
			 .removeAttr('checked')
			 .removeAttr('selected');

			return false;
		}
	});

	/**
	 * Resources pop-up registration
	**/
	// handle protected downloads if no reg form has yet been submitted
	if ($.cookie('resource-registered')) {
		return;
	}

	// if user hasn't registered, then protect all links. We switch the href to
	// show pop up reg form. Once form is sent, we swtich back, activate the
	// resource link and set the cookie
	$('.resource-piece a.protected').each( function() {
		var $link = $(this);
		// set actual href as data
		$link.data('href', $link.attr('href'));
		// replace href with pop up
		$link.attr('href', '#resourceform');

		// bind link to form
		$link.fancybox({
			overlayColor: '#483030',
			overlayOpacity: '0.8'
		});

		// store ref to clicked link for use later
		$link.click( function() {
			$.data(document.body, 'selectedLink', $(this).data('href'));
		});
	});

	$theForm = $('#resourceform');

	// add campaign id from cookie if it exists
	if(cid) {
		$theForm.find('input[name=Campaign_ID]').val(cid);
	}

	$theForm.find('input[type=submit]').ajaxStart(function() {
		$(this).val(formSendingMessage);
	});

	// add validation
	$theForm.validate({
		errorPlacement: function(errorMap, errorList) {
			// override default so errors aren't shown on labels
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				$(this).find("div.form-errors").html(formValidationMessage).show();
			} else {
				$(this).find("div.form-errors").hide();
			}
		},
		submitHandler: function(form) {
			var $form = $(form);
			var url = $form.find('input[name=url]').val();
			var data =  $form.serialize();

			$.ajax({
				type: 'GET',
				url: url,
				data: data
			});

			// set URLs back on the links
			$('a.protected').each( function() {
				var $link = $(this);
				$link.attr('href', $link.data('href'));

				// unbind fancybox from link
				$link.unbind();
			});

			// replace form with selected link
			$download = $('<p><a class="download" href="' +$.data(document.body, 'selectedLink') + '" onclick="javascript:$.fancybox.close();" target="_blank">' + downloadMessage + '</a></p>')
				.hide()
				.insertAfter('#demo-form-wrapper');

				$('#resourceform').animate( {marginBottom: 0}, 100, function() {
					$('#demo-form-wrapper').slideUp( function() {
						$download.fadeIn();
					});
				});

			// set cookie
			$.cookie('resource-registered', 1, {
				expires: 30,
				path: '/'
			});

			return false;
		}
	});

	/**
	 * Events pop-up registration
	**/
	// handle protected downloads if no reg form has yet been submitted
	if ($.cookie('event_registered')) {
		return;
	}

	// if user hasn't registered, then protect all links. We switch the href to
	// show pop up reg form. Once form is sent, we swtich back, activate the
	// resource link and set the cookie
	$('.event-piece a.protected').each( function() {
		var $link = $(this);
		// set actual href as data
		$link.data('href', $link.attr('href'));
		// replace href with pop up
		$link.attr('href', '#eventform');

		// bind link to form
		$link.fancybox({
			overlayColor: '#483030',
			overlayOpacity: '0.8'
		});

		// store ref to clicked link for use later
		$link.click( function() {
			$.data(document.body, 'selectedLink', $(this).data('href'));
		});
	});

	$theForm = $('#eventform');

	// add campaign id from cookie if it exists
	if(cid) {
		$theForm.find('input[name=Campaign_ID]').val(cid);
	}

	$theForm.find('input[type=submit]').ajaxStart(function() {
		$(this).val(formSendingMessage);
	});

	// add validation
	$theForm.validate({
		errorPlacement: function(errorMap, errorList) {
			// override default so errors aren't shown on labels
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				$(this).find("div.form-errors").html(formValidationMessage).show();
			} else {
				$(this).find("div.form-errors").hide();
			}
		},
		submitHandler: function(form) {
			var $form = $(form);
			var url = $form.find('input[name=url]').val();
			var data =  $form.serialize();

			$.ajax({
				type: 'GET',
				url: url,
				data: data
			});

			// set URLs back on the links
			$('a.protected').each( function() {
				var $link = $(this);
				$link.attr('href', $link.data('href'));

				// unbind fancybox from link
				$link.unbind();
			});

			// replace form with selected link
			$download = $('<p><a class="download" href="' +$.data(document.body, 'selectedLink') + '" onclick="javascript:$.fancybox.close();">' + eventLinkMessage + '</a></p>')
				.hide()
				.insertAfter('#event-form-wrapper');

				$('#eventform').animate( {marginBottom: 0}, 100, function() {
					$('#event-form-wrapper').slideUp( function() {
						$download.fadeIn();
					});
				});

			// set cookie
			$.cookie('event-registered', 1, {
				expires: 30,
				path: '/'
			});

			return false;
		}
	});

	/**
	 * Newsletter pop-up registration
	**/
	$('.newsletter-sign-up a')
		.attr('href', '#newsletterpopupform')
		.fancybox({
			overlayColor: '#483030',
			overlayOpacity: '0.8'
		});

		$theForm = $('#newsletterpopupform');

		// add campaign id from cookie if it exists
		if(cid) {
			$theForm.find('input[name=Campaign_ID]').val(cid);
		}

		$theForm.find('input[type=submit]').ajaxStart(function() {
			$(this).val(formSendingMessage);
		});

		// add validation
		$theForm.validate({
			errorPlacement: function(errorMap, errorList) {
				// override default so errors aren't shown on labels
			},
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					$(this).find("div.form-errors").html(formValidationMessage).show();
				} else {
					$(this).find("div.form-errors").hide();
				}
			},
			submitHandler: function(form) {
				var $form = $(form);
				var url = $form.find('input[name=url]').val();
				var data =  $form.serialize();

				$.ajax({
					type: 'GET',
					url: url,
					data: data
				});

				// replace form with message
				$download = $('<p>' + newsletterRegMessage + '</p>')
					.hide()
					.insertAfter('#newsletterpopup-form-wrapper');

					$('#newsletterpopupform').animate( {marginBottom: 0}, 100, function() {
						$('#newsletterpopup-form-wrapper').slideUp( function() {
							$download.fadeIn();
						});
					});

				return false;
			}
		});
}

/*
jQuery Url Plugin
	* Version 1.0
	* 2009-03-22 19:30:05
	* URL: http://ajaxcssblog.com/jquery/url-read-get-variables/
	* Description: jQuery Url Plugin gives the ability to read GET parameters from the actual URL
	* Author: Matthias Jäggli
	* Copyright: Copyright (c) 2009 Matthias Jäggli under dual MIT/GPL license.
*/
(function ($) {
	$.url = {};
	$.extend($.url, {
		_params: {},
		init: function(){
			var paramsRaw = "";
			try{
				paramsRaw =
					(document.location.href.split("?", 2)[1] || "").split("#")[0].split("&") || [];
				for(var i = 0; i< paramsRaw.length; i++){
					var single = paramsRaw[i].split("=");
					if(single[0])
						this._params[single[0]] = unescape(single[1]);
				}
			}
			catch(e){
				//alert(e);
			}
		},
		param: function(name){
			return this._params[name] || "";
		},
		paramAll: function(){
			return this._params;
		}
	});
	$.url.init();
})(jQuery);
