// Page specific JavaScript

var queryString = encodeURI(document.location.href).replace(/^[^¥?]+¥??/,'');
var params = parseQuery(queryString);
//alert(params['prop_type']);


function parseQuery(query) {
	var Params = {};
	if (!query) {return Params;}// return empty object
	var Pairs = query.split(/[;&]/);
	for (var i=0; i<Pairs.length; i++) {
		var KeyVal = Pairs[i].split('=');
		if (! KeyVal || KeyVal.length != 2) {continue;}
		var key = unescape(KeyVal[0]);
		var val = unescape(KeyVal[1]);
		val = val.replace(/¥+/g, ' ');
		Params[key] = val;
	}
	return Params;
};


$(function() {
		   
/**
 * @desc Enter description here...
 *
 */
	// get the form's id.	   
	var frm_rr = $("#RefineResultsForm");
	var frm_sp = $("#SearchPadForm");

/**
 * @desc Enter description here...
 *
 */
	_initCheckboxes();

	function _initCheckboxes() {
		var sel_prop_type = frm_sp.find("#FormPropType").val();
		if(sel_prop_type == '') {
			$(".checkbox").each(function(i){
				++i;
				frm_rr.find("#FormPropType" + i).attr('checked', 'checked');
			});
		}
	};
/**
 * @desc Enter description here...
 *
 */
	_initRoomLayout();

	function _initRoomLayout() {
		selected = frm_sp.find("#FormNumOfRooms").val();
		if(selected != '') {
			frm_sp.find("#FormRoomLayout").show();
		} else {
			frm_sp.find("#FormRoomLayout :selected").attr('selected', '');
			frm_sp.find("#FormRoomLayout").hide();
		}
	};
/**
 * @desc Enter description here...
 *
 */
 	var _q = frm_sp.find("#FormQ:text");
	
	_setColorFormQ();
	
	_q.focus( function() {
		var _q = frm_sp.find("#FormQ:text");
		_q.css("color", "#000000");
	}).blur( function() {
		 _setColorFormQ();
	});
	
	_q.change(function(){
		_setColorFormQ();
	});
	
	function _setColorFormQ() {
		var _q = frm_sp.find("#FormQ:text");
		var iptQ_val = $.trim(_q.val());
		iptQ_val = str_replace(['島根県'], '', iptQ_val);
		switch(iptQ_val) {
			case "松江":
				_q.val('松江市');				
				break;
			case "簸川":
				_q.val('簸川郡');
				break;
			case "出雲市":
				//_q.css("color", "#bbbbbb");
				_q.val('出雲市');				
				break;
			case "出雲":
				//_q.css("color", "#bbbbbb");
				_q.val('出雲市');				
				break;
			/*case "":
				_q.css("color", "#bbbbbb");
				_q.val('出雲市');				
				break;*/
			default:
				//_q.css("color", "#000000");
		}
		
		/*if (iptQ_val == "" || iptQ_val == "出雲市"){
			_q.css("color", "#bbbbbb");
			_q.val('出雲市');
		} else {
			_q.css("color", "#000000");
		}*/		
	}
/**
 * @desc Enter description here...
 *
 */
	var currentFocus = null;
	$(':text').focus( function() {
		currentFocus = this;
		$(currentFocus).css("background", "#FFFAC1");
	}).blur( function() {
		$(currentFocus).css("background", "#ffffff");
		currentFocus = null;
	}); 
/**
 * @desc Try to bring the values in the Search Pad and submit the main form.
 *
 */
	frm_sp.find(':button').click(function(){
		
		/*var _q = frm_sp.find("#FormQ:text");
		var iptQ_val = $.trim(_q.val());
		if(iptQ_val == '出雲市') _q.val('');*/

		var a = ['FormQ', 'FormPriceLow', 'FormPriceHigh', 'FormNumOfRooms', 'FormRoomLayout'];
		$.each(a, function(i) {
			value = frm_sp.find("#"+a[i]).val().replace(/<\/?[^>]+>/gi, '');
			frm_rr.find("#"+a[i]).val(value);
		});
		
		frm_rr.submit(); // submit
	});
/**
 * @desc Try to bring the selected value in the Search Pad.
 * @desc Show the roomLayoutDv if it matches any of the criteria, else hide it.
 * 
 */
 
 	_initRoomDv();
	
	frm_sp.find("#FormPropType").change(function(){

		// try to bring the selected value in the Search Pad.
		var sel_prop_type = frm_sp.find("#FormPropType").val();
		
		if(sel_prop_type == '') {
			_initCheckboxes();
		} else {
			$(".checkbox").each(function(i){
				++i;
				frm_rr.find("#FormPropType" + i).attr('checked', '');
			});
			frm_rr.find("#FormPropType" + sel_prop_type).attr('checked', 'checked');
		}

		//-------------
		
		// show the roomLayoutDv if it matches any of the criteria, else hide it.
		_initRoomDv();
 	});
	
	function _initRoomDv() {
		// show the roomLayoutDv if it matches any of the criteria, else hide it.
		value = params['prop_type'];
		if (frm_sp.find("#FormPropType").val()) {
			value = frm_sp.find("#FormPropType").val();
		}
		actives = [2, 3, 4, 5, 6];
		found = false;
		// loop through array
		for (key in actives) {
			if (actives[key] == value) {
				found = true;
				break;
			}
		}
		if(found == true) {
			frm_sp.find(".roomLayoutDv").show();
		} else {
			frm_sp.find(".roomLayoutDv").hide();
			frm_sp.find("#FormNumOfRooms").val('');
			frm_sp.find("#FormRoomLayout option").attr('selected', '');
			frm_sp.find("#FormRoomLayout").hide();
		}
	}
/**
 * @desc Enter description here...
 * 
 */
	frm_sp.find("#FormNumOfRooms").change(function(){
		_initRoomLayout();
		$("#FormNumOfRooms :hidden").val($("#FormNumOfRooms :visible").val());
	});
/**
 * @desc Enter description here...
 * 
 */
	frm_sp.find("#FormRoomLayout").change(function(){
		$("#FormRoomLayout :hidden").val($("#FormRoomLayout :visible").val());
	});
/**
 * @desc Enter description here...
 *
 */
	$("#sortByRecommendLnk").click(function(){
		frm_rr.find("#FormSort").val('');
		current_direction = frm_rr.find("#FormDirection").val();
		directon = (current_direction == 'rand') ? 'rand' : 'rand'; 
		frm_rr.find("#FormDirection").val(directon);
		frm_rr.submit();
		return false;
	});
/**
 * @desc Enter description here...
 *
 */
	$("#sortByDateLnk").click(function(){
		frm_rr.find("#FormSort").val('created');
		current_direction = frm_rr.find("#FormDirection").val();
		directon = (current_direction == 'asc') ? 'desc' : 'asc'; 
		frm_rr.find("#FormDirection").val(directon);
		frm_rr.submit();
		return false;
	});
/**
 * @desc Enter description here...
 *
 */
	$("#sortByPriceLnk").click(function(){
		frm_rr.find("#FormSort").val('price');
		current_direction = frm_rr.find("#FormDirection").val();
		directon = (current_direction == 'asc') ? 'desc' : 'asc'; 
		frm_rr.find("#FormDirection").val(directon);
		frm_rr.submit();
		return false;
	});
/**
 * @desc Try to bring the selected value of NumOfItems and submit the main form.
 *
 */
	$("#NumOfItems").change(function(){
		$("#FormN").val($("#NumOfItems").val());
		frm_rr.submit();
	});

/**
 * @desc Show the options if it is enabled, else hide it.
 * 
 */
 	var options_cookie = getCookie('for_sale.options.enable');

	if(options_cookie == null) {
		$(".options").show();
	} else if (options_cookie == 0) {
		$(".options").hide();
		$("#showSearchOptions").show();
	} else {
		$(".options").show();
	}
	
	$("#showSearchOptions").children('a').click(function(){
		$(this).parent('div').hide();
		$(".options").show();
		$("#hideSearchOptions").show();
		date=new Date;
		date.setMonth(date.getMonth()+3);
		setCookie('for_sale.options.enable', 1, date);
	});		   
	$("#hideSearchOptions").children('a').click(function(){
		$(this).parent('div').hide();
		$(".options").hide();
		$("#showSearchOptions").show();
		//delCookie('for_sale.options.enable');
		
		// empty selected values
		frm_sp.find("#FormNumOfRooms").val('');
		frm_sp.find("#FormRoomLayout option").attr('selected', '');
		frm_sp.find("#FormRoomLayout").hide();		

		date=new Date;
		date.setMonth(date.getMonth()+3);
		setCookie('for_sale.options.enable', 0, date);
	});
/**
 * @desc Count elements in an array, or properties in an object
 *
 */
	function count( mixed_var ) {
		var key, cnt = 0;
		for (key in mixed_var){
			cnt++;
			if( mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
				cnt += count(mixed_var[key], 1);
			}
		}
		return cnt;
	}
/**
 * @desc Get the json data for the selects.
 * 
 */
	$.getJSON("/modules/el_schools/gen", {
		'hl': generic.params.hl,
		'sel': ""
		},
		function(data, status) {

			var values = ['- 指定しない -'];

			$.each(data, function(i, item){
				values.push(item);
				//$("#sales_res").append(item);
			});
			
			var sel = params['el_school'];
			if(sel == '') sel = 0;
			
			$('#el_schools').numericOptions({
				from:0,
				to:count(data),
				labels:values,
				selectedIndex: sel
				//exclude:[2,3,5,10]
			});
		}
	);

	$.getJSON("/modules/jh_schools/gen", {
		'hl': generic.params.hl,
		'sel': ""
		},
		function(data, status) {
		
			var values = ['- 指定しない -'];

			$.each(data, function(i, item){
				values.push(item);
				//$("#sales_res").append(item);
			});

			var sel = params['jh_school'];
			if(sel == '') sel = 0;
			
			$('#jh_schools').numericOptions({
				from:0,
				to:count(data),
				labels:values,
				selectedIndex: sel
				//exclude:[2,3,5,10]
			})
		}
	);

/**
 * @desc jQuery Facebox Plugin.
 *
 */
	$('a[rel*=facebox]').facebox({
		loading_image : '/js/jquery/plugins/facebox/loading.gif',
		close_image   : '/js/jquery/plugins/facebox/closelabel.gif'
	});

});

