(function($) {
    $.fn.extend({
        isChildOf: function( filter_string ) {
          
          var parents = $(this).parents().get();
         
          for ( j = 0; j < parents.length; j++ ) {
           if ( $(parents[j]).is(filter_string) ) {
                return true;
           }
          }
          
          return false;
        }
    });
})(jQuery); 

$(function() {

        $.prettyLoader();
        
        function initCufon(){
          Cufon.replace('h1', {fontFamily: 'Tahoma'});
          Cufon.replace('h2', {fontFamily: 'Tahoma'});       
          Cufon.replace('.question', {fontFamily: 'Tahoma'});
        }
        initCufon();
        
        
        $('.content-left li li ul, .content-right li li ul').css('display','none');

        $('.content-left li li, .content-right li li').each(function(){
            if($(this).find('ul').length) 
            {
               $(this).prepend('<div class="arrow" style="width:9px; cursor:s-resize; padding:10px 2px; padding-right:6px; margin-right:-3px; height:7px; background: url(/images/arrow-down.png) center center no-repeat; float:right;"></div>');
               $(this).find('.arrow').first().click(function(){
                   if($(this).parent().find('ul').first().css('display')=='none')
                   {
                      $(this).css('background-image','url(/images/arrow-up.png)'); 
                      $(this).parent().find('ul').first().slideDown();
                   }
                   else
                   {
                      $(this).css('background-image','url(/images/arrow-down.png)'); 
                      $(this).parent().find('ul').first().slideUp();                       
                   }
               });
               //this.nodeName.toLowerCase()

               if($(this).find('.arrow').first().length)
               if($(this).find('.arrow').first().next().get(0).tagName.toLowerCase()=='div') {
                  $(this).find('.arrow').first().next().click( function(){ $(this).prev().click(); }).css('cursor','s-resize');
               }
            }    
            else
            {
            }
            
        });
    
        $('.content-left li li a, .content-right li li a').each(function (){
            if($(this).attr('href')==window.location.pathname)
            {
                var i=0;
                $(this).parents('li').each(function() {
                    i=i+1;
                    if($(this).find('ul').first().css('display')=='none')
                    {    
                        $(this).find('.arrow').first().css('background-image','url(/images/arrow-up.png)'); 
                        $(this).find('ul').first().css('display','block'); 
                    }
                });
            }
        });    
        
        $('a').each(function () {
            if($(this).attr('href')==window.location.pathname) $(this).addClass('active');
        });
        
        $('.anwser').each(function() {
           height=$(this).height()+15;
           $(this).css('height', height+'px' ); 
        });
        
        $('.anwser').css('display', 'none');
        
        $('.question').css('cursor', 'pointer').click(function(){
            var what=$(this).next();
            if(what.css('display')=='none') what.slideDown(600);
            else what.slideUp(600);

            $('.anwser').each( function(){    
              if($(this).attr('id')!=what.attr('id')) $(this).slideUp(400,  function(){});
            });    
        });

        $('input[class="reset"]').each(function() {
          var button = $(this);
          tag=$('<a class="buttonfront"><span>'+button.val()+'</span></a>').click(function() {
              // add button params to form
              form = $(this).parents('form').first();
              form.append('<input type="hidden" name="' + button.attr('name') + '" value="' + button.attr('value') + '" />');
              form.submit();
              form.find('input[name="' + button.attr('name') + '"]');

              return false;
          });
          button.parent().append(tag);
          $(this).remove();
        });
        
        function ajaxFormSubmit(){
            $('input[type="submit"]').each(function() {
              var but=$(this);    
              $(this).css('display','none');  

              if(!$(this).hasClass('former'))
              {              
                  $(this).parent().append('<a class="buttonfront form-link"><span>'+$(this).attr('value')+'</span></a>').click(
                    function() {$(this).parents('form').submit();}
                  );       
              }
              else
              {
                 var but=$(this);  
                 var form=$(this).parents('form').eq(0); 
                 
                 $(this).parent().append('<a class="buttonfront form-link"><span>'+$(this).attr('value')+'</span></a>').click(function (){
                      form=$(this).parents('form').eq(0); 
                      form.submit();
                 });
                 
                 form.ajaxForm({
                        //target: '#top',
                        beforeSubmit: function(a,f,o) {
                            o.dataType = 'html';
                            //$(this).css('border','1px solid red');
                            //form.parents('.former-wrapper').eq(0).html('Submitting...');
                        },
                        error:function (xhr, ajaxOptions, thrownError){
                              alert(xhr.status);
                              alert(thrownError);
                        },                        
                        success: function(data) {
                            var $out = $('body').find('.former-wrapper').eq(0);
                            //alert(data);
                            //$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
                            if (typeof data == 'object' && data.nodeType)
                                data = elementToString(data.documentElement, true);
                            else if (typeof data == 'object')
                                data = objToString(data);
                            $out.html(data);
                            ajaxFormSubmit();
                            initCufon();
                        }
                    });

    
//                  .click(
//                    function() {
//                       form=$(this).parents('form').eq(0);
//                       
//                       var options = {   
//                            success: function (data) {
//                                alert('aa'+data);
//                              form.parents('.former-wrapper').eq(0).html(data);
//                              ajaxFormSubmit();
//                              initCufon();
//                            }                            
//                       };                        
//                       
//                       form.ajaxSubmit(options);
////                       $.ajax({
////                            url: form.attr('action'),
////                            data: form.serialize(),
////                            type: form.attr('method'),       
////                            success: function (data) {
////                              form.parents('.former-wrapper').eq(0).html(data);
////                              ajaxFormSubmit();
////                              initCufon();
////                            }
////                        });                   
//                    }
//                  );                 
              }
              
              $(this).remove();
            });              
        }
        
        ajaxFormSubmit();
        

        
        $('input').keypress(function(e) {
            c = e.which ? e.which : e.keyCode;
            if(c == 13) { 
                $(this).parents('form').submit();
            }
        });        
        
        $('#search').focus(
        function(){
            if($(this).val()=='Wpisz szukany tekst') $(this).val('');
        }
        );     

        $('#search').blur(
        function(){
            if($(this).val()=='') $(this).val('Wpisz szukany tekst');
        }
        );  
            
        $('#search_submit').click(
        function(){ 
           if($(this).parent().find('input').eq(0).val()!='Wpisz szukany tekst') $(this).parents('form').submit();
        }
        );              
        
        $('#navigation ul').superfish({
            delay:       200,                            // one second delay on mouseout
            animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation
            speed:       'fast',                          // faster animation speed
            autoArrows:  false,                           // disable generation of arrow mark-up
            dropShadows: true,                            // disable drop shadows
            pathLevels:    4
        });       
        
        $(".tipsy-north[title]").tipsy({fade: true, trigger: 'hover', gravity: 'n', html: true, title: 'title'});
        $(".tipsy-south[title]").tipsy({fade: true, trigger: 'hover', gravity: 's', html: true, title: 'title'});
                        
        $('#side-navigation a').hover(
        function(){
            str=$(this).find('img').attr('src');
            $(this).find('img').attr('src',str.replace('.png','-h.png'));
            $(this).animate({paddingTop: '5px'}, 300);
        },
        function(){
            str=$(this).find('img').attr('src');
            $(this).find('img').attr('src',str.replace('-h.png','.png'));  
            $(this).stop().animate({paddingTop: '0px'}, 300);
            
        }
        );
            
        $(".fancy a").fancybox({
                'titleShow'	: true,
                'titlePosition'	: 'inside',
                'transitionIn'	: 'elastic',
                'transitionOut'	: 'elastic',
                'onComplete'        : function() {

//                            $('#fancybox-img').parent().addClass('zoom-small-image');
//                            var html=$('#fancybox-img').parent().html();
//                            var src=$('#fancybox-img').attr('src');
//
//                            $('#fancybox-img').parent().html('<a href="'+src+'" class="cloud-zoom" rel="softFocus: true, position:\'inside\', smoothMove:2">'+html+'</a>');
//                            $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();

                }
        });   
        
    $('.zoom-img').each(function(){    
        $(this).parent().addClass('zoom-small-image');
        var html=$(this).parent().html();
        var src=$(this).parent().attr('big');

        $(this).parent().html('<a href="'+src+'" class="cloud-zoom" rel="softFocus: true, position:\'inside\', smoothMove:2">'+html+'</a>');
        $('.cloud-zoom').CloudZoom();       
    });    
             
   
    var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline = 0;
    var delay=6800;
    var stop=0;
    var speed_out=900;
    var speed_in=1200;
    
    if($.browser.msie){
        speed_out=0;
        speed_in=0;              
    }
    
    headline_count = $('.rotator .rotator-element').size();

    co=-1;
    
    if(headline_count>1)
    {    
    $(".rotator li div").css('cursor','pointer').click(function (){
            if(stop==0){
      
                clearInterval(headline_interval);
                headline_interval = setInterval(headline_rotate,delay);
                
                next=$('.rotator li div').index(this);
                co=next;
                
                if(next<current_headline) headline_rotate();
                if(next>current_headline)  headline_rotate();
                if(next==current_headline) return false; // headline_interval = setInterval(headline_rotate,delay);
            }
    });
    
    
    $(".rotator li div").css('cursor','pointer').click(function (){
            if(stop==0){
      
                clearInterval(headline_interval);
                headline_interval = setInterval(headline_rotate,delay);
                
                next=$('.rotator li div').index(this);
                co=next;
                
                if(next<current_headline) headline_rotate();
                if(next>current_headline)  headline_rotate();
                if(next==current_headline) return false; // headline_interval = setInterval(headline_rotate,delay);
            }
    });  
    

    headline_interval = setInterval(headline_rotate,delay);
    
    
        
    function headline_rotate() {
      current_headline = old_headline + 1;
      if(current_headline==headline_count) current_headline=0;
      
      if(co!=-1) {current_headline=co;co=-1;}

      stop=1;
 
      $(".rotator .rotator-element").eq(old_headline).fadeOut(speed_out, function(){});
      $(".rotator .rotator-element").eq(current_headline).fadeIn(speed_in, function(){stop=0;});
      
      $(".rotator li div").eq(old_headline).addClass('active');
      $(".rotator li div").eq(current_headline).removeClass('active');
      
      old_headline = current_headline;
    }
    }
    
    
    
    
               
//    var com_headline_count;
//    var com_headline_interval;
//    var com_old_headline = 0;
//    var com_current_headline = 0;
//    var com_delay=4800;
//    var com_stop=0;
//    var com_speed_out=900;
//    var com_speed_in=900;
//    var kierunek=1;
//    
//    if($.browser.msie){
//        com_speed_out=0;
//        com_speed_in=0;              
//    }
//    
//    com_co=-1;
//    
//
//    com_headline_count = $('.company-rotator .company-rotator-element').size();
//    com_headline_interval = setInterval(com_headline_rotate,com_delay);
//
//
//
//    $(".rotator-prev").css('cursor','pointer').click(function (){
//            if(com_stop==0){
//      
//                clearInterval(com_headline_interval);
//                kierunek=-1;
//                com_headline_interval = setInterval(com_headline_rotate,com_delay);
//                com_headline_rotate();
//            }
//    });  
//
//    $(".rotator-next").css('cursor','pointer').click(function (){
//            if(com_stop==0){
//      
//                clearInterval(com_headline_interval);
//                kierunek=1;
//                com_headline_interval = setInterval(com_headline_rotate,com_delay);
//                com_headline_rotate();
//            }
//    });  
//
//
//    function com_headline_rotate() {
//      com_current_headline = com_old_headline + (1*kierunek);
//      if(com_current_headline==com_headline_count && kierunek==1) com_current_headline=0;
//      if(com_current_headline<0 && kierunek==-1) com_current_headline=com_headline_count-1;
//      //alert(com_current_headline);
//      if(com_co!=-1) {com_current_headline=com_co; com_co=-1;}
//
//      com_stop=1;
//      
//      var zmienna=$(".company-rotator .company-rotator-element").eq(com_old_headline).width()*kierunek; 
//      $(".company-rotator .company-rotator-element").eq(com_old_headline).css('left','0px');
//      $(".company-rotator .company-rotator-element").eq(com_current_headline).css('left',zmienna+'px');
//      zmienna=-1*$(".company-rotator .company-rotator-element").eq(com_old_headline).width()*kierunek;
//
//      $(".company-rotator .company-rotator-element").eq(com_old_headline).animate({left:zmienna},com_speed_out, function(){});
//      $(".company-rotator .company-rotator-element").eq(com_current_headline).animate({left:0},com_speed_out,  function(){com_stop=0;}); 
// 
//
//      
//      com_old_headline = com_current_headline;
//    }    
    
    
    
    
    
    
    
    
    $('#product_filters_category_id option:selected').each(function (){
        
      $(".filter li .page input[value="+$(this).attr('value')+"]").parent().addClass('active'); 
       
    }); 
    
   
    if($('.map-data').size() )
    {
       var maps=new Array();
       var markers=new Array();
       var infowindow=new Array();
       
       $('.map-data').each(function(){
            var id=$(this).find('.id').eq(0).html();
            var is_routable=$(this).find('.is_routable').eq(0).html();
            var is_automatic=$(this).find('.is_automatic').eq(0).html();  
            var latitude = $(this).find('.latitude').eq(0).html();
            var longitude = $(this).find('.longitude').eq(0).html();
            var zoom = parseInt($(this).find('.zoom').eq(0).html());
             
            var geocoder = new google.maps.Geocoder();
            var options = {
                zoom:      zoom,
                center:    new google.maps.LatLng(latitude, longitude),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            
            maps[id] = new google.maps.Map(document.getElementById('map'+id), options);
            
            
            directionMarker = new google.maps.Marker({
                map: maps[id], 
                title: 'Punkt początkowy',
                icon: '/images/marker-dir.png',
                position: new google.maps.LatLng(latitude, longitude)}
            );          
                
            directionMarker.setVisible(false);      
            
            var bounds = new google.maps.LatLngBounds();
            
            google.maps.event.addListener(maps[id], 'click', function() {
                for (i in infowindow) {infowindow[i].close();}
            });
            
            $(this).find('.marker').each(function () {
                
                var marker_id=$(this).find('.id').html();
                var icon=$(this).find('.icon').html();
                var title=$(this).find('.title').html();
                var description=$(this).find('.description').html();
                    
                markers[marker_id] = new google.maps.Marker({
                    map: maps[id], 
                    title: title,
                    icon: '/images/marker-'+icon+'.png',
                    position: new google.maps.LatLng($(this).find('.latitude').html(), $(this).find('.longitude').html())}
                );
                    
                if(description!='')    
                {    
                    
                    infowindow[marker_id] = new google.maps.InfoWindow({
                      content: '<div style="max-width:340px;"><h2>'+title+'</h2><p>'+description+'</p></div>'
                    });                    
                    google.maps.event.addListener(markers[marker_id], 'click', function() {
                      // When clicked, open an Info Window
                      for (i in infowindow) {infowindow[i].close();}
                      infowindow[marker_id].open(maps[id], markers[marker_id]);
                    });
                }
                
                bounds.extend(markers[marker_id].getPosition()); 
                if(is_automatic=='1') maps[id].fitBounds(bounds);

                markers[marker_id].setVisible(true);    
            });  
            

        function rad(x) {return x*Math.PI/180;}
        function find_closest_marker( lat, lng ) {
            var R = 6371;
            var distances = [];
            var closest = -1;
            for (i in markers) {
                var mlat = markers[i].position.lat();
                var mlng = markers[i].position.lng();
                var dLat  = rad(mlat - lat);
                var dLong = rad(mlng - lng);
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = R * c;
                distances[i] = d;
                if ( closest == -1 || d < distances[closest] ) {
                    closest = i;
                }
            }
            return closest;
            //alert(markers[closest].title);
        }         
        
   
        var directionsDisplay = new google.maps.DirectionsRenderer();
        var directionsService = new google.maps.DirectionsService();
        
        function mapDirections(origin){
                directionsDisplay.setMap(null);
                directionsDisplay = new google.maps.DirectionsRenderer();
                
                
                var marker;
                
                geocoder.geocode({address: origin}, function (results, status) {
                    if(status=='OK')
                    {  
                        marker=find_closest_marker( results[0].geometry.location.lat(),  results[0].geometry.location.lng() ); 

                        directionMarker.setPosition(new google.maps.LatLng(results[0].geometry.location.lat(),  results[0].geometry.location.lng()));


                        var options= {suppressMarkers: true};
                        directionsDisplay.setOptions(options);
                        

                        
                        var request = {
                          origin: origin,
                          destination: markers[marker].position,
                          avoidTolls:false,
                          
                          travelMode: google.maps.DirectionsTravelMode.DRIVING,
                          unitSystem: google.maps.DirectionsUnitSystem.METRIC,
                          provideRouteAlternatives: true//,
                          //waypoints: [{location: "Górczewska",stopover:false}]
                        };
                        
                        directionsService.route(request, function(response, status) {
                                if (status == google.maps.DirectionsStatus.OK) {
                                        directionsDisplay.setDirections(response);
                                        markers[marker].setZIndex(9999999);
                                        directionMarker.setVisible(true);
                                        directionsDisplay.setMap(maps[id]);
                                        
                                        
                                } else {
                                    directionMarker.setVisible(false);
                                    alert('Error: ' + status);
                                }
                        });                    
                    
                    }else alert('Nie odnaleziono podanego adresu');             
                });                 


        }
        
        
        $('.map-find').click(
        function() {
           mapDirections($(this).next().next().val()); 
        }
        );    
  
        
        
     
       }); 
        
    }    
    
});


