/**
 * @author Jon Hartmann
 * Controller to handle adding/removing messages to the product detail table
 * and the Ajax interactions involved.
 *
 
 * Controller.cartItems(string);
 * Pass any integer into Controller.cartItems to update the count inside of the cart item
 * display at the top.
 * 
 * Example: Controller.cartItems(1000);
 *          Updates the cart message to read: My Cart (1000) Items
 * Example: Controller.cartItems('1,000');
 *          Updates the cart message to read: My Cart (1,000) Items
 *  
 *  
 *  Controller.renderMessage(element, type, message)
 *  Arguments: element  - Either an ID, an HTML element, or a jQuery result for the row that needs
 *                        the message
 *             type     - The type of message, either 'success', 'error', or 'list'
 *             message  - A string to be used as the message, such as 'Item added to your Cart'
 *  
 * Example: Controller.renderMessage('row-234', 'success', 'Added to Cart');
 *          Applies the success style to the row with ID 'row-234' and puts the message 'Added to Cart'
 * Example: Controller.renderMessage(jQuery('#row-234'), 'error', 'Error');
 *          Applies the error style to the jQuery result for '#row-234' and puts the message 'Error'
 */
 var pickedImage;
 var spinLength=0;
 var startOk=true;
Controller = function () {
	// Private Vars
	var config = {
		// These are default messages for the ajax returns
		messages : {
	    success: 'This item has been added to your cart.',
	    list: 'This item has been added to your list.',
	    error: 'This item has an error.',
			invalidQtyMessage: 'The quanity you entered is invalid, please enter only numeric values.',
			
			listProcessing: 'Adding to list...',
			listReady: 'Save to Shopping List'
	  },
		// jQuery selectors to get certain data
		selectors: {
			successMessage: '.success-message',
			listMessage: '.list-message',
			errorMessage: '.error-message',
			addToCartLink: '.addToCartLink',
			addToListLink: '.addToListLink',
			requestQuoteLink: '.requestQuoteLink',
			requestQuoteCustFormLink: '.requestQuoteCustFormLink',
			listSelect: '#addToListSelect',
			addToListDialogue: '#addToListDialogue',
			addToListButton: '#addToListSubmit',
			cartItemCounter: '#cartItems',
			extraValues: 'div.extraValues input[type=hidden]'
		},
		// Classes to be applied in certain circumstances
		classes: {
			successHighlight: 'success',
      listHighlight: 'list',
      errorHighlight: 'error',
			alternateRow: 'alt'
		}
	};
	// Holds default controller values, currently unused
	var defaults = {};
	// Holds controller values once extended, currently unused
	var options = {};
	
	// tracks the state of aspects of the controller
  var state = {
		listLoaded : false
	};
	
	// "Private Methods" These functions can only be called from within the controller
	function openMessage (element, type, message) {
		// This handles the creation of an message of a given type with or without a given message
		var row = $(element)
		var message = message ? message : config.messages[type];
		
		// Remove the alt class from the row
		row.removeClass('alt');
    
		// Create a new row for the message
    var newRow = $('<tr></tr>')
      .addClass(type + '-message')
      .html('<th colspan="'+row.children().length+'">' + message + '</th>');
    
		// Add the new class and insert the new row;
    row.addClass(config.classes[type+'Highlight']).before(newRow);
	}
	
	function closeMessage (message) {
		// This handles closing a given message type
    var $this = $(message);
    var $next = $this.next();
		// Determine if the row should be an alt row
		var alt = !$this.prev().hasClass(config.classes.alternateRow);
		
    // Remove the divider
    $this.remove();
		
		//Remove old classes
		$next.removeClass(config.classes.successHighlight)
		  .removeClass(config.classes.listHighlight)
			.removeClass(config.classes.errorHighlight);
		
    // See if the last row wasn't an alternate row
    if ( alt ) {
      // Make he next row an alternate row
      $next.addClass(config.classes.alternateRow);
    }
  }
	function getID (element) {
		// This function returns the numeric ID value stored in the class string as "row-XXXX"
		return parseInt($(element).attr('class').toString().replace(/\D/g, ''))
	}
	
  function getRowID (element) {
    // This function returns the row ID value stored in the class string as "row-XXXX"
    var classes = $(element).attr('class').split(' ');
		var rowID = null;
		
    for (var i=0; i < classes.length; i ++) {
      if ( classes[i].match('row-') ) {
        rowID = classes[i]
      }
    }
		return rowID;
  }
	
	function loadLists (event) {
		//determine the current row 
		 var $this = $(event.target);
		  var id = getID($this);
			var row = $('#row-'+id);
		//add any extra values to the hash of data to post
					var extras = {};
					$(config.selectors.extraValues, row).each(function() {
					  var $this = $(this);
					  extras[$this.attr('name')] = $this.val();
			});
			
		// This function makes an AJAX call to load the list selection with lists via JSON
		$.post(
		  // use the appropriate URL from the config
		  options.URLs.listJSONData,extras,
			// Create the callback function
			function (data) {
				// Get the Select for the lists
				var divJson=$(data).text();
				//var jsonData=(new Function("return "+$(data).find("div#jsonHotList").text()))();
				
				var jsonData=(new Function("return "+divJson))();
				var select = $(config.selectors.listSelect);
				
				// Delete all existing items in the select
				select.html('');
				
				// Loop over each item in the returned lists
				$.each(jsonData.items, function (i, item) {
					// Append an option to the inside of the select
					select.append(
					 //Create an option out of the current item
					 $('<option value="'+item.id+'">'+item.title+'</option>')
					);
				})
			}
		)
	}
	
	function validateRadio(input) {
		var result=false;
		for (i=0;i<input.length;i++) {
			result=input[i].checked;
			if (result==true)
				break;
		}
		return result;
	}
	
	function validateInt (input) {
		// validates that a given input is numeric
		// Commented for defect Id 1087 Debabrata Barik (c00s7h) 12-23-09 
		//return !isNaN(parseInt(input));
		// Added for defect Id 1087 Debabrata Barik (c00s7h) 12-23-09 
		return !isNaN(parseInt(input))&& parseInt(input)!=0 ;
	}
		
	// "Public Methods" these functions can be access publicly as methods of the Controller object
	return {
		// Initialization Function for the Controller
		init: function (_options) {
			// Take an user provided options, and merge them with the defaults
			options = $.extend(defaults, _options);
			
			// Attach click event listeners for add-to-cart, add-to-list, and request-quote links.
			//$(config.selectors.addToCartLink).bind('click', Controller.handleAddToCart);
			$(config.selectors.addToListLink).bind('click', Controller.handleAddToList);
			//$(config.selectors.requestQuoteLink).bind('click', Controller.handleRequestQuoteLink);
			//$(config.selectors.requestQuoteCustFormLink).bind('click', Controller.handleRequestQuoteCustFormLink);
			
			
			// Instantiate the dialog
			$(config.selectors.addToListDialogue).dialog({
        dialogClass: 'listModal',
        bgiframe: true,
        autoOpen: false,
        height: 'auto',
        modal: false,
        width: 330,
        draggable: false,
        resizeable: false
      });
			// Attach click events for dialogue buttons
			$('#addToListSubmit').bind('click', Controller.handleSubmitAddToList);
			$('#addToListCancel').bind('click', Controller.closeAddToListDialogue);
		},
		// Removes all existing messages
		closeMessages: function () {
			// remove all event messages messages
	    closeMessage($(config.selectors.successMessage));
      closeMessage($(config.selectors.listMessage));
      closeMessage($(config.selectors.errorMessage));
		},
		// Adds a new message
    renderMessage: function (element, type, message) {
			// Close all event messages
      Controller.closeMessages();
			// Open the new message on the given row
      openMessage(element, type, message);
    },
		// Handles the ajax calls for adding an item to the cart
		handleAddToCart: function (event) {
			// Prevent the default action
			event.preventDefault();
  
		  var $this = $(event.target);
		  var id = getID($this);
			var row = $('#row-'+id);
			
			var quantity = $(':text', row).val();
			var units=$(':radio',row);
			
			
			if ( !validateInt(quantity) ) {
       				 Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidQtyMessage);
				return;
			}
			
			if (!validateRadio(units)) {
				Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidUnitsMessage);
				return;
			}
			
			//Call Webtrends
			dcsMultiTrack('WT.si_n', 'Product Purchase', 'WT.si_x', '2','WT.pn_sku',id,'WT.tx_u',quantity+'_'+units,'WT.tx_e','a');
			
			// Create a new object of values to be posted back to the server
			var postData = {
				ids : id,
				shoppingCartUnits: $(':radio:checked', row).val(),
				shoppingCartQty: quantity,
				type: 'addToCart'
			};
			
			//add any extra values to the hash of data to post
			var extras = {};
			$(config.selectors.extraValues, row).each(function() {
			  var $this = $(this);
			  extras[$this.attr('name')] = $this.val();
			});
			
			postData = $.extend(postData, extras);
			
			// Create an Ajax submit to post the information to the server
			$.post(
			  // Use the appropriate URL from the config
			  options.URLs.cartJSONResponse,
				postData,
				// Create a call back
				function (data) {
					if ( data.result.toString() == 'true' ) {
						Controller.renderMessage($this.closest('tr'), 'success', data.message);
						if (data.type.toString() == 'addToCart') {
							dcsMultiTrack('WT.si_n', 'Product Purchase', 'WT.si_x', '2', 'WT.pn_sku', 'SKU_OF_ITEM', 'WT.tx_u', 'QUANTITY_UNITS', 'WT.tx_e', 'a');
						} else if (data.type.toString() == 'requestAQuote') {
							dcsMultiTrack('DCSext.QuoteRequestStep1', 'Step 1');
						}
					} else {
            Controller.renderMessage($this.closest('tr'), 'error', data.message);
					}
					Controller.cartItems(data.totalItems);
				},
				// Specify that the result of the post action will be JSON data
				'json'
			);
		},
		handleAddToCartCustForm: function (event) {
			event.preventDefault();
			  
			 var $this = $(event.target);
			 var id = getID($this);
			 var row = $('#row-'+id);
						
			 var quantity = $(':text', row).val();
			 var units=$(':radio',row);
		         
						
			 if ( !validateInt(quantity) ) {
			       	 Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidQtyMessage);
				return;
			}
						
			if (!validateRadio(units)) {
				Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidUnitsMessage);
				return;
			}
			
			//Call Webtrends
			dcsMultiTrack('WT.si_n', 'Product Purchase', 'WT.si_x', '2','WT.pn_sku',id,'WT.tx_u',quantity+'_'+units,'WT.tx_e','a');
			
			var shoppingCartCatNum=$(':input[name=shoppingCartCatNum]',row);
			var productId=$(':input[name=productId]',row);
			var errorProductId=$(':input[name=errorProductId]',row);
			var formId=$(':input[name=formId]',row);
			var leadType=$(':input[name=leadType]',row);
			var url=options.URLs.cartCustFormResponse+"&ids="+id+"&shoppingCartUnits="+units.val()+"&shoppingCartQty="+quantity+"&shoppingCartCatNum="+shoppingCartCatNum.val()+"&productId="+productId.val()+"&errorProductId="+errorProductId.val()+"&formId="+formId.val()+"&leadType="+leadType.val();
			window.open(url);
			
			},
		// Handles Clicking the 'Add To List' Link
		handleAddToList: function (event) {
			// Prevent the default action
			event.preventDefault();
			
      var $this = $(event.target);
      var id = getID($this);
     
      
			// See if the information about the lists has not been loaded
			if ( !state.listLoaded ) {
				// Call private method to get lists
				loadLists(event);
			}
			
			// Ask the controller to open the dialogue
      Controller.openAddToListDialogue($this, id);
    },

    //Handle Request Quote with Custom Form
    handleRequestQuoteCustFormLink: function (event) {
    	event.preventDefault();
		  
		var $this = $(event.target);
		var id = getID($this);
		var row = $('#row-'+id);
					
		var quantity = $(':text', row).val();
		var units=$(':radio',row);
					
		if ( !validateInt(quantity) ) {
			Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidRequestQuoteQtyMessage);			
			return;
		}
					
		if (!validateRadio(units)) {
			Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidUnitsMessage);
			return;
		}
		
		//Call Webtrends
		dcsMultiTrack('DCSext.QuoteRequestStep1', 'Step 1');

		var shoppingCartCatNum=$(':input[name=shoppingCartCatNum]',row);
		var productId=$(':input[name=productId]',row);
		var errorProductId=$(':input[name=errorProductId]',row);
		var formId=$(':input[name=formId]',row);
		var leadType=$(':input[name=leadType]',row);
		var url=options.URLs.quoteCustFormResponse+"&ids="+id+"&shoppingCartUnits="+units.val()+"&shoppingCartQty="+quantity+"&shoppingCartCatNum="+shoppingCartCatNum.val()+"&productId="+productId.val()+"&errorProductId="+errorProductId.val()+"&formId="+formId.val()+"&leadType="+leadType.val();
		window.open(url);
	},    
    
    handleSubmitAddToList: function (event) {
			var id = $('#addToListID').val();
			 var row = $('#row-'+id);
			 var postData = {
			       		hListIdForDisplay: $('#addToListSelect').val(), 
			       		groupAndHotlistID:$('#addToListSelect').val(),
         				 type: 'addToList'
			 };
      
			 var extras = {};
			 			$(config.selectors.extraValues, row).each(function() {
			 			  var $this = $(this);
			 			  extras[$this.attr('name')] = $this.val();
			});
			postData = $.extend(postData, extras);
			
			//Track using Site Catalyst / Omniture
			s.linkTrackVars='prop28';
		    s.linkTrackEvents='None';
		    s.prop28='Add To List';
			s.tl(true,'o','Add To List');
			
			//Create an indication on the dialogue that something has happend.
			$(config.selectors.addToListButton).val(config.messages.listProcessing).attr('disabled', 'disabled');
			
			// Create Ajax call to post data to the server
			$.post(
			  // Use the appropriate URL from the config
        options.URLs.listAddJSONResponse, postData,
				
      			// Create the callback
        function (data) {
          // Close the dialogue
					Controller.closeAddToListDialogue();
					
          if ( data.result.toString() == 'true' ) {
            Controller.renderMessage($('#row-'+id), 'list', data.message);
          } else {
            Controller.renderMessage($('#row-'+id), 'error', data.message);
          }
					
					// Set indicators back to normal
          $(config.selectors.addToListButton).val(config.messages.listReady).attr('disabled', '');
        },
				// Specify that the result of the post will be JSON
        'json'
      );
		},

		//Handles requesting a quote
		handleRequestQuoteLink: function (event) {

			//Prevent the default event action
			event.preventDefault();
			
			var $this = $(event.target);
			var id = getID($this)
			var row = $('#row-'+id);
			var quantity = $(':text', row).val();
      		var units=$(':radio',row);
      		var partnum = $.trim($('.partnum',row).text());
      			
  			if ( !validateInt(quantity) ) {
				Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidRequestQuoteQtyMessage);
          		return;
      		}
      			// c00s4y Girija Behera commented below for the defect 2186 starts
      		/* if (!validateRadio(units)) {
      			Controller.renderMessage($this.closest('tr'), 'error', options.messages.invalidUnitsMessage);
      			return;
      		}*/
      			// c00s4y Girija Behera commented below for the defect 2186 ends
				
    		//Call Webtrends
    		dcsMultiTrack('DCSext.QuoteRequestStep1', 'Step 1');
    		
    		//Call Omniture/SiteCatalyst
			s.linkTrackVars='events,products';
			s.linkTrackEvents='event3,event4';
			s.events='event3,event4';
			s.products=';'+partnum+';'+quantity;
			s.tl($(event.target),'o','Quote Add to Cart');

    		//Create a new object of values to be posted back to the server
      		var postData = {
      			ids : id,
      			shoppingCartUnits: $(':radio:checked', row).val(),
      			shoppingCartQty: quantity,
      			type: 'addToCart'
			};
      			
      		//Add any extra values to the hash of data to post
      		var extras = {};
      		$(config.selectors.extraValues, row).each(
      			function() {
      				var $this = $(this);
      				extras[$this.attr('name')] = $this.val();
      			}
      		);
      			
			postData = $.extend(postData, extras);
			
			//Create an Ajax call to post the data to the server
			$.post(
				//Use the appropriate URL from the config
				options.URLs.requestQuoteJSONResponse,postData,
	
				//Create the callback
				function (data) {
					if ( data.result.toString() == 'true' ) {
						Controller.renderMessage($('#row-'+id), 'success', data.message);
					} else {
						Controller.renderMessage($('#row-'+id), 'error', data.message);
					}
					Controller.cartItems(data.totalItems);         
				},
				//Specify that the result is JSON
				'json'
			);
		},
		
		// Opens and positions the dialogue for adding elements to the list
		openAddToListDialogue: function (element, id) {
			// Close the dialogue if it is open
			Controller.closeAddToListDialogue();
			// Calculate the needed offsets for the current link
      var link = $(element);
      var offset = link.offset();
      var popX = offset.left - (link.width() / 2);
      //var popY = offset.top - $(document).scrollTop() + link.height();
	  var popY = offset.top + link.height();
      
			// Update the id for the item that would be added to the list
			$('#addToListID').val(id);
			
			// Position the dialogue and open it.
			//$(config.selectors.addToListDialogue).dialog('option','position',[popX,popY]).dialog("open");	
			$("#addToListDialogue").parent().css({"position": "absolute", "left": popX, "top": popY, "display": "block"});			
		},
		// Closes the add-to-list dialogue
		closeAddToListDialogue: function () {
			$(config.selectors.addToListDialogue).dialog('close')
		},
		// Updates the item count displayed in the cart
		cartItems: function (itemCount) {
			$(config.selectors.cartItemCounter).html(' ('+itemCount+') Items');
		}
	};
}();


