document.onclick = function() {
	jQuery('.panel').hide();
}

jQuery(document).ready(function() {
	jQuery("#loading").ajaxStart(function(){
		jQuery(this).show();
	});
	jQuery("#loading").ajaxStop(function(){
		jQuery(this).hide();
	});
	jQuery(".dialog").dialog({
		modal: true,
		autoOpen: false,
		width: 500
	});
	jQuery("INPUT.numeric").numeric();

	(function($) {
		$.validator.addMethod('remote_zf', function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";

			var previous = this.previousValue(element);

			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;

			param = typeof param == "string" && {url:param} || param;

			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						if ( response.result ) {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] =  response.result || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						}
						previous.valid = response.result;
						validator.stopRequest(element, response.result);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		}, 'asd');
	})(jQuery);
	
});

jQuery.fn.quantity = function(options) {

	var settings = jQuery.extend({
		quantityContainerClass: 'quantityWrap',
		quantityUpdateClass: 'quantityUpdate',
		updateButtonImage: '/img/icons/menhetn/redo_16.png',
		updateClick: function(data) {}
	}, options);

	this.each(function(){
		jQuery(this).wrap('<div class="' + settings.quantityContainerClass + '"></div>');
		jQuery(this).after(jQuery('<input type="image" src="' + settings.updateButtonImage + '" name="updateQuantity" value="update" class="' + settings.quantityUpdateClass + '" />').unbind('click').bind('click', jQuery(this), settings.updateClick));
	});
	
	return jQuery(this);
};

var print = {
	open: function(url, name, properties) {
		if(!properties) properties = 'status=0,toolbar=0,location=0,menubar=0,scrollbars=1,width=880,height=600';
		window.open(url, name, properties);
	}
}

var site = {

	addToCart: function(data, callback) {
		jQuery.getJSON('/en/shop/add-to-cart', {productId: data.productId, sellerId: data.sellerId, quantity: data.quantity, format: 'json'}, function(response) {
			if(response.result) {
				if(data.quantity == undefined) data.quantity = 1;
				var n = jQuery('.numberOfProductsInCart').html() == '' ? 0 : parseInt(jQuery('.numberOfProductsInCart').html());
				jQuery('.numberOfProductsInCart').html(n + parseInt(data.quantity));
			}
			if(typeof callback == 'function') callback(response);
		});
	},
	
	removeFromCart: function(data, callback) {
		jQuery.getJSON('/en/shop/remove-from-cart', {productId: data.productId, cartId: data.cartId, format: 'json'}, function(response) {
			if(response.result) {}
			if(callback != undefined) {
				callback(response);
			}
		});
	},

	setQuantity: function(data, callback) {
		jQuery.getJSON('/en/shop/set-quantity', {productId: data.productId, cartId: data.cartId, quantity: data.quantity, format: 'json'}, function(data) {
			if(callback != undefined) {
				callback(data);
			}
		});
	},

	setStatus: function(cartId, status, callback) {
		jQuery.getJSON('/en/shop/set-cart-status', {cartId: cartId, status: status, format: 'json'}, function(data) {
			if(callback != undefined) {
				callback(data);
			}
		});
	},
	setStatusCallback: function(data) {},

	reviewPagingAction: function (url, options) {
		jQuery('.contentReview').load(url + '/?format=html', options, function(data) {
			jQuery('input.starComment').rating('disable');
		});
	},

	addCommentAction: function (commentContainerId, description, rating, callback) {
		var url = '/en/comment/add-comment/';
		jQuery.post(url + '/?format=json', { comment_container_id: commentContainerId, description: description, rating: rating }, function(data) {
			switch(data.result) {
				case true:
					if(typeof callback == 'function') callback();
				 break;
			}
		}, 'json');
	},
	
	addCommentComplaintAction: function (url, complaintId, complaintType) {
		jQuery.post(url + '/?format=json', { complaintId: String(complaintId), complaintType: complaintType}, function(data) {
			switch(data.result) {
				case true:
					 jQuery('.reportOptions-' + complaintId).addClass('hidden');
					break;
			}
		}, 'json');
	},

	loadImage: function(container, data, callback) {
		var url = '/en/image/load/format/html';
		//jQuery(container).html('<img src="/img/loading.gif" width="50" height="50" alt="loading" />');
		jQuery(container).load(url, data, function() {
			if(typeof(callback) == 'function') callback(data);
		});
	},

    openAddToCartDialog: function () {
        jQuery("#addToCartDialog").dialog('open');
    },

	follow: function(entity, id, container, text) {
		jQuery.getJSON('/en/account/follow-entity/format/json', {entity: entity, id: id}, function(data)
		{
			if(data.result) {
				jQuery(container).html(text);
			}
		});
	},

	acceptDigits: function (objtextbox)
	{
		var exp = /[^\d]/g;
		objtextbox.value = objtextbox.value.replace(exp,'');
	}
	
}

jQuery.jPrintArea=function(el)
{
	var iframe=document.createElement('IFRAME');
	var doc=null;
	jQuery(iframe).attr('style','position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
	document.body.appendChild(iframe);
	doc=iframe.contentWindow.document;
	var links=window.document.getElementsByTagName('link');
	for(var i=0;i<links.length;i++)
	if(links[i].rel.toLowerCase()=='stylesheet')
	doc.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');
	doc.write('<div class="'+jQuery(el).attr("class")+'">'+jQuery(el).html()+'</div>');
	doc.close();
	iframe.contentWindow.focus();
	iframe.contentWindow.print();
	alert('Printing...');
	document.body.removeChild(iframe);
}


function displayCategory(selector)
{
	jQuery('.navigationCategories LI .active').removeClass('active');
	jQuery('A:first', selector).addClass('active');
	jQuery(selector).parents('UL').show();
	jQuery(selector).children('UL').show();
}

function updateStatus(cartId, status, element)
{
	site.setStatus(cartId, status, function(data){
		if(data.result) {
			jQuery(element).parent().parent().html('<strong>Order is ' + status + '</strong>' )
		} else {
			alert('nok');
		}
	});
	return false;
}

function printPage(container)
{
	var w = window.open('', '', 'resizable=no,width=800,height=600,menubar=yes,status=no,scrollbars=yes');
	w.document.write('<html><head><link href="/css/site.css" media="screen" rel="stylesheet" type="text/css" /></head><body>'); 
	w.document.write(jQuery(container).html());
	w.document.write('</body></html>');
	w.document.close();
	w.focus();
	w.print();
	w.close();
}