// 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;
  // 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 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) {
    alert("ChangePageStatus immediate unimplemented.");
//    gsDoTask("featureName=gsSites&task=manageSites&statusSiteID="+siteID+"&newSiteStatus="+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();
}

//
// 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;
	}
}

// onsubmit handler for inline WYSIWYG forms.
// Split into two functions so status updates nicely.
function gsWYSIWYGSubmit(f, to)
{
  // NOTE: changing the window status is disabled by default in Mozilla/Firefox
  // browsers (controlled by preference dom.disable_window_status_change; type
  // abount:config in Firefox location box to see/change).
  window.status="Saving...";
  var func2 = function() { gsWYSIWYGSubmit2(f,to);} 
  setTimeout(func2, 0);
  return false;
}

function gsWYSIWYGReadyHandler()  // Do-nothing handler...
{
  if (httpObject.readyState != 4) { return; }
  return;
}

function gsWYSIWYGSubmit2(f, to)
{
  submit_form();
  var code = postForm(to, encodeFormData(f), false);
  var ww = document.getElementById(f.wysiwygName.value);
  ww.savedValue = ww.value;
  var toRefresh = new Array();
  toRefresh[toRefresh.length] = ww;
  toRefresh[toRefresh.length] = ww.value;

  // Look for other unsaved WYSIWYG forms on the page:
  var otherforms = document.getElementsByTagName("FORM");
  for (var i=0; i<otherforms.length; i++) {
    var ff = otherforms[i];
  	if (code == 200 && f != ff && ff.className == "gsWYSIWYG") {
      ww = document.getElementById(ff.wysiwygName.value);
      if (ww.value != ww.savedValue) {
        ww.savedValue = ww.value;
        toRefresh[toRefresh.length] = ww;
        toRefresh[toRefresh.length] = ww.value;
        // Do other forms on the page asynchronously:
        postForm(to, encodeFormData(ff), gsWYSIWYGReadyHandler);
      }
	}
  }

  if (code == 200) {
    window.status = "Saved.";
    setTimeout("window.status='';", 3000);
    alert("Save complete.");
  }
  else {
    alert("Save FAILED; contact your site administrator.\n(Status code: " + code + ")");
  }

  // There's a nasty Firefox display bug where blank lines/paragraphs disappear
  // when you poke Save.  This is the workaround:
  var i;
  for (i = 0; i < toRefresh.length; i += 2) {
    toRefresh[i].setCode(toRefresh[i+1]);
  }

  return false; // We never want form submitted/page refreshed...
}

//rotate through a list of images, all of the same height and width and in the same directory.
function showImage(baseurl,imagearray) {
	var p = imagearray.length;
	var whichImage = Math.round(Math.random()*(p-1));
	document.write('<img src="gsCMS/httpRoot/templates/images/rotating/'+imagearray[whichImage]+'"height="259" width="386">');
}