/**
 *Set global variables 
 */
var global_var = {
    ia_paramname_pow_do_ogrzania : 'pow-do-ogrzania',
    ia_paramname_liczba_mieszkancow : 'liczba-mieszkancow',
    ia_cookie_expire: 30
};




/**
 * round float to n decimal points
 */
if (!Number.toFixed) {
  Number.prototype.toFixed=function(n){
    return Math.round(this*Math.pow(10, n)) / Math.pow(10, n);
  }
}

var $ia = jQuery.noConflict();

/* @ia jtutaj
 * based on
 * http://www.kevinleary.net/jquery-fadein-fadeout-problems-in-internet-explorer/
 * 
 *  fadeIn and fadeOut wrapper - png problem for ie
 */
(function($ia) {
	$ia.fn.customFadeIn = function(speed, callback) {
		if($ia.browser.msie && parseInt($ia.browser.version, 10) < 9) {
			$ia(this).show();
			if (callback != undefined) {
				callback();
			}		
		} else {
			$ia(this).fadeIn(speed, function() {
				if (callback != undefined) {
					callback();
				}		
			});
		}
	
	};
	$ia.fn.customFadeOut = function(speed, callback) {
		if($ia.browser.msie && parseInt($ia.browser.version, 10) < 9) {
			$ia(this).hide();
			if (callback != undefined) {
				callback();
			}		
			
		} else {
			$ia(this).fadeOut(speed, function() {
				if (callback != undefined) {
					callback();
				}		
			});
		}
		
	};
})(jQuery);

var configurator;
var cmpProduct;
$ia(document).ready(function() {
    getConfiguratorData();

    


});


/* animation part */

function ia_puff_out(jQueryElement) {
	
	jQueryElement.hide("puff",{},1000);
	
}
function ia_puff_in(jQueryElement) {
	jQueryElement.show("puff",{},1000);

}
/**
 * 
 * @param resultWrapper - box where result is
 * @param resultValueWrapper - a place for value
 * @param resultUnitWrapper - a place for unit
 * @return
 */
function ia_animate_result(resultWrapper,resultValueWrapper,resultUnitWrapper) {
	/* png ie hack 8*/
	if($ia.browser.msie && parseInt($ia.browser.version, 10) < 9) {
		
		resultWrapper.show();
	} else {
		//show result wrapper
		resultWrapper.show('drop', {direction: 'down'} , 1000);	
	}
	
		
}
/**
 * 
 * @param state 
 *   'default' - initial state of product masks: heat products without mask, water & air products with mask
 *   'heat-selected' - second state of product masks: heat products with mask, water & air products without mask
 * @return
 */
function ia_animate_masks_and_year_slider(state) {
	
	if (state === 'default') {
		
		//hide heat product mask
		$ia('.ia-products-mask',$ia('#ia-products-heat')).customFadeOut('slow');
		//show water and air product mask
		$ia('.ia-products-mask',$ia('#ia-products-water,#ia-products-air')).customFadeIn('slow');
		
		//hide year slider
		$ia('#ia-year-slider-container').customFadeOut('slow');
	
	} else if (state == 'heat-selected') {
		//show heat product mask
		$ia('.ia-products-mask',$ia('#ia-products-heat')).customFadeIn('slow');
		// hide water and air product mask
		$ia('.ia-products-mask',$ia('#ia-products-water,#ia-products-air')).customFadeOut('slow');	
		
		//show year slider
		$ia('#ia-year-slider-container').customFadeIn('slow');
	}
		

}
/* -animation part */

function hideMask() {
	ia_puff_out($ia('#ia-mask'));
}

/// This script will format positive money values. Pass it a number
//with or without decimal digits. It will be formatted with the currency,
//thousands, and decimal symbols passed to it.
/// PASSED PARAMETERS
/// theNumber - the number to be formatted
/// theCurrency - the currency symbol
/// theThousands - the thousands separator
/// theDecimal - the decimal separator

function isThousands(position) {
	if (Math.floor(position/3)*3==position) return true;
	return false;
};

function formatMoney (theNumber,theCurrency,theThousands,theDecimal) {
	var theDecimalDigits =
	Math.round((theNumber*100)-(Math.floor(theNumber)*100));
	theDecimalDigits= ""+ (theDecimalDigits + "0").substring(0,2);
	theNumber = ""+Math.floor(theNumber);
	var theOutput = theCurrency;
	for (x=0; x<theNumber.length; x++) {
	theOutput += theNumber.substring(x,x+1);
	if (isThousands(theNumber.length-x-1) && (theNumber.length-x-1
	!=0)) {
	theOutput += theThousands;
	};
	};
	//@ia
	//commented out because we don't need decimals
	//theOutput += theDecimal + theDecimalDigits;
	return theOutput;
};

/**
 * 
 * @param float value - main value to show
 * @param unit - string - description for value
 * @param id - id to set
 * @param resultPart1 - not mandatory partial of main value 
 * @param resultPart2 - not mandatory partial of main value
 * @return taggedResult
 */
function getTaggedResult(value, unit, id, resultPart1, resultPart2) {
    //set font size
    var pStyle = '';
    if(value > 9999999){
        pStyle = 'style = "font-size:26px"';
        
    } else if(value >= 1000000){
            pStyle = 'style = "font-size:28px"';
    } else {
        pStyle = 'style = "font-size:36px"';
    }
    var formattedValue = formatMoney(value,'',' ','.');
    
    var czasAnalizy = configurator.getConfig('czas-analizy');
    var yearPostfix = ' za ' + czasAnalizy + ' lat';
    
    //if main value consists of two values 
    
    if (resultPart1 !== undefined && resultPart2 !== undefined) {
    	//format values to prefered format
    	var formattedResultPart1 = formatMoney(resultPart1,'',' ','.');
    	var formattedResultPart2 = formatMoney(resultPart2,'',' ','.');
    
    	var taggedResult = '<p class="ia-result-wrapper" id="' + id +'"' + pStyle + ' resultPart1="' + formattedResultPart1 + '" resultPart2="'+ formattedResultPart2 +'">' + formattedValue + '</p><p class="ia-result-unit">' + unit + ' ' +yearPostfix + '</p>';
    } else {
    	var taggedResult = '<p class="ia-result-wrapper" id="' + id +'"' + pStyle + '>' + formattedValue + '</p><p class="ia-result-unit">' + unit +  ' ' +yearPostfix + '</p>';	
    }
	
	return taggedResult;
}
 
function showResults(result) {
	
	
	var installationCost = parseFloat(result['installation-cost']).toFixed(-2);
	var operatingCost = parseFloat(result['operating-cost']).toFixed(-2);
	var emission = result['emission'].toFixed(-2);
	
	//alert('installation-cost: ' + installationCost + 'operating-cost' + operatingCost);
	var overall = installationCost + operatingCost;
	
	if (overall !== 0) {
		$ia('#ia-result-overall').customFadeOut(10,function() {
			$ia('#ia-result-overall').html(getTaggedResult(overall,'zł','ia-overall-value',installationCost,operatingCost));
			
			//sets partial values to tooltip
			var tooltip = $ia('#ia-overall-value').parent().prev();
			var installation_value = $ia('#ia-overall-value').attr('resultpart1');
			var operation_value = $ia('#ia-overall-value').attr('resultpart2');
			$ia('#ia-installation-value',tooltip).html(installation_value);
			$ia('#ia-operation-value',tooltip).html(operation_value);
			
			//animate result
			ia_animate_result($ia('#ia-result-overall'),$ia('#ia-overall-value'),$ia('.ia-result-unit',$ia('#ia-result-overall')));
				
					
		});
		
	} else {
		$ia('#ia-result-overall').customFadeOut(10);
		$ia('#ia-result-overall').html('<span class="ia-result-question">?</span>');
		$ia('#ia-result-overall').customFadeIn(1000);
	}
	
	if (emission >=0 && overall !==0) {
		$ia('#ia-result-ecological-footprint').customFadeOut(10,function() {
			$ia('#ia-result-ecological-footprint').html(getTaggedResult(emission,'ton CO<sub>2</sub>','ia-ecological-value'));
			
			ia_animate_result($ia('#ia-result-ecological-footprint'),$ia('#ia-ecological-value'),$ia('.ia-result-unit',$ia('#ia-result-ecological-footprint')));
		});
	} else {
		$ia('#ia-result-ecological-footprint').customFadeOut(10);
		$ia('#ia-result-ecological-footprint').html('<span class="ia-result-question">?</span>');
		$ia('#ia-result-ecological-footprint').customFadeIn(1000);
	}
	
}
/**
 *
 */

