/**
 * Shop/Menu
 * @autor:Christoph Gentsch
 * Ironshark Entertainment
 */
 var menu;
 var cat;
 var prodList;
 
 var Menu = Class.create();
 Menu.prototype = {
 	initialize:function(){
 		
 		$A( $$('#shopMenu a') ).each( function(item) {
 				
 			var regexp = /menu\/([0-9]+)/;
			var index = regexp.exec(item.href);
			
			//Testen für lesbare URL falls NULL
			if(index==null)
			{
				regexp = /[\W\w]+\/([0-9]+)\/$/;
				index = regexp.exec(item.href);
			}
			
			if(index!=null) {
				index = index[1]; 
	 			
	 			item.id = "linkMenu" + index;
	 			
	 			//kategorien sortierung aktivieren, wenn als admin eingeloggt
	 			if($("shopMenu").getAttribute("type")=="admin") {
					
					// Kontrolle ob Pfeile schon eingefuegt, ansonsten einfuegen
					var parentLink = $(item).parentNode;
					var linkCode = parentLink.innerHTML;
					if (linkCode.indexOf("arrowUp")==-1)
					{
					
					$(item).setAttribute('class', 'noBackground');
					$(item).setAttribute('style', 'display: inline; padding: 6px 0 6px 2px;');

					var newUpArrow = document.createElement("a");
					newUpArrow.setAttribute('href', '#');
					newUpArrow.setAttribute('style', 'display: inline; padding: 6px 0 6px 8px;');
					newUpArrow.setAttribute('id', 'arrowUp');
					newUpArrow.setAttribute('cid', index);
					newUpArrow.innerHTML = "<img src="+Core.url("/views/default/images/backend/icons/up.gif")+" alt='up' title='hoch'/>";

					var newDownArrow = document.createElement("a");
					newDownArrow.setAttribute('href', '#');
					newDownArrow.setAttribute('style', 'display: inline; padding: 6px 0 6px 0;');
					newDownArrow.setAttribute('class', 'noBackground');
					newDownArrow.setAttribute('id', 'arrowDown');
					newDownArrow.setAttribute('cid', index);
					newDownArrow.innerHTML = "<img src="+Core.url("/views/default/images/backend/icons/dn.gif")+" alt='up' title='runter'/>";

					$(item).parentNode.insertBefore(newUpArrow,$(item));
					$(item).parentNode.insertBefore(newDownArrow,$(item));		 			
				
					$A( $(item.parentNode).childNodes ).each( function(item){ 
					
						if(item.tagName=="A" && item.id=="arrowUp") {
							$(item).observe('click', function(event){
								new Ajax.Request( Core.url("/shop/sortMenu/"+item.getAttribute("cid")+"/up"), { method:'get', onSuccess:function(){
									new Ajax.Request( Core.url("/shop/menu/"+index), { method:'get', onSuccess:function(trans){$('shopMenu').replace(trans.responseText); menu.initialize();} });
								}});
							});
						}
						else if(item.tagName=="A" && item.id=="arrowDown") {
							$(item).observe('click', function(event){
								new Ajax.Request( Core.url("/shop/sortMenu/"+item.getAttribute("cid")+"/down"), { method:'get', onSuccess:function(){
									new Ajax.Request( Core.url("/shop/menu/"+index), { method:'get', onSuccess:function(trans){$('shopMenu').replace(trans.responseText); menu.initialize();} });
								}});
							});
						}
					});
	 			}
	 			
			} }
 		}); 
 	} 	
 }
 
