function BasketDialog(data)
{
	if (!data['available'])
	{
		resetSizeSelect(data['id'], 'Out of stock');
	}

	var qbasket = data['cost'] + ' (' + data['count'] + ')';
	$('qbasket').update(qbasket);
	
	jQuery('#basketHoverBox').load(basket_url, function(){
		jQuery(".basketHoverBox").show();
		jQuery("#productsSlider").bxSlider({
	        mode: "vertical",
	        infiniteLoop: false
	        //hideControlOnEnd: true
	    });
		jQuery(".basketHoverBox").hide();
		jQuery("#basketHoverBox").show();
		setTimeout("jQuery('#basketHoverBox').hide();", 5000);
	});
	var showCount = 0;
	var hideCount = 0;
	new PeriodicalExecuter(function(pe) {
	  if (++hideCount > 4)
	  {
	    pe.stop();
	  }
	  else
	  {
	    //$('qbasket-item-'+data['id']).setStyle({  backgroundColor: '#fff'});
	  }
	}, 0.8);
	new PeriodicalExecuter(function(pe2) {
	new PeriodicalExecuter(function(pe) {
	  if (++showCount > 4)
	  {
	    pe.stop();
	  }
	  else
	  {
	    //$('qbasket-item-'+data['id']).setStyle({  backgroundColor: '#FEE5E8'});
	  }
	}, 0.8);
	pe2.stop();
  } , 0.4);

  new PeriodicalExecuter(function(pe) {
  	//$('addToBasketTip').setStyle({  display: 'none'});
  	pe.stop();
  	}, 3);
}

function AvailableProduct(id, select_id)
{
	var select = $(select_id);
	if(select)
	{
		for(var i = 0; i < select.options.length; i++)
		{
			if(select.options[i].value == id)
			{
				if(select.options[i].text.indexOf("Out of stock") == -1)
					return true;
				else
					return false;
			}
		}
	}
}

function empty(val)
{
	if ((0 === val) || (null === val) || ('' === val)) return true;
	return false;
}

