function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

$(document).ready(function () {
  if(typeof google != "undefined") {
 

    /* MAP laden */
    //------- Google Maps ---------//
  	var map;
        
  	// Creating a LatLng object containing the coordinate for the center of the map
  	var latlng = new google.maps.LatLng(53.385846,-1.471385);
  	  
  	// Creating an object literal containing the properties we want to pass to the map  
  	var options = {  
  		zoom: 15, // This number can be set to define the initial zoom level of the map
  		center: latlng,
  		mapTypeId: google.maps.MapTypeId.ROADMAP // This value can be set to define the map type ROADMAP/SATELLITE/HYBRID/TERRAIN
  	};  
  	// Calling the constructor, thereby initializing the map  
  	map = new google.maps.Map(document.getElementById('fdealer_map'), options);  
  	
  	// Define Marker properties
  	var image = new google.maps.MarkerImage('/2012/fileadmin/templates/vis/ico/pin.png',
  		// This marker is 17 pixels wide by 20 pixels tall.
  		new google.maps.Size(17, 20),
  		// The origin for this image is 0,0.
  		new google.maps.Point(0,0),
  		// The anchor for this image is the base of the flagpole at 18,42.
  		new google.maps.Point(17, 20)
  	);
  	
  	    // Create information window
  	createInfo = function(content) {
  		return '<div class="infowindow">'+content+'</div>';
  	} 
    
    // Go to Position
    placeMarker = function(location,content) {

      var marker = new google.maps.Marker({
          position: location, 
          map: map,
          icon: image
      });
      
      
    	// Add listener for a click on the pin
    	google.maps.event.addListener(marker, 'click', function() {  
    		infowindow.open(map, marker);  
    	});
    		
    	// Add information window
    	var infowindow = new google.maps.InfoWindow({  
    		content:  createInfo(content)
    	}); 
      
    }
    
    /* Center Position */
     gotoLocation = function(location,zoom) {
      map.setCenter(location);
      map.setZoom(zoom);
    }
    
    /* GET Coordinates for Location via Google */
    gotoAddress = function(address,zoom) {
  				geocoder = new google.maps.Geocoder();
  				geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              var location =  results[0].geometry.location;
              gotoLocation(location,zoom);
            }
          });   
  	}
  	
  	markAddress = function(address) {
  				geocoder = new google.maps.Geocoder();
  				geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              var location =  results[0].geometry.location;
              placeMarker(location);
            }
          });   
  	}  
  	
  	gotoAddress('Fulda, Deutschland',6);
  	
  	/*/ Add Marker
  	var marker1 = new google.maps.Marker({
  		position: new google.maps.LatLng(53.385846,-1.471385), 
  		map: map,		
  		icon: image // This path is the custom pin to be shown. Remove this line and the proceeding comma to use default pin
  	});	
  	
  	// Add listener for a click on the pin
  	google.maps.event.addListener(marker1, 'click', function() {  
  		infowindow1.open(map, marker1);  
  	});
  		
  	// Add information window
  	var infowindow1 = new google.maps.InfoWindow({  
  		content:  createInfo('Evoluted New Media', 'Ground Floor,<br />35 Lambert Street,<br />Sheffield,<br />South Yorkshire,<br />S3 7BH<br /><a href="http://www.evoluted.net" title="Click to view our website">Our Website</a>')
  	}); */
    
    $(".showonmap").click(function(event) {
      var address = $(this).parent().next('.onethirdwom').children('.address').html();
      gotoAddress(address,14);
      event.preventDefault();
    });
    
    /**$("#fdealerform").click(function() {
         $("#fdealer-results").slideDown('fast'); 
         var address = $("#fdealer-address").val() + ", " + $("#fdealer-country").val();
         gotoAddress(address);
         $('#fdealer-results .address').each( function() {
            address = $(this).html();
            markAddress(address);
            gotoAddress(address,6);
         });
         
         return false;         
    });**/ 
  }

  $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" });
  
  $("#HomeCampaign .scrollable").scrollable({ circular: true }).autoscroll({autoplay: true, interval: 5000}).navigator();

  $(".primarynavigation .sf-menu").superfish(); 
   
  /******/  
  
  $('#bikeseries_switchview .coverflow').click(function() {
       toggleBikeViewtocoverflow();
  }); 
  
  $('#bikeseries_switchview .matrix').click(function() {
       toggleBikeViewtomatrix();
  });
  
  /* Ipad standardmaessig auf matrix switchen sonst imageflow laden */
  if ( $("#ImageMatrixBikes").html != '' && (navigator.userAgent.indexOf('iPad') != -1) ) {  
     toggleBikeViewtomatrix();
  } else if( $("#ImageFlow > img").size() < 2 ) {
    toggleBikeViewtomatrix();
    $('#bikeseries_switchview').hide();
  } else {
     bikesimageflow_start();
  }    
  
  function toggleBikeViewtocoverflow() {
    $('#ImageMatrixBikes').fadeOut(100, function() {
      /* Imageflow muss neu geladen werden da Script bei Display none beendet wird */ 
      bikesimageflow_start();
      $('#ImageFlow').fadeIn(100); 
    } );
  }
  
  function toggleBikeViewtomatrix() {
    $('#ImageFlow').fadeOut(100, function() { $('#ImageMatrixBikes').fadeIn(100).tinyscrollbar(); } );
  }
  
  /* Bike Coverflow initialisieren und Wipe Events auf Bikes aktivieren */
  function bikesimageflow_start () {
    var bikesimageflow = new ImageFlow();
    bikesimageflow.init({ 
      ImageFlowID: 'ImageFlow', 
      imageFocusM: 1.10,
      reflections: false, 
      imageFocusMax: 1,
      aspectRatio: 1.40,
      imagesM: 0.63,
      xStep: 108,
      slider: false,
      reflectionP: 2,
      buttons: true,
      startID: 2,
      startAnimation: true,
      imageCursor: 'pointer',
      onClick: function() { window.open(bikesimageflow.imagesDiv.childNodes[bikesimageflow.imageID].getAttribute('title'), '_self'); }
    });
    
    $('.imageflow').wipetouch({
        wipeLeft: function(result) { bikesimageflow.MouseWheel.handle(-1); },
        wipeRight: function(result) { bikesimageflow.MouseWheel.handle(1); }
    });
    
    $('.imageflowcontrol a.prev').click(function() {
    bikesimageflow.MouseWheel.handle(1);
    }); 
    $('.imageflowcontrol a.next').click(function() {
      bikesimageflow.MouseWheel.handle(-1);
    }); 
  } 
  
  /* Funktion zum Abholen des Vimeo Embed Codes fuer Videos ueber die API */
  function biketvstartwoembed( videourl ) {
     $.ajax({
      type: "GET",
      data: "url=http%3A//"+videourl+"?callback=?",
      url: "http://vimeo.com/api/oembed.json?url=http%3A//"+videourl,
      dataType: "jsonp",
      success: function(data) {
                  $("#VidCover .biketv").html(data.html);
                  
                  $("#VidCover .biketv iframe").attr('width','960');
                  $("#VidCover .biketv iframe").attr('height','540');
                  $("#VidCover .biketv iframe").attr('src', $("#VidCover .biketv iframe").attr('src')+'?autoplay=1' );
               }
      });
  }
  
  /* Funktion zum Abholen der Twitter Updates via JSON API */
  function update_twitter_widget( data ) {
      
      $.each(data, function(key, val) {
        tweetuser = val.user.profile_image_url;
        tweetdate = val.created_at;
        tweet = val.text;
        $(".twitter_widget .container").prepend('<li class="tweet'+ key +'"><img src="'+ tweetuser +'" alt="" class="left marginr10" /><div><b>'+ tweetdate +'</b><br /><span class="grey">' + tweet + '</span></div><div class="clean"></div></li>');
        $(".twitter_widget .container li.tweet"+key).fadeIn(500);
      });
      $(".twitter_widget").linkify();
  }
  function getghosttweets() {
     $.ajax({
      type: "GET",
      data: "count=5&callback=?",
      url: "http://twitter.com/status/user_timeline/ghostbikesgmbh.json",
      dataType: "jsonp",
      success: function(data) {
                  update_twitter_widget(data);
               }
      });
  }
  
  getghosttweets();
  
  /* Imageflow fuer Biketv Steuerung*/
  biketvimageflow_start();
  function biketvimageflow_start () {
    var $_GET = getQueryParams(document.location.search);
    if($_GET["vid"]>0) startid = $_GET["vid"]; else startid = 2;
    var biketvimageflow = new ImageFlow();
    biketvimageflow.init({ 
      ImageFlowID: 'BikeTVImageFlow', 
      imageFocusM: 0.85,
      reflections: false, 
      imageFocusMax: 1,
      aspectRatio: 4.3,
      reflectionP: 0.1,
      imagesM: 0.67,
      xStep: 112,
      slider: false,
      percentLandscape: 100, 
      percentOther: 50, 
      buttons: true,
      imageCursor: 'pointer',
      startID: 2,
      startAnimation: true,
      onClick: function() { biketvstartwoembed(biketvimageflow.imagesDiv.childNodes[biketvimageflow.imageID].getAttribute('href')); }
    });
    
    $('#BikeTVImageFlow').wipetouch({
        wipeLeft: function(result) { biketvimageflow.MouseWheel.handle(-1); },
        wipeRight: function(result) { biketvimageflow.MouseWheel.handle(1); }
    });
    
    $('#BikeTVControl a.prev').click(function() {
    biketvimageflow.MouseWheel.handle(1);
    }); 
    $('#BikeTVControl a.next').click(function() {
      biketvimageflow.MouseWheel.handle(-1);
    }); 
  } 
  
  /* Tabs starten */
  $("#bikedetails-tabselect").tabs("#bikedetails-tabs > div");
  $("#bikedetails_switchcolor_select").tabs(".cover .bike > div");
  $("#experience-tabselect").tabs("#experience-tabs > div", {history: true });
  $("#default-tabselect").tabs("#default-tabs > div", {history: true });
  deftabs_api = $("#default-tabselect").data("tabs");
  biketabs_api = $("#bikedetails-tabselect").data("tabs");
  
  // Tabs mit Anchor und Index als Array schreiben
  var tabswpagination = new Array();
  tabarr = new Array();
  $("#default-tabselect").children().each( function(index) {
     var tabname = $(this).children('li a').attr('href');

     tabswpagination.push(tabname);
  });
  
  // Pagination in Tabs mit Tabname versehen damit nach Seitenreload der TAb offen ist
  $("#default-tabs > div").each( function(index) {
    $(this).find("li a").attr('href',function() {
          urlneu = $(this).attr('href')+tabswpagination[index];
          return urlneu;
    });
  });
  
  // Klcika uf Testlogo oeffnet testberichte tab
  $(".bike .thecert").click(function() {
    biketabs_api.click(3);
  });
  
  /* Fix for HTML5 Video in IFrame */
  /*deftabs_api.onClick(function(obj, index) {
       var  panes = deftabs_api.getPanes();
       var pane = $(panes).get(index);
       var panecontent = $(pane).html();
       $(pane).html('').delay(10000).html( panecontent ).children('iframe').css('display','block').css('border','10px solid red');
  });*/
  
  /* Navigate right through Tabs - if last is reached go to first */
  function tabs_next(api) {
    api.next();
  }
  /* Navigate left through Tabs - if first is reached go to last */ 
  function tabs_prev(api) {
    api.prev();
  }
  if($('#default-tabcontrol').hasClass('wipetouch')) {
    if((navigator.userAgent.indexOf('iPad') != -1)) $('#default-tabcontrol .title').html('Swipe to navigate...');
    $('#default-tabcontrol').wipetouch({
        wipeLeft: function(result) { tabs_next(deftabs_api); },
        wipeRight: function(result) { tabs_prev(deftabs_api); }
    });
  }
  $('#default-tabcontrol .next').click(function() { 
      tabs_next(deftabs_api);
  });
  
  $('#default-tabcontrol .prev').click(function() { 
    tabs_prev(deftabs_api);
  });
  
  /* Selects mit listbox ersetzen */
  $(".bikeselect select").selectbox();
  $(".listfield").selectbox();
  
  /* Toggle Fields z.b. FAQ */
  $(".toggler").click(function() {
     $(this).next('.toggle').toggle(100);
  });
  $(".toggler-after").click(function() {
        $(this).parent('.toggle').toggle(100);
  });
  
  /* Bikeinfo holen nach Select Change */
  $("#bikeaselect").change(function() {
    $(this).children("option:selected").each(function () {
       bikea = $(this).val();
       bikeaname = $(this).text();
    });

    $.post("api/bikeapi.php", { bike: bikea, bikename: bikeaname, tpl: "vergleich" },
     function(data) {
       $("#ImageMatrixBikeVergleich .bikea .prodimg").attr('src',data['prodimg']);
       $("#ImageMatrixBikeVergleich .bikea .caption").html(data['caption']);
       $("#ImageMatrixBikeVergleich .bikea .cert").html(data['cert'])
       $("#bikeainfo").html(data['bikeinfo']);
    }, "json");
  });
  $("#bikebselect").change(function() {
    $(this).children("option:selected").each(function () {
       bikeb = $(this).val();
       bikebname = $(this).text();
    });

    $.post("api/bikeapi.php", { bike: bikeb, bikename: bikebname, tpl: "vergleich" },
     function(data) {
       $("#ImageMatrixBikeVergleich .bikeb .prodimg").attr('src',data['prodimg']);
       $("#ImageMatrixBikeVergleich .bikeb .caption").html(data['caption']);
       $("#ImageMatrixBikeVergleich .bikeb .cert").html(data['cert'])
       $("#bikebinfo").html(data['bikeinfo']);
    }, "json");
  });
  $("#bikecselect").change(function() {
    $(this).children("option:selected").each(function () {
       bikec = $(this).val();
       bikecname = $(this).text();
    });

    $.post("api/bikeapi.php", { bike: bikec, bikename: bikecname, tpl: "vergleich" },
     function(data) {
       $("#ImageMatrixBikeVergleich .bikec .prodimg").attr('src',data['prodimg']);
       $("#ImageMatrixBikeVergleich .bikec .caption").html(data['caption']);
       $("#ImageMatrixBikeVergleich .bikec .cert").html(data['cert'])
       $("#bikecinfo").html(data['bikeinfo']);
    }, "json");
  });
  /****/
  
  /* Lightbox fuer Detailshots in Bikedetail */
  $('#bikedetails_detailshots a').fancybox({cyclic: true});
  $('a.lightbox').fancybox();
  $("a.vimeovid").click(function() {
        $.fancybox({
	          'padding'       : 10,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'         : 640,
            'height'        : 385,
            'href'			: this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
            'type'          : 'swf',
            'swf'           : {
            'wmode'             : 'transparent',
            'allowfullscreen'   : 'true'
            }
        });
 
        return false;
  }); 
  
  /* Bikeoverview Toggle Overlay */
  $("#BikeOverview li").hover(function() {
     if($.browser.msie < 9) $(this).children('.bikeoverlay').toggle();
     else $(this).children('.bikeoverlay').slideToggle(100);
  });
  
  /* Video im Cover einblenden */
  if ($(".cover .clip").html != '' && (navigator.userAgent.indexOf('iPad') != -1) ) {  
     $(".cover .clip").css('display','block');
     $(".cover .clip").css('height','1px');
     $(".cover .clip").css('overflow','hidden');     
     
     $(".cover .coverclip").click(function() {
         $(".cover").animate({height: '650px'});
         $(".cover .clip").animate({height: '540px'});
     });
     $(".cover .clip .cancel").click(function() {
         $(".cover").animate({height: '618px'});
         $(".cover .clip").animate({height: '1px'});
     });

  } else {
     $(".cover .coverclip").click(function() {
        $(".cover").animate({height: '650px'});
        $(".cover .clip").fadeIn(300);
      });
      $(".cover .clip .cancel").click(function() {
         $(".cover .clip").fadeOut(300);
         $(".cover").animate({height: '618px'});
      });
  }
  
  // Bike Preview Box
  $(".bikepreview").hover(function() {
      bikeid = $(this).attr('id');
      previewdiv = "#bikepreview-"+bikeid.substring(8);
      
      // Bild aus rel lesen und anzeigen
      bikeimg = $("img.bike",previewdiv).attr('alt');
      $("img.bike",previewdiv).attr('src',bikeimg);
      
      // Positionierung
      position = $(this).offset();
      positionoff = $('#stdSite').offset();
      
      width = $(this).parent().width();
      $(previewdiv).css('left',(position.left-positionoff.left+width-11)+"px");
      
      $(previewdiv).fadeIn();
      
      height = $(previewdiv).height();
      if( (height+position.top)<=640 ) $(previewdiv).css('top',position.top+"px");
      else $(previewdiv).css('top',(position.top-height+15)+"px");
      
  }, function() {
      $(".bikepreviewdiv").fadeOut();
  });
  
  /* Bei diesen Browsern ist bekannt dass font-face nicht geht und somit die Schrift zu gross dargestellt
  wird und somit umbricht - passe Schriftgroesse an */
  if( ($.browser.opera && $.browser.version < 10) || ($.browser.safari && $.browser.version < 5) ) {
    $('.primarynavigation .sf-menu a').css('font-size','12px');
  }
  
  
});

var changelang = function(langid){
	document.getElementById("langvalue").value=langid;
	document.langform.submit();
}

var changelang2 = function(langid){
	document.getElementById("langvalue2").value=langid;
	document.langform2.submit();
}

