/**
 * This anonymous function runs instantly, creating as this file is loaded and creates a closure whit real private members.
 * @param $ - the jQuery object. - This way collisions on $ name can be avoided.
 */
(function($) {

   $.extend(true, {
    random: function(X) {
        return Math.floor(X * (Math.random() % 1));
    },
    randomBetween: function(MinV, MaxV) {
      return MinV + $.random(MaxV - MinV + 1);
    }
  });
  
  /**
   * This method is going to measure the occupied height in an element.
   * For this reason it takes all the children nodes and ask them, for their height,
   * accumulate this value and returns it.
   */
  var sumChildrenHeight = function (parent) {
    var accumulatedHeight = 0;
    var children = parent.children();
    children.each(function() {
      accumulatedHeight += $(this).height();
    });

    return accumulatedHeight;
  }  
  
 
  var fillWithImageDefaultConfig = {
    'sprite'            :   'random-image'
    , 'images_on_sprite' :   31 //27
    , 'height'           :   170
  }
  /**
   * This method takes an node, counts the summarized height of the its
   * children nodes and fills the rest of the space with random images.
   * @param obj - The node which is going to be filled.
   * @param actualParameters - Optional parameters. All the required parameters has default values.
   */
  var fillWithImage = function(obj, actualParameters) {
    var containerHeight = $('#content-right-border').height();
    
    var config = $.extend(true,  fillWithImageDefaultConfig, actualParameters);
    var setOptionalCssParameters = function (obj, cssParameter, value) {
        if (!!value) {
          obj.css(cssParameter, value);
        }
    }

    var freeHeight = containerHeight - sumChildrenHeight(obj);
    
    if (!!config.height) {
      var requiredImageCounter = Math.floor(freeHeight / config.height);
      for(var i = requiredImageCounter; i > 0; --i) {
        var newImage = $('<div>');
        setOptionalCssParameters(newImage, 'width', config.width);
        setOptionalCssParameters(newImage, 'height', config.height);
        if (!!config.sprite) {
          newImage.addClass(config.sprite);
        }

        var selectedImage = $.randomBetween(0, config.images_on_sprite);
        newImage.css({'background-position': '0px -' + (selectedImage * config.height) + 'px'});

        obj.append(newImage);
      }
    }
    obj
      .hide()
      .fadeIn('slow');
  }

  var show = function(link, submenu) {
      link.unbind('click').addClass('opened').removeClass('closed').click(function() {
          hide(link, submenu);
          return false;
      });
      submenu.stop(true, true, true).show(200);
      return false;
  };

  var hide = function(link, submenu) {
      link.unbind('click').removeClass('opened').addClass('closed').click(function() {
          show(link, submenu);
          return false;
      });
      submenu.stop(true, true, true).hide(300);
      return false;
  };

  var prepareMenu = function() {
	$('#main-menu>li ol[id="#"]').each(function() {
      var submenu = $(this);
      var link = submenu.prev('a');
	 
	  if (link.length != 0) {
	  //the class "open" has been added in the contentmanager->getMenu function... 
        if ( submenu.attr('class') == 'open' )
		{
			link.addClass('opened').click(function() {hide(link, submenu);return false;}).prepend('<span class="has-sub-menu ">.</span>');
			submenu.show();
		}
		else
		{
			link.addClass('closed').click(function() {show(link, submenu);return false;}).prepend('<span class="has-sub-menu ">.</span>');
			submenu.hide();
		}
      }
    });
  }

  var prepareGallery = function() {
    $('.colorbox a').colorbox({
        title: function(){
            var url = $(this).attr('href');
            var title = $(this).find('img').attr('title');
            var titleText = '';
            if (title != '') {
                titleText = title;
            }
            return titleText;
        }
        ,
        maxWidth: '1100px'
    });
  }

  var prepareVideoGallery = function() {
    $('.videok a').colorbox({
        title: function(){
//            var url = $(this).attr('href');
            var title = $(this).find('img').attr('title');
            var titleText = '';
            if (title != '') {
                titleText = title;
            }
            return titleText;
        }
        , iframe:true, innerWidth:425, innerHeight:344
    });
  }

  
//Preparecartoon: az eredeti szét lett kaszabolva, de nincs időm, se energiám rendesen újraírni. Bocs!
  var comics = {
    'items' : {
    }
    , 'container'       : '<li class="comics-sprite-opened" />'
    , 'textContainer'  : '<span class="text-hidden bulb" />'
  }

  var prepareCartoon = function (actualConfig) {
    var defaultConfig = {
        'suffix'	:	'-on-home-page'
        , 'duration': 	800
        , 'container'	:	'#comics'
		, 'overlay'		: '#comics-overlay'
        , 'closedSignal' : 'closed'
        , 'cartoonItems' : comics
    };
    var config = $.extend(true,  defaultConfig, actualConfig);
    
    var status = {};

    var header = $('#header');
    var container = $(config.container);
    var overlay = $(config.overlay);
	
	var showBulb = function () {
		var bulb = $(this).children('.bulb');
        bulb.stop(true, true).show(300);
    };
    
    var hideBulb = function () {
		var bulb = $(this).children('.bulb');
        bulb.stop(true, true).delay(300).hide(300);
    };
	
	$('#comics-overlay>div').each( function() {
		$(this).hover(showBulb, hideBulb);
	});
 
	
    var changeState = function(toShow, toHide) {
        toShow.each(function() {
            var obj = $(this);
            obj.css({'visibility': 'visible', 'opacity' : 0}).stop(true, true).animate({opacity: 1}, config.duration, function() {
                obj.attr('style', 'border-style: none'); 
            });
        });

        toHide.each(function() {
            var obj = $(this);
            obj.css({'opacity' : 1}).stop(true, true).animate({opacity: 0}, config.duration, function() {
                obj.css({'visibility': 'hidden'});
                obj.attr('style', 'border-style: none');
            });
        });
    };

    var openComics = function() {
        var link = $(this);
        link.unbind('click').click(closeComics);

        var toShow = $(config.container + '>:not(div[id$="'+config.suffix+'"])');
        var toHide = $(config.container + '>div[id$="'+config.suffix+'"]');
        changeState(toShow, toHide);

        status.header = {marginTop: header.css('margin-top')};
        header.stop(true, true).animate({marginTop: 0}, config.duration, function () {link.html('Képregény elrejtése'); header.removeClass(config.closedSignal); header.attr('style', '');});
		
		overlay.show();
	   
        return false;
    };

    var closeComics = function() {
        var link = $(this);
        link.unbind('click').click(openComics);
 
        var toShow = $(config.container + '>div[id$="'+config.suffix+'"]');
        var toHide = $(config.container + '>:not(div[id$="'+config.suffix+'"])');
        changeState(toShow, toHide);

        header.stop(true, true).animate(status.header, config.duration, function () {link.html('Képregény megnyitása'); header.addClass(config.closedSignal); header.attr('style', '');});
		
		overlay.hide();
        return false;
    };


    var openCloseLink = 
        $('<a>')
            .attr('href', 'comicsControl')
            .attr('id', 'comicsController')
            .html('Képregény megnyitása').click(openComics);
    var menu = $('#main-menu');
    menu.before(openCloseLink);
	
	overlay.hide();
  };

 
 var ShowHideContent = function()
  {
		
		$('a[id^="toggle_"]').each( function(){

			var link = $(this);
			var link_id = link.attr("id");
			var target_id = link_id.replace("toggle_", "");
			var target = $("#" + target_id);
			
			if ( target.attr("class") != "show")
			{
				target.hide();
			}
			
			link.click(function () {
				if  ( target.is(':visible') )
				{
					target.hide(0);
				}
				else
				{
					//HideAll
					$('a[id^="toggle_"]').each( function(){
						var hide_target_id = $(this).attr("id").replace("toggle_", "");
						var hide_target = $("#" + hide_target_id);
						hide_target.hide();
					});
					target.show(0);
				}
				return false;
			
			});
		
		});
		
  };
  
  $(document).ready(function() {
    prepareMenu();
    prepareCartoon();
    fillWithImage($('#right-panel-content'));
    prepareGallery();
    prepareVideoGallery();
	ShowHideContent();
  });

})(jQuery);

