/*  freshfactory
 *  File:       freshfactory.js
 *  Abstract:   javascript for http://freshfactory.com/
 *  Version:    1.0
 *  (c):       Marc Wright | Team Tejat Hamburg 2011
  
*/


$.fn.infiniteCarousel = function () {
    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
    $(this).fadeIn(700);
    
    return this.each(function () {
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ul'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible);            


        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li'); // reselect
        
        // 3. Set the left position to the first 'real' item
        $wrapper.scrollLeft(singleWidth * visible);
        
        // 4. paging function
        function gotoPage(page) {
            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 200, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                } 

                currentPage = page;
            });                
            
            return false;
        }
        
        
        $wrapper.after('<span class="productSliderNavigation"><a class="prev"></a><a class="next"></a><a class="autoplay"></a></span>');
        
        // 5. Bind to the forward and back buttons
        $('a.prev', this).click(function () {
            window.clearInterval(aktiv);
            return gotoPage(currentPage - 1);
        });
        
        $('a.next', this).click(function () {
            window.clearInterval(aktiv);
            return gotoPage(currentPage + 1);
        });
        
        /* a seconf forward link for the autoplay trigger */
        $('a.autoplay', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        
        // create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
    });  
};
/* the interval that triggers the autoplay */
var aktiv = setInterval("autoplay()", 7000); // time in ms

/* the autoplay function */
function autoplay(){
  $('a.autoplay').trigger('click');
}

function onBefore() {
  $('.homeHeaderRotationText').filter(':not(:animated)').fadeOut('fast');
}
function onAfter() {
  $('.homeHeaderRotationText').filter(':not(:animated)').fadeIn('fast');
}

$(document).ready(function(){
    
    /* open all  links in a new window  */
       $("a.ext", this).click(function(){
         window.open(this.href) //, "Action", "width=600,height=400,scrollbars=yes";
         return false;
       });
       
       
      /* init fancybox for a --> jpg png or gif */
      //$("a[href$=.jpg],a[href$=.png],a[href$=.gif]").
      $('a[href$=.jpg],a[href$=.png],a[href$=.gif]').fancybox({
        'showNavArrows'   : true,
        'overlayOpacity'  : 0.8,
        'padding'         : 20,
        'transitionIn'    : 'elastic',
        'transitionOut'   : 'elastic',
        'speedIn'         : 200, 
        'speedOut'        : 200, 
        'overlayShow'     : true
      });
    $('.infiniteCarousel').infiniteCarousel();
    
    /* count elemets; >2 init cycle */
      numImages = $('#homeHeaderRotation').children().size();
      
      if(numImages >= 2 ){
              /* init cycle */
              $('#homeHeaderRotation').each(function() {
                $(this)
                    .cycle({ 
                     fx: 'fade',
                        delay:              6000,            // additional delay (in ms) for first transition (hint: can be negative)
                        speed:              1000,
                        timeout:            5000,
                        pause:              0,          // true to enable "pause on hover" 
                        pauseOnPagerHover:  0,          // true to pause when hovering over pager link 
                        pager:              '#pager',
                        next:               '.next',
                        prev:               '.prev',
                        fastOnEvent:        1,
                        before:             onBefore,
                        after:              onAfter  
              });
      })
    }
    
    /* init text since it gets faded first trough onBefore */
    $('.homeHeaderRotationText').fadeIn('fast');
});


/* the key bindings */
$(document).keydown(function (e) {
      numImages = $('#homeHeaderRotation').children().size();
      if(numImages >= 2 ){
            /* right */
            if (e.which == 39) {
              $(".next").trigger('click');
              $('#home_header').cycle('pause');
            /* left */
            } 
             if (e.which == 37) {
              $(".prev").trigger('click');
              $('#home_header').cycle('pause');
            }
      }
});



/* Google maps */
  var map;
  var gdir;
  var startIcon;
  var endIcon;

/* icon setter */
function createSpecialMarker(point, specialKey, specialIcon) {
  	if(specialIcon === undefined) {
  		specialIcon = startIcon;
  	}
    markerOptions = { icon:specialIcon, clickable: false };
  	var marker = new GMarker(point, markerOptions );
  	return marker;
}


