$j = jQuery.noConflict();
//fix IE compat issue
window.onerror=function(){
 alert('An error has occurred!')
 return true
}


$j(document).ready(function(){
   getMashablesList(mashupStart, mashupCount, paginationToken);
   //getTagCloud();
   $j('#block-tag_cloud-0').hide();
 });

var tempUserName = '';
var tempApiPwd = '';
var realUserName = '';
var callbackTrigger = '';
var paginationToken = '';
var mashupStart = -1;
var mashupCount = 10;
var mashupTotal = 0;
var emmlClick = '';
var origApiUser = 'Cloud_Wall';
var apiUser = 'Cloud_Wall';
var apiPwd = 'Cloud_Wall';
var apiAdminUser = 'admin';
var apiAdminPwd = 'adminadmin';
var commPaginationToken = '';
var commStart = -1;
var commCount = 2;
var commTotal = 0;
var commClick = '';
var itemId = '';
var commLimit = 2;
var isWires = 0;

/* establish the server connection */
var prestoConfig = {
  prestoUrl: "http://cloud.jackbe.com/presto", 
  username: apiUser, 
  password: apiPwd,
  crossDomainPost: false
}
var connection = new Presto.Connection(prestoConfig);

/* list presto items */
function listMashables(ds) {
     //alert('in listMashables');
   outputstr = '';   
   $j("#listMashablesFooter").html('');
   $j('#listMashables').html('');
   ds.each(function(item) {
     outputstr = '';
     
     var strTags = '';
     //alert(item.tags);
     strTags = (item.tags)?getItemTags(item.tags):strTags;
     var avgRating = item.feedbackStatistics.avarageRating * 1;
     var description = item.description;
     if (typeof description == 'object')description = '';
     outputstr = outputstr + '<div id="node-' + item.name +  '" class="node" style="line-height:normal;">';
     outputstr = outputstr + '<div id="msg' + item.name +  '" ></div>';
     outputstr = outputstr + '<p style=""><img src="http://www.jackbe.com/enterprise-mashup/wall/images/profile_mdc_90x52.jpg" align="left" style="margin:6px; margin-top:4px; margin-left:0px;" />';
     outputstr = outputstr + '<span id="fav' + item.name +  '" style=""></span> ';
     outputstr = outputstr + ' <span style="font-weight:bold;">' + item.name + '</span>';
     outputstr = outputstr + ' &nbsp;<span id="rating' + item.name +  '"  style="vertical-align:text-top;"></span>';
     outputstr = outputstr + '<br />Created <span title="' + item.lastChangedDate +  '"><small style="font-size:80%;">' + item.lastChangedDate +  '</small></span> by ' + item.creator +  ' ';
     outputstr = outputstr + strTags;
     outputstr = outputstr + '<span style="display:block; margin-top:4px;">' + description + '</span>';
     outputstr = outputstr + '</p>';
     outputstr = outputstr + '<div class="content clear-block"></div><div id="navComm' + item.name +  '">';
     outputstr = outputstr + '<a href="javascript:void(0);" title="show comments" id="btnComm' + item.name +  '" onclick="toggleComments(\'' + item.name +  '\')">show comments</a>';
     outputstr = outputstr + ' | <a href="javascript:void(0);" title="share comments" id="btnShare' + item.name +  '" onclick="displayCommentsDialog(\'' + item.name +  '\')">add comments</a>';
     outputstr = outputstr + ' | <a href="javascript:void(0);" title="view Mashup details" id="btnShare' + item.name +  '" onclick="displayMashupDialog(\'' + item.name +  '\')">Mashup Details &amp; Actions</a>';
     outputstr = outputstr + '</div><div id="comm' + item.name +  '" style="margin-left:16px;"></div></div>';
     
     //$j('#listMashables').append(outputstr);
     $j(outputstr).appendTo('#listMashables');
     //getComments(item.name, 2);
     $j('#rating' + item.name).rater(item.name, {style: 'inline', curvalue:avgRating});
     $j('#fav' + item.name).rater(item.name, {maxvalue:1, style: 'inline'}); 
     
  });
  //alert('mashupStart: ' + mashupStart + ' mashupTotal: ' + mashupTotal + ' mashupCount: ' + mashupCount);
   outputstr = '<div class="btn btnContent"><a href="javascript:updateMashablesList(\'' + mashupStart + '\', \'' + mashupCount + '\', \'' + paginationToken + '\');" onclick="updateMashablesList(\'' + mashupStart + '\', \'' + mashupCount + '\', \'' + paginationToken + '\'); return false;">MORE</a></div>';
   if(0 == mashupCount){ 
     outputstr = '<div class="btn btnContent">Viewing ' + mashupTotal + ' of ' + mashupTotal + ' Results.</div>';
   }
   $j("#listMashablesFooter").html(outputstr);
   outputstr = '';
    //$j('<p><a href="javascript:void(0)" style="text-decoration:underline;" onclick="updateMashablesList(\'' + mashupStart + '\', \'' + mashupCount + '\', \'' + paginationToken + '\'); return false;">List All Mashups</a></p>').prependTo('#listMashables');
    $j('<p><a href="javascript:void(0)" style="text-decoration:underline;" onclick="mashupCount = 10;getMashablesList(\'-1\', \'10\', \'\'); return false;">List All Mashups</a></p>').prependTo('#listMashables');

   //displayItemComments(ds);
 }
