﻿/*
 * this file is for common javascript functions used by all websites.  if the feature is specific to a 
 * particular website then it should go in the site specific js file (ie pflex.js)
 */

common = {
	// define global variables
	site: '',
	locale: 'enUS',
	sectionName: '',
	identifier: '',

	// variable to identify what section we are in when doing ajax
	// so landing page can be looked up
	ajaxSectionName: '',

	// static text strings
	overlayCloseText: 'hide',

	preinit: function() {
		common.site = site;
		common.locale = locale;
		common.sectionName = sectionName;
		common.identifier = identifier;
		common.ajaxSectionName = sectionName;
	}
}
common.privacyPolicy = {


	showDialog: function(evt) {

		j$('#privacyPolicyOverlay').dialog({
			modal: true,
			position: 'center',
			width: 800,
			height: 600,
			/*title: title,*/
			closeText: common.overlayCloseText
		});
		
		return false;
	}
}
common.drivingDirections = {

	initialize: function() {
		j$("a[data-location]").live('click', common.drivingDirections.showDirectionsDialog);
		j$("#messageOverlay .submitArrow").live('click', common.drivingDirections.showDrivingDirections);
	},

	showDrivingDirections: function(event) {

		var toAddress = j$("#messageOverlay #toAddress").val();
		var fromAddress = j$("#messageOverlay #txtLocationID").val();
		j$('#messageOverlay').dialog('close');

		openPopup(encodeURI('../DrivingDirections/default.html?title='
			+ document.title + '&to=' + common.string.trimWhitespace(toAddress) + '&from=' + common.string.trimWhitespace(fromAddress))
		);

		return false;
	},

	showDirectionsDialog: function(event) {

		var drivingLocation = j$(this).data("location");

		j$("#messageOverlay form #toAddress").val(drivingLocation);

		var title = 'Driving Directions';

		if (j$("#messageOverlay .dialog-title").length > 0) {
			title = j$("#messageOverlay .dialog-title").text();
		}

		j$('#messageOverlay').dialog({
			modal: true,
			position: 'center',
			height: 'auto',
			minHeight: 100,
			width: 400,
			title: title,
			closeText: common.overlayCloseText
		});

		return false;
	}
};
common.scrollable = {

	initialize: function() {
		j$('#relatedProducts .scrollable').sltscrollable({
			prevBtn: '.carousel-first-button',
			nextBtn: '.carousel-next-button'
		});
	}
}

common.hires = {

	/*
	* highRes overlay functions
	*/
	initialize: function() {

		// determine if there are any high res images for the product
		var highResExist = false;
		if (j$("ul#galleryViewItems li").length > 0) {
			highResExist = true;
		}

		j$(".variationsTab tbody tr td.colorSwatch").each(function(idx, item) {
			// find the img info and make sure there is a high res image to display.
			// if not, then don't enable link
			var highresImg = j$(item).parent().data('highres');
			if (highresImg.length > 0) {
				if (site.toLowerCase() == 'pflex' || (site.toLowerCase() == 'esseltenextgen' && locale == 'enCA')) {
					j$(item).click(common.hires.handlePflexVariationClick);
				} else {
					j$(item).click(common.hires.handleVariationClick);
				}

				j$(item).hover(function() {
					j$(this).css('cursor', 'pointer');
				}, function() {
					j$(this).css('cursor', 'default');
				});

				j$('div', item).hover(function() {
					j$(this).css('text-decoration', 'underline');
				}, function() {
					j$(this).css('text-decoration', 'none');
				});
			}
		});

		if (highResExist) {
			var galleryItemsLength = j$("ul#galleryViewItems li").length;
			if (galleryItemsLength == 1) {
				j$("#highResImageOverlay").addClass("singleThumbnail");
			}

			// initialize the galleryview component
			var panelSize = 600;
			if (site == 'pflex' || site == 'xyron') {
				panelSize = 500;
			}

			// parameter in galleryView to check if the window is loaded
			// a hack to override the value so that buildGallery function in galleryView will be called to render
			window_loaded = true;

			j$('#galleryViewItems').galleryView({
				nav_theme: site,
				panel_width: panelSize,
				panel_height: panelSize,
				frame_width: 65,
				frame_height: 65,
				frame_start: 1,
				filmstrip_size: 7,
				overlay_opacity: 0.5,
				pause_on_hover: true,
				transition_interval: 5000,
				transition_speed: (j$("ul#galleryViewItems li").length == 1) ? 0 : 800
			});

			// this blocks the images and the icons in UI.
			j$('#galleryViewItems .loader').remove();
			
			// initialize click events on image and link
			j$('#prodImage img').click(common.hires.handleClickEvent)
				.hover(
					function() {
						j$(this).css('cursor', 'pointer');
					}, function() {
						j$(this).css('cursor', 'default');
					});
			j$('#highResImageLink').click(common.hires.handleClickEvent).show();
		}
	},

	handleClickEvent: function(event) {
		var sku = j$('#productContainer').data('sku');
		common.hires.show(sku);
	},

	handlePflexVariationClick: function(event) {

		// find the product image for the select variation and open overlay to that image
		var sku = j$(this).parent().data('sku');
		common.hires.show(sku);
	},

	handleVariationClick: function(event) {

		var sku = j$(this).parent().data('sku');
		var prodImage = j$(this).parent().data('prodimage');
		var hiresImage = j$(this).parent().data('highres');
		var eancode = j$(this).parent().data('eancode');

		j$("#details .sku .value").text(sku);
		j$("#prodImage img").attr('src', prodImage);
		j$("#highResImageOverlay ul.filmstrip li:first-child img").attr("src", hiresImage);
		j$("#highResImageOverlay div.panel:first-child img").attr("src", hiresImage);

		// Updating the Commerce connector button link with clicked variation 'eanCode'
		if (j$("#details .commerceConnectorDiv a").length > 0) {
			var ccHREF = j$("#details .commerceConnectorDiv a").attr("href").split('?eanCode=')[0] + "?eanCode=" + eancode;
			j$("#details .commerceConnectorDiv a").attr("href", ccHREF);
		}
	},

	show: function(item) {

		j$('#highResImageOverlay').dialog({
			modal: true,
			position: 'center',
			height: 'auto',
			width: 640,
			closeText: common.overlayCloseText,
			open: function(event, ui) {
				// initialize the galleryview component
				j$('li[alt="img-' + item + '"]').click();
			}
		});
	}
}

