function initialize() {
    geocoder = new google.maps.Geocoder();
	//initial position for that country
    latlng = new google.maps.LatLng(launch_lat, launch_lng);
    myOptions = {
      zoom: launch_zoom,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
	  mapTypeControl: false,
	  navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN,
			position: google.maps.ControlPosition.TOP_LEFT
		}
    }
	$('.prodtype-td').hide();
    map = new google.maps.Map(document.getElementById("map"), myOptions);
	//Add a link to "change country"
	
	//var homeControlDiv = document.createElement('DIV');
	//var homeControl = new HomeControl(homeControlDiv, map);
	//homeControlDiv.index = 1;
	//map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
}

function HomeControl(controlDiv, map) {
//Function used to add a link to the hub (url retrieved from the wep bar)
  controlDiv.style.paddingTop = '0px';
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = '#e9eef8';
  controlUI.style.borderStyle = 'solid';
  controlUI.style.borderColor = '#6688cc';
  controlUI.style.borderWidth = '2px';
  controlUI.style.cursor = 'pointer';
  controlUI.style.textAlign = 'center';
  controlUI.title = 'Click to change country';
  controlDiv.appendChild(controlUI);
  var controlText = document.createElement('DIV');
  controlText.style.fontSize = '12px';
  controlText.style.fontWeight = '700';
  controlText.style.padding = '4px';
  controlText.style.color = '#f26522';
  controlText.innerHTML = 'Change country';
  controlUI.appendChild(controlText);
  google.maps.event.addDomListener(controlUI, 'click', function() {loc_url= $('.wepCountryBtnWrap li a').attr('href');window.location.replace(loc_url);});
}

//function finding the center of the map based on the search box
function codeAddress() {
	
	if(wep.locale=='ru_KZ'){var address = $("#addressInput").val()+ ', ' + $('#russia_cy option:selected').html(); }else{	
    var address = $("#addressInput").val()+ ', ' + str_Country;}
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		$('#waiting').empty();
		var center_set = results[0].geometry.location;
        map.setCenter(center_set);
		FirstLaunchSearchLocNear(center_set,'all');	
	  } else {
        $('#waiting').append('<span class="warning"><br/>' + str_error +' ('+ status + ')</span>');
		$('#waiting').css('display','block');
      }
 	}
);
}