function displayItemComments(ds){
  ds.each(function(item) {
    getComments(item.name, 2);
  });
}
function displayMashupDialog(itemId){
  var myOptions = {};
  var mySpeed = 1000;
  var myEffect = 'blind';
  var thisItemId = itemId;
  itemId = itemId;
  //$j('#dialog').html(displayLoading());
  $j('#dialog').dialog('destroy');
  $j('#dialog').html(tabbedDialog());
  $j('#tabs-1').html(displayLoading());
  $j('#tabs-2').html(displayLoading());
  //$j('#tabs-3').html(displayLoading());
  $j("#tabs").tabs();

  getEmml(itemId);
  getServiceDetails(itemId);
  //$j('#tabs-3').html(displayRun(itemId));
  
  $j.fx.speeds._default = mySpeed;
  $j("#dialog").dialog({
    title: ' ' + itemId,
    bgiframe: true,
    autoOpen: false,
    height: 400,
    width: 700,
    modal: true,
    buttons: {
      'Launch in Wires': function() {
      //$j('#dialog').html(displayLoading());
            if(origApiUser == apiUser){
                $j("#tabs").tabs( 'remove' , 2 );
              $j("#tabs").tabs( 'add' , '#tabs-4' , 'Login', 2);
              $j('#tabs-4').html(displayLoading());
              $j("#tabs").tabs( 'select' , '#tabs-4');
              $j('#tabs-4').html(getPrestoLoginForm('wiresLoginDialog', itemId));
              $j('#dialog').dialog('option', 'width', '548px');
              $j('#dialog').height('320px');
              //$j("#dialog").dialog('option', {title: 'VIEW ' + itemId + ' IN WIRES'});
            }
            else{
               //$j('#dialog').html(displayWires(itemId));
               displayWires(itemId);
            }
      },
      'Clone in Wires': function() {
      //$j('#dialog').html(displayLoading());
            if(origApiUser == apiUser){
                $j("#tabs").tabs( 'remove' , 2 );
              $j("#tabs").tabs( 'add' , '#tabs-4' , 'Login', 2);
              $j('#tabs-4').html(displayLoading());
              $j("#tabs").tabs( 'select' , '#tabs-4');
              $j('#tabs-4').html(getPrestoLoginForm('cloneLoginDialog', itemId));
              $j('#dialog').dialog('option', 'width', '548px');
              $j('#dialog').height('320px');
              //$j("#dialog").dialog('option', {title: 'CLONE ' + itemId + ''});
            }
            else{
               displayClone(itemId);
            }
      }
        },
      close: function() {
        itemId = '';
      }
  });
  $j('#dialog').dialog('open');
  t=setTimeout("modButton(\"" + thisItemId + "\")",500);
}
function modButton(itemId){
  if(isWires == -1){
    $j('.ui-dialog-buttonpane > button').attr('disabled',true);
    $j('.ui-dialog-buttonpane > button').addClass( 'ui-state-disabled' );
  }
  else if(apiUser != origApiUser && apiUser != ''){
  $j('.ui-dialog-buttonpane').html('');
  //var cloneURL = encode64(encodeURIComponent('mashupId=' + itemId + '&dialog=saveas&u=' + apiUser + '&p=' + apiPwd + '&end=y'));
  var cloneURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas';
  var launchURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId;
  //$j('<a class="button ui-state-default ui-corner-all" href="login.html?v=' + launchURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-left:6px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
  //$j('<a class="button ui-state-default ui-corner-all" href="login.html?v=' + cloneURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-left:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');
  $j('<a class="button ui-state-default ui-corner-all" href="' + launchURL + '" target="_blank" style="padding:4px 12px;margin-top:6px;margin-left:6px;margin-bottom:6px;margin-right:6px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
  $j('<a class="button ui-state-default ui-corner-all" href="' + cloneURL + '" target="_blank" style="padding:4px 10px;margin-top:6px;margin-bottom:6px;margin-left:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');
  }
}
function displayLoading(){
    data='<div title="Loading Content..." style="display:block; width:100%; height:100%; background: #ccc url(http://www.jackbe.com/enterprise-mashup/wall/images/wait.gif) no-repeat center center;"></div>';
    return data;
}
function displayWires(itemId){
    prestoWin = window.open('http://cloud.jackbe.com/wires/?mashupId=' + itemId,'_newtab','width=900,height=600');
    prestoWin.moveTo(10,10);
    //data='Opening Wires view of <strong>' + itemId + '</strong> in a <a target="_blank" style="text-decoration:underline;" href="http://cloud.jackbe.com/wires/?mashupId=' + itemId + '">new window</a>.';
    //return data;
}
function displayClone(itemId){
    prestoWin = window.open('http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas','_newtab','width=900,height=600');
    prestoWin.moveTo(10,10);
    //data='Opening Clone Inteface for <strong>' + itemId + '</strong> in a <a target="_blank" style="text-decoration:underline;" href="http://cloud.jackbe.com/wires/?mashupId=' + itemId + '">new window</a>.';
    //return data;
}
function displayRun(itemId){
    data='This is where RUN instructions will appear';
    return data;
}
function toggleComments(itemId){
  var el = '#btnComm' + itemId;
  var elTitle = $j(el).attr('title');
  if(elTitle == 'show comments'){
    getComments(itemId, 0);
  $j(el).attr('title', 'hide comments');
    $j(el).text('hide comments');
  return false;
  }
  $j('#comm' + itemId).html('');
  $j(el).attr('title', 'show comments');
  $j(el).text('show comments');
  return false;
}
function shareComments(itemId){
  if(origApiUser == apiUser)
  {
    //alert('Please login to Presto before using this feature.'); 
    displayUserLogin();
    return false;
  }
  if($j('#dialog').dialog){
    $j('#dialog').dialog('close');
  }
  displayServiceDialog(itemId);
  getCommentsForm(itemId, 0);
  return false;
}
function highlightElement(eId, hcolor, hspeed){
  var hcolor = (typeof(hcolor)=='undefined' || hcolor=='')?'#FE6019':hcolor;
  var hspeed = (typeof(hspeed)=='undefined' || hspeed=='')?'2000':hspeed;
  $j(eId).effect('highlight', {color: hcolor}, hspeed);
}
function getCommentsFormForDisplay(itemId){
  data = '<div id="commentHelp">Please add your comments below.</div><div><form class="commentForm" onsubmit="getItemFeedbackData(); return false;" ><input id="serviceId" name="serviceId" type="hidden" value="' + itemId + '"/><div><textarea id="comment" name="comment" type="text" style="width:95%; height:5em;"  maxlength="250" onkeyup="return ismaxlength(this)"></textarea></div><div style="display:block; float:right; margin-right:20px;"><a href="javascript:void(0);" onclick="$j(\'#dialog\').dialog(\'close\');" style="margin-top:6px;">Cancel</a> &nbsp; <input id="submitComment" name="submitComment" type="submit" value="Add Comment" style="display:inline;"></div></form></div><div style="clear:both;"></div>'; return data;
}
/***********************************************
* Textarea Maxlength script-  Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

var testPrestoLoginCallback = { 
  onSuccess: function(response) {
  //console.dir(response);
  //alert('enabled: ' + response.response.enabled);
  if(true == response.response.enabled){
    testPrestoLoginStep2(tempUserName, tempApiPwd, callbackTrigger);
    return;
  }
  else{
    if('prestoLoginDialog' == callbackTrigger){
      $j('#dialog').html(getPrestoLoginFormWithTerms(callbackTrigger, itemId));
      return;
    }
    else if('cloneLoginDialog' == callbackTrigger || 'wiresLoginDialog' == callbackTrigger){
      $j('#tabs-4').html(getPrestoLoginFormWithTerms(callbackTrigger, itemId));
      return;
    }
    else{
      return;
    }
  }
    realUserName = tempUserName;
    apiUser = tempUserName;
    apiPwd = tempApiPwd;
    prestoConfig = {
      prestoUrl: "http://cloud.jackbe.com/presto", 
      username: apiUser, 
      password: apiPwd,
      crossDomainPost: false
    }
    connection = new Presto.Connection(prestoConfig);
    $j('#' + callbackTrigger + 'Msg').html('Logged in as ' + realUserName);
    highlightElement('#' + callbackTrigger + 'Msg');
    if('prestoLoginDialog' == callbackTrigger){
      $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
      $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
      $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
      $j('#dialog').dialog('option', 'height', '175px');
        $j('#dialog').html(getCommentsFormForDisplay(itemId));
    }
    else if('runLoginDialog' == callbackTrigger){
      $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
      $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
      $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
      
      $j('#dialog').html(displayRun(itemId));
    }
    else if('wiresLoginDialog' == callbackTrigger){
      //$j('#dialog').html(displayWires(itemId));
      $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
      $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
      $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
      var launchURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId;
      var cloneURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas';
    //$j('#tabs-4').css( 'background-image', 'none' );
      $j('#tabs-4').css( 'height', '230px' );
      //$j('#tabs-4').html('<div><p style="margin-left:380px;"><br /><small style="font-size:80%;">Logged in as ' + realUserName + '</small></p></div><div style="margin-left:18px;"><a target="_blank" style="text-decoration:underline;" href="' + launchURL + '">Launch in Wires</a></div>');
      $j('#tabs-4').html('<div style="margin-left:325px; margin-top:53px; color:#000;"><small style="font-size:80%; color:#000;">Logged in as ' + realUserName + '</small><br /><a target="_blank" style="text-decoration:underline; color:#fff; margin-top:4px;" href="' + launchURL + '">Launch in Wires</a></div>');
      $j('.ui-dialog-buttonpane').html('');
      $j('<a class="button ui-state-default ui-corner-all" href="' + launchURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;margin-right:16px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
      $j('<a class="button ui-state-default ui-corner-all" href="' + cloneURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-left:6px;margin-bottom:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');
      
          //$j("#tabs").tabs( 'remove' , 2);
          //$j("#tabs").tabs( 'select' , 0);
          //displayWires(itemId);
    }
    else if('cloneLoginDialog' == callbackTrigger){
      //$j('#dialog').html(displayWires(itemId));
      $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
      $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
      $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
      var launchURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId;
      var cloneURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas';
      //$j('#tabs-4').css( 'background-image', 'none' );
      $j('#tabs-4').css( 'height', '230px' );
      $j('#tabs-4').html('<div style="margin-left:325px; margin-top:53px; color:#000;"><small style="font-size:80%; color:#000;">Logged in as ' + realUserName + '</small><br /><a target="_blank" style="text-decoration:underline; color:#fff; margin-top:4px;" href="' + cloneURL + '">Clone in Wires</a></div>');
        
      //$j("#tabs").tabs( 'remove' , 2 );
          //$j("#tabs").tabs( 'select' , 0);
          //displayClone(itemId);
      $j('.ui-dialog-buttonpane').html('');
      $j('<a class="button ui-state-default ui-corner-all" href="' + launchURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;margin-right:16px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
      $j('<a class="button ui-state-default ui-corner-all" href="' + cloneURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');

      
    }
    else{
      //do nothing or show error message
    }
    
  }, 
  onFailure: function(err) {      
    //console.dir(err);
    //alert('Failure:  ' +  err.message);
    //return;
      $j('#' + callbackTrigger + 'Msg').html('<div style="background-color:red; padding:4px;">Login failed, please try again.</div>');

  }, 
    scope: this 
};
var testPrestoLoginStep2Callback = { 
    onSuccess: function(response) {
      //console.dir(response);
  
  //alert(callbackTrigger); 
  
  
      realUserName = tempUserName;
      apiUser = tempUserName;
      apiPwd = tempApiPwd;
      prestoConfig = {
        prestoUrl: "http://cloud.jackbe.com/presto", 
        username: apiUser, 
        password: apiPwd,
        crossDomainPost: false
      }
      connection = new Presto.Connection(prestoConfig);
      $j('#' + callbackTrigger + 'Msg').html('Logged in as ' + realUserName);
      highlightElement('#' + callbackTrigger + 'Msg');
      if('dialog2' == callbackTrigger){
        $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
        $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
        $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
        $j('#dialog').close();
      }
        if('prestoLoginDialog' == callbackTrigger){
        $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
        $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
        $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
        $j('#dialog').dialog('option', 'height', '175px');
          $j('#dialog').html(getCommentsFormForDisplay(itemId));
      }
      else if('runLoginDialog' == callbackTrigger){
        $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
        $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
        $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
        
        $j('#dialog').html(displayRun(itemId));
      }
      else if('wiresLoginDialog' == callbackTrigger){
        //$j('#dialog').html(displayWires(itemId));
        $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
        $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
        $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
        var launchURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId;
        var cloneURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas';
      //$j('#tabs-4').css( 'background-image', 'none' );
        $j('#tabs-4').css( 'height', '230px' );
        //$j('#tabs-4').html('<div><p style="margin-left:380px;"><br /><small style="font-size:80%;">Logged in as ' + realUserName + '</small></p></div><div style="margin-left:18px;"><a target="_blank" style="text-decoration:underline;" href="' + launchURL + '">Launch in Wires</a></div>');
        $j('#tabs-4').html('<div style="margin-left:325px; margin-top:53px; color:#000;"><small style="font-size:80%; color:#000;">Logged in as ' + realUserName + '</small><br /><a target="_blank" style="text-decoration:underline; color:#fff; margin-top:4px;" href="' + launchURL + '">Launch in Wires</a></div>');
        $j('.ui-dialog-buttonpane').html('');
        $j('<a class="button ui-state-default ui-corner-all" href="' + launchURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;margin-right:16px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
        $j('<a class="button ui-state-default ui-corner-all" href="' + cloneURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-left:6px;margin-bottom:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');
        
            //$j("#tabs").tabs( 'remove' , 2);
            //$j("#tabs").tabs( 'select' , 0);
            //displayWires(itemId);
      }
      else if('cloneLoginDialog' == callbackTrigger){
        //$j('#dialog').html(displayWires(itemId));
        $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
        $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
        $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
        var launchURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId;
        var cloneURL = 'http://cloud.jackbe.com/wires/?mashupId=' + itemId + '&dialog=saveas';
        //$j('#tabs-4').css( 'background-image', 'none' );
        $j('#tabs-4').css( 'height', '230px' );
        $j('#tabs-4').html('<div style="margin-left:325px; margin-top:53px; color:#000;"><small style="font-size:80%; color:#000;">Logged in as ' + realUserName + '</small><br /><a target="_blank" style="text-decoration:underline; color:#fff; margin-top:4px;" href="' + cloneURL + '">Clone in Wires</a></div>');
          
        //$j("#tabs").tabs( 'remove' , 2 );
            //$j("#tabs").tabs( 'select' , 0);
            //displayClone(itemId);
        $j('.ui-dialog-buttonpane').html('');
        $j('<a class="button ui-state-default ui-corner-all" href="' + launchURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;margin-right:16px;float:right;">Launch in Wires</a>').appendTo('.ui-dialog-buttonpane');
        $j('<a class="button ui-state-default ui-corner-all" href="' + cloneURL + '" target="_blank" style="padding:4px;margin-top:6px;margin-bottom:6px;margin-left:6px;float:right;">Clone in Wires</a>').appendTo('.ui-dialog-buttonpane');

        
      }
      else{
        //do nothing or show error message
      }
      
    }, 
    onFailure: function(err) { 
      var el = '#dialog';
      if('cloneLoginDialog' == callbackTrigger || 'wiresLoginDialog' == callbackTrigger){
        el = '#tabs-4';
      }
      $j(el).html(getPrestoLoginForm(callbackTrigger, itemId));
      $j('#' + callbackTrigger + 'Msg').html('<div style="background-color:red; padding:4px;">Login failed, please try again.</div>');
      //alert('Failure:  ' +  err.message); 
      //console.dir(err);
    }, 
      scope: this 
  };
function testPrestoLogin(userName, userPassword, callbackTrigger){
  //testPrestoLoginStep2(userName, userPassword, callbackTrigger);
  
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "getUserDetails", 
      "params": [userName]
  }
  connection.request(requestConfig, testPrestoLoginCallback);
}
function testPrestoLoginStep2(userName, userPassword, callbackTrigger){
  //alert('userName: ' + userName + ' userPassword: ' + userPassword);
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "login", 
      "params": [userName, userPassword]
  }
  connection.request(requestConfig, testPrestoLoginStep2Callback);
}
function getPrestoLoginForm(parentElementId, itemId){
  data = '<div id="' + parentElementId + '"><p id="' + parentElementId + 'Msg">&nbsp;</p>'
  +'<form id="' + parentElementId + 'Form" name="' + parentElementId + 'Form" onsubmit="setPrestoLogin(\'' + parentElementId + '\'); return false;">'
+'<fieldset>'
+'<input id="' + parentElementId + 'ItemId" name="' + parentElementId + 'ItemId" type="hidden" value="' + itemId + '"/>'
+'<label for="' + parentElementId + 'UserName"><span style="padding:3px;color:black;margin-bottom:3px; background-color:white;">Name</span></label>'
+'<input type="text" name="' + parentElementId + 'UserName" id="' + parentElementId + 'UserName" value="' + tempUserName + '" class="text ui-widget-content ui-corner-all" />'
+'<label for="' + parentElementId + 'UserPassword"><span style="padding:3px;color:black; margin-bottom3px; background-color:white;">Password</span></label>'
+'<input type="password" name="' + parentElementId + 'UserPassword" id="' + parentElementId + 'UserPassword" value="" class="text ui-widget-content ui-corner-all" />'
+'<div><input id="' + parentElementId + 'Btn" name="' + parentElementId + 'Btn" type="submit" value="Log in" /></div>'
+'</fieldset></form></div>';
return data;
}
function getPrestoLoginFormWithTerms(parentElementId, itemId){
  data = '<div id="' + parentElementId + '"><p id="' + parentElementId + 'Msg">&nbsp;</p>'
  +'<form id="' + parentElementId + 'Form" name="' + parentElementId + 'Form" onsubmit="setPrestoTerm(\'' + parentElementId + '\'); return false;">'
+'<fieldset>'
+'<div style="padding:3px;color:black; margin-bottom0px; background-color:white;"><label for="' + parentElementId + 'Terms"><span style="padding:3px;color:black; margin-bottom3px; background-color:white;">Please agree to terms before using Presto.</span></label></div>'
+'<div style="padding:3px;color:black; margin-bottom0px; background-color:white;"><br /><input type="checkbox" name="' + parentElementId + 'Terms" id="' + parentElementId + 'Terms" value="agree" style="display:inline;" /><span style="padding:3px;color:black; margin-bottom0px; background-color:white;"> I agree to the <a target="_blank" href="http://cloud.jackbe.com/terms.html" style="color:#000;text-decoration:underline">Terms and Conditions</a></span></div>'
+'<div><br /><input id="' + parentElementId + 'Btn" name="' + parentElementId + 'Btn" type="submit" value="Accept" /></div>'
+'</fieldset></form></div>';
return data;
}
function setPrestoLogin(parentElementId){
  var eId = '#' + parentElementId;
  var userName = $j(eId + 'UserName').val();
  itemId = $j(eId + 'ItemId').val();
  tempUserName = userName;
  var userPassword = $j(eId + 'UserPassword').val();
  tempApiPwd = userPassword;
  callbackTrigger = parentElementId;
  testPrestoLogin(userName, userPassword, callbackTrigger);
  return false;
}
function setPrestoTerm(parentElementId){
  var eId = '#' + parentElementId;
  callbackTrigger = parentElementId;
  var agree = $j(eId + 'Terms').attr('checked')?1:0;
  if(!agree){
    $j(eId + 'Msg').html('<div style="background-color:red; color:#fff; padding:4px;">Please agree to terms.</div>');
    return;
  }
  enableUser(tempUserName);
  return false;
}

var enableUserCallback = { 
    onSuccess: function(response) { 
      //console.dir(response);
      $j('#' + callbackTrigger + 'Msg').html('<div style="background-color:green; color:#fff; padding:4px;">Account enabled.</div>');
      addXigniteUser(tempUserName);
    }, 
    onFailure: function(err) { 
      //console.dir(err);
      $j('#' + callbackTrigger + 'Msg').html('<div style="background-color:red; color:#fff; padding:4px;">Account disabled, please try again.</div>');
    }, 
    scope: this 
};

function enableUser(tempUserName){
  
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "enableAccount", 
      "params": [tempUserName]
  }
  connection.request(requestConfig, enableUserCallback);
}

var postXigniteUserCallback = { 
    onSuccess: function(response) { 
      //console.dir(response);
      if('presto-cloud-block-content2' == callbackTrigger){
        setNewPassword();
      }
      else if('dialog' == callbackTrigger){
        //loginUserStep2(tempUserName, tempApiPwd, callbackTrigger);
        setNewPassword();
      }
      else{
        //testPrestoLoginStep2(tempUserName, tempApiPwd, callbackTrigger);
        setNewPassword();
      }
    }, 
    onFailure: function(err) { 
      //console.dir(err);
      if('presto-cloud-block-content2' == callbackTrigger){
        setNewPassword();
      }
      else if('dialog' == callbackTrigger){
        loginUserStep2(tempUserName, tempApiPwd, callbackTrigger);
      }
      else{
        //testPrestoLoginStep2(tempUserName, tempApiPwd, callbackTrigger);
        setNewPassword();
      }
    }, 
    scope: this 
};

function postXigniteUser(email, name, key){
  var requestConfig = {
       "version": "1.1", 
      "sid": "XIGNITEAddUserMashup", 
      "svcVersion": "0.1", 
      "oid": "runMashup", 
      "params": [email, name, key]
  }
  connection.request(requestConfig, postXigniteUserCallback);
}

var addXigniteUserCallback = { 
    onSuccess: function(response) { 
      //console.dir(response);
      var email = response.response.email;
      var key = email;
      var name = tempUserName;
      postXigniteUser(email, name, key);
    }, 
    onFailure: function(err) { 
      //console.dir(err);
    }, 
    scope: this 
};
function addXigniteUser(userName){
  
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "getUserDetails", 
      "params": [userName]
  }
  connection.request(requestConfig, addXigniteUserCallback);
}


function displayCommentsDialog(itemId){
  var myOptions = {};
  var mySpeed = 1000;
  var myEffect = 'blind';
  var commentsForm = getCommentsFormForDisplay(itemId);
  var prestoLoginForm = getPrestoLoginForm('prestoLoginDialog', itemId);
  $j('#dialog').dialog( 'destroy' );
  var dialogContent = (origApiUser == apiUser)?prestoLoginForm:commentsForm;
  var dialogHeight = (origApiUser == apiUser)?'250':'175';
  $j('#dialog').html(dialogContent);
  $j.fx.speeds._default = mySpeed;
  $j("#dialog").dialog({
    title: 'Comments for ' + itemId,
    bgiframe: true,
    autoOpen: false,
    height: dialogHeight,
    width: 400,
    modal: true,
      close: function() {
    /*
    if($j('#newComments').html() != '') {
        $j('#comm' + itemId).html($j('#newComments').html());

        $j('#btnComm'+itemId).attr('title', 'show comments');
        $j('#btnComm'+itemId).text('show more comments');
    }
    */
    getComments(itemId, 0);
    $j('#btnComm'+itemId).attr('title', 'hide comments');
    $j('#btnComm'+itemId).text('hide comments');
    
        itemId = '';
      }
  });
  $j('#dialog').dialog('open');
}
var listMashablesCallback = { 
      onSuccess: function(response) { 
       //alert('in listMashablesCallback');
      //console.dir(response);
    if(0 != mashupCount){
    paginationToken = response.header.pagination.paginateToken;
    mashupCount = response.header.pagination.paginateCount * 1;
    mashupStart = response.header.pagination.paginateStart * 1;
    mashupTotal = response.header.pagination.totalRecords * 1;
    mashupStart = (mashupStart == -1)?11:(mashupCount + mashupStart);
    mashupCount = (mashupStart + mashupCount > mashupTotal)?(mashupTotal - mashupStart):mashupCount;
    }
    listMashables(response.response.ServiceSummary_Array.ServiceSummary);
      }, 
      onFailure: function(err) { 
        //alert('Failure:  ' +  err.message); 
    //console.dir(err);
      }, 
      scope: this 
};