function displayStep(bCheckCookie){
    //this is boolean value, if data are not get from cookies then are get from input fields
    var bDataFromCookies = false;
    var ia_val_param_pow_do_ogrzania = false;
    var ia_val_param_liczba_mieszkancow = false;
    if(bCheckCookie){
        ia_val_param_liczba_mieszkancow = $ia.cookie(global_var.ia_paramname_liczba_mieszkancow);
        ia_val_param_pow_do_ogrzania = $ia.cookie(global_var.ia_paramname_pow_do_ogrzania);
        if(!isNaN(ia_val_param_liczba_mieszkancow) && ia_val_param_liczba_mieszkancow && !isNaN(ia_val_param_pow_do_ogrzania) && ia_val_param_pow_do_ogrzania){
            bDataFromCookies = true; //now data won't be read from input fields
        } else {
            //not exits required cookie, will be display step 1
            return ;
        }
    }
                
    //if date aren't get from cookies then get from input
    if(!bDataFromCookies){
        ia_val_param_pow_do_ogrzania = $ia('#ia_init_val_param_pow_do_ogrzania').val();
        ia_val_param_liczba_mieszkancow = $ia('#ia_init_val_param_liczba_mieszkancow').val();    
    }
                
    //cookie are always set even when val is get from there becasue expires needs update
    $ia.cookie(global_var.ia_paramname_liczba_mieszkancow, ia_val_param_liczba_mieszkancow, {
        expires: global_var.ia_cookie_expire
        });
    $ia.cookie(global_var.ia_paramname_pow_do_ogrzania, ia_val_param_pow_do_ogrzania, {
        expires: global_var.ia_cookie_expire
        });
    /*
		 * transfer data to horizontal inputs
		 */
                
    $ia('#ia_val_param_pow_do_ogrzania').val(ia_val_param_pow_do_ogrzania);		
    $ia('#ia_val_param_liczba_mieszkancow').val(ia_val_param_liczba_mieszkancow);
    /**
		 * switch steps
		 */
    $ia('#ia-main-teaser').customFadeOut('slow', function(){
        $ia('#ia-inputs').css('display','block');
    });
    //hide step2 name if data from cookie
    if(bDataFromCookies){
        $ia('.ia-step-name', '#ia-step2').css('display','none');
    }
    $ia('#ia-step1').customFadeOut('slow', function() {
        $ia('#ia-step2').customFadeIn('slow', function() {
            /* start scroll bar */
            $ia('#ia-products-heat').tinyscrollbar({
                sizethumb: 76
            });
        });
			
    });
		
    //show ia-area borders
    $ia("#ia-heat-area").css('border-width','1px');
    $ia("#ia-water-area").css('border-width','1px');
    $ia("#ia-air-area").css('border-width','1px');
    
    //show cmp box if cookie exists
    var oCmp = new IA_Comparison();
    oCmp.displayCmpBoxFromCookie();
    oCmp = null;
    
}
function displayProductBar(type,name) {
	
	//set name
	$ia('.ia-dp-name',$ia('#ia-ldp-' + type)).html(name);
	
	//show button
	$ia('#ia-ldp').css('display','inline');
	$ia('#ia-ldp-' + type).css('display','inline');
}
/**
 * replaces img src param.
 * @param imgElement = jQuery image element
 * @return
 */
function changeIAImgElementSrc(imgElement, src) {
	$ia(imgElement).attr('src',src);
}
/**
 * 
 * @param configurator
 * @param type - heat/water/air
 * @param id - product id
 * @return
 */
function deleteProduct(configurator,type,id) {
	
	//unregister from LDP
	configurator.unregisterProduct(type);
	
	//move back to rest of Prods
	moveProductToDefault(id);
	
	//enable droppable
	$ia("#ia-" + type + "-area").droppable( "option", "disabled", false );
	$ia("#ia-" + type + "-area").css('border-width','1px');
	
	//hide dp by type
	$ia('#ia-ldp-' + type).customFadeOut('slow');

	refreshBenefits(configurator);
	
	
	//if last product
	if (!configurator.RegisteredIds['heat'] && !configurator.RegisteredIds['water'] && !configurator.RegisteredIds['air']) {
		//hide ldp 
		$ia('#ia-ldp').customFadeOut('slow');
		//hide comparison-button-wrapper
		$ia('#ia-comparison-button-wrapper').customFadeOut('slow');
		
		ia_animate_masks_and_year_slider('default');
		
	}
}
function refreshProductBars(configurator) {
	
	if (configurator.RegisteredIds['heat']) {
		//get registered heat product
		var HeatProduct = configurator.getProductById(configurator.RegisteredIds['heat']);

		//HEAT 
		
		displayProductBar('heat',HeatProduct.name);
		
		//show comparison-button-wrapper
		$ia('#ia-comparison-button-wrapper').css('display','inline');
		
		if (configurator.RegisteredIds['water']) {
			
			//get registered water product
			var WaterProduct = configurator.getProductById(configurator.RegisteredIds['water']);
		
			//WATER 
			displayProductBar('water',WaterProduct.name);
			
			//unbind previously binded click handler
			$ia('.ia-delete-product',$ia('#ia-ldp-water')).unbind('click');
			//WATER bind click handler (delete product)
			$ia('.ia-delete-product',$ia('#ia-ldp-water')).click(function(){
				
				//deleteProduct
				deleteProduct(configurator,'water',WaterProduct.id);
				
				showResults(configurator.calculate());		
				refreshBenefits(configurator);
			});		
			
		}
		
		if (configurator.RegisteredIds['air']) {
			
			//get registered air product
			var AirProduct = configurator.getProductById(configurator.RegisteredIds['air']);
			
			//AIR 
			displayProductBar('air',AirProduct.name);
			
			//unbind previously binded click handler
			$ia('.ia-delete-product',$ia('#ia-ldp-air')).unbind('click');
			//AIR bind click handler (delete product)
			$ia('.ia-delete-product',$ia('#ia-ldp-air')).click(function(){
				
				//deleteProduct
				deleteProduct(configurator,'air',AirProduct.id);
				
				showResults(configurator.calculate());		
				refreshBenefits(configurator);
			});		
		}
	
		//unbind previously binded click handler
		$ia('.ia-delete-product',$ia('#ia-ldp-heat')).unbind('click');
		//HEAT bind click handler (delete product)
		$ia('.ia-delete-product',$ia('#ia-ldp-heat')).click(function(){
			
			//deleteProduct
			deleteProduct(configurator,'heat',HeatProduct.id);
	
			if (configurator.RegisteredIds['water']) {
				var WaterProduct = configurator.getProductById(configurator.RegisteredIds['water']);
			
				deleteProduct(configurator,'water',WaterProduct.id);
				
			}
			if (configurator.RegisteredIds['air']) {
				var AirProduct = configurator.getProductById(configurator.RegisteredIds['air']);
			
				deleteProduct(configurator,'air',AirProduct.id);
				
			}
			showResults(configurator.calculate());
			refreshBenefits(configurator);
			
			
		});
	} else {
		/* clearAll */
	}

}
function refreshBenefits(configurator) {
	var k;
	var i;
	var all_pros = '';
	var all_cons = '';
	var pros = [];
	var cons = [];
	var types = ['heat','water','air'];
	
	var defaultHeader = '<p>Dodatkowe korzyści</p>';
	/*
	 * for each type get product and push its features to tables
	 */
	for (k=0;k<types.length;k++) {
		if (configurator.RegisteredIds[types[k]]) {
			//get registered heat product
			var Product = configurator.getProductById(configurator.RegisteredIds[types[k]]);
			if (Product.Features.length !== 0) {
				
				for (i=0; i<Product.Features.length; i++) {
					if (Product.Features[i].is_virtue == 1) {
						pros.push(Product.Features[i].description);
					}
					else {
						cons.push(Product.Features[i].description);
					}
				}
			}
			
		}	
	}
	
	if (pros.length !== 0) {
		for (var i=0;i<pros.length;i++) {
			 all_pros += '<span>' + pros[i] + '</span>';
		}
		all_pros = defaultHeader + all_pros;
	} else {
		all_pros = '';
	}
	if (cons.length !== 0) {
		for (var i=0;i<cons.length;i++) {
			 all_cons += '<span>' + cons[i] + '</span>';
		}	
	} else {
		all_cons = '';
	}
	
	
	$ia('#ia-benefit-pros').html(all_pros);
	$ia('#ia-benefit-cons').html(all_cons);
}
/*
 * Moves product to its default position
 */
