/**---------------------------------
 * common.js
 *
 * ...
 * author	: takaaki koyama
 *
 * @use jQuery 1.4 later
 ---------------------------------*/
;(function($){

	$.extend($.easing, {
		def: 'easeOutQuad',
		swing: function (x, t, b, c, d) {
			return $.easing[$.easing.def](x, t, b, c, d);
		},
		easeOutQuad: function (x, t, b, c, d) {
			return - c * (t/=d) * (t-2) + b;
		}
	});

	$.extend({
		uif : {
			setup : (function(){

				var setup = function(){
					setup.rollover();
					setup.externalLink();
					setup.popup();
					setup.smoothScroll();
					//setup.css3Utils();
					setup.formUtils();
				}

				//rollover
				// switching image xxx_off.xxx -> xxx_on.xxx
				// if image name is bnr_xxxx or btn_xxx which don't has neme _off , _on
				// fade effect on mouse over.
				setup.rollover = function(option){
					var config = {
						off : '_off.',
						on : '_on.',
						currentClass : 'current'
					}
					$.extend(config,option);

					var offRegExp = new RegExp(config.off);
					var onRegExp = new RegExp(config.on);


					function rollOverHandler(){
						var $t = $(this);
						if ($t.attr("src").match(offRegExp)){
							$t.attr("src",$t.attr("src").replace(config.off, config.on));
							return;
						}
					};

					function rollOutHandler(){
						var $t = $(this);
						if (!$t.hasClass(config.currentClass) && $t.attr("src").match(onRegExp)){
							$t.attr("src",$t.attr("src").replace(config.on, config.off));
							return;
						}
					}


					$("a img[src*='"+config.on+"']").addClass(config.currentClass);
					$("a img,:image")
						.unbind("mouseover",rollOverHandler)
						.bind("mouseover",rollOverHandler);

					$("a img[class!='current'],:image")
						.unbind("mouseout",rollOutHandler)
						.bind("mouseout",rollOutHandler);


					//preload images
					var images = [];
					$("a img,:image").each(function(index){
						if($(this).attr("src").match(offRegExp)){
							images[images.length] = (new Image()).src = $(this).attr("src").replace(config.on, config.off);
						}
					});
				}

				//externalLink
				//if has class .extenal -> open _blank window
				setup.externalLink = function(option){
					var config = {
						className : 'external',
						ignoreURLs : []
					}
					$.extend(config,option);

					// target _blank auto add
					var domains = [document.domain];
					if(config.ignoreURLs.length){
						domains = domains.concat(config.ignoreURLs);
					}
					var selector = ""
					var ls= ":not([href^=http://";
					var lss= ":not([href^=https://";
					var rs = "])";
					selector  = ls + domains.join(rs + ls) + rs;
					selector += lss + domains.join(rs + lss) +rs;
					$("a[href^=http]:not([class^=popup])" + selector).addClass(config.className);
					$("area[href^=http]:not([class^=popup])" + selector).addClass(config.className);

					function windowOpen(){
						window.open(this.href,"_blank");
						return false;
					}


					$("a."+config.className)
						.unbind("click",windowOpen)
						.bind("click",windowOpen);
					$("area."+config.className)
						.unbind("click",windowOpen)
						.bind("click",windowOpen);

				}

				//popup
				// class="popup400x600"
				//  -> window.open(this.href,"popup","width=400,height=600,...)
				//
				// open in popup parent window.
				// add class="openParentWin" on a-tag in a popup window.
				setup.popup = function(){

					function popupOpen(){
						if($.browser.safari ){
							window.open(this.href,"_blank");
							return false;
						}
						var className = $(this).attr("class").match(/popup([0-9]{1,})x([0-9]{1,})/) ;
						var width = RegExp.$1;
						var height = RegExp.$2;
						var state = [];
						var notHasSize = "yes"
						if(width != null && height != null){
							state = [
								"width=" + width,
								"height=" + height
							];
							notHasSize = "no";
						}
						state = state.concat([
							"location=" + notHasSize,
							"toolbar=" + notHasSize,
							"directories=" + notHasSize,
							"status=yes",
							"menubar=no",
							"scrollbars=yes",
							"resizable=yes",
							"alwaysRaised=yes"
						]);

						window.name = document.domain + "_root";
						window.open(this.href,"popup"+(new Date()).getTime().toString(),state);

						return false;
					}


					function openParentWindow(){
						window.open(this.href,document.domain + "_root");

						return false;
					}

					$("a[class^='popup']")
						.unbind('click', popupOpen)
						.bind('click', popupOpen);

					$("a.openParentWin")
						.unbind('click', openParentWindow)
						.bind('click', openParentWindow);

				}

				//smoothScroll
				setup.smoothScroll = function(target){
					var $t = target? $(target) : $($.browser.safari ? 'body' : 'html');
					function smoothScroll() {
						var target = $(this.hash);
						if(target.size()) {
							var top = target.offset().top;
							$t.animate({scrollTop:top}, 800, 'easeOutQuad');
						}
						return false;
					}

					$('a[href^=#]')
						.unbind("click",smoothScroll)
						.bind("click",smoothScroll);
				}

				setup.css3Utils = (function(){

					var css3Utils = function(){
						css3Utils.firstChild();
						css3Utils.lastChild();
						css3Utils.evan();
						css3Utils.odd();
					}

					css3Utils.firstChild = function(){
						css3Utils._set(":first-child","first-chlid");
					}

					css3Utils.lastChild = function(){
						css3Utils._set(":last-child","last-chlid");
					}

					css3Utils.nthChild = function(nth,className){
						css3Utils._set(":nth-chlid(" + nth + ")", className);
					}

					css3Utils.evan = function(){
						css3Utils._set(":even","even");
					}

					css3Utils.odd = function(){
						css3Utils._set(":odd","odd");
					}

					css3Utils._set = function(selecter,className){
						css3Utils._clear(className);

						$("ol > li" + selecter).addClass(className);
						$("dl > dt" + selecter).addClass(className);
						$("dl > dd" + selecter).addClass(className);
						$("tr > th" + selecter).addClass(className);
						$("tr > td" + selecter).addClass(className);
						$("table > tr" + selecter).addClass(className);
						$("thead > tr" + selecter).addClass(className);
						$("tbody > tr" + selecter).addClass(className);
						$("tfoot > tr" + selecter).addClass(className);
					},

					css3Utils._clear = function(className){
						$("."+className).removeClass(className);
					}

					return css3Utils;
				})()

				setup.formUtils = function(){
					$("input,textarea,select")
						//.focus(function(){$(this).addClass("focus")})
						//.blur(function(){$(this).removeClass("focus")})
						.hover(function(){
								$(this).addClass("hover")
							},function(){
								$(this).removeClass("hover")
							});
				}

				return setup;
			})()
		}
	})


	$(function(){
		$.uif.setup();


		// message hide;
		$(".warning_message, .notice_message, .info_message")
			.click(function(){
				var $t = $(this);
				$t.fadeOut(500,function(){
					$t.remove();
				})
			})

		//テキストフィールドのデフォ値
		if($(".shadow_text").size()){
			$('.shadow_text').each(function(){
				var $t = $(this);
				var word = $t.attr('title');
				$t.focus(function(){
					if($t.val() == word){
						$t.val('');
					}
					$t.removeClass('shadow_text');
				})
				$t.blur(function(){
					if($t.val() == ''){
						$t.val(word);
						$t.addClass('shadow_text');
					}
				})

				$t.parents('form').submit(function(){
					if($t.val() == word){
						$t.val('');
					}
				})

				if($t.val() == '' ){
					$t.val(word);
					$t.addClass('shadow_text');
				}else
				if($t.val() != word){
					$t.removeClass('shadow_text');
				}
			});
		}

		//グローバルの検索
		$("#navi_keyword_search form, #foot_search_keyword form").submit(function(){
				var $t = $(this);
				if($t.find('.shadow_text').size()){
					return false;
				}
				var $cat = $t.find('.keyword_search_category');
				if($cat.size()){
					if($cat.is('select')){
						this.action = $cat.val();
					}else{
						this.action = $cat.find(':checked').val();
					}
				}
		})

		$("#global_navi li:has('.sub_global_navi')").each(function(){
				var $t = $(this);
				var $a = $t.find("> a")
				var $sub = $t.find(".sub_global_navi");
				$t.mouseenter(function(){ 	$sub.css("display","block"); })
					.mouseleave(function(){	$sub.css("display","none"); })
				$a.click(function(){ return false });

				$sub.css("display","none");
		})


		// 画像の遅延読み込み
		if($.fn.lazyload){
			$("img.lazyload").lazyload({
					placeholder : "/img/front/common/s.gif",
					effect : "fadeIn"
			});
		}
		
		//clickable_table
		if($('.clickable_table').size()){
			$('.clickable_table tbody td')
				.mouseover(function(){
						$(this).parents('tr').not(".secret").addClass('hover');
				})
				.mouseout(function(){
						$(this).parents('tr').not(".secret").removeClass('hover');
				})
				.click(function(){
					var $t = $(this);
					$t.unbind('mouseover').unbind('mouseout').unbind('click');
					window.location = $t.parents('tr').find('a:eq(0)').attr('href');
				})
		}


		//google map
		$(".gmap").each(function(){
			var $t = $(this);
			var lat = $t.find('.latitude').text();
			var lng = $t.find('.longitude').text();

			if(!!lat && !!lng){

				var latlng = new google.maps.LatLng(lat, lng, true);
				var classList = $t.attr("class");

				var use_ui = classList.indexOf('use_ui') != -1;
				var use_street = $t.find('.street').size() > 0;
				var zoom = 14;

				var reg = new RegExp(/^zoom\[(.*)\]$/)
				classList = classList.split(" ");
				$.each(classList,function(index, elem){
						if(reg.test(elem)){
							zoom = RegExp.$1;
							return false;
						}
				})

				var node;
				if($t.find('.road').size()){
					node = $t.find('.road').get(0);
				}else{
					node = $t.get(0);
				}

				var gmap = new google.maps.Map(node,{
						zoom : parseInt(zoom),
						center : latlng,
						disableDefaultUI : !use_ui,
						keyboardShortcuts : use_ui,
						streetViewControl: use_street,
						mapTypeId: google.maps.MapTypeId.ROADMAP
				});

				new google.maps.Marker({
					clickable : false,
					position : latlng,
					map : gmap
				})

				if(use_street){
					var gStreetView = new google.maps.StreetViewPanorama($t.find('.street').get(0),{
						pov : {
							heading: 0,
          		pitch: 1,
          		zoom: 0
        		}
					})
					gmap.setStreetView(gStreetView);

					var radius = 50;
					var client = new google.maps.StreetViewService();
					var callback = function(result, status) {
						if (status == google.maps.StreetViewStatus.OK) {
							gStreetView.setPosition(result.location.latLng);
						}else
						if(status == google.maps.StreetViewStatus.ZERO_RESULTS){
							radius += 50;
							client.getPanoramaByLocation(latlng, radius, callback);
						}
					}
					client.getPanoramaByLocation(latlng, radius, callback);

				}
			}
		})

	});

})(jQuery);



