$(document).ready(function () {

    // Get book list start page index from hidden field
    $("div.books-list").each(function () {
        var bookListStartPageIndex = $(this).find("input[id*='hdnStartPageIndex']").val();
        var slides = $(this).find("li.slide-item");
        if (bookListStartPageIndex < slides.length) {
            $(slides[bookListStartPageIndex]).addClass("active");
        }
    });

    $('div.partner-box').galleryCircle({
        btPrev: 'a.arrow-prev',
        btNext: 'a.arrow-next',
        holderList: 'div',
        scrollElParent: 'ul',
        scrollEl: 'li',
        step: true,
        numHolder: 'div.swicher',
        numCreate: true,
        switchTime: false,
        duration: 500,
		showPreviousAtIndex0: true
    });
    $('div.books-list').galleryCircle({
        btPrev: 'a.btn-prev',
        btNext: 'a.btn-next',
        holderList: 'div',
        scrollElParent: 'ul.gallery-list',
        scrollEl: 'li.slide-item',
        step: true,
        numHolder: 'div.swicher',
        numCreate: false,
        switchTime: false,
        duration: 800,
        showPreviousAtIndex0: false
    });
    initSlide();
    initTabs();
    hideFormText();
    //initLightbox();
    initLightbox($(document));
});
function initTabs() {
	$('ul.tabset').each(function(){
		var _list = $(this);
		var _links = _list.find('a.tab');

		_links.each(function() {
			var _link = $(this);
			var _href = _link.attr('href');
			var _tab = $(_href);

			if(_link.hasClass('active')) _tab.show();
			else _tab.hide();

			_link.click(function(){
				_links.filter('.active').each(function(){
					$($(this).removeClass('active').attr('href')).hide();
				});
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
	});
}
/* hideForm */
function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index])
						this.value = '';
				}
				_inputs[i].onblur = function(){
					if (this.value == '')
						this.value = _value[this.index];
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index])
					this.value = '';
			}
			_txt[i].onblur = function(){
				if (this.value == '')
					this.value = _value['txt'+this.index];
			}
		}
	}
}
/* slide block */
function initSlide(){
	var _duration = 400; //in ms
	$('ul.accordion > li').each(function(){
		var _hold = $(this);
		var _box = _hold.find('div.slide');
		var _btn = _hold.children('a');
		var _h = _box.height();
		if(_hold.hasClass('opened')) _box.show();
		else _box.hide();
		
		_btn.click(function(){
			if(_hold.hasClass('opened')){
				_hold.removeClass('opened');
				_box.stop().animate({height:0}, _duration, function(){
					$(this).css({display:'none', height:'auto'});
				});
			}
			else{
				_hold.addClass('opened');
				if(_box.is(':hidden')){
					_box.show();
					_h = _box.height();
					_box.height(0);
				}
				_box.stop().animate({height: _h}, _duration, function(){ 
					$(this).height('auto');
				})
			}
			return false;
		});
		
	});
}
function initLightbox(root) {

    if (root.find('a.lightbox-opener').length != 0) {

        var _ind = 0;

        root.find('a.lightbox-opener').click(function () {
            
            _ind = root.find('a.lightbox-opener').index($(this));
            var _rel = $(this).attr('rel');
            var titleId = _rel.split(",")[0];

            if ($(this).attr("href") == "#lightbox1") {
                // if BookDetailPopover
                GetBookDetailPopoverHtml(titleId);
            } else {
                initTabs();
                initBtnClose();
            }

            return false;
        });

        root.find('a.lightbox-opener').fancybox({
            'titleShow': false,
            'overlayColor': '#000',
            'overlayOpacity': 0.6,
            'scrolling': 'no',
            'onClosed': function () {
                $("#lightbox1").html("<div style='height: 450px; width: 905px;'><img src='" + appRootFull  + "images/loading_animation_2.gif' alt='cancelled' style='position: absolute; top: 198px; left: 430px;'/></div>");
            }
        });
    }
}

function GetBookDetailPopoverHtml(titleId) {

    $("#lightbox1").find("img").attr("alt", "loading");

    $.ajax({
        type: "POST",
        url: appRootFull + "/Web/Services/AES.asmx/GetBookDetailHTML",
        data: "{titleId:" + titleId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, status) {
            if ($("#lightbox1").find("img").attr("alt") == "loading") {
                $("#lightbox1").html(data.d);       // Get BookDetail Html
                initLightbox($("#lightbox1"));      // Initialize light box for series books
                initTabs();                         // Initialize tabs
                initBtnClose();                     // Initialize close button click event
                centerLightbox();                   // Center light box
                //$('div.popup').find('a[rel=' + _rel.split(",")[1] + ']').click();
            }
        },
        error: function (XMLHttpRequest, status, errorThrown) {
            alert('ajax failure:' + status + ' error: ' + errorThrown);
        }
    });

}