function getMashablesList(start, count, paginationToken){
  //alert('in getMashablesList');
  $j('#listMashables').html('<img alt="Loading Content" src="http://www.jackbe.com/enterprise-mashup/wall/images/wait.gif" /> &nbsp; Loading content from the cloud');
  var requestConfig = {
           /* sid: "FilteredServices", */
		   sid: "ServicesFilteredSorted",
       oid: "runMashup",
       //sid: "RDSService", 
       //oid: "getListOfServicesForType",
       header:{"paginateRecord":"/ServiceSummary_Array/ServiceSummary",
         "paginateStart":start,
         "paginateCount":count,
         "returnServiceHeaders":"true"
      }, 
       params: {"values":""}
  }
  connection.request(requestConfig,listMashablesCallback);
}

function updateMashablesList(start, count, paginationToken){
  //alert('in updateMashablesList');
  mashupCount = 0;
  var requestConfig = {
           /* sid: "FilteredServices", */
		   sid: "ServicesFilteredSorted",
           oid: "runMashup",
           params: {"values":""}
  }
  connection.request(requestConfig,listMashablesCallback);
}
var getTagCloudCallback = { 
      onSuccess: function(response) { 
    //console.dir(response.response.tagCloudItems);
    setTagCloud(response.response.tagCloudItems);
      }, 
      onFailure: function(err) { 
        //alert('Failure:  ' +  err.message); 
    //console.dir(err);
      }, 
      scope: this 
};

