/**
 * Copyright (c) 2011 ZhongLigang. All Rights Reserved
 * $Id: common.js 438 2011-10-17 16:24:41Z maojiming $ 
 * 
 * @file js/common.js
 * @author zhongligang <ZhongLigang@gmail.com>
 * @date 2011-07-20 00:19:03
 */
var loading_mask;
var spinner;
var password_interval, text_interval;

function htmlspecialchars (str) {
    return String(str)
        .replace(/&/g,'&amp;')
        .replace(/</g,'&lt;')
        .replace(/>/g,'&gt;')
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
}

$(document).ready(function () {
    loading_mask = '<div class="J-loading-mask loading-mask"><img src="' + root_url + 'mod/flatstanley/img/loading.gif' + '"></div>';

    $('.comment-input textarea').focus(function () {
        $(this).parent().parent().find('label').hide();
    }).blur(function () {
        this.value === '' && $(this).parent().parent().find('label').show();
    }).blur();
    $('.input label').click(function () {
        $(this).hide();
        $(this).parent().find('input').focus();
    });
    $('.input input[type=password]').focus(function () {
        $(this).parent().find('label').hide();
    }).blur(function () {
        this.value === '' && $(this).parent().find('label').show();
    }).blur();
    $('.input input[type=text]').focus(function () {
        $(this).parent().find('label').hide();
    }).blur(function () {
        this.value === '' && $(this).parent().find('label').show();
    }).blur();
    $('.J-like').click(do_like);
    $('.J-comment').keydown(do_comment).keyup(do_comment_up);
    $('.J-flag').click(do_flag);
    $('.J-delete-comment').click(do_delete_comment);
    if ($('.col2 .feed-bd').size() > 0) {
        home_feed_auto_paging_init();
    }
    if ($('#homePhotoList li').size() > 0) {
        home_photo_auto_paging_init();
    }
    spinner = $('.status').html();
    var inputs = $('.input input[type=password]');
    if (inputs.size() > 0) {
        password_interval = window.setInterval(function () {
            var inputs = $('.input input[type=password]'),
                i, j;
            for (i = 0, j = inputs.size(); i < j; i++) {
                if (inputs.eq(i).val() !== '') {
                    inputs.eq(i).parent().find('label').hide();
                } else {
                    if (inputs.eq(i)[0] !== document.activeElement) {
                        inputs.eq(i).parent().find('label').show();
                    }
                }
            }
        }, 100);
    }

    inputs = $('.input input[type=text]');
    if (inputs.size() > 0) {
        text_interval = window.setInterval(function () {
            var inputs = $('.input input[type=text]'),
                i, j;
            for (i = 0, j = inputs.size(); i < j; i++) {
                if (inputs.eq(i).val() !== '') {
                    inputs.eq(i).parent().find('label').hide();
                } else {
                    if (inputs.eq(i)[0] !== document.activeElement) {
                        inputs.eq(i).parent().find('label').show();
                    }
                }
            }
        }, 100);
    }
});

var home_feed_auto_paging_interval_id = 0;
function home_feed_auto_paging_init() {
    $('.col2').append(loading_mask);
    home_feed_auto_paging_interval_id = window.setInterval(home_feed_auto_paging, 200);
}
function home_feed_auto_paging(e) {
    var el = $('.feed-cmt:last'),
        t = el.offset().top || 0,
        axis = $(window).scrollTop() + $(window).height(),
        root = $('.col2');

    if (axis >= t && !root.data('loading')) {
        root.data('loading', true);
        $.get(get_method_url('user.feed2'), {target_guid:user_id, count: 10, offset:$('.col2 .feed-bd').size()}, function (data) {
            var el;
            if (data.status === 0) {
                data.result = $.trim(data.result);
                if (data.result.length <= 10) {
                    root.find('.J-loading-mask').remove();
                    home_feed_auto_paging_interval_id && window.clearInterval(home_feed_auto_paging_interval_id);
                    home_feed_auto_paging_interval_id = 0;
                } else {
                    el = $(data.result); 
                    el.find('.comment-input textarea').focus(function () {
                        $(this).parent().parent().find('label').hide();
                    }).blur(function () {
                        this.value === '' && $(this).parent().parent().find('label').show();
                    }).blur();
                    el.find('.J-like').click(do_like);
                    el.find('.J-comment').keydown(do_comment).keyup(do_comment_up);
                    el.find('.J-flag').click(do_flag);
                    el.find('.J-delete-comment').click(do_delete_comment);

                    root.find('.J-loading-mask').before(el);

                    $('.J-photo-detail').attr('href', function (i, val) {
                        if (val.substr(-8) != 'iframe=1') {
                            return val + '&iframe=1';
                        } else {
                            return val;
                        }
                    }).fancybox({
                        type: 'iframe',
                        width: 880,
                        height: 600,
                        onStart: disable_scroll,
                        onClosed: resume_scroll,
                        autoScale: false
                    });
                }
            }
            root.data('loading', false);
        }, 'json');
    }
}

