$(document).ready(function(){

	//add an empty element to the start of the array so the page count starts at 1
    var popon = new Array("empty");
    imagesArray = popon.concat(imagesArray)

    //set the number of images the user has to see to refresh the ads
    var adRefreshClicks = 1;

    if(adChannel == "girls" || adChannel == "mynuts"){
        adRefreshClicks = 2;
    }

    var clicks = 0;
    
    function updateHash(key){
        //add the image ID to the url hash.  The Jquery history plugin will then detect this and update the image
        parent.location.hash = key;
    }

    function replaceImage(key){
        clicks ++;
        //swap the image
        $('a#galleryLink img').attr('src','/images/gallery/'+imagesArray[key]['filename']);
        
        var img_id = imagesArray[key]['image_id'];
        
        if($('a#galleryLinkMynuts img').length){
        	$('a#galleryLinkMynuts img').attr('src',imagesArray[key]['filename']);
        	
        	if($('.photo_count').length){
                // facebook link
                var newstring = $('.facebook > li > iframe').attr('src').replace(/photos\/.*\/album/,'photos/'+img_id+'/album');
                $('.facebook > li > iframe').attr('src',newstring);
                // added on
               // var fDate = formatDate(imagesArray[key]['stamp_create']);
                $('#added_on').html('Added on '+imagesArray[key]['stamp_create']);
                // send to a friend
            	var friendUrl = $('#send_to_a_friend_url').val().replace(/photos\/.*\/album/,'photos/'+img_id+'/album');
                $('#send_to_a_friend_url').val(friendUrl);
                // rating
                setRating(img_id,imagesArray[key]['rating']);
                // tags - todo [are there any?]
            };
        }

        //change the page numbering
        if($('.photo_count').length){
            $('.photo_count').children('p').html('Photo '+key+' of '+arrayLength);
        };
        
        //replace the image caption
        if(imagesArray[key].caption.length){
            $('.heading h2').html(imagesArray[key].caption+' - '+articleTitle);
            if($('div.caption').length){
                $('div.caption').html(imagesArray[key].caption);
            }
        }
        // now post meta data to omniture
        if (typeof s != "undefined") {
            void(s.t());
        }
        //and to google analytics
        if(typeof(_gaq) != "undefined") {
		        _gaq.push(
		          ['localPageTracker0._setAccount', 'UA-67691-7'],
		          ['localPageTracker0._trackPageLoadTime'],
		          ['localPageTracker0._trackPageview', location.host+location.pathname]
		        );

		        _gaq.push(
		          ['globalPageTracker0._setAccount', 'UA-11428852-1'],
		          ['globalPageTracker0._trackPageLoadTime'],
		          ['globalPageTracker0._trackPageview', location.host+location.pathname]
		        );
		}

        //replace or refresh the ads, only if the required number of pics have been seen
       if(clicks == adRefreshClicks){
            refreshAds('ad_leaderboard728x90','leaderboard');
            refreshAds('ad_mpu300x250','mpu');
            refreshAds('ad_skyscraper160x600','sky');
            clicks = 0;
        }
        
        if($('a#galleryLinkMynuts img').length){
            // mynuts only
            if(imagesArray[key]['image_id']){
           	replaceComments(imagesArray[key]);
            }
        }
    }

    function refreshAds(id,format){
        //if the ads currently exist on the page in an unchanged state (ie- the user has not clicked 'next' yet)
        if($('#'+id).is('div')){
            //create a new iframe with the same height/width as the ad
            var myIFrame = $('<iframe />');
            $(myIFrame).attr({
                frameBorder : '0',
                scrolling : 'no',
                width : $('#'+id).css('width'),
                height : $('#'+id).css('height'),
                border : 0
            });
            //replace the ad with the iframe
            $('div#'+id).replaceWith($(myIFrame));
            //load a new ad into the iframe
            $(myIFrame).attr({
                src : '/application/ad/format/'+format+'/adchannel/'+adChannel,
                id : id
            })
        }else if($('#'+id).is('iframe')){
            //if the ad is already in an iframe, just refresh it.
            document.getElementById(id).contentWindow.location.reload(true);
        }
    }
    
    function replaceComments(image){
    	/* is owner */
    	if('owner' == userstatus){
			var ownr=1;
		}

    	$('#comments').empty();
    	data = image['comments'];
    	if(3 < data.length){
    		$('#comments').addClass('scroll');
    	}
    	
    	photoid = image['image_id'];

    	$.each(data, function(i, item){
    		$('#comments').append('<div class="article_small" id="id'+i+'"></div>');
    		if(data.length == (i-1)){
    			$('#comments > div#id'+i).addClass("last");
    		}
    		
    		dateTime = item['stamp_create'];

    		$('#comments > div#id'+i).append('<a href="/mynuts/'+item['username']+'"><img /></a>');
    		$('#comments > div#id'+i+' > a > img').attr('src','/avatar.php?u='+item['user_id']);
    		$('#comments > div#id'+i+' > a > img').attr('alt',item['username']);
    		$('#comments > div#id'+i).append('<h4><a href="/mynuts/'+$.trim(item['username'])+'">'+$.trim(item['username'])+'</a> says:</h4>');
    		$('#comments > div#id'+i).append('<p>'+item['comment']+'</p>');
    		$('#comments > div#id'+i).append('<ul></ul>');
    		$('#comments > div#id'+i+' ul').append('<li class="date">'+dateTime+'</li>');
    		if(1 == ownr){
    			$('#comments > div#id'+i+' ul').append('<li class="delete"><span class="delete"><a href="javascript:reportComment(\'/mynuts/'+item['username']+'/comments/report/'+item['comment_id']+'\');">Report&nbsp;comment&nbsp;to&nbsp;moderator</a></span> | or | <span class="delete"><a id="cdl" href="/mynuts/'+item['username']+'/comments/delete/'+item['comment_id']+'">Remove comment</a></span></li>');
    		} else {
        		$('#comments > div#id'+i+' ul').append('<li class="delete"><a href="javascript:reportComment(\'/mynuts/'+item['username']+'/comments/report/'+item['comment_id']+'\');">Report comment to moderator</a></li>');
    		}
    	});
		
    	// update number of comments label
		$('.header > h3').html('Comments '+data.length);
		
		// comments form
		if($('.comments input#comments_itemid').length){
		    $('.comments input#comments_itemid').val(photoid);
	    }

    }
    
    function setRating(img_id,rating)
    {
    	$('#ratecontainertext').html('Rate:');
    	$('ul#stars').empty();
    	$('ul#stars').css('visibility','visible');
    	
    	var counter = [1,2,3,4,5];
    	$.each(counter, function(i, item){
			var letter_s = 's';
			if(0 < i){
				letter_s = '';
			}
			if(rating >= item){
				var	current_rating = 'class="current-rating"';
			} else {
			var	current_rating = null;
			}
    		$('ul#stars').append('<li><a href="/mynuts/ratings/add/'+img_id+'/nuts.photo/'+item+'" title="'+item+' star'+letter_s+' out of 5" '+current_rating+'>'+item+'</a></li>\n');
    	});

    }
    
    // how many images do we have? Get this here for use in various loops below
    var arrayLength = imagesArray.length-1;  

    currentImage = imgRequest;
    $('a.next, a#galleryLink, a#galleryLinkMynuts, li.next, div.next a, li.rating a').click(function(){
        currentImage ++;
        if (currentImage > arrayLength) { // loop back to start
            currentImage = 1;
        }
        updateHash(currentImage);
        return false;
    });
    $(document).bind('keydown', 'right', function(){
        currentImage ++;
        if (currentImage > arrayLength) { // loop back to start
            currentImage = 1;
        }
        updateHash(currentImage);
        return false;
    });
    $('a.prev, li.previous, div.prev a, li.prev a').click(function(){
        currentImage --;
        if (currentImage < 1) { // loop back to end
            currentImage = arrayLength;
        }
        updateHash(currentImage);
        return false;
    });
    $(document).bind('keydown', 'left', function(){
        currentImage --;
        if (currentImage < 1) { // loop back to end
            currentImage = arrayLength;
        }
        updateHash(currentImage);
        return false;
    });
    $.history.init(function(hash){
        //when the window loads, or the hash on the URL changes...
        if(hash.length && is_int(hash)){
            replaceImage(hash);
            currentImage = hash;
        }
    });

});

function is_int(value){
	if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
	return true;
	} else {
	return false;
}
}


