var locker = new Locker();
var motif_table_locker = new Locker();
var send_order_locker = new Locker();
var change_payment_locker = new Locker();

var labels = $H({'1' : $H({'initiated' : false, 'chars_notification' : false, 'current_product' : '', 'current_color' : ''})});
var active_label = '1';

var disc_table = new Hash();

var products = new Hash();
var product_identifiers = new Array();
var products_loaded = false;

var colors = new Hash();
var color_identifiers = new Array();
var colors_loaded = false;

var msgs_table = new Hash();
var messages_loaded = false;

var optim_texts = new Hash();
var optim_texts_loaded = false;

var project_id = '';
var fract_price = false;
var use_discounts = false;
var use_colors = false;
var use_coupons = false;
var use_aweber = false;
var site_vpath = '';
var currency = '';
var motifs_path = '';
var max_txt_len = 0;
var restrict_max_text_length = false;
var coupon_discount = 0;
var use_credit_limit = false;
var total_threshold = 0;
var use_for_methods = new Array();
var payment_method = '';
var use_motifs_selector = true;
var use_samples_rendering = true;
var allow_email_stub = false;
var email_stub_string = '';
var color_selector_type = 'radio'; 

/**
* initialization procedure on page loaded
*/ 
function initial_loading() 
{
	Event.observe('navnelapper1', 'click', on_design_selection);
	reset_payment_methods_selector();
	set_color_selector_type();
	load_messages();
}

/**
* toggle progressbar visibility
*/
function toggle_progressbar_visibility() 
{
	if ($('process_loader_container'))
	{
		$('process_loader_container').toggle();			
	}

	if ($('submit_button_container'))
	{
		$('submit_button_container').toggle();			
	}
}

/**
* set first payment method selected
*/ 
function reset_payment_methods_selector() 
{
	if ($('main'))
	{
		var pm_existing = $('main').select('input[id^="payment_method_"]').each(function(item){
			if (item.hasAttribute('checked')) {
				item.checked = true;	
			} else {
				item.checked = false;
			}
		});
	}
	
	if (!$('klarna-monthly-cost-box')) 
	{ 
		toggle_progressbar_visibility();
	}
}

/**
* set color selector type - radio or drop-down menu
*/ 
function set_color_selector_type() 
{
	if ($('main'))
	{
		var color_selector_exists = $('main').select('input[id^="color_button_'+active_label.toString()+'_"]');
		
		if (color_selector_exists.length == 0)
		{
			color_selector_type = 'select';
		}
	}
}

/**
* send request to load project properties
*/ 
function load_project_props() 
{
	new Ajax.Request(ajax_path+'project_props.php',{method:"post", parameters : $H({'site_cpath' : site_cpath}).toQueryString(), onSuccess:onSusccessLoadProjectProps});
}

/**
* loading project properties from xml string
*/ 
function onSusccessLoadProjectProps(transport)
{
	//alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
		fract_price	= data.fract_price;
		currency	= data.currency_name;
		site_vpath	= data.server_vpath;
		motifs_path = data.motifs_path;
		project_id  = data.project_id;
		max_txt_len = data.max_text_length;
		use_discounts = data.use_discounts;
		use_colors = data.use_colors;
		use_coupons = data.use_coupons;
		use_aweber = data.use_aweber;
		use_credit_limit = data.use_credit_limit;
		total_threshold = data.total_threshold;
		use_for_methods = data.use_for_methods;
		use_motifs_selector = data.use_motifs_selector;
		use_samples_rendering = data.use_samples_rendering;
		restrict_max_text_length = data.restrict_max_text_length;
		allow_email_stub = data.allow_email_stub;
		email_stub_string = data.email_stub_string;
		
		if ((use_discounts == true) && $('discount_amt_container'))
		{
			$('discount_amt_container').style.display = 'block';
		}
		
		if (use_coupons == true)
		{
			if ($('coupon_code_container'))
			{
				$('coupon_code_container').style.display = 'block';
			}
			
			if ($('coupon_code_stub'))
			{
				$('coupon_code_stub').style.display = 'none';
			}
		}
		else
		{
			if ($('coupon_code_container'))
			{
				$('coupon_code_container').style.display = 'none';
			}
			
			if ($('coupon_code_stub'))
			{
				$('coupon_code_stub').style.display = 'block';
			}
		}

		if (use_aweber == true)
		{
			if ($('signup_checkbox_container'))
			{
				$('signup_checkbox_container').style.display = 'block';
			}
		}
		else
		{
			if ($('signup_aweber'))
			{
				$('signup_aweber').checked = false;
			}
		}
		
		if ( $('coupon_code') && ($('coupon_code').value != '') ) {
			check_coupon();
		}
	
		load_products();
	}
}

/**
* send request to load products table
*/ 
function load_products() 
{
	new Ajax.Request(root_prefx+'xml/products.xml',{method:"get", onSuccess:onSusccessLoadProducts});
}

/**
* loading products table from xml
*/ 
function onSusccessLoadProducts(transport)
{
	//alert(transport.responseText);
	
	var products_xml = transport.responseXML.getElementsByTagName('product');
	
	if (products_xml.length > 0)
	{
		for (var i = 0; i < products_xml.length; i++)
		{
			var atts = products_xml[i].attributes;
			var lbls = products_xml[i].getElementsByTagName('selector_label');
			var tmbs = products_xml[i].getElementsByTagName('selector_thumbnail');
			var imgs = products_xml[i].getElementsByTagName('selector_fullsize');
			
			var product_data = new Hash();

			if (lbls.length > 0) {
				product_data.set('description', lbls[0].firstChild.nodeValue);
			}

			if (tmbs.length > 0) {
				product_data.set('thumbnail', tmbs[0].firstChild.nodeValue);
			}

			if (imgs.length > 0) {
				product_data.set('fullsize', imgs[0].firstChild.nodeValue);
			}

			var identifier = 'product_'+i.toString();
			
			for (j = 0; j < atts.length; j++) 
			{
				var att = atts.item(j);
				var att_key = att.nodeName.toLowerCase();
				var att_value = att.nodeValue;
				
				switch (att_key)
				{
					case 'id':
						identifier = att_value;
						//product_data.set('description', products_xml[i].firstChild.nodeValue);
						break;
					default:
						product_data.set(att_key, att_value);
						break;
				}
			}
			
			products.set(identifier, product_data);
		}
	}
	
	//alert(products.inspect());
	
	products_loaded = true;
	product_identifiers = products.keys();
	
	if (use_motifs_selector == true) {
		select_category('');
	}
	
	load_discounts();
}

/**
* send request to load colors table
*/ 
function load_colors() 
{
	new Ajax.Request(root_prefx+'xml/colors.xml',{method:"get", onSuccess:onSusccessLoadColors});
}

