Epson.WhereToBuy = function( element )
{
	var _self = this;
	var _element = element;
	var _search_field = null;
	var _form = null;
	var _records = 0;
	globalElement = element;
	var _map = null;
	var _router = null;
	var _point = null;
	var _zoom_widget = null;
	var _view_widget = null;
	var _overview_widget = null;

	var _product_url = '';
	var _prod_id = '';
	var _error_url = '';
	var _product_name = '';
	var _mm_url = 'http://www.multimap.com/maps/'
	var _print_url = '/jsps/storeLocator/pageMap.jsp';
	var _email = location.protocol+'//'+ location.host + '/jsps/storeLocator/emailPage.jsp';
	var _short_url = 'http://www.multimap.com/mod/common/short_url.htm?long_url=';
	var _directions_url = 'http://www.multimap.com/directions/';
	var _data_source = '';
	var _filters = [];
	var _filter_logic = 'AND';
	var _email_url = '';
	var _country_code = '';
	var _location = '';
	var _location_title = '';
	var _sku = false;
	var _width_radius = true;
	var _curr_postcode = '';
	var _marker_details = null;
	var tempvar = 100;
	var Consts =
	{
		max_pages:5,
		results_per_page:10,
		max_distance:100
	}
	var dataI = -1;


	function setup()
	{
		// pull out mm data
		var data = {  };
		jQuery.each( _element.className.split( ' ' ), function()
		{
			var match = this.match( /^wtb-([^-]+)-(.+)$/ );

			if ( match )
			{
				if ( data[ match[1] ] )
				{
					if ( data[ match[1] ] instanceof Array ) data[ match[1] ].push( convertpEnc2Char( match[2] ) );
					data[ match[1] ] = [ data[ match[1] ], convertpEnc2Char( match[2] ) ];
				}
				else data[ match[1] ] = convertpEnc2Char( match[2] );
			}
		} );
		jQuery.each( data, function( key )
		{
			if (( this instanceof Array ) || (key == 'filters')) eval( '_'+key+'=this' );
			else eval( '_'+key+'="'+this+'"' );

			if ( key == 'country_code') _country_code = this;

		} );
		// set up markers
		if ( MMFactory ) Markers.setup();

		// set up filters
		Filters.setup();

		// bind event to link
		if ( _element.nodeName == 'A' )
		{
			if ( _location ) jQuery( _element ).bind( 'click', UI.openMap );
			else jQuery( _element ).bind( 'click', UI.open );
		}
		else
		{
			_search_field = _element;
			_form = jQuery( _search_field ).parents( 'form' );
			_form.bind( 'submit', Search.search );

			// pre-popuplate the search field if a value was stored
			var saved_query = Epson.Cookies.read( 'postcode' );
			if ( saved_query && jQuery( _search_field ).val() == '' ) jQuery( _search_field ).val( saved_query );

			Validation.setup();
		}
	}
	
	//Added as part of Epson 1.4.5.4 release to fix encoding issue in GR locale by Avinash-Start
	function convertpEnc2Char(str) {
	 
	str = str.replace(/((%[A-Fa-f0-9]{2})+)/g, 
		 function( matchstr, parens) {
		   return convertpEsc2Char(parens); 
		 }); 
	 return str;
	} 
	 
	function convertpEsc2Char ( str ) {
	 // converts to characters a sequence of %-separated hex numbers representing bytes in utf8
	 // str: string, the sequence to be converted
	 
	 var outputString = "";
	 var counter = 0;
	 var n = 0;
	 
	 var listArray = str.split('%');
	 for ( var i = 1; i < listArray.length; i++ ) {
	  var b = parseInt(listArray[i], 16);  // alert('b:'+dec2hex(b));
	  switch (counter) {
	  case 0:
	   if (0 <= b && b <= 0x7F) {  // 0xxxxxxx
		outputString += dec2char(b); } 
	   else if (0xC0 <= b && b <= 0xDF) {  // 110xxxxx
		counter = 1;
		n = b & 0x1F; }
	   else if (0xE0 <= b && b <= 0xEF) {  // 1110xxxx
		counter = 2;
		n = b & 0xF; }
	   else if (0xF0 <= b && b <= 0xF7) {  // 11110xxx
		counter = 3;
		n = b & 0x7; }
	   else {
		outputString += 'convertpEsc2Char: error ' + dec2hex(b) + '! ';
		}
	   break;
	  case 1:
	   if (b < 0x80 || b > 0xBF) {
		outputString += 'convertpEsc2Char: error ' + dec2hex(b) + '! ';
		}
	   counter--;
	   outputString += dec2char((n << 6) | (b-0x80));
	   n = 0;
	   break;
	  case 2: case 3:
	   if (b < 0x80 || b > 0xBF) {
		outputString += 'convertpEsc2Char: error ' + dec2hex(b) + '! ';
		}
	   n = (n << 6) | (b-0x80);
	   counter--;
	   break;
	  }
	  }
	 return outputString;
	}
	 
	function dec2char ( n ) {
	 // converts a single string representing a decimal number to a character
	 // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
	 // dec: string, the dec codepoint to be converted
	 var result = '';
		if (n <= 0xFFFF) { result += String.fromCharCode(n); } 
	 else if (n <= 0x10FFFF) {
	  n -= 0x10000
	  result += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
		 } 
	 else { result += 'dec2char error: Code point out of range: '+dec2hex(n); }
	 return result;
	}
	//Added as part of Epson 1.4.5.4 release to fix encoding issue in GR locale by Avinash-End
	

	
	// The addHandler method that Microsoft have provided pass an argument to the function that
	// looks similar to an event, but there are major differences. This means that we can't rely
	// on otherwise simple things like e.target or e.preventDefault() to mean what they should or
	// event anything at all. As as result, we need these two functions to help us take the false
	// event argument and do useful things with it.
	function getTarget(e) {
		var evt = e || window.event,
			target;
		if (evt) {
			
			// Check to see if the genuine event is stored and if it has a target property.
			if (evt.originalEvent && evt.originalEvent.target) {
				target = evt.originalEvent.target;
			
			// Next check to see if we're using the old Microsoft model.
			} else if (evt.srcElement) {
				target = evt.srcElement;
			
			// Finally, check to see if the event simply has a target property. We do this last
			// because the addHandler method that Microsoft have provided send a target property
			// with their "event" argument, but it simply maps to the containing element to which
			// the event was bound, not the element that originated the event.
			// TODO: check that this is even useful in any way.
			} else if (evt.target) {
				target = evt.target;
			}
		}
		return target;
	}
	function stopDefault(e) {
		var evt = e || window.event;
		if (evt) {
			// You never know, we may get lucky.
			if (evt.preventDefault) {
				e.preventDefault();
			
			// Not lucky, huh? Did Microsoft send us the genuine event?
			} else if (evt.originalEvent && evt.originalEvent.preventDefault) {
				e.originalEvent.preventDefault();
			
			// Still no? How about the old Microsoft model - is that being used here?
			} else if (evt.hasOwnProperty('returnValue')) {
				evt.returnValue = false;
			}
		}
	}


	var Map =
	{
	//	callback:null,
		map:null,
		load: function()
		{
			jQuery( 'head' ).append( '<script charset="UTF-8" type="text\/javascript"src="http:\/\/ecn.dev.virtualearth.net\/mapcontrol\/mapcontrol.ashx?v=7.0&mkt=en-GB"><\/script>' );
			
			Map.map = new Microsoft.Maps.Map(document.getElementById("WTBMMap"),{credentials:"AmqoIN12wAG8HhElyEz8f_7zQNER1T8XfNYjsvfsmJTMmrXDJUMrTYujjHGGuxew",center : new Microsoft.Maps.Location(0, 0), zoom: 0});
			
			Microsoft.Maps.Events.addHandler(Map.map, 'click', Markers.closeInfobox);
			
			$('#WTBResults').get(0).scrollTop = 0;
			
		},

		pollLoad: function()
		{
			//if ( !MMFactory ) setTimeout( Map.pollLoad, 200 );
			if ( Map.callback )
			{
				// set up markers
			//	Markers.setup();

				// set up filters
					Filters.setup();

					Map.callback();
				}
			}
			
		}

		var Markers = 
		{
			icon :null,
			point: null,
			data: [],
			pinInfobox: null,

			setup: function () {
				/*Markers.icon = new MMIcon( Epson.Path + 'images/ico_MMMarker_blue.png' );
				Markers.icon.iconSize = new MMDimensions( 25, 32 );
				Markers.icon.iconAnchor = new MMPoint( 12, 37 );
				Markers.icon.infoBoxAnchor   = new MMPoint( 12, -5 );*/
			},

			create: function (record) {

				var pinInfobox,  //the pop up info box
					infoboxLayer = new Microsoft.Maps.EntityCollection(),
					pinLayer = new Microsoft.Maps.EntityCollection(),
					html = [],
					i18n = Epson.Localisation.WhereToBuy,
					latLon = new Microsoft.Maps.Location(record.Latitude, record.Longitude),
					pin = new Microsoft.Maps.Pushpin(latLon, {
						text: ''+record.counter+'',
						typeName: record.counter,
						icon: Epson.Path + 'images/ico_MMMarker_blue.png'
					});

				html.push('<div class="infobox_title">', record.store_name, '<\/div>');
				html = html.concat(['<div class="infobox_address">'], Markers.formatAddress(record), ['<\/div>']);
				html.push('<div class="infobox_directions">',
							  '<a href="#" class="infobox_from">', i18n.TXT003, '<\/a>',
							  '<label>', i18n.TXT004, '<\/label>',
							  '<input type="text" class="f_directions_to"\/>',
							  '<a class="route" href="#">', i18n.TXT005, '<\/a>',
						  '<\/div>');
				html.push('<div class="buttons">',
							  '<a href="#" class="buttonSmall print"><span>', i18n.TXT006, '<\/span><\/a>',
							  '<a href="#" class="buttonSmall email"><span>', i18n.TXT007, '<\/span><\/a>',
						  '<\/div>');
				
				// Add the HTML content to an infobox wrapper.
				html = ['<div class="infobox">',
							'<div class="infobox_top infobox_group">',
								'<div class="infobox_left"></div>',
								'<div class="infobox_right"></div>',
								'<div class="infobox_centre"></div>',
							'</div>',
							'<div class="infobox_middle infobox_group">',
								'<div class="infobox_centre">',
									'<button class="infobox_close">X</button>'].concat(html,
						   [	'</div>',
							'</div>',
							'<div class="infobox_bottom infobox_group">',
								'<div class="infobox_left"></div>',
								'<div class="infobox_right"></div>',
								'<div class="infobox_centre"></div>',
							'</div>',
							'<div class="infobox_connector"></div>',
						'</div>']);

				pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), {
					visible: false,
					htmlContent: html.join('')
				});
				infoboxLayer.push(pinInfobox);
		    
				pinLayer.push(pin); //add pushpin to pinLayer
		    
				Microsoft.Maps.Events.addHandler(pin, 'click', function (e) {

					pinInfobox.setOptions({
						visible: true,
						offset: new Microsoft.Maps.Point(-40, e.target.getHeight() + 40)
					});
					pinInfobox.setLocation(e.target.getLocation());

					var buffer = 25,
						
						infoboxOffset = pinInfobox.getOffset(),
						infoboxAnchor = pinInfobox.getAnchor(),
						infoboxLocation = Map.map.tryLocationToPixel(e.target.getLocation(), Microsoft.Maps.PixelReference.control),
						
						dx = infoboxLocation.x + infoboxOffset.x - infoboxAnchor.x,
						dy = infoboxLocation.y - 100 - infoboxAnchor.y;  // was 25

					if (Markers.pinInfobox !== null) {
						Markers.closeInfobox();
					}


					if (dy < buffer) {    //Infobox overlaps with top of map.
						//Offset in opposite direction.
						dy *= -1;
					
						//add buffer from the top edge of the map.
						dy += buffer;
					} else {
						//If dy is greater than zero than it does not overlap.
						dy = Map.map.getHeight() - infoboxLocation.y + infoboxAnchor.y - pinInfobox.getHeight();
						
						//If dx is greater than zero then it does not overlap.
						if (dy > buffer) {
							dy = 0;
						} else {
							//add a buffer from the right edge of the map.
							dy -= buffer;
						}

					}
					
					if (dx < buffer) {    //Check to see if overlapping with left side of map.
						//Offset in opposite direction.
						dx *= -1;
					
						//add a buffer from the left edge of the map.
						dx += buffer;
					} else {              //Check to see if overlapping with right side of map.
						dx = Map.map.getWidth() - infoboxLocation.x + infoboxAnchor.x - pinInfobox.getWidth();
						
						//If dx is greater than zero then it does not overlap.
						if (dx > buffer) {
							dx = 0;
						} else {
							//add a buffer from the right edge of the map.
							dx -= buffer;
						}
					}
					
					//Adjust the map so infobox is in view
					if (dx != 0 || dy != 0) {
						Map.map.setView({ centerOffset: new Microsoft.Maps.Point(dx, dy), center: Map.map.getCenter() });
					}
					
					
					Markers.pinInfobox = pinInfobox;
					_marker_details = record;
					_curr_postcode = record.PostalCode;
					
				});

				Map.map.entities.push(pinLayer);
				Map.map.entities.push(infoboxLayer);
				
				Microsoft.Maps.Events.addHandler(pinInfobox, 'click', function (e) {
					
					var jQtarget = $(getTarget(e));
					
					if (jQtarget.size()) {
						if (jQtarget.parents('a').size()) {
							jQtarget = jQtarget.parents('a');
						}

						if (jQtarget.is('a')) {
							
							target = jQtarget.get(0);
							
							if (jQtarget.hasClass('infobox_from')) {
								Directions.open.call(target, e);
							
							} else if (jQtarget.hasClass('route')) {
								Directions.find.call(target, e);
							
							} else if (jQtarget.hasClass('print')) {
								Print.load.call(target, e);
							
							} else if (jQtarget.hasClass('email')) {
								Email.load.call(target, e);
							}
							
						} else if (jQtarget.is('button')) {
							if (jQtarget.hasClass('infobox_close')) {
								Markers.closeInfobox();
							}
						}
					}

					
				});

				Microsoft.Maps.Events.addHandler(pinInfobox, 'keydown', function (e) {
					
					var jQtarget = $(getTarget(e));
					
					if (jQtarget.size()) {
						if (jQtarget.is('input') && jQtarget.parents('div.infobox_directions').size()) {
							Directions.find.call(jQtarget.get(0), e);
						}
					}
				
				});

				Markers.data.push(pin);
				
			},

			
			closeInfobox: function () {
				if (Markers.pinInfobox !== null) {
					Markers.pinInfobox.setOptions({visible:false});
					Markers.pinInfobox = null;
					_marker_details = null;
					_curr_postcode = null;
					dataI = -1;
				}
			},
			
			// Formats the pin's address and returns it as an array.
			formatAddress: function (pin) {

				var address = [],
					parts   = ['AddressLine', 'Street2', 'Street3', 'Locality',
							   'AdminDistrict', 'PostalCode', 'Telephone'],
					div     = '<div>|<\/div>',
					i       = 0,
					il      = parts.length;
				
				while (i < il) {
					if (pin.hasOwnProperty(parts[i]) && pin[parts[i]] !== '') {
						address.push(div.replace('|', pin[parts[i]]));
					}
					i += 1;
				}
				
				return address;
				
			}
			
		}

		var Location =
		{
			load: function()
			{
				var map_block = jQuery( '<div id="WTBMMap" class="wide"></div>' );

				// reload popup with map
				Epson.UI.Popup.clear();
				Epson.UI.Popup.populate( map_block );
				Epson.UI.Popup.dimension();
				Epson.UI.Popup.Loader.display();

				// detect if MultiMap has been loaded in
				if ( !MMFactory ) return Map.load( Location.load );

				// set up geo-search criteria
				var address = new MMAddress();
				address.qs = _location;
				//added if condition for Multimaps CR - Sandeep Myana -start
				if(_country_code=='GB' || _country_code=='BE'){
					
					address.country_code='';
				}
				else address.country_code = _country_code;
				//added if condition for Multimaps CR - Sandeep Myana -end
				// perform geo-search
				var geocoder = new MMGeocoder( function( result )
				{
					_point =  result[0].coords;

					Epson.UI.Popup.Loader.hide();

					// SET UP MULTIMAP API
					// set up map widgets
					_zoom_widget = new MMPanZoomWidget( new MMBox () ); 
					_zoom_widget.setContainer( jQuery( '#WTBMMap' )[0] );
		
					_view_widget = new MMMapTypeWidget ( undefined, new MMBox() );
					_view_widget.setContainer ( jQuery( '#WTBMMap' )[0] );
		
					_overview_widget = new MMOverviewWidget ( undefined, undefined, new MMBox () );
					_overview_widget.setContainer( jQuery( '#WTBMMap' )[0] );
		
					// set up map
					_map = MMFactory.createViewer( jQuery( '#WTBMMap' )[0] , MM_WORLD_MAP );
					_map.setMappingAPI( 'multimap' );
					_map.goToPosition( new MMLocation ( _point ) );
					_map.addWidget ( _zoom_widget );
		
					// zoom to bounds
			//		_map.goToPosition( ( _map.getAutoScaleLocation( bounds ) ) );
				} );
				geocoder.geocode( address );
			}
		}

		var Search =
		{
			data:null,
			page:0,
			query:'',
			counter:1,
			countryName:null,

			search: function(e)
			{
				var field = jQuery( '#WTBSearchField' ).length ? jQuery( '#WTBSearchField' ) : ( _search_field ? jQuery( _search_field ) : null );
				var value = field ? field.val() : ( Search.query ? Search.query : '' );

				if ( e ) e.preventDefault();

				if ( Validation.validator.validateForm() )
				{
					// display loader
					UI.Loader.display();

					// reset progrssive filtering
					_sku = true;
					_width_radius = true;

					Search.query = value;

					// reset pagination page
					Pagination.page = 0;

					// set up geo-search criteria

					Search.counter=1;
					setup();
					
					if(_country_code=="ES"){
						Search.countryName = "Spain"
					}
					else if(_country_code=="PT"){
						Search.countryName = "Portugal"
					}
					else if(_country_code=="IT"){
						Search.countryName = "Italy"
					}
					else if(_country_code=="FR"){
						Search.countryName = "France"
					}
					else if(_country_code=="GR"){
						Search.countryName = "Greece"
					}
					else if(_country_code=="TR"){
						Search.countryName = "Turkey"
					}
					else if(_country_code=="SL"){
						Search.countryName = "Slovenia"
					}
					else if(_country_code=="SK"){
						Search.countryName = "Slovakia"
					}
					else if(_country_code=="RS"){
						Search.countryName = "Serbia"
					}
					else if(_country_code=="RO"){
						Search.countryName = "Romania"
					}
					else if(_country_code=="LV"){
						Search.countryName = "Latvia"
					}
					else if(_country_code=="LT"){
						Search.countryName = "Lithuania"
					}
					else if(_country_code=="HU"){
						Search.countryName = "Hungary"
					}
					else if(_country_code=="HR"){
						Search.countryName = "Croatia"
					}
					else if(_country_code=="ZA"){
						Search.countryName = "South Africa"
					}
					
				    bingGeoCoding(Search);
					//Search.handleGeoResult(result,'');
				}
				dataI = -1;
			},

			geoSearch: function()
			{
				// display loader
				UI.Loader.display();

				start_index = ( Pagination.page * Consts.results_per_page );
				Search.counter = start_index+1;
				 bingGeoSearch(_point, start_index, Filters.data, _data_source);
			},

			handleGeoResult: function( data, error )
			{
				if ( data.resourceSets[0].resources && data.resourceSets[0].resources.length == 1 )
				{
					var result = data.resourceSets[0].resources[0];
		
					// save geo-search result centre-point
					_point = result.point.coordinates;
					
					// search based on predefined point
					Search.geoSearch();
				}
				else if ( data.resourceSets[0].resources && data.resourceSets[0].resources.length > 1 )
				{
					
					// if popup doesn't exist, load it
					if ( !jQuery( '#Popup' ).length ) UI.open();

					// if map doesn't exist, load if
					if ( !jQuery( '#WTBMMap' ).length )
					{
						var result_block = jQuery( '<div class="supportList genericRoundedCorners"><div class="top"><div class="tl"></div><div class="tr"></div><div class="t"></div></div><div class="content"><ul id="WTBResults" class="listOfCentres "></ul><div class="mapNavigation"><div id="WTBPagination" class="pagination"><a href="#" class="buttonPrevious">&nbsp;<span>' + Epson.Localisation.WhereToBuy.TXT010 + '</span></a></li><span class="numbering"></span><a href="#" class="buttonNext">&nbsp;<span>' + Epson.Localisation.WhereToBuy.TXT011 + '</span></a></div></div></div><div class="bottom"><div class="bl"></div><div class="br"></div><div class="b"></div></div></div>' );
						var map_block = jQuery( '<div class="mapSection "><div class="findStore"><p>' + Epson.Localisation.WhereToBuy.TXT001 + '</p><form id="WTBSearch" action="#" method="GET"><label for="WTBSearchField" class="fl_info">' + Epson.Localisation.WhereToBuy.TXT008 + '</label><input id="WTBSearchField" class="ft_text" type="text" name="" value="' + Search.query + '"/><button type="submit"><strong class="buttonBlue"><span>' + Epson.Localisation.WhereToBuy.TXT009 + '</span></strong></button><p class="postcodeExample">' + Epson.Localisation.WhereToBuy.TXT002 + '</p></form></div><div id="WTBMMap"></div></div>' );

						
		
						// reload popup with map
						Epson.UI.Popup.clear();
						Epson.UI.Popup.populate( result_block );
						Epson.UI.Popup.populate( map_block );
						Epson.UI.Popup.dimension();
						if ( !_search_field ) Epson.UI.Popup.addButton( '<<', UI.open );
		
						// bind search event
						jQuery( '#WTBSearch' ).bind( 'submit', Search.search );

						// set up validation
						Validation.setup();

						// set up form elements
						map_block.find( 'label.fl_info' ).each( Epson.Forms.InfoLabels.setup );

						// bind pagination events
						jQuery( '#WTBPagination a' ).bind( 'click', Pagination.paginate );

						Map.load();
					}

					// clear overlays
				//	_map.removeAllOverlays();
					if(Map.map!=null){
						Map.map.entities.clear();
					}
					// reset data
					Search.data = [];
		
					// reset markers
					Markers.data = [];
		
					// clear results
					jQuery( '#WTBResults li' ).remove();
					
					// iterate through possible locations and populate result pane
					var index=1;
					jQuery.each( data.resourceSets[0].resources, function(i)
					{
						//added if condition for Multimaps CR - Sandeep Myana -start
						if(_country_code=='GB'){
							if(this.address.countryRegion.match('United Kingdom') || this.address.countryRegion.match('Ireland')){
							var addresses = this.address.formattedAddress.split( ',' );
							var results = jQuery( '<li><a href="#" class="marker blueMarker"><span>' + index + '</span></a><div class="centreDetails"><h4><a href="#">' + addresses[0] + '</a></h4></div></li>' );
							index++;
							addresses.shift();
							jQuery.each( addresses, function()
							{
						
								results.find( '.centreDetails' ).append( jQuery( '<div>' + this + '</div>' ) );
							} );

							// bind jump to event to links
							var coords = this.point.coordinates;
							results.find( 'a' ).bind( 'click', function(e) { _point = coords; Search.geoSearch(); e.preventDefault(); } );
		
							// add into list
							jQuery( '#WTBResults' ).append( results );}
							
							} else if(_country_code=='BE'){
								if(this.address.countryRegion.match('Belgium') || this.address.countryRegion.match('Luxembourg')){
								var addresses = this.address.formattedAddress.split( ',' );
								var results = jQuery( '<li><a href="#" class="marker blueMarker"><span>' + index + '</span></a><div class="centreDetails"><h4><a href="#">' + addresses[0] + '</a></h4></div></li>' );
								index++;
								addresses.shift();
								jQuery.each( addresses, function()
								{
							
									results.find( '.centreDetails' ).append( jQuery( '<div>' + this + '</div>' ) );
								} );
		
								// bind jump to event to links
								var coords = this.coords;
								results.find( 'a' ).bind( 'click', function(e) { _point = coords; Search.geoSearch(); e.preventDefault(); } );
			
								// add into list
								jQuery( '#WTBResults' ).append( results );}
								
							}else {
								var addresses = this.address.formattedAddress.split( ',' );
								//alert(typeof(addresses));//
								var results = jQuery( '<li><a href="#" class="marker blueMarker"><span>' + index + '</span></a><div class="centreDetails"><h4><a href="#">' + addresses[0] + '</a></h4></div></li>' );
								index++;
								addresses.shift();
								jQuery.each( addresses, function()
								{
							
									results.find( '.centreDetails' ).append( jQuery( '<div>' + this + '</div>' ) );
								} );

								// bind jump to event to links
								var coords = this.point.coordinates;
								results.find( 'a' ).bind( 'click', function(e) { _point = coords; Search.geoSearch(); e.preventDefault(); } );
		
								// add into list
								jQuery( '#WTBResults' ).append( results );
						
						}
						if(index==1){
							if ( !jQuery( '#Popup' ).length ) UI.open();

							Epson.UI.Popup.load( _error_url, function()
							{
								// bind search event
								jQuery( '#WTBSearch' ).bind( 'submit', Search.search );
								jQuery( '#WTBSearchField' ).val( Search.query );

								// set up validation
								Validation.setup();

								// set up form elements
								jQuery( '#Popup label.fl_info' ).each( Epson.Forms.InfoLabels.setup );

								Epson.UI.Popup.dimension();
							} );

							Epson.UI.Popup.addButton( '<<', UI.open );

							// remove loader
							UI.Loader.hide();
					}
					//added if condition for Multimaps CR - Sandeep Myana -end
					} );

					// hide pagination
					UI.ResultsPane.hidePagination();

					// remove loader
					UI.Loader.hide();
				}
				else
				{
					// if popup doesn't exist, load it
					if ( !jQuery( '#Popup' ).length ) UI.open();

					Epson.UI.Popup.load( _error_url, function()
					{
						// bind search event
						jQuery( '#WTBSearch' ).bind( 'submit', Search.search );
						jQuery( '#WTBSearchField' ).val( Search.query );

						// set up validation
						Validation.setup();

						// set up form elements
						jQuery( '#Popup label.fl_info' ).each( Epson.Forms.InfoLabels.setup );

						Epson.UI.Popup.dimension();
					} );

					Epson.UI.Popup.addButton( '<<', UI.open );

					// remove loader
					UI.Loader.hide();
				}
				
			},

			handleSearchResult: function(data,error)
			{
				//var bounds = new MMBounds();

				if ( data.d.results.length > 0 )
				{
					// save the query in a cookie
					Epson.Cookies.write( 'postcode', Search.query );

					// save record count for pagination
					_records = data.d.__count;

					// if popup doesn't exist, load it
					if ( !jQuery( '#Popup' ).length ) UI.open();

					// if map doesn't exist, load if
					if ( !jQuery( '#WTBMMap' ).length )
					{
						var result_block = jQuery( '<div class="supportList genericRoundedCorners"><div class="top"><div class="tl"></div><div class="tr"></div><div class="t"></div></div><div class="content"><ul id="WTBResults" class="listOfCentres "></ul><div class="mapNavigation"><div id="WTBPagination" class="pagination"><a href="#" class="buttonPrevious">&nbsp;<span>' + Epson.Localisation.WhereToBuy.TXT010 + '</span></a></li><span class="numbering"></span><a href="#" class="buttonNext">&nbsp;<span>' + Epson.Localisation.WhereToBuy.TXT011 + '</span></a></div></div></div><div class="bottom"><div class="bl"></div><div class="br"></div><div class="b"></div></div></div>' );
						var map_block = jQuery( '<div class="mapSection "><div class="findStore"><p>' + Epson.Localisation.WhereToBuy.TXT001 + '</p><form id="WTBSearch" action="#" method="GET"><label for="WTBSearchField" class="fl_info">' + Epson.Localisation.WhereToBuy.TXT008 + '</label><input id="WTBSearchField" class="ft_text" type="text" name="" value="' + Search.query + '"/><button type="submit"><strong class="buttonBlue"><span>' + Epson.Localisation.WhereToBuy.TXT009 + '</span></strong></button><p class="postcodeExample">' + Epson.Localisation.WhereToBuy.TXT002 + '</p></form></div><div id="WTBMMap"></div></div>' );
		
						// reload popup with map
						Epson.UI.Popup.clear();
						Epson.UI.Popup.populate( result_block );
						Epson.UI.Popup.populate( map_block );
						Epson.UI.Popup.dimension();
						if ( !_search_field ) Epson.UI.Popup.addButton( '<<', UI.open );

						// bind search event
						jQuery( '#WTBSearch' ).bind( 'submit', Search.search );

						// set up validation
						Validation.setup();

						// set up form elements
						map_block.find( 'label.fl_info' ).each( Epson.Forms.InfoLabels.setup );

						// bind pagination events
						jQuery( '#WTBPagination a' ).bind( 'click', Pagination.paginate );


						
					}
		
					// clear overlays
					//_map.removeAllOverlays();
					if(Map.map!=null && Markers.data.length>0){
						Map.map.entities.clear();
					}
					Map.load();
					 Map.map.setView({ center: new Microsoft.Maps.Location(_point[0], _point[1]), zoom: 9});	
					// reset data
					Search.data = [];
		
					// reset markers
					Markers.data = [];
		
					// clear results
					jQuery( '#WTBResults li' ).remove();
		
					// iterate through resultset
					if ( data.d.__count > 0 && data.d.results && data.d.results.length > 0 )
					{
						jQuery.each( data.d.results, function()
						{
							if(isUndefined(this.counter)){
								this.counter = Search.counter;
								Search.counter++;
							} 
							// save data
							Search.data.push( this );

							// create a marker on the map for each record
							Markers.create( this );
							
						} );
					}
		
					// zoom to bounds
					//_map.goToPosition( ( _map.getAutoScaleLocation( bounds ) ) );
		
					// display results in pane
					UI.ResultsPane.populate();
					UI.ResultsPane.updatePagination();
		
					// remove loader
					UI.Loader.hide();
				}

				else
				{
					// if popup doesn't exist, load it
					if ( !jQuery( '#Popup' ).length ) UI.open();

					Epson.UI.Popup.load( _error_url, function()
					{
						// bind search event
						jQuery( '#WTBSearch' ).bind( 'submit', Search.search );
						jQuery( '#WTBSearchField' ).val( Search.query );

						// set up validation
						Validation.setup();

						// set up form elements
						jQuery( '#Popup label.fl_info' ).each( Epson.Forms.InfoLabels.setup );

						Epson.UI.Popup.dimension();
					} );

					Epson.UI.Popup.addButton( '<<', UI.open );

					// remove loader
					UI.Loader.hide();
				}
			}
		}

		var Filters =
		{
			data:null,

			setup: function()
			{
				jQuery( _filters ).each( function()
				{
					var filter = this.match( /^([^\+]+)/ );
					var operator = this.match( /\+([^\+]+)\+/ );
					var value = this.match( /([^\+]+)$/ );

					if ( filter && operator && value )
					{
						// Epson SKU logic
						if ( filter[1] == 'sku' ) _sku = true;

						Filters.data=filter[1]+" "+ operator[1]+" '"+ value[1]+"'";
					}
				} );
			},

			resetWithoutSKU: function()
			{
				_sku = false;
				Filters.data = null;

				jQuery( _filters ).each( function()
				{
					var filter = this.match( /^([^\+]+)/ );
					var operator = this.match( /\+([^\+]+)\+/ );
					var value = this.match( /([^\+]+)$/ );

					// Epson SKU logic
					if ( filter && filter[1] != 'sku' && operator && value ) Filters.data=filter[1]+" "+ operator[1]+" '"+value[1]+"'"; 
			} );
		}
	}

	var Pagination =
	{
		page:0,

		paginate: function(e)
		{
			if ( this.className.match( /next/i ) ) Pagination.page++;
			else if ( this.className.match( /previous/i ) ) Pagination.page--;
			
			dataI = -1;

			Search.geoSearch();

			e.preventDefault();
		}
	}

	var Directions = 
	{
		
		route:null,

		open: function(e)
		{

			var jQinfobox = $(this).parents('div.infobox');
			
			$('div.infobox_directions a', jQinfobox).hide();
			$('label, input, a.route', jQinfobox).show();
			$('input', jQinfobox).focus().val(Search.query);

			stopDefault(e);
		},
		
		find: function(e)
		{
			if ( ( e.keyCode && e.keyCode == 13 ) || !e.keyCode )
			{
				var jQinfobox = $(this).parents('div.infobox'),
					_directions_from = escape($('input', jQinfobox).val()),
					_directions_to = _curr_postcode === null ? escape(Search.query) : escape(_curr_postcode),
					url = _directions_url + '?qs_1=' + _directions_from
						+ '&countryCode_1=' +  _country_code + '&qs_2=' + _directions_to
						+ '&displayName_2=' + _directions_to + '&countryCode_2=' + _country_code
						+ '&mode=driving&optimizeFor=time&mapData=917',
					w, h;
				
				//open in full screen
				if (jQuery.browser.msie) { w = screen.availWidth; h = screen.availHeight; }
				else { w = window.innerWidth; h = window.innerHeight; }
				
				if ( _directions_from != _directions_to ) {
					window.open( url, 'map', 'width=' + w +', height=' + h + ', left=0, top=0, menubar=yes, resizable=yes, toolbar=yes, statusbar=yes, scrollbars=yes' );
				}
					
				stopDefault(e);
				//e.preventDefault();
			}
		}		
	}

	var Print =
	{
		load: function(e)
		{

			var curr_marker = [],
				elems = ['store_name', 'AddressLine', 'street2', 'street3', 'PostalCode', 'telephone',
						 'fax', 'website', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
						 'saturday', 'sunday'],
				i = 0,
				il = elems.length,
				value;
			
			// Add the data to curr_marker and preserve the order, even if there is no information.
			while (i < il) {
				value = '';
				if (_marker_details.hasOwnProperty(elems[i])) {
					value = _marker_details[elems[i]];
				}
				curr_marker.push(value);
				i += 1;
			}
			
			Epson.Cookies.write('Store',curr_marker);

			
			var url = _print_url + '?' + '&loc_lat=' + _marker_details.Latitude + '&loc_lon=' + _marker_details.Longitude + '&zoomFactor=' + ( parseInt(Map.map.getZoom(), 10)  ) ;

			var w, h;
			if (jQuery.browser.msie) { w = screen.availWidth; h = screen.availHeight; }
			else { w = window.innerWidth; h = window.innerHeight; }
			window.open( url, 'map', 'width=' + w +', height=' + h + ', left=0, top=0, menubar=yes, resizable=yes, toolbar=yes, statusbar=yes, scrollbars=yes' );
			
			stopDefault(e);
			
			dataI = -1;
		}
	}

	var Email =
	{
		load: function(e)
		{
			var url = (_email_url.match( /\?/ ) ? '&' : '?') + 'link='
				+ escape(_email + '?' + '&id=' + _marker_details.EntityID + '&zoomFactor='
					+ (parseInt(Map.map.getZoom(), 10)) + '&prodid=' + _prod_id);

			Epson.UI.Popup.load(_email_url + url , Email.setup);

			stopDefault(e);

			dataI = -1;

		},

		setup: function()
		{
			Epson.Email.setup();

			Epson.UI.Popup.element.find( '.headerContent .backButton a' ).unbind( 'click' ).bind( 'click', function() { jQuery( this ).unbind( 'click' ).bind( 'click', UI.open ); Search.search() } );

			Epson.UI.Popup.dimension( Epson.UI.Popup.undimension );
		}
	}

	var Validation =
	{
		validator:null,

		setup: function()
		{
			var id = _search_field ? _search_field.id : 'WTBSearchField';
			Validation.validator = new jQuery.validation( { form:_form, auto:false, event:'change', error:Epson.Forms.displayError } );
			Validation.validator.validate( {id:id, type:'is_string', error_message:Epson.Localisation.WhereToBuy.TXT012, required:true } );
		}
	}

	var UI =
	{
		open: function(e)
		{
			// display popup
			Epson.UI.Popup.open( _product_name );

			// remove back button if there was one
			Epson.UI.Popup.removeButton();

			// call ajax to load in content
			if ( !_search_field ) Epson.UI.Popup.load( _product_url, UI.setup );

			if (e) e.preventDefault();
			
			dataI = -1;
		},

		openMap: function(e)
		{
			// display popup
			Epson.UI.Popup.open( _location_title );

			Location.load();

			if (e) e.preventDefault();
		},

		setup: function()
		{
			Epson.UI.Popup.dimension();

			// bind search event to field search
			jQuery( '#WTBSearch' ).bind( 'submit', Search.search );

			// pre-popuplate the search field if a value was stored
			var saved_query = Epson.Cookies.read( 'postcode' );
			if ( saved_query && jQuery( '#WTBSearchField' ).val() == '' ) jQuery( '#WTBSearchField' ).val( saved_query );

			// set up validation
			Validation.setup();

			// set up form elements
			jQuery( '#Popup label.fl_info' ).each( Epson.Forms.InfoLabels.setup );
		},

		ResultsPane:
		{
			populate: function()
			{
				jQuery.each( Search.data, function(i)
				{
					/*var special_store = this.store_type && Epson.StoreMapping.store_types[ this.store_type.toString().toLowerCase() ] ? '<img src="' + Epson.StoreMapping.store_types[ this.store_type.toString().toLowerCase() ] + '" />' : '';*/
					var special_store = this.image ? '<img src="' + Epson.StoreMapping.image.path.toString().toLowerCase() + this.image + '" />' : '';
					var marker_style = this.partner_status && Epson.StoreMapping.partner_statuses[ this.partner_status.toString().toLowerCase() ] ? 'background-image:url(' + Epson.StoreMapping.partner_statuses[ this.partner_status.toString().toLowerCase() ] + ')' : '';
					var results = jQuery( '<li><a href="#" class="marker blueMarker" style="' + marker_style + '"><span>' + this.counter + '</span></a><div class="centreDetails">' + special_store + '<h4><a href="#">' + this.store_name + '</a></h4><div>' + this.street2 + '</div><div>' + this.street3 + '</div><div>' + this.Locality + '</div><div>' + this.PostalCode + '</div></div></li>' );

					// bind jump to event to links
					results.find('a').click(function(e) {
						
						if (dataI !== i) {
							// I have to provide the event argument!? Shouldn't an event invokation do that automatically?
							Microsoft.Maps.Events.invoke(Markers.data[i], 'click', {
								originalEvent: e,
								target: Markers.data[i]
							});
							dataI = i;
						}
						e.preventDefault();
					});
	
					// add into list
					jQuery( '#WTBResults' ).append( results );
				} );
			},

			updatePagination: function()
			{
				jQuery( '#WTBPagination' ).css( { display:'' } );

				// hide buttons if necessary
				var visibility = ( Pagination.page == 0 ) ? { visibility:'hidden' } : { visibility:'visible' };
				jQuery( '#WTBPagination a.buttonPrevious' ).css( visibility );
				var visibility = ( Pagination.page >= Consts.max_pages || Search.data.length < Consts.results_per_page || ( ( Pagination.page + 1 ) * Consts.results_per_page ) >= _records ) ? { visibility:'hidden' } : { visibility:'visible' };
				jQuery( '#WTBPagination a.buttonNext' ).css( visibility );

				// update text
				jQuery( '#WTBPagination span' ).text( ( ( Pagination.page * Consts.results_per_page ) + 1 ) + ' - ' + ( ( Pagination.page * Consts.results_per_page ) + Search.data.length ) );
			},

			hidePagination: function()
			{
				jQuery( '#WTBPagination' ).css( { display:'none' } );
			}
		},

		Loader:
		{
			display: function()
			{
				if ( !jQuery( '#WTBLoader' ).length )
				{
					var field = jQuery( '#WTBSearchField' ).length ? jQuery( '#WTBSearchField' ) : ( _search_field ? jQuery( _search_field ) : null );

					if ( field )
					{
						var width = field.width();
						var offset = field.offset();

						jQuery( '#Container' ).append( jQuery( '<div id="WTBLoader" class="loader"></div>' ).css( { position:'absolute', top:offset.top+6+'px', left:offset.left+width-10+'px' } ) );
					}
				}
			},
	
			hide: function()
			{
				jQuery( '#Container .loader' ).remove();
			}
		}
	}

	$(function () {
		$('.whereToBuy').click(function () {
			dataI = -1;
		});
	});

	setup();
}

