jQuery(function() {
    $('.loader').fadeTo(0, 0.5);
    Menu.init();
    Submenu.init();
    Address.init();
    Debug.init();
    if($.address.value() == '/') {
        Page.init();
    }
    
    if($('#jquery_jplayer').length) {
        $("#jquery_jplayer").jPlayer({
            swfPath: '/javascripts/jplayer/',
            ready: function () {
                $("#jquery_jplayer").jPlayer("setFile", '/javascripts/jplayer/deshielo_128K.mp3');// 'http://www.miaowmusic.com/audio/mp3/Miaow-05-The-separation.mp3');
                if($('#music_playpauze').hasClass('pause')) {
                    $("#jquery_jplayer").jPlayer("play");
                }
            }
        });
    }
    
    // Autostart player
    if($('#music_playpauze').length) {
        $('#music_playpauze').click(function() {
            if($(this).hasClass('pause')) {
                $("#jquery_jplayer").jPlayer('pause');
                $(this).addClass('pplay').removeClass('pause').html('Play');
            }
            else {
                $("#jquery_jplayer").jPlayer('play');
                $(this).addClass('pause').removeClass('pplay').html('Pause');
            }
            return false;
        });
        
        if($('#music_playpauze').hasClass('pause')) {
            $("#jquery_jplayer").jPlayer("play");
        }
    }
    
    // Auto-Repeat
    $("#jquery_jplayer").jPlayer("onSoundComplete", function() {
        this.element.jPlayer("play"); 
    });
	
    jQuery("input[type=text], textarea").not('.noempty').emptyonclick();
});

var Debug = {
    init: function() {
        //$('body').append('<div id="debugger" />');
        //$('#debugger').css({'z-index': 100, 'position' : 'absolute', 'background-color': '#FFF', 'top':0, left:0, 'color': '#000', 'padding' : '5px'});
    },
    rebuild: function() {
        //$('#debugger').html('Page open: '+Page.is_open+' '+Page.category + ' '+Page.page+'<br />Gallery: '+Gallery.is_open+' '+Gallery.current_page);
    }
};

var Address = {
    init: function() {
        jQuery('.map-button').click(function() {
            Address.go(jQuery(this).attr('href'));
            return false;
        });
        
        jQuery('.menu li, .submenu li:not(.active), #logo h1').click(function() {
            var url = jQuery('a', this).attr('href');
            Address.go(url);
            return false;
        });
        
        jQuery('.moduletable-footer a').click(function() {
            var url = jQuery(this).attr('href');
            if(url == '#') {
                url = window.location.toString();
                url = url.split('.com');
                base = url[0]+'.com';
                url = url[1].split('#');
                url = url[0];
                Address.go(url);
                //window.location = base+url;
            }
            else {
                Address.go(url);
            }
            
            return false;
        });
        
        jQuery('.submenu li.active').click(function() {
            var url = '/'+jQuery('a', this).attr('title').replace('##', '/').replace('##', '/');
            window.location.hash = url;
            return false;
        });
        
        $.address.change(function(event) {
            /* /en/general-information/project */
            var url = $.address.value();
            url = url.split('/');
            
            var lang = jQuery('#active_language span').attr('lang');
            
            if(lang == 'en') {
                if(url[1] == '' || url[2] == 'home') {
                    Advert.show();
                }
                else {
                    Advert.close(function() {
                        Advert.hide();
                    });
                }
            }
            else {
                Advert.hide();
            }
            
            if(url[3] && url[3] != '') {
                Page.show($.address.value());
                if(!Submenu.is_open) {
                    Submenu.open(url[2]);
                }
            }
            else if(url[2] && url[2] != '') {
                Submenu.open(url[2]);
                $('.loader').hide();
            }
            else if(url[1] && url[1] != '') {
                Page.hide();
                Submenu.close();
            }
        });
    },
    go: function(a) {
        $.address.value(a);
    },
    open: function(hash) {
        window.location.hash = hash;
        return false;
    }
};

var Menu = {
    init: function() {
        jQuery('.menu li').click(function() {
            jQuery('.menu li').removeClass('active');
            jQuery(this).addClass('active');
            return false;
        });
    }
};

