isLoading = false;

/**
 * init embedCode
 */
(function($){
    $.fn.getEmbededCode = function(options){
        var opts = $.extend({}, $.fn.getEmbededCode.defaults, options);
        var ectimer = null;
        $('#' + opts.codeLayer).html($('#' + opts.wrapper).html());
        $('#' + opts.wrapper).html('');
        
        var clip = new ZeroClipboard.Client();
        clip.glue(opts.linkButton, opts.codeLayer);
        
        var txt = $('#' + opts.copyText).val();
        clip.setText(txt);
        clip.setHandCursor(true);
        clip.setCSSEffects(true);
        // Add a complete event to let the user know the text was copied
        clip.addEventListener('complete', function(client, text){
            $('#' + opts.showLayer).fadeIn('fast');
            ectimer = setTimeout(function(){
                $('#' + opts.showLayer).fadeOut('fast');
            }, 3000);
        });
        
        $('#' + opts.showLayer).hover(function(){
            clearTimeout(ectimer);
        }, function(){
            ectimer = setTimeout(function(){
                $('#' + opts.showLayer).fadeOut('fast');
            }, 3000);
        });
        
        $('#' + opts.showLayer + ' a.close').click(function(){
            clearTimeout(ectimer);
            $('#' + opts.showLayer).fadeOut('slow');
            return false;
        });
        
    };
    $.fn.getEmbededCode.defaults = {
        wrapper: 'embedCodeWrapper',
        copyText: 'embedCodeInput',
        codeLayer: 'copyEmbedCode',
        showLayer: 'embedCodeSuccess',
        linkButton: 'embedCodeButton'
    };
})(jQuery);


/**
 * show subMenu in the search/topic navi
 */
(function($){
    var naviTimer = null;
    var childInputIsBlur = true;
    $.fn.showSubMenu = function(){
        $('.quicknavi li a').click(function(){
            var checkElement = $(this).next();
            
            if ((checkElement.is('.submenu')) && (checkElement.is(':visible'))) {
                checkElement.find('input').blur();
                clearTimeout(naviTimer);
                checkElement.parent().removeClass("hi");
                checkElement.fadeOut('fast');
                $('.ac_results').hide();
                $('.noresult').remove();
                checkElement.find('input').val('');
                return false;
            }
            if ((checkElement.is('.submenu')) && (!checkElement.is(':visible'))) {
                // clearTimeout(naviTimer);
                
                $(this).parent().find('.submenu').hover(function(){
                    clearTimeout(naviTimer);
                }, function(){
                    clearTimeout(naviTimer);
                    if (childInputIsBlur) {
                        naviTimer = setTimeout(function(){
                            checkElement.parent().removeClass("hi");
                            checkElement.fadeOut('fast');
                            $('.noresult').remove();
                            checkElement.find('input').val('');
                            return false;
                        }, 2000);
                    }
                });
                
                clearTimeout(naviTimer);
                $('.quicknavi .submenu:visible').fadeOut('fast');
                $('.quicknavi .submenu:visible').parent().removeClass("hi");
                
                checkElement.fadeIn('fast');
                checkElement.parent().addClass("hi");
                
                checkElement.find('input').focus(function(){
                    childInputIsBlur = false;
                    clearTimeout(naviTimer);
                });
                
                checkElement.find('input').blur(function(){
                    childInputIsBlur = true;
                    naviTimer = setTimeout(function(){
                        checkElement.parent().removeClass("hi");
                        checkElement.fadeOut('fast');
                        $('.noresult').remove();
                        checkElement.find('input').val('');
                        return false;
                    }, 2000);
                });
                
                return false;
            } // is.submenu
        });
    }
}(jQuery));

/**
 * close spamlayer
 */
(function($){
    $.fn.closeSpamLayer = function(){
        $(".spamlayer a").click(function(){
            $(".spamlayer").hide();
            return false;
        });
    }
}(jQuery));

/**
 * delete the dashed border by clicken on a link (type3 fuction)
 */
function blurLink(i){
    i.blur();
}

/**
 * change the default value by clicking in an input field with the class
 * "displace"
 */
(function($){
    $.fn.changeDefaultValue = function(){
        $(".displace").focus(function(){
            // Check for the change
            if (this.value == $(this).attr("title")) {
                this.value = ''
            }
        });
        $(".displace").blur(function(){
            // Check for the change
            if (this.value == '') {
                this.value = $(this).attr("title");
            }
        });
    }
}(jQuery));


/**
 * fade-in the page after loading
 */
(function($){
    $.fn.pageFadeIn = function(){
    	if ($.browser.msie){}
    		else {
    			$('#content').css({
    				opacity: 0
    			})
    			$('#content').animate({
    				opacity: 1
    			}, 800);
    		}
    }
}(jQuery));

/**
 * show own Social-Media Layer
 */