var searchObj;
function bingGeoCoding(Object){
	searchObj = Object;
        if(searchObj.countryName!=null){ 
		var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"+searchObj.countryName+"/"+searchObj.query+"?output=json&jsonp=GeocodeCallback&key=AmqoIN12wAG8HhElyEz8f_7zQNER1T8XfNYjsvfsmJTMmrXDJUMrTYujjHGGuxew";
	}
	else{
		var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"+searchObj.query+"?output=json&jsonp=GeocodeCallback&key=AmqoIN12wAG8HhElyEz8f_7zQNER1T8XfNYjsvfsmJTMmrXDJUMrTYujjHGGuxew";
	}	
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", geocodeRequest);
	document.body.appendChild(script);
}

function GeocodeCallback(result) {
	searchObj.handleGeoResult(result, '');
}
function bingGeoSearch(point, start_index, filterData, _data_source){
	var centerPoint = new Microsoft.Maps.Location(point[0], point[1]);
	var radius = 30; 
        var requestUrl="";
        if(filterData.search("contains")!= -1){
        	requestUrl = "http://spatial.virtualearth.net/REST/v1/" +
        	"data/"+_data_source+"/Store?$format=json&jsonp=GeoSearchCallback&spatialFilter=nearby(" +
        	centerPoint.latitude + "," +centerPoint.longitude +"," + radius + ")" +
        	"&$inlinecount=allpages&$skip="+start_index+"&$top=10&key=AmqoIN12wAG8HhElyEz8f_7zQNER1T8XfNYjsvfsmJTMmrXDJUMrTYujjHGGuxew";
        }
        else{
		requestUrl = "http://spatial.virtualearth.net/REST/v1/" +
		"data/"+_data_source+"/Store?$format=json&jsonp=GeoSearchCallback&spatialFilter=nearby(" +
		centerPoint.latitude + "," +centerPoint.longitude +"," + radius + ")" +"&$filter="+filterData+
		"&$inlinecount=allpages&$skip="+start_index+"&$top=10&key=AmqoIN12wAG8HhElyEz8f_7zQNER1T8XfNYjsvfsmJTMmrXDJUMrTYujjHGGuxew";
	}
	sendRequest(requestUrl);
}
function sendRequest(requestUrl) {
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", requestUrl);
	document.body.appendChild(script);
}
function GeoSearchCallback(result) {
    searchObj.handleSearchResult(result, '');
}
function isUndefined(ref) {
	return typeof ref === "undefined";
}

function closeInfobox(data){
    data.pinInfobox.setOptions({visible:false});
}

