﻿var Categories={
	List:[],
	_clientCache:{},

	Init:function () {
		//alert(absolutePath);
		if ($("CategoryBackground")) Categories.HomeBackground=$("CategoryBackground").src;

		var initSequence=new Devign.Sequence();
		initSequence.Add(Categories.AssignToElements);
		initSequence.Add(Categories.PreloadImages);
		initSequence.Add(Categories.AssignEventsToTabs);
		initSequence.Add(Categories.Hashtableize);
		initSequence.Add(Categories.SetEmptyTabSize);
		initSequence.Add(Categories.FadeAllElements);
		initSequence.Start();
	},
	
//	Handling the new in curver box on HP: {
	zoomHover:function(){
	    var more = $("navigation").getElementsBySelector(".moreDetails")[0];
	    new Effect.Morph(more, {style: {width: '73px'} , duration: 0.3 });
	},
	zoomOut:function(){
	    var more = $("navigation").getElementsBySelector(".moreDetails")[0];
	    new Effect.Morph(more, {style: {width: '0px'} , duration: 0.6 });
	},
	popUpDetails:function(){
	    var currentProduct = $("NewInCurverBox").getElementsBySelector(".current")[0];
	    var currentProductId = currentProduct.getAttribute("id").split('_')[1];
	    ProductClick(currentProduct,currentProductId,false);
	},
	nextProduct:function(){
	    
	    var nextIcon = $("navigation").getElementsBySelector(".next")[0];
	    if(nextIcon.hasClassName("disabled")) return ;
	    
	    var currentProduct = $("NewInCurverBox").getElementsBySelector(".current")[0];
	    var nextProduct = currentProduct.next('.newProduct');
	    
	    nextIcon.addClassName("disabled");
	    if(!nextProduct){
			nextProduct = $("NewInCurverBox").getElementsBySelector(".newProduct")[0];
	    }
        Effect.Appear(nextProduct , 
                        { duration: 0.3 , 
                            queue: 'end' , 
                            afterFinish:function () {  
                                nextIcon.removeClassName("disabled");
                            } });
                            
        Effect.Fade(currentProduct , 
                        { duration: 0.4 , 
                            queue: 'front' , 
                            afterFinish:function () {  
                                
                            } });
	        
        currentProduct.removeClassName('current');
        nextProduct.addClassName('current');
	},
	prevProduct:function(){
	    var prevIcon = $("navigation").getElementsBySelector(".prev")[0];
	    if(prevIcon.hasClassName("disabled")) return ;
	    
	    var currentProduct = $("NewInCurverBox").getElementsBySelector(".current")[0];
	    var prevProduct = currentProduct.previous('.newProduct');
	    
	    prevIcon.addClassName("disabled");
	    if(!prevProduct){
			var allProducts = $("NewInCurverBox").getElementsBySelector(".newProduct");
			prevProduct = $("NewInCurverBox").getElementsBySelector(".newProduct")[allProducts.length-1];
	    }
        Effect.Appear(prevProduct , 
                        { duration: 0.3 , 
                            queue: 'end' , 
                            afterFinish:function () { 
                                prevIcon.removeClassName("disabled");
                            } });
                            
        Effect.Fade(currentProduct , 
                        { duration: 0.4 , 
                            queue: 'front' , 
                            afterFinish:function () {  
                                
                            } });
        
        currentProduct.removeClassName('current');
        prevProduct.addClassName('current');
	},
//	Handling the new in curver box on HP }
	
	AssignEventsToTabs:function (initSequence) {
		$A($("MainCategories").getElementsByClassName("tab")).each(function (tab) {
			// todo nicer
			if (tab.id=="MainTabEmptyLeft") return;

			var productCategory=tab.ProductCategory;

			tab.observe("click",function (e) {
				Categories.TabClick(productCategory);
			});
			tab.observe("mouseover",function (e) {
				var related=Event.relatedElement(e,false);
				if (!related || (related && related.childOf && related.childOf(tab))) return;
				Categories.TabOver(productCategory);
			});
			tab.observe("mouseout",function (e) {
				var related=Event.relatedElement(e,true);
				if (!related || (related && related.childOf && related.childOf(tab))) return;
				Categories.TabOut(productCategory);
			});
		});
		initSequence.Next();
	},
	AssignToElements:function (initSequence) {
		// assign each category to an HtmlDivElement, back and forth
		Categories.List.each(function (cat) {
			$("MainTab"+cat.ProductCategoryId).ProductCategory=cat;
			cat.Element=$("MainTab"+cat.ProductCategoryId);
		});
		initSequence.Next();
	},
	Hashtableize:function (initSequence) {
		Categories.List.ById={};
		var l=Categories.List.ById;
		Categories.List.each(function (cat) { l[cat.ProductCategoryId]=cat; });
		initSequence.Next();
	},
	PreloadImages:function (initSequence) {
		var images=[],hovers=[];
		Categories.List.each(function (cat) {
			images.push(cat.BackgroundImage);
			hovers.push(cat.OpenedTabImage);
		});
		var imagesLength=images.length;
		// preload them all
		images.each(function (src) {
			preloadImage(src,imageLoaded);
		});
		hovers.each(function (src) {
			preloadImage(src);
		});
		function preloadImage(src,imageLoaded) {
			var img=document.createElement("img");
			img.src=src;
			if (imageLoaded) Element.observe(img,"load",imageLoaded);
		}
		function imageLoaded() {
			imagesLength--;
			if (imagesLength==0) {
				if (!loaded) setTimeout(function () {
					initSequence.Next();
				},100);
				loaded=true;
			}
		}
		var loaded=false;
		setTimeout(function () {
			status="Done .";
			if (!loaded) {
				initSequence.Next();
				loaded=true;
				status+".";
			}
		},4000);
	},
	SetEmptyTabSize:function (initSequence) {
		if(Categories.List.length==8) {
			//$("MainTabEmptyLeft").hide(); // we deleted that div 08.02.2007
		}else if (Categories.List.length<7) {
			// width=95+1 marginLeft
			var calc=776-(Categories.List.length+1)*96-1;
			if($("MainTabEmptyRight")) {
			    $("MainTabEmptyRight").setStyle({width:calc+"px"});
			    $("MainTabEmptyRight").show();
			}
		}
		initSequence.Next();
	},
	FadeAllElements:function (initSequence) {
		var tabsLength=Categories.List.length;
		if(tabsLength >= 4) {
		    var seq=new Devign.Sequence();
		    seq.Add(function (currSequence) {
			    Categories.List.each(function (tab,i) {
				    tab.Element.setOpacity(0);
					tab.Element.setStyle({visibility:"visible"});
				    new Effect.Appear(tab.Element,{delay:i*.1,duration:.3});
				    setTimeout(function () { Categories.TabOver(tab); },i*200+450);
				    setTimeout(function () { Categories.TabOut(tab); },i*200+800);
			    });
				$("CategoryBackground").setStyle({visibility:"visible"});
				$("HomeSlogenContainer").setStyle({visibility:"visible"});
			    $("CategoryBackground").hide();
			    $("HomeSlogenContainer").hide();
			    setTimeout(function () {
				    $("CategoryBackground").show();
				    $("HomeSlogenContainer").show();
				    currSequence.Next();
			    },1100);
		    }.bind(this));
		    seq.Add(Wiper.WipeOut);
		    seq.Start();
		} else if (tabsLength < 4 && tabsLength != 1) {
		    var seq=new Devign.Sequence();
		    seq.Add(function (currSequence) {
			    Categories.List.each(function (tab,i) {
				    tab.Element.setOpacity(0);
				    new Effect.Appear(tab.Element,{delay:i*.1,duration:.3});
				    setTimeout(function () { Categories.TabOver(tab); },i*200+350);
				    setTimeout(function () { Categories.TabOut(tab); },i*200+700);
			    });
			    $("CategoryBackground").hide();
			    $("HomeSlogenContainer").hide();
			    setTimeout(function () {
				    $("CategoryBackground").show();
				    $("HomeSlogenContainer").show();
				    currSequence.Next();
			    },800);
		    }.bind(this));
		    seq.Add(Wiper.WipeOut);
		    seq.Start();
		} else {
		    var seq=new Devign.Sequence();
		    seq.Add(function (currSequence) {
			    Categories.List.each(function (tab,i) {
				    tab.Element.setOpacity(0);
				    new Effect.Appear(tab.Element,{delay:i*.1,duration:.3});
				    setTimeout(function () { Categories.TabOver(tab); },i*200+350);
				    setTimeout(function () { Categories.TabOut(tab); },i*200+650);
			    });
			    $("CategoryBackground").hide();
			    $("HomeSlogenContainer").hide();
			    setTimeout(function () {
				    $("CategoryBackground").show();
				    $("HomeSlogenContainer").show();
				    currSequence.Next();
			    },400);
		    }.bind(this));
		    seq.Add(Wiper.WipeOut);
		    seq.Start();
		}
		initSequence.Next();
	},
	LastTab:null,
	TabOver:function (productCategory) {
		if (productCategory==Categories.LastTab) return;
		var tab=productCategory.Element;
		var bg=tab.getElementsByClassName("bg")[0];
		var queueOut=Effect.Queues.get("catOut"+productCategory.ProductCategoryId);

		if (queueOut.effects.length) Categories.CancelEffects(queueOut.effects);

		tab.addClassName("hover");
		if (bg.filters && bg.filters[0]) bg.filters[0].src=productCategory.OpenedTabImage;
		else bg.style.backgroundImage="url('"+productCategory.OpenedTabImage+"')";

		new Effect.Move(bg,{y:-6,duration:.2,mode:"absolute",queue:{position:"end",scope:"catOver"+productCategory.ProductCategoryId}});
	},
	TabOut:function (productCategory) {
		if (productCategory==Categories.LastTab) return;
		var tab=productCategory.Element;
		var bg=tab.getElementsByClassName("bg")[0];
		var queueOver=Effect.Queues.get("catOver"+productCategory.ProductCategoryId);

		if (queueOver.effects.length) Categories.CancelEffects(queueOver.effects);

		new Effect.Move(bg,{
			y:0,
			duration:.1,mode:"absolute",
			queue:{position:"end",scope:"catOut"+productCategory.ProductCategoryId},
			afterFinish:function () {
				if (bg.filters && bg.filters[0]) bg.filters[0].src=productCategory.ClosedTabImage;
				else bg.style.backgroundImage="url('"+productCategory.ClosedTabImage+"')";

				tab.removeClassName("hover");
			}
		});
	},

	TabCloseAll:function () {
		this.TabClose();
		$("SubCategoriesWrap").hide();
		$("ProductsWrap").hide();
	},
	TabClose:function (tab) {
		if (!this.LastTab) return;
		this.LastTab.Element.removeClassName("active");
		var last=this.LastTab;
		this.LastTab=null;
		this.TabOut(last);
		$("CategoryBackground").src=Categories.HomeBackground;
		$("HomeSlogenContainer").show();
        $("downloadBlock").show();
		$("CategoryContentTitle").hide();
		$("CategoryContentDescription").hide();

		HideProductsLayer();

		if (Categories.OpenSequence) Categories.OpenSequence.Abort();
	},

	TabClick:function (productCategory) {
		ShowFloatLogin(false);

		ClosePopup('ProductPopupWrap');

		$("ProductLoader").show();

		$("ProductsList").innerHTML="";

		var tab=productCategory.Element;

		isCategoryLobby=true;

		// click on one when already open - close it
		if (Categories.LastTab==productCategory) {
			this.TabClose(Categories.LastTab);
			return;
		}

		if (Categories.OpenSequence) {
			Categories.OpenSequence.Abort();
		}

		var sequence=new Devign.Sequence();

		var last=Categories.LastTab;
		Categories.LastTab=0;

		// click on one when the other is already open - close the current
		if (last) {
			sequence.Add(function (currSequence) {
				Categories.TabOut(last);
				last.Element.removeClassName("active");
				Categories.LastTab=productCategory;
				Effect.SlideUp('SubCategoriesWrap',{duration:.15,afterFinish:function () { currSequence.Next(); }});
			});
		}
		else Categories.LastTab=productCategory;

		tab.addClassName("active");

		$("HomeSlogenContainer").hide();
        $("downloadBlock").hide();

		$("SubCategoryTitleWrap").hide();
		$("ProductsListWrap").addClassName("wide");
		$("CategoryContentTitle").hide();
		$("CategoryContentDescription").hide();
		$("CategoryBackground").hide();

		// bg image
		sequence.Add(function (currSequence) {
			if (productCategory.BackgroundImage) {
				var b; // image loaded?
				Element.observe($("CategoryBackground"),"load",function() { currSequence.Next();b=true; });
				// changed from $("CategoryBackground").onload;
				setTimeout(function () {
					// if not loaded, next anyway
					if (!b) {
						currSequence.Next();
						b=true;
					}
				},1500);
				//alert(productCategory.BackgroundImage);
				$("CategoryBackground").src=productCategory.BackgroundImage;
			}
		});

		sequence.Add(function (currSequence) {
			if (productCategory.NavCssClass) {
				$('SubCategoriesWrap').hide();
				$("SubCategoriesEmptyBackground").show();
				$("Page").className="category"+productCategory.NavCssClass;

				$("TopLayerWrap").className="category"+productCategory.NavCssClass;

				$("ProductsList").innerHTML="";
				$("ProductsWrap").show();
				//Effect.Appear('ProductsWrap', { duration: 0.5});
			}
			$("CategoryContentTitle").innerHTML=productCategory.HomeHeader+((productCategory.IconImage!='')?('<img src="'+productCategory.IconImage+'" alt="" class="categoryIcon" />'):(''));
			$("CategoryContentDescription").innerHTML=productCategory.Description.replace("\n","<br/>");
                
			currSequence.Next();
		});

		// wipe all
		sequence.Add(Wiper.WipeOut);

		// will be assigned in the sequence before use
		var categoryData;

		// texts
		sequence.Add(function (currSequence) {
			var cached=Categories._clientCache["GetCategory("+productCategory.ProductCategoryId+",true)"];
			if (cached) {
				categoryData=cached;
				setTimeout(function () {
					//1
					currSequence.Next();
				},100);
			}

			Mantis.Curver.Pages.Default.GetCategory(
				productCategory.ProductCategoryId,true,
				AjaxProOutput(function(categoryDataResponse) {
					categoryData=categoryDataResponse;

					Categories._clientCache["GetCategory("+productCategory.ProductCategoryId+",true)"]=categoryDataResponse;
					currSequence.Next();
				})
			);
		});


		sequence.Add(function (currSequence) {
			var cacheKey="Category.ChildProductCategoriesLinks(ProductCategoryId="+productCategory.ProductCategoryId+")";
			var cached=Categories._clientCache[cacheKey];
			var productsElement;

			if (cached) productsElement=cached;
			else {
				// print subs
				var sb=[];
				var seperator="<span>|</span>";

				categoryData.getValue("ChildProductCategories").each(function (cpc) {
					Categories.List.ById[cpc.ProductCategoryId]=cpc;
					sb.push('<a href="#" id="subCategoryLink_'+ cpc.ProductCategoryId +'" onclick="Categories.SubTabClick('+cpc.ProductCategoryId+',this)">'+cpc.NavigationHeader+'</a> '+seperator);
				});

				var str=sb.join("");
				// remove the last seperator
				if (str.length>seperator.length)str=str.substring(0,str.length-seperator.length);

				productsElement=document.createElement("div");
				productsElement.innerHTML=str;

				Categories._clientCache[cacheKey]=productsElement;
			}

			while ($("SubCategories").lastChild) $("SubCategories").removeChild($("SubCategories").lastChild);
			$("SubCategories").appendChild(productsElement);
			$("SubCategoriesWrap").style.height="25px";
			Effect.SlideDown('SubCategoriesWrap',{duration:.2,
				afterFinish:function () {
					//2
					currSequence.Next();
				}
			});
		});
		
//      Load the first subcategory products:
		sequence.Add(function (currSequence) {
			var linkObj = $("SubCategories").getElementsBySelector('a')[0];
			var subCategoryId = linkObj.getAttribute("id").split('_')[1];
			Categories.SubTabClick(subCategoryId,linkObj);
			
			currSequence.Next();
		});
		
		sequence.Add(function (currSequence) {
			$("ProductLoader").hide();
			currSequence.Next();
		});
        
//      Load the favorite category products:
//		sequence.Add(function (currSequence) {
//			PrintProducts(
//				productCategory.HomeHeader,
//				categoryData.getValue("Products"),
//				function () {
//					currSequence.Next();
//				}
//			);
//		});

		Categories.OpenSequence=sequence;

		sequence.OnEnd=function () {
			Categories.OpenSequence=null;
		};

		sequence.Start();
	},

	SubTabClick:function (clickedProductCategoryId,linkObj) {
		var categoryData=Categories.List.ById[clickedProductCategoryId];
        
		ShowFloatLogin(false);
		isCategoryLobby=false;
		$("SubCategoryTitle").innerHTML="";
		$("SubCategoryTitleWrap").show();
		$("ProductsListWrap").removeClassName("wide");
		$("ProductsList").innerHTML="";

		Mantis.Curver.Pages.Default.GetCategory(
			clickedProductCategoryId,false,
			AjaxProOutput(function(categoryData) {
				PrintProducts(categoryData.getValue("HomeHeader"),categoryData.getValue("Products"));
				//in addition, set header image if exists.
				var HeaderImage = categoryData.getValue("HeaderImage");
				if(HeaderImage.length)
				{
					$("SubCategoryTitle").setStyle({'background-image':'url(data/uploads/'+HeaderImage+')'});
					$("SubCategoryTitle").addClassName('bgimg');
				}
				else
				{
					$("SubCategoryTitle").setStyle({'background-image':'none'});
					$("SubCategoryTitle").removeClassName('bgimg');
				}
			})
		);
		
		//console.log(linkObj);
		//console.log($('SubCategories').getElementsBySelector('a'));
		//console.log($A($('SubCategories').getElementsByTagName('a')).map(Element.extend));
		
		
		$('SubCategories').getElementsBySelector('a').each(function(el){
		    //console.log(el);
		    el.removeClassName("selected");
		});
		linkObj.addClassName("selected");
	},

	CancelEffects:function (effects) {
		effects.each(function (effect) { effect.cancel(); });
		effects.length=0;
	}
};

