//store locator google maps / jquery javascript file

var country='',citystatezip='',current_page=0,retailer_ids=new Array();
var map, bounds, geocoder;
var cities_json = {
	"city_1" : [
		{lat: '35.6648967', lng: '139.7132025'},
		{lat: '35.699641' , lng: '139.412888' },
		{lat: '35.6430576', lng: '139.7139947'},
		{lat: '35.6913236', lng: '139.6995305'},
		{lat: '35.7286478', lng: '139.7117692'},
		{lat: '35.7303421', lng: '139.7105637'},
		{lat: '35.6700698', lng: '139.7628064'},
		{lat: '35.6924875', lng: '139.7025273'},
		{lat: '35.6730915', lng: '139.7599204'},
		{lat: '35.671353' , lng: '139.765834' }
	],
	"city_2" : [{lat: '35.4656441', lng: '139.6250896'}, {lat: '35.4431912', lng: '139.6508192'}],
	"city_4" : [{lat: '35.702163' , lng: '139.985163' }],
	"city_5" : [{lat: '35.1683066', lng: '136.9077009'}, {lat: 35.169697, lng: 136.883975} ],
	"city_6" : [{lat: '34.9671369', lng: '136.6189851'}],
	"city_7" : [
		{lat: '34.6731483', lng: '135.5009602'},
		{lat: '34.702956', lng: '135.495273'}
	],
	"city_8" : [{lat: '34.6931743', lng: '135.19555'}, {lat: '34.6877543', lng: '135.1929366'}],
	"city_9" : [{lat: '34.3958530', lng: '132.4570405'}],
	"city_10": [{lat: '33.8837767', lng: '130.8780241'}, {lat: '33.589411', lng: '130.411127'}, {lat: '33.588383', lng: '130.400205' }, {lat: '33.588548', lng: '130.398369' }],
	"city_11" : [
		{lat: '40.7212239', lng: '-73.9988748'},
		{lat: '40.7740153', lng: '-73.9640075'},
		{lat: '34.0748336', lng: '-118.3836489'},
		{lat: '25.88857', lng: '-80.124922'},
		{lat: '41.9112513', lng: '-87.6773259'},
		{lat: '36.121098', lng: '-115.172371'},
		{lat: '36.1077084', lng: '-115.1735613'},
		{lat: '42.351504', lng: '-71.07638'},
		{lat: '38.9624727', lng: '-77.085533'}
	],
	"city_12" : [{lat: '51.5143905', lng: '-0.2005566'}]
};

//201012004011600 +
var cities_zoom = {
	"city_1" : 12,
	"city_2" : 13,
	"city_3" : 14,
	"city_4" : 14,
	"city_5" : 13,
	"city_6" : 13,
	"city_7" : 13,
	"city_8" : 14,
	"city_9" : 13,
	"city_10": 9,
	"city_11" : 0,
	"city_12" : 0
};

jQuery(document).ready(function() {
	jQuery('.show-city').click(function() {
		jQuery('.show-city').removeClass('active');
		jQuery(this).addClass('active');

		jQuery('.store-info').removeClass('store-info-show');
		jQuery('.store-info').addClass('store-info-hide');

		var id = '#'+jQuery(this).attr('href');
		jQuery(id).addClass('store-info-show');

		var coor = jQuery(this).attr('rel');
		var href = jQuery(this).attr('href');
		coor = coor.split(',');

		var city_json_raw = {
			center : {
				'lat' : coor[0],
				'lng' : coor[1]
			},
			more : 'no',
			prev : 'no',
			input : {
				'country' : '',
				'citystatezip' : ''
			},
			points : []
		}

		for(var i=0,len=cities_json[href].length;i<len;i++) {
			city_json_raw.points[i] = { lat : cities_json[href][i].lat, lng : cities_json[href][i].lng, title : '' };
		}

		city_json = JSON.stringify(city_json_raw);
		createMap(JSON.parse(city_json));

        //201012004011600 +
        if (cities_zoom[href] > 0) map.setZoom(cities_zoom[href]);

        //20101130013500 +
        jQuery('#center').css('height', '551px');
        jQuery('#center').jScrollPane({showArrows:true});
        jQuery('.jScrollPaneTrack').css('width', '13px');
        jQuery('.jScrollPaneTrack').css('background-color', '#bbbbbb');
        jQuery('.jScrollPaneDrag').css('width', '11px');
        jQuery('.jScrollPaneTrack').css('border', '1px solid gray');
        jQuery('#center').css('background-color', '#F5F1F0');
        jQuery('.jScrollPaneContainer').css('background-color', '#F5F1F0');
		return false;
	});

	jQuery('.map-pan').click(function(){
		var coor = jQuery(this).attr('rel');
		coor = coor.split(',');
		move(this, coor[0], coor[1]);

		return false;
	});

	formSearch();
	renewHandling();

	if (jQuery('#first-view').length) {
	  jQuery('#first-view').click();
	}
});

function imageCurtain() {
	if( jQuery('#store-pic').css('left') == '0px' ) {
		var navWidth = jQuery('#map-container').css('width');
		jQuery('#store-pic').animate( { 'left' : navWidth }, 460);
	}
}


