$(document).ready(function() {
    $("input.locationSuggester").inputField({ cssClass: "watermark" });

    $('.link').hover(

        function() {
            $(this).find('.smallImg').hide();
            $(this).find('.bigImg').show();
        },
        function() {
            $(this).find('.smallImg').show();
            $(this).find('.bigImg').hide();
        }
    );

    // LANDING PAGE DS PODIUM

    // tracking
    $(".landingpage .landing-content .sidebar ul li a.flag").click(function(event) {
        $(".landingpage .landing-content .sidebar .track.bmw").append('<img src="http://altfarm.mediaplex.com/ad/bk/15160-101188-3840-0?click_partnerschaften=1&mpuid=' + session_id_for_tracking + '" height="1" width="1" alt="Mediaplex_tag" />');
    });
    $(".landingpage .landing-content .sidebar ul li a.facebook").click(function(event) {
        $(".landingpage .landing-content .sidebar .track.fbfan").append('<img src="http://altfarm.mediaplex.com/ad/bk/15160-101188-3840-0?click_facebook=1&mpuid=' + session_id_for_tracking + '" height="1" width="1" alt="Mediaplex_tag" />');
    });
    $(".landingpage .landing-content .sidebar ul li a.search").click(function(event) {
        $(".landingpage .landing-content .sidebar .track.retailer").append('<img src="http://altfarm.mediaplex.com/ad/bk/15160-101188-3840-0?click_haendler=1&mpuid=' + session_id_for_tracking + '" height="1" width="1" alt="Mediaplex_tag" />');
    });

    // email default text
    var emailtext = "E-Mail Adresse";

    $(".landingpage .landing-content .content.contest div.button a.btn-send").click(function() {

        // hide error constantly or probably only temporary
        $(".container.error.response, .container.error.email").hide("fast");

        // get values
        var response1 = $("table.frage1 input:checked");
        var response2 = $("table.frage2 input:checked");
        var isValidEmail = isValidEmailAddress($("input.email").val());

        // if everything is ok		
        if (response1.is(':checked') && response2.is(':checked')) {

            if (isValidEmail) {
                $(".landingpage .landing-content .content.contest").hide();
                $(".landingpage .landing-content .content.thankyou").show();
            }
            else {
                $(".container.error.email").show("slow");
                return false;
            }
        }
        // else show error pane 
        else {
            $(".container.error.response").show("slow");
            return false;
        }

    });

    // watermark
    $(".landingpage .landing-content .content.contest input.email").watermark(emailtext);

    // email validation
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    }

    // LANDING PAGE DS PODIUM
});