var productBoxWidth=125;
var maxHomepageHeaderLength=24;
var similarThumbBoxWidth=50;
var hiddenProductsWidth=0;
var hiddenSimilarThumbsWidth=0;
var hiddenBodyHeight=0;
var isCategoryLobby=false;
var productsSlider=null;
var similarSlider=null;
var contentSlider=null;
var currentProductsWidth=0;
var currentSimilarThumbsWidth=0;
var lastPromoId=0;
var lastEnlargedProduct=0;
var lastQueryName="";

function HideProductsLayer() {
	$("SubCategoriesEmptyBackground").hide();
	//Effect.SlideUp('SubCategoriesWrap',{duration:.3});

	Categories.TabCloseAll();
}

function RestoreProductsLayer() {

	$("SubCategoriesEmptyBackground").show();
	Effect.SlideUp('SubCategoriesWrap',{duration:.3});
	$('ProductsWrap').setOpacity(0);
	Effect.Appear ("ProductsWrap",{duration:0.5});
}

function PrintProducts(categoryHeader,productList,callback) {
	var cacheKey="PrintProducts(ProductCategoryId='"+categoryHeader+"',"+productList.length+")";

	$("SubCategoryTitle").innerHTML=categoryHeader;
	$("ProductsList").innerHTML="";

	var cached=Categories._clientCache[cacheKey];
	var productsElement;

	if (cached) productsElement=cached;
	else {
		var str=[];
		var productsImages=[];
		var productsImagesLength=0;

		productList.each(function (product) {

			if(product.HomepageImage=="") product.HomepageImage=product.MediumImage;


			pId=product.ProductId;
			if (product.HomepageHeader=="")product.HomepageHeader=product.Header;
			if (product.HomepageHeader.length>maxHomepageHeaderLength)product.HomepageHeader=product.HomepageHeader.substring(0,(maxHomepageHeaderLength-3))+"...";

			str.push('<span class="productWrap" onclick="ProductClick(this,'+ pId+',false)"><div class="productImageWrap"><img alt="" id="ProductImage'+pId+'" style="display:none" src="'+absolutePath+'Data/Uploads/'+product.HomepageImage+'" onload="this.style.display=\'\'"/></div><h3>'+product.HomepageHeader+'</h3></span>\n');

			if (product.HomepageImage) productsImagesLength++;
		});

		productsElement=document.createElement("div");
		productsElement.innerHTML=str.join("");
	}

	var productsList=$("ProductsList");
	productsList.setOpacity(0);

	while (productsList.lastChild) productsList.removeChild(productsList.lastChild);
	productsList.appendChild(productsElement);

	currentProductsWidth=productBoxWidth*productsImagesLength;

	hiddenProductsWidth=currentProductsWidth - (productBoxWidth*5);

	$("ProductsList").setStyle({width: currentProductsWidth+'px'});

	if (productsSlider==null) {
		productsSlider=new Control.Slider('Tracker','Slider',{sliderValue:0});

		productsSlider.options.onSlide=function(v) { ScrollProducts(v); }
		productsSlider.options.onChange=function(v) { ScrollProducts(v); }
	}
	else productsSlider.setValue(0);

	if (hiddenProductsWidth>0 && !isCategoryLobby) SetProductsSliderMode(true);
	else SetProductsSliderMode(false);

	new Effect.Appear($("ProductsList"),{afterFinish:function () {
		if (callback) callback();
	}});
}

