var PRICES_REQUEST_URL = '/service/pricing/widget';

$(function(){
	prices.disclaimerDate();
});

var prices = {
	/** Selecting current section of gradesInfo JSON
	 * aSteps - array with selected steps ['gradeType', 'bodyType', ....]
	 */	
	selectSection : function(aSteps){
		if (!$.isArray(aSteps)) 
			return false;
		var jInputs = gradesInfo;
		$.each(aSteps, function(index, currentStep){
			if (jInputs[currentStep] != null) {
				jInputs = jInputs[currentStep];
			}
			else {
				return false;
			}
		});
		return jInputs;
	},
	
	/** Activating all inputs in selected block
	 * oBlock - selected block object
	 * jInputs - section of gradesInfo JSON started from selected block
	 * aSteps - array with selected steps ['gradeType', 'bodyType', ....]
	 */
	activateInputs : function(oBlock, jInputs, aSteps){
		if((oBlock == null) || (jInputs == null) || (!$.isArray(aSteps))) return false;
		
		//Returning all inputs to default state
		oBlock.find('li').removeClass('active');
		oBlock.find('li input').show().unbind('click');
		
		//Activating inputs which are in JSON
		$.each(jInputs, function(currentInput, currentInputValue){
			oBlock.find('input[value='+currentInput+']').parents('li').addClass('active');
		});		
		
		//Binding onClick action for activated inputs
		if(oBlock.find('li.active').length < 2){
			//One input
			prices.bindInput(oBlock.find('li.active input'), aSteps);
			oBlock.find('li.active input').click().hide();
		}else{
			//Two or more inputs
			oBlock.find('li.active input').each(function(){
				prices.bindInput($(this), aSteps);
			});
			
			var oSelectedInput = oBlock.find('li input').filter(':checked');
			if(oSelectedInput[0] != null){
				if (oSelectedInput.parents('li').hasClass('active')) {
					oSelectedInput.click();
				}
				else{
					oBlock.find('li.active input').filter(':first').click();
				}
			}else{
				oBlock.find('li.active input').filter(':first').click();
			}
		}
		oBlock.show();
	},	
	
	/** Binding onClick action for single input
	 * oInput - input object
	 * aSteps - array with selected steps ['gradeType', 'bodyType', ....]
	 */
	bindInput : function(oInput, aSteps){
		if((!$.isArray(aSteps)) || (oInput == null)) return false;
		
		var aNextSteps = new Array();
		$.each(aSteps, function(index, step){aNextSteps[index] = step;});
		aNextSteps.push(oInput.val());
		
		oInput.click(function(){
			$(this).parents('.item').find('li').removeClass('current');
			$(this).parents('li').addClass('current');	
			prices.processStep(aNextSteps, oInput.parents('.item'));
		});		
	},	
	
	/** Processing gradeType block
	 */	
	processGrade : function(){
		var oGradesBlock = $('#gradeType');
		
		//Binding onClick action for all grades
		oGradesBlock.find('li input').each(function(){
			$(this).parents('li').addClass('active');
			$(this).click(function(){
				oGradesBlock.find('li').removeClass('current');
				$(this).parents('li').addClass('current');	
				prices.processStep([$(this).val()], oGradesBlock);
				
				/*TRACKING*/
				if(!VEHICLE_ABBR) {
					VEHICLE_ABBR = 'unspecified vehicle';
				}
				tracking.event.activate('trackingevent', {EventClass:"Pricing",Action:"Start",Vehicle: VEHICLE_ABBR});
			});
		});
		
		//Processing input if it was selected before
		var oSelectedInput = oGradesBlock.find('li input').filter(':checked');
		if(oSelectedInput[0] != null){
			oSelectedInput.click();
		}else{
			oGradesBlock.find('li input').filter(':first').click();
		}
		
		$('#gradeType').show();
	},	

	/** Processing all steps in between of gradeType and colourType
	 * aSteps - array with selected steps ['gradeType', 'bodyType', ....]
	 * oBlock - clicked input's parent block object
	 */	
	processStep : function(aSteps, oBlock){
		//Defining active block
		if((!$.isArray(aSteps)) || (oBlock == null)){
			return false;
		}else if(oBlock.attr('id') == 'transmissionType'){
			prices.processColours(aSteps);
			return;
		}else{
			var oActiveBlock  = oBlock.next();
			if(oActiveBlock[0] == null){
				oActiveBlock = $('#transmissionType');
			}
		}
		
		//Selecting current section of gradesInfo JSON
		var jInputs = prices.selectSection(aSteps);
	
		//Activating inputs in active block
		prices.activateInputs(oActiveBlock, jInputs, aSteps);
	},
		
	/** Processing colors
	 * aSteps - array with selected steps ['gradeType', 'bodyType', ....]
	 */
	processColours : function(aSteps){
		if(!$.isArray(aSteps)) return false;
		
		var jGradeInfo = prices.selectSection(aSteps);
		if((!$.isArray(jGradeInfo.colors)) || (jGradeInfo.id == null)) return false;
		
		var oColoursBlock = $('#colourType');
				
		//Returning all inputs to default state
		oColoursBlock.find('li').removeClass('active').unbind('click');
		
		//Activating inputs which are in JSON
		$.each(jGradeInfo.colors, function(index, currentColor){
			oColoursBlock.find('input[value='+currentColor+']').parents('li').addClass('active');
		});		
		
		//Binding onClick action for activated colors
		oColoursBlock.find('li.active').each(function(){
			$(this).click(function(){
				oColoursBlock.find('li').removeClass('current');
				oColoursBlock.find('li input').attr('checked','');
				$(this).addClass('current');
				$(this).find('input').attr('checked','checked');
				prices.displayPrice(jGradeInfo['id'], $(this).find('input').val());
				return false;
			}).hover(
				function(){$(this).addClass('hover');},
				function(){$(this).removeClass('hover');}
			);
		});
		
		//Processing input if it was selected before
		var oSelectedInput = oColoursBlock.find('li input').filter(':checked');
		if(oSelectedInput[0] != null){
			if (oSelectedInput.parents('li').hasClass('active')) {
				oSelectedInput.parents('li').click();
			}
			else {
				oColoursBlock.find('li.active').filter(':first').click();
			}
		}else{
			oColoursBlock.find('li.active').filter(':first').click();
		}		
	
		oColoursBlock.show();
		$('#colors-disclaimer').show();
	},	
	
	/** Displaying price
	 * sGradeId - grade ID string
	 * sColourCode - colour code string
	 */
	displayPrice : function(sGradeId, sColourCode){
		function displayLoading(){
			$('.response').html('<div class="loading"><img src="/static/global/images/toyota-loader.gif" width="100" height="100"></div>').show();
			$('#prices-disclaimer').hide();
			$('#special-offers-disclaimer').html('');
		}
		function displayError(){
			$('.response').html('<div class="error"><div class="message"><p>Unfortunatly due to technical difficulties no results are availible at this time.</p><p>Please contact your preferred local dealer:</p></div><div class="local-dealer"></div></div>');
    		module.pricingError.knownUser();
		}
		
		if ((metallicColoursInfo[sColourCode] != null) && (metallicColoursInfo[sColourCode] == true)){
			sMetallicColour = 'true';
		}else{
			sMetallicColour = 'false';
		}
		
		displayLoading();
		$.ajax({
			type: "GET",
			dataType: 'json',
			url: PRICES_REQUEST_URL+'/'+sGradeId+'/'+sColourCode.toUpperCase()+'/'+userDetailsPostcode+'/'+userDetailsRegType+'.json?suburb='+encodeURI(userDetailsSuburb)+'&state='+encodeURI(userDetailsState)+'&metallic='+sMetallicColour,
			error: function(data, textStatus, errorThrown) {
				displayError();
			},
			success: function(response){				
				var data = response.widgetPricingDto;
				if(data.valid == true){
					
					var sResponseHtml = data.html;
					if(typeof specificationsLinksInfo != 'undefined'){
						if(specificationsLinksInfo[sGradeId] != null){
							sResponseHtml = sResponseHtml+'<div class="specifications-link"><a class="more-link" href="'+specificationsLinksInfo[sGradeId]+'">Specifications</a></div>';
						}
					}
					
					$('.response').html(sResponseHtml);
					$('#prices-disclaimer').show();
					
					/*TRACKING*/
					var sTransmisionType = $('#transmissionType').find('ul.radio li.current input').val();
					var sColourName = $('#colourType').find('ul.radio li.current label').text().toLowerCase();
					tracking.event.activate('trackingevent', {EventClass: "Pricing", Action: "Complete", Vehicle: VEHICLE_ABBR, Grade: sGradeId, Body: 'not specified', Transmission: sTransmisionType, Colour: sColourName});
					
					if(offers) {
						$('.response .special-offer a').click(function() {
							var sOfferId = $('.response .special-offer').attr('id').split('-')[1];
							createOverlay({customClass: 'offer-details'});
							showOverlay(deleteOverlay, offers.knownUser.show.details.overlay, sOfferId);
							return false;
						});
					}
					if ((data.disclaimer != null) && (data.disclaimer != '')) {
						$('#special-offers-disclaimer').html(data.disclaimer);
					}
				}else if(data.valid == false){
					$('.response').html(data.html);
					module.pricingError.knownUser();
				}else{
					displayError();
				}
			}
		});
	},	
	/** Pre-populating data collected from URL
	 */
	prePopulate : function(){
		function getUrlVars() {
			var aGetVars = {};
			window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
				aGetVars[key] = value;
			});
			return aGetVars;
		}
		
		var aGetVars = getUrlVars();
		$.each(aGetVars, function(inputName, inputValue){
			var currentInput = $('input[name='+inputName+'][value='+inputValue+']');
			if(currentInput[0] != null){
				currentInput.parents('.item').find('li input').attr('checked','');
				currentInput.attr('checked','checked');
			}
		});
	},	
	disclaimerDate : function(){
		var oDate = new Date();
		var sDay = oDate.getDate();
		var sMonth = oDate.getMonth() + 1;
		var sYear = oDate.getFullYear();
		
		if(sDay < 10) sDay = '0' + sDay;
		if(sMonth < 10) sMonth = '0' + sMonth;
		
		$('#prices-disclaimer .current-date').html(sDay + "/" + sMonth + "/" + sYear);	
	}	
}