/**
 * @author Jeremy Flores
 * The product detail page uses a pile of js to show various product images in various product sizes. It's a mashup of the
 * jQuery lightbox plugin from http://leandrovieira.com and the jQuery GalleryView plugin from
 * http://www.spaceforaname.com/jquery/galleryview/.
 *
 * The GalleryView plugin requires jquery.timers and recommends jquery.easing. Since we're only using GalleryView on the product
 * detail page, for now, I've included jquery.timers-1.12 and jquery.easing.1.3 at the end of this file rather than including them
 * as separate files.
 *
 * The lightbox and galleryview plugins been modified to the point that they're wholly unusable separately.
 * I combined them into one file for easier maintenance and greater modularity.
 * Don't try to use this script outside of product detail unless you've replicated the DOM structure from
 * the product detail page.
 *
 * Not included in this script is the toolTip code by Jon Hartmann (see application.js). It's use is implied in the way the lightbox
 * pulls its captions, but no specific calls or dependencies to the toolTip code exists.
 *
 * Here's an example of how instantiation and customization are working on the product detail page:
 $(document).ready(function () {
   // SNIP!
   //activate image carousel
		$('#galleryView').galleryView({
			panel_width: 190,
			panel_height: 144,
			frame_width: 25,
			frame_height: 25,
			overlay_opacity: 0.9,
			background_color: 'white',
			overlay_text_color: 'white',
			caption_text_color: 'black',
			border: '1px solid black',
			nav_theme: 'dark',
			border: 'none',
			overlay_color: '#222',			
			overlay_height: 0
		});
 	
 	//activate product image lightbox
   $(function() {
     $('#galleryView div.panel > a').lightBox({	
       overlayOpacity: 0.6,
       imageLoading: "/images/lightbox/lightbox-ico-loading.gif",
       imageBtnClose: "/images/lightbox/bordered_close.gif",
       imageBtnPrev: "/images/lightbox/dbarrow_prev.gif",
       imageBtnNext: "/images/lightbox/dbarrow_next.gif",
       containerResizeSpeed: 350,
       txtImage: 'Image',
       txtOf: 'of'
     });
   });
   
   //bind 'expand' link to active lightbox
   $('#enlargeImage a').bind('click',function(event) {
     $('#galleryView div.panel:visible > a').click();
     return false; //stop bubbling
   });
   
   // END SNIP!
   
 });
 */

