var URL_ROOT = (location.href.match(/^https:/) ? 'https://' : 'http://') + location.hostname + (location.port == 80 ? '' : ':' + location.port) + '/';
var URL_PAGE = location.pathname.replace(/(\..+)$/, '');
URL_PAGE = URL_PAGE.substring(URL_PAGE.indexOf('/') + 1);
if(URL_PAGE.indexOf('/') != -1){
	URL_PAGE = URL_PAGE.substring(0, URL_PAGE.indexOf('/'));
}


/*-- common --*/
function dw(obj){
	alert(var_dump(obj));
}
function var_dump(obj) {
	if(typeof(obj) == "object") {
		return "Type: "+ typeof(obj) + ((obj.constructor) ? "\nConstructor: "+ obj.constructor : "") + "\nValue: " + obj;
	}else{
		return "Type: " + typeof(obj) + "\nValue: " + obj;
	}
}

function getUnixTime(date){
	if(!date){
		date = new Date();
	}
	return ~~(date/1000);
}

function myRand(max){
	if(max == undefined){
		max = 10000000;
	}
	var ret = max * Math.random();
	if(ret == 0.0){
		ret = 1;
	}else{
		ret = Math.ceil(ret)
	}
	return ret;
}

String.prototype.nl2br = function(){
	return this.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\r?\n/g, '<br />');
}