/**
* loading colors table from xml
*/ 
function onSusccessLoadColors(transport)
{
	var colors_xml = transport.responseXML.getElementsByTagName('color');
	
	if (colors_xml.length > 0)
	{
		for (var i = 0; i < colors_xml.length; i++)
		{
			var atts = colors_xml[i].attributes;
			
			var color_data = new Hash();
			
			var identifier = 'color_'+i.toString();
			for (j = 0; j < atts.length; j++) 
			{
				var att = atts.item(j);
				var att_key = att.nodeName.toLowerCase();
				var att_value = att.nodeValue;
				
				switch (att_key)
				{
					case 'id':
						identifier = att_value;
						color_data.set('description', colors_xml[i].firstChild.nodeValue);
						break;
					default:
						color_data.set(att_key, att_value);
						break;
				}
			}
			
			colors.set(identifier, color_data);
		}
	}
	
	//alert(colors.inspect());
	
	colors_loaded = true;
	color_identifiers = colors.keys();
	labels.set(active_label, labels.get(active_label).merge({'current_product' : product_identifiers[0]}));
	change_color(1, color_identifiers[0]);
	update_label_section(1, '');
}

/**
* send request to load messages table
*/ 
function load_messages() 
{
	new Ajax.Request(root_prefx+'xml/messages.xml',{method:"get", onSuccess:onSusccessLoadMessages, onFailure:onFailureLoadMessages});
}

/**
* loading messages table from xml
*/ 
function onSusccessLoadMessages(transport)
{
	
	var msg_xml = transport.responseXML.getElementsByTagName('message');
	
	if (msg_xml.length > 0)
	{
		for (var i = 0; i < msg_xml.length; i++)
		{
			var atts = msg_xml[i].attributes;
			var value = msg_xml[i].firstChild.nodeValue
			
			for (j = 0; j < atts.length; j++) 
			{
				var key = atts.item(j).nodeValue;
				msgs_table.set(key, value);
				break;
			}
			
		}
		
		messages_loaded = true;
	}
	
	//alert(msgs_table.inspect());
	
	load_optim_text();
}

/**
* despite messages loading failed, the process must go on
*/
function onFailureLoadMessages()
{
	load_optim_text();
}

/**
* getting message text by message id
* @param msg_id string identifier of message 
* @param substitutes array list of strings for replacement in message text by index 
*/
function get_msg_by_id(msg_id, substitutes)
{
	var text = msgs_table.get(msg_id);
	
	if ((substitutes != null) && (substitutes.length > 0))
	{
		for (i = 0; i < substitutes.length; i++)
		{
			text = text.replace('{'+i.toString()+'}', substitutes[i]);
		}
	}
	
	return text;
}

/**
* send request to load optimization permissions options table
*/ 
function load_optim_text() 
{
	new Ajax.Request(root_prefx+'xml/optimization.xml',{method:"get", onSuccess:onSusccessLoadOptText, onFailure:onFailureLoadOptText});
}

/**
* loading optimization permissions options table from xml
*/ 
function onSusccessLoadOptText(transport)
{
	//alert(transport.responseText);
	
	var opt_xml = transport.responseXML.getElementsByTagName('opt_text');
	
	if (opt_xml.length > 0)
	{
		for (var i = 0; i < opt_xml.length; i++)
		{
			var atts = opt_xml[i].attributes;
			var value = opt_xml[i].firstChild.nodeValue
			
			for (j = 0; j < atts.length; j++) 
			{
				var key = atts.item(j).nodeValue;
				optim_texts.set(key, value);
				break;
			}
		}
		
		optim_texts_loaded = true;
	}
	
	//alert(optim_texts.inspect())
	
	load_project_props();
}

/**
* despite messages loading failed, the process must go on
*/
function onFailureLoadOptText()
{
	load_project_props();
}

/**
* send request to load discounts table from xml
*/ 
function load_discounts() 
{
	new Ajax.Request(root_prefx+'xml/discounts.xml', {method:"get", onSuccess:onSusccessLoadDiscounts, onFailure:onFailureLoadDiscounts});
}

/**
* loading discounts table from xml
*/ 
function onSusccessLoadDiscounts(transport) 
{
	//alert(transport.responseText);
	
	var disc_xml = transport.responseXML.getElementsByTagName('discount');
	
	if (disc_xml.length > 0)
	{
		for (var i = 0; i < disc_xml.length; i++)
		{
			var atts = disc_xml[i].attributes;
			var h_key = '', h_value = '';

			for (j = 0; j < atts.length; j++) 
			{
				var att = atts.item(j);
				var att_key = att.nodeName.toLowerCase();
				var att_value = parseInt(att.nodeValue);
				
				switch (att_key)
				{
					case 'quantity_value':
						h_key = att_value;
						
						break;
					case 'percent_value':
						h_value = att_value;
						
						if (h_key != 0)
						{
							disc_table.set(h_key, h_value);
						}
						
						break;
				}
			}
		}
	}
	
	if (use_colors == true)
	{
		load_colors();
	}
	else
	{
		change_price(1, product_identifiers[0]);
		update_label_section(1, '');
	}
}

/*
* despite discounts loading failed, process must go on
*/
function onFailureLoadDiscounts()
{
	if (use_colors == true)
	{
		load_colors();
	}
	else
	{
		change_price(1, product_identifiers[0]);
		update_label_section(1, '');
	}
}

/** 
* send ajax request for picture render
* @param label_section identifier of section 
*/
function render_label(label_section)
{
	//alert(labels.inspect());
	if (!locker.locked())
	{
		locker.lock();
		
		var color_selected = '';
		
		if (use_colors == true)
		{
			if (color_selector_type == 'radio')
			{
				color_selected = Form.getInputs('Form','radio','color_button_'+label_section.toString()).find(function(radio) { return radio.checked; }).value;
			}
			else if ($('label_color'+label_section.toString()))
			{
				color_selected = $('label_color'+label_section.toString()).value;
			}
		}
		
		if ( ($F('textfield'+label_section.toString()+'_1').length == 0) && ($F('textfield'+label_section.toString()+'_2').length == 0) && ($F('textfield'+label_section.toString()+'_3').length == 0) && ($F('final_image'+label_section.toString()).length == 0) )
		{
			current_label_state = false;
		}
		else
		{
			current_label_state = true;	
		}
		
		labels.set(label_section.toString(), labels.get(label_section.toString()).merge({'initiated' : current_label_state}));

		if (use_samples_rendering == true)
		{
			var lines = new Hash();
	
			if ($('main'))
			{
				var section_textfields = $('main').select('input[id^="textfield'+label_section.toString()+'_"]').each(function(item){
					var line_name  = 'line'+$(item).readAttribute('name').replace('textfield'+label_section.toString()+'_', '');
					var line_value = $(item).value;
					lines.set(line_name, line_value);
				});
			}
			
			new Ajax.Request(ajax_path+'render_label.php', {method:"post", parameters : $H({label_section : label_section.toString(), 'label_name' : $F('label_name_'+label_section.toString()), lines : Object.toJSON(lines), final_image : $F('final_image'+label_section.toString()), font : $F('font'+label_section.toString()), align : $F('align'+label_section.toString()), color : color_selected, site_apath : site_apath, site_cpath : site_cpath, label_type : 'normal'}).toQueryString(), onSuccess:render_label_actions, onFailure : safe_failure});
		}
		else
		{
			locker.unlock();

			if ($('label_status_'+label_section))
			{
				$('label_status_'+label_section).value = label_section;
			}
					
			if ($('label_name_'+label_section))
			{
				$('label_name_'+label_section).value = 'empty';
			}

			update_section(label_section);
		}
	}
}

