/**
 * @author rbentz
 */
/* Call in the onClick of the model dropdown */
taxonomySearchGAQ.setModel = function(newValue) {
	this.criteriaList[MODEL_NAME].value = newValue;
	this.criteriaList[MODEL_NAME].resetNodeLists(false);
	this.criteriaList[TRIM_NAME].set(this.searchForm);
	
	var clearedField = clearColorOptions();
	//searchXML({colors:true,photos:true}); per business requirements, no photo or color searching is done
	jQuery('#lslp_gaq_vehImgCont').empty();
	
}

/* Call in the onClick of the trim dropdown */
taxonomySearchGAQ.setTrim = function(newValue) {
	this.criteriaList[TRIM_NAME].value = newValue;
	this.criteriaList[TRIM_NAME].resetNodeLists(false);
	this.advancedFactory.setAll();
	
	populateColors({colors:true,trim:newValue,photos:true,model:taxonomySearchGAQ.getModel()}); //gets color XML if not present, otherwise cruises through color XML and gets trim photo and color options
}

function clearColorOptions() {
	var selectFieldSize = leadFormGAQ.color.options.length;
	for(var i=0; i < selectFieldSize; i++) {
		leadFormGAQ.color[leadFormGAQ.color.options.length - 1] = null;
	}
	leadFormGAQ.color[0] = new Option('Select a Color');
	leadFormGAQ.color.selectedIndex = 0;
	
	return leadFormGAQ.color;
}

function setColorOptions(arrColors) {
	var clearedField = clearColorOptions();
	for(var j=0; j < arrColors.length; j++) {
		leadFormGAQ.color[leadFormGAQ.color.options.length] = new Option(arrColors[j], arrColors[j]);
	}
}

function searchXML(options) {
	var o = options;
	if(o.colors) {
		var colorSelect = jQuery('#gaq_color');
		var arrColors = new Array();
		var colorsUpdated = false;
		/**
		 * Fix for bug 112517 [Cadillac: GAQ: No colors are populated in the dropdown for CTS and DTS model.].
		 * There are some trims with slash (/) [eg. 4dr Sedan w/1SD] available for these makes (CTS, DTS etc). In such cases
		 * the find() is NOT able to fetch the 'colors' attribute properly thus colors dropdown NOT populated with appropriate
		 * values. 
		 * By modifying the previous code "jQuery(colorXML).find('Color[@trim='+o.trim+'][@model='+o.model+']').each("
		 * as follows we can confirm this issue got resolved.
		 */
		jQuery(colorXML).find('Color[@model='+o.model+']').each(function() {
			varTrim = jQuery(this).attr('trim');
			if (varTrim.replace('/','') == o.trim.replace('/','')) {
				arrColors = jQuery(this).attr('colors').split(',');
				jQuery.unique(arrColors);
				colorsUpdated = true;
			}
			
		});
		
		setColorOptions(arrColors);
				
	}
	
	/*if(o.photos) {
		var photoContainer = jQuery('#lslp_gaq_vehImgCont');
		jQuery(colorXML).find('Color[@trim='+o.trim+'][@model='+o.model+']:first').each(function() {
			var photoString = jQuery(this).attr('image');
			var photoHTML = '<img src="'+photoString+'" width="160" />';
			//jQuery("#lslp_gaq_vehImgCont").empty();
			//jQuery(thisRecord).parent().parent().find('img:first').clone().css("width", "160px").appendTo("#lslp_gaq_vehImgCont");
			photoContainer.html(photoHTML);			
		});
	}*/
}


function populateColors(options) {
	if(!colorXML) {
		jQuery.ajax({
			type: "POST",
			dataType: "xml",
			async: "false",
			url: "getColors.ajax", 
			success: function(data) {
				colorXML = data;
				//searchXML({colors:true,trim:trim});
				searchXML(options);
			},
			error: function(oXHR, err, oExc) {
				alert(err);
			}
		});
	} else {	
		searchXML(options);
	}
}

