jQuery.fn.hint = function(hint_text) {
	var item = this;

	if(hint_text != null) {
		var hint = hint_text;
	}
	else {
		var hint = item.attr('title');
	}
	
	if(item.val() == '') {
		item.val(hint);
		item.addClass('hint');
	}
	
	item.focus( function(){
		if( $.trim(item.val()) == hint ){ 
			item.val('');
			item.removeClass('hint');
		}
	});
	item.blur( function(){
		if( $.trim(item.val()) == '' ){ 
			item.val(hint);
			item.addClass('hint');
		}
	});
}


//Define main metalworks namespace
var metalworks = metalworks || {};
var submit_lock = false;

metalworks.orderForm = (function() {   
   var uuid = false;

   function reload(data) {
         $('.b-order-form').before(data).remove();
   }
   
    function initForm(data) {
        if ($('.b-order-form').length) {
            var old_upload = $('#uploadify_widget');
            $('.b-order-form').before(data).remove();
	        $('#uploadify_widget').replaceWith(old_upload);
        }
        else {
            $('body').append(data);
        }
      
        var that = this;

        $('.b-order-form .b-next').click(function() {
            submit();
            return false;
        });
        $('.b-order-form .b-delete').click(function() {
            hide();
             return false;
        });
        $('.b-order-form .delete').click(function() {
            hide();
            return false;
        });
   }
   
    function show() {
        if ($('.b-order-form').length) {
            $('#overlay').show();
            $('.b-order-form').show();
        }
        else {
            $.get('/orders/form/', false, initForm, 'html');
            $('<div id="overlay" class="overlay" />').appendTo('body').click(hide);
        }
    }

    function hide() {
        $('#overlay').hide();
        $('.b-order-form').hide();
    }

    function submit() {
        if (submit_lock) {
            return false;
        }

        var data = {
            'name': $('#id_name').val(),
            'email': $('#id_email').val(),
            'phone': $('#id_phone').val(),
            'description': $('#id_description').val(),
            'public_allow': $('#id_public_allow').attr("checked") ? 1 : 0,
            'uuid': metalworks.orderForm.uuid
        };

        $('.b-order-form div, .b-order-form .b-next, .b-order-form p').remove();
        $('.b-order-form').append($('<p>Ваша заявка успешно принята. В течение ближайшего рабочего дня мы свяжемся с вами.</p>'));

        $.post('/orders/form/', data);
        _gaq.push(['_trackEvent', 'order_form', 'submit']);
   }
   
   return {
      'show': show,
      'hide': hide,
      'uuid': uuid
   };
   
})();