var Submenu = {
    is_open: false,
    init: function() {
        jQuery('.submenu li').click(function() {
            jQuery('.submenu li').removeClass('active');
            jQuery(this).addClass('active');
            return false;
        });
        
        if(jQuery('.submenu ul:visible').length) {
            Submenu.is_open = true;
        }
        
        jQuery('.submenu .close-x').click(function() {
            Submenu.close(750);
            Page.animations.hide(750);
        });
        
        Debug.rebuild();
    },
    open: function(name) {
        //console.log('open submenu');
        //if(Page.category == 'home') {
            Page.animations.hide();
        //}
        if(Page.is_open == false) {
            //Gallery.hide();
        }

        if(Submenu.is_open) {
            Submenu.is_open = true;
            Submenu.animations.close(350, function() {
                jQuery('.submenu ul').hide();
                jQuery('.'+name).show();
                if(jQuery('.'+name).children('li').length) {
                    Submenu.animations.open(350);
                }
                Debug.rebuild();
            });
        }
        else {
            Submenu.is_open = true;
            jQuery('.submenu ul').hide();
            jQuery('.'+name).show();
            if(jQuery('.'+name).children('li').length) {
                Submenu.animations.open(350);
            }
        }
        Debug.rebuild();
        return false;
    },
    close: function(speed, callback) {
        //console.log('close submenu');
        if(!callback) {
            callback = function(){};
        }
        Submenu.is_open = false;
        Submenu.animations.close(speed, function() {
            callback();
            Debug.rebuild();
        });
        return false;
        Debug.rebuild();
    },
    animations: {
        open: function(speed, callback) {
            //console.log('open submenu anim');
            if(!callback) {
                callback = function(){};
            }
            jQuery('.submenu').animate({opacity: 1, left: '238px'}, speed, function() {
                callback();
                if(!$.support.opacity) {
    				$('.submenu').css('filter', '');
    			}
                Debug.rebuild();
            });
        },
        close: function(speed, callback) {
            //console.log('open submenu anim');
            if(!callback) {
                callback = function(){};
            }
            jQuery('.submenu').animate({opacity: 0, left: '100px'}, speed, function() {
                callback();
                if(!$.support.opacity) {
    				//$('.submenu').css('filter', '');
    			}
                Debug.rebuild();
            });
        }
    }
};

