var popupStatus = 0;
var slideshowTimer;
//chyba pri ajaxe
$(document).ajaxError(function (request,settings,e) {
    alert('Error requesting URL: '+e.url);
});


//funkcia na ziskanie URL routera
var Router = function (route,params) {
    //parametre
    if (typeof(params) == 'object') {
        var p = '';
        $.each(params,function (name,value) {
            if (p != '') {
                p += '&';
            }
            p += escape(name)+'='+escape(value);
        });
        return Router(route)+'?'+p;
    }
    else {
        return '/' + route;
    }
};
Router.route = function (route,params) {
    var url = Router(route,params);
    location.href = url;
}

/* Plugin na input hint */
jQuery.fn.inputHint = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('input[type=text]')) {
            jQuery.inputHintShow(self);
            self.focus(function () {
                jQuery.inputHintHide(this);
            }).blur(function () {
                jQuery.inputHintShow(this);
            }).closest('form').submit(function () {
                jQuery.inputHintHide(self);
                return true;
            });
        }
    });
    return this;
};
jQuery.inputHintShow = function (inpt) {
    inpt = jQuery(inpt);
    if (inpt.val() == inpt.attr('title') || inpt.val() == '') {
        inpt.addClass('hint').val(inpt.attr('title'));
    }
}
jQuery.inputHintHide = function (inpt) {
    inpt = jQuery(inpt);
    inpt.removeClass('hint');
    if (inpt.val() == inpt.attr('title')) {
        inpt.val('');
    }
}
popupInit();

