$.fn.emailencode = function() {

    return this.each( function() {
        var email = $.trim( $(this).text() );
        email = email.replace( ' at ', '@' );
        email = email.replace( ' dot ', '.' );

        if( $(this).hasClass('simple') ) {
            $(this).text( email );
        }
        else {
            $(this).text("");
            $(this).append( $('<a href="mailto:'+email+'">'+email+'</a>') );
        }
    } );


};

$.fn.clearForm = function() {
    return this.each( function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        
        if (tag == 'form')
            return $(':input',this).clearForm();

        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    } );
};

$.fn.imageThumbGallery = function() {

    return this.each( function() {
        var $this = $(this);
        var ul = $(this).find('ul');

        var ulWidth = ul.find('li').length * 66;
        ul.css( 'width', ulWidth );

        var fullWidth = parseInt( $this.css('width'), 10 ) / 2;
        var marginLeft = 0;

        $('#image-gallery-left, #image-gallery-right').click( function() {

            if( $(this).attr('id') == 'image-gallery-left' ) marginLeft = marginLeft - 638;
            if( $(this).attr('id') == 'image-gallery-right' ) marginLeft = marginLeft + 638;

            if( marginLeft < 0 ) marginLeft = 0;
            if( marginLeft > ( ulWidth - 638 ) ) marginLeft = ulWidth - 638;

            ul.animate( { 'margin-left': -marginLeft + 'px' }, 'slow' );

        } );
        
        marginLeft = ul.find('li.active').prevAll().length * 66;
        if( marginLeft < 0 ) marginLeft = 0;
        if( marginLeft > ( ulWidth - 638 ) ) marginLeft = ulWidth - 638;
        ul.animate( { 'margin-left': -marginLeft + 'px' }, 'slow' );

    } );
};



$.fn.formFuRepeatable = function(options) {

    this.each( function() {
        $(this).click( function() {
            
            var $this = $(this);

            var max = $('input[name=count]').attr('max') || 500;

            $('<div class="clear"></div>').insertAfter( $('button.remove').length ? 'button.remove:last' : '.repeatable:last' );
            $('.repeatable:last')
                .clone()
                .insertAfter( $this.parents('fieldset').find('.clear:last') );

            // re-bind events
            JoinEvent.bindProfileName();

            $('<button class="remove"></button>')
                .click( function() {
                    $(this).prevAll(':first').remove();
                    $(this).remove();

                    $this.parents('div.button:first').show();

                    // update price on remove
                    JoinEvent.fillMinEntrancePrice();
                } )
                .insertAfter('.repeatable:last');

            $('.repeatable:last [name]').each( function() {
                var counter = /(\d+)/.exec( $(this).attr('name') );

                $(this).val("");
                $(this).attr('name', $(this).attr('name').replace(counter[0], parseInt(counter[0], 10)+1) );
            } );
            $('input[name=count]').val( $('.repeatable').length );

            // update price
            JoinEvent.fillMinEntrancePrice();

            if ( $('input[name=count]').val() == max ) {
                $(this).parents('div.button:first').hide();
                return;
            }

        } );
    } );

    return this;

};

$.fn.selectAll = function( options ) {
    var config = { target: 'input[type=checkbox]' };

    if( options ) $.extend( config, options );

    this.each( function() {
        $(this).click( function() {

            $(config.target).attr('checked', $(this).attr('checked') );

        } );
    } );

    return this;
}

$.fn.timestamp = function() {
    return this.each( function() {
        if( $(this).attr('timestamped') ) return;

        var s_nd = $.trim( $(this).text() ).split(/[ :,]/);

        var nd = new Array();
        for(var i = 0; i < s_nd.length; i++) if(s_nd[i] && s_nd[i] != undefined) nd[nd.length] = s_nd[i];

        var my_date = new Date( Date.UTC(nd[5], CoolCoz.month[nd[3]], nd[4], nd[0], nd[1]) );

        var y = my_date.getFullYear();
        var m = CoolCoz.get_month[my_date.getMonth()];
        var d = my_date.getDate() < 10 ? "0"+my_date.getDate() : my_date.getDate();
        var h = my_date.getHours(); if(h>12) h=h-12; if(h<10) h="0"+h;
        var min = my_date.getMinutes(); if(min<10) min="0"+min;
        var tz = my_date.getHours() <= 12 ? "AM" : "PM";


        var new_date = h+":"+min+" "+tz+" "+m+" "+d+", "+y;

        if( $(this).find('a').length ) {
            $(this).find('a:first').text(new_date);
        }
        else {
            $(this).text(new_date);
        }

        $(this).attr('timestamped', true);

        var s_nd = $
    } );
}


