// JavaScript Document

function tip()
{
		
}

function validateRegisterCommunity()
{
	//var data    = $('registerForm').serialize(true);
	var form    = $('reg_form');
	new Ajax.Request(form.action, 
					 { 
					 	method: 'post',
					 	parameters: form.serialize(true), 
						onComplete: function (result) 
						{ 
							if(result.responseText.match('Беше Ви изпратен мейл за потвърждение на регистрацията Ви')) 
							{ 
								successValidate(result.responseText);
							} 
							else
							{ 
								notSucessValidate(result.responseText);
							} 
						}
					 }
					);
}


function successValidate(msg)
{
	// hide error container
	$('reg_error').innerHTML = msg;
	
	// reset form
	$('reg_form').reset();
	$('reg_form').hide();
}

function notSucessValidate(err)
{
	$('reg_error').innerHTML = err;
}


function enlargePic(imgSrc, alt)
{
	var src   = imgSrc;
	var img = $('bigImg');	
	
	var imgPreloader = new Image();
	
	new Effect.Opacity(img, Object.extend(
						{
					   		duration: 0.25, 
							from:1.0, 
							to:0.0,
							afterFinishInternal: function(effect) 
							{
								imgPreloader.src = src;
							}
						})
			);	
	
	// once image is preloaded, appear the image
	imgPreloader.onload = function()
	{
		img.src = src;
		new Effect.Appear(img, {duration: 0.25});
		img.alt = alt;
	}	
}

function makeEditable(id, table)
{
	new Ajax.InPlaceEditor('comment_text_' + id, file + '?el=text&func=editComment&id=' + id + '&table=' + table, 
						   		{
									formClassName:'formEdit',
									highlightcolor: '#eeeeee',
									hoverClassName: 'overEdit',
									clickToEditText: 'Редактирай',
									rows:10
								}
						   );	
}

function deleteComment(id, table)
{
	new Ajax.Request(file, 
					 { parameters: 
					 	{ 
							func: 'deleteComment',
							id: id,
							table: table
						}, 
						onComplete: function (result) { if(result.responseText == "done") $('comment_' + id).remove();}
					 }
					);
}

function addToBasket()
{
	var data  = $('products_list_form').serialize(true);
	data.func = "addToBasket";
	new Ajax.Request(file, 
					 { 
					 	method: 'post',
					 	parameters: data, 
						onComplete: function (result) 
						{ 
							//alert(result.responseText);
							loadBasicBasket();
							alert("Кошницата е обновена.");
							$('products_list_form').reset();
						}
					 }
					);
}

function clearAddProductForm()
{
	$('products_list_form').reset();	
}

function loadBasicBasket()
{
	new Ajax.Updater('menu_basket_container', file, 
					 { 
					 	method: 'post',
					 	parameters: { func: 'loadBasketBasic'}
					 }
					);	
}

function deleteFromBasket(chk, row)
{
	if(confirm("Наистина ли желаете да изтриете този продукт от кошницата? Ако той е част от промоция ще бъде изтрита цялата промоция."))
	{
		new Ajax.Request(file, 
						 { 
							method: 'post',
							parameters: 
							{
								func : 	'deleteFromBasket',
								row : row
							}, 
							onComplete: function (result) 
							{ 
								// remove tr node
								//chk.parentNode.parentNode.remove();
								// reload basic basket
								//loadBasicBasket();
								window.location.reload();
							}
						 }
						);
	}
}

function sendTestemony()
{
	var data  = $('testemony_form').serialize(true);
	data.func = "sendTestemony";
	data.json = 1;
	
	new Ajax.Request(file, 
					 { 
					 	method: 'post',
					 	parameters: data, 
						onComplete: function (result) 
						{ 
							var res = eval("(" + result.responseText + ")");
							$('form_msg').innerHTML = res.msg;
							
							if(res.status == "ok")
							{
								$('testemony_form').reset();	
							}
						}
					 }
					);	
}

function loadTotal()
{
	new Ajax.Updater('total_container', file, 
					 { 
					 	method: 'post',
					 	parameters: { func: 'loadTotal'}
					 }
					);	
}

function openTestimonialsForm()
{
	$('commentForm').show();	
}

function closeTestimonialsForm()
{
	$('commentForm').hide();	
}

function calcTotalPrice()
{
	if(checkMinQuantity())
	{
		var price    	= 0;
		var quanityA 	= $('promotionForm').getElementsByClassName('value_quantity');
		var priceA		= $('promotionForm').getElementsByClassName('value_price');
			
		//alert(priceA.length);	
			
		for(var i=0; i<quanityA.length; i++)
		{
			price += parseInt(quanityA[i].value)*priceA[i].value;
		}
		
		$('totalPriceSpan').innerHTML = price;
	}
}

function checkInputMinQuantity(inp)
{
	var min_q  = parseInt((inp.nextSibling).value);
	var result = parseInt(inp.value)>=min_q;
	if(!result)
	{
		alert("Минималното количество за да важи промоцията за този продукт е " + min_q + ". Моля въведете нова стойност.");
		inp.value = 0;
		inp.focus;
	}
	return result;
}

function checkMinQuantity()
{
	var flag        = true;
	var i           = 0;
	var quantityA	= $('promotionForm').getElementsByClassName('value_quantity');
	while(i<quantityA.length && flag)
	{
		flag = checkInputMinQuantity(quantityA[i]);
		i++
	}
	return flag;
}

function promotionToBasket()
{
	var price = parseInt($('totalPriceSpan').innerHTML);
	if(price <= 0)
	{
		alert("Моля изберете продукти.");
	}
	else
	{
		$('promotionForm').submit();
	}
}

function productToBasket()
{
	if(parseInt($F('product_details_quantity'))>0)
	{
		$('productDetails').submit();
	}
	else
	{
		alert("Попълнете `Количество`");
		$('product_details_quantity').focus();
	}
}

function saveAsHtml() {
    if (!!window.ActiveXObject) {
        document.execCommand("SaveAs");
    } else if (!!window.netscape) {
        var r=document.createRange();
        r.setStartBefore(document.getElementsByTagName("head")[0]);
        var oscript=r.createContextualFragment('<script id="scriptid" type="application/x-javascript" src="chrome://global/content/contentAreaUtils.js"><\/script>');
        document.body.appendChild(oscript);
        r=null;
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            saveDocument(document);
        } catch (e) {
            //no further notice as user explicitly denied the privilege
        } finally {
            var oscript=document.getElementById("scriptid");    //re-defined
            oscript.parentNode.removeChild(oscript);
        }
    }
}


function noteField(el)
{
	el = $(el);
	var txt = el.value;
	new Event.observe(el, 'focus', function() 
	{
		if(el.value == txt)
		{
			el.value = "";
		}
	});
	
	new Event.observe(el, 'blur', function() 
	{
  		if(el.value == "")
		{
			el.value = txt;
		}	
	});
}

function pagingCats($param)
{
	var page = $('cats_go_page').value;
	if (page)
	{
		window.location.href = '?cpage=' + page;	
	}
	
	return false;
}

function pagingProducts($param)
{
	var page = $('products_go_page').value;
	if (page)
	{
		window.location.href = '?ppage=' + page;	
	}
	
	return false;
}