function updateVirtualInventory(pxType) {
	var postParameters = serializeForm(jQuery('#virtual_inventory_form'));
	// If there is no model param in postParameters, then set model=All
	// 		- check for empty param
	if (postParameters.indexOf('model=&') != -1) {
		postParameters = removeSubstring(postParameters, 'model=&')
	}
	var st = (postParameters.indexOf('model=') == -1) ? 'model=All&' + postParameters : postParameters;
	ContextManager.updateProperties(st);
	//
	jQuery.ajax({
		type: "POST",
		dataType: "html",
		async: "false",
		data: st,
		url: "listVirtualVehicles.ajax", 
		success: function(data) {
			jQuery('#lslp_virtualVehicles').fadeOut('fast', function() {
				jQuery('#lslp_virtualVehicles').empty();
				jQuery('#lslp_virtualVehicles').html(data);
				jQuery('#lslp_virtualVehicles').fadeIn('fast');
			});
			// new tag
			EventManager.publish({
				eventName:'com.cobaltgroup.ws.view.results.inventory'
			});
		},
		error: function(oXHR, err, oExc) {
			alert(err);
		}
	});
}

function checkValidRange(thisInput) {
	var inputRex = new RegExp("\\D");
	if((inputRex.test(thisInput.val()) == true) || (thisInput.val() == "")) return false;
	if(thisInput.attr('id').indexOf('min') != -1) {
		return (parseInt(thisInput.val()) >= parseInt(thisInput.parents('.sliderInputRow').find('input:eq(1)').val())) ? false : true;
	} else if(thisInput.attr('id').indexOf('max') != -1) {
		return (parseInt(thisInput.val()) <= parseInt(thisInput.parents('.sliderInputRow').find('input:eq(0)').val())) ? false : true;
	}
	return false;
}

function setVisitorZip() {
	var visitorZip = jQuery("#dmaSearchZipInput").val();
	if(visitorZip != "") jQuery("#gaq_zip").val(visitorZip);
	jQuery("#gaq_zip").triggerHandler("change");
}

function GAQvalidate(someForm) {	
	FormUtility.resetErrors();
	var missingFields = FormUtility.getMissingRequired(someForm);
	if (missingFields.length) throw new MissingRequiredError(missingFields);
	var badFields = FormUtility.getBadlyFormatted(someForm);
	if (badFields.length) throw new BadFormatError(badFields);
}

function createDealerHTML(dealerData,useXML) {
	var dealerCount = 0;
	var tempHTML = "";
	if(useXML) {
		jQuery(dealerData).find('Dealer').each(function() {
			if(dealerCount <= 4) {
				var jQueryDealer = jQuery(this);
				tempHTML += '<div class="selectDealerRow"> ';
				tempHTML += '<div class="selectDealerRadioWrapper"><input type="radio" required="true"  class="dealerSelect" id="dealer' + dealerCount +'" name="dealerSelect" value="'+jQueryDealer.attr('webId')+'" /></div>';
				tempHTML += '<div class="selectDealerAddressWrapper">';
				tempHTML += '<label for="dealer'+dealerCount+'">';
				tempHTML += '<span class="dealerNameText">' + jQueryDealer.attr('name') +'</span><br />';
				var arrAddresses = jQueryDealer.find('Address');
				var dealerAddress = arrAddresses;
				tempHTML += dealerAddress.attr('street1') + '<br />';
				tempHTML += (dealerAddress.attr('street2') != undefined) ? dealerAddress.attr('street2') + '<br />' : '';
				tempHTML += dealerAddress.attr('city') + ', ' +  dealerAddress.attr('state') + ' ' + dealerAddress.attr('zip') + ' ';
				var distance = parseInt(jQueryDealer.attr('distance'));
				tempHTML += (distance == -1) ? '' : '(' + parseInt(jQueryDealer.attr('distance')) + ' mi)';
				tempHTML += '</label></div></div>';
				
				/* The following 2 lines pertain to using a standard select form element for selecting a dealer -- not the DHTML version */
				/*leadFormGAQ.selectDealer[leadFormGAQ.selectDealer.options.length] = new Option(jQueryDealer.attr('name'), jQueryDealer.attr('webId'));
				leadFormGAQ.selectDealer[leadFormGAQ.selectDealer.options.length] = new Option(Math.ceil(parseInt(jQueryDealer.attr('distance')))+" mi",Math.ceil(parseInt(jQueryDealer.attr('distance'))));*/
					
				dealerCount++;
			} 
		});
	}
	else {
		for(var i=0; i < dealerData.length; i++) {
			if(dealerCount <= 4) {
				tempHTML += '<div class="selectDealerRow"> ';
				tempHTML += '<div class="selectDealerRadioWrapper"><input type="radio" required="true" class="dealerSelect" id="dealer' + i +'" name="dealerSelect" value="'+dealerData[i].webId+'" /></div>';
				tempHTML += '<div class="selectDealerAddressWrapper">';
				tempHTML += '<label for="dealer'+i+'">';
				tempHTML += '<span class="dealerNameText">' + dealerData[i].dealerName +'</span><br />';
				tempHTML += dealerData[i].street1 + '<br />';
				tempHTML += (dealerData[i].street2) ? dealerData[i].street2 + '<br />' : '';
				tempHTML += dealerData[i].city + ', ' +  dealerData[i].state + ' ' + dealerData[i].zip + ' ';
				var distance = parseInt(dealerData[i].distance);
				tempHTML += (distance == -1) ? '' : '(' + parseInt(dealerData[i].distance) + ' mi)';
				tempHTML += '</label></div></div>';
				
				dealerCount++;
			}
		}
	}
	
	return tempHTML;
};