var FormHelpers = {

    init: function() {
        $('#eventform-allow_paypal_payment, #causeform-allow_paypal_payment').each( function() {
            if( $(this).attr('checked') ) $('#allowed_paypal_payment').show();
            else $('#allowed_paypal_payment').hide();

            $(this).click( function() {
                if( $(this).attr('checked') ) $('#allowed_paypal_payment').show();
                else $('#allowed_paypal_payment').hide();
            } );
        } );
    }

};



var CoolComment = {
    init: function() {

        if( !$('#comment-list').length ) return;

        CoolComment.setCommentEvents( $('ul#comments li') );
        CoolComment.setAddCommentEvents();
        
        CoolComment.setMoreEvent();

        CoolComment.hideLoader();
    },

    rows: 50,

    setCommentEvents: function( comment ) {

        var $comment_count = $('#comment-list h1');

        comment.each( function() {

            var $this = $(this);

            var $delete_form = $(this).find('div.comment-delete form');
            $delete_form.attr('action', $delete_form.attr('action')+'?ajax=1');
            $delete_form.ajaxForm( {
                beforeSubmit: function() {
                    $this.css( 'opacity', 0.5 );
                },
                success: function( response ) {
                    if( response.success ) {
                        $comment_count.text( counter( response.count, 'Comments', 'Comment', 'Comments' ) );

                        $this.slideUp( 'fast', function() { $this.remove(); } );
                    }
                }

            } );

        } );
    
    },

    setAddCommentEvents: function() {
    
        var $add_comment_form = $('form#comment');
        $add_comment_form.attr('action', $add_comment_form.attr('action')+'?ajax=1');

        var $add_comment_form_submit = $('form#comment input[type=submit]');
        var $add_comment_form_textarea = $('form#comment textarea');
        var $comment_count = $('#comments-title');

        $add_comment_form.ajaxForm( {
            beforeSubmit: function() {
                $add_comment_form.css( 'opacity', 0.5 );
            },
            success: function( response ) {
                if( response.success ) {
                    $add_comment_form.css( 'opacity', 1 );

                    $comment_count.text( counter( response.count, 'Comments', 'Comment', 'Comments' ) );
        
                    $add_comment_form_submit
                        .val( $add_comment_form_submit.attr('hidden_val') )
                        .removeClass('noclick');

                    $add_comment_form_textarea.val("");

                    $('ul#comments').show().prepend( $(response.html).hide() );
                    $('ul#comments li:first').slideDown( 'slow' );

                    CoolComment.setCommentEvents( $('ul#comments li:first') );
                }
            }
        } );
    },

    ajaxLoad: function( url ) {

        CoolComment.showLoader();

        $.get( url, { rows: CoolComment.rows }, function( response ) {

            CoolComment.hideLoader();

            var $html = $(response.html);

            CoolComment.setCommentEvents( $html );
            
            $('ul#comments').append( $html );

            CoolComment.updateMore( response.href );

        } ); 
         
    },

    setMoreEvent: function() {

        $('#comment-list #comments-more a').click( function() {

            CoolComment.ajaxLoad( $(this).attr('href') );

            return false;

        } ).click();

    },

    updateMore: function( href ) {

        var $more = $('#comment-list #comments-more a');
    
        if( $more.attr('href') == href ) {
            $more.hide();
        }
        else {
            $more.show();
            $more.attr('href', href);
        }

    },

    showLoader: function() { $('#comments-loader').show(); },
    hideLoader: function() { $('#comments-loader').hide(); }
    
    

};

