from django.conf import settings
from django import template
register = template.Library()

from rldjango.apps.imadj.models import Image
from itertools import chain



@register.simple_tag
def gallery_transition(box_id, tag_id, size_id='', limit=0, border=True, width=0, height=0):
    images = Image.objects.all()
    if tag_id:
        images = images.filter(tags__id=tag_id)
    if size_id:
        images = images.filter(size__id=size_id)
    images = images.filter(format__in=('JPEG','GIF','PNG'))
    images_head = images.filter(ordering__gt=0).order_by('ordering')
    images_foot = images.filter(ordering=0).order_by('?')
    images = list(chain(images_head,images_foot))
    if limit:
        images = images[0:limit]
    
    border_class = ''
    if border != 'False' and border != '0' and border != 0:
        border_class = ' transition_border'
    
    if len(images):
        if not width or not height:
            width = images[0].width
            height = images[0].height
        html = '<div id="%s" class="transition%s" style="width:%dpx; height:%dpx">' % (box_id, border_class, width, height)
        for image in images:
            html += """<a><img src="%s/%s" border="0" /></a>""" % (settings.IMADJ_URL, image.id)
        html += '</div>'
    else:
        if not width or not height:
            width = 300
            height = 200
        html = """<div id="%s" class="transition%s" style="width:%dpx; height:%dpx; border:2px solid #f00; color:#f00; font-weight:bold; text-align:center">NO IMAGES</div>""" % (box_id, border_class, width, height)
        
    return html

@register.simple_tag
def gallery_transition_head(box_id, timeout='3000', speed='1000', fx='fade'):
    html = """
        <script type="text/javascript" src="%simadj/rsrc/js/jquery.cycle.all.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#%s').cycle({
                    timeout: %s,
                    speed: %s,
                    fx: '%s'
                });
            });
        </script>""" % (settings.MEDIA_URL, box_id, timeout, speed, fx)
    return html
