var path_to_script = 'boardbuilder/boardbuilder/get_products.aspx';
var _menu = [];
var _cart_box = false;
var _category = '';
var _category_name = '';
var categoryNames = {'decks':'deck','trucks':'truck','wheels':'wheel','bearings':'bearing','griptype':'grip type','skateaccessories':'skate acc.','hardware':'hardware'};

var _catcache = {};

function initMenu()
{
	var nav = document.getElementById("cart-nav");
	if (nav)
	{
		var nodes = nav.getElementsByTagName("a");
		for (var i = 0; i < nodes.length; i++)
		{
			nodes[i].href="javascript:;";
			nodes[i].onclick = function()
			{
				_category = this.rel;
				_category_name = _category;
				if(categoryNames[_category_name]) _category_name = categoryNames[_category_name];
				if(_catcache[_category])
				{
					processResponce(_catcache[_category]);
				}
				else
				{
					getHttpRequest(path_to_script + '?type=' + this.rel);
				}
				clearActiveMenu();
				this.className = "active";
			}
			_menu[_menu.length] = nodes[i];
		}
		if(nodes[0].onclick)
		{
			nodes[0].onclick();
		}
	}
	//initScroll();
	//restoreCart();
}

function clearActiveMenu()
{
	for (var i = 0; i < _menu.length; i++)
	{
		_menu[i].className = '';
	}
}

/*
if (window.addEventListener)
	window.addEventListener("load", initMenu, false);
else if (window.attachEvent)
	window.attachEvent("onload", initMenu);
*/

var scrollposition = 0;
var ul = false;
var ul_offsetWidth = 0;
var _step = 121;
var _prev_clone_cnt = 0;
var _next_clone_cnt = 0;
var innerHTMLs = [];
var total_cnt = 0;
var liPerDiv = 5;

function initScroll()
{
	scrollposition = 0;
	ul = false;
	ul_offsetWidth = 0;
	_step = 121;
	_prev_clone_cnt = 0;
	_next_clone_cnt = 0;
	innerHTMLs = [];
	total_cnt = 0;
	liPerDiv = 5;

	ul = document.getElementById('step-scroll');
	anext = document.getElementById('btn-next');
	aprev = document.getElementById('btn-prev');
	if(ul && aprev && anext)
	{

		var lis = ul.getElementsByTagName('li');
		var reminder = (lis.length) % liPerDiv;
		if(reminder > 0)
		{
			for(var i=0; i< liPerDiv-reminder; i++)
			{
				var _li = document.createElement('li');
				var _div = document.createElement('div');
				_div.className = "clear-div";
				_div.innerHTML = "&nbsp";
				var __div = _li.appendChild(_div);
				var __li = ul.appendChild(_li);
			}
		}
		
		var lis = ul.getElementsByTagName('li');
		total_cnt = lis.length;

		ul.parentNode.id = "slide-div";
		ul_offsetWidth = ul.offsetWidth;		
		ul.parentNode._ul_offsetWidth = ul_offsetWidth;
		ul.parentNode._step = _step;
		
		ul.parentNode.mooeffect = new fx.Styles( ul.parentNode.id, {duration: 500,
						
					onStart: function(){
					},
					onComplete: function(){
												
						if(this.element.offsetLeft > this.element._start)
						{
							this.set({'left': this.element._end});
						}
						else if(this.element.offsetLeft < this.element._end)
						{
							this.set({'left': this.element._start});							
						}
					}		
			
			});
			
		ul.innerHTML = ul.innerHTML + ul.innerHTML + ul.innerHTML;

		ul.parentNode.mooeffect.set({'left': ul.parentNode.offsetLeft -1 * ul_offsetWidth });

		ul.parentNode._start = ul.parentNode.offsetLeft;
		ul.parentNode._end = ul.parentNode.offsetLeft - ul_offsetWidth + liPerDiv*_step;
		
		anext.href = 'javascript:;';
		aprev.href = 'javascript:;';
		
		aprev.onclick = function()
		{
			_prev();
		}
		anext.onclick = function()
		{
			_next();
		}
				
	}
}

function _next(step)
{
	if(ul && aprev && anext)
	{
		ul.parentNode.mooeffect.custom({'left':[ul.parentNode.offsetLeft,ul.parentNode.offsetLeft - _step*liPerDiv]});
	}
}

function _prev()
{
	if(ul && aprev && anext)
	{
		ul.parentNode.mooeffect.custom({'left':[ul.parentNode.offsetLeft,ul.parentNode.offsetLeft + _step*liPerDiv]});
	}
}


