﻿var debug = false;
//If no product/category or tab we add the color tab for the AJAX back functionalty
//alert("qs: " + (location.search == '') + " #: " + (location.hash == ''));
if((location.search == '') && (location.hash == '') && (location.href.indexOf("our_collection.aspx") >= 0)){
	//self.location="our_collection.aspx?tab=color";
	self.location.replace("our_collection.aspx?tab=color");
}



var qsProductCategoryId = 0;
var qsProductId = 0;
var qsTab = "";
if (location.href.indexOf("#")>-1 && location.href.indexOf("?")==-1){
	var qs = location.href.substring(location.href.indexOf("#")+1);
	var qsCatKey = "category";
	var qsProductKey = "product";
	var qsTabKey = "tab";

	var pairArr ;

	qsKeys = qs.split("&");

	for(var i=0;i<qsKeys.length;i++){
		pairArr = qsKeys[i].split("=");

		if (pairArr.length>0){

			switch (pairArr[0]){
				case qsCatKey:
					qsProductCategoryId = parseInt(pairArr[1]);
					break;
				case qsProductKey:
					qsProductId = parseInt(pairArr[1]);
					break;
				case qsTabKey:
					qsTab = pairArr[1];
					break;
				default:
					break;
			}
		}
	}

}

var Tabs={
	lastTab:"",

	dicArr:[],

	setDicValue:function(key, value){
		if (Tabs.dicArr) Tabs.dicArr[key] = value;
	},

	getDicValue:function(key){
		if(Tabs.dicArr && Tabs.dicArr[key]) return Tabs.dicArr[key]
		return key;
	}

};

var ProductCategories = {
	clientCache:$H(),
	childCategoriesIds:[],
	colorCubesHTML:null,
	lastSelectedGroup:0,
	AddToCache:function(categoriesList){
		if (!categoriesList)return;
		if(!categoriesList.length)categoriesList=new Array(categoriesList);
		categoriesList.each(
			function(productCategory){
					if (!ProductCategories.clientCache["ProductCategory"+productCategory.ProductCategoryId]){
						ProductCategories.clientCache["ProductCategory"+productCategory.ProductCategoryId] = productCategory;
					}
				}
			);
	},
	GetById:function(productCategoryId){
		var productCategory = null;
		if (ProductCategories.clientCache["ProductCategory"+productCategoryId]){
			productCategory = ProductCategories.clientCache["ProductCategory"+productCategoryId];
		}else{
			Mantis.CaesarStone.Pages.ProductsControlBase.GetCategory(
				productCategoryId,
				AjaxProOutput(function(serverResponse){
					productCategory = serverResponse;
					ProductCategories.clientCache["ProductCategory"+productCategoryId] = productCategory;
				})
			);
		}
		return productCategory;
	},
	MouseEvent:function(mouseEvent, obj){
		if(mouseEvent){
			if(mouseEvent == 'over'){
				$("ColorCubes").removeClassName("hideCubes");
			}
			else{
				$("ColorCubes").addClassName("hideCubes");
			}
		}
	},

	View:function(productCategoryId){
		if (productCategoryId==0)return;
		var startImage = location.hash.indexOf("image=")>-1 ? "&image="+location.hash.substring(location.hash.indexOf("image=")+6) +"": "" ;
	}
};

var Products = {
    clientCache: $H(),
    currentProductId: 0,
    GetCachedList: function() {
        return Products.clientCache.values().clone();
    },
    CurrentProductId: function() {
        return Products.currentProductId;
    },
    AddToCache: function(productsList) {
        if (!productsList) return;
        if (!productsList.length) productsList = new Array(productsList);
        productsList.each(
			function(product) {
			    if (!Products.clientCache["Product" + product.ProductId]) {
			        Products.clientCache["Product" + product.ProductId] = product;
			    }
			}
			);
    },
    GetById: function(productId, funcAfterFinish, argument) {
        if (productId == 0 || typeof (productId) == undefined) return;

        var product = null;
        if (Products.clientCache["Product" + productId]) {
            //alert ("from cache: " + productId);
            product = Products.clientCache["Product" + productId];
            if (funcAfterFinish) funcAfterFinish(product, argument);
        } else {
            //alert ("not in cache:" + productId);
            Mantis.CaesarStone.Pages.ProductsControlBase.GetProduct(
				productId,
				AjaxProOutput(function(serverResponse) {
				    product = serverResponse;
				    Products.clientCache["Product" + productId] = product;
				    if (funcAfterFinish) funcAfterFinish(product, argument);
				})
			);
        }
        return product;
    },

    View: function(productId, enableViewing, keepLocation) {
        // ofir 21-11-07 Products.ViewWithForce(productId,enableViewing,keepLocation, false)
        self.location = 'Product.aspx?productId=' + productId;


    },

    MarkCurrentThumb: function(productId) {
        if (productId) {
            Products.currentProductId = productId;
        }

        if ($("ThumbInCategory" + Products.CurrentProductId())) {
            $("ThumbInCategory" + Products.CurrentProductId()).addClassName("current");

            var offsetAr = Position.positionedOffset($("ThumbInCategory" + Products.CurrentProductId()));
            var catLeft = $("CurrentCategorySamples").getStyle("left");

            if (catLeft != null) catLeft = parseInt(catLeft.substring(0, catLeft.indexOf("px")));

            var catTop = $("CurrentCategorySamples").getStyle("top")
            if (catTop != null) catTop = parseInt(catTop.substring(0, catTop.indexOf("px")));

            $("ThumbMarker").setStyle({
                left: (offsetAr[0] + catLeft + 2) + 'px',
                top: (offsetAr[1] + catTop + 2) + 'px'
            });
            $("ThumbMarker").show();

        }
    },
    ToggleImages: function(toShow) {
        toShow ? $("ProductImages").show() : $("ProductImages").hide();
    },
    ViewSimilarByTexture: function() {
        //$("SimilarProducts").show();
        //find current texture
        var product = Products.GetById(Products.CurrentProductId(), Products.ViewSimilarByTextureComplete);
    },
    ViewSimilarByTextureComplete: function(product) {
        new Effect.Appear("SimilarProducts", { duration: 1.0 });
    },
    CloseSimilar: function() {
        if ($("SimilarProducts") && Element.visible($("SimilarProducts"))) {
            Effect.Fade("SimilarProducts");
        }
    }
};

