var quick_search_cnt = 0;
var da = new Array();

function quick_search_chk(){
	if(quick_search_cnt == 0) {
		quick_search_cnt = 1;
		document.quick_search.submit();
	}
}

htmlspecialchars = function(ch) {
    ch = ch.replace(/&/g,"&amp;") ;
    ch = ch.replace(/"/g,"&quot;") ;
    ch = ch.replace(/'/g,"&#039;") ;
    ch = ch.replace(/</g,"&lt;") ;
    ch = ch.replace(/>/g,"&gt;") ;
    return ch ;
};

m_win = function(url,windowname,width,height) {
 var features="location=no, menubar=no, status=no, scrollbars=yes,resizable=yes, toolbar=no";
 if (width) {
  if (window.screen.width > width)
   features+=", left="+(window.screen.width-width)/2;
  else width=window.screen.width;
  features+=", width="+width;
 }
 if (height) {
  if (window.screen.height > height)
   features+=", top="+(window.screen.height-height)/2;
  else height=window.screen.height;
  features+=", height="+height;
 }
 window.open(url,windowname,features);
};

function wdoc(url,cs,as){
    if(cs == undefined){
	cs = 'shift-jis';
    }
    if(as == undefined){
	as = '';
    }else{
	as = 'async';
    }
    
    document.write('<scr'+'ipt src="' + url + '" charset="' +cs+ '" ' +as+ '></scr' + 'ipt>');
}
function idoc(url,id){
	if(id != undefined){
	  jQuery('#'+id).append('<ifr'+'ame src="' + url + '" id="iframe' + id + '"' + ' style="display:none;"></ifr' + 'ame>');
	}else{
      document.write('<ifr'+'ame src="' + url + '" style="display:none;"></ifr' + 'ame>');
    }
}
function wasyn(url,id){
    var ele = document.createElement("script");
    ele.type = "text/javascript";
    ele.src = url;
    jQuery(id)[0].appendChild(ele);
}
function iasyn(url,id){
	s = '<ifr'+'ame src="' + url + '" style="display:none;"></ifr' + 'ame>';
    jQuery(id).append(s);
}
function debugvar(da){
	for(i in da){ jQuery("#headerArea").append( i + ': "' + da[i] + '"<br>' ); }
}
function replaceAll(expression, org, dest){  
    return expression.split(org).join(dest);  
}  
function fEventAdd(el,fs){

  var tfunc = function(){
        if( jQuery(el).length!=0 ){ eval(fs);clearInterval(timer); }
  }
  var timer = setInterval(tfunc,1000);
}
function uriShorten(){
      var longUrl = "http://journal.mycom.co.jp" + window["canoBase"];
      var LOGIN = "mycomj";
      var API_KEY = "R_ccb5095fd4192be1a7954225ce47cdf9";

      $.ajax({
        type: "GET",
        url: "http://api.j.mp/shorten?version=2.0.1&longUrl=" + encodeURIComponent(longUrl) + "&login=" + LOGIN + "&apiKey=" + API_KEY,
        dataType: "jsonp",
        success: function(data) {
            if (data.results && data.results[longUrl]["shortUrl"]) {
                   setsUrl(data.results[longUrl]["shortUrl"]);
            }
        }
      });
}
function printDisp(){
  if( window.confirm('印刷用ページを表示します') ){
    location.href = window['canoBase'] + '?lazy=off';
  }
}
function printEvent(){
  if( getParam("lazy") == "" ){
    jQuery("p.printBtn a").attr('href','javascript:void(0)');
    jQuery("p.printBtn a").unbind().click(function(){printDisp();return false});
  }
}
function getParam(param) {
  var q = document.location.search || document.location.hash;
  if (param == null) { return q; }
  if(q) {
    var pairs = q.substring(1).split("&");
    for (var i=0; i < pairs.length; i++) {
      if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
        return pairs[i].substring((pairs[i].indexOf("=")+1));
      }
    }
  }
  return "";
}
function getCDN(src){ 
	if( src.match(/news.mynavi.jp/) ){
		src = src.replace(/news.mynavi/,"n.mynv");
	}else if( src.match(/^\//) ){
		src = "http://n.mynv.jp" + src;
	}else if( src.match(/^images/) ){
		location.href.match(/.*\//);
		src = RegExp.lastMatch.replace(/news.mynavi/,"n.mynv") + src;
	}
  return src;
}

var news_func = { scroll:{height:1,avg:0,sigma:0} };
curVer = "100510";
adomain = "http://news.kali.mynavi.jp/js.ng/site=journal&SpaceDesc=";

var sc_callback = function(data){
}

var tileid1=Math.floor(1000000*Math.random());var tileid2=Math.floor(1000000*Math.random());var tileid3=Math.floor(1000000*Math.random());

news_func.loadDisqus = function(){
  var disqus_shortname = 'mynavi-news-mj05';
  var disqus_title = 'マイナビニュース';

  if( $("#disqus_thread").length!=0 ){

    $(function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async=true;
        dsq.charset = 'utf-8';
	dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    });
  }
}

news_func.scrollTo = function(ele){
  $('html, body').animate({scrollTop:$(ele).offset().top -10});
}

news_func.scrollTop = function(){
  return (document.documentElement.scrollTop || document.body.scrollTop);
}

news_func.authDisqus = function(sv){
  this.scrollTo("#disqus_thread");

  if( $("span.dsq-share-"+sv).length == 0 ){
    return DISQUS.dtpl.actions.fire('auth.'+sv);
  }else if( !$("span.dsq-share-"+sv).attr("class").match(/toggled/) ){
    $("span.dsq-share-"+sv).toggleClass("dsq-share-toggled");
    DISQUS.dtpl.actions.fire('share.toggle', this, sv, null);
  }
} 

news_func.appendCSS = function(file){
  var headID = document.getElementsByTagName("head")[0];
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'stylesheet';
  cssNode.href = file;
  cssNode.media = 'screen';
  headID.appendChild(cssNode);
}

news_func.appendJS = function(file){
  var headID = document.getElementsByTagName("head")[0];         
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = file;
  headID.appendChild(newScript);
}

news_func.islogin = function(){
  if(!$.cookie('MsA5')){
    return false;
  }else{
    return { "job1":$.cookie('MsA1'),"job2":$.cookie('MsA2'),"job3":$.cookie('MsA3'),"age":$.cookie('MsA4'),"sex":$.cookie('MsA5'),"ken":$.cookie('MsA6') };
  }
}

news_func.test = function(){
  var err = "";
  if( !window["news_vars"]){
    err += "  news_vars";
  }else{
    if( !news_vars.canoBase){
      err += "  canoBase(afterGA)";
    }
    if( !news_vars.end){
      err += "  end_of_footer";
    }
  }
  if(err !=""){
     alert(err);
  }
}

news_func.purenews = function(){
  if(location.href.match(/(http...news.mynavi.jp)|(http.*pc.mycom.co.jp)/) && !location.href.match(/http...news.mynavi.jp\/r_/) && !$("body").attr("class").match(/kakakuChild/) ){
	return true;
  }else{ return false; }
}

news_func.shuffle = function(list) {
  var i = list.length;

  while (--i) {
    var j = Math.floor(Math.random() * (i + 1));
    if (i == j) continue;
    var k = list[i];
    list[i] = list[j];
    list[j] = k;
  }

  return list;
}

function tbadge(account, design, color, side, top)
{
	top = parseInt(top);
	
	box_style='position:fixed; top:'+top+'px; z-index:6000; cursor:pointer; '+side+': 0px;';
	label_style='position:fixed; z-index:7000; cursor:pointer; '+side+': 0px;';

	var designs = new Array();
	designs['left'] = new Array(
		'',
		'<div id="tbadge_box" style="'+box_style+' color: '+color+'; width:35px; height:120px;  background: '+color+' url(http://twitbtn.com/ui/images/tbadge/02_l.png) no-repeat;"></div><div id="tbadge_label" style="'+label_style+' top:'+(top+120)+'px; width: 35px; height: 20px; background: url(http://twitbtn.com/ui/images/tbadge/copy_l1.png) no-repeat;">&nbsp;</div>',
		''
	);

	if(document.getElementById('tbadge'))
		document.body.removeChild(document.getElementById('tbadge'));

	init = document.createElement('div');
	init.setAttribute('id','tbadge');
	document.body.appendChild(init);
	
	init.innerHTML = designs[side][design-1] + '<style>#tbadge_label{visibility:hidden;} #tbadge:hover #tbadge_label{visibility:visible;}</style>';
	
	document.getElementById('tbadge_box').onclick=function(){
		window.open('http://twitter.com/'+account);
	}
	
	document.getElementById('tbadge_label').onclick=function(){
		window.open('http://twitbtn.com/');
	}
}

jQuery.cookie = function (key, value, options) {

    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

(function($) {

    $.fn.lazyload = function(options) {
        var settings = {
            threshold    : 0,
            failurelimit : 0,
            event        : "scroll",
            effect       : "show",
            container    : window
        };
                
        if(options) {
            $.extend(settings, options);
        }

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        var elements = this;
        if (0 == settings.event.indexOf("scroll")) {
            $(settings.container).bind(settings.event, function(event) {
                var counter = 0;
                elements.each(function() {
                    if ($.abovethetop(this, settings) ||
                        $.leftofbegin(this, settings)) {
                            /* Nothing. */
                    } else if (!$.belowthefold(this, settings) &&
                        !$.rightoffold(this, settings)) {
                            $(this).trigger("appear");
                    } else {
                        if (counter++ > settings.failurelimit) {
                            return false;
                        }
                    }
                });

                /* Remove image from array so it is not looped next time. */
                var temp = $.grep(elements, function(element) {
                    return !element.loaded;
                });
                elements = $(temp);

            });
        }
        
        this.each(function() {
            var self = this;            
            self.loaded = false;
            
            /* When appear is triggered load original image. */
            $(self).one("appear", function() {
                if (!this.loaded) {
                    $("<img />")
                        .bind("load", function() {
                            $(self)
                                .hide()
                                .attr("src", $(self).data("original"))
                                [settings.effect](settings.effectspeed);
                            self.loaded = true;
                        })
                        .attr("src", $(self).data("original"));
                    if($(self).data("original")=="http://n.mynv.jp/images/common/fb2.gif"){  news_func.loadDisqus();
			if( news_func.scrollTop() > 300 ){
			  $("#socialBookmarkList").appendTo("div.str-icon-social:eq(1)");}
		    }
                };
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if (0 != settings.event.indexOf("scroll")) {
                $(self).bind(settings.event, function(event) {
                    if (!self.loaded) {
                        $(self).trigger("appear");
                    }
                });
            }
        });
        
        /* Force initial check if images should appear. */
        $(settings.container).trigger(settings.event);
        
        return this;

    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $(element).offset().top - settings.threshold;
    };
    
    $.rightoffold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $(element).offset().left - settings.threshold;
    };
        
    $.abovethetop = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };
    
    $.leftofbegin = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };
    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() */

    $.extend($.expr[':'], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0, container: window}) },
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0, container: window}) },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0, container: window}) },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0, container: window}) }
    });
    
})(jQuery);

