function log(e){
    //return false;
    if (typeof(console) == 'object') 
        console.log(e);
    //else alert(e);  
}

// pridat stranku do zaloziek
function AddFavorite(linkObj, addUrl3, addTitle3){
    if (document.all && !window.opera) {
        window.external.AddFavorite(addUrl3, addTitle3);
        return false;
    }
    else if (window.opera && window.print) {
        linkObj.title = addTitle3;
        return true;
    }
    else if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function')) {
        window.sidebar.addPanel(addTitle3, addUrl3, '');
        return false;
    }
    window.alert('Po potvrzení stiskněte CTRL-D,\nstránka bude přidána k Vašim oblíbeným odkazům.');
    return false;
}

/*
 <a href="#" onclick="return AddFavorite(this,'http://<?=$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].($_GET['lang']?'?lang='.$_GET['lang']:'')?>','Energy 21 - <?=$title?>');">Přidat do oblíbených</a>
 */
var menu = {
    config: {
        listLI: 'ul#menuMain > li',
        listUL: 'ul#menuMain',
        duration: 150
    },
    init: function(){
        if (!$(this.config.listLI).length) 
            return false;
        $(this.config.listLI).children().children('span').after('<span class="overlay"></span>');
        $(this.config.listLI).children('ul').hide();
        $(this.config.listLI).each(function(){
            if (!$(this).children('ul').children('li').length) 
                $(this).children('ul').remove();
        });
        $(this.config.listLI).hover(menu.min, menu.mout);
        $(this.config.listUL).removeClass('static');
    },
    min: function(){
        if ($(this).hasClass('act')) {
            $(this).children('ul').show();
        }
        else {
            $(this).children('ul').show();
            $(this).children().children('.overlay').animate({
                top: '0px'
            }, menu.config.duration).queue(function(){
                //$(this).parent().parent().children('ul').show();//slideDown(menu.config.duration);
                $(this).addClass('opened');
                $(this).dequeue();
            });
        }
    },
    mout: function(){
        if ($(this).children('ul').length) {
            $(this).children('ul').hide().queue(function(){ //.slideUp(menu.config.duration)
                $(this).parent().children().children('.overlay').animate({
                    top: '48px'
                }, menu.config.duration).removeClass('opened');
                $(this).dequeue();
            });
        }
        else {
            $(this).children().children('.overlay').animate({
                top: '48px'
            }, menu.config.duration).removeClass('opened');
        }
        if (!$(this).hasClass('act')) {
            setTimeout('menu.afterCheck(\'' + $(this).attr('id') + '\')', menu.config.duration * 2.5);
        }
    },
    afterCheck: function(id){
        $('#' + id).children('ul').hide()//.slideUp(menu.config.duration);
    }
}

//auto rollovers
var imageHover = {
    elementsFilter: '*[src*=but_],#partners img',
    replaceSrcNormal: '.png',
    replaceSrcHover: '_hover.png',
    init: function(){
        if (!$(this.elementsFilter).length) 
            return false;
        $(this.elementsFilter).each(function(key){
            imageHover.images[key] = new Image();
            imageHover.images[key].src = $(this).attr('src').replace(imageHover.replaceSrcNormal, imageHover.replaceSrcHover);
            //if(imageHover.isLoaded(imageHover.images[key]))
            //{
            $(this).hover(function(){
                $(this).attr('src', $(this).attr('src').replace(imageHover.replaceSrcNormal, imageHover.replaceSrcHover));
            }, function(){
                $(this).attr('src', $(this).attr('src').replace(imageHover.replaceSrcHover, imageHover.replaceSrcNormal));
            });
            //}
        });
    },
    isLoaded: function(el){
        if (!el.complete) {
            return false;
        }
        if (typeof el.naturalWidth != "undefined" && el.naturalWidth == 0) {
            return false;
        }
        return true;
    },
    images: new Array()
}

var bookmarks = {
    config: {
        wrapper: '.bookmarks',
        activeLink: 'act'
    },
    init: function(){
        if (!$(this.config.wrapper).length) 
            return false;
        $('.bookmarkHeader').hide();
        $('.bookmarkContent').addClass('bookmarkContentJS');
        $(this.config.wrapper).show().each(function(){
            $(this).children('a:first').addClass('first').addClass('act');
            $(this).children('a').click(function(){
                bookmarks.show($(this));
                return false;
            });
            $($(this).children('a:not(.' + bookmarks.config.activeLink + ')').attr('href')).hide();
        });
    },
    show: function(controller){
        $(bookmarks.config.wrapper + ' a').each(function(){
            $($(this).removeClass(bookmarks.config.activeLink).attr('href')).hide()
        });
        $($(controller).addClass(bookmarks.config.activeLink).attr('href')).show();
    }
}