function process_marker(asc,prod){
	
	if(full){var distance = parseFloat(asc.getElementsByTagName("distance")[0].childNodes[0].nodeValue);}else{var distance=false};
		var productCat = asc.getElementsByTagName("productCategories")[0];

//We show a marker for all products if no fliter is on, or for the filtered product; only within the defined radius
	if((prod=='all'|| (productCat.getAttribute(prod)=="True"))&& distance<radius){
		var rank = asc.getElementsByTagName("Rank")[0].childNodes[0].nodeValue;
		var name = asc.getElementsByTagName("companyName")[0].childNodes[0].nodeValue;
		var street = asc.getElementsByTagName("street")[0].childNodes[0].nodeValue;
		var zip = asc.getElementsByTagName("zipCode")[0].childNodes[0].nodeValue;
		var city = asc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
		var email = asc.getElementsByTagName("email")[0].childNodes[0].nodeValue;
		var phone = asc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
		var phone2 = asc.getElementsByTagName("phone2")[0].childNodes[0].nodeValue;
		var phone3 = asc.getElementsByTagName("phone3")[0].childNodes[0].nodeValue;
		var website = asc.getElementsByTagName("website")[0].childNodes[0].nodeValue;
		var fax = asc.getElementsByTagName("fax")[0].childNodes[0].nodeValue;
		var optime = asc.getElementsByTagName("openingTimes")[0].childNodes[0].nodeValue;
		var notes = asc.getElementsByTagName("notes")[0].childNodes[0].nodeValue;
		var oow = asc.getElementsByTagName("oow")[0].childNodes[0].nodeValue;
		var ratings; (wep.locale=='ru_RU')? ratings = asc.getElementsByTagName("ratings")[0]: ratings='';
		if(zip=='1'){zip=''};
		var address = street + '<br/>' + zip + ' ' + city;
		
		//Prepare data necessary to create a marker point
		var point = new google.maps.LatLng(parseFloat(asc.getElementsByTagName("point")[0].getAttribute('lat')),parseFloat(asc.getElementsByTagName("point")[0].getAttribute('lng')));
	    var image = new google.maps.MarkerImage('/support/css/imgs/flag.png', new google.maps.Size(40,40), new google.maps.Point(0,0),new google.maps.Point(0, 32));
	   // var baseSonyIcon = new GIcon(G_DEFAULT_ICON);
	    //baseSonyIcon.iconSize = new GSize(34, 38);
	    //baseSonyIcon.image = 'http://www.sony.co.uk/bravia/image/layout/content/imgDealerResultNumber' + 1 + '.png';
	    //baseSonyIcon.shadow = '';

	    marker = new google.maps.Marker({ map: map, position: point, icon: image, title: name });
	    //marker = new google.maps.Marker({ map: map, position: point, icon: baseSonyIcon, title: name });
		bound.extend(point);
		
		//Prepare data necessary to create the infowindow that opens on click
	    ($.trim(website) =='' || website == 'n/a' || website == null)? website = '' : website = '<a href=http://'+website+'>'+website+'</a>';
		if(city=='n/a'){city=''};
			
			
		var asc_html = "<h4>"+$.trim(name)+"</h4><h5>" + adr_str + '</h5><p>' +address + "<br/></p>";
		asc_html += "<h5>" + adr_phone + '</h5><p>' + phone ;
		
		/* ASC locator change : Add  message on bubble when oow's asc*/
		if (prod== 'IT' && oow =='True' ) { asc_html += oow_mess  ;  }
		//	asc_html += "<p><img src=\"/support/css/imgs/repair-flag.gif\" align=\"center\"/></p>";				
		
		var infowindow = new google.maps.InfoWindow();
		
		infowindow.setContent(asc_html);
		
		//infowindow.maxWidth=400;
		asc_html='';
		google.maps.event.addListener(marker, 'click', function() {infowindow.open(map, this);});
		//Save them in an array to be able to remove them afterwards
		markersArray.push(marker);
		//Prepare data to be shown in the table underneath.
		theEntry = createSidebarEntry(marker, name, city, address, distance, website, email, phone, phone2, phone3, fax, productCat, optime, notes, ratings);
		//Sort the entries depending on their rank
		if(wep.locale!='ro_RO'){
			switch(rank){
				case '1' : $('#VIPresults').append(theEntry); break;
				case '3' : $('#TR2results').append(theEntry); break;
				default : $('#ascresults').append(theEntry);
			};
		}else{if(productCat.getAttribute('IT')=="True"){$('#VIPresults').append(theEntry);}else{$('#ascresults').append(theEntry);}}
			
	}
}