//functions that serve as callbacks to the GalleryView plugin.
 carousel = {
   //updates the larger preview image when the user cycles to a new image
   makeActive: function(li) {
      var imagePath = typeof Paths == "object"
        ? Paths.carouselLargePreview
        : "/images";
     li.siblings('active').removeClass('active');
     li.addClass('active');
     var title = li.children(':first').attr('title');
     $('#productImage').attr({ src: Paths.carouselLargePreview + title + '.jpg' });
   }
 };

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		imgBasePath=typeof imgBasePath=="undefined" ? "../images/" : imgBasePath;
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		true,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			imgBasePath+'lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			imgBasePath+'lightbox-btn-prev.gif',		// (string) Path and the name of the prev button image
			imageBtnNext:			imgBasePath+'lightbox-btn-next.gif',		// (string) Path and the name of the next button image
			imageBtnClose:			imgBasePath+'lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				imgBasePath+'lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Some info needed to add the carousel to the lightbox (jnf)
			carouselThumbs:    "ul#spinner", //the ul containing the thumbnails in the primary carousel
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			if(startOk){
				// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
				$('embed, object, select').css({ 'visibility' : 'hidden' });
				// Call the function to create the markup structure; style some elements; assign events in some elements.
				_set_interface();
				// Unset total images in imageArray
				settings.imageArray.length = 0;
				// Unset image active information
				settings.activeImage = 0;
				// We have an image set? Or just an image? Let´s see it.
				if ( jQueryMatchedObj.length == 1 ) {
				  // user the child span's text instead of the title to set the caption - plays nice with infotips (jnf)
					settings.imageArray.push(
					  new Array(
					    objClicked.getAttribute('href'),
					    $(objClicked).children('span.tooltip').text()
					  )
					);
				} else {
					// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
					for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
						// user the child span's text instead of the title to set the caption - plays nice with infotips (jnf)
						settings.imageArray.push(
						  new Array(
						    jQueryMatchedObj[i].getAttribute('href'),
						    $(jQueryMatchedObj[i]).children('span.tooltip').text()
						  )
						);
					}
				}
				while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
					settings.activeImage++;
				}
				//attach carousel to lightbox header (jnf)
				_startCarousel();
				// Call the function that prepares image exibition
				_set_image_to_view();
				startOk=false;
			}
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image" />
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif" />
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif" />
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-carousel"><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '" /></a></div></div><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image" /><div style="" id="lightbox-nav"><div id="lightbox-nav-btnPrev"><a href="#" id="prevarrow" style="display:block; width:55px; height:50px; margin-top:25px; float:left;"></a></div><div id="lightbox-nav-btnNext"><a href="#" id="nextarrow" style="display:block; width:53px; height:50px; float:right; margin-top: 25px;"></a></div></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '" /></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div></div></div></div>');
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
			  top: arrPageScroll[1] + (arrPageSizes[3] / 20), 
				//top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				//_finish();  // Functionality removed to address defect 2498
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				// If image has changed make original match the new one:
				spinLength=$("#spinner").children().length;
				var newIndex=settings.activeImage;
				if(pickedImage==undefined){
					pickedImage=0;
				}
				if(pickedImage!=newIndex && (pickedImage-(spinLength/3))!=newIndex && pickedImage-((spinLength/3)*2)!=newIndex){
					$("#spinner li:nth-child("+(newIndex+1)+")").click();
				}
				keyPressed=false;
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image´s preloader to calculate it´s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			if(settings.imageArray[settings.activeImage]){
				$('#lightbox-loading').show();
				if ( settings.fixedNavigation ) {
					$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
				} else {
					// Hide some elements
					$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber, #prevarrow, #nextarrow').hide();
				}
				// Image preload process
				var objImagePreloader = new Image();
				objImagePreloader.onload = function() {
					$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
					// Perfomance an effect in the image container resizing it
					_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
					//	clear onLoad, IE behaves irratically with animated gifs otherwise
					objImagePreloader.onload=function(){};
				};
				objImagePreloader.src = settings.imageArray[settings.activeImage][0];
			}
			settings.activeImage=Math.max(settings.activeImage, 0);
			settings.activeImage=Math.min((settings.imageArray.length-1), settings.activeImage);
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image´s width that will be showed
		 * @param integer intImageHeight The image´s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect - leave the width alone (jnf)
			$('#lightbox-container-image-box').animate({ width: intCurrentWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			}
			//fix the sizes of the carousel top and info bottom (jnf)
      $('#lightbox-carousel').css({ width: intCurrentWidth });
			$('#lightbox-container-image-data-box').css({ width: intCurrentWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			//remove the 'active' marker from the thumbnails
			$('#lightbox-carousel ul > li').css({ 'border': '1px solid #999' });
			//add the 'active' class to the new thumbnail
			$('#lightbox-carousel ul > li:eq(' + settings.activeImage + ')').css({ 'border': '1px solid #000' });
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').fadeIn();
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			} 
			// If we have a image set, display 'Image X of X'
			// Removed this based on defect #2717.
			//if ( settings.imageArray.length > 1 ) {
			//	$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			//}		
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }).bind('click', function(){this.blur();});
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$("#prevarrow").show();
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 2em no-repeat' });
					$("#prevarrow")
						.unbind()
						.bind('click',function() {
							this.blur();
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Previous buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 2em no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show();
					$("#prevarrow").bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			} else {
				$("#prevarrow").hide();
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$("#nextarrow").show();
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 2em no-repeat' });
					$("#nextarrow")
						.unbind()
						.bind('click',function() {
							this.blur();
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 2em no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show();
					$("#nextarrow").bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			} else {
				$("#nextarrow").hide();
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			return false;
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we´re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we´re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		 
		function _finish() {
			startOk=true;
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		* Prep and add image thumbnails to lightbox header (jnf)
		*/
		function _startCarousel() {
		  if ( settings.imageArray.length > 1 && "function" == typeof $.fn.galleryView) {		    
		    //prep thumbs
		    var thumbs = $(settings.carouselThumbs).html();
		    
		    //insert prepped items into lightbox header
		    $('#lightbox-carousel').append('<ul>'+baseClump+'</ul>');
		    
		    //fix some cruft set by the carousel script
		    $('#lightbox-carousel ul > li').css({
		      'float': 'left',
		      'margin': '2px',
		      'padding': '0',
		      'border': '1px solid #999'
		    });
		    
		    //bind the click action to alter the lightbox image
		    $('#lightbox-carousel ul > li').each(function(index) {
		      $(this).bind('click', function() {
		        settings.activeImage = index;
						_set_image_to_view();
		        return false; //stop bubbling
		      })
		    });
    		return true;
		  } else {
		    return false;
		  }
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object





//END LIGHTBOX, BEGIN GALLERYVIEW






/*

	GalleryView - jQuery Content Gallery Plugin
	Author: 		Jack Anderson
	Version:		1.1 (April 5, 2009)
	Documentation: 	http://www.spaceforaname.com/jquery/galleryview/
	
	Please use this development script if you intend to make changes to the
	plugin code.  For production sites, please use jquery.galleryview-1.0.1-pack.js.
	
*/
(function($){
	$.fn.galleryView = function(options) {
		var opts = $.extend($.fn.galleryView.defaults,options);
		
		var id;
		var iterator = 0;
		var gallery_width;
		var gallery_height;
		var frame_margin = 0;
		var strip_width;
		var wrapper_width;
		var item_count = 0;
		var slide_method;
		var img_path;
		var paused = false;
		var frame_caption_size = 20;
		var frame_margin_top = 5;
		var pointer_width = 2;
		
		//Define jQuery objects for reuse
		var j_gallery;
		var j_filmstrip;
		var j_frames;
		var j_panels;
		var j_pointer;
		
/************************************************/
/*	Plugin Methods								*/
/************************************************/	
		function showItem(i) {
			pickedImage=i;
			//Disable next/prev buttons until transition is complete
			$('img.nav-next').unbind('click');
			$('img.nav-prev').unbind('click');
			j_frames.unbind('click');
			if(has_panels) {
				if(opts.fade_panels) {
					//Fade out all panels and fade in target panel
					j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed,function(){
						if(!has_filmstrip) {
							$('img.nav-prev').click(showPrevItem);
							$('img.nav-next').click(showNextItem);		
						}
					});
				} 
			}
			
			if(has_filmstrip) {
				//Slide either pointer or filmstrip, depending on transition method
				if(slide_method=='strip') {
					//Stop filmstrip if it's currently in motion
					j_filmstrip.stop();
					
					//Determine distance between pointer (eventual destination) and target frame
					var distance = getPos(j_frames[i]).left - (getPos(j_pointer[0]).left+2);
					var leftstr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
					
					//Animate filmstrip and slide target frame under pointer
					//If target frame is a duplicate, jump back to 'original' frame
					j_filmstrip.animate({
						'left':leftstr
					},opts.transition_speed,opts.easing,function(){
						//Always ensure that there are a sufficient number of hidden frames on either
						//side of the filmstrip to avoid empty frames
						if(i>item_count) {
							i = i%item_count;
							iterator = i;
							j_filmstrip.css('left','-'+((opts.frame_width+frame_margin)*i)+'px');
						} else if (i<=(item_count-strip_size)) {
							i = (i%item_count)+item_count;
							iterator = i;
							j_filmstrip.css('left','-'+((opts.frame_width+frame_margin)*i)+'px');
						}
						
						if(!opts.fade_panels) {
							j_panels.hide().eq(i%item_count).show();
						}
						$('img.nav-prev').click(showPrevItem);
						$('img.nav-next').click(showNextItem);
						enableFrameClicking();
					});
				} else if(slide_method=='pointer') {
					//Stop pointer if it's currently in motion
					j_pointer.stop();
					//Get position of target frame
					var pos = getPos(j_frames[i]);
					//Slide the pointer over the target frame
					j_pointer.animate({
						'left':(pos.left-2+'px')
					},opts.transition_speed,opts.easing,function(){	
						if(!opts.fade_panels) {
							j_panels.hide().eq(i%item_count).show();
						}	
						$('img.nav-prev').click(showPrevItem);
						$('img.nav-next').click(showNextItem);
						enableFrameClicking();
					});
				}
			
				if($('a',j_frames[i])[0]) {
					j_pointer.unbind('click').click(function(){
						var a = $('a',j_frames[i]).eq(0);
						if(a.attr('target')=='_blank') {window.open(a.attr('href'));}
						else {location.href = a.attr('href');}
					});
				}
			}
		};
		function showNextItem() {
			$(document).stopTime("transition");
			if(++iterator==j_frames.length) {iterator=0;}
			showItem(iterator);
			$(document).everyTime(opts.transition_interval,"transition",function(){
				showNextItem();
			});
		};
		function showPrevItem() {
			$(document).stopTime("transition");
			if(--iterator<0) {iterator = item_count-1;}
			//alert(iterator);
			showItem(iterator);
			$(document).everyTime(opts.transition_interval,"transition",function(){
				showNextItem();
			});
		};
		function getPos(el) {
			var left = 0, top = 0;
			var el_id = el.id;
			if(el.offsetParent) {
				do {
					left += el.offsetLeft;
					top += el.offsetTop;
				} while(el = el.offsetParent);
			}
			//If we want the position of the gallery itself, return it
			if(el_id == id) {return {'left':left,'top':top};}
			//Otherwise, get position of element relative to gallery
			else {
				var gPos = getPos(j_gallery[0]);
				var gLeft = gPos.left;
				var gTop = gPos.top;
				
				return {'left':left-gLeft,'top':top-gTop};
			}
		};
		function enableFrameClicking() {
			j_frames.each(function(i){
				//If there isn't a link in this frame, set up frame to slide on click
				//Frames with links will handle themselves
				if($('a',this).length==0) {
					$(this).click(function(){
						$(document).stopTime("transition");
						showItem(i);
						iterator = i;
						$(document).everyTime(opts.transition_interval,"transition",function(){
							showNextItem();
						});
					});
				}
			});
		};
		
		function buildPanels() {
			//If there are panel captions, add overlay divs
			if($('.panel-overlay').length>0) {j_panels.append('<div class="overlay"></div>');}
			
			if(!has_filmstrip) {
				//Add navigation buttons
				$('<img />').addClass('nav-next').attr('src',img_path+opts.nav_theme+'/dbarrow_next_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'zIndex':'1100',
					'cursor':'pointer',
					'top':((opts.panel_height-22)/2)+'px',
					'right':'10px',
					'display':'none'
				}).click(showNextItem);
				$('<img />').addClass('nav-prev').attr('src',img_path+opts.nav_theme+'/dbarrow_prev_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'zIndex':'1100',
					'cursor':'pointer',
					'top':((opts.panel_height-22)/2)+'px',
					'left':'10px',
					'display':'none'
				}).click(showPrevItem);
				
				$('<img />').addClass('nav-overlay').attr('src',img_path+opts.nav_theme+'/dbarrow_next_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'zIndex':'1099',
					'top':((opts.panel_height-22)/2)-10+'px',
					'right':'0',
					'display':'none'
				});
				
				$('<img />').addClass('nav-overlay').attr('src',img_path+opts.nav_theme+'/dbarrow_prev_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'zIndex':'1099',
					'top':((opts.panel_height-22)/2)-10+'px',
					'left':'0',
					'display':'none'
				});
			}
			j_panels.css({
				'width':(opts.panel_width-parseInt(j_panels.css('paddingLeft').split('px')[0],10)-parseInt(j_panels.css('paddingRight').split('px')[0],10))+'px',
				'height':(opts.panel_height-parseInt(j_panels.css('paddingTop').split('px')[0],10)-parseInt(j_panels.css('paddingBottom').split('px')[0],10))+'px',
				'position':'absolute',
				'top':(opts.filmstrip_position=='top'?(opts.frame_height+frame_margin_top+(opts.show_captions?frame_caption_size:frame_margin_top))+'px':'0px'),
				'left':'0px',
				'overflow':'hidden',
				'background':'white',
				'display':'none'
			});
			$('.panel-overlay',j_panels).css({
				'position':'absolute',
				'zIndex':'999',
				'width':(opts.panel_width-20)+'px',
				'height':opts.overlay_height+'px',
				'top':(opts.overlay_position=='top'?'0':opts.panel_height-opts.overlay_height+'px'),
				'left':'0',
				'padding':'0 10px',
				'color':opts.overlay_text_color,
				'fontSize':opts.overlay_font_size
			});
			$('.panel-overlay a',j_panels).css({
				'color':opts.overlay_text_color,
				'textDecoration':'underline',
				'fontWeight':'bold'
			});
			$('.overlay',j_panels).css({
				'position':'absolute',
				'zIndex':'998',
				'width':opts.panel_width+'px',
				'height':opts.overlay_height+'px',
				'top':(opts.overlay_position=='top'?'0':opts.panel_height-opts.overlay_height+'px'),
				'left':'0',
				'background':opts.overlay_color,
				'opacity':opts.overlay_opacity
			});
			$('.panel iframe',j_panels).css({
				'width':opts.panel_width+'px',
				'height':(opts.panel_height-opts.overlay_height)+'px',
				'border':'0'
			});
		};
		
		function buildFilmstrip() {
			//Add wrapper to filmstrip to hide extra frames
			j_filmstrip.wrap('<div class="strip_wrapper"></div>');
			if(slide_method=='strip') {
				j_frames.clone().appendTo(j_filmstrip);
				j_frames.clone().appendTo(j_filmstrip);
				j_frames = $('li',j_filmstrip);
			}

			//If captions are enabled, add caption divs and fill with the image titles
			if(opts.show_captions) {
				j_frames.append('<div class="caption"></div>').each(function(i){
					$(this).find('.caption').html($(this).find('img').attr('title'));			   
				});
			}
			
			j_filmstrip.css({
				'listStyle':'none',
				'margin':'0',
				'padding':'0',
				'width':strip_width+'px',
				'position':'absolute',
				'zIndex':'900',
				'top':'5px',
				'left':'0',
				'height':(opts.frame_height+10)+'px',
				'background':opts.background_color
			});
			j_frames.css({
				'float':'left',
				'position':'relative',
				'height':opts.frame_height+'px',
				'zIndex':'901',
				'marginTop':frame_margin_top+'px',
				'marginBottom':'0px',
				'marginRight':frame_margin+'px',
				'padding':'0',
				'cursor':'pointer'
			});
			$('img',j_frames).css({
				'border':'none'
			});
			$('.strip_wrapper',j_gallery).css({
				'position':'absolute',
				//move the thing down 20px so we can shove the 'expand' link in - jnf
				'top':(opts.filmstrip_position=='top'?'0px':opts.panel_height+20+'px'),
				'left':((gallery_width-wrapper_width)/2)+'px',
				'width':wrapper_width+'px',
				'height':(opts.frame_height+frame_margin_top+(opts.show_captions?frame_caption_size:frame_margin_top))+'px',
				'overflow':'hidden'
			});
			$('.caption',j_gallery).css({
				'position':'absolute',
				'top':opts.frame_height+'px',
				'left':'0',
				'margin':'0',
				'width':opts.frame_width+'px',
				'padding':'0',
				'color':opts.caption_text_color,
				'textAlign':'center',
				'fontSize':'10px',
				'height':frame_caption_size+'px',
				
				'lineHeight':frame_caption_size+'px'
			});
			var pointer = $('<div></div>');
			pointer.attr('id','pointer').appendTo(j_gallery).css({
				 'position':'absolute',
				 'zIndex':'1000',
				 'cursor':'pointer',
				 'top':getPos(j_frames[0]).top-(pointer_width/2)+'px',
				 'left':getPos(j_frames[0]).left-(pointer_width/2)+'px',
				 'height':opts.frame_height-pointer_width+'px',
				 'width':opts.frame_width-pointer_width+'px',
				 'border':(has_panels?pointer_width+'px solid '+(opts.nav_theme=='dark'?'black':'white'):'none')
			});
			j_pointer = $('#pointer',j_gallery);

/* No thanks. (jnf)
      if(has_panels) {
        var pointerArrow = $('<img />');
        pointerArrow.attr('src',img_path+opts.nav_theme+'/pointer'+(opts.filmstrip_position=='top'?'-down':'')+'.png').appendTo($('#pointer')).css({
          'position':'absolute',
          'zIndex':'1001',
          'top':(opts.filmstrip_position=='bottom'?'-'+(10+pointer_width)+'px':opts.frame_height+'px'),
          'left':((opts.frame_width/2)-10)+'px'
        });
      }
*/

			//If the filmstrip is animating, move the strip to the middle third
			if(slide_method=='strip') {
				j_filmstrip.css('left','-'+((opts.frame_width+frame_margin)*item_count)+'px');
				iterator = item_count;
			}
			//If there's a link under the pointer, enable clicking on the pointer
			if($('a',j_frames[iterator])[0]) {
				j_pointer.click(function(){
					var a = $('a',j_frames[iterator]).eq(0);
					if(a.attr('target')=='_blank') {window.open(a.attr('href'));}
					else {location.href = a.attr('href');}
				});
			}
			
			//Add navigation buttons
			if(($("#spinner").children().length/3)>5){
				$('<img />').addClass('nav-next').attr('src',img_path+opts.nav_theme+'/dbarrow_next_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'cursor':'pointer',
					//the +20 is mine. It needs to move down - jnf
					'top':(opts.filmstrip_position=='top'?0:opts.panel_height)+frame_margin_top+((opts.frame_height-22)/2)+24+'px',
					'right':(gallery_width/2)-(wrapper_width/2)-10-20+'px'
				}).click(showNextItem);
				$('<img />').addClass('nav-prev').attr('src',img_path+opts.nav_theme+'/dbarrow_prev_small.gif').appendTo(j_gallery).css({
					'position':'absolute',
					'cursor':'pointer',
					//the +20 is mine. It needs to move down - jnf
					'top':(opts.filmstrip_position=='top'?0:opts.panel_height)+frame_margin_top+((opts.frame_height-22)/2)+24+'px',
					'left':(gallery_width/2)-(wrapper_width/2)-10-22+'px'
				}).click(showPrevItem);
			}
			if(($("#spinner").children().length)<2){ // Do not have to divide this by three as it will not have been multiplied by 3 previously!
				$(".strip_wrapper").hide();
				$("#pointer").hide();
			}
		};
		
		//Check mouse to see if it is within the borders of the panel
		//More reliable than 'mouseover' event when elements overlay the panel
		function mouseIsOverPanels(x,y) {		
			var pos = getPos(j_gallery[0]);
			var top = pos.top;
			var left = pos.left;
			return x > left && x < left+opts.panel_width && y > top && y < top+opts.panel_height;				
		};
		
/************************************************/
/*	Main Plugin Code							*/
/************************************************/
		return this.each(function() {
			j_gallery = $(this);
			//Determine path between current page and filmstrip images
			//Scan script tags and look for path to GalleryView plugin
			$('script').each(function(i){
				var s = $(this);
				// this lives in the productDetail page. Look for it rather than the
				// 'jQuery.galleryview' string in the regex/split.
				if(s.attr('src') && s.attr('src').match(/productDetail/)){
					//don't use this - use the inherited Paths (jf)
					//img_path = s.attr('src').split('productDetail')[0]+'themes/';
					img_path = typeof Paths == "object"
						? Paths.carouselControlImages
						: s.attr('src').split('productDetail')[0]+'themes/';
				}
			});
			
			//Hide gallery to prevent Flash of Unstyled Content (FoUC) in IE
			j_gallery.css('visibility','hidden');
			
			//Assign elements to variables for reuse
			j_filmstrip = $('.filmstrip',j_gallery);
			j_frames = $('li',j_filmstrip);
			j_panels = $('.panel',j_gallery);
			
			id = j_gallery.attr('id');
			
			has_panels = j_panels.length > 0;
			has_filmstrip = j_frames.length > 0;
			
			if(!has_panels) opts.panel_height = 0;
			
			//Number of frames in filmstrip
			item_count = has_panels?j_panels.length:j_frames.length;
			
			//Number of frames that can display within the screen's width
			//64 = width of block for navigation button * 2
			//5 = minimum frame margin
			strip_size = has_panels?Math.floor((opts.panel_width-64)/(opts.frame_width+frame_margin)):Math.min(item_count,opts.filmstrip_size); 
			
			
			/************************************************/
			/*	Determine transition method for filmstrip	*/
			/************************************************/
					//If more items than strip size, slide filmstrip
					//Otherwise, slide pointer
					if(strip_size >= item_count) {
						slide_method = 'pointer';
						strip_size = item_count;
					}
					else {slide_method = 'strip';}
			
			/************************************************/
			/*	Determine dimensions of various elements	*/
			/************************************************/
					
					//Width of gallery block
					gallery_width = has_panels?opts.panel_width:(strip_size*(opts.frame_width+frame_margin))-frame_margin+64;
					
					//Height of gallery block = screen + filmstrip + captions (optional)
					gallery_height = (has_panels?opts.panel_height:0)+(has_filmstrip?opts.frame_height+frame_margin_top+(opts.show_captions?frame_caption_size:frame_margin_top):0);
					
					//Width of filmstrip
					if(slide_method == 'pointer') {strip_width = (opts.frame_width*item_count)+(frame_margin*(item_count));}
					else {strip_width = (opts.frame_width*item_count*3)+(frame_margin*(item_count*3));}
					
					//Width of filmstrip wrapper (to hide overflow)
					wrapper_width = ((strip_size*opts.frame_width)+((strip_size-1)*frame_margin));
			
			/************************************************/
			/*	Apply CSS Styles							*/
			/************************************************/
					j_gallery.css({
						'position':'relative',
						'margin':'0',
						'background':opts.background_color,
						'border':opts.border,
						'width':gallery_width+'px',
						'height':gallery_height+'px'
					});
			
			/************************************************/
			/*	Build filmstrip and/or panels				*/
			/************************************************/
					if(has_filmstrip) {
						buildFilmstrip();
					}
					if(has_panels) {
						buildPanels();
					}

			
			/************************************************/
			/*	Add events to various elements				*/
			/************************************************/
					if(has_filmstrip) enableFrameClicking();
					
						
						
						$().mousemove(function(e){							
							if(mouseIsOverPanels(e.pageX,e.pageY)) {
								if(opts.pause_on_hover) {
									$(document).oneTime(500,"animation_pause",function(){
										$(document).stopTime("transition");
										paused=true;
									});
								}
								if(has_panels && !has_filmstrip) {
									$('.nav-overlay').fadeIn('fast');
									$('.nav-next').fadeIn('fast');
									$('.nav-prev').fadeIn('fast');
								}
							} else {
								if(opts.pause_on_hover) {
									$(document).stopTime("animation_pause");
									if(paused) {
										$(document).everyTime(opts.transition_interval,"transition",function(){
											showNextItem();
										});
										paused = false;
									}
								}
								if(has_panels && !has_filmstrip) {
									$('.nav-overlay').fadeOut('fast');
									$('.nav-next').fadeOut('fast');
									$('.nav-prev').fadeOut('fast');
								}
							}
						});
			
			
			/************************************************/
			/*	Initiate Automated Animation				*/
			/************************************************/
					//Show the first panel
					j_panels.eq(0).show();

					//If we have more than one item, begin automated transitions
					if(item_count > 1) {
						$(document).everyTime(opts.transition_interval,"transition",function(){
							showNextItem();
						});
					}
					
					//Make gallery visible now that work is complete
					j_gallery.css('visibility','visible');
		});
	};
	
	$.fn.galleryView.defaults = {
		panel_width: 400,
		panel_height: 300,
		frame_width: 80,
		frame_height: 80,
		filmstrip_size: 3,
		overlay_height: 70,
		overlay_font_size: '1em',
		transition_speed: 400,
		transition_interval: 0,
		overlay_opacity: 0.6,
		overlay_color: 'black',
		background_color: 'black',
		overlay_text_color: 'white',
		caption_text_color: 'white',
		border: '1px solid black',
		nav_theme: 'light',
		easing: 'swing',
		filmstrip_position: 'bottom',
		overlay_position: 'bottom',
		show_captions: false,
		fade_panels: true,
		pause_on_hover: false
	};
})(jQuery);

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	if(jQuery.timer.global!=null){
		jQuery.each(jQuery.timer.global, function(index, item) {
			jQuery.timer.remove(item);
		});
	}
});

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