/**
* show rendered picture
*/
function render_label_actions(transport)
{
	locker.unlock();
	//alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	//addition of just rendered image
	if ( (data.label) && (data.label_section) )
	{
		
		if ($('label_status_'+data.label_section))
		{
			$('label_status_'+data.label_section).value = data.label_section;
		}
				
		if ($('label_name_'+data.label_section))
		{
			$('label_name_'+data.label_section).value = data.label;
		}

		$('label_cell'+data.label_section).update('<img src="'+root_prefx+'output/'+data.label+'.jpg" class="label_image" border="0" />');
		
		// display image in box 
		switch (project_id)
		{
			case 'idband':
				render_label_idband(data.label_section);//num);
				break;
			default:
				update_label_section(data.label_section, data.label);
				break;
		}
	}
}

/**
* additional idband rendering actions
* @param label_section identifier of section 
*/
function render_label_idband(label_section)
{
	if (!locker.locked())
	{
		switch (project_id)
		{
			case 'idband':
				var colorradio = -1;
				var product_index = 0;
				
				products.each(function(product_data) 
				{
					if ($('radiobutton'+label_section+'_'+product_data.key))
					{
						//alert('radiobutton'+label_section+'_'+product_data.key+' checked = '+$('radiobutton'+label_section+'_'+product_data.key).checked);
						
						if ($('radiobutton'+label_section+'_'+product_data.key).checked)
						{
							colorradio = product_index;//$("radiobutton_order"+label_section+"_"+product_data.key).value;
						}
					}
					
					product_index++;
				});
				
				if (colorradio != -1)
				{
					backpic = site_vpath+"wristband/"+colorradio+"_"+colorradio+".gif";
					$("image_cell"+label_section+"_1").style.background="url('" + backpic + "')  no-repeat";
					$("colorbandhid").value = "true"
				}
				break;
			default:
				break;
		}

		locker.lock();
		
		var color_selected = '';
		
		if (use_colors == true)
		{
			if (color_selector_type == 'radio')
			{
				color_selected = Form.getInputs('Form','radio','color_button_'+label_section.toString()).find(function(radio) { return radio.checked; }).value;
			}
			else
			{
				color_selected = $('label_color'+n.toString()).value;
			}
		}

		var lines = new Hash();

		if ($('main'))
		{
			var section_textfields = $('main').select('input[id^="textfield'+label_section.toString()+'_"]').each(function(item){
				var line_name  = 'line'+$(item).readAttribute('name').replace('textfield'+label_section.toString()+'_', '');
				var line_value = $(item).value;
				lines.set(line_name, line_value);
			});
		}
		
		new Ajax.Request(ajax_path+'render_label.php', {method:"post", parameters : $H({label_section:label_section.toString(), 'label_name' : $F('label_name_'+label_section.toString()), lines : Object.toJSON(lines), final_image : $F('final_image'+label_section.toString()), font : $F('font'+label_section.toString()), align : $F('align'+label_section.toString()), color : color_selected, site_apath : site_apath, site_cpath : site_cpath, site_apath : site_apath, label_type : 'small'}).toQueryString(), onSuccess:render_label_actions_idband, onFailure : safe_failure});
	}
}

/**
* additional rendered picture
*/
function render_label_actions_idband(transport)
{
	locker.unlock();
	//alert(transport.responseText);
	var data = eval('(' + transport.responseText + ')');
	//addition of just rendered image
	if ( (data.label) && (data.label_section) )
	{
		// display image in box 
		update_label_section(data.label_section, data.label);		
	}
}

/**
* send AJAX request to update section 
* @param label_section integer number of label section to be handled
*/
function update_section(label_section)
{
	if (labels.get(label_section.toString()).get('initiated') == true)
	{
		switch (project_id)
		{
			case 'idband':
			break;
			default:
				update_label_section(label_section, $F('label_name_'+label_section.toString()));
			break;
		}
	}
}

/**
* update current label section representation 
* @param label_section integer number of label section to be handled
* @param image_label string image file name
*/
function update_label_section(label_section, image_label)
{	
	products.each(function(product_data) 
	{
		if ($('radiobutton'+label_section+'_'+product_data.key))
		{
			if ($('radiobutton'+label_section+'_'+product_data.key).checked)
			{
				switch (project_id)
				{
					case 'idband':
						if (image_label != '') {
							$('image_cell'+label_section+'_2').update('<img src="'+root_prefx+'output/'+image_label+'.jpg" border="0" />');
						}
					break;
					case 'dorskilt':
						//alert(product_data.inspect());
						var product_thumbnail = product_data.value.get('thumbnail');
						if ((product_thumbnail != undefined) && (product_thumbnail != '')) {
							$('image_cell'+label_section+'_2').update('<img src="'+root_prefx+'images/'+product_thumbnail+'" border="0" />');
						}
					break;
					default:
						if ( project_id.indexOf('stamp') == -1 )
						{
							$('image_cell'+label_section+'_1').update('&nbsp;');
						}
							
						if (product_data.value.get('iron') == 'true')
						{
							if ( project_id.indexOf('stamp') == -1 )
							{
								if (image_label.length > 0) {
									$('image_cell'+label_section+'_1').update('<img src="'+root_prefx+'output/'+image_label+'.jpg" class="label_image_summary" />');
								}
								
								$('image_cell'+label_section+'_1').className = 'label_area';
							}
							else
							{
								$('housing_stamp_image'+label_section).className = "visible";
							}
							
							$('text_cell'+label_section+'_1').className = "visible";
						}
						else
						{
							if ( project_id.indexOf('stamp') == -1 )
							{
								$('image_cell'+label_section+'_1').className = 'label_area_disabled';
							}
							else
							{
								$('housing_stamp_image'+label_section).className = "hidden";
							}
							
							$('text_cell'+label_section+'_1').className = "hidden";
						}
						
						$('image_cell'+label_section+'_2').update('&nbsp;');
							
						if (product_data.value.get('self') == 'true')
						{
							if (image_label.length > 0) {
								$('image_cell'+label_section+'_2').update('<img src="'+root_prefx+'output/'+image_label+'.jpg" class="label_image_summary" />');
							}
							$('image_cell'+label_section+'_2').className = 'label_area';
							$('text_cell'+label_section+'_2').className = "visible";
						}
						else
						{
							$('image_cell'+label_section+'_2').className = 'label_area_disabled';
							$('text_cell'+label_section+'_2').className = "hidden";
						}
						
						
						if ( (product_data.value.get('iron') == 'true') && (product_data.value.get('self') == 'true') )
						{
							$('image_cell'+label_section+'_sign').update('+');
						}
						else
						{
							$('image_cell'+label_section+'_sign').update('&nbsp;');	
						}
					break;	
				}
			}
		}
	});
}

/** 
* send ajax request for picture removal
* @param label_section integer identifier of section 
* @param label_name string name of label image to be removed 
*/
function remove_label(label_section, label_name)
{
	//alert(label_name);
	new Ajax.Request(ajax_path+'remove_label.php', {method:"post", parameters : $H({label_section:label_section.toString(), 'label_name' : label_name, site_apath : site_apath}) });
}

