/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
js('/files/javascript/diapo.min.js');
js('/files/javascript/jquery.easing.1.3.js');  


// Variant system
// --------------------------------
// beskrivelse
// version: 1.1 - 2011-02-02
(function($){
// TODO:
//		Lav dokumentation til hvordan plugin'et bliver brugt

	/**
	 * Activate the variantsystem on productinfo pages
	 * @param {Object} options contains an optional settings object that can override or add functionality found in the default object
	 */
	$.fn.variantSystem = function(options){
	
		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.variantSystem.defaults, options);
		
		// activate the script for each instance found in the selector
		return this.each(function(){
			var $this = $(this);
			
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
			
			// We need the variantDataObject to continue - if this does not exist, we cannot continue
			if (o.variantDataObject != null){

				// start by clearing the productid inputfield, as it now needs to be a variant
				$this.closest('form').find('input[name="' + o.productidName + '"]').val('');
					
				// run a anonymous change function on every selectbox used for the variantsystem
				$this.find('select').change(function(){
					
					// run optional onBeforeChange callback function
					if (o.onBeforeChange) {
						o.onBeforeChange($this, $(this), o);
					}

					// everytime a selectbox is changed, we need to clear the productid in the form
					$this.closest('form').find('input[name="' + o.productidName + '"]').val('');
					
					// continue if an option with a value have been selected
					if ($(this).val() != '') {
			  		var objVariantcollection = $(this).find('option').eq(this.selectedIndex).data(o.optionDataObjectName)[0];
			  	
				  	// find out if we are on the last selectbox
						if (typeof(objVariantcollection) != 'undefined') {
							// there is a variantcollection and another selectbox after this one
							
							var intNextBoxIndex = $this.find('select').index(this) + 1;
							
							// fill out the next variant selectbox
							fillVariantBox(o, $this, intNextBoxIndex, objVariantcollection);
						}
						else {
							// this is the final selectbox in the variant selection and we need to get the productid
							
							// get the productid
							var strProductid = $(this).val();
							
							// insert the prooductid in the correct inputfield in the form
							$this.closest('form').find('input[name="' + o.productidName + '"]').val(strProductid);
						}
						
						// if the updateBaseLayout is allowed to run, run it
						if (!o.disableUpdateBaseLayout){
							updateBaseLayout($this, $(this), o);
						}
						
						// run optional onUpdateLayout function to update the layout of the page (images, text, links etc.)
						if (o.updateLayout) {
							o.updateLayout($this, $(this), o);
						}
						
					}
					
					// run optional onBeforeChange callback function
					if (o.onAfterChange) {
						o.onAfterChange($this, $(this), o);
					}
					
				});
				
				// fill out the first variantbox
				fillVariantBox(o, $this);
				
				// run optional onBeforeChange callback function
				if (o.onCreate) {
					o.onCreate($this, o);
				}
			} else {
				log_debug('ERROR in jQuery variantSystem plugin: the option "variantDataObject" is not set in the template - it is needed to activate the variantSystem plugin');
			}
		});
	}
	
	
	
	/**
	 * Fill variant box with data from the objVariantCollection, if it is supplied
	 * @param {Object} o	The options object for the plugin
	 * @param {jQueryObject} $productVariantContainer	The jQuery object for the containing element
	 * @param {number} intIndex	Index of the affected selectbox. Optional (if not specified, first selectbox will be chosen)
	 * @param {Object} objVariantCollection	The variantcollection object from the previously chosen option. Optional (if not specified, it will get the first variantcollection from objVariants)
	 */
	function fillVariantBox(o, $productVariantContainer, intIndex, objVariantcollection){
		var $variantBox, arrVariantValues;
		var intBoxIndex = 0;
		
		// if intIndex exists, use its value in intBoxIndex
		if (typeof(intIndex) != 'undefined') {
			intBoxIndex = intIndex;
		}
		
		// get the selectbox to insert new data into
		$variantBox = $productVariantContainer.find('select').eq(intBoxIndex);
		
		if ($variantBox.size() == 0){
			return false;
		}
		
		// set the array of values to insert into the selectbox
		if (typeof(objVariantcollection) != 'undefined'){
			// if the objVariantcollection parameter have been passed to us, use it
			
			arrVariantValues = objVariantcollection.values;
		} else {
			// otherwise use the first variantcollection in the data object
			
			arrVariantValues = o.variantDataObject.variantcollection[0].values;
		}
		
		// retrieve the first option (choose [varianttype])
		var $firstOption = $variantBox.find('option').eq(0);
		
		// empty the current options and append the previous first option (choose [varianttype])
		$variantBox.empty().append($firstOption);
		
		for(var i = 0, arrLength = arrVariantValues.length; i<arrLength;i++){
			// append new variant options and insert the variantcollection as a data object on the option
			
			// find the variant object for the current productid, so it can be stored as well
			var variantObject;
			for(var j=0, objVarsLength = o.variantDataObject.variants.length; j<objVarsLength; j++){
				if (o.variantDataObject.variants[j].productid == arrVariantValues[i].productid){
					variantObject = o.variantDataObject.variants[j];
					break;
				}
			}
			
			// test if the variant value already exists in this variantbox and do not insert it if it does.
			var variantValueExists = false;
			$variantBox.find('option').each(function(){
				if (arrVariantValues[i].value == $(this).text()){
					variantValueExists = true;
				}
			});
			
			if (!variantValueExists) {
	  		// setup and append the option to the selectbox along with some dataobjects
				$variantBox.append($('<option/>', {
					text: arrVariantValues[i].value,
					value: arrVariantValues[i].productid
				}).data(o.optionDataObjectName, arrVariantValues[i].variantcollection).data(o.optionVariantObjectName, variantObject));
			}
		}
	}
	
	
	
	/**
	 * Update the base layout of the page with the new information, based on the given productid of the selectbox
	 * @param {jQueryObject} $productVariantContainer	The jQuery object for the containing element
	 * @param {jQueryObject} $box	The jQuery object for the selectbox which have been changed
	 * @param {Object} $box	The options object for the plugin
	 */
	function updateBaseLayout($productVariantContainer, $box, o){
		
		/*
		//TODO: make context work properly, so the updateBaseLayout function also is able to handle productlists
		
		var $productContext = $productVariantContainer.closest(o.outerLimitProduct);
		var $productListItemContext = $productVariantContainer.closest(o.outerLimitProductListItem);
		
		// if there is no context, we cannot figure out where to limit ourselves to and therefore we must stop here
		if ($productContext.size() == 0 && $productListItemContext.size() == 0){
			return false;
		}
		*/

		var objVariant = $box.find('option').eq($box.get(0).selectedIndex).data(o.optionVariantObjectName);
		
		// if there is no objVariant, then cancel the entire function
		if (typeof(objVariant) == 'undefined') {
			return false;
		}
		
		// define all the used variables here, that will come from the objVariant object
		var strProductid = '';
		var strNewImage = '';
		var strNetPrice = '';
		var strNetPrice2 = '';
		var intInstock;
		
		// define all references to jQuery objects here
		var $basicProperties = $('#productBasicProperties');
		var $productidInfo = $basicProperties.find('.productidInfo strong');
		var $netprice = $('#jsProductnetprice');
		var $netprice2 = $('#jsProductnetprice2');
		
		// set all the variables here from the object
		
		if (typeof(objVariant.productid) != 'undefined') {
			strProductid = objVariant.productid;
		}
		if (typeof(objVariant.imagefilename) != 'undefined') {
			strNewImage = objVariant.imagefilename;
		}
		if (typeof(objVariant.netprice) != 'undefined') {
			strNetPrice = objVariant.netprice;
		}
		if (typeof(objVariant.netprice2) != 'undefined') {
			strNetPrice2 = objVariant.netprice2;
		}
		
		if (typeof(objVariant.instock) != 'undefined') {
			intInstock = objVariant.instock;
		}
		
		
		
		// #########################################################################
		// the following data will be changed no matter which selectbox is changed #
		// #########################################################################
		
		// change productimage based on variants, if there is an image specified and there is an actual productimage on the page
		if ($('#productImages').size() > 0){
			
			var objFirstimage = $('#productImages').find('img:first');
			var objFirstimageLink = objFirstimage.parent('a');
			if (objFirstimage.size() > 0 && strNewImage != '' && strNewImage != 'undefined'){
	
				var intIndexOfSlash = objFirstimage.attr('src').lastIndexOf('/')+1;
				objFirstimage.attr('src',objFirstimage.attr('src').substring(0,intIndexOfSlash) + strNewImage);
				
				if (objFirstimageLink.size() > 0) {
					var intIndexOfSlash2 = objFirstimageLink.attr('href').lastIndexOf('/')+1;
					objFirstimageLink.attr('href',objFirstimageLink.attr('href').substring(0,intIndexOfSlash2) + strNewImage);
				}
			}
			
			// if we have a lightbox container that should be updated, execute this function, if it exists
			if (typeof updateProductImagesLightbox == 'function'){
				updateProductImagesLightbox();
			}
		}
		
		// change netprice of the product, if it exists on the page and there is something in the variable (not 0,00 and 0.00)
		if ($('#jsProductnetprice').size() > 0 && strNetPrice != '' && strNetPrice != '0,00' && strNetPrice != '0.00'){
			$('#jsProductnetprice').text(strNetPrice);
		}
		
		// change netprice2 of the product, if it exists on the page and there is something in the variable (not 0,00 and 0.00)
		if ($('#jsProductnetprice2').size() > 0 && strNetPrice2 != '' && strNetPrice2 != '0,00' && strNetPrice2 != '0.00'){
			$('#jsProductnetprice2').text(strNetPrice2);
		}
		
		
		
		// #########################################################################################################
		// test if we are at the last selectbox and either reset to defaults or do what the last selectbox defines #
		// #########################################################################################################
		
		if ($productVariantContainer.find('select').index($box) == $productVariantContainer.find('select').size()-1){
			// only do the following if we are at the last selectbox
			
			// change instock status to represent the chosen variant
			if (!isNaN(intInstock) && $basicProperties.size() > 0){
				if (intInstock < 1){
					$basicProperties.find('.instock').hide();
					$basicProperties.find('.notinstock').show();
				} else {
					$basicProperties.find('.instock').show();
					$basicProperties.find('.notinstock').hide();
				}
			}
			
			if (strProductid != '' && $productidInfo.size() > 0){
				$productidInfo.text(strProductid);
			}
			
			
			
		} else {
			// if we are not at the last selectbox, reset some of the page content to the default
			
			// show that the product is in stock since we don't have a variant to measure on yet
			$('#productBasicProperties').find('.instock').show();
			$('#productBasicProperties').find('.notinstock').hide();
			
			// reset the productid information
			if ($productidInfo.size() > 0){
				$productidInfo.text($productidInfo.closest('#productPage').find('form input[name="original_productid"]').val());
			}
			
		}
		
	}
	
	// default values for the options
	$.fn.variantSystem.defaults = {
		productidName: 'productid',
		variantDataObject: null,
		optionDataObjectName: 'variantcollection',
		optionVariantObjectName: 'variant',
		onCreate: null,
		onBeforeChange: null,
		onAfterChange: null,
		updateLayout: null,
		disableUpdateBaseLayout: false,
		outerLimitProduct: '#tProductinfo',
		outerLimitProductListItem: '.productlistVerbose li'
	};
})(jQuery);



/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function () {
	validateForms();
	toggleMainMenu();
	toggleAreaMenu();
	activateAjaxShopping();
	autocompletePostalCode();
	productlistImage();
	postPolls();
	quizWizzard();
	tracktrace();
	feedReader();
	changeProductImage();
	flashLoad();
	openPopups();
	showInlineHelp();

	activatePixDiapo();

	
	//variantSelection();

	// resize the left column as needed, so it fills out 100% of the content
	//resizeLeftColumn();

	$('#productVariantsNew').variantSystem();
});

// resize the left column as needed, so it fills out 100% of the content 
function resizeLeftColumn(){
	var $this = $('#mainLeft');
	$this.height('auto');
	var parentHeight = $this.parent().innerHeight() - parseInt($this.parent().css('padding-top')) - parseInt($this.parent().css('padding-bottom'));
	$this.css({
		height: parentHeight + 'px'
	});
}


function activatePixDiapo() {
	if ($('.pix_diapo').size() > 0) {
		$('.pix_diapo').diapo();
	}
}
