// Admin common scripts

var globalID='';
var globalSuccessID='';
var globalType='';

//var popupTop=new Element('div',{'class': 'popup-top'});
var popupTop=$("<div class=\"popup-top\"> </div>");
//var popupBottom=new Element('div',{'class': 'popup-bottom'});
var popupBottom=$("<div class=\"popup-bottom\"> </div>");
//var confirmPadding=new Element('div',{'class': 'confirm-padding'});
var confirmPadding=$("<div class=\"confirm-padding\"> </div>");
//var progressBar=new Element('div',{id: 'progress'});
var progressBar=$("<div id=\"progress\"> </div>");


/**
 * o		Object of button pushed
 * id		ID of container to receive return results
 * type		Matches PHP page class name
 * bShowPopup		bShowPopup
 * bPoll	Whether this request is going to require polling and a progress bar
 *
 */
function submitThisForm(o,type,id,bShowPopup,successID,bPoll)
{
	if (o) { clearButtons(o); }
	if (!o.form) {
		o=$('#'+o)
		o=o[0];
	}
	var thisForm=$(o.form) ,i;
	var formVars = ajax.getForm(thisForm[0]);
	globalID=id;
	globalSuccessID=successID;
	globalType=type;
	if (bPoll) {
		ajax.abort_timeout=-1;
		//ajax.ignoreCall=1;
		//ajax.failed_threshold=10000; // Silly high number
	}
	ajax.call('action='+type+formVars,function(resp){
		$('#popup').html('');
		if (resp&&$('#'+globalID)) {
			//!!! Somwhere here to check if response is an array or not
			if (resp.resp) {
				if (resp.bSuccess&&resp.bSuccess===true) {
					$('#'+globalSuccessID).html(resp.resp);
					hidePopup();
				}
				else
					$('#'+globalID).html(resp.resp);
			}
			else
				$('#'+globalID).html(resp);
//			initNavigation();
			initStripeTbl('results');
			if (window.initExtra)
				initExtra();
			initGlobalMsg();
		}
		else if (!resp && resp!==null){//=='false')
			window.location=window.location;
			return;
		}
		else if (resp===null) {
			hidePopup();
			initGlobalMsg();
		}		
//		initTipPopout();
		
		hideLoading();
	});
	if (bShowPopup) { showPopup(); }
	else { hidePopup(); }
	
	return false;

}

function doOutput(resp)
{
	$('#popup').html('');
	if (resp&&$('#'+globalID)) {
		//!!! Somwhere here to check if response is an array or not
		if (resp.resp)
			$('#'+globalID).html(resp.resp);
		else
			$('#'+globalID).html(resp);
//		initNavigation();
		initStripeTbl('results');
		if (window.initExtra)
			initExtra();
		initGlobalMsg();
	}
	else if (!resp && resp!==null){//=='false')
		window.location=window.location;
		return;
	}
	else if (resp===null) {
		hidePopup();
		initGlobalMsg();
	}
	
	hideLoading();
}
/**
 * Function to return a network error message
 *
 *
 */
 
function getNetworkStatus()
{
	setPopup('<p>Sorry, this last command was not received correctly. Please refresh the page and try again</p>'
										 +'<form action="./index.php" method="post" enctype="multipart/form-data">'
										 +'<div class="buttonset">'
										 +'<input class="btn action" type="image" src="../_image/cancel.gif" name="GlobalForm[Action][Cancel]" id="GlobalFormPopup_Cancel" value="OK" onclick="hidePopup();" />'
										 +'</div></form>'
										 +'<div class="clearall"> </div>');
//	popupTop.inject($('#popup'));
//	popupBottom.inject(popupTop);
//	confirmPadding.set('html', '<p>Sorry, this last command was not received correctly. Please refresh the page and try again</p>'
//										 +'<form action="./index.php" method="post" enctype="multipart/form-data">'
//										 +'<div class="buttonset">'
//										 +'<input class="btn action" type="image" src="../_image/cancel.gif" name="GlobalForm[Action][Cancel]" id="GlobalFormPopup_Cancel" value="OK" onclick="hidePopup();" />'
//										 +'</div></form>'
//										 +'<div class="clearall"> </div>'
//										 );
//	confirmPadding.inject(popupBottom);
	showPopup();
}
/**
 * id		ID of Form
 * type		Matches PHP page class name
 * contID	ID of container to receive return results
 * o		Object of button pushed
 * b		bShowPopup
 *
 */