/** 
* function generates icons grid for motif table
* @param category_name string name of category containing images  
*/
function select_category(category_name)
{
	if (!motif_table_locker.locked())
	{
		motif_table_locker.lock();

		//new Ajax.Request(ajax_path+'motif_table.php', {method:"post", parameters : $H({'category_name' : category_name, 'motifs_path' : motifs_path, 'site_apath' : site_apath}), onSuccess : select_category_actions, onFailure : safe_motif_unlock });
		new Ajax.Request(ajax_path+'motif_table.php', {method:"post", parameters : $H({'category_name' : category_name, 'site_cpath' : site_cpath}), onSuccess : select_category_actions, onFailure : safe_motif_unlock });
	}
}

/**
* form icons grid
*/
function select_category_actions(transport)
{
	motif_table_locker.unlock();
	
	//alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	
	$('icons_grid').update(data.icons_grid);
	
	if (data.category.length > 0)
	{
		var selected_tabs = $('tabs').getElementsBySelector('[class="tab_selected"]')
		
		if (selected_tabs.length > 0)
		{
			selected_tabs.each(function(tab_element) {tab_element.className = 'tab';});
		}
		
		if ($(data.category))
		{
			$(data.category).className = 'tab_selected';
		}
 	}
}

/**
* function disable locker case of ajax request for motif table generation failed
*/
function safe_motif_unlock()
{
	motif_table_locker.unlock();
}

/**
* function disable locker case of ajax request for picture generation failed
*/
function safe_failure()
{
	locker.unlock();
}

/*
* change label color processing
* @param n integer identifier of section
* @param color string identifier of color
*/
function change_color(n,color_identifier)
{
	if (color_selector_type != 'radio')
	{
		color_identifier = $('label_color'+n.toString()).value;
	}
	
	colors.each(function(color_data) 
	{
		if (color_data.key == color_identifier)
		{
			var checked_state = 'checked';	
			
			if ($('label_color'+n.toString()))
			{
				($('label_color'+n.toString())).value = color_data.value.get('description');
			}
			
			labels.set(n.toString(), labels.get(n.toString()).merge({'current_color' : color_identifier}));
		}
		else
		{
			var checked_state = '';	
		}
		
		//alert(color_data.key+' / state = '+checked_state);
	
		if ($('color_button_'+n.toString()+'_'+color_data.key))
		{
			($('color_button_'+n.toString()+'_'+color_data.key)).checked = checked_state;
		}

		if ($('btm_color_button_'+n.toString()+'_'+color_data.key))
		{
			($('btm_color_button_'+n.toString()+'_'+color_data.key)).checked = checked_state;
		}
	});

	render_label(n);
	change_price(n, '');
}
/**
* change picture on the label
* @param category_name string current category name
* @param motifpic string current picture
*/
function change_motif(category_name, motifpic)
{
	var allow_to_change = true;
	
	// if text length check should be performed
	if (max_txt_len > 0)
	{
		for (l = 1; l <= 3; l++)
		{
			if ($('textfield'+active_label+'_'+l))
			{
				var txt_len = $('textfield'+active_label+'_'+l).value;
				
				if (txt_len.length > max_txt_len)
				{
					// if strict limitation should be used - no text longer than max_txt_len
					if (restrict_max_text_length == true)
					{
						var substs = [max_txt_len.toString()];
						alert(get_msg_by_id('max_text_length_restricted', substs));
						allow_to_change = false;
						break;
					}
					// if only warning for text longer than max_txt_len
					else 
					{
						if (labels.get(parseInt(active_label)).get('chars_notification') == false)
						{
							var substs = [max_txt_len.toString()];
							alert(get_msg_by_id('max_text_length_reached', substs));
							labels.set(active_label, labels.get(active_label).merge({'chars_notification' : true}));
						}
						break;
					}
				}
			}
		}
	}
	
	if (!allow_to_change)
	{
		return;
	}
	
	new Ajax.Request(ajax_path+'motif_change.php', {method:"post", parameters : $H({'category_name' : category_name, 'motif_img' : motifpic, 'site_cpath' : site_cpath}), onSuccess : change_motif_actions });
}

/**
* selected image highlighting
*/
function change_motif_actions(transport)
{
	//alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	
	if ((data.result == 'ok') && (data.category_name != ''))
	{
		if ($('final_image'+active_label))
		{
			$('final_image'+active_label).value = data.motif_img;//motifpic;
		}
		
		if ($('current_image'))
		{
			$('current_image').remove();
		}
		
		var current_image_identifier = data.motif_img.slice(0, -4);//motifpic.slice(0, -4);
		
		if ($(current_image_identifier)) 
		{	
			Insertion.Bottom(current_image_identifier, data.selector);
		}
		
		render_label(active_label);
		
//		if ((max_txt_len > 0) && (labels.get(parseInt(active_label)).get('chars_notification') == false) && $('final_image'+active_label))
//		{
//			var final_image = $('final_image'+active_label).value;
//			
//			if (final_image.length > 0)
//			{
//				for (l=1; l<=3; l++)
//				{
//					if ($('textfield'+active_label+'_'+l))
//					{
//						var txt_len = $('textfield'+active_label+'_'+l).value;
//						
//						if (txt_len.length >= max_txt_len)
//						{
//							alert(get_msg_by_id('max_text_length_reached', null));
//							labels.set(active_label, labels.get(active_label).merge({'chars_notification' : true}));
//							break;
//						}
//					}
//				}
//			}
//		}
	}
}

/**
* removal of motif picture
* @param n integer section identifier
*/ 
function hide_motif(n)
{
	
	if ($('final_image'+n))
	{
		if ($($F('final_image'+n)))
		{
			$($F('final_image'+n)).remove();
		}
		$('final_image'+n).value = '';
	}
	
	render_label(n);
}

function set_backimage(rowcnt,imgcnt)
{	
	//alert(site_vpath+' '+rowcnt+' '+imgcnt);
	
	if ($("colorbandhid"))
	{
	
		if ($("colorbandhid").value == "false")
		{
			backpic = site_vpath+"wristband/"+imgcnt+".gif";
		}
		else if ($("colorbandhid").value == "true")
		{						
			backpic = site_vpath+"wristband/"+imgcnt+"_"+imgcnt+".gif";
		}
	}
	
	//alert(backpic);
	
	$("image_cell"+rowcnt+"_1").style.background="url('" + backpic + "') no-repeat ";
}

