function loadCookie(name) {
    var cookie = document.cookie + ';';
    var start  = cookie.indexOf(name + '=');
    return start != -1 ? unescape(cookie.substr(start + name.length + 1,
        cookie.indexOf(';', start) - start - name.length - 1)) : '';
}

function factory(element_id, lat, lng, zoom) {
	var map = new GMap2($(element_id));
	map.setCenter(new GLatLng(lat, lng), zoom);
	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    var map2 = new GOverviewMapControl(new GSize(120,120));
    map.addControl(map2);

    //マウスホイールによる地図の縮小拡大に対応
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    ua = navigator.userAgent;
    if (ua.match("Gecko"))  GEvent.addDomListener($('map'), "DOMMouseScroll", cancelEvent); //For Firefox
    if (ua.match("MSIE") || ua.match("Safari")) GEvent.addDomListener($('map'), "mousewheel", cancelEvent); //For IE and Safari

	return map;
}

function searchAddress(geocoder, address, options) {
	var latlng = null;
	geocoder.getLatLng(address, function(latlng) {
		if (latlng != null) {
			map.clearOverlays();
			map.setCenter(latlng);
			
			if (options.marker_flg) {
				map.addOverlay(createMarker(latlng));
			}
			if (options.element_id) {
				geocoder.getLocations(address, function(locations) {
					$(options.element_id).innerHTML = locations['Placemark'][0]['address'].replace(/（?日本）?/, '');
				});
			}
		} else {
			alert('指定された住所は見つかりませんでした。');
		}
	});
	return latlng;
}

function moveDefaultPosition(address, sw_x, sw_y, ne_x, ne_y)
{
    var gc = new GClientGeocoder();
    gc.getLatLng(address, function(lc) {
        if (lc != null) {
            if (sw_x && sw_y && ne_x && ne_y) {
                if (lc.lng() >= sw_x && lc.lng() <= ne_x && lc.lat() >= sw_y && lc.lat() <= ne_y) {
                    map.setCenter(lc);
                }
            } else {
                map.setCenter(lc);
            }
        }
    });
}


function createInfoWindow(info_data, is_route) {
    if (typeof is_route == 'undefined') is_route = true;

    var dt = new Wired.Date(info_data.updated_at.replace(/-/g, '/'));
    var upd_at = dt.format("%Y年%m月%d日 %H:%M");

    var close_link_text = '';
    close_link_text = '<div style="text-align:right">';
    close_link_text += '<a style="font-size:13px" href="javascript:void(0);" onclick="map.closeInfoWindow();">- 閉じる -</a>';
    close_link_text += '</div>';

	var html = '';
	html += '<table class="info" style="word-break: break-all;width:290px;height:100%;vertical-align:top"><tr><td style="width:170px;vertical-align:top">';
	html += '<h2 style="margin:0;padding:0;" class="info_text">' + info_data.title + '</h2>';
    html += info_data.blog_link ? ('<p class="info_text_2">（<a href="' + info_data.blog_link + '">' + info_data.name + '</a>）</p>') : ('<p class="info_text_2">（' + info_data.name + '）</p>');
	html += '<span class="info_text_2">' + info_data.comment + '</span>';
	html += info_data.url ? '<p class="info_text_2"><a href="' + info_data.url + '" target="_blank">' + info_data.url + '</a></p>' : '';
    html += (info_data.coupon_comment) ? '<br /><input type="button"  value="クーポン情報を見る" onclick="var new_win = window.open(\'' + info_data.coupon_comment + '\',\'\',{size:\'400x400\'}); new_win.focus(); return false;">' : '';
    html += info_data.chirashi_file ? '<br /><input type="button" onclick="var ch = window.open(\'' + info_data.chirashi_file + '\',\'\',{size:\'800x600\'})" value="チラシを見る">' : '';
	html += '</td><td style="width:120px;" class="info_text_2"><br />';
	html += info_data.image ? 
				(info_data.right_url ? '<a href="' + info_data.right_url + '"><img src="' + info_data.image + '"></a>'
				 : '<img src="' + info_data.image + '">')
			: '';
	html += info_data.right_url ? '<p class="info_text_2" style="text-align:center"><a href="' + info_data.right_url + '">' + info_data.right_url_text + '</a></p>' : '';
	html += '</td></tr>';
	html += is_route ? (info_data.map_route ? '<tr><td class="info_text_2">[<a href="' + info_data.map_route + '">ルートを表示する</a>]</td></tr>' : '') : '';
    html += '<tr><td><span id="link_text"><input type="button" value="リンクを表示する" onclick="dispMapLinkText(\'' + info_data.marker_link + '\');" /></span></td></tr>';
    html += '<tr><td style="font-size:11px">' + upd_at + '</td></tr>';
	html += '</table>';
	return html;
}