var FaceTag = {

    tagging: false,

    handler: function( start_handler, stop_handler ) {

        $('#image-area img').load( function() {
            $('#facetags').css( 'width', $('#image-area img').outerWidth() + 'px' );
        } );

        start_handler.click( function() {
            if( FaceTag.tagging ) { return; }
            FaceTag.init( $('#image-area img') );
            
            $(this).hide();
            stop_handler.show();
        } );        

        stop_handler.click( function() {
            if( !FaceTag.tagging ) { return; }
            FaceTag.stop();

            $(this).hide();
            start_handler.show();
        } ).hide();
 
        $('form#facetag-form input:first' ).autocomplete( {
            source: $('form#facetag-form').attr('action') + '/search',
            minLength: 2,
            select: function( event, ui ) {
                $('form#facetag-form input[name=profile_id]').attr( 'value', ui.item.id );
            },
            search: function() {
                $('form#facetag-form input[name=profile_id]').attr( 'value', "" );
            }
        } );
        
        $('form#facetag-form input[type=reset]').click( function() {
            FaceTag.hideFrame();
        } );

        $('form#facetag-form').ajaxForm( {
            beforeSubmit: function() {
                var submit = $('form#facetag-form input[type=submit]');
                submit.attr('value', submit.attr('hidden_val') );

                if( $('form#facetag-form input[name=name]').val().length == 0 ) {
                    return false;
                }
            },
            success: function( response ) {

                $('#image-facetags').html( response.facetags_html );

                FaceTag.container.find( '.image-facetag' ).remove();
                FaceTag.container.append( response.image_facetags_html );

                FaceTag.hideFrame();
            }
        } );

        $('#image-facetags a.remove').live( 'click', function() {

            $.post( $(this).attr('href'), function( response ) {

                $('#image-facetags').html( response.facetags_html );

                $('#facetags').find( '.image-facetag' ).remove();
                $('#facetags').append( response.image_facetags_html );
            }, 'json' );

            return false;
        } );
   
    },

    stop: function() {
        
        FaceTag.tagging = false;

        FaceTag.image.removeClass( 'image-crosshair' );

        FaceTag.container.unbind( 'click' );

        FaceTag.image.bind( 'click.myEvents', function() {        
            window.location.assign( $('#image-controls a:first').attr('href') );
        } );

        FaceTag.hideFrame();
    },

    init: function( image ) {

        if( image.length == 0 ) { return; }

        FaceTag.tagging = true;

        FaceTag.image = image;
        FaceTag.setContainer();

        FaceTag.image.addClass( 'image-crosshair' );
    },

    setContainer: function() {

        var imageParent = FaceTag.image.parents(':first');

        FaceTag.container = $('#facetags');
        FaceTag.frameContainer = $('#facetag');
        FaceTag.frame = $('#facetag-inner-frame');

    
        FaceTag.setEvents();
    },

    setEvents: function() {

        FaceTag.image.unbind( 'click' );

        FaceTag.container.bind( 'click.myEvents', function( e ) {

            FaceTag.showFrame( this, e );

            return false;
        } );
        
        FaceTag.frameContainer.click( function( e ) {
            e.stopPropagation();
        } );


    },

    showFrame: function( element, e ) {

        var x = e.pageX - element.offsetLeft;
        var y = e.pageY - element.offsetTop;

        var frameWidth = parseInt( FaceTag.frame.css('width'), 10 ) + 6;
        var frameHeight = parseInt( FaceTag.frame.css('height'), 10 ) + 6;
        
        var minX = 0; var maxX = FaceTag.image.width() - frameWidth;
        var minY = 0; var maxY = FaceTag.image.height() - frameHeight;

        x = x - frameWidth / 2;
        y = y - frameHeight / 2;

        if( x < minX ) { x = minX; }
        if( y < minY ) { y = minY; }
        if( x > maxX ) { x = maxX; }
        if( y > maxY ) { y = maxY; }

        FaceTag.frameContainer.css( {
            top: y + 'px',
            left: x + 'px'
        } ).show();

        $('form#facetag-form input[name=name]:first').attr( 'value', "" ).focus( function() { } ).focus();
        $('form#facetag-form input[name=profile_id]').attr( 'value', "" );
        $('form#facetag-form input[name=x]').attr( 'value', x );
        $('form#facetag-form input[name=y]').attr( 'value', y );
    },

    hideFrame: function() {
        FaceTag.frameContainer.hide();
    }

};


