var HTTP_ADDRESS='http://www.chateaudax.it';
/**
 * Created by JetBrains PhpStorm.
 * User: Cristi
 * Date: 09.03.2011
 * Time: 12:44
 */
jQuery.fx.interval = 150;


var imagesCDNBaseAddress = 'http://chateau.faromedia.it';
var minimumWidth = 600;
var minimumHeight = 320;
var stripeRatio = 0.45;
var pageTransition = 4000;
var customPageDefinedFunction = null;
var slideshowItems = null;
var slideshowIndex = null;
var slideshowTimeoutHandler = null;
var bgImageTimeoutHandler = null;
var howToUseMessage = null;
var currentResolutionX = 0;
var currentResolutionY = 0;
var requestsHistory = new Array();
var loadJustContentFromAjax = false;
var displayConsole = false;
var consoleHistory = new Array();

function debug(message){
    if(displayConsole){
        var consoleWrapper = $('#customConsole');
        if(!consoleWrapper.length){
            $('body').append('<div id="customConsole" style="background: white; max-height: 300px; overflow: scroll; padding: 10px;position: absolute; top:10px; left:20px; z-index: 5000"></div>');
            consoleWrapper = $('#customConsole');
            if(consoleHistory.length){
                for(msg in consoleHistory){
                    consoleWrapper.append('<p>'+msg+'</p>');
                }
            }
        }
        consoleWrapper.append('<p>'+message+'</p>');
    }
    //console.log(message);
}

$(function() {
    initHashOpen();
    //run();

    $(document).keydown(function(event) {
        if(jQuery.inArray(event.keyCode, [37, 38, 39, 40]) >=0){
            event.preventDefault();
            switch (event.keyCode) {
                case 37:
                    //left
                    if($('div.slider.left').length && $('div.slider.left').is(':visible')){$('div.slider.left').click();}
                break;
                case 38:
                    //up
                    if($('a.drillDownContent').length && $('div.textwrapper').is(':visible')){
                        hideContentTextInPage();
                    }else{
                        if(!$('div.textwrapper').is(':visible') && $('a.thumbController').length){
                            $('a.thumbController').click();
                        }
                    }
                break;
                case 39:
                    //right
                    if($('div.slider.right').length && $('div.slider.right').is(':visible')){$('div.slider.right').click();}
                break;
                case 40:
                    //down
                    if($('a.thumbController').length && $('.thumbnails').is(':visible')){
                        $('a.thumbController').click();
                    }else{
                        if($('a.drillDownContent').is(':visible')){
                            $('a.drillDownContent').click();
                        }
                    }
                break;
            }
        }
    });
});


function loadAjaxPageByUrl(pageUrl, justContent){
    var ajaxData = '';
    var trackUrl = pageUrl;
    if(trackUrl.indexOf('?')>0){
        trackUrl = trackUrl.substring(0, trackUrl.indexOf('?'));
    }
    trackUrl = trackUrl.replace(HTTP_ADDRESS, '');
    _gaq.push(['_trackPageview', trackUrl]);

    $.ajax({
        url: pageUrl,
        type:'POST',
        success: function(data, textStatus, jqXHR) {
            ajaxData = data;

            if(!justContent){
                $('body').find('*:not(#videoHome)').animate({
                    opacity: 0
                }, pageTransition / 4, 'jswing', function() {
                    $(this).remove();
                });

                if (ajaxData.length) {
                    customPageDefinedFunction = null;
                    $('body').empty();
                    $('body').html(ajaxData);
                    hidePageContentAtLoad();
                    requestsHistory.push({type:'page', url:pageUrl});
                    run();
                }
            }else{
                if (ajaxData.length) {
                    var newContent = $(ajaxData);
                    if(newContent.find('#content')){
                        customPageDefinedFunction = null;
                        $('body').find('#content').empty();
                        $('body').find('#content').html(newContent.find('#content').html());
                        hidePageContentAtLoad();
                        requestsHistory.push({type:'semipage', url:pageUrl});
                        rebuildPageContent();
                    }
                }
            }
        }
    });
}

function run() {
    initResizing();
    initBackground();
    initMenu();
    initControllers();
    initHandles();
    initSlideshows();
    //initSliders();
    preloadImages();
    initPageTransitions($('a'));
    if ($('#videoWrapper').length) {
        $('#videoWrapper:not(#content #videoWrapper)').css('margin-top', parseInt(($(window).height() - $('#videoHome').height()) / 2)-20);
        setTimeout('initHomePageVideo()', 1500);
    }
    if ($.isFunction(customPageDefinedFunction)) {
        customPageDefinedFunction();
    }
}

function rebuildPageContent(){
    initSlideshows(true);
    resizeContent();
    initPageTransitions($('#content a'));
    if ($.isFunction(customPageDefinedFunction)) {
        debug('is function');
        customPageDefinedFunction();
    }else{
        //ugly fix for ajax loaded pages from where we extract just the $(#content).html() and can not evaluate the customPageDefinedFunction
        var content__ = $('.textwrapper').find('.txtScroll');
        if(parseInt($('.textwrapper').height())>200 && content__.length){
            content__.height(200).width($('.textwrapper').width()-20).jScrollPane({animateScroll: true});
        }
    }
}

function initHashOpen() {
    $(window).hashchange(function () {
        var justCtnt = loadJustContentFromAjax;
        loadJustContentFromAjax = false;
        loadAjaxPageByUrl(HTTP_ADDRESS+getCurrentPage(), justCtnt);
    });

    var url = HTTP_ADDRESS + getCurrentPage();
    if(getCurrentPage().length>5){
        url += '/res/'+saveBrowserResolution(true);
    }else{
        saveBrowserResolution();
    }

    url+='?rand='+(new Date())+Math.random();
    $.ajax({
        url: url,
        type:'POST',
        success: function(data, textStatus, jqXHR) {
            customPageDefinedFunction = null;
            $('body').empty();
            $('body').html(data);
            hidePageContentAtLoad();
            requestsHistory.push({type:'page', url:url});
            run();
        },
        async:   false
    });
}

