/*!
 * DLsite.com JavaScript Library.
 *
 * Copyright (C) 1996-2011 DLsite.com. All rights reserved.
 * http://www.dlsite.com/
 */

var general_sites = ['home','comic','soft','eng','home-touch','comic-touch','eng-touch'];
var female_sites  = ['girls','girls-pro','girls-touch','girls-pro-touch'];
var gay_sites     = ['gay','gay-eng','gay-touch','gay-eng-touch'];

/**
 * xmlオブジェクトから指定されたelementの値を取得しStringにキャストして返す
 * @deprecated global scope
 */
function toString(xml, element) {
    return String($(xml).find(element).first().text());
}

/**
 * 引数selectorにテキストを設定する
 * @deprecated global scope
 */
function renderText(selector, msg, css_class) {
    if (css_class) {
        $(selector).addClass(css_class);
    }
    return $(selector).text(msg);
}

/**
 * 引数selectorからテキストを削除する
 * @deprecated global scope, 未使用?
 */
function removeText(selector, css_class) {
    if (css_class) {
        $(selector).removeClass(css_class);
    }
    return $(selector).text('');
}

/**
 * ドメインからサイト名を取得
 * @deprecated global scope
 * @see $.getSiteName
 */
function getSiteName() {
    return $.getSiteName();
}

/**
 * サイト名から言語を取得
 * @deprecated global scope
 * @see $.getSiteName
 */
function getSiteLang() {
    return $.getSiteLang();
}

/***
 * サイトに応じた画像パスを取得
 *  @deprecated global scope
 */
function getSiteImagepath() {
    var site_name = getSiteName();
    var image_path = '/images/web/';
    switch(site_name) {
        case 'gay':
            return image_path + 'gay/';

        case 'girls':
        case 'girls-pro':
            return image_path + 'girls/';

        case 'eng':
        case 'ecchi-eng':
        case 'fra':
        case 'ecchi-fra':
        case 'gay-eng':
            return image_path + 'abroad/';

        case 'home-touch':
        case 'maniax-touch':
        case 'books-touch':
        case 'comic-touch':
        case 'pro-touch':
            return image_path + 'hometouch/';

        case 'gay-touch':
            return image_path + 'gaytouch/';

        case 'girls-touch':
        case 'girls-pro-touch':
            return image_path + 'girlstouch/';

        case 'eng-touch':
        case 'ecchi-eng-touch':
//        case 'gay-eng-touch':
            return image_path + 'abroadtouch/';

        default:
            return image_path + 'home/';
    }
}

/**
 * GETパラメータを取得
 * @deprecated global scope
 * @see $.getDLocation
 */
function getParameter(name) {
    var path = location.pathname;
    if (!path) return null;
    var params = path.split('/=/')[1];
    if (!params) return null;
    var pname, pval;
    params = params.split('/');
    for (var i in params) {
        pname = (params[i] ? params[i] : null);
        i++;
        pval  = (params[i] ? params[i] : null);
        if (pname && pval) {
            if (pname == name) {
                return pval.replace('\.html', '');
            }
        } else {
            break;
        }
    }

    return null;
}

/**
 * htmlエスケープ
 * @deprecated 
 * @see _.escape
 */
jQuery.escapeHTML = function(val){
    return jQuery('<div />').text(val).html();
};

jQuery.conv2TouchURL = function() {
    var ps = getSiteName();
    var ts = $.conv2TouchSite(getSiteName());
    if (ts) {
        return document.URL.replace(ps, ts);
    }
    return document.URL;
};

jQuery.conv2TouchSite = function(site){
    switch (site) {
        case 'maniax':
        case 'girls':
        case 'girls-pro':
        case 'ecchi-eng':
        case 'home':
        case 'eng':
        case 'books':
        case 'comic':
        case 'pro':
        case 'gay':
//        case 'gay-eng':
            return (site + '-touch');
    }
    return null;
};

jQuery.getSiteAgeCategory = function(){
    var sid = getSiteName();
    if ($.inArray(sid, general_sites)>-1) return 'general';
    return 'adult';
};

jQuery.isAdultSite = function(){
    return ($.getSiteAgeCategory()=='adult');
}

jQuery.getSiteSexCategory = function(){
    var sid = getSiteName();
    if ($.inArray(sid, female_sites)>-1) return 'female';
    if ($.inArray(sid, gay_sites)>-1) return 'gay';
    return 'male';
}

jQuery.isFemaleSite = function(){
    return ($.getSiteSexCategory()=='female');
}