function isNumeric(val)
{
  if ((null != val) && !val.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  return true;
}

var isBasketErr = false;

//FIXED Instant checkout added
function addToBasketNew(product_id, quantity, redirect_url, cnt, select_id)
{
	if (isBasketErr)
	{
		if ('size' == select_id)
		{
			if ($('divSize') && $('divQuantity'))
			{
				$('divSize').removeClassName('propertyBoxError');
				$('divQuantity').removeClassName('propertyBoxError');
				$('divSize').removeClassName('propertyBoxErrorOut');
				$('divQuantity').removeClassName('propertyBoxErrorOut');
			}
		}
		else
		{
			jQuery('.errorMessage-popup').hide();
			jQuery('.errorMessageOut-popup').hide();
		}
		
	}
	
	if (empty(product_id) || !AvailableProduct(product_id, select_id) || (empty(quantity) || (0 >= quantity) || !isNumeric(quantity)))
	{
		isBasketErr = true;
		if (empty(product_id))
		{
			if ('size' == select_id)
			{
				if ($('divSize'))
				{
					$('divSize').addClassName('propertyBoxError');
				}
			}	
			else
			{
				jQuery('.errorMessage-popup').show();
			}
		}
		else if (!AvailableProduct(product_id, select_id))
		{
			if ('size' == select_id)
			{
				if ($('divSize'))
					{
						$('divSize').addClassName('propertyBoxErrorOut');
					}
			}
			else
			{
				jQuery('.errorMessageOut-popup').show();
			}
		}

		if (empty(quantity) || (0 >= quantity) || !isNumeric(quantity))
		{
			$('divQuantity').addClassName('propertyBoxError');
		}
		return false;
	}

	var cntr = $(cnt);
	jQuery("#overlay").show();
	jQuery("#overlay").css({ width: jQuery(window).width(), height: jQuery(".mainContainer").height()});
	
	var top = jQuery(window).height()/2+jQuery(window).scrollTop();
	var left = (jQuery(window).width()) / 2;
	jQuery("#overlay").find("img").css({ top: top}); 
	jQuery("#overlay").find("img").css({ left: left});
	new Ajax.Request(base_path + '/cart/add', {
		method: 'post',
		parameters: {id: product_id, quantity: quantity, ajax: true},
		onFailure: function(cntr) {
			
		}.bind(this, cntr),
		onSuccess: function(cntr, redirect_url, transport, json)
		{
		  	var data = transport.responseText.evalJSON();
			if (!data['banned'])
			{
				if (!data['available'])
				{
				 	resetSizeSelect(data['id'], 'Out of stock');
				}

				//instant checkout
				var isInstantCheckout = getCookie('instant_isChecked');
				if (!isInstantCheckout) {isInstantCheckout = 'yes';}
				if (data.content && ('' !== data.content))
				{
					//$('quick-basket-container-main').setStyle({display: 'block'});
					//$('quick-basket').insert(data.content);
				}

				if (redirect_url && ('no' !== isInstantCheckout))
				{
					window.location.href = redirect_url;
				}
				else
				{
					//start show dialog
					BasketDialog(data);
				   //end show dialog
				}
				//end instant checkout
			}
			jQuery("#overlay").hide();
		}.bind(this, cntr, redirect_url)
	});

	return false;
}

function resetSizeSelect(id, status)
{
	var select = $('size');
	if(select)
	{
		for(var i=0; i < select.options.length;i++)
		{
			if(select.options[i].value == id)
			{
				var index = select.options[i].text.indexOf(' - ');
				var temp_Str = select.options[i].text.substr( 0, index+3) + status;
				select.options[i].text = temp_Str;
				return true;
			}
		}
	}

}

function deleteBasketItem(product_id)
{
	var cont = $('qbasket-item-' + product_id);
	//cont.startWaiting('waiting');

	new Ajax.Request(base_path + '/cart/delete', {
		method: 'post',
		parameters: {id: product_id},
		onFailure: function(cont) {
			//cont.stopWaiting();
		}.bind(this, cont),
		onSuccess: function(cont, transport, json) {
			var data = transport.responseText.evalJSON();
			if (data['available'])
			{
				resetSizeSelect(data['id'], 'In stock');
				/*
				$('tip' + data['id']).removeClassName('out_of_stock');
				$('tip' + data['id']).setStyle({backgroundColor: '#ED1C24'});
				$('tip' + data['id']).setStyle({color: '#FFFFFF'});
				$('tip' + data['id']).onclick = function(){return addToBasket(this);}.bind(data['id']);
				eval('if(prototip_'+data['id']+'){prototip_'+data['id']+'.content = "Add to basket";prototip_'+data['id']+'.tip.innerHTML = "Add to basket<div style=\'clear:both;\'></div>"}');
				*/
			}
			$('qbasket-item-'+data['id']).remove();

			if ($('quick-basket').empty())
			{
				$('quick-basket-container-main').hide();
//				$('checkout-button').hide();
			}
			$('basket-price').update(data['cost']);
			$('basket-count').update(data['count']);
			/*
			$('tip'+data['id']).setStyle({  backgroundColor: '#ffffff'});
			$('tip'+data['id']).setStyle({  color: '#ED1C24'});
			*/
			//cont.stopWaiting();
		}.bind(this, cont)
	});
	return false;
}

function UserResolution()
{

	if (!getCookie("treds_user_resolution")) {
		var height = 0;
		var width = 0;

		if (self.screen) { // for NN4 and IE4
			width = screen.width
			height = screen.height
		}
		else
			if (self.java) { // for NN3 with enabled Java
				var jkit = java.awt.Toolkit.getDefaultToolkit();
				var scrsize = jkit.getScreenSize();
				width = scrsize.width;
				height = scrsize.height;
			}
		setCookie("treds_user_resolution", width+'x'+height, null, null, null, false);
	}

}
function setCookie(name, value, expires, path, domain, secure)
{
	var cookie=name+"="+escape(value);
    if (expires) {
        cookie+="; expires="+expires.toGMTString();
    }
    if (path) {
        cookie+="; path="+path;
    }
	else
	{
		cookie+="; path=/";
	}
    if (domain) {
        cookie+="; domain="+domain;
    }

    if (secure) {
            cookie+="; secure";
    }
    document.cookie=cookie;
}
function deleteCookie(name)
{
	setCookie(name,'null',new Date(0),null,null,false);
}
function getCookie( name )
{
    var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
    if (cookieStartIndex == -1)
            return null
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
    if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}
function changeHeight(cusHeight)
{
	document.getElementById('ifrBlog').style.height = cusHeight + 'px';
}

//Event.observe(document, 'dom:loaded', UserResolution.bindAsEventListener() );