var Properties = {
	clientCache:$H(),
	texturesId:[],
	GetCachedList:function(){
		return Properties.clientCache.values().clone();
	},
	AddToCache:function(propertiesList){
		if (!propertiesList)return;
		if(!propertiesList.length)propertiesList=new Array(propertiesList);
		propertiesList.each(
			function(property){
					if (!Properties.clientCache["Property"+property.PropertyId]){
						Properties.clientCache["Property"+property.PropertyId] = property;
					}
				}
			);
	},
	GetById:function(propertyId){
		var property = null;
		if (Properties.clientCache["Property"+propertyId]){
			property = Properties.clientCache["Property"+propertyId];
		}else{
			Mantis.CaesarStone.Pages.ProductsControlBase.GetProperty(
				propertyId,
				AjaxProOutput(function(serverResponse){
					property = serverResponse;
					Properties.clientCache["Property"+propertyId] = property;
				})
			);
		}
		return property;
	},
	ViewTexturesList:function(){
		if ($("LISTtexture").innerHTML!=""){
			Tabs.View("texture",false);
			return;
		}
		var textureTemplate = '<div class="textureGroup" id="Texture{0}" style="display:none;"  >\
			<h2>{1}</h2><div class="samples" >\
				<div id="Texture{0}_Products" class="samplesWraper"></div>\
				<br class="clear" />\
			</div>\
		</div>';

		var texturesHTML = [];
		// fill the textures titles
		var t = 0;
		Properties.clientCache.values().each(function(property)
			{
				if (property.Type==1){
					Properties.texturesId.push(property.PropertyId);
					texturesHTML.push(String.format(textureTemplate,property.PropertyId,property.Header));
				}
			}

		);
		$("LISTtexture").innerHTML = texturesHTML.join("");
		setTimeout(Properties.FillListWithProducts, 100);
	},
	FillListWithProducts:function(){
		var sampleTemplate = '<div class="thumb" onclick="Products.View({0},true);//self.location=\'our_collection.aspx?productId={0}\';" >\
				<img src="{1}" alt="{2}" />\
				<div class="magnifier" >{3}</div>\
				</div>';
		var samplesHTML = [];

		// fill the products for each of the textures
		var groupId = 0;
		var products;
		products = Products.GetCachedList();

		for(var t=0,texturesLen=Properties.texturesId.length;t<texturesLen;t++){
			groupId = Properties.texturesId[t];
			samplesHTML.clear();
			for (var p=0, productLen=products.length;p<productLen;p++){
				for (var prop=0, propertiesLen=products[p].Properties.length ;prop<propertiesLen;prop++){
					if (products[p].Properties[prop].PropertyId==groupId){
						samplesHTML.push(String.format (sampleTemplate, products[p].ProductId, products[p].LobbyImage,products[p].Header.escapeHTML(), products[p].Header));
					}
				}
			}
			Properties.RenderList(t, groupId, samplesHTML.join(""));
		}
	},
	RenderList:function(num, groupId,html){
		setTimeout(function(){
			if (html!=""){
				$("Texture"+groupId+"_Products").innerHTML = html;
				//$("Texture"+groupId).show();
				Effect.Appear("Texture"+groupId);
			}
		}, 200*num );
	}
};

var needToFixHeight = false;

function updateHeights(){
	var spaceNeeded = $("GalleryHolder").getHeight() + $("CollectionPanel").getHeight();
	needToFixHeight= (spaceNeeded==0);
	$("DetailsTextWrap").setStyle({'margin-top':spaceNeeded +'px'});
	$("RelatedContent").setStyle({'margin-top':spaceNeeded +'px'});
}