function get_method_url(method) {
    return root_url + 'services/api/rest/json?method=' + method;
}

function do_delete_comment(e) {
    e && e.preventDefault && e.preventDefault();

    var id = this.getAttribute('data-guid'),
        me = this;

    if (!confirm(__('Sure to delete this comment?'))) {
        return false;
    }
    $.post(get_method_url('comment.delete2'), {target_guid:id}, function (data) {
        if (data.status === 0) {
            $(me).closest('.J-comment-item').remove();
        } else {
            alert(data.message);
        }
    }, 'json');
}

function do_flag(e) {
    e.preventDefault();

    var id = this.getAttribute('data-guid'),
        me = this;
    $.get(get_method_url('flag.add2'), {target_guid:id}, function (data) {
        if (data.status === 0) {
            //alert('success');
            location.reload();
        } else {
            if (data.message === __('You should login first')) {
                LoginBox.show(function () {
                    do_flag.call(me, {preventDefault:emptyFn});
                });
                return;
            }

            alert(data.message);
        }
    }, 'json');
}

function do_like(e) {
    e.preventDefault();

    var id = this.getAttribute('data-guid'),
        me = this;
    $.get(get_method_url('like.add2'), {target_guid:id}, function (data) {
        var span = $(me).parent().find('.J-like-string'),
            count = parseInt(me.getAttribute('data-count'), 10);
        if (data.status === 0) {
            if (count === 0) {
                span.html(__(' You like this'));
            } else if (count === 1) {
                span.html(__(' You and 1 other person like this'));
            } else {
                span.html(__(' You and #{0} others like this', count));
            }
            if ($(me).hasClass('J-like-remove')) {
                $(me).remove();
            }
        } else {
            if (data.message === __('You should login first')) {
                LoginBox.show(function () {
                    do_like.call(me, {preventDefault:emptyFn});
                });
                return;
            }

            alert(data.message);
        }
    }, 'json');
}

function do_comment_up(e) {
    var val, $me, w, h, tmp, $p;
    if (e.keyCode != '13') {
        $me = $(this);
        w = $me.width();
        val = this.value;

        tmp = $('<div style="font-family:'+$me.css('fontFamily')+';font-size:'+$me.css('fontSize')+';line-height:'+$me.css('lineHeight')+';width:'+w+'px;">'+val+' anohter <div>'); 
        $(document.body).append(tmp);
        h = tmp.height();
        tmp.remove();

        h = h <= 18 ? 18 : h;
        $me.css({
            height: h
        });

        $p = $me.parent().parent();
        $p.css({
            height: 47 + h
        });
    }
}

function do_comment(e) {
    var id, msg, me;

    if (e.keyCode == '13') {
        e.preventDefault();
        id = this.getAttribute('data-guid'),
        msg = $.trim(this.value),
        me = this;

        if (msg) {
            $.get(get_method_url('comment.add2'), {target_guid:id,message:msg,force:true}, function (data) {
                var button,
                    count = 0,
                    el = $('#commentViewCount' + id),
                    match = / (\d+) /.exec(el.html()),
                    loading,
                    new_html = '';

                if (data.status === 0) {
                    unloading = view_comment(me, 0, 2);
                    if (el.data('viewall')) {
                        match = / (\d+) /.exec(el.data('originalhtml'));
                    }

                    if (match) {
                        count = parseInt(match, 10) + 1;
                    } else {
                        count = 1;
                    }

                    if (unloading) {
                        if (el.data('viewall')) {
                            new_html = el.data('originalhtml').replace(/ \d+ /, ' ' + count + ' ');
                        } else {
                            new_html = el.html().replace(/ \d+ /, ' ' + count + ' ');
                        }
                        el.html(new_html);
                        el.data('viewall', 0);

                        if (count > 2) {
                            el.show();
                        }
                    } else {
                        if (el.data('viewall')) {
                            new_html = el.data('originalhtml').replace(/ \d+ /, ' ' + count + ' ');
                            el.data('originalhtml', new_html);
                        } else {
                            new_html = el.html().replace(/ \d+ /, ' ' + count + ' ');
                            el.html(new_html);
                        }
                    }
                    me.value = '';
                    $(me).css({
                        height: $(me).css('lineHeight')
                    });
                } else {
                    if (data.message === __('You should login first')) {
                        LoginBox.show(function () {
                            do_comment.call(me, {preventDefault:emptyFn,keyCode:13});
                        });
                        return;
                    }

                    alert(data.message);
                }
            }, 'json');
        }
    }
}