$(function(){
    //zaheslovane clanky
    if(navigator.userAgent.toString().indexOf('Googlebot') < 1){
        $('#contentText').find('.passworded').hide();
    }
    
    // IE login submit
    $('#chipLoginForm input[type=password]').keypress(function (e) {
        if (e.which == 13){
            // $('#chipLoginForm input.submit').click();
            $('#chipLoginForm').submit();
        }
    });
    $('input[name=login]','#chipLoginForm').keyup(function () {
             if($(this).val()){
                 if($('#loginButton').html() != 'OK'){
                     var text = $('#loginButton').html();
                     $('#loginButton').attr('title',text);
                 }
                 $('#loginButton').html('OK');
             }else{
                 $('#loginButton').html($('#loginButton').attr('title'));
             }
     });
     $('#loginButton').click(function () {
         $('#chipLoginForm').submit();
         return false;
     });
    
	//hinty vo formularoch
	$('input.hint').inputHint();
	//chipsy na pravoboku
	$('#rightPanel div.chip').hover(function () {
        $(this).addClass('chip-hover');
    },function () {
        $(this).removeClass('chip-hover');
    }).mousedown(function () {
        $(this).addClass('chip-active');
    }).mouseup(function () {
        $(this).removeClass('chip-active');
    });
   	//chipsy na lavoboku
    $('#leftPanel div.chip-small').hover(function () {
        $(this).addClass('chip-hover');
    },function () {
        $(this).removeClass('chip-hover');
    }).mousedown(function () {
        $(this).addClass('chip-active');
    }).mouseup(function () {
        $(this).removeClass('chip-active');
    });
    //zvacsime pismo tam kde je vyska mensia
    $('#rightPanel div.chip').each(function () {
        if ($(this).height() > 60) {
            $(this).css('font-size', '94%');
        }
    });
    //animacia chipsov na lavoboku
    $('#leftPanel div.chip-article').each(function () {
        //mame zoznam chipsov, zobrazime vzdy dalsi nezobrazeny
        var chip = this;
        displayNextChipItem.call(this, true);
    });
    
    // var flowplayers = $('a.flowplayer');
    // if (flowplayers.length) {
    //     function createFlowPlayer(idx) {
    //         var a = flowplayers.eq(idx);
    //         if (a.length) {
    //             var player = $('<div></div>');
    //             player.width(a.width())
    //                   .height(a.height());
    //             a.after(player);
    //             a.hide();
    //             // player.css('background', 'red');
    //             flowplayer(player[0], "/public/flowplayer/flowplayer-3.2.2.swf", {
    //                 clip: {
    //                     scaling: 'fit',
    //                     url: a.attr('href'),
    //                     autoPlay: false,
    //                     autoBuffering: true
    //                 }
    //             });
    //             window.setTimeout(function () {
    //                 createFlowPlayer(idx + 1);
    //             }, 1000);
    //         }
    //     }
    //     createFlowPlayer(0);
    // }
    flowplayer("a.flowplayer", "/public/flowplayer/flowplayer-3.2.2.swf", {
        clip: {
            scaling: 'fit'
        }
    });
    
    $('a.videoplayer').css('display', 'block');
    flowplayer("a.video", "/public/flowplayer/flowplayer-3.2.2.swf", {
        clip: {
            scaling: 'fit'
        }
    });
    
    //mainmenu - floating menu
    $('#mainMenu ul.menu > li').each(function () {
        var mmenu = $(this);
        var mmenua = mmenu.find('a');
        var submenu = $(this).find('ul.subMainmenu');
        if (submenu.length) {
            //append submenu to body - fixing IE6 z-index
            submenu.appendTo($('body'));
            mmenua.mouseover(function () {
                if (submenu.is(':hidden')) {
                    var offset = mmenu.offset();
                    submenu.css({
                        top: (offset.top + 30) + 'px',
                        left: (offset.left) + 'px'
                    });
                    submenu.fadeIn(200);
                }
            });
            mmenua.mouseout(function (event) {
                var mousein = $(event.relatedTarget);
                if (
                    !mousein.is('ul.subMainmenu') &&
                    !mousein.closest('ul.subMainmenu').length &&
                    !mousein.closest('#' + mmenu.attr('id')).length
                ) {
                    submenu.fadeOut('fast');
                }
            });
            mmenu.mouseout(function (event) {
                var mousein = $(event.relatedTarget);
                if (
                    !mousein.is('ul.subMainmenu') &&
                    !mousein.closest('ul.subMainmenu').length &&
                    !mousein.closest('#' + mmenu.attr('id')).length
                ) {
                    submenu.fadeOut('fast');
                }
            });
            submenu.mouseout(function (event) {
                var mousein = $(event.relatedTarget);
                if (
                    !mousein.is('ul.subMainmenu') &&
                    !mousein.closest('ul.subMainmenu').length &&
                    !mousein.closest('#' + mmenu.attr('id')).length
                ) {
                    submenu.fadeOut('fast');
                }
            });
        }
    });
    
    /*
    $('a.showAjaxAddToCart').click(function () {
        var opener = this;
        centerPopup(550,300);
        loadPopup();
        popupInit();
        $('#popupWindow').load(this.href + ' #popupData',function(){ 
                $('#popupWindow').html(
                            '<a id="popupWindowClose">Fenster schließen X</a>'
                            + $('#popupWindow').html()
                             );
                //$('#popupWindow').css({});
                popupInit();
            }
        );
     return false;
    });
    
    //detaily produktu - aksu vygenerovane v html
    if ($('div.productDetail').length > 0) {
        productShowDetailsCommon($('div.productDetail'));
        productShowDetailsPositioning($('div.productDetail'));
        productShowDetails($('div.productDetail').attr('id').substring(8));
    }
    
    //nastavime linky na produkty, aby neboli aktivne a aby sa zobrazovali produkty ajaxom
    $('a.showAjaxAddToCart').click(function () {
        productShowDetails($(this).attr('rel'));
        return false;
    });
    
    $("#showGoodsWindow").click(function(){
             centerPopup(550,300);
             loadPopup('<a id="popupWindowClose">Fenster schließen X</a>'
                 + $('#popupData').html());
             popupInit();
    });
    */
    
    $("#popupWindowClose").click(function(){
            disablePopup();
    });
    
    $("#backgroundPopup").click(function(){
            disablePopup();
    });
    
    $(document).keypress(function(e){  
            if(e.keyCode==27 && popupStatus==1){
                disablePopup();
            }
    });
    
    $('select#country').change(function(){
        if($(this).val() == 'Andere'){
            $('input#otherCountry').removeAttr("disabled");
        }
        else {
            $('input#otherCountry').val("");
            $('input#otherCountry').attr("disabled","disabled");
        }
    });
    
    $('span.submit').click(function(){
        var form = $(this).closest('form');
        if(form.length){
            form.submit();
        }
        //disablePopup();
     });
    var form;
    
    $('span.submitWithCurrency').click(function(){
       form = $(this).closest('form');
       if(form.length){
           if(typeof orderCurrency == 'undefined'){
               centerPopup(200,100);
               loadPopup($('#currencyMessage').html());
               
               $("span.currencyEur").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=EUR');
                    form.submit();
                });
                $("span.currencyChf").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=CHF');
                    form.submit();
                });
           }
           else{
                form.submit();
           }
           
           //if ($(this).hasClass('eur')){
           //    form.attr('action',form.attr('action') + '?orderCurrency=EUR');
           //} else if ($(this).hasClass('chf')){
           //    form.attr('action',form.attr('action') + '?orderCurrency=CHF');
           //}
           //form.submit();
       }
    });
    
    /*
    $("form.submitAjax").submit(function(){
        centerPopup(300,200);
        loadPopup();
        $.post($(this).attr('action'),$(this).serialize(),function(data){
                     $('#popupWindow').html(
                        '<a id="popupWindowClose">Fenster schließen x</a>'
                        + $(data).find('#whereToGoContainer').html()
                        );
                     popupInit();
                 })
        return false;
    });
    
    if($('.slideshow').length){
        slideshow();
    }
    
    $('div.sh','#seminar-termine').each(function () {
        var sh = $(this).find('div.seminarhotel');
        sh.appendTo($('body'));
        $(this).find('a.shhover').hover(function (e) {
            sh.show();
            sh.css({
                    position: 'absolute',
                    top: e.pageY + 10, // $(window).scrollTop()
                    left: e.pageX + 10
            });
        }, function () {
            sh.hide();
        }).mousemove(function (e) {
            sh.css({
                    position: 'absolute',
                    top: e.pageY + 10, // $(window).scrollTop()
                    left: e.pageX + 10
            });
        });
    });
    */
    
    $('select','#productQuickSelect').change(function () {
         if($(this).find('option:selected').attr('rel') != ''){
             window.location.href = $(this).find('option:selected').attr('rel');
         }else{
             $(this).closest('form').submit();
         }
    });

});
function productShowDetails(pid) {
    var pdetail = $('#productDetail_' + pid);
    if (pdetail.length > 0) {
        productShowOverlay();
        $('div.detailContainer',pdetail).hide();
        productShowDetailsPositioning(pdetail,function () {
            $('div.detailContainer',pdetail).show();
            $('div.descrOpacity',pdetail).height($('div.descrContainer',pdetail).height());
        });
    } else {
        pdetail = $('<div></div>');
        pdetail.attr('id','productDetail_' + pid);
        pdetail.addClass('productDetail');
        pdetail.hide();
        pdetailContainer = $('<div></div>').addClass('detailContainer').appendTo(pdetail).hide();
        $('#content').prepend(pdetail);
        pdetail.bind('click.removeme',function () {
            pdetail.remove();
            productHideOverlay();
        });
        productShowOverlay();
        productShowDetailsPositioning(pdetail,function () {
            var loader = $('<img src="' + WEBROOT + '/public/themes/images/ajax-loader3.gif" alt="" />');
            pdetail.append(loader);
            pdetailContainer.load($('#product-' + pid).attr('href') + ' #popupData',function () {
                productShowDetailsCommon(pdetail);
                pdetailContainer.show();
                $('div.descrOpacity',pdetail).height($('div.descrContainer',pdetail).height());
                loader.remove();
                pdetail.unbind('click.removeme');
            });
        });
    }
}

