/*

	Ajax Saver for Google Gears
	2009-10-10 Rafal Mikolajczak
	
	usage:
	asg.submit("ajax_saver.php?x=y","spostvar=abc&anotherpostvar=xyz","saving user data");
	anywhere at anytime, multiple calls allowed

	requires:
	jQuery
	Google Gears
	
*/

var asg_loaded = false;
var asg_indicator = true;

if(typeof(google) == "undefined") {
	
	//slimak-mode
	var asg_ops = new Array();
	var asg_opcounter = 0;
	
	function asg_op (idop,sget,spost,sinfo) {
		this.idop = idop;
		this.sget = sget;
		this.spost = spost;
		this.sinfo = sinfo;
	}
	
	function asg_ready_to_leave() {
		return asg_check_all_done();
	}
	
	//checks if all save ops are completed
	function asg_check_all_done() {
		if(asg_ops.length>0) return false;
		if (typeof jQuery != 'undefined') $('img#asg_icon').attr('src','/img/gears/done.gif');
		return true;
	}
	
	//submits a save
	function asg_submit_method(sget,spost,sinfo) {
		asg_opcounter++;
		asg_ops[asg_opcounter] = new asg_op(asg_opcounter,sget,spost,sinfo);
		if (typeof jQuery != 'undefined') $('img#asg_icon').attr('src','/img/gears/gears.gif');
		setTimeout('asg.donext();',300);
   }
	
	function asg_do_next() {
		if(this.idop>0) return;
		if(asg_ops.length>0) {
			var aop = asg_ops[0];
			this.idop = aop.idop;
			
			if (typeof jQuery != 'undefined') $('div#asg_target').text(aop.sinfo);
			if(asg_indicator) {
				$('div#asg_box').fadeIn();
				$('div#asg_target').fadeIn();
			}
			
			this.ohttp = asg_gethttpobject();
			this.ohttp.open("POST", aop.sget, true);
			this.ohttp.onreadystatechange = asg_handleresponse;
			this.ohttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			//this.ohttp.send(rs.field(2));
			setTimeout("asg.ohttp.send('"+aop.spost+"');",200);
		}
		else {
			if (typeof jQuery != 'undefined') $('img#asg_icon').attr('src','/img/gears/done.gif');
			setTimeout('asg.slideoff();',2000);
		}
	}

	function asg_clear_done_op(idop) {
		asg_ops.splice(0,1);
		asg.idop = 0;
	}
	
	function asg_retry_op(idop) {
		var aop = asg_ops[0];
		if (typeof jQuery != 'undefined') $('div#asg_target').text('RETRY: '+aop.sinfo);
		this.ohttp = asg_gethttpobject();
		this.ohttp.open("POST", aop.sget, true);
		this.ohttp.onreadystatechange = asg_handleresponse;
		this.ohttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		setTimeout("asg.ohttp.send('"+aop.spost+"');",2000);
	}
	
}
else {
	
	//TURBO GEARS MODE
	var db = google.gears.factory.create('beta.database');
	db.open('database-test');
	//db.execute('drop table if exists ASGops');
	db.execute('create table if not exists ASGops (idop INTEGER PRIMARY KEY, sget TEXT, spost TEXT, sinfo TEXT, ntry INTEGER,tqueued INTEGER)');
	//db.execute('delete from ASGops where ntry>99');
	/*
	db.execute("insert into ASGops (Sget,Spost,Sinfo,Tqueued) values ('ajax_ok.php','x=y&a=b','testing...',"+new Date().getTime()+")");
	var rs = db.execute('select * from ASGops order by Tqueued');
	while (rs.isValidRow()) {
	  document.write(rs.field(0) + ' | ' + rs.field(1) + '<br />');
	  rs.next();
	}
	rs.close();
	*/
	
	function asg_ready_to_leave() {
		return true;
	}
	
	//checks if all save ops are completed
	function asg_check_all_done() {
		var rs = db.execute('select count(*) as ncount from ASGops');
		var ncnt = 0;
		if(rs.isValidRow()) ncnt = rs.field(0);
		rs.close();
		if(ncnt>0) return false;
		if (typeof jQuery != 'undefined') {
			if($('img#asg_icon').css('src')!='/img/gears/warning.gif')
			$('img#asg_icon').attr('src','/img/gears/done.gif');
		}
		return true;
	}
	
	//submits a save
	function asg_submit_method(sget,spost,sinfo) {
		db.execute("insert into ASGops (sget,spost,sinfo,ntry,tqueued) values ('"+sget+"','"+spost+"','"+sinfo+"',0,"+new Date().getTime()+")");
		if (typeof jQuery != 'undefined') $('img#asg_icon').attr('src','/img/gears/gears.gif');
		setTimeout('asg.donext();',300);
   }
	
	function asg_do_next() {
		if(this.idop>0) return;
		var rs = db.execute('select idop,sget,spost,sinfo from ASGops order by ntry,idop limit 1');
		if(rs.isValidRow()) {
			this.idop = rs.field(0);
			
			if (typeof jQuery != 'undefined') $('div#asg_target').text(rs.field(3));
			if (typeof jQuery != 'undefined') if(asg_indicator) {
				$('div#asg_box').fadeIn();
				$('div#asg_target').fadeIn();
			}
			
			this.ohttp = asg_gethttpobject();
			//alert('sget='+rs.field(1));
			this.ohttp.open("POST", rs.field(1), true);
			this.ohttp.onreadystatechange = asg_handleresponse;
			this.ohttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			//this.ohttp.send(rs.field(2));
			setTimeout("asg.ohttp.send('"+rs.field(2)+"');",200);
		
			rs.close();
			db.execute('update ASGops set ntry=ntry+1 where idop='+this.idop);
		}
		else {
			//if($('img#asg_icon').css('src')!='/img/gears/warning.gif')
			//$('img#asg_icon').attr('src','/img/gears/done.gif');
			setTimeout('asg.slideoff();',2000);
		}
	}

	function asg_clear_done_op(idop) {
		db.execute('delete from ASGops where idop='+asg.idop);
		asg.idop = 0;
	}
	
	function asg_retry_op(idop) {
		db.execute('update ASGops set ntry=ntry+1, tqueued='+new Date().getTime()+' where idop='+asg.idop);
		//db.execute('delete from ASGops where idop='+asg.idop);
		asg.idop = 0;
	}
	
}


