// Common JavaScript code for Gravity Switch Universes

// The MM_ functions are Dreamweaver (MacroMedia) thingies:
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function gsSetCookie(c, val)
{
  document.cookie = c + "=" + escape(val);
}

//use this to preload images before MM preloadimages does.  This should fix flickers.
//send it a comma separated list of images that you would want to preload.
function gsPreloadImages(){
	var imageArray = new Array(); 
	var j=imageArray.length;
	for (i=0;i<gsPreloadImages.arguments.length;i++){
		imageArray[j]=new Image; 
		imageArray[j++].src=gsPreloadImages.arguments[i];
	}
}

//
// This is used for lightweight UI stuff; example usage:
//   <a href="javascript: gsDoTask('task=moveWidgetUp')">Edit</a>
// Pass in a url-type query string.
//
function gsDoTask(args)
{
  var url = location.href;
  //see if there is a redirect command.  If so, encode it so that it doesn't do BAD THINGS later.
  if (args.indexOf("redirect") != -1){
  	argArray = args.split("&redirect=");
	//reescape the redirect information
	redirectString = escape(argArray[1]);
	//recombine the beginning of the arg with the split off redirect
	args = argArray[0] + '&redirect=' + redirectString; 
  }
  // Set gsT cookie:
  gsSetCookie('gsT', args);
  location.replace(url);  // Reload page, without affecting history
  if (url.indexOf("#") != -1) {
    location.reload(); // dunno why this is necessary if there's a #
                       // in the URL, but it is...
  }
}

function gsRememberValue(element)
{
  element.gsPrevValue = element.value;
}

function gsChangeWidgetStatus(element, widgetID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this item?')) {
      element.value = element.gsPrevValue;
      return;
    }
  }
  if (widgetID > 0) {
    gsDoTask("featureName=gsWebPage&task=changeWidgetStatus&widgetStatus="+newStatus+"&widgetID="+widgetID);
  }
}

function gsChangeSiteStatus(element, siteID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this site?')) {
      element.value = element.gsPrevValue;
      gsDoTask("featureName=gsSites&task=manageSites");
      return;
    }
  }
  if (siteID > 0) {
    gsDoTask("featureName=gsSites&task=manageSites&statusSiteID="+siteID+"&newSiteStatus="+newStatus);
  }
}

function gsChangeUserStatus(element, userID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to make this user inactive?')) {
      element.value = element.gsPrevValue;
      gsDoTask("featureName=gsUsers&task=manageUsers");
      return;
    }
  }
  if (userID > 0) {
    gsDoTask("featureName=gsUsers&task=manageUsers&userID="+userID+"&changeUserStatusID="+newStatus);
  }
}

function gsChangeItemStatus(element, itemID, newStatus, deleteStatus, featureName) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this item?')) {
	  element.value = element.gsPrevValue;
      gsDoTask("featureName="+featureName+"&task=manage");
      return;
    }
  }
  if (itemID > 0) {
    gsDoTask("featureName="+featureName+"&task=manage&itemID="+itemID+"&changeStatus="+newStatus);
  }
}

function gsChangeEventStatus(element, eventID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this Event?')) {
	  element.value = element.gsPrevValue;
      gsDoTask("featureName=gsEvent&task=manageEvents");
      return;
    }
  }
  if (eventID > 0) {
    gsDoTask("featureName=gsEvent&task=manageEvents&statusEventID="+eventID+"&newEventStatus="+newStatus);
  }
}

function gsChangeNewsStatus(element, newsID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this News?')) {
	  element.value = element.gsPrevValue;
      gsDoTask("featureName=gsNews&task=manageNews");
      return;
    }
  }
  if (newsID > 0) {
    gsDoTask("featureName=gsNews&task=manageNews&statusNewsID="+newsID+"&newNewsStatus="+newStatus);
  }
}

function gsChangeGalleryItemStatus(element, itemID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this gallery item?')) {
	  element.value = element.gsPrevValue;
      return;
    }
  }
  if (newsID > 0) {
    // This might get implemented when a Manage Gallery Items screen is done...
    alert("ChangeGalleryItemStatus immediate unimplemented.");
  }
}

