/* PageInit */
var Slide = function(){return true};
$(document).ready(function(){
	initGallery();
	$('.fancy').fancybox({
		'titleShow'		: false
	});
	initPopupFunc();
});

/* Popup */
function initPopupFunc(){
	var open_class = 'open';
	var speed = 300;
	var popup_open_links = $('.other-fancy');
	var body = $('body').eq(0);
	popup_open_links.each(function(){
		// init links
		var popup_open_link = $(this);
		var popup_open =  popup_open_link.parents('li').eq(0).find('.lightbox').eq(0);
		var html = popup_open.html();
		var popup_holder = popup_open.parents('.holder:eq(0)');
		if(popup_open_links.filter('.'+ open_class).length > 1){
			popup_open_links.removeClass(open_class);
			popup_open_links.eq(0).addClass(open_class);
		}
		if(!popup_open_link.hasClass(open_class)){
			popup_open.hide();
		}else{
			popup_open.show();
		}
		popup_open_link.click(function(){
			body.find('>.'+popup_open.attr('class')).remove();
			body.append('<div style="display:none;" class="'+ popup_open.attr('class') + '">' + html + '</div>');
			if(typeof(Cufon)=='function'){
				Cufon.replace('body>.lightbox h3, body>.lightbox .close-box a.spin', { fontFamily: 'TradeGothicLTStd'});
			}
			var popup = body.find('>.'+popup_open.attr('class'));
			popup.css({
				opacity:0,
				width: popup.outerWidth(true),
				left:popup_holder.offset().left,
				top:popup_holder.offset().top,
				position:'absolute',
				zIndex: 500
			});
			popup.show().stop().animate({
				opacity:1
			}, {queue:false, duration:speed, complete:function(){
				popup.css({opacity:'auto'});
				popup.find('.spin').click(function(){
					popup.stop().animate({
						opacity:0
					}, {queue:false, duration:speed, complete:function(){
						popup.remove();
					}});
					return false;
				});
			}});
			// init close on click out the popup
			$(document).bind('mousedown', function(e){
				if(popup){
					e = e || event;
					var t = e.target || e.srcElement;
					t = $(t);
					if(!t.parents('.lightbox').length){
						popup.stop().animate({
							opacity:0
						}, {queue:false, duration:speed, complete:function(){
							popup.remove();
						}});
					}
				}
			});
			return false;
		});
	});
	// init close-link func
	var popup_close_links = $('.spin');
	popup_close_links.each(function(){
		var popup_close_link = $(this);
		var popup_close = popup_close_link.parents('.lightbox').eq(0);
		popup_close_link.click(function(){
			popup_close_link.removeClass(open_class);
			popup_close.removeClass(open_class);
			popup_close.hide();
			return false;
		});
	});
}

var activeGalleryItem = null;
var activeGalleryItemChangedHandler = null;

