/**
*	Basic Image Viewer 
*   TODO: add carousel/ thumbnails
**/
POP.ImageViewer = function (targets, config) {
    var _self = this,
		targets = $(targets),
		config = $.extend({
		    type: 'detail',
		    speedOut: 300,
		    speedIn: 300,
		    leftOffset: 10,
		    endlessScroll: true
		}, config || {}),
		_animate,
		_pageURL = null,
		_isInit = true,
		_isAnimating = false;

    __init();

    function __init() {
        _animate = (jQuery.support.opacity) ? true : false;
		_pageURL = document.location.pathname;
        for (var i = 0, len = targets.length; i < len; i++) {
            //TODO: get the type dynamically from the ul element
            var imageViewer = POP.ImageViewerType.factory(config.type);
            imageViewer.view($(targets[i]), __create, null, _self);
        }
    }

    //put together the elements from POP.ImageViewerType.view on callback
    function __create(obj) {
        var ul = $(obj.find('.viewer-assets')),
			li = ul.find('li'),
			firstLI = li.first(),
			windowWidth = obj.width(),
			assetLength = li.length,
			origLeft = li.css('left'),
			arr = obj.find('.viewer-ui-left a');

        //console.log('Create: ' + obj.html());

        //store needed values
        obj.data({
            'left': origLeft,
            'length': assetLength,
            'width': windowWidth,
            'current': -1
        });

        //position all list items
        li.css({
            'left': windowWidth + 'px'
        });

        //go to first slide 
        //TODO: Abstract this out w/o using btn click event
        __onRightBtnClick(obj);
        __addEventListeners(obj);
    }

    function __addEventListeners(obj) {
        var leftBtn = obj.find('.viewer-ui-left a'),
			rightBtn = obj.find('.viewer-ui-right a');

        leftBtn.bind('click', function (e) {
            e.preventDefault();
            var inactive = $(e.currentTarget).hasClass('inactive');
            if (!inactive) {
                __onLeftBtnClick(obj);
            }
        });

        rightBtn.bind('click', function (e) {
            e.preventDefault();
            var inactive = $(e.currentTarget).hasClass('inactive');
            if (!inactive) {
                __onRightBtnClick(obj);
            }
        });
    }

    function __update(obj, num, len) {
        if (!config.endlessScroll) {    // if endlessScroll, no need to disable arrows
            __updateArrows(obj, num, len);
        }
        __updateCounter(obj, num, len);
        __updateCaption(obj, num, len);
        __updateCredit(obj, num);
		_isInit = false;
    }

    function __updateArrows(obj, num, len) {
        var arrLeft = obj.find('.viewer-ui-left a'),
			arrRight = obj.find('.viewer-ui-right a');
        if (num <= 0) {
            $(arrLeft).addClass('inactive');
        } else {
            $(arrLeft).removeClass('inactive');
        }
        if (num >= len - 1) {
            $(arrRight).addClass('inactive');
        } else {
            $(arrRight).removeClass('inactive');
        }
    }

    function __onLeftBtnClick(obj) {
        var prev = obj.data('current'),
			len = obj.data('length'),
			next = prev - 1,
            current,
            goneBeyondBounds = false;

        if (prev == 0) {
            prev = len - 1;
            goneBeyondBounds = true;
        }

        current = prev;
        if (current <= 0) {
            current = 0;
        }
        if (current >= len - 1) {
            current = len - 1;
        }

        if (goneBeyondBounds) {
            // start over: reset image positions and set current
            obj.find('.viewer-assets').find('li').css('left', obj.data('left'));
            current++;
        } else {
            __slideRight(obj, current);
        }

        obj.data('current', current - 1);
        __update(obj, current - 1, len);
    }

    function __onRightBtnClick(obj) {
        var prev = obj.data('current'),
			len = obj.data('length'),
			next = prev + 1,
            current,
            goneBeyondBounds = false;

        if (next > len - 1) {
            next = 0;
            goneBeyondBounds = true;
        }

        current = next;
        if (current < 0) {
            current = 0;
        }
        if (current >= len - 1) {
            current = len - 1;
        }
        if (goneBeyondBounds) {
            // start over: reset image positions, then slide first image in
            obj.find('.viewer-assets').find('li').css('left', obj.data('width'));
            __slideLeft(obj, 0);
        } else {
            __slideLeft(obj, current);
        }

        obj.data('current', current);
        __update(obj, current, len);
    }

    function __slideLeft(obj, num) {
        var left = obj.data('left'),
			li = obj.find('.viewer-assets').find('li:eq(' + num + ')');
        li.stop().animate({
            'left': left
        }, config.speedOut, function () {
            _isAnimating = false;
        });
    }

    function __slideRight(obj, num) {
        var left = obj.data('width'),
			li = obj.find('.viewer-assets').find('li:eq(' + num + ')');
        li.stop().animate({
            'left': left
        }, config.speedIn, function () {
            _isAnimating = false;
        });
    }

    function __updateCounter(obj, num, len) {
        var counter = obj.find('.viewer-ui-counter');
        counter.html(Number(num + 1) + ' of ' + len);
    }

    function __updateCaption(obj, num, len) {
        var caption = obj.find('.viewer-ui-caption'),
			img = obj.find('li:eq(' + num + ')').find('img'),
        	html = img.attr('title'),
			src = img.attr('src'),
			imgName;
			
        if (_animate) {
            caption.hide(0, function () {
                caption.html(html);
                caption.fadeIn(300);
            });
        } else {
            caption.html(html);
        }
		imgName = src.split('/');
		imgName = imgName[imgName.length - 1];
		imgName = imgName.slice(0, imgName.indexOf('?'));
		
		__trackEvent('Photos', imgName);
    }

    function __updateCredit(obj, num) {
        var credit = obj.find('.viewer-ui-credit'),
        html = obj.find('li:eq(' + num + ')').find('img').data('credit');
        if (_animate) {
            credit.hide(0, function () {
                credit.html(html);
                credit.fadeIn(300);
            });
        } else {
            credit.html(html);
        }
    }

	function __trackEvent(category, label) {
		if(_isInit) {return;}
        //console.log('Track: ', category, label);
        _gaq.push([
			'_trackEvent',
			category,
			_pageURL,
			label
		]);
    }

    //Public Methods
    return {

	}
}