function dispMapLinkText(marker_link) {
    $('link_text').innerHTML = '<input type="text" name="link_text" value="' + marker_link + '" onclick="Field.select(this)" />';
}


function createInfoWindowOfRoute(title, comment) {
	var html = '';
	html += '<table><tr><td style="width:220px;vertical-align:top">';
	html += '<h2 style="margin:0;padding:0">' + title + '</h2>';
	html += (comment? comment.replace(/\r?\n/g, '<br />') : '') + '</td>';
	html += '</tr></table>';
	return html;
}

function createMarkerForMapSite(latlng, info_window_html, icon_file, marker_code, marker_group) {
    var close_link_text = '';
    close_link_text = '<div style="text-align:right">';
    close_link_text += '<a style="font-size:13px" href="javascript:void(0);" onclick="map.closeInfoWindow();">- 閉じる -</a>';
    close_link_text += '</div>';

	var marker;
	if (icon_file) {
		var icon = new GIcon();
		icon.iconSize = new GSize(25, 25);
		icon.iconAnchor = new GPoint(13, 25);
		icon.infoWindowAnchor = new GPoint(13, 3);
		icon.image = icon_file;
		marker = new GMarker(latlng, icon);
	} else {
		marker = new GMarker(latlng);
	}

	if (info_window_html) {
		GEvent.addListener(marker, "click", marker.openInfo = function() {

            if (Number(marker_group) == 2 || Number(marker_group) == 3 || Number(marker_group) == 6) {
                tabList = [
                    new GInfoWindowTab('情報', '<div id="info_window" style="width:310px;height:200px;overflow-y:auto;border:none;z-index:13;">' + info_window_html + '</div>' + close_link_text),
                    new GInfoWindowTab('コメント一覧', '<div style="width:317px;height:210px;z-index:12" id="info_comment_list"></div>')
                ];
                marker.openInfoWindowTabsHtml(tabList, {selectedTab:0});

                var url = '/index/show_comment';
                new Ajax.Request(url,
                {
                    method: 'get',
                    parameters:'marker_code=' + marker_code,
                    onSuccess: function(response)
                    {
                        var dat = response.responseText;
                        $('info_comment_list').innerHTML = dat;
                    },
                    onFailure: function()
                    {
                        alert('データが一件もありません。');
                    }
                });
            } else {
       			marker.openInfoWindowHtml('<div id="info_window" style="width:310px;height:200px;overflow-y:auto;border:none;z-index:0">' + info_window_html + '</div>' + close_link_text);
            }
    	});
	}
	return marker;
}

function createMarker(latlng, info_window_html, icon_file) {
    var close_link_text = '';
    close_link_text = '<div style="text-align:right">';
    close_link_text += '<a style="font-size:13px" href="javascript:void(0);" onclick="map.closeInfoWindow();">- 閉じる -</a>';
    close_link_text += '</div>';



	var marker;
	if (icon_file) {
		var icon = new GIcon();
		icon.iconSize = new GSize(25, 25);
		icon.iconAnchor = new GPoint(13, 25);
		icon.infoWindowAnchor = new GPoint(13, 3);
		icon.image = icon_file;
		marker = new GMarker(latlng, icon);
	} else {
		marker = new GMarker(latlng);
	}
	if (info_window_html) {
		GEvent.addListener(marker, "click", marker.openInfo = function() {
			marker.openInfoWindowHtml('<div id="info_window" style="width:310px;height:205px;overflow-y:auto;border:none;z-index:0">' + info_window_html + '</div>' + close_link_text);
		});
	}
	return marker;
}

