// JavaScript Document



var currentPost;
var currentEditor;
var newTitle;
var removalCandidate;



var th = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','/js/common.js');
th.appendChild(s);

var s = document.createElement('link');
s.setAttribute('type','text/css');
s.setAttribute('rel','stylesheet');
s.setAttribute('href','/styles/common/admin.css');
th.appendChild(s);
var fieldInfo = [];

function adminLogout(){
	
	
		new Ajax.Request('/connector.php', {
		  parameters: { req:'adminLogout'},
		  onComplete: function(transport){
			var resData = JSON.parse( transport.responseText );
			try{var resData = JSON.parse( transport.responseText );} catch(e){ alert(transport.responseText);}
			if(resData.success){
				Modalbox.show('<div>Sie haben sie ausgeloggt</div>', {title: 'ADMIN PANEL'});
				setTimeout("Modalbox.hide();",1500);	
				destroyAdmin();
			}
				
		}});
	
}

function adminLogin(step2){
	
	if(step2){
		$('adminForm').down('div#formDiv').hide();
		new Ajax.Request('/connector.php', {
		  parameters: { req:'adminLogin', name:$('adminNameInput').getValue(), pw:$('adminPwInput').getValue()},
		  onComplete: function(transport){
			var resData = JSON.parse( transport.responseText );
			try{var resData = JSON.parse( transport.responseText );} catch(e){ alert(transport.responseText);}
			if(resData.success){$('adminForm').down('div#resDiv').update("Login erfolgreich!"); setTimeout("Modalbox.hide(); setupAdmin();",1500);}
			else{$('adminForm').down('div#resDiv').update("Falscher Login!"); setTimeout("$('adminForm').down('div#formDiv').show()",1500); setTimeout("$('adminForm').down('div#resDiv').update('');",1500);}
			
		}});
		return;
	}

	Modalbox.show('<div id="adminForm"><h3>Bitte geben sie die Administrator - Login Daten ein:</h3><div id="resDiv"></div><div id="formDiv"><input style="margin:1px" type="text" id="adminNameInput" name="name"><input style="margin:1px" type="password" id="adminPwInput" name="pw"><div style="margin-top:2px"><button onclick="Modalbox.hide();" class="minibutton"><span>abbrechen</span></button> <button onclick="adminLogin(1);" class="minibutton blue"><span>weiter</span></button></div></div></div><script language="javscript">addInactiveTextToInput("adminNameInput","Admin Name"); addInactiveTextToInput("adminPwInput","Passwort"); </script>', {title: 'ADMIN LOGIN'});
		
	
}


function setupList(){
	
	for(var i in newsItems){
		if(newsItems[i].className == "newsItem"){
			
			//newsItems[i].onMouseOut=adminUnHover(newsItems[i]);
			newsItems[i].insert({top:"<div id='buttonsTop' style='display:none; position:absolute; margin-top:1px; background-color:#ffffff; clear:none; text-align:right; padding:2px; float:right'><button onclick='startPostEdit();' class='minibutton' name='code' value='de'><span>Bearbeiten</span></button> <button onclick='deletePost()'; class='minibutton' name='code' value='de'><span>L&ouml;schen</span></button></div>"}) ;
			newsItems[i].insert({top:"<img src='/images/drag.png' id='dragButton' style='display:none; position:absolute; left:2px; top:2px; cursor:move; clear:none; text-align:left; float:left'/>"});
			newsItems[i].writeAttribute({'onMouseOver':'adminHover(this)'});
			newsItems[i].writeAttribute({'onMouseOut':'adminUnHover(this)'});
			
			
		}
	
	}
	$('addPostBtnFrame').appear();
	//Sortable.create("newsArea",{tag:'div', handles:$$('#newsArea #dragButton'), onUpdate:saveOrder});//{handles:$$('#newsArea img')} function(sortable){alert(Sortable.serialize(sortable))}
		
		
	
		//	
	
		
}



