/**
 * 全ページに適用するjqueryによる処理を記述する
 */
$(function(){
	$("#flashMessage").flashMessage();
	$("img").preloadImages();
	$("table.detail tr:odd").addClass('odd');
	$(".marquee").marquee();
	
	/* Japanese initialisation for the jQuery UI date picker plugin. */
	/* Written by Kentaro SATO (kentaro@ranvis.com). */
	$.datepicker.regional['ja'] = {
		closeText: '閉じる',
		prevText: '&#x3c;前',
		nextText: '次&#x3e;',
		currentText: '今日',
		monthNames: ['1月','2月','3月','4月','5月','6月',
		'7月','8月','9月','10月','11月','12月'],
		monthNamesShort: ['1月','2月','3月','4月','5月','6月',
		'7月','8月','9月','10月','11月','12月'],
		dayNames: ['日曜日','月曜日','火曜日','水曜日','木曜日','金曜日','土曜日'],
		dayNamesShort: ['日','月','火','水','木','金','土'],
		dayNamesMin: ['日','月','火','水','木','金','土'],
		weekHeader: '週',
		dateFormat: 'yy/mm/dd',
		firstDay: 0,
		isRTL: false,
		showMonthAfterYear: true,
		yearSuffix: '年'};
	$.datepicker.setDefaults($.datepicker.regional['ja']);
});

/**
 * 共通プラグイン
 * @author sano
 */
