var PageBuilder = {
	myCookie: null,
	key : null,
	eventURL : null,
	user : null,
	save_bd : 0,
	margin : null,
	datos_sections : null,
	idPage : null,
	idSection : null,
	backme : null,
	literal : null,
	keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	init: function(root,idpage,idsecc,datos,margin,save_bd,literals,user,jsoninit,eventURL,deleteme){
		this.eventURL = eventURL;
		this.backme=new Object();
		this.literal=eval('('+literals+')');;
		this.idSection = idsecc;
		this.save_bd = save_bd;
		this.user = user;
		this.datos_sections = eval('('+datos+')');
		this.idPage = idpage;
		this.margin = margin;
		if(this.margin == null)
		{ this.margin = 0; }
		this.key=root+this.idPage;
		if(this.save_bd && this.user != 'anonimo'){this.key+='_'+this.user;}
		this.myCookie = myCookies.readCookie(this.key);
		if(this.save_bd == 1 && jsoninit!='' && this.myCookie != jsoninit)
		{ this.myCookie=jsoninit;myCookies.createCookie(this.key,jsoninit,'3000'); }
		this.setsortables();
		if(this.myCookie == null)
		{ this.saveCookie(0); this.back_htmls(); }
		this.makeinit();
		this.createitems();
		document.getElementById('content_page_'+this.idPage).style.display='block';
		if(deleteme){this.deleteme();}
	},
	deleteme:function()
	{
		var now = jQuery('#page_builder_'+this.idSection);
		while(now)
		{
			if(now.parent())
			{ now = now.parent(); }
			if(!now.get(0)){return;}
			if(now.get(0).tagName == 'BODY' || now.get(0).tagName == 'HTML'){now=null;}
			if(now != null)
			{
				var str = new String(now.attr('class'));
				if(str.match('groupItem'))
				{ now.remove();now=null; }
			}
		}
	},
	refresh:function()
	{
		document.location.href=document.location.href;
	},
	reset:function()
	{
		var doit = confirm(this.literal['sure']);
		if(doit)
		{
			myCookies.eraseCookie(this.key);
			if(this.save_bd && this.user != 'anonimo')
			{
				var vars = new Object();
				vars['delete'] = 1;
				vars['idpage'] = this.idPage;
				ajaxCaller.postForPlainText(this.eventURL+'saveJsonb64', vars, PageBuilder.refresh );
			}
			else
			{PageBuilder.refresh();}
		}
	},
	addContent:function(idsection){
		var doit=true;
		jQuery('div.groupWrapper').each(function(i){
			var re = new RegExp('content_section_'+idsection);
			if (this.innerHTML.match(re))
			{doit=false;}
		});
		if(doit)
		{
			var title = 'section '+idsection;
			if(this.datos_sections['name_'+idsection].length>0){title=this.datos_sections['name_'+idsection];}
			if(this.backme['container_section_'+idsection])
			{ jQuery('div.groupWrapper:eq(0)').prepend('<div style="margin-bottom: '+this.margin+'px;" class="groupItem "><div class="itemHeader"><div class="title_label">'+title+'</div><div onclick="javascript:PageBuilder.deleteItem(this);" class="delete"><img src="/images/point.gif" alt=""/></div><div onclick="javascript:PageBuilder.MinimizeItem(this);" class="minimize"><img src="/images/point.gif" alt=""/></div><div style="clear:both;"></div></div><div class="content"><div id="container_section_'+idsection+'">'+this.backme['container_section_'+idsection]+'</div></div></div>');
			}
			else
			{
				jQuery('div.groupWrapper:eq(0)').prepend('<div style="margin-bottom: '+this.margin+'px;" class="groupItem "><div class="itemHeader"><div class="title_label">'+title+'</div><div onclick="javascript:PageBuilder.deleteItem(this);" class="delete"><img src="/images/point.gif" alt=""/></div><div onclick="javascript:PageBuilder.MinimizeItem(this);" class="minimize"><img src="/images/point.gif" alt=""/></div><div style="clear:both;"></div></div><div class="content"><div id="container_section_'+idsection+'"><div id="content_section_'+idsection+'"></div></div></div></div>');
				eBDSection.reload(idsection,this.datos_sections['link_'+idsection]);
//				PageBuilder.newid=idsection;
//				eBDSection.show(this.datos_sections['link_'+idsection],function(html){sethtml('content_section_'+PageBuilder.newid,html);});
			}
			PageBuilder.setsortables();
			this.saveCookie();
		}
		else
		{ alert(this.literal['isthere']); }
	},
	makeinit:function(){
		this.delete_all();
		var objects = eval('('+this.decode64(this.myCookie)+')');
		for(var x=0;x<objects.length;x++)
		{
			var items = objects[x];
			for(var i=0;i<items.length;i++)
			{
				if(this.backme['container_section_'+items[i]] != null)
				{ jQuery('div.groupWrapper:eq('+x+')').append('<div style="margin-bottom: '+this.margin+'px;" class="groupItem "><div id="container_section_'+items[i]+'">'+this.backme['container_section_'+items[i]]+'</div></div>'); }
				else if(this.datos_sections['link_'+items[i]] != null)
				{
					jQuery('div.groupWrapper:eq('+x+')').append('<div style="margin-bottom: '+this.margin+'px;" class="groupItem "><div id="container_section_'+items[i]+'"><div id="content_section_'+items[i]+'"></div></div></div>');
					eBDSection.reload(items[i],this.datos_sections['link_'+items[i]]);
				}
			}
		}
	},
	MinimizeItem:function(href){
		if(href.parentNode.parentNode.childNodes[1] != null && href.parentNode.parentNode.childNodes[1].childNodes[0].id.length>0)
		{ jQuery('#'+href.parentNode.parentNode.childNodes[1].childNodes[0].id).toggle(300,function(){if(this.style.display == 'none'){jQuery('.minimize',href.parentNode).addClass('maximize');jQuery('.minimize',href.parentNode).removeClass('minimize');}else{jQuery('.maximize',href.parentNode).addClass('minimize');jQuery('.maximize',href.parentNode).removeClass('maximize');}}); }
	},
	deleteItem:function(href){
		href=href.parentNode.parentNode;
		var re = new RegExp('content_section_'+this.idSection);
		if (!href.innerHTML.match(re)) {
			href.id = 'todelete';
			jQuery('#todelete').remove();
			this.saveCookie();
		}
		else
		{alert(this.literal['nodelete']);}
	},
	back_htmls:function(){
		jQuery("div.groupItem").each(function(i){
			if(jQuery(this).children()[0] != null)
			{ PageBuilder.backme[jQuery(jQuery(this).children()[0]).attr('id')] = jQuery(jQuery(this).children()[0]).html(); }
		});
	},
	delete_all:function(){
		this.back_htmls();
		jQuery('div.groupWrapper').empty();
	},
	saveCookie:function(first){
		if(first == null){first=6;}
		var json = '[';
		jQuery('div.groupWrapper').each(function (i)
		{
			if(json.length>1){json+=',';}
			json+='[';
			var obj='';
			jQuery('div.groupItem',this).each(function(i)
			{
				var divs = jQuery('div',this);
				if(divs[first])
				{
					var lista = divs[first].id.match(/^container_section_(\d+)$/i);
					if(lista)
					{
						if(obj.length>0)
						{obj+=',';}
						obj+=lista[1];
					}
				}
			});
//			this.style.height='';
//			if(obj.length == 0){this.style.height='50px';}
			json+=obj+']';
		});
		json+=']';
		json = this.encode64(json);
		if(this.save_bd && this.user != 'anonimo')
		{
			var vars = new Object();
			vars['json'] = json;
			vars['idpage'] = this.idPage;
			ajaxCaller.postForPlainText(this.eventURL+'saveJsonb64', vars, function(){},true );
		}
		this.myCookie=json;
		myCookies.createCookie(this.key,json,'3000');
	},

	createitems:function(){
		jQuery("div.groupItem").each(function(i){
			var title = 'section';
			var del = 'onclick="javascript:PageBuilder.deleteItem(this);" class="delete"';
			if(this.childNodes[0] != null)
			{
				var str = new String(this.childNodes[0].id);
				var x = str.match(/^container_section_(\d+)$/);
				if(x != null)
				{
					if(x[1] == PageBuilder.idSection){del='onclick="javascript:PageBuilder.reset();" class="reset" title="'+PageBuilder.literal['title_reset']+'"';}
					if(PageBuilder.datos_sections['name_'+x[1]] != null)
					{ title = PageBuilder.datos_sections['name_'+x[1]]; }
					else
					{title+=' '+x[1];}
				}
			}
			this.innerHTML = '<div class="itemHeader"><div class="title_label">'+title+'</div><div '+del+'><img src="/images/point.gif" alt=""/></div><div class="minimize" onclick="javascript:PageBuilder.MinimizeItem(this);"><img src="/images/point.gif" alt=""/></div><div style="clear:both;"></div></div><div class="content">'+this.innerHTML+'</div>';
		});
		PageBuilder.setsortables();
	},
	setsortables:function(){

		var todos = jQuery('#content_page_'+this.idPage).children().children();
		for(var x=0;x<todos.length;x++)
		{

			if(!jQuery(todos[x]).attr('id'))
			{
				var str = new String(todos[x].style.width);
				if(str.match('%')){jQuery(todos[x]).addClass('groupWrapper');}
			}
		}


		jQuery('div.groupWrapper').Sortable({
					accept: 'groupItem',
					helperclass: 'sortHelper',
					handle: 'div.itemHeader',
					tolerance: 'pointer',
					onStop : function()
					{ PageBuilder.saveCookie(); }
		});
	},
	encode64:function(input){
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		do
		{
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2))
			{
				enc3 = enc4 = 64;
			}
			else if (isNaN(chr3))
			{
				enc4 = 64;
			}

			output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) +
			this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
		} while (i < input.length);

		return output;
	},
	decode64:function(input){
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
		input = input.replace(/[^A-Za-z0-9\+\/\=_]/g, "");

		do
		{
			enc1 = this.keyStr.indexOf(input.charAt(i++));
			enc2 = this.keyStr.indexOf(input.charAt(i++));
			enc3 = this.keyStr.indexOf(input.charAt(i++));
			enc4 = this.keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64)
			{ output = output + String.fromCharCode(chr2); }
			if (enc4 != 64)
			{ output = output + String.fromCharCode(chr3); }
		} while (i < input.length);

		return output;
	}
};

