var statusMap = {
	'pendingBillingPartFulfilled' : 'Partial Shipment.'
}
function parseValue(valueText) {
	if(!valueText || valueText == '') return '';
	var dateExp = new RegExp('[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}');
	if(statusMap[valueText]) {
		r = statusMap[valueText];
		return r;
	} else if(valueText.match(dateExp)) {
		r = valueText.replaceAll('/','.');
		return r;
	} else {
		return valueText;
	}
}

function drawRecentOrders(ordersCollection,tempId,containerId) {
	var maxRecentOrders = 3;

	for(var o = 0; o < maxRecentOrders; o++) {
		var currentOrder = ordersCollection[o];

		var currentOrderRow = jQuery('#' + tempId).clone();
			currentOrderRow.attr('id','order_' + o);
		for(var od in currentOrder) {
			if(jQuery(currentOrderRow).find('#fld_' + od).length > 0) {
				jQuery(currentOrderRow).find('#fld_' + od).html('<a href="/Order?id=' + currentOrder['tranid'] + '" target="_blank">' + parseValue(currentOrder[od]) + '</a>');
			}
		}
		jQuery('#' + containerId).append(currentOrderRow.show());
	}
}

var userData;
$.get('/app/site/hosting/scriptlet.nl?script=13&deploy=1', function(data) {
	jQuery('.loading_ro').hide();
	try {
		eval("userData = " + data);
		if(userData.status == "OK") {
			if(userData.orders.length > 0) {
				drawRecentOrders(userData.orders, 'row_template', 'recent_orders_tbl');
				jQuery('#recent_orders_tbl, .right_col_bottom_link').fadeIn('normal');
			} else {
				jQuery('#recent_orders .content').append('<p>No orders were found.</p>');
			}
		} else {
			jQuery('#recent_orders .content').append('<p>No orders were found.</p>');
		}
	} catch(e) {}
});
/////////////////////////////////////////////////
/////////////////////////////////////////////////

// Set event for first "new item" field
var hideResults = true;
jQuery('#qa_item_id_1').keyup(function(e) {
	getSugest(this, e, 1);
}).blur(function() {
	if(hideResults) {
		jQuery('#suggestForThis_id_1').hide();
		jQuery('#suggestForThis_id_1 .sugesetion_row.mover').removeClass('mover');
	}
});

ons_callback_s = function(cIndex) {
	var currentIndex = cIndex;
	jQuery('#suggestForThis_id_' + currentIndex).hover(function() {
		hideResults = false;
	}, function() {
		hideResults = true;
	});

	jQuery('#suggestForThis_id_' + currentIndex + ' .sugests_inner .sugesetion_row').hover(function() {
		jQuery(this).addClass('m_over');
	}, function() {
		jQuery(this).removeClass('m_over');
	}).click(function() {
		jQuery('#suggestForThis_id_' + currentIndex + ' .sugests_inner .sugesetion_row').removeClass('m_over');

		jQuery('#qa_item_id_' + currentIndex).val(jQuery(this).attr('rel'));
		jQuery('#qa_item_id_' + currentIndex).focus().select();
		jQuery('#suggestForThis_id_' + currentIndex).hide();

		// get options here
		jQuery('#qa_item_id_' + currentIndex).attr('disabled','true');
		jQuery('#qa_item_string_' + currentIndex).val(jQuery(this).find('.sugestion_internalid').text());
		jQuery('#qa_row_' + currentIndex + ' > td.c_size').html('Loading options...');
		//jQuery('#qa_row_' + currentIndex + ' > td.c_size').load(jQuery(this).find('.sugestion_url').text() + ' #custcol1', null, function() {
		jQuery('#qa_row_' + currentIndex + ' > td.c_size').load(jQuery(this).find('.sugestion_url').text() + ' #sc_table_kore select', function() {
			jQuery('#qa_item_id_' + currentIndex).removeAttr('disabled');
			if(jQuery(this).text() == '') {
				jQuery(this).text('No options');
			} else {
				jQuery('#qa_row_' + currentIndex + ' > td.c_size select').removeAttr('onclick').removeAttr('onchange');
			}
		});
	});
}