(function($){
    $.fn.showSocialMedia = function(){
        $('.sharelink').mouseover(function(){
            $('.lightbox').fadeIn('fast');
            return false;
        });
        $('.lightbox_close').click(function(){
            $('.lightbox').fadeOut('fast');
            return false;
        });
    }
}(jQuery));

/**
 * show Text in the BlogNavi on mouse-over
 */
(function($){
    $.fn.showBlogNaviText = function(){
        $(".blognavi a").hover(function(){
            $('.navitext').html($(this).html());
        }, function(){
            $('.navitext').html('');
        });
    }
}(jQuery));


/**
 * loading next li's from next site on overview page
 */
/*(function($){
    $.fn.loadNextPage = function(options){

        $('#paging').hide(); // hides paging first
        $('#nextPostsLoader').css({
            'visibility': 'hidden'
        }); // hide loading
        var opts = $.extend({}, $.fn.loadNextPage.defaults, options);

        
        $(window).scroll(function(){
			if (!isLoading)
            if ($(window).scrollTop() >= $(document).height() - $(window).height() - 50) {
            
                var newURL = (opts.nextPage == '' ? (opts.pageUrl).split('/') : (opts.nextPage).split('/'));
                var nextURL = '';
                
                // Search for /page/ and set the next folder or file with a
				// number one up
                for (i = 0; i < newURL.length; i++) {
                    if (newURL[i - 1] == 'page') {
                        if ((newURL[i]).indexOf(opts.pageDivider) > -1) {
                            partPage = (newURL[i]).split(opts.pageDivider);
                            pageNo = partPage[0];
                            pageNo++;
                            nextURL += pageNo + opts.pageDivider;
                        }
                        else {
                            pageNo = newURL[i];
                            pageNo++;
                            nextURL += pageNo;
                        }
                        
                    }
                    else {
                        nextURL += newURL[i];
                    }
                    if (i != (newURL.length - 1)) {
                        nextURL += '/';
                    }
                }
                
                opts.nextPage = nextURL;
                
                if (opts.pageCounter > 0) {
                    $('#nextPostsLoader').css({
                        'visibility': 'visible'
                    }); // show loading
                    
	                    $.ajax({
	                        url: nextURL,
	                        type: 'GET',
	                        dataType: 'ajax',
	                        timeout: 5000,
	                        error: function(){
	                            // alert('Error loading Page');
	                            $('#nextPostsLoader').css({
	                                'visibility': 'hidden'
	                            }); // hide loading
	                        },
	                        beforeSend: function(data){
	                        	isLoading = true;
	                        },
	                        success: function(data){
	                        
	                            var newData = ($('<div>' + data + '</div>').find('#indexpage'));
	                            
	                            $('#nextPostsLoader').css({
	                                'visibility': 'hidden'
	                            }); // hide loading
	                            $(newData.html()).addClass('li-opacity').appendTo("ul#indexpage");
	                            
	                            $('#content').scaleIndexImages();
	                         
	                            isLoading = false;
	                        }
	                    });
	                    opts.pageCounter--;
                    
                }
                return false;
            }
        });
    };
    $.fn.loadNextPage.defaults = {
        pageUrl: 'http://blogazine.dedon.de/blogazine/page/0/',
        pageDivider: '.html'
    };
})(jQuery);*/

(function($) {
    $.fn.loadNextPage = function(options) {

        $('#paging').hide(); // hides paging first
        $('#nextPostsLoader').css({
            'visibility': 'hidden'
        }); // hide loading
        var opts = $.extend({}, $.fn.loadNextPage.defaults, options);

        $('#loadAllArticles').bind('click', function() {
            if(!isLoading) {
                var newURL = (opts.nextPage == '' ? (opts.pageUrl).split('/') : (opts.nextPage).split('/'));
                var nextURL = '';

                // Search for /page/ and set the next folder or file with a
                // number one up
                for (i = 0; i < newURL.length; i++) {
                    if (newURL[i - 1] == 'page') {
                        if ((newURL[i]).indexOf(opts.pageDivider) > -1) {
                            partPage = (newURL[i]).split(opts.pageDivider);
                            pageNo = partPage[0];
                            pageNo++;
                            nextURL += pageNo + opts.pageDivider;
                        }
                        else {
                            pageNo = newURL[i];
                            pageNo++;
                            nextURL += pageNo;
                        }

                    }
                    else {
                        nextURL += newURL[i];
                    }
                    if (i != (newURL.length - 1)) {
                        nextURL += '/';
                    }
                }

                opts.nextPage = nextURL;
                
            
                if(opts.pageCounter == 1){
                  $('#loadAllArticles').hide();
                }

                if (opts.pageCounter > 0) {
                    $('#nextPostsLoader').css({
                        'visibility': 'visible'
                    }); // show loading

                    $.ajax({
                        url: nextURL,
                        type: 'GET',
                        //dataType: 'ajax',
                        timeout: 5000,
                        error: function(jqXHR, textStatus, errorThrown) {
                            //alert('Error loading Page');
                            $('#nextPostsLoader').css({
                                'visibility': 'hidden'
                            }); // hide loading
                        },
                        beforeSend: function(data) {
                            isLoading = true;
                        },
                        success: function(data) {

                            var newData = ($('<div>' + data + '</div>').find('#indexpage'));

                            $('#nextPostsLoader').css({
                                'visibility': 'hidden'
                            }); // hide loading

                            $(newData.html()).addClass('li-opacity').appendTo("ul#indexpage");

                            //$('#content').scaleIndexImages();
                            $("#indexpage li").setPriority();

                            isLoading = false;
                        }
                    });
                    opts.pageCounter--;

                }
            }
            return false;
        });
    };
    $.fn.loadNextPage.defaults = {
        pageUrl: 'http://blogazine.dedon.de/blogazine/page/0/',
        pageDivider: '.html'
    };
})(jQuery);

