﻿

$.fn.gridMenu = function (options) {
	
	var _this = $(this);
	 $(_this).bind("contextmenu",function(e){
              return false;
       });
	var menu = $('.grid-menu:first', this);
	$('.menu-entry', menu).hover(
		function(e){
			$(this).css('background-color', 'gray');
			$('a', this).css('color', 'white');
		},
		function(e){
			$(this).css('background-color', 'white');
			$('a', this).css('color', 'gray');
		}
	);
	var formContent = $('.popup-content-' + $(menu).attr('data-editFormId'));
	//alert($(menu).attr('data-editFormId'));
	$('.menu-items .form-popup', $(menu)).unbind('click');
	$('.menu-items .form-popup', $(menu)).click(function(e){
		
		var url = '/admin/' + options['action'];
		var itemId  = $(this).attr('data-hoveredItemId');
		var fType = $(this).attr('data-formType');
		//alert('sectionId : ' + options['sectionId'] + ', id : ' + itemId + ', formType: '  + fType);
		$.ajax({
            type: "POST",
            url: url,
            data: {sectionId : options['sectionId'], itemId : itemId, formType: fType},
            dataType: "html",
            success: function (data) {
				$('div[data-fieldName]', data).each(function(e){
					if($(this).attr('data-contentType') != 'Html'){
						
						$('.ui-dialog .form-box[data-formType='+fType+'] div[data-fieldName='+$(this).attr('data-fieldName')+']').html($('div[data-fieldName='+$(this).attr('data-fieldName')+']', data).html());
					}
					else
					{
						$('.ui-dialog .form-box[data-formType='+fType+'] div[data-fieldName='+$(this).attr('data-fieldName')+'] .html-editor').html($('div[data-fieldName='+$(this).attr('data-fieldName')+']  .html-editor', data).html());
					}			
                });
                $('.ui-dialog .form-box[data-formType='+fType+'] .buttons:first').html($('.buttons:first', data).html());
                $('.ui-dialog .form-box[data-formType='+fType+'] .html-editor textarea').cleditor();
				var urlParts = $('.ui-dialog .form-box[data-formType='+fType+'] form ').attr('action').split('/');
				if(isNaN(parseFloat(urlParts[urlParts.length - 1]))){
					$('.ui-dialog .form-box[data-formType='+fType+'] form ').attr('action', $('.ui-dialog .form-box[data-formType='+fType+'] form ').attr('action') + '/' + itemId);
				}
				if(fType == 'DisplayForm'){
					$('.html-editor-disabled .html-editor textarea:first').cleditor()[0].disable(true).refresh();
				}
				$(menu).hide();
            }
        });
	});
	$(this).unbind('mousedown');
	$('tr', this).mousedown(
		function(e){
			if(e.which == 3)
			{
				var rowOn = $(this);
				var itemId = $('td div[data-fieldName=PrimaryKey]:first input:first', rowOn).val();
				$('.menu-items .form-popup', $(menu)).attr('data-hoveredItemId', itemId);
				//alert(window.mouseXPos);
				$(menu).css('top', window.mouseYPos - $($(menu).parent()).offset().top);
				$(menu).css('left', window.mouseXPos);
				$(menu).show();
			}
			return true;
		})
};