function view_more_comment(el) {
    var offset = $(el).parent().data('offset');
    if (!offset) {
        offset = 10;
    }

    view_comment(el.parentNode, offset);
}

function view_all_comment(el) {
    var ele = $(el),
        id = el.getAttribute('data-guid');
        cnt = $('#commentView' + id);

    if (ele.data('viewall')) {
        if (view_comment(el, 0, 2)) {
            ele.html(ele.data('originalhtml'));
            ele.data('viewall', 0);
        }
    } else {
        if (view_comment(el, 0, 10)) {
            ele.data('viewall', 1);
            ele.data('originalhtml', ele.html());
            ele.html('Collapse');
        }
    }
}

function view_comment(el, offset, count) {
    var id = el.getAttribute('data-guid');
    if ($('#commentView'+id).data('requesting')) {
        return false;
    }
    $('#commentView'+id).data('requesting', 1);
    $('#commentView' + id).find('.cmt-viewmore').addClass('loading');

    if (!offset || offset < 0) {
        offset = 0;
    }
    $('#commentView'+id).data('offset', offset);

    count = count || 10;
    $.get(get_method_url('comment.list.web'), {target_guid:id, count:count, offset:offset}, function (data) {
        var res = null,
            el = $('#commentView'+id),
            size = 0,
            offset = 0;
        if (data.status === 0) {
            res = $(data.result);
            res.find('.J-like').click(do_like);
            res.find('.J-flag').click(do_flag);
            res.find('.J-delete-comment').click(do_delete_comment);
            size = res.find('div.author').size();
            offset = el.data('offset');
            if (!offset) {
                offset = 0;
            }

            if (offset == 0) {
                el.empty().append(res);
            } else {
                el.append(res);
                el.find('.cmt-viewmore').remove();
            }

            if (size >= 10) {
                el.append('<a onclick="view_more_comment(this);return !1;" class="cmt-viewmore"><img src="' + root_url + 'mod/flatstanley/img/loading.gif' + '">More</a>');
            }

            el.data('offset', offset + size);
            el.data('requesting', 0);
            el.find('.cmt-viewmore').removeClass('loading');
        } else {
            alert(data.message);
            el.data('requesting', 0);
            el.find('.cmt-viewmore').removeClass('loading');
        }
    }, 'json');

    return true;
}

function friend_search_focus(el) {
    el = $(el);

    if ($.trim(el.val()) === el.attr('data-tip')) {
        el.val('').css({
            color: '#666'
        });
    }
}

function friend_search_blur(el) {
    el = $(el);

    if ($.trim(el.val()) === '') {
        el.val(el.attr('data-tip')).css({
            color: '#e3e3e3'
        });
    }
}

function friend_search_down(event) {
    if (event.which != 13 && event.keyCode != 13) {
        return false;
    }

    var input = $('#friendList').find('input'),
        root = '',
        val = $.trim(input.val());

    if (val == input.attr('data-tip')) {
        val = '';
    }

    root = $('#friendList');
    root.data('offset', 0);
    friend_search_request(val);
}

function friend_search_submit() {
    var root = $('#friendList'),
        input = root.find('input');
}

function init_followings() {
    var root = $('#friendList'),
        title = root.find('h3'),
        input = root.find('input');

    title.html('Followings');
    input.css({
        color: '#E3E3E3'
    }).val(input.attr('data-tip'));

    root.data('searchType', 'following').data('offset', 0);

    friend_search_request();
}