function getHttpRequest(url, is_forcache)
{
	var httpRequest = false;

	if (window.XMLHttpRequest) 
	{
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) 
		{
			httpRequest.overrideMimeType('application/json');
		}
	}
	else if (window.ActiveXObject) 
	{
		try 
		{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) 
			{
			}
		}
	}

	if (!httpRequest)
	{
		alert('Unfortunatelly you browser doesn\'t support this feature.');
		return false;
	}

	httpRequest.onreadystatechange = function()
	{
		if (httpRequest.readyState == 4)
		{
			if (httpRequest.status == 200 || httpRequest.status == 0)
			{
				if(is_forcache)
				{
					cacheResponce(httpRequest.responseText,is_forcache);
				}
				else
				{
					processResponce(httpRequest.responseText);
				}
			}
			else
			{
				alert('There was a problem with the request.(Code: ' + httpRequest.status + ')');
			}
		}
	}

	httpRequest.open('GET', url, true);
	httpRequest.send(null);

}

function cacheResponce(answer,__cat)
{
	if(typeof answer == "string")
	{
		var _json = eval( '' + answer + '' );
	}
	else
	{
		var _json = answer;
	}
	json = _json;

	_catcache[__cat] = json;

}

function processResponce(answer)
{
	if(typeof answer == "string")
	{
		var _json = eval( '' + answer + '' );
	}
	else
	{
		var _json = answer;
	}
	json = _json;

	_catcache[_category] = json;

	ul = document.getElementById('step-scroll');
	_cart_box = document.getElementById('cart-box');
	if(json.length > 0 && ul)
	{
		ul.innerHTML = "";
		ul.parentNode.style.left = '0';
		for(var i = 0; i < json.length ;i++)
		{			
			//create product list
			var _li = document.createElement('li');
			var _div = document.createElement('div');
			var _a = document.createElement('a');
			_a.href = "javascript:;";
			//_a.rel = json[i].ids;
			_a.rel = i;

			var _img = document.createElement('img');
			_img.src = json[i].picture;
			
			var __li = ul.appendChild(_li);
			var __div = __li.appendChild(_div);
			var __a = __div.appendChild(_a);


			var __img = __a.appendChild(_img);
			
		}
		
		initScroll();
		initItemHandlers();
				
	}
	
}

var _itemLinks = [];
var popup_timeout = false;

function initItemHandlers()
{
	_itemLinks = ul.getElementsByTagName('a');
	for(var i = 0; i < _itemLinks.length ;i++)
	{		
		_itemLinks[i].onclick = function()
		{
			addToCart(this.rel);
			hidePopup('popup2');
		}
		_itemLinks[i].onmouseover = function()
		{
			if(popup_timeout)
			{
				clearTimeout(popup_timeout);
			}
			//alert(this._json_id);
			showPopup(this.rel,getRealTop(this) + (this.rel - Math.floor(this.rel/liPerDiv)*5)*121,getRealTop(this));
			var _pa = document.getElementById('popup-add');
			if(_pa)
			{
				_pa.href="javascript:;";
				_pa.onclick = function()
				{
					addToCart(this.parentNode.parentNode._show_index);
					hidePopup('popup2');
				}
			}
		}
		_itemLinks[i].onmouseout = function()
		{
			popup_timeout = setTimeout("hidePopup('popup2')",50);
		}
	}
	var _p = document.getElementById("popup2");
	if(_p)
	{
		_p.onmouseover = function()
		{
			if(popup_timeout)
			{
				clearTimeout(popup_timeout);
			}
		}
		_p.onmouseout = function()
		{
			popup_timeout = setTimeout("hidePopup('popup2')",50);
		}
	}
	var _ps = document.getElementById("popup-select");
	if(_ps)
	{
		_ps.onclick = function()
		{
			if(popup_timeout)
			{
				clearTimeout(popup_timeout);
			}
		}
/*		
		var _opt = _ps.getElementsByTagName('option');
		for(var i = 0; i < _opt.length ;i++)
		{			
			_opt[i].onmouseover = function()
			{
				if(popup_timeout)
				{
					clearTimeout(popup_timeout);
				}
			}
		}
*/
	}	
}

function addToCart(_id,__json,__category)
{
	fixCart();
	if(!__json)
		__json = json;
	if(!__category)
		__category = _category;
	if(_cart_box && __json[_id])
	{
		var _li = document.createElement('li');
		var _h2 = document.createElement('h2');
		_h2.innerHTML = "my " + categoryNames[__category];
		var __h2 = _li.appendChild(_h2);
		var _div = document.createElement('div');
		var _a = document.createElement('a');
		var _img = document.createElement('img');
		_img.alt = "";
		_img.src = __json[_id].picture;
		var __img = _a.appendChild(_img);
		_a.href = "#";
		var __a = _div.appendChild(_a);
		var __div = _li.appendChild(_div);
		var _span = document.createElement('span');
		_span.className = "name";
		_span.innerHTML = __json[_id].brand;
		var __span = _li.appendChild(_span);
		var _span = document.createElement('span');
		_span.className = "type";
		_span.innerHTML = __json[_id].type;
		var __span = _li.appendChild(_span);
		var _span = document.createElement('span');
		_span.className = "price";
		_span.forLink = "my" + __category + "=" + __json[_id].ids + "&amp;";
		_span.forCache = "['" + __category + "','" + __json[_id].ids + "']";
		_span.innerHTML = __json[_id].price;
		var __span = _li.appendChild(_span);
		var _span = document.createElement('br');
		var __span = _li.appendChild(_span);
		var __li = _cart_box.appendChild(_li);
		__li.onclick = function()
		{
			this.parentNode.removeChild(this);
			calculateCart();
		}

		calculateCart();

	}
}