function getTagCloud(){
  $j("#block-tag_cloud-0-content").html(displayLoading());
  var requestConfig = {
         sid: "RDSService", 
           oid: "getTagCloud", 
           params: {"values":""}
  }
  connection.request(requestConfig, getTagCloudCallback);
}

function setTagCloud(ds) {
   var i = 5;
   var outputstr = '<ul>';
   ds.each(function(item) {
     outputstr = outputstr + '<li class="tag' + i + '"><a href="#" rel="tag" onclick="mashupTagSearch(\'' + item.tagName +  '\'); return false;">' + item.tagName +  '</a></li>';
    i--;
    if(i<1){ i = 5; }
      });
   outputstr += '</ul>';
  $j("#block-tag_cloud-0-content").html(outputstr);
  setTagCloudFunctions();
}

function setTagCloudFunctions(){
   //uses http://plugins.jquery.com/project/TinySort
  $j("#block-tag_cloud-0-content ul li").tsort({order:"asc"});
  var cloudNav = '<div class="cloud_nav" style="clear:both;"><a href="javascript:void(0)" class="btn popularity" title="sort by popularity">popularity</a> | <a href="javascript:void(0)" class="btn alpha" title="sort alphabetically">alpha</a> | <a href="javascript:void(0)" class="btn change" title="change appearance">change</a></div>';
  $j('#block-tag_cloud-0-content').append(cloudNav);
  
    // handle change event
    var switcher = $j('.cloud_nav .change').toggle(
      function(){
        $j("#block-tag_cloud-0-content ul").hide().addClass("alt").fadeIn("fast");
      },
      function(){
        $j("#block-tag_cloud-0-content ul").hide().removeClass("alt").fadeIn("fast");
      }
    );
    
    // handle alpha event
    var sortabc = $j('.cloud_nav .alpha').toggle(
      function(){
        $j("#block-tag_cloud-0-content ul li").tsort({order:"desc"});
      },  
      function(){
        $j("#block-tag_cloud-0-content ul li").tsort({order:"asc"});
      }   
      );
    
    // handle popularity event
    var sortstrength = $j('.cloud_nav .popularity').toggle(
      function(){
        $j("#block-tag_cloud-0-content ul li").tsort({order:"desc",attr:"class"});
      },  
      function(){
        $j("#block-tag_cloud-0-content ul li").tsort({order:"asc",attr:"class"});
      }   
      );
}     
      