/**
* changing price for a cell
* @param n integer identifier of section to be changed
* @param product_identifier string identifier of product
*/
function change_price(n, product_identifier)
{
	var price = 0;
	var price_color = 0;
	
	if (product_identifier == '')
	{
		product_identifier = labels.get(n.toString()).get('current_product');
	}
		
	if (use_colors == true)
	{
		color_identifier = labels.get(n.toString()).get('current_color');
		
		colors.each(function(color_data) 
		{
			if (color_data.key == color_identifier)
			{
				price_color = color_data.value.get('price');
			}
		});
	}
	
	//alert(products.inspect()+'  '+n.toString());
	products.each(function(product_data) 
	{
		if (product_data.key == product_identifier)
		{
			var checked_state = 'checked';	
			
			if ($('product'+n.toString()))
			{
				($('product'+n.toString())).value = product_data.value.get('description');
			}
			
			price = product_data.value.get('price');
			
			labels.set(n.toString(), labels.get(n.toString()).merge({'current_product' : product_identifier}));
		}
		else
		{
			var checked_state = '';	
		}
	
		if ($('radiobutton_order'+n.toString()+'_'+product_data.key))
		{
			($('radiobutton_order'+n.toString()+'_'+product_data.key)).checked = checked_state;
		}
		
		if ($('radiobutton'+n.toString()+'_'+product_data.key))
		{
			($('radiobutton'+n.toString()+'_'+product_data.key)).checked = checked_state;
		}
	});
	
	var quantity_used = 1;
	
	switch (project_id)
	{
		case 'idband':
			price = parseFloat($("size"+n.toString()).value);
			break;
		default:	
			if ($('quantity'+n.toString()))
			{
				quantity_used = parseInt($('quantity'+n.toString()).value);
			}
	}
	
	if (fract_price) // price is not integer
	{
		price = parseFloat(price); //(price).toFixed(2);
		price_color = parseFloat(price_color); //(price_color).toFixed(2);
		price = (price + price_color).toFixed(2);
	}
	else
	{
		price = parseInt(price);
		price_color = parseInt(price_color);
		price = price + price_color;
	}

	//alert('section = '+n+', product = '+product_identifier+', color price = '+price_color+', price = '+price+', qty = '+quantity_used);

	var discount_used = 0;
	
	if ((use_discounts) && (coupon_discount == 0))
	{
		var discount_items = disc_table.findAll(function(d){return quantity_used >= parseInt(d.key);});
		
		if ((discount_items != undefined) && (discount_items.length > 0))
		{
			discount_used = discount_items.pop().value;
		}
	
		if (isNaN(discount_used) || (discount_used == undefined))
		{
			discount_used = 0;
		}
	}
	else if ((use_coupons) && (coupon_discount != 0))
	{
		discount_used = coupon_discount;
	}
	
	if ($('disc_prc'))
	{
		$('disc_prc').update(discount_used);
	}
	
	var multiplier = ((100 - discount_used) / 100);
	
	if (fract_price) // price is not integer
	{
		var amount = (price * multiplier).toFixed(2);
		var result_price = (amount * quantity_used).toFixed(2);
	}
	else
	{
		var amount = Math.ceil(price * multiplier);
		var result_price = amount * quantity_used;
	}
	
	//alert(price);
	
	$('price'+n.toString()).innerHTML = price;

	if ($('price_whole'+n.toString())) // if discounts block exists
	{
		$('price_whole'+n.toString()).value = price;
	}

	if ($('price_hidden'+n.toString()))
	{
		$('price_hidden'+n.toString()).value = result_price;
	}
	
	if ($('amount_'+n.toString()))
	{
		$('amount_'+n.toString()).value = amount;
	}
	
	if ($('price_label'+n.toString()))
	{
		$('price_label'+n.toString()).innerHTML = result_price;
	}
	
	update_total();
	update_section(n);
}

/**
* updating total
*/
function update_total()
{
	totalinnerHTML = 0;
	
	if ($('handling_fee_amt'))
	{
//		totalinnerHTML = totalinnerHTML + parseFloat($('handling_fee_amt').innerHTML);	
		totalinnerHTML = totalinnerHTML + parseFloat($('handling_fee_amt').value);	
	}
	
	if ($('disc_amt'))
	{
		full_totalinnerHTML = totalinnerHTML;
	}
	
	labels.each(function(label_data)
	{
		if (fract_price) // price is not integer
		{
			totalinnerHTML = totalinnerHTML + parseFloat($('price_label' + label_data.key).innerHTML);
		}
		else
		{
			totalinnerHTML = totalinnerHTML + parseInt($('price_label' + label_data.key).innerHTML);
		}
		
		var quantity_used = 1;
		
		if ((project_id != 'idband') && $('quantity' + label_data.key))
		{
			quantity_used = parseInt($('quantity' + label_data.key).value);
		}
		
		if ($('disc_amt'))
		{
			var price_whole = 0;
			
			if (fract_price) // price is not integer
			{
				price_whole = (quantity_used * $('price_whole' + label_data.key).value).toFixed(2);
			}
			else
			{
				price_whole = quantity_used * parseInt($('price_whole' + label_data.key).value);
			}
			
			full_totalinnerHTML = full_totalinnerHTML + price_whole;
		}
	});
	
	//alert(full_totalinnerHTML);
	
	$('total').innerHTML = totalinnerHTML.toFixed(2);
	
	if ($('disc_amt'))
	{
		if (fract_price) // price is not integer
		{
			$('disc_amt').innerHTML = (full_totalinnerHTML - totalinnerHTML).toFixed(2);
		}
		else
		{
			$('disc_amt').innerHTML = (full_totalinnerHTML - totalinnerHTML);
		}
	}
	
	if ($('klarna-monthly-cost-box'))
	{
		new Ajax.Request(ajax_path+'klarna_calc_cost.php',{ method:'post', parameters:$H({site_cpath : site_cpath, host_name : vh_name, total_price: $('total').innerHTML}), onSuccess:onSuccessKlarnaCalcCost});
	}
}

/**
* remove label
* @param n integer identifier of section 
*/
function del_design(n)
{
	if (confirm(get_msg_by_id('design_deleting_confirmation', null)))
	{
		remove_label(n, $F('label_name_'+n.toString()));
		
		//clearing item from the cart	
		if ($('order_label'+n.toString()))
		{
			total_labels_active = labels.findAll(function(label_data) { return label_data.value.get('initiated'); } );
			
			if (labels.size() > 1)
			{
				if ($('order_label'+n.toString()))
				{
					$('order_label'+n.toString()).remove();
				}
				
				if ($('navnelapper'+n.toString()))
				{
					$('navnelapper'+n.toString()).remove();	
				}

				labels.unset(n.toString());
			}
			else
			{
				$('label_status_'+n.toString()).value = '0';
				$('final_image'+n.toString()).value = '';
				$('textfield'+n.toString()+'_1').value = '';
				$('textfield'+n.toString()+'_2').value = '';
				$('textfield'+n.toString()+'_3').value = '';
				$('label_cell'+n.toString()).update('');
				
				//$('image_cell'+n.toString()+'_1').update('&nbsp;');
				
				if ($('image_cell'+n.toString()+'_2'))
				{
					$('image_cell'+n.toString()+'_2').update('&nbsp;');
				}
				
				////////////////////////////////////////////////////////
				switch (project_id)
				{
					case 'idband':
						var colorradio = -1;
						var product_index = 0;
						
						products.each(function(product_data) 
						{
							if ($('radiobutton'+n.toString()+'_'+product_data.key))
							{
								if ($('radiobutton'+n.toString()+'_'+product_data.key).checked)
								{
									colorradio = product_index;
								}
							}
							
							product_index++;
						});
						
						if (colorradio != -1)
						{
							backpic = site_vpath+"wristband/"+colorradio+"_"+colorradio+".gif";
							//alert(backpic);
							$("image_cell"+n.toString()+"_1").style.background="url('" + backpic + "')  no-repeat";
							$("colorbandhid").value = "true"
						}
						break;
					default:
						if ( project_id.indexOf('stamp') == -1 )
						{
							$('image_cell'+n.toString()+'_1').update('&nbsp;');
						}
						break;
				}
				////////////////////////////////////////////////////////
				
				labels.set(n.toString(), labels.get(n.toString()).merge({'initiated' : false, 'chars_notification' : false}));
		
			}
			
			active_label = labels.keys().max().toString();
			
			reset_selected_design(active_label);
		}
	}
	
	update_total();
}