function SetProductsSliderMode(isEnabled) {

	if (isEnabled) {

		if (productsSlider!=null)productsSlider.setEnabled()
		$("SliderLeftArrow").setStyle({visibility: 'visible'});
		$("SliderRightArrow").setStyle({visibility: 'visible'});
		$("Slider").setStyle({visibility: 'visible'});

	}else{
		if (productsSlider!=null)productsSlider.setDisabled();
		$("SliderLeftArrow").setStyle({visibility: 'hidden'});
		$("SliderRightArrow").setStyle({visibility: 'hidden'});
		$("Slider").setStyle({visibility: 'hidden'});
	}
}

function ScrollProducts(percent) {
	var xVal=(percent*( hiddenProductsWidth)).toFixed();
	$("ProductsList").setStyle({left:-xVal+'px'});
}

var slidingIntervalId=0;
function IncrementSlider(val,autoMovement) {
	if (val!=0) {
		var newVal=productsSlider.value+val;
		productsSlider.setValue(newVal);
		if (slidingIntervalId==0 ) {
			slidingIntervalId=setInterval(function() {IncrementSlider(val,true)}, 200);
		}
	} else{
		clearInterval(slidingIntervalId);
		slidingIntervalId=0;
	}

}

function ShowFloatLogin(toShow) {

	var o=$("TopLoginLink");

	if (o.hasClassName("selected"))toShow=false;
	if (toShow) {
	    HideProductsLayer();
        if($('ProductPopupWrap').visible != true) { /*Effect.Fade('ProductPopupWrap');*/ $("ProductPopupWrap").hide(); }
		Effect.Appear("FloatLogin",{duration:0.5});
		o.addClassName("selected");
	}else{
		$("FloatLogin").hide();
		o.removeClassName("selected");
	}
}

