﻿
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};


/*
*
* Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
* 
* Version 1.0
* Demo: http://www.texotela.co.uk/code/jquery/numeric/
*
* $LastChangedDate$
* $Rev$
*/

/*
* Allows only valid characters to be entered into input boxes.
* Note: does not validate that the final text is a valid number
* (that could be done by another script, or server-side)
*
* @name     numeric
* @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
* @param    callback     A function that runs if the number is not valid (fires onblur)
* @author   Sam Collett (http://www.texotela.co.uk)
* @example  $(".numeric").numeric();
* @example  $(".numeric").numeric(",");
* @example  $(".numeric").numeric(null, callback);
*
*/
jQuery.fn.numeric = function(decimal, callback) {
	decimal = decimal || ".";
	callback = typeof callback == "function" ? callback : function() { };
	this.keypress(
		function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if (key == 13 && this.nodeName.toLowerCase() == "input") {
				return true;
			}
			else if (key == 13) {
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if (key < 48 || key > 57) {
				/* '-' only allowed at start */
				if (key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) {
					allow = false;
				}
				// check for other keys that have special purposes
				if (
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				) {
					allow = false;
				}
				else {
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if (typeof e.charCode != "undefined") {
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if (e.keyCode == e.which && e.which != 0) {
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if (e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field
				if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) {
					allow = true;
				}
			}
			else {
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function() {
			var val = jQuery(this).val();
			if (val != "") {
				var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
				if (!re.exec(val)) {
					callback.apply(this);
				}
			}
		}
	);
	return this;
}




/// Restores the state of the the product list display
function InitProductListView() {
	if (jQuery.cookie('ProductListStyle') == 'table')
		SetProductListView($('a.style_switch_table_view'));
	else
		SetProductListView($('a.style_switch_grid_view'));
}


/// Sets the product list display mode
function SetProductListView(/*element*/element) {
	$('a.style_switch_table_view,a.style_switch_grid_view').removeClass('selected');
	element.addClass('selected');

	if (element.hasClass('style_switch_table_view')) {
		$('div.product_canvas_grid').removeClass('product_canvas_grid').addClass('product_canvas_table');
		// Odd coloration
		$('div.product_canvas_table div.product:even').addClass('even');

		jQuery.cookie('ProductListStyle', 'table');
	}
	else {
		$('div.product_canvas_table').removeClass('product_canvas_table').addClass('product_canvas_grid');
		jQuery.cookie('ProductListStyle', 'grid');
	}
}

function openCenteredWindowNoScroll(url, height, width) {
	var left = Math.floor((screen.width - width) / 2);
	var top = Math.floor((screen.height - height) / 2);
	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
	winParms += "," + "titlebar=no,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,alwaysRaised=yes,AlwaysOnTop=yes";
	popupWindow = window.open(url, "", winParms);
}

// Opens a popup window for the specified product url
function OpenProductPopup(/*string*/url) {
	$.modal(
		'<iframe src="' + url + '" height="675" width="100%" style="border:0;background:none;">', {
			containerCss: {
				backgroundColor: "#fff",
				borderColor: "#000000",
				borderWidth: "0px",
				height: 675,
				padding: 0,
				width: 640
			},
			overlayClose: true,
			appendTo: 'form'
		}
	);
}

// Closes the popup window
function ClosePopup() {
	$.modal.close();
};

function do_print() {
	window.print();
}


// Loads and displays the ajax cart
function LoadCart() {
	$.get('CartHandler.ashx?dt=' + new Date().getTime(), function(xml) {
		var ph = $('#miniCartPlaceholder #cartContentsPlaceholder #cartContents');
		ph.empty();

		var content = '<ol>';

		$(xml).find('Cart').each(function() {
			var totalProducts = $(this).find('CartItem').length;

			if (totalProducts == 0) {
				$('#cartContentsPlaceholder .mini_basket_empty').show();
				$('#miniCartPlaceholder #cartTotal').html('0.00 &euro;');
			}
			else {
				$('#miniCartPlaceholder #cartTotal').html($(xml).find("Total").text() + $(xml).find('Currency').text());

				$('#cartContentsPlaceholder .mini_basket_full').show();

				$(this).find('CartPart').each(function() {
					$(this).find('CartItem').each(function() {

						var decimalDigitsAllowed = parseInt($(this).find('MeasurementUnit').attr("DecimalDigitsAllowed"));

						content += '<li class="item">';
						content += '<span class="mbc_qty">' +
													'<input type="hidden" name="mincart_cartItemId" value="' + $(this).attr("ID") + '" />' +
													'<input type="text" class="quantity" name="minicart_quantity_' + $(this).attr("ID") + '" value="' + $(this).find("Quantity").text() + '" />\n' +
												'</span>';
						content += '<span class="mbc_details">' +
													$(this).find('Product').text() +
													' <strong>' + $(this).find("TotalPrice").text() + $(xml).find('Currency').text() + '</strong>' +
												'</span>';
						content += '<span class="mbc_delete">' +
													'<a href="javascript:DeleteCartItem(' + $(this).attr("ID") + ')" class="remove-item">X</a>' +
												'</span>';
						content += '</li>';
					});
				});

				content += '</ol>';

				$('#miniCartPlaceholder .mini_basket_buy').show();
				$('#miniCartPlaceholder .mini_basket_update').show();
			}
		});

		ph.append(content);

		InitNumeric();
	});
};


function ChangeQuantity(/*obj*/element, /*decimal*/amount) {
	var input = $(element).parents('td:first').find('input:text');
	var value = input.val().replace(',', '.');

	var dVal = parseFloat(value);
	if (!isNaN(dVal))
		dVal += amount;

	if (dVal >= 0) {
		input.val(dVal.toString().replace('.', ','));
	}
};
