// Execute ajax request and display in facebox
function fb(url)
{
	fb(forceRequestOnUrl(url), null);
}
function fb(url, cssClass)
{
	jQuery.facebox(function()
	{
		jQuery.get(forceRequestOnUrl(url), function(data)
		{
			jQuery.facebox(data, cssClass);
		})
	})
}

// Append random digits to url to bypass browser cache and force request each time
function forceRequestOnUrl(url)
{
	if (url.indexOf('?') >= 0) url += '&' + Math.floor(Math.random() * 10001);
	else url += '?' + Math.floor(Math.random() * 10001);
	return url;
}

function forceFormAction(frm)
{
	var _action = $(frm).attr('action');
	$(frm).attr('action', forceRequestOnUrl(_action));
}

// this enables us to submit ajax forms programmatically, even if MvcAjax has already been bound to onsubmit
function fixAjaxSubmitForm(id)
{
	forceFormAction($('#' + id));
	
	$('#' + id).submit(function(event) { eval($(this).attr("onsubmit")); return false; });
	$('#' + id + ' input').bind('keypress', function(event)
	{
		if (event.which == 13)
		{
			$('#' + id).submit();
			return false;
		}
		return true;
	});
}

/**
 * Switch tab on product info page (content, comments, related, etc)
 * @param tab		- ID of tab to switch to
 */
function selectProductContentTab(tab)
{
	$('.product_tab').removeClass('product_tab_active');
	$('.product_tab_content').hide();
	$('#product_tab_tab_' + tab).addClass('product_tab_active');
	$('#product_tab_content_' + tab).show();
	Cufon.replace('.product_tab a', { fontFamily: 'Myriad Pro' });
}

// Error occurred during ajax request
function ajaxError(content)
{
	alert(C_LANGVARS['ErrorOnQuery']);
}

/**
 * Callback method for saving feedback. Displays added feedback in product profile
 */
function AddProductFeedbackComplete(content)
{
	$('#product_add_comment').html(content.get_data());
}

/**
* Callback method for displaying additional comments on product profile
*/
function displayMoreFeedback(content)
{
	$('<div style="display:none;">' + content.get_data() + '</div>').appendTo('#product_tab_content_comments_list').slideDown();
}

/**
 * Display editing form for product description
 */
function editProductDescription()
{
	toggleProductDescription();
}

/**
 * Save changes to product description
 */
function saveProductDescription(frm)
{
	$.getJSON('/Catalog/ChangeProductDescription', $('#' + frm).serialize(),
		function(data)
		{
			if (data.status)
				$('#product_tab_content_description_display').html($('#product_description').val().replace(/\n/g,'<br/>'));
			else
				alert(C_LANGVARS['ErrorSavingDescription']);

			toggleProductDescription();
			$('#product_tab_content_description_display').show();
		});	
}

// Toggle product description display mode between edit/view
function toggleProductDescription()
{
	$('#product_tab_content_description_edit').toggle();
	$('#product_tab_content_description_display').toggle();
	$('#product_tab_content_description_edit_icon').toggle();
}

// Callback method for updating shopping cart
function UpdateCartContentsComplete(content)
{
	$('#cartContents').html(content.get_data());
}

// Reload cart link & total in header
function updateHeaderCartTotal()
{
	$('#header_cart').load('/ostukorv/CartLink');
}

// Update quantity in shopping cart
var updateQuantityTimer;
function initUpdateCartQuantity(productId, input)
{
	clearTimeout(updateQuantityTimer);
	updateQuantityTimer = setTimeout(function() { updateCartQuantity(productId, input); }, 200);
}
function updateCartQuantity(productId, input)
{
	var val = $(input).val();
	if ((val != '') && (!isNaN(val)))
	{
		val = parseInt(val);

		if (val < 1)
		{
			alert(C_LANGVARS['AmountMustBeAboveZero']);
			input.focus();
		}
		else {
			$.getJSON('/ostukorv/UpdateCartQuantity', { 'productId': productId, 'quantity': parseInt(val) },
				function(data)
				{
					if (data.quantity != null) $('#txtQuantity' + productId).val(data.quantity);
					if (data.itemtotal != null) $('#totalFor' + productId).text(data.itemtotal.toFixed(2));

					if (data.totalquantity != null) $('#totalQuantity').text(data.totalquantity);
					if (data.total != null) $('#totalPrice').text(data.total.toFixed(2));

					if (data.error != null)
						alert(data.error);

					toggleProductDescription();
					updateHeaderCartTotal();
					$('#product_tab_content_description_display').show();
				});
		}
	}
}