//COMMON UNIVERSAL METHODS

	function asg_do_when_all_done(script) {
		if(asg_check_all_done()) eval(script);
		else setTimeout('asg_do_when_all_done("'+script+'")',1000);
	}
	
	function asg_do_when_ready_to_leave(script) {
		if(asg_ready_to_leave()) eval(script);
		else setTimeout('asg_do_when_ready_to_leave("'+script+'")',1000);
	}
	
   //handles http object response
	function asg_handleresponse() {
		var httpobj = asg.ohttp;
		if(httpobj.readyState==4) {
			
			/* wyciagamy javascript */
			var strippedresponse = '';
			var buf = httpobj.responseText;
			var i=1;
			while(buf.indexOf("<script ")>0) {
				strippedresponse+= buf.substring(0,buf.indexOf("<script "));
				var sodscript = buf.substring(buf.indexOf("<script "),buf.length);
				var sodpoczatku = sodscript.substring(sodscript.indexOf(">")+1,sodscript.length);
				var sjustscript = sodpoczatku.substring(1,sodpoczatku.indexOf("</script>"));
				i++;
				setTimeout(sjustscript,i*100);
				buf = buf.substring(buf.indexOf("<script ")+sodscript.indexOf(">")+sodpoczatku.indexOf("</script>")+10,buf.length);
			}
			strippedresponse+= buf;
			//$('div#asg_target').text(httpobj.responseText);
			if (typeof jQuery != 'undefined') $('div#asg_target').text(strippedresponse);

			if(httpobj.responseText.substring(0,3)=='OK:') {
				asg_clear_done_op(asg.idop);
				setTimeout('asg.donext();',300);
			}
			else {
				if (typeof jQuery != 'undefined') {
					$('img#asg_icon').attr('src','/img/gears/warning.gif');
					$('img#asg_icon').attr('title','click to cancel operation');
					$('img#asg_icon').css('cursor','pointer');
					$('img#asg_icon').click(function(){ asg_clear_done_op(asg.idop); asg.donext(); });
					$('div#asg_box').fadeIn();
					$('div#asg_target').fadeIn();
				}
				if(httpobj.responseText.substring(0,6)=='SORRY:') setTimeout('asg_clear_done_op('+asg.idop+'); asg.donext();',5000);
				else setTimeout('asg_retry_op('+asg.idop+'); asg.donext();',5000);
			}
		}
	}

	function asg_slideoff() {
		if(this.idop>0) return;
		if (typeof jQuery != 'undefined') {
			if(asg_check_all_done()) 
			$('div#asg_target').fadeOut();
			$('div#asg_box').fadeOut();
		}
	}
	
	//creates http object
	function asg_gethttpobject() {
  		var xmlhttp;
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (E) {
            xmlhttp = false;
			}
		}
      if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			try {
				xmlhttp = new XMLHttpRequest();
         } catch (e) {
				xmlhttp = false;
         }
		}
      return xmlhttp;
   }

	//object constructor
	function ajaxSaverObject() {
		
		//public
		this.submit = asg_submit_method;
		this.alldone = asg_check_all_done;
		
		//private
		this.handleresponse = asg_handleresponse;
		this.donext = asg_do_next;
		this.slideoff = asg_slideoff;
		this.idop = 0;
		this.clearop = asg_clear_done_op;

		//PREPARE
		document.write("<div id=\"asg_box\" name=\"asg_box\" style=\"position:absolute; top:0; left:0; z-index:900; background-color:#ffffff; ");
		document.write("border:#000055 1px solid; padding:10px; text-align:center; width:200px; display:none;\">");
		document.write('<img id="asg_icon" name="asg_icon" src="/img/gears/gears.gif" align="left" />');
		document.write("<div id=\"asg_target\" name=\"asg_target\">&nbsp;</div></div>");
	}

	asg = new ajaxSaverObject();
	asg_loaded = true;
	setTimeout('asg.donext();',2000);
	
	//helpfull
	function ajax_submit(sget,spost,sinfo) {
		asg.submit(sget,spost,sinfo);
	}
	
	function ajax_dowhendone(script) {
		asg_do_when_all_done(script);
	}
	
	function ajax_doasap(script) {
		asg_do_when_ready_to_leave(script);
	}
	
	