function createLine(latlngs, color, weight) {
	return new GPolyline(latlngs, color ? color : '#ff0000', weight ? weight : 3);
}

function getQueryString(params) {
	var strings = [];
	$H(params).each(function(pair) {
		strings.push(pair[0] + '=' + pair[1]);
	});
	return strings.join('&');
}

function getRouteLatLngs(route) {
	var latlngs = [];
	var route_zahyos = route.route_zahyos;
	route_zahyos.each(function(zahyo) {
		var zahyo_ = zahyo.split(',');
		latlngs.push(new GLatLng(Number(zahyo_[0]), Number(zahyo_[1])));
	});
	return latlngs;
}

function adjustRouteMap(latlngs, map) {
	var bounds = new GBounds(latlngs);
	var sw_latlng = new GLatLng(bounds.minY, bounds.minX);
	var ne_latlng = new GLatLng(bounds.maxY, bounds.maxX);
	var latlng_bounds = new GLatLngBounds(sw_latlng, ne_latlng);
	map.setCenter(latlng_bounds.getCenter(), map.getBoundsZoomLevel(latlng_bounds));
}

function cancelEvent(event)
{
    e = event;
    if (typeof e.preventDefault == 'function')
        e.preventDefault();
    
    if (typeof e.stopPropagation == 'function')
        e.stopPropagation();
    
    if (window.event) {
        window.event.cancelBubble = true; // for ie
        window.event.returnValue = false; // for ie
    }
}

function changeSmallGenres(obj_self, large_genre_id, categories)
{
    var url = '/area/genreJson';

    $A(document.getElementsByName("l_genres")).each(function(l_genre) {
        Element.setStyle(l_genre, { fontWeight:"normal" });
    });

    obj_self.style.fontWeight = 'bold';

    new Ajax.Request(url,
    {
        method: 'get',
        parameters:'large_genre_id=' + large_genre_id + '&categories=' + categories,
        onSuccess: function(response)
        {
            var dat = eval('(' + response.responseText + ')');
            html_data = '';
            $A(dat).each(function(a) {
                html_data += '<li><a href="#" name="s_genres" onclick="changeMarkers(this,' + a.id + ',\'\',\'' + categories + '\');">' + a.genre_name + '</a></li>';
            });
            $('small_genres').innerHTML = html_data;
        },
        onFailure: function()
        {
            alert('データが一件もありません。');
        }
    });
}

function changeMarkers(obj_self, genre_id, marker_icons, categories)
{
    var url = '/area/markerJson';

    $A(document.getElementsByName('search_mode')).each(function(elem) {
        if (elem.checked == true) {
            search_mode = elem.value;
        }
    });

    $A(document.getElementsByName("s_genres")).each(function(s_genre) {
        Element.setStyle(s_genre, { fontWeight:"normal" });
    });

    if (obj_self) obj_self.style.fontWeight = 'bold';

    new Ajax.Updater({success:'markers'},
    url, {
        method: 'get',
        parameters: 'genre_id=' + genre_id + '&categories=' + categories,
        onFailure: function() {
            alert('データが一件もありません。');
        }
    });
}

function replaceNewLine(text, replace_text)
{
    text = text.replace(/(\r?\n|\t|<br>|<br \/>)/g, replace_text);
    return text;
}   