/**
 * set h2, p, img within the rte-content into right direction
 */
(function($){
    $.fn.count = function(options){
        var opts = $.extend({}, $.fn.count.defaults, options);
        var c = 0;
        return this.each(function(i){
            var $this = $(this);
            if ((this.nodeName.toLowerCase() === 'p') && (!$this.hasClass(opts.topImage))) {
                if (c % 2 == 0 && opts.even.length) {
                    $this.addClass(opts.odd);
                }
                else {
                    $this.addClass(opts.even);
                }
                c++;
            }
            else {
                if ((this.nodeName.toLowerCase() !== 'img')) {
                    if (c % 2 == 0 && opts.even.length) {
                        $this.addClass(opts.odd);
                    }
                    else {
                        $this.addClass(opts.even);
                    }
                }
            }
        });
    };
    $.fn.count.defaults = {
        odd: 'odd',
        even: 'even',
        topImage: 'topImage'
    };
})(jQuery);

/**
 * set the priority and direction of the images on the start page
 */
(function($){
    $.fn.setPriority = function(){
        // $("#indexpage").attr('style', 'padding-top: 180px;');
        var z = 8000;
        return this.each(function(i){
            var $this = $(this);
            var marginTop = 0;
            if ($this.find("img").height() < 120 && i > 0) 
                marginTop = 40;
	    var marginBottom = $this.height() / 16 * 7;
	    // if next element is a shortnews teaser
	    if ($this.find("img").height() > 120 && $this.next().find("img").height() < 120)
		marginBottom = 60;

            if (i % 3 == 0) {
                //$this.attr('style', 'margin-bottom: -' + marginBottom + 'px; margin-top: ' + marginTop + 'px; left: 0; width:' + $(this).find('img').width() + 'px; z-index:' + z);
                $this.attr('style', 'margin-bottom: 10px; left: 0; width:' + $(this).find('img').width() + 'px; z-index:' + z);
            }
            else 
                if (i % 3 == 1) {
                    rightPos = 960 - $(this).find('img').width();
                    //$this.attr('style', 'margin-bottom: -' + marginBottom + 'px; margin-top: ' + marginTop + 'px; left: ' + rightPos + 'px; width:' + $(this).find('img').width() + 'px; z-index:' + z);
                    $this.attr('style', 'margin-bottom: 10px; left: ' + rightPos + 'px; width:' + $(this).find('img').width() + 'px; z-index:' + z);
                }
                else {
                    middlePos = (960 - $(this).find('img').width()) / 2;
                    //$this.attr('style', 'margin-bottom: -' + marginBottom + 'px; margin-top: ' + marginTop + 'px; left: ' + middlePos + 'px; width:' + $(this).find('img').width() + 'px; z-index:' + z);
                    $this.attr('style', 'margin-bottom: 10px; left: ' + middlePos + 'px; width:' + $(this).find('img').width() + 'px; z-index:' + z);
                }
            if ($this.hasClass('li-opacity')) {
                $this.animate({
                    opacity: 1
                }, 400);
                $this.removeClass('li-opacity');
            }
            z--;
            //$this.css("margin-left", 14);
        });
    };
})(jQuery);

/*
(function($){
    $.fn.scaleIndexImages = function(){
        $("#indexpage li h2").hover(function(e){
            if (e.relatedTarget != null) {
                this.image = $(this).children('a').children('img:first');
                if (!this.image.hasClass("hover")) {
                    this.newMargin = -(this.image.width() / 100 * 2);
                    this.oldHeight = this.image.height();
                    this.newHeight = this.oldHeight / 100 * 104;
                    this.oldWidth = this.image.width();
                    this.newWidth = this.oldWidth / 100 * 104;
                    this.oldZindex = $(this).parent().css('z-index');
                    this.image.addClass("hover");
                }
                this.image.stop().animate({
                    marginLeft: this.newMargin,
                    width: this.newWidth,
                    height: this.newHeight
                }, 150);
                $(this).parent().css({
                    'z-index': '8000'
                });
            }
        }, function(e){
            if (e.relatedTarget != null) {
                $(this).parent().css({
                    'z-index': this.oldZindex
                });
                if (this.image != undefined) 
                    this.image.animate({
                        marginLeft: '0',
                        width: this.oldWidth,
                        height: this.oldHeight
                    }, 150);
            }
        });
        $("#indexpage li").setPriority();
    };
}(jQuery));
*/

