var slider_id;
var rb = new Resource({ 	CONFIG_LIST:['store_locator'],LIMIT:['not_compatible','need_more_criteria','need_more_criteria_nozip','no_criteria','search_error','no_results','email_required','first_name_required', 'zip_required', 'driving_search_error']
	});
 		
document.observe('dom:loaded', function () { 
	storeLocator.init();
	if (slider_id) {
		setTimeout("onloadShowSlider(slider_id)", 3000); }
});
	
var storeLocator = { 
    maxResults : 26,
    init : function() {   
  	//stop default form submission
  	$$(".no-submit").each(function($_) {  
  	     $_.onsubmit = function (){   
        	         $_.select(".submit")[0].triggerEvent('click'); 
  	         return false;
  	     } 
	});  
    
    	//create contextual dropdowns
    	if (locationsUS) { 	 
    		this.createFilter(
    			$('locator-search-us').select(".state")[0],
    			$('locator-search-us').select(".city")[0],
    			locationsUS.states,"cities"
    		); 
    		$('locator-search-us').searchPrefs = {ifMapResults:true}; 
    	}
	if (locationsIntl) {
		this.createFilter(
			$('locator-search-intl').select(".country")[0],
			$('locator-search-intl').select(".city")[0],
			locationsIntl.countries,"cities"
		);  
	}
	
	//custom look selects for bobbi
	$('locator-search-us').select(".state")[0].addClassName("replaceselect");
    	$('locator-search-us').select(".city")[0].addClassName("replaceselect");
    	$('locator-search-intl').select(".country")[0].addClassName("replaceselect");
	$('locator-search-intl').select(".city")[0].addClassName("replaceselect");
	$('locator-search-us').select(".perimeter")[0].addClassName("replaceselect");
	bb.page.replaceSelects(); 
	
	/**US - clear zip if state and vice-versa
	this.localSelected = false; 
    	$('locator-search-us').select("select.city")[0].observe("change",function(){ 
    		if (storeLocator.localSelected) { //zip was entered
    			storeLocator.localSelected = false; 
    		}  else {
    			console.log("select city"); 
    			storeLocator.localSelected = true;
    			$('locator-search-us').select(".zip")[0].value = "";  
    		}
    	});    	
    	$('locator-search-us').select(".zip")[0].observe("blur",function(){  
    		if (storeLocator.localSelected) { //city was entered
    			storeLocator.localSelected = false; 
    		}  else { 
    			console.log("select zip");
    			storeLocator.localSelected = true;
    			$('locator-search-us').select("select.state")[0].selectedIndex = 0; 
    			$('locator-search-us').select("select.city")[0].selectedIndex = 0; 
    		          selectMe('',0,0,true);
    		          selectMe('',0,1,true);  
    		}
    	});**/  
	
	//btns 
	$$(".show-search").each(function($_) { $_.observe("click",storeLocator.showLocationsSearch); });  
	$$(".find-stores").each(function($_) {
		$_.frm = $_.getAncestor("FORM");  
		var eObj = $_.frm.select(".error");
      		$_.eObj = (eObj.length>0) ? eObj[0] : false; 
      	          $_.frm.domestic = true;
      		$_.frm.mapLocations = true;
      		$_.observe("click", storeLocator.findLocations); 
	}); 
	$$("#locator-search-intl .find-stores").each(function($_) { 
		$_.frm.domestic = false;
      		$_.frm.mapLocations = false; 
	}); 
	
 	$$(".find-directions").each(function($_) { $_.observe("click", storeLocator.findDirections)});  
 	//$$(".show-map").each(function($_) { $_.observe("click",storeLocator.showLocationsMap);  });  
 	
 	//html objs
 	this.htmlObjs = {};
 	this.htmlObjs.wrapper = $$('.store-finder-body')[0]; 
 	this.htmlObjs.locations = {};
 	this.htmlObjs.locations.map = $('map'); 
 	this.htmlObjs.locations.count = $$('#show_map .count')[0];   
 	this.htmlObjs.locations.list =  $('event-body');
 	this.htmlObjs.directions = {};
 	this.htmlObjs.directions.address = $('show_address');
 	this.htmlObjs.directions.map = $('driving_map');  
 	this.htmlObjs.directions.route =  $('route');   
 	this.htmlObjs.directions.error =  $$('#driving-form .error')[0];    
    },
    
    createFilter : function(parentSelect, childSelect, dataObj, childType) {  
    	var filter = {
parentSelect:parentSelect,childSelect:childSelect,dataObj:dataObj,childType:childType,filterCities:storeLocator.filterCities}; 
    	parentSelect.filter = filter;  
    	$H(dataObj).each(function(pair) {  
  		parentSelect.insert('<option value="'+pair.key+'">' + pair.key + '</option>');
	});
	parentSelect.selectedIndex = 0; 
    	parentSelect.observe("change",parentSelect.filter.filterCities);  
    }, 
    filterCities : function() { 
    	var childSelect = this.filter.childSelect;
    	var initial = childSelect.select("option")[0];
    	var parentType = this.options[this.options.selectedIndex].value;
    	try { //change event other than user selecting parent dropdown
    		var kids = this.filter.dataObj[parentType][this.filter.childType];
    	} catch(e) {
    		return;
    	}
    	childSelect.select("option").each(function($_){$_.remove()});
    	childSelect.insert(initial);
    	kids.each(function($_) {  
  		childSelect.insert('<option value="'+$_+'">' + $_ + '</option>');
	});
	childSelect.selectedIndex = (kids.length>1) ? 0 : 1; 
	updateOptions(childSelect, childSelect.selectedIndex);
    },
    
    showLocationsMap: function(){
	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-directions-results");
	}, 
    showLocationsSearch: function(){
    	storeLocator.htmlObjs.wrapper.removeClassName('locator-view-directions-search');  
    	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-directions-results");     
	},
    showDirectionsSearch: function(lat,lon,fulladdress,city,state,zip){ 
    		storeLocator.htmlObjs.wrapper.scrollTo();
    		var address = storeLocator.scrubAddress(fulladdress);
		$('DESTINATION_ADDRESS').value=address;
		$('DESTINATION_CITY').value=city;
		$('DESTINATION_STATE').value=state;
		$('DESTINATION_ZIP').value=zip;
		var address_display = address + '<br/>' + city + ', ' + state + ' ' + zip;
		storeLocator.htmlObjs.directions.address.update(address_display);
		storeLocator.htmlObjs.wrapper.removeClassName("locator-view-directions-results");     
		storeLocator.htmlObjs.wrapper.addClassName("locator-view-directions-search");  
    },
    
    showErrors : function(obj, msg) { 
    	if (!obj) return;   
	obj.select('li').each(function(elm){elm.remove()});	
	obj.insert('<li>' + msg + '</li>');
	obj.show(); 
    },
    hideErrors : function(error) { 
	$$('.error').invoke('hide');
    },
    scrubAddress: function(fulladdress) {
    	return (fulladdress.indexOf("<br>")>-1) ? fulladdress.substring(0,fulladdress.indexOf("<br>")) : fulladdress; 
    },
    
    findLocations: function() {     
    	var frm = this.frm;
      	if (!valid('select.city') && !valid('.zip')) {  	
      		var e = (frm.select('.zip').length>0)? 'need_more_criteria' : 'need_more_criteria_nozip';
      		storeLocator.showErrors(this.eObj, rb.keys.get(e)); 
		return;
      	} 
      	storeLocator.hideErrors(); 
      	
      	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-maps");
      	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-list");
	storeLocator.htmlObjs.wrapper.addClassName("locator-view-locations-loading");
	storeLocator.htmlObjs.locations.list.update('');
	storeLocator.htmlObjs.locations.count.update('');
	
	var params = [{"ARGS" : {
			"MAXRESULTS" : storeLocator.maxResults, 
			"CITY" : this.frm.select('select.city')[0].getValue()
			}}]
	
          if (frm.select("select.country").length>0) params[0].ARGS["COUNTRY"] = this.frm.select('select.country')[0].getValue();
	if (frm.select(".zip").length>0) params[0].ARGS["ZIP"] = this.frm.select('.zip')[0].getValue(); 
	if (frm.select("select.state").length>0) params[0].ARGS["STATE"] = this.frm.select('select.state')[0].getValue(); 
	if (frm.select("select.perimeter").length>0) params[0].ARGS["RADIUS"] = this.frm.select('select.perimeter')[0].getValue();  
  
	var gBrowser = GBrowserIsCompatible(); 
	var showLocations = (frm.mapLocations && gBrowser) ? storeLocator.mapLocations : storeLocator.listLocations; 
	var rpc = (frm.domestic) ? 'storelocator.results' : 'storelocator.intl-results';
 	
	var id = jsonrpc.fetch(
		rpc, 
		params,
		{ 	onSuccess: showLocations.bind(this),
			onFailure: function () {
				console.log('Store Locator JSON failed to load '); 	  
			storeLocator.showErrors(this.eObj,rb.keys.get('search_error')).bind(this);
			}
		}
	);
	
	function valid(prop) {
	   var prop = frm.select(prop); 
	   if (prop.length==0) return false;
	   prop = prop[0]; 
	   var propValue = prop.getValue();
	   if (propValue == "") return false; //not selected 
	   if (prop.hasClassName("zip")&&propValue.match(/\D/g)) return false; //invalid
	   return true;
	}
    }, 
     
    mapLocations: function(id) {    
          storeLocator.htmlObjs.locations.list.fire("showLocations:results", {}); //reporting
            
	var response = id.responseText.evalJSON(true)[0];
	
	var error = response.error;
	if (error) {  
		console.log("showLocations e: "+ error);
		storeLocator.showErrors(this.eObj, rb.keys.get('no_results'));
		storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-loading"); 
		return;
	}
	 
	var data = $H(response.result);   
	var c_lat = data.get('latitude');
	var c_lon = data.get('longitude'); 
	var doors = data.get('results');
	
	if (doors.length==0) {
		console.log("showLocations count e");
		storeLocator.showErrors(this.eObj, rb.keys.get('no_results'));
		return;
	}   		
		
	var map = new GMap2(storeLocator.htmlObjs.locations.map);
	var axis = new GLatLng(c_lat, c_lon);
	map.setCenter(axis, 10); 
	var bounds = new GLatLngBounds();
	
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
	function createMarker(latlng, id, letter, info) { 
		var letteredIcon = new GIcon(baseIcon);
		letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png"; 
		markerOptions = { icon:letteredIcon };
		var marker = new GMarker(latlng, markerOptions);
		marker.value = id;
		GEvent.addListener(marker,"click", function() {
			map.openInfoWindowHtml(latlng, info);
			});
		return marker;
		}
		 
	doors.each( function (door, idx) {  
		var lat = door.lat;
		var lon = door.lon;
		var letter = String.fromCharCode("A".charCodeAt(0) + idx); 
		door.letter = letter;
		
		var point = new GLatLng(lat, lon);
		bounds.extend(point); 
		var info = "<b>" + door.DOOR_NAME + "</b><br><br>" + storeLocator.scrubAddress(door.ADDRESS) + "<br>" + door.CITY + ", " + door.STATE + " " + door.ZIP;
		
	 	var themark=createMarker(point, door.DOOR_ID, letter, info);
		map.addOverlay(themark); 
			
		if (idx == 0) {  
			map.openInfoWindowHtml(point, info);
		} 
						
		try {
			templatefactory.get('store-locator-result-row').evaluateCallback({
				object: door,
				callback: function(html) { 
					storeLocator.htmlObjs.locations.list.insert(html);
					var loclinkid = $("door_" + door.DOOR_ID);
					var maplinkid = $("maplink_" + door.DOOR_ID);
					loclinkid.observe('click', function(evt) {
						console.log("clicked door_" + door.DOOR_ID);
				        storeLocator.showDirectionsSearch(door.lat,door.lon,door.ADDRESS,door.CITY,door.STATE,door.ZIP);
						GEvent.trigger(themark, 'click');
						}); 
			//		GEvent.addDomListener(loclinkid,"click", function() {GEvent.trigger(themark, 'click');});
			//		GEvent.addDomListener(maplinkid,"click", function() {GEvent.trigger(themark, 'click');});
					}
					
			 });
		 } catch(e) {	
		    //alert(e.description);
		 } 
		 
	}); //doors.each
			 
			 
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter()); 
	map.addControl(new GSmallMapControl());
	//map.addControl(new GMapTypeControl());
	
	storeLocator.htmlObjs.locations.count.update(doors.length);
	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-loading");
	storeLocator.htmlObjs.wrapper.addClassName("locator-view-locations-maps"); 
    },
    
    listLocations: function(id) {   
   	storeLocator.htmlObjs.locations.list.fire("showLocations:results", {}); //reporting
            
	var response = id.responseText.evalJSON(true)[0];
	
	var error = response.error;
	if (error) {  
		console.log("showLocations e: "+ error);
		storeLocator.showErrors(this.eObj, rb.keys.get('no_results'));
		storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-loading"); 
		return;
	}
	 
    	var data = $H(response.result);     
	var doors = data.get('results'); 
 
	if (doors.length==0) {
		console.log("showLocations count e");
		storeLocator.showErrors(this.eObj, rb.keys.get('no_results'));
		return;
	}   		
 
	doors.each( function (door, idx) {   
		var letter = String.fromCharCode("A".charCodeAt(0) + idx); 
		door.letter = letter;
		
		try {
			templatefactory.get('store-locator-result-row').evaluateCallback({
				object: door,
				callback: function(html) { 
					storeLocator.htmlObjs.locations.list.insert(html); 
					}
					
			 });
		 } catch(e) {	
		     //alert(e.description);
		 } 
		 
	}); //doors.each 
	
	storeLocator.htmlObjs.locations.count.update(doors.length);
	storeLocator.htmlObjs.wrapper.removeClassName("locator-view-locations-loading");
	storeLocator.htmlObjs.wrapper.addClassName("locator-view-locations-list"); 
    },
    
    findDirections: function() {
       	if (!GBrowserIsCompatible()) { 
		alert(rb.keys.get('not_compatible')); 
		return;
    	} 
    	
    	if ($F('ORIGIN_ADDRESS')==""||$F('ORIGIN_CITY')==""||$F('ORIGIN_STATE')== ""){   
      		storeLocator.showErrors(storeLocator.htmlObjs.directions.error, rb.keys.get('no_criteria'));
		return;
      	} 
     
	storeLocator.hideErrors();	 
	storeLocator.htmlObjs.directions.route.update('');   
	storeLocator.htmlObjs.wrapper.addClassName('locator-view-directions-results');   
	
	var address = $F('ORIGIN_ADDRESS');
	var city = $F('ORIGIN_CITY');
	var state = $F('ORIGIN_STATE');
	var address2 = $F('DESTINATION_ADDRESS');
	var city2 = $F('DESTINATION_CITY');
	var state2 = $F('DESTINATION_STATE');
	var zip2 = $F('DESTINATION_ZIP');
	
	var map = new GMap2(storeLocator.htmlObjs.directions.map); 
          var directions = new GDirections(map, storeLocator.htmlObjs.directions.route); 
	directions.load("from: " + address + ", " + city + ", " + state + " to: " + address2 + ", " + city2 + ", " + state2 + " " + zip2);  
          
          GEvent.addListener(directions, "error", function() {
		console.log(directions.getStatus().code + " " + directions.getStatus().request);	
		storeLocator.htmlObjs.wrapper.removeClassName('locator-view-directions-results');   
		storeLocator.showErrors(storeLocator.htmlObjs.directions.error, rb.keys.get('driving_search_error'));
	}); 
 
    }
}	 