function setupSingleItem(element,dbTable){
	
		element.insert({top:"<div id='buttonsTop' style='display:none; position:absolute; margin-top:-25px; background-color:#ffffff; clear:none; text-align:right; padding:2px; float:right'><button onclick='startPostEdit();' class='minibutton' name='code' value='de'><span>Bearbeiten</span></button></div>"}) ;
	//	element.insert({top:"<img src='/images/drag.png' id='dragButton' style='display:none; position:absolute; left:2px; top:2px; cursor:move; clear:none; text-align:left; float:left'/>"});
		element.writeAttribute({'onMouseOver':'adminHover(this)'});
		element.writeAttribute({'onMouseOut':'adminUnHover(this)'});
		element.writeAttribute({'dbTable':dbTable});
		element.addClassName('areaEditable');
		
		fieldInfo[element.getAttribute('id')] = [{id:'title_de',type:'text'},{id:'content_de',type:'html'}];
}

function setupAdmin(){
	
	//var list1Items = $('body').getElementsByClassName('list1Items');
	//setupList(list1Items);
	setupSingleItem($('mainContent'),'articles');
	$(document.body).insert({bottom:"<div id='adminToolbar'> <button onclick='adminLogout();' class='minibutton' name='code' value='de'><span>Logout</span></button><button onclick='adminMakePage();' class='minibutton' name='code' value='de'><span>Neue Seiter erstellen</span></button></div>"}) ;
	//var my_div = document.createElement('div',{id:"adminToolbar"});
	//my_div.update("<button onclick='startPostEdit();' class='minibutton' name='code' value='de'><span>Logout</span></button>");
	//Element.extend(my_div);
	//document.body.appendChild(my_div);
	
}


function destroyAdmin(){
	
	//var list1Items = $('body').getElementsByClassName('list1Items');
	//setupList(list1Items);
	//setupSingleItem($('mainContent'),'articles');
	document.reload();
	
}


function saveOrder(){
	
	
	
	new Ajax.Request('/connector.php', {
		  parameters: { req:'saveOrder', order:Sortable.sequence('newsArea').join(',')},
		  onComplete: function(transport){
			try{var resData = JSON.parse( transport.responseText );} catch(e){ alert(transport.responseText);}
			
			if(resData.success){
				//Modalbox.show('<p>Neue Reihenfolge gespeichert</p>', {title: 'ACHTUNG'});
				//setTimeout("Modalbox.hide();",3000);
			}
					
		}});
	
}

function adminHover(postLayer){
	if(currentPost || currentEditor || removalCandidate){return;}
	currentPost = postLayer;
	try{postLayer.down('img#dragButton').show();} catch(e){}
	postLayer.down('div#buttonsTop').show();
	postLayer.addClassName('areaEditableHover');
	postLayer.addClassName({'class':'postEdit'})
}

function adminUnHover(postLayer){
	if(currentEditor || removalCandidate){return;}
	postLayer.down('div#buttonsTop').hide();
	try{postLayer.down('img#dragButton').hide();} catch(e){}
	postLayer.addClassName({'class':'newsItem'});
	postLayer.removeClassName('areaEditableHover');
	postLayer.setStyle({'backgroundColor':''});
	currentPost=null;
}