function FloatUserLogin() {

	var u=$("FloatUserName");
	var p=$("FloatUserPass");
	var isOk=true;

	if (u.value.length==0) {
		focus(u);
		setHtml("FloatLoginMessage","Please type a username",false);
		isOk=false;
	}
	if (p.value.length==0 && isOk) {
		focus(p);
		setHtml("FloatLoginMessage","Please type a password",false);
		isOk=false;
	}
	if (isOk) {
		Mantis.Curver.Pages.Default.ValidateUser(
			u.value,
			p.value,
			AjaxProOutput(
				function(returnedValue) {
					if(returnedValue != "Welcome") {
					  setHtml("FloatLoginMessage",returnedValue,false);
					} else { /*setHtml("FloatLoginMessage",returnedValue,false);*/ location.href=absolutePath+'buyers_area.aspx'; }
				}
			)
		);
	}

}

function UserLogin()
{
	var u=$("UserName");
	var p=$("UserPass");
	var isOk=true;

	if (u.value.length==0) {
		focus(u);
		setHtml("LoginMessage","Please type a username",false);
		isOk=false;
	}
	if (p.value.length==0 && isOk) {
		focus(p);
		setHtml("LoginMessage","Please type a password",false);
		isOk=false;
	}
	if (isOk) {
		Mantis.Curver.Pages.Default.ValidateUser(
			u.value,
			p.value,
			AjaxProOutput(
				function(returnedValue) {
					if(returnedValue != "Welcome") {
					  setHtml("LoginMessage",returnedValue,false);
					} else { /*setHtml("LoginMessage",returnedValue,false);*/ location.href=absolutePath+'buyers_area.aspx'; }
				}
			)
		);
	}

}

