var InMotion = false;
var SearchOpen = true;
var CurrentCatLevel = 0;
var arrCats = new Array("","","","");
var objCatRequest = null;
var objProdRequest = null;
var IconOpen = null;
var IconClose = null;
var ShowHideButton = null;
var ActiveRows = new Array(null,null,null,null);
var Brand = "";

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	InitShowHide
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function InitShowHide() {
	ShowHideButton =  $("ShowHideButton");
	IconClose = new Element("img", {
		"src" : "_img/icon_close.jpg"
	});
	IconOpen = new Element("img", {
		"src" : "_img/icon_open.jpg"
	});
	ShowHideButton.addEvent("click", function() {
		if (!InMotion) {
			InMotion = true;
			if (SearchOpen) {
				SearchOpen = false;
				$$('.ColumnContainer').each(function(cc){
					cc.setStyle("display","none");
				});
				var myFx = new Fx.Slide('AdvancedSearch').slideOut().chain(function(){
					ShowHideButton.empty();
					IconOpen.clone().inject(ShowHideButton);
					ShowHideButton.appendText("SHOW SEARCH");
					InMotion = false;
				});
			} else {
				SearchOpen = true;
				var myFx = new Fx.Slide('AdvancedSearch').slideIn().chain(function(){
					$$('.ColumnContainer').each(function(cc){
						cc.setStyle("display","block");
					});
					ShowHideButton.empty();
					IconClose.clone().inject(ShowHideButton);
					ShowHideButton.appendText("HIDE SEARCH");
					InMotion = false;
				});
			}

		}
	});
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	Init Tabs
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function InitTabs() {
	var CategoryTab = $("CategoryTab");
	var BrandTab = $("BrandTab");
	CategoryTab.addEvent("click", function() {
		SetSearchDisplay("Category");
	});
	BrandTab.addEvent("click", function() {
		SetSearchDisplay("Brand");
	});

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	SetSearchDisplay
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function SetSearchDisplay(DisplayValue) {
	//alert(DisplayValue);
	var CategoryTab = $("CategoryTab");
	var BrandTab = $("BrandTab");
	var CategoryHeaders = $("CategoryHeaderWrapper");
	var BrandHeaders = $("BrandHeaderWrapper");
	var CategoryColumns = $("CategoryColumnWrapper");
	var BrandColumns = $("BrandColumnWrapper");
	var ProductsList = $("ProductsListWrapper");
	if (DisplayValue == "Category") {
		BrandTab.setStyles({
			"border" : "1px solid #fff",
			"border-bottom" : "0",
			"color" : "#FE4A29",
			"background-image": "url()"
		});

		CategoryTab.setStyles({
			"border" : "1px solid #FE4A29",
			"color": "#fff",
			"background-image" : "url(_css/CatSearch/SearchTabBG.jpg)",
			"background-repeat" : "repeat-x"
		});
		CategoryHeaders.setStyle("display", "block");
		BrandHeaders.setStyle("display", "none");
		CategoryColumns.setStyle("display", "block");
		BrandColumns.setStyle("display", "none");
		ProductsList.setStyle("display", "block");
	} else {
		CategoryTab.setStyles({
			"border" : "1px solid #fff",
			"border-bottom" : "0",
			"color" : "#FE4A29",
			"background-image": "url()"
		});

		BrandTab.setStyles({
			"border" : "1px solid #FE4A29",
			"color": "#fff",
			"background-image" : "url(_css/CatSearch/SearchTabBG.jpg)",
			"background-repeat" : "repeat-x"
		});
		CategoryHeaders.setStyle("display", "none");
		BrandHeaders.setStyle("display", "block");
		CategoryColumns.setStyle("display", "none");
		BrandColumns.setStyle("display", "block");
		ProductsList.setStyle("display", "none");
	}
}



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	LoadBrands
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function LoadBrands() {
	var JsonURL = "BrandJson.php";

	objBrandRequest = new Request.JSON({
		url: JsonURL,
		onComplete: function(jsonObj) {
			if(jsonObj != null) {
				DisplayBrands(jsonObj.brands);
			}
			objBrandRequest = null;
		}
	}).send();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	DisplayBrands
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DisplayBrands(brands, container, ColumnContainerWidth) {
	var cContent = null;
	var MainContainer = null;
	var CurrentColumn = 0;
	var NumberPerColumn = Math.ceil(brands.length/4) + 1;
	var CurrentRow = NumberPerColumn;
	brands.each(function(c) {
		if (CurrentRow >= NumberPerColumn) {
			CurrentRow = 0;
			if (CurrentColumn > 0) {
				cContent.inject(MainContainer);
			}
			CurrentColumn++;
			MainContainer = $("Brand" + CurrentColumn);
			var ColumnContainerWidth = MainContainer.getStyle("width");
			cContent = new Element("div", {
				"class" : "ColumnContainer",
				"id" : "cscc",
				"styles": {
					"width": ColumnContainerWidth
				}
			});
		}
		CurrentRow ++;
		DisplayBrandRow(c.brand_name,c.brand_id, cContent, ColumnContainerWidth);
	});
	cContent.inject(MainContainer);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	DisplayBrandRow
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DisplayBrandRow(brand_name, brand_id, Container, ColumnContainerWidth) {


	var BrandDiv = new Element("div", {
		"class": "BrandRow"
	});
	BrandDiv.appendText(brand_name);
	BrandDiv.inject(Container);
	BrandDiv.addEvent("click", function() {
		Brand = brand_id;
		LoadCategory(1, null, null);
		SetSearchDisplay("Category");
	});
}


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	LoadCategory
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function LoadCategory(CatLevel, Category, NumProducts) {
	if(CurrentCatLevel >= CatLevel && CatLevel < 5) {
		for(l = CurrentCatLevel; l >= CatLevel; l--) {
			if ($("Cat" + l)) {
				$("Cat" + l).empty();
				$("CatHeader" + l).empty();
				arrCats[l-1] = "";
			}
		}
	}
	if (objCatRequest != null) {
		objCatRequest.cancel();
		objCatRequest = null;
	}
	if (objProdRequest != null) {
		objProdRequest.cancel();
		objProdRequest = null;
	}

	CurrentCatLevel = CatLevel;
	arrCats[CatLevel-2] = Category;

	if(parseInt(CatLevel) < 5) {

		var MainContainer = $("Cat" + CatLevel);
		var ColumnContainerWidth = MainContainer.getStyle("width");



		var LoadingDiv = new Element("div", {
			"class": "Loading",
			"id": "LoadingDiv"
		});
		LoadingDiv.inject(MainContainer);
		var JsonURL = "CatJson.php?TargetLevel=" + CatLevel + "&Brand=" + Brand;
		if (Category != null) {
			l = 0;
			while ( l < 4 && arrCats[l].length > 0) {
				JsonURL += "&cat" + (l+1).toString() + "=" + escape(arrCats[l]);
				l++;
			}
			$("CatHeader" + CatLevel).appendText(Category);
		}

		objCatRequest = new Request.JSON({
			url: JsonURL,
			onComplete: function(jsonObj) {
				if(jsonObj != null) {
					DisplayCategories(jsonObj.categories, MainContainer, LoadingDiv, ColumnContainerWidth);
				}
				objCatRequest = null;
			}
		}).send();
	}
	$("ProductsList").empty();
	if (NumProducts != null && (NumProducts < 21 || CatLevel > 2) ) {
		var ProdLoadingDiv = new Element("div", {
			"class": "LoadingProducts",
			"id": "ProdLoadingDiv"
		});
		ProdLoadingDiv.inject($("ProductsList"));
		JsonURL = "ProdJson.php?level=" + (parseInt(CatLevel) - 1).toString() + "&Brand=" + Brand;
		l = 0;
		while ( l < 4 && arrCats[l].length > 0) {
			JsonURL += "&cat" + (l+1).toString() + "=" + escape(arrCats[l]);
			l++;
		}
		objProdRequest = new Request.JSON({
			url: JsonURL,
			onComplete: function(objProdJson) {
				if(objProdJson != null) {
					DisplayProducts(objProdJson.products, ProdLoadingDiv);
				}
				objProdRequest = null;
			}
		}).send();
	}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	DisplayCategories
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DisplayCategories(categories, container, LoadingDiv, ColumnContainerWidth) {
	var cContent = new Element("div", {
		"class" : "ColumnContainer",
		"id" : "cscc",
		"styles": {
			"width": ColumnContainerWidth
		}
	});
	var sContent = new Element("div", {
		"class" : "scrollContent",
		"id" : "cssc"
	});
	sContent.inject(cContent);

	var Sbar = new Element("div", {
		"class" : "scrollbar"
	});
	var Knob = new Element("div", {
		"class" : "knob"
	});
	Knob.inject(Sbar);
	Sbar.inject(sContent, 'after');
	categories.each(function(c) {
		DisplayRow(CurrentCatLevel, c.category, c.NumProducts,sContent);
	});
	LoadingDiv.dispose();
	cContent.inject(container);
	var myScrollbars = new Scrollbar(cContent,{});
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	DisplayRow
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DisplayRow(Level, Name, NumProducts, Container) {
	DestCat = (parseInt(Level)+1);
	var CatDiv = new Element("div", {
		"class": "CategoryRow",
		"rel": DestCat,
		"alt": NumProducts
	});
	CatDiv.appendText(Name);
	CatDiv.inject(Container);
	CatDiv.addEvent("click", function() {
		ArrayLoc = parseInt(CatDiv.getProperty("rel")) -2;
		if (ActiveRows[ArrayLoc] != null) {
			ActiveRows[ArrayLoc].set("class", "CategoryRow");
		}
		CatDiv.set("class", "CategoryRowHot");
		ActiveRows[ArrayLoc] = CatDiv;
		LoadCategory(CatDiv.getProperty("rel"), Name, CatDiv.getProperty("alt"));
	});

}

function Get_Cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	DisplayProducts
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function DisplayProducts(Products, LoadingDiv) {
	LoadingDiv.dispose();
	var FirstRow = true;
	Products.each(function(p) {
		if (FirstRow) {
			FirstRow = false;
		} else {
			var DividerDiv = new Element("div", {
				"class":"RowDivider"
			});
			DividerDiv.inject($("ProductsList"));
		}
		var ProdDiv = new Element("div", {
			"class": "ProductRow"
		});

		// Number
		var PNumberDiv = new Element("div", {
			"class": "PNumber"
		});
		PNumberDiv.appendText(p.part_number);
		PNumberDiv.inject(ProdDiv);

		// Model
		var PModelDiv = new Element("div", {
			"class": "PModel"
		});
		PModelDiv.appendText(p.short_code);
		PModelDiv.inject(ProdDiv);

		// Image
		var PImageDiv = new Element("div", {
			"class": "PImage",
			"id": "pimg" + p.id
		});
		if (p.products_image1.length > 3) {
			var ProdImage = new Asset.image(p.products_image1, {
				onload: function() {
					// Resize Image
					coords = ProdImage.getCoordinates();
					var CorrectWidth = coords.width;
					var CorrectHeight = coords.height;
					if (coords.width > 73) {
						CorrectWidth = 73;
						CorrectHeight = Math.round((73/coords.width) * coords.height);
						if (CorrectHeight < 45) {
							CorrectMargin = Math.round((45/2) - (CorrectHeight/2));
						} else {
							CorrectMargin = 0;
						}
						ProdImage.setStyles({
							"height" : CorrectHeight,
							"width" : CorrectWidth,
							"margin-top" : CorrectMargin
						});
					}
				}
			});
		}
		ProdImage.inject(PImageDiv);
		PImageDiv.inject(ProdDiv);


		// Description
		var PNameDiv = new Element("div", {
			"class": "PDescrip"
		});
		PNameDiv.appendText(p.products_name);
		PNameDiv.inject(ProdDiv);


		// Availability
		var AvDiv = new Element("div", {
			"class" : "PAva"
		});
		var WarSel = new Element("select", {
			"name" : "ship_from[]"
		});
		var cookies_wareId = Get_Cookie('warehouse_id');
		p.warehouses.each(function(w) {
			if( cookies_wareId == w.id) {
				var WarOpt = new Element("option", {
					 "value": w.id, "selected":"selected"
				});
			} else {
				var WarOpt = new Element("option", {
					 "value": w.id
				});
			}
			WarOpt.appendText(w.name + " : " + w.quantity);
			WarOpt.inject(WarSel);

		});
		WarSel.inject(AvDiv);
		AvDiv.inject(ProdDiv);

		// Price
		var cookies_userId = Get_Cookie('custaccount');
		var Nprice = p.price.split(" ");
		if (cookies_userId > 0) {
			if (Nprice[1] == undefined) {
				var PPriceDiv = new Element("div", {
					"class": "PPrice"
				});
				PPriceDiv.appendText(Nprice[0]);
				PPriceDiv.inject(ProdDiv);
				//var priceSplit = Nprice[0];
				//PPriceDiv.appendText(priceSplit);
			} else {
				var PPriceDiv = new Element("div", {
					"class": "RPrice"
				});
				PPriceDiv.appendText(Nprice[0]);
				PPriceDiv.inject(ProdDiv);

				var Sprice = new Element("div", {
					"class" : "SPrice"
				});
				Sprice.appendText(Nprice[1]);
				Sprice.inject(ProdDiv);
				
			}
		} else {
			var PPriceDiv = new Element("div", {
				"class": "PPrice"
			});
			PPriceDiv.appendText("N/A");
			PPriceDiv.inject(ProdDiv);
		}
//this.style.text-decoration = "line-through"  + 

		// Quantity
		var QDiv = new Element("div", {
			"class" : "PQuan"
		});
		var Inp = new Element("input", {
			"type": "text",
			"name": "qty[]"
		});
		var Inp_hidden = new Element("input", {
			"type": "hidden",
			"name": "products_id[]",
			"value": p.id
			
		});
		QDiv.appendText("X ");
		Inp.inject(QDiv);
		Inp_hidden.inject(QDiv);
		QDiv.inject(ProdDiv);



		ProdDiv.inject($("ProductsList"));

		var DivClear = new Element("div", {
			"class":"clear"
		});
		DivClear.inject($("ProductsList"));

		// Blow up image
		if (p.products_image2.length > 3) {
			var DivHover = new Element("div", {
				"class" : "PHoverImage",
				"id": "pimg" + p.id + "_smarthbox"
			});
			var HoverImage = new Element("img", {
				"src" : p.products_image2
			});
			HoverImage.inject(DivHover);
		}


		DivHover.inject($("ProductsList"));
		// Detail div
		if (p.product_detail.length > 0) {
			var DetailDiv = new Element("div", {
				"class" : "ProductDetailRow",
				"id" : p.id
			});
			DetailDiv.appendText(p.product_detail);
			DetailDiv.inject($("ProductsList"));

			PNumberDiv.setStyles({
				"color" : "#D71C00",
				"text-decoration" : "underline",
				"cursor" : " pointer"
			});
			PNumberDiv.addEvent("click", function(){
				if (DetailDiv.getStyle("display") == "block") {
					DetailDiv.setStyle("display","none");
				} else {
					DetailDiv.setStyle("display","block");
				}
			});

			var DivClear = new Element("div", {
				"class":"clear"
			});
			DivClear.inject($("ProductsList"));
		}
	});

	smartHoverBox(
             0, //delay before vanishing
             30, //x offset
             0,  //y offset
             '_smarthbox', //smart hover box suffix
             'smarthbox_close' //hover box close class
       );
	/*
	var sh = new smartHoverBox({
		boxTimer: 0,
		yOffset: -10,
		xOffset: 0,
		lockY: 'top',
		lockX: 'right'
	});
	*/
}

	function DisplayPopUp(PartNum) {
		alert (PartNum);
	}