// Setup jQuery Address Listener
    $.address.init(function(event) {
            if (location.href.indexOf('#') < 0) {
                // URL has no hash value and is a permalink, e.g. /about/
               
            }
            else{
            
            $.get($.address.value(),function(data) {
      		alias = location.href.replace(/http:\/\/www.rionefontana.com/i, '');
      		alias = alias.replace('/#/', '');
      		$.address.value(alias);
			changePage(alias);
            });
            }

    });


$(document).ready(function(){

var bgOffset;

orientationchange();
window.onorientationchange = orientationchange;
window.onresize = orientationchange;

if(navigator.userAgent.match(/iPad/i)) {

document.ontouchmove = function(e){
             e.preventDefault();
}
 

if ($('#videoHome').html()!='' && $('#videoHome').html()!=null){
	$('#videoHomeFlash').remove();
}

if ($('#flipCode').html()!='' && $('#flipCode').html()!=null){
	$('#flipFlash').remove();
}


}
else{
	if ($('#videoHome').html()!='' && $('#videoHome').html()!=null){
		$('#videoHomeHtml5').remove();
	}
	
	if ($('#flipCode').html()!='' && $('#flipCode').html()!=null){
		$('#flipCodeGallery').remove();
	}
}


$('#mainMenu LI A').live('click',
	    function() {
	        var alias = $(this).attr('href');
	        if(alias=='http://www.rionefontana.com/blog' || alias=='https://www.facebook.com/pages/Rione-Fontana/254990498878'){ window.open(alias,"_self"); return false;}
	        alias = alias.replace(/http:\/\/www.rionefontana.com/i, '');
			changePage(alias);
			$('#mainMenu li').removeClass('active');
			$('#bottomMenu li').removeClass('active');
			$(this).parent().addClass('active');
	        $.address.value(alias);
	        return false;
	    });
	    
$('#bottomMenu LI A').live('click', 
	    function() {
	        var alias = $(this).attr('href');
	        alias = alias.replace(/http:\/\/www.rionefontana.com/i, '');
			changeGallery(alias);
			$('#bottomMenu li').removeClass('active');
			$(this).parent().addClass('active');
	        $.address.value(alias);
	        return false;
	    });

if ($('#contentBox').html()!='' && $('#contentBox').html()!=null){

	$('#contentBox').animate({
			right: '0px'
		}, 500, 'easeInOutQuad');

} 
 
if ($('#galleryCode').html()!='' && $('#galleryCode').html()!=null){ 
 	$('#bottomMenu').animate({
				top: '0px'
			}, 400, 'easeInOutQuad');
}


setTimeout(function(){closeMenu()},1000);
startPageLoading();
setTimeout(function(){ stopPageLoading(); }, 1000);

});


function orientationchange() {
        if (window.orientation == 90
            || window.orientation == -90) {
            document.getElementById('main').className = 'landscape';
        }
        else {
            document.getElementById('main').className = 'portrait';
        }
        $('#main').height($(window).height());
		$('#main').width($(window).width());
    }


function openMenu(){
	$('#mainMenuLink').animate({
			left: '-40px'
		}, 200, 'easeInOutQuad', function() {
    	$('#mainMenu').animate({
			left: '0px'
		}, 400, 'easeInOutQuad');
 		 });
}

function closeMenu(){
	$('#mainMenu').animate({
			left: '-220px'
		}, 400, 'easeInOutQuad', function() {
    	$('#mainMenuLink').animate({
			left: '0px'
		}, 200, 'easeInOutQuad');
 		 });
}


function openContent(){

	$('#contentBoxLink').animate({
			right: '-40px'
		}, 200, 'easeInOutQuad', function() {
    	$('#contentBox').animate({
			right: '0px'
		}, 500, 'easeInOutQuad');
 		 });
 	
}

function closeContent(){

	$('#contentBox').animate({
			right: '-660px'
		}, 500, 'easeInOutQuad', function() {
    	$('#contentBoxLink').animate({
			right: '0px'
		}, 200, 'easeInOutQuad');
 		 });
 
}



function changePage(event){

var alias = event;
alias = ( alias != '' && alias.indexOf('.html') != '-1' ) ? alias : alias;	

            $.ajax({
                url: '/ajax-backend/get-page-from-alias.php?alias=' + alias ,
                dataType: 'json',
                success: function(data, textStatus, xhr) {
                    setPage(data, alias);
                }
            });


}


function changeGallery(event){

var alias = event;
alias = ( alias != '' && alias.indexOf('.html') != '-1' ) ? alias : alias;	

            $.ajax({
                url: '/ajax-backend/get-page-from-alias.php?alias=' + alias ,
                dataType: 'json',
                success: function(data, textStatus, xhr) {
                    setPage(data, alias);
                }
            });


}