/**
* add new navigation panel
*/
function add_design()
{
	new_label_index = parseInt(labels.keys().max())+1;
	labels.set(new_label_index.toString(), $H({'initiated' : false, 'chars_notification' : false}));	
	active_label = new_label_index.toString();
	
	if (products_loaded == false)
	{
		load_products();	
	}
	
	if ((colors_loaded == false) && (use_colors == true))
	{
		load_colors();	
	}
	
	new Ajax.Request(ajax_path+'add_design.php',{method:"post", parameters : $H({section_no : new_label_index, site_apath : site_apath, site_cpath : site_cpath, skin_name: skin_name}), onSuccess:onSusccessInsertDesign});

}

/**
* process succsessful design section request
*/
function onSusccessInsertDesign(transport)
{
//	alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');

	if (data.result == 'ok')
	{
		var divTag = document.createElement('div');
		
		divTag.innerHTML = data.design_item;
		divTag.setAttribute('id','navnelapper'+data.sect_no);
		
		$('navnelapperdiv').appendChild(divTag);
		
		$('navnelapper'+data.sect_no).addClassName('lab_general');
		
		Event.observe('navnelapper'+data.sect_no, 'click', on_design_selection);

		reset_selected_design(data.sect_no);
		
		new Ajax.Request(ajax_path+'add_cart_item.php',{method:"post", parameters : $H({section_no : data.sect_no, site_apath : site_apath, site_cpath : site_cpath, skin_name: skin_name}), onSuccess:onSusccessInsertCartItem});
	}
	else
	{
		alert(get_msg_by_id('design_adding_error', null));
	}
}

function on_design_selection()
{
	var selected_label = $(this).readAttribute('id').replace('navnelapper','');
	reset_selected_design(selected_label);
}

/**
* reset selected design
*/
function reset_selected_design(active_section)
{
	if (isNaN(active_section))
	{
		return;
	}
	
	var lab_selected = $('navnelapperdiv').select('div.lab_selected');

	if (lab_selected.length > 0)
	{
		lab_selected.each(function(elm){
			$(elm).removeClassName('lab_selected').addClassName('lab_unselected');
		});
	}
	
	var lab_unselected = $('navnelapperdiv').select('div.lab_unselected');
	
	if (lab_unselected.length != 1)
	{
		var lab_existing = $('navnelapperdiv').select('div[id^="navnelapper"]');
		
		if (lab_existing.length > 1)
		{
			if (lab_unselected.length == 0)
			{
				lab_existing.each(function(elm){
					$(elm).removeClassName('lab_initial').addClassName('lab_unselected');
				});
			}
			
			$('navnelapper'+active_section.toString()).removeClassName('lab_unselected').addClassName('lab_selected');
		}
	}
	else
	{
		$(lab_unselected[0]).removeClassName('lab_unselected').removeClassName('lab_selected').addClassName('lab_initial');
	}
	
	active_label = active_section;
}

/**
* process succsessful cart item request
*/
function onSusccessInsertCartItem(transport)
{
//	alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
		Insertion.Bottom('order_labels', data.cart_item);
		
		switch (project_id)
		{
			case 'idband':
				$('finalrowcnthid').value = data.sect_no
				break;
			default:
				break;
		}
		
		if (use_samples_rendering == false)
		{
			update_label_section(data.sect_no, '');
		}
		
		change_price(data.sect_no, product_identifiers[0]);
		change_color(data.sect_no, color_identifiers[0]);
	}
	else
	{
		alert(get_msg_by_id('design_adding_error', null));
	}
}

/**
* increases or decreases quantity of labels
* @param n integer identifier of section 
* @param direction integer flag of increasing or decreasing action
*/
function change_quantity(n, direction)
{
	var r_button_selected = product_identifiers[0];
	
	products.each(function(product_data)
	{
		if ($('radiobutton'+n+'_'+product_data.key))
		{
			if ($('radiobutton'+n+'_'+product_data.key).checked)
			{
				r_button_selected = product_data.key;
				throw $break;
			}
		}
	});

	var curr_quant = parseInt($('quantity'+n).value);

	switch (direction)
	{
		case -1:
			if (curr_quant > 1)
			{
				$('quantity'+n).value = curr_quant - 1;
			}
			
			change_price(n, r_button_selected);
			
			break;
		case 1:
			if (curr_quant < 9)
			{
				$('quantity'+n).value = curr_quant + 1;
			}
			
			change_price(n,r_button_selected);
			
			break;
		default:
			update_total();
			
			break;
	}
}

/**
* checks symbols entered in quantity
* @param e integer identifier of section 
*/
function check_symb(e)
{
	// Make sure to use event.charCode if available
	var p_key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);

	// Ignore special keys
	if (e.ctrlKey || e.altKey || p_key < 32)
	{
		return true;
	}
  
	p_key = String.fromCharCode(p_key);
  
	return /[\d]/.test(p_key);
}

/**
* checks entered value in range allowed
* @param n integer identifier of section 
*/
function check_val(n)
{
	var r_button_selected = product_identifiers[0];
	
	products.each(function(product_data)
	{
		if ($('radiobutton'+n+'_'+product_data.key))
		{
			if ($('radiobutton'+n+'_'+product_data.key).checked)
			{
				r_button_selected = product_data.key;
				throw $break;
			}
		}
	});
	
	var curr_quant = parseInt($('quantity'+n).value);
	
	if ((curr_quant < 1) || (isNaN(curr_quant)))
	{
		$('quantity'+n).value = '1';
	}
	else if (curr_quant > 9)
	{
		$('quantity'+n).value = '9';
	}
	
	change_price(n,r_button_selected);
}

/**
* check conditions on line text input allowed
* @param n integer section number
* @param l integer text line number
* @param e integer window event
*/
function check_chr_count(n, l, e)
{
	// if user already notified
	if (labels.get(n.toString()).get('chars_notification') == true) 
	{
		return true;
	}
	
	
	e = e || window.event;
	var target = e.target || e.srcElement;
	var code = e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode)

	switch (code){
		case 13:
		case 8:
		case 9:
		case 46:
		case 37:
		case 38:
		case 39:
		case 40:
			return true;
	}

	var input_allowed = true;
	
	if ($('textfield'+n+'_'+l) && $('final_image'+n))
	{
		var txt_len = $('textfield'+n+'_'+l).value;
		var final_image = $('final_image'+n).value;
		
		// if text length check should be performed, text length more than max_txt_len and motif already selected
		if ((max_txt_len > 0) && (txt_len.length >= max_txt_len) && (final_image.length > 0))
		{
			// case of strict limitation for text length - no text longer than max_txt_len could be entered
			if (restrict_max_text_length == true)
			{
				var substs = [max_txt_len.toString()];
				alert(get_msg_by_id('max_text_length_restricted', substs));
				input_allowed = false;
			}
			// case of showing warning only if text longer than max_txt_len entered
			else
			{
				var substs = [max_txt_len.toString()];
				alert(get_msg_by_id('max_text_length_reached', substs));
				labels.set(n.toString(), labels.get(n.toString()).merge({'chars_notification' : true})); 
			}
		}
	}

	return input_allowed;
}