function createSidebarEntry(marker, name, city, address, distance, website, email, phone, phone2, phone3, fax, productCat, optime, notes, ratings) {
	 
      var div = $( document.createElement('div') );
	  var theProducts='<ul>   ';
	  var R1='';var R2='';var R3='';var R4='';var R5='';
	
	if(productCat){
		for(j=0; j<(productCat.attributes.length);j++){
			if(productCat.attributes[j].value!=='False'){
				var productCatName = eval("str_"+productCat.attributes[j].name);
				theProducts += '<li>' + productCatName +'</li> ';
			}
		};
	theProducts = theProducts.slice(0,theProducts.length-2);
	theProducts +='</ul>';
	};
	  
	  //create a table to append at the end of the page
	  var html = '<div class="shopDetailsListViewItem"><div class="shopDetailsColumnWrapper clearfix">';
	  
 	  //first col contains distance
	  html += '<div class="shopDetailsColumn shopDetailsColumnSize2">';
	  
		if(distance){
			if(unit_d=="M"){html += '<div class="shopDetailsVisuals"> <div class="distance"><strong>'+str_distance+'</strong>' + distance.toFixed(1) + ' miles </div></div>';
			}
			else if(wep.locale=='ru_RU'){html += '<div class="shopDetailsVisuals"> <div class="distance"><strong>'+str_distance+' </strong>' + distance.toFixed(1) + ' '+ru_km+' </div></div>';
			}
			else{html += '<div class="shopDetailsVisuals"> <div class="distance"><strong>'+str_distance+' </strong>' + distance.toFixed(1) + ' KM </div></div>';}
		};     
		html +='</div>';
		//end of first column
		
		//second column contains shop name + webiste
		html += '<div class="shopDetailsColumn shopDetailsColumnMain"><h2><span>' + name+'</span></h2>' ;
		if(website && $.trim(website)!='n\/a'){html += '<p><strong>' + website + '</strong></p>';};
		html += '<div class="shopDetailsColumnDetail"><h3>'+str_allProd+'</h3><p>'+theProducts+'</p></div>';
		html +='</div>';
		//end of second column

		//third column
	  	html +='<div class="shopDetailsColumn">';
		if(address && $.trim(address)!='n\/a'){html += '<div class="shopDetailsColumnDetail"><h3>' + listadr_str + '</h3> <p>' + address +'</p></div>';};
		if(optime && $.trim(optime)!='' && $.trim(optime)!='n\/a'){html += '<div class="shopDetailsColumnDetail"><h3>' + optime_str + '</h3><p> ' + optime +'</p></div>';};
		html+='</div>';
		//end of third column
		
		//fourth column
		html+='<div class="shopDetailsColumn lastColumn">';
		if(phone && $.trim(phone)!='n\/a')
			{
				html += '<div class="shopDetailsColumnDetail"><h3>' + adr_phone + '</h3><p>' + phone;
				if(phone2 && $.trim(phone2)!='n\/a')html += '<br/>' + phone2;
				if(phone3 && $.trim(phone3)!='n\/a')html += '<br/>' + phone3;
				html += '</p></div>';
			}
	  	if(fax&& $.trim(fax)!='n\/a'){html += '<div class="shopDetailsColumnDetail"><h3>' + fax_str + '</h3><p>' + fax +'</p></div>';};

	  
	  	if (wep.locale!='en_GB' && wep.locale!='en_IE' && wep.locale!='pl_PL'){
			if(email && $.trim(email)!='n\/a'){html += '<div class="shopDetailsColumnDetail"><h3>' + email_str + '</h3><p><a href="mailto:' + email + '">'+email+'</a></p></div>';};
		};
		
		if(theProducts.lastIndexOf('VAIO')!=-1){notes+=vaio_mess};
	
		if(notes && $.trim(notes)!='' && $.trim(notes)!='n\/a'){html += '<div class="shopDetailsColumnDetail"><h3>' + notes_str + '</h3><p> ' + notes +'</p></div>';};
		html+='</div>';
		//end fourth column
		
		
		//Only for Russia
		
		
		
		if(wep.locale=='ru_RU'){
			var r0_img="<img src=\"/support/css/imgs/r0.png\" alt=\"ZERO\" width=\"100px\" height=\"20px\" />" 
			var r1_img="<img src=\"/support/css/imgs/r1.png\" alt=\"ONE\" width=\"100px\" height=\"20px\" />"
			var r2_img="<img src=\"/support/css/imgs/r2.png\" alt=\"TWO\" width=\"100px\" height=\"20px\" />"
			var r3_img="<img src=\"/support/css/imgs/r3.png\" alt=\"THREE\" width=\"100px\" height=\"20px\" />"
			var r4_img="<img src=\"/support/css/imgs/r4.png\" alt=\"FOUR\" width=\"100px\" height=\"20px\" />"
			var r5_img="<img src=\"/support/css/imgs/r5.png\" alt=\"FIVE\" width=\"100px\" height=\"20px\" />"
			
			//var QR_img = eval('r'+ratings.attributes[0].value+'_img');
			//var OW_img = eval('r'+ratings.attributes[1].value+'_img');
			//var VOC_img = eval('r'+ratings.attributes[2].value+'_img');
			if(ratings.attributes[3].value=='1'){var ihs="<img src=\"/support/css/imgs/YES.png\" alt=\"Yes\" />";}else{var ihs="<img src=\"/support/css/imgs/NO.png\" alt=\"No\" />";};

			var QR_content;
			var OW_content;
			var VOC_content;
			
			//always show the iimage even if it is a zero
//			QR_content = '<span class="ascexpl">'+slow +'</span>'+QR_img+'<span class="ascexpl">'+ fast+'</span>';
			

			//QR_content = QR_img;
			//if rating is 0, display "no information"
			/*if (ratings.attributes[1].value=='0'){OW_content=no_opinion}else{OW_content = OW_img};
			if (ratings.attributes[2].value=='0'){VOC_content=no_opinion}else{VOC_content = VOC_img};*/
			if (ratings.attributes[0].value=='-1'){QR_content=no_opinion}else{QR_content = eval('r'+ratings.attributes[0].value+'_img')};
			if (ratings.attributes[1].value=='-1'){OW_content=no_opinion}else{OW_content = eval('r'+ratings.attributes[1].value+'_img')};
			if (ratings.attributes[2].value=='-1'){VOC_content=no_opinion}else{VOC_content = eval('r'+ratings.attributes[2].value+'_img')};
			html += '<table class="innerASC"><tr><td>'+ str_qrep+'</td><td>'+QR_content+'</td></tr><tr><td>'+str_owcost+ '</td><td>'+OW_content+'</td></tr><tr><td>'+str_voc+ '</td><td>'+VOC_content+'</td></tr></table>';
			};


	  html+='</div> <div class="listItemSeperator">&nbsp;</div>';
    
	  div.html(html);

     
      return div;

}

