//counter for the photo click
var clickCount;

var timerID = null
var timerRunning = false
var delay = 1000

function initializeTimer(){
        // Set the length of the timer, in seconds
        secs = 10
        stopTheClock()
        startTheTimer()
}

function stopTheClock(){
        if(timerRunning)
            clearTimeout(timerID)
        timerRunning = false
}

function startTheTimer(){
        if (secs==0){
            stopTheClock();
            $('#photo-ad-box').hide();
            $('#ad-close-btn').hide();
            $('#photo-player').show();
            $('#media-photos .controller').show();
            refreshAdsAndAnalytics();
        }else{
            self.status = secs
            secs = secs - 1
            timerRunning = true
            timerID = self.setTimeout("startTheTimer()", delay)
        }
}

function checkClickCount() {
    //change to every click instead of every 3 clicks.
    if (clickCount % 5 == 0) {
        //place in photo ad
        $('#photo-player').hide();
        $('#media-photos .controller').hide();
        $('#photo-ad-box').show();
        $('#ad-close-btn').show();
        document.getElementById('photo-ad-box-iframe').src = adIFrameUrl + '?pos=photogallery&size=300x250&tile=' + tileNumberAndDcopt();
        //after 10 second, remove in photo ad
        initializeTimer();

            //refreshAdsAndAnalytics();
    } else
        refreshAdsAndAnalytics();
}