<!--
// transform spec and ordering table
$(function(){
	// First remove any cdata items and any rogue paragraph items:
	$(".agTable").each(
		function(){
			var scriptId=$(this).children('script:first').attr("id");
			var thisId=$(this).attr("id");
			$(this).html($("#"+scriptId).html().split('<![CDATA[').join("").split("]]>").join("").split('<P style="margin-top: 0.5em; margin-bottom: 0.5em">').join("___").split("&nbsp;").join(" "));
			$(this).find("td").each(
				function(){
					$(this).html($(this).html().split("___").join("<br/><br/>"));
				}
			);
			$(this).html($(this).html().split("___").join(""));
			$(this).find("tr:first").attr("split", "header");
			$(this).find("*").removeAttr("style").removeAttr("valign").removeAttr("parastyle").removeAttr("widthlock").removeAttr("rotateaxis").removeAttr("iscomplex").removeAttr("cansplit").removeAttr("allowoverride").removeAttr("autoheight");
			$(this).find("tr").removeAttr("height");
			$(this).find("col").remove();
		}
	);
	// Make single-cell headers appear like formatted headers ready for the next step:
	$("#specTable tr td:first-child").each(
		function(){
			var cs=$(this).attr("colspan");
			cs=cs==undefined ? 1 : cs;
			if((cs==1)){
				if(jQuery.trim($(this).next().text()).length==0){
					$(this).next().remove();
					$(this).attr("colspan", cs+1);
					$(this).parent().attr("split", "header");
				}
			}
		}
	);
	// Now replace the <td> elements inside <tr>'s that have the split/header attribute with standard <th> elements:
	//$(".agTable tr[split='header'], .agTable tr[split='subheader'], #specTable tr:first, #infoTable tr:first").children().each(
	$(".agTable tr[split='header'], .agTable tr[split='subheader']").children().each(
		function(){
			var cs=$(this).attr("colspan");
			var rs=$(this).attr("rowspan");
			$(this).replaceWith('<th colspan="'+(cs==undefined ? 1 : cs)+'" rowspan="'+(rs==undefined ? 1 : rs)+'">'+$(this).html()+'</th>');
		}
	);
	// Remove any italics in header rows:
	$(".agTable th>i").each(
		function(){
			$(this).replaceWith($(this).html());
		}
	);
	//code comment for the  INC826020 & INC801840
	 
	// Finally, for the information table only, remove the last cell, or reduce its colspan by 1:
	/*$("#infoTable tr td:last-child, #infoTable tr th:last-child").each(
		function(){
			alert("Line 2119");
			var cs=$(this).attr("colspan");
			if(cs==undefined || cs==1){
				$(this).remove();
			} else {
				$(this).attr("colspan", cs-1);
			}
		}
	);*/
	
	//code added for  INC826020 & INC801840 starts here
	// Finally, for the information table only, remove the price header and its column
	
	var totalColspan=0;
	$("#infoTable tr td").each(
		function(){
			totalColspan=parseInt(totalColspan)+parseInt($(this).attr("colspan"));
			
		}
	);
	
	var totalColspan=0;
	var maxColSize =0;
	var colZeroSetFirst =0;
	$("#infoTable tr th").each(
		function(){
			totalColspan=parseInt(totalColspan)+parseInt($(this).attr("colspan"));
			var headertext=$(this).text();
			if(headertext.indexOf("|Price")!=-1 || headertext.indexOf("|Case")!=-1 || headertext.indexOf("|Pack")!=-1 || headertext.indexOf("|Each")!=-1 || headertext.indexOf("|Pair")!=-1){
				$(this).remove();
				$('#infoTable tr td:nth-child('+(totalColspan)+')').remove();
			}
		});
		
		
		
		
		
      //code ends here
	$("#tabHeaders a").hover(
		function(){
			$(this).attr("title", $(this).text());
		}
	);
});
//-->
/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

