var carrousel = null;
var merkmale  = null;
$(document).ready(function(){
    // Carrousel
	if ($('div.carrousel').is(':visible')) {
		carrousel = new ArticleCarrousel();
        carrousel.init();
	}
	//alert('javascript.js');
	merkmale = new Merkmale();
});

var ArticleCarrousel = function() {};
ArticleCarrousel.prototype = {
  articles:            [],
  coordinates:         [],
  currentPositionLow:  -1,
  currentPositionHigh: -1,
  autorunTimer:        null,
  init: function() {
	var me = this; 
	var settings   = new ArticleCarrouselSettings();
	me.articles    = settings.articles;
	me.coordinates = settings.coordinates;
		
	if (me.articles.length < 3) {
		// Do not activate carrousel
		$('div.carrousel .offer').css({'cursor':'auto'});
		return;
	}
	
	var visibleCount = $('div.carrousel .offer').length;
	$('div.carrousel .offer').each(function(key) {  
       $(this).attr('rel', visibleCount - key);
	});
	
	me.currentPositionLow   = 0;
	me.currentPositionHigh  = me.coordinates.length - 3;
	if (me.currentPositionHigh > me.articles.length - 1) {
		me.currentPositionHigh = me.articles.length - 1;
	}
	
	// Button 'prev'
	$('div.carrousel .prev').click(function() {
		me.stopAutorun(me);
		me.moveByStep(-1, me);
        return false;
    });
	
	// Button 'next'
    $('div.carrousel .next').click(function() {
    	me.stopAutorun(me);
    	me.moveByStep(1, me);
        return false;
    });
    
    if (!$.cookie('articleCarrouselFirstId')) { 
		me.startAutorun(me);
	}
    
    me.bindEvents(me);
  },
  
  startAutorun: function(me) {	
	  me.autorunTimer = setInterval(function() { me.moveByStep(1, me); }, 7000);
  },
  
  stopAutorun: function(me) {  
	  if (me.autorunTimer != null) {
		  clearInterval(me.autorunTimer);
		  me.autorunTimer = null;
	  }
  },
  
  $getArticle: function(index) {
	  var me = this; 
	  
      var result = $('<div class="offer" />')
      	.css('position', 'absolute');
      
      var $id          = me.articles[index]['id'],
          $imgSrc      = me.articles[index]['imgSrc'],
          $href        = me.articles[index]['href'],
          $name        = me.articles[index]['name'],
          $artNr       = me.articles[index]['artNr'],
          $priceNormal = me.articles[index]['priceNormal'],
          $priceAction = me.articles[index]['priceAction'];
          
      result.append(
    	'<input type="hidden" class="id" value="' + $id + '" />' +
		'<div class="offer-content">' +	
		     '<div class="imagecontainer">' + 
		     	'<img alt="" src="' + $imgSrc + '" class="carrousel-article"/>' +
		     '</div>' +
		     '<div class="data">' +
			     ' <a class="artListItemCellBez bold" href="' + $href + '">' +
			     $name +
			     '</a>' +
			   '<div>' +
				     ' <span class="artListItemCellBez" href="' + $href + '">' +
				     $artNr +
				     '</span>' +
			   '</div>' +
			   '<div>' +
				   '<table cellspacing="0" cellpadding="0">' +
				    '<tr>' +
					'<td class="priceNormal">' +
					  ' <span class="priceNormal">' +
					   $priceNormal + 
					  '</span>' +
				    '</td>' +
				    ' <td class="priceAction">' +
				     ' <a class="priceAction" href="' + $href + '">' +
				     $priceAction +
				     '</a>' +
				    '</td>' +
				    '</tr>' +
				    '</table>' +
			   '</div>' +
		     '</div>' +
		'</div>');
      
	  return result;
  },
   
  moveByStep: function(step, me) {
	    me.unbindEvents();
	  
	    me.currentPositionLow += step;
	    if (me.currentPositionLow < 0) { 
	    	me.currentPositionLow = me.articles.length - 1; 
	    }
	    if (me.currentPositionLow >= me.articles.length) { 
	    	me.currentPositionLow = 0; 	    	
	    }
	    
	    me.currentPositionHigh += step;
	    if (me.currentPositionHigh < 0) { 
	    	me.currentPositionHigh = me.articles.length - 1; 
	    }
	    if (me.currentPositionHigh >= me.articles.length) { 
	    	me.currentPositionHigh = 0; 	    	
	    }
	    
	    // Slow or very slow
	    var duration = (me.autorunTimer == null)?'slow':5000;
	    	    
	    var maxpos = me.coordinates.length;
	    var rotate = function() {
	        var pos = parseInt($(this).attr('rel'));
	        var newpos = pos + step;
	        if (newpos < 0 || newpos >= maxpos) { 
	        	return; 
	        }
	        
	        $(this).attr('rel', newpos).css('zIndex', me.coordinates[newpos].zIndex);
	        
	        $(this).animate({'left':(step>0)?'+=10':'-=10'})
	         .animate({'left':(step>0)?'-=3':'+=3'}).animate(me.coordinates[newpos], duration, function() {
	            if (newpos == 0 || newpos == maxpos-1) { 
	            	$(this).remove(); 
	            }
	        });
	    }
	    
	    $('div.carrousel .offer').each(rotate);	

	    if (step > 0) {
	        var newe = me.$getArticle(me.currentPositionHigh);  // alert('newindex=' + newindex);
	        newe.attr('rel', 1).css(me.coordinates[0]).css('zIndex', me.coordinates[1].zIndex);
	        newe.appendTo($('div.carrousel'));
	        newe.animate(me.coordinates[1], duration, function() {
	        	me.unbindEvents();
	        	me.bindEvents(me);	        	
	        });
	    }
	    
	    if (step < 0) {
	        var newe = me.$getArticle(me.currentPositionLow); // alert('newindex=' + newindex);
	        newe.attr('rel', maxpos-2).css(this.coordinates[maxpos-1]).css('zIndex', me.coordinates[maxpos-2].zIndex);
	        newe.appendTo($('div.carrousel'));
	        newe.animate(me.coordinates[maxpos-2], duration, function() {
	        	 me.unbindEvents();
	        	me.bindEvents(me);	        	
	        });
	    }
   },
   
   bindEvents: function(me) {
	    //return;
	   var iMax = 5;
	   
	   if (me.articles.length < 5) {
		   iMax = me.articles.length;
	   }
	   
	   for (var i=1; i<=iMax; i++) {
		 	if (i-1 < iMax/2) {
		 		$('div.carrousel div.offer[rel="' + i + '"] .imagecontainer').bind('click', function() {
		 			me.stopAutorun(me);
		 			me.moveByStep(1, me);
		 		});
		    } else {
		    	$('div.carrousel div.offer[rel="' + i + '"] .imagecontainer').bind('click', function() {
		    		me.stopAutorun(me);
		    		me.moveByStep(-1, me);		 			
		 		});
			};
	   }
	   
	   var maxLeft = 0,
	       val     = 0;
	   $('div.carrousel .offer').each(function () {
		   var left = parseInt($(this).css('left'));
		   if (left > maxLeft) {
			   maxLeft = left;
			   val = $(this).children('input.id').val();
		   }
	   });
	   $.cookie('articleCarrouselFirstId', val, {expires: 0});
	   //alert(val);
   },
   
   unbindEvents: function() {
	   $('div.carrousel div.offer .imagecontainer').unbind('mousemove click');
   }   
};

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var Merkmale = function() {};
Merkmale.prototype = {
	urlDatasource: '',
	init: function(urlDatasource) 
	{
		var me = this;
		me.urlDatasource = urlDatasource;
		//alert('Merkmales init');
		//alert('datasource=' + me.urlDatasource);
		
		me.createNextDepthSelect(me);
		
	},	
	
	createNextDepthSelect: function(me)
	{
		//alert('createNextDepthSelect()');
		if ($('#ArtMerkmalContainer select.merkmalSelect').length >= $('#ArtMerkmalContainer div.merkmalSelectContainer').length) {
			//alert('return');
			xajax_ECAX_MerkmalChanged(xajax.getFormValues('form1'));
			return;
		}
		var merkmalAtts = []; 
		$('#ArtMerkmalContainer select.merkmalSelect').each(function() {
			merkmalAtts.push(this.value);
		});
		//alert('merkmalAtts=' + merkmalAtts);
		me.createSelect(merkmalAtts);
	},
	
	createSelect: function(merkmalAtts)
	{
		var me = this;
		var depth      = merkmalAtts.length + 1;
		var depthIndex = depth - 1;
		var grpLfdnr   = $('#form1 input[name="grpLfdnr"]').val();
		var url        = this.urlDatasource;	
		$.getJSON(url, {'grpLfdnr': grpLfdnr, 'merkmalAtts': merkmalAtts}, function(json) {
			switch (json.isSuccess) {
				case true:
					//alert(json.records.length);
					//<select onchange="xajax_ECAX_MerkmalChanged(xajax.getFormValues('form1'));" size="1" name="merkmal_8_3_1" id="merkmal_8_3_1" class="merkmalSelect">
					//<option value="5">Qualität 1</option>
					//<option value="7">Qualität 2</option>
					//</select>
					var select = '&nbsp;-';
					if (0 < json.records.length) {
						// Attributes exists
						var classes = $('#ArtMerkmalContainer div.merkmalSelectContainer').eq(depthIndex).attr('class').split(' ');
						// Get name of the select (second class of the merkmalSelectContainer)
						var name    = classes[1];
						select = '<select onchange="merkmale.onChangeSelect(this)" size="1" name="' + name + '" id="' + name + '" class="merkmalSelect">' + "\n";
						$(json.records).each(function(i, item) {
							//alert(item.value + ' : ' + item.text);
							select += '<option value="' + item.value + '">' + item.text + '</option>' + "\n";
						});
						select += '</select>' + "\n";
					}					
					$('#ArtMerkmalContainer div.merkmalSelectContainer:gt(' + depthIndex + ')').empty().html("&nbsp;-");
					$('#ArtMerkmalContainer div.merkmalSelectContainer').eq(depthIndex).empty().html(select);
					if (0 < json.records.length) {
						me.createNextDepthSelect(me);
					} else {
						xajax_ECAX_MerkmalChanged(xajax.getFormValues('form1'));
					}
				break;
				default:
					//alert(decodeHtml(json.message));		 
				break;
			}
		});
	},
	
	onChangeSelect: function(changedSelect) 
	{
		$('#ArtMerkmalContainer select.merkmalSelect').each(function(i, item) {
			if (this == changedSelect) {
				$('#ArtMerkmalContainer div.merkmalSelectContainer:gt(' + i + ')').empty();
				//alert('select changed: ' + i);
			}
		});
		Merkmale.prototype.createNextDepthSelect(this);
		//alert('onChangeSelect()');
	}
}

