function redirectToDealersPage(rootPath,segment,defaultLanguage,dealerType,isGeneral)
{	
	//alert('rootPath:'+rootPath+'|segment:'+segment+'|defaultLanguage:'+defaultLanguage+'|dealerType:'+dealerType+'|isGeneral:'+isGeneral);
	var subCatList=document.getElementById('category_list');
	var regionList =document.getElementById('regions_list');
	var productList =document.getElementById('product_list');

	if (isGeneral!=undefined && !isGeneral){
		subCatList=document.getElementById(dealerType+'_category_list');
		regionList =document.getElementById(dealerType+'_regions_list');
		productList =document.getElementById(dealerType+'_product_list');
	}
	

	var subCategory = subCatList.options[subCatList.selectedIndex].value;
	var region = regionList.options[regionList.selectedIndex].value;
	var product =productList.options[productList.selectedIndex].value;

	var url= rootPath+"/"+segment;
	
	if(segment == 'personal')
		url += "/web/buying/dealers";
	else
		url +="/web/sales/dealers";
	url+="?languageCode="+defaultLanguage;
	
	if (subCategory !='default' )
		url+="&subcategory="+subCategory;
	if (region !='default' )
		url+="&region="+region;
		

	if(product !='default' )
	{
		url +="&product="+product;
	}
	if (dealerType !=undefined && dealerType!='')
	{
		url +="&dealerType="+dealerType;
	}
	

	
	document.location.href = url;
}

function isEmpty(ob){
   for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
  return true;
}

function sortingFunction(a,b){
	if(a.name == b.name){
        return 0;
	}
	return (a.name < b.name) ? -1 : 1;
}

function isEmpty(ob){
   for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
  return true;
}

function sortingFunction(a,b){
	if(a.name == b.name){
        return 0;
	}
	return (a.name < b.name) ? -1 : 1;
}