function fixCart()
{
	if(_cart_box)
	{
		var lis = _cart_box.getElementsByTagName('li');
		for (var i = 0; i < lis.length; i++)
		{
			if(lis[i].innerHTML == '')
			{
				lis[i].parentNode.removeChild(lis[i]);
			}
		}		
	}
}

function calculateCart()
{
	if(_cart_box)
	{
		var totalPrice = 0;
		var _link = "boardbuilder/add_to_cart.aspx?";
		var _cache = '';
		var nodes = _cart_box.getElementsByTagName("span");
		var cnt = 0;
		for (var i = 0; i < nodes.length; i++)
		{
			if(nodes[i].className == "price")
			{
				totalPrice += parseFloat(nodes[i].innerHTML.replace("$",""));
				_link += nodes[i].forLink;
				_cache += nodes[i].forCache + ",";
				cnt++;
			}
		}
		var _cart_total = document.getElementById('cart-total');
		if(_cart_total)
		{
				var __p = ((totalPrice % 1) ? totalPrice + "" : totalPrice + ".00");
				__p = __p.substring(0,__p.indexOf(".") + 3);
				_cart_total.innerHTML = "$" + __p;
		}
		var _buy_link = document.getElementById('buy-link');
		if(_buy_link)
		{
			if(cnt > 0)
			{
				_buy_link.href = _link.substring(0,_link.length - 5);	
			}	
			else
			{
				_buy_link.href = "#";	
			}	
		}
		if(cnt > 0)
		{
			setCookie('wb_cart',"[" + _cache.substring(0,_cache.length-1) + "]");
		}
		else
		{
			deleteCookie('wb_cart');
		}

	}
}
var _requests = {};
function restoreCart()
{
	var _cookie = getCookie('wb_cart');
	if(_cookie != null)
	{
		var cnt = 0;
		var _cache = eval(_cookie);
		for(var i = 0; i < _cache.length; i++)
		{
			if(!_catcache[_cache[i][0]])
			{
				if(!_requests[_cache[i][0]])
				{
					getHttpRequest('jsons/' + _cache[i][0] + ".json",_cache[i][0]);
					_requests[_cache[i][0]] = true;
				}
			}
			else
			{
				cnt++;
			}
		}
		if(cnt != _cache.length)
		{
			setTimeout('restoreCart()',1000);
		}
		else
		{
			for(var i = 0; i < _cache.length; i++)
			{			
				addToCart(_cache[i][1],_catcache[_cache[i][0]],_cache[i][0]);
			}
		}
	}
}

function hidePopup(_id)
{
	var _p = document.getElementById(_id);
	if(_p)
	{
		//_p._show_index = -1;
		_p.style.display = "none";
	}
}

function showPopup(_index,_left,_top)
{
	var _p = document.getElementById("popup2");
	var _oul = document.getElementById('popup-select');
	if(_p)
	{
		if(json[_index])
		{
			for(key in json[_index])
			{
				var _node = document.getElementById('popup-' + key);
				if(_node)
				{
					_node.innerHTML = json[_index][key];	
				}
				
			}
		}
		if(_oul && json[_index].dropdown_items)
		{
			_oul.innerHTML = "";
			var di = json[_index].dropdown_items;
			for(key in di)
			{
				var _opt = document.createElement('option');
				_opt.innerHTML = di[key];
				_opt.value = key;
				var __opt = _oul.appendChild(_opt);
			}
		}
		_p._show_index = _index;

		_p.style.top = _top + 154 + "px";
		_p.style.left = _left - 66 + "px";


		if (window.attachEvent)
		{
			_p.style.top = _top + 139 + "px";
			_p.style.left = _left - 78 + "px";
		}

		_p.style.display = "block";
	}
}

//some functuons

function getRealTop(elem)
{
	var nTop = 0;
	if(elem)
	{
		do
		{
			nTop += elem.offsetTop - elem.scrollTop;
			elem = elem.offsetParent;
		}
		while(elem)
	}
	return nTop;
}

function getRealLeft(elem)
{
	var nLeft = 0;
	if(elem)
	{
		do
		{
			nLeft += elem.offsetLeft - elem.scrollLeft;
			elem = elem.offsetParent;
		}
		while(elem)
	}
	return nLeft;
}

function setCookie(name,value,days,path,domain,secure) {
  var expires, date;
  if (typeof days == "number") {
    date = new Date();
    date.setTime( date.getTime() + (days*24*60*60*1000) );
		expires = date.toGMTString();
  }
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie(name) {
  var nameq = name + "=";
  var c_ar = document.cookie.split(';');
  for (var i=0; i<c_ar.length; i++) {
    var c = c_ar[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameq) == 0) return unescape( c.substring(nameq.length, c.length) );
  }
  return null;
}

function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}