function setPage(data, alias){
		
		// Page title
		$.address.title(data.pagetitle);
		
		// Google Analytics tracking
		//trackPage( '/' + alias );
		
		// Background image
		background = data.customBackground;
		
		startPageLoading();
		
		if(background!=''){
		
		
		
		loadBackground(background,function() {
				resetFlip(data.templateId);
				showBackground(data.templateId,500, function(){
					changeContent(data);
				});
		});
		
		}
		else{
				changeContent(data);
		}
		
		
    }
    
    function changeContent(data){
    	
    	/*
    	1 BaseTemplate
    	2 ContentTemplate
    	3 GalleryTemplate
    	4 ListGalleryTemplate
    	5 HomeTemplate
    	6 FlipTemplate
    	*/
    	
    	
    	if(data.templateId==2){
    		resetPanels(data.templateId,function() {
    			if(data.content!=''){
					$('#contentBox').html(data.content);
					
				
       				$('#contentBox').animate({
							right: '0px'
						}, 500, 'easeInOutQuad',function() {
       					resetContents(data.templateId);
       				});
       				
 				}
    		});
    	}
    	else if(data.templateId==3){
    		resetPanels(data.templateId,function() {
    		if($('#galleryCode').html()!='' && $('#galleryCode').html()!=null){
    				$('#supersized').remove();
    				$('#galleryCode').remove();
        		}
        		
    			$('#main').append(data.content); 
    			
    			$('#galleryCode').delay('500').animate({
            		height: '100%'
        		},
       			1000, 'easeInOutQuad', function() {
       				deleteBackground(500);
       				resetContents(data.templateId);
       			});
    		});
    	}
    	else if(data.templateId==4){
    		resetPanels(data.templateId,function() {
    			$('#bottomMenu').animate({
					top: '0px'
				}, 400, 'easeInOutQuad', function() {
				resetContents(data.templateId);
				});
    		});
    	}
    	else if(data.templateId==5){
    	$("#backstretch").css('z-index','100');
    		$('#main').append(data.content); 
    		
    		if(navigator.userAgent.match(/iPad/i)) {
    				$('#videoHomeFlash').remove();
				}
				else{
					$('#videoHomeHtml5').remove();
				}
    		
    		
    		resetPanels(data.templateId,function() {
    			deleteBackground(500);
    			resetContents(data.templateId);
    			stopPageLoading();
    			
    		});
    	}
    	else if(data.templateId==6){
    		resetPanels(data.templateId,function() {
    			$('#main').append(data.content); 
    			
    			if(navigator.userAgent.match(/iPad/i)) {
    				$('#flipFlash').remove();
				}
				else{
					$('#flipCodeGallery').remove();
				}
    			
    			
    			$('#flipCode').delay('500').animate({
            		height: '100%'
        		},
       			1000, 'easeInOutQuad', function() {
       			resetContents(data.templateId);
       			});
    		});
    	}
    }
    
    
    function resetPanels(type,callback){
    	
    	//reset
		if($('#bottomMenu').css('top')=="0px" && type!=3 && type!=4){
			$('#bottomMenu').animate({
				top: '-45px'
			}, 400, 'easeInOutQuad', function() {
			});
		}

		if($('#bottomMenuLinks').css('top')=="0px" && type!=3){
			$('#bottomMenuLinks').animate({
				top: '-45px'
			}, 400, 'easeInOutQuad', function() {
			});
		}
		
		if($('#mainMenu').css('left')=="0px"){
			closeMenu();
		}
		
		if($('#contentBoxLink').css('right')=="0px"){
			$('#contentBoxLink').animate({
				right: '-40px'
			}, 400, 'easeInOutQuad', function() {
			});
		}
		

		if($('#contentBox').css('right')=="0px"){
			$('#contentBox').animate({
				right: '-660px'
			}, 500, 'easeInOutQuad', function() {
			});
		}
		
		setTimeout(function(){callback();},500);
		
    }
    
    function resetContents(type){
    	if(type!=5) $('#videoHome').remove();
		if(type!=3) $('#galleryCode').remove();
		if(type!=3) $('#supersized').remove();
		if(type!=6) $('#flipCode').remove();
		if(type!=6) $('.flippage').remove();
    }
    
    function resetFlip(type){
		if(type!=6) $('#flipCode').remove();
		if(type!=6) $('.flippage').remove();
    }
    
    
    function showBackground(templateId,delay,callback) {

        var modulus = ($(".bg-mask img").height() % 2);
        var offset = (modulus != 0) ? 0: 1;

        mask.delay(delay).animate({
            height: '100%'
        },
        700, 'easeInOutQuad',
        function() {
            mask.css({
                top: 0,
                left: 0,
                bottom: 'auto',
                width: 'auto',
                height: 'auto',
                zIndex: '-10'
            });
            $(".bg-mask img")
            .css({
                position: 'relative',
                top: ($.browser.webkit || ($.browser.msie && parseInt($.browser.version) < 9)) ? -Math.round(bgOffset) : -(bgOffset),
                bottom: 'auto'
            });
            $('#backstretch').remove();
            mask.attr('id', 'backstretch').removeClass('bg-mask');
            stopPageLoading();
            resetContents(templateId);
            callback();
        });
                
    }
    
    function deleteBackground(delay) {

        var modulus = ($(".bg-mask img").height() % 2);
        var offset = (modulus != 0) ? 0: 1;
		var mask = $("#backstretch");
		
        mask.delay(delay).animate({
            height: '0%'
        },
        700, 'easeInOutQuad',
        function() {
            mask.css({
                top: 0,
                left: 0,
                bottom: 'auto',
                width: 'auto',
                height: 'auto',
                zIndex: '0'
            });
            
            $('#backstretch').remove();
            stopPageLoading();
        });
    }
    
    
    function loadBackground(background, callback) {

        var bg = background;

        $to_remove = $('#backstretch > img');

        mask = $('<div class="bg-mask" />').css({
            width: '100%',
            height: 0,
            overflow: 'hidden',
            position: 'fixed',
            bottom: 0,
            zIndex: '0'
        }).prependTo($('body'));

        var img = $('<img />').css({
            position: 'absolute',
            bottom: 0,
            left: 0,
            zIndex: '0',
            display: 'block'
        })
        .bind("load",
        function(e) {
            $('#loading-page').css('z-index', '0').remove();
            if (typeof timer_page != 'undefined') clearTimeout(timer_page);
            var self = $(this);
            imgRatio = $(e.target).width() / $(e.target).height();

            	_adjustBG(function() {
                /*self.css({
					top: 'auto',
					position: 'absolute'
				});*/

            });
        })
        .appendTo(mask);
        img.attr("src", bg);
        // Hack for IE img onload event
        $(window).resize(_adjustBG());

        checkSize = setInterval(function() {

            var agent = navigator.userAgent.toLowerCase();
            var is_iphone = (agent.indexOf('iphone') != -1);
            var is_ipad = (agent.indexOf('ipad') != -1);

            if (is_iphone || is_ipad) {

                if (img.width() == parseInt(img.css('width'))) {
                    clearInterval(checkSize);
                    callback();
                }

            } else {

                if (img.width() >= mask.width()) {
                    clearInterval(checkSize);
                    callback();
                }

            }

        },
        10);

    }
    
    
    function _adjustBG(fn) {
    
    	rootElement = ("onorientationchange" in window) ? $(document) : $(window);
    
        try {
            bgCSS = {
                left: 0,
                top: 0
            }
            bgCSSMask = {
                left: 0,
                top: 0
            }
            bgWidth = rootElement.width();
            bgHeight = bgWidth / imgRatio;

            // Make adjustments based on image ratio
            // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
            if (bgHeight >= rootElement.height()) {
                bgOffset = (bgHeight - rootElement.height()) / 2;
                bgCSS = {
                    top: "-" + bgOffset + "px"
                };
                bgCSSMask = {
                    bottom: "-" + bgOffset + "px"
                };
            } else {
                bgHeight = rootElement.height();
                bgWidth = bgHeight * imgRatio;
                bgOffset = (bgWidth - rootElement.width()) / 2;
                bgCSS = {
                    left: "-" + bgOffset + "px"
                };
                bgCSSMask = {
                    left: "-" + bgOffset + "px"
                };
            }
            if ($(".bg-mask").length == 0) $("#backstretch img").width(bgWidth).height(bgHeight).css(bgCSS);
            if ($(".bg-mask").length > 0) $(".bg-mask img").width(bgWidth).height(bgHeight).css(bgCSSMask);
        } catch(err) {
            // IE7 seems to trigger _adjustBG before the image is loaded.
            // This try/catch block is a hack to let it fail gracefully.
            }

        // Executed the passed in function, if necessary
        if (typeof fn == "function") fn();
    }
    
	function startPageLoading() {

        
        $('<div id="overlay-loading" style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:100000;" />').css('opacity', 0).appendTo($('body'));

        
        $('<div id="loading-page" />').css({
            position: 'absolute',
            top: (($(window).height() - 80) / 2) - 20,
            left: ($(window).width() / 2) - 20,
            width: 40,
            height: 40,
            backgroundImage: "url('/assets/images/loading-page.png')",
            zIndex: 2
        })
        .appendTo($('body'));

        position_page = 1;
       setTimeout(function(){ changeLoader(); }, 200);

    }
    
    function stopPageLoading(){
    	$('#overlay-loading, #loading-page').remove();
    }
    
    function changeLoader(){
       
        if (position_page == 5) {
            $('#loading-page').css('background-position', '0 0');
            position_page = 1;
        } else {
            $('#loading-page').css('background-position', '0 ' + -position_page * 40 + 'px');
            position_page++;
        }
        
        setTimeout(function(){ changeLoader(); }, 200);
        
       }
    
    
    