var Cat = Class.create();
 Cat.prototype = {
 	initialize:function() {
 		$A( $$("div.moreColors img.preview") ).each( function(item) 
 		{
			var pid = item.readAttribute('product_id');
 			$(item).onmouseover = function()
			{
				$('main_'+pid).src = item.readAttribute('altSrc');
			};
			$(item).onmouseout = function()
			{
				$('main_'+pid).writeAttribute('src',$('main_'+pid).readAttribute('altSrc'));
			};
		});
 		$A( $$('#shopCat a') ).each( function(item) {
 				
 			var regexp = /cat\/([0-9]+)/;
			var index = regexp.exec(item.href);
			
			//Falls NULL testen für lesbaren Link
			if(index==null)
			{
				regexp = /[\W\w]+\/([0-9]+)\/$/;
				index = regexp.exec(item.href);
			}

			if(index!=null) {
				/*
				index = index[1];
				var regexp = /cat\/[0-9]+(\W\w+)/;
				var extra = regexp.exec(item.href);
	 			if (extra!=null){
	 				extra = extra[1];
	 			}else{
	 				extra = "";
	 			}
	 			
	 			item.id = "shopCat" + index + extra; 
	 			item.writeAttribute("href",null); 
	 			item.addClassName("pointer");

	 			$(item).observe('click', function(event) {
	 				document.body.style.cursor = 'wait';
	 				
	 				highlight(item);
	 				
	 				//new Ajax.Request( Core.url("/shop/menu/"+index+extra), { method:'get', onSuccess:function(trans){ $('shopMenu').replace(trans.responseText); menu.initialize(); } });
	 				
	 				new Ajax.Request( Core.url("/shop/cat/"+index+extra), { method:'get', onSuccess:function(trans) { 
	 					$('shopCat').replace(trans.responseText);
	 					cat.initialize(); 
	 					prodList.initialize(); 
	 					document.body.style.cursor = 'default'; 
	 					if( typeof window["zeroclick"] !== 'undefined' )
	 						zeroclick.initialize(); } });
	 			});*/
	 			
	 			//stats-popup
	 			if($("shopMenu").getAttribute("type")=="admin" && $("shopMenu").getAttribute("showstats")=="1") {
 			
		 			$(item).observe('mouseover', function(event) {
						Event.stop(event);	
						if(mypop.endDate==null) {
							mypop.endDate = new Date(); mypop.startDate = new Date(mypop.endDate - (4*7*24*60*60*1000));   //= - 4 wochen
						}
			 			new Ajax.Request( 
		 				Core.url("shop/ajaxGetStats/cat/"+index+"/"+mypop.startDate.format("ddMMyyyy")+"/"+mypop.endDate.format("ddMMyyyy")), 
		 						{ method:'get', onSuccess:function(trans){ 
		 							var message = eval('(' + trans.responseText + ')');
		 							message.pid=index; message.type="cat";
		 							mypop.update(message);
		 							mypop.show(item);
		 						}});	 						
			 		});
			 		
			 		$(item).observe('mouseout', function(event) {
			 			if( !within([event.pointerX(),event.pointerY()], $("popStats"), 0))
			 				$("popStats").hide();
					});
	 			}
	 			///
			}
 		});
 		
 	}
 }
 
 var Zeroclick = Class.create();
 Zeroclick.prototype = {
		 	initialize:function(){
		
		if($("cartApplet"))
            {
                this.prepareCart();
            }
        if($("wishlistApplet"))
        {
                this.prepareWishlist();    
        }

		
		//wird nur in der produktliste aktiv
		if($$("div.c33").length>0) {
			
	 		var aIcon = Element.extend(Builder.node('img',{src:skinDir+'/images/frontend/icons/addProduct.png'}));
	 		var pIcon = Element.extend(Builder.node('img',{src:''}));
	 		var pI = Element.extend(Builder.node('div',{pid:0},[pIcon,aIcon]));
	 		pI.setAttribute('style','display:none');
	 		document.body.appendChild(pI);
			
			$A($$("div.c33")).each( function(item)
			{
				item = Element.extend(item);
				
				var pidv = item.down().getAttribute("pid");	
				
				$(item).onmousedown = function(e)
				{
					var event = e || window.event;
					var imgSrc = Event.element(event).getAttribute('src');

					pIcon.setAttribute('src',imgSrc);					
	 				pI.setAttribute('pid',pidv);
	 				pI.setAttribute('style','display:visible');
	 				
			 		pIcon.setStyle({
			 			width:60+'px',
						height:60+'px'
			 		});
			 		
			 		aIcon.setStyle({
			 			position:'relative',
			 			top:'-17px',
			 			left:'43px'
			 		});
			 		
			 		pI.setStyle({
			 			position:'absolute',
			 			width:60+'px',
						height:60+'px',
						opacity:0.00,
						/*border:'1px solid #cdcdcd',*/
						top:Event.pointerY(event)+10+'px',
						left:Event.pointerX(event)+10+'px'
			 		});


			 		var dragObj = new Draggable(pI,{scroll:window,
						'onDrag':function(tt,event) {
				 			new Effect.Opacity(pI, { from: 0.8, to: 0.00, duration: 2 });
						},
						'onStart':function(){
							Effect.Pulsate('cartApplet');
							Effect.Pulsate('wishlistApplet');
							//$("cartApplet").highlight({startcolor:'#BEE0C0'});
							//$("cartApplet").addClassName("highlight");
							
						},
						'onEnd':function(){
							dragObj.destroy();
							pI.setStyle({
								top:-100+'px',
								left:-100+'px'
					 		});							
							//$("cartApplet").removeClassName("highlight");
						}
					});	
					dragObj.initDrag(event);

					return false;
				};

			});
		}
	},
 	prepareCart:function(){
		Droppables.add( $("cartApplet"), {
		  onDrop: function(element) {  
		  	var pid = element.getAttribute("pid");
		  	if(pid!=null) {
			  	new Ajax.Request( Core.url("cart/add/"+pid) , {method:'get', onSuccess:function(transport){ 
			  		
	 				new Ajax.Request(Core.url("cart/applet"),{
	 							method:'get',
	 							onSuccess:function(trans){
	 								var re = /<span id="cart_product_count">([.\s\S]*)<\/span>/g;
	 								var r = trans.responseText.match(re);
	 								$("cart_product_count").replace(r[0]);
	 								//$("cartApplet").replace(trans.responseText);
	 								//zeroclick.prepareCart();
	 							}
	 						});

	 				$("noticeArea").update( transport.responseText );
	 				
	 				if(!$("noticeArea").visible()) {
		 				Effect.BlindDown( $("noticeArea") );
		 				
		 				new PeriodicalExecuter(function(pe) {
			  					Effect.BlindUp( $("noticeArea") );
			  					pe.stop();
							}, 5
						);
	 				}
					
	 			} });
		  	}
		  } 
		});
 	},prepareWishlist:function(){
		Droppables.add( $("wishlistApplet"), {
			  onDrop: function(element) {  
				var pid = element.getAttribute("pid");
			  	if(pid!=null) {
				  	new Ajax.Request( Core.url("cart/wishlistAdd/"+pid) , {method:'get', onSuccess:function(transport){ 
				  		
		 				new Ajax.Request(Core.url("cart/wishlistApplet"),{
		 							method:'get',
		 							onSuccess:function(trans){
		 								var re = /<span id="wishlist_product_count">([.\s\S]*)<\/span>/g;
		 								var r = trans.responseText.match(re);
		 								$("wishlist_product_count").replace(r[0]);
		 							}
		 						});

		 				$("noticeArea").update( transport.responseText );
		 				
		 				if(!$("noticeArea").visible()) {
			 				Effect.BlindDown( $("noticeArea") );
			 				
			 				new PeriodicalExecuter(function(pe) {
				  					Effect.BlindUp( $("noticeArea") );
				  					pe.stop();
								}, 5
							);
		 				}
						
		 			} });
			  	}
			  	var pid = element.getAttribute("pid");
			  	
			  } 
			});
	 	}
 }
 
 
 //für das stats-popup
 var ProdList = Class.create();
 ProdList.prototype = {
 	initialize:function(){
 		
 		$A( $$('#shopCat a') ).each( function(item)
 		{
 			if(item.href.match(/page\/([\d]+)\/.*prod\/([\d]+)/)) {
 	 			var pageId = RegExp.$1;
 	 			var pid = RegExp.$2;
 			}

			if(pid==null)
			{
				regexp = /[\W\w]+\/[0-9]+\/[\W\w]+\/([0-9]+)/;
				pid = regexp.exec(item.href);
			}
			
			if(pid!=null) {				
				
				item.addClassName("pointer");
				
				/*	
				item.observe('mousedown', function(event){
				  		var zeit = new Date();
				  		prodList.mstart = zeit.getTime();
				});

				item.observe('mouseup', function(event){
					var zeit = new Date();
					if((zeit.getTime()-prodList.mstart)<300) {
							highlight(item);
							sid = "";
							if (current_session!="")
							{
								sid =	'?sid='+current_session
							}							
							document.body.style.cursor = 'wait';

							//Produktseite aufrufen
							window.location = Core.url("/page/"+pageId+"/__/shop/prod/"+pid[1]+sid);
					}
				});*/
				
				//activate stats-popup
				if($("shopMenu").getAttribute("type")=="admin" && $("shopMenu").getAttribute("showstats")=="1") { 
			 		$(item).observe('mouseover', function(event) {
						Event.stop(event);	
						if(mypop.endDate==null) {
							mypop.endDate = new Date(); mypop.startDate = new Date(mypop.endDate - (4*7*24*60*60*1000));   //= - 4 wochen
						}
						var new_pid = this.getAttribute("pid");
						if (new_pid == null) new_pid = 0;
						new Ajax.Request( 
		 				Core.url("shop/ajaxGetStats/prod/"+this.getAttribute("pid")+"/"+mypop.startDate.format("ddMMyyyy")+"/"+mypop.endDate.format("ddMMyyyy")), 
		 						{ method:'get', onSuccess:function(trans){ 
		 							var message = eval('(' + trans.responseText + ')');
		 							message.pid=new_pid; message.type="prod";
		 							mypop.update(message);									
									mypop.show(item);
		 						}});	 						
			 		});
			 		
	 				$(item).observe('mouseout', function(event) {
			 			if( !within([event.pointerX(),event.pointerY()], $("popStats"), 4) )
			 				$("popStats").hide();
					});
				}
			}
 		});
	}
 }
 
 function miniClone(item) {	
	var clone = item.cloneNode(true);
	item.parentNode.insertBefore(clone, item);
	
	Position.absolutize(clone);
	$(clone).hide();
      				
   	var bigImage = clone.childNodes[1].src;
					
	bigImage = bigImage.split("/");
	bigImage = bigImage[bigImage.length-1];
					
	var regexp = /([0-9]+)_000_184x184.jpg/;
	var erg = regexp.exec(bigImage);
	if(erg!=null) {
		clone.childNodes[1].setAttribute("src",Core.url("content/images/products/"+item.getAttribute("pid")+"/"+String(erg[1])+"_000_40x40.jpg"));
		clone.childNodes[1].style.margin="80px";
	}	
	
	clone.style.zIndex = 1000;
	
	return clone;
 }
 
 function highlight(item) {
 	item.id =  "mouseup";
	new Effect.Opacity("mouseup", {from: 1, to: 0, duration: 0.1 } );
	new Effect.Opacity("mouseup", {from: 0, to: 1, duration: 0.6 } );
	item.writeAttribute("id", null);
 }
 
 function within(pos, myElement, margin) {
 	var posElement = $(myElement).cumulativeOffset();
	var dims = $(myElement).getDimensions();
	
		if( pos[0]>=(posElement[0]-margin) && pos[0]<=(posElement[0]+dims.width+margin) ) {
		 	if(pos[1]>=(posElement[1]-margin) && pos[1]<=(posElement[1]+dims.height+margin) ) {
		 		return true;		 						
			}
			else
				return false;
		}
		else
			return false;
 }

function fixPageHeightByRightColumn()
{
	var rightColumn = $$('.columnRight')[0];
	var fullContent = $$('.bgWrapper')[0];
	var footer = $$('.columnFooter')[0];
	var columnLeft = $$('.columnLeft')[0];

	if(rightColumn == null || fullContent == null || footer == null || columnLeft == null)
	{
		return ;
	}

	var rightColumnHeight = rightColumn.getDimensions().height;
	var footerHeight = footer.getDimensions().height;
	var contentHeight = fullContent.getDimensions().height - footerHeight;

	if(contentHeight < rightColumnHeight)
	{
		columnLeft.style.height = rightColumnHeight + 'px';
	}
}

 Event.observe(window,'load',function() {
	menu = new Menu();
	cat = new Cat();
	prodList = new ProdList();
	fixPageHeightByRightColumn();
	//zeroclick = new Zeroclick();
 	
 	if($("shopMenu").getAttribute("type")=="admin" && $("shopMenu").getAttribute("showstats")=="1") {
		mypop = new PopStats();
 	}

	
 });
 
 