function gsChangePageStatus(element, pageID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to delete this page?')) {
      element.value = element.gsPrevValue;
      return;
    }
  }
  if (pageID > 0) {
    gsDoTask("featureName=gsWebPage&task=manage&statusPageID="+pageID+"&newPageStatus="+newStatus);
  }
}

function gsChangeCouponStatus(element, couponID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to make this coupon inactive?')) {
      element.value = element.gsPrevValue;
      return;
    }
  }
  if (couponID != '') {
    gsDoTask("featureName=gsCoupon&task=doManage&statusCouponID="+couponID+"&newCouponStatus="+newStatus);
  }
}

function gsChangeOrderStatus(element, orderID, newStatus, deleteStatus) {
  if (newStatus == deleteStatus) {
    if (!confirm('Are you sure you want to void this order?')) {
      element.value = element.gsPrevValue;
      return;
    }
  }
  if (orderID != '') {
    gsDoTask("featureName=gsOrders&task=doManage&statusOrderID="+orderID+"&newOrderStatus="+newStatus);
  }
}

function toggleAdvanced(object) {
  var advanced = document.getElementById(object);
    if (advanced.style.display == 'none')
         show(object);
    else
        hide(object);
}

function show(object) {
   var advanced = document.getElementById(object);
   advanced.style.display = 'block';
}

function hide(object) {
    var advanced = document.getElementById(object);
   advanced.style.display = 'none';
}

// --- preload functions:
function newImage(arg) {
     if (document.images) {
          rslt = new Image();
          rslt.src = arg;
          return rslt;
     }
}

// Pass css style sheet to use, if you wanna style it:
function quickTipWindow(){
	//create the string for the open window
	quickTipString =  "<html>\n<head>\n<title>HTML Quick Tips</title>\n";
    if (quickTipWindow.arguments.length > 0) {
    	quickTipString += "<style type='text/css' media='all'>@import'"+quickTipWindow.arguments[0]+"';</style>\n";
    }
	quickTipString += "</head>\n<body name='admin' id='admin' style='margin:20px; onLoad='this.window.focus();'>\n";
	quickTipString += "<center><div style='text-align:left;font-size:70%;'><h2>HTML Quick Tips</h2>\n";
	quickTipString += "<p style='margin-left:10px;'>&lt;b&gt;bold&lt;/b&gt;<br>\n";
	quickTipString += "example: &lt;b&gt;<b>More about Us</b>&lt;/b&gt;</p>";
	quickTipString += "<p style='margin-left:10px;'>&lt;i&gt;italics&lt;/i&gt;<br>\n";
	quickTipString += "example: &lt;i&gt;<i>More about Us</i>&lt;/i&gt;</p>\n";
	quickTipString += "<p style='margin-left:10px;'>&lt;img&gt;images<br>\n";
	quickTipString += "example: &lt;img	src='http://www.gravityswitch.com/images/logo.gif' height='45'	width='553' alt='Logo' &gt;</p>\n";
	quickTipString += "<p style='margin-left:10px;'>&lt;a&gt;links<br />\n";
	quickTipString += "example: &lt;a href='http://www.gravityswitch.com/about/'&gt;<a href='http://www.gravityswitch.com/about/'>More about Us</a>&lt;/a&gt;</p>\n";
	quickTipString += "<p style='margin-left:10px;'>&lt;a&gt;link opens in new window<br />\n";
	quickTipString += "example: &lt;a href='http://www.gravityswitch.com/about/' target='_blank'&gt;<a href='http://www.gravityswitch.com/about/' target='_blank'>More about Us</a>&lt;/a&gt;</p>\n";
	quickTipString += "\n</div></center>\n</body>\n</html>\n";
	//open the window
	newWindow = window.open('','QuickTips','width=500,height=400');
	newWindow.document.write(quickTipString);
	newWindow.document.close();
}

function gsImageWindow(url, width, height) {
  var attributesList = "toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width="+(width+112)+",height="+(height+142);
  var imageWindow = window.open(url,'image',attributesList);
  imageWindow.focus();
}