function initMetaLayerScrollPane(oid){
    $(oid).jScrollPane({
        showArrows: true,
        arrowSize: 20,
        scrollbarWidth: 14,
        dragMinHeight: 14,
        scrollbarMargin: 20
    });
}

function initSearchLayerScrollPane(oid){
    $(oid).jScrollPane({
        showArrows: true,
        arrowSize: 20,
        scrollbarWidth: 14,
        dragMinHeight: 14,
        height: 150,
        scrollbarMargin: 20
    });
}

function prebuildGallery(){
    if ($(".gallery").length > 0) {
        var galleryLayer = $("<div id='gallery-layer' style='width:713px; height:521px; display:none;'></div>");
        var gallery = $("<div id='nyrogallery' style='display:none;' class='nyro-ad-gallery'></div>");
        var adImageWrapper = $("<div class='ad-image-wrapper'></div>");
        var adControls = $("<div class='ad-controls'></div>");
        var adNavWrapper = $("<div class='ad-nav-wrapper'></div>");
        var adNav = $("<div class='ad-nav'></div>");
        var adThumbs = $("<div class='ad-thumbs'></div>");
        var adThumbList = $("<ul class='ad-thumb-list'></ul>");
        
        $("a.gallery").each(function(e){
            $(this).attr("rel", $(this).attr("href"));
            $(this).attr("href", "#gallery-layer");
        });
        
        $(adThumbs).append($(adThumbList));
        $(adNav).append($(adThumbs));
        $(adNavWrapper).append($(adNav));
        $(gallery).append($(adImageWrapper));
        $(gallery).append($(adControls));
        $(gallery).append($(adNavWrapper));
        $(galleryLayer).append($(gallery));
        $("body").append($(galleryLayer));
    }
}

function arrangeImages(){
    var galleries = new Array();
    var i = 0;
    $("p.gallery a.gallery").each(function(){
        var cl = $(this).attr("class").split(" ")[1];
        if (galleries[i - 1] != cl) {
            galleries[i] = cl;
            i++
        }
    });
    
    for (var i = 0; i < galleries.length; i++) {
        $("p.gallery a." + galleries[i]).not(".galleryCaption").each(function(index){
            if (index < 2) {
                $(this).css("margin-right", 20);
            }
            if (index > 2) 
                $(this).hide();
            if (index != $("p.gallery a." + galleries[i]).not(".galleryCaption").length - 1 || index == 2) 
                $(this).css("float", "left");
			if ($("p.gallery a." + galleries[i]).not(".galleryCaption").length < 3)
				$("p.gallery a." + galleries[i] + ".galleryCaption").css("display", "block");
            $(this).children().css("margin-bottom", 18);
        });
        $("p.gallery a." + galleries[i] + ".galleryCaption").each(function(){
            var imageCount = $("a." + $(this).attr("class").split(" ")[1]).not(".galleryCaption").length;
            if (imageCount > 1) 
                $(this).children("span:first").next().text(" (" + imageCount + " Pictures)");
            else 
                $(this).children("span:first").next().text(" (" + imageCount + " Picture)");
        });
    }
}

function updateFilterBox(){
    var countResults = $("#ajaxSearch ul li").length;
    if (countResults < 11 && countResults > 0) {
        $("#ac_results").height(countResults * 19);
    }
    else {
        $("#ac_results").height(194);
    }
}


/* Google Analytics Tracking */

function trackingMovieStarted(){
	pageTracker._trackEvent('Video', 'Play', document.title, document.URL);
}

function trackingPodcastStarted(){
	pageTracker._trackEvent('Podcast', 'Play', document.title, document.URL);
}


/* Social Media - Facebook / Twitter */

function connectFacebook() { 
	$("#connectLogin").html('<div class="connectLoggedIn clear"><fb:profile-pic uid="loggedinuser" size="square" facebook-logo="true"></fb:profile-pic><ul><li><span><fb:name uid="loggedinuser" useyou="false" linked="false"></fb:name></span></li><li><a href="#" onclick="logoutFacebook(); return false;" class="logout">Log out</a></li></ul></div>');
	$("#connectLogin").removeClass("connectLogin");
	
	$('#li_commentauthor').html('<input type="hidden" name="tx_t3blog_pi1[blogList][facebookUser]" value="' + FB.Facebook.apiClient.get_session().uid + '" />');
	$('#li_commentauthoremail').html('');
	FB.XFBML.Host.parseDomTree(); 
}