function startPostEdit(){
	
	
	
	//currentPost.morph('background:#d6e4f0; color:#fff; duration: 0.1');
	currentPost.writeAttribute({'onMouseOver':''});
	currentPost.writeAttribute({'onMouseOut':''});
	currentPost.insert({bottom:"<div id='buttonsBottom' style='background-color:#ffffff; margin-top:-36px; clear:none; text-align:right; padding:2px; float:right'><button onclick='stopPostEdit();' class='minibutton' name='code' value='de'><span>abbrechen</span></button> <button class='minibutton blue' onclick='savePostEdit();' name='code' value='de'><span>Speichern</span></button></div>"}) ;
	currentPost.down('div#buttonsTop').hide();
	try{currentPost.down('img#dragButton').hide();} catch(e){}
	currentPost.down('div#buttonsBottom').morph('background:#d6e4f0; color:#fff; duration: 0.3');
	
	
	
	var fInfo = fieldInfo[currentPost.getAttribute('id')];
	
	for(var i in fInfo){
		
		if(fInfo[i].type=="html"){
			var oldHTML = currentPost.down('div#'+fInfo[i].id).innerHTML;
			currentPost.down('div#'+fInfo[i].id).writeAttribute({'id':'currentText'});
			currentPost.down('div#currentText').writeAttribute({'oldVal':oldHTML});
			currentEditor = CKEDITOR.replace( 'currentText' );
		}
		else if(fInfo[i].type=="text"){
			var oldTitle=currentPost.down('div#'+fInfo[i].id).innerHTML;
			currentPost.down('div#'+fInfo[i].id).update("<input type='text' onchange='dupeVal(this,this.value)' id='currentTitle' name='title' style='width:100%;' value='"+oldTitle+"'/>");
			currentPost.down('div#'+fInfo[i].id).writeAttribute({'oldVal':oldTitle});
			//updateTitle(oldTitle);
			$('currentTitle').activate();
		}
		
		if(!fInfo[i].id){break;}
	}
	
	
	
	/*
	oldDateTime=currentPost.down('div#dateTime').innerHTML;
	var parts = oldDateTime.split(" | ");
	c=parts[0].replace("[","");
	d=parts[1].replace(" Uhr]","");
	
	var times = "";
	for(i=0;i<=23;i++){o=i.toString(); 
		if(o.length==1){o="0"+o;}
		selected1=""; selected2="";
		if(o+":00"==d){selected1="selected";} if(o+":30"==d){selected2="selected";}
		times+="<option "+selected1+" value='"+o+":00'>"+o+":00 Uhr</option><option "+selected2+" value='"+o+":30'>"+o+":30 Uhr</option>"
	}
	
	currentPost.down('div#dateTime').update("<select id='currentTime' name='time' style='width:45; margin:2px'>"+times+"</select><input type='text' id='currentDate' name='date' style='width:45%; margin:2px' value='"+c+"'>");
*/
	
	
	
	//currentPost.down('div#textContainer').setStyle({'marginBottom':'15px'});
	//Modalbox.show("xxx");
	
}


function deletePost(confirmed){
	
	currentPost.writeAttribute({'onMouseOver':''});
	currentPost.writeAttribute({'onMouseOut':''});
	
	removalCandidate = currentPost;
	
	
	if(!confirmed){
		Modalbox.show('Soll dieser Eintrag wirklich gel&ouml;scht werden?<br><button onclick="Modalbox.hide(); cancelDelete();" class="minibutton"><span>Abbrechen</span></button> <button onclick="deletePost(1); Modalbox.hide();" class="minibutton blue"><span>L&ouml;schen</span></button>', {title: 'ACHTUNG'});
	}
	else{
		new Ajax.Request('/connector.php', {
		  parameters: { 'req': 'removePost', 'id': currentPost.down('input#postId').getValue()},
		  onSuccess: function(transport) {
			removalCandidate.remove();
			removalCandidate=null;
			//alert('Form data saved: '+transport.responseText)
		  }
		});

		
	}
	//Modalbox.show('Soll dieser Eintrag wirklich gel&ouml;scht werden?', {title: 'Achtung'});
}


function cancelDelete(){
	removalCandidate.writeAttribute({'onMouseOver':'adminHover(this)'});
	removalCandidate.writeAttribute({'onMouseOut':'adminUnHover(this)'});	
	adminUnHover(removalCandidate);
	removalCandidate=null;
}

function dupeVal(t,val){
	
	t.writeAttribute({'newVal':val});
}