function init_followers() {
    var root = $('#friendList'),
        title = root.find('h3'),
        input = root.find('input');

    title.html('Followers');
    input.css({
        color: '#E3E3E3'
    }).val(input.attr('data-tip'));

    root.data('searchType', 'followers').data('offset', 0);

    friend_search_request();
}

function friend_search_request(q) {
    var root = $('#friendList'),
        type = root.data('searchType'),
        offset = root.data('offset'),
        id = root.attr('data-guid'),
        limit = 8,
        requesting = root.data('requesting');

    if (requesting) {
        return false;
    }
    root.data('requesting', 1);

    q = q || '';

    root.find('.op a').addClass('loading');
    $.get(get_method_url('user.'+type+'2'), {target_guid:id, offset:offset, count:limit, q:q}, friend_search_callback, 'json');

    return true;
}

function friend_search_callback(data) {
    var root = $('#friendList'),
        offset = root.data('offset');

    if (data.status === 0) {
        var total = data.result.total,
            friends = data.result.friends,
            num = friends.length,
            html = [],
            i;

        for (i = 0; i < num; i++) {
            html.push(friend_search_render_friend(friends[i]));
        }

        html = $(html.join(''));
        html.find('.J-follow').click(friend_search_follow);
        html.find('.J-unfollow').click(friend_search_unfollow);
        if (offset == 0) {
            root.find('ul').empty().append(html);
        } else {
            root.find('ul').append(html);
        }
        if (num != 0) {
            root.find('.op p').html(1 + ' - ' + (offset+num) + ' of ' + total);
        }
        root.data('offset', offset + num);
    } else {
        alert(data.message);
    }
    root.data('requesting', 0);
    root.find('.op a').removeClass('loading');
}

function friend_search_unfollow(e) {
    e.preventDefault();

    var id = this.getAttribute('data-guid'),
        thisEl = $(this);

    $.get(get_method_url('user.unfollow2'), {target_guid:id}, function (data) {
        if (data.status === 0) {
            thisEl.removeClass('J-unfollow').removeClass('following').html('Follow').unbind().bind('click', friend_search_follow);
        } else {
            alert(data.message);
        }
    }, 'json');
}

function friend_search_follow(e) {
    e.preventDefault();

    var id = this.getAttribute('data-guid'),
        thisEl = $(this);

    $.get(get_method_url('user.follow2'), {target_guid:id}, function (data) {
        if (data.status === 0) {
            thisEl.removeClass('J-follow').addClass('following').html('Following').unbind().bind('click', friend_search_unfollow);
        } else {
            alert(data.message);
        }
    }, 'json');
}

function friend_search_more(el) {
    friend_search_request();
}

function friend_search_render_friend(friend) {
    var html = [];

    html.push('<li>');
    html.push('<a class="avatar" href="'+friend.homeLink+'" target="_blank"><img src="'+friend.avatar+'"></a>');
    html.push('<div class="meta">');
    html.push('<p class="username"><a href="'+friend.homeLink+'" target="_blank">'+friend.username+'</a></p>');
    html.push('</div>');
    if (friend.followedByMe) {
        html.push('<a href="#" class="follow following J-unfollow" data-guid="'+friend.guid+'">'+__('Following')+'</a>');
    } else {
        html.push('<a href="#" class="follow J-follow" data-guid="'+friend.guid+'">'+__('Follow')+'</a>');
    }
    html.push('</li>');

    return html.join('');
}

var home_photo_auto_paging_interval_id = 0;
function home_photo_auto_paging_init() {
    $('#homePhotoList').append(loading_mask);
    home_photo_auto_paging_interval_id = window.setInterval(home_photo_auto_paging, 200);
}
function home_photo_auto_paging() {
    var el = $('#homePhotoList li:last'),
        t = el.offset().top,
        axis = $(window).scrollTop() + $(window).height();

    if (axis >= t) {
        home_photo_loadmore();
    }
}