function setDetail(marker_code, genre_id, categories)
{
    var url = '/area/markerDetailJson';

    new  Ajax.Request(url,
    {
        method: 'get',
        parameters: 'marker_code=' + marker_code,
        onSuccess: function(response)
        {
            var dat = eval('(' + response.responseText + ')');

        	var html_data = '';
        	html_data += '<table ><tr><td style="vertical-align:top;white-space:normal;word-break:break-all;">';
        	html_data += '<span style="margin:0;padding:0;font-size:14px;font-weight:bold">' + dat[0].title + '</span>';
            html_data += dat[0].blog_link ? ('<p>（<a href="' + dat[0].blog_link + '">' + dat[0].name + '</a>）</p>') : ('<p>（' + dat[0].name + '）</p>');
        	html_data += dat[0].comment.replace(/\r?\n/g, '<br />');
        	html_data += dat[0].url ? '<p><a href="' + dat[0].url + '" target="_blank">' + dat[0].url + '</a></p>' : '';
            html_data += (dat[0].coupon_comment) ? '<br /><input type="button" onclick="var cnp = window.open(\'' + dat[0].coupon_comment + '\',\'\',{size:\'400x400\'}); cnp.focus(); return false;" value="クーポン情報を見る">' : '';
            html_data += dat[0].chirashi_file ? '<br /><input type="button" onclick="var ch = window.open(\'' + dat[0].chirashi_file + '\',\'\',{size:\'800x600\'})" value="チラシを見る">' : '';
        	html_data += '</td><td><br />';
        	html_data += dat[0].image ? 
        				(dat[0].right_url ? '<a href="' + dat[0].right_url + '"><img src="' + dat[0].image + '"></a>'
        				 : '<img src="' + dat[0].image + '">')
        			: '';
        	html_data += dat[0].right_url ? '<p style="text-align:center"><a href="' + dat[0].right_url + '">' + dat[0].right_url_text + '</a></p>' : '';
        	html_data += '</td></tr>';
        	html_data += dat[0].map_route ? '<tr><td>[<a href="' + dat[0].map_route + '">ルートを表示する</a>]</td></tr>' : '';
            html_data += '<tr><td>&nbsp;</td></tr><tr><td>';
            html_data += dat.map_top_url ? '[<a href="' + dat.map_top_url + '">マップ上で見る</a>] ' : '';
            html_data += '[<a href="#" onclick="changeMarkers(null,' + genre_id + ',\'\',\'' + categories + '\')">一覧に戻る</a>]</td></tr>';
        	html_data += '</table>';

            $('markers').innerHTML = html_data;
       },
       onFailure: function() {
           alert('データがありません');
       }
   });
}

function setDefaultLatLng(map_obj)
{
    var latlngTmp = map_obj.getCenter();
    var param_string = 'lat=' + encodeURI(latlngTmp.lat()) + '&lng=' + encodeURI(latlngTmp.lng()) + '&zoom=' + encodeURI(Number(map_obj.getZoom()));
    url = '/index/saveDefault';

    new Ajax.Request(url,
    {
        method: 'get',
        parameters: param_string,
        onSuccess: function(response) {
            alert('現在の中心地点を保存しました。');
        }
    });
}

ViewPort = Class.create();

ViewPort.prototype = {
	_userUA: navigator.userAgent,
	_userVersion: navigator.appVersion,
	isIE: false,
	isOpera: false,

	initialize: function() {
		var temp = this._userUA;
		if (temp.indexOf('Opera') >= 0) {
			isOpera = true;
			isIE = false;
		} else if(temp.indexOf('MSIE') >= 0) {
			isOpera = false;
			isIE = true;
		}
	},

    getWidth: function() {
        var width = self.innerWidth; //safari
        var mode = document.compatMode;

        if (mode || this.isIE) { //IE, Gecko, Opera
            width = (mode == 'CSS1Compat') ?
                document.documentElement.clientWidth : // Standards
                document.body.clientWidth; //Quirks
        }
        return width;
    },

    getHeight: function() {
        var height = self.innerHTML; //safari, opera
        var mode = document.compatMode;

        if ((mode || this.isIE) && !this.isOpera) { //IE, Gecko
            height = (mode == 'CSS1Compat') ?
                document.documentElement.clientHeight : // Standards
                document.body.clientHeight; //Quirks
        }
        return height;
    }
};