/**
 * @desc Load Google Maps
 *
 */
var map;
var gGeo;
var apikey = 'ABQIAAAA7TWIqiwj1mKi9xrVruRP-RSFNoZaEohrif3PXbFqDEaOoQuvQRQsOtzjBI6YOCeLsuaBuuExvpFS8Q';

$(function() {

	var _wrapper = $("#MdMap");
	var _map = $("#map");
	var _mapsShowLnk = $("#mapsShowLnk");
	var _mapsHideLnk = $("#mapsHideLnk");
	var _mapSizeLnk = $("#mapSizeLnk");
	var _expandSizeTxt = $("#expandSizeTxt");
	var _reduceSizeTxt = $("#reduceSizeTxt");
		   
	if(Cookie.isActive() == true) {
		
		loadScript();
		if(Cookie.isExpanded() == true) {
			_mapSizeLnk.text(_reduceSizeTxt.text()).removeClass("expand").addClass("reduce");
			_map.css('height', '500px');
			Cookie.expand();
		}
		Cookie.activate();
		_wrapper.show();	
	} else {
		_wrapper.hide();
		_mapsShowLnk.show();
		Cookie.deactivate();
	};
	
	_mapsShowLnk.click(function(){
		_wrapper.show();
		_map.show();
		loadScript();
		_mapsShowLnk.hide();
		Cookie.activate();
	});
	
	_mapsHideLnk.click(function(){
		_map.slideUp();
		_wrapper.slideUp();
		_mapsShowLnk.show();
		Cookie.deactivate();
	});
		
	_mapSizeLnk.click(function(){
		loadScript();						
		if(_mapSizeLnk.hasClass("expand")) {
			_mapSizeLnk.text(_reduceSizeTxt.text()).removeClass("expand").addClass("reduce");
			_map.css('height', '500px');
			Cookie.expand();
			
		} else if(_mapSizeLnk.hasClass("reduce")) {
			_mapSizeLnk.text(_expandSizeTxt.text()).removeClass("reduce").addClass("expand");
			_map.css('height', '250px');
			Cookie.reduce();
		}
	});

});