var Gallery = {
    is_open: false,
    images: [],
    thumbs: [],
    page: null,
    submenu_was_open: null,
    page_was_open: null,
    current_page: null,
    hide: function() {
        Gallery.link.hide(500);
        Gallery.navigation.hide(500);
        Gallery.animations.hide(500);
    },
    link: {
        show: function(speed, callback) {
            if(!callback) {
                callback = function(){};
            }
            
            if(Gallery.images.length <= 1) {
                callback();
                Debug.rebuild();
                return;
            }
            
            jQuery('.label-tab').animate({opacity: 1, right: 16}, speed, function() {
                callback();
                Debug.rebuild();
            }).click(function() {
                Gallery.link.hide(250, function() {
                    Gallery.navigation.show(500);
                    Debug.rebuild();
                });
            });
            Debug.rebuild();
        },
        hide: function(speed, callback) {
            if(!callback) {
                callback = function(){};
            }
            
            if(Gallery.images.length <= 1) {
                callback();
                Debug.rebuild();
                return;
            }
            
            jQuery('.label-tab').animate({opacity: 0, right: -4}, speed, function() {
                callback();
                Debug.rebuild();
            });
            Debug.rebuild();
        }
    },
    navigation: {
        show: function(speed, callback) {
            if(!callback) {
                callback = function(){};
            }
            
            if(Gallery.images.length <= 1) {
                callback();
                Debug.rebuild();
                return;
            }
            
            if(Page.is_open) {
                Gallery.page_was_open = true;
                Page.animations.hide();
            }
            
            if(Submenu.is_open) {
                Gallery.submenu_was_open = true;
                Submenu.animations.close();
            }
            
            jQuery('.gallery-pp').unbind('click.playpause');
            jQuery('.gallery-pp').bind('click.playpause', function() {
                if(jQuery(this).hasClass('play')) {
                    jQuery(this).removeClass('play');
                    jQuery('#slideshow').cycle('resume').cycle('next');
                }
                else {
                    jQuery(this).addClass('play');
                    jQuery('#slideshow').cycle('pause');
                }
                
                return false;
            });
            
            var current_page = Page.category+Page.page;

            if(current_page != Gallery.current_page) {
                jQuery('.cycle-pager').remove();
                jQuery('#slideshow').cycle({
                    fx: 'fade',
                    pager: '.cont-gallery',
                    before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
                        jQuery.fn.fullscreenr({width: jQuery(nextSlideElement).width(), height: jQuery(nextSlideElement).height(), bgID: nextSlideElement});
                    },
                    pagerAnchorBuilder: function(idx, slide) { 
                        return '<a href="#" class="cycle-pager"><img src="' + slide.alt + '" /></a>'; 
                    },
                    next: '.gallery-next'
                });

                jQuery('.gallery-pp').removeClass('play');
                Gallery.current_page = current_page;
            }
            else {
                jQuery('.gallery-pp').removeClass('play');
                jQuery('#slideshow').cycle('resume');
            }
            jQuery('#slideshow').show();
            jQuery('.gallery-next, .gallery-pp').fadeIn(speed);
            jQuery('.cont-gallery').animate({opacity: 1, right: 16}, speed, function() {
                callback();
                Debug.rebuild();
            });
            Debug.rebuild();
        },
        hide: function(speed, callback) {
            if(!callback) {
                callback = function(){};
            }
            
            if(Gallery.images.length <= 1) {
                callback();
                Debug.rebuild();
                return;
            }
            
            jQuery('.gallery-next, .gallery-pp').fadeOut(speed);
            jQuery('#slideshow').cycle('pause');
            jQuery('.cont-gallery').animate({opacity: 0, right: -72}, speed, function() {
                callback();

                Debug.rebuild();
            });
            Debug.rebuild();
        }
    },
    animations: {
        hide: function(speed, callback) {
            if(!callback) {
                callback = function(){};
            }
            Gallery.current_page = null;
            
            jQuery('#slideshow, .gallery-next, .gallery-pp').fadeOut('slow', function() {
                //jQuery('#slideshow').cycle('destroy');
                //jQuery('#slideshow').html('');
                Gallery.is_open = false;
                callback();
                Debug.rebuild();
            });
            
            Debug.rebuild();
        },
        showfirst: function(speed, callback) {
            if(callback == undefined) {
                var callback = function(){
                    
                };
            }
            
            jQuery('#slideshow').cycle('stop');
            jQuery('#slideshow').html('');
            
            jQuery('#slideshow').append('<img src="'+Gallery.images[0]+'" alt="'+Gallery.thumbs[0]+'" />');
            
            jQuery('#slideshow img').hide();
            jQuery('#slideshow').show();
            
            jQuery('#slideshow img').each(function(i, element) {
                if(!jQuery(element).hasClass('fullscreen')) {
                    jQuery(element).addClass('fullscreen');
                    var height = jQuery(element).height();
                    var width = jQuery(element).width();
                    if(width == 0) {
                        width = 1460;
                    }
                    if(height == 0) {
                        height = 1043;
                    }
                    jQuery.fn.fullscreenr({width: width, height: height, bgID: element});
                }
            });
            
            jQuery('#slideshow img:first').fadeIn(speed, callback);
            
            Debug.rebuild();
        },
        show: function(speed, callback) {
            if(callback == undefined) {
                var callback = function(){
                    
                };
            }
            
            if(Gallery.is_open == true) {
                callback();
                return false;
            }
            
            for (image in Gallery.images) {
                if(image >= 1) {
                    jQuery('#slideshow').append('<img src="'+Gallery.images[image]+'" alt="'+Gallery.thumbs[image]+'" />');
                }
            }
            
            jQuery('#slideshow img:not(:first)').hide();
            jQuery('#slideshow img').each(function(i, element) {
                if(!jQuery(element).hasClass('fullscreen')) {
                    jQuery(element).addClass('fullscreen');
                    jQuery.fn.fullscreenr({width: jQuery(element).width(), height: jQuery(element).height(), bgID: element});
                }
            });
            jQuery('#slideshow').show();
            Gallery.is_open = true;
            
            Debug.rebuild();
        }
    },
    show: function(speed, page) {
        if(Gallery.page != page) {
            Gallery.images = [];
        }
        
        jQuery('.label-tab').prepend('<div class="label-tab-inner"></div>');
        jQuery('.cont-gallery img').each(function(i, image) {
            jQuery(image).hide();
            Gallery.thumbs[i] = image.src;
            Gallery.images[i] = image.src.replace('/thums', '');
        });
        
        if(Gallery.images.length <= 1) {
            jQuery('.cont-gallery').hide();
            jQuery('.label-tab').hide();
        }
        
        if(Gallery.images.length < 1) {
            $('.loader').hide();
        }
        else {
            var images = [];
            for(var i=1; i<Gallery.images.length; i++) {
                images.push(Gallery.images[i]);
            }
            var img_1 = Gallery.images[0];
            // Preload the images
            
            new ImagePreload([img_1], function(loader) {}, function(loader) {
                Gallery.animations.showfirst(750, function() {
                    $('.loader').hide();
                    jQuery('#slideshow').show();
                });
                
                if(images.length) {
                    new ImagePreload(images, function(loader) {}, function(loader) {
                        Gallery.animations.show(750, function() {
                            $('.loader').hide();
                            jQuery('#slideshow').show();
                        });
                        Gallery.link.show(750);
                    });
                }
            });

            jQuery('.close-G').click(function() {
                Gallery.navigation.hide(500, function() {
                    Gallery.link.show(250);
                });
                
                if(Gallery.page_was_open == true) {
                    Page.animations.show();
                }

                if(Gallery.submenu_was_open == true) {
                    Submenu.animations.open();
                }
            });
        }
        
        Debug.rebuild();
    }
};