function logoutFacebook() 
{
	FB.Connect.logout();
	$("#connectLogin").html('<p>Comment as guest or login below.</p><ul class="clear"><li><a href="#" onclick="FB.Connect.requireSession(); return false;" class="facebookConnect"><span>Connect with Facebook</span></a></li><li><a href="#" onclick="connectTwitter(); return false;" class="twitterConnect">Sign in with Twitter</a></li></ul>');
	$("#connectLogin").addClass("connectLogin");
	
	$('#li_commentauthor').html('<div class="clear"><input type="text" id="commentauthor" title="Name" class="text displace" name="tx_t3blog_pi1[blogList][commentauthor]" value="Name" /></div>');
	$('#li_commentauthoremail').html('<div class="clear"><input type="text" title="Email (will not be shown)" class="text displace" name="tx_t3blog_pi1[blogList][commentauthoremail]" value = "Email (will not be shown)" /></div>');			
	FB.XFBML.Host.parseDomTree(); 
}
				
function connectTwitter()
{
	var url = '/index.php?eID=twitterconnect&url='+window.location;
	window.location = url;
}
				
function logoutTwitter()
{
	$('#socialLogin').load('/index.php?eID=twitterlogout');		
	$('#li_commentauthor').html('<div class="clear"><input type="text" id="commentauthor" title="Name" class="text displace" name="tx_t3blog_pi1[blogList][commentauthor]" value="Name" /></div>');
	$('#li_commentauthoremail').html('<div class="clear"><input type="text" title="Email (will not be shown)" class="text displace" name="tx_t3blog_pi1[blogList][commentauthoremail]" value = "Email (will not be shown)" /></div>');			
}

/* flowplayer scripts */
/*
 * function istantiatePlayer(){ $f("videoPlayer", "/_swf/flowplayer-3.1.5.swf", {
 * key: '#$0865606576061d0ecbc', wmode: 'transparent', clip: { autoPlay: false,
 * autoBuffering: false, //HACK TO LOOP CLIP onBeforeFinish: function(){ return
 * false; } }, playlist: [{ url: '/_mp3/_dummy/rain.mp3', image: false, }],
 * plugins: { controls: { url: '/_swf/flowplayer.controls-3.1.5.swf',
 * 
 * scrubberBorderRadius: 0, borderRadius: '0', all: false, play: true, mute:
 * true, scrubber: false, fullscreen: false, time: false, next: false,
 * 
 * height: 25, tooltips: { buttons: false, scrubber: null } } }, onLoad:
 * function(){ hidePlayer(); },
 * 
 * }); }
 */

function hidePlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").hide();
	}
}

function mutePlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").mute();
		$('#mutePlayer').hide();
		$('#unmutePlayer').show();
	}
}

function unmutePlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").unmute();
		$('#mutePlayer').show();
		$('#unmutePlayer').hide();
	}
}

function startPlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").play();
	}
}

function stopPlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").stop();
	}
}

function resumePlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").resume();
	}
}

function pausePlayer(){
	if ($f("videoPlayer")) {
		$f("videoPlayer").pause();
	}
}


/**
 * newsletter subscription form
 */
(function($){
    $.fn.newsletterForm = function(){

		// --- behavior
		$('.checkboxfake').css('display', 'block');
		$('.input-check').css('display', 'none');
		$('.checkboxfake').click(function(){
            if ($(this).hasClass("off")) {
				// radiobox behavior for checkboxgroup
				if ($(this).prev().attr('name') == 'newslettertype'){					
					$('input[name=newslettertype]').attr('checked', false);
					$('input[name=newslettertype]').next().removeClass("on").addClass("off");
				}
				$(this).addClass("on").removeClass("off").prev().attr('checked', true);
			}
			else {
				$(this).addClass("off").removeClass("on").prev().attr('checked', false);
			}
        });
		$('.nlsubscr .input-text').toggleValue();
		
		// --- validation
		var action = $('.nlsubscr').attr('action');
		// custom method making the default values invalid
		jQuery.validator.addMethod("defaultInvalid", function(value, element) {
			return value != element.defaultValue;
		}, "");
		jQuery.validator.messages.required = "";
		
		$(".nlsubscr").validate({		
			invalidHandler: function(e, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					$("p.catalogintro").html($("span.errortext").text());
					$("p.catalogintro").addClass('errormsg');	
				}
			},
            errorPlacement: function(error, element) {},
            submitHandler: function(form){
				var dataString = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: action,
                    data: dataString,
                    success: function(data){
						var result = $(data).find("#metaContent").html();
						$("#nyroModalContent").children().fadeOut("fast", function(){
                            $("#nyroModalContent").children().remove();
                            $("#nyroModalContent").append(result).children().hide().fadeIn("fast");                      
                        });
                    }
                });
            }
        });	
    }
}(jQuery));


/**
 * catalog order form
 */