var maxRows = 10;
function addNewRow() {
	var currentIndex = jQuery('.add_to_cart_row').length + 1
	if(jQuery('.add_to_cart_row').length < maxRows) {
		jQuery('<tr id="qa_row_' + currentIndex + '" class="add_to_cart_row"><td class="quickadd_row c_item"><input type="text" id="qa_item_id_' + currentIndex + '" class="qa_item_id" /><input type="hidden" id="qa_item_string_' + currentIndex + '" class="qa_item_string" /><div id="suggestForThis_id_' + currentIndex + '" class="suggestForThis" style="display: none;"></div></td><td class="quickadd_row c_qty"><input type="text" id="qa_item_qty_' + currentIndex + '" class="qa_item_qty" value="1" /></td><td class="quickadd_row c_size"></td></tr>').appendTo('#new_items_qa_box > table > tbody');

		jQuery('#qa_item_id_' + currentIndex).keyup(function(e) {
			getSugest(this, e, currentIndex);
		}).blur(function() {
			if(hideResults) {
				jQuery('#suggestForThis_id_' + currentIndex).hide();
				jQuery('#suggestForThis_id_' + currentIndex + ' .sugesetion_row.mover').removeClass('mover');
			}
		});
	} else {
		alert('The maximum allowed is ' + maxRows + ' rows');
	}
}

function removeLastRow() {
	if(jQuery('.add_to_cart_row').length > 1) {
		if(jQuery('.add_to_cart_row:last > td > input:first').val() == '') {
			jQuery('.add_to_cart_row:last').remove();
		} else {
			if(confirm('The item # field is not empty! Are you sure?')) {
				jQuery('.add_to_cart_row:last').remove();
			}
		}
	} else {
		alert('Must to have at less one row');
	}
}

var currentSugests = [];
var lastKeyword = '';
var searchTimer, reqObj;

