/*
+---------------------------------------------------------------+
| PSilo by bugrain (www.bugrain.plus.com)
|
| A artifact for the e107 Website System (http://e107.org)
|
| Copyright 2007, Neil Harrison (AKA bugrain)
|
| $Source: e:\_repository\e107_plugins/psilo/psilo.js,v $
| $Revision: 1.17 $
| $Date: 2008/01/16 20:03:22 $
| $Author: Neil $
+---------------------------------------------------------------+
*/
document.observe("dom:loaded", function() {
   var el = null; // generic elemnt variable

   // Population of upload fields from previous version of an artifact
   if (el = $("ui_artifact_name_list")) {
      el.observe("change", function(ev) {
         psiloHelper.populateArtifactFields(ev.element().value);
      });
   }

   // Tooltips for download status icons
   $$('.psilo_dl_img').each(function(el){
      new Tip(el, el.alt, {
         title:   el.title,
         effect:  'appear'
      });
      el.title = "";
   });

   // Expandable sections
   $$('a.psilo_expandit_blind').invoke("observe", "click", function(ev) {
      new Effect.toggle(ev.element().up().next(), "blind")
      ev.stop();
   });
   $$('div.psilo_expandit_blind').invoke("observe", "click", function(ev) {
      new Effect.toggle(ev.element().next(), "blind")
      ev.stop();
   });

   $$('a.psilo_expandit_slide').invoke("observe", "click", function(ev) {
      new Effect.toggle(ev.element().up().next(), "slide")
      ev.stop();
   });
   $$('div.psilo_expandit_slide').invoke("observe", "click", function(ev) {
      new Effect.toggle(ev.element().next(), "slide")
      ev.stop();
   });

   $$('div.psilo_expandit_accordion').invoke("observe", "click", function(ev) {
      psiloHelper.accordion(ev.element());
      ev.stop();
   });

   $$('a.psilo_expandit_accordion').invoke("observe", "click", function(ev) {
      psiloHelper.accordion(ev.element().up());
      ev.stop();
   });

   // Manage population of version number drop down based on selection from artifact drop down for language pack upload page
   if (el = $("ui_language_pack_artifact_name")) {
      el.observe("change", psiloHelper.populateArtifactVersionDropdown.bind(this, el, $A(["ui_language_pack_artifact_id"])));
   }

   // Manage population of version number drop down based on selection from artifact drop down for request page
   if (el = $("ui_prequest_artifact_name")) {
      el.observe("change", psiloHelper.populateArtifactVersionDropdown.bind(this, el, $A(["ui_prequest_artifact_id"])));
   }

   // Manage population of version number drop down based on selection from artifact drop down for relationships page
   if (el = $("psilo_relationship_artifact")) {
      el.observe("change", psiloHelper.populateArtifactVersionDropdown.bind(this, el, $A(["psilo_relationship_min", "psilo_relationship_max"])));
   }

   // Stuff for managing the reltionships sub-form
   if (el = $("psilo_relationship_add")) {
      el.observe("click", psiloHelper.relationshipFormAdd.bind(this, el));
   }
   if (el = $("psilo_relationship_edit")) {
      el.observe("click", psiloHelper.relationshipFormEdit.bind(this, el));
   }
   if (el = $("psilo_relationship_delete")) {
      el.observe("click", psiloHelper.relationshipFormDelete.bind(this, el));
   }


   //// Check for highlighting form fields
   //$$('.formfield').invoke("observe", "focus", function (ev) {
   //   new Effect.Highlight(ev.element())
   //});

   // Check for message areas to be 'flashed'
   $$('.flasher').each(function (e) {
      Effect.Pulsate(e, {duration: 4.0})
   });

   // Check for help links to other pages
   $$('a.psilo_help_page').invoke("observe", "click", function(ev) {
      psiloHelper.helpPage(ev.element());
      ev.stop();
   });

   // Check for request preview button
   if (el = $("psilo_preview_request_button")) {
      el.observe("click", psiloHelper.requestPreview);
   }
});