// Update delivery selection page totals
function updateDeliveryTotal(input)
{
	var val = $(input).val();
	var txtTransportPrice = $('#transport' + val).text();

	var transportPrice = parseFloat(txtTransportPrice.replace(/\s+/g, ''));
	if (isNaN(transportPrice))
		alert(C_LANGVARS['InvalidPriceOnDeliveryOption'].replace('{0}', val));
	else
	{
		var eur_transportPrice = (transportPrice / 15.6466);
		$('#transportPrice').html(transportPrice.toFixed(2) + ' <span class="eur_price">(' + eur_transportPrice.toFixed(2) + ' EUR)</span>');

		var txtOrderPrice = $('#orderPrice').text();
		var orderPrice = parseFloat(txtOrderPrice.replace(/\s+/g, ''));

		var totalPrice = (orderPrice + transportPrice);
		var eur_totalPrice = (totalPrice / 15.6466);
		$('#totalPrice').html(totalPrice.toFixed(2) + ' <span class="eur_price">(' + eur_totalPrice.toFixed(2) + ' EUR)</span>');
	}
}

function downloadEbook(productId, format)
{
	$.getJSON(forceRequestOnUrl(C_EBOOK_ROOTURL + '/konto/eraamatud/DownloadContent?productId=' + productId + '&format=' + format), function(data)
	{
		if (!data.status)
		{
			alert(data.error);
			return;
		}

		window.location.href = forceRequestOnUrl(C_EBOOK_ROOTURL + '/konto/eraamatud/DownloadContent?sendFile=true&productId=' + productId + '&format=' + format);
	});
}

// Callback method for ajax requests in facebox window
function faceboxRequestComplete(content)
{
	$('#faceboxContent').html(content.get_data());
}

// Callback method for ajax requests in login process
function rrAjaxRequestComplete(content)
{
	$('#ajaxContainer').html(content.get_data());
}
// Callback method for ajax requests in login process
function rrDialogRequestComplete(content)
{
	$('#dialogContainer').html(content.get_data());
}

// Top list widget content updating
function toplistUpdated(content)
{
	$('#toplist').html(content.get_data());
	Cufon.replace('.sidebar_top_position', { fontFamily: 'ZineSansDis' });
}

function addToFavorite(productId, listId, link)
{
	$.getJSON('/Catalog/SubmitAddToList?json=true&productId=' + productId + '&listId=' + listId,
		function(data)
		{
			if (data.result)
			{
				$(link).removeClass('btn_favorite').addClass('btn_favorited').text('Lemmik');
				link.setAttribute('onclick', link.getAttribute('onclick').replace('addToFavorite', 'removeFromFavorite'));
				//$(link).unbind('click');
				//$(link).click(function() { removeFromFavorite(productId, listId, this); });
				//return false;
			}
			else
				alert(C_LANGVARS['ErrorAddingProductToList']);
		});
}

function removeFromFavorite(productId, listId, link)
{
	$.getJSON('/Catalog/RemoveFromList?productId=' + productId + '&listId=' + listId,
		function(data)
		{
			if (data.result)
			{
				$(link).removeClass('btn_favorited').addClass('btn_favorite').text(C_LANGVARS['SetAsFavourite']);
				link.setAttribute('onclick', link.getAttribute('onclick').replace('removeFromFavorite', 'addToFavorite'));
				//$(link).unbind('click');
				//$(link).click(function() { addToFavorite(productId, listId, this); });
				//return false;
			}
			else
				alert(C_LANGVARS['ErrorRemovingProductFromList']);
		});
}

function removeProductFromList(productId, listId, removeProduct)
{
	$.getJSON('/Catalog/RemoveFromList?productId=' + productId + '&listId=' + listId,
		function(data)
		{
			if (data.result)
			{
				if (removeProduct)
					$('#list_product_item' + productId).slideUp();
				else
					$('#productlist' + productId + '_' + listId).remove();
			}
			else
				alert(C_LANGVARS['ErrorRemovingProductFromList']);
		});
}

function setAdminUser(chkbox, accountId, isAdmin)
{
	var additionalPwd = prompt('Sisesta parool');
	$.getJSON('/haldus/SetAdmin?accountId=' + accountId + '&isAdmin=' + isAdmin + '&additionalPwd=' + encodeURIComponent(additionalPwd),
		function(data)
		{
			if (!data.result)
			{
				chkbox.attr('checked', !(chkbox.attr('checked')));
					
				alert((data.error != null) ? data.error : 'Õiguste muutmine ebaõnnestus');
			}
		});
}