function home_photo_loadmore() {
    var el = $('#homePhotoList'),
        offset = el.attr('data-offset'),
        limit = el.attr('data-limit'),
        guid = el.attr('data-guid'),
        requesting = el.data('requesting');

    if (requesting) {
        return false;
    }

    el.data('requesting', 1);

    $.get(get_method_url('photo.user2'), {target_guid:guid, count:limit, offset: offset}, function (data) {
        var el = $('#homePhotoList'),
            res, i, j,
            html = [];

        if (data.status === 0) {
            res = data.result;

            j = res.length
            if (j === 0) {
                el.find('.J-loading-mask').remove();
                home_photo_auto_paging_interval_id && window.clearInterval(home_photo_auto_paging_interval_id);
                home_photo_auto_paging_interval_id = 0;
            } else {
                for (i = 0; i < j; i++) {
                    html.push(home_photo_get_item(res[i]));
                }
                html = $(html.join(''));
                el.find('ul').append(html);

                offset = parseInt(offset, 10) || 0;
                el.attr('data-offset', offset + j);

                $('.J-photo-detail').attr('href', function (i, val) {
                    if (val.substr(-8) != 'iframe=1') {
                        return val + '&iframe=1';
                    } else {
                        return val;
                    }
                }).fancybox({
                    type: 'iframe',
                    width: 880,
                    height: 600,
                    onStart: disable_scroll,
                    onClosed: resume_scroll,
                    autoScale: false
                });
            }
        } else {
            alert(data.message);
        }
        el.data('requesting', 0);
    }, 'json');
}

function home_photo_get_item(photo) {
    var html = [];

    html.push('<li><a href="');
    html.push(photo.detail_url);
    html.push('" class="J-photo-detail" rel="photo-group"><img src="');
    html.push(photo.thumbsmall);
    html.push('"></a></li>');

    return html.join('');
}

function init_visiting_stanleys() {
    var el = $('#stanleyList');

    el.data('offset', 0).data('count', 12).data('type', 'visiting').find('ul').empty();
    stanley_request();
}
function init_created_stanleys() {
    var el = $('#stanleyList');

    el.data('offset', 0).data('count', 12).data('type', 'created').find('ul').empty();
    stanley_request();
}
function init_public_stanleys() {
    var el = $('#stanleyList');

    el.data('offset', 0).data('count', 12).data('type', 'public').find('ul').empty();
    stanley_request();
}
function stanley_request() {
    var el = $('#stanleyList'),
        id = el.attr('data-guid'),
        offset = el.data('offset'),
        count = el.data('count'),
        type = el.data('type'),
        requesting = el.data('requesting');
    if (requesting) {
        return false;
    }
    el.data('requesting', 1);
    el.find('.op a').addClass('loading');

    $.get(get_method_url('stanley.'+type), {target_guid:id, offset:offset, count:count}, stanley_load_callback, 'json');
}
function stanley_load_callback(data) {
    var el = $('#stanleyList'),
        offset = el.data('offset'),
        i, j, html = [];

    el.data('requesting', 0);
    el.find('.op a').removeClass('loading');

    if (data.status === 0) {
        data = data.result;
        j = data.length;

        if (j <= 0) {
            //alert('no more');
            return false;
        }

        for (i = 0; i < j; i++) {
            html.push(stanley_get_item(data[i]));
        }
        if (offset == 0) {
            el.data('offset', offset + j).find('ul').empty().append(html.join(''));
        } else {
            el.data('offset', offset + j).find('ul').append(html.join(''));
        }
        $.fancybox.center();
    } else {
        alert(data.message);
    }
}
function stanley_get_item(stanley) {
    var html = [];

    html.push('<li><div class="avatar"><img src="');
    html.push(stanley.medium_avatar);
    html.push('"><a href="');
    html.push(stanley.detail_url);
    html.push('" target="_blank"></a></div><p class="name"><a href="');
    html.push(stanley.detail_url);
    html.push('">');
    html.push(stanley.title);
    html.push('</a></p></li>');

    return html.join('');
}
function stanley_load_more(el) {
    stanley_request();
}

function load_more_participant_by_location(load_prev) {    
    var el = $('#participantList'),
        before = el.data('before'),
        after = load_prev?el.data('after'):'',
        count = el.data('count'),
        requesting = el.data('requesting'),
        lat_up = el.data('lat_up');
        lat_down = el.data('lat_down');
        lon_left = el.data('lon_left');
        lon_right = el.data('lon_right');
        all = el.data('all');
    
    if (requesting) {
        return false;
    }
    el.data('requesting', 1);
    
    var data = {
        lat_up:lat_up,
        lat_down:lat_down,
        lon_left:lon_left,
        lon_right:lon_right,
        all:all,
        after:after,
        before:before,
        count:count
    }
    $.post(get_method_url('participant.load.bylocation'), data, participant_load_callback, 'json');
}