function moveProductToDefault(id) {
	var imgElement = $ia('img','div[product-id="' + id + '"]');
	var Product = configurator.getProductById(id);
	
	
	
	/*
	 * delete product clone in droppable area
	 * (it's id ends with area)
	 */
	$ia('div[product-id="' + id + '"]',$ia('[id$="area"]')).remove();
	//show product on the right side again
	$ia('img','div[product-id="' + id + '"]').css('visibility','visible');
}

/**
 * Function shows results (after calculation), refresh Product Bars, refresh benefits
 * @param oConfigurator
 * @return
 */
function refreshAll(oConfigurator) {
	showResults(oConfigurator.calculate());
	refreshProductBars(oConfigurator);
	refreshBenefits(oConfigurator);

}
/**
 * Function operates with Draggable to show it in droppable area properly 
 * 
 * @param ui (jQuery ui object)
 * @param droppable (droppable area)
 * @return
 */
function operateDraggable(ui,droppable) {
	

	//hide small picture on the right side
	$ia('img',ui.draggable).css('visibility','hidden');
        
	
	//clone small picture to show it in droppable area 
	var draggableClone = ui.draggable.clone();
	
	// switch clone small picture to big one
	var imgElement = $ia('img',draggableClone);
	var Product = configurator.getProductById(draggableClone.attr("product-id"));
	changeIAImgElementSrc(imgElement, Product.img_url_dropped);
	
	
	draggableClone.appendTo(droppable);
	
	//now clone is ready to be displayed
	$ia('img',draggableClone).css('visibility','visible');
        $ia('img',draggableClone).css('cursor','default');
	
}
/**
 * @param JSON oResponse - this is data get from server as JSON and storage in Configurator.Data
 */
function initConfigurator(oResponse) {
    //constants
    //set min and max value param pow-do-ogrzania
    var i_min_pow_do_ogrzania = 1;
    var i_max_pow_do_ogrzania = 500;
    //set min and max value param liczba-mieszkancow
    var i_min_liczba_mieszkancow = 1;
    var i_max_liczba_mieszkancow = 9;
    
    configurator = new Configurator();
    configurator.setConfiguratorData(oResponse);
    cmpProduct = new IA_Comparison();
    setComparisonHandler();
    configurator.setParamsHandler('ia_init_val_param_pow_do_ogrzania',global_var.ia_paramname_pow_do_ogrzania, false, i_min_pow_do_ogrzania, i_max_pow_do_ogrzania);
    configurator.setParamsHandler('ia_init_val_param_liczba_mieszkancow', global_var.ia_paramname_liczba_mieszkancow, true, i_min_liczba_mieszkancow, i_max_liczba_mieszkancow);
    
    configurator.setParamsHandler('ia_val_param_pow_do_ogrzania', global_var.ia_paramname_pow_do_ogrzania, false, i_min_pow_do_ogrzania, i_max_pow_do_ogrzania);
    configurator.setParamsHandler('ia_val_param_liczba_mieszkancow', global_var.ia_paramname_liczba_mieszkancow, true, i_min_liczba_mieszkancow, i_max_liczba_mieszkancow);
    
    $ia('#ia-consult-button-wrapper').live('click', function(){
        var url = configurator.Data.SiteConfig.consult_link;
        if(url){
            window.location.href = url;
        }
    });
	for (var i=0;i<configurator.Data.Products.length;i++) {
		
		var ProductId = configurator.Data.Products[i].id;
		
		//set default css left and top
		$ia('div[product-id="' + ProductId + '"]').css("left", 0);
		$ia('div[product-id="' + ProductId + '"]').css("top", 0);
		
		//save default src, left and top position
		$ia('div[product-id="' + ProductId + '"]').data("Left", 0);
		$ia('div[product-id="' + ProductId + '"]').data("Top", 0);
		
		
		//alert($ia('div[product-id="' + ProductId + '"]').data("Left"));
		$ia('div[product-id="' + configurator.Data.Products[i].id + '"]').draggable({
			scope: configurator.Data.Products[i].type,
			revert: 'invalid',
			snap: '.drop-area',
			snapMode: 'inner',
			snapTolerance: 25, /* half of area width */
			/* create helper 
			 * to get rid of overflow hidden and z-index problem 
			 * when dragging outside of overflow hidden pane */
			helper: function (e,ui) {
		      return $ia(this).clone().appendTo('body').css('zIndex',5).show();
		    },
			stop: function(e,ui) {
		    	//if product is not in droppable area
		    	if ($ia('div[product-id="' + $ia(this).attr('product-id') + '"]',$ia('[id$="area"]')).length <= 0) {
		    		$ia('img',$ia(this)).css('visibility','visible');
		    	}
		    	
		    }
		});

	};
	
	$ia("#ia-heat-area").droppable({
		
		scope: 'heat',
		/*
		 * $this don't work so there are 3 definitions for each droppable
		 * scope: $ia(this).attr("id"),
		 *  
		 */
		activate: function(event, ui) { 
		
			$ia('img',ui.draggable).css('visibility','hidden');
			$ia(this).css('border-width','6px');
		},
		deactivate: function(event, ui) { 
			
			
			$ia(this).css('border-width','1px');
		},

		drop: function(event,ui) { 
			
			/* puts draggable into droppable */ 				
			operateDraggable(ui,$ia(this));
			
			// hide step info
			$ia('.ia-step-name',$ia('#ia-step2')).css('visibility','hidden');
			
			ia_animate_masks_and_year_slider('heat-selected');
			
			//after drop - disable droppable for other products 
			$ia(this).droppable( "option", "disabled", true );
			$ia(this).css('border-width','0px');
			//registerProduct to List of Dropped Products
			configurator.registerProduct(ui.draggable.attr("product-id"),'heat');
			
			refreshAll(configurator);
		}
	});
	
	$ia("#ia-water-area").droppable({
		
		scope: 'water',
		activate: function(event, ui) { 
			$ia('img',ui.draggable).css('visibility','hidden');
			$ia(this).css('border-width','6px');
		},
		deactivate: function(event, ui) { 
	
			$ia(this).css('border-width','1px');
		},
		drop: function(event,ui) { 
				
			
			if (configurator.RegisteredIds['heat']) {
				
				/* puts draggable into droppable */ 				
				operateDraggable(ui,$ia(this));
				
				// after successful drop - disable droppable for other products 
				$ia(this).droppable( "option", "disabled", true );
				$ia(this).css('border-width','0px');
				
				//registerProduct to List of Dropped Products
				configurator.registerProduct(ui.draggable.attr("product-id"),'water');
				
				refreshAll(configurator);
				
			}
			else {
								
				displayAlert('Najpierw przeciągnij produkt z kategorii ciepło');
				moveProductToDefault(ui.draggable.attr("product-id"));
				
			}
			
	
		}
	});
	$ia("#ia-air-area").droppable({
		
		scope: 'air',
		activate: function(event, ui) { 
			$ia('img',ui.draggable).css('visibility','hidden');
			//$ia(this).css('background','white');
			$ia(this).css('border-width','6px');
			
		},
		deactivate: function(event, ui) { 
			//$ia(this).css('background','transparent');
			$ia(this).css('border-width','1px');
		},
		drop: function(event,ui) { 
			
			if (configurator.RegisteredIds['heat']) {
				
				/* puts draggable into droppable */ 				
				operateDraggable(ui,$ia(this));
				
				// after drop - disable droppable for other  products 
				$ia(this).droppable( "option", "disabled", true );
				$ia(this).css('border-width','0px');
				
				//registerProduct to List of Dropped Products
				configurator.registerProduct(ui.draggable.attr("product-id"),'air')
				refreshAll(configurator);
				
			}
			else {
				
				displayAlert('Najpierw przeciągnij produkt z kategorii ciepło');
				moveProductToDefault(ui.draggable.attr("product-id"));
				
			}
	
		}
	});
	/**
	 * 'ia-next-step' click handler
	 */
	$ia('#ia-next-step').click(function(){
            displayStep(false);       	
	});
	
	/**
	 * ia-products-mask hover handler
	 */
	$ia('.ia-products-mask').hover(
		function() {
			
			$ia('.ia-mask-description',$ia(this)).customFadeIn();
		},
		function() {
			$ia('span',$ia(this)).customFadeOut();
		}
	);
	
	/**
	 * white tooltips over results
	 */
	$ia('#ia-overall-value').live('mouseover mouseout', function(event) {
			if (event.type == 'mouseover') {
				$ia('#ia-overall-value').parent().prev().css('top','-95px');
				$ia('#ia-overall-value').parent().prev().customFadeIn();
			} else {
				$ia('#ia-overall-value').parent().prev().customFadeOut();
			}
	});
	$ia('#ia-ecological-value').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$ia('#ia-ecological-value').parent().prev().css('top','-138px');
			$ia('#ia-ecological-value').parent().prev().customFadeIn();
		} else {
			$ia('#ia-ecological-value').parent().prev().customFadeOut();
		}
	});
	

	/**
	 * year horizontal slider 
	 */
	
	$ia( "#ia-year-slider" ).slider({
		value:20,
		min: 10,
		max: 30,
		step: 10,
		slide: function( event, ui ) {
			configurator.setConfig('czas-analizy', ui.value);
        	var result = configurator.calculate();
        	showResults(result);
			
		}
	});
	
        displayStep(true);
	hideMask();
}

