/*
 -*- mode: javascript; coding: utf-8 -*-
 $Id$

 Copyright (c) 2010 ISHIKAWA Mutsumi <ishikawa@hanzubon.jp>
 This program is covered by the GNU General Public License 2
*/

function noreferrer(a){
    if (!$(a).hasClass('href_replaced')) {
	var url = $(a).attr('href');
	var html = '<html><head><script type="text/javascript">'
	    + 'document.write(\'<meta http-equiv="refresh" content="0;url='+url+'">\');'
	    + '<'+'/script></head><body></body></html>';
	$(a).attr('href', 'data:text/html;charset=utf-8,'+encodeURIComponent(html)).addClass('href_replaced');
    }
}

function restore_original(a){
    $(a).attr('href', $(a).attr('o_href')).removeClass('href_replaced');
}


/* だいぶカオスってきたので整理しないとダメだな こりゃ(わら */
jQuery(document).ready(function($) {
    /* 画像の preload */
    var preload_image = new Array('right_arrow.png', 'stripe.png',
				  'twg_iphone_toolbar_icons/icon_arrow_left.png',
				  'twg_iphone_toolbar_icons/icon_circle_arrow_right.png',
				  'twg_iphone_toolbar_icons/icon_blog.png',
				  'twg_iphone_toolbar_icons/icon_users.png',
				  'twg_iphone_toolbar_icons/icon_post.png',
				  'twg_iphone_toolbar_icons/icon_flag.png',
				  'twg_iphone_toolbar_icons/icon_cancel.png',
				  'ajax-loader.gif');

    for (i = 0; i < preload_image.length; i++) {
	$('#preload').append('<img src="' + web_root + preload_image[i] + '" />');
    }

    /* animation end event がハンドリングできるか判定 */
    var animation_end = false;
    var el = document.createElement('div');
    if ('WebkitTransform' in el.style) {
	animation_end = 'webkitAnimationEnd';
    }
    el = null;

    var has_ws = ('WebSocket' in window);
    var ws = false;

    var map_load = true;
    var myScroll;

    $(window).bind('orientationchange', function(){
	adjust_height();
	adjust_map();
	setTimeout(scrollTo, 300, 0, 1);
    });

    /* 初期ページデータのロード */
    $('#index').load(web_root + session_id + '/index', reinit);

    function _ws_ping() {
	if (has_ws && ws) {
	    ws.send('ABC');
	    alert('send ABC');
	}
	setTimeout(_ws_ping, 10000);
    }

    /* _ws_ping(); */

    function adjust_map() {
	if ($('#map_canvas').length != 0) {
	    var pos = $(document).height() - 20;
	    setTimeout(scrollTo, 300, 0, 1);
	    $('#map_canvas').height(pos);
	}
    }


    function adjust_height() {
	$('.scroll_wrap').each(function() {
	    $(this).height(0);
	});
	var hi = $('.current:first').height();
	$('.toolbar, .edit, .info').each(function() {
	    hi -= $(this).attr('offsetHeight');
	});
	$('.scroll_wrap').each(function() {
	    $(this).height(hi);
	});
    }

    function reinit(resp, status, xhr) {
	if (status != 'success' || typeof resp == 'undefined' || resp == '' || xhr.status != 200) {
	    var reload_url = window.location.protocol + '//' + window.location.host + web_root;
	    window.location.replace(reload_url);
	    return false;
	}

	var from = $('.current');
	var to = $(this);
	var animation = to.attr('animation');

	if (animation_end != false && animation && animation != '')  {
	    to.addClass(animation + ' in current').one(animation_end, _animation_callback);
	    from.addClass(animation + ' out');
	} else {
	    to.addClass('current');
	    _animation_callback();
	}
	$('#loading').css('display', 'none').height(0);

	function inner_reload(url, anim, param) {
	    scrollTo(0, 0);
	    $('#loading').css('display', 'block').height($(document).height());
	    $('body').append($('<div id="'+url.replace('/','_')+'"></div>').attr('animation', anim).load(web_root + session_id + '/' + url, param, reinit));

	    if (ws) {
		ws.close();
		ws = false;
	    }

	    if (has_ws && url.match(/all\/([0-9]+)/)) {
		var cid = RegExp.$1;
		ws = new WebSocket('ws://' + location.host + '/' + session_id + '/push/' + cid);
		ws.addEventListener("open",
				    function () {
					/* alert('open'); */
				    },false);
		ws.addEventListener("close",
				    function () {
					/* alert('close') */
				    }, false);
		ws.addEventListener("message",
				    function (e) {
					var data = JSON.parse(e.data);
					$('div.scroll_wrap ul.edgetoedge li.sep').after(data.formatted);
				    },false);
	    }

	    return false;
	}

	function _animation_callback() {
	    from.remove();
	    to.removeClass('in reverse slide');
	    adjust_height();
	    setTimeout(scrollTo, 300, 0, 1);

	    $('.internal').one('click', function() {
		var anim = ($(this).hasClass('no_anime') ? '' : $(this).hasClass('reverse') ? 'slide reverse' : 'slide');
		inner_reload($(this).attr('rel'), anim);
		return false;
	    });

	    $('.internal_form').bind('submit', function () {
		$('#m').blur();
		if (has_ws && ws) {
		    ws.send(JSON.stringify({url: $(this).attr('action'),
					    param: $(this).serializeArray()}));
		    $('#m', this).val('');
		    $("input[name='stamp']", this).val(parseInt((new Date)/1000));
		    $('li.messagenew').addClass('message').removeClass('messagenew');
		} else {
		    inner_reload($(this).attr('action'), '', $(this).serializeArray());
		}
		return false;
	    });

	    $('.menu_button').bind('click', function() {
                $('.floaty').toggle();
                $('#send_location').forcus();
                return false;
            });

	    if (!navigator.geolocation) {
		$('#post_location').css({'display': 'none'});
	    }

	    if ($('#map_canvas').length != 0) {
		adjust_map();
		if (map_load) {
		    map_load = false
		    $.getScript(web_root + 'geopost-keitairc.js', function() {
			append_location();
		    });
		} else {
		    append_location();
		}
	    }

	    if ($('#scroll').length != 0) {
		if (typeof myScroll != 'undefined' && myScroll != null) {
		    myScroll.element.removeEventListener('touchstart', myScroll);
		    myScroll.element.removeEventListener('touchmove', myScroll);
		    myScroll.element.removeEventListener('touchend', myScroll);
		    myScroll.element.removeEventListener('DOMSubtreeModified', myScroll);
		    window.removeEventListener('orientationchange', myScroll);
		    myScroll = null;
		}
		myScroll = new iScroll('scroll');
		var sc = $('#scroll');
		var mark = $('#reload_mark');
		if (mark.length != 0) {
		    sc.bind('touchmove', function() {
			if (myScroll.y > 30) {
			    mark.attr('reload', 'on').show();
			}
		    });
		    sc.bind('touchend', function() {
			mark.hide();
			if (mark.attr('reload') == 'on') {
			    mark.removeAttr('reload');
			    inner_reload(mark.attr('rel'), '');
			}
		    });
		}
		$('.toolbar h1').bind('click', function() {
		    myScroll.scrollTo(0,0);
		});
	    }
	}
    }
});
