/*
 * common.js
 * 
 * depends jquery.js;
 * 
 */

(function($) {

	$(function() {

		// JavaScript enabled?
		$('body').addClass('js-enabled');

		// input type
		$().inputType();

		// グローバルナビゲーション
		$('#nav-global a:not(.current a)').fadeInOut(200, 400);
		$('.history-back a, .teacher-index a').fadeInOut(400, 400);

		// Popup
		$('.popup').popup(768, 576);
		$('#banner-pamph a').popup(1010, 655);

		// Section
		$('.section:last-child').addClass('last-section');

		// マルチカラム
		$('.cols-1').cols(1);
		$('.cols-2').cols(2);

		// Pic
		$('.pic img:last-child').addClass('last-child');

		// Links
		$('[href^="http"]').each(function() {
			if (this.hostname != window.location.hostname) {
				$(this).addClass('external');
			}
		});
		$('a[href$=".pdf"]').addClass('pdf external');
		$('a.external').not('#banner-pamph a').openWindow();

		// News
		$('.news')
			.find('.title:not(:has(a))').wrapInner('<span class="no-link"></span>').end()
			.find('.title a, .no-link').inlineBgFix();

		// Tabs
		$('.tabs').tabs();

		// Rollovers
		$('.btn').rollover();

		// Animated Scrolling: depends jQuery Easing v1.3
		$('.back-to-top a').backToTop();
		$('.toc a').animateScroll();

		// Inline-List
		$('.inline-list').inlineList();
		$('.links ul ul').inlineList({ delimiter: ' |' });

	});

	// クリックで新規ウィンドウを開く
	$.fn.openWindow = function() {
		$(this).click(function() {
			window.open(this.href);
			return false;
		});
		return this;
	}

	// ポップアップ
	$.fn.popup = function(w, h) {
		$(this).click(function() {
			window.open(this.href, 'popup', 'width=' + w + ',height=' + h + ',location,menubar,resizable,scrollbars,status,toolbar');
			return false;
		});
		return this;
	}

	// Fade-In/Out
  $.fn.fadeInOut = function(speedIn, speedOut) {
		$(this)
			.css('backgroundImage', 'none')
			.hover(function() {
				$(this).append('<span class="fx"></span>');
				$(this).find('.fx').css('display', 'none').fadeIn(speedIn);
			}, function() {
				$(this).find('.fx').fadeOut(speedOut, function() {
					$(this).remove();
				});
			});
		return this;
  }

	// Rollover
	$.fn.rollover = function() {
		$(this).each(function() {
			this.normalSrc = $(this).attr('src');
			this.hoverSrc = this.normalSrc.replace(/(\.gif|\.jpg|\.png)/, '-h$1');
			this.hoverImg = new Image;
			this.hoverImg.src = this.hoverSrc;
		}).hover(function() {
			$(this).attr('src', this.hoverSrc);
		}, function() {
			$(this).attr('src', this.normalSrc);
		});
		return this;
	}

	// マルチカラム
  $.fn.cols = function(c) {
    $(this).each(function() {
      var col = $(this).children('.col');
			var r = col.length % c;
			/*
      col
        .filter(':nth-child(' + c + 'n+1)').addClass('first-in-row').end()
        .filter(':nth-child(' + c + 'n)').addClass('last-in-row');
			*/
			if (r == 0) {
        col.filter(':nth-child(n+' + (col.length - c + 1) + ')').addClass('last-row');
			} else {
				for (var i = 0; i < r; i ++) {
					col.filter(':nth-child(' + (col.length - i) + ')').addClass('last-row remainder last-' + (i + 1));
				}
			}
    });
		return this;
  }

	// タブ
	$.fn.tabs = function(options) {
		var o = $.extend({
			selected: 0
		}, options);
		$(this).each(function(i) {
			var tabsName = 'tabs-' + (i + 1);
			var tabsNav = $(this).children('ul');
			var tabsBody = $(this).children('div');
			$(tabsNav).addClass('tabs-nav').children('li').each(function(j) {
				$(this).addClass('tab-' + (j + 1));
			});
			$(tabsBody).addClass('tabs-body');
			var c = $.cookie(tabsName);
			if (c) {
				o.selected = c;
			}
			selectTabs(o.selected);
			$(tabsNav).find('[href^="#"]').click(function() {
				selectTabs($(tabsNav).children('li').index($(this).parent('li')));
				return false;
			});
			function selectTabs(index) {
				$(tabsBody).hide();
				$(tabsNav)
					.children('.tabs-nav-selected').removeClass('tabs-nav-selected').end()
					.children('li').eq(index).addClass('tabs-nav-selected');
				$($(tabsNav).find('.tabs-nav-selected a').attr('href')).show();
				$.cookie(tabsName, index);
			}
		});
		return this;
	}
		
	// Back-to-Top
	$.fn.backToTop = function() {
		var elem = $.browser.opera? 'html': 'html, body';
		$(this).click(function() {
			$(elem).animate({scrollTop: 0}, 800, 'easeOutExpo');
			return false;
		});
	}

	$.fn.animateScroll = function() {
    $(this).click(function() {
			if ($.browser.opera || ($.browser.msie && $.browser.version == 7.0)) return;
      var targetOffset = $(this.hash).offset().top;
      var documentHeight = $(document).height();
      var windowHeight = $(window).height();
				if ((documentHeight - targetOffset) < windowHeight) {
					targetOffset = (documentHeight - windowHeight);
				}
      $('html, body').animate({scrollTop: targetOffset}, 800, 'easeOutExpo');
    });
		return this;
	}

	// IE6/7 で改行を含むインライン要素に指定した背景画像の表示位置がずれるバグに対処
	$.fn.inlineBgFix = function() {
		if ($.browser.msie && $.browser.version < 8.0) {
			$(this)
				.addClass('inline-bg-fix')
				.prepend('<span class="bg-l">&nbsp;</span>')
				.append('<span class="bg-r">&nbsp;</span>');
		}
		return this;
	}

	// Inline-List
	$.fn.inlineList = function(options) {
		var o = $.extend({
			children: 'li',
			delimiter: '&nbsp;/'
		}, options);
		var selector = o.children + ':not(:last-child)';
		$(this).children(selector).append(o.delimiter);
		return this;
	}

	// :first-child, :last-child
	$.fn.firstChild = function() {
		$(this).find(':first-child').addClass('first-child')
		return this;
	}
	$.fn.lastChild = function() {
		$(this).find(':last-child').addClass('last-child')
		return this;
	}
	
	$.fn.inputType = function() {
		$('input').each(function() {
			$(this).addClass($(this).attr('type'));
		});
	}

})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright c 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend(jQuery.easing, {
	def: 'easeOutExpo',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	}
});
/*
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright c 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