function getItemTags(objTags){
  if(objTags.string){
    aryTags = (typeof objTags.string == 'string')? new Array(objTags.string.split(',')):objTags.string;
  }
  else if(objTags.length > 0){
    aryTags = objTags;
  }
  else{
    aryTags = new Array();
  }
  var tagData = '';
  var aryLen = aryTags.length;
   if(aryLen > 0){
     tagData = tagData + ' &nbsp; <img alt="tags" title="tags" src="http://www.jackbe.com/enterprise-mashup/wall/images/bg-tags.png" style="width:16; height:16;" /> &nbsp;';
   }
   var sep = '';
   for ( var i=0, len=aryLen; i<len; ++i ){
     tagData = tagData + sep + '<a href="#" rel="tag" title="' + aryTags[i] + '"  onclick="mashupTagSearch(\'' + aryTags[i] +  '\'); return false;">' + aryTags[i] + '</a>';
     sep = ', ';
   }
   return tagData;
}
function getEmml(itemId){
  
  emmlClick = itemId;

  var requestConfig = {
           sid: "JEMSDesigner", 
           oid: "getClientScript",
           header:{"resultFormat":"xml"},
          params: [itemId]
  }
  connection.request(requestConfig,EmmlCallback);
}
function setIsWires(v){
  isWires = v;
  //alert(isWires);
}
function getIsWires(){
  return isWires;
}
var EmmlCallback = { 
  onSuccess: function(response) { 
  //console.dir(response);
  //console.dir(EmmlCallback);
  v = response.response.indexOf("presto-meta wires");
  setIsWires(v);
  //alert(v);
  //remove xml header 
  response.response = response.response.replace('<?xml version="1.0" encoding="UTF-8"?>','');
  //remove presto meta
  response.response = response.response.replace(/\<presto-meta .*<\/presto-meta>/g, '');
  // Turn < and > into &LT; and &GT; (case matters)
  response.response = response.response.replace(/\<([^!])/g, '&LT;$1');
  response.response = response.response.replace(/([^-])\>/g, '$1&GT;');
  // Handle attribute="value" - make the attribute red and value blue
  response.response = response.response.replace(/([a-zA-Z0-9:]+)\=\"([^"]*)"/g, '<span style="color:red">$1</span><span style="color:blue">="$2"</span>');
  // Color tag openers and closers brown
  response.response = response.response.replace(/\&LT\;([a-zA-Z0-9:]+)/g, '&LT;<span style="color:brown">$1</span>');
  response.response = response.response.replace(/\&LT\;\/([a-zA-Z0-9:]+)/g, '&LT;/<span style="color:brown">$1</span>');
  // Comments are green
  response.response = response.response.replace(/\<\!--/g, '<span style="color:green">&lt;!--');
  response.response = response.response.replace(/--\>/g, '--&gt;</span>');
  // The < and > characters are blue
  response.response = response.response.replace(/\&LT\;/g, '<span style="color:blue">&lt;</span>');
  response.response = response.response.replace(/\/\&GT\;/g, '<span style="color:blue">/&gt;</span>');
  response.response = response.response.replace(/\&GT\;/g, '<span style="color:blue">&gt;</span>');
  // Turn hard tabs into four spaces
  response.response = response.response.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
  response.response = response.response.replace(/,/g, ', ');
  
  response.response = response.response.replace(/\s\s+/g, ' ');
  response.response = response.response.replace(/\&lt\;/g, '<br />&lt;');

  response.response = response.response.replace(/\<\/span\>(\s+)?\&gt\;(\s+)?\<span/g, '</span><span');

  //console.dir(response);
  
  //<a href="javascript:void(0);" onclick="selectEmml(); return false;">Select All</a>
  $j("#tabs-2").html('<div id="emmlTextarea" style="display:block; width:610px; height:250px; overflow:scroll; background-color:#ccc; white-space: nowrap;">' + response.response + '</div>');
  }, 
  onFailure: function(err) { 
  //alert('Failure:  ' +  err.message); 
  //console.dir(err);
    isWires = -1;
  var msg = 'EMML not available, please try later.';
  $j("#tabs-2").html(msg);
  }, 
  scope: this 
};
function selectEmml(){
 $j("#emmlTextarea").focus();
 $j("#emmlTextarea").select();
}
function tabbedDialog(){
  data = '<div id="tabs"><br />'
  +'<ul>'
  +'  <li><a href="#tabs-1">Details</a></li>'
  +'  <li><a href="#tabs-2">EMML</a></li>'
  +'  </ul>'
  +'  <div id="tabs-1"></div>'
  +'  <div id="tabs-2"></div>'
  +'  </div>';
  return data;
}

function displayComments(ds){
   var aryLen = ds.length;
   var temp = '';
   var commentCount = 0;
   var limit = commLimit *1;
   var thisItemId = itemId;
   var parentE = '#comm' + thisItemId;
   $j(parentE).html('');
   ds.each(function(item) {
     if(item.comment != null  || undefined != item.comment ){
       temp = temp + '<div style="padding-left:4px; border-top:1px dotted #666666;"><a href="javascript:void(0);"><img src="http://www.jackbe.com/enterprise-mashup/wall/images/profile_default.jpg" style="display:block; width:32px; height:32px; text-align:left; padding:4px; float:left;"/></a><span><strong>' + item.userName + '</strong> </span> <span>' + item.comment + '</span><br /><span><small style="color:#666; font-size:75%;">' + item.created + '</small></span><div style="clear:both;"></div></div>';
       $j(parentE).append(temp);
       commentCount ++;
       temp = '';
     }
     if(commentCount >= limit && limit != 0)throw $break;
   });
   if(commentCount == 0){
     $j(parentE).append('<div style="padding-left:4px; border-top:1px dotted #666666;">No comments available</div>');
   }
    //$j(parentE).effect("highlight", {}, 2000);
}
var commentsCallback = { 
        onSuccess: function(response) {
        //console.dir(response);
        displayComments(response.response.UserFeedbackTO_Array.UserFeedbackTO);
        }, 
        onFailure: function(err) { 
          //alert('Failure:  ' +  err.message); 
      //console.dir(err);
          $j('#comm' + itemId).html('<p>Comments not available at this time, please try later.</p>');
        }, 
        scope: this 
};
function getComments(thisItemId, limit){
  commClick = thisItemId;
  itemId = thisItemId;
  commLimit = limit;
  //alert(commClick);
  var requestConfig = {
           sid: "MashupFeedbackSorted", 
           oid: "Invoke",
           params: [itemId] 
  }
  connection.request(requestConfig,commentsCallback);
}
function displayGetCommentsForm(ds, itemId, commLimit){
   var aryLen = ds.length;
   var temp = '';
   var commentCount = 0;
   var commLimit = 0;
   $j('#dialog').html('');
   $j('#dialog').append('<div id="commentHelp">Your comments are greatly appreciated.</div><div><form class="commentForm"><input id="serviceId" name="serviceId" type="hidden" value="' + itemId + '"/><div><input id="comment" name="comment" type="text" style="width:95%; height:3em;"></div><div><input id="submitComment" name="submitComment" type="button" value="update" onclick="getItemFeedbackData()" style="float:right; margin-right:20px;"></div></form></div><div style="clear:both;"></div><br /><div id="newComments"></div>');
   ds.each(function(item) {
     if(item.comment != null){
       temp = temp + '<div style="padding-left:4px; border-top:1px dotted #666666;"><a href="javascript:void(0);"><img src="http://www.jackbe.com/enterprise-mashup/wall/images/profile_default.jpg" style="display:block; width:32px; height:32px; text-align:left; padding:4px; float:left;"/></a><span><strong>' + item.userName + '</strong> </span> <span>' + item.comment + '</span><br /><span><small style="color:#666; font-size:75%;">' + item.created + '</small></span><div style="clear:both;"></div></div>';
       $j('#dialog').append(temp);
       commentCount ++;
       temp = '';
     }
     if(commentCount >= commLimit && commLimit != 0)throw $break;
   });
}
var getCommentsFormCallback = { 
        onSuccess: function(response) {
        //console.dir(response);
        displayGetCommentsForm(response.response, commClick, commLimit);
        }, 
        onFailure: function(err) { 
          //alert('Failure:  ' +  err.message); 
      //console.dir(err);
        }, 
        scope: this 
};
function getCommentsForm(itemId, commLimit){
  commClick = itemId;
  commLimit = commLimit;
  //alert(commClick);
  var requestConfig = {
           sid: "RDSService", 
           oid: "findFeedbacksForEntity",
           params: [itemId, "Service"] 
  }
  connection.request(requestConfig,getCommentsFormCallback);
}

