﻿var pressroom = {
	setGlobals: function() {
		$mainWrapper = $('#main-wrapper');
		$contentWrapper = $('#content-wrapper');
		$header = $('#header');
		$nav = $('#main-nav');
		$signInForm = $('#sign-in-form');
		$curURL = document.URL;
		$remoteURL = $('#remoteContentURL').val();
	},

	signInSlider: function() {

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var menuSpeed = 500;
		var hideDelay = 500;

		$signInForm.hide();
		$('#ideafolio-sign-in-btn').click(function() {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				$signInForm.slideUp(menuSpeed, function() {
					shown = false;
					$('#ideafolio-sign-in-btn').css('background-position', '0 2px');
				});
			} else {
				// reset position of info box
				beingShown = true;
				$('#ideafolio-sign-in-btn').css('background-position', '0 -18px');
				$signInForm.slideDown(menuSpeed, function() {
					$('#sign-in-email input').focus();
					beingShown = false;
					shown = true;
				});
			}
			return false;
		});

		$('div.sign-in-form-container a#btnReset').click(function() {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function() {
				hideDelayTimer = null;
				$signInForm.slideUp(menuSpeed, function() {
					$('#ideafolio-sign-in-btn').css('background-position', '0 2px');
					shown = false;
				});

			}, 0);

			return false;
		});
	},

	// this can be loaded after critical content
	setupSubNav: function() {
		if ($('#main-nav').length) {
			var config = {
				sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
				interval: 120, // number = milliseconds for onMouseOver polling interval    
				over: function() {
					$('.subnav', $(this)).slideDown(230);
					$('select').addClass('dropped-down'); //Hide <select> tags in IE.
				}, // function = onMouseOver callback (REQUIRED)    
				timeout: 300, // number = milliseconds delay before onMouseOut    
				out: function() {
					$('.subnav', $(this)).slideUp(230);
					$('select').removeClass('dropped-down'); //Reveal <select> tags in IE.
				} // function = onMouseOut callback (REQUIRED)
			};

			$('li.main').hoverIntent(config);

			// Check whether browser is IE using feature detection
			if (jQuery.support.hrefNormalized) { // Not IE
				Cufon.replace('ul.subnav a', { hover: true, textShadow: '-1px -1px rgba(255, 255, 255, 0.4), 1px -1px rgba(255, 255, 255, 0.4), -1px 1px rgba(255, 255, 255, 0.4), 1px 1px rgba(255, 255, 255, 0.4)' });
			} else { // Is IE
				Cufon.replace('ul.subnav a');
			}
		}
	},

	setupLoggedInLinks: function() {
		// Setup logged-in/logged-out menu items
		if ($.cookie('UserLoggedIn') != null && $.cookie('UserLoggedIn') == 'true') {
			$('li.logged-out').hide();
			$('li.logged-in').show();
		} else {
			$('li.logged-out').show();
			$('li.logged-in').hide();
		}
	},

	setButtonStyles: function() {
		var $myWidth, $myHeight;
		var $myHorzPadding = 0;
		var $myVertPadding = 0;

		var $myHtml, $curButtonLink, $curButton;
		var i = 0;

		$('button.button-replacer, input.button-replacer').each(function() {
			$myHtml = $.trim($(this).html()).length == 0 ? $(this).val() : $(this).html();
			$(this).css({ 'position': 'absolute', 'width': '1px', 'height': '1px', 'top': '-2px', 'left': '0', 'border': '0 none' });
			$(this).wrap('<div class="button-replaced-container" style="position: relative; display: inline;"></div>');
			if ($(this).hasClass('arrow')) {
				$(this).after('<a href="#" class="button-replaced button-replacer arrow" id="button-replacement-' + i + '" ValidationGroup="mailingList">' + $myHtml + '</a>');
			} else {
				$(this).after('<a href="#" class="button-replaced button-replacer" id="button-replacement-' + i + '">' + $myHtml + '</a>');
			}
			$(this).attr('rel', 'button-replaced-ref-' + i);
			i++;
		});

		$('button.button-replacer-primary, input.button-replacer-primary').each(function() {
			$myHtml = $.trim($(this).html()).length == 0 ? $(this).val() : $(this).html();
			$(this).css({ 'position': 'absolute', 'width': '5px', 'height': '5px', 'top': '0', 'left': '0', 'border': '0 none' });
			$(this).wrap('<div class="button-replaced-container" style="position: relative; display: inline;"></div>');
			if ($(this).hasClass('arrow')) {
				$(this).after('<a href="#" class="button-replaced button-replacer-primary arrow" id="button-replacement-' + i + '">' + $myHtml + '</a>');
			} else {
				$(this).after('<a href="#" class="button-replaced button-replacer-primary" id="button-replacement-' + i + '">' + $myHtml + '</a>');
			}
			$(this).attr('rel', 'button-replaced-ref-' + i);
			i++;
		});

		$('a.button-replaced').each(function() {
			$curButtonLink = $(this);
			$curButtonLink.click(function() {
				var replacementId = $(this).attr('id').split('-');
				$('input[rel=button-replaced-ref-' + replacementId[replacementId.length - 1] + ']').click();
				return false;
			});
		});

		$('a.button-replacer').each(function() {
			if ($(this).hasClass('arrow')) {
				$(this).append('<span class="button-arrow"></span>');
				$(this).css('padding-right', '14px');
			};
		});

		$('a.button-replacer-primary').each(function() {
			if ($(this).hasClass('arrow')) {
				$(this).append('<span class="button-arrow"></span>');
				$(this).css('padding-right', '14px');
			};
		});
		
		$('h1').each(function() {
			$(this).click(function(){
				return false;
			});
		});
	},

	activateCufon: function() {
		var $buttonReplacers = $('a.button-replacer').not('.project-dropdown a.button-replacer'), $h2s = $('h2').not('.colorbox-inline-content h2'), $h3s = $('h3').not('#hardware-window-bottom h3, h3.article-title');
		Cufon.replace('h1', { textShadow: '2px 2px rgba(0,0,0,0.1), 1px 1px rgba(0,0,0,0.2)', fontFamily: 'Helvetica Neue' });
		Cufon.replace($h2s, { fontFamily: 'Helvetica Neue' });
		Cufon.replace($h3s, { fontFamily: 'Helvetica Neue' });
		Cufon.replace('h3.inline-heading', { fontFamily: 'Helvetica Neue' });
		//Cufon.replace('ul#footer-nav a', { hover: true, fontFamily: 'Helvetica Neue' });
		Cufon.replace('#footer-site-links-title', { fontFamily: 'Helvetica Neue' });
		Cufon.replace('h3.your-style strong', { textShadow: '2px 2px rgba(0,0,0,0.1), 1px 1px rgba(0,0,0,0.2)', fontFamily: 'Helvetica Neue' });
		Cufon.replace($buttonReplacers, { fontFamily: 'Helvetica Neue', textShadow: '1px 1px rgba(0, 0, 0, 0.3), 0 1px rgba(0, 0, 0, 0.3), 1px 0 rgba(0, 0, 0, 0.3)' });
		Cufon.replace('a.button-replacer-primary', { fontFamily: 'Helvetica Neue', textShadow: '1px 1px rgba(0, 0, 0, 0.3), 0 1px rgba(0, 0, 0, 0.3), 1px 0 rgba(0, 0, 0, 0.3)' });
		Cufon.replace('h4', { fontFamily: 'Helvetica Neue' });
	},

	/*
	* initialize login click handler for global login control
	*/
	loginConfig: function() {
		$('#loginErrorMsg').hide();
		$('#loginMsg').hide();

		pressroom.initLoginClick('login-email', 'login-password', 'loginMsg', 'loginErrorMsg');
	},

	/*
	* bind the login click event for the login control or registration page
	*/
	initLoginClick: function(emailId, passwordId, loginMsg, loginErrorMsgId, jsonUrl) {
		$('.login-submit').bind('click', { emailId: emailId, passwordId: passwordId, loginMsg: loginMsg, loginErrorMsgId: loginErrorMsgId }, pressroom.loginClick);
	},

	/*
	* login click action, performs JSON call that either displays 
	* a message if there is an error or redirects the user to the 
	* scrapbook page if it is successful.
	*/
	loginClick: function(event) {
		var email = $('.' + event.data.emailId).val();
		var password = $('.' + event.data.passwordId).val();

		/* add local scoped variables for event data, IE does not recognize the event data within the getJSON callback */
		var loginErrorMsgId = event.data.loginErrorMsgId;
		var loginMsg = event.data.loginMsg;

		// Loop through fields on this form and check if valid.
		var isValid = true;
		$.each($('.validation-login'), function() {
			if (!$(this).valid()) {
				isValid = false;
			}
		});

		if (isValid) {
			var jsonArgs = {};
			jsonArgs['globalLogin_Email'] = email;
			jsonArgs['globalLogin_Password'] = password;
			jsonArgs['nocache'] = (new Date()).getTime();

			$.getJSON($remoteURL + '/ideafolio/login-submit.html?jsoncallback=?', jsonArgs, function(data) {
				if (data.IsValid) {
					$.cookie('UserLoggedIn', 'true', { expires: 1, path: '/', domain: pressroom.getDomain() });
					$('#' + loginErrorMsgId).hide();
				} else {
					$.cookie('UserLoggedIn', null, { expires: 1, path: '/', domain: pressroom.getDomain() });
					$('#' + loginErrorMsgId).show();
					$('#' + loginErrorMsgId).text(data.Message);
				}

				// Hide/display logged in items
				pressroom.setupLoggedInLinks();
				$('#' + loginMsg).hide();
			});
		}

		event.preventDefault();
},
	/*
	* initialize forgot password click handler for global login control
	*/
	forgotPasswordConfig: function() {
		$('#loginErrorMsg').hide();
		$('#loginMsg').hide();

		pressroom.initForgotPasswordClick('forgotPass', 'login-email', 'loginMsg', 'loginErrorMsg');
	},

	/*
	* bind the forgot password click event for the login control or registration page
	*/
	initForgotPasswordClick: function(forgotPasswordId, emailId, loginMsg, loginErrorMsgId) {
		$('#' + forgotPasswordId).bind('click', { emailId: emailId, loginMsg: loginMsg, loginErrorMsgId: loginErrorMsgId }, pressroom.forgotPasswordClick);
	},

	/*
	* forgot password click action that makes a JSON call and 
	* displays either a confirmation or error message.
	*/
	forgotPasswordClick: function(event) {
		var email = $('.' + event.data.emailId).val();

		var jsonArgs = {};
		jsonArgs["email"] = email;
		jsonArgs['nocache'] = (new Date()).getTime();

		$.getJSON($remoteURL + '/ideafolio/forgot-password-submit.html?jsoncallback=?', jsonArgs, function(data, status) {
			if (data.IsValid) {
				$('#' + event.data.loginErrorMsgId).hide();
				$('#' + event.data.loginMsg).show();
				$('#' + event.data.loginMsg).text(data.Message);
			} else {
				$('#' + event.data.loginMsg).hide();
				$('#' + event.data.loginErrorMsgId).show();
				$('#' + event.data.loginErrorMsgId).text(data.Message);
			}
		});

		event.preventDefault();
	},

	/*
	* logout click event that will update the cookie flag "UserLoggedIn". This flag is used
	* by the Merillat Pressroom to determine if the user is logged in.
	*/
	logoutConfig: function() {
		$('#idea-folio-sign-out-btn').click(function() {
			$.cookie('UserLoggedIn', null, { expires: 1, path: '/', domain: pressroom.getDomain() });
		});
	},

	/* 
	* This function is used to retrieve the domain information, which will be used to
	* set up the cookie for "UserLoggedIn".
	*/
	getDomain: function() {
		var domainFields = document.domain.split('.');
		return domainFields.length == 1 ? null : '.' + domainFields[domainFields.length - 2] + '.' + domainFields[domainFields.length - 1];
	},

	setValidations: function() {
		if ($("#aspnetForm").length > 0) {
			// Initialize validation on the entire ASP.NET form.
			$("#aspnetForm").validate({
				// This prevents validation from running on every
				//  form submission by default.
				onsubmit: false
			});
		};

		if ($('.validationGroup .causesValidation').length > 0) {
			// Search for controls marked with the causesValidation flag 
			//  that are contained anywhere within elements marked as 
			//  validationGroups, and wire their click event up.
			$('.validationGroup .causesValidation').click(pressroom.ValidateAndSubmit);

			// Select any input[type=text] elements within a validation group
			//  and attach keydown handlers to all of them.
			$('.validationGroup :text').keydown(function(event) {
				// Only execute validation if the key pressed was enter.
				if (event.keyCode == 13) {
					pressroom.ValidateAndSubmit(event);
				}
			});
		}
	},

	ValidateAndSubmit: function(event) {
		// Ascend from the button that triggered this click event 
		//  until we find a container element flagged with 
		//  .validationGroup and store a reference to that element.
		var $group = $(event.currentTarget).parents('.validationGroup');

		var isValid = true;

		// Descending from that .validationGroup element, find any input
		//  elements within it, iterate over them, and run validation on 
		//  each of them.
		$group.find(':input').each(function(i, item) {
			if (!$(item).valid())
				isValid = false;
		});

		// If any fields failed validation, prevent the button's click 
		//  event from triggering form submission.
		if (!isValid)
			event.preventDefault();
	},

	/*
	* handler to highlight search terms globally on the page.
	*/
	highlightSearchTerms: function() {
		var getUrlParam = function(name) {
			var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.search);
			if (!results) { return ''; }
			return results[1] || '';
		};

		var searchTerm = decodeURIComponent(getUrlParam('query'));
		if (searchTerm && searchTerm != '') {
			searchTerm = searchTerm.replace(/\+/g, ' ');

			$(document).SearchHighlight({
				style_name: 'searchhighlight',
				exact: 'whole',
				style_name_suffix: false,
				keys: searchTerm,
				min_length: 3,
				highlight: '#content-wrapper',
				nohighlight: '.search-phrase, select option, ul.media-options, .content-navigation, #mailing-list'
			});
		}		
	},

	sideNavSetup: function() {
		$('ul.secondary-nav-list').hide();
		$('body.news-releases .content-navigation li a.selected').siblings('ul.secondary-nav-list').show();
		$('body.news-releases .content-navigation li a.selected').siblings('span.arrow-link').addClass('arrow-link-down');
		$('body.featured-stories .content-navigation li a.selected').siblings('ul.secondary-nav-list').show();
		$('body.featured-stories .content-navigation li a.selected').siblings('span.arrow-link').addClass('arrow-link-down');
		$('body.sustainability .content-navigation li a.selected').siblings('ul.secondary-nav-list').show();
		$('body.sustainability .content-navigation li a.selected').siblings('span.arrow-link').addClass('arrow-link-down');
		$('body.sustainability .content-navigation li a.selected').parent().parent().show();
		$('body.sustainability .content-navigation li a.selected').parent().parent().siblings('span.arrow-link').addClass('arrow-link-down');

		$('.content-navigation span.arrow-link').click(function() {
			if ($(this).siblings().length > 0) {
				var secondaryNav = $(this).siblings('ul.secondary-nav-list');
				$(secondaryNav).slideToggle(200);
				$(this).toggleClass('arrow-link-down');
			}
		});
	},

	noResults: function() {
		if ($('#photo-carousel-inner li#no-results').length > 0) {
			$('#photo-carousel span.next').addClass('disabled');
		}

		if ($('body.image-gallery #photo-carousel-inner ul li').length < 4) {
			$('#photo-carousel span.next').addClass('disabled');
		}

		if ($('body.news-releases #article-photo-carousel-inner ul li').length < 5) {
			$('#article-photo-carousel span.next').addClass('disabled');
		}
		
		if ($('body.news-releases #article-resources-carousel-inner ul li').length < 6) {
			$('#article-resources-carousel span.next').addClass('disabled');
		}
	},
	
	removeFlashFromClosingIframe: function() {
        $().bind('cbox_cleanup', function() {
            $('#cboxIframe').contents().find('object, embed').remove();
			alert('removed');
        });
    }
}

$(document).ready(function() {
	lib.externalLinks();
	lib.fileLinks();
	pressroom.setGlobals();
	pressroom.signInSlider();
	pressroom.setButtonStyles();
	pressroom.activateCufon();
	pressroom.loginConfig();
	pressroom.forgotPasswordConfig();
	pressroom.logoutConfig();
	pressroom.setValidations();
	pressroom.highlightSearchTerms();
	pressroom.sideNavSetup();
	pressroom.noResults();
	pressroom.removeFlashFromClosingIframe();

    $('#fbLogin').click(function () {
        FB.login(function (response) {
            if (response.session) {
                $.ajax({
                    url: $remoteURL + '/ideafolio/facebook-login-json.html',
                    data: response.session,
                    dataType: 'jsonp',
                    jsonp: false,
                    success: function (data) {
                        if (data.LoggedIn) {
                            $.cookie('UserLoggedIn', 'true', { expires: 1, path: '/', domain: pressroom.getDomain() });
                        }
						
						// Hide/display logged in items
						pressroom.setupLoggedInLinks();
                    }
                });

            } else {
                // user cancelled login
            }
        }, { perms: "email" });
    });
});
