

function alert(a, width, height)
{
	// a = a.replace(/\n/g, '<br/>');
	
	if ( !width ) width = 400;
	if ( !height ) height = 200;
	
	$('#dialog').html('');
	$('#dialog').html(a);
	$('#dialog').dialog({width: width, height: height});
	$('#dialog').dialog('open');
}


function DeliveryAddress_copyBillingAddress()
{
	
	$('input', '#checkout_deliveryAddress').each(function()
	{
		var n = $(this).attr('id').replace(/da_/, '');
		$(this).val( $('#' + n).val() );
	});
	$('select', '#checkout_deliveryAddress').each(function()
	{
		
		var n = $(this).attr('id').replace(/da_/, '');

		$(this).val( $('#' + n).val() );
	});
	$('#da_country_id').trigger('change');
	checkRequiredFields();
	
}





function populateProductSelectOptions(theSelect, category_id, selected_product_id)
{
	if ( category_id > 0 )
	{
		$('#' + theSelect).append('<option value="">Loading...</option>');
		$('#' + theSelect).load('/p/populateProducts.php?category_id=' + category_id + '&selected_product_id=' + selected_product_id);
	}
}





function setRequiredFields()
{
	// append a asterisk to the required fields labels
	$('body#front .required').each(function()
	{
		if ( $('img', $(this)).length == 0 )
		{
			$(this).append('<img src="/img/forms/required.gif" alt="Required Field" style="margin:0 0 5px 5px;" />');
		}
	});
	
}


function unsetRequiredFields(fieldset)
{
	$('label.required img', '#' + fieldset).remove();
}






function getGridPrice()
{
	if ( $('#price_grid_width').length < 1 )
	{
		return;
	}
	
	var w = parseInt($('#price_grid_width').val());
	var h = parseInt($('#price_grid_height').val());
	var g = parseInt($('#grid_id').val());
	
	var mw = parseInt($('#maximumWidth').val());
	var mh = parseInt($('#maximumHeight').val());

	if ( w > 0 && w <= mw && h > 0 && h <= mh )
	{
		$.post('/p/get.price.php', {w: w, h: h, g: g}, function(data)
		{
			$('#price_grid_price_display').html('Loading...');
			if ( data.price != '' && data.price_id > 0 )
			{
				$('#price_matrix_prices_id').val(data.price_id);
				$('#price_grid_price_display').html('&pound;' + data.price);
				$('#price_grid_price').attr('value', data.price);
				// alert(data.price);
			}
			else
			{
				$('#price_matrix_prices_id').val(0);
				$('#price_grid_price_display').html('<em>Call Us</em>');
				$('#price_grid_price').val(0);
			}
		}, 
		'json'
		);
	}
	else if ( $('#maximumWidth').length > 0 )
	{
		alert('Please make sure that you enter valid numbers.\n\nMaximum Width: ' + mw + 'cm\nMaximum Height: ' + mh + 'cm');
	}
	else
	{
		
	}
}





// pop up help tip

function showTip(what)
{
	switch (what)
	{
		case 'orientation':
			a = $.get('/inc/layout/html/tip.orientation.html', function(a){alert(a, 560, 460);});
			break;
		case 'position':
			a = $.get('/inc/layout/html/tip.position.html', function(a){alert(a, 560, 460);});
			break;
		default:
			alert('error. no content.');
			break;
	}
}





// checkout page / admin create order

function checkRequiredFields()
{
	$('.checkoutBlock').each(function()
	{
		var id = $(this).attr('id');
		var ok = true;

		$('.required', $(this)).each(function()
		{
			eid = $('#' + $(this).attr('for')).attr('id');
			// console.log( 'checking: ' +  eid);
			ev = $('#' + $(this).attr('for')).val();
			// console.log('val: ' + ev);
			if ( ev == '' )
			{
				// console.log(' : EMPTY');
				ok = false;
			}
		});
		if ( ok == true)
		{
			$('#' + id.replace(/checkout_/, 'head_') + ' span').removeClass('fieldsBad').addClass('fieldsGood');
		}
		else
		{
			$('#' + id.replace(/checkout_/, 'head_') + ' span').removeClass('fieldsGood').addClass('fieldsBad');
		}
	});
}


function createAccountOption(me)
{
	if ( $(me).attr('checked') )
	{
		$('#account_username_label, #account_password_label').addClass('required');
		$('#username, #password').attr('disabled', false);
		setRequiredFields();
	}
	else
	{
		unsetRequiredFields('checkout_loginDetails');
		$('#account_username_label, #account_password_label').removeClass('required');
		$('#username, #password').val('').attr('disabled', 'disabled');
	}
}







function addToBasket(formObject)
{
	error = false;
	hasQty = false;
	
		
	// check other required fields in this form.
	
	// height
	if ( $('#price_grid_height').length )
	{
		if ( $('#price_grid_height').val() == '' )
		{
			showBasketError();
			return false;
		}
	} 
	
	// width
	if ( $('#price_grid_width').length )
	{
		if ( $('#price_grid_width').val() == '' )
		{
			showBasketError();
			return false;
		}
	}
	
	// position
	if ( $('#productPositionSelect').length )
	{
		if ( $('#productPositionSelect').val() == '' )
		{
			showBasketError();
			return false;
		}
	}

	// orientation
	if ( $('#productOrientationSelect').length )
	{
		if ( $('#productOrientationSelect').val() == '' )
		{
			showBasketError();
			return false;
		}
	}
	
	// custom text
	if ( $('#customText').length )
	{
		if ( $('#customText').val() == '' )
		{
			showBasketError();
			return false;
		}
	}
	
	// make sure theres at least one quantity box with a value...
	$('input.qty', $(formObject)).each(function()
	{
		if ( $(this).val() > 0 )
		{
			hasQty = true;
		}
	});
	
	// return error;
	if ( error || !hasQty )
	{
		showBasketError();
	}
	else
	{
		// alert('ok to add to basket');
		postToBasket(formObject);
	}
	
	return false;
}




function showBasketError()
{
	alert('Please make sure you have filled all required fields and entered a quantity.');
	return false;
}

function postToBasket(formObject)
{
	$.post('/p/addToBasket.php', $(formObject).serialize(), function(added)
	{
		$('#basketSummaryOverview').load('/p/basketSummaryOverview.php');
		alert(added, 500, 400);
	});
	return false;
}



function roundNumber(num, dec) 
{
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}






// borrowed functions

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