function Configurator() {
        
    /**
     *This function set Configurator.Data
     * @param Configurator oConfigurator - Configurator object
     * @param JSON oResponse - this is json object configurator data, get by ajax from server
     * @return void
     */
	this.RegisteredIds = new Array();
	
    this.setConfiguratorData = function(oResponse){
        this.Data = oResponse;
    }
	this.registerProduct = function(id, type) {
		
		this.RegisteredIds[type] = id;
		
		//alert('Registered: ' + this.RegisteredIds[type]);
		
		return true;
	}
	this.unregisterProduct = function(type) {
		this.RegisteredIds[type] = null;
		
		return true;
	}
	this.getProductById = function(id) {
		for (i=0;i<this.Data.Products.length;i++) {
			if (this.Data.Products[i].id == id) {
				return this.Data.Products[i];
			}
		}
	}
	this.getRegisteredProductIdByType = function(type) {
		return this.RegisteredIds[type];
	}
	
	/*
	 * gets heat part of result
	 */
	this.getHeatResult = function() {
		var result = new Array();
		
		/* 
		 * hear put real equations 
		 */
		var i;
		var moc = this.get_moc();
		
		//alert(moc);
		
		result['installation-cost'] = this.getInstallationCostByType('heat',moc);
		result['operating-cost']= this.getOperatingCostByType('heat');
		result['emission']= this.getEmissionByType('heat');
		
		return result;
	}
	/*
	 * gets water part of result
	 */
	this.getWaterResult = function(result) {
		
		var oProduct = this.getProductById(this.getRegisteredProductIdByType('water'));
		
		var dzienne_zapotrzebowanie_na_energie = this.get_dzienne_zapotrzebowanie_na_energie();
		var installation_cost = this.getInstallationCostByType('water',dzienne_zapotrzebowanie_na_energie) * (1 - this.getProductParam(oProduct,'procent-dotacji-do-zakupu'));
		
		var operating_cost = this.getOperatingCostByType('water');
		
		//alert('installation-cost: ' + installation_cost + 'operating-cost' + operating_cost);
		
		result['installation-cost'] += installation_cost;
		result['operating-cost'] += operating_cost;
		result['emission'] -= this.getEmissionByType('water');
		return result;
	}
	/**
	 * gets air part of result
	 */
	this.getAirResult = function(result) {
		
		var oProduct = this.getProductById(this.getRegisteredProductIdByType('air'));
		
		var kubatura = this.get_kubatura();
		var installation_cost = this.getInstallationCostByType('air',kubatura);
		
		var operating_cost = this.getOperatingCostByType('air');
		
		//alert('installation-cost: ' + installation_cost + 'operating-cost' + operating_cost);
		
		result['installation-cost'] += installation_cost;
		result['operating-cost'] += operating_cost;
		result['emission'] -= this.getEmissionByType('air');
		
		return result;
	}
	/**
	 * type - 'heat', 'water', 'air'
	 * value_to_compare - moc/kubatura/other
	 */
	this.getInstallationCostByType = function(type,value_to_compare) {
		
		var Product = this.getProductById(this.getRegisteredProductIdByType(type));
		var installation_cost;
		
		for (i=0;i<Product.InstallScope.length;i++) {
			
			if (value_to_compare <= Product.InstallScope[i].power) {
				return parseFloat(Product.InstallScope[i].cost);
			}
		}
		
		return parseFloat(Product.InstallScope[Product.InstallScope.length-1].cost);
            
	}
	/**
	 * This function gets operating cost by type
	 * @param String type - possible values: 'heat','water','air'
	 * @return Float
	 */
	this.getOperatingCostByType = function(type) {
		var oProduct = this.getProductById(this.getRegisteredProductIdByType(type));
		var operating_cost;
		
		if(oProduct.type == 'heat') {
			 operating_cost = this.get_koszt_serwisu_w_zadanym_czasie(oProduct) + this.get_koszt_paliwa_w_zadanym_czasie(oProduct);
			 //alert('koszt paliwa w zadanym czasie' + this.get_koszt_paliwa_w_zadanym_czasie(oProduct));
		} else if (oProduct.type == 'water') {
			operating_cost = this.get_koszt_serwisu_w_zadanym_czasie(oProduct) - this.get_oszcz_paliwa_w_zadanym_czasie(oProduct);
		} else if (oProduct.type == 'air') {			
			operating_cost = this.get_koszt_serwisu_w_zadanym_czasie(oProduct) - this.get_oszcz_paliwa_w_zadanym_czasie(oProduct);
		}
		return parseFloat(operating_cost);
	}
	/**
	 * This function gets CO2 emission by type
	 * @param String type - possible values: 'heat','water','air'
	 * @return Float
	 */
	this.getEmissionByType = function(type) {
		var oProduct = this.getProductById(this.getRegisteredProductIdByType(type));
		var emission;
		
		if(oProduct.type == 'heat') {
			 emission = this.get_zapotrzebowanie_na_energie_w_ciagu_zadanego_czasu() / (this.getProductParam(oProduct,'cop') * this.getProductParam(oProduct,'sprawnosc-ukladu')) * oProduct.Fuel.emission; 
			 
		} else if (oProduct.type == 'water') {
			var heatProduct = this.getProductById(this.getRegisteredProductIdByType('heat'));
			emission = this.get_oszcz_energii_w_roku(oProduct) * this.getConfig('czas-analizy') / this.getProductParam(heatProduct,'cop') * heatProduct.Fuel.emission;
		} else if (oProduct.type == 'air') {		
			var heatProduct = this.getProductById(this.getRegisteredProductIdByType('heat'));
			var czas_analizy = this.getConfig('czas-analizy');
			emission = this.get_oszcz_w_roku_bez_uwzgl_potrzeb_wlasnych_urzadzenia(oProduct) * czas_analizy / this.getProductParam(heatProduct,'cop') * heatProduct.Fuel.emission - this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew() * czas_analizy * oProduct.Fuel.emission;
			
		}
		return parseFloat(emission);
	}
	this.calculate = function() {
		
		//result has installation cost and operating cost
		var result;
		
		if (this.RegisteredIds['heat']) {
			
			
			result = this.getHeatResult();
			
			if (this.RegisteredIds['water']) {
				result = this.getWaterResult(result);
			};
			if (this.RegisteredIds['air']) {
				result = this.getAirResult(result);
			}
			return result;
		} else {
			
			result = new Array();
			result['installation-cost']=0;
			result['operating-cost']=0;
			result['emission']=0;
			
			
			return result;
		}

	}
        /**
         *This function set handlers focus and change for param input and exec hanlder functions.
         * @param string sId - DOM elemnt id (don't use prefix #)
         * @param string sParamName - param name stored in Confiuguratar.Data.Config - this variable will be updated when handle onChange
         * @param boolean bParseToInt - If varaible is set as true then input data will be parse to intieger
         * @param integer iMinVal - if value is less than iMinVal then value is set as iMimValue, if not use min value then set -1
         * @param integer iMaxVal - if value is greater than iMaxVal then value is set as iMaxValue, if not use max value then set -1
         * @return void()
         */
        this.setParamsHandler = function(sId, sParamName, bParseToInt, iMinVal, iMaxVal){
            var el = $ia('#'+sId);
            iMinVal = parseInt(iMinVal, 10);
            iMaxVal = parseInt(iMaxVal, 10);
            el.focus(function(){
                configurator.onFocusParams(el);
            });
            el.change(function(){
                configurator.onChangeParams(el, sParamName, bParseToInt, iMinVal, iMaxVal);
            });
            
        }
        /**
         * This function is exec when param input field will be focused.
         * Input filed value is get and store in attribute tmpValue (uses when rollback).
         * Background field is reset(when error has occured background is set to red)
         * @param object el - DOM input element
         */
        this.onFocusParams = function(el){
            iVal = el.val();
            el.attr('tmpValue', iVal);
            el.css('background', '');
        }
        
        /**
         * This function is exex when param input field will be changed
         * If input value is correct then for this variable Config is updated, resutl is recalculated
         * and refreshed. Temporary value for rollback is reset
         * Else input value is rollback
         * @param object el - DOM input element
         * @param string sParamName - this is config name which will be updated when input correct
         * @param boolean bParseToInput - thi varibable cause that if is set to true then input value is parse to integer
         * @param integer iMinVal - if value is less than iMinVal then value is set as iMimValue, if not use min value then set -1
         * @param integer iMaxVal - if value is greater than iMaxVal then value is set as iMaxValue, if not use max value then set -1
         * @return void()
         */
        this.onChangeParams = function(el, sParamName, bParseToInt, iMinVal, iMaxVal){
            iVal = false;
            iVal = el.val();
            if(!isNaN(iVal) && iVal){
                if(bParseToInt){
                    iVal = parseInt(iVal, 10);

                }
                //constraint for min val
                if(iMinVal !=-1 && iMinVal > iVal){
                    iVal = iMinVal;
                }
                if(iMaxVal !=-1 && iMaxVal < iVal){
                    iVal = iMaxVal;
                }
                el.val(iVal);
            
                if(this.setConfig(sParamName, iVal)){
                    var result = this.calculate();
                    showResults(result);
                    el.attr('tmpValue','');
                     $ia.cookie(sParamName, iVal, {expires: global_var.ia_cookie_expire});
                } else {
                    this.rollbackOnChangeParams(el);
                }
            } else {
                this.rollbackOnChangeParams(el);
            }
            
        }
        
        /**
         * This function is exec when onChangeParam function faild.
         * Value is get from tmpValue and update, tmpValue is reset and background is set to red
         */
        this.rollbackOnChangeParams = function(el){
            var tmpVal = el.attr('tmpValue');
            el.val(tmpVal);
            el.attr('tmpValue', '');
            el.css('background', 'red');
            displayAlert('Niepoprawna wartość parametru.');
            
        }
        
	/**
	 * This function return parameter from Config (part of JSON object)
	 * @param param_name - name of parameter
	 * @return Float parameter value
	 */
	this.getConfig = function(param_name) {
		for (i=0;i<this.Data.Config.length;i++) {
			if (this.Data.Config[i].name == param_name) {
				
				return parseFloat(this.Data.Config[i].value);
			}
		}
		return false;
	}
        /**
         * This function find Config by name and set value.
         *  If value is incorrect then function return false otherwise true.
         *  
         * @param string sParamName - config name
         * @param integer iValue - value of config
         */
        this.setConfig = function(sParamName, iValue){
            if(isNaN(iValue)){
                return false; 
            }
            var length = this.Data.Config.length;
            while(length >0){
                if (this.Data.Config[length-1].name == sParamName) {
                    this.Data.Config[length-1].value = iValue;
                    length = 0;
                } else {
                    length--;
                }
            }
            return true;
        }
        
	this.getProductParam = function(oProduct, param_name) {
		for (i=0;i<oProduct.Params.length;i++) {
			if (oProduct.Params[i].name == param_name) {
				
				return parseFloat(oProduct.Params[i].value);
			}
		}
		return false;
	}
	this.get_moc = function() {
		var moc = this.get_moc_potrzebna_do_ogrzania_budynku() + this.get_moc_potrzebna_do_ogrzania_wody();
		
		return moc;
	}
	this.get_dzienne_zapotrzebowanie_na_energie = function() {
		var dzienne_zapotrzebowanie_na_energie = this.get_cieplo_wlasciwe() * this.getConfig('liczba-mieszkancow') * this.getConfig('srednie-dzienne-zuzycie-cwu-na-osobe') * (this.getConfig('temp-cieplej-wody') - this.getConfig('temp-zimnej-wody'));

		return parseFloat(dzienne_zapotrzebowanie_na_energie);
	}
	this.get_moc_potrzebna_do_ogrzania_budynku = function() {
		var moc_potrzebna_do_ogrzania_budynku = this.get_kubatura() * this.getConfig('wsk-zapotrz-na-moc-cieplna-m3')/1000;
		//alert('moc_potrzebna_do_ogrzania_budynku' + parseFloat(moc_potrzebna_do_ogrzania_budynku));
		return parseFloat(moc_potrzebna_do_ogrzania_budynku); 
	}
	this.get_moc_potrzebna_do_ogrzania_wody = function() {
		return parseFloat(0);
	}
	this.get_koszt_serwisu_w_zadanym_czasie = function(oProduct) {
		var koszt_serwisu_w_zadanym_czasie = this.getProductParam(oProduct,'roczny-koszt-serwisu-urz') * this.getConfig('czas-analizy');
		
		return parseFloat(koszt_serwisu_w_zadanym_czasie);
	}
	this.get_koszt_paliwa_w_zadanym_czasie = function(oProduct) {
		var calkowite_roczne_zapotrzebowanie_na_energie = this.get_calkowite_roczne_zapotrzebowanie_na_energie();
		
		var get_koszt_paliwa_w_zadanym_czasie = this.get_paliwo_za_rok(oProduct,calkowite_roczne_zapotrzebowanie_na_energie) * (1 - Math.pow(1 + parseFloat(oProduct.Fuel.price_growth),this.getConfig('czas-analizy')))/(-parseFloat(oProduct.Fuel.price_growth));
		//alert('get_paliwo_za_rok' + this.get_paliwo_za_rok(oProduct,calkowite_roczne_zapotrzebowanie_na_energie));
		return parseFloat(get_koszt_paliwa_w_zadanym_czasie);
	}
	this.get_oszcz_paliwa_w_zadanym_czasie = function(oProduct) {
		var heatProduct = this.getProductById(this.getRegisteredProductIdByType('heat'));
		var oszcz_energii_w_roku = this.get_oszcz_energii_w_roku(oProduct);
		
		//passing HeatProduct because this is equation for savings based on heatProduct fuel
		if (oProduct.type == 'water') {
			var total_paliwo_za_rok = this.get_paliwo_za_rok(heatProduct,oszcz_energii_w_roku);
		} else if (oProduct.type == 'air') {
			var total_paliwo_za_rok = this.get_paliwo_za_rok(heatProduct,oszcz_energii_w_roku) - this.get_koszt_en_elektrycznej_na_prace_rekuperatora();
		}
		var oszcz_paliwa_w_zadanym_czasie = total_paliwo_za_rok * (1 - Math.pow(1 + parseFloat(heatProduct.Fuel.price_growth),this.getConfig('czas-analizy')))/(-parseFloat(heatProduct.Fuel.price_growth));
		return parseFloat(oszcz_paliwa_w_zadanym_czasie);
	}
	/**
	 * 
	 * @param bidOrSavingRate - if heat - it's bid for energy, if water or air- it's saving of energy
	 * 
	 */
	this.get_paliwo_za_rok = function(oProduct, bidOrSavingRate) {
		var udzial_energii_el_w_taryfie_dziennej = parseFloat(this.getProductParam(oProduct,'udzial-energii-el-w-taryfie-dziennej'));
		var paliwo_za_rok = (bidOrSavingRate / oProduct.Fuel.fuel_value * (oProduct.Fuel.day_price * udzial_energii_el_w_taryfie_dziennej + oProduct.Fuel.night_price * (1 - udzial_energii_el_w_taryfie_dziennej)) / this.getProductParam(oProduct,'sprawnosc-ukladu')) / this.getProductParam(oProduct,'cop');
		
		//alert('paliwo_za_rok' + paliwo_za_rok);
		return parseFloat(paliwo_za_rok);
	}
	
	this.get_calkowite_roczne_zapotrzebowanie_na_energie = function() {
		var calkowite_roczne_zapotrzebowanie_na_energie = this.get_roczne_zapotrzebowanie_na_energie('heat') + this.get_roczne_zapotrzebowanie_na_energie('water');
		
		
		return parseFloat(calkowite_roczne_zapotrzebowanie_na_energie);
	}
	this.get_zapotrzebowanie_na_energie_w_ciagu_zadanego_czasu = function() {
		var zapotrzebowanie_na_energie_w_ciagu_zadanego_czasu = this.get_calkowite_roczne_zapotrzebowanie_na_energie() * this.getConfig('czas-analizy');
		return parseFloat(zapotrzebowanie_na_energie_w_ciagu_zadanego_czasu);
	}
	this.get_oszcz_energii_w_roku = function(oProduct) {
		var oszcz_energii_w_roku;
		
		if(oProduct.type=='water') {
			
			oszcz_energii_w_roku = this.getProductParam(oProduct,'stopien-pokrycia') * this.get_roczne_zapotrzebowanie_na_energie('water');
		
		} else if (oProduct.type == 'air') {
			oszcz_energii_w_roku = this.get_strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN() * this.getProductParam(oProduct,'sprawnosc-ukladu');
		}
		return parseFloat(oszcz_energii_w_roku);
	}
	/**
	 * function returns roczne zapotrzebowanie na energię depending on type
	 * @param String type (heat/water)
	 * @return roczne_zapotrzebowanie_na_energie
	 */
	this.get_roczne_zapotrzebowanie_na_energie = function(type) {
		var roczne_zapotrzebowanie_na_energie;
		if (type=='heat') {
		
			roczne_zapotrzebowanie_na_energie = this.get_kubatura() * this.getConfig('wsk-zapotrz-na-moc-cieplna-m3') * this.getConfig('czas-pracy') / 1000;
			
		}else if (type == 'water') {
			
			roczne_zapotrzebowanie_na_energie = this.get_cieplo_wlasciwe() * this.get_roczne_zuzycie_cwu() * (this.getConfig('temp-cieplej-wody') - this.getConfig('temp-zimnej-wody')); 
		
		} else {
		
			roczne_zapotrzebowanie_na_energie = false;
		
		}
		return parseFloat(roczne_zapotrzebowanie_na_energie);
		
	}
	this.get_roczne_zuzycie_cwu = function() {
		var roczne_zuzycie_cwu = this.getConfig('liczba-mieszkancow') * this.getConfig('srednie-dzienne-zuzycie-cwu-na-osobe') * 365;
		return parseFloat(roczne_zuzycie_cwu);
	}
	this.get_cieplo_wlasciwe = function() {
		var cieplo_wlasciwe = 0.001166676;
		return parseFloat(cieplo_wlasciwe);
	}
	this.get_kubatura = function() {
		var kubatura = this.getConfig('pow-do-ogrzania') * this.getConfig('srednia-wysokosc-pomieszczen');
		return parseFloat(kubatura);
	}
	this.get_koszt_en_elektrycznej_na_prace_rekuperatora = function() {
		
		var oProduct = this.getProductById(this.getRegisteredProductIdByType('air'));
		
		var udzial_energii_el_w_taryfie_dziennej = parseFloat(this.getProductParam(oProduct,'udzial-energii-el-w-taryfie-dziennej'));
		
		var koszt_en_elektrycznej_na_prace_rekuperatora = this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew() * (oProduct.Fuel.day_price * udzial_energii_el_w_taryfie_dziennej + oProduct.Fuel.night_price * (1 - udzial_energii_el_w_taryfie_dziennej ));
		return parseFloat(koszt_en_elektrycznej_na_prace_rekuperatora);
	}
	this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew = function() {
		var ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew = this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_went() + this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_nagrzew();
		//alert('ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew' + ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew);
		return parseFloat(ilosc_zuzytej_en_elektrycznej_w_roku_przez_went_i_nagrzew);
	}
	this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_went = function() {
		var oProduct = this.getProductById(this.getRegisteredProductIdByType('air'));
		var ilosc_zuzytej_en_elektrycznej_w_roku_przez_went = this.get_strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN() * this.getProductParam(oProduct,'udzial-energii-dla-went-w-stos-do-zapotrz-na-went');
		//alert('ilosc_zuzytej_en_elektrycznej_w_roku_przez_went' + ilosc_zuzytej_en_elektrycznej_w_roku_przez_went);
		return parseFloat(ilosc_zuzytej_en_elektrycznej_w_roku_przez_went);
	}
	this.get_strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN = function() {
		var strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN = 38 * this.get_wymagany_strumien_powietrza_wentylacyjnego_dla_budynku(); 
		//alert('strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN ' + strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN);
		return parseFloat(strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN);
	}
	this.get_wymagany_strumien_powietrza_wentylacyjnego_dla_budynku = function() {
		var wymagany_strumien_powietrza_wentylacyjnego_dla_budynku = this.get_kubatura() * this.getConfig('wsp-krotnosci-wymiany');		
		
		//alert('wymagany_strumien_powietrza_wentylacyjnego_dla_budynku ' + wymagany_strumien_powietrza_wentylacyjnego_dla_budynku);
		return parseFloat(wymagany_strumien_powietrza_wentylacyjnego_dla_budynku);
	}
	this.get_ilosc_zuzytej_en_elektrycznej_w_roku_przez_nagrzew = function() {
		var udzial_energii_dla_nagrzewnic_w_stosunku_do_zapotrzebowania_na_wentylacje = 0;
		
		var ilosc_zuzytej_en_elektrycznej_w_roku_przez_nagrzew = this.get_strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN() * udzial_energii_dla_nagrzewnic_w_stosunku_do_zapotrzebowania_na_wentylacje;
		
		return parseFloat(ilosc_zuzytej_en_elektrycznej_w_roku_przez_nagrzew);
	}
	this.get_oszcz_w_roku_bez_uwzgl_potrzeb_wlasnych_urzadzenia = function(oProduct) {
		var get_oszcz_w_roku_bez_uwzgl_potrzeb_wlasnych_urzadzenia = this.get_strata_ciepla_na_podgrzanie_powietrza_went_w_sez_grzewczym_PN() * this.getProductParam(oProduct,'sprawnosc-ukladu');
		
		return parseFloat(get_oszcz_w_roku_bez_uwzgl_potrzeb_wlasnych_urzadzenia);
	}
}
/**
 * This function get data from server using AJAX and when recieve put this data to configurator object by exec function initConfigurator
 * @return void()
 */
