$(function() {
    var bg  = $("#bg"),
        wrap = $('#wrap'),
        content = $('#content'),
        wrapMinHeight = parseInt(wrap.css('minHeight').split('px')[0]) || 800,
        rightNavBar = $('.right-nav-bar'),
        subNavGrnd = $('<div id="subnav-grnd"></div>').insertBefore('#header .nav');

        function getImgSize(imgSrc)
    {
	var newImg = new Image();
	newImg.src = imgSrc;
	return newImg.height;
    }


    function resizeBg() {
        //var h = bg.height();
    if (document.getElementById('bg')){
	 var h = getImgSize(document.getElementById('bg').src);
        h = h < wrapMinHeight ? wrapMinHeight : h;
        bg.css({
            height: h,
            marginBottom: -h
        });

        rightNavBar.height(content.height() - 65);
    }
    }    
    
    $(window).resize(resizeBg).trigger("resize");
    
    var imageNum = 0;
    
      
    if (document.getElementById('main-bk')) 
    {
    var slides = $("#main-bk").html().split("<");
    
    var ImagesList = new Array();
    
    var srcs = new Array();
    for(var i = 1; i < slides.length; i++)
    {
    	src = slides[i].split("\"");
    	var j;
    	for (j=0; j<src.length; j++)
    		if (src[j].toString().indexOf('src=') + 1) break;
    	srcs[i-1] = src[j+1];
    	var cim = new Image();
    	cim.src = src[j+1];
    	ImagesList[i-1] = cim;
    }
    
    function chBg()
    {
    	$("#bg").attr("src", ImagesList[imageNum].src);
    	if (imageNum == (srcs.length-1)) imageNum=0; else imageNum++;
    }
    
    setInterval(chBg, 4000); 
    
    }
    

    $('#header .nav')
    .delegate('li', 'mouseover', function() {
        var h = $('ul', this).height();
        if (h) {
            subNavGrnd.css({
                height: h,
                paddingBottom: 15
            });
        }
    })
    .delegate('li', 'mouseout', function() {
        subNavGrnd.css({
            height: 0,
            paddingBottom: 0
        });
    });

    /* gallerific */
    if (undefined !== $.galleriffic) {
    
        // Initialize Advanced Galleriffic Gallery
        var gallery = $('#thumbs').galleriffic({
            delay:                     2500,
            numThumbs:                 10,
            preloadAhead:              1,
            enableBottomPager:         false,
            syncTransitions:           true,
            renderSSControls:          false,
            defaultTransitionDuration: 500,
            prevLinkText:              '',
            nextLinkText:              '',
            imageContainerSel: '#slideshow',
            controlsContainerSel: '#controls',
            captionContainerSel: '#caption',
            loadingContainerSel: '#loading',
            onSlideChange: function(prevIndex, nextIndex) {
                /* TODO: make ajax response to get info about product */
            },
            onTransitionOut: function(slide, caption, isSync, callback) {
                $('#zoomed-img').fadeIn(300).empty();
                callback();
            },
            onTransitionIn: function(newSlide, newCaption, isSync) {
	            	var d = newSlide.find('img').attr('src').split('/');
	            	d = d[d.length-2].split('_');
            		$.get(
		                    'index.php?mact=Products,cntnt01,get_product_details,0&cntnt01showtemplate=false&cntnt01returnid=15',
		                    {
		                        product_id: d[1]
		                    },
		                    function(data) {
		                    	$('#product-details').html(data);
		                    },
		                    'html'
		                );
	            	
	            	newSlide
                    .find('a')
                    .addClass('cloud-zoom')
                    .attr({
                        'href': newSlide.find('img').attr('src'),
                        'rel' : 'zoomWidth: "auto", zoomHeight: "auto", position: "zoomed-img", adjustY: 10, title: false'
                    })
                    .CloudZoom();

                newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
                if (newCaption) {
                    newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
                }
            },
            onPageTransitionOut: function(callback) {
                this.fadeTo('fast', 0.0, callback);
            },
            onPageTransitionIn: function() {
                var pages = $('.thumbs-prev, .thumbs-next').css('visibility', 'hidden');

                // Show appropriate next / prev page links
                if (this.displayedPage > 0) {
                    pages.filter('.thumbs-prev').css('visibility', 'visible');
                }

                var lastPage = this.getNumPages() - 1;
                if (this.displayedPage < lastPage) {
                    pages.filter('.thumbs-next').css('visibility', 'visible');
                }

                this.fadeTo('fast', 1.0);
            }
        });
        
        var tmp = new Array();      
        var tmp2 = new Array();    
        var param = new Array();
         
        var get = location.search;  
        if(get != '') {
            tmp = (get.substr(1)).split('&');
            for(var i=0; i < tmp.length; i++) {
                tmp2 = tmp[i].split('=');
                param[tmp2[0]] = tmp2[1];
            }}
            
        gallery.gotoIndex(param['item'], false, true);

        /**************** Event handlers for custom next / prev page links **********************/
        $('.thumbs-prev').click(function() {
            gallery.previousPage();
        });

        $('.thumbs-next').click(function() {
            gallery.nextPage();
        });
    }
	if ('function' === typeof $.fn.collectionSlider) {
        $('#collection-slider').collectionSlider({
            itemLoadCallback: function(slider) {
                $.get(
                    'index.php?mact=Products,cntnt01,get_images,0&cntnt01showtemplate=false&cntnt01returnid=15',
                    {
                        //collection: 'carousel.first'
                    	collection: $('#collection_name').html()
                    },
                    function(xml) {
                        var images = [];
                        
                        $('image', xml).each(function(i) {
                            var item = $(this);
                            images.push(
                                '<a href="index.php?page=product-details&item=' + item.attr('id') + '&collection=' + $('#collection_name').html() + '">' +
                                    '<img src="' + item.text() + '" alt="" />' +
                                '</a>'
                            );
                        });

                        slider.add(images);
                    },
                    'xml'
                );
            }
        });
    }

});
