$(document).ready(function() {
    // check for map container existance
    if ($('#geo-map').length == 0) {
        return;
    }

    var startLat;
    var startLon;
    var zoomLevel;

    // map layout handler - initializes the controls on the map
    function layoutMapControls(instance) {
        instance.addControl(new GLargeMapControl());

        var markerIcons = [];
        markerIcons['default'] = new GIcon(G_DEFAULT_ICON);

        var lyrId = 'certina';
        var layers_morebutton = [
            { checked: true, name: lyrId, iconUrl: null, obj: new o8.Gis.MapLayer(lyrId, markerIcons['default']) }
        ];

        // add map layer control
        instance.addControl(new o8.Gis.LayerControl(layers_morebutton), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(-100, -100)));

        // for debugging
        //instance.addControl(new o8.Gis.CoordboxControl());
        //instance.addControl(new o8.Gis.CrosshairControl());
    }

    // marker info window provider
    function markerInfoHtmlContentProvider(markerId, markerType, properties) {
        var tmpString = '<div id="certina-gmap-info" style="width:200px;">';
        tmpString += '<h3>' + properties.Title + '</h3>';

        tmpString += properties.Address1 + '<br />';
        tmpString += properties.Zip + ' ' + properties.City + '<br />';

        tmpString += '</div>';
        return tmpString;
    }

    // instantiate and initialize the google map
    var gisMap = new o8.Gis.Map(layoutMapControls, markerInfoHtmlContentProvider);

    if (isNaN(startLat) || isNaN(startLon) || isNaN(zoomLevel))
        gisMap.initialize('geo-map', { 'Lat': 20.0, 'Lon': 7.53043 }, 2);
    else
        gisMap.initialize('geo-map', { 'Lat': startLat, 'Lon': startLon }, zoomLevel);
    //gisMap.setBounds({ 'Lat': 45.8, 'Lon': 5.95 }, { 'Lat': 47.8, 'Lon': 10.5 });
    gisMap.setAllowedZoomLevels(2, 18);

    function moveEndhandler() {
        var maxResults = 50;
        var mapBounds = gisMap.getBounds();
        var data = new Object;
        var lyrId = 'certina';
        data.layerId = lyrId;
        data.southWest = mapBounds.SouthWest;
        data.northEast = mapBounds.NorthEast;
        data.maxResults = maxResults + 1;
        var jsonData = $.toJSON(data);

        o8.Gis.fetchDataFromService('GetMarkersEx', jsonData, function(response) {
            if ((response == null) || response.GeoMarkers == null) {
                $('#poi-address-list').hide();
                return;
            }

            if (response.GeoMarkers.length > maxResults) {
                $('#poi-address-list').hide();
                return;
            }

            $('#poi-address-list').fillTemplate(response);
            $('#lblNumberOfStores').html(response.GeoMarkers.length);
            $('#poi-address-list').show();
        });
    }

    // add modeend handler
    gisMap.addMoveEndListener(moveEndhandler);
    // force loading of poi list
    moveEndhandler();
    // ensure that the allocated memory will be freed
    $(window).unload(function() { GUnload(); });

    var lockSearch = false;
    $('input.locationSuggester').change(function(e) {
        setTimeout(searchDealers, 300);
    });

    $('input.locationSuggester').keypress(function(e) {
        if (e.which == 13) {
            setTimeout(searchDealers, 300);
        }
    });

    function searchDealers() {
        var input = $('.locationSuggester').val();
        $.ajax({
            async: false,
            type: "POST",
            url: '/GeoService.asmx/GetPosition',
            data: "{ address: '" + input + "', host: '" + window.location.hostname + "' }",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                pos = data;
                gisMap.setCenter(pos, 13);
            }
        });
    }

    $('.locationSuggester').autocomplete({ source: function(term) {
        var querys = "{query:'" + term + "'}";
        var response;
        $.ajax({
            async: false,
            type: "POST",
            url: '/GeoService.asmx/GetSuggestedLocations',
            data: querys,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                response = data;
            }
        });
        return response;
    },
        parse: function(data) {
            if (data == null)
                return;
            var parsed = [];
            var rows = data;
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: row[0]
                    };
                }
            }
            return parsed;
        }
    });
});

$(document).ready(function() {
    // create mediaplex mpuid
    var date = new Date()
    var ticks = date.getTime()

    var src = $('iframe').attr('rel');
    if (src == null || src == 'undefined')
        return;

    var idx = src.indexOf("&mpuid=");
    var mpuid = src.substring(idx);
    src = src.replace(mpuid, "&mpuid=" + ticks);

    $('iframe').removeAttr('rel');
    $('iframe').attr('src', src);
});


// displaying language switcher on mouseover
$(document).ready(function() {
    $("div#lang").hover(
		function() {
		    $(this).find(".drop-lang").show();
		},
		function() {
		    $(this).find(".drop-lang").hide();
		}
	)
});

// top sub navigation
/*
$(document).ready(function() {
var navList = $("#nav");
var subNavList = $(".add-nav");

$("#nav > li").mouseenter(function() {
subNavList.hide();
$(this).find(".add-nav").show();
});

navList.mouseleave(function() {
subNavList.hide();
});
});
*/

