var app = new A3M();

$(document).ready(function(){
  if (ids.length > 0){
    app.init();    
  }
});

function A3M() {
  this.opened = null;
  this.closing = false
  this.perline = 4;
}

A3M.prototype.init = function(){
  for (i=(ids.length-1);i>=0;i--){
    $('#content').append(this.create_box(ids[i]));
  }
  this.define_hovers();
}

A3M.prototype.create_box = function(id){
  var box = $.create('div',{'class':'box_small','id':ids[i]});
  box.innerHTML = $("#"+ids[i]+"_scontent").html();
  $(box).bind('click', $.extend({}), function (e) {
	  eval("app.resizeToMax($(this).attr('id'))");
  });
  
  return $(box);
}

A3M.prototype.resizeToMax = function(id){
  if (this.opened!=null){ this.resizeToMin(false); } //ak je otvorene tak zavrie
  
  if ((this.closing!=true) && (this.opened!=id)){
    $("#"+id).html('<div class="bgr_1"><div class="bgr_2"><p class="close"><a href="#"><img src="./skin/box_big_close.png" class="box_close" alt="zatvoriť" width="15" height="15" /></a></p><div class="loading"></div></div></div>');
    
    var pos = id.substring(1);
    if (((pos)%4)==0 || ((pos)%4)==3){
      for (i=(ids.length-1);i>=0;i--){
        $("#"+ids[i]).css('float','right');
      }
      $("#"+id).css('float','left');
    }else{
      for (i=(ids.length-1);i>=0;i--){
        $("#"+ids[i]).css('float','left');
      }
      $("#"+id).css('float','right');
    }
    
    $("#"+id).stop().animate({width: "470px",height: "670px"}, 'slow');
    $("#"+id).unbind();
    $("#"+id).removeClass("box_small");
    $("#"+id).attr({"class":"box_big"});

    $("#"+id).load('data/'+id+'/'+id+'.html',function() { // nacitanie dat z HTML data/
      $("#"+id+" .box_close").attr("id","b"+id);
      $("#"+id+" .box_close").bind('click', $.extend({}), function (e) {
        eval("app.resizeToMin(true)");
      });
    });
    this.opened = id;
  }
  this.closing = false;
  this.define_hovers();
  
  var pos = $("#"+id).offset();
  $.scrollTo(pos.top - 150);
}

A3M.prototype.resizeToMin = function(param){
  if (param==true){
   this.closing = true;
  }else{
   this.closing = false;
  }

  $("#"+this.opened).html('');

  for (i=(ids.length-1);i>=0;i--){
    $("#"+ids[i]).css('float','left');
  }
  $("#"+this.opened).stop().animate({width: "210px",height: "310px"}, 'slow');
  $("#"+this.opened).removeClass("box_big");
  $("#"+this.opened).attr({"class":"box_small"});

  $("#"+this.opened).html($("#"+this.opened+"_scontent").html());
  $("#"+this.opened).bind('click', $.extend({}), function (e) {        //nadefinuje sa rozklikavanie   
	  eval("app.resizeToMax($(this).attr('id'))");
  });
  
  this.opened = null;
}

A3M.prototype.define_hovers = function(){
	$(".box_small").hover(function () {
		$(this).addClass("box_small_over");
	},
	function () {
		$(this).removeClass("box_small_over");
	});
}

//##############################################################################
jQuery.create = function() {
    if (arguments.length == 0) return [];
    var args = arguments[0] || {}, elem = null, elements = null;
    var siblings = null;

    // In case someone passes in a null object,
    // assume that they want an empty string.
    if (args == null) args = "";
    if (args.constructor == String) {
        if (arguments.length > 1) {
            var attributes = arguments[1];
                if (attributes.constructor == String) {
                            elem = document.createTextNode(args);
                            elements = [];
                            elements.push(elem);
                            siblings =
        jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
                            elements = elements.concat(siblings);
                            return elements;

                    } else {
                        var buggy                                     =   "No";

                        // create element
                        if(args.toUpperCase() == "INPUT" || args.toUpperCase() == "SELECT"){
                          /**
                           * try catch block for compatibility
                           * http://www.quirksmode.org/bugreports/archives/2006/01/Changing_the_type_of_an_input_field.html
                           */
                          try {
                            if (arguments[1]){
                              var attr = arguments[1];

                              var attributes                            =   "<" + args +" ";

                              for (key in attr) {
                                attributes                              +=  key +"=\""+ attr[key] +"\" ";
                              }

                              attributes                                +=  ">";
                            }

                            var elem                                    =   document.createElement(attributes);
                            var buggy                                 =   "Yep";
                          }
                          catch (element) {

                          }
                        }

                        /**
                         * For normal browsers ;).
                         */
                        if (buggy == "No") {
                            elem = document.createElement(args);

                            // Set element attributes.
                            var attributes = arguments[1];
                            for (var attr in attributes)
                                jQuery(elem).attr(attr, attributes[attr]);
                        }

                        if(arguments[2]){
                            // Add children of this element.
                            var children = arguments[2];
                            children = jQuery.create.apply(null, children);
                            jQuery(elem).append(children);
                        }

                        // If there are more siblings, render those too.
                        if (arguments.length > 3) {
                                siblings =
    jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
                                return [elem].concat(siblings);
                        }
                        return elem;
                    }
                    // adding textnode here
            } else return document.createTextNode(args);
      } else {
              elements = [];
              elements.push(args);
              siblings =
        jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
              elements = elements.concat(siblings);
              return elements;
      }
};

;(function( $ ){
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};
	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};
})( jQuery );