common.flash = {

	initialize: function() {
		// initialize any js that is using dynamic publishing
		j$('[data-flashinfo]').each(function(index, item) {
			var flashinfo = j$(item).data('flashinfo');
			var id = j$(item).attr('id');
			swfobject.embedSWF(flashinfo.movieFile, id, flashinfo.width, flashinfo.height, '9.0.0', 'expressInstall.swf', flashinfo.flashvars, flashinfo.params, flashinfo.attributes);
		});
	}
}

common.video = {

	initialize: function() {
		j$('div.video').click(function(event) {
			var file = j$(this).data("file");
			common.video.showVideo(file);
		}); 
	},
	showVideo: function(videoUrl) {
	
		var title = 'Video Player'; 
		if( j$("#videoPlayer h2").length > 0 ){
			title = j$("#videoPlayer h2").text();
		}
		
		j$('#videoPlayer').dialog({
			modal: true,
			position: 'center',
			height: 'auto',
			width: '590px',
			minHeight: '400px',
			closeText: common.overlayCloseText,
			title: title
		});
		
		wimpyConfigs.playlist = videoUrl;
		makeWimpyPlayer(wimpyConfigs);
	}
}

common.accordion = {

	initialize: function() {

		j$('.accordion').accordion({
			autoHeight: false,
			change: function(event, ui) {
				ui.oldHeader.parent().removeClass('selected');
				ui.oldHeader.parent().find('.selected').removeClass('selected');
				ui.newHeader.parent().addClass('selected');
			}
		});

		j$('.submenu li').click(function(event) {
			j$('.submenu li').removeClass('selected');
			j$(this).addClass('selected');
		});
	},

	refresh: function(url) {

		var menuitems = j$('#leftNav [data-link="' + url + '"]');
		if (menuitems.length == 0) {
			// this is a bottom level item not in the menu, try to find it's parent in the menu instead
			var urlparts = url.match(/(\/[a-z]{2}[A-Z]{2}\/)([\w-]+)(\/.+)(\/)/);
			if (urlparts != null) {
				menuitems = j$('#leftNav [data-link$="' + urlparts[3] + '.html"]');
			}
		}

		if (menuitems.length > 0) {
			// only process first item in case there are dups
			var firstitem = menuitems[0];
			if (firstitem.tagName == 'LI') {
				// this is a leaf menu item
				j$(firstitem).addClass('selected');

				// activate the leaf's grandparent accordion item
				var menu = j$(firstitem).parents('ul')[2];
				var menuitem = j$(firstitem).parents('li')[1];
				j$(menu).accordion("option", "active", j$(menuitem).parent().children('li').index(menuitem));

				// activate the leaf's parent accordion item
				menu = j$(firstitem).parents('ul')[1];
				menuitem = j$(firstitem).parents('li')[0];
				j$(menu).accordion("option", "active", j$(menuitem).parent().children('li').index(menuitem));

			} else if (firstitem.tagName == 'H4') {
				// activate the top level accordion
				var menu = j$(firstitem).parents('ul')[1];
				var menuitem = j$(firstitem).parents('li')[1];
				j$(menu).accordion("option", "active", j$(menuitem).parent().children('li').index(menuitem));

				// activate the second level accordion
				menu = j$(firstitem).parents('ul')[0];
				menuitem = j$(firstitem).parents('li')[0];
				j$(menu).accordion("option", "active", j$(menuitem).parent().children('li').index(menuitem));

			} else if (firstitem.tagName == 'H3') {

				// activate the top level accordion
				menu = j$(firstitem).parents('ul')[0];
				menuitem = j$(firstitem).parents('li')[0];
				j$(menu).accordion("option", "active", j$(menuitem).parent().children('li').index(menuitem));

			}
		}
	}
}

common.string = {

	// Remove leading and trailing whitespace from a string
	trimWhitespace: function(string) {

		var newString = '';
		var substring = '';
		beginningFound = false;

		// copy characters over to a new string
		// retain whitespace characters if they are between other characters
		for (var i = 0; i < string.length; i++) {

			// copy non-whitespace characters
			if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {

				// if the temporary string contains some whitespace characters, copy them first
				if (substring != '') {
					newString += substring;
					substring = '';
				}
				newString += string.charAt(i);
				if (beginningFound == false) beginningFound = true;
			}

			// hold whitespace characters in a temporary string if they follow a non-whitespace character
			else if (beginningFound == true) substring += string.charAt(i);
		}
		return newString;
	}
}