function productShowOverlay() {
    //zobrazime overlay
    if ($('#productOverlay').length == 0) {
        var overlay = $('<div></div>').attr('id','productOverlay');
        overlay.height($(document).height());
        overlay.width($(document).width());
        overlay.css({display: 'none'});
        overlay.appendTo($('body'));
        $('#productOverlay').fadeIn('slow');
    } else {
        $('#productOverlay').fadeIn('slow');
    }
}
function productHideOverlay() {
    $('#productOverlay').fadeOut('slow');
}

function productShowDetailsCommon(pdetail) {
    //button na zatvorenie produktu  
    $('#productOverlay').click(function(){
        pdetail.fadeOut("slow");
        productHideOverlay();
    });
    $('#popupWindowClose').click(function () {
        pdetail.fadeOut("slow");
        productHideOverlay();
    });
    $("span.submitWithCurrency").click(function(){
       form = $(this).closest('form');
       if(form.length){
           if(typeof orderCurrency == 'undefined'){
               centerPopup(200,100);
               loadPopup($('#currencyMessage').html());
               
               $("span.currencyEur").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=EUR');
                    form.submit();
                });
                $("span.currencyChf").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=CHF');
                    form.submit();
                });
           }
           else{
                form.submit();
           }
    }});
}

function productShowDetailsPositioning(pdetail, onAnimComplete) {
    //zacentrujeme detaily
    var finalTop = ($(window).height() - 600) / 2 + $(document).scrollTop();
    var finalLeft = ($(window).width() - 600) / 2 + $(document).scrollLeft();
    pdetail.css({
        position: 'absolute',
        top: $(window).height() / 2 + $(document).scrollTop(),
        left: $(window).width() / 2 + $(document).scrollLeft(),
        width: 0,
        height: 0
    });
    pdetail.fadeIn();
    pdetail.animate({
        left: finalLeft,
        width: 550
    },{
        duration: 700,
        complete: function () {
            $(this).animate({
                top: finalTop,
                height: 300
            },{
                duration: 700,
                complete: onAnimComplete
            })
        }
    });
}