(function(){

	var controls, end_slide, gallery, index_current, index_last, info_box, li_width, player, src_next, src_prev;

	controls      = false; // DOM object
	end_slide     = {      // Object to store params for the end slide.
		'path'   : '/imgs/decoration/end-slide.gif',
		'name'   : 'End of Slideshow',
		'desc'   : 'Browse other recommended slideshows.',
		'cred'   : ''
	};
	gallery       = false; // Object to store the current gallery index
	index_current = 0;     // Index for current slide
	index_last    = 0;     // Index for last slide
	info_box      = false; // DOM object
	li_width      = 65;    // Desired outerWidth of thumbnails
	player        = false; // DOM object
	src_next      = false; // Path to next image
	src_prev      = false; // Path to previous image

	function findInJson(slug) {
		gallery = false;
		// Determine the current gallery slug.
		for (var i = 0; i < HISTORY.photo_galleries.length; i++) {
			if (HISTORY.photo_galleries[i].slug === slug) {
				return HISTORY.photo_galleries[i];
			}
		}
		// By default, the gallery will be the first in JSON.
		return HISTORY.photo_galleries[0];
	}

	function pageThumbs() {
		$('ul.media-thumbs-photos a.thumb, #end-slide a.thumb').live('click', function (e) {

			e.preventDefault();

			// This assumes an href structure wherein the last element is the slug for
			// the linked gallery. On topic media pages only, it uses the hash mark for
			// identifying the slug.
			var split_char = (this.href.indexOf('/topics/') === -1) ? '/' : '#';
				slug_parts = this.href.split(split_char),
				slug = slug_parts[slug_parts.length - 1];

			// Change the hash in the URL.
			window.location.hash = slug;

			// Create a new gallery from the slug.
			createFromSlug(slug);

			$.scrollTo($('#media-photos'), 400);

            clickCount++;
            checkClickCount();
		});
	}

	function generateMarkup() {
		// Create a new gallery using the data found in the JSON.
		var list = '<div class="slideshow-wrapper"><div class="slideshow-container"></div>' +
			'<div class="controls clearfix"><a class="pill pill-arrow-left" href="#">Prev</a>' +
			'<div class="list"><ul>';

		// Loop through remaining images and add them as well.
		for (var i = 0; i < gallery.photos.length; i++) {
			list += '<li';
			if (i === HISTORY.initial_slide) {
				list += ' class="active"';
			}
			list += '><img class="thumb" src="' +
				HISTORY.static_server_path + gallery.photos[i].path +
				'" /><span></span></li>';
		}
		// Close out the list markup.
		list += '</ul></div><a class="pill pill-arrow-right" href="#">Next</a></div></div>';
		// Append to player.
		player.empty().append(list);
	}

	function renderEndSlide() {
		var markup, to_show, items, playing, item, klass, bg_image;

		items = $('ul.media-thumbs-photos li.col');
		playing = items.index($('ul.media-thumbs-photos li.playing'));

		markup = '<div id="end-slide" style="background-image:url(' + src_prev +
			')"><div class="mask"></div><div class="content clearfix"><h3>More Photos</h3>';

		to_show = (items.length - 1 - playing >= 3) ? 3 : items.length - 1 - playing;

		for (var i = 1; i <= to_show; i++) {
			item = $('ul.media-thumbs-photos li.col:eq(' + (playing + i) + ')');
			bg_image = item.css('backgroundImage').toString().replace(/"/g, "'");
			klass = (i == 3) ? 'col col-2 col-last' : 'col col-2';
			markup += '<div class="' + klass + '" style="background-image:' + bg_image +
				';"><a class="thumb" href="' + $('a', item).attr('href') + '">' +
				$('a', item).text() + '</a> <span class="count">' + $('span.count', item).text() + '</span></div>';

		}
		markup += '</div></div>';
		$('div.slideshow-container', player).prepend(markup);
	}

	function updatePage(slug) {
		for (var i = 0; i < HISTORY.photo_galleries.length; i++) {
			if (HISTORY.photo_galleries[i].slug === slug) {
				$('ul.media-thumbs-photos li.playing').removeClass('playing');
				$('ul.media-thumbs-photos a.thumb[href$="' + slug + '"]').parent().addClass('playing');
			}
		}
	}

	function updateInfoBox() {
		var photo_info, cite_links, middle_path, total, current;

		// Calculate the total number of slides, ignoring the end slide which does not appear on the last slideshow.
		total   = (gallery.slug === HISTORY.photo_galleries[HISTORY.photo_galleries.length - 1].slug) ? gallery.photos.length : gallery.photos.length - 1;
		// Calculate the number of the current slide, ignoring the end slide and the last slideshow.
		current = (total !== gallery.photos.length && index_current + 1 === gallery.photos.length) ? index_current : index_current + 1;

		$('h4', info_box).text(gallery.title);

        // update the share button
        var url = 'http://www.history.com' + HISTORY.context_path + ((HISTORY.body.attr('id') === 'show-photos') ? '/shows/' + HISTORY.show_slug : '' )+ '/photos/' + gallery.slug;
        /*$('ul.content-controls a.addthis_button')
            .attr('addthis:url', url)
            .attr('addthis:title', escape(gallery.title));
        if (window.addthis){
            window.addthis.ost = 0;
            try {
                window.addthis.ready();
            } catch (err){}
        }*/

		$('div.status > span', info_box).text(current + ' of ' + total);

		photo_info  = '<strong>' + gallery.photos[index_current].name +
			':</strong> ' + gallery.photos[index_current].desc;

		photo_info += (gallery.photos[index_current].cred.length > 0) ?
			' <em class="smaller">(Photo Credit: ' + gallery.photos[index_current].cred +
			')</em>' : '';

		$('p:first', info_box).html(photo_info);
		$('p.smaller', info_box).empty();

		if (gallery.slug !== HISTORY.initial_slideshow) {
			$('p.smaller', info_box).empty().append('<a href="' + HISTORY.context_path + '/photos/' + gallery.slug + '" class="more"><span>Browse similar slideshows</span></a>');
		}

		cite_links = $('ul.content-controls a.cite-this');
		middle_path = (HISTORY.body.attr('id') === 'show-photos') ? '/shows/' + HISTORY.show_slug + '/photos/' : '/photos/';
		cite_links.attr('href', HISTORY.context_path + '/ajax/cite.jsp?title=' + escape(gallery.title) +
			'&path=' + escape(HISTORY.context_path + middle_path + gallery.slug));
	}

	function scrollThumbs() {
		var wrap, list, offset;

		// This only applies if there are 9 or more slides.
		if (index_last > 7) {
			wrap = $('div.list', player);
			list = $('ul', wrap);
			offset = 0;

			// Slides 0 thru 3 are positioned full left.
			if (index_current > 3) {
				// Slides (last-3) thru (last), position list full right.
				if (index_current >= index_last - 3) {
					offset = (parseInt(list.width(), 10) - parseInt(wrap.width(), 10));
				} else { // Otherwise, center on the current slide.
					offset = (index_current - 3) * li_width - Math.round(li_width / 2);
				}
				list.animate({ "left" : "-" + offset + "px" }, 500);
			} else {
				list.animate({ "left" : "0px" }, 500);
			}
		}
	}

	function bindPrevNext() {
		$('#photo-player a.pill-arrow-left, #media-photos div.controller a.arrow-lt')
			.unbind('click').click(function (e) {
				e.preventDefault();
				if (src_prev) {
					activate(src_prev);
				}

                clickCount++;
                checkClickCount();
			});
		$('#photo-player a.pill-arrow-right, #media-photos div.controller a.arrow-rt')
			.unbind('click').click(function (e) {
				e.preventDefault();
				if (src_next) {
					activate(src_next);
				}

                clickCount++;
                checkClickCount();
			});
	}

	function disableNext() {
		$('a.pill-arrow-right', controls).addClass('pill-arrow-right-disabled');
		$('a.arrow-rt', info_box).addClass('arrow-rt-disabled');
	}

	function enableNext() {
		$('a.pill-arrow-right-disabled', controls).removeClass('pill-arrow-right-disabled');
		$('a.arrow-rt-disabled', info_box).removeClass('arrow-rt-disabled');
	}

	function disablePrev() {
		$('a.pill-arrow-left', controls).addClass('pill-arrow-left-disabled');
		$('a.arrow-lt', info_box).addClass('arrow-lt-disabled');
	}

	function enablePrev() {
		$('a.pill-arrow-left-disabled', controls).removeClass('pill-arrow-left-disabled');
		$('a.arrow-lt-disabled', info_box).removeClass('arrow-lt-disabled');
	}

	function calculateIndices() {
		index_last = gallery.photos.length - 1;

		// Determine the current index based on which thumb is active.
		index_current = $('ul li', player).index($('ul li.active', player));

		if (index_current == 0) {
			// First slide
			src_prev = false;
			src_next = HISTORY.static_server_path + gallery.photos[1].path;
			disablePrev();
			enableNext();
		} else if (index_current == index_last) {
			// Last slide
			src_prev = HISTORY.static_server_path + gallery.photos[index_current - 1].path;
			src_next = false;
			enablePrev();
			disableNext();
		} else {
			// Middle slide
			src_prev = HISTORY.static_server_path + gallery.photos[index_current - 1].path;
			src_next = HISTORY.static_server_path + gallery.photos[index_current + 1].path;
			enablePrev();
			enableNext();
		}
	}

	function activate(src) {
		var container = $('div.slideshow-container', player);
		var thumb = $('ul img[src=\"' + src + '\"]', player).parent();

		thumb.addClass('active').siblings('.active').removeClass('active');

		container.empty();

		calculateIndices();
		scrollThumbs();
		updateInfoBox();

		if (src !== HISTORY.static_server_path + end_slide.path) {
			$('<img src="' + src + '" class="slide" style="display:none;" />').appendTo(container);
			// Brief pause to make sure the image is loaded into the DOM before revealing.
			setTimeout(function(){
				$('img.slide', container).fadeIn(1500)
			}, 100);
		} else {
			renderEndSlide();
		}
	}

	function createFromSlug(slug) {
		var obj, thumb;

		// Subsequent or hash-requested slideshows begin on the first slide;
		if (slug !== HISTORY.initial_slideshow) {
			HISTORY.initial_slide = 0;
		}

		gallery = findInJson(slug);

		generateMarkup();

		controls = $('div.controls', player);

		$('ul', player).width(gallery.photos.length * li_width);

		for (var i = 0; i < gallery.photos.length; i++) {
			obj = $('ul li:eq(' + i + ')', player);
			obj.click(function() {
				activate($(this).find('img').attr('src'));

                clickCount++;
                checkClickCount();
			}).hover(function() {
				$(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			});
		}

		bindPrevNext();
		controls.hide();
		updatePage(gallery.slug);
		activate(HISTORY.static_server_path + gallery.photos[HISTORY.initial_slide].path);
	}

	// Gallery Initialization
	jQuery(function ($) {

		HISTORY.initial_slide--; // Initial slide is 1-indexed, slides are 0-indexed.

        clickCount = 0;

        $('#ad-close-btn').live('click',function (e){
            $('#photo-ad-box').hide();
            $('#ad-close-btn').hide();
            $('#photo-player').show();
            $('#media-photos .controller').show();
            stopTheClock();
            refreshAdsAndAnalytics();
        });

        //hide in photo ad div on page load
        $('#photo-ad-box').hide();
        $('#ad-close-btn').hide();

		// Only initialize on first page load.
		if (!player) {

			player = $('#photo-player');
			info_box = player.next();

			if (player.length > 0) {

				// Append end slides to all but the last gallery.
				for (var i = 0; i < HISTORY.photo_galleries.length - 1; i++) {
					HISTORY.photo_galleries[i].photos[HISTORY.photo_galleries[i].photos.length] = end_slide;
				}

				// Add live click event to the gallery image.
				$('img.slide', player).live('click', function (e) {
					if (src_next) {
						activate(src_next);

                        clickCount++;
                        checkClickCount();

					}
				});

				player.hover(function () {
					setTimeout(function () {
						controls.show();
						scrollThumbs();
					}, 500);
				}, function () {
					setTimeout(function () {
						controls.hide();
					}, 750);
				});

				pageThumbs();

				// Create initial gallery with slug precedence:
				//     URL hash > initial_slideshow global > first gallery in JSON
				createFromSlug(window.location.hash.length > 1 ?
					window.location.hash.replace('#','') : (HISTORY.initial_slideshow.length > 0 ?
					HISTORY.initial_slideshow : HISTORY.photo_galleries[0].slug));
			}
		}
	});

})();