/** from clinique, just in case ie6 needs it 
function fieldChange(field,thing){
	$(field).value=thing;
	console.log("IE hack: " + field + "=" + thing);
	}
**/

 
//-------reporting
document.observe("showLocations:results", function(event) { 
   $('reporting-img').src = "http://s0b.bluestreak.com/ix.e?bb&t=37365";
});

  
//--------extend prototype
var extendElement = {
    getAncestor: function(element, s){
       	var ancestors = element.ancestors();
		var type = "tagName";
		if (s.substring(0,1)==".") {
			type = "className";
			s = s.substring(1,s.length);
		} 
		var oRegExp = new RegExp("(\\b)" + s + "(\\b)");
		var result = false;
		find(result); 
		return result;
		
		function find(o) { 
			for (var i=0; i<ancestors.length; i++) { 
				if (oRegExp.test((type=="tagName")? ancestors[i].tagName : ancestors[i].className)) {  
					result = ancestors[i]; 
					break;
				}  
			}  
		}
    },
    triggerEvent: function(element, eventName) {  	
      if (document.createEvent) { 
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);  
        element.dispatchEvent(evt);
     }
     if (document.createEventObject) { 
      var evt = Object.extend(document.createEventObject());
      element.fireEvent('on' + eventName, evt);
     } 
    }  
}

Element.addMethods(extendElement);

