/// <reference path="~/Scripts/jquery-1.6.2-vsdoc.js" />
/// <reference path="~/Scripts/linq-vsdoc.js" />
/// <reference path="~/Scripts/jquery-ui-1.8.14.js" />

function SegmentPropertiesDialog(saveAndCloseCallback, closeWithoutSaveCallback)
{
  this.OpenForNew = function (pageId)
  {
    displaySegmentTypeDialog(function (segmentTypeId)
    {
      console.log(segmentTypeId);
      createEditDialog('/segment/new/' + pageId + '/' + segmentTypeId + '/?dialog=true', {
        pageId: pageId,
        segmentTypeId: segmentTypeId,
        action: 'add'
      });
    });
  };

  this.OpenForEdit = function (segmentId)
  {
    createEditDialog('/segment/' + segmentId + '/edit?dialog=true', {
      segmentId: segmentId, 
      action: 'edit'
    });
  };

  function createEditDialog(dialogUrl, options)
  {
    $('body').append('<div id="dialogSpace" />');

    $("#dialogSpace").load(dialogUrl, function ()
    {
      //each segment admin UI sets the webframe.segmenttype.adminhandler to the loaded admin object
      var adminhandler = webframe.segmenttype.adminhandler;

      //this is common
      $('#tabsContainer').tabs();
      $('.hideInDialog').hide();

      var handlerOptions = {
        segmentTypeId: options.segmentTypeId,
        segmentId: options.segmentId,
        pageId: options.pageId,
        saveAndCloseCallback: saveAndCloseCallback || function(){ },
        closeWithoutSaveCallback: closeWithoutSaveCallback || function () { },
        action: options.action
      };
      // bundle up the creation of the passed options...contains safe callbacks, segment ids...
      adminhandler(handlerOptions);

    });
  }
}

function displaySegmentTypeDialog(okCallback)
{ 
  function enterFunction()
  {
    var segmentTypeId = $('#cboSegmentType').val();
    $("#dialogSpace").dialog('close');

    if (okCallback != null)
    { okCallback.call(null, segmentTypeId); }
  }
  
  $('body').append('<div id="dialogSpace" />');
  $("#dialogSpace").load('/contentpage/SegmentTypeSelection', function ()
  {
    $("#dialogSpace").dialog(
		  {
		    buttons:
			  {
			    'OK': function ()
			    {
			      enterFunction();
			    },
			    'Cancel': function ()
			    { $(this).dialog('close'); }
			  },
			  width: 300,
		    height: 150,
		    modal: true,
		    title: 'Choose Segment Type',
		    close: function ()
		    {
		      $("#dialogSpace").remove();
		      document.isDialogOpen = false;
		    },
		    open: function ()
		    {
		      $('#cboSegmentType').keypress(function (e)
		      {
		        console.log(e);
		        if (e.keyCode === $.ui.keyCode.ENTER)
		        { enterFunction(); }
		      });
		    }
		  });
  });   
}