function launch_full(){
	//url of the applic with zip code search box
	//show the input for zip code
	full=true;
	$('#loclabel, #locinput').css('display','block');
	//if($('#prodtype')){$('#prodtype').bind('change', function(e){codeAddress();return false;});};
	$('#addressInput').bind('keydown',function(e){if (e.keyCode == 13){codeAddress();return false;}});
	$('#addressSubmit').bind('click',function(e){ if($('#addressInput').val()!=''){codeAddress();return false;}else{
																							   //raise an alert if the imput is not filled in
		    var newAlert = $('<div class="alert-content" title="Warning"> '+$('#enter_asc').html()+' </div>');
			$( '#addressSubmit' ).after(newAlert);	
			$(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
																							   
																							   }});
}
//reset the UI.
function empty_asc_fields(){deleteOverlays();$('#ascresults,#VIPresults,#TR2results').text('');}
// Deletes all markers in the array by removing references to them

//Bugs with wep script
//function deleteOverlays() {if (markersArray) {for (i in markersArray) {markersArray[i].setMap(null);}markersArray.length = 0;}}
function deleteOverlays() {if (markersArray) {for (i=0;i < markersArray.length; i++) {markersArray[i].setMap(null);}markersArray.length = 0;}}
//Empty the map and the DIVs, show the wait icon, get the new location, get the radius value,

function searchLocationsNear(loc,prod){
	bound = new google.maps.LatLngBounds();
	(wep.locale == "lt_LT") ? local_ws = "en_LV": local_ws=wep.locale;
	(full)? url_ws='/support/webservices/asclist.asmx/listlocator?locale='+local_ws+'&lat2=' + loc.lat() + '&long2=' + loc.lng() + '&unit='+unit_d:url_ws='/support/webservices/ascall.asmx/countryASC?locale=' + local_ws;
	empty_asc_fields();
	$('#waiting_IMG').show();
	
	radius = $('#radiusSelect').val();
	$.ajax({type:"GET",url:url_ws,dataType:"xml",success:function(xml){
				//Notify omniture
				s.pageName="spt : Service center search results";s.t();
				empty_asc_fields();
				/*$('#topofmapNotification').hide();*/
				var markers=$(xml).find('serviceAddress');
				for (i = 0; i < markers.length; i++) {process_marker(markers[i],prod);}
				$('#waiting_IMG').hide();
				map.fitBounds(bound);
																	 
				 if(wep.locale=="en_GB" || wep.locale=="tr_TR" || wep.locale=="ro_RO"){
						title = $('<div class="titlebar"></div>').html(str_othRep+'<p></p>');
						if ($('*', $('#ascresults')).length !== 0)$('#ascresults').prepend(title);			
						titleTR2=$('<div class="titlebar"></div>').html(str_altRep+'<p></p>');
						if ($('*', $('#TR2results')).length !== 0)$('#TR2results').prepend(titleTR2);
						titleVIP=$('<div class="titlebar"></div>').html(str_vipRep);
						if ($('*', $('#VIPresults')).length !== 0)$('#VIPresults').prepend(titleVIP);
						$('#VIPresults .titlebar h3,#ascresults .titlebar h3,#TR2results .titlebar h3').prepend('<img src="/support/css/imgs/flag.png"/>')
				}										 			
														 			 
				if(full)$('#selRadius, #labelRadius, #selRadiusDist').show();
				var shopOptions = getTheOptions(xml);	
				$('#prodtype').text('');
				$('#prodtype').append(shopOptions);
				$('.prodtype-td').show();
				$('#locatorNotification').hide();				
				$('.locatorTabs').css('visibility','visible');															 
				$('#selProd').css('display','block');
				var country = wep.locale.substring(3);
				
				/* ASC locator change : Add top of map message depending on country*/
				if (prod == 'IT' && (country =='DE' || country == 'GB'|| country == 'BE'|| country == 'CH'|| country == 'CZ'|| country == 'DK'|| country == 'FI'|| country == 'FR'|| country == 'EL'|| country == 'KZ'|| country == 'LU'|| country == 'NO'|| country == 'SV'|| country == 'UK'|| country == 'AT' ))
				{   
					/*$('#topofmapNotification').html(vaio_iw); */
					$('.vaio_iw').show(); 
					$('#topofmapNotification').show(); 
				}
				else if (prod == 'IT' && (country =='BG' || country == 'ES'|| country == 'HU'|| country == 'IE' || country == 'IT'|| country == 'PL' || country == 'RO' || country == 'SK') )
				{
					/*$('#topofmapNotification').html(vaio_oow); */
					$('.vaio_oow').show(); 
					$('#topofmapNotification').show(); 
				}																																																					 																																																																																																																								
				else {$('#topofmapNotification').hide();} 
						
  			    $('#prodtype').bind('change', function(){	/*if ($(this).val()) = null {	*/									
						empty_asc_fields();
						(full)?searchLocationsNear(loc,$(this).val()):searchLocationsNear(null,$(this).val());
						$('#prodtype option[value='+$(this).val()+']').attr("selected", "selected");
																			/*}*/
				});	
				if(prod!='all'){$('#prodtype option[value='+prod+']').attr("selected", "selected");}
			}});
};

function FirstLaunchSearchLocNear(loc,prod){
	bound = new google.maps.LatLngBounds();
	(wep.locale == "lt_LT") ? local_ws = "en_LV": local_ws=wep.locale;
	(full)? url_ws='/support/webservices/asclist.asmx/listlocator?locale='+local_ws+'&lat2=' + loc.lat() + '&long2=' + loc.lng() + '&unit='+unit_d:url_ws='/support/webservices/ascall.asmx/countryASC?locale=' + local_ws;
	empty_asc_fields();
	$('#waiting_IMG').show();
	
	radius = $('#radiusSelect').val();
	$.ajax({type:"GET",url:url_ws,dataType:"xml",success:function(xml){
				//Notify omniture
				s.pageName="spt : Service center search results";s.t();
				empty_asc_fields();
				$('#topofmapNotification').hide();				 																	 			 
				if(full)$('#selRadius, #labelRadius, #selRadiusDist').show();
				var shopOptions = getTheOptions(xml);	
				$('#prodtype').text('');
				$('#prodtype').append(shopOptions);
				$('.prodtype-td').show();
				$('#locatorNotification').hide();					
				$('#selProd').css('display','block');	
				var country = wep.locale.substring(3);
				if (country =='NL' || country == 'PT')
				{					
					$('.vaio_nowarr').show(); 
					$('#topofmapNotification').show(); 
				}	
				
  			    $('#prodtype').bind('change', function(){												
						empty_asc_fields();
						(full)?searchLocationsNear(loc,$(this).val()):searchLocationsNear(null,$(this).val());
						$('#prodtype option[value='+$(this).val()+']').attr("selected", "selected");		
				});
				if(prod!='all'){$('#prodtype option[value='+prod+']').attr("selected", "selected");}
			}});
};

function getTheOptions(xml){
		select_opt==''? select_opt='Select an option':select_opt=select_opt;
		var productCats = xml.documentElement.getElementsByTagName('radius');
		var shopOptions = '<option disabled="disabled" selected=\"1\" >'+select_opt+'</option>';
		for(i=0;i<productCats.length;i++){
			if(productCats[i].getAttribute('DIST')== radius || !full){
				if(!full){init_compt=0}else{init_compt=1};
				for(j=init_compt; j<(productCats[i].attributes.length);j++){
					if(productCats[i].attributes[j].value!=0){
						var productCatName = eval("str_"+productCats[i].attributes[j].name);
						shopOptions += "<option value=\""+productCats[i].attributes[j].name+"\">"+productCatName+"</option>";
						/*shopOptions += '<p><input type="radio" value="'+ productCats[i].attributes[j].name +'" id="'+ productCats[i].attributes[j].name +'" name="RadioButton" class="radio left" /><label>'+ productCatName+'<span class="asc_prod_type"> ('+productCats[i].attributes[j].value;
						//Poland doesnt want the word adress.
						if(wep.locale!='pl_PL'){shopOptions+=' '+adr_str};
						shopOptions +=')</span></label></p>';*/
						}
					}
			};
		};
		shopOptions+='';
		return shopOptions;
}

var markersArray = [];var full=false; var geocoder; var map;

$(document).ready(function() {
  	  
	   var set_zoom=8;
		switch(wep.locale){
			case 'en_GB' : unit_d="M"; initialize(); $('#radiusSelect').val(25); launch_full();
							break;
			case 'ru_RU' : unit_d="K"; initialize(); $('#radiusSelect').val(50); launch_full();
							break;
			case 'it_IT' : 
			case 'pt_PT' : 											 
			case 'ru_KZ' : 
			case 'es_ES' : 
			case 'tr_TR' :
			case 'pl_PL' : unit_d="K"; initialize(); $('#radiusSelect').val(100); launch_full();
							break;
			default : 		unit_d="K"; initialize(); $('#radiusSelect').val(100); FirstLaunchSearchLocNear(latlng,'all'); $('#addressSubmit').hide();
		}

	//show or hide the view depending on the tab that is clicked.
	$("#listViewLink").bind("click",function(e){
		e.preventDefault();
		var tab=$(this);
		updateActiveTab(tab);
	});
	$("#mapViewLink").bind("click",function(e){
		e.preventDefault();
		var tab=$(this);
		updateActiveTab(tab);
	});

});


function updateActiveTab(A){
	$(".locatorTabs").find("a").removeClass("activeTab");
	$(".locatorTabContent").removeClass("activeTabContent");
	A.addClass("activeTab");
	$(A.attr("href")).addClass("activeTabContent")
}