/**
* process form of order
*/
function process_form()
{
	if ((payment_method.length < 1) && $('payment_methods'))
	{
//		payment_method = $('payment_methods').select('input[name="payment_method"]').first().value; // - does NOT work
//		payment_method = $('main').select('input[name="payment_method"]').first().value;
		payment_method = $$('#Form input[name="payment_method"]').first().value;
	}

	var credit_limit = false;

	if ( (use_credit_limit) &&
		 (use_for_methods.indexOf(payment_method) != -1) &&
		 (parseFloat($('total').innerHTML) > total_threshold) )
	{
		credit_limit = true;
	}

	if ( (emailCheck() == true) && (!locker.locked()) &&
		 ( (!credit_limit) || (confirm(get_msg_by_id('credit_limit_confirmation', null))) ) )
	{
		locker.lock();

		var disabled = $$('#Form input[disabled]');
		disabled.each(function(item) {
			item.disabled = false;
		});

		var form_data = $('Form').serialize();
		form_data = form_data + '&' + $H({site_cpath : site_cpath, host_name : vh_name}).toQueryString();
		 
		disabled.each(function(item) {
			item.disabled = true;
		});
		
		toggle_progressbar_visibility();
		
		if ($('process_loader_text'))
		{
			$('process_loader_text').show();
		}
		
		new Ajax.Request(ajax_path+'process_form_action.php', { 
			method:'post', 
			parameters:form_data, 
			onSuccess:onSuccessProcessForm, 
			onComplete: function() {
				if (!send_order_locker.locked()) {
					toggle_progressbar_visibility();
					
					if ($('process_loader_text'))
					{
						$('process_loader_text').hide();
					}
					
					locker.unlock();		
				}
			}																																																	        });
	}
}

function onSuccessProcessForm(transport)
{
	//alert(transport.responseText);

	var data = eval('(' + transport.responseText + ')');

	if (data.result == 'ok')
	{
		if ($('current_order_id'))
		{
			$('current_order_id').value = data.order_id;
		}

		if (data.postprocess == 'ok')
		{
			if ($('order_data'))
			{
				$('order_data').update(data.order_data);
			}
			
			if ($(data.order_id_transmitter))
			{
				$(data.order_id_transmitter).value = data.order_id;
			}
			
			if ($(data.order_certificate))
			{
				$(data.order_certificate).value = data.invoice_id;
			}
			
			if ($(data.order_total))
			{
				$(data.order_total).value = data.order_amount;
			}
		
			$('payment_form').submit();
		
			send_order_locker.lock();
		}
		else
		{
			alert(data.message);
		}
	}
	else if (data.result == 'invalid_method')
	{
		alert(get_msg_by_id('invalid_payment_method', null));
	}
	else if (data.result == 'error_price')
	{
		alert(get_msg_by_id('empty_price_error', null));
	}
	else if (data.result == 'error_email')
	{
		alert(get_msg_by_id('wrong_email', null));
		$('Epost').focus();
	}
//	else if (data.result == 'error_klarna_validation')
//	{
//		alert(data.message);
//	}
}

/**
*	payment form changing
*   @param method_alias string alias for selected payment method
*/
function change_payment_interface(method_alias)
{
	if (!change_payment_locker.locked())
	{
		change_payment_locker.lock();
		payment_method = method_alias;
		new Ajax.Request(ajax_path+'change_payment.php',{ method:'post', parameters:$H({payment_method_alias : method_alias, site_cpath : site_cpath, host_name : vh_name}), onSuccess:onSuccessPaymentChanged});
	}
}

/**
*
*/
function onSuccessPaymentChanged(transport)
{
	//alert(transport.responseText); 
	
	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
		$('payment_form_container').update(data.form_text);
		
		$('payment_form').action = data.process_url;
		
		if (use_aweber == true)
		{
			if ($('signup_checkbox_container'))
			{
				$('signup_checkbox_container').style.display = 'block';
			}
		}
		else
		{
			if ($('signup_aweber'))
			{
				$('signup_aweber').checked = false;
			}
		}
/*		
		if (data.handling_fee > 0)
		{
			$('handling_fee_amt_container').show();
		}
		else
		{
			$('handling_fee_amt_container').hide();
		}
		
		$('handling_fee_amt').update(data.handling_fee);
*/		
		$('handling_fee_amt').value = data.handling_fee;
		
		update_total();
		
		if (data.klarna_calc_cost == true)
		{
			// new Ajax.Request(ajax_path+'klarna_calc_cost.php',{ method:'post', parameters:$H({site_cpath : site_cpath, host_name : vh_name, total_price: $('total').innerHTML}), onSuccess:onSuccessKlarnaCalcCost});
		}
		else 
		{
			toggle_progressbar_visibility();
			change_payment_locker.unlock();
		}
	}
	else
	{
		change_payment_locker.unlock();
	}
}

/**
* Calc month part payment for klarna
*/
function onSuccessKlarnaCalcCost(transport)
{
	//alert(transport.responseText); 
	
	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
		$('klarna-monthly-cost').update(data.monthly_cost);
		$('klarna-monthly-cost').show();
		$('klarnaInvoice').show();
		$('klarna-pp-box').show();
		$('klarna-monthly-cost-box').show();
	}
	else
	{
		$('klarnaInvoice').hide();
		$('klarna-monthly-cost').hide();
		$('klarna-pp-box').hide();
		$('klarna-monthly-cost-box').hide();	
	}

	toggle_progressbar_visibility();
	change_payment_locker.unlock();
}

/**
* changing permission for label optimization
*/
function change_mod_permission()
{
	if (optim_texts_loaded == false)
	{
		load_optim_text();
		return false;
	}
	
	if ($('opt_allowed'))
	{	
		if ($('optimize_label').checked == false)
		{
			$('opt_allowed').value = optim_texts.get('unchecked');
		}
		else
		{
			$('opt_allowed').value = optim_texts.get('checked');
		}
	}
}

/**
* performing login request
*/
function check_login()
{
	var form_data = $('login_form').serialize();
		
	form_data = form_data + '&' + $H({site_cpath:site_cpath}).toQueryString();
	
	new Ajax.Request(ajax_path+'login.php',{method:"post", parameters:form_data, onSuccess:validate_actions});
}

/**
* actions after form validation performed
*/
function validate_actions(transport)
{
	//alert(transport.responseText);
	
	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
    	$('login_form').submit();
	}
	else
	{
		alert(get_msg_by_id('login_error', null));
		
		$('login').value = '';
		$('password').value = '';
		$('login').focus();
	}
}

/**
* check coupon code request
*/
function check_coupon()
{
	var coupon_code = '';
	
	if ($('coupon_code'))
	{
		coupon_code = $('coupon_code').value;
	}
	
	if ((!use_coupons) || (coupon_code == ''))
	{
		return;
	}
		
	new Ajax.Request(ajax_path+'check_coupon.php',{method:"post", parameters:$H({coupon_code : coupon_code, site_cpath : site_cpath}), onSuccess:set_coupon_discount});
}

