var entrants = '';
var votingEnabled = true;

window.addEvent('domready', function(){
	if($('pods')){
		new Request.JSON({
			'url': rooturl + 'gallery',
			'data': {},
			'onComplete': function(ret){
				entrants = ret.competitionentrants.rows;
				
				showEntrants();
			}
		}).send();
	}

    if($('votebtn'))
        $('votebtn').addEvent('click', doVote);
		
	$(document.body).addEvent('contextmenu', function(){return false});
});

function showEntrants(){
    $('pods').setStyle('width', (Math.floor((entrants.length + 1) / 2) * 217 + 13) +'px');

    new Slider($('scrollbar'), $('dragger'), {
        'onChange': function(step){
            $('pods').setStyle('left', 0 - (($('pods').getCoordinates().width - $('galleryBox').getCoordinates().width) * step / 100) + 'px');
        }
    });

    var curIndex = -1;
	$each(entrants, function(entrant, i){
		new Asset.image('http://www.artsphotography.co.uk' + entrant.photo_thumb.value, {
			onload: function(img){
                curIndex += 1;

				var container = new Element('div', {
					'class': 'entrant',
					'styles': {
						'top':  (curIndex % 2) * 172 + 20,
						'left': Math.floor(curIndex / 2) * 217 + 13
					}
				}).inject($('pods'));
				
				container.store('details', entrant);

				var dimensions = scaleDimensions(img.width, img.height, 204, 136);
                new Element('img', {
                    'class': 'buyNow',
                    'src': 'http://www.lntm.co.uk/webapp/templates/images/buy_now_btn.png',
                    'width': 38,
                    'height': 35,
                    'styles': {
                        'position': 'absolute',
                        'top': 0,
                        'left': 0,
                        'cursor': 'pointer'
                    },
                    'events': {
		                'click': function(e){
                            var target = $(e.target);
                            while(target.retrieve('id', 0) == 0)
                                target = target.getParent();
							if (confirm("Please note:  You will now be safely re-directed to the Arts Photography Events website where you can purchase your image.\n\nFor further assistance please call 0113 267 8888"))
                            location = 'http://www.artsphotography.co.uk/customer/events/event_orderform.php?preload='+target.retrieve('id');
		                }
                    }

                }).inject(container).store('id', entrant.photo_id.value);

				new Element('img', {
					'class': 'photo',
					'src': 'http://www.artsphotography.co.uk' + entrant.photo_thumb.value,
					'alt': 'Entrant Photo',
					'width': dimensions.width,
					'height': dimensions.height,
					'styles': {
						'top': dimensions.top,
						'left': dimensions.left,
                        'cursor': 'pointer'
					},
                    'events': {
                        'click': function(e){
		                    var img = $(e.target);

                            Milkbox.showThisImage('http://www.artsphotography.co.uk' + img.retrieve('large'), '');
                        }
                    }
				}).inject(container).store('large', entrant.photo_filename.value);
                new Element('div', {
                    'class': 'detailbar',
                    'text': entrant.forename.value + (entrant.age.value > 0 ? ' - ' + entrant.age.value : '')
                }).inject(container);

                if(votingEnabled){
    				new Element('img', {
    				    'src': rooturl + 'webapp/templates/images/votebutton_off.png',
    					'class': 'vote hover',
    					'width': 82,
    					'height': 85,
    					'alt': 'Vote for me',
    					'events': {
    						'click': function(e){
    							var entrant = $(e.target).getParent('.entrant').retrieve('details');

                                doVote(entrant);
    						}
    					}
    				}).inject(container);
                } else {
                    alert('Voting is not enabled yet!');
                }

			}.bind(this)
		});
	}.bind(this));
}

function doVote(entrant){
    if(Cookie.read(competition_id+'voted') == '1') {
        alert('Sorry! You are not allowed to vote more than once!');
        return;
    }

    if($defined(entrant.id)) {
        $('competitionentrant_id').value = entrant.id.value;
        $('competition_id').value = competition_id;
        $('voting').showModal();
        return;
    }

  	new Request.JSON({'url': rooturl + 'vote', 'data': $('voting').getElement('form').toQueryString(), 'onComplete': function(t){
    	if(t.redirect){
          new Request.JSON({'url': rooturl + 'vote', 'onComplete': function(t){
            if(t.messages.length == 2 && t.messages[1] == 'voted'){
              Cookie.write(competition_id+'voted', '1');
              var voteImages = $$('img.vote');
              $each(voteImages, function(img){
                  img.destroy();
              });
              $('voting').getElement('fieldset').setStyle('padding-bottom', '10px');
              $('voting').getElement('fieldset').set('html', 'Thank you for your vote!<br /><img src="'+rooturl+'webapp/templates/images/btn_close_off.png" alt="Close" class="hover" style="float: right; cursor: pointer" onclick="$(\'voting\').hideModal()" />');
            } else {
              alert('There was an error with your vote, did you provide a correct email address?');
            }
          }}).send();
    	}
    }}).send()

    return false;
}