function OpenPromo(promoId) {
	ShowFloatLogin(false);
	//if (lastPromoId!=promoId) {
		$("ContentPopupBody").innerHTML="";
		lastPromoId=promoId;
		lastQueryName="";
		//PreparePopup();
		HideProductsLayer();
		Effect.Appear("ContentPopup",{duration:.5});
		$("PopupBackgroundImage").hide();
	    $("popupContentWrap").className="popupContentWrap";
	    $("PopupLoadingMessage").show();


	Mantis.Curver.Pages.Default.LoadPromo(
		promoId,
		AjaxProOutput(function(promoData) {
			//<div class="description">'+promoData.Description+'</div>
			var str='<div class="shortText"><h1>'+promoData.Header+'</h1><div class="body">'+promoData.Body+'</div></div>';
			FillPopupContent (promoData.PromoImage, str , promoData.CssClass );
		})
	);
}

function ClosePopup(id) {
	Effect.Fade(id,{duration:.5});

	if (Categories.LastTab && id!="ProductPopupWrap") {
		RestoreProductsLayer();
	}
}

function LoadContentPage(queryName) {
	ShowFloatLogin(false);
    if($('ProductPopupWrap').visible != true) { /*Effect.Fade('ProductPopupWrap');*/ $("ProductPopupWrap").hide(); }
	if (queryName.toLowerCase()=="contact") {
		// "contact" is a seperate popup
		HideProductsLayer();
		//$('ContactPopup').setOpacity(0);

		//Effect.Appear("ContactPopup", {duration:0.5});

	    $('ContactPopup').show();
	    $('ContactPopup').style.position = "relative";
		$('ContactPopup').style.top=-600;

		new Effect.Move('ContactPopup',{
			duration:0.8,y:0,mode:"absolute"
		});
		return;
	}

	if (lastQueryName!=queryName) {
		$("ContentPopupBody").innerHTML="";
		lastQueryName=queryName;
		lastPromoId=0;
		PreparePopup();
	}else{
		// the content is already there
		RestorePopup();
	}

	Mantis.Curver.Pages.Default.LoadContentPage(
		queryName,
		AjaxProOutput(function(contentPageData) {
			str='<h1>'+contentPageData.Header+'</h1><div class="description">'+contentPageData.Description.replace("\n","<br/>")+'</div><div class="body">'+contentPageData.Body+'</div>';
			FillPopupContent(contentPageData.Image,str,contentPageData.CssClass);
		})
	);
}