var CoolCoz = {
    month: { "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 },
    get_month: { 0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec" }
};

var GoogleMaps = {
    geocoder: undefined,
    map: undefined,
    marker: undefined,
    init: function() {

        if( $('#gmap-toggle').length ) {
            $("#gmap-toggle a").click( function() {
                $('#gmap-canvas').toggleClass( 'visible' );
                if( $('#gmap-canvas').hasClass( 'visible' ) )
                    GoogleMaps.mapInit( $('#gmap-canvas') );
            } );
        }
        
        $('.gmap-handler').click( function() {
            var rel = $(this).attr('rel');

            var lat = parseFloat( rel.split(':')[0] );
            var lng = parseFloat( rel.split(':')[1] );

            GoogleMaps.mapAddressInit( $('#gmap-canvas'), lat, lng );
            
            $('#gmap-canvas').dialog( { title: "Event location", width: 450, height: 350 } );
        } );
    },

    mapInit: function( container ) {
        GoogleMaps.geocoder = new google.maps.Geocoder();
        
        var latlng;
        var lat = $('[name="gmap_latitude"]').val();
        var lng = $('[name="gmap_longitude"]').val();
        
        if( lat && lng ) {
            latlng = new google.maps.LatLng(lat, lng); 
        }
        else {
            latlng = new google.maps.LatLng(55.75136641220011, 37.62814725933839); 
        }
        
        var myOptions = { 
            zoom: 8, 
            center: latlng, 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        } ;
        GoogleMaps.map = new google.maps.Map( container.get(0), myOptions ); 
        google.maps.event.addListener( GoogleMaps.map, 'click', function(event) {
            GoogleMaps.addMarker( event.latLng );
        } ); 
        
        GoogleMaps.marker = new google.maps.Marker({
            position: latlng,
            map: GoogleMaps.map
        } );
 
        if( lat == 0 ) GoogleMaps.codeAddress( "Moscow" );
    },

    mapAddressInit: function( container, lat, lng ) {
        GoogleMaps.geocoder = new google.maps.Geocoder(); 
        var latlng = new google.maps.LatLng( lat, lng );
        
        var myOptions = { 
            zoom: 8, 
            center: latlng, 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        }; 
        GoogleMaps.map = new google.maps.Map( container.get(0), myOptions ); 
            
        GoogleMaps.marker = new google.maps.Marker( {
            position: latlng,
            map: GoogleMaps.map
        } );
    },
    
    addMarker: function( loc ) {
        GoogleMaps.marker.setMap(null);
        GoogleMaps.marker = new google.maps.Marker( {
            position: loc,
            map: GoogleMaps.map
        } );

        $('[name="gmap_latitude"]').val( loc.lat() );
        $('[name="gmap_longitude"]').val( loc.lng() );

        return false;
    },

    codeAddress: function( text ) {
        GoogleMaps.geocoder.geocode( { 'address': text }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                GoogleMaps.map.setCenter(results[0].geometry.location);             
                GoogleMaps.addMarker( results[0].geometry.location );
            } else { 
                alert("Geocode was not successful for the following reason: " + status); 
            } 
        } );
    }
}

var Dropdown = {
    init: function() {
        $('#menu a#organizations-link').hover( function() {
            $('#dropdown').css('left',$(this).position().left - 5).css('top',$(this).position().top + 20).show();
        });
        $('#dropdown').hover( function(){}, function() {
            $(this).hide();
        });
    }
};