var Cookie = {
	isActive: function() {
		return getCookie('for_sale.map.enable');
	},
	isExpanded: function() {
		return getCookie('for_sale.map.expanded');
	},
	activate: function() {
		date=new Date;
		date.setMonth(date.getMonth()+3);
		setCookie('for_sale.map.enable', 1, date);
	},
	deactivate: function() {
		delCookie('for_sale.map.enable');
	},
	expand: function() {
		date=new Date;
		date.setMonth(date.getMonth()+3);
		setCookie('for_sale.map.expanded', 1, date);
	},
	reduce: function() {
		delCookie('for_sale.map.expanded');
	}
};

function makeMap(){
	
	$("#MdSearchResultItemsDefault h3").each(function(i){

		// get elements to create markers. 
		var _loc = $("#map_location-"+i);
		var location = '島根県' + _loc.text();
		var proptype = $("#map_proptype-"+i).text();
		var price = $("#map_price-"+i).text();
		var href = _loc.attr('href');
		//var name = $("#spot-name-"+i).text();
		//var location = document.getElementById("spot-location-"+i).value; 
		
		addMarker(location, proptype, price, href, i);
   });
	
   function addMarker(location, proptype, price, href, idx){ 

	   gGeo.getLatLng(location , 
		   function (point){ 
			   if (point) {
				   
				   // creates a new marker manager that controlls visibility of markers for the specified map. 
				   var marker = new GMarker(point); 
				   GEvent.addListener(marker, "click", function() { 
						var txt =
							"<div style='width:220px;'>"
								+ "<div align='left'>"
								+ "<b>住所：</b>" + str_replace('島根県', '', location) + "<br />"
								+ "<b>種別：</b>" + proptype + "<br />"
								+ "<b>価格：</b>" + price
								+ "</div>"
								+ "<div align='right'>"
								+ "<a href='" + href + "'>&raquo; 詳細を見る</a>"
								+ "</div>";
							+ "</div>";
					  marker.openInfoWindowHtml(txt); 
				   }); 
				   // Adds an overlay to the map and fires the addoverlay event.
				   map.addOverlay(marker); 

				   // if the first marker, sets the map view to the given center and 
				   // triggers the event on page load.
				   /*if(idx==1){
					  map.setCenter(point);
					  GEvent.trigger(marker,"click");
				   }*/
			   } 
		   } 
	   )
   }
};

function loadScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = 'http://maps.google.com/maps?file=api&v=2.x&key='+apikey+'&async=2&callback=loadMap';
	document.body.appendChild(script);
};
function loadMap(){
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(35.368895, 132.791748), 10);
	//map.addControl(new GLargeMapControl());
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl()); 				
	gGeo = new GClientGeocoder();
	makeMap();

};

function refresh(){ // currently not used
	map.clearOverlays();
	makeMap();
};

function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
    while(j = 0, i--){
        while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f);
    }
    return sa ? s : s[0];
}
function is_array( mixed_var ) {
    return ( mixed_var instanceof Array );
}

function setCookie(name, value, expires, path, domain, secure) {
	document.cookie= name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
};

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
	begin = dc.indexOf(prefix);
	if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
};

function delCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name+"="+((path)?";path="+path:"")+((domain)?";domain="+ domain:"")+";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
};