function submitForm(id,type,contID,o,b)
{
	if (o) { clearButtons(o); }
	var formVars = ajax.getForm(id);
//	alert(formVars);
	globalID=contID;
	globalType=type;
	ajax.call('action='+type+formVars,doOutput);
	if (b) { showPopup(); }
	else { hidePopup(); }
//	ajax.call('action='+type+formVars,id);

	return false;
}

/*
 *
 * Function to start the polling process.
 * Creates a file of name SessID.transfer
 * Polls every second until file no longer exists
 * Stop
 *
 */
function startPoll() {
	var ProgressID=readCookie('SessionID');
	var sFile='_progress/'+ProgressID+'.transfer';
	var poll = new Request.HTML({
			url:'./_php/file_put_contents.php'
		}).post({
			'filename': '/admin/'+sFile,'html':'1'
		});

		
//	$('popup').innerHTML='<div class="popup-top"><div class="popup-bottom"><div class="confirm-padding"><div id="progress"></div><h3>Loading...</h3></div></div></div>';
	$('#popup').innerHTML='';
	popupTop.inject($('#popup'));
	popupBottom.inject(popupTop);
	confirmPadding.set('html', '<h3>Transferring data to CreateSend</h3>');
	confirmPadding.inject(popupBottom);
	progressBar.inject(confirmPadding);
	
	ajax.abort_timeout=-1;
	//$('popup').innerHTML='';
	var percent=1;
	var pb = new ProgressBar({
		container: $('progress'),
		startPercentage: percent,
		speed:1000,
		boxID: 'box',
		percentageID: 'perc'
		});
	var progress = new Request({method: 'get'
		,url: sFile
		,initialDelay: 1000
		,delay: 500
		,onSuccess: function(response){
			showPopup();
			if (!response||response=='') {
				this.stopTimer();
				//var percent=99;
				//pb.set(percent);
				hidePopup();
				return;
			}
			percent=response.toInt();
			pb.set(percent);
			}
		,onFailure: function(){
				this.stopTimer();
				hidePopup();
			}
		}).startTimer();	
	hidePopup();
	
}

function readCookie(name) {
	var cookiename = name + "=";
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);
	}
	return null;
}

function initGlobalMsg(){
	ajax.call('action=GlobalMsg',doMsgOutput);
}

//window.addEvent('domready',initGlobalMsg);
$(document).ready(initGlobalMsg);


function doMsgOutput(resp)
{
	if ($('#GlobalMsg')) {
		$('#GlobalMsg').html(resp);
		if (resp)
			$('#GlobalMsg').css('display', 'block');
		else
			$('#GlobalMsg').css('display', 'none');
	}
}



function clearButtons(ob)
{
	// Find all buttons in this form
	// Clear all apart from this one
	var o=ob;
	if (!o.form) {
		o=$('#'+o)
		o=o[0];
	}
	var thisForm=$(o.form) ,i;

	thisForm.each(function(){
		var aInput = $(this).find('input');
		aInput.each(function(){
			if (this.type!="submit"&&this.type!="image"&&this.type!="button")
				return;
			if (this.id==o.id)
				return;
			this.name='';
		});
	});
		
}

function parseGetVars() {
	var getVars = new Array();
	var qString = unescape(top.location.search.substring(1));
	var pairs = qString.split(/\&/);
	for (i=0;i<pairs.length;i++) {
//	for (var i in pairs) {
		var nameVal = pairs[i].split(/\=/);
		getVars[nameVal[0]] = nameVal[1];
	}	
	return getVars;
}
	
function initExtra() {
	$("table:even").addClass("td_odd");
	var sURL = document.URL;
	var bAdmin = sURL.indexOf('admin');
	if (bAdmin != -1)
		return;
	ajax.call('action=Cart&CartForm%5BAction%5D%5BViewShortCart%5D=View',function(resp){
		if ($('#cart')) {
			$('#cart').html(resp);
		}
	});
}

$(document).ready(function(){
	var sReferrer = document.referrer;
	var sURL = document.URL;
	var bUnify = sReferrer.indexOf('unify');
	var bAdmin = sURL.indexOf('admin');
	if (bUnify != -1 || bAdmin != -1)
		return;
//	globalID='cart_update';
//	globalType='Cart';
//	ajax.call('action=Cart',doOutput);
	if ($('#CartForm_Default').length>0)
		submitThisForm('CartForm_Default','Cart','cart_update');
	if ($('#cart')) {
		ajax.call('action=Cart&CartForm%5BAction%5D%5BViewShortCart%5D=View',function(resp){
	//		if ($('#cart')) {
				$('#cart').html(resp);
	//		}
		});
	}
});