function RestorePopup() {
	HideProductsLayer();
	//$('ContactPopup').setOpacity(0);
	//Effect.Appear("ContentPopup",{duration:.5});
	$('ContentPopup').show();
	    $('ContentPopup').style.position = "relative";
		$('ContentPopup').style.top=-600;

		new Effect.Move('ContentPopup',{
			duration:0.8,y:0,mode:"absolute"
		});
}

function PreparePopup() {
	RestorePopup();
	$("PopupBackgroundImage").hide();
	$("popupContentWrap").className="popupContentWrap";
	$("PopupLoadingMessage").show();
}

function FillPopupContent(backgroundImage, body, cssClass) {
	$("PopupLoadingMessage").hide();

	if (backgroundImage!=null) {
		var preloaderImg=new Image();

		Element.observe(preloaderImg,"load",function() {
			$("PopupBackgroundImage").src = preloaderImg.src;
			$('PopupBackgroundImage').setOpacity(0);
			Effect.Appear("PopupBackgroundImage", {duration:0.5});
		});

		preloaderImg.src=absolutePath+'Data/Uploads/'+backgroundImage;
	}


	if (cssClass!="")$("popupContentWrap").addClassName(cssClass);

	$("ContentPopupBody").innerHTML=body;

	hiddenBodyHeight=$("ContentPopupBody").getHeight() - $("ContentPopupBodyWrap").getHeight();
	if (contentSlider==null) {
		contentSlider=new Control.Slider('ContentTracker','ContentSlider',
				{
				axis:'vertical',
				sliderValue:0
				}
			);

		contentSlider.options.onSlide=function(v) {ScrollContentPopup(v);}
		contentSlider.options.onChange=function(v) {ScrollContentPopup(v);}

	}else{
		contentSlider.setValue(0);
	}

	var visibleValue=(hiddenBodyHeight<=0)?("hidden"):("visible");
	$("ContentSliderTopArrow").setStyle({visibility:visibleValue});
	$("ContentSliderBottomArrow").setStyle({visibility:visibleValue});
	$("ContentSlider").setStyle({visibility:visibleValue});

	if (hiddenBodyHeight<=0) {
		$("popupContentWrap").addClassName("notScrolled");
	}
	else{
		$("popupContentWrap").removeClassName("notScrolled");
	}
}

function ScrollContentPopup(percent) {
	var xVal=(percent*( hiddenBodyHeight)).toFixed();
	$("ContentPopupBody").setStyle({top:(-xVal+'px')});
}

function IncrementContentSlider(val) {contentSlider.setValue(contentSlider.value+val);}

function OpenVideo(filename, width, height) {
	width = 640;
	height = 480;
	var v=window.open(absolutePath+'View.aspx?file='+filename+'&width='+width+'&height='+height,'videoWindow','width='+width+',height='+height+',resizable=no,scalable=no,status=yes,scrollbars=no');
	v.focus();
}


