if(typeof console === "undefined") {
    console = { log: function() { } };
}

if(typeof fix === "undefined") {
    fix = function() { };
}

jQuery.fn.center = function () {
    this.css("top", "50%");
    this.css("left", "50%");
    this.css("margin-top", -(this.height() / 2) + "px");
    this.css("margin-left", -(this.width() / 2) + "px");
    return this;
};

jQuery.fn.center_x = function () {
    this.css("left", "50%");
    this.css("margin-left", -(this.width() / 2) + "px");
    return this;
};

var historyObjects = new Object();

function setHistoryState(idx) {
    historyObjects[idx] = new Array();
    return historyObjects[idx];
}

function isHistoryBack () {
    return (historyObjects[history.length] != undefined);
}

function handleAjax(data, textStatus) {
    if (textStatus == 'success') {
        $.address.title(data.title + ' PANEANGELI');        
        var newHistory = setHistoryState(history.length);
        
        /*if (data.container_id == 'content') {
            newHistory.push({
                'container_id':data.container_id,
                'object_id':data.object_id,
                'content':$('#' + data.container_id).children()
            });                    
            
            $('#' + data.container_id).empty();
        }*/
        
        newHistory.push({
            'container_id':data.container_id,
            'object_id':data.object_id,
            'content':$('#' + data.object_id)
        });
        
        var toRemove = $('#' + data.object_id);
        
        // check expose
        try {
            var toRemoveExpose = toRemove.expose();
            if (toRemoveExpose.isLoaded()) {
                toRemoveExpose.close();
            }
        } catch (Error) {}
        
        toRemove.remove();
        
         var sidebarButtons = $('#' + data.container_id +' #sidebarButtons');
         if (sidebarButtons.length >0){
            $(data.html).insertAfter('#' + data.container_id+' #sidebarButtons');
         }  else {
            $('#' + data.container_id).prepend(data.html);   
         }    
        
               
        /*
        if (data.container_id != 'website') {
            $('.history_' + (history.length)).remove();
            $('#' + data.object_id).addClass('history_' + history.length);
        }   
        */
        
        if (data.immagine_dispensa) {
            var link = $('#recipe_image_dispensa');
            var img = $('#recipe_image_dispensa img');
            
            newHistory.push({
                'container_id':'dispensa',
                'object_id':'recipe_image_dispensa',
                'content':link
            });
            
            img.attr('src', data.immagine_dispensa);
            img.attr('title', data.title);
            link.attr('href', $.address.value());
            fix(img);            
        }
        
        if (data.classe_dispensa) {
            $('#dispensa').removeClass().addClass(data.classe_dispensa);
        }
        
        if (data.popup_content) {
            $('#popup_area').removeClass('hide_intro').prepend(data.popup_content);
        }
            
        $('.popup').each( function() {
            var p = $(this);
            p.center();
            p.find('.popup_bottom').center_x();
            p.expose({
                api: true, 
                color: '#DAF4EE',
                closeOnClick: false,
                closeOnEsc: false,
                loadSpeed: 0,
                closeSpeed: 0
            }).load(); 
        });
        
        var close_text = "Chiudi";
        var close_href = '/';
        if (data.close_text) {
            close_text = data.close_text;
        }
        if (data.close_href) {
            close_href = data.close_href;
        }
        
	if ($.address.value() != '/') {
		$('.block_notes').append('<a href="' + close_href + '" class="block_notes_close">' + close_text + '</a>');
		
	}

        fix();
        
        if (data.redirect_to) {
            $.address.value(data.redirect_to);
        }
        else {
            $.scrollTo('#' + data.container_id);
        }
        
        checkCookie();        
    }
}

$.address.change(function(event) {
    if (isHistoryBack()) {
        var historyState = setHistoryState(history.length);
        for (var i=0; i < historyState.length; i++) {
            var toBeDeleted = $('#' + historyState[i].object_id).css('visibility', 'hidden');
            $('#' + historyState[i].container_id).prepend(historyState[i].content);
            toBeDeleted.remove();
            $.scrollTo('#' + historyState[i].container_id);
        }
    }
    
    var url = event.value;
    
    if (url == "sondaggio" || url == "glossario") {    
        return;    
    }
    
    $.ajax({
        cache: true,
        url: url,
        dataType: 'json',
        success: handleAjax
    });
    
    // $.getJSON(
    //         url,
    //         handleAjax
    //     );
});

function getHref(link) {
    return $(link).attr('href').replace($.address.baseURL(), '');
}

function closeMovie() {
    $('#popup_area').empty().removeClass('visible replay_intro');
    $('#website').fadeIn('fast');
}

