$(document).ready(function () {
    $('#load_content_0').css({'display':'none'});
    $('#load_content_1').css({'display':'none'});
    $('#page').css({'height':'300px'});

    Cufon.replace('#top ul li a', {hover: true});
    Cufon.replace('h1');

    // jquery events listen init
    events();
    dispatcher = new Dispatcher();
});


function set_page_height(frame, resize) {
    var docHeight = $(window).height();
    var page_height = Number(
            docHeight - $('#top').height() - $('#footer').height() - $('#footer_bar').height() - 58
        );

    var loaded_content_height = $('#load_content_'+frame).height();
    var animate_h_diff = 0;

    if(loaded_content_height< page_height) {
        animate_h_diff = page_height;
    } else {
        animate_h_diff = loaded_content_height;
    }


    if(typeof resize!='undefined') {
        $('#page').height(animate_h_diff);
        return;
    }

    $('#page').animate({
                height: animate_h_diff+'px',
            }, 300, function() {
        });
}

/**
 *  Jquery events bind
 */
function events() {
    $('a').live('click', function () {
            //alert($(this).attr('href').search('http://'))
        if($(this).attr('href').search('http://')!=-1) {
            $(this).attr('target', '_blank');
        } else {
            window.location.hash = $(this).attr('href');
            return false;
        }
    });


    $.address.change(function(event) {
        dispatcher.intercept()
    });
}

/**
 * dispatcher function
 * @use :  for loading javascript files in page
 * @is : constructor function for the dispache object
 * @param used_frame - keeps count of the used div for loading new page
 * @param loaded_elements - keeps track of loaded js files
 **/
function Dispatcher() {
    this.used_frame = 0;
    this.lock = 0;
    this.current_page = '';
    this.current_page_elem = '';
    this.url_params = [];
    this.js_load_script = '';
    this.loaded_elements = [];
    this.id_url_lnk =  {
        'index':'m1', 'about':'m2', 'portfolio':'m3', 'projects':'m4',
        'friends':'m5', 'blog':'m6', 'contact':'m7'
    };
}

/**
 *  Decides what to do with the clied link makes the ajax reqest
 *  and dispaches the jobs to other functions
 **/
Dispatcher.prototype.intercept = function () {
    this.menu_select();
    this.process_url();

    $.ajax({ url: this.current_page, context: '',
        success:function(result){
            if(dispatcher.used_frame==0) {
               var frame = 1
            } else {
               var frame = 0;
            }
            $('#load_content_'+frame).html(result);
            dispatcher.after_load_content();
            dispatcher.load_js_script()
        }
    });
}

/**
 *  * After loading new page fade in effect and switch between loaded divs
 **/
Dispatcher.prototype.after_load_content = function() {
    this.used_frame_old = dispatcher.used_frame;
    (dispatcher.used_frame==0) ? dispatcher.used_frame=1 : dispatcher.used_frame=0;

    $('#load_content_'+dispatcher.used_frame).fadeIn('slow', function () {
        $('#load_content_'+dispatcher.used_frame_old).css('display','none');
    })
    $('#load_content_'+dispatcher.used_frame).css('z-index', 4);
    $('#load_content_'+this.used_frame_old).css('z-index', 2);
    $('#load_content_'+this.used_frame_old).html('');
    var page_title = $('h1', $('#load_content_'+this.used_frame)).html().replace(/(<([^>]+)>)/ig,"");
    document.title = page_title;
}

/**
 * Top menu
 *
 */
Dispatcher.prototype.menu_select = function () {

    var parse_url = function (url) {
            url = url.split('.');
            var new_page = '';
            if(url[0]=='mainapp') {
                new_page = url[1];
            } else {
                new_page = url[0];
            }

            return dispatcher.id_url_lnk[new_page];
        };

    if(String(window.location).indexOf('#')==-1) {
       var new_active = String(window.location.pathname);
    } else {
       var new_active = String(window.location.hash).substring(1);
    }

    new_active = parse_url(this.process_url(new_active));
    var old_active = parse_url(this.current_page_elem);

    $('#'+new_active).css('color','red');
    $('#'+old_active).css('color','white');

    Cufon.replace('#top ul li a', {hover: true});
};

/**
 *    Check and load the script. If current page has been loaded access the init
 *    function and return (do not load content + script again)
 */
Dispatcher.prototype.load_js_script = function () {
    if(this.loaded_elements.indexOf(this.js_load_script)!=-1) {
        this.call_init(this.js_load_script);
    } else {
        this.loaded_elements.push(this.js_load_script);
        var js_load_script = this.js_load_script;

        // file exists disabled for static files so manually adding list
        var no_js = ['mainapp.contact', 'mainapp.friends', 'portfolio.project'];

        if(no_js.indexOf(js_load_script)==-1) {
            $.getScript('/media/js/'+js_load_script.replace('.', '/')+'.js', function() {
                    dispatcher.call_init(js_load_script);
                });
        } else {
            dispatcher.call_init(js_load_script);
        }
    }
}

/**
 *  Process url hash
 *  @description = Processes the url and sets the constructor variables
 *  @param return_url_elem = is sent when we want to get the link element withought setting variables
 *  @return = only if return_url_elem is set
 **/
Dispatcher.prototype.process_url = function (return_url_elem) {
    var main_controller = ['', 'about', 'contact', 'friends', 'projects'];

    if(typeof return_url_elem!='undefined') {
        var lscript = return_url_elem;
    } else {
        var lscript = String(window.location.hash.substring(1));
        if(String(window.location).indexOf('#')==-1) {
            lscript = String(window.location.pathname);
        }
    }


    lscript = lscript.replace(/\//g, ' ').trim().replace(/ /g, '.').split('.');

    // fix if url belongs to main controller add main as the first array element
    if(main_controller.indexOf(lscript[0])!=-1) {
        lscript.unshift('mainapp');
    }

    // fix for index page of controller
    if(lscript[1]=='' || typeof lscript[1]=='undefined') {
        lscript[1] = 'index';
    }

    if(typeof return_url_elem!='undefined') {
        return lscript[0]+'.'+lscript[1];
    }

    this.current_page_elem = lscript[0]+'.'+lscript[1];
    this.current_page = '/'+lscript[0]+'/'+lscript[1]+'/';


    // firx for blog since both pages will have only one category
    if(lscript[0]=='blog') {
        this.js_load_script = 'blog.main';
    } else {
        this.js_load_script = lscript[0]+'.'+lscript[1];
    }

    this.url_params = [];
    for(var i=2; i<lscript.length; i++) {
        this.url_params.push(lscript[i]);
        this.current_page += lscript[i]+'/';
    }

}

Dispatcher.prototype.call_init = function (function_name) {
    var function_name = function_name.replace('.', '_')+'_init';
    if(window[function_name]) {
        eval(function_name+'()');
    }
    set_page_height(this.used_frame);
}

$(window).resize(function() {
    set_page_height(dispatcher.used_frame, 1);
});