function ProductClick(obj,productId, isSimilarClick) {
	if (!isSimilarClick) {

        ShowFloatLogin(false);
		$("SimilarThumbsList").innerHTML="";
		$("ProductPopupWrap").setOpacity(0);
		Effect.Appear("ProductPopupWrap",{duration:.5});
		$("SimilarSliderLeftArrow").setStyle({visibility:'hidden'});
		$("SimilarSliderRightArrow").setStyle({visibility:'hidden'});
		$("SimilarSlider").setStyle({visibility:'hidden'});

		lastEnlargedProduct=productId;


	}else{
		// flip clicked similar object and current enlarged product

        //alert(obj.className);

		//Effect.Appear("SimilarThumbWrap"+lastEnlargedProduct); Effect id disabled because after Effect can't setted className is not work IE6/7
        $("SimilarThumbWrap"+lastEnlargedProduct).show();
        //$("SimilarThumbWrap"+productId).className = "transON";
        $("SimilarThumbWrap"+lastEnlargedProduct).className = "transOFF";

		$("SimilarThumbWrap"+productId).setStyle({display:'none'});
	}

	$("ProductName").innerHTML="";
	$("ProductSerialWrap").hide();
	$("ProductSizeWrap").hide();

	$("ProductLargeImageWrap").hide();

	Mantis.Curver.Pages.Default.LoadProductDetails(
		productId, !isSimilarClick,
		AjaxProOutput(
			function(productData) {
				PrintProductDetails(productData[0]);

				if (!isSimilarClick) {
					PrintSimilarGallery (productData[1]);

				}else{
					lastEnlargedProduct=productData[0].ProductId;


				}
			}
		)
	);
}

function SetOverOpacity(obj) {
    //alert(obj);
    obj.style.opacity = "100%";
}

function PrintSimilarGallery(similarList) {
	var str=[];
	var similarImages=[];
	var similarThumbsImagesLength=0;
	var curStyle="";
	for(var i in similarList) {
		if(typeof(similarList[i])=="object") {
			// debug params
			if(similarList[i].SmallImage=="")similarList[i].SmallImage="Promos/video_link.gif";
			// end of debug params

			pId=similarList[i].ProductId;

			curStyle=(pId!=lastEnlargedProduct)?(""):(" style=\"display:none;\" ");

			str.push('<div id="SimilarThumbWrap'+pId+'" onclick="ProductClick(this,'+ pId+',true)"'+curStyle+'><img id="SimilarImage'+pId+'" style="display:none" alt="'+similarList[i].Header+'" src="'+absolutePath+'Data/Uploads/'+similarList[i].SmallImage+'" onload="this.style.display=\'\'"/></div>');

			if (similarList[i].SmallImage!="") similarThumbsImagesLength++;
		}

	}

	$("SimilarThumbsList").innerHTML=str.join("");

	currentSimilarThumbsWidth=similarThumbBoxWidth*(similarThumbsImagesLength+1);
	hiddenSimilarThumbsWidth=currentSimilarThumbsWidth - (similarThumbBoxWidth*8);

	$("SimilarThumbsList").setStyle({width: currentSimilarThumbsWidth+'px'});

	if (similarSlider==null) {
		similarSlider=new Control.Slider('SimilarTracker','SimilarSlider',{sliderValue:0});

		similarSlider.options.onSlide=function(v) {ScrollSimilarThumbs(v);}
		similarSlider.options.onChange=function(v) {ScrollSimilarThumbs(v);}

	}
	else similarSlider.setValue(0);
	var visibleValue=(hiddenSimilarThumbsWidth<=0)?("hidden"):("visible");

	$("SimilarSliderLeftArrow").setStyle({visibility:visibleValue});
	$("SimilarSliderRightArrow").setStyle({visibility:visibleValue});
	$("SimilarSlider").setStyle({visibility:visibleValue});

}

function ScrollSimilarThumbs(percent) {
	var xVal=(percent*( hiddenSimilarThumbsWidth)).toFixed();
	$("SimilarThumbsList").setStyle({left:-xVal+'px'});
}

function IncrementSimilarSlider(val) {

    //alert(val);
    new Effect.MoveBy("SimilarThumbsList",0,val,{duration:0.7});

    //similarSlider.setValue(similarSlider.value+val);
}