function getConfiguratorData() {
            var data = {
		action: 'ia_get_configurator_data'
		
            };
            var pathName = getPathName();
            
            var ajaxurl = pathName+ 'wp-includes/ajax.php';
            
            $ia.post(ajaxurl, data, function(response) {
                
            	initConfigurator(response);
            });
    
}
/**
 * This is block of ia_comparison_products
 */

/**
 * This is class which is dedicated to get info from confiugrator and store it to comparison with other products configuradion.
 * When user use function to save and comparision product then is creat and append div to html wiht registered products, confiugrator is resete and result updated.
 * Each div can be remove.
 */
function IA_Comparison(){
    
    //set global variables for IA_Comparison scope
    var classCmpPane = '.ia_products_cmp';
    var idCmpTable = '#ia-comparison-line-wrapper';
    var idResultOverall ='#ia-overall-value';
    var idDescOverall = '#ia-dec-overall';
    var idDescEcological = '#ia-desc-ecological-footprint';
    var idResultEcological = '#ia-ecological-value';
    var idDescPowDoOgrzania = '#ia_desc_param_pow_do_ogrzania';
    var idValPowDoOgrzania = '#ia_val_param_pow_do_ogrzania';
    var idDescLiczbaMieszkancow = '#ia_desc_param_liczba_mieszkancow';
    var idValLiczbaMieszkancow = '#ia_val_param_liczba_mieszkancow';
    var idConsultButton = '#ia-consult-button-wrapper';
    var separatorValue = 'EOD';
    var separatorLine = 'EOT';
    
    var aProductTypes = new Array('heat', 'water', 'air'); 
    
    /**
     * This function get data about products from confiugrator and append to html div wiht this data.
     * If any product is not registred in configurator then is display alert about it (from function Validate()
     * @return void()
     */
    this.AddLine = function(){
        if(this.Validate()){
          var Line = this.retrieveRegisteredProducts();  
        } else {
            return false;
        }
        
        //add line to html
        $ia(idCmpTable).append(Line);
        
    }
    
    /*
     * This function retrive all registered products, and create comparizon line with product info,
     * deregister from configurator and refres Result
     * @return Line - html as string with product info
     * @uses IA_Comparison.AddLine()
     */
    IA_Comparison.prototype.retrieveRegisteredProducts = function(){
        var aIds = new Array();
        for(index in aProductTypes){
            var type = aProductTypes[index];
            var Id = configurator.getRegisteredProductIdByType(type);
            if(Id !=undefined ){
                aIds.push(Id); 
                deleteProduct(configurator, type, Id);
                
            }
        } 
        if(aIds.length >0){
            var sProductName = this.ConcatenateProductName(aIds);
            var Line = this.CreateLine(sProductName);
            var result = configurator.calculate();
            showResults(result);
            return Line;
        } 
    }
    
    /**
     * This function remove line wiht info about product to comparison
     * @param object elDelButton DOM - clickable  DOM elemnt which handle remove line
     * @return void()
     */
    IA_Comparison.prototype.DelLine = function(elDelButton){
        
        var elDiv = elDelButton.parent();
        var aCmp = this.cmpCookieToArray();
        var iIndex = elDiv.index();
        //remove cmp line from cookie
        if(aCmp.length >= iIndex){
            aCmp.splice(iIndex, 1);
            var sCookie = this.ArrayToCmpCookie(aCmp);
            this.setCmpCookie(sCookie);
        }
        
        elDiv.remove();
    }
    /**
     * This function check if confiugrator has registered products and return boolean value;
     * @return boolean bIsValid - if configurator can be add to comparision return true else false
     * @uses IA_Comparison.retrieveRegisteredProducts()
     */
    IA_Comparison.prototype.Validate = function(){
        var bIsValid = false;
      
        for(index in aProductTypes){
            var type = aProductTypes[index];
            var Id = configurator.getRegisteredProductIdByType(type);
            if(Id !=undefined ){
               bIsValid = true;
               break;
            }
        } 
        if(!bIsValid){
            displayAlert('Żaden produkt nie został wybrany.');
        }
        return bIsValid;
        
    }
    /**
     *This function get comparison data sotred in cookie and convert it to array. If cookie not exits then array is empty
     * @return array aCmp - this is indexed array comparison line which contain array wiht indexed value
     * array([0] => array(value1, value2, ... , valueN),
     * ....
     * [N] => array(value1, value2, ... , valueN)
     * )
     */
    IA_Comparison.prototype.cmpCookieToArray = function(){
        var sCookie = this.getCmpCookie();
        
        var aCmp = new Array();
        
        if(sCookie){
            var aCmpLine = sCookie.split(separatorLine);
            if(aCmpLine.length >0){
                for(var i=0; i<aCmpLine.length;i++){
                    aCmpValue = aCmpLine[i].split(separatorValue);
                    aCmp.push(aCmpValue);
                }
            }
        }
        
        return aCmp;
    
    }
    /**
     * This function recive array comparison data (get from cookie)
     * @param array aCmpCookie  - array comparison data
     * @return string sCookie  - this is data converted to string (all value in line are joined by separator and all line are joined by separator)
     */
    IA_Comparison.prototype.ArrayToCmpCookie = function(aCmpCookie){
        var sCookie = '';
        if(aCmpCookie.length >0){
            var aCookieValue = new Array();
            var sCookieLine = '';
            for(var i=0; i<aCmpCookie.length;i++){
                aCookieValue.push(aCmpCookie[i].join(separatorValue));
            }
            sCookie = aCookieValue.join(separatorLine);
        }
        return sCookie;
    }
    /**
     * This function get 'cmp' cookie if not exists then return false
     * @return string|boolean - sCookie if not exits then false
     */
    IA_Comparison.prototype.getCmpCookie = function(){
        var sCookie = false;
        sCookie = $ia.cookie('cmp');
        if(sCookie && sCookie != undefined){
            return sCookie;
        } else {
            return false;
        }
    }
    
    /**
     * This function  update or create cookie for new comparison data line
     * @param object(Line) oLine creted by function IA_Compariosn.CreateObjectLine()
     * @see IA_Compariosn.CreateObjectLine()
     * @return void()
     */
    IA_Comparison.prototype.addCmpLineToCookie = function(oLine){
        sCookie = this.getCmpCookie();
        var aCmpLineValue = new Array();
        $ia.each(oLine, function(key, value) {
                aCmpLineValue.push(value);
            });
            var sCmpCookie = aCmpLineValue.join(separatorValue);
        
        if(sCookie){
            sCmpCookie =  sCookie + separatorLine + sCmpCookie;
        }
        this.setCmpCookie(sCmpCookie);
        
    }
    /**
     * This function recive sCookie and set variable 'cmp' in cookie object\
     * if sCookie is empty then 'cmp' is set to null
     * @return void()
     */
    IA_Comparison.prototype.setCmpCookie = function(sCookie){
        if(!sCookie || sCookie == ''){
            sCookie = null;
        }
        $ia.cookie('cmp', sCookie, {expires: global_var.ia_cookie_expire});
    }
    /**
     * This function crete body object Line. This object is used to render html: repetitive divs wiht comparison data
     * @see IA_Compariosn..RenderCmpLine
     * @return object Line
     */
    IA_Comparison.prototype.CreateObjectLine = function(){
           var Line = {};
        //Shema
       
        Line.resultOverall = '';
        Line.installationCost = '';
        Line.operatingCost = '';
        Line.resultEcological = '';
        Line.valPowDoOgrzania = '';
        Line.valLiczbaMieszkancow = '';
        Line.valScale = '';
        Line.ProductName = '';
        
        return Line;
      
    }
    /**
     * This function get data as array object Line and fill up html template by this data
     * @see IA_Comparison.CreateObjectLine()
     * @return string sHtml - this is populated html wiht data, if input data are empty or false then html is set to default string ''
     *
     */
    IA_Comparison.prototype.RenderCmpLine = function(aOLine){
        sHtml = '';
        if(aOLine.length > 0){       
        
            for(var i=0; i<aOLine.length; i++)    {
                Line = aOLine[i];
                var unitLiczbaMieszkancow = (Line.valLiczbaMieszkancow > 1)?' osób':' osoba';
                var spanPowDoOgrzania = '<span class="ia_pow_do_ogrz_cmp">' + Line.valPowDoOgrzania + unitLiczbaMieszkancow +'</span>';
                var spanLiczbaMieszkancow = '<span class="ia_liczba_mieszkancow_cmp">' + Line.valLiczbaMieszkancow + '</span>';
                var spanProductName = '<span class="ia_product_name">' + Line.ProductName + '</span>';
                var spanOverall = '<span class="ia_overall_cmp">' + Line.resultOverall + '</span>';
                var spanInstallationCost = '<span class="ia_installation_cmp">' + Line.installationCost + '</span>';
                var spanOperatingCost = '<span class="ia_operating_cmp">' + Line.operatingCost + '</span>';
                var spanEcological = '<span class="ia_ecological_cmp">' + Line.resultEcological + '</span>';
                var spanScale = '<span class="ia_scale_cmp">' + Line.valScale + ' lat</span>';
                var sItemLine = '<div class="ia_comparison_line"> <span class="ia_del_line"></span>' + spanProductName + spanOverall + spanInstallationCost + spanOperatingCost + spanEcological + spanScale + '</div>';
                sHtml += sItemLine;
            }
        
        } else if(aOLine !== false) {
            alert('Niepoprawny argument!');
        }
        return sHtml;
    }
    /**
     * This function get cmp cookie and convert to array object Line
     * @see IA_Comparison.CreateObjectLine()
     * @return array|false aOLines - array wiht object Line
     * array(Line, Line, Line, ..., Line) or return false
     *
     */
    IA_Comparison.prototype.CmpCookieToArrayObjectCmpLine = function(){
        var aCmpLines = this.cmpCookieToArray();
        if(aCmpLines.length > 0){
            var aOLines = new Array();
            var Line = this.CreateObjectLine();
            var oLine = {};
            for(var i=0; i<aCmpLines.length;i++){
                var k=0;
                oLine = {};//clear oLine
                //for each Line key set valu from array aCmpLines this id is created from data stored in cookies
                $ia.each(Line, function(key, value) {
                    value = (aCmpLines[i][k] != undefined)?aCmpLines[i][k]:null;
                    k++;
                    oLine[key] = value;               
                });
                aOLines[i] = oLine;
            }
            return aOLines;
        } else {
            return false;
        }
  
    }
    /**
     * This function get html cmpTable and append to DOM if html is not empty
     * @see IA_Comparison.RenderCmpLine()
     * return void()
     */
    IA_Comparison.prototype.displayCmpBoxFromCookie = function(){
       
       var aOCmpLine = this.CmpCookieToArrayObjectCmpLine();
       var html = this.RenderCmpLine(aOCmpLine);
       if(html!=''){
            $ia(classCmpPane).customFadeIn('slow', function() {
                $ia(idConsultButton).css('display', 'inline');
                $ia(idCmpTable).append(html);
            });            
        }
   
    }
    /**
     * This function get data about registered products in configurator, next put this info to html div and return this div as string
     * @param string sProductName - Concatenated  registered products name 
     * @return string sLine - div as string 
     * @uses IA_Comparison.retrieveRegisteredProducts()
     */
    IA_Comparison.prototype.CreateLine = function(sProductName){
      
        var Line = this.CreateObjectLine();
        
        //get data
       
        Line.resultOverall = $ia(idResultOverall).text(); 
        Line.installationCost = $ia(idResultOverall).attr('resultpart1');
        Line.operatingCost = $ia(idResultOverall).attr('resultpart2');
        Line.resultEcological = $ia(idResultEcological).text();
        Line.valPowDoOgrzania = $ia(idValPowDoOgrzania).val();
        Line.valLiczbaMieszkancow = $ia(idValLiczbaMieszkancow).val();
        Line.valScale = configurator.getConfig('czas-analizy');
        Line.ProductName = sProductName;
        
        var aOLine = new Array();
        aOLine[0] = Line;
        
        this.addCmpLineToCookie(Line);
               
        //create html elemnts
        var sItemLine = this.RenderCmpLine(aOLine);
        return sItemLine;
    }
    
    
    /**
     *This function get products from configurator by input array ids and return concatenated name by chars ', '
     *@param array aIds - product ids array
     *@return string sProductName - concatenated products name by separator '+'
     */
    IA_Comparison.prototype.ConcatenateProductName = function(aIds){
        var aProductName = new Array();
        for(index in aIds){
            var Product = configurator.getProductById(aIds[index]);
            aProductName.push(Product.name);
        }
        var sProductName = aProductName.join(', ');
        return sProductName;
    }
    
 
}



/**
 * End Block ia_comparison_products
 */
   /**
     *This function set hendler on button which will be get and store comparison data
     *@return void()
     */
    function setComparisonHandler(){
        $ia('#ia-comparison-button-wrapper').live('click', function(){
            cmpProduct.AddLine();
            
            //show products compare box
            $ia('.ia_products_cmp').css('display','inline');
            
            //show consult button
            $ia('#ia-consult-button-wrapper').css('display','inline');
        });
        $ia('.ia_del_line').live('click', function(e){
            var target = $ia(e.target);
            cmpProduct.DelLine(target); 
            
            // hide compare box if no lines left
            if ($ia('.ia_comparison_line').length == 0) {
            	$ia('.ia_products_cmp').customFadeOut('slow');
            }
        });
    }
    
    /**
     * This function display message
     * @param sMsg - message to display
     * 
     */
    function displayAlert(sMsg){
        alert(sMsg);
    }
