/*********************************************************************************
 * fabrique d'images ebusiness GmbH
 * Ankergässele 2
 * 87435 Kempten
 * Germany
 * http://www.fdi.de
 * info[at]fdi.de
 *
 * @Creation: 01.08.2011
 * @Version: 1.0
 *
 * @Client:             Wilhelm Geiger GmbH & Co.KG
 * @Clientwebsite:      http://www.w-geiger.de
 * @Project:            Relaunch 2011
 *
 * JavaScript:
 * @Author:				Markus Pezold
 * @Authorwebsite:      http://www.fdi.de | http://www.black-forever.de
 *
 *********************************************************************************/

var Geiger = {
	"init": function () {
		Geiger.registerEvents();
        Geiger.makeGallery();
        Geiger.makeSlideShow();
        Geiger.initSearch();
    },

    "registerEvents": function () {

        // Add print button to the page - unobtrusive JavaScript print function
        if($('#functions').length) {

            $('#functions').prepend('<a href="#print" title="Seite ausdrucken" id="printButton">Seite drucken</a>');
            $('#functions a#printButton').click(function() {
                window.print();
                return false;
            });
        }
        
        // add lightbox functionality to linked mediums in #content div
        if ($("#content .medium a").length) {
            $("#content .medium a").lightBox({fixedNavigation:true});
        }

        // Add history back function to links with the class 'back' (a.back)
        /*if($('a.back').length){
            $('a.back').click(function() {
                history.back();
                return false;
            });
        }*/

	
        // Add unobtrusive JavaScript function for input value within the search
       if($('#search').length) {

            var defaultValue = "Suchbegriff eingeben ..."; // You can change here the defaultValue for the Search Input

            $('#searchInput').val(defaultValue);

            $('#searchInput').click(function() {
                if (this.value == defaultValue) {
                    this.value = '';
                }
            });

            $('#searchInput').focus(function() {
                if (this.value == defaultValue) {
                    this.value = '';
                }
            });

            $('#searchInput').blur(function() {
                if (this.value == '') {
                    this.value = defaultValue;
                }
            });
        }

	//Kontaktformular-Validierungen
	if ($('#contactForm').length > 0) {
		$("[name='_formular']").validate();
	}

        // Facebook Like it (or not!)

        function showFacebookLike() {
            var curURL = location.href;
            $("#facebookLike").html('<iframe src="http://www.facebook.com/plugins/like.php?locale=de_DE&href=' + curURL + '&layout=button_count&show_faces=false&width=140&height=20&action=like" width="140" height="20" scrolling="no" frameborder="0" allowTransparency="false" style="height:20px;width:140px;"></iframe>');
        }

        if ($("#showFacebookLike")) {

            showFacebookLike();

            /* Facebook Privacy hack is commented out upon customer request.

            $("#showFacebookLike").click( function (e) {
                showFacebookLike();
                e.preventDefault();
            });  */
        }

	},

    "makeGallery": function () {

        // Make Gallery - based on the JQuery plugin Galleriffic
        // Url: http://www.twospy.com/galleriffic/
        // Credits: Trent Foley - http://trentacular.com

        if($('#thumbs').length) {


            // Config-Script for Gallerific - Change the Value if you need?

            $('#thumbs').galleriffic({
                delay:                     4000,
                numThumbs:                 16,
                preloadAhead:              32,
                enableTopPager:            false,
                enableBottomPager:         true,
                maxPagesToShow:            7,
                imageContainerSel:         '#slideshow',
                controlsContainerSel:      '#controls',
                captionContainerSel:       '#galleryCaption',
                loadingContainerSel:       '',
                renderSSControls:          true,
                renderNavControls:         true,
                playLinkText:              'Slideshow starten',
                pauseLinkText:             'Slideshow stoppen',
                prevLinkText:              '',
                nextLinkText:              '',
                nextPageLinkText:          'Weiter',
                prevPageLinkText:          'Zurück',
                enableHistory:             false,
                enableKeyboardNavigation:  true,
                autoStart:                 true,
                syncTransitions:           true,
                defaultTransitionDuration: 3000,
                onSlideChange: function(prevIndex, nextIndex) {this.find('ul.thumbs').children().eq(nextIndex).fadeTo('fast', 1.0);},
                onPageTransitionOut: function(callback) {this.fadeTo('fast', 0.0, callback);},
                onPageTransitionIn: function() {this.fadeTo('fast', 1.0);}
            });
        }

    },

    "makeSlideShow": function () {

        // Make SlideShow with JQuery - based on the Tutorial on Sohtanaka.com
        // Url: http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery
        // Credits: Soh Tanaka - http://www.sohtanaka.com
        // Customization & improvements: Markus Pezold - http://www.fdi.de

        if($('.slideshow').length) {

            //Show the paging and activate its first link

            $(".slidePaging").show();

            $(".slidePaging a:first").addClass("active");

            //Adjust Caption for the first image

            var imgCaption = $('.slideImages img[rel="1"]').attr("alt");

            if (imgCaption != "") {
                $(".slidePaging").css({'right' : '360px'});
                $(".slideCaption").show();
                $(".slideCaption p").html(imgCaption);
            }

           //Get size of the image, how many images there are, then determin the size of the image reel.

           var imageWidth = $(".slides").width();
           var imageSum = $(".slideImages img").size();
           var imageReelWidth = imageWidth * imageSum;

           //Adjust the image reel to its new size

            $(".slideImages").css({'width' : imageReelWidth});

           //Paging and Slider Function

           rotate = function(){
                var triggerID = $active.attr("rel") - 1;            //Get number of times to slide
                var image_reelPosition = triggerID * imageWidth;    //Determines the distance the image reel needs to slide

                $(".slidePaging a").removeClass('active');          //Remove all active class
                $active.addClass('active');                         //Add active class (the $active is declared in the rotateSwitch function)

                //Slider Animation

                if ($.browser.msie) {
                    $(".slideImages").hide();
                    $(".slideImages").css("left", -image_reelPosition);
                    $(".slideImages").show();
                 }

                else {
                    $(".slideImages").fadeOut(800);
                    $(".slideImages").animate({left: -image_reelPosition}, 200 );
                    $(".slideImages").fadeIn(800);
                }

                // Dynamic Caption with Alt-Tags

                $imgRel = $(".slidePaging a.active").attr("rel");
                var relCaption= "rel='" + $imgRel + "'";
                var dynCaption = $('.slideImages img['+relCaption+']').attr("alt");

                if (dynCaption != "") {
                    $(".slidePaging").css({'right' : '360px'});
                    $(".slideCaption").show();
                    $(".slideCaption p").html(dynCaption);
                }

                else {
                   $(".slideCaption").hide();
                   $(".slidePaging").css({'right' : '10px'});
                }
            };

            //Rotation  and Timing Event

            rotateSwitch = function(){

                play = setInterval(function(){                      //Set timer - this will repeat itself every 7 seconds
                    $active = $('.slidePaging a.active').next();    //Move to the next paging

                    if ( $active.length === 0) {                    //If paging reaches the end...
                        $active = $('.slidePaging a:first');        //go back to first
                    }

                rotate();                                           //Trigger the paging and slider function
                }, 10000);                                          //Timer speed in milliseconds (10 seconds)

             };

            rotateSwitch();                                         //Run function on launch

            //On Hover

            $(".slideImages a").hover(function() {
                    clearInterval(play);                            //Stop the rotation
                }, function() {
                    rotateSwitch();                                 //Resume rotation timer
            });

            //On Click

            $(".slidePaging a").click(function() {
                $active = $(this);                                  //Activate the clicked paging

            //Reset Timer

            clearInterval(play);                                    //Stop the rotation
            rotate();                                               //Trigger rotation immediately
            rotateSwitch();                                         // Resume rotation timer
            return false;                                           //Prevent browser jump to link anchor

            });



        }

    },

   "initSearch": function () {
        if ($("#searchInput").length) {
            $("#searchInput").fdiAjaxSearch({
                'lang': $("#curr_lang").val(),
                'searchButtonSelector': '#searchButton',
                'loadResultsInSelector': '#content',
                'showWaitSelector': '#showAjaxWaitStatus',
                'renderResult': Geiger.showSearchResults,
                'search': {
                    'sort': 0,
                    'ftsearch': 1,
                    'oua': 1,
                    'ns': 1
                }
            });
        }
    },

    "log": function (msg) {
        if (window.console && typeof (window.console.log) === "function") {
            console.log(msg);
        }
    },

'showSearchResults': function (result, showResultsInSelector) {
        var amountResults = result.data.length - 1;
        var final_count = 0; 
            i = 0;
            var resultItem = null;
            var htmlResult = "";
      /*  for (i = 0; i < amountResults; i++) {*/
		for(i=amountResults;i>0;i--) {
      	      resultItem = result.data[i];
            if (resultItem.bezeichnung !== "") {
                if(resultItem.art == "ergebnis") {
                    if (resultItem.typ == "medien") {
                    		if(resultItem.doctype != "JPG" && resultItem.doctype != "PNG" && resultItem.doctype != "GIF") {
                    			 htmlResult += "<li class='media'><a href='" + resultItem.url + "'> " + resultItem.bezeichnung + " (" + resultItem.score + "%)</a> <span>( " + resultItem.doctype + " | " + resultItem.filesize + " )</span></li>";
                        		final_count = final_count + 1;
                    		}
                    } else {
                    	if(resultItem.url.indexOf('/id/') > 0) {
                        	htmlResult += "<li class='page'><a href='" + resultItem.url + "?OpenDocument&highlight=" + result.key + "'>" + resultItem.bezeichnung + " (" + resultItem.score + "%)</a></li>";
                    	} else {
                    	    htmlResult += "<li class='page'><a href='" + resultItem.url + "'>" + resultItem.bezeichnung + " (" + resultItem.score + "%)</a></li>";	
                    	}
                        final_count = final_count + 1;
                    }
                 }
            }
        }
        htmlResult = '<h2>Suchergebnisse</h2><div id="txt1" class="txt first"><p>' + 'Ihre Suche nach <strong>"' + result.key + '"</strong> lieferte <strong>' + final_count + '</strong> Ergebnisse</p></div><ul id="searchResults">' + htmlResult;
        htmlResult += "</ul>";
        if ($(".sub_main").length) {
            $(".sub_main").hide()
        }
        $(showResultsInSelector).html(htmlResult);
    }
};