function getCurrentPage(){
    if (!window.location.hash.length){
        var currentPage = window.location.href.replace(HTTP_ADDRESS,'');
        if(currentPage.length>2){
            window.location = HTTP_ADDRESS+'/#'+currentPage;
        }else{
            window.location.hash = '/';
        }

    }

    return window.location.hash.replace('#', '');
}

function initBackground() {
    if(!$('#backgroundImage').length)
        return false;

    var pageBg = $('#realBody').css('backgroundColor');
    $('body').css({backgroundColor:pageBg});
    $('#realBody').css({'background':'url('+HTTP_ADDRESS+'/images/loading2.gif) center center no-repeat'});


    var image = new Image();
    var position = 'center';

    //change image bg src and preload image first;
    var imageSrc = $('#backgroundImage').attr('src');
    $('#backgroundImage').attr('src',HTTP_ADDRESS+'/images/spacer.gif').attr('alt', imageSrc);

    if($('#backgroundImage').attr('class').length){
        position = $('#backgroundImage').attr('class').replace('imagePosition_', '');
    }
    image.onload = function() {
        $('#realBody').css({'background':'none'});
        $('#backgroundImage').attr('src',imageSrc).attr('alt', '');
        var FullscreenrOptions = {
            width: image.width,
            height: image.height,
            bgID: '#backgroundImage',
            position: position
        };
        $.fn.fullscreenr(FullscreenrOptions);
    }
    image.src = imageSrc;
}

function initResizing() {
    hidePage();
    resizeContent(loadPage());

    $(window).resize(function() {
        resizeContent(false);
        saveBrowserResolution()
    });
}

function initMenu() {
    if ($('#bottomMenu').length) {
        $('.submenu:not(.forceVisible)').hide();
        $('#bottomMenu li').hover(
                function () {
                    //for now do nothing.
                    return false;

                    var relMenu = $(this).find('a').attr('rel')
                    if (relMenu.length) {
                        $('.submenu.' + relMenu).parent().find('.submenu').hide();
                        $('.submenu.' + relMenu).show();
                        $('.submenu.' + relMenu).find('ul').each(function() {

                            var contentWidth = 0;
                            $(this).find('li').each(function() {
                                $(this).find('img').hide().fadeIn('slow');
                                contentWidth += $(this).width();
                            });
                            if (contentWidth > $(window).width()) {
                                activateSubmenuSlider($(this));
                            } else
                                deactivateSubmenuSlider($(this));
                        });
                    }
                },
                function() {
                    //for now do nothing.
                    return false;

                    var relMenu = $(this).find('a').attr('rel')
                    if (relMenu.length) {
                        var obj = $(this);
                        var timeout = setTimeout(function() {
                            var currentObj = $(this);
                            currentObj.find('img').fadeOut('slow', function() {
                                currentObj.hide()
                            });
                        }, 300);

                        $('.submenu.' + relMenu).hover(function() {
                            clearTimeout(timeout);
                        }, function () {
                            var currentObj = $(this);
                            currentObj.find('img').fadeOut('slow', function() {
                                currentObj.hide()
                            });
                        });
                    }
                });
    }
}

function activateSubmenuSlider(menu) {
    if (!menu.find('.scroll').length) {
        menu.prepend('<li class="scroll left">&nbsp;</li>');
        menu.append('<li class="scroll right">&nbsp;</li>');

        menu.find('.scroll').hover(
                function() {
                    var location = 0;
                    if ($(this).hasClass('right')) {
                        location = $(window).width() - menu.width();
                    }
                    menu.animate({
                        marginLeft: location
                    }, 2000);
                },
                function () {
                    menu.stop();
                });
    }
}

function deactivateSubmenuSlider(menu) {
    menu.find('.scroll').remove();
}

function resizeContent(callback) {
    var windowContainer = $('#realBody');
    if (!windowContainer.length)
        return;

    // set the window container to have the exact width and height as the window
    windowContainer.css('height', $(window).height() + 'px');
    windowContainer.css('width', $(window).width() + 'px');

    // check if the window container complies with the minimum/maximum values for width and height
    if (windowContainer.height() < minimumHeight || windowContainer.width() < minimumWidth) {
        // inform the user that his current window sucks!

        windowError('Your window is too small!<br/>Try running in full screen mode.');
    } else {
        hideWindowError();
        // proceed with the resizing

        var menuHeight = parseInt($('#bottomMenu').height()+$('underTheBottomMenu').height());
        var content = $('#content');
        var strip = content.find('.strip');
        var thumbnails = content.find('.thumbnails');
        var showcase = content.find('.showcase');
//        var initialShowcaseHeight = showcase.height();
        var sliders = content.find('.slider');

        content.css('height', (windowContainer.height() - menuHeight) + 'px');
        content.css('width', windowContainer.width() + 'px');

        if(content.find('.contentText').length && content.find('.contentText').hasClass('centered')){
            var textContent = content.find('.contentText');
            var mTop = parseInt((parseInt(content.height())-parseInt(textContent.height()))/2);
            if(mTop<0){
                mTop = 10;
            }

            var mLeft = parseInt((parseInt(content.width())-parseInt(textContent.width()))/2);
            if(mLeft<0){
                mLeft = 10;
            }
            textContent.css({left:mLeft+'px', top:mTop+'px'});
        }

        if (strip.length) {
            //var newStripHeight = content.height() / 2 > 250 ? content.height() / 2 : 250;
            var newStripHeight = 354;

            strip.css('height', newStripHeight + 'px');
            strip.css('margin-top', ((content.height() - newStripHeight) * stripeRatio) + 'px');
            strip.css('width', content.width());
        }

        if (thumbnails.length) {
            thumbnails.css('width', content.width());
        }

        var thumbController = $('#bottomMenu').find('a.thumbController');
        thumbController.css('left', (parseInt($('#bottomMenu').width()-25)/2)+'px');

        if (sliders.length) {
            sliders.css('top', ((content.height() + menuHeight - sliders.height()) / 2) + 'px');
        }
        initControllers();
    }
    if ($.isFunction(callback))
        callback();
}