var poll = {
    config: {
        wrapperId: '.poll'
    },
    init: function(){
        if (!$(this.config.wrapperId).length) 
            return false;
        
        $('.poll span.othersrc').each(function(){
        
            $(this).find('input').click(function(){
            
                if ($(this).attr('checked')) 
                    $(this).parent().parent().parent().children('.other').show();
                else 
                    $(this).parent().parent().parent().children('.other').hide();
                
            });
            
            $(this).parent().children('.other').filter(function(){
                return !$(this).parent().find('.othersrc').find('input').attr('checked')
            }).hide();
        });
        
    }
}

var articleSlider = {
    config: {
        wrapperId: '#articleSlider',
        innerId: '#articleSliderInner',
        pagerId: '#articleSliderPager',
        controlsL: '<a href="#" id="sliderPrev" onclick="articleSlider.prev();return false;"><span>&lt;</span></a>',
        controlsR: '<a href="#" id="sliderNext" onclick="articleSlider.next();return false;"><span>&gt;</span></a>',
        durSkip: 500
    },
    init: function(){
        if (!$(this.config.wrapperId).length) 
            return false;
        
        articleSlider.itemsCount = $(articleSlider.config.innerId).children().length;
        if (articleSlider.itemsCount > 1) {
            articleSlider.step = parseInt($(articleSlider.config.wrapperId).width());
            articleSlider.active = 0;
            
            articleSlider.controls = articleSlider.config.controlsL;
            for (var i = 0; i < articleSlider.itemsCount; i++) {
                articleSlider.controls += '<a href="#" onclick="articleSlider.slide(' + i + ');return false;" class="slide">' + (i + 1) + '</a>';
            }
            articleSlider.controls += articleSlider.config.controlsR;
            $(articleSlider.config.wrapperId).after('<p id="' + (articleSlider.config.pagerId.replace('#', '')) + '" class="cleaned"><span class="inner">' + articleSlider.controls + '</span></p>');
            $(articleSlider.config.pagerId).children('.slide:eq(' + (articleSlider.itemsCount - 1) + ')').addClass('last');
            articleSlider.slide(0);
        }
    },
    slide: function(n){
        articleSlider.active = n;
        $(articleSlider.config.innerId).animate({
            marginLeft: -articleSlider.active * articleSlider.step + 'px'
        }, articleSlider.config.durSkip);
        $(articleSlider.config.pagerId).children('.slide').removeClass('act');
        $(articleSlider.config.pagerId).children('.slide:eq(' + articleSlider.active + ')').addClass('act');
        clearTimeout(articleSlider.timeoutHandler);
        articleSlider.timeoutHandler = setTimeout('articleSlider.next()', 8000);
    },
    prev: function(){
        if (articleSlider.active > 0) 
            articleSlider.slide(articleSlider.active - 1);
        else 
            articleSlider.slide(articleSlider.itemsCount - 1);
    },
    next: function(){
        if (articleSlider.active < articleSlider.itemsCount - 1) 
            articleSlider.slide(articleSlider.active + 1);
        else 
            articleSlider.slide(0);
    }
}


