var order = null;
var direction = null;
var id = null;

function doLoadingStuff()
{
	changeFormSubmitButtons();
	if(id != null && type != null && page != null && order != null && direction != null)
	{
		getProductList(id, type, page, order, direction, formId);
	}
}

function setCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function changeFormSubmitButtons()
{
	// fetch all inputs we have
    var inputs = $$('input');

	// loop them all
    for(i=0;i<inputs.length;i++)
    {
    	// if we found a submit button, we want to prepend a spinner to it
    	if(inputs[i].type=='submit' && inputs[i].className != 'no_spiffy')
		{
			inputs[i].onclick = function()
			{
				if(this.id != '')
				{
					var inputValue = this.id;
				}
				else
				{
					var inputValue = this.value;
				}
				
				this.value = inputValue;
				this.className = 'pressedButton';
/* 				this.disabled = true; */
			}
		}
    }
}

function getProductList(id, type, page, order, direction, formId)
{
	if(order == null)
	{
		order = '';
	}
	
	if(direction == null)
	{
		direction = '';
	}
	
	if(formId == null || formId == '')
	{
		var url = '/product/list/type/' + type + '/page/' + page + '/order/' + order + '/direction/' + direction + '/id/' + id;
		new Ajax.Updater('results', url, {method:'get'});
	}
	else
	{
		var url =  '/product/list/type/' + type + '/page/' + page + '/order/' + order + '/direction/' + direction + '/id/' + id;
		new Ajax.Updater('results', url, {parameters:Form.serialize(formId) } );
	}
}

function doFilterSubmit(page)
{
	if(page == null)
	{
		var page = 1;
	}
	else
	{
		$('pageCounter').value = page;
	}
	
	var typeFilter = $F('filtertype');
	var id = $F('genre_id');
	
	getProductList(id,typeFilter,1,null,null,'filter');
//	new Ajax.Updater('results', '/genre/filter/' + page, {asynchronous:true, parameters:Form.serialize($('genre'))});
//	return false;
}

function updateCartCount()
{
	new Ajax.Request('/cart/amount',{onSuccess:function(t){
		$('cart_link').update('(' + t.responseText + ')');
		if(t.responseText > 0)
		{
			new Effect.Appear('cartlink');
			new Effect.Shake('cartlink',{endcolor:'#07425F'});
		}
		else
		{
			new Effect.Fade('cartlink');
		}
	}})
}

function addToCart(id)
{
	id = parseInt(id)
	if(id != 0)
	{
		url = '/cart/add/id/' + id;
		new Ajax.Request(url, {onSuccess:updateCartCount});
		return false;
	}
	else
	{
		// do we print an error?
		return true;
	}
}

function changeCart(id, amount)
{
	id = parseInt(id)
	if(id != 0)
	{
		url = '/cart/change/id/' + id + '/amount/' + amount;
		new Ajax.Updater('cart', url, {onSuccess:updateCartCount});
	}
	return false;
}

function emptyCart()
{
	url = '/cart/empty';
	new Ajax.Updater('cart',url,{onSuccess:updateCartCount});
}

function changeView(type)
{
	setCookie('view',type,365,'/');
/* 	alert(type); */
	if(type == 'table')
	{
		$('list_table').style.display = 'block';
		$('list_thumbnails').style.display = 'none';
		$('list_image').src = '/images/list_active.png';
		$('thumbnails_image').src = '/images/thumbnail_inactive.png';
	}
	else
	{
		$('list_table').style.display = 'none';
		$('list_thumbnails').style.display = 'block';
		$('list_image').src = '/images/list_inactive.png';
		$('thumbnails_image').src = '/images/thumbnail_active.png';
	}
	return false;
}

function addComment(comment)
{
	new Ajax.Updater('comments', '/comment/add/', {asynchronous:true, parameters:Form.serialize($('addComment'))});
	return false;
}

function addFileInput()
{
	new Ajax.Updater('fileinputs','/product/file',{insertion:Insertion.Bottom});
	return false;
}

function deleteAttachment(id)
{
	if(confirm('Are you sure you want to delete this attachment?'))
	{
		new Ajax.Updater('attachment_list','/product/deleteattachment/id/' + id);
//		new Effect.Fade('attachment_' + id);
	}
	return false;
}

function deleteProduct(id)
{
	url = '/product/delete/id/' + id;
	if(confirm('Are you sure you want to delete this product?'))
	{
		document.location.href = url;
	}
	
	return false;
}

function checkPublishForm()
{
	if($('conditions').checked == false)
	{
		alert('You need to agree with the conditions');
		$('conditions').focus();
		return false;
	}

	if(parseInt($F('pages')) == 0 || isNaN($F('pages')) == true)
	{
		alert('"' + $F('pages') + '" is not a valid page number');
		$('pages').focus();
		return false;
	}
	
	if($F('artikel') == '')
	{
		alert('A title should be present');
		$('artikel').focus();
		return false;
	}
	
	if($F('composer') == '')
	{
		alert('A composer should be present');
		$('composer').focus();
		return false;
	}
	
	if($F('id_categorie') == '')
	{
		alert('A genre should be selected');
		$('id_categorie').focus();
		return false;
	}
	
	if($F('id_instrument') == '')
	{
		alert('Please select an instrument');
		$('id_instrument').focus();
		return false;
	}
	
	var files = $$('#fileinputs .file');
	var prices = $$('#fileinputs .price');
	var zeroprice = false;
	
	for(i=0;i<files.length;i++)
	{
		if(files[i].value != '' && prices[i].value == '')
		{
			alert('You are trying to add a file with an invalid price');
			prices[i].focus();
			return false;
		}
		
//		if((parseFloat(prices[i].value) == 0 || isNaN(parseFloat(prices[i].value))) && files[i].value != '')
		if(checkDecimal(prices[i].value) == false)
		{
			var zeroprice = true;
		}
	}
	
	if(zeroprice == true)
	{
		if(confirm('You have prices present which will be set to 0.00 after publishing, is this correct?') == false)
		{
			prices[0].focus();
			return false;
		}
	}
	
	// show a publishing screen, so users will not be clicking multiple times
	$('publish_div').style.display = 'none';
	$('loading').style.display = 'block';
	return true;
}

function checkDecimal(price)
{
	return /^-?\d+(\.\d+)?$/.test(price)
}

function deleteAttachment(id)
{
	if(id && confirm('Are you sure you want to delete this file?'))
	{
		url = '/product/deleteattachment/id/' + id;
		new Ajax.Updater('attachments',url);
	}
	return false;
}

function addToOnload(functionObject)
{
    var nowOnload = window.onload; // Let's save the existing assignment, if any
    window.onload = function () {
		functionObject();			

        // Now we call old function which was assigned to onLoad, thus playing nice
        if(nowOnload != null && typeof(nowOnload) == 'function') {
            nowOnload();
        }
    }
}