function initBtnClose() {
    var _closer = $('div.popup, div.popup3').find('a.btn-close, a.close');
    _closer.click($.fancybox.close);
    _closer.click(function(){
    	return false;
     });
}

function centerLightbox() {
    var clientWindowHeight = window.innerHeight;
    var interval = setInterval(function () {
        var lightboxHeight = $("#lightbox1").outerHeight();
        if (lightboxHeight != 0) {
            clearInterval(interval);
            var scrollTop = window.pageYOffset;
            var lightboxTop = ((clientWindowHeight - lightboxHeight) / 2) + scrollTop;
            var lightboxLeft = $("#lightbox1").offset().left;
            //alert(clientWindowHeight + ":" + lightboxHeight + ":" + scrollTop);
            $("#lightbox1").offset({ top: lightboxTop, left: lightboxLeft });
        }
    }, 100);
}

/*
 * jQuery galleryCircle v1.0.4
 *****************************************************************
	btPrev: 'a.prev',				button prev
	btNext: 'a.next',				button next
	holderList: 'div',				holder of elements window were you see sliding elements !  CSS for this element:	 div {position: relative;	width: "your width" ; 	overflow: hidden;}
	scrollElParent: 'ul',			holder of all sliding elements
	scrollEl: 'li',					element wich would slide
	numHolder: 'div.num-control',	holder of control element
	numCreate: false,				create new num control or use default (wich exist in markup) can be: False or True
	step: false,					boolean false= scroll on window width, true = scroll on each element width
	innerMargin: 0,					if "ul" has some default margin that is not  "0" set it here
	switchTime: false,				time between sliding image: 	false or some integer 1000 = 1 sec
	duration : 1500					time of animation			some integer 1000 = 1 sec
	showPreviousAtIndex0 : false	controls whether the previous button will be available at index zero on start (for scroll through lists)
 *****************************************************************
 */

