jQuery(function($) {

/*----------------------------------------
    * Global
----------------------------------------*/

    /**
    * @description
    * Ajax setups
    */
    $.ajaxSetup({
	url: '/ajax.php',
	global: false,
	type: 'POST',
    	timeout: 30000,
	error: function() {
	    fn.loading.stop();
	}
    });

    /**
    * @description
    * Global functions
    */
    var fn = {};

    /**
    * @description
    * Global variables
    */
    var global = {};

    /**
    * @description
    * Functions for global
    */
    fn.global = {
        get: function(variable) {
            return global[variable];
        },
        set: function(variable, value) {
            global[variable] = value;
        },
        random: function(min, max) {
            return(min+parseInt(Math.random()*(max-min+1)));
        }
    };

    /**
    * @description
    * Set timeout
    */
    fn.global.set('timeout', undefined);

/*----------------------------------------
    * Loading
----------------------------------------*/

    /**
    * @description
    * Functions for loading
    */
    fn.loading = {
        start: function() {
            $('#mainCont').empty().html('<div id="ctLoading"></div>');
            fn.loading.load(0);
        },
        load: function(percent) {
            if ($('#ctLoading').length == 1) {
                var timeout = fn.global.get('timeout');
                timeout = undefined;
                (timeout != undefined) ? clearTimeout(timeout) : '';
                timeout = setTimeout(function() {
                    fn.global.set('timeout', undefined);
                    $('#ctLoading').text(percent+' %');
                    percent += (percent <= 75) ? fn.global.random(5, 10) : Math.floor((100-percent)/2);
                    fn.loading.load(percent);
                }, fn.global.random(10, 100));
                fn.global.set('timeout', timeout);
            }
        },
        stop: function(callback) {
	    $('#ctLoading').text('100 %')
            clearTimeout(fn.global.get('timeout'));
	    setTimeout(function() {
		callback();
	    }, 250);
        }
    };

/*----------------------------------------
    * Address / Deep-Links
----------------------------------------*/

    var baseUrl = $.address.baseURL().replace(/http:\/\/+(.*?)/, '$1').split('/');

    baseUrl = 'http://'+baseUrl[0];

    /**
    * @description
    * Deeplink behaviour
    */
    $('.deepLink').address(function() {
        return $(this).attr('href').replace(baseUrl, '');
    });

    /**
    * @description
    * External address change behaviour
    */
    $.address.externalChange(function() {
        ($.address.path().replace('/', '') != '') ? self.location.href = $.address.path() : null;
    });

    /**
    * @description
    * Internal address change behaviour
    */
    $.address.internalChange(function() {
        ($.address.path().replace('/', '') != '') ? fn.page.get($.address.path()) : null;
    });

/*----------------------------------------
    * QucikInfo
----------------------------------------*/

    /**
    * @description
    * Functions for quickinfo
    */
    fn.quickInfo = {
      get: function(obj) {
          var id = $(obj).attr('id');
          switch (id) {
              case 'circle':
                  return 0;
               break;
               case 'square':
                   return 1;
               break;
           }
      },
      show: function(number) {
          $('#hdCont h3:eq('+number+')').show();
      },
      hide: function(number) {
          $('#hdCont h3:eq('+number+')').hide();
      }
    };

    /**
    * @description
    * Quickinfo behaviour
    */
    $('#hdCont .quickInfo').hover(function() {
        fn.quickInfo.show(fn.quickInfo.get(this));
    }, function() {
        fn.quickInfo.hide(fn.quickInfo.get(this));
    });

/*----------------------------------------
    * Lists
----------------------------------------*/

    /**
    * @description
    * Function for colsplitting in lists
    */
    fn.cols = function() {
        var h = 18;
        var list = $('.cols ul').children('li');
        var rightList = [];
        var leftList = [];
        var middle = Math.ceil(list.length/2);
        for (var i = 0; i < middle; i++) {
            leftList.push($(list[i]).text());
            (list[middle+i] != undefined) ? rightList.push($(list[middle+i]).text()) : null;
        }
        $('.cols').addClass('clearfix').empty().append('<ul class="col"></ul><ul class="col"></ul>');
        var left = 0;
        var right = 0;
        var leftPlus = [];
        var rightPlus = [];
        $.each(leftList, function(i) {
            $('.cols ul:eq(0)').append('<li>'+this+'</li>');
            var height = $('.cols ul:eq(0) li:eq('+i+')').height();
            left += Math.floor(height/h);
            if (height > h) {
                leftPlus.push(i);
            }
        });
        $.each(rightList, function(i) {
            $('.cols ul:eq(1)').append('<li>'+this+'</li>');
            var height = $('.cols ul:eq(1) li:eq('+i+')').height();
            right += Math.floor(height/h);
            if (height > h) {
                rightPlus.push(i);
            }
        });
        var diff = left-right;
        i = Math.abs(diff);
        while (i > 1) {
            if (diff > 0) {
                var last = $('.cols ul:eq(0)').children('li').length-1;
                i += ($.inArray(last, leftPlus) != -1) ? -2 : -1;
                if (i < 0) {
                    break;
                }
                $('.cols ul:eq(1) li:eq(0)').before($('.cols ul:eq(0) li:eq('+last+')').clone());
                $('.cols ul:eq(0) li:eq('+last+')').remove();
            } else if (diff < 0) {
                var first = 0;
                i += ($.inArray(last, rightPlus) != -1) ? -2 : -1;
                if (i < 0) {
                    break;
                }
                $('.cols ul:eq(1) li:eq('+first+')').clone().appendTo('.cols ul:eq(0)');
                $('.cols ul:eq(1) li:eq('+first+')').remove();
            }
        }
    };

    /**
    * @description
    * Colsplitting
    */
    fn.cols();

/*----------------------------------------
    * Page
----------------------------------------*/

    /**
    * @description
    * Functions for page
    */
    fn.page = {
        get: function(path) {
            $.ajax({
                beforeSend: function() {
                    fn.loading.start();
                },
                data: {
                    getPageByPath: true,
                    path: path
                },
                success: function(data) {
                    fn.loading.stop(function() {
                        $('#ctCont').html(data);
                        fn.cols();
                    });
                }
            });
        }
    };

});