/**
*	Stub functions for ImageViewer types - should be overwritten
**/

POP.ImageViewerType = function() {};

POP.ImageViewerType.prototype = {
	model: function() {},
	view: function(obj, callback, callbackParams, ctx) {}
};

/**
*	Factory methods for making different ImageViewer Types
**/
POP.ImageViewerType.factory = function(type) {
	var constr = type,
		newType;
		
	if(typeof POP.ImageViewerType[constr] !== "function") {
		throw {
			name: "Error",
			message: constr + " doesn\'t exist."
		};
	}
	
	if(typeof POP.ImageViewerType[constr].prototype.model !== 'function') {
		POP.ImageViewerType[constr].prototype = new POP.ImageViewerType();
	}
	
	newType = new POP.ImageViewerType[constr]();
	return newType;
}

/**
*	Detail Type ImageViewer 
**/
POP.ImageViewerType.detail = function() {};

POP.ImageViewerType.detail.prototype.model = function() {
	var data = null;
	return data;
};

POP.ImageViewerType.detail.prototype.view = function(obj, callback, callbackParams, ctx) {
	var html = '',
	tempObj = obj.clone(),
	data;
	
	data = this.model();
	//if(!data) { return; }

	html += '		<div class="clear"></div>';
    html += '		<div class="viewer-container">';
	html += '			<div class="viewer-assets"></div>';	
	html += '			<div class="viewer-ui">';
	html += '				<div class="viewer-ui-left">';
	html += '					<a href="" class="arrow ir">Left Arrow</a>';
	html += '				</div>';
	html += '				<div class="viewer-ui-mid">';
	html += '					<div class="viewer-ui-caption">';
	html += '					</div>';
	html += '					<div class="viewer-ui-credit">';
	html += '					</div>';
	html += '					<div class="viewer-ui-counter">';
	html += '						5 of 7';
	html += '					</div>';
	html += '				</div>';
	html += '				<div class="viewer-ui-right">';
	html += '					<a href="" class="arrow ir">Right Arrow</a>';
	html += '				</div>';
	html += '			</div>';
	html += '		</div>';
	html += '		<div class="clear"></div>';

	html = $(html);
	html.find('.viewer-assets').append(tempObj);
	obj.replaceWith(html);
	
	if(typeof callback === 'function') {
		var ctx = ctx || this;
		callback.apply(ctx, [html, callbackParams]);
	}
}

/**
*	Select Seat Type ImageViewer 
**/
POP.ImageViewerType.selectSeat = function() {};

POP.ImageViewerType.selectSeat.prototype.model = function() {
	var data = null;
	return data;
};

POP.ImageViewerType.selectSeat.prototype.view = function(obj, callback, callbackParams, ctx) {
	var html = '',
	tempObj = obj.clone(),
	data;
	
	data = this.model();
	//if(!data) { return; }

    html += '		<div class="viewer-container">';
	html += '			<div class="viewer-assets"></div>';	
	html += '			<div class="viewer-ui">';
	html += '				<div class="viewer-ui-left">';
	html += '					<a href="" class="arrow ir">Left Arrow</a>';
	html += '				</div>';
	html += '				<div class="viewer-ui-mid">';
	html += '					<div class="viewer-ui-caption">';
	html += '					</div>';
	html += '					<div class="viewer-ui-credit">';
	html += '					</div>';
	html += '					<div class="viewer-ui-counter">';
	html += '						5 of 7';
	html += '					</div>';
	html += '				</div>';
	html += '				<div class="viewer-ui-right">';
	html += '					<a href="" class="arrow ir">Right Arrow</a>';
	html += '				</div>';
	html += '			</div>';
	html += '		</div>';
	html += '		<div class="clear"></div>';

	html = $(html);
	html.find('.viewer-assets').append(tempObj);
	obj.replaceWith(html);
	
	if(typeof callback === 'function') {
		var ctx = ctx || this;
		callback.apply(ctx, [html, callbackParams]);
	}
}