// slideshows
$(document).ready(function() {
	// home

	$(".slideshow-home").cycle({
		next: $("a.link-next"),
		prev: $("a.link-prev"),
		fx: "fade",
		timeout: 4000
	});

	var homeImageWidth = 1879;
	$(window).resize(function() {
		centerSlideshow();
	});

	$(".slider.home a.link-next, .slider.home a.link-prev").click(function(e) {
		e.preventDefault();
		centerSlideshow();
	});

	function centerSlideshow() {
		if ($(window).width() > homeImageWidth) {
			var containerWidth = $('.slideshow-home').outerWidth();
			$(".slideshow-image-container").each(function(e) {
				$(this).css('left', (containerWidth - $(this).outerWidth()) / 2);
			});
		}
	}

	centerSlideshow();

	// collection overview
	$(".photo:not(.no-slideshow)").each(function() {
		var $pagerDiv = $(this).parent("li").find(".num");
		var $nextButton = $pagerDiv.find("> .next");
		var $prevButton = $pagerDiv.find("> .prev");
		var $currentCount = $pagerDiv.find(".currentCount");
		var $totalCount = $pagerDiv.find(".totalCount");
		var $title = $(this).parent("li").find(".title > .family-link");
		$(this).cycle({
			next: $nextButton,
			prev: $prevButton,
			fx: "fade",
			timeout: 0,
			speed: 500,
			after: function(curr, next, opts) {
				$currentCount.html((opts.currSlide + 1));
				$totalCount.html(opts.slideCount);
				//alert($title.html());
				//$title.attr("href", $title.attr("href").replace(/(\?m=)\d/, "?m=" + (opts.currSlide + 1)));
				$title.attr("href", $title.attr("href").replace(/(\?m=)\d/, "") + "?m=" + (opts.currSlide + 1));
			}
		});
	});

	// displaying the corresponding watch model if coming to the collection detail page with a "?m=X" url parameter
	var showSpecificModel = false;
	var $watchModels = $(".frame .slideshow > li.detail-item");
	var shitBrowser = ($.browser.msie && (parseInt($.browser.version) < 9)); // the famous shitBrowser variable, hehe
	
	if ($watchModels.size() > 1) {
		var modelIndex = parseInt(location.search.substring((location.search.indexOf("m=") + 2)));
		if (!isNaN(modelIndex) && modelIndex <= $watchModels.size()) {
			if (shitBrowser) {
				$watchModels.hide();
				$watchModels.filter(":nth-child(" + modelIndex + ")").show();
			}
			else {
				$watchModels.hide().css("opacity", 0);
				$watchModels.filter(":nth-child(" + modelIndex + ")").show().css("opacity", 1);
			}
			showSpecificModel = true;
		}
	}

	if (!showSpecificModel) {
		// hiding all li's (except the first one) so we can do a fadeIn on them later
		if (shitBrowser) {
			$(".slideshow > li").not(":first").hide();
		}
		else {
			$(".slideshow > li").not(":first").hide().css("opacity", 0);
		}
	}
	$(".slideshow > li").each(function(index) {
		$(this).find(".currentCount").html((index + 1));
	})

	// collection detail: NEXT click
	var $firstLi = $("ul.slideshow").find("> li:first");
	$(".slideshow > li .next-image").click(function(e) {
		e.preventDefault();
		// hiding current item (setting opacity:0 and display:none)
		var $currentLi = $(this).parents("li");
		var $nextLi = $(this).parents("li").next("li");
		if (shitBrowser) {
			$currentLi.hide();
			if ($nextLi.size()) {
				$nextLi.show();
			}
			else {
				$firstLi.show();
			}
		}
		else {
			$currentLi.fadeTo(500, 0, function() { $(this).hide(); });
			if ($nextLi.size()) {
				$nextLi.show().fadeTo(500, 1);
			}
			else {
				$firstLi.show().fadeTo(500, 1);
			}
		}
	});

	// collection detail: PREVIOUS click
	var $lastLi = $("ul.slideshow").find("> li:last");
	$(".slideshow > li .prev-image").click(function(e) {
		e.preventDefault();
		// hiding current item (setting opacity:0 and display:none)
		var $currentLi = $(this).parents("li");
		var $prevLi = $(this).parents("li").prev("li");
		if (shitBrowser) {
			$currentLi.hide();
			if ($prevLi.size()) {
				$prevLi.show();
			}
			else {
				$lastLi.show();
			}
		}
		else {
			$currentLi.fadeTo(500, 0, function() { $(this).hide(); });
			if ($prevLi.size()) {
				$prevLi.show().fadeTo(500, 1);
			}
			else {
				$lastLi.show().fadeTo(500, 1);
			}
		}
	})

});


// setting content height dynamically on home
$(document).ready(function() {
	setContentHeight();
	function setContentHeight() {
		var newContentHeight = $(window).height() - $("#header").height() - $("#footer").height() - 100;
		$(".slider.home").height(newContentHeight);
	}
	// recalculating height on window resize
	$(window).resize(function() {
		setContentHeight();
	});
});


// open link in new window
$(document).ready(function() {
	$("a[rel='external']").each(function() {
		$(this).attr("target", "_blank");
	});
});


// activating indication labels on collection and collection detail (when hovering over arrow images)
$(document).ready(function() {
	$(".link-prev").mouseenter(function() {
		$(this).prev(".indication").addClass("active");
	}).mouseleave(function() {
		$(this).prev(".indication").removeClass("active");
	});
	$(".link-next").mouseenter(function() {
		$(this).prev(".indication").addClass("active");
	}).mouseleave(function() {
		$(this).prev(".indication").removeClass("active");
	});
});


// hiding vertical sub-sub-nav when not active (ok, this is a hack $=)
$(document).ready(function() {
	$(".sub-nav > li:not(.active) > ul").hide();
});




