/*!
 * DLsite sample popover
 * copyright 2013 EISYS, Inc.
 */

 /*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.6
 *
 * Requires: jQuery 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        version: '3.1.6',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

}));


(function($, undefined){
	'use strict';

	var sampleItem = {
		popupMinWidth: 800,
		popupMinHeight: 600,
		hideDelay: 300,
		workid: '',
		baseItemUrl: '',
		lang: 'ja',
		$workVisual: null,
		$items: null,
		$overlay: null,
		$popup: null,
		$mainbox: null,
		$mainitem: null,
		$loading: null,
		fadeTimer: null,
		isMouseonShowing: false,
		itemZoomable: false,
		i18n: {
			'en': {
				'actualSize': 'Always display in actual size',
				'toolDesc': '<span>[Esc] Close</span><span>[S] Zoom to actual size</span><span>[<-] Previous</span><span>[->] Next</span>',
			},
			'ja': {
				'actualSize': '常に等倍で表示する',
				'toolDesc': '[ESC] 閉じる [S] 等倍切り替え [←] 前へ [→] 次へ',
			}
		}
	};

	var props = ['Width', 'Height'], prop;

	while (prop = props.pop()) {
		(function (natural, prop) {
			$.fn[natural] = (natural in new Image()) ? 
			function () {
			return this[0][natural];
			} : 
			function () {
			var 
			node = this[0],
			img,
			value;
			if (node.tagName.toLowerCase() === 'img') {
				img = new Image();
				img.src = node.src,
				value = img[prop];
			}
			return value;
			};
		}('natural' + prop, prop.toLowerCase()));
	}

	// initialize
	sampleItem.init = function() {
		var site = location.pathname.split('/');
		sampleItem.lang = (site[1] === 'eng' || site[1] === 'ecchi-eng') ? 'en' : 'ja';
		sampleItem.$mainVisual = $('#work_visual');
		sampleItem.$workVisual = $('<div class="dlpopup-work-visual"/>').appendTo(sampleItem.$mainVisual);
		sampleItem.$items = $('#work_sample a[rel="sample_images"]');
		sampleItem.workid = $('#work_sample').attr('data-work-id');
		sampleItem.baseItemImage = sampleItem.$workVisual.css('background-image');
	};

	// setEvents
	sampleItem.setEvents = {
		// マウスオーバーでサンプルを確認
		control: function(){
			sampleItem.$items.bind({
				'mouseover': function(){
					clearTimeout(sampleItem.fadeTimer);
					var src = $(this).attr('data-thumb') || $(this).attr('href');
					if($(this).attr('data-thumb') === undefined) sampleItem.$workVisual.css('background-size', 'contain');
					else sampleItem.$workVisual.css('background-size', 'auto');
					var delay = sampleItem.isMouseonShowing ? 0 : sampleItem.hideDelay;
					sampleItem.fadeTimer = setTimeout(function(){
						sampleItem.util.setWorkVisual(src);
						sampleItem.isMouseonShowing = true;
					}, delay);
				},
				'mouseout': function(){
					clearTimeout(sampleItem.fadeTimer);
					sampleItem.fadeTimer = setTimeout(function(){
						sampleItem.util.resetWorkVisual();
						sampleItem.isMouseonShowing = false;
					}, sampleItem.hideDelay);
				},
				'click': function(){
					clearTimeout(sampleItem.fadeTimer);
					sampleItem.util.showOverlay(sampleItem.$items.index(this));
					sampleItem.isMouseonShowing = false;
					return false;
				}
			});
		},
		// ポップアップ上のアイテム選択時
		popupControl: function($item){
			$item.bind({
				'click': function(){
					$(window).unbind('.setMainitemPosition');
					$item.removeClass('active');
					$(this).addClass('active');
					sampleItem.$overlay.text($(this).attr('alt') || '');
					sampleItem.util.setMainbox($(this).attr('data-type') || 'img', $(this).attr('href'));
					return false;
				}
			});
			sampleItem.$mainbox.data('click', false).bind({
				'mousedown': function(){
					$(this).data('click', true);
				},
				'mousemove': function(){
					$(this).data('click', false);
				},
				'mouseup': function(){
					if($(this).data('click')) sampleItem.util.setZoomable();
					$(this).data('click', false);
				}
			});
		},
		// アイテムのドラッグ
		draggableItem: function($item){
			$item.bind('mousedown.draggable', function(e){
				e.preventDefault();
				if(sampleItem.itemZoomable) {
					var drg_h = $item.outerHeight();
					var drg_w = $item.outerWidth();
					var pos_y = $item.offset().top + drg_h - e.pageY;
					var pos_x = $item.offset().left + drg_w - e.pageX;

					$(document).bind({
						'mousemove.draggableItem': function(e){
							e.preventDefault();
							$item.offset({
								top: e.pageY + pos_y - drg_h,
								left: e.pageX + pos_x - drg_w
							});
						},
						'mouseup.draggableItem': function(e) {
							e.preventDefault();
							$(document).unbind('.draggableItem');
						}
					});
				}
			});
		}
	};

	// util
	sampleItem.util = {
		// workVisualに画像をセット
		setWorkVisual: function(url){
			if(sampleItem.$loading !== null) sampleItem.$loading.remove();
			sampleItem.$loading = $('<img/>').attr('src', url).one('load', function(){
				sampleItem.$workVisual.css('background-image', 'url(' +url+ ')').stop(true, true).fadeIn('fast');
			});
			if(sampleItem.$loading[0].width > 0) sampleItem.$loading.trigger('load');
		},
		// workVisualをメイン画像にリセット
		resetWorkVisual: function(){
			sampleItem.$workVisual.stop(true, true).fadeOut('fast');
		},
		// オーバーレイを表示＆スクロールを抑制
		showOverlay: function(i){
			$(window).scrollTop(0);
			sampleItem.$overlay = $('<div class="dlpopup-overlay"/>').bind('click', sampleItem.util.hideOverlay).hide();
			$('body').css({
				'position': 'relative',
				'overflow': 'hidden',
				'min-width': sampleItem.popupMinWidth,
				'min-height': sampleItem.popupMinHeight
			}).append(sampleItem.$overlay);

			// ポップアップを表示
			var popup = '<div class="dlpopup-popup"><a href="#" class="dlpopup-close" />';
			popup += '<div class="dlpopup-rightpane"><div class="dlpopup-sidebar"></div>';
			popup += '<div class="dlpopup-arrows"><div class="dlpopup-button"><img class="dlpopup-prev" src="/images/web/common/dlsite-popover-prev.png"><img class="dlpopup-next" src="/images/web/common/dlsite-popover-next.png"></div><div class="dlpopup-count"></div></div></div>';
			popup += '<div class="dlpopup-leftpane"><div class="dlpopup-mainbox"></div><div class="dlpopup-tool"><div class="dlpopup-zoomable"><input type="checkbox" id="dlpopup-zoomable-check"'+ ($.cookie('dlpopup-zoom') === '1' ? ' checked' : '' ) +'><label for="dlpopup-zoomable-check">'+sampleItem.i18n[sampleItem.lang].actualSize+'</label></div><div class="dlpopup-description">'+sampleItem.i18n[sampleItem.lang].toolDesc+'</div></div></div>';
			popup += '</div>';
			sampleItem.$popup = $(popup).hide().appendTo('body');
			sampleItem.$popup.find('.dlpopup-close').bind('click', function(){
				sampleItem.$overlay.triggerHandler('click');
				return false;
			});
			sampleItem.$mainbox = sampleItem.$popup.find('.dlpopup-mainbox');
			sampleItem.$sidebar = sampleItem.$popup.find('.dlpopup-sidebar');

			sampleItem.itemZoomable = $.cookie('dlpopup-zoom') === '1' ? true : false;

			$(document).bind('keyup.closePopup', function(e) {
				if(e.keyCode === 27) { // esc
					sampleItem.$overlay.triggerHandler('click');
				} else if(e.keyCode === 39) { // right
					sampleItem.$popup.find('.dlpopup-next').triggerHandler('click');
				} else if(e.keyCode === 37) { // left
					sampleItem.$popup.find('.dlpopup-prev').triggerHandler('click');
				} else if(e.keyCode === 83) { // s
					sampleItem.$popup.find('#dlpopup-zoomable-check').trigger('click');
				}
			});

			$(sampleItem.$mainbox).bind('mousewheel.closePopup', function(event, delta, deltaX, deltaY){
				if(deltaY < 0) {
					event.preventDefault();
					sampleItem.$popup.find('.dlpopup-next').triggerHandler('click');
				} else {
					event.preventDefault();
					sampleItem.$popup.find('.dlpopup-prev').triggerHandler('click');
				}
			});

			sampleItem.$popup.find('#dlpopup-zoomable-check').bind('click', function(){
				sampleItem.itemZoomable = $(this).attr('checked');
				$.cookie('dlpopup-zoom', sampleItem.itemZoomable ? 1 : 0, { expires: 365 });
				sampleItem.util.setZoomable(sampleItem.itemZoomable);
			});

			sampleItem.$popup.find('.dlpopup-next').bind('click', function(){
				var next = sampleItem.$sidebar.find('.active').next();
				if(next.length === 1) next.triggerHandler('click');
				else sampleItem.$sidebar.find('a:first').triggerHandler('click');
			});

			sampleItem.$popup.find('.dlpopup-prev').bind('click', function(){
				var prev = sampleItem.$sidebar.find('.active').prev();
				if(prev.length === 1) prev.triggerHandler('click');
				else sampleItem.$sidebar.find('a:last').triggerHandler('click');
			});

			var $items = sampleItem.$items.clone(false);
			sampleItem.setEvents.popupControl($items);
			sampleItem.$sidebar.append($items);
			sampleItem.$popup.fadeIn('fast');
			sampleItem.$overlay.fadeIn('fast');
			$items.eq(i).triggerHandler('click');
		},
		// オーバーレイを非表示
		hideOverlay: function() {
			$(window).unbind('.setMainitemPosition');
			$(document).unbind('.closePopup');
			sampleItem.$overlay.fadeOut('fast', function(){
				$(this).remove();
			});
			sampleItem.$popup.fadeOut('fast', function(){
				$(this).remove();
			});
			$('body').css({
				'position': '',
				'overflow': '',
				'min-width': '',
				'min-height': ''
			});
		},
		// アイテムをセット
		setMainbox: function(type, src){
			// sampleItem.itemZoomable = false;

			// カウンターをセット
			var now = sampleItem.$sidebar.find('a').index(sampleItem.$sidebar.find('.active')) + 1;
			sampleItem.$popup.find('.dlpopup-count').text(now +' / '+ sampleItem.$sidebar.find('a').length);


			if(sampleItem.$mainitem !== null) {
				sampleItem.$mainitem.fadeOut(0, function(){
					sampleItem.$mainitem.remove();
					sampleItem.util.setMainboxExec(type, src);
				});
			} else {
				sampleItem.util.setMainboxExec(type, src);
			}
		},
		setMainboxExec: function(type, src){
			if(type === 'img') {
				sampleItem.$mainitem = $('<img/>').css({
					'position': 'absolute',
					'left': 0,
					'top': 0
				}).attr({
					'src': src,
					'class': 'dlpopup-mainitem'
				}).one({
					'load': function(){
						$(window).bind('resize.setMainitemPosition', sampleItem.util.setMainitemPosition);
						sampleItem.setEvents.draggableItem(sampleItem.$mainitem);
						sampleItem.$mainbox.empty().append(sampleItem.$mainitem);
						sampleItem.util.setMainitemPosition();
						$(this).show();
					},
					'error': function(){
						sampleItem.$mainbox.empty();
					}
				}).hide();
				if(sampleItem.$mainitem[0].width > 0) sampleItem.$mainitem.trigger('load');
			} else if(type === 'iframe') {
				var adultchecked = ($.cookie('adultchecked') !== null && $.cookie('adultchecked') === '1') ? '1' : '0';
				src += '?dlsite=1&adultchecked='+adultchecked;
				sampleItem.$mainitem = $('<iframe style="width: 100%; height: 100%;" src="'+src+'" frameborder="0" allowfullscreen></iframe>');
				sampleItem.$mainbox.empty().append(sampleItem.$mainitem);
			}
		},
		// ポジションの調整
		setMainitemPosition: function(){
			var height = $('.dlpopup-popup').height();
			sampleItem.$mainbox.height(height - 66);
			sampleItem.$popup.find('.dlpopup-leftpane, .dlpopup-rightpane').height(height);
			var boxWidth = sampleItem.$mainbox.width();
			var boxHeight = sampleItem.$mainbox.height();
			var imgWidth = sampleItem.$mainitem[0].naturalWidth || sampleItem.$mainitem.naturalWidth();
			var imgHeight = sampleItem.$mainitem[0].naturalHeight || sampleItem.$mainitem.naturalHeight();
			var cursor = sampleItem.itemZoomable ? 'move' : 'url("/images/web/common/popover-zoom-in.cur"), pointer';

			if(!sampleItem.itemZoomable) {
                if (imgHeight > boxHeight
                    && imgWidth > boxWidth){
                    //高さと幅が両方エリアより大きい場合
                    //たて横比率によって処理を分ける
                   if(imgHeight > imgWidth){
                        //高さの方が大きい場合
                        var orgWidth = imgWidth;
                        imgWidth = boxWidth;
                        //autoでは対応仕切れないため計算を実施
                        imgHeight = imgHeight * (boxWidth/orgWidth);
                        if (imgHeight > boxHeight) {
                            //修正してなお表示領域の幅を超える場合
                            //幅に収まるように変更
                            var orgHeight = imgHeight;
                            imgHeight = boxHeight;
                            imgWidth = imgWidth * (boxHeight/orgHeight);
                        }

                   } else if(imgWidth > imgHeight) {
                        var orgHeight = imgHeight;
                        imgHeight = boxHeight;
                        //autoでは対応仕切れないため計算を実施
                        imgWidth = imgWidth * (boxHeight/orgHeight);
                        if (imgWidth > boxWidth) {
                            //修正してなお表示領域の幅を超える場合
                            //幅に収まるように変更
                            var orgWidth = imgWidth;
                            imgWidth = boxWidth;
                            imgHeight = imgHeight * (boxWidth/orgWidth);
                        }
                   } else {
                        //正方形の場合
                        //高さか幅のいずれか小さい方を採用する
                        imgWhdth = boxWidth > boxHeight ? boxHeight : boxWidth;
                        imgHeight = boxWidth > boxHeight ? boxHeight : boxWidth;
                   }
                }
                if(imgHeight > boxHeight){
					imgHeight = boxHeight;
					imgWidth = 'auto';
				} else if(imgWidth > boxWidth) {
					imgWidth = boxWidth;
					imgHeight = 'auto';
				} else {
					cursor = 'default';
				}
			}

			sampleItem.$mainitem.css({
				'width': imgWidth,
				'height': imgHeight,
				'cursor': cursor
			});

			sampleItem.$mainitem.css({
				'left': (boxWidth - sampleItem.$mainitem.width()) / 2,
				'top': (boxHeight - sampleItem.$mainitem.height()) / 2
			});

		},
		// ズーム切り替え
		setZoomable: function(bool){
			var boxWidth = sampleItem.$mainbox.width();
			var boxHeight = sampleItem.$mainbox.height();
			var imgWidth = sampleItem.$mainitem[0].naturalWidth || sampleItem.$mainitem.naturalWidth();
			var imgHeight = sampleItem.$mainitem[0].naturalHeight || sampleItem.$mainitem.naturalHeight();

			if(boxWidth < imgWidth || boxHeight < imgHeight) {
				if(bool === undefined) sampleItem.itemZoomable = !sampleItem.itemZoomable;
				sampleItem.$popup.find('#dlpopup-zoomable-check').attr('checked', sampleItem.itemZoomable ? 'checked' : '');
				$.cookie('dlpopup-zoom', sampleItem.itemZoomable ? 1 : 0, { expires: 365 });
				sampleItem.util.setMainitemPosition();
			}
		}
	};

	// 実行
	$(function(){
		sampleItem.init();
		sampleItem.setEvents.control();
	});

})(jQuery);