(function($){

	$.fn.marquee = function(options){
		if ($.browser.msie && $.browser.version == 6) {
			return this;
		}
		
		var elements = this;

		// 
		// @name marquee.js
		// @author miya2000
		// @namespace http://d.hatena.ne.jp/miya2000/
		// @version 1.0.0
		// 
		var Marquee = function (id, opt){
		    if( ! document.getElementById(id) ) throw 'invalid id. [' + id + ']';
		    var option = opt || {};
		    this.id     = id;
		    this.amount = option.amount || 6;
		    this.delay  = option.delay  || 100;
		    this.position = Number.POSITIVE_INFINITY; // means out of range.
		    this._wrap();
		    this.start();
		};
		
		Marquee.prototype = {
		    /* wrap child nodes */
		    _wrap : function() {
		        var t = document.getElementById( this.id );
		        with ( t.style ){
		            position = 'relative'; // for ie6.
		            overflow = 'hidden';
		            whiteSpace = 'nowrap';
		        }
		        var w = document.createElement( 'div' );
		        with ( w.style ){
		            margin     = '0';
		            padding    = '0';
		            background = 'transparent';
		            border     = 'none';
		        }
		        t.normalize();
		        while( t.firstChild ){
		            w.appendChild( t.removeChild( t.firstChild ) );
		        }
		        t.appendChild(w);
		        /* get minimum width. */
		        w.style.position = 'absolute';
		        this.minWidth = w.offsetWidth;
		        /* put back */
		        w.style.position = 'relative';
		        w.style.width = '100%'; // for ie6.
		    },
		    start : function() {
		        this.stop();
		        this._next();
		    },
		    _next : function() {
		        var t = document.getElementById( this.id );
		        this.curWidth = Math.min(t.offsetWidth,t.parentNode.offsetWidth); // dirty. (for "overflow:hidden" parent)
		        this.position = this.position - this.amount;
		        if ( this._isOutOfRange() ) {
		            this.position = this._startPosition();
		        }
		        var w = t.firstChild;
		        w.style.left = this.position + 'px';
		        var self = this;
		        this.tid = window.setTimeout(
		            function(){ self._next(); },
		            this.delay
		        );
		    },
		    _startPosition : function() {
		        return ( this.amount > 0 ) ?  this.curWidth
		                                   : -this.minWidth;
		    },
		    _isOutOfRange : function() {
		        return this.position < -this.minWidth || this.curWidth < this.position;
		    },
		    stop : function() {
		        if ( this.tid ) window.clearTimeout( this.tid );
		        this.tid = null;
		    },
		    isMarqueeing : function() {
		        return ( this.tid ) ? true : false;
		    }
		};

		var counter = 0;
		elements.each(function(){
			var element = $(this);
			
			var id = element.attr("id");
			if(id == null || id == "") {
				id = "marquee" + counter;
				element.attr("id", id);
			}
			
			new Marquee(id);
			
			counter++;
		});
		return this;
	};
	
	/**
	 *  jquery-ui-dialogで画像をアップロードする
	 *  
	 *  オプション
	 *  action: アップロードを行うアクション
	 *  title: ダイアログのタイトル
	 *  imageTag: アップロードした画像を表示するimgタグのID
	 *  target: アップロードした画像のIDをセットするinputタグのID
	 *  filename: アップロードした画像のファイル名をセットするタグのID
	 *  thumbname: アップロードした画像のサムネイル名をセットするタグのID
	 */
	$.fn.ajaxUploadImage = function(options) {
		var elements = this;
		var op = $.extend({
			title: "画像をアップロード"
		}, options);
		
		elements.each(function(){
			var element = $(this);	
			
			var clickUpload = function(){
				var dialog = $(this);
				dialog.find("form:first").ajaxSubmit({
					url: op.action,
					success: function(res, status, xhr, form){
						var id = $(res).find("#Id").text();
						var filename = $(res).find("#Filename").text();
						var thumbname = $(res).find("#Thumbname").text();
						
						if(id != "") {
							dialog.dialog("close");
							
							$(res).dialog({
								title: "アップロードしました！",
								modal: true,
								width: 800,
								height: 600,
								buttons: {
									"OK": function(){
										$(op.target).val(id);
										$(op.filename).val(filename);
										$(op.thumbname).val(thumbname);
										$(op.imagetag).attr("src", op.imgdir + thumbname);
										
										$(this).dialog("close");
									},
									"Cancel": function(){$(this).dialog("close");}
								}
							});
						} else {
							dialog.html($(res).html());
						}
					}
				});
			};
			
			element.click(function(){
				$.ajax({
					url: op.action,
					dataType: "html",
					type: "GET",
					success: function(data, status, xhr){
						$(data).dialog({
							title: op.title,
							modal: true,
							width: 800,
							height: 600,
							buttons: {
								"Upload": clickUpload,
								"Cancel": function(){$(this).dialog("close");}
							}
						});
					}
				});
				return false;
			});
		});
		return this;
	};
	
	/** CakePHPのflashMessageをtwitterのメッセージ風に表示する. */
	$.fn.flashMessage = function(options){
		var elements = this;
		var op = $.extend({sec:5}, options);
		elements.each(function(){
			var element = $(this);
			var close = function(){element.slideUp();};
			element.slideDown();
			element.click(close);
			setTimeout(close, op.sec * 1000);
		});
		return this;
	};
	/** preload images */
	$.fn.preloadImages=function(){var images=this;images.each(function(){$("<img/>").attr("src",$(this));});return this;};
	/** dump */
	$.fn.dump=function(){var elements=this;var dumphtml=[];elements.each(function(){var element=$(this);if($.browser.msie){for(var i=0;i<element.length;i++){dumphtml.push(element[i].outerHTML.replace(/^[\r\n\t]+/,''));dumphtml.push("\n");}}else{for(var i=0;i<element.length;i++){dumphtml.push('<'+element[i].nodeName.toLowerCase());for(var j=0;j<element[i].attributes.length;j++){dumphtml.push(' '+element[i].attributes[j].nodeName+'="'+element[i].attributes[j].nodeValue+'"');}dumphtml.push('>'+element[i].innerHTML);dumphtml.push('<\/'+element[i].nodeName.toLowerCase()+'>');dumphtml.push("\n");}}});alert(dumphtml.join(''));return this;};
})(jQuery);