var Page = {
    is_open: false,
    category: null,
    page: null,
    init: function() {
        if(jQuery('.cont-texts').length) {
            Page.show(false);
        }
    },
    show: function(link) {
        //console.log('show page');
        jQuery('.map-button').click(function() {
            Address.go(jQuery(this).attr('href'));
            return false;
        });
        Gallery.hide();
        
        $('.loader').show();
        
        if(Page.is_open) {
            Page.hide(300, function() {
                if(link) {
                    jQuery('#whitebox').load(link+'.js', function() {
                        if((jQuery('#category').val() == 'home' || $('.sitemap').length) && Submenu.is_open) {
                            Submenu.close();
                        }
                        jQuery('.map-button').click(function() {
                            Address.go(jQuery(this).attr('href'));
                            return false;
                        });
                        Page.category = jQuery('#category').val();
                        Page.page = jQuery('#page').val();
                        jQuery("input[type=text], textarea").not('.noempty').emptyonclick();
                        Page.animations.show(450);
                        Gallery.show(450, link);
						jQuery("input[type=text], textarea").not('.noempty').emptyonclick();
                    });
                }
                else{
                    Page.animations.show(450);
                    Gallery.show(450, link);
                }
            });
        }
        else {
            if(link) {
                jQuery('#whitebox').load(link+'.js', function() {
                    if((jQuery('#category').val() == 'home' || $('.sitemap').length) && Submenu.is_open) {
                        Submenu.close();
                    }
                    jQuery('.map-button').click(function() {
                        Address.go(jQuery(this).attr('href'));
                        return false;
                    });
                    Page.category = jQuery('#category').val();
                    Page.page = jQuery('#page').val();
                    jQuery("input[type=text], textarea").emptyonclick();
                    Page.animations.show(450);
                    Gallery.show(450, link);
	                jQuery("input[type=text], textarea").emptyonclick();
                });
            }
            else {
                if((jQuery('#category').val() == 'home' || $('.sitemap').length) == 'home') {
                    Submenu.close();
                }
                Page.category = jQuery('#category').val();
                Page.page = jQuery('#page').val();
                Page.animations.show(750);
                Gallery.show(750, link);
            }
        }
        
        Debug.rebuild();
        return false;
    },
    hide: function(speed, callback) {
        //console.log('page is open'+Page.is_open);
        //console.log('hide page');
        if(!callback) {
            callback = function(){};
        }
        //Gallery.hide();
        Page.animations.hide(speed, function() {
            callback();
            Debug.rebuild();
        });
        return false;
    },
    checkScrollButtons: function() {
        if($(".scrollpane").height() - $("#scroller").height() == $("#scroller").css('margin-top').replace('px', '')) {
            $(".scrollpane-btn-down").addClass('disabled');
            $(".scrollpane-btn-up").removeClass('disabled');
        }
        else if($("#scroller").css('margin-top').replace('px', '') == 0) {
            $(".scrollpane-btn-up").addClass('disabled');
            $(".scrollpane-btn-down").removeClass('disabled');
        }
        else {
            $(".scrollpane-btn-down, .scrollpane-btn-up").removeClass('disabled');
        }
    },
    animations: {
        show: function(speed, callback) {
            if(Page.is_open != false) {
                Debug.rebuild();
                return;
            }
            //console.log('show page anim');
            
            if(!callback) {
                callback = function(){};
            }
            
            Page.is_open = true;
            
            if(jQuery('.wide-div').length || jQuery('#category').val() == 'home') {
                jQuery('.cont-texts').css('left', '190px');
                jQuery('#slideshow').html('');
                var left = 238;
            }
            else {
                var left = 399;
            }
            jQuery('.cont-texts h2').fadeIn(speed);
            $(".scrollpane").height($(window).height()-208-75);
            jQuery('.cont-texts').animate({opacity: 1, left: left+'px'}, speed, function() {
                if(!$.support.opacity) {
                    $('.cont-texts').css('filter', '');
                }
                
                $(".scrollpane").wrapInner('<div id="scroller">');
                //alert($("#scroller").height());
                if($(".scrollpane").height() < $("#scroller").height()) {
                    $(".scrollpane").parent().append('<div class="scrollpane-btn-up">').append('<div class="scrollpane-btn-down">');
                    Page.checkScrollButtons();
                    $(".scrollpane-btn-down").hover(
                        function() {
                            $("#scroller").stop();
                            $("#scroller").animate({'margin-top': $(".scrollpane").height()-$("#scroller").height()}, ($(".scrollpane").height()-$("#scroller").height())*-10, Page.checkScrollButtons);
                        },
                        function() {
                            $("#scroller").stop();
                    });

                    $(".scrollpane-btn-up").hover(
                        function() {
                            $("#scroller").stop();
                            $("#scroller").animate({'margin-top': '0'}, ($(".scrollpane").height()-$("#scroller").height())*-10, Page.checkScrollButtons);
                        },
                        function() {
                            $("#scroller").stop();
                    });
                }
                
                callback();
                Debug.rebuild();
            });
            Debug.rebuild();
        },
        hide: function(speed, callback) {
            //console.log('hide page anim');
            if(Page.is_open != true) {
                return;
            }
            
            if(!callback) {
                callback = function(){};
            }
            Page.is_open = false;
            
            if(jQuery('.wide-div').length || jQuery('#category').val() == 'home') {
                var left = 190;
            }
            else {
                var left = 349;
            }
            jQuery('.scrollpane-btn-up, .scrollpane-btn-down').remove();
            jQuery('.cont-texts h2').fadeOut(speed);
            jQuery('.cont-texts').animate({opacity: 0, left: left+'px'}, speed, function() {
                callback();
                if(!$.support.opacity) {
                    //$('.cont-texts').css('filter', '');
                }
                Debug.rebuild();
            });
            Debug.rebuild();
        }
    }
};