/**
* actions after coupon code check performed
*/
function set_coupon_discount(transport)
{
//	alert(transport.responseText);

	var data = eval('(' + transport.responseText + ')');
	
	if (data.result == 'ok')
	{
		if ($('coupon_id'))
		{
			$('coupon_id').value = data.coupon_id;
		}

		if ($('coupon_disc'))
		{
			$('coupon_disc').value = data.coupon_discount;
		}
		
		if ($('disc_prc_container'))
		{
			$('disc_prc_container').style.display = 'inline';
		}
		
		if ((use_discounts == false) && $('discount_amt_container'))
		{
			$('discount_amt_container').style.display = 'block';
		}
		
		coupon_discount = data.coupon_discount;
		
		alert(get_msg_by_id('coupon_code_correct', null));
		
		labels.each(function(label_data)
		{
			change_price(label_data.key, '');
		});
	}
	else
	{
		alert(get_msg_by_id('coupon_code_wrong', null));
		
		if ($('disc_prc_container'))
		{
			$('disc_prc_container').style.display = 'none';
		}
		
		if ((use_discounts == false) && $('discount_amt_container'))
		{
			$('discount_amt_container').style.display = 'none';
		}
		
		if ($('coupon_code'))
		{
			$('coupon_code').value = '';
		}
		
		if ($('coupon_id'))
		{
			$('coupon_id').value = '';
		}

		if ($('coupon_disc'))
		{
			$('coupon_disc').value = '';
		}
		
		if ($('disc_amt'))
		{
			$('disc_amt').update('0');
		}
		
		coupon_discount = 0;
		
		labels.each(function(label_data)
		{
			change_price(label_data.key, '');
		});
	}
}

function emailCheck() 
{
	 	
	 if ((products_loaded == false) || ((use_colors == true) && (colors_loaded == false)))
	 {
		 if (messages_loaded == true)
		 {
	 	 	alert(get_msg_by_id('data_downloading', null));
		 }
		 else
		 {
			alert('* Not all required data downloaded yet. Please wait until downloading completed. *');
		 }
		 
		 return false;
	 }
	 
     if ( ( $('name') ) && ( $('name').readAttribute('type') != "hidden" ) && ( $('name').value == "" ) )
	 {
	 	alert(get_msg_by_id('empty_name', null));
	 	$('name').focus();
	 	return false;
     }
	 
	 if ( ( $('pno') ) && ( $('pno').readAttribute('type') != "hidden" ) && ( $('pno').value == "" ) )
	 {
	 	alert(get_msg_by_id('empty_pno', null));
	 	$('pno').focus();
	 	return false;
     }
	 
	 if ( ( $('fname') ) && ( $('fname').readAttribute('type') != "hidden" ) && ( $('fname').value == "" ) )
	 {
	 	alert(get_msg_by_id('empty_fname', null));
	 	$('fname').focus();
	 	return false;
     }
	 
	 /*if ( ( $('lname') ) && ( $('lname').readAttribute('type') != "hidden" ) && ( $('lname').value == "" ) )
	 {
	 	alert(get_msg_by_id('empty_lname', null));
	 	$('lname').focus();
	 	return false;
     }*/
	 
	 if ( ( $('adresse') ) && ( $('adresse').readAttribute('type') != "hidden" ) && ( $('adresse').value == "" ) )
	 {
		 alert(get_msg_by_id('empty_address', null));
		 $('adresse').focus();
		 return false;
	 }
	 
     if ( ( $('postnr') ) && ( $('postnr').readAttribute('type') != "hidden" ) && ( $('postnr').value == "" ) )
	 {
		 alert(get_msg_by_id('empty_postcode', null));
		 $('postnr').focus();
		 return false;
     }
	 
     if ( ( $('posrsted') ) && ( $('posrsted').readAttribute('type') != "hidden" ) && ( $('posrsted').value == "" ) )
	 {
		 alert(get_msg_by_id('empty_city', null));
		 $('posrsted').focus();
		 return false;
     }
	 
     if ( ( $('customer_email') ) && ( $('customer_email').readAttribute('type') != "hidden" ) )
	 {
		 if ($('customer_email').value=="") 
		 {
			alert(get_msg_by_id('empty_email', null));
			$('customer_email').focus();
			return false;
		 }
		 
		 if ((allow_email_stub == false) || ($('customer_email').value != email_stub_string))
		 {
			 if($('customer_email').value.indexOf('\@', 0) == -1)
			 {
				alert(get_msg_by_id('wrong_email', null));
				$('customer_email').focus();
				return false;
			 }
			 
			 if($('customer_email').value.indexOf('.', 0) == -1)
			 {
				alert(get_msg_by_id('wrong_email', null));
				$('customer_email').focus();
				return false;
			 }
		 }
	 }
	 
	 if ( ( $('cellno') ) && ( $('cellno').readAttribute('type') != "hidden" ) && ( $('cellno').value == "" ) )
	 {
		 alert(get_msg_by_id('empty_cellno', null));
		 $('cellno').focus();
		 return false;
     }
	 
	 if ( ( $('ysalary') ) && ( $('ysalary').readAttribute('type') != "hidden" ) && ( $('ysalary').value == "" ) )
	 {
		 alert(get_msg_by_id('empty_ysalary', null));
		 $('ysalary').focus();
		 return false;
     }
	 
	 if ( ( $('terms') ) && ( $('terms').readAttribute('type') != "hidden" ) && ( $('terms').checked == "" ) )
	 {
		 alert(get_msg_by_id('empty_terms', null));
		 $('terms').focus();
		 return false;
     }
	 
	 if (labels.any(function(pair) { return pair.value.get('initiated'); }) == false)
	 {
	 	alert(get_msg_by_id('empty_label', null));
		$('textfield'+labels.keys().min().toString()+'_1').focus();
	 	return false;
	 }
     return true;     
}

function emailCheckEnkel() 
{
	if ($('Navn').value == "") 
	{
		alert(get_msg_by_id('empty_name', null));
		$('Navn').focus();
		return false;
	}
	if ($('Adresse').value == "") 
	{
		alert(get_msg_by_id('empty_address', null));
		$('Adresse').focus();
		return false;
	}
	if ($('Country').value == "") 
	{
		alert(get_msg_by_id('empty_country', null));
		$('Country').focus();
		return false;
	}
	if ($('Postnr').value == "") 
	{
		alert(get_msg_by_id('empty_postcode', null));
		$('Postnr').focus();
		return false;
	}
	if ($('Poststed').value == "") 
	{
		alert(get_msg_by_id('empty_city', null));
		$('Poststed').focus();
		return false;
	}
	if ($('Epost').value == "") 
	{
		alert(get_msg_by_id('empty_email', null));
		$('Epost').focus();
		return false;
	}
	if ((allow_email_stub == false) || ($('Epost').value != email_stub_string))
	{
		if($('Epost').value.indexOf('\@', 0) == -1)
		{
			alert(get_msg_by_id('wrong_email', null));
			$('Epost').focus();
			return false;
		}
		if($('Epost').value.indexOf('.', 0) == -1)
		{
			alert(get_msg_by_id('wrong_email', null));
			$('Epost').focus();
			return false;
		}
	}
	if (($('Linje_1').value == "") && ($('Linje_1').value == "") && ($('Linje_1').value == "") && ($('motiv').checked == true))
	{
		alert(get_msg_by_id('empty_label', null));
		$('Linje_1').focus();
		return false;
	}
	
	return true;
}