(function($){
    $.fn.catalogForm = function(){
		// --- behavior
		$('.checkboxfake').css('display', 'block');
		$('.input-check').css('display', 'none');
		$('.checkboxfake').click(function(){
            if ($(this).hasClass("off")) {
				// radiobox behavior for checkboxgroup
				if ($(this).prev().attr('name') == 'catalogtype'){					
					$('input[name=catalogtype]').attr('checked', false);
					$('input[name=catalogtype]').next().removeClass("on").addClass("off");
				}
				$(this).addClass("on").removeClass("off").prev().attr('checked', true);
			}
			else {
				$(this).addClass("off").removeClass("on").prev().attr('checked', false);
			}
        });
		$('#ordercatalog .input-text').toggleValue();
		
		// --- validation
		var action = $('#ordercatalog').attr('action');
		var defaultPobox = $('#pobox').attr('value');
		// custom method making the default values invalid
		jQuery.validator.addMethod("defaultInvalid", function(value, element) {
			return value != element.defaultValue;
		}, "");
		// custom method making street and number invalid if PO Box is not
		// filled
		jQuery.validator.addMethod("adressInvalid", function(value, element) {
			if ($("#pobox").val() == defaultPobox || $("#pobox").val() == '')
				return value != element.defaultValue;
			return true;
		}, "");
		jQuery.validator.messages.required = "";
		
		$("#ordercatalog").validate({		
			invalidHandler: function(e, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					$("p.catalogintro").html($("span.errortext").text());
					$("p.catalogintro").addClass('errormsg');	
				}
			},
            errorPlacement: function(error, element) {},
            submitHandler: function(form){
				var dataString = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: action,
                    data: dataString,
                    success: function(data){
						var result = $(data).find("#metaContent").html();
						$("#nyroModalContent").children().fadeOut("fast", function(){
                            $("#nyroModalContent").children().remove();
                            $("#nyroModalContent").append(result).children().hide().fadeIn("fast");                      
                        });
                    }
                });
            }
        });	
    }
}(jQuery));

/**
 * toggle defaulttext in input fields
 */
(function($){
	$.fn.toggleValue = function(){
			return this.each(function() {
				$(this).focus(function() {
					var defaultText = $(this).attr('title');
					if ($(this).val() == defaultText) {
						$(this).val('');
					}
					$(this).blur(function () {
						if ($.trim($(this).val()) == '') {
							$(this).val(defaultText);
						}
					});
				});
			});
		}
}(jQuery));


/**
 * append teaser on blog indexpage
 */
(function($){
    $.fn.getBlogteaser = function(){
		
		if ($('#indexpage').length > 0)
		{
			$.ajax({
		        url: '/index.php?id=1180',
		        type: 'GET',
		        dataType: 'html',
		        timeout: 3000,
		        error: function(){
		        },
		        success: function(data){
		            var newData = ($(data).find('#blogteasercontainer'));
					newData = $('<div id="blogteasercontainer">' + $(newData).html() + '</div>');
		            $(newData).prependTo("#content").fadeIn();
		            $('#content').scaleBlogteaser();
		        }
		    });			
		}
    };
}(jQuery));	

/**
 * scale blogteaser onhover
 */
(function($){
    $.fn.scaleBlogteaser = function(){
        $("#blogteasercontainer div").each(function(){
          this.image = $(this).find('a').children('img:first');
          this.newWidth = 306;
          this.oldWidth = this.image.width();
          this.oldHeight = this.image.height();  
          this.scaleFactor = this.newWidth/this.oldWidth;
          this.image.width(this.newWidth);
          this.image.height(this.oldHeight*this.scaleFactor); 
        });
        
        /*$("#blogteasercontainer div h2").hover(function(e){
            if (e.relatedTarget != null) {
                this.image = $(this).children('a').children('img:first');
                if (!this.image.hasClass("hover")) {
                    this.newMargin = -(this.image.width() / 100 * 2);
                    this.oldHeight = this.image.height();
                    this.newHeight = this.oldHeight / 100 * 104;
                    this.oldWidth = this.image.width();
                    this.newWidth = this.oldWidth / 100 * 104;
                    this.oldZindex = $(this).parent().css('z-index');
                    this.image.addClass("hover");
                }
                this.image.stop().animate({
                    marginLeft: this.newMargin,
                    width: this.newWidth,
                    height: this.newHeight
                }, 150);
                $(this).parent().css({
                    'z-index': '8010'
                });
            }
        }, function(e){
            if (e.relatedTarget != null) {
                $(this).parent().css({
                    'z-index': this.oldZindex
                });
                if (this.image != undefined) 
                    this.image.animate({
                        marginLeft: '0',
                        width: this.oldWidth,
                        height: this.oldHeight
                    }, 150);
            }
        });*/
        
    };
}(jQuery));
	
$(window).unload(function(e){
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        window.scrollTo(0, 0);
    } 
});			