$(document).ready( function() {

    Dropdown.init();

    GoogleMaps.init(); 

    FaceTag.handler( $('#image-tag-handler'), $('#image-tag-handler-stop') );

    FormHelpers.init();

    CoolComment.init();

    $('#tool-menu-handler').click( function() {

        var $menu = $( $(this).attr('handles') );

        if( $menu.css('display') == 'block' ) {
            $menu.css('display', 'none');
            $(this).find('span.ui-icon-triangle-1-s').show();
            $(this).find('span.ui-icon-triangle-1-n').hide();
        }
        else {
            $menu.css('display', 'block');
            $(this).find('span.ui-icon-triangle-1-n').show();
            $(this).find('span.ui-icon-triangle-1-s').hide();
        }

    } );

    if( $('#upcoming-events ul li').length < 8 ) {
        $('.see-all-upcoming').hide();
        if( $('#upcoming-events ul li').length < 4 ) {
            $('#upcoming-events').css( 'height', '220px' );
        }
    }

    $('.see-all-upcoming').click( function() {
        var height = $('#upcoming-events ul').css('height');
        $('#upcoming-events').animate( { height: height }, 'slow' );
        $(this).hide();
        return false;
    } );
    $('.see-all-past').click( function() {
        var height = $('#past-events ul').css('height');
        $('#past-events').animate( { height: height }, 'fast' );
        $(this).hide();
        return false;
    } );

    $('#tabs').tabs();
    $('#tabs ul li a').click( function () {
        var hash = $(this).attr('href');
        hash = hash.replace('#', '#tab-');
        location.hash = hash; 
    } );
    $(window).bind( 'hashchange', function() {
        var hash = location.hash; hash = hash.replace('tab-', '');
        $('#tabs a[href='+hash+']').click();
    } );

    $('#tabs .ui-tabs-panel').each( function() {
        $(this).find('ul li:last').css( 'border-bottom', 0 );
    } );

    $('form input:submit').removeClass('noclick');
    $('form').submit( function() {
        if( $(this).find('input:submit').hasClass('noclick') ) {
            return false;
        }

        var $submit = $(this).find('input:submit');

        $submit.each( function() {

            $(this).addClass('noclick')
                .attr('hidden_val', $(this).val())
                .val('Please wait...');
        } );
    } );


    $('.repeat-handler').formFuRepeatable();
    $('#invitation-form input[name=selectall]')
        .selectAll( {
            target: 'input[type=checkbox][name=invitation_id]'
        } );

    $('form input#timepicker').datetimepicker( {
        timeFormat: 'hh:mm',
        dateFormat: 'yy-mm-dd',
        stepMinute: 10,
        constrainInput: false,
        showOn: 'both',
        buttonImage: '/static/images/calendar.gif',
        buttonImageOnly: true
    } );

    $('form#filter input[name=datetime]').datetimepicker( {
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText, inst) {
            $(this).parents('form:first').submit();
        }
    } );

    $('*[rel=tooltip]').tooltip( {
        track: false,
        showURL: false,
        delay: 0,
        bodyHandler: function() {
            return $( $(this).siblings('div.tooltip').html() );
        }
    } );

    $('table[class!=sponsor-list] tr[class!=uncount]:even')
        .css( { backgroundColor: '#f0f0f0' } );

    $('input[name=location]').autocomplete( {
        source: '/autocomplete/city',
        minlength: 1
    } );
    $('input[name=city]').autocomplete( {
        source: '/autocomplete/city',
        minlength: 1
    } );
    $('input[name=country]').autocomplete( {
        source: '/autocomplete/country',
        minlength: 1
    } );
    $('input[name=coolcoz_username]').autocomplete( {
        source: '/profile-autocomplete/username',
        minlength: 1
    } );

    $('#image-thumb-gallery').imageThumbGallery();

    $('span.email').emailencode();    


    $('#filter div.reset input:reset').click( function() {
        $(this).parents('form:first').clearForm().submit();
    } );


    $('#form-register input[name=name]').keyup( function() {

        var username = $(this).val().toLowerCase().replace( /\s+/, '-' );

        $('#form-register input[name=username]').val( username );

    } );

    $('#host-sponsors.sortable')
        .sortable( {
            placeholder: 'ui-state-highlight',
            stop: function(event, ui) {

                var sponsor_order = $('#host-sponsors').sortable('toArray').join(',');

                $.post(
                    $('#host-sponsors.sortable').attr('sortable-at'),
                    {
                        sponsor_order: sponsor_order
                    }
                );
            }
        } )
        .disableSelection();

    $('#dialog').dialog( {
        autoOpen: false
    } );
       
    $('.pop-dialog').click( function() {

        var $this = $(this);
        
        var options = {
            title: $(this).attr('title'),
            width: 'auto',
        };
 
        $('#dialog')
            .dialog( 'open' )
            .dialog( options );

        $.getJSON( $(this).attr('href'), function( response ) {

            if( response.redirect ) {
                if( response.redirect == 'self' ) { 
                    document.location.reload( true );
                    return true;
                }

                document.location.href = response.redirect;
            }

            $('#dialog').html( response.html );
            
            var width = parseInt( $('#dialog').find(':first').css('width'), 10 ) + 33;

            $('#dialog').dialog( 'option', 'width', width );
            
            
            $('#verify_raised_cash .textarea').hide();
            $('input[name=cash]').parent().hide();
            
            $('input[name=took_place]:radio[value=0]').click( function() {
                $('#verify_raised_cash .textarea').show();
                $('input[name=cash]').parent().hide();
            });
            $('input[name=took_place]:radio[value=1]').click( function() {
                $('#verify_raised_cash .textarea').hide();
                $('input[name=cash]').parent().show();
            });

            var dataType = 'json';
            if( $this.attr('html') ) dataType = 'xml';
            
            var options = {
                dataType: dataType,
                success: function( response ) {

                    var data = response;
                    
                    if( dataType == 'xml' ) {
                        data = eval( '(' + $(response).text() + ')' );
                    }
                    
                    if( data.redirect ) {
                        if( data.redirect == 'self' ) { 
                            document.location.reload( true );
                            return true;
                        }

                        document.location.href = data.redirect;
                    }

                    if( data.html ) {
                        $('#dialog')
                            .html( data.html )
                            .find( 'form' ).ajaxForm( options );
                        
                    }
                }
            }

            $('#dialog').find('form').ajaxForm( options );

        } );

        return false;
    } );

    $('#profile-image').hover(
        function() { $(this).find('span.hidden').show(); },
        function() { $(this).find('span.hidden').hide(); }
    );


    $('.ts').timestamp();

    if( $('#grid-list').length ) {

        var timeoutHnd;

        $('#grid-search input').keydown( function() { $('#grid-search').submit(); } );
        $('#grid-search select').change( function() { $('#grid-search').submit(); } );

        $('#grid-search').submit( function() {
            if(timeoutHnd) clearTimeout(timeoutHnd);
            timeoutHnd = setTimeout( function() {

                var serialized = $('#grid-search').serialize();

                var newUrl = jqgrid_config['url'] + "?" + serialized;

                $('#grid-list').jqGrid('setGridParam',{ url: newUrl, page: 1 } ).trigger("reloadGrid");

            }, 500 );

            return false;
        } );
        
        
        $('#grid-search div.submit input').click( function() {
            $('#grid-search input[name=search_for]').val("");
            $('#grid-search').submit();
        } );

        var config = {
            datatype: 'json',
            height: 500,
            rowNum: 50,
            rowList: [ 10, 20, 30, 50, 100 ],
            mtype: 'POST',
            pager: '#grid-pager',
            sortorder: 'desc',
            viewrecords: true,
        };        

        config = $.extend( true, config, jqgrid_config );

        $('#grid-list').jqGrid( config );

        if( $('#invitation-update').length ) {
            $('input[type="submit"]').click( function() {
                var ids = $('#grid-list').jqGrid('getGridParam', 'selarrrow');
               
                $('#invitation-update fieldset#hidden-elements').empty(); 
                for(var i = 0; i < ids.length; i++) {
                    $('#invitation-update fieldset#hidden-elements').append(
                        $('<input name="invitation_id" value="'+ids[i]+'" />')
                    );
                }

            } );
        }
        
        
        
        if( $('#hosting-request-update').length ) {
            $('#hosting-request-update').submit( function() {
                var ids = $('#grid-list').jqGrid('getGridParam', 'selarrrow');
               
                $('#hosting-request-update fieldset#hidden-elements').empty(); 
                for(var i = 0; i < ids.length; i++) {
                    $('#hosting-request-update fieldset#hidden-elements').append(
                        $('<input name="hosting_request_id" value="'+ids[i]+'" />')
                    );
                }

            } );
        }

    }

    if( $('form#newsletter').length ) {
        var event_fk = $('#newsletter input[name=event_fk]').val();
        if( event_fk ) {
            $('#newsletter div.select').show();
        }
        else {
            $('#newsletter div.select').hide();
        }

        $('#newsletter-causes-sortable').sortable( { connectWith: '#newsletter-causes' } ).disableSelection(); 
        $('#newsletter-causes').sortable( { connectWith: '#newsletter-causes-sortable' } ).disableSelection(); 
        $('#newsletter-events-sortable').sortable( { connectWith: '#newsletter-events' } ).disableSelection(); 
        $('#newsletter-events').sortable( { connectWith: '#newsletter-events-sortable' } ).disableSelection(); 


    }

    $('#ckeditor-static-page-handle').click( function() {

        $('#ckeditor-static-page').show();
        $('#static-page').hide();

    } );

    $('#image-facetags span').live( 'mouseover mouseout', function( e ) {
        var facetagId = $(this).attr('facetagId');

        if( e.type == 'mouseover' ) {
            $('div.image-facetag[facetagId='+facetagId+']').mouseover();
        }
        else {
            $('div.image-facetag[facetagId='+facetagId+']').mouseout();
        }
    } );

    $('#facetags .image-facetag').live( 'mouseover mouseout', function( e ) { 
        if( e.type == 'mouseover' ) {
            $(this).find( 'span' ).show();
            $(this).addClass('image-facetag-active');
        }
        else {
            $(this).find( 'span' ).hide(); 
            $(this).removeClass('image-facetag-active');
        }
    } );

    JoinEvent.init();
    
    
    
    
} );