String.prototype.escapeHtml = function(){
	return this.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

String.prototype.replaceAnchor = function(){
	return this.replace(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/g,"<a href='$1' class='outlink' target='_blank' rel='nofollow'>$1</a>");
}

String.prototype.format = function(format){
	switch(format){
		case 'num':
			var ret = this.replace(/,/g, '');
			while(ret != (ret = ret.replace(/^(-?\d+)(\d{3})/, '$1,$2')));
			return ret;
			break;
		case 'zip':
			var ret = this.replace(/-/, '');
			if(ret.length > 3){
				ret = ret.substring(0, 3) + ret.substring(3);
			}
			return ret;
			break;
		default:
			return this;
	}
}

String.prototype.trim = function(){
	return this.replace(/^[\s　]+|[\s　]+$/g, '');
}

Date.prototype.toYmd = function(){
	return this.getFullYear() + '-' + ('00' + (this.getMonth() + 1)).slice(-2) + '-' + ('00' + this.getDate()).slice(-2);
}


function isSmartphone(){
	var useragents = [
		'iPhone',// Apple iPhone
		'iPod',// Apple iPod touch
		'Android',// 1.5+ Android
		'dream',// Pre 1.5 Android
		'CUPCAKE',// 1.5+ Android
		'blackberry',// blackberry
		'webOS',// Palm Pre Experimental
		'incognito',// Other iPhone browser
		'webmate'// Other iPhone browser
	];
	var pattern = new RegExp(useragents.join('|^'), 'i');
	return pattern.test(navigator.userAgent);
}

function timestamp(){
	var now_time = new Date();
	return now_time.getTime();
}

function compact(obj){
	for(var field in obj){
		if(field != undefined && ((obj[field] == null) || (obj[field] == undefined))){
			delete obj[field];
		}
	}
	return obj;
}

// デフォルトの処理を無効にする
function preventDefault(e){
	if(e.preventDefault){
		e.preventDefault();
	}else if(window.event){
		window.event.returnValue = false;
	}
}

function innerScroll(selecter, speed){
	if($(selecter).size() == 0){
		return;
	}
	if(speed == null){
		speed = 'slow';
	}
	$('html,body').animate(
		{scrollTop: $(selecter).offset().top - 103}
		, {easing: 'easeOutExpo', duration : speed}
	); 
}


var state_simple_modal = 0;
function loadSimpleModal(){
	if(state_simple_modal == 0)(function(){
		if(_helperLoadSimpleModal() != 2){
			setTimeout(arguments.callee, 100);
		}
	})();
}
function _helperLoadSimpleModal(){
	if(state_simple_modal == 0){
		state_simple_modal = 1;
		$('head').append(
			'<link type="text/css" href="/_style/simple_modal/basic.css" rel="stylesheet" media="screen" chatset="utf-8" />'
		);
		if($.browser.msie6){
			$('head').append(
				'<link type="text/css" href="/_script/simple_modal/basic_ie6.css" rel="stylesheet" media="screen" chatset="utf-8" />'
			);
		}
		$.getScript('/_script/jquery.simplemodal.js', function(){
			state_simple_modal = 2;
		});
	}
	return state_simple_modal;
}

var state_ajax_upload = 0;
function loadAjaxFileload(){
	if(state_ajax_upload == 0)(function(){
		if(_helperLoadAjaxFileload() != 2){
			setTimeout(arguments.callee, 100);
		}
	})();
}
function _helperLoadAjaxFileload(){
	if(state_ajax_upload == 0){
		state_ajax_upload = 1;
		$.getScript('/_script/ajaxfileupload.js', function(){
			state_ajax_upload = 2;
		});
	}
	return state_ajax_upload;
}

function initImageFunc(){
	if($.fn.fitParent){
		return;
	}
	$.fn.extend({
		'fitParent' : function() {
			this.each(function(){
				var img_width = $(this).width();
				var img_height = $(this).height();
				var parent_width = $(this).parent().width();
				var parent_heght = $(this).parent().height();
				var margin_left, margin_top;
				
				if(img_width > parent_width){
					img_height = parent_width / img_width * img_height;
					img_width = parent_width;
				}
				if(img_height > parent_heght){
					img_width = parent_heght / img_height * img_width;
					img_height = parent_heght;
				}
				margin_top = (parent_heght - img_height) / 2;
				margin_left = (parent_width - img_width) / 2;
				
				$(this).css({
					'height' : img_height + 'px'
					, 'width' : img_width + 'px'
					, 'margin-top' : margin_top + 'px'
					, 'margin-left' : margin_left + 'px'
				});
			});
		}
		, 'setImage' : function(info) {
			if(!info['thumb_height']){
				info['thumb_height'] = 360;
			}
			if(!info['thumb_width']){
				info['thumb_width'] = 480;
			}
			if(!info['height']){
				info['height'] = info['thumb_height'];
			}
			if(!info['width']){
				info['width'] = info['thumb_width'];
			}
			var src = info['src'];
			if(info['thumb'] != ''){
				src = info['thumb'];
			}
			if(info['base_url'] != ''){
				src = info['base_url'] + src;
			}
			var title = '';
			if(info['title']){
				title = info['title'];
			}
			var class_name = '';
			if(info['class']){
				class_name = info['class'];
			}
			var attr = '';
			if(info['attr']){
				attr = info['attr'];
			}
			return jQuery(this).append('<img src="' + src + '" alt="' + title + '" class="' + class_name + '" ' + attr + ' />');
		}
	});
}

(function($){
	$.cloneObject = function(source, is_deep){
		if(is_deep === false){
			return $.extend({}, source);
		}else{
			return $.extend(true, {}, source);
		}
	};
	$.anchor = function (val, skip) {
		var fn = arguments.callee;
		switch (typeof val) {
			// getter
			case 'undefined':
				var ret = location.hash;
				if (!ret) {
					return null;
				}
				ret = ret.replace(/^#/, '');
				return $.browser.fx ? ret : decodeURIComponent(ret);
			// callback
			case 'function':
				if (!fn.tid) {
					fn.hash = location.hash;
					(function rec() {
						if (!fn.skip && fn.hash !== location.hash) {
							fn.hash = location.hash;
							$(window).trigger('changeAnchor', $.anchor());
						}
						fn.tid = setTimeout(rec, 300);
					})();
				}
				return $(window).bind('changeAnchor', val);
			// setter
			default:
				if (skip) {
					fn.skip = true;
					location.hash = encodeURIComponent(val);
					fn.hash = location.hash;
					fn.skip = false;
				}
				else {
					location.hash = encodeURIComponent(val);
				}
				return;
		}
	};
	
	$.fn.rollover = function(suffix) {
		suffix = suffix || '_over';
		var check = new RegExp(suffix + '\\.\\w+$');
		var check_on = new RegExp('_on' + '\\.\\w+$');
		return this.each(function() {
			var img = jQuery(this);
			var src = img.attr('src');
			if(check_on.test(src)){
				src = img.attr('src').replace(/_on(\.\w+)$/, '$1');
				img.attr({'src' : src});
			}
			if(check.test(src)){
				if(img.attr('data-src')){
					src = img.attr('data-src');
					img.attr({'src' : src});
				}else{
					return;
				}
			}
			var on_src = src.replace(/\.\w+$/, suffix + '$&');
			img.attr({'data-src' : src});
			img.attr({'data-over_src' : on_src});
			jQuery('<img>').attr({'src' : on_src});
			img.hover(
				function() { img.attr({'src' : on_src}); },
				function() { img.attr({'src' : src}); }
			);
		});
	};
	
	$.fn.generatePager = function(count, page, par_page, disp_page_num, options){
		options = jQuery.extend({}, options);
		
		if(!disp_page_num || disp_page_num < 2){
			//最小表示ページ数(当該ページを含む)
			disp_page_num = 5;
		}
		var disp_page_apart = Math.ceil((disp_page_num - 1) / 2);
		var page_max = Math.ceil(count / par_page);
		var page_start = 1;
		var page_end = page_max;
		if(page_max > disp_page_num){
			page_start = Math.min(page_max - disp_page_num + 1, page - disp_page_apart);
			if(page_start <= 0){
				page_start = 1;
			}
			page_end = Math.max(page_start + disp_page_num - 1, page + disp_page_apart);
			if(page_end > page_max){
				page_end = page_max;
			}
		}
		var pager = $(this).empty();
		if(options.show_total){
			pager.append('<span class="total">全' + count + '件</span>');
		}
		for(var page_idx = page_start;page_idx <= page_end;page_idx++){
			pager.append('<span class="cmd' + (page_idx == page ? ' here' : '') + '" data-page="' + page_idx + '">' + page_idx + '</span>');
		}
		if(page_start > 1){
			pager.prepend('<span class="cmd" data-page="' + (page_start - 1) + '">...</span>');
		}
		if(page_max - page_end >= 1){
			pager.append('<span class="cmd" data-page="' + (page_end + 1) + '">...</span>');
		}
		if(options.show_first && page > 1){
			pager.append('<span class="cmd page_first" data-page="1">最初のページ</span>');
		}
		if(options.show_move && page > 1){
			pager.append('<span class="cmd page_move page_before" data-page="' + (page - 1) + '">&lt;&lt;&nbsp;前のページ</span>');
		}
		if(options.show_move && page < page_max){
			pager.append('<span class="cmd page_move page_after" data-page="' + (page + 1) + '">&gt;&gt;&nbsp;次のページ</span>');
		}
		return pager;
	}

})(jQuery);

function changeView(editable){
	if(editable){
		$('.view').hide();
		$('.edit').show();
	}else{
		$('.view').show();
		$('.edit').hide();
	}
}

function initRollover(){
	$('#menu_list img, .roll').rollover();
	var path = URL_PAGE;
	var anchor = $.anchor();
	if(anchor){
		path = path + '_' + anchor;
	}
	var menu_btn = $('#menu_' + path);
	if(menu_btn.size() > 0){
		menu_btn.unbind('mouseenter').unbind('mouseleave').attr({'src' : menu_btn.attr('src').replace(/\.\w+$/, '_on$&')});
	}
}

function toggleRollover(selector, dest){
	var img = jQuery(selector);
	if(img.size() == 0){
		return;
	}
	if(!dest){
		if(img.src == img.attr('data-src')){
			img.src = img.attr('data-over_src');
		}else{
			img.src = img.attr('data-src');
		}
	}else{
		if(dest == 'on'){
			img.unbind('mouseenter').unbind('mouseleave').attr({'src' : img.attr('data-over_src')});
		}else{
			img.attr({'src' : img.attr('data-src')}).hover(
				function() { img.attr({'src' : img.attr('data-over_src')}); },
				function() { img.attr({'src' : img.attr('data-src')}); }
			);
		}
	}
}

jQuery(document).ready(function($){
	$.browser.msie6 = ($.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent));
	
	initRollover();
	if($('#side_bar_left').size() > 0){
		if($(window).height() < '800'){
			if($.browser.msie6){
				$('#side_bar_left').css({
					'position' : 'static'
					, 'float' : 'left'
				});
				$('#content_body_right').css({
					'margin-left' : '210px'
					, 'margin-top' : '0'
				});
			}else{
				$('#side_bar_left').css({
					'position' : 'static'
					, 'float' : 'left'
					, 'margin-top' : '95px'
				});
			}
		}else{
			if($.browser.msie6){
				$('#side_bar_left, #head').exFixed();
			}
		}
	}
	
	if($.anchor() != ''){
		innerScroll('#' + $.anchor());
	}
	
	$('a.scroll').click(function(e){
		var href = $(this).attr('href');
		var sharp_idx = href.lastIndexOf('#');
		if(sharp_idx == -1){
			return true;
		}
		if(sharp_idx == 0 || href.substring(0, href.lastIndexOf('#')) == URL_PAGE){
			var anchor = href.substring(href.lastIndexOf('#') + 1);
			innerScroll('#' + anchor);
			$.anchor(anchor);
			if($(this).hasClass('menu_item')){
				toggleRollover(this, 'off');
				initRollover();
			}
			return false;
		}
		return true;
	});
});