function getSugest(element, e, resIndex) {
	if(element.value.length >= 2) {
		var kcode = e.keyCode ? e.keyCode : e.which;
		var currentSearch = jQuery(element).val();

		if(parseInt(kcode) == 27) {
			jQuery('#suggestForThis_id_' + resIndex).hide();
			jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('mover');
			return false;
		}
		if(currentSearch.split('').length >= 2) {
			if(restrictKeys[kcode] != true && (parseInt(kcode) < 111 || parseInt(kcode) > 123)) {
				clearTimeout(searchTimer);
				if(reqObj) {
					reqObj.abort();
					reqObj = null;
				}
				if(checkChanges(currentSearch) && currentSugests && currentSugests.length > 0) {
					if(currentSearch.split('').length > lastKeyword.split('').length) {
						lastKeyword = currentSearch;
					}
					var sugestsHTML = '<div class="sugests_inner">';

					for(var s = 0; s < currentSugests.length; s++) {
						sugestsHTML += '' +
						'<div class="sugesetion_row" id="sugestion_row_' + currentSugests[s]['id'] + '" rel="' + unescape(currentSugests[s]['itemid']) + '">' +
							'<div class="sugestion_name">' +
								'' + unescape(currentSugests[s]['storedisplayname']) + '' +
							'</div>' +
							'<span class="sugestion_url" style="display: none;">' + unescape(currentSugests[s]['itemurl']).replace('/n.2/','/n.1/') + '</span>' +
							'<span class="sugestion_internalid" style="display: none;">' + unescape(currentSugests[s]['id']) + '</span>' +
						'</div>';
					}
					sugestsHTML += '</div>';

					jQuery('#suggestForThis_id_' + resIndex).html(sugestsHTML);
					if(window.ons_callback_s) {
						ons_callback_s(resIndex);
					}
				}
				lastKeyword = currentSearch;
				searchTimer = setTimeout(function() {
					reqObj = AJAXSend({
						'url' : suiteletURL + '&token=' + escape(currentSearch),
						'oncomplete' : function(resString) {
							eval(resString);
							currentSugests = items;
							jQuery('#suggestForThis_id_' + resIndex).removeClass('searching');
							jQuery('#suggestForThis_id_' + resIndex).show();

							if(currentSugests.length > 0) {
								var sugestsHTML = '<div class="sugests_inner">';
								for(var s = 0; s < currentSugests.length; s++) {
									sugestsHTML += '' +
									'<div class="sugesetion_row" id="sugestion_row_' + currentSugests[s]['id'] + '" rel="' + unescape(currentSugests[s]['itemid']) + '">' +
										'<div class="sugestion_name">' +
											'' + unescape(currentSugests[s]['storedisplayname']) + ' (' + unescape(currentSugests[s]['itemid']) + ')' +
										'</div>' +
										'<span class="sugestion_url" style="display: none;">' + unescape(currentSugests[s]['itemurl']).replace('/n.2/','/n.1/') + '</span>' +
										'<span class="sugestion_internalid" style="display: none;">' + unescape(currentSugests[s]['id']) + '</span>' +
									'</div>';
								}

								sugestsHTML += '</div>';
							} else {
								sugestsHTML = '<div class="results_info">No items found for "<i>' + unescape(currentSearch) + '</i>"</div>';
								jQuery('#suggestForThis_id_' + resIndex).addClass('searching');
							}

							jQuery('#suggestForThis_id_' + resIndex).html(sugestsHTML);
							if(window.ons_callback_s) {
								ons_callback_s(resIndex);
							}
						},
						'onload' : function() {
							jQuery('#suggestForThis_id_' + resIndex).show();
							jQuery('#suggestForThis_id_' + resIndex).html('<div class="results_info">Performing search...</div>').addClass('searching');
						}
					});
				}, 300);
			}
		}

		// up arrow key event
		if(parseInt(kcode) == 38) {
			if(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').length == 0 || jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover:eq(0)').attr('id') == jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row:first').attr('id')) {
				jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('mover');
				jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row:last').addClass('mover');
			} else {
				jQuery(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('mover').prev()).addClass('mover');
			}
		}
		// down arrow key event
		else if(parseInt(kcode) == 40) {
			if(jQuery('#suggestForThis_id_' + resIndex).css('display') == 'none') {
				jQuery('#suggestForThis_id_' + resIndex).show();
			} else {
				if(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').length == 0 || jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover:eq(0)').attr('id') == jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row:last').attr('id')) {
					jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('mover');
					jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row:first').addClass('mover');
				} else {
					jQuery(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('mover').next()).addClass('mover');
				}
			}
		}
		// enter and tab keys event
		else if(parseInt(kcode) == 13 || parseInt(kcode) == 9) {
			if(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').length > 0) {
				// put item id on field
				jQuery('#qa_item_id_' + resIndex).val(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').attr('rel'));
				jQuery('#qa_item_id_' + resIndex).focus().select();
				jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover').removeClass('m_hover');
				jQuery('#suggestForThis_id_' + resIndex).hide();

				// get options here
				jQuery('#qa_item_id_' + resIndex).attr('disabled','true');
				jQuery('#qa_item_string_' + resIndex).val(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_internalid').text());
				jQuery('#qa_row_' + resIndex + ' > td.c_size').html('Loading options...');
				//jQuery('#qa_row_' + resIndex + ' > td.c_size').load(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_url').text() + ' #custcol1', null, function() {
				jQuery('#qa_row_' + resIndex + ' > td.c_size').load(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_url').text() + ' #sc_table_kore select', function() {
					jQuery('#qa_item_id_' + resIndex).removeAttr('disabled');
					if(jQuery(this).text() == '') {
						jQuery(this).text('No options');
					} else {
						jQuery('#qa_row_' + resIndex + ' > td.c_size select').removeAttr('onclick').removeAttr('onchange');
					}
				});

				return false;
			} else {
				if(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row').length == 1) {
					jQuery('#qa_item_id_' + resIndex).val(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row').attr('rel'));

					// get options here
					jQuery('#qa_item_id_' + resIndex).attr('disabled','true');
					jQuery('#qa_item_string_' + resIndex).val(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_internalid').text());
					jQuery('#qa_row_' + resIndex + ' > td.c_size').html('Loading options...');
	//				jQuery('#qa_row_' + resIndex + ' > td.c_size').load(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_url').text() + ' #custcol1', null, function() {
					jQuery('#qa_row_' + resIndex + ' > td.c_size').load(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row.mover .sugestion_url').text() + ' #sc_table_kore select', function() {
						jQuery('#qa_item_id_' + resIndex).removeAttr('disabled');
						if(jQuery(this).text() == '') {
							jQuery(this).text('No options');
						} else {
							jQuery('#qa_row_' + resIndex + ' > td.c_size select').removeAttr('onclick').removeAttr('onchange');
						}
					});
				} else {
					if(jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row').length > 1) {
						jQuery('#suggestForThis_id_' + resIndex + ' .sugesetion_row:first').addClass('mover');
						jQuery('#suggestForThis_id_' + resIndex).show();
					} else {
						jQuery('#suggestForThis_id_' + resIndex).show();
					}
				}
			}
		}
	}
}