function createDealerLocator(dType){
	var config = {
			defaultOption : 'default',
			categoryOptions : '#category_list',
			regionOptions : '#regions_list',
			productOptions : '#product_list',
			dealerResults : '#dealer_results',
			searchButton : '#search_button'
		};
	if (dType!='general')
	{
		config = {
				defaultOption : 'default',
				categoryOptions : '#'+dType+'_category_list',
				regionOptions : '#'+dType+'_regions_list',
				productOptions : '#'+dType+'_product_list',
				dealerResults : '#dealer_results',
				searchButton : '#search_button'
			};
		
	}
	
	var map = null, geocoder = null,  dealerpage = true,
	params = {
		dealerpage : true,
		selectedCategory : config.defaultOption,
		selectedRegion : config.defaultOption,
		selectedProduct : ''
	},
	
	currentDealers = [],
	
	coordinatesDealer = {},
	
	coordinatesDealerCount = {};
	
	copy = {},
	
	priv = {
		
		
		//creates the <option> tags for  both categories and regions; 
		setOptions : function ( dataToAdd, selector, mapping ) {
			var options = {};
			for ( var key in dataToAdd ) {
				if (dataToAdd.hasOwnProperty(key)) {
					options[key] = mapping[key];
				};
			};
			//keys.sort();
			for ( var i in options ) {
				//var optionObj = new Option(keys[i], keys[i]) ;
				// Replaced above line, does not work in ie
				$(selector).append('<option value="'+i+'">'+options[i]+'</option>');
			};			
		},
		
		//creates the results from the dropdowns, appends it and adds it to the map
		//this methid is commonly iused within a loop
		updateView : function () {
			
			var html = '';
			var dealer = null;
			
			currentDealers.sort(sortingFunction);
			
			for (var i=0; i<currentDealers.length; i++) {
				
				dealer = currentDealers[i];
				html = '<div class="spacer"></div>'+
						'<div id="result_'+dealer.id+'" class="dealer_search_result">'+
						'<h3><a href="javascript:void(0)" class="red">' +dealer.name+ '</a></h3>'+
						'<div style="clear:both;"></div>'
						+dealer.addressLink1+'<br/>'
						+dealer.addressLink2+'<br/>';
					
				if(dealer.addressLink3 != undefined && dealer.addressLink3 != ''){
					html+=dealer.addressLink3+'<br/>';
				}
				if(dealer.addressLink4 != undefined && dealer.addressLink4 != ''){
					html+=dealer.addressLink4+'<br/>';
				}
				if (dealer.remark != undefined && dealer.remark != '') {
					html += '<div style="clear:both;"></div>'+
							'<div class="italic">* ' + dealer.remark + '</div>';
				}
				if (dealer.phone != undefined && dealer.phone != '') {
					html += '<div style="clear:both;"></div>'+
							'<div class="italic">' +copy.phonePrefix + dealer.phone+ '</div>';
				}
				
				if (dealer.fax != undefined && dealer.fax != '') {
					html += '<div style="clear:both;"></div>'+
							'<div class="italic">' +copy.faxPrefix + dealer.fax+ '</div>';
				}

				if (dealer.email != undefined && dealer.email != '') {
					html += '<div style="clear:both;"></div><div style="word-wrap: break-word;">'+
							copy.emailPrefix + '<a href="mailto:' + dealer.email + '"  class="underline">' + dealer.email + '</a></div>';
				}
				
				if (dealer.url != undefined && dealer.url != '') {
					html += '<div style="clear:both;"></div>'+
							copy.urlPrefix + '<a href="' + dealer.url + '"  class="underline" target="_blank">' + dealer.url + '</a><br />';
				}
				
				if (!dealer.longitude || !dealer.latitude) {
					// Nelson : Added id to remove the mark later if the long/lat is found by geocoder
					html += '	<div id="dealerLocationNotFound_' + dealer.id + '" class="italic red">'+copy.notFound+'</div>';
				}
				
				html += '</div>';
				
				

				$(config.dealerResults).append(html);
				priv.addDealerOnMap(dealer,dealer.id,html,true);
				
				// Nelson : Added this to geocode the long and lat, then add the marker on the map
				if (!dealer.longitude || !dealer.latitude) {
					priv.getDealerLocationAndAddOnMap(dealer, dealer.id, html);
				}
			}			
			
			
			
		},
		
		//sets google maps;
		configureGoogleMaps : function (lat,lng,zoomLevel) {
			if (GBrowserIsCompatible()) {
				map = new GMap2(document.getElementById('map_canvas'));
				geocoder = new GClientGeocoder();
				map.setCenter(new GLatLng(lat, lng), zoomLevel);
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
			};
			if (location.hash) {
				priv.setPreferredOptions(location.hash);
			};
		},
		
		//adds a dealer on the map and binds it to the result in the left column;
		addDealerOnMap : function (dealer, id, html, dealerpage) {
			if (dealerpage) {
			
			if (dealer.longitude && dealer.latitude) {
				var point = new GLatLng(dealer.latitude, dealer.longitude),
					marker = new GMarker(point);
				
				var coordKey = dealer.longitude + ',' + dealer.latitude;
				
				if (coordinatesDealer[coordKey] != undefined){
					coordinatesDealerCount[coordKey]++;
					coordinatesDealer[coordKey] += html;
				}
				else {
					coordinatesDealer[coordKey] = html;
					coordinatesDealerCount[coordKey] = 1;
				}
				
				
				
				map.addOverlay(marker);
				GEvent.addListener( marker, 'click', function () {
					
					var style ="";
					if (coordinatesDealerCount[coordKey]>6) {
						style = "max-height:570px; overflow-y:auto;";
					}
					
					var markerHTML = '<div style="width:220px; '+style+'">'+coordinatesDealer[coordKey]+'</div>';
					marker.openInfoWindowHtml(markerHTML);
					return false;
				});
				
				$('#result_' +id+ ' h3 a').click( function () {
					marker.openInfoWindowHtml(html);
					return false;
				});
			} else {
				$('#result_' +id+ ' h3 a').click( function () {
					map.closeInfoWindow();
					return false;
				});
			}
			}
		},
		
		/*
		 * Function added to get longitude and latitude from geocoder, then add the marker on the map
		 * by : Nelson, CXRUS Solution Pte Ltd 2011/04/04
		 */
		getDealerLocationAndAddOnMap : function (dealer, id, html) {
			
			if (geocoder)
			{
				var address = dealer.addressLink1;
				
				if(dealer.addressLink2 && dealer.addressLink2 != undefined) {
					address += "," + dealer.addressLink2;
				}
				
				if(dealer.addressLink3 && dealer.addressLink3 != undefined) {
					address += "," + dealer.addressLink3;
				}
				
				if(dealer.addressLink4 && dealer.addressLink4 != undefined) {
					address += "," + dealer.addressLink4;
				}
				
				geocoder.getLatLng(
					address,
					function(point)
					{
						if (!point)
						{
							//alert(address + " not found");
						} else {
							//map.setCenter(point, 13);
							var marker = new GMarker(point);
							//alert(address+' got point:'+point);
							//alert(address+' got lat : ' + point.lat());
							//alert(address+" got lng : " + point.lng());
							dealer.longitude = point.lng();
							dealer.latitude = point.lat();

							var notFoundDiv = document.getElementById('dealerLocationNotFound_' + dealer.id);

							if(notFoundDiv) {
								notFoundDiv.style.display = "none";
							}

							priv.addDealerOnMap(dealer,dealer.id,html,true);
						}
					}
				);
			}
			
		},
		/* 
		 * End of additional code.
		 */
		
		//added by ivon start here
		
		showResult : function (data,dealerpage,selectedRegion,selectedProduct) {
			map.clearOverlays();
			$(config.dealerResults).slideUp(300).empty();

			if (dealerpage) {
				var obj, n, id = 0;
				if (isEmpty(data['prodlink']) || selectedProduct!=''){
					if (selectedProduct != '') {
						if (selectedProduct != 'others')
							obj = data['prodlink'][selectedProduct];
						else {
							obj = data['subcatlink'];
						}
					}
					else {
						obj = data['subcatlink'];
						
					}
					
					currentDealers = [];
					coordinatesDealer = {};
					coordinatesDealerCount = {};
					
					if (selectedRegion != config.defaultOption){
						var dealerContainer = obj[selectedRegion];
						if (dealerContainer.length == undefined) {
							currentDealers.push(dealerContainer);
						} else {
							for ( var i = 0; i < dealerContainer.length; i++ ) {
								currentDealers.push(dealerContainer[i]);
							};
						};
					}
					else {
						for ( var reg in obj ) {
							var dealerContainer = obj[reg];
							if (dealerContainer.length == undefined) {
								currentDealers.push(dealerContainer);
							} else {
								for ( var i = 0; i < dealerContainer.length; i++ ) {
									currentDealers.push(dealerContainer[i]);
								};
							};
						}
					}
					
					priv.updateView();
					$(config.dealerResults).slideDown(300);			
				}
				
			}

		},
		
		//added by ivon until here
		
		//if a selection for GM is made from the buying section, this method will set the dropdowns;
		setPreferredOptions : function ( hash ) {
			var	params = hash.replace(/#/g, '').split(';');
			var urlParams = {};
				//pos = [], num = [];
				
			for ( var i in params ) {
				num = params[i].split('=');
				urlParams[num[0]] = num[1];
			};
			
			if (urlParams['subcategory'] != undefined){
				$(config.categoryOptions).val(urlParams['subcategory']);
				$(config.categoryOptions).change();
			}
			
			if (urlParams['product'] != undefined){
				$(config.productOptions).val(urlParams['product']);
				$(config.productOptions).change();
			}
			
			if (urlParams['region'] != undefined){
				$(config.regionOptions).val(urlParams['region']);
				$(config.regionOptions).change();
			}
		}
	};
	
	return {
		
		//is set to false if current page is not the dealer locator
		isDealerPage : function ( bool ) {
			params.dealerpage = bool;
		},
		
		//retrieves and sets json;
		setJsonData : function ( json ) {
			if (dType=='general'){
				data = json['data'];
				mapping = json['mapping'];
			}
			else if (dType=='sales'){
				data_sales = json['data'];
				mapping_sales = json['mapping'];
			}
			else if (dType=='parts'){
				data_parts = json['data'];
				mapping_parts = json['mapping'];
			}
			else if (dType=='service'){
				data_service = json['data'];
				mapping_service = json['mapping'];
			}
		},
		

		addDealers : function (obj) {
			var n,id = 0;
			n = obj.length;
			if (n == undefined) {
				//priv.createHtmlElements( obj, 0 );
				currentDealers.push(obj);
			} else {
				for ( var i = 0; i < n; i++ ) {
					//priv.createHtmlElements( obj[i], id );
					currentDealers.push(obj[i]);
				};
			};
		},

		
		//sets preferred region as a global variable in the dealerLocator object;
		setRegionOption : function (dealerpage) {
			var obj, n, id = 0;
			
			if (dealerpage) {
				map.clearOverlays();
				$(config.dealerResults).slideUp(300).empty();
			}
			params.selectedRegion = $(config.regionOptions).val();
			
			var curData={},curMapping={};
			if (dType=='general'){
				curData = data;
				curMapping = mapping;
			}
			else if (dType=='sales'){
				curData = data_sales;
				curMapping = mapping_sales;
			}
			else if (dType=='parts'){
				curData = data_parts;
				curMapping= mapping_parts;
			}
			else if (dType=='service'){
				curData = data_service;
				curMapping = mapping_service;
			}
			
			if (params.selectedProduct != '') {
				if (params.selectedProduct != 'others')
					obj = curData[params.selectedCategory]['prodlink'][params.selectedProduct];
				else {
					obj = curData[params.selectedCategory]['subcatlink'];
					if (params.selectedRegion == config.defaultOption){
						params.selectedRegion = $(config.regionOptions).find(':first-child').val();
						$(config.regionOptions).removeAttr('disabled').find('> option', this).not(':first-child').remove();
						priv.setOptions( curData[params.selectedCategory]['subcatlink'], config.regionOptions,curMapping );
					}
				}
			}
			else {
				obj = curData[params.selectedCategory]['subcatlink'];
				
			}
			if (dealerpage){
				currentDealers = [];
				coordinatesDealer = {};
				coordinatesDealerCount = {};
				
				if (params.selectedRegion != config.defaultOption){
					var dealerContainer = obj[params.selectedRegion];
					this.addDealers(dealerContainer);
				}
				else {
					for ( var reg in obj ) {
						var dealerContainer = obj[reg];
						this.addDealers(dealerContainer);
					}
				}
			
				priv.updateView();
				$(config.dealerResults).slideDown(300);
			}
		},
		
		//onchange event on the region dropdown;
		filterRegionOptions : function ( elem, dealerpage ) {
			$(config.productOptions).hide();
			params.selectedCategory = $(config.categoryOptions).val();
			params.selectedProduct = '';
			
			var curData={},curMapping={};
			if (dType=='general'){
				curData = data;
				curMapping = mapping;
			}
			else if (dType=='sales'){
				curData = data_sales;
				curMapping = mapping_sales;
			}
			else if (dType=='parts'){
				curData = data_parts;
				curMapping= mapping_parts;
			}
			else if (dType=='service'){
				curData = data_service;
				curMapping = mapping_service;
			}
			
			if (params.selectedCategory == config.defaultOption) {
				$(config.regionOptions).attr('disabled','disabled').get(0).selectedIndex = 0;
			} else {

				if (!isEmpty(curData[params.selectedCategory]['subcatlink'])){
					if (isEmpty(curData[params.selectedCategory]['prodlink'])){
						params.selectedRegion = $(config.regionOptions).find(':first-child').val();
						$(config.regionOptions).removeAttr('disabled').find('> option', this).not(':first-child').remove();
						priv.setOptions( curData[params.selectedCategory]['subcatlink'], config.regionOptions,curMapping );
						if (dealerpage) {
							this.setRegionOption(dealerpage);
						}
					}
					else {
						$(config.productOptions).show();
						$(config.productOptions).find('> option', this).not(':first-child').remove();
						priv.setOptions( curData[params.selectedCategory]['prodlink'], config.productOptions,curMapping );
						$(config.productOptions).append('<option value="others">Other Products</options>');
						$(config.regionOptions).attr('disabled','disabled').get(0).selectedIndex = 0;
						if (dealerpage) {
							map.clearOverlays();
							$(config.dealerResults).slideUp(300).empty();
						}
					}
				}
				else {
					$(config.productOptions).show();
					$(config.productOptions).find('> option', this).not(':first-child').remove();
					priv.setOptions( curData[params.selectedCategory]['prodlink'], config.productOptions,curMapping );
					$(config.regionOptions).attr('disabled','disabled').get(0).selectedIndex = 0;
					if (dealerpage) {
						map.clearOverlays();
						$(config.dealerResults).slideUp(300).empty();
					}
				}
				//priv.setOptions( data[params.selectedCategory], config.regionOptions );
			};
	
		},
		
		productChange : function (elem, dealerpage) {
			var curData={},curMapping={};
			if (dType=='general'){
				curData = data;
				curMapping = mapping;
			}
			else if (dType=='sales'){
				curData = data_sales;
				curMapping = mapping_sales;
			}
			else if (dType=='parts'){
				curData = data_parts;
				curMapping= mapping_parts;
			}
			else if (dType=='service'){
				curData = data_service;
				curMapping = mapping_service;
			}
			var selectedProduct = elem[elem.selectedIndex].value;
			params.selectedRegion = $(config.regionOptions).find(':first-child').val();
			$(config.regionOptions).removeAttr('disabled').find('> option', this).not(':first-child').remove();
			
			priv.setOptions( curData[params.selectedCategory]['prodlink'][selectedProduct], config.regionOptions,curMapping );
			params.selectedProduct = selectedProduct;
			this.setRegionOption(dealerpage);
		},
				
		
		//initiate is triggered after document onload event;
		initiate : function (lat,lng,zoomLevel,dealerpage) {
			if (dType=='general')
				priv.setOptions(data, config.categoryOptions,mapping);
			else if (dType=='sales')
				priv.setOptions(data_sales, config.categoryOptions,mapping_sales);
			else if (dType=='parts')
				priv.setOptions(data_parts, config.categoryOptions,mapping_parts);
			else if (dType=='service')
				priv.setOptions(data_service, config.categoryOptions,mapping_service);
			
			if (dealerpage) {
				priv.configureGoogleMaps(lat,lng,zoomLevel);
			};
		},
		
		//added by ivon start here
		initiate2 : function (lat,lng,zoomLevel, data, dealerpage,selectedRegion,selectedProduct) {
			priv.configureGoogleMaps(lat,lng,zoomLevel);
			priv.showResult(data,dealerpage,selectedRegion,selectedProduct);
		},
		setSelectedCategory : function ( selectedCategory ) {
			params.selectedCategory = selectedCategory;
		},
		setSelectedRegion : function ( selectedRegion ) {
			params.selectedRegion = selectedRegion;
		},
		setSelectedProduct : function ( selectedProduct ) {
			params.selectedProduct = selectedProduct;
		},

		//added by ivon until here
		
		setCopy : function (copy_) {
			copy = copy_;
		}
	};
	
	
}

var dealerLocator = createDealerLocator('general');
var salesLocator = createDealerLocator('sales');
var partsLocator = createDealerLocator('parts');
var serviceLocator = createDealerLocator('service');