function load_participant_by_location(lat_up, lat_down, lon_left, lon_right, all) {
    var el = $('#participantList');
    el.data('before', '');
    el.data('total' , 0);
    el.data('lat_up', lat_up);
    el.data('lat_down', lat_down);
    el.data('lon_left', lon_left);
    el.data('lon_right', lon_right);
    el.data('all', all);
    el.data('count', 10);
    el.find('ul').empty();
    load_more_participant();
}

function load_more_participant(load_prev) {
    var el = $('#participantList'),
        before = el.data('before'),
        after = load_prev?el.data('after'):'',
        count = el.data('count'),
        requesting = el.data('requesting'),
        city_ids = el.data('city-ids');
    
    if (requesting) {
        return false;
    }
    el.data('requesting', 1);

    $.post(get_method_url('participant.load'), {city_ids:city_ids, after:after, before:before, count:count}, participant_load_callback, 'json');
    return true;
}

function load_participant(city_ids) {
    var el = $('#participantList');
    el.data('before', '');
    el.data('total' , 0);
    el.data('city-ids', city_ids);
    el.data('count', 10);
    el.find('ul').empty();
    load_more_participant();
}

function participant_load_callback(data) {
    var el = $('#participantList'),
        total = el.data('total'),
        i, j, html = [];

    el.data('requesting', 0);
    if (data.status === 0) {
        var count = data.result.count;
        var after = data.result.after;
        data = data.result.data;
        j = data.length;

        el.find('.J-loading-mask').remove();
        if (j <= 0) {
            //alert('no more');
            return false;
        }
        el.data('after', data[0].timestamp);
        if (!total) {
            total = count;
            el.data('total', total);
        }
        for (i = 0; i < j; i++) {
            html.push(participant_get_item(data[i]));
        }
        el.data('before', data[j-1].timestamp).find('ul').append(html.join(''));
        if (j === parseInt(el.data('count'), 10)) {
            el.append('<div class="J-loading-mask loading-mask"><img src="' + root_url + 'mod/flatstanley/img/loading.gif' + '"></div>');
        }
        //var start = (after?count-j+1:total-count+1);
        //var end = start + j - 1;
        //pagination_info = start + '-' + end + ' of ' + total;
        //$('.particpant-pagination').text(pagination_info);
        //if(total <= j)
        //    $('.participant-nav').hide();
        //else {
        //    $('.participant-nav').show();
        //    if (start == 1)
        //        $('.participant-nav .prev').hide();
        //    else
        //        $('.participant-nav .prev').show();
        //    
        //    if (end == total)
        //        $('.participant-nav .next').hide();
        //    else
        //        $('.participant-nav .next').show();
        //}
    } else {
        alert(data.message);
    }
}

function participant_get_item(participant) {
    var html = [
        '<li data-type="user" data-id="',participant.guid,'" data-description="', htmlspecialchars(participant.comments),'" data-name="',htmlspecialchars(participant.name),'" data-time="',participant.last_action,'" data-school="',htmlspecialchars(participant.school),'" data-location="',htmlspecialchars(participant.location),'" data-user-id="',participant.guid,'" onclick="Pp.contact(this)">',
            '<img class="avatar" src="', participant.avatar,'">',
            '<div class="info">',
                '<p class="name">',
                    '<span class="lastlogin">',
                        participant.last_action_short,
                    '</span>',
                    '<span class="user-name">',
                    participant.name,
                    '</span>',
                '</p>',
                (
                    participant.school
                    ? ('<p class="description description-school">' + participant.school + '</p>')
                    : ''
                ),
                '<p class="description description-location">',
                    participant.location,
                '</p>',
                (
                    participant.comments
                    ? ( '<p class="description">'
                            + (
                                participant.comments.length >= 73 
                                ? participant.comments.substr(0, 70) + '...'
                                : participant.comments
                            )
                        + '</p>'
                      )
                    : ''
                ),
            '</div>',
        '</li>'
    ];

    //html.push('<li><a href="#" onclick="message_participant(this, ');
    //html.push(participant.guid);
    //html.push(',\'' + participant.name + '\'); return !1;">');
    //html.push('<p class="name">');
    //html.push(participant.name);
    //html.push('</p></a><p class="school">');
    //html.push(participant.school);
    //html.push('</p><p class="address">');
    //html.push(participant.location);
    //html.push('</p><p class="last">Last Action: ');
    //html.push(participant.last_action);
    //html.push('</p><p class="email">');
    //html.push(participant.email);
    //html.push('</p><p class="phone">');
    //html.push(participant.phone);
    //html.push('</p><p class="comments">');
    //html.push(participant.comments);
    //html.push('</p></li>')

    return html.join('');
}

