﻿/*
* this file is for javascript functions specific for pendaflex.
*/

pflex = {
	preinit: function() {
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, pflex.nav.changePage);
		j$('[data-link]').live('click', pflex.nav.clickDataLink);

		// initialize any js that is using dynamic publishing
		common.flash.initialize();
		common.accordion.initialize();
		common.overlayCloseText = 'Close x';
	},
	initializeHomePage: function() {
		j$('#bannerContainer').sltbanner();
		j$('#promotions .scrollable').sltscrollable();
	},
	initializeContactUs: function() {
		common.drivingDirections.initialize();
	},
	initializePrivacydefault: function() {
		j$("#privacyPolicyLink a").click(  common.privacyPolicy.showDialog );
	},
	initializeBio: function() {
		// nothing addtional to do
	}
}

pflex.about = {
	initialize:function(){
		j$("#listings").jPaginate({items:5});
	}
}

pflex.nav = {

	xhr: null,

	clickDataLink: function(event) {
		var link = j$(this).data('link');
		var baseUrl = j$(this).data('baseurl');

		// parse locale and .html extension
		link = link.substring(6, link.length);
		link = link.substring(0, link.length - 5);

		if (baseUrl != null) {
			// create expected base href
			var targetBaseUrl = document.location.protocol + '//' + document.location.hostname + baseUrl;
			if (document.location.href.indexOf(targetBaseUrl) == 0) {
				SWFAddress.setValue(link);
			} else {
				document.location = targetBaseUrl + '#/' + link;
			}

		} else {
			SWFAddress.setValue(link);
		}

		return false;
	},
	changePage: function(swfevent) {

		document.body.style.cursor = 'wait';

		var col1Selector = '.col1';
		var col2Selector = '.col2';

		// ensure this is not a result of a powerreview click
		if (swfevent.path.match(/^pr-header-/)) {
			return false;
		}

		var url = '';
		if (swfevent.path == '/') {
			url = pflex.nav.landingPagesUrls[common.ajaxSectionName];
		} else if (swfevent.path.length > 1) {
			url = '/' + locale + swfevent.path + '.html';
		}

		if (typeof url != 'undefined' && url != '') {

			// reset the navigation code
			pflex.nav.reset();

			pflex.nav.xhr = j$.get(url, function(data, textstatus) {
				var htmlResult = j$(data);
				pflex.nav.xhr == null;

				var col1Data = htmlResult.find(col1Selector);

				if (j$('.fullpage').length > 0) {
					if (j$('.fullpage', data).length > 0) {
						// going from full page to full page
						j$(col1Selector).replaceWith(col1Data);
					} else {
						// going from full page to left col page
						j$('.colmask').replaceWith('<div class="colmask leftmenu"><div class="colleft"><div class="col1"></div><div class="clear"></div><div class="col2"></div></div><div id="breadcrumb" /></div>');
						j$(col1Selector).replaceWith(col1Data);
						j$(col2Selector).replaceWith(j$(col2Selector, data));

						// initialize accordion as we have just got it from the ajax call and it wasn't there before
						common.accordion.initialize();
					}

				} else if (j$('.leftmenu')) {
					if (j$('.leftmenu', data).length > 0) {
						// going from left col page to left col page
						j$(col1Selector).replaceWith(col1Data);
					} else {
						// going from left col page to full page
						j$('.colmask').replaceWith('<div class="colmask fullpage"><div class="col1"></div><div class="clear"></div><div id="breadcrumb" /></div>');
						j$(col1Selector).replaceWith(col1Data);
					}
				}

				// update smaller areas
				j$('#breadcrumb').replaceWith(j$('#breadcrumb', data));
				document.title = 'Pendaflex | ' + j$('h1:first', data).text();

				// update global variables
				var urlparts = url.match(/\/([\w-]+)\/([\w-]+)(\/(.+))*\/([\w-]+).html/);
				common.sectionName = urlparts[2];
				common.identifier = urlparts[5];

				// update css for presentation
				if (common.identifier == 'default') {
					j$('#content').attr('class', 'page-' + common.sectionName.toLowerCase() + common.identifier.toLowerCase());
				} else {
					j$('#content').attr('class', 'page-' + common.sectionName.toLowerCase());
				}

				if (htmlResult.filter("#highResImageOverlay").length > 0) {
					var highResContent = htmlResult.filter("#highResImageOverlay").html();
					if (j$("#highResImageOverlay").length == 1) {
						j$("#highResImageOverlay").html(highResContent);
					} else {
						j$("body").append('<div style="display: none;" class="popup" id="highResImageOverlay">' + highResContent + "</div>");
					}
				}

				// set target to _blank on downloadable files so it will open in new window	
				j$.each(["doc", "xls", "ppt", "docx", "xlsx", "pptx", "dot", "zip", "pdf", "csv"], function() {
					j$('a[href$=.' + this + ']').attr("target", "_blank");
				});

				// initialize pages if necessary
				switch (common.sectionName) {
					case 'Segments':
					case 'Categories':
						{
							pflex.product.initializeProductListings();
							break;
						}
					case 'Products':
						{
							if (common.identifier != 'default') {
								pflex.product.initializeProductDetail();
							}
							break;
						}
					case 'SolutionCategory':
					case 'Solutions':
						{
							pflex.solutions.initializeSolutions();
							break;
						}
					case 'Templates':
						{
							pflex.templates.initializeTemplates();
							break;
						}
				}

				// refresh left nav accordion if necessary so correct menu item is loaded
				if (swfevent.path != '/') {
					common.accordion.refresh(url);
				}

				// TODO: trigger webtrends

				document.body.style.cursor = 'default';
			});
			
		} else {
			document.body.style.cursor = 'default';
		}
	},
	reset: function() {
		// abort any outstanding ajax calls to the server
		if (pflex.nav.xhr != null) {
			pflex.nav.xhr.abort();
			pflex.nav.xhr == null;
		}

		// clear any event queues
	},

	// this object provides the urls for the landing pages for specific sections when
	// there is not an anchor on the url
	landingPagesUrls: {
		'ProductsAjax': '/' + common.locale + '/Products/default.html',
		'SolutionsAjax': '/' + common.locale + '/Solutions/default.html',
		'TemplatesAjax': '/' + common.locale + '/Templates/Templates.html'
	}
}