function quickAddToCart() {
	var accountNumber = '1135977', siteNumber = '1';
	var cURL = '/app/site/backend/additemtocart.nl?c=' + accountNumber + '&n=' + siteNumber;

	var urls = [];
	var itemsWithoutOptions = {};
	var itemsWithOptions = {};

	var fieldErrors = false;
	jQuery('.add_to_cart_row').each(function() {
		///////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////
		//NEW GENERATION

		var cItemInternalid = jQuery(this).find('.qa_item_string').val();
		var cItemQty = jQuery(this).find('.qa_item_qty').val();
		var cItemOptions = [];

		var someOptionsIsEmpty = false;

		jQuery(this).find('.c_size select').each(function() {
			var cOption = {};
			cOption.fieldid = jQuery(this).attr('id');
			cOption.fieldval = jQuery(this).val();

			if(cOption.fieldval == '') {
				someOptionsIsEmpty = true;
			}

			cItemOptions.push(cOption);
		});

		if(!cItemInternalid || someOptionsIsEmpty || !cItemQty || cItemQty == '' || isNaN(cItemQty)) {
			jQuery(this).find('td').addClass('error');
			fieldErrors = true;
		} else {
			jQuery(this).find('td').removeClass('error');
		}

		if(cItemOptions.length > 0) {
			// with options
			itemsWithOptions[cItemInternalid] = {};
			itemsWithOptions[cItemInternalid]['qty'] = cItemQty;
			itemsWithOptions[cItemInternalid]['options'] = cItemOptions;
		} else {
			// without options
			itemsWithoutOptions[cItemInternalid] = {};
			itemsWithoutOptions[cItemInternalid]['qty'] = cItemQty;
		}
	});

	if(fieldErrors) {
		alert('One of fields is empty, all fields are mandatory');
		return;
	} else {
		// create url for multiple items without options
		var multiItemsURL = cURL + '&buyid=multi&qty=1';
		var multiIds = '&multi=';
		for(var ita in itemsWithoutOptions) {
			multiIds += ita + ',' + itemsWithoutOptions[ita]['qty'] + ';';
		}

		multiItemsURL += multiIds;
		urls.push(multiItemsURL);

		// create urls for items with options
		for(var itb in itemsWithOptions) {
			var currentURL = cURL;
				currentURL += '&buyid=' + itb;
				currentURL += '&qty=' + itemsWithOptions[itb]['qty'];
			for(var op = 0; op < itemsWithOptions[itb]['options'].length; op++) {
				currentURL += '&' + itemsWithOptions[itb]['options'][op]['fieldid'] + '=' + itemsWithOptions[itb]['options'][op]['fieldval'];
			}

			urls.push(currentURL);
		}
	}

	AJAXSend({
		'urls' : urls,
		'oncomplete' : function(resString) {
			document.location.href = '/s.nl?sc=3';
		},
		'onload' : function() {
			if(jQuery('.quick_adding_items_').length < 1) {
				jQuery('#add_toca').append('<p class="quick_adding_items_">Adding items to cart, <b>DO NOT</b> close the window or change pages!</p>');
			}
		}
	});
}
