/**
 * 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            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
        }
        // CAUTION: 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;
    }
};


if(!window.jQuery){throw("jQuery must be referenced before using the 'onImagesLoad' plugin.");}
/* 
* jQuery 'onImagesLoaded' plugin 1.0.5
* Fires a callback function when all images have loaded within a particular selector.
*
* Copyright (c) Cirkuit Networks, Inc. (http://www.cirkuit.net), 2008.
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* For documentation and usage, visit "http://includes.cirkuit.net/js/jquery/plugins/onImagesLoad/1.0/documentation/"
*/
(function($){
  $.fn.onImagesLoad = function(options){
    var opts = $.extend({}, $.fn.onImagesLoad.defaults, options);

    return this.each(function(){
      var container = this;
      var $imgs = $('img', container);
      if($imgs.length === 0 && opts.callbackIfNoImagesExist && opts.callback){
        opts.callback(container); //call callback immediately if no images were in selection
      }
      var loadedImages = [];
      $imgs.each(function(i, val){
        $(this).bind('load', function(){
          if(jQuery.inArray(i, loadedImages) == -1){ //don't double count images
            loadedImages.push(i); //keep a record of images we've seen
            if(loadedImages.length == $imgs.length){
              if(opts.callback){ opts.callback(container); }
            }
          }
        }).each(function(){
          if(this.complete || this.complete===undefined){ this.src = this.src; } //needed for potential cached images
        });
      });
    });
  };
  
  $.fn.onImagesLoad.defaults = {
    callback: null, //the function you want called when all images within $(yourSelector) have loaded
    callbackIfNoImagesExist: true //if no images exist within $(yourSelector), should the callback be called?
  };
  
})(jQuery);


/* Smooth scrolling
   Changes links that link to other parts of this page to scroll
   smoothly to those links rather than jump to them directly, which
   can be a little disorienting.
   
   sil, http://www.kryogenix.org/
   
   v1.0 2003-11-11
   v1.1 2005-06-16 wrap it up in an object
*/

var ss = {
  fixAllLinks: function() {
    // Get a list of all links in the page
    var allLinks = document.getElementsByTagName('a');
    // Walk through the list
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) && 
          ( (lnk.pathname == location.pathname) ||
	    ('/'+lnk.pathname == location.pathname) ) && 
          (lnk.search == location.search)) {
        // If the link is internal to the page (begins in #)
        // then attach the smoothScroll function as an onclick
        // event handler
        if ( !(lnk.getAttribute("rel") == "noscroll") ) {
          ss.addEvent(lnk,'click',ss.smoothScroll);
        }
      }
    }
  },

  smoothScroll: function(e) {
    // This is an event handler; get the clicked on element,
    // in a cross-browser fashion
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;

    // Make sure that the target is an element, not a text node
    // within an element
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }
  
    // Paranoia; check this is an A tag
    if (target.nodeName.toLowerCase() != 'a') return;
  
    // Find the <a name> tag corresponding to this href
    // First strip off the hash (first character)
    anchor = target.hash.substr(1);
    // Now loop all A tags until we find one with that name
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }
    if (!destinationLink) destinationLink = document.getElementById(anchor);

    // If we didn't find a destination, give up and let the browser do
    // its thing
    if (!destinationLink) return true;
  
    // Find the destination's position
    var destx = destinationLink.offsetLeft; 
    var desty = destinationLink.offsetTop;
    var thisNode = destinationLink;
    while (thisNode.offsetParent && 
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }
  
    // Stop any current scrolling
    clearInterval(ss.INTERVAL);
  
    cypos = ss.getCurrentYPos();
  
    ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
    ss.INTERVAL = setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
  
    // And stop the actual click happening
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
  },

  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ss.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ss.getCurrentYPos();
    isAboveNow = (iscypos < dest);
    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
      // if we've just scrolled past the destination, or
      // we haven't moved from the last scroll (i.e., we're at the
      // bottom of the page) then scroll exactly to the link
      window.scrollTo(0,dest);
      // cancel the repeating timer
      clearInterval(ss.INTERVAL);
      // and jump to the link directly so the URL's right
      // location.hash = anchor;
    }
  },

  getCurrentYPos: function() {
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
  },

  addEvent: function(elm, evType, fn, useCapture) {
    // addEvent and removeEvent
    // cross-browser event handling for IE5+,  NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  } 
}