/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#",
		prev_text:"前のページ",
		next_text:"次のページ",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}
		
		/**
		 * Calculate start and end point of pagination links depending on 
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}
		
		/**
		 * This is the event handling function for the pagination links. 
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ if($("#pagingContent").attr("data-long")=="1"){eval('news_func.scrollTo("#pagingContent");')};_gaq.push(['_trackEvent', 'innerPage', news_vars.canoBase, 'pageClick', page_id, true]);return pageSelected(page_id,evt); }
			}
			// Helper function for generating a single link (or a span tag if it's the current page)
			var appendItem = function(page_id, appendopts){
				page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
				appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
				if(page_id == current_page){
					var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/,page_id));
						
						
				}
				if(appendopts.classes){lnk.addClass(appendopts.classes);}
				panel.append(lnk);
			}
			// Generate "Previous"-Link
			if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
				appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
			}
			// Generate starting points
			if (interval[0] > 0 && opts.num_edge_entries > 0)
			{
				var end = Math.min(opts.num_edge_entries, interval[0]);
				for(var i=0; i<end; i++) {
					appendItem(i);
				}
				if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
			}
			// Generate interval links
			for(var i=interval[0]; i<interval[1]; i++) {
				appendItem(i);
			}
			// Generate ending points
			if (interval[1] < np && opts.num_edge_entries > 0)
			{
				if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
				var begin = Math.max(np-opts.num_edge_entries, interval[1]);
				for(var i=begin; i<np; i++) {
					appendItem(i);
				}
				
			}
			// Generate "Next"-Link
			if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
				appendItem(current_page+1,{text:opts.next_text, classes:"next"});
			}
		}
		
		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);
		// Attach control functions to the DOM element 
		this.selectPage = function(page_id){ pageSelected(page_id);}
		this.prevPage = function(){ 
			if (current_page > 0) {
				pageSelected(current_page - 1);
				return true;
			}
			else {
				return false;
			}
		}
		this.nextPage = function(){ 
			if(current_page < numPages()-1) {
				pageSelected(current_page+1);
				return true;
			}
			else {
				return false;
			}
		}
		// When all initialisation is done, draw the links
		drawLinks();
        // call callback function
        opts.callback(current_page, this);
	});
}