function windowError(text, callback) {
    hideWindowError();
    if (!$('#windowError').length) {
        $('body').append('<div id="windowError"><p>' + text + '</p></div>');
    }
    if ($.isFunction(callback))
        callback();
}

function hideWindowError() {
    if ($('#windowError').length)
        $('#windowError').remove();
}

function initControllers() {
    var content = $('#content');

    var showcase = $('.thumbnails').find('.showcase');
    var width = 0;
    var noOfItems;

    if (showcase.length) {
        noOfItems = showcase.find('.item').length;
        if (noOfItems) {
            showcase.find('.item').each(function() {
                width += $(this).width();
            });
            //add hovers
        }

        if (width > content.width()) {
            var controller = content.find('.controller');
            if(controller.length<2){
                content.prepend('<div class="controller right">&nbsp;</div><div class="controller left">&nbsp;</div>');
                controller = content.find('.controller');
                controller.filter('.left').width(0);
            }
            if(!$('.thumbnails').hasClass('swipeActivated')){
                $('.thumbnails').swipe({swipe:function(event, direction, distance){
                    var offset = 0;
                    var destination = 0;
                    var width = 0;
                    showcase.find('.item').each(function() {
                        width += parseInt($(this).width());
                    });
                    var contentWidth = content.width();
                    var multiply = distance/100;
                    if(multiply<1){
                        multiply = 1;
                    }

                    debug(direction+'__'+width+'/'+contentWidth);
                    if(direction=='left'){
                        offset = parseInt(showcase.css('marginLeft'));
                        destination = offset-(multiply*201);
                        if((destination+width)<contentWidth)
                            destination=parseInt(contentWidth-width);
                        showcase.animate({marginLeft: destination + 'px'}, 1000, 'jswing');
                    }else{
                        if(direction=='right'){
                            offset = parseInt(showcase.css('marginLeft'));
                            destination = offset+(multiply*201);
                            if(destination > 0){
                                destination = 0;
                            }
                            showcase.animate({marginLeft: destination + 'px'}, 1000, 'jswing');
                        }
                    }
                },threshold:50,fingers:1});
                $('.thumbnails').addClass('swipeActivated');
            }

            controller.each(function() {
                var thisController = $(this);
                var destination = 0;
                if (thisController.hasClass('right')) {
                    destination = parseInt(showcase.css('marginLeft')) - (width - (parseInt(showcase.css('marginLeft')) + content.width()));
                }

                thisController.hover(function() {
                    var delay = Math.abs(parseInt(showcase.css('marginLeft')));
                    if (thisController.hasClass('right'))
                        delay = Math.abs(destination);
                    delay *= 4;
                    showcase.animate({marginLeft: destination + 'px'}, delay, 'jswing',
                            function() {
                                //thisController.addClass('disabled').hide();
                                if(thisController.hasClass('left') && 0==parseInt(showcase.css('marginLeft'))){
                                    controller.filter('.left').width(0);
                                }else{
                                    controller.filter('.left').width(60);
                                }

                    });

                }, function() {
                    showcase.stop();
                    if(parseInt(showcase.css('marginLeft'))){
                        controller.filter('.left').width(60);
                    }else{
                        controller.filter('.left').width(0);
                    }
                });
            });
        } else {
            var controller = content.find('.controller');
            controller.remove();
        }
    }

    //move sensitive points
    var sensitivePoints = $('a.sesitive_point');
    if(sensitivePoints.length){
        var offset = $('#backgroundImage').offset();
        var offsetTop = parseInt(offset.top);
        var offsetLeft = parseInt(offset.left);
        sensitivePoints.each(function(){
            var location = $(this).attr('rel');
            if(location){
                location = location.split('x');
                location[0] -= 40;
                location[1] -= 35;
                $(this).css({
                    'left':(parseInt(location[0])+offsetLeft)+'px',
                    'top':(parseInt(location[1])+offsetTop)+'px'
                });
            }
        });
    }
}

function initContentSwipe(){
    $('#content').swipe({swipe: function(event, direction){
        if(direction=='left'){//go right
            if($('div.slider.right').length && $('div.slider.right').is(':visible')){$('div.slider.right').click();}
        }else{
            if(direction=='right'){//go left
                if($('div.slider.left').length && $('div.slider.left').is(':visible')){$('div.slider.left').click();}
            }else{
                if(direction=='up'){//go down
                    if($('a.drillDownContent').length && $('div.textwrapper').is(':visible')){
                        hideContentTextInPage();
                    }else{
                        if(!$('div.textwrapper').is(':visible') && $('a.thumbController').length){
                            $('a.thumbController').click();
                        }
                    }
                }else{
                    if(direction=='down'){//go up
                        if($('a.thumbController').length && $('.thumbnails').is(':visible')){
                            $('a.thumbController').click();
                        }else{
                            if($('a.drillDownContent').is(':visible')){
                                $('a.drillDownContent').click();
                            }
                        }
                    }
                }
            }
        }
    }, threshold:50, fingers:1});
}

