/*
 * JLI - General JS functions
 */

/**
 * popupRegistration
 */
function popupRegistration()
{
//  var _win = window.open('/','jli_register', 'height=250,width=550,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');
//  if(_win == null) alert("We could not pop up a new window, you might need to disable your Popup blocker to continue");
  window.location = '/';
}

/**
 * Displays Serenity in a new window
 */
function openSerenity()
{
   this._jliwin = window.open("/serenity","serenity_window","");
   if(!this._jliwin)
   {
    window.alert("Oops, it appears you have a popup blocker on!\nPlease allow popups for this site before continuing.");  
   }
}

/**
 * contactUs
 */
function contactUs()
{
  var self = this;
  var comment_field = dojo.byId("contact_comments");
  var email_field = dojo.byId("contact_email");
  
  //optional reason field
  var reason_field = dojo.byId("contact_reason");
  
  var send_button = dojo.byId("contact_send");
  
  //make sure they have entered a comment...
  if(comment_field.value == null 
    || comment_field.value == "" 
    || comment_field.value == comment_field.getAttribute("defaultValue"))
  {
    alert("Please enter a message to send");
    return;
  }
  
  //make sure they have entered an email address..
  if(email_field.value == null 
    || email_field.value == "" 
    || email_field.value == email_field.getAttribute("defaultValue"))
  {
    alert("Please enter a your email address");
    return;
  }
  
  //and email is valid...
  if(email_field.value.indexOf("@") == -1)
  {
    alert("Please enter a valid email address");
    return;
  }
  
  //disable button
  send_button.disabled = true;

  //send comment...
  dojo.xhrPost({
    url: "/contact_us",
    content: { email: email_field.value, body: comment_field.value, reason: (reason_field == null ? "" : reason_field.value)},
    load: function(response, ioargs) 
    { 
      //on successful comment sent...
      alert("Your Message has been sent, thank you.");      
      send_button.disabled = false;
      email_field.value = (email_field.defaultValue ? email_field.defaultValue : "");
      comment_field.value = (comment_field.defaultValue ? comment_field.defaultValue : "");
    },
    error: function(response, ioArgs) 
    { 
      //on comment send error...
      alert("An error has occured sending your message.");      
      send_button.disabled = false;
    }
  });
}

/**
 * prefixObjectProperties - utility method for converting all of
 * a JS object's properties from <property> to <prefix>[<property>]
 * Useful for submitting forms with "scoped" variables
 * 
 * Example:
 * dojo.xhrPost({
 *   url: 'http://10.10.1.79:3000/library/images/1/placements',
 *   content: prefixObjectProperties("placement", {
 *     asset_id: 49
 *   })
 * })
 * 
 */

prefixObjectProperties = function(prefix, object) {
  var result = {}
  var key;
  var prop;
  for(prop in object) {
    key = dojo.string.substitute("${0}[${1}]",[prefix,prop])
    result[key] = object[prop]
  }
  return result;
}

dojo.addOnLoad(function(){
  
  dojo.xhrPut = function(params) {
    params.content = params.content || {}
    params.content._method = 'put'
    return dojo.xhrPost(params)
  }

  dojo.xhrDelete = function(params) {
    params.content = params.content || {}
    params.content._method = 'delete'
    return dojo.xhrPost(params)
  }
  
});





Ajax = {
  Request: function(url, options) {
    xhrOptions = {
      "url": url,
      "sync": !options.asynchronous || false,
      "content": options.parameters
    };
    if (options.evalScripts == true) {
      dojo.mixin(xhrOptions, {
        "handleAs": "javascript",
        "headers": { "Accept": "application/javascript" }
      });
    }
    dojo.xhr(
      options.method || "post",
      xhrOptions
    );
  },
  Updater: function(id, url, options) {
    xhrOptions = {
      "url": url,
      "sync": !options.asynchronous || false,
      "load": function(data) {
        el = document.createElement('div');
        el.innerHTML = data;
        dojo.byId(id).innerHTML = "";
        dojo.place(el, id, "only" );
        if (typeof options.onLoaded == "function") {
          options.onLoaded();
        }
      }
    };
    dojo.xhr(
      options.method || "post",
      xhrOptions
    );
  }
}

Form = {
  serialize: function(form)
  {
    return dojo.formToObject(form);
  }
}

function argumentsToArray() { 
  var arr = []; 
  for (i=0; i<arguments.length; i++) { 
    arr[i] = arguments[i]; 
  } 
  return arr; 
}

// TODO: integrate all this into the rewrite
dojo.require("dijit.form.FilteringSelect");
dojo.require("dojo.data.ItemFileReadStore");

dojo.addOnLoad(function(){
  groupSelElement = document.createElement('div');
  groupSelElement.id = "groupSelector";
  groupSelElement.innerHTML = '<label>Group: </label>'
  dojo.style(groupSelElement, "marginLeft", "5px")

  cb = function(groupId){
    dojo.xhrPut({
      url: "/my/spaces/" + theSpaceId,
      content: {
        "space[group_id]": groupId
      }
    });
  }

  groupStore = new dojo.data.ItemFileReadStore({ url: "/groups.json" });


  sel = new dijit.form.FilteringSelect({
    "store": groupStore,
    "searchAttr": "label",
    "onChange": cb,
    "require": false
  });
  sel.placeAt(groupSelElement, "last");

  dojo.subscribe("ManagerSpacesPanel/OnDataItemSelected", function(item){
    if (!leapin.session.user.isLoggedIn() || leapin.jlisession.user.id != item.user_id) {
      return;
    }
    var spaceId = item.space_id || item.id;
    theSpaceId = spaceId;
    var refNode = dojo.query('div.previewPanelDetails div.detailItem')[0];
    dojo.place(groupSelElement, refNode, "after");
    sel.destroy();
    foo = new leapin.connector.BaseConnector();
    foo.createDataRequest({
      uri: "/my/spaces/" + spaceId + ".json",
      type: "GET",
      onload: function(response){
        var groupId = response.item.group_ids[0];
        groupId = groupId ? groupId + '' : '-1';

        sel = new dijit.form.FilteringSelect({
          "store": groupStore,
          "searchAttr": "label",
          "onChange": cb,
          "value": groupId,
          "require": false
        });
        sel.placeAt(groupSelElement, "last");
      }
    });
  });
});