function popupInit(){ 
    $("span.submitWithCurrency").click(function(){
       form = $(this).closest('form');
       if(form.length){
           if(typeof orderCurrency == 'undefined'){
               disablePopup(); 
               centerPopup(200,100);  
               loadPopup($('#currencyMessage').html());
               $("span.currencyEur").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=EUR');
                    form.submit();
                });
                $("span.currencyChf").click(function(){
                    form.attr('action',form.attr('action') + '?orderCurrency=CHF');
                    form.submit();
                });
           }
           else{
                form.submit();
           }
    }});
        
     $("#popupWindowClose").click(function(){
                disablePopup();
     });
     /*
     $("#goodsTable").hide(); 
     $("#showGoodsTable").click(function(){
         if($("#goodsTable").is(":hidden")){
            $("#goodsTable").fadeIn();
         }
         else{
            $("#goodsTable").fadeOut();
         }
     });
     $("#hideGoodsTable").click(function(){
            $("#goodsTable").fadeOut();
     });
     */
     $("span.submit").click(function(){
        var form = $(this).closest('form');
        if(form.length){
            form.submit();
        }
     });
}

function showCloseButton(){
    $('#popupWindow').html('<a id="popupWindowClose">x</a>' + $('#popupWindow').html);
}
     
function displayNextChipItem(init) {
    var $chip = $(this);
    if ($chip.find('div.chipItem').length > 1) {
        //prave zobrazeny chip
        var chipItemCur = $chip.find('div.chipItem-show');
        var duration = 0;
        if (init) {
            duration = parseInt(chipItemCur.find('input[name=duration]').val());
            //nastavime absolutnu poziciu na chipsy
            $chip.find('div.chipItem').css({
                position: 'absolute'
            });
            $chip.find('div.bottom').height(chipItemCur.height());
        } else {
            var nextItem = chipItemCur.next('div.chipItem-hide');
            if (nextItem.length == 0) {
                nextItem = $chip.find('div.chipItem:eq(0)');
            }
            //animacia
            $chip.find('div.bottom').animate({
                height: nextItem.height()
            },500);
            chipItemCur.removeClass('chipItem-show').addClass('chipItem-hide').fadeOut(300);
            nextItem.removeClass('chipItem-hide').addClass('chipItem-show').fadeIn(500);
            duration = parseInt(nextItem.find('input[name=duration]').val());
        }
        if (!duration) {
            duration = 4000;
        }
        window.setTimeout(function () {
            displayNextChipItem.call($chip[0]);
        },duration + 500);
    }
}

function loadPopup(content){
    if(popupStatus==0){
        $("#backgroundPopup").css({
                "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#popupWindow").fadeIn("slow");
            popupStatus = 1;
        if(typeof content !== 'undefined'){
            $('#popupWindow').html(content);
        }
        else{
            $('#popupWindow').html('<a id="popupWindowClose">x</a><div id="ajaxLoader"></div>');
            $('#ajaxLoader').css({width : $('#popupWindow').width(),height: $('#popupWindow').height()});
        }
     } 
}

function disablePopup(){
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#popupWindow").fadeOut("slow");
        popupStatus = 0;
    }  
}

function centerPopup(popupWidth,popupHeight){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    //center
    $("#popupWindow").css({  
            "position": "absolute",
            "width": popupWidth,
            "min-height": popupHeight,
            "top": $(window).scrollTop() + (windowHeight/4),
            "left": windowWidth/2-popupWidth/2
    });  
    //ie6
    $("#backgroundPopup").css({
            "height": windowHeight
    });
}

function slideshow(){
    slideshowTimer = setTimeout(function (){
        $('.slideshow .galleryCell:visible').fadeOut(500,function (){
            var position = $('.slideshow .galleryCell').index($(this));
            if($('.slideshow .galleryCell').length > parseInt(position + 1)){
                var active = $('.slideshow .galleryCell:eq('+ parseInt(position + 1) +')');
            } else{
                var active = $('.slideshow .galleryCell:eq(0)');
            }
            
            active.fadeIn(500);
        });
        
        slideshow();
    },5000);
}

function startLightBoxSlideshow(){
    $('a','.lightbox').click(function(){
         clearTimeout(slideshowTimer);     
         goLightBoxSlideshow();   
    });
    $('a:first','.lightbox').trigger('click');
}
function goLightBoxSlideshow(){  
    slideshowTimer = setTimeout(function (){
       $('#lightbox-nav-btnNext').trigger('click');
       goLightBoxSlideshow();
    },5000);
    
}