function deleteGalleryImage(imageId)
{
	if (confirm('Oled kindel?'))
	{
		$.getJSON('/haldus/DeleteImageFromGallery?imageId=' + imageId,
		function(data)
		{
			if (!data.result)
			{
				alert((data.error != null) ? data.error : 'Pildi kustutamine ebaõnnestus');
			}
			else
			{
				$('#gallery_edit_image' + imageId).hide('fast');
			}
		});
	}
}

var listsOverTimer = null;
function listsOver()
{
	$('#listsLinks').show();
	clearTimeout(listsOverTimer);
}
function listsOut()
{
	listsOverTimer = setTimeout(function() { $('#listsLinks').hide(); }, 300);
}
function listsClear()
{
	$('#listsLinks').hide();
	clearTimeout(listsOverTimer);
}



/**
* Validate form
* @param form - form element
*/
function validateForm(form)
{
	var inputs = form.getElementsByTagName("input");
	var selects = form.getElementsByTagName("select");
	var textareas = form.getElementsByTagName("textarea");
	var fields = new Array();
	for (var i = 0; i < inputs.length; i++)
		fields.push(inputs[i]);
	for (var i = 0; i < selects.length; i++)
		fields.push(selects[i]);
	for (var i = 0; i < textareas.length; i++)
		fields.push(textareas[i]);

	for (var i = 0; i < fields.length; i++)
	{
		if (fields[i].getAttribute("valtype") == "required")
		{

			if ((fields[i].value.length < 1) || (fields[i].value == ""))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "required group")
		{
			for (var j = 0; j < fields.length; j++)
			{
				if (((fields[i].value.length < 1) || (fields[i].value == "")) && (fields[j].id != fields[i].id) && (fields[j].getAttribute("valgroup") == fields[i].getAttribute("valgroup")) && ((fields[j].value.length < 1) || (fields[j].value == "-1")))
				{
					alert(fields[i].getAttribute("valmessage"));
					fields[i].focus();
					return false;
				}
			}
		}
		else if (fields[i].getAttribute("valtype") == "integer")
		{
			if (fields[i].value.length > 0)
			{
				var parsedInt = parseInt(fields[i].value);
				if (isNaN(parsedInt))
				{
					alert(fields[i].getAttribute("valmessage"));
					fields[i].focus();
					return false;
				}
			}
		}
		else if (fields[i].getAttribute("valtype") == "required integer")
		{
			var parsedInt = parseInt(fields[i].value);
			if (isNaN(parsedInt))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "date")
		{
			if ((fields[i].value.length > 0) && ((fields[i].value.length != 10) || (!validateDate(fields[i].value))))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "time")
		{
			if ((fields[i].value.length > 0) && ((fields[i].value.length != 5) || (!validateTime(fields[i].value))))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "required time")
		{
			if ((fields[i].value.length != 5) || (!validateTime(fields[i].value)))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "datetime")
		{
			if ((fields[i].value.length > 0) && ((fields[i].value.length != 16) || (!validateDateTime(fields[i].value))))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "required datetime")
		{
			if ((fields[i].value.length != 16) || (!validateDateTime(fields[i].value)))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "checked")
		{
			if (!fields[i].checked)
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "passmatch")
		{
			var matchField = document.getElementById(fields[i].getAttribute("valmatch"));

			if (fields[i].value != matchField.value)
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "passmatch required")
		{
			if ((fields[i].value.length < 1) || (fields[i].value == "-1"))
			{
				alert(fields[i].getAttribute("valmessagerequired"));
				fields[i].focus();
				return false;
			}

			var matchField = document.getElementById(fields[i].getAttribute("valmatch"));

			if (fields[i].value != matchField.value)
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
		else if (fields[i].getAttribute("valtype") == "username")
		{
			var re = new RegExp('^[\\w]+$');
			if ((fields[i].value.length < 1) || (fields[i].value == "") || (!fields[i].value.match(re)))
			{
				alert(fields[i].getAttribute("valmessage"));
				fields[i].focus();
				return false;
			}
		}
	}

	return true;
}
function validateDateTime(str)
{
	var regExPattern = "([0-3][0-9][.][0-1][0-9][.]20[0-9][0-9] [0-2][0-9]:[0-5][0-9])";

	return (str.match(regExPattern));
}
function validateDate(str)
{
	var regExPattern = "([0-3][0-9][.][0-1][0-9][.][1-2][0-9][0-9][0-9])";

	return (str.match(regExPattern));
}
function validateTime(str)
{
	var regExPattern = "([0-2][0-9]:[0-5][0-9])";

	return (str.match(regExPattern));
}