ss.STEPS = 25;

ss.addEvent(window,"load",ss.fixAllLinks);



/* =====================================================================
*
*    User Plugin :: Browser Selection
*
* =================================================================== */

var os;
var uAgent = navigator.userAgent.toUpperCase();
if (uAgent.indexOf("MAC") >= 0) { os = "Mac"; }
if (uAgent.indexOf("WIN") >= 0) { os = "Win"; }
if (uAgent.indexOf("X11") >= 0) { os = "UNIX"; }
if (uAgent.indexOf("WINDOWS NT 6") >= 0) { os = "Vista"; }

var browser;
var aName = navigator.appName.toUpperCase();
var uName = navigator.userAgent.toUpperCase();
if (uName.indexOf("SAFARI") >= 0) { browser = "Safari"; }
if (uName.indexOf("OPERA") >= 0) { browser = "Opera"; }
if (uName.indexOf("FIREFOX") >= 0) { browser = "Firefox"; }
if (uName.indexOf("FIREFOX/3") >= 0) { browser = "Firefox3"; }
if (uName.indexOf("NETSCAPE") >= 0) { browser = "Netscape"; }
if (aName.indexOf("MICROSOFT") >= 0) { browser = "Explorer"; }


/* ---------------------------------
*    Apply CSS to Mac Firefox 2.x
*/

var cssScript = '';

if (browser == "Firefox" && os == "Mac") {
	cssScript += '<link rel="stylesheet" href="/common/css/ff.css" type="text/css" media="screen, tv" />'; 
	document.writeln(cssScript);
}



/* =====================================================================
*
*    検索
*
* =================================================================== */


/* ---------------------------------
*    Search Type の切換
*/

function changeSubmit(pushBtn) {
	switch(pushBtn) {
		case "tagBtn":
			document.headSearch.searchType[0].checked = false;
			document.headSearch.searchType[1].checked = true;
			document.getElementById('tagBtn').className = "on";
			document.getElementById('contentBtn').className = "off";
			$.cookie("searchType", "tagBtn", { expires: 7, path: "/" });
			break;
		case "contentBtn":
			document.headSearch.searchType[0].checked = true;
			document.headSearch.searchType[1].checked = false;
			document.getElementById('tagBtn').className = "off";
			document.getElementById('contentBtn').className = "on";	
			$.cookie("searchType", "contentBtn", { expires: 7, path: "/" });
			break;
		default:
			return false;
	}
}


/* ---------------------------------
*    検索処理
*/


function doSearch() {
	var query = $("#search").val().replace(/ /g, "+");

	if ( query != "") {
		st = $("#searchTypeBox input[@type='radio']:checked").val();

		var url_base;
		
		switch (st) {
			case "contentSearch":
				url_base = "/search/";
				break;
			case "tagSearch":
				url_base = "/tag/";
				break;
			default:
				url_base = "/search/";
		}
		
		var url = url_base + query;
		location.href = url;
	} else {
		return false;
	}
}



/* =====================================================================
*
*    Remember Me
*
* =================================================================== */

function remember(o) {
	if ($("#comment-bake-cookie").attr("checked") == true) {
		document.getElementById('rememberBtn').className = "on";
	}
	else {
		document.getElementById('rememberBtn').className = "off";
	}
	mtRememberMeOnClick(o);
}



/* =====================================================================
*
*    Archive Accordion
*
* =================================================================== */

function accord(HEADER) {
	jQuery().ready( function() {
		var acHeader = HEADER + ".accord";
		jQuery('#arcListCont').accordion({
			autoheight: false,
			header: acHeader,
			event: "mouseover"
		});
	});
}


/* =====================================================================
*
*    ページロード時の処理
*
* =================================================================== */

/* ---------------------------------
*    検索ボックス
*/


$(document).ready( function() {
	$("#search").keypress(function(e) {
		if (e.which == "13") {
			doSearch();
			return false;
		}
	});
	$("#submitBtn input").click(function() {
		doSearch();
	});
	
	changeSubmit($.cookie("searchType"));
});