/* SlideGallery init */
function initGallery() {
    var _gallery = $('#carousel'),
    // param
		_list = _gallery.find('.holder>ul'),
		_listWidth = 0,
		_holderWidth = _gallery.find('.holder').outerWidth() / 2,
		speed = 10000,
		_work_duration = 0,
		_direction = true,
		_prev = _gallery.find('a.prev'),
		_next = _gallery.find('a.next'),
		_els = _gallery.find('.holder>ul>li'),
		_elsLength = _els.length,
		_popup = $('.lightbox'),
		_flag = true,
		_flag2 = true,
        iconPause = 1000,
		_t = 0;

        _list.find("li:first").addClass("firstItem");
        var _cloneEl = _els.clone();
        var _cloneEl2 = _els.clone();
		
		_els.each(function(){
			_listWidth += $(this).outerWidth();

});

        _list.find("li").addClass("mainItem");
        _list.find("li:first").addClass("active");
		_list.append(_cloneEl);
		_list.prepend(_cloneEl2);

		var _startOffset = (_list.find("li.active").position().left + _list.find("li.active").width() / 2 + parseInt(_list.css('marginLeft'))) - _holderWidth;
		var _startMargin = parseInt(_list.css('marginLeft')) - _startOffset;
		_list.css({ "marginLeft": _startMargin });

		Slide = function () {
		    if (_list.attr("stop") == null) {
		        var _offset = (_list.find("li.active").next().position().left + _list.find("li.active").next().width() / 2 + parseInt(_list.css('marginLeft'))) - _holderWidth;
		        var _margin = parseInt(_list.css('marginLeft')) - _offset;
		        _work_duration = Math.abs(_offset) * speed / _listWidth;

		        _list.animate({
		            marginLeft: _margin
		        }, _work_duration, 'linear', function () {
		            var $next = _list.find("li.active").next();
		            _list.find("li.active").removeClass("active");
		            $next.addClass("active");
		            activeGalleryItem = $next;
		            if (activeGalleryItemChangedHandler != null) activeGalleryItemChangedHandler($next);
		            if (!$next.hasClass("mainItem") && $next.hasClass("firstItem")) {
		                var _offset = (_list.find(".mainItem:first").position().left + _list.find(".mainItem:first").width() / 2 + parseInt(_list.css('marginLeft'))) - _holderWidth;
		                var _margin = parseInt(_list.css('marginLeft')) - _offset;
		                _list.css({ "marginLeft": _margin });
		                $next.removeClass("active");
		                _list.find(".mainItem:first").addClass("active");
		            }
		            setTimeout(function () { Slide(); }, iconPause);
		        });
		    }
		}
		Slide();

		var _els2 = _gallery.find('.holder>ul>li');
		// click move gallery func
		var _clickFlag = true;
		_els2.each(function (i) {
		    $(this).click(function () {
		        _list.attr("stop", "1");
		        if (_clickFlag) {
		            clearTimeout(_t);
		            _clickFlag = false;
		            _flag = false;
		            _list.stop();
		            var _offset = ($(this).position().left + $(this).width() / 2 + parseInt(_list.css('marginLeft'))) - _holderWidth;
		            var _current = 0;
		            var summ = 0;
		            _gallery.find('.holder>ul>li').removeClass('active');
		            if (i < _elsLength) {
		                _current = i + _elsLength;
		                summ = _els2.eq(_current).position().left - $(this).position().left;
		            } else if (i >= _elsLength * 2) {
		                _current = i - _elsLength;
		                summ = $(this).position().left - _els2.eq(_current).position().left;
		            } else {
		                _current = i;
		                summ = 0;
		            }
		            _els2.eq(i).addClass('active');
		            activeGalleryItem = _els2.eq(i);
		            if (activeGalleryItemChangedHandler != null) activeGalleryItemChangedHandler(_els2.eq(i));

		            var _margin = parseInt(_list.css('marginLeft')) - _offset;
		            _work_duration = Math.abs(_offset) * speed / _listWidth;
		            _list.animate({
		                marginLeft: _margin
		            }, _work_duration / 4, 'linear', function () {
		                if (summ) {
		                    var _ind = parseInt(_list.css('marginLeft'));
		                    if (_ind < -_listWidth * 1.5) {
		                        _ind += summ;
		                    } else {
		                        _ind -= summ;
		                    }
		                    _list.css('marginLeft', _ind);
		                }
		                _gallery.find('.holder>ul>li').removeClass('active');
		                _els2.eq(_current).addClass('active');
		                if ($("body").attr("notShowDialog") == null) {
		                    if (_els2.eq(_current).find('.fancy').length) {
		                        _els2.eq(_current).find('.fancy').trigger('click');
		                        var trackingUrl = "/" + $("iframe.tracking").attr("language") + "/Tracking/" + _els2.eq(_current).attr("tracking");
		                        $("iframe.tracking").attr("src", trackingUrl);
		                    } else {
		                        _els2.eq(_current).find('.other-fancy').trigger('click');
		                    }
		                }
		                $("body").removeAttr("notShowDialog");
		                _flag = true;
		                _clickFlag = true;
		            });
		        }
		        // init click SPIN func
		        $('.spin').unbind('click').click(function () {
		            parent.$.fancybox.close();
		            return false;
		        })
		        return false;
		    });
		});

		// init click out of the lightbox
		var _popup = $('#fancybox-outer');
		$(document).bind('mousedown', function(e){
			if(_popup&& _popup.is(':visible')){
			e = e || event;
			var t = e.target || e.srcElement;
			t = $(t);
			if(t.parents('#fancybox-wrap').length == 0){
				parent.$.fancybox.close();
			}}
		});
		/* init ie6 png-fix */
		if ($.browser.msie && $.browser.version < 7) {
			if (typeof(DD_belatedPNG.fix)=='function'){
				try{document.execCommand("BackgroundImageCache",false,true)}catch(r){}
				DD_belatedPNG.createVmlNameSpace();
				DD_belatedPNG.createVmlStyleSheet()
				DD_belatedPNG.fix('#carousel ul li span a');
			}
		}
}