function formSearch() {
	jQuery('#retailerForm').submit(function() {
		var retailer_form = $('retailerForm');
		var error = $('storelocator_error');

		if($F(retailer_form['citystatezip']) === '') {
			error.innerHTML = 'Please fill in a city and state, or a zip code.';
			error.show();
			return;
		} else if ($F(retailer_form['citystatezip']).match(/\D+\d+|\d+\D+/g)) {
			error.innerHTML = 'Please fill in ONLY a city and state, or a zip code.';
			error.show();
			return;
		}

		error.hide();

		current_page = 0;
		citystatezip = $F(retailer_form['citystatezip']);
		country = $F(retailer_form['country']);

		geocodeIt(function(results) {
			searchAjaxRequest(results.geometry.location);
		});

		return false;
	});
}

function searchAjaxRequest(latlng) {
	jQuery('.store-info-show').each(function(){
		jQuery('.store-info').removeClass('store-info-show');
		jQuery('.store-info').addClass('store-info-hide');
	});

	new Ajax.Request(response_url, {
 		method: 'post',
		parameters: { 'page' : current_page, 'lat' : latlng.lat(), 'lng' : latlng.lng(),
					  'country' : country, 'citystatezip' : citystatezip},
		onCreate: function() { stopHandling(); },
		onFailure: function() { renewHandling(); },
    	onSuccess: function(t) { createMap(JSON.parse(t.responseText)); },
		onComplete: function() { renewHandling(); }
	});
}

function createMap(response) {
	var center = response["center"], input = response["input"];
	citystatezip=input["citystatezip"];
	country = input["country"];

	var center_point = new google.maps.LatLng(center["lat"],center["lng"]);
    var my_options = { zoom: 13, center: center_point, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false };
    map = new google.maps.Map( $("map"), my_options );

//ここを生かすと死ぬ    $("retailer_info").innerHTML = "";
    imageCurtain();
//ここを生かすと死ぬ	more_or_prev(response["more"], response["prev"]);

	if(typeof(response["points"]) == 'string') {
		response["points"] = eval(response["points"]);
	}

try {
    if(response["points"] !== undefined) {
		bounds = new google.maps.LatLngBounds();
		for(var i=0,len=response["points"].length; i<len; i++) {
			var j = i+1; var point = response["points"][i];
			addMarker(point["lat"], point["lng"], j);

			if(point["title"] !== '') {
				var locDiv = new Element('div').update(display_retailerinfo(point,j));
				$('retailer_info').insert({ 'bottom' : locDiv });
				$('gmap_zoom_'+j).observe('click', move.bindAsEventListener(this, point["lat"], point["lng"]));
			}
		}

		if(response["points"].length > 1) {
			map.fitBounds(bounds);
		} else {
			map.setCenter(new google.maps.LatLng(response["points"][0]["lat"],response["points"][0]["lng"]));
			map.setZoom(15);
		}
	} else {
		var locDiv = new Element('div').update("There are no retailers near you within "+map_diameter+" miles.");
		$('retailer_info').insert({ 'bottom' : locDiv });
	}
} catch (e) { alert('createMap(' + e + ')'); }
}

function geocodeIt(callback) {
	geocoder = new google.maps.Geocoder();

	geocoder.geocode({'address' : citystatezip+' '+country}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			if(results[0]) {
				callback(results[0]);
			}
		} else {
			var error = $('storelocator_error');
			error.innerHTML = "That was not a valid location.";
			error.show();
			return;
		}
	});
}

function display_retailerinfo(point,j) {
	var output =  "<div class='shop'>";
		output += "<h3>"+point['title']+"</h3>";
		output += "<p>"+point['addr']+"<br />"+point['city']+" "+point['state']+" "+point['zip']+"<br />T: "+point['phone']+"</p>";
		output += "<a href='#' id='gmap_zoom_"+j+"' onclick='return false'>View map<\/a>";
		output += "</div>";

	return output;
}

function more_or_prev(more, prev) {
	if(more === 'yes') { $("results_more").setStyle({ display : "block" }); }
		else { $("results_more").setStyle({ display : "none" }); }
	if(prev === 'yes') { $("results_prev").setStyle({ display : "block" }); }
		else { $("results_prev").setStyle({ display : "none" }); }
}

function move(evt, lat, lon) {
	map.panTo(new google.maps.LatLng(lat, lon));
}

function addMarker(lat, lon, number) {
	var point = new google.maps.LatLng(lat,lon);
	bounds.extend(point);
	var marker = new google.maps.Marker({
		position: point, map: map,
		icon: new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+String.fromCharCode(64+number)+"|EB8063|111111")
	});
}

function getMore() {
try {
	$('results_more').observe('click', function(evt) {
		current_page++;
		geocodeIt(function(results) {
			searchAjaxRequest(results.geometry.location);
		});
	});
} catch(e) { /* alert('getMore(' + e + ')'); */ }
}

function getPrev() {
try {
	$('results_prev').observe('click', function(evt) {
		current_page--;
		geocodeIt(function(results) {
			searchAjaxRequest(results.geometry.location);
		});
	});
} catch(e) { /* alert('getPrev(' + e + ')'); */ }
}

function stopHandling() {
	$('results_more').stopObserving('click');
	$('results_prev').stopObserving('click');
}

function renewHandling() {
	getMore();
	getPrev();
}

// converts array to object
function oc(a) {
  var o = {};
  for(var i=0;i<a.length;i++) { o[a[i]]=''; }
  return o;
}