/* Michael Wheatley - Thermo Scientific Product Display Tab */
function getQueryParams(qs) {
	qs = qs.split("+").join(" ");
	var params = {},
		tokens,
		re = /[?&]?([^=]+)=([^&]*)/g;
	while (tokens = re.exec(qs)) {
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
	}
	return params;
}
var $_GET = getQueryParams(document.location.search);
jQuery.cookie = function (key, value, options) {
	if (arguments.length > 1 && String(value) !== "[object Object]") {
		options = jQuery.extend({}, options);
		if (value === null || value === undefined) {
			options.expires = -1;
		}
		if (typeof options.expires === 'number') {
			var days = options.expires, t = options.expires = new Date();
			t.setDate(t.getDate() + days);
		}
		value = String(value);
		return (document.cookie = [
			encodeURIComponent(key), '=',
			options.raw ? value : encodeURIComponent(value),
			options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
			options.path ? '; path=' + options.path : '',
			options.domain ? '; domain=' + options.domain : '',
			options.secure ? '; secure' : ''
		].join(''));
	}
	options = value || {};
	var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
	return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

var autoTab=0;
$(function(){
	if(typeof thisProductId != 'undefined'){
		// Committed changees for fixing the defect 5062
		//setButton(1);
		if($.cookie("index")!=null && $.cookie("productId")!=null && $.cookie("productId")==thisProductId){
			autoTab=$.cookie("index");
		}
		$("#tabHeaders a").click(function(){
			var index = $("#tabHeaders a").index(this);
			$.cookie("pagePath", window.location.pathname);
			$.cookie("index", index);
			$.cookie("productId", thisProductId);
		});
	}
});

