// Turn off the ckeck of the phone field
jQuery.is.phone = function(val) {
	return true;
}

jQuery.fn.extend({
	toggleAvailBy: function( flag )
	{
		if (flag == false) {
			this.attr('disabled', false);
		} else {
			this.val('').attr('disabled', true);
		}

		return true;
	},
	
	reset: function ( fn )
	{
		return fn ? this.bind("reset", fn) : this.trigger("reset");
	},

	serializeJSON: function()
	{
		var json = {};
		jQuery.map($(this).serializeArray(), function (n, i) {
			json[n['name']] = n['value'];
		});
		return json;
	}
});

$(document).ready(function() {

	if (jQuery.area == 'A') {
		fn_product_attributes_init();
	}
});

function fn_product_attributes_init()
{
	var qtyDiscountsContainer = $('#content_qty_discounts');
	if (qtyDiscountsContainer.length == 0) {
		return;
	}

	var productPriceFields = $('#price_price').add('input.product-price:first', qtyDiscountsContainer);

	productPriceFields.change(function() {
		productPriceFields.val(this.value);
	});

	$('tr:eq(1) input.license-exists', qtyDiscountsContainer).click(function() {
		return false;
	});

	$('tr:eq(1) select.usergroup:first', qtyDiscountsContainer).change(function() {
		this.selectedIndex = 0;
	});
}

function fn_switch_attributes(elm)
{
	var inp = $('input', $(elm).parents('.cm-value-changer:first'));
	var new_val = parseInt(inp.val()) + ($(elm).is('a.cm-increase') ?  1 : ($(elm).is('a.cm-decrease') ? -1 : 0));
	var _id = inp.attr('id').replace('product_id_', '');

	var disable = new_val > 0 ? false : true;

	$('#product_attributes_' + _id).switchAvailability(disable, false);

}

function fn_is_one_checked(name)
{
	return !!$('input:checked[name="' + name + '"]').length;
}

function fn_toggle_license_domain(licenseId, elementId)
{
	if (licenseId != 0) {
		$('#' + elementId).val('');
		$('#' + elementId).parent().siblings('label').removeClass('cm-required');
		$('#' + elementId).parent().hide();
	} else {
		$('#' + elementId).parent().siblings('label').addClass('cm-required');
		$('#' + elementId).parent().show();
	}
}

/**
 * Specificator dialog. 
 *
 * Provides the ability for a user to specify some details after some action, that mustn't lead to page reload
 * (for example, after changing a status of an object) by rendering and processing a dialog with a form.
 *
 */
(function($){
	var methods = {
		_init: function(params) {
			
			params = params || {};

			$(this).data('_params', params);

			if (params.requestParams.obj && params.requestParams.obj.hasClass('cm-ajax')) {
				params.requestParams.obj.removeClass('cm-ajax');
				params.requestParams.obj.parents('.cm-popup-box').zIndex(26);
			}

			// Prevent caching of the dialog DOM tree so as to be properly updated via ajax
			$(this).dialog('destroy');
			$('.object-container', this).find('>:first-child').unwrap();

			$(this).ceDialog('open', params.dialogParams);

			if (params.preProcessing) {
				params.preProcessing.apply(this);
			}

			var _this = this;
			$('form', this).eq(0).unbind('submit').submit(function () { return _this.specDialog('submit') });

			return false;
		},

		submit: function() {

			var params = $(this).data('_params');
			var form = $('form', this).eq(0);

			params.requestParams.data = $(':input', form).serializeJSON();

			
			if (!form.get(0).f.check()) {
				return false;
			}

			var	url = typeof(params.requestParams.url) != 'undefined' ? params.requestParams.url : form.attr('action');

			params.requestParams.force_exec = true; // Important for scripts inside the form (for example calendars)

			$.ajaxRequest(url, params.requestParams);

			$(this).specDialog('close');

			return false;
		},

		close: function() {
			$(this).ceDialog('close');
		}
	};

	$.fn.specDialog = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if ( typeof method === 'object' || ! method ) {
			return methods._init.apply(this, arguments);
		} else {
			$.error('ty.specDialog: method ' + method + ' does not exist');
		}
	}
})(jQuery);

/**
 * New message dialog
 */
(function($){
	var methods = {
		_init: function(params) {
			params = params || {};

			if (area == 'A') {
				var wrapper_height = (parseInt(window.innerHeight) || 900) - 100;
				if (!$('#hd_bottom_wrapper').length) {
					$('#main_column').after('<div id="hd_bottom_wrapper" style="display: block; height: ' + wrapper_height + 'px;">&nbsp;</div>');
				}
				
				$(jQuery.browser.opera ? 'html' : 'html,body').animate({scrollTop: ($('#comet_container').offset().top)}, 0); //jQuery.scrollToElm($('#comet_container'));
				
				$(this).ceDialog('close');
				$(this).ceDialog('open', {
					modal: false,
					position: 'bottom',
					height: wrapper_height + 140
				});
				
			} else {
				$(this).ceDialog('open');
			}

			return false;
		}
	};

	$.fn.messageDialog = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if ( typeof method === 'object' || ! method ) {
			return methods._init.apply(this, arguments);
		} else {
			$.error('ty.messageDialog: method ' +  method + ' does not exist');
		}
	};
})(jQuery);


/*
 AJAX field validator
*/
(function($) {
	var timer = null;

	$(document).bind('keyup', function(e) {
		var jelm = $(e.target);
		var elm = e.target;
		var s;
		e.which = e.which || 1;

		if ((e.type == 'click' || e.type == 'mousedown') && jQuery.browser.mozilla && e.which != 1) {
			return true;
		}
		
		if (e.type == 'keyup') {
			if (jelm.hasClass('cm-ajax-validation')) {
				if (timer) {
					clearTimeout(timer);
				}

				timer = setTimeout(function() {
					
					$.ajaxRequest(fn_url('validators.license_domain'), {method: 'get', data: {domain: jelm.val()}, callback: function(data) {
						if (data.valid_domain) {
							jelm.removeClass('cm-failed-field');
							$('#invalid_' + jelm.attr('id')).hide();
							$('#valid_' + jelm.attr('id')).show();
						} else {
							$('#invalid_' + jelm.attr('id')).show();
							$('#valid_' + jelm.attr('id')).hide();
						}
					}});

				}, 300);
			}
		}
	});


})(jQuery);

function fn_hd_check_domain(elm_id)
{
	if ($('#valid_' + $('#' + elm_id).attr('id')).is(':visible')) {
		return true;
	}

	return '';
}