jQuery.fn.galleryCircle = function (_options) {
    // defaults options
    var _options = jQuery.extend({
        btPrev: 'a.prev',
        btNext: 'a.next',
        holderList: 'div',
        scrollElParent: 'ul',
        scrollEl: 'li',
        numHolder: false,
        numCreate: false,
        step: false,
        innerMargin: 0,
        curPage: false,
        onClick: null,
        easing: 'linear',
        switchTime: false,
        duration: 1500,
		showPreviousAtIndex0: false
    }, _options);

    return this.each(function () {
        var _this = jQuery(this);
        var _next = jQuery(_options.btNext, _this).length ? jQuery(_options.btNext, _this) : false;
        var _prev = jQuery(_options.btPrev, _this).length ? jQuery(_options.btPrev, _this) : false;
        var _holderList = jQuery(_options.holderList, _this);
        var _scrollElParent = jQuery(_options.scrollElParent, _holderList);
        var _scrollEl = jQuery(_options.scrollEl, _scrollElParent);
        var _numHolder = false;
        if (_options.numHolder) _numHolder = jQuery(_options.numHolder, _this).length ? jQuery(_options.numHolder, _this) : false;
        var _step, _t = null;
        var _widthSum = 0;
        var _sum = _this.find('em.info');
        _scrollEl.each(function () { _widthSum += jQuery(this).outerWidth(true); })
        var _startPosition = _scrollEl.index(_scrollEl.filter('.active'));
        if (_startPosition == -1) _startPosition = 0;
        _scrollEl.removeClass('active');
        var _easing = _options.easing;

        if (!_options.step) _step = _holderList.innerWidth();
        var _margin = _widthSum;
        _scrollElParent.append(_scrollEl.clone(true));
        _scrollElParent.prepend(_scrollEl.clone(true));

        var _offsetStartPosition = 0;
        _offsetStartPosition = culcOffset(_startPosition);

        _scrollElParent.css('marginLeft', (-_margin + _options.innerMargin - _offsetStartPosition));
        _sum.html(_startPosition + 1 + ' of ' + _scrollEl.length);
        //auto rotation
        if (_options.switchTime) {
            _t = setTimeout(function () {
                nextSlides();
            }, _options.switchTime)
        }

        //hide prev button if start position is 0
        if (_startPosition == 0 && _options.showPreviousAtIndex0 == false) {
            _prev.hide();
        }
        //hide next button if there is only one slide or last slide
        if (_scrollEl.length == 1 || _startPosition + 1 == _scrollEl.length) {
            _next.hide();
        }
        //hover next, prev button
        _prev.hover(function () {
            _prev.css("color", "brown");
        }, function () {
            _prev.css("color", "#C0B9B6");
        });
        _next.hover(function () {
            _next.css("color", "brown");
        }, function () {
            _next.css("color", "#C0B9B6");
        }); 4

        //button next "click"
        if (_options.btNext) {
            _next.click(function () {
                if (!_scrollElParent.is(':animated')) {
                    if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
                    nextSlides();
                }
                return false;
            });
        }

        //button prev "click"
        if (_options.btPrev) {
            _prev.click(function () {
                if (!_scrollElParent.is(':animated')) {
                    if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
                    prevSlides();
                }
                return false;
            });
        }

        //curent position
        function getCurElIndex() {
            var _curMargin = parseInt(_scrollElParent.css('marginLeft')) + _widthSum - _options.innerMargin;
            for (i = 0; i < _scrollEl.length; i++) {
                if (_curMargin == 0) return i;
                if (_curMargin <= _options.innerMargin) _curMargin += _scrollEl.eq(i).innerWidth(true);
                else _curMargin -= _scrollEl.eq(i).innerWidth(true);
                if (_curMargin == _options.innerMargin) return i + 1;
            }
        }

        // offset of gallery if when activ element not first at start 
        function culcOffset(_ind) {
            var _tmpcounter = 0;
            var _pos = 0;
            while (_tmpcounter < _ind) {
                _pos += _scrollEl.eq(_tmpcounter).outerWidth(true);
                _tmpcounter++;
            };
            return _pos;
        }

        //go next slide
        function nextSlides() {
            if (_t) clearTimeout(_t);
            if (_options.step) {
                _curElIndex = getCurElIndex();
                _step = _scrollEl.eq(_curElIndex).innerWidth(true);
            };
            _margin = -parseInt(_scrollElParent.css('marginLeft'));
            _margin += _step;

            _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                if (_margin >= _widthSum * 2) {
                    _margin = _widthSum + (_margin - _widthSum * 2);
                }
                _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);
                _sum.html(_curElIndex + 1 + ' of ' + _scrollEl.length);
                //autoslide
                if (_options.switchTime) {
                    _t = setTimeout(function () {
                        nextSlides();
                    }, _options.switchTime)
                }
                //hide next button if last slide
                if (_curElIndex + 1 == _scrollEl.length) {
                    _next.hide();
                }
                //show prev button
                _prev.show();
            }
            });
        }

        //go prev slide
        function prevSlides() {
            if (_t) clearTimeout(_t);
            if (_options.step) {
                _curElIndex = getCurElIndex();
                if (_curElIndex == 0) _curElIndex = _scrollEl.length;
                _step = _scrollEl.eq(_curElIndex - 1).innerWidth(true);
            };
            _margin = -parseInt(_scrollElParent.css('marginLeft'));
            _margin -= _step;
            _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                if (_margin < _widthSum) {
                    _margin = _widthSum * 2 - (_widthSum - _margin);
                }
                _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);
                _sum.html(_curElIndex + 1 + ' of ' + _scrollEl.length);
                //autoslide
                if (_options.switchTime) {
                    _t = setTimeout(function () {
                        nextSlides();
                    }, _options.switchTime)
                }
                //hide prev button if last slide
                if (_curElIndex + 1 == 1 && _options.showPreviousAtIndex0 == false) {
                    _prev.hide();
                }
                //show next button
                _next.show();
            }
            });
        }

        // Number list Create
        jQuery.fn.galleryCircle.numListCreate = function (_numHolder, _scrollEl) {
            var _numListElC = '';
            for (var i = 0; i < _scrollEl.length; i++) {
                _numListElC += '<li><a href="">' + (i + 1) + '</a></li>';
            }
            jQuery(_numHolder).html('<ul>' + _numListElC + '</ul>');
        };

        // Number list Activate
        jQuery.fn.galleryCircle.numListActive = function (_numHolder, _scrollEl) {
            _curElIndex = getCurElIndex();
            if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina ' + (getCurElIndex() + 1) + '/' + _scrollEl.length);
            if (_numHolder) {
                jQuery('a', _numHolder).removeClass('active');
                jQuery('a', _numHolder).eq(_curElIndex).addClass('active');
            }
        };

        //click on control elemens
        function numClick() {
            jQuery(_options.numHolder, _this).find('a').click(function () {
                if (_t) clearTimeout(_t);
                var _aList = jQuery(_options.numHolder, _this).find('a');
                var _index = _aList.index(jQuery(this));
                _margin = _widthSum + _index * _scrollEl.outerWidth(true);
                _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                    if (_margin >= _widthSum * 2) {
                        _margin = _widthSum + (_margin - _widthSum * 2);
                    }
                    _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                    _aList.removeClass('active').eq(_index).addClass('active');

                    //autoslide
                    if (_options.switchTime) {
                        _t = setTimeout(function () {
                            nextSlides();
                        }, _options.switchTime)
                    }
                }
                });
                return false;
            });
        };

        // init creating num list
        if (_options.numCreate) jQuery.fn.galleryCircle.numListCreate(_numHolder, _scrollEl);

        // pagination first init (example Page 2/6)
        if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina ' + (getCurElIndex() + 1) + '/' + _scrollEl.length);

        // init activate num list item and init numClick()
        if (_options.numHolder) {
            jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);
            numClick();
        }
    });
}