$(document).ready(function () {
    $('.J-photo-detail').attr('href', function (i, val) {
        if (val.substr(-8) != 'iframe=1') {
            return val + '&iframe=1';
        } else {
            return val;
        }
    }).fancybox({
        type: 'iframe',
        width: 880,
        height: 600,
        onStart: disable_scroll,
        onClosed: resume_scroll,
        autoScale: false
    });
});

function show_photo_detail(el) {
    el = $(el);
    if (el.data('binded')) {
        return false;
    }
    el.data('binded', 1);

    $(el).attr('href', function (i, val) {
        if (val.substr(-8) != 'iframe=1') {
            return val + '&iframe=1';
        } else {
            return val;
        }
    }).fancybox({
        type: 'iframe',
        width: 880,
        height: 600,
        onStart: disable_scroll,
        onClosed: resume_scroll,
        autoScale: false
    }).click();
    return true;
}
var emptyFn = function () {};
var LoginBox = {
    inited: false,
    el: null,
    overlay: null,
    callback: emptyFn,
    show: function (callback) {
        if (!this.inited) {
            this.init();
        }
        this.callback = callback,
        this.reposition();
        this.initVal();
        this.overlay.show();
        this.el.show();
    },
    initVal: function () {
        this.el.find('input[type=password]').val('').blur();
        this.el.find('input[type=text]').val('').focus();
    },
    reposition: function () {
        this.overlay.css({
            width:  $(document).width(),
            height: $(document).height()
        });
        var top = left = 0;
        left = ($(document).width() - this.el.width())/2;
        top = $(document).scrollTop() + 100;

        this.el.css({
            top:  top,
            left: left
        });
    },
    init: function () {
        var el= '',
            overlay = '';

        el = [
            '<div class="widget widget-login" style="position:absolute;z-index:999">',
                '<a class="close" onclick="LoginBox.close();return !1;"></a>',
                '<h3>Login to Join The Fun</h3>',
                '<div class="form">',
                    '<form action="" method="post">',
                        '<span class="input">',
                            '<input type="text" name="username">',
                            '<label>', __('ID or Email'), '</label>',
                        '</span>',
                        '<span class="input">',
                            '<input type="password" name="password" class="password">',
                            '<label>', __('password'), '</label>',
                        '</span>',
                        '<button onclick="$(this.form).submit();return !1;">', __('Sign In'), '</button>',
                        '<p class="getpassword-link">',
                            '<a target="_blank" href="'+flatstanley_root_url+'user/getpassword'+'">', __('Forgot Password?'), '</a>',
                        '</p>',
                        '<label class="rememberme"><input type="checkbox" name="persistent" value="true" checked/><span>', __('Remember Me'), '</span></label>',
                    '</form>',
                '</div>',
                '<p class="errormsg"></p>',
                '<h4>', __('Not a member?'), '</h4>',
                '<p class="register">',
                    __('create an account for free and join the fun today'), '<br>',
                    '<a target="_blank" href="'+flatstanley_root_url+'user/signup'+'">', __('Get Started'), '</a>',
                '</p>',
            '</div>'
        ].join('');
        overlay = '<div style="position:absolute;z-index:5;top:0;left:0;background:black;opacity:.8;-ms-filter:&quot;progid:DXImageTransform.Microsoft.Alpha(Opacity=80)&quot;;filter:alpha(opacity=80);"></div>';

        el = $(el);
        overlay = $(overlay);

        el.find('span.input label').click(function () {
            var me = $(this);
            me.hide();
            me.parent().find('input').focus();
        });
        el.find('input[type=text]').blur(function () {
            var me = $(this);
            if ($.trim(me.val()) == '') {
                me.val('');
                me.parent().find('label').show();
            }
        }).focus(function () {
            var me = $(this);
            me.parent().find('label').hide();
        });
        el.find('input[type=password]').blur(function () {
            var me = $(this);
            if ($.trim(me.val()) == '') {
                me.val('');
                me.parent().find('label').show();
            }
        }).focus(function () {
            var me = $(this);
            me.parent().find('label').hide();
        });

        el.find('form').submit(function (e) {
            e.preventDefault();
            var form = $(this).parent(),
                username = form.find('input[type=text]').val(),
                password = form.find('input[type=password]').val(),
                persistent = form.find('input[type=checkbox]')[0].checked;

            $.post(
                get_method_url('user.login2'),
                {username:username,password:password,persistent:persistent},
                function (data) {
                    if (data.status == 0) {
                        $.isFunction(LoginBox.callback) && LoginBox.callback(data);
                        LoginBox.close();
                    } else {
                        alert(data.message);
                    }
                },
                'json'
            );
        });

        $(document.body).append(el);
        $(document.body).append(overlay);
        this.el = el;
        this.overlay = overlay;
    },
    close: function () {
        this.el.hide();
        this.overlay.hide();
        this.callback = emptyFn;
    }
};