$.extend({

    /**
     * 正規表現パターンのエスケープ
     * @param {string} str
     * @returns {string}
     */
    escapeRegExp: function (str) {
        return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    },

    /**
     * left trim
     * @param {string} str
     * @param {...*} var_args 任意の削除文字
     * @returns {string}
     */
    ltrim: function (str, var_args) {
        var charmask = (typeof arguments[1] !== 'undefined') ? $.escapeRegExp(arguments[1]) : ' ',
            pattern = new RegExp('^[' + charmask + ']+','g');
        return str.replace(pattern, '');
    },

    /**
     * right trim
     * @param {string} str
     * @param {...*} var_args 任意の削除文字
     * @returns {string}
     */
    rtrim: function (str, var_args) {
        var charmask = (typeof arguments[1] !== 'undefined') ? $.escapeRegExp(arguments[1]) : ' ',
            pattern = new RegExp('[' + charmask + ']+$','g');
        return str.replace(pattern, '');
    },

    /**
     * URLをパース
     * @param {string} url
     * @returns {object}
     */
    parseUrl: function (url) {
        var a = document.createElement('a');
        a.href = url;
        var loc = {
            protocol: a.protocol,
            host: a.host,
            hostname:a.hostname,
            port: a.port,
            pathname: a.pathname,
            hash: a.hash,
            search: a.search
        };
        a = null;
        return loc;
    },

    /**
     * URLコンポーネントを組み立てる
     * @param {object|Location} comps urlcomponents
     * @returns {string}
     */
    composeUrl: function (comps) {
        return comps.protocol 
            + '//'
            + comps.host
            + comps.pathname
            + comps.search
            + comps.hash;
    },
    
    /**
     * LocationをDLサイトのURLに合わせて拡張したObjectを返す。
     * @param cache default:true キャッシュから取得（location.hash, pushStateを気にしない場合） 
     * @returns {object}
     */
    getDLocation: function (cache) {
        
        cache = (arguments.length > 0) ? cache : true;
        
        // キャッシュから取得
        if (cache && typeof $._dlocationCache === 'object') {
            return $._dlocationCache;
        }
        
        var loc = _.clone(location),
            path = location.pathname.split('/=/'),
            pathname = path[0],
            query = (typeof path[1] === 'string' ? path[1] : ''),
            sitename = $.getSiteName();

        var action = pathname.replace(/^\/[^/]+/, '');
        
        if (action.slice(-1) !== '/') {
            action += '/';
        }
        
        var param = [],
            queryArr = query.replace(/\.html?(\/|$)/, '/').split('/');
        
        for (var i = 0, l = queryArr.length; i < l; i += 2) {
            queryArr[i] && (param[ queryArr[i] ] = (typeof queryArr[i + 1] === 'string') ? queryArr[i + 1] : '');
        }
        
        // オブジェクトを保持
        $.extend({
            _dlocationCache: _.extendOwn(loc, {
                'pathname': pathname,
                'search': '/=/' + query,
                'query': query,
                'sitename': sitename,
                'action': action,
                'param': param
            })
        });
        
        return _.extendOwn({}, $._dlocationCache);
    },

    /**
     * touchからpcのurlを取得
     * @param {string} url
     * @returns {string}
     */
    getPcUrl: function (url) {
        var comps = $.parseUrl(url),
            pattern = new RegExp('^\/([a-z-]+)touch\/(.*)$'),
            matches = pattern.exec(comps.pathname)||[];
        if (matches.length > 0) {
            comps.pathname = '/' + $.rtrim(matches[1], '-') + '/' + matches[2];
        }
        return $.composeUrl(comps);
    },

    /**
     * pcからtouchのurlを取得
     * @param {string} url
     * @returns {string}
     */
    getTouchUrl: function (url) {
        var comps = $.parseUrl(url),
            pattern = new RegExp('^\/([a-z-]+)\/(.*)$');
        if (comps.pathname.indexOf('touch/') === -1) {
            comps.pathname = comps.pathname.replace(pattern, '/$1-touch/$2');
        }
        return $.composeUrl(comps);
    },

    /**
     * ドメインからサイト名を取得
     */
    getSiteName: function () {
        // キャッシュから取得
        if (typeof $._dlocationCache === 'object') {
            return $._dlocationCache.sitename;
        }
        
        var statics = {
            'index.html'  : 'maniax',
            'touch.html'  : 'home-touch',
            'touch-r.html': 'maniax-touch',
            'touch-f.html': 'girls-touch',
            'touch-e.html': 'eng-touch'
        };
        
        var sitename;
        
        // canonicalを優先させる
        if (location.pathname === '/index.php') {
            var canonicalUrl = $('link[rel=canonical]').attr('href');
            sitename = $.parseUrl(canonicalUrl).pathname.split('/')[1];
            // canonicalにはtouch入ってない
            var viewport = document.getElementsByName('viewport');
            if (viewport.length > 0 && viewport[0].tagName === 'META' && sitename.indexOf('touch') === -1) {
                sitename += 'touch';
            }
        } else {
            sitename = location.pathname.split('/')[1];
        }
        
        if (typeof statics[sitename] === 'string') {
            sitename = statics[sitename];
        }

        // ハイフン区切りでない場合
        if (sitename.indexOf('touch') !== -1 && !/\-touch$/.test(sitename)) {
            var sites = _.union(general_sites, female_sites, gay_sites),
                found = _.some(sites, function (id) {
                    if (sitename === id.replace(/\-/g, '')) {
                        sitename = id;
                        return true;
                    } else {
                        return false;
                    }
                });
            if (!found) {
                sitename = sitename.replace('touch', '-touch')
            }
        }

        return sitename;
    },

    /**
     * サイト名から言語を取得
     */
    getSiteLang: function () {
        var site_name = $.getSiteName();
    
        switch (site_name) {
            case 'eng':
            case 'ecchi-eng':
            case 'eng-touch':
            case 'ecchi-eng-touch':
            case 'gay-eng':
            // case 'gay-eng-touch':
                return 'en';
            case 'index.php':  // POSTリクエスト
                return document.getElementsByTagName('html')[0].lang != 'ja' ? 'en' : 'jp';
            default:
                return 'jp';
        }
    },

    /**
     * java.lang.String.hashCodeのクローン
     * @param {string} str
     * @returns {number}
     * @link http://werxltd.com/wp/2010/05/13
     */
    hashCode: function (str) {
        var hash = 0, i, chr, len;
        if (str.length === 0) return hash;
        for (i = 0, len = str.length; i < len; i++) {
            chr   = str.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    },
    
    /**
     * @deprecated
     * @see $.isMobile $.isTablet
     */
    isSmartphone: function () {
        var ua = navigator.userAgent;
        return (ua.indexOf('iPhone')>0||ua.indexOf('iPad')>0||ua.indexOf('iPod')>0||ua.indexOf('Android')>0);
    },

    /**
     * スマホ判定
     * @returns {boolean}
     */
    isMobile: function () {
        return /^.*(iPhone|Android.*Mobile|Windows Phone|IEMobile).*$/i.test(window.navigator.userAgent);
    },

    /**
     * タブレット判定
     * @returns {boolean}
     */
    isTablet: function () {
        return /^.*(iPad|Android.*(?!Mobile)).*$/i.test(window.navigator.userAgent);
    },

    /**
     * スマホサイト判定
     * @returns {boolean}
     */
    isSmartphoneSite: function () {
        return /touch$/.test($.getSiteName());
    }
    
});

jQuery(function($){

    // form ui @todo form関係は切り出す
    
    // 重複サブミットの抑制
    $('form.synchronized').each(function(){

        $(this).bind('submit', function(e){

            // 重複抑制
            if ($(this).attr('data-synchronized'))
            {
                return false;
            }

            $(this).attr('data-synchronized', 1);
        });

        // event実行順序の変更
        $._data(this).events.submit.unshift($._data(this).events.submit.pop());

    });

    // 重複処理のhistory.back対応
    $(window).bind('pageshow', function(e){
        $('form.synchronized').removeAttr('data-synchronized');
    });

    // トグルスイッチ
    $('form')
        .each(function (i, form) {
            var parent = $(form);
            parent
                .find('ul.toggle_switch')
                .each(function (n, ul) {
                    var swi = $(ul),
                        name = swi.data('name'),
                        items = swi.find('li[data-value]'),
                        activeClass = ($.getSiteName().indexOf('touch') !== -1) ? 'current' : 'on';

                    if (!name) {
                        console.warn('toggle_switch: "data-name" attribute not found.');
                        return;
                    } else if (items.length === 0) {
                        console.warn('toggle_switch: "data-value" attribute not found.');
                        return;
                    }

                    var hidden = parent.find('input[name="' + name + '"]');
                    if (hidden.length === 0) {
                        parent.append('<input type="hidden" name="' + name + '" value="" />');
                    }

                    items
                        .bind('click', function (e) {
                            var item = $(e.currentTarget);
                            items.removeClass(activeClass);
                            item.addClass(activeClass);
                            parent.find('input[name="' + swi.data('name') + '"]').val(item.data('value'));
                        });
                });
        });
    
    // end form ui

    // プラグインが読み込まれている場合、メールアドレスのサジェストを設定
    if (typeof $.fn.emailComplete === 'function') {
        var $emailInputs = $('._email-complete');

        // 日本語サイトの場合のみ表示
        if (getSiteLang() == 'jp' && $emailInputs.length > 0) {
            var i = 0;

            $emailInputs.each(function () {
                $(this).emailComplete({
                    index: i++,
                    isSmartphoneSite: $.isSmartphoneSite()
                });
            });
        }
    }

    // 日本語ユーザ以外には英語サイトへの誘導を追加する
    if (getSiteLang() == 'jp' && !/ja/.test(navigator.languages&&navigator.languages[0]||navigator.language||navigator.userLanguage) && $.cookie && !$.cookie('_jp_user'))
    {
        var site = 'eng';

        // 成人向け
        if ($.isAdultSite())
        {
            site = 'ecchi-eng';
        }

        // ゲイ向け
        if ($.getSiteSexCategory() == 'gay')
        {
            site = 'gay-eng';
        }

        // スマホサイト
        if ($.isSmartphone())
        {
            site = $.conv2TouchSite(site)||site;
        }

        var $leader = $('<div class="eng_lead"><a href="#" class="close" alt="Close" title="Close"></a><a href="http://www.dlsite.com/' + site + '/" class="bnr" alt="Click here to shop in English!" title="Click here to shop in English!"></a></div>');

        $leader
            .children('a.close')
                .bind('click', function(e){
                    $.cookie('_jp_user', 1, {"path":"/","expires":1024});
                    $leader.hide();
                    e.preventDefault();
                });

        $('body').append($leader);
    }

    // ネタバレ表示イベントを設定
    $(document).delegate('.review_open', 'click', function () {
        var $reviewMain = $(this).parents('._review_main');

        $reviewMain.find('._SW1').hide();
        $reviewMain.find('._SW2').show();
    });
});

// 作品フィルタリング
(function() {
    var workBlockWorks = {};
    var text_no_work = getSiteLang() === 'en' ? 'Sorry, we did not find any results for your search.' : '該当する作品が見つかりませんでした';
    var format_count = getSiteLang() === 'en' ? '(#cnt# Titles)' : '（#cnt# 本）';
    var $emptyTemplate = $(
        [
        '<div class="main_liquid_box">',
        '  <div class="main_liquid_box_inner_2 pb20 pt20">',
        '    <div class="modify_white_box">',
        '      <div class="modify_white_box_inner">',
        '        <div class="modify_white_box_main">',
        '          <p class="title_message_only">' + text_no_work + '</p>',
        '        </div>',
        '      </div>',
        '    </div>',
        '  </div>',
        '</div>'
        ].join('')
    );

    function workFiltering(params) {
        params = (typeof params === 'object' ? params : {});
        var ageCategory = params.ageCategory || [1, 2, 3];
        var sexCategory = params.sexCategory || [1, 2, 3];

        $('.work_block').each(function(i) {
            if(!$(this).hasClass('filter-ready')) {
                workBlockWorks[i] = $(this).find('td').not('[colspan="2"]');
                $(this).addClass('filter-ready');
            }
        });

        // each
        $.each(workBlockWorks, function(j, $works) {
            var works = [];
            var $tbody = $('<tbody/>')

            $works.each(function(){
                if($.inArray($(this).data('age-category'), ageCategory) !== -1 && $.inArray($(this).data('sex-category'), sexCategory) !== -1) {
                    works.push($(this).clone());
                }
            });

            if(works.length > 0) {
                for(var i = 0; i < works.length; i += 2) {
                    var $tr = $('<tr/>').append(works[i]);

                    if(works[i + 1]) {
                        $tr.append(works[i + 1]);
                    } else {
                        $tr.append($('<td/>'));
                    }

                    $tbody.append($tr);
                }

            } else {
                $tbody.append($emptyTemplate.clone());
            }

            var $header = $('.work_block:eq(' + j + ') .work_update_left h3 span');
            $header.text(format_count.replace(/#cnt#/, works.length));
            $('.work_block:eq(' + j + ') table').empty().append($tbody);
        });
    }

    $(window).bind('workFiltering', function(e, option) {
        workFiltering(option);
    });

    // underscore.string
    if (typeof s === 'function') {
        _.mixin(s.exports());
    }

})();

//流入元計測用(utm_campaign取得cookieにてへ保存)
(function() {
    if(location.search.match(/utm_campaign=(.*?)(&|$)/)){
        var utm_campaign = location.search.match(/utm_campaign=(.*?)(&|$)/)[1];
        if ($.cookie){
            $.cookie('utm_c', utm_campaign, {"path":"/","domain":"dlsite.com","expires": 182});
        }
    }
})();