function PrintProductDetails(productDetails) {


	$("ProductName").innerHTML=productDetails.Header;

    //if(productDetails.Serial != "") { $("ProductSerial").innerHTML=productDetails.Serial; } else { $("ProductSerialWrap").hide();  }

    //$("ProductSerialWrap").hide();

    //if(productDetails.SizeDescription) { $("ProductSize").innerHTML=productDetails.SizeDescription; } else { $("ProductSizeWrap").hide(); }
    //if(productDetails.PU != "") { $("ProductPU").innerHTML=productDetails.PU; } else { $("ProductPUWrap").hide(); }
    //if(productDetails.Pallet != "") { $("ProductPallet").innerHTML=productDetails.Pallet; } else {  $("ProductPalletWrap").hide(); }

    $("ProductSerial").innerHTML=productDetails.Serial;
    $("ProductSize").innerHTML=productDetails.SizeDescription;
	$("ProductPU").innerHTML=productDetails.PU;
	$("ProductPallet").innerHTML=productDetails.Pallet;

    $("ProductPUWrap").hide();
    $("ProductPalletWrap").hide();

	if(productDetails.Serial.length>1)$("ProductSerialWrap").show();
	if(productDetails.SizeDescription.length>1)$("ProductSizeWrap").show();
    if(productDetails.PU != "")$("ProductPUWrap").show();
    if(productDetails.Pallet != "")$("ProductPalletWrap").show();


	Element.observe($("ProductLargeImage"),"load",function() {
		$("ProductLargeImageWrap").show();
	});


	$("ProductLargeImage").src=absolutePath+'Data/Uploads/'+productDetails.LargeImage;

}

function SendContact() {
	var fullname=$("ContactFullname").value;
	var email=$("ContactEmail").value;
	var phone=$("ContactPhone").value;
	var comments=$("ContactComments").value;

	$("ContactResponse").innerHTML="";
	var errList="";

	var validEmailReg=/^[a-z][\w\-\.]*@([a-z0-9\-]+\.)+[a-z]{2,}$/i;

	if (fullname=="") {
		errList+="<li>Please write your name</li>";
		$("ContactFullname").focus();
	}

	if (!validEmailReg.test (email)) {
		errList+="<li>Please use a valid email address</li>";
		$("ContactEmail").focus();

	}

	if (errList!="") {
		$("ContactResponse").innerHTML="<ul>"+errList+"</ul>";
		return;

	}

	$("ContactResponse").innerHTML="Sending... please wait";
	Effect.Fade("ContactSubmit");

	var country=(typeof(ipBasedCountry)=="undefined")?(""):(ipBasedCountry);
	Mantis.Curver.Pages.Default.SendContact(
		fullname, email, phone, comments, country,
		AjaxProOutput(function(response) {
			if (response=="1") {
				$("ContactResponse").innerHTML="Your message was sent successfully";
			}else{
				$("ContactResponse").innerHTML="Error. Please try again later.";
			}
		})
	);
}

var Wiper=(function () {
	var element;

	return {
		Init:function () {
			element=$("Wiper");
		},
		WipeOut:function (currSequence) {
			element.show();
			element.style.top=0;
			//element.style.left=0;
			new Effect.Move(element,{
				//duration:1,x:-1200,mode:"absolute",
				duration:1,y:-1200,mode:"absolute",
				beforeStart:function () {
					$("CategoryBackground").show();
					$("CategoryContentTitle").show();
					$("CategoryContentDescription").show();
				},
				afterFinish:function () {
					//3
					element.hide();
					currSequence.Next();
				}
			});
			//setTimeout(function () { currSequence.Next(); },500);
		},
		WipeIn:function () {
			return
			element.style.left=element.offsetWidth+"px";
			new Effect.Move(element,{duration:1,x:0,mode:"absolute"});
		}
	};
})();

onContent(function() {
	AjaxProFix();
	Wiper.Init();
});

var Devign={};
// Devign.Sequence class
Devign.Sequence=function () {
	// private fields
	// a list of functions
	this.list=[];
	this.index=-1;
	this.aborted=false;
	// /private fields

	// public fields
	this.Finished=false;
	// /public fields
};

// public methods
Devign.Sequence.prototype={
	// adds a new function
	Add:function (sequenceFunction) {
		this.list.push(sequenceFunction);
	},
	// starts the sequence from the first function
	// fires 'OnStart' if exists
	Start:function () {
		this.index=-1;
		this.aborted=false;
		this.Next();
		if (typeof(this.OnStart)=="function") this.OnStart();
	},
	// ends the sequence
	// fires 'OnEnd' if exists
	End:function () {
		if (typeof(this.OnEnd)=="function") this.OnEnd();
		this.Finished=true;
	},
	// proceeds the sequence
	// if the sequence has finished calls 'End'
	Next:function () {
		// if sequence was aborted - ignore next statements
		if (this.aborted) return;

		this.index++;

		if (this.index==this.list.length) return this.End();

		var tf=this.list[this.index];

		// calls the function with the sequence as an argument
		if (tf) tf(this);
	},
	// aborts the sequence by setting the index to 'not started'
	Abort:function () {
		this.index=-1;
		this.aborted=true;
	}
};
// /public methods
// /Devign.Sequence class

function AjaxProFix() {
	Object.extend(Ajax.Web.Dictionary.prototype, {
		setValue:function(k, v) {
			for(var i=0; i<this.keys.length && i<this.values.length; i++) {
				if(this.keys[i] == k){
					this.values[i] = v;
					return i;
				}
			}
			return this.add(k, v);
		}
	});
}

function ChangeCountry(countryName) {
    if(countryName != null && countryName != "undefined") {
	    $('country').innerHTML= "Welcome to the " + countryName+ " site"
	    location.href="?country=" + countryName;
	    //$('LoginBox').show();
	    //$('MapBox').hide();
	}
}