function HideFlashIntro() {
    console.log('hide');
    //$('#popup_area').empty().removeClass('visible intro intro_jumping');
    $('#popup_area').css({'margin-top':'-5000px'});
    //$('#popup_area').removeClass('visible intro intro_jumping').addClass('hide_intro');
}

function jumpIntro() {
    console.log('jump');
    $('#website').css('display', 'block');
    $('#popup_area').removeClass('intro').addClass('intro_jumping');
}

function track(href) {
    try {
        pageTracker._trackPageview(href);
    } catch(Error){ console.log(Error);}
}

$(document).ready(function() {
    
    $('#replay_intro').live('click', function() {
        var website = $('#website');
        website.fadeOut('fast', function() {
            $('#popup_area').empty().removeClass('hide_intro').addClass('visible replay_intro');
            flashembed('popup_area', {
                'src':"/media/website/swf/anim_torte.swf",
                'width': '1000px',
                'height': '630px',
                'wmode': 'transparent'
            }); 
        });
        
        
        return false;
    });
    
    $('.main_typology_name').live('click', function() {
        return false; 
    });
    
    $('.tab_link').live('click', function() {
        $(this).parents('.tabs').find('.tab').removeClass('visible');
        var targetId = $(this).attr('href');
        targetId = targetId.substr(targetId.indexOf('#'));
        $(targetId).addClass('visible');
        return false; 
    });
    
    $('[rel^="rollover"]').live('mouseover', function() {
        try {
            var srcs = this.rel.split(':')[1].split('|');
            $(this).find('img').attr('src', srcs[1]);
            fix(this);
        } catch (err) {}
    });
    
    $('[rel^="rollover"]').live('mouseout', function() {
        try {
            var srcs = this.rel.split(':')[1].split('|');
            $(this).find('img').attr('src', srcs[0]);
            fix(this);
        } catch (err) {}
    });
    
    $('[rel="paginate"]').live('click', function() {  
        try {
            $.address.value($.address.path() + getHref(this));
            return false;
        } catch (err) {}
    });
    
    $('[rel^="close"]').live('click', function() {  
        try {
            var objToClose = $('#' + this.rel.split(':')[1]);
            if (objToClose.hasClass('popup')) {
                objToClose.expose({api: true}).close();
            }            
            objToClose.remove();
        } catch (err) {}
    });
    
    $('[rel^="close_no_ajax"]').live('click', function() {  
        try {
            var objToClose = $('#' + this.rel.split(':')[1]);
            
            if (objToClose.hasClass('popup')) {
                objToClose.expose({api: true}).close();
            }
            
            objToClose.remove();
            
            return false;
        } catch (err) {}
    });
    
    $('[rel^="back"]').live('click', function() {  
        try {
            history.back(-1);
            return false;
        } catch (err) {}
    });
    
    $('[rel^="close_and_back"]').live('click', function() {  
        try {
            var objToClose = $('#' + this.rel.split(':')[1]);
            
            if (objToClose.hasClass('popup')) {
                objToClose.expose({api: true}).close();
            }
            
            objToClose.remove();            
            history.back(-1);
            return false;
        } catch (err) {}
    });
    
    $('[rel="popup"]').live('click', function() {
        window.open(getHref(this), "popup", 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=400');
        return false;
    });
    
    $('[rel^="print"]').live('click', function() {
        window.open(getHref(this), "popup", 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=500');
        return false;
    });
    
    $('[rel="external_resource"]').live('click', function() {
        var href = getHref(this);
        track(href);
        window.open(href);
        return false;
    });
    
    $('a[rel!="no_ajax"]').live('click', function() {  
        $.address.value(getHref(this));
        return false;
    });
    
    $('.ajax_submit').live('click', function() {
        var theForm = $(this).parents('form');
        theForm.append('<div class="loading"></div>');
           
        theForm.ajaxSubmit({
           success: function(data, textStatus) {
               $('.loading').remove();
               //$.address.value(this.url);
               handleAjax(data, textStatus);
           },
           dataType: 'json'
       });
       return false;
    });
    
    $('input').live('keypress', function(e) {
        function isEnter(e) {
            if (null == e)
                e = window.event ;
            if (e.keyCode == 13)  {
                return true;
            }
            return false;
        }
        
        if (isEnter(e)) {
            var theForm = $(this).parents('form');
            theForm.addClass('loading');
                   
            theForm.ajaxSubmit({
               success: function(data, textStatus) {
                   $('.loading').removeClass('loading');
                   $.address.value(this.url);
                   handleAjax(data, textStatus);
               },
               dataType: 'json'
           });
            return false;
        }
    });
    
    $('.environment_link').live('mouseover', function() {
        $(this).next().show();
    });
    
    $('.environment_link').live('mouseout', function() {
        $(this).next().hide();
    });
});