function gsPopWindow(url, width, height) {
  var attributesList = "toolbar=yes,location=yes,directories=yes,status=yes,scrollbars=yes,menubar=yes,resizable=yes,copyhistory=no,width="+(width)+",height="+(height);
  var imageWindow = window.open(url,'image',attributesList);
  imageWindow.focus();
}

//
// Spiffy way of doing a set of JavaScript try()'s:
//
var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

//
// Post form data (urlencoded) via XMLHttpRequest.
// Returns server response status, or false.
//

var httpObject = false;

function postForm(to, encodedData, asynchronous, readyHandler)
{
   httpObject = (Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
   ) || false);
 
   if (! httpObject) { alert('Create httpObject failed'); return false; }

   httpObject.open('POST', to, asynchronous);
   /* if there is a ready handler to get the result, define it here */
   if (readyHandler) {
   	httpObject.onreadystatechange = readyHandler;
   }

   httpObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   httpObject.send(encodedData+'&fromAJAX=1');

   if (asynchronous) { return httpObject; }

   return httpObject.status;
}

// Pass in a form, get back x-www-form-urlencoded string you can send() via XMLHttpRequest
function encodeFormData(f) {
  var result = '';
  var item;
  var strLastElemName = '';

  for (i = 0; i < f.elements.length; i++) {
    item = f.elements[i];
    switch (item.type) {
      case 'text':
      case 'hidden':
      case 'textarea':
      case 'select-one':
      case 'password':
        result += item.name + '=' + encodeURIComponent(item.value) + '&'
        break;
      case 'radio':
        if (item.checked) {
          result += item.name + '=' + encodeURIComponent(item.value) + '&'
        }
        break;
      case 'checkbox':
        if (item.checked) {
          if (item.name == strLastElemName) {
            if (result.lastIndexOf('&') == result.length-1) {
              result = result.substr(0, result.length - 1);
            }
            result += ',' + encodeURIComponent(item.value);
          }
          else {
            result += item.name + '=' + encodeURIComponent(item.value);
          }
          result += '&';
          strLastElemName = item.name;
        }
        break;
      }
    }
  result = result.substr(0, result.length - 1);
  return result;
}

function getNewCouponID(to){
	/* use the information from WYSIWYG stuff to get the new coupon ID */
	encodedData = '';
	postForm(to, encodedData, true, couponHandler)

}

function couponHandler() {
	/* Make sure that the transaction has finished. The XMLHttpRequest object 
		has a property called readyState with several states:
		0: Uninitialized
		1: Loading
		2: Loaded
		3: Interactive
		4: Finished */
	if(httpObject.readyState == 4){ //Finished loading the response
		/* We have got the response from the server-side script,
			let's see just what it was. using the responseText property of 
			the XMLHttpRequest object. */
		var response = httpObject.responseText;
		/* And now we want to change the product_categories <div> content.
			we do this using an ability to get/change the content of a page element 
			that we can find: innerHTML. */
		document.getElementById('couponID').value = response;
	}
}

/*
 * Generic onload() handler used by gsAddOnloadCode()
 */
function gsOnloadHandler(event) {
  var i;
  for (i = 0; i < window.gs_onloadStuff.n; i++) {
    var f = window.gs_onloadStuff[i];
    if (typeof f == 'function') { f(event); }
    if (typeof f == 'string') { eval(f); }
  }
}
/*
 * Add code (in a string OR pass a function) to body's onload.
 */
function gsAddOnloadCode(code) {
  if (null == code) return;
  if (null == window.gs_onloadStuff) {
    window.gs_onloadStuff = new Array();
    window.gs_onloadStuff.n = 0;
    if (window.onload != gsOnloadHandler) {
     var old = window.onload;
     window.onload=gsOnloadHandler;
     gsAddOnloadCode(old);
    }
  }
  var n = window.gs_onloadStuff.n;
  window.gs_onloadStuff[n] = code;
  window.gs_onloadStuff.n = n+1;
}