pflex.product = {

	initializeProductLanding: function() {
		// nothing addtional to do
	},
	initializeProductListings: function() {

		j$('.item').each(function(index) {
			var page_id = j$(this).data('compelid');
			var pr_snippet = j$('.pr_snippet', this);

			POWERREVIEWS.display.snippet(
				{
					write: function(content) {
						j$(pr_snippet).append(content);
					}
				},
				{
					pr_page_id: page_id,
					pr_snippet_min_reviews: 1
				}
			);
		});
	},
	initializeProductDetail: function() {

		j$('.tabs').slttabs();

		j$('#relatedProducts .scrollable').sltscrollable({
			prevBtn: '.carousel-first-button',
			nextBtn: '.carousel-next-button'
		});

		var productId = j$('#productContainer').data('compelid');
		pflex.product.displayPowerReviews(productId);

		common.hires.initialize();

		var gplusOptions = { 
			"size": 'medium',
			"href" : window.location.pathname
		}
		gapi.plusone.render('plusone-product-container', gplusOptions);
	},
	displayPowerReviews: function(page_id) {
		POWERREVIEWS.display.engine(
			{
				write: function(content) {
					j$("#pr_review_summary").append(content);
				}
			},
			{ pr_page_id: page_id }
		);
		POWERREVIEWS.display.snippet(
			{
				write: function(content) {
					j$("#pr_snippet").append(content);
				}
			},
			{
				pr_page_id: page_id,
				pr_read_review: "javascript:pflex.product.showPowerReviewsTab()"
			}
		);
	},
	showPowerReviewsTab: function() {
		j$('.tab-nav .productReviews').click();
	}
}

pflex.solutions = {

	initializeSolutions: function() {

		j$('#relatedProducts .scrollable').sltscrollable({
			prevBtn: '.carousel-first-button',
			nextBtn: '.carousel-next-button'
		});
	}
}

pflex.templates = {

	initializeTemplates: function() {
		j$('#relatedProducts .scrollable').sltscrollable({
			prevBtn: '.carousel-first-button',
			nextBtn: '.carousel-next-button'
		});
	}
}

pflex.campaign = {

	initializeCampaignLanding: function() {
		// nothing addtional to do
	},
	initializeCampaign: function() {
		// nothing addtional to do
	}
}

pflex.innovations = {

	// common variables
	animationSpeed: 'slow', 	// how fast should the slide up/down move

	initializeLandingPage: function() {
		// fetch configured campaign page for better performance
		j$('[data-rel]').each(function(index, item) {
			pflex.innovations.fetchInnovationDetails(index, item)
		});

		// initialize the waterwheel carousel
		j$('#waterwheel-carousel').waterwheelCarousel({
			startingWaveSeparation: 0,
			centerOffset: 30,
			startingItemSeparation: 200,
			itemSeparationFactor: .7,
			itemDecreaseFactor: .75,
			clickedCenter: pflex.innovations.changeInnovation
		});
	},

	fetchInnovationDetails: function(index, item) {
		var url = j$(item).data('rel');
		var innovationId = j$(item).data('item');

		j$.get(url, function(data, status) {
			// do nothing...just want the pages to compile for performance
		});
	},

	changeInnovation: function(item) {

		// determine what innovation needs to be displayed
		var innovationId = j$(item).data('item');
		var title = j$(item).data('title');
		var description = j$(item).data('description');
		var showlink = j$(item).data('showlink');
		var url = j$(item).data('rel');

		// get the page from the server
		j$.get(url, function(data, status) {
			// update the innovations container
			var campaignDetails = j$(data).find('#campaignPage .mainColumnContent');
			j$('#innovations-container').html('<div id="' + innovationId + '" class="innovation" style="display:none; width: 750px;">' + j$(campaignDetails).html() + '</div>');

			var titletext = '<h2>' + title + '</h2>';
			if (description.length > 0) titletext += '<div class="description">' + description + '</div>';
			if (showlink) titletext += '<a href="' + url + '" class="moreLink">See Full Campaign</a>';

			// initialize any js that is using dynamic publishing
			common.flash.initialize();

			j$('#' + innovationId).dialog({
				title: titletext,
				modal: true,
				position: 'center',
				height: 'auto',
				width: '780px',
				dialogClass: 'innovation-overlay',
				closeText: common.overlayCloseText
			});
		});
	}
}