// Adjust the Caption-Width to Content-Images
function adjustImageCaptions() {
	var final_width = 540;
	$(".aligncenter").each(function() {
		final_width = $(this).css("width");
		$(this).children("IMG").each(function() {final_width = $(this).width();});
		if(isNan(final_width) | parseFloat(final_width) < 1) {
			$(this).css("width", "539px");
		} else {
			$(this).css("width", final_width + "px");
		}
		$(this).children("DIV").show();
	});
}


$(document).ready(function () {

    	Geiger.init();
		
		/******************************************************************************************************************************/
		/******************************************************************************************************************************/
		/******************************************************************************************************************************/
		
		if($('.mapNavigation').length) {	
	    if($('#divisions').length != 1) {
			var availableDivisions=new Array();
			var mapNavigation='<ul id="divisions">';
			for(var i=0; i<locations.length; i++){
				for(var k=0; k<locations[i].data.divisions.length; k++){
					if(jQuery.inArray(locations[i].data.divisions[k], availableDivisions) == -1){
						mapNavigation+='<li><a href="#map" target="_self" title="' + locations[i].data.divisions[k] + '">' + locations[i].data.divisions[k] + '</a></li>'; 
						availableDivisions.push(locations[i].data.divisions[k]);
					}
				}
			}
			mapNavigation+='</ul>';
		
			mapNavigation+='<ul id="allDivisions"><li><a href="#map" target="_self">Alle Standorte</a></li></ul>';
			$('.mapNavigation').append(mapNavigation);
		}
	
	    $('.mapNavigation #divisions a').click(function() {
	
	            $('#divisions a').removeClass();
	            $(this).addClass('active');
	            GM.clearMarkers();
				GM.changeMarkers($(this).attr('title'));
				GM.zoom();
	            return false;
		});
	
	    $('.mapNavigation #allDivisions a').click(function() {
	
	            $('#divisions a').removeClass();
	            $(this).addClass('active');
	
	            //map.setCenter(new google.maps.LatLng(49.143145, 9.219295));
	            //map.setZoom(6);
	
	            GM.deleteMarkers();
	            GM.defineMarkers();
				GM.zoom();
	            return false;
		});	
	}
});