function displayServiceDialog(itemId){
  if(origApiUser == apiUser)
  {
    displayUserLogin();
    return false;
  }
  var myOptions = {};
  var mySpeed = 500;
  var myEffect = 'blind';

  $j('#dialog').dialog( 'destroy' );
  $j('#navComm'+itemId).hide();
  var content = $j('#node-'+itemId).html();
  $j('#dialog').html(content);
  $j.fx.speeds._default = mySpeed;
  $j("#dialog").dialog({
    title: 'Summary',
    show: 'slide',
    hide: 'highlight',
    bgiframe: true,
    autoOpen: false,
    height: 300,
    width: 500,
    modal: true,
    buttons: {
      OPTIONS: function() {
        $j('#dialog').html('');
            $j("#dialog").hide(myEffect, myOptions, mySpeed, function(){
            $j('#dialog').html(content);
        $j('#dialog').append(getItemOptions(itemId));
            }); 
         $j("#dialog").show(myEffect, myOptions, mySpeed);
     
      },
    EMML: function() {
      $j('#dialog').html('');
        $j("#dialog").hide(myEffect, myOptions, mySpeed, function(){
      
                getEmml(itemId);
        }); 
        //$("#effect").hide(selectedEffect,options,500,callback);
        
        $j("#dialog").show(myEffect, myOptions, mySpeed);
        },
   COMMENTS: function() {
   $j('#dialog').html('');
        $j("#dialog").hide(myEffect, myOptions, mySpeed, function(){
        
           getCommentsForm(itemId, 0);
        }); 
      $j("#dialog").show(myEffect, myOptions, mySpeed);
      },
      MAIN: function() {
        $j('#dialog').html('');
            $j("#dialog").hide(myEffect, myOptions, mySpeed, function(){
            $j('#dialog').html(content);
            }); 
         $j("#dialog").show(myEffect, myOptions, mySpeed);
      }
      },
      close: function() {
        //alert('apiUser: ' + apiUser + ' apiPwd: ' + apiPwd);
        $j('#node-'+itemId).html(content);
        $j('#dialog').dialog( 'destroy' );
      $j('#navComm'+itemId).show();
      $j('#btnComm'+itemId).attr('title', 'hide comments');
      $j('#btnComm'+itemId).text('hide comments');
       getComments(itemId, 0);
      }
  });
  $j('#dialog').dialog('open');
  /* dialog seems a bit sticky. Here are some thoughts about fixing that
  alert($j('#dialog').dialog('option', 'width'));
  var newWidth = $j('#dialog').dialog('option', 'width') * 1 + 5;
  $j('#dialog').dialog('option', 'width', newWidth);
  var position = $j('#dialog').position();
    x= $j('#dialog').position().left;
    y= $j('#dialog').position().top;
  x = Math.floor(x) * 1 + 10;
  y = Math.floor(y) * 1 + 10;
  $('#dialog').dialog({ position: [x,y] });
  */
  $j('#node-'+itemId).html('');
}
function displayUserLogin(){
  $j('#dialog').dialog( 'destroy' );
  $j('#dialog').html('<p id="validateTips">All form fields are required.</p><form onsubmit="loginUser(\'' + $j("#userName").val() + '\', \'' + $j("#userName").val() + '\'); return false;">'
  +'<fieldset>'
  +'<label for="userName">Name</label>'
  +'<input type="text" name="userName" id="userName" class="text ui-widget-content ui-corner-all" />'
  +'<label for="userPassword">Password</label>'
  +'<input type="password" name="userPassword" id="userPassword" value="" class="text ui-widget-content ui-corner-all" />'
  +'</fieldset></form>');
  $j("#dialog").dialog({
    title: 'Presto Login',
    bgiframe: true,
    autoOpen: false,
    height: 300,
    width: 250,
    modal: true,
    buttons: {
      login: function() {
          //validate & do post stuff here
          //alert('logging in');
      var userName = $j("#userName").val();
      tempUserName = userName;
      var userPassword = $j("#userPassword").val();
      tempApiPwd = userPassword;
      loginUser(userName, userPassword);
      
          },
        cancel: function() {
        //remove display and vars
      $j(this).dialog('close');
          $j('#dialog').dialog( 'destroy' );
        //alert('cancelled');
          }
      },
      close: function() {
      $j(this).dialog('close');
        $j('#dialog').dialog( 'destroy' );
      }
  });
  $j('#dialog').dialog('open');
}