function show_status_bar () {
    $('.status').html(spinner);
    $('.status').css('background-color', '#999');
    $('.status').fadeIn();
};

function hide_status_bar () {
    $('.status').hide();
};
function ajax_error(msg) {
    if(msg)
        display_error(msg);
    else
        display_error(__('Unknown error, please try again later'));
}
function display_error (msg) {
    var el = $('.statusd');
    if (el.length) {
        el.show();
        el.css('background-color', 'red');
        $('.loading').hide();
        el.text(msg);
    } else {
        alert(msg);
    }
};
function notify_user (msg, persistent) {
    var el = $('.status');
    if (el.length) {
        $('.loading').hide();
        el.show();
        el.css('background-color', '#999');
        el.text(msg);
        if(!persistent)
            el.delay(2000).fadeOut('slow');
    } else {
        alert(msg);
    }
};
function disable_scroll() {
    $("body").css({'overflow':'hidden'});
    $("html").css({"overflow":"hidden"}); 
}
function resume_scroll() {
    $("body").css({"overflow":"visible"});
    $("html").css({"overflow":"-moz-scrollbars-vertical"}); 
    $("html").css({"overflow":"auto"});
}
$.fn.selectRange = function(start, end) {
    try {
        return this.each(function() {
            if (this.setSelectionRange) {
                this.focus();
                this.setSelectionRange(start, end);
            } else if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
        });
    } catch (err) {
        return false;
    }
};

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

function ios_pop() {
    return;//sz:disable for now
    var e = new Date(), w = $(document).width(), h = $(document).height();
    e.setTime(e.getTime() + 86400000000);

    if (/*!window.ios_popuped && */!/(^| )__ios_popuped=1(;|$)/i.test(document.cookie)) {

        $(document.body).append([
            '<div style="opacity:.6;background:black;width:',w,'px;height:',h,'px;position:absolute;z-index:10001;top:0;left:0;" id="iosPopupOverlay" onclick="$(\'#iosPopupContent\').remove();$(this).remove();">',
            '</div>',
            '<div style="background:url(',root_url,'mod/flatstanley/img/ios-popup.png);width:828px;height:509px;position:absolute;z-index:10002;left:',(w-828)/2,'px;top:40px;" id="iosPopupContent" onclick="$(\'#iosPopupOverlay\').remove();$(this).remove();">',
                '<div style="padding:144px 268px 0 150px;">',
                    '<p style="color:#06182b;font-size:28px;line-height:60px;font-weight:bold;font-family:Helvetica,Arial;">Flat Stanley Has Gone Mobile</p>',
                    '<p style="margin-top:8px;color:#76797c;font-size:18px;line-height:1.2;font-weight:bold;font-family:Helvetica,Arial;text-align:center;">download the free Flat Stanley  app for your iphone, ipad of ipod touch</p>',
                    '<p style="margin-top:28px;text-align:center;"><a href="http://itunes.apple.com/us/app/flat-stanley/id382161936?mt=8"><img src="',root_url,'mod/flatstanley/img/ios-popup-download.png" width="203" height="66"></a></p>',
                '</div>',
            '</div>'
        ].join(''));
        document.cookie = '__ios_popuped=1; expires='+e.toGMTString();
    }
}
//if (/(iphone)|(ipod)|(ipad)/i.test(navigator.userAgent)) {
    $(document).ready(ios_pop);
//}
/* vim: set ts=4 sw=4 sts=4 tw=100 et: */