function makeNewPost(){
	
	//var useHTML = $('newsArea').down('.newsItem').innerHTML;
	
	
	var clone = new Element('div');
	clone.update("<div class='newsItem'>"+$('newsArea').down('.newsItem').innerHTML+"</div>");
	$('newsArea').insert({top:clone}) ;
	$('addPostBtnFrame').hide();

	adminHover($('newsArea').down('.newsItem'));
	currentPost.down('div#title').update('');
	
	var t = new Date()
	var hours = t.getHours()
	var minutes = t.getMinutes()
	if(minutes>30){minutes=30;} else {minutes=0;}
	
	
	currentPost.down('div#dateTime').update('['+t.getDate()+'.'+(t.getMonth()+1)+'.'+t.getFullYear()+' | '+hours+':'+minutes+' Uhr]');
	currentPost.down('input#postId').writeAttribute({'value':'0'});
	currentPost.down('div#content').update('');
	startPostEdit();
}

function stopPostEdit(save){
	
		
	currentPost.down('div#buttonsBottom').remove();
	currentPost.down('div#buttonsTop').show();
	try{currentPost.down('img#dragButton').show();} catch(e){}
	currentPost.setStyle({'backgroundColor':'#fff'});
	currentPost.writeAttribute({'onMouseOver':'adminHover(this)'});
	currentPost.writeAttribute({'onMouseOut':'adminUnHover(this)'});
	
 	try{currentEditor.destroy();} catch(e){}
	//currentPost.down('div#dateTime').update("["+currentPost.down('input#currentDate').getValue()+" | "+currentPost.down('select#currentTime').getValue()+"Uhr ]");
	
	
	
	var fInfo = fieldInfo[currentPost.getAttribute('id')];
	var newVal;
	
	for(var i in fInfo){
		newVal = "";
		
		if(!fInfo[i].id){break;}
		if(fInfo[i].type=="html"){	$('currentText').writeAttribute({'id':fInfo[i].id}); }	
		if(fInfo[i].type=="text"){newVal = currentPost.down('div#'+fInfo[i].id).firstDescendant().getValue();}
		
		if(save){if(newVal){currentPost.down('div#'+fInfo[i].id).update(newVal);}}
		else{currentPost.down('div#'+fInfo[i].id).update(currentPost.down('div#'+fInfo[i].id).getAttribute('oldVal'));}
		
	}
	
	
	
	
	
	//if(!currentPost.down('div#content').innerHTML){currentPost.remove(); currentPost = null;}
	try{$('addPostBtnFrame').show();} catch(e){}
	currentEditor=null;
	adminUnHover(currentPost);
}

function savePostEdit(){
	
	var newForm = new Element('form', { 'action': '/connector.php'})
	var fInfo = fieldInfo[currentPost.getAttribute('id')];
	
	for(var i in fInfo){
		
		if(fInfo[i].type=="html"){
			newForm.insert(new Element('input', { 'type': 'hidden', 'value': currentEditor.getData(),'name':fInfo[i].id }));
		}
		else if(fInfo[i].type=="text"){
			newForm.insert(new Element('input', { 'type': 'hidden', 'value': currentPost.down('div#'+fInfo[i].id).firstDescendant().getValue(),'name':fInfo[i].id}));
		}
		
		if(!fInfo[i].id){break;}
	}

	//var newInput = new Element('input', { 'type': 'hidden', 'value': currentEditor.getData(),'name':'txt' })
	//currentPost.down('form#form0').insert({top:newInput});
	newForm.request({
	  parameters: { req:'saveItem',postId:currentPost.getAttribute('dbid'),dbTable:currentPost.getAttribute('dbTable')},
	  onComplete: function(transport){
		
		try{var resData = JSON.parse( transport.responseText );} catch(e){ alert(transport.responseText);}
		//alert(transport.responseText);
		if(resData.newId){
			currentPost.down('input#postId').writeAttribute({'value':resData.newId});
			currentPost.writeAttribute({'id':'no_'+resData.newId});
			//saveOrder();
		}
		stopPostEdit("saveIt");
	}
	})
	
	
}