var getCurrentUserCallback = { 
  onSuccess: function(response) { 
    //console.dir(response);
  }, 
  onFailure: function(err) { 
    //alert('Failure:  ' +  err.message); 
    //console.dir(err);
  }, 
  scope: this 
};
function getCurrentUser(){
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "getCurrentUser", 
      "params": []
  }
  connection.request(requestConfig, getCurrentUserCallback);
}
var loginUserCallback = { 
    onSuccess: function(response) {
  console.dir(response);
  if(true == response.response.enabled){
    loginUserStep2(tempUserName, tempApiPwd, callbackTrigger);
    return;
  }
  else{
      $j('#' + callbackTrigger).html(getPrestoLoginFormWithTerms(callbackTrigger, itemId));
      //callbackTrigger = 'presto-cloud-block-content2';
      return;
  }
  }, 
  onFailure: function(err) { 
      $j('#validateTips').html('<div style="background-color:red; padding:4px;">Login Failed</div>');
    //alert('Failure:  ' +  err.message); 
    console.dir(err);
  }, 
    scope: this 
};
var loginUserStep2Callback = { 
    onSuccess: function(response) {
      //console.dir(response);
      realUserName = tempUserName;
      apiUser = tempUserName;
      apiPwd = tempApiPwd;

      $j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
      $j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
      prestoConfig = {
        prestoUrl: "http://cloud.jackbe.com/presto", 
        username: apiUser, 
        password: apiPwd,
        crossDomainPost: false
      }
      connection = new Presto.Connection(prestoConfig);
      $j('#validateTips').html('<div style="background-color:green; padding:4px;">Logged in as ' + realUserName + '</div>');
      //$j("#dialog").dialog('option', {buttons:{Close: function(){ $j(this).dialog('close'); $j('#dialog').dialog( 'destroy' ); }}});
      $j('#dialog').dialog( 'destroy' );
      $j('#presto-cloud-block-form').html('<div class="btnContent"><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
      //getCurrentUser();
    }, 
    onFailure: function(err) { 
        $j('#validateTips').html('<div style="background-color:red; padding:4px;">Login failed, please try again.</div>');
      //alert('Failure:  ' +  err.message); 
      //console.dir(err);
    }, 
      scope: this 
  };
function loginUser(userName, userPassword){
  callbackTrigger = 'dialog';
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "getUserDetails", 
      "params": [userName]
  }
  connection.request(requestConfig, loginUserCallback);
}
function loginUserStep2(userName, userPassword, callbackTrigger){
  //alert('userName: ' + userName + ' userPassword: ' + userPassword);
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "login", 
      "params": [userName, userPassword]
  }
  connection.request(requestConfig, loginUserStep2Callback);
}
var setItemFeedbackCallback = { 
    onSuccess: function(response) {
  //console.dir(response);
  //$j("#newComments").prepend('<div style="padding-left:4px; border-top:1px dotted #666666;"><a href="javascript:void(0);"><img src="http://www.jackbe.com/enterprise-mashup/wall/images/profile_default.jpg" style="display:block; width:32px; height:32px; text-align:left; padding:4px; float:left;"/></a><span><strong>' + apiUser + '</strong> </span> <span>' + $j("#comment").val() + '</span><br /><span><small style="color:#666; font-size:75%;">' + new Date().toUTCString() + '</small></span><div style="clear:both;"></div></div>');
  $j("#comment").val("");
  //$j('#commentHelp').html('<div style="padding:6px;">Thank you for your comment.</div>');
  //highlightElement('#commentHelp','',3000);
  //highlightElement('#newComments:first');

  $j('#dialog').dialog('close');
  

}, 
onFailure: function(err) { ;
  //alert('Failure:  ' +  err.message); 
  //console.dir(err);
$j('#commentHelp').html('<div style="padding:6px;">Sorry, your comment could not be added at this time.  Please try later.</div>');
highlightElement('#commentHelp','',3000);
  }, 
    scope: this 
};
function setItemFeedback(serviceId, comment){
  var requestConfig = {
    "version": "1.1", 
    "sid": "RDSService", 
    "svcVersion": "0.1", 
    "oid": "addFeedbackForEntity", 
    "params": [
    serviceId, 
    "Service", 
    comment, 
    0
  ]
  }
  connection.request(requestConfig, setItemFeedbackCallback);
}
function getItemFeedbackData(){
  var serviceId = $j("#serviceId").val();
  var comment = $j("#comment").val();
  //alert('serviceId: ' + serviceId + ' comment: ' + comment);
  setItemFeedback(serviceId, comment);
  return false;   
}

var getServicesByKeywordCallback = { 
  onSuccess: function(response) {
    //console.dir(response);
    var total = response.response.length;
    //alert(total);
    if(total < 1){
      $j('#searchMashupsMsg').html('No results found. Please try another term.');
      return false;
    }
    else{
      $j('#searchMashupsMsg').html('');
      mashupCount = 0;
      mashupTotal = total;
      listMashables(response.response);
    }
  }, 
  onFailure: function(err) {
     $j('#searchMashupsMsg').html('Error on results. Please try again.');
    //alert('Failure:  ' +  err.message); 
    //console.dir(err);
  }, 
    scope: this 
};
function getServicesByKeyword(searchTerm){
  //alert(searchTerm);
  var requestConfig = {
  "version": "1.1", 
  "sid": "RDSService", 
  "svcVersion": "0.1", 
  "oid": "getListOfServicesForKeyword", 
  "params": [searchTerm]
  }
  connection.request(requestConfig, getServicesByKeywordCallback);
}
function mashupSearch(){
  var searchTerm = $j("#searchTerm").val();
  var msgBox = '#searchMashupsMsg';
  var boxMsg = 'Searching';
  if('' == searchTerm){
    $j(msgBox).html('Please enter search term.');
    return false;
  }
  $j(msgBox).html(boxMsg);
  getServicesByKeyword(searchTerm);
  return false;
}

var getServicesByTagCallback = { 
  onSuccess: function(response) {
    //console.dir(response);
    mashupCount = 0;
    mashupTotal = response.response.length;
    listMashables(response.response);
  }, 
  onFailure: function(err) { ;
    //alert('Failure:  ' +  err.message); 
    //console.dir(err);
  }, 
    scope: this 
};
function getServicesByTag(tag){
  //alert(tag);
  var requestConfig = {
  "version": "1.1", 
  "sid": "RDSService", 
  "svcVersion": "0.1", 
  "oid": "getListOfServicesForTag", 
  "params": [tag]
  }
  connection.request(requestConfig, getServicesByTagCallback);
}
function mashupTagSearch(tag){
  getServicesByTag(tag);
  return false;
}
function getItemOptions(itemId){
  var temp = '<div id="itemOptions><br />';
  temp = temp + '<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"><div id="cloneMsg"></div><button class="ui-state-default ui-corner-all" style="padding:4px;" type="button" onclick="setCloneItem(\'' + itemId + '\');">CLONE</button> ';
  temp = temp + '<a class="ui-state-default ui-corner-all" style="padding:4px;" target="_newtab" href="http://cloud.jackbe.com/wires/?mashupId=' + itemId + '">VIEW IN WIRES</a> ';
  temp = temp + '<a class="ui-state-default ui-corner-all" style="padding:4px;" target="_newtab" href="http://cloud.jackbe.com/presto">PRESTO CLOUD</a>';
  temp = temp + '</div></div>';
  return temp;
}

var setCloneCallback = { 
  onSuccess: function(response) {
    //console.dir(response);
    $j("#cloneMsg").html('Clone Successful! <a target="_newtab" href="http://cloud.jackbe.com/serviceexplorer/jsp/RunServiceExplorer.jsp?serviceId=' + response.response + '">View it in Presto</a>');
  }, 
  onFailure: function(err) { ;
    //alert('Failure:  ' +  err.message); 
    //<a target="_blank" href="http://cloud.jackbe.com/serviceexplorer/jsp/RunServiceExplorer.jsp?serviceId=' + apiUser + '-' + this.itemId + '">View clone in Presto</a>
    $j("#cloneMsg").html('You cloned this already  ' );
    //console.dir(err);
    //console.dir(this);
  }, 
    scope: this 
};
function setClone(itemId, newItemId){
  //alert(tag);
  var requestConfig = {
  "version": "1.1", 
  "sid": "RDSService", 
  "svcVersion": "0.1", 
  "oid": "cloneService", 
  "params": [itemId, newItemId]
  }
  connection.request(requestConfig, setCloneCallback);
}
function setCloneItem(itemId){
  this.itemId = itemId;
  var newItemId = apiUser + '-' + itemId;
  setClone(itemId, newItemId);
}

function prestoLogin(){
  var userName = $j("#username").val();
  tempUserName = userName;
  var userPassword = $j("#password").val();
  tempApiPwd = userPassword;
  callbackTrigger = 'presto-cloud-block-content';
  loginPrestoUser(userName, userPassword);
}

var loginPrestoUserCallback = { 
    onSuccess: function(response) {
    console.dir(response);
    if(true == response.response.enabled){
      loginPrestoUserStep2(tempUserName, tempApiPwd, callbackTrigger);
      return;
    }
    else{
        $j('#' + callbackTrigger).html(getPrestoLoginFormWithTerms(callbackTrigger + '2', itemId));
        callbackTrigger = 'presto-cloud-block-content2';
        return;
    }
    }, 
    onFailure: function(err) { 
        $j('#prestoCloudFormMsg').html('<div style="background-color:red; padding:4px;">Login Failed</div>');
      //alert('Failure:  ' +  err.message); 
      console.dir(err);
    }, 
      scope: this 
  };


