// Common JavaScript code for Gravity Switch Universes

// The MM_ functions come from Dreamweaver, (c) Adobe
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 i,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 without adding to the history

	// This code should only execute if the reload fails:
	if (url.indexOf("#") != -1) {	// Is there an anchor in the URL? The browser probably only scrolled.
		location.reload();			// Force a reload in this instance.
	}
}

function gsRememberValue(element) {
	if (!element.gsGotValue) {
		element.gsGotValue = true;
		element.gsPrevValue = element.value;
	}
}
function gsRememberIndex(element) {
	if (!element.gsGotIndex) {
		element.gsGotIndex = true;
		element.gsPrevIndex = element.selectedIndex;
	}
}

function gsChangeStatus(itemID, newStatus, deleteStatus, forFeature, forTask, forItem, forStatus, whatToDo, element) {
  if (!whatToDo) whatToDo = 'delete this item';
  if (newStatus == deleteStatus && !confirm('Are you sure you want to '+whatToDo+'?')) {
    if (element) { element.selectedIndex = element.gsPrevIndex; }
    return;
  }
  if (itemID > 0) {
     gsDoTask("featureName="+forFeature+"&task="+forTask+"&"+forItem+"="+itemID+"&"+forStatus+"="+newStatus);
  }
}

function gsChangeItemStatus(itemID, newStatus, deleteStatus, forFeature) {
	gsChangeStatus(itemID, newStatus, deleteStatus, forFeature, 'manage', 'itemID', 'changeStatus', null, null);
}

function gsChangeWidgetStatus(widgetID, newStatus, deleteStatus) {
	gsChangeStatus(widgetID, newStatus, deleteStatus, 'gsWebPage', 'changeWidgetStatus', 'widgetID', 'widgetStatus', null, null);
}

function gsChangeSiteStatus(element, siteID, newStatus, deleteStatus) {
	gsChangeStatus(siteID, newStatus, deleteStatus, 'gsSites', 'manageSites', 'statusSiteID', 'newSiteStatus', 'delete this site', element);
}

function gsChangeUserStatus(element, userID, newStatus, deleteStatus) {
	gsChangeStatus(userID, newStatus, deleteStatus, 'gsUsers', 'manageUsers', 'userID', 'changeUserStatusID', 'make this user inactive', element);
}

function gsChangePageStatus(element, pageID, newStatus, deleteStatus) {
	gsChangeStatus(pageID, newStatus, deleteStatus, 'gsWebPage', 'manage', 'statusPageID', 'newPageStatus', 'delete this page', element);
}

function gsChangeCouponStatus(element, couponID, newStatus, deleteStatus) {
	gsChangeStatus(couponID, newStatus, deleteStatus, 'gsCoupon', 'doManage', 'statusCouponID', 'newCouponStatus', 'make this coupon inactive', element);
}

function gsChangeOrderStatus(element, orderID, newStatus, deleteStatus) {
	gsChangeStatus(orderID, newStatus, deleteStatus, 'gsOrders', 'doManage', 'statusOrderID', 'newOrderStatus', 'void this order', element);
}

function gsChangeGalleryItemStatus(element, itemID, newStatus, deleteStatus) {
	gsChangeStatus(itemID, newStatus, deleteStatus, 'gsGallery', 'manage', 'itemID', 'changeStatus', 'deactivate this image', element);
}

function toggleVisible(id) {
	var element = document.getElementById(id);
	if (element)
		element.style.display = (element.style.display == 'block') ? 'none' : 'block';
}

function show(id) {
	var element = document.getElementById(id);
	if (element)
		element.style.display = 'block';
}