function ImagePreload( p_aImages, p_pfnPercent, p_pfnFinished ) {
    // Call-back routines
    this.m_pfnPercent = p_pfnPercent;
    this.m_pfnFinished = p_pfnFinished;
    
    // Class Member Vars
    this.m_nLoaded = 0;
    this.m_nProcessed = 0;
    this.m_aImages = new Array;
    this.t_aImages= new Array;
    this.m_nICount = p_aImages.length;

    // Preload Array of Images
    for( var i = 0; i < p_aImages.length; i++ ) {
        this.Preload( p_aImages[i] );
    }
};

ImagePreload.prototype.Preload = function( p_oImage ) {
    var oImage = new Image;
    this.m_aImages.push(oImage);
    this.t_aImages.push(p_oImage);

    oImage.onload = ImagePreload.prototype.OnLoad;
    oImage.onerror = ImagePreload.prototype.OnError;
    oImage.onabort = ImagePreload.prototype.OnAbort;

    oImage.oImagePreload = this;
    oImage.bLoaded = false;
    oImage.source = p_oImage;
    oImage.src = p_oImage;
};

ImagePreload.prototype.OnComplete = function() {
    this.m_nProcessed++;
    if ( this.m_nProcessed == this.m_nICount )
        this.m_pfnFinished(this);
    else
        this.m_pfnPercent(this);
};

