/* BEYAZ JS */
var base_url = window.location.host;

$(document).ready(function(){
    
    /* GALLERY PAGE */
    
    gallery(); // gallery slider animation & collapse/expand toggle
    
    /* GLOBAL JS */

    // minimize/maximize header
    header();
    // top_menu submenus toggle
    top_menu();
    // load background image(s)
    background_load();

    /* CONTENT PAGE */

    // align h2 span background
    span_bg();
    // set content wrapper height
    content_wrapper();

    /* VALORISATION IMOBILLIERE PAGE */

    ba(); // before and after slider animation
	
    // Open all external links and PDF in new window
	$("a[href^='http:']:not([href*='" + base_url + "']), a[href$='.pdf']:not([href*='" + base_url + "']), a[href$='.pdf']").live('click', function() {
		$(this).attr('target','_blank');
	});
	
	// fullscreen control
	fullscreen();

});

/* WINDOW RESIZE */
$(window).resize(function(){
    // resize the background
    bg_resize();
    // change h2 span bg position
    span_bg();
    // resize content_wrapper height
    content_wrapper();
});

function header() {
    /*
     * This function handles collapse/expand animation for the header and big/small logo replacement
    */
    
    // check if there's a cookie set for header's state
    var header_state = $.cookie('beyaz_header_state');
    
    // if header is collapsed
	if(header_state == 'collapsed' || $('#header').hasClass('minheader')) {
		// set header height
		$('#header_wrapper,#header').height(40);
		// set small logo
		$('.logo').addClass('small_logo');
		// set content/contact top margin
		$('#content,#contact').css({'margin-top':115});
		// remove class maximized header
		$('.minimize_header').removeClass('maximized_header');
	}
	
	// if header is expanded
	if(header_state == 'expanded') {
		// set header height
		$('#header_wrapper,#header').height(125);
		// set small logo
		$('.logo').removeClass('small_logo');
		// set content/contact top margin
		$('#content,#contact').css({'margin-top':200});
		// remove class maximized header
		$('.minimize_header').addClass('maximized_header');
	}
	
	// toggle expand/collapse header
    $('.minimize_header').click(function(){
        var logo_fade_speed = 200; // logo fades when switching between header heights
        if($(this).hasClass('maximized_header')) {
            $('#header_wrapper,#header').stop(true,true).animate({
                height:40
            },250,function(){
            	// set collapsed header cookie
            	$.cookie('beyaz_header_state','collapsed');
            	// recalculate welcome position
            	welcome();
            });
            // replace logo with the small one
            $('.logo').fadeOut(logo_fade_speed,function(){
                $(this).addClass('small_logo');
            }).fadeIn(logo_fade_speed);
            // content margin-top
            $('#content,#contact').stop(true,true).animate({
                marginTop:115
            },250,function(){
                span_bg()
            });
            //
            $(this).removeClass('maximized_header');
        } else {
            $('#header_wrapper,#header').stop(true,true).animate({
                height:125
            },250,function(){
            	// set expanded header cookie
            	$.cookie('beyaz_header_state','expanded');
            	// recalculate welcome position
            	welcome();
            });
            // replace logo with the big one
            $('.logo').fadeOut(logo_fade_speed,function(){
                $(this).removeClass('small_logo');
            }).fadeIn(logo_fade_speed);
            // content margin-top
            $('#content,#contact').animate({
                marginTop:200
            },250,function(){
                span_bg()
            });
            //
            $(this).addClass('maximized_header');
        }
    })
}
function top_menu() {
    /*
     * This function handles the submenu animation of the top menu
    */

    $('#top_menu li.expandable').hoverIntent({
        over:function(){
            $('ul',this).width($(this).width()).stop(true,true).slideDown(250);
        },
        out:function() {
            $('ul',this).delay(150).slideUp(250);
        },
        timeout:150
    });
}
function background_load() {
    /*
     * This function adds a gif preloader until the background images are loaded
    */
    // Preload background image
   	var cache = [];
    		
   	var cacheImage = document.createElement('img');
   	cacheImage.src = $('#background img:first').attr('src');
   	cache.push(cacheImage);

    // remove any active loader
    $('.loader').remove();
    // add loader
    $('#main').prepend('<div class="loader hide"></div>');
    // fadein loader
    $('.loader').fadeIn(150);
    //
    $('#background img:first').one('load', function() {
        $('#background,#welcome').fadeIn(500);
        $('.loader').fadeOut(150,function(){
            $(this).remove()
        });
        // resize background images to fit the window
        bg_resize();
       	console.log('background load');
    }).each(function() {
        if(this.complete) $(this).load(function(){
        });
    });
    
    // Still does not loaded?
   	setTimeout(function() {
   		$('#background,#welcome').fadeIn(500);
   		$('.loader').fadeOut(150,function(){
   		    $(this).remove()
   		});
   		// resize background images to fit the window
   		bg_resize();  	
   	},1500);
}
function bg_resize() {
    /*
     * This function calculates the size of the background relative to window size and centers it
    */
    $('#background').height($(window).height());
    //
    $('#background img').each(function(){
        var ratio = $(this).width()/$(this).height();
        // if bg width is smaller than window width
        if($(this).width() < $(window).width()) {
            $(this).width($(window).width());
        }
        // if bg height is smaller than window height
        if($(this).height() < $(window).height()) {
            $(this).height($(window).height());
            $(this).width($(this).height()*ratio)
        }
        // position to center of the screen
        $(this).css({
            'margin-left':'-'+($(this).width()-$(window).width())/2+'px',
            'margin-top':'-'+($(this).height()-$(window).height())/2+'px'
        })
        // check welcome screen position
        welcome();
    });
}
function welcome() {
    /*
     * This function adds some top and bottom margin if the view port height is smaller than welcome screen
    */
   
    // if no welcome screen return false
    if($('#welcome').length == 0) {
    	return false;
    }
   
    // center welcome to screen
    var mt = Math.round(($(window).height()-$('#welcome').height())/2) - 60; // margin top / 60 is the box padding
   
    // always keep a 30px under header
    var min_mt = 140+30;
   
    // if header is collapsed calculate new margin top
	if($.cookie('beyaz_header_state') == 'collapsed') {
		min_mt = 40+30;
	}
	
	// set css rules
	if(mt>=min_mt) {
		$('#welcome').css({'top':mt+'px','margin-top':0});	
	} else {
		$('#welcome').css({'top':min_mt+'px','margin-top':0});	
	}
	
	//
	var wh = $('#welcome').height();
	// if window height is short // 80 is the bottom margin
	if($(window).height() < (wh+min_mt+80)) {
		// set new background height
		$('#background').height(min_mt+wh+120);
		// recalculate background image position
		$('#background img').each(function(){
				$(this).css({
					'margin-top':'-'+($(this).height()-(min_mt+80+wh))/2+'px'
				});
			});
	}
}
function span_bg() {
    /*
     * This function changes the position of the h2 span background relative to content_wrapper background so the marble pattern to be in the exact position
    */
    $('h2 span').each(function(){
        var offset = $(this).position();
        $(this).css('background-position','-'+offset.left+'px -'+offset.top+'px');
    })
}
function content_wrapper() {
    /*
     * This function changes the height of content_wrapper so the marble pattern to cover all the document height
    */
    $('#content_wrapper').height($(document).height());
}
function gallery() {
    /*
     * This function handles the gallery collapse/expand toggle
    */
    // check if gallery exists
    if($('#the_images').length == 0) {
    	return false;
    }
    // check window hash
    var hash = window.location.hash
    if(hash != '') {
    	hash = hash.substr(1);
    }
    // check if hash points to category id
    if(hash != '' && $('#categories #'+hash).length > 0) {
    	$('#categories #'+hash).addClass('selected');
    } else {
    	// if no gallery hash select the first gallery
    	$('#categories a:first').addClass('selected');
    }
    
    // calculate index of the selected category
    var category = $('#categories a').index($('#categories a.selected'));
    
    // add class last to last category
    $('#categories a:last').addClass('last');
    
    // populate gallery content with category content
    $('#gallery_content').html($('#the_images div:eq('+category+')').html());

    // load gallery first image as background
    $('#background img').remove();
    $('#background').append('<img src="'+$('#gallery_content a:first').attr('href')+'" />');
    
    // remove left arrow
    $('.arrow_left').hide();
    
    // change image category
    $('#categories a').click(function(){
    	if($(this).hasClass('selected')) {
    		return false;
    	}
    	// calculate index of the selected category
    	var i = $('#categories a').index($(this));

    	// remove class selected
    	$('#categories a').removeClass('selected');

    	// add class selected to clicked index
    	$(this).addClass('selected');

    	// populate gallery content with category content
    	$('#gallery_content').html($('#the_images div:eq('+i+')').html());

    	// add offset class to first image
    	$('#gallery_content a:first').addClass('offset');
    	
    	// hide or show arrows depending on gallery size
    	if($('#gallery_content a').length <= 5) {
    		$('.arrow_left, .arrow_right').hide();
    	} else {
    		$('.arrow_left, .arrow_right').show();
    	}
    	

    	// load gallery first image as background
    	galleryShow(0);
    	
    	// set margin of the gallery_content
    	$('#gallery_content').css('margin-left',0);
    	
    	// remove left arrow
    	$('.arrow_left').hide();
    })
    
    // check if image gallery cookie exists
    var gallery_state = $.cookie('beyaz_gallery_state');
    // if gallery is collapsed
    if(gallery_state == 'collapsed') {
    	// set bottom margin
    	$('#gallery_wrapper').css({'bottom':-80});
    	// change toggle span
    	$('.toggle').removeClass('toggle_hide').text('voir');
    	// arrows position
    	$('.arrow_left,.arrow_right','#gallery_wrapper').css({'top':0});  	
    	// gallery wrapper class
    	$('#gallery_wrapper').removeClass('extended');
    }
    // if gallery is extended
    if(gallery_state == 'expanded') {
    	// set bottom margin
    	$('#gallery_wrapper').css({'bottom':30});    	
    	// change toggle span
    	$('.toggle').addClass('toggle_hide').text(translations['hide']);
    	// arrows position
    	$('.arrow_left,.arrow_right','#gallery_wrapper').css({'top':72});
    	// gallery wrapper class
    	$('#gallery_wrapper').addClass('extended');
    }
    

    /* toggle gallery */
    $('.toggle').click(function(){
        var gh = $('#gallery').height();
        if(!$('#gallery_wrapper').hasClass('extended')) {
            $('#gallery_wrapper').animate({
                bottom:30
            },250,function(){
            	// set collapsed header cookie
            	$.cookie('beyaz_gallery_state','expanded');
            });
            //
            $('.toggle').addClass('toggle_hide').text(translations['hide']);
            $('#gallery_wrapper').addClass('extended');
            // reposition arrows
            $('.arrow_left,.arrow_right','#gallery_wrapper').animate({
                top:72
            },250);
        } else {
            $('#gallery_wrapper').animate({
                bottom:-80
            },250,function(){
            	// set collapsed header cookie
            	$.cookie('beyaz_gallery_state','collapsed');
            });
            //
            $('.toggle').removeClass('toggle_hide').text('voir');
            $('#gallery_wrapper').removeClass('extended');
            // reposition arrows
            $('.arrow_left,.arrow_right','#gallery_wrapper').animate({
                top:0
            },250);
        }
    })
    // gallery hover
    $('#gallery_content a').live({
    	mouseenter : function() {
    		if(!$(this).hasClass('active')) {
    		            $('img',this).stop(true,true).animate({
    		                opacity:1
    		            },150);
    		        }
    	},
    	mouseleave : function() {
    		if(!$(this).hasClass('active')) {
    		            $('img',this).animate({
    		                opacity:.4
    		            },150);
    		        }
    	}
    })

    // set first image as active
    $('#gallery_content a:first').addClass('active').addClass('offset');
    
    // mouse over
    $('#gallery_content a').hover(function(){
    	$('img:first',this).stop(true,true).fadeOut();
    	$('img:eq(1)',this).stop(true,true).fadeIn();
    },function(){
    	$('img:first',this).fadeIn();
    	$('img:eq(1)',this).fadeOut();
    })
    //
    $('#gallery_content a').live('click',function(){
        galleryShow($('#gallery_content a').index($(this)));
        return false;
    });
    // clicking next/prev
    $('.arrow_left,.arrow_right','#gallery_wrapper').click(function(){
        if(!$('#gallery_wrapper').hasClass('extended')) {
            galleryNext(this);
        } else {
            gallerySlide(this);
        }
    })
	
}
function galleryNext(e) {
    /*
     * This function calculates the index of the next or previous image in the gallery when arrows are clicked
    */

    var totalImages = $('#gallery_content a').size();
    // calculate active index
    var activeIndex = $('#gallery_content > a').index($('.active'));
    var d = 1; // direction left to right
    if($(e).hasClass('arrow_left')) {
        d = -1;
    }
    if(activeIndex == 0 && d==-1) {
        return false;
    }
    if(activeIndex == totalImages-1 && d==1) {
        return false;
    }
    if(activeIndex+d < totalImages-1) {
    	$('.arrow_right').show();
    } else {
    	$('.arrow_right').hide();
    }
    if(activeIndex+d < 1) {
    	$('.arrow_left').hide();
    } else {
    	$('.arrow_left').show();
    }
    
    galleryShow(activeIndex+d);

}
function gallerySlide(e) {
    /*
     * This function handles the gallery slider when the gallery is expanded
    */
    var totalImages = $('#gallery_content a').size();
    // calculate active index
    var activeIndex = $('#gallery_content > a').index($('.offset'));
    //
    var d = 1; // direction left to right
    if($(e).hasClass('arrow_left')) {
        d = -1;
    }
    // if gallery has less or 5 images don't animate
    if(totalImages<=5) {
        return false;
    }
    //
    if(d==1 && totalImages-activeIndex-1<5) {
        return false;
    }
    if(d==-1 && activeIndex==0) {
        return false
    }
    // animate
    var slideWidth = 172;
    var offset = $('#gallery_content').position();
    var ml = 0 - ((offset.left)+slideWidth*(activeIndex+d));
    // remove first class
    $('#gallery_content .offset').removeClass('offset');
    // move first class to activeIndex+d
    $('#gallery_content a:eq('+(activeIndex+d)+')').addClass('offset');
    $('#gallery_content').stop(true,true).animate({
        marginLeft:ml
    },250,function(){
    	activeIndex = $('#gallery_content > a').index($('.offset'));
    	if(totalImages-activeIndex-1<5) {
    		$('.arrow_right').hide();
    	} else {
    		$('.arrow_right').show();
    	}
    	if(activeIndex < 1) {
    		$('.arrow_left').hide();
    	} else {
    		$('.arrow_left').show();
    	}
    	
    	
    	
    });
    

	
}
function galleryShow(i) {
    /*
     * This function changes the background with the image selected from the gallery
    */

    // remove any active loader
    $('.loader').remove();
    // add loader
    $('#main').prepend('<div class="loader hide"></div>');
    // fadein loader
    $('.loader').fadeIn(150);
    //
    $('#background').append('<img src="'+$('#gallery_content a:eq('+i+')').attr('href')+'" />');
    $('#background img:last').one('load', function() {
        bg_resize();
        // remove any active class
        $('#gallery_content .active').removeClass('active');
        // add class active to active index
        $('#gallery_content a:eq('+i+')').addClass('active');
        // fade out inactive images
        $('#gallery_content a').each(function(){
            if(!$(this).hasClass('active')) {
                $('img',this).animate({
                    opacity:.4
                },150);
            } else {
                $('img',this).animate({
                    opacity:1
                },150);
            }
        })
        // fade out and remove first image
        $('#background img').not(':last').fadeOut(500,function(){
            $(this).remove()
        });
        // remove loader
        $('.loader').fadeOut(150,function(){
            $(this).remove()
        });
       	console.log('gallery load');
    }).each(function() {
        if(this.complete) $(this).load();
    });
}
function ba() {
    /*
     * This function handles before & after slider initialization and
    */

    // add active index to first slide
    $('#ba_content div:first').addClass('active');
    
    // set title
    $('#ba_wrapper > h2').text($('#ba_content div.active > h3').text());
    
    // set first item image as background
    $('#background img:first').attr('src',$('a.before:first').attr('href'));
    
    // hide arrow left
    $('.arrow_left').hide();

    $('.arrow_left,.arrow_right','#ba_wrapper').click(function(){
        baNext(this);
    });
    // click on before/after
    $('a.before,a.after','#ba_content .active').live('click',function(){
        // remove class selected
        $('.selected',$(this).parent()).removeClass('selected');
        // add class selected
        $(this).addClass('selected');
        // replace font
        Cufon.replace('#ba_content .bell',{
            hover:true,
            fontFamily: 'Bell MT'
        });
        // change images
        baChangebg($(this).attr('href'));
        return false;
    });
}
function baNext(e) {
    /*
     * This function calculates the next/prev index of before & after page and handles slider animation
    */

    // count slides
    var totalSlides = $('#ba_content > div').size();
    // slide width
    var slideWidth = 500;
    //
    var d = 1;
    if($(e).hasClass('arrow_left')) {
        d = -1;
    }
    // calculate active index
    var activeIndex = $('#ba_content > div').index($('.active'));
    //
    if(activeIndex == 0 && d == -1) {
        return false;
    }
    if(activeIndex == totalSlides-1 && d==1) {
        return false;
    }
    //
    var offset = $('#ba_content').position();
    var ml = 0 - ((offset.left)+slideWidth*(activeIndex+d));
    // animate
    $('#ba_content').stop(true,true).animate({
        marginLeft:ml
    },250,function(){
        // remove any active class
        $('#ba_content .active').removeClass('active');
        // add class active to active index
        $('#ba_content > div:eq('+(activeIndex+d)+')').addClass('active');
        // set title
        $('#ba_wrapper > h2').text($('#ba_content div.active > h3').text());
        Cufon.replace('#ba_wrapper > h2',{
            hover:true,
            fontFamily: 'Bell MT'
        });
        // update ba_counter
        $('.ba_counter .current').text(activeIndex+d+1);
        Cufon.replace('.ba_counter',{
            hover:true,
            fontFamily: 'Corbel'
        });
        
        // recalculate
        activeIndex = $('#ba_content > div').index($('.active'));
        if(activeIndex < totalSlides-1) {
        	// remove right arrow
        	$('.arrow_right').show();
        } else {
        	$('.arrow_right').hide();
        }
        // remove left arrow
        if(activeIndex < 1) {
        	$('.arrow_left').hide();
        } else {
        	$('.arrow_left').show();
        }
        
        // change bg
        baChangebg($('.before','#ba_content .active').attr('href'));
    })
}
function baChangebg(url) {
    /*
     * This function changes the background for before & after after slider animation and on avant/apres click
    */

    // remove any active loader
    $('.loader').remove();
    // add loader
    $('#main').prepend('<div class="loader hide"></div>');
    // fadein loader
    $('.loader').fadeIn(150);
    //
    $('#background').append('<img src="'+url+'" />');
    $('#background img:last').one('load', function() {
        bg_resize();
        //
        $('#background img').not(':last').fadeOut(500,function(){
            $(this).remove()
        });
        // remove loader
        $('.loader').fadeOut(150,function(){
            $(this).remove()
        });
    }).each(function() {
        if(this.complete) $(this).load();
    });
}
function fullscreen() {
	$('.fullscreen').click(function(){
		if(!$(this).hasClass('fullscreen_active')) {
			// fade out main
			$('#main').stop(true,true).fadeOut(250);
			// collapse header
			$('#header_wrapper').stop(true,true).animate({
				top: 0 - $('#header_wrapper').height()
				}, 250);
			// collapse footer
			$('#footer_wrapper').stop(true,true).animate({
				bottom: 0 - $('#footer_wrapper').height()
				}, 250);
			// add fullscreen active class
			$(this).addClass('fullscreen_active').attr('title', translations['to_gallery']);
		} else {
			// fade in main
			$('#main').fadeIn(250);
			// show header
			$('#header_wrapper').animate({
				top: 0
				}, 250);
			// show footer
			$('#footer_wrapper').animate({
				bottom: 0
				}, 250);
			// remove fullscreen active class
			$(this).removeClass('fullscreen_active').attr('title', translations['view_fullsize']);
		}
	});
}

/* END OF BEYAZ JS */