var JoinEvent = {
    count:null,
    payment_method:null,
    donation_amount:null,   
    entrance_price:null,
    can_donate:null,

    init: function() {
        JoinEvent.payment_method  = $('input[name=payment_method]');

        if (JoinEvent.payment_method.length <= 0) { // not join event page
            return;
        }       
        
        JoinEvent.count           = $('input[name=count]');
        JoinEvent.donation_amount = $('input[name=donation_amount]');
        JoinEvent.entrance_price  = $('input[name=entrance_price]');

        JoinEvent.can_donate = JoinEvent.donation_amount.length <= 0 ? 0 : 1;

        JoinEvent.bindTriggers();
        JoinEvent.defaults();
    },

    bindTriggers: function() {
        JoinEvent.payment_method.click(function() {
            JoinEvent.managePaymentMethod(1);
        });
     
        JoinEvent.bindProfileName();
    },

    bindProfileName: function() {
        if (JoinEvent.can_donate == 0) { // no donation => fixed entrance
            return;
        }

        // unbind all events
        $('.profile_name').unbind('keyup');

        $('.profile_name').bind('keyup', function() {
            JoinEvent.fillMinEntrancePrice();
        });
    },

    managePaymentMethod: function(fill_min_amount) {
        if (JoinEvent.can_donate == 0) { // no donation => fixed entrance
            return;
        }
        
        if (JoinEvent.selectedPaymentMethod() == 'paypal') {
            if (fill_min_amount) {
                JoinEvent.fillMinEntrancePrice();
            }

            JoinEvent.donation_amount.parent().show();
        }
        else {
            JoinEvent.donation_amount.parent().hide();
        }
    },

    fillMinEntrancePrice: function() {
        if (JoinEvent.can_donate == 0) { // no donation => fixed entrance
            return;
        }

        var entrance_price = JoinEvent.entrance_price.attr('value');
        entrance_price *= JoinEvent.numberOfTickets();

        JoinEvent.donation_amount.attr('value', entrance_price);
    },

    numberOfTickets: function() {
        var real_number = 1;
        var count = parseInt(JoinEvent.count.attr('value'), 10);

        for (var i = 1; i <= count; i++) {
            if ($('input[name=profiles_' + i + '.name]').attr('value')) {
                real_number += 1;
            }
        }
       
        return real_number;
    },

    selectedPaymentMethod: function() {
        for (var i = 0; i < JoinEvent.payment_method.length; i++) {
            var elem = JoinEvent.payment_method[i];
            
            if (elem.checked == true) {
                return elem.value;
            }
        }
    },

    defaults: function() {
        JoinEvent.managePaymentMethod(0);
    }
};













function counter( nr, a, b, c ) {
    if( nr == 0 ) return nr + " " + a;
    if( nr == 1 ) return nr + " " + b;
    return nr + " " + c;
}