ImagePreload.prototype.OnLoad = function() {
    // 'this' pointer points to oImage Object
    this.bLoaded = true;
    this.oImagePreload.m_nLoaded++;
    this.oImagePreload.OnComplete(this);
};

ImagePreload.prototype.OnError = function() {
    // 'this' pointer points to oImage Object
    this.bError = true;
    this.oImagePreload.OnComplete(this);
};

ImagePreload.prototype.OnAbort = function() {
    // 'this' pointer points to oImage Object
    this.bAbort = true;
    this.oImagePreload.OnComplete(this);
};

var Advert = {
	init: function() {
		this.cont = $('.advert');
		this.btn = $('.open-button');
		this.timeout = null;
		this.image_1 = $('#image_1');
		this.image_2 = $('#image_2');
		var that = this;
		this.btn.click(function() {
			if($(this).hasClass('open')) {
				that.open();
			}
			else {
				that.close();
			}
		});
	},
	show: function() {
	    if(!this.cont) {
	        this.init();
	    }
	    else {
	        this.cont.show();
	    }
	    
	    this.open();
	},
	hide: function() {
	    if(!this.cont) {
	        this.init();
    	    this.cont.hide();
	    }
	    else {
    	    this.cont.fadeOut();
	    }
	},
	open: function() {
		var that = this;
		this.cont.animate({
		 	right: "16px"
		});	
		this.btn.removeClass('open');
		this.startCycle();
		this.image_1.fadeIn(400, function() {
			that.image_2.show();
		});
	},
	close: function(callback) {
		var that = this;
		this.cont.animate({
			right: "-295px"
		}, {
			complete: function() {
				that.btn.addClass('open');
				if(callback) {
    				callback();
				}
			}
		});
		this.stopCycle();
		if($('#image_1:visible').length) {
			this.image_2.hide();
			this.image_1.fadeOut();
		}
		else {
			this.image_2.fadeOut();
		}
	},
	startCycle: function() {
		var that = this;
		this.stopCycle();
		this.timeout = setInterval(function() {
			if($('#image_1:visible').length) {
				that.image_1.fadeOut();
			}
			else {
				that.image_1.fadeIn();
			}
		}, 12000);
	},
	stopCycle: function() {
		if(this.timeout) {
			clearInterval(this.timeout);
			this.timeout = null;
		}
	}
};


/*
* jQuery emptyonclick plugin
*
* Created by Andreas Creten (andreas@madewithlove.be) on 2008-06-06.
* Copyright (c) 2008 madewithlove. All rights reserved.
*
* Version: 1.2
*
* Changelog :
* Version 1.2 (17 Jun 2008)
*  - Empty the fields onsubmit when they are not changed
*
* Version 1.1 (11 Jun 2008)
*  - Fixed a bug when working with an empty field (no default value)
*
* Version 1.0 (06 Jun 2008):
*  - Original version
*/

jQuery.fn.emptyonclick = function(options) {
    return this.each(function(options){
        $.emptyonclick(this, options);
    });
};

$.emptyonclick = function(element, options) {
    var defaultValue = jQuery(element).val();
    
    // Bind event handlers to the element
    jQuery(element)
    // On Focus: Store the default value if it's not set, empty the field
    .bind("focus", function(e) {
        if(defaultValue == jQuery(this).val())
            jQuery(this).val('');

    })
    // On Blur: if the field is empty, reset the default value
    .bind("blur", function(e) {
        if(!jQuery(this).val()) {
            jQuery(this).val(defaultValue);
        }
    });

    // Search for the form which has the element
    jQuery(element).parents('form')
    // If the form gets resetted, set the default value back
    .bind('reset', function(e) {
        jQuery(element).val(defaultValue);
        jQuery(element).removeClass(options.changeClass);
    }) 
    // If the form gets submitted empty, remove the default values
    .bind('submit', function(e) {
        if(jQuery(element).val() == defaultValue)
            jQuery(element).val('');
    });
};