/* initialisze on load */
function initialize() {
    if (GBrowserIsCompatible()) {      
      map = new GMap2(document.getElementById("map_canvas"));
      gdir = new GDirections(map, document.getElementById("directions"));
      
      map.addControl(new GMapTypeControl());
      map.addControl(new GLargeMapControl());
      map.addControl(new GScaleControl());
      map.addControl(new GMapTypeControl());
      
      map.setCenter(new GLatLng(53.521, 10.09), 14); /*hh Fresfactory*/
      map.removeMapType(G_NORMAL_MAP);
      map.removeMapType(G_SATELLITE_MAP);
      map.firstRun = true;
      
      var HomeIcon = new GIcon(G_DEFAULT_ICON);
      HomeIcon.shadow = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_shadow.png";
      HomeIcon.image = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_end.png";
      HomeIcon.iconSize = new GSize(75, 65);
      HomeIcon.shadowSize = new GSize(75, 65);
      HomeIcon.iconAnchor = new GPoint(23, 64); /* -left offset */
      HomeIcon.infoWindowAnchor = new GPoint(19, 5);
      // Set up our GMarkerOptions object
      markerOptions = { icon:HomeIcon };
      
      /* set up the MarkerManager class */
      routingmgr = new MarkerManager(map);
      routingmgr.hide();
      
      map.specialMarkers = [];
      
      var latlng = new GLatLng(53.523100, 10.0965);
      var ffPosition = new GMarker(latlng, markerOptions);
      map.addOverlay(ffPosition);
      
      
      /* fresh start Icon */
      var startIcon = new GIcon();
      startIcon.shadow = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_shadow.png";
      startIcon.image = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_start.png";
      startIcon.iconSize = new GSize(75, 65);
      startIcon.shadowSize = new GSize(75, 65);
      startIcon.iconAnchor = new GPoint(23, 64); /* -left offset */
      startIcon.infoWindowAnchor = new GPoint(19, 5);
      
      /* fresh end Icon */
      var specialIcon = new GIcon();
      specialIcon.shadow = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_shadow.png";
      specialIcon.image = "http://freshfactory.com/wp-content/themes/freshfactory/images/marker_end.png";
      specialIcon.iconSize = new GSize(75, 65);
      specialIcon.shadowSize = new GSize(75, 65);
      specialIcon.iconAnchor = new GPoint(23, 64); /* -left offset */
      specialIcon.infoWindowAnchor = new GPoint(19, 5);
      
      /* flash section */
      var myPano = new GStreetviewPanorama(document.getElementById("pano"));
      fenwayPark = new GLatLng(53.522509,10.095861);
      myPOV = {yaw:338.94659986187695,pitch:0};
      myPano.setLocationAndPOV(fenwayPark, myPOV);
      //GEvent.addListener(myPano, "error", handleNoFlash);
      
      /* set direction poly == darkgreen on load*/
      GEvent.addListener(gdir,"load",function() {
         var poly=gdir.getPolyline(); 
         poly.color = "#52f710"; 
         map.addOverlay(poly); 
         map.removeOverlay(ffPosition); /* removes the origin from the map*/
      }); 
       
      GEvent.addListener(gdir, "addoverlay", function() {
          
          newSearch(); // remove old search?
          
          /* hide default marker */
          gdir.getMarker(0).hide();
     			gdir.getMarker(1).hide();
          
          /* pass directions into map */ 
          routingmgr.addMarker(createSpecialMarker(gdir.getMarker(0).getLatLng(), "", startIcon), 1);
					routingmgr.addMarker(createSpecialMarker(gdir.getMarker(1).getLatLng(), "", specialIcon), 1);
					routingmgr.show();
          
      })
      
      /* errorhandling */
      GEvent.addListener(gdir, 'error', function() {
          handleErrors();
      });
      
    }
}

$(window).unload( function () { GUnload(); } );



function newSearch() {
  $('#googleSearchError').html(''); // clear display of errors the appeared before
  
  if($('.topTabDirections').attr('class') == "topTabDirections active" ){
    $('#gmaps').trigger('click');
  }
  
  if(gdir.getStatus().code == 500 || gdir.getStatus().code == 200){     // if direction is clear...
     $(".topTabDirections").show();     // show last tab directions
     $("#googlePrint").show();          // show last tab directions
     $('#googleSearchError').html(''); // clear display of errors the appeared before
  }
  
  /*clear old markers */
  routingmgr.clearMarkers();
	routingmgr.hide();
}  
  
/* search function */
function setDirections(fromAddress, toAddress, locale) {
  newSearch();
  
  gdir.load("from: " + fromAddress + " to: " + toAddress,
            { "locale": locale });
              
}

/* google search errors */
function handleErrors(){
     if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
       $('#googleSearchError').html('Es konnte keine entsprechende geografische Position für die angegebene Adresse gefunden werden. Dies kann daran liegen, dass die Adresse relativ neu oder möglicherweise falsch ist.');
     else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
       $('#googleSearchError').html("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
     else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) //
       $('#googleSearchError').html("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
     else if (gdir.getStatus().code == G_GEO_BAD_KEY)
       $('#googleSearchError').html("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
     else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
       $('#googleSearchError').html("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
     else $('#googleSearchError').html("An unknown error occurred.");
}

/*the tabs */
$(document).ready(function(){
  $(".topTabDirections").hide(); //Show first tab content
  $(".tab_content").hide(); //Hide all content
  $("ul.tabs li:first").addClass("active").show(); //Activate first tab
 
  /* route back to map */
  /*$("div#directions.tab_content div").click(function(){
      $("#gmaps").trigger('click');
      console.log('trigger');
  })
  */
  /* hide search google field? in sreetview  */
  $("#gstreetview").click(function(){
      $("#googleSearch").hide();
  })
  
  /* hide search google field? in sreetview  */
  $("#gmaps, #gdirections").click(function(){
      $("#googleSearch").show();
  })
  
  
  $(".tab_content:first").show(); //Show first tab content
  
  //On Click Event
  $("ul.tabs li").click(function() {
  	$("ul.tabs li").removeClass("active"); //Remove any "active" class
  	$(this).addClass("active"); //Add "active" class to selected tab
  	$(".tab_content").hide(); //Hide all tab content
  	var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
  	//$(activeTab).fadeIn(); //Fade in the active content
  	$(activeTab).show(); //Fade in the active content
    
  	return false;
  });
})


/* Input text value change on click // by www.lotsofcode.com  */
/* required in bigbox.php */
$(document).ready(function() {
      $('.pufields').click(
          function() {
              if (this.value == this.defaultValue) {
                  this.value = '';
                  //$('.pufields').select();
              }
          }
      );
      $('textarea').focus(
          function() {
              if (this.value == this.defaultValue) {
                  this.select();                  
                  //this.value = this.defaultValue;
                  //$('.pufields').select();
                  
              }
          }
      );
      $('.pufields').blur(
          function() {
              if (this.value == '') {
                  this.value = this.defaultValue;
              }
          }
      );
                
});