function getDealerXmlGAQ(zipCode) {
	var url = "getDealersForGAQ.ajax?zip="+zipCode;
	var optionListHTML;
    jQuery.ajax({
   		type: "GET",
	   	url: url,
	   	dataType: "xml",
   		success: function(xml) {
			
			var jQuerySelDealerList = jQuery("#selectDealerDropdownOptions");
			jQuerySelDealerList.empty();
			
			/* The following for loop is for the select element only -- not the DHTML version */
			/*for(var i=0; i < leadFormGAQ.selectDealer.options.length; i++) {
				leadFormGAQ.selectDealer.options[i] = null;
			}*/
			
			var htmlDropdown = createDealerHTML(xml,true);
			
			jQuerySelDealerList.html(htmlDropdown);
   		}, 
   		complete: function() {
   			jQuery("#dealerZipWaitIcon").hide();
   		}
	});
}

jQuery(document).ready(function() {	
	jQuery(".btn_GAQ_virtInv:not(.noResultsLink)").livequery("click", function(e) {
		var thisRecord = jQuery(this);
		jQuery(thisRecord).parent().parent().find('img:first').clone().css("width", "160px").appendTo("#lslp_gaq_vehImgCont");
		var recordModel = jQuery(thisRecord).parent().parent().find(".thisRecordModel").text();
		var recordTrim = jQuery(thisRecord).parent().parent().find(".thisRecordTrim").text();
		var virVehName = jQuery(thisRecord).parent().parent().find(".lslp_virVehName").text();
		var virVehTrim = jQuery(thisRecord).parent().parent().find(".lslp_virVehTrim").text();
		initTBMap(recordModel, recordTrim, virVehName, virVehTrim);
		return false;
	});
	
	jQuery(".noResultsLink").livequery("click", function(e) {
		FormUtility.resetErrors();
		resetGAQ();
		var tbGAQ = tb_show("Get a Quote", "#TB_inline?width=593&height=238&inlineId=gaqFormWrapper", null);
		var thisRecord = jQuery(this);
		jQuery(tbGAQ).ready(function () {
			jQuery("#lslp_gaq_vehImgCont").empty();
			// tweak Thickbox CSS
			jQuery("#TB_title").css("height", "30px");
			jQuery("#TB_ajaxWindowTitle").css("padding-top", "4px");
			jQuery("#TB_ajaxContent").css("overflow","hidden");
			jQuery("#gaq_fromMapField").val("false");
			//if(jQuery("#gaq_zip").val() != "") jQuery("#gaq_zip").triggerHandler("change");
			sendPixelTag({
				pageLabel:"GAQ_Inventory",
				pageLayoutName: "GAQ",
				pageName:"GAQ"
			});
			EventManager.publish({
				eventName:'com.cobaltgroup.ws.view.leadForm.getAQuote',
				publisherData:{
					pageLabel:"GAQ_Inventory",
					pageLayout: "GAQ",
					pageName:"GAQ"
				}
			});
		});
		return false;
	});
	
	jQuery("a.seeAllVehiclesLink").livequery("click", function(e) {
		//taxonomySearch.criteriaList.resetCriteria("model");
		jQuery("#virtual_inventory_form").resetForm();
		// reset price sliders
		priceRangeSlider.sliderMoveTo(priceRangeValues[0], '', true, '', 0);
		priceRangeSlider.sliderMoveTo(priceRangeValues[1], '', true, '', 1);
		updateVirtualInventory();
		//
		return false;
	});
});