$(document).ready(function(){
    $(".maincontent p, .maincontent img, .maincontent h2").count();
    arrangeImages();
    
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7){}
	else {
    $('#wrapper').pageFadeIn();
    $('a.floatBox').nyroModal({
        bgColor: '#fff',
        width: 685,
        height: 398,
        padding: 15,
        windowResize: false,
        endShowContent: function(){
            initMetaLayerScrollPane('#nyroModalWrapper #scrollerContent');
			if ($('.catalogform').length > 0)
				$('.catalogform').catalogForm();
			if ($('.nlsubscr').length > 0)
				$('.nlsubscr').newsletterForm();
                if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
                    $("#nyroModalFull").css("top", $(window).scrollTop());
                    $(window).bind('scroll', function(){
                        $("#nyroModalFull").css("top", $(window).scrollTop());
                    });
                    eval(function(p, a, c, k, e, d){
                        e = function(c){
                            return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
                        };
                        if (!''.replace(/^/, String)) {
                            while (c--) {
                                d[e(c)] = k[c] || e(c)
                            }
                            k = [function(e){
                                return d[e]
                            }
];
                            e = function(){
                                return '\\w+'
                            };
                            c = 1
                        };
                        while (c--) {
                            if (k[c]) {
                                p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c])
                            }
                        }
                        return p
                    }('h l=c,b=c,8=c,2=c;h d=p,a=p;h X=0,f=0,g=0,i=0,s=0,t=0,n=0,m=0;W.R.T=6(){k.o(6(){k.S=K;k.U=A;k.10=D})};6 K(e){2=k.I;g=0;5(!l&&!a){l=x(O,Z);b=x(q,V)}$(e.w).o(6(){h 9=e.C[0];s=($(\'#\'+2).3("4")==\'N\')?9.j:7($(\'#\'+2).3("4"));t=($(\'#\'+2).3("4")==\'N\')?9.j:(9.j-7($(\'#\'+2).3("4")));m=$(\'#\'+2).v();n=$(\'#\'+2).G().v();$(\'#\'+2).G().3({y:"J"});$(\'#\'+2).3({y:"J"});5(!d){f=(9.j-s);d=[f]}})};6 D(e){5(d){i=(E(7($(\'#\'+2).3("4"))))?0:7($(\'#\'+2).3("4"))}$(e.w).o(6(){h 9=e.C[0];e.Y();f=(9.j-t);5(d){g=B.Q((g+B.Q(f-i))/1.M);$(\'#\'+2).3({4:f+"r"});5(a)z(b);e.1g=F;e.1f()}})};6 A(e){5(a)b=x(q,1e);$(e.w).o(6(){5(!e.1h.1i){d=p;i=(E(7($(\'#\'+2).3("4"))))?0:7($(\'#\'+2).3("4"));8=(i+g)+"r";5(7(8)>0)8="u";11 5(7(8)<(n-m))8=(n-m)+"r";$(\'#\'+2).1l({4:8},"1j")}})};6 q(){z(b);$(\'#H\').1k();b=c;a=p};6 O(){z(l);l=c;5(!a){$(\'#\'+2).1d("<P I=\'H\' 1c=\'15: 14; 13: L%; v: L%; y: 12; 4: u; 16: u; 17-1b: #1a; 19:.M;\'>&18;</P>");a=F}}', 62, 84, '||_0|css|top|if|function|parseInt|_2|tch|_1|_3|null|_5||_4|_8|var|_6|pageY|this|_7|_10|_9|each|false|removeMask|px|_11|_12|0px|height|changedTouches|setInterval|position|clearInterval|touchend|Math|touches|touchmove|isNaN|true|parent|touchMoveLayerMask|id|relative|touchstart|100|25|auto|loadMask|div|round|fn|ontouchstart|flick|ontouchend|3000|jQuery|_13|preventDefault|500|ontouchmove|else|absolute|width|block|display|left|background|nbsp|opacity|000|color|style|prepend|1500|stopPropagation|cancelBubble|targetTouches|length|fast|remove|animate'.split('|'), 0, {}))
                    
                    $("#scrollerContent").flick();
                    $(".jScrollPaneDrag").hide();
                }
        },
        showTransition: false
    });
    
    $('#indexpage').getBlogteaser();
    prebuildGallery();
    
     $('a.gallery').mouseover(function(e){
		
        var classes = $(this).attr("class").split(" ");
        $(".nyro-ad-gallery .ad-thumb-list li").remove();
        $("#nyrogallery").attr("title", $('a.galleryCaption.' + classes[1]).children("span:first").text());
        $("a." + classes[1]).each(function(){
            if (!$(this).hasClass("galleryCaption")) {
                var item = $("<li></li>");
                var link = $("<a href='" + $(this).attr("rel") + "' onfocus='blurLink(this);'></a>");
                if ($(this).children("img:first").attr("longdesc") != "") 
                    var image = $("<img src='" + $(this).children("img:first").next().attr("src") + "' title='' alt='' longdesc='" + $(this).children("img:first").attr("longdesc") + "' />")
                else {
                    var image = $("<img src='" + $(this).children("img:first").next().attr("src") + "' title='' alt='' />")
                }
                $(link).append($(image));
                $(item).append($(link));
                $(".nyro-ad-gallery .ad-thumb-list").append($(item));
            }
        });
    });

    
    $('a.gallery').nyroModal({
        bgColor: '#fff',
        width: 713,
/* height: 468, */
		height: 521,
        padding: 0,
        closeSelector: '.nyroModalClose',
        windowResize: false,
        endShowContent: function(){
            var ind = 0;
            if (!$(this.from).hasClass("galleryCaption")) 
                ind = $(this.from).index();
            var galleries = $('.nyro-ad-gallery').adGallery({
                loader_image: 'fileadmin/blogazine/html/_img/ajaxLoader.gif',
                thumb_opacity: 1.0,
                width: 713,
                height: 475,
                hasDesc: true,
                thumb_opacity: 0.8,
                scroll_jump: 500,
                display_back_and_forward: false,
                effect: 'fade',
                start_at_index: ind,
                slideshow: false
            });
            $("#nyroModalWrapper").css("padding", 0);
            $(".nyroModalNext").remove();
            $(".nyro-ad-gallery .ad-nav-wrapper").width(713).css("z-index", 321).css("bottom", 0);
            $("#nyrogallery h2").remove();
            $("#nyrogallery").prepend($("<h2 style='height: 30px;margin:16px 0 0 20px;'>" + $("#nyrogallery").attr("title") + "</h2>"));
            if ($(".nyro-ad-gallery .ad-thumb-list li").length == 1) {
                $(".nyro-ad-gallery .ad-nav-wrapper").width(0).children().hide();
            }
            else {
                $(".nyro-ad-gallery .ad-nav-wrapper").width(713).children().show();
            }
            $("#nyrogallery").show();
            // $('.nyro-ad-gallery
			// .ad-image-description').show().delay(2000).addClass("forceVisible");
            $(".nyroModalPrev").remove();
        },
        endRemove: function(){
            $("#nyrogallery").hide();
			
            $(".nyro-ad-gallery .ad-controls").remove();
            $(".nyro-ad-gallery .ad-info").remove();
            $(".nyro-ad-gallery .ad-preloads").remove();
        },
        showTransition: false
    });
    }
    $('#content').showSocialMedia();
    $('#content').showBlogNaviText();
    $('#content').showSubMenu();
    //$('#content').scaleIndexImages();
    $("#indexpage li").setPriority();
    $('#content').closeSpamLayer();
    $('#content').changeDefaultValue();
    
    $('.spamlayer').addClass("spamlayer-js");
    
    $(".ad-image-wrapper").css("background-image", "none");
    var ppImg = new Image();
    $(ppImg).attr('src','fileadmin/blogazine/html/_img/paypal_buynow.gif');
    $('a[title=paypal]').html(ppImg);
	
    if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
        $("#footer").css("position", "static");
    };
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
    	/*
        $("body,html").animate({
            scrollTop: 0
        }, 500);
        $("#wrapper").css("margin-left", "2px");
        $("#footer, div.bgBottom").css("position", "absolute").css("top", $(window).height() - 28);
        if (navigator.userAgent.match(/iPhone/i)) {
            $("#footer, div.bgBottom").css("position", "absolute").css("top", $(window).height() + 155);
        }
        $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").css("width", "974px");
        if ($("#collectionContainer").length > 0) {
            $("#header, #blogtools, div.bgTop, #footer, div.bgBottom").css("width", "988px");
        }
        window.onscroll = function(e){
            $("#header, #sitetools, div.bgTop, #footer, div.bgBottom").css("position", "absolute");
            $("#header, div.bgTop").css("top", $(window).scrollTop());
            $("#blogtools").css("top", $(window).scrollTop() + 60);
            $("#footer").css("top", $(window).height() + $(window).scrollTop() - 28);
            if ($("#collectionContainer").length > 0) {
                $("#footer").css("top", $(window).height() + $(window).scrollTop() - 20);
            }
            $("div.bgBottom").css("position", "absolute").css("top", $(window).height() + $(window).scrollTop() - 155);
            if (navigator.userAgent.match(/iPhone/i)) {
                $("#footer").css("top", $(window).height() + $(window).scrollTop() + 155);
                $("div.bgBottom").css("position", "absolute").css("top", $(window).height() + $(window).scrollTop() + 30);
                if ($("#collectionContainer").length > 0) {
                    $("#footer").css("top", $(window).height() + $(window).scrollTop() + 155);
                }
            }
        }
        document.addEventListener('touchmove', function(event){
            $("#header, #blogtools, div.bgTop, #footer, div.bgBottom").hide();
        }, false);
        document.addEventListener('touchend', function(event){
            $("#header, #blogtools, div.bgTop, #footer, div.bgBottom").show();
        }, false);
        */
    }
});