var psiloHelper = {
   // Ajax function
   helpPage : function (el) {
      var win = new Window({
         className:     "alphacube",
         title:         "Help",
         top:           10,
         right:         10,
         width:         400,
         height:        500,
         url:           el.href,
         showEffectOptions: {
            duration:   1.5
         }
      });
      win.show();
   },
   relationshipFormAdd : function (el) {
      var list    = $('psilo_relationships_list');
      var atype   = psiloHelper.selectValueText('psilo_relationship_type');
      var aid     = psiloHelper.selectValueText('psilo_relationship_artifact');
      var amin    = psiloHelper.selectValueText('psilo_relationship_min');
      var amax    = psiloHelper.selectValueText('psilo_relationship_max');

      if (aid.value == 0) {
         alert("You must select a plugin");
         return;
      }
      if (list.options.length == 1 && list.options[0].value == "") {
         list.options.length = 0;
      }
      var value = atype.value+"::"+aid.text+"::"+amin.value+"::"+amax.value;
      var text = aid.text+" : "+amin.text+" - "+amax.text+" ("+atype.text+")";

      list.options[list.options.length] = new Option(text, value);
      psiloHelper.relationshipBuildList(el);
   },
   relationshipFormEdit : function (el) {
      var list = $('psilo_relationships_list');
      if (list.options.length == 0) {
         alert("There is nothing to edit");
         return;
      }
      if (list.selectedIndex == -1) {
         alert("You must select an item in the list to edit");
         return;
      }
      var values = $F('psilo_relationships_list').split("::");
      $('psilo_relationship_type').setValue(values[0]);
      $$('#psilo_relationship_artifact option').each(function(opt, ix) {
         if (values[1] == opt.text) {
            $('psilo_relationship_artifact').selectedIndex = ix;
            psiloHelper.populateArtifactVersionDropdown($('psilo_relationship_artifact'), $A(["psilo_relationship_min", "psilo_relationship_max"]));
            throw $break;
         }
      });
      $('psilo_relationship_min').setValue(values[2]);
      $('psilo_relationship_max').setValue(values[3]);
      // Delete the list entry - much easier than trying to add it back in in the right place!
      list.options[list.selectedIndex] = null;
      psiloHelper.relationshipBuildList(el);
   },
   relationshipFormDelete : function (el) {
      // Check we have something to delete
      var list = $('psilo_relationships_list');
      if (list.options.length == 0) {
         alert("There is nothing to delete");
         return;
      }
      if (list.selectedIndex == -1) {
         alert("You must select an item in the list to delete");
         return;
      }
      // No confirmation - it's not saved until the page is submitted anyway
      list.options[list.selectedIndex] = null;
      psiloHelper.relationshipBuildList(el);
   },
   relationshipBuildList : function (el) {
      var list = $('psilo_relationships_list');
      var text = $('psilo_relationships_related');
      if (list.options.length == 0) {
         text.value = "";
         return;
      }
      text.value = "";
      $$('#psilo_relationships_list option').each(function(opt, ix) {
         text.value = ix==0 ? opt.value : text.value + "##" + opt.value;
      });

      psiloHelper.updateField($('psilo_artifactid').value, 'psilo_artifact_related', 'psilo_relationships_related', '');
   },
   selectValueText : function (elid) {
      var el = $(elid);
      return {
         value: el.value,
         text:  el.selectedIndex >= 0 ? el.options[el.selectedIndex].text : ""
      }
   },
   requestPreview : function () {
      e107Helper.logEnter("psilo.requestPreview()");
      //e107HelperAjax.addParm("psilo_action", "requestpreview");
      //e107HelperAjax.addParm("psilo_form", $('psilo').serialize());
      //e107HelperAjax.addParm("psilo_title", $('psilo_post_ui_prequest_title').value);
      //e107HelperAjax.addParm("psilo_description", $('psilo_post_ui_prequest_description_').value);
      //e107HelperAjax.post("psilo_ajax.php");
      var params = $H({
         psilo_action:        "requestpreview",
         psilo_title:         $('psilo_post_ui_prequest_title').value,
         psilo_description:   $('psilo_post_ui_prequest_description_').value
      });
      Dialog.alert({
         url: "psilo_ajax.php",
         options: {
            method:     'post',
            parameters: "json="+params.toJSON()
         }},
         {
            className:  "alphacube",
            width:      540,
            okLabel:    "Close"
         }
      );

      e107Helper.logExit("psilo.requestPreview()", "null");
   },
   populateArtifactFields : function (artifact) {
      e107Helper.logEnter("psilo.populateArtifactFields()");
      e107HelperAjax.addParm("psilo_action", "populateartifactfields");
      e107HelperAjax.addParm("psilo_artifact", artifact);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.populateArtifactFields()", "");
   },
   setStatus : function (newstatus, artifactid) {
      e107Helper.logEnter("psilo.setStatus("+newstatus+","+artifactid+")");
      e107HelperAjax.addParm("psilo_action", "setstatus");
      e107HelperAjax.addParm("psilo_newstatus", newstatus);
      e107HelperAjax.addParm("psilo_artifactid", artifactid);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.setStatus()", "");
   },
   setRequestStatus : function (newstatus, requestid) {
      e107Helper.logEnter("psilo.setRequestStatus("+newstatus+","+requestid+")");
      e107Helper.message("psiloMessage", "... please wait.");
      e107HelperAjax.addParm("psilo_messageid", "psiloMessage");
      e107HelperAjax.addParm("psilo_action", "setrequeststatus");
      e107HelperAjax.addParm("psilo_newstatus", newstatus);
      e107HelperAjax.addParm("psilo_requestid", requestid);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.setRequestStatus()", "");
   },
   setAuthor : function (newauthor, artifactid) {
      e107Helper.logEnter("psilo.setAuthor("+newauthor+","+artifactid+")");
      e107HelperAjax.addParm("psilo_action", "setauthor");
      e107HelperAjax.addParm("psilo_newauthor", newauthor);
      e107HelperAjax.addParm("psilo_artifactid", artifactid);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.setAuthor()", "");
   },
   updateField : function (artifactid, fieldname, field, container) {
      e107Helper.logEnter("psilo.updateField(id="+artifactid+", fieldName="+fieldname+", field="+field+")");
      e107Helper.message("psiloMessage", "... please wait.");
      e107HelperAjax.addParm("psilo_messageid", "psiloMessage");
      e107HelperAjax.addParm("psilo_action", "updatefield");
      e107HelperAjax.addParm("psilo_artifactid", artifactid);
      e107HelperAjax.addParm("psilo_field", fieldname);
      e107HelperAjax.addParm("psilo_container", container);
      e107HelperAjax.addParm("psilo_value", $(field).value);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.updateField()", "");
   },
   ssMove : function (artifactid, ssnum, inc) {
      e107Helper.logEnter("psilo.ssMove("+artifactid+","+ssnum+","+inc+")");
      e107HelperAjax.addParm("psilo_action", "ssmove");
      e107HelperAjax.addParm("psilo_artifactid", artifactid);
      e107HelperAjax.addParm("psilo_ssnum", ssnum);
      e107HelperAjax.addParm("psilo_inc", inc);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.ssMove()", "");
   },
   ssDelete : function (artifactid, ssnum) {
      e107Helper.logEnter("psilo.ssDelete("+artifactid+","+ssnum+")");
      e107HelperAjax.addParm("psilo_action", "ssdelete");
      e107HelperAjax.addParm("psilo_artifactid", artifactid);
      e107HelperAjax.addParm("psilo_ssnum", ssnum);
      e107HelperAjax.post("psilo_ajax.php");
      e107Helper.logExit("psilo.ssDelete()", "");
   },
   // Client only functions
   showDiv : function (divid, prefix) {
      var container = $(prefix+"_container");
      if (null != container) {
         var divs = container.getElementsByTagName("div");
         for (var i=0; i<divs.length; i++) {
            var match = new RegExp("^"+prefix+"(.*)$");
            if (divs[i].id.match(match)) {
               if (divs[i].id == divid) {
                  divs[i].style.display = "";
                  e107HelperStyle.addClass($(divs[i].id+"_li"), "tab6current");
               } else {
                  divs[i].style.display = "none";
                  e107HelperStyle.removeClass($(divs[i].id+"_li"), "tab6current");
               }
            }
         }
      }
   },
   populateArtifactVersionDropdown : function (el, ids) {
      ids.each(function (id) {
         var versions = $(id)
         versions.options.length = 1;
         if (el.value != "") {
            versions.disabled = false;
            var values = el.value.split("::");
            for (var i=0; i<values.length; i++) {
               var values2 = values[i].split("++")
               versions.insert(new Element('option', {value: values2[0]}).update(values2[1]))
            }
         }
      });
   },
   accordion : function (el) {
      if (el.next().visible()) {
         return;
      }
      var options = {duration: 0.3};
      var elnext = el.next();
      // Find all siblings and make sure they are hidden (there should only be 1!)
      el.siblings().each(function (sib) {
         if (sib != elnext && sib.visible() && sib.hasClassName("psilo_expandit_accordion_content")) {
            new Effect.BlindUp(sib, options);
         }
      });
      if (!el.next().visible()) {
         new Effect.BlindDown(el.next(), options);
      }
   }
}

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/
function startCallback() {
   // make something useful before submit (onStart)
	return true;
}
function completeCallback(response) {
   // make something useful after (onComplete)
	$('psilo_screenshot_container').innerHTML = response;
}

AIM = {
	frame : function(c) {
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
		var i = $(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
		return n;
	},
	form : function(f, name) {
		f.setAttribute('target', name);
	},
	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
	loaded : function(id) {
		var i = $(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}
}




