// T.HERO Site Signage System
//   Ad image player
// Copyright (c)2009 TECHNICAL HERO All rights reserved.

var adimgplayer_loaded = new Date();
//
// create closure
//
(function($) {
	var $this;

	//
	// plugin definition
	//
	$.fn.extend({
		
		adimgplayer: function(options) { 

			$.ap_pv.opt = $.extend({},$.adimgplayerSetup.defaults, options);		// extend options
			$this = $(this);
			
			new $.adimgplayerSetup();
		},

		adimgplayer_force_next: function() {
			if ($.ap_pv.timer_id) {
				window.clearTimeout($.ap_pv.timer_id);
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_show_next_img(true, true);
		},

		adimgplayer_force_prev: function() {
			if ($.ap_pv.timer_id) {
				window.clearTimeout($.ap_pv.timer_id);
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_show_prev_img(true);
		},

		adimgplayer_force_first: function() {
			if ($.ap_pv.timer_id) {
				window.clearTimeout($.ap_pv.timer_id);
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_show_first_img(true);
		},

		adimgplayer_force_last: function() {
			if ($.ap_pv.timer_id) {
				window.clearTimeout($.ap_pv.timer_id);
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_show_last_img(true);
		},

		adimgplayer_rewind: function() {
			if ($.ap_pv.timer_id) {
				window.clearTimeout($.ap_pv.timer_id);
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_show_first_img(false);
		},

		adimgplayer_get_item_count: function() {
			return $.ap_pv.item_count;
		},

		adimgplayer_get_current_item_info: function() {
			return $.ap_pv.cur_idx;
		}
	});

	//
	// private function for debugging
	//
	function debug(msg) {
		if (window.console && window.console.log)
		window.console.log(msg);
		window.status = msg.srcElement;
	};

	//
	// plugin setup
	//
	$.adimgplayerSetup = function() {
		$this.css({
			"width": $.ap_pv.opt.width+"px",
			"height": $.ap_pv.opt.height+"px",
			"overflow": "hidden",
			"position": "relative",
			"background-color": "#000000",
			"z-index": 0
		});
		if (!$.ap_pv.opt.data) return;
		$.ap_pv.bk = $(document.createElement('div'));
		$.ap_pv.bk.css({
			"width": $.ap_pv.opt.width+"px",
			"height": $.ap_pv.opt.height+"px",
			"overflow": "hidden",
			"position": "absolute",
			"left": "0px",
			"top": "0px",
			"background-color": "#000000",
			"z-index": 15
		});
		$this.append($.ap_pv.bk);

		$.ap_pv.item_count = $.ap_pv.opt.data.length;
		$.ap_pv.cur_img_elem_id = $.ap_pv.opt.prefix+'_cur_imgbox';
		$.ap_pv.next_img_elem_id = $.ap_pv.opt.prefix+'_next_imgbox';
		var material_list = $.ap_pv.opt.data;
		var i;
		$.each(material_list, function(i,item){
			var imgbox = document.createElement("div");
			$(imgbox).css({
				"position": "absolute",
				"left": "0px",
				"top": "0px",
				"z-index": "-10",
				"visibility": "hidden",
				"border": "0",
				"background-color": "#000000",
				"overflow": "hidden",
				"width": $.ap_pv.opt.width+"px",
				"height": $.ap_pv.opt.height+"px"
			}).attr({
				"id": $.ap_pv.opt.prefix+i
			});
			$this.append($(imgbox));
			if (item.imgtype == 'swf') {
				var html = TH_AC_FL_GenerateContent(
					'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+$.ap_pv.opt.flash_ver,
					'width', $.ap_pv.opt.width,
					'height', $.ap_pv.opt.height,
					'src', item.imgurl,
					'quality', 'high',
					'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
					'align', 'middle',
					'play', 'true',
					'loop', 'true',
					'scale', 'showall',
					'wmode', 'transparent',
					'devicefont', 'false',
					'menu', 'true',
					'allowFullScreen', 'false',
					'allowScriptAccess','sameDomain',
					'movie', item.imgurl,
					'salign', ''
					);
				$(imgbox).html(html);
				if (item.link_url) {
					var $a = $(document.createElement("a"));
					var $dmyimg = $(document.createElement("img"));
					$dmyimg.attr({
						'src': $.ap_pv.opt.spaceimg
					}).css({
						'width': $.ap_pv.opt.width+'px',
						'height': $.ap_pv.opt.height+'px',
						'border': '0'
					});
					$a.append($dmyimg);
					$a.css({
						'position': 'absolute',
						'left': '0px',
						'top': '0px',
						'width': $.ap_pv.opt.width+'px',
						'height': $.ap_pv.opt.height+'px'
					});
					if ($.ap_pv.opt.counter) {
						if (item.link_target) {
							$a.attr({
								'href': item.link_url,
								'target': item.link_target
							}).click(function() {
								$.ad_countup($.ap_pv.opt.counter,item.mid);
								return true;
							});
						} else {
							$a.attr({
								'href': 'javascript:void(0)'
							}).click(function() {
								$.ad_countup2($.ap_pv.opt.counter,item.mid,item.link_url,item.link_target);
								return true;
							});
						}
					} else {
						$a.attr({
							'href': item.link_url,
							'target': item.link_target
						});
					}
					$(imgbox).append($a);
				}
			} else {
				var f = $.adimgplayer_calcfitsize($.ap_pv.opt.width, $.ap_pv.opt.height, item.width, item.height);
				var $a = $(document.createElement("a"));
				$a.css({
					position: 'absolute',
					left: f.left+'px',
					top: f.top+'px',
					width: f.width+'px',
					height: f.height+'px'
				});
				var img = document.createElement("img");
//				$(img).bind("load", this, function(e) {
//					$(this).unbind('load');
//					$.adimgplayer_imgfit($(this),item.width, item.height);
//				});
				$(img).css({
					width: f.width+'px',
					height: f.height+'px'
				});
				$(imgbox).append($a);
				$(img).attr("src", item.imgurl);
				$a.append($(img));
				if (item.link_url) {
					if ($.ap_pv.opt.counter) {
						if (item.link_target) {
							$a.attr({
								'href': item.link_url,
								'target': item.link_target
							}).click(function() {
								$.ad_countup($.ap_pv.opt.counter,item.mid);
								return true;
							});
						} else {
							$a.attr({
								'href': 'javascript:void(0)'
							}).click(function() {
								$.ad_countup2($.ap_pv.opt.counter,item.mid,item.link_url,item.link_target);
								return true;
							});
						}
					} else {
						$a.attr({
							'href': item.link_url,
							'target': item.link_target
						});
					}
				}
			}

			$.ap_pv.opt.data[i].element = $(imgbox);
		});
		if ($.ap_pv.opt.iniimg_id) {
			var $iniimg = $('#'+$.ap_pv.opt.iniimg_id);
			if ($iniimg.length > 0) {
				// initial image exists
				$iniimg.fade_out({speed:500}, function() {
					$iniimg.remove();
					$.adimgplayer_show_next_img(true, false);
				});
				return;
			}
		}
		$.adimgplayer_show_next_img(true, false);
	};
	//
	// plugin defaults
	//
	$.adimgplayerSetup.defaults = {
		prefix: 'adimg',
		data: null,
		width: 680,
		height: 260,
		flash_ver:"9,0,0,0",
		spaceimg:"img/space.gif",
		infownd: null,
		iniimg_id: '',
		iniimg_runtime: 10
	};
	$.ap_pv = {
		timer_id: 0,
		item_loaded: 0,
		timetbldata: null,
		opt: null,
		cur_idx: -1,
		item_count: 0,
		cur_img_elem_id: '',
		next_img_elem_id: ''
	};

	$.adimgplayer_swich_img = function(dir, flg, noeffect) {
		if (!$.ap_pv.item_count) return;
		var dt = new Date();
		var cur_min = dt.getHours() * 60 + dt.getMinutes();
		var off;
		var img_idx;
		switch (dir) {
			case 'first':
				img_idx = 0;
				break;
			case 'next':
				img_idx = ($.ap_pv.cur_idx+1)%$.ap_pv.item_count;
				break;
			case 'last':
				img_idx = $.ap_pv.item_count-1;
				break;
			case 'prev':
				img_idx = $.ap_pv.cur_idx ? ($.ap_pv.cur_idx-1) : ($.ap_pv.item_count-1);
				break;
		}
		while (img_idx != $.ap_pv.cur_idx) {
			var d;
			var dlist = $.ap_pv.opt.data[img_idx].timelist;
			var b_show = false;
			for (d = 0; d < dlist.length; d++) {
				if (dlist[d].s <= cur_min && cur_min < dlist[d].e) {
					b_show = true;
					break;
				}
			}
			if (b_show) {
				break;
			} else {
				switch (dir) {
					case 'first':
						dir='next';
					case 'next':
						img_idx = (img_idx+1)%$.ap_pv.item_count;
						break;
					case 'last':
						dir='prev';
					case 'prev':
						img_idx = img_idx ? (img_idx-1) : ($.ap_pv.item_count-1);
						break;
				}
			}
		}
		if (img_idx == $.ap_pv.cur_idx) {
			if (flg) {
				var d = new Date();
				var v = (60 - d.getSeconds()) * 1000;
				$.ap_pv.timer_id = window.setTimeout(function(){$.adimgplayer_show_next_img(true, false)}, v);
			} else {
				$.ap_pv.timer_id = 0;
			}
			return;
		}

		// prepare next image
		var $next_img = $.ap_pv.opt.data[img_idx].element.clone(true);
		$next_img.attr('id', $.ap_pv.next_img_elem_id)
		.css({
			'visibility': 'visible',
			'z-index': 10
		});
		$this.append($next_img);

		var ef = 0;
		var et = 0;
		var es = 0;
		if ($.ap_pv.cur_idx >= 0) {
			ef = parseInt($.ap_pv.opt.data[$.ap_pv.cur_idx].effecttype, 10);
			et = ef % 1000;
			es = (ef-et)/1000;
		}

		switch (et) {
		case 1:	// fade out (black)
		case 2:	// fade out (white)
		case 3:	// dissolv
			break;
		default:
			et = 0;
			break;
		}
		var $cur_img = $this.find('#'+$.ap_pv.opt.prefix+'_cur_imgbox');
		if (noeffect || (et == 0)) {
			$next_img.attr('id', $.ap_pv.cur_img_elem_id).css({'z-index': 20});
			$.ap_pv.bk.css({'visibility': 'hidden'});
			$cur_img.css({'z-index':10}).remove();
			$.ap_pv.cur_idx = img_idx;
			if (flg) {
				$.ap_pv.timer_id = window.setTimeout(function(){$.adimgplayer_show_next_img(true, false)}, ($.ap_pv.opt.data[img_idx].imgtype == '' ? 1 : $.ap_pv.opt.data[img_idx].runtime) * 1000);
			} else {
				$.ap_pv.timer_id = 0;
			}
			$.adimgplayer_upd_infownd();
			return;
		}

		switch (et) {
		case 1:	// fade out (black)
		case 2:	// fade out (white)
		case 3:	// dissolv
			switch (et) {
			case 1:
				$.ap_pv.bk.css({
					'background-color': '#000000',
					'visibility': 'visible'
				});
				break;
			case 2:
				$.ap_pv.bk.css({
					'background-color': '#FFFFFF',
					'visibility': 'visible'
				});
				break;
			case 3:
				$.ap_pv.bk.css({
					'visibility': 'hidden'
				});
				break;
			}
			$cur_img.fade_out({speed:es}, function() {
				$next_img.attr('id', $.ap_pv.cur_img_elem_id).css({'z-index': 20});
				$.ap_pv.bk.css({'visibility': 'hidden'});
				$cur_img.css({'z-index':10}).remove();
				$.ap_pv.cur_idx = img_idx;
				if (flg) {
					$.ap_pv.timer_id = window.setTimeout(function(){$.adimgplayer_show_next_img(true, false)}, ($.ap_pv.opt.data[img_idx].imgtype == '' ? 1 : $.ap_pv.opt.data[img_idx].runtime) * 1000);
				} else {
					$.ap_pv.timer_id = 0;
				}
				$.adimgplayer_upd_infownd();
				return;
			});
			break;
		}
	};

	$.adimgplayer_upd_infownd = function() {
		if ($.ap_pv.opt.infownd) {
			var $infownd = $('#'+$.ap_pv.opt.infownd);
			$infownd.find('.playidx').text($.ap_pv.cur_idx+1);
			$infownd.find('.item_count').text($.ap_pv.item_count);
			$infownd.find('.item_runtime').text($.ap_pv.opt.data[$.ap_pv.cur_idx].runtime);
			$infownd.find('.item_link_url').text($.ap_pv.opt.data[$.ap_pv.cur_idx].link_url);
			var ef = parseInt($.ap_pv.opt.data[$.ap_pv.cur_idx].effecttype, 10);
			var et = ef % 1000;
			var es = (ef - et) / 1000;
			var ef_txt = '';
			switch (et) {
			case 0:
				ef_txt = 'エフェクトなし';
				break;
			case 1:
				ef_txt = 'フェードアウト（黒）';
				break;
			case 2:
				ef_txt = 'フェードアウト（白）';
				break;
			case 3:
				ef_txt = 'ディゾルブ';
				break;
			}
			if (et != 0) {
				ef_txt += (es <= 1000 ? ', 速い' : (es <= 2000 ? ', 普通' : ', 遅い'));
			}
			$infownd.find('.item_effecttype').text(ef_txt);
		}
	};
		
	$.adimgplayer_show_next_img = function(flg,noeffect) {
		$.adimgplayer_swich_img('next', flg, noeffect);
	};

	$.adimgplayer_show_prev_img = function(flg) {
		$.adimgplayer_swich_img('prev', flg, true);
	};

	$.adimgplayer_show_first_img = function(flg) {
		$.adimgplayer_swich_img('first', flg, true);
	};

	$.adimgplayer_show_last_img = function(flg) {
		$.adimgplayer_swich_img('last', flg, true);
	};

	$.adimgplayer_calcfitsize = function (ow, oh, iw, ih) {
		var fw = iw;
		var fh = ih;
		if (iw > ow || ih > oh) {
			var mw = iw / ow;
			var mh = ih / oh;
			if (mw > mh) {
				fw = ow;
				fh = parseInt(ih/mw, 10);
			} else {
				fw = parseInt(iw/mh, 10);
				fh = oh;
			}
		}
		var fl = parseInt((ow-fw)/2, 10);
		var ft = parseInt((oh-fh)/2, 10);
		return { left:fl, top:ft, width:fw, height:fh };
	};

	$.adimgplayer_imgfit = function($img, w, h) {
		var bw = $.ap_pv.opt.width;
		var bh = $.ap_pv.opt.height;
		var new_w = w;
		var new_h = h;
		if (w > bw || h > bh) {
			var mw = w / bw;
			var mh = h / bh;
			if (mw > mh) {
				new_w = bw;
				new_h = parseInt(h/mw, 10);
				$img.width(bw+'px');
				$img.height(new_h+'px');
			} else {
				new_w =parseInt(w/mh, 10); 
				new_h = bh;
				$img.width(new_w+'px');
				$img.height(bh+'px');
			}
		}
		$img.parent().css({
			'left': parseInt((bw-new_w)/2, 10)+'px',
			'top': parseInt((bh-new_h)/2, 10)+'px'
		});
		$img.css({
			'visibility': 'visible'
		});
	};

	$.ad_countup = function(pg,mid) {
		(new Image()).src=pg+mid;
		return true;
	};

	$.ad_countup2 = function(pg,mid,l,t) {
		$(document.createElement("img")).load(function(){$(this).unbind('load');window.open(l, t?t:'_self');}).attr("src", pg+mid);
		return true;
	};


//
// end of closure
//
})(jQuery);