function initHandles() {
    var handle = $('.handle');
    if (handle.length) {
        handle.find('a').click(function() {
            if (!$(this).hasClass('closed')) {
                $(this).parent().parent().animate({
                    marginBottom: -120
                }, 500);
                $(this).addClass('closed');
                $(this).find('img').attr('src', $(this).find('img').attr('src').replace('close.png', 'open.png'));
                $('.controller').hide();
            } else {
                $(this).parent().parent().animate({
                    marginBottom: 0
                }, 500);
                $(this).removeClass('closed');
                $(this).find('img').attr('src', $(this).find('img').attr('src').replace('open.png', 'close.png'));
                $('.controller').show();
            }
        });

        var ics;
        handle.hover(function() {
            ics = setInterval(function() {
                if (handle.find('a').hasClass('closed'))
                    handle.find('a').click();
            }, 666);
        }, function() {
            clearInterval(ics);
        });
    }
}

function initSlideshows(setFirstImageAfterLoad) {

        slideshowItems = new Array();
        var slideshowIndex = 0;
        var thumbnailControlls = false;

        if(getCurrentPage().length>1){
            var currentURL = getCurrentPage();
            $.getJSON(HTTP_ADDRESS + '/slideshow/get-images'+currentURL.replace('/slideshow/get-images', ''), function(data) {
                $.each(data, function(key, val) {
                    if(val.thumbImg!=undefined){
                        thumbnailControlls = true;
                    }
                    slideshowItems.push(val);
                });
                clearInterval(slideshowTimeoutHandler);
                slideshowIndex = 0;

                if(slideshowItems.length==1 && $('#backgroundImage').length){
                    if($('#backgroundImage').attr('src').indexOf(slideshowItems[0].img)>=0 || $('#backgroundImage').attr('alt').indexOf(slideshowItems[0].img)>=0){
                        slideshowItems = new Array();
                    }
                }

                if(slideshowItems.length){
                    $('.slider.right').show();

                    if(setFirstImageAfterLoad){
                        if(slideshowItems.length>1){
                            $('.slider.right').show();
                            $('.slider.left').hide();
                        }else{
                            $('.slider').hide();
                        }
                        //changeBackgroundImage(HTTP_ADDRESS + slideshowItems[slideshowIndex].img);
                        changeBackgroundImage(imagesCDNBaseAddress + slideshowItems[slideshowIndex].img);
                    }

                    initContentSwipe();

                    if(thumbnailControlls){
                        if(!$('.thumbnails').length){
                            $('<div class="thumbnails"><div class="showcase"></div></div>').insertAfter('#bottomMenu');
                            $('#bottomMenu').find('a.logo').before('<a class="thumbController" rel="opened" href="javascript:void(0)"><img alt="Chiudi" src="'+HTTP_ADDRESS+'/images/close.png" /></a>');
                            addListenersOnThumbsController($('#bottomMenu').find('.thumbController'));
                        }
                        $('#bottomMenu').css('bottom', '150px');
                        var thumbWrapper = $('.thumbnails .showcase');
                        thumbWrapper.find('*').remove();
                        thumbWrapper.html('');
                        var lastThumbUrl = '';
                        if(requestsHistory.length){
                            for(var x = requestsHistory.length-1;x>=0;x--){
                                if(requestsHistory[x].type=='thumbs'){
                                    lastThumbUrl = requestsHistory[x].url;
                                    break;
                                }
                            }

                        }else{
                            lastThumbUrl = getCurrentPage();
                        }
                        thumbWrapper.append('<div class="item active"><div class="focus"></div><a class="thumb" href="'+lastThumbUrl.replace(HTTP_ADDRESS, '')+'" rel="">&nbsp;</a><img alt="" src="'+HTTP_ADDRESS+'/images/backThumb.png"></div>');
                        $.each(slideshowItems, function(key, val) {
                            if(val.thumbImg!=undefined){
                                var class_name = 'notfocus';
                                var html = '<div class="item'+(class_name=='focus'?' active':'')+'"><div class="'+class_name+'">'+val.htmlTitle+'</div><a class="pseudoThumbnail" href="javascript:void(0)" rel="'+key+'">&nbsp;</a><img alt="'+val.htmlTitle+'" src="'+imagesCDNBaseAddress+val.thumbImg+'" /></div>';
                                thumbWrapper.append(html);
                            }
                        });
                        thumbWrapper.animate({marginLeft:0}, 1700);
                        thumbWrapper.find('a.thumb').hover(function(){
                                if(!$(this).parent().hasClass('active'))
                                    $(this).siblings('div').removeClass('notfocus').addClass('focus');
                            },function(){
                                if(!$(this).parent().hasClass('active'))
                                    $(this).siblings('div').removeClass('focus').addClass('notfocus');
                            }).click(function(e){
                                e.preventDefault();
                                getThumbnails($(this).attr('href'));
                        });
                        thumbWrapper.find('a.pseudoThumbnail').hover(function(){
                                if(!$(this).parent().hasClass('active'))
                                    $(this).siblings('div').removeClass('notfocus').addClass('focus');
                            },function(){
                                if(!$(this).parent().hasClass('active'))
                                    $(this).siblings('div').removeClass('focus').addClass('notfocus');
                            }).click(function(){
                                var idx = parseInt($(this).attr('rel'));
                                if(idx!=undefined && idx>=0 && idx<slideshowItems.length){
                                    slideshowIndex = idx;
                                    //changeBackgroundImage(HTTP_ADDRESS + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
//                                    debug('Schimb bg-ul cu '+imagesCDNBaseAddress + slideshowItems[slideshowIndex].img);
                                    changeBackgroundImage(imagesCDNBaseAddress + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
                                    if(slideshowItems[slideshowIndex].htmlContent!=undefined){
//                                        debug('Schimb si continutul cu '+slideshowItems[slideshowIndex].htmlTitle);
                                        setContentHtml(slideshowItems[slideshowIndex].htmlContent, slideshowItems[slideshowIndex].htmlTitle, slideshowItems[slideshowIndex].htmlSubTitle);
                                    }else{
//                                        debug('Nu am continut sa schimb');
                                    }
                                    $(this).parent().siblings('.active').removeClass('active').find('div').removeClass('focus').addClass('notfocus');
                                    $(this).parent().addClass('active');
                                    if (slideshowIndex == slideshowItems.length - 1) {
                                        $('.slider.right').addClass('disabled').hide();
                                        $('.slider.right').siblings('.slider').removeClass('disabled').show();
                                    }
                                    else{
                                        $('.slider').removeClass('disabled').show();
                                        if(slideshowIndex==0){
                                            $('.slider.left').addClass('disabled').hide();
                                            $('.slider.left').siblings('.slider').removeClass('disabled').show();
                                        }
                                    }
                                }
                        });
                        initControllers();
                    }

                    if($('.slider').length){
                        displayMessageHowToUse();
                        $('.slider').each(function() {
                            $(this).click(function() {
                                if($(this).hasClass('disabled'))
                                    $(this).hide();
                                hideContentTextInPage();
                                hideThumbs(true, function(){
                                    var objj = $('#bottomMenu').find('a.thumbController');
                                    objj.attr('rel', 'closed');
                                    objj.find('img').attr('src', objj.find('img').attr('src').replace('close.png', 'open.png'));
                                });
                                hideMessageHowToUse();

                                if ($(this).hasClass('left')) {
                                    slideshowIndex--;
                                    if (slideshowIndex < 0)
                                        slideshowIndex = 0;

                                    if (slideshowIndex >= slideshowItems.length)
                                        slideshowIndex = slideshowItems.length - 1;

                                    if (0 == slideshowIndex) {
                                        $(this).addClass('disabled').hide();
                                        $(this).siblings('.slider').removeClass('disabled').show();
                                    }
                                    else
                                        $('.slider').removeClass('disabled').show();
                                    //changeBackgroundImage(HTTP_ADDRESS + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
                                    changeBackgroundImage(imagesCDNBaseAddress + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
                                    if(slideshowItems[slideshowIndex].htmlContent!=undefined){
										debug('is not undefined');
                                        setContentHtml(slideshowItems[slideshowIndex].htmlContent, slideshowItems[slideshowIndex].htmlTitle, slideshowItems[slideshowIndex].htmlSubTitle);
                                        if($('a.pseudoThumbnail').length && slideshowItems[slideshowIndex].thumbImg){
                                            var currentThumbObj = $('a.pseudoThumbnail').filter('a[rel='+slideshowIndex+']');
                                            currentThumbObj.parent().siblings('.active').removeClass('active').find('div').removeClass('focus').addClass('notfocus');
                                            currentThumbObj.parent().addClass('active').find('div').removeClass('notfocus').addClass('focus');
                                        }
                                    }else{
										debug('is undefined');
                                        var tmp_index = slideshowIndex-1;
                                        while(tmp_index>=0){
                                            if(slideshowItems[tmp_index].htmlContent!=undefined){
                                                setContentHtml(slideshowItems[tmp_index].htmlContent, slideshowItems[tmp_index].htmlTitle, slideshowItems[tmp_index].htmlSubTitle);
                                                break;
                                            }else{
                                                tmp_index--;
                                            }
                                        }
                                    }
                                }
                                if ($(this).hasClass('right')) {
                                    slideshowIndex++;
                                    if (slideshowIndex < 0)
                                        slideshowIndex = 0;

                                    if (slideshowIndex > slideshowItems.length)
                                        slideshowIndex = slideshowItems.length;

                                    if (slideshowIndex == slideshowItems.length - 1) {
                                        $(this).addClass('disabled').hide();
                                        $(this).siblings('.slider').removeClass('disabled').show();
                                    }
                                    else
                                        $('.slider').removeClass('disabled').show();
                                    //changeBackgroundImage(HTTP_ADDRESS + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
                                    changeBackgroundImage(imagesCDNBaseAddress + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points);
                                    if(slideshowItems[slideshowIndex].htmlContent!=undefined){
                                        setContentHtml(slideshowItems[slideshowIndex].htmlContent, slideshowItems[slideshowIndex].htmlTitle, slideshowItems[slideshowIndex].htmlSubTitle);
                                        if($('a.pseudoThumbnail').length && slideshowItems[slideshowIndex].thumbImg){
                                            var currentThumbObj = $('a.pseudoThumbnail').filter('[rel='+slideshowIndex+']');
                                            currentThumbObj.parent().siblings('.active').removeClass('active').find('div').removeClass('focus').addClass('notfocus');
                                            currentThumbObj.parent().addClass('active').find('div').removeClass('notfocus').addClass('focus');
                                        }
                                    }
                                }
                            })
                        });
                    }else{
                        //play in slideshow
                        slideshowTimeoutHandler = setInterval(function(){
                            slideshowIndex++;
                            if (slideshowIndex >= slideshowItems.length)
                                slideshowIndex = 0;

                            if (slideshowIndex < 0)
                                slideshowIndex = 0;
                            if(slideshowItems[slideshowIndex]!=undefined){
                                //changeBackgroundImage(HTTP_ADDRESS + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points, 2000);
                                changeBackgroundImage(imagesCDNBaseAddress + slideshowItems[slideshowIndex].img, slideshowItems[slideshowIndex].points, 2000);
                            }
                        }, 7000);
                    }

                    $.each(slideshowItems, function(key, val) {
                        //preloadImgBySrc(HTTP_ADDRESS + val.img);
                        preloadImgBySrc(imagesCDNBaseAddress + val.img);
                    });
                }else{
                    $('.slider.right').hide();
                }
            });
        }
        //end get slideshow images
}

function setContentHtml(htmlContent, title, subtitle){
    if($('.textwrapper').length){
        $('.textwrapper').html(htmlContent);
        var content__ = $('.textwrapper').find('.txtScroll');
        if(parseInt($('.textwrapper').height())>200 && content__.length){
            content__.height(200).width($('.textwrapper').width()-20).jScrollPane({animateScroll: true});
        }
        if(title!=undefined){
            $('.textwrapper').siblings('h1').html(title);
        }
        if(subtitle!=undefined){
            $('.textwrapper').siblings('h2').html(subtitle);
            var eventName = title+'#'+subtitle;
            _gaq.push(['_trackEvent', eventName, 'loadContent']);
        }
    }
}


function hideContentTextInPage() {
    if ($('.textwrapper').is(':visible')) {
        $('.textwrapper').slideUp('slow', function() {
            var dropDownButton = $(this).siblings('a.drillDownContent').show()
            if(!dropDownButton.hasClass('triggerAdded')){
                dropDownButton.addClass('triggerAdded').click(function() {
                    $('.textwrapper').slideDown('slow', function(){
                        var paneData = $('.textwrapper').find('.txtScroll').data('jsp');
                        if(paneData!=undefined){
                            paneData.reinitialise();
                        }
                    });
                    $(this).hide();
                });
            }
        });
    }
}

function changeBackgroundImage(src, points, timeout) {
    if(timeout==undefined)
        timeout = 700;
    clearInterval(bgImageTimeoutHandler);
    $('a.sesitive_point').fadeOut('fast', function(){ $(this).remove(); });
    preloadImgBySrc(src, function(){
        $('#backgroundImage').stop().animate({opacity: 0}, 500, 'jswing', function() {
            $(this).attr('src', src);
            $(this).animate({
                opacity: 1
            }, timeout,'jswing',function(){
                bgImageTimeoutHandler = setInterval('zoomAndMovePicture()', 100);
                if(points != undefined && points.length){
                    var offsetTop = parseInt($(this).offset().top);
                    var offsetLeft = parseInt($(this).offset().left);
                    $.each(points, function(key, val){
                        if(val.x.length && val.y.length){
                            var ics = parseInt(val.x)+offsetLeft;
                            var igrec = parseInt(val.y)+offsetTop;
                            if(val.url.length==0)
                                val.url = '#';
                            else{
                                if(val.act=='thumb'){
                                    val.url = '#'+val.url;
                                }
                            }
                            var htmlCode = '<a class="sesitive_point '+val.act+'" rel="'+val.x+'x'+val.y+'" href="'+val.url+'" title="'+val.des+'" style="left:'+ics+'px;top:'+igrec+'px">&nbsp;</a>';
                            $(htmlCode).appendTo('#realBody');
                        }
                    });
                    showSensitivePoints();
                }
            });
        });
    });
}

function showSensitivePoints(){
    $('a.sesitive_point').fadeIn('fast', function(){
        $('a.sesitive_point').each(function(){
            if($(this).hasClass('thumb')){
                $(this).click(function(e){
                    e.preventDefault();
                    var url = $(this).attr('href');
                    getThumbnails(url);
                });
            }else{
                if($(this).hasClass('page')){
                    initPageTransitions($(this));
                }
            }
        }).qtip({position:{my:'left bottom'},style:{classes:'ui-tooltip-dark ui-tooltip-shadow ui-tooltip-rounded'}});
    });
}

function getThumbnails(url, callback){
    var ajaxurl = HTTP_ADDRESS + '/slideshow/get-thumbnails'+url.replace('#', '').replace('/slideshow/get-thumbnails', '');
    $.getJSON(ajaxurl, function(data) {
        if(data.length){
            requestsHistory.push({type:'thumbs', url:ajaxurl});
            $('.submenu').remove();
            if(!$('.thumbnails').length)
                $('<div class="thumbnails"><div class="showcase"></div></div>').insertAfter('#bottomMenu');

            var thumbWrapper = $('.thumbnails .showcase');
            thumbWrapper.parent().hide();
            thumbWrapper.find('*').remove();
            thumbWrapper.html('');
            $.each(data, function(key, val) {
                var class_name = 'notfocus';
                var linkClass = ' thumbImage justContent';
                if(val.act==getCurrentPage()){
                    class_name = 'focus';
                }
                if(val.hasChildren){
                    linkClass = '';
                }
                if(val.type=='button'){
                    linkClass = ' thumbImage';
                }
                var imageSrc = val.img;
                if(imageSrc.indexOf('backThumb.png')>=0){
                    imageSrc = HTTP_ADDRESS+imageSrc;
                }else{
                    imageSrc = imagesCDNBaseAddress+imageSrc;
                }
                var html = '<div class="item'+(class_name=='focus'?' active':'')+'"><div class="'+class_name+'">'+val.title+'</div><a class="thumb'+linkClass+'" href="'+HTTP_ADDRESS+val.act+'" rel="">&nbsp;</a> <img alt="'+val.title+'" src="'+imageSrc+'" /></div>';
                thumbWrapper.append(html);
                //preloadImgBySrc(HTTP_ADDRESS+val.img);
                preloadImgBySrc(imagesCDNBaseAddress+val.img);
            });
            thumbWrapper.animate({marginLeft:0}, 1700);
            showThumbs(true, function(){
                initThumbs();
                initPageTransitions($('.thumbnails').find('a'));
                if ($.isFunction(callback))
                    callback();
            });
        }
    });
}

function showThumbs(withMenu, callback){
    if(withMenu){
        $('#bottomMenu').animate({
            bottom: '150'
        }, 1000, function() {
            $('.thumbnails').fadeIn(1000);
            if($('.controller').length){
                $('.controller').height(120);
            }
            if ($.isFunction(callback))
                callback();
        });
    }
}

function hideThumbs(withMenu, callback){
    var thumbWrapper = $('.thumbnails');
    if(thumbWrapper.length && thumbWrapper.is(':visible')){
        thumbWrapper.fadeOut('slow', function(){
            if(withMenu){
                $('#bottomMenu').animate({bottom: '30'}, 900, function() {
/*                    if($('#bottomMenu').find('.thumbController').length){
                        var c_img = $('#bottomMenu').find('.thumbController').find('img');
                        c_img.attr('src', c_img.attr('src').replace('close.png', 'open.png'));
                        $('#bottomMenu').find('.thumbController').attr('rel', 'closed');
                    }*/
                    if($('.controller').length){
                        $('.controller').height(0);
                    }
                    if ($.isFunction(callback))
                        callback();
                });
            }
        });
    }
}

function initThumbs(){
    $('.thumbnails .thumb').hover(function(){
        if(!$(this).parent().hasClass('active'))
            $(this).siblings('div').removeClass('notfocus').addClass('focus');
    },function(){
        if(!$(this).parent().hasClass('active'))
            $(this).siblings('div').removeClass('focus').addClass('notfocus');
    }).click(function(){
            if($(this).hasClass('thumbImage') && $(this).hasClass('justContent')){
                $(this).parent().siblings('.active').removeClass('active').find('div').removeClass('focus').addClass('notfocus');
                $(this).parent().addClass('active');
            }
    });
//    $('#bottomMenu').find('a.thumbController').remove();
    if(!$('#bottomMenu').find('a.thumbController').length){
        $('#bottomMenu').find('a.logo').before('<a class="thumbController" rel="opened" href="javascript:void(0)"><img alt="Chiudi" src="'+HTTP_ADDRESS+'/images/close.png" /></a>');
        var thumbController = $('#bottomMenu').find('.thumbController');
        addListenersOnThumbsController(thumbController);
    }
    initControllers();
}

function addListenersOnThumbsController(obj){
        var menuWidth = parseInt($('#bottomMenu').width());
        var mLeft = parseInt((menuWidth-parseInt(obj.width()))/2);
        obj.css('left', mLeft+'px');

        obj.click(function(){
            var c_img = $(this).find('img');
            var objj = $(this);
            if($(this).attr('rel')=='closed'){
                showThumbs(true, function(){
                    objj.attr('rel', 'opened');
                    c_img.attr('src', c_img.attr('src').replace('open.png', 'close.png'));
                });

            }else{
                if($(this).attr('rel')=='opened'){
                    hideThumbs(true, function(){
                        objj.attr('rel', 'closed');
                        c_img.attr('src', c_img.attr('src').replace('close.png', 'open.png'));
                    });
                }
            }
        });
}

function zoomAndMovePicture(){
    return;
    var img = $('#backgroundImage');
    var offsetTop = parseInt(img.offset().top);
    var offsetLeft = parseInt(img.offset().left);
    var width = parseFloat(img.width());
    var height = parseFloat(img.height());
    var ratio = width/height;
    width += 0.3;
    height = width/ratio;
    console.debug(width+' X '+height);
    img.css({
        'width':(width)+'px',
        'height':(height)+'px'
    });
}

function preloadImages() {
    var images = $('.thumbnails .thumb');
    images.each(function() {
        var currentImage = $(this).attr('rel');
        preloadImgBySrc(currentImage);
    });
}

function preloadImgBySrc(src, callback) {
    var image = new Image()
    image.onload = function() {
        if ($.isFunction(callback))
            callback();
    }
    image.src = src
}

function initPageTransitions(objs) {
    objs.click(function(evv) {
            if ($(this).attr('href').indexOf(HTTP_ADDRESS) >= 0 && !$(this).hasClass('literal')) {
                evv.preventDefault();
                if($(this).hasClass('clicked')){
                    return false;
                }
                //$(this).addClass('clicked');

                if($(this).hasClass('thumb') && !$(this).hasClass('thumbImage')){
                    getThumbnails($(this).attr('href').replace(HTTP_ADDRESS, ''));
                    return false;
                }
                if($(this).hasClass('justContent')){
                    loadJustContentFromAjax = true;
                }


                var goToUrl = $(this).attr('href').replace(HTTP_ADDRESS, '');
                if(window.location.hash==goToUrl || window.location.hash=='#'+goToUrl){
                    loadAjaxPageByUrl($(this).attr('href')+'?cache='+(new Date()), $(this).hasClass('justContent'));
                }else{
                    window.location.hash = goToUrl;
                }
                return false;
            }else{
                return true;
            }
    });
}

function hidePageContentAtLoad(){
    if($('.textwrapper').hasClass('leaveOpen'))
        return;

    var dropDownButton = $('.textwrapper').hide().addClass('hidden').siblings('a.drillDownContent').removeClass('hidden').show()
    if(!dropDownButton.hasClass('triggerAdded')){
        dropDownButton.addClass('triggerAdded').click(function() {
            $('.textwrapper').removeClass('hidden').slideDown('slow', function(){
                var paneData = $('.textwrapper').find('.txtScroll').data('jsp');
                if(paneData!=undefined){
                    paneData.reinitialise();
                }
            });
            $(this).hide();
        });
    }
}


function displayMessageHowToUse(){
    if(!howToUseMessage){
        $('body').append('<div id="howToUseMessage">&nbsp;</div>');
        $('#howToUseMessage').show('slow');
        howToUseMessage = true;
    }
}

function hideMessageHowToUse(){
    if(howToUseMessage && $('#howToUseMessage').length){
        $('#howToUseMessage').show('slow', function(){
            $('#howToUseMessage').remove();
        });
    }
}

function saveBrowserResolution(returnVal){
    var res_x = $(window).width();
    var res_y = $(window).height();
    var resol = res_x+'x'+res_y;
    if(returnVal!=undefined && returnVal){
        return resol;
    }
    if(Math.abs(res_x-currentResolutionX)>50 || Math.abs(res_y-currentResolutionY)>40){
        currentResolutionX = res_x;
        currentResolutionY = res_y;
        $.ajax({
            url: HTTP_ADDRESS+'/slideshow/set-resolution/res/'+resol,
            success: function(data) {},
            async:   false
        });
        testInternetSpeedAndSetPreferences();
    }
    return true;
}

function testInternetSpeedAndSetPreferences(){
    return;
    var startDate = new Date();
    var t1 = startDate.getTime();
    $.get(HTTP_ADDRESS+'/internetspeed.file?date'+startDate, function(){
        var responseTime = new Date();
        var t2 = responseTime.getTime();

        var diff = (t2-t1)/1000;
        $.get(HTTP_ADDRESS+'/slideshow/set-internet-speed/speed/'+diff);
    });
}


function hidePage() {
    $('body').find('*').hide();
}

function loadPage() {
    $('body').find('*:not(.hidden,.disabled)').fadeIn(pageTransition / 2);
}var globalVariableToSeeIfIETriggers = false;

function initHomePageVideo() {
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
		$('#videoWrapper').html('<iframe title="YouTube video player" width="622" height="350" src="https://www.youtube.com/embed/6GWmuK-LzOg" frameborder="0" allowfullscreen></iframe>');

        if(getCurrentPage().length>5){
            return false;
        }
        $('#videoWrapper').css('margin-top', (($(window).height() - $('#videoWrapper').height()) - 50) / 2);
		$('body').find('a.skipintro').remove();
		$('body').append('<a class="skipintro" href="' + HTTP_ADDRESS + '/pagina/index.html">skip promo</a>');

		var mtop = parseInt($('#videoWrapper').offset().top + parseInt($('#videoWrapper').height()) + 10);
		var mleft = parseInt(parseInt($(window).width()) / 2) - 30;
		$('body').find('a.skipintro').css({'marginTop':mtop,'marginLeft':mleft}).show();
		initPageTransitions($('body').find('a.skipintro'));
	}else{
		if($('#videoWrapper').find('#videoHome').length){
            $('#videoWrapper').stop().css({opacity:1});
			jwplayer("videoHome").setup({
				flashplayer: HTTP_ADDRESS + "/player/player.swf",
				file:HTTP_ADDRESS + "/video/promo_february_2012.flv",
                image: HTTP_ADDRESS + '/images/previewImage.jpg',
				height: 351,
				width: 622,
				autostart: false,
				controlbar: 'none',
				events: {
					'onReady': function(callback) {
                        if(getCurrentPage().indexOf('intro')<0){
                            return false;
                        }

                        globalVariableToSeeIfIETriggers = true;

						$('#videoWrapper').stop().css({opacity:1});
                        //$('#videoWrapper').css('margin-top', (($(window).height() - $('#videoWrapper').height()) - 50) / 2);

                        //do not comment this line because it fixes the flash to center vertically in IE8
                        $('#videoWrapper:not(#content #videoWrapper)').css('margin-top', (($(window).height() - $('#videoHome').height()) - 50) / 2);
						$('body').find('a.skipintro').remove();
						$('body').append('<a class="skipintro" href="' + HTTP_ADDRESS + '/pagina/index.html">skip promo</a>');

						var mtop = parseInt($('#videoWrapper').offset().top + parseInt($('#videoWrapper').height()) + 10);
						var mleft = parseInt(parseInt($(window).width()) / 2) - 50;
						$('body').find('a.skipintro').css({'marginTop':mtop,'marginLeft':mleft}).show();
						initPageTransitions($('body').find('a.skipintro'));
					}
				}
			});
		}
	}

    setTimeout(function(){
        if(!globalVariableToSeeIfIETriggers){

            globalVariableToSeeIfIETriggers = true;

            $('#videoWrapper').stop().css({opacity:1});
                        //$('#videoWrapper').css('margin-top', (($(window).height() - $('#videoWrapper').height()) - 50) / 2);

            //do not comment this line because it fixes the flash to center vertically in IE8
            $('#videoWrapper:not(#content #videoWrapper)').css('margin-top', (($(window).height() - $('#videoHome').height()) - 50) / 2);

            $('body').find('a.skipintro').remove();
            $('body').append('<a class="skipintro" href="' + HTTP_ADDRESS + '/pagina/index.html">skip promo</a>');

            var mtop = parseInt($('#videoWrapper').offset().top + parseInt($('#videoWrapper').height()) + 10);
            var mleft = parseInt(parseInt($(window).width()) / 2) - 50;
            $('body').find('a.skipintro').css({'marginTop':mtop,'marginLeft':mleft}).show();
            initPageTransitions($('body').find('a.skipintro'));
        }
    }, 2500);
}