var order = {
    config: {
        wrapperId: '#demandForms',
        itemId: '.demandForm',
        //        itemId: '.demandForm:not(.new)',
        chatBlinks: 3
    },
    init: function(){
        if (!$(this.config.wrapperId).length) 
            return false;
        //        if (typeof(DEVELOPER) == 'undefined') 
        //            return false;
        
        order.el.form = $(this.config.wrapperId);
        
        $('a[href*=#demand-form-]').fancybox({
            speedIn: 600,
            speedOut: 200,
            //hideOnContentClick: true,
            autoDimensions: true,
            centerOnScroll: true,
            showCloseButton: false,
            showNavArrows: false,
			enableEscapeButton: false,
            overlayShow: true,
            overlayOpacity: 0.8,
            overlayColor: '#D6E5F3',
			useLRKeys: false,
			titleShow: false,
            //width: 526,
            //height: fboxHeight,
            onClosed: function(){
                order.minimizeChat()
            },
            onComplete: function(){
				if (!( $.browser.msie && $.browser.version <= 7 )) {
					var bwidth = 554;
					$('#fancybox-wrap').width(bwidth + 'px');
					$('#fancybox-inner').width(bwidth - 20 + 'px');
				}

				order.openedId = $('#fancybox-inner').find(order.config.itemId).attr('id');
//                log('opened id: ' + order.openedId);
            }
        });
        
        order.initSubmitCatch();
        order.initFormActions();
		
        //$zopim.livechat.window.show();
        $zopim.livechat.window.setColor('#ff0000');
        setTimeout(function(){
            $zopim.livechat.window.setColor('');
            //$zopim.livechat.window.hide();
        }, 100);
    },
    initFormActions: function(){
    	//log('init actions');
        $('.demandForm input[type=checkbox]').each(function(){
            order.cToggleState($(this));
        })
        $('.demandForm input[type=checkbox]').bind('focus click', function(){
            order.cToggleState($(this));
        });
    },
    openedId: false,
    initSubmitCatch: function(elid){
        var el;
        if (typeof(elid) != 'undefined') {
            el = $('#' + elid);
            el.unbind('submit');
//            log('reinit submit on id: ' + elid);
        }
        else {
            el = $(this.config.itemId);
//            log('init submit on all');
        }
        el.submit(function(){
            var purl = $(this).attr('action');
            var pid = $(this).attr('id');
            var pdata = $(this).serialize();
            pdata += '&formid=' + pid;
            order.toggleLoading(1);
            $.post($(this).attr('action'), pdata, function(data){
                var dform = $(data).find('#' + pid);
//                log('finding form in result ' + pid);
                $('#fancybox-inner').html(dform);
                order.initSubmitCatch(pid);
                order.initFormActions(pid);
                order.toggleLoading(0);
            }, 'html');
            
            return false;
            
        });
        
    },
    el: {},
    closePopup: function(){
        $.fancybox.close();
        order.minimizeChat();
        
        $.get(window.location.href, 'formid=' + order.openedId, function(data){
            var dform = $(data).find('#' + order.openedId);
            $(order.openedId).replaceWith(dform);
            order.initSubmitCatch(order.openedId);
            order.initFormActions(order.openedId);
//            log('reloaded id:' + order.openedId);
            order.openedId = false;
        }, 'html');
        
    },
    minimizeChat: function(){
        $zopim.livechat.window.setColor('');
    },
    initChat: function(){
        $zopim.livechat.set({
    	    name: $('#fancybox-inner input[name*=usr_demand_name]').attr('value'),
    	    email: $('#fancybox-inner input[name*=usr_demand_email]').attr('value')
        });
        $zopim.livechat.window.show();
        for (var i = 0; i < order.config.chatBlinks * 2; i = i + 2) {
            setTimeout(function(){
                $zopim.livechat.window.setColor('#ff0000');
            }, 300 * i);
            setTimeout(function(){
                $zopim.livechat.window.setColor('');
            }, 300 * (i + 1));
        }
    },
    cToggleState: function(el){
        if ( $(el).attr('checked') ) {
            var pinput = $(el).parents('.entries').find('.pieces').show().find('input[type=text]');
			if (!pinput.attr('value')) {
				pinput.attr('value', '1');
			}
        }
        else {
            var pinput = $(el).parents('.entries').find('.pieces').hide().find('input[type=text]');//.attr('value', '0');
            pinput.attr('value', '');
        }
    },
    toggleLoading: function(oo){
        if (oo === 1) {
            $('#fancybox-outer').append('<div id="order-fancy-loading"><div class="innerA"><!-- --></div><div class="innerB"><!-- --></div></div>')
        }
        else if (oo === 0) {
        	$('#order-fancy-loading').remove();
        }
        
    }
}


//--------------------------------------------------------------------------

$(document).ready(function(){

    menu.init();
    imageHover.init();
    
    $('a[rel*=lightbox],.productImages a').lightBox({
        overlayBgColor: '#D6E5F3',
        containerResizeSpeed: 200
    });
    bookmarks.init();
    
    //$('a.link.index').wrapInner('<span></span>');
    poll.init();
    articleSlider.init();
    
    $('#twitter a').cTwitter({
        userId: '71503414'
    });
    
    order.init();
    
})