var loginPrestoUserStep2Callback = { 
    
  onSuccess: function(response) {
  //alert('userName: ' + tempUserName + ' userPassword: ' + tempApiPwd);
    console.dir(response);
    realUserName = tempUserName;
    apiUser = tempUserName;
    apiPwd = tempApiPwd;
    prestoConfig = {
      prestoUrl: "http://cloud.jackbe.com/presto", 
      username: apiUser, 
      password: apiPwd,
      crossDomainPost: false
    }
    connection = new Presto.Connection(prestoConfig);
    //$j('#prestoCloudFormMsg').html('Logged in as ' + realUserName);
    //$j('#prestoCloudFormMsg').effect("highlight", {}, 2000);
    var el = callbackTrigger;
    el = (el == 'dialog2')?'prestoCloudFormMsg':el;
    $j('#' + el).html('<div class="btnContent">Logged in as ' + realUserName + '<br /><a target="_newtab" href="http://cloud.jackbe.com/presto">Go to Presto Cloud</a></div>');
    //getCurrentUser();
  }, 
  onFailure: function(err) { 
    //alert('error: userName: ' + tempUserName + ' userPassword: ' + tempApiPwd);
      $j('#prestoCloudFormMsg').html('<div style="background-color:red; padding:4px;">Login Failed</div>');
    //alert('Failure:  ' +  err.message); 
    console.dir(err);
  }, 
    scope: this 
};

function loginPrestoUser(userName, userPassword){
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "getUserDetails", 
      "params": [userName]
  }
  connection.request(requestConfig, loginPrestoUserCallback);
}

function loginPrestoUserStep2(userName, userPassword, callbackTrigger){
  //alert('userName: ' + userName + ' userPassword: ' + userPassword);
  $j('#' + callbackTrigger).html('<div id="prestoCloudFormMsg"></div>'
  +'<form id="prestoCloudForm" onsubmit="prestoLogin(); return false;" name="prestoCloudForm">'
  +'User Name:'
  +'<br/><input id="username" type="text" name="username" value="' + tempUserName + '"/>'
  +'Password:<br/><input id="password" type="password" name="password"/>'
  +'<div><input id="prestoCloudBtn" type="submit" value="Log in" name="prestoCloudBtn"/>'
  +'</div></form>');
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "login", 
      "params": [userName, userPassword]
  }
  connection.request(requestConfig, loginPrestoUserStep2Callback);
}

var getServiceDetailsCallback = { 
  onSuccess: function(response) {
    //console.dir(response);
    item = response.response[0];
      //$j("#tabs-1").html('<h4>' + data.name + '</h4><div>' + data.description + '</div>');

     outputstr = '';
     
     var strTags = '';
     //alert(item.tags);
     strTags = (item.tags)?getItemTags(item.tags):strTags;
     var avgRating = item.feedbackStatistics.avarageRating * 1;
     var description = item.description;
     if (typeof description == 'object')description = '';
     outputstr = outputstr + '<div id="dnode-' + item.name +  '" class="node" style="line-height:normal;border:none;">';
     outputstr = outputstr + '<div id="dmsg' + item.name +  '" ></div>';
     outputstr = outputstr + '<p style=""><img src="http://www.jackbe.com/enterprise-mashup/wall/images/profile_mdc_90x52.jpg" align="left" style="margin:6px; margin-top:4px; margin-left:0px;" />';
     outputstr = outputstr + '<span id="dfav' + item.name +  '" style=""></span> ';
     outputstr = outputstr + ' <span style="font-weight:bold;">' + item.name + '</span>';
     outputstr = outputstr + ' &nbsp;<span id="drating' + item.name +  '"  style="vertical-align:text-top;"></span>';
     outputstr = outputstr + '<br />Created <span title="' + item.lastChangedDate +  '"><small style="font-size:80%;">' + item.lastChangedDate +  '</small></span> by ' + item.creator +  ' ';
     outputstr = outputstr + strTags;
     outputstr = outputstr + '<span style="display:block; margin-top:4px;">' + description + '</span>';
     outputstr = outputstr + '</p>';
     outputstr = outputstr + '<div class="content clear-block" style="border:none;"></div>';
     //outputstr = outputstr + '<div id="navComm' + item.name +  '">';
    // outputstr = outputstr + '<a href="javascript:void(0);" title="show comments" id="btnComm' + item.name +  '" onclick="toggleComments(\'' + item.name +  '\')">show comments</a>';
     //outputstr = outputstr + ' | <a href="javascript:void(0);" title="share comments" id="btnShare' + item.name +  '" onclick="displayCommentsDialog(\'' + item.name +  '\')">add comments</a>';
    // outputstr = outputstr + ' | <a href="javascript:void(0);" title="view Mashup details" id="btnShare' + item.name +  '" onclick="displayMashupDialog(\'' + item.name +  '\')">Mashup Details &amp; Actions</a>';
     //outputstr = outputstr + '</div>';
     //outputstr = outputstr + '<div id="comm' + item.name +  '" style="margin-left:16px;"></div>';
     outputstr = outputstr + '</div>';

     $j("#tabs-1").html(outputstr);
     
     $j('#drating' + item.name).rater(item.name, {style: 'inline', curvalue:avgRating});
     $j('#dfav' + item.name).rater(item.name, {maxvalue:1, style: 'inline'}); 
  }, 
  onFailure: function(err) { 
      //alert('Failure:  ' +  err.message); 
    //console.dir(err);
    $j("#tabs-1").html('Details not available.');
  }, 
    scope: this 
};
function getServiceDetails(itemId){
  var requestConfig = {
              "version": "1.1", 
            "sid": "RDSService", 
            "svcVersion": "0.1", 
            "oid": "getListOfServicesForName", 
            "params": [itemId]
  }
  connection.request(requestConfig, getServiceDetailsCallback);
}
//This code was written by Tyler Akins and has been placed in the
//public domain.  It would be nice if you left this header intact.
//Base64 code from Tyler Akins -- http://rumkin.com
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) {
  var StringMaker = function () {
    this.str = "";
    this.length = 0;
    this.append = function (s) {
      this.str += s;
      this.length += s.length;
    }
    this.prepend = function (s) {
      this.str = s + this.str;
      this.length += s.length;
    }
    this.toString = function () {
      return this.str;
    }
  }
} else {
  var StringMaker = function () {
    this.parts = [];
    this.length = 0;
    this.append = function (s) {
      this.parts.push(s);
      this.length += s.length;
    }
    this.prepend = function (s) {
      this.parts.unshift(s);
      this.length += s.length;
    }
    this.toString = function () {
      return this.parts.join('');
    }
  }
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
var output = new StringMaker();
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;

while (i < input.length) {
 chr1 = input.charCodeAt(i++);
 chr2 = input.charCodeAt(i++);
 chr3 = input.charCodeAt(i++);

 enc1 = chr1 >> 2;
 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
 enc4 = chr3 & 63;

 if (isNaN(chr2)) {
   enc3 = enc4 = 64;
 } else if (isNaN(chr3)) {
   enc4 = 64;
 }

 output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4));
}

//return encodeURIComponent(output.toString());
return output.toString();

}

var setNewPasswordCallback = { 
    onSuccess: function(response) { 
      //console.dir(response);
  if('presto-cloud-block-content2' == callbackTrigger){
    loginPrestoUserStep2(tempUserName, tempApiPwd, callbackTrigger);
  }
  else if('dialog' == callbackTrigger){
    loginUserStep2(tempUserName, tempApiPwd, callbackTrigger);
    
  }
  else{
    testPrestoLoginStep2(tempUserName, tempApiPwd, callbackTrigger);
  }
    }, 
    onFailure: function(err) { 
      //console.dir(err);
      $j('#' + callbackTrigger + 'Msg').html('<div style="background-color:red; color:#fff; padding:4px;">Account disabled, please try again.</div>');
    }, 
    scope: this 
};

function setNewPassword(){
  /* establish the server connection */
  var prestoConfig = {
    prestoUrl: "http://cloud.jackbe.com/presto", 
    username: apiAdminUser, 
    password: apiAdminPwd,
    crossDomainPost: false
  }
  var connection = new Presto.Connection(prestoConfig);
  
  var requestConfig = {
      "version": "1.1", 
      "sid": "UserManagerService", 
      "svcVersion": "0.1", 
      "oid": "resetPassword", 
      "params": [tempUserName, tempApiPwd]
  }
  connection.request(requestConfig, setNewPasswordCallback);
}