function hide(id) {
	var element = document.getElementById(id);
	if (element)
		element.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 gsImagePopWindow(url, width, height) {
	var attributesList = "toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width="+(width+50)+",height="+(height+50);
	var imageWindow = window.open('','imagepop',attributesList);
	imageWindow.document.write("<html><head><style>body{background-color:#eee;font-family: Arial, Geneva, Tahoma, sans-serif;font-size:80%;}a:link,a:visited,a:hover,a:active{color:#000;}</style></head><body><div style=\"text-align:right;\"><a href=\"javascript:self.close();\" title=\"close window\">close window</a></div>");
	imageWindow.document.write("<img src=\""+url+"\" />");
	imageWindow.document.close();
	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 i,returnValue;

		for (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 (var 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) {
	for (var i=0; i<window.gs_onloadStuff.n; i++) {
		var f = window.gs_onloadStuff[i];
		if (typeof f == 'function') { f(event); }
		if (typeof f == 'string') {
			try { eval(f); } catch(err) {}
		}
	}
}
/*
 * 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;
		var old = window.onload;
		if (old != gsOnloadHandler) {
			window.onload = gsOnloadHandler;
			if (null != old) {
				gsAddOnloadCode(old);
			}
		}
	}
	window.gs_onloadStuff[window.gs_onloadStuff.n++] = code;
}

/*
 * Generic Ready handler used by gsAddReadyCode()
 */
function gsReadyHandler(event) {
	for (var i=0; i<window.gs_readyStuff.n; i++) {
		var f = window.gs_readyStuff[i];
		if (typeof f == 'function') { f(event); }
		if (typeof f == 'string') {
			try { eval(f); } catch(err) {}
		}
	}
}
/*
 * Add a function to document's Ready State callback.
 */
function gsAddReadyCode(code) {
	if (null == code) return;
	if (null == window.onDomReady) {
		window.onDomReady = DomReady;
		window.onDomReady(gsReadyHandler);
	}
	if (null == window.gs_readyStuff) {
		window.gs_readyStuff = new Array();
		window.gs_readyStuff.n = 0;
	}
	window.gs_readyStuff[window.gs_readyStuff.n++] = code;
}

//Setup the event
function DomReady(fn)
{
	//W3C
	if(document.addEventListener) {
		document.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else {
		document.onreadystatechange = function(){readyState(fn)}
	}
}

//IE execute function
function readyState(fn)
{
	//dom is ready for interaction
	if(document.readyState == "complete") {
		fn();
	}
}

// Add an image url to the preload list, to be fired when the document loads
function gsAddImagePreload(url) {
	if (null == window.gs_preloads) {
		window.gs_preloads = new Object;
		gsAddReadyCode("gsLoadPreloads();");
	}
	window.gs_preloads[url] = 1;
}
function gsLoadPreloads() {
	for (url in window.gs_preloads) {
		MM_preloadImages(url);
	}
}

// Using JQuery to toggle the universe privilege checkboxes
$(document).ready(function() {
    $('#check_all_universe_privileges').click(function() {
        $("input.universe_privilege").attr('checked', $('#check_all_universe_privileges').is(':checked'));
        
    });
});



function toggleHidden(id) {
	for (i=0; i<tablist.length; i++) {
		if (tablist[i] != id) {
			hide(tablist[i]);
		}
	}
	var section = document.getElementById(id);
	if (section.style.display == 'none')
		show(id);
}

function saveAndPublishWYSIWYG(form) {
	wp_submit_editors();
	form.submit_publish.value = 1;
	form.submit();
}

function saveWYSIWYGUnpublished(form) {
	wp_submit_editors();
	form.submit_publish.value = 0;
	form.submit();
}

function disableWYSIWYGSave(formkey) {
	var f = document.forms[formkey+'_form'];
	if (!f.is_saving) {
		f.is_saving = true;
		var s = document.getElementById(formkey+'_wp_save');
		if (s) {
			s.disabled = true;
			s.className = 'wpDisabled';
			s.onMouseOut = s.onMouseDown = '';
		}

		var sap = document.getElementById(formkey+'_sap');
		if (sap) {
			sap.className = 'wpDisabled';
			sap.onclick = sap.onMouseOut = sap.onMouseDown = '';
		}
		return true;
	}
	return false;
}

// find pos X of html element
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
		while(1) {
			curleft += obj.offsetLeft;
			if (!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
// find pos Y of html element
function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
		while (1) {
			curtop += obj.offsetTop;
			if (!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


