jQuery.extend(
	jQuery.expr[ ":" ], 
	{ reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);

var MD = function() {
	return {
		emailTestRegexp : /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
		lightBoxParams : {
			imageBtnClose: '/assets/img/lightbox/lightbox-btn-close.gif',
			imageBtnPrev: '/assets/img/lightbox/lightbox-btn-prev.gif',
			imageBtnNext: '/assets/img/lightbox/lightbox-btn-next.gif',
			imageLoading: '/assets/img/lightbox/lightbox-ico-loading.gif',
			imageBlank: '/assets/img/lightbox/lightbox-blank.gif',
			fixedNavigation: true
		},
		lightBox: function(selector) {
			$(selector).lightBox(this.lightBoxParams);
			return this;
		},
		lightBoxforContainer: function(selector) {
			$(selector).each(
				function() {
					$(this).find('a').lightBox(MD.lightBoxParams);
				}
			);
			return this;
		},
		quickQuote: function() {
				$('[name=quantity]').keyup(function() {
						var id = $(this).parent().find('[name=id]').val();
						if ($(this).parent().find('[name=door]').val() != null) // Мы на странице описания двери, добавляем с установленными frame, hardware и prehung 
						shop.setQuantityChecked(this, id);
						else
							shop.setQuantity(this, id);
				});
				$('.up').click(function() {
						var id = $(this).parent().parent().find('[name=id]').val();
						if ($(this).parent().parent().find('[name=door]').val() != null) // Мы на странице описания двери, добавляем с установленными frame, hardware и prehung
							shop.addProduct({id: id, add: 1, frame:true, hardware:true, prehung:true});
						else
							shop.addProduct({id: id, add: 1});
						var quantity = $(this).parent().parent().find('[name=quantity]');
						quantity.val(parseInt(quantity.val()) + 1);
				});
				$('.down').click(function() {
						var id = $(this).parent().parent().find('[name=id]').val();
						if ($(this).parent().parent().find('[name=door]').val() != null) // Мы на странице описания двери, добавляем с установленными frame, hardware и prehung
							shop.addProduct({id: id, add: -1, frame:true, hardware:true, prehung:true});
						else
							shop.addProduct({id: id, add: -1});
						var quantity = $(this).parent().parent().find('[name=quantity]');
						quantity.val(parseInt(quantity.val()) - 1);
				});
				$('.delete').click(function() {
					var tr = $(this).parent().parent();
					var id = tr.find('[name=id]').val();
						if (confirm('Are you sure you want to remove this door?')) {
							shop.addProduct({id: id, add: 0, set: true});
								var quantity = tr.find('[name=quantity]');
								quantity.val(0);
								tr.remove();
						}
						
						var quantity = $(this).parent().parent().find('[name=quantity]');
						quantity.val(parseInt(quantity.val()) - 1);
				});
				return this;
			},
		interiorDoorOrdering: function() {
			MD.fieldsEvents();
			$('#add_door').click(function() {
				var index = $('#index').val();
				var new_door = $($('#sample').html().replace(/#index#/g, index).replace(/#/g, ''));
				new_door.appendTo($('#doors'));
				MD.fieldsEvents(new_door);
				$('#index').val(parseInt(index)+1);
			});
			$('form').submit(function() {
				$('.required input, .required select').removeClass('error');
				$('#error_message, #error_message_form, #error_message_doors').html('');
				$('.form .required input, .form .required select, .modified .required input, .modified .required select').each(function() {
					if ($(this).is(':reallyvisible') && $(this).val().replace('Door Name', '') == '')
						$(this).addClass('error');
				});
				var email = $('#doors_odering_email');
				if(MD.emailTestRegexp.test(email.val()) == false)
					 email.addClass('error');
				var error_form = $('.form .required input, .form .required select').hasClass('error');
				var error_doors = $('.modified .required input, .modified .required select').hasClass('error');
				if (error_form || error_doors) {
					$('#error_message').html($('<div/>').addClass('flash flash-error').html('Your order has not been sent. Check the correctness of the entered data.'));
					if (error_form)
						$('<p/>').addClass('error').html('Please fill required fields').appendTo($('#error_message_form'));
					if (error_doors)
						$('<p/>').addClass('error').html('Your order is not formed correctly').appendTo($('#error_message_doors'));
					return false;
				}
				else {
					cookie.del('order');
					return true;
//          $('form').submit();
				}
			});
			return this;
		},
		fieldsEvents: function(el) {
			if (!el)
				el = $();
			$('[id^=door] input, [id^=door] select', el).change(function() {
			var index = -1;
			var regexp = /\[(\d+)\]/
			var matches = regexp.exec($(this).attr('name'));
				
			if (matches != null && matches.length > 1)
					var index = matches[1];
			
			$('#door' + index).addClass('modified');
			$('#modified' + index).val('1');
			});
			$('input.name', el).focus(function() {
				if ($(this).val() == 'Door Name')
					$(this).val('');
			});
			$('input.name', el).blur(function() {
				if ($(this).val() == '')
					$(this).val('Door Name');
			});
			$('[id^=model]', el).change(function() {
				var index = $(this).attr('id').replace('model', ''); 
				var colors_select = $('#color' + index); 
				colors_select.html('<option/>');
				var colors = models_colors[$(this).val()];
				if (colors) {
					for (var key in colors) {
						var option = $('<option/>').val(key).html(colors[key]);
						option.appendTo(colors_select);
					}
//          for (var i = 0; i < colors.length; i++) {
//            var option = $('<option/>').html(colors[i]);
//            if (colors[i] == $(this).val())
//              option.attr('selected', 'selected');
//            option.appendTo(colors_select);
//          }
				}
			});
			$('[id^=color]', el).change(function() {
					var index = $(this).attr('id').replace('color', ''); 
//          var id = $('#id' + index);
					var color_hidden = $('#color_hidden' + index);
//          id.val($(this).val());
					color_hidden.val($('option:selected', this).html());
				});
			$('[id^=thickness]', el).change(function() {
					var index = $(this).attr('id').replace('thickness', ''); 
					var thickness_hidden = $('#thickness_hidden' + index);
					thickness_hidden.val($('option:selected', this).html());
				});
			$('select.custom', el).change(function() {
				if ($(this).val() == 'custom')
					$('#custom_' + $(this).attr('id')).css('display', 'block');
				else
					$('#custom_' + $(this).attr('id')).css('display', 'none');
			});
			$('[name*=type]', el).change(function() {
				var regexp = /(\d+)/;
				var index = regexp.exec($(this).attr('name'))[0];
				switch($(this).val()) {
					case 'swing':
						$('#hardware' + index + ', #prehung' + index + ', #opening_left' + index +
							', #opening_right' + index).css('display', 'block');
						$('#fix' + index).css('display', 'none');
						if($('#hardware' + index + ' input').is(':checked')) {
							$('#privacy' + index).css('display', 'block');
							$('#items_hardware' + index).css('display', 'table-row');
						}
						else
							$('#privacy' + index + ', #items_hardware' + index).css('display', 'none');
						break;
					case 'double':
						$('#prehung' + index + ', #hardware' + index).css('display', 'block');
						$('#opening_left' + index + ', #opening_right' + index).css('display', 'none');
						if($('#hardware' + index + ' input').is(':checked')) {
							$('#privacy' + index + ', #fix' + index).css('display', 'block');
							$('#items_hardware' + index).css('display', 'table-row');
						}
						else
							$('#privacy' + index + ', #fix' + index + ', #items_hardware' + index).css('display', 'none');
						break;
					case 'pocket':
					case 'sliding':
						$('#hardware' + index + ', #privacy' + index + ', #prehung' + index + ', #fix' + index +
							', #opening_left' + index + ', #opening_right' + index +
							', #items_hardware' + index).css('display', 'none');
						break;
				}
			});
			$('[name*=opening]', el).change(function() {
				var regexp = /(\d+)/;
				var index = regexp.exec($(this).attr('name'))[0];
				switch($(this).val()) {
					case 'left':
						$('#opening_left' + index + ' img').attr('src', '/assets/img/p_swing_L_on.gif');
						$('#opening_right' + index + ' img').attr('src', '/assets/img/p_swing_R_off.gif');
						break;
					case 'right':
						$('#opening_right' + index + ' img').attr('src', '/assets/img/p_swing_R_on.gif');
						$('#opening_left' + index + ' img').attr('src', '/assets/img/p_swing_L_off.gif');
						break;
				}
			});
			$('[id^=hardware] input', el).click(function() {
				var index = $(this).parent().attr('id').replace('hardware', ''); 
				$('#items_hardware' + index + ', #privacy' + index).toggle();
				if ($('#door' + index + ' [name*=type]:checked').val() == 'double' && $(this).is(':checked'))
					$('#fix' + index).css('display', 'block');
				else
					$('#fix' + index).css('display', 'none');
			});
			$('[id^=delete]', el).click(function() {
					var index = $(this).attr('id').replace('delete', ''); 
					if (confirm('Are you sure you want to remove this door?'))
						$('#door_over' + index).remove();
				});
			if ($.browser.msie) {
				$('[name*=type], [name*=opening]', el).click(function () {
						this.blur();
						this.focus();
				});
			}
		},
		exteriorDoorOrdering: function() {
			$('#configuration').change(function() {
				$('#transom_field, #left_sidelight_field, #right_sidelight_field').css('display', 'none');
				if ($(this).val().indexOf('Transom') > 0)
					$('#transom_field').css('display', 'block');
				if ($(this).val().indexOf('Left Sidelight') > 0 || $(this).val().indexOf('2 Sidelights') > 0)
					$('#left_sidelight_field').css('display', 'block');
				if ($(this).val().indexOf('Right Sidelight') > 0 || $(this).val().indexOf('2 Sidelights') > 0)
					$('#right_sidelight_field').css('display', 'block');
			});
			$('#casing').change(function() {
					$('#jamb_field').css('display', 'none');
					if ($(this).val() == 'For Door Replacement')
						$('#jamb_field').css('display', 'block');
				});
			$('form').submit(function() {
				$('.required input, .required select').removeClass('error');
				$('#error_message_form').html('');
				$('.required input, .required select').each(function() {
					if ($(this).is(':reallyvisible') && $(this).val() == '')
						$(this).addClass('error');
				});
				var email = $('#doors_odering_email');
				if(MD.emailTestRegexp.test(email.val()) == false)
					 email.addClass('error');
				var error = $('.required input, .required select').hasClass('error');
				if (error) {
					$('#error_message').html($('<div/>').addClass('flash flash-error').html('Your order has not been sent. Check the correctness of the entered data.'));
					$('<p/>').addClass('error').html('Please fill required fields').appendTo($('#error_message'));
					return false;
				}
				else
					return true;
					//$('form').submit();
			});
			return this;
		},
		doorsResult: function() {
				$('#show_schedule').click(function() {
					MD.showWindow('schedule', 'Door Schedule', $('#print_header').html() + $('#schedule').html());
					return false;
				});
				$('#show_estimate').click(function() {
					MD.showWindow('estimate', 'Estimate', $('#print_header').html() + $('#estimate').html());
					return false;
				});
			return this;
		},
		showWindow: function(id, title, html) {
			win1 = window.open('', id, 'toolbar=0,scrollbars=1,location=0,width=800,height=380');
//      if (win1.document.body.childElementCount == 0) {
				win1.document.close();
				win1.document.open();
				win1.document.writeln('<html><head><title>' + title + '</title>' + 
				'<style>' +
					'body {font-family:Arial,Tahoma,Verdana,san-serif; font-size:14px;}' +
					'.quick_quote table {border-collapse: collapse;border: 0;padding: 0;margin: 0;margin-top: 30px;}' +
					'.quick_quote td {padding: 5px 10px;font-size: 14px;border: 1px solid #000;}' +
					'.quick_quote thead td {font-size: 14px;font-weight:bold;background-color: #dfdfdf;}' +
					'.quick_quote tfoot td {background-color: #dfdfdf;font-weight: bold;padding: 7px 10px 3px;}' +
					'.quick_quote tfoot td.clear {background: none;border: none;}'+
					'.quick_quote tfoot td.total p {color: #c4152a;font-size: 14px;font-weight: normal;position: relative;top: -3px;}' +
					'.quick_quote tfoot td.total p span {font-size: 20px;font-weight: bold;}' +
					'.right {text-align: right !important;}' +
					'.print {text-align: center;}' +
					'a {background: url(/assets/img/print-btn.gif) no-repeat left center;padding-left:15px;text-align: center;}' +
					'@media print { a { display: none; } }' +
				'</style>' + 
				'</head><body>');
				win1.document.writeln(html);
				win1.document.writeln('<div class="print"><a href="#" onclick="window.print(); return false;">Print</a></div></body></html>');
				if ($.browser.msie)
					win1.location.reload(true);
				if (window.focus)
					win1.focus();
				win1.print();
		},
		payment: function() {
			$('#payment_copy').click(function() {
				if ($(this).is(':checked')) {
					$('[id^=payment_bill_]').each(function() {
						var name = $(this).attr('id').replace('payment_bill_', '');
						$('#payment_ship_' + name).val($(this).val());
					});
					$('div[id^=field_payment_bill_] select').each(function() {
						var name = $(this).parent().attr('id').replace('field_payment_bill_', '');
						$('#field_payment_ship_' + name + ' select').attr('selectedIndex', $(this).attr('selectedIndex'));
					});
				}
				else {
					$('[id^=payment_ship_]').val('');
					$('div[id^=field_payment_ship_] select').attr('selectedIndex', 0);
				}
			});
			$('form').submit(function() {
			var error = '';
			$('.required').each(function() {
				if ($(this).find('input, select').val() == '' || (this.id.indexOf('email') > 0 && MD.emailTestRegexp.test($(this).find('input').val()) == false)) {
					error = $(this).find('label').html().replace('<span>*</span>', '').replace(':', '') + ' required';
					return false;
				}
			});
			if (error != '') {
				alert(error);
				return false;
			}
			else
			return true;
//        $('form').submit();
			});
			return this;
		},
		forms: function() {
			$('form').submit(function() {
				$('.required input, .required select, .required textarea').removeClass('error');
				$('.required input, .required select, .required textarea').each(function() {
					if ($(this).val() == '')
						$(this).addClass('error');
				});
				var email = $('input[id$=_email]');
				if(MD.emailTestRegexp.test(email.val()) == false)
					email.addClass('error');
				var error = $('.required input, .required select, .required textarea').hasClass('error');
				if (error) {
					$('#error_message').html($('<div/>').addClass('flash flash-error').html('Your message has not been sent. Check the correctness of the entered data.'));
					$('<p/>').addClass('error').html('Please fill required fields').appendTo($('#error_message'));
					return false;
				}
				return true;
//        $('form').submit();
			});
			return this;
		}
	};
}();
