﻿//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]

shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

function cloneEventsRecursive(from,to)
{
	try{to.cloneEvents(from);}catch(e){return to;};
	for(var x=0;x<from.childNodes.length;x++) if(from.childNodes[x].nodeType!=3) cloneEventsRecursive(from.childNodes[x],to.childNodes[x]);
	return to;
}

function hoverAndAct(img,dataType)
{
	img.parentNode.className="active";
	img.src=img.src.substring(0,img.src.length-(dataType.length+2))+"h."+dataType;
}

function normalAndDeact(img,dataType)
{
	img.parentNode.className="";
	normal(img,dataType);
}

function setWholeHight(elid,size)
{
  var sz=$(elid).getStyle("paddingTop").toInt()+$(elid).getStyle("paddingBottom").toInt()+$(elid).getStyle("marginTop").toInt()+$(elid).getStyle("marginBottom").toInt();
	$(elid).setStyle("height",size-sz+"px");
}

function setDivsSameHight(elids)
{
	var height,i,pb,pt,mt,mb,hh;
	height=0;
	
	for(i=0;i<elids.length;i++)
	{
		if(elids[i]==null) return;
		hh=$(elids[i]).getSize().y-$(elids[i]).getStyle("margin-top").toInt()-$(elids[i]).getStyle("margin-bottom").toInt();
		height=(hh>height)?hh:height;
	}
	for(i=0;i<elids.length;i++)
	{
		pt=$(elids[i]).getStyle("padding-top").toInt();
		pb=$(elids[i]).getStyle("padding-bottom").toInt();
		mt=$(elids[i]).getStyle("margin-top").toInt();
		mb=$(elids[i]).getStyle("margin-bottom").toInt();
		$(elids[i]).setStyle("height",height-pt-pb);
	}
}

function getOuterDimensions(elid)
{
	var pt,pb,mt,mb,pl,pr,ml,mr,w,h;
	pt=$(elid).getStyle("padding-top").toInt();
	pb=$(elid).getStyle("padding-bottom").toInt();
	
	mt=$(elid).getStyle("margin-top").toInt();
	mb=$(elid).getStyle("margin-bottom").toInt();
	
	pl=$(elid).getStyle("padding-left").toInt();
	pr=$(elid).getStyle("padding-right").toInt();
	
	ml=$(elid).getStyle("margin-left").toInt();
	mr=$(elid).getStyle("margin-right").toInt();
	
	w=$(elid).getStyle("width").toInt()+pl+pr+ml+mr;
	h=$(elid).getStyle("height").toInt()+pt+pb+mt+mb;
	
	return {width: w,height: h};
}


function initNav(img,dataType)
{
	nimg=new Image();
	nimg.src=img.src.substring(0,img.src.length-(dataType.length+2))+"h."+dataType;
	nimg.style.display="none";
	$(document.body).appendChild(nimg);
	normal(img,dataType);
}

function onloadNav(elId,dataType)
{
  var imgs=$(elId).getElements("img");
	for(i=0;i<imgs.length;i++) 
  {
    imgs[i].onmouseout=function(e) {normal( this,dataType );};
    imgs[i].onmouseover=function(e) {hover( this,dataType );};  
    initNav(imgs[i],dataType);
  }
}

function normal(img,dataType)
{
	if(img.parentNode.className=="active") n="h";
	else n="n";
	img.src=img.src.substring(0,img.src.length-(dataType.length+2))+n+"."+dataType;
}

function hover(img,dataType)
{
	img.src=img.src.substring(0,img.src.length-(dataType.length+2))+"h."+dataType;
}


function addOverlay(el,overlayName)
{
	if(overlayName==null) overlayName="";
	var zIndex=100+($$(".overlay").length*2);
	var div=new Element("div",
	{
		id: "overlay"+overlayName,
		"class":"overlay "+overlayName,
		styles: {
		position:"absolute",
		zIndex:zIndex,
		height:$(document.body).getScrollSize().y+"px",
		width:$(document.body).getScrollSize().x+"px",
		left:0,
		top:0
		}
	});
	
	$(document.body).insertBefore(div,$(document.body).firstChild);
	
	div=new Element("div");
	div.id="overlayInput"+overlayName;
	div.setStyles({
		position:"absolute",
		zIndex:zIndex+1,
		//width: "auto"
		overflow: "auto"
	});
	
	var backLink=new Element("a",{href:"#",title:"Schließen",id:"closeOverlayDivA",'class':"closeOverlayDivA"});
	backLink.adopt(document.createTextNode("x"));
	backLink.onclick=function(){closeOverlay(overlayName); return false;};
	
	div.adopt(backLink);
	div.adopt(el);
	
	$(document.body).insertBefore(div,$(document.body).firstChild);
	
	window.addEvent("resize",function()	{newPosOverlay(overlayName);});
	newPosOverlay(overlayName);
}

function newPosOverlay(overlayName)
{
	if(overlayName==null) overlayName="";
	if($("overlayInput"+overlayName)==null) return;
	var boSz=$(document.body).getSize();
	var boSc=$(document.body).getScroll();
	var elSz=$("overlayInput"+overlayName).getSize();
	var t=Math.round((boSz.y-elSz.y)/2);
	t=(t<0)?0:t;
	$("overlayInput"+overlayName).style.top=t+boSc.y+"px";
	var l=Math.round((boSz.x-elSz.x)/2);
	l=(l<0)?0:l;
	$("overlayInput"+overlayName).style.left=l+boSc.x+"px";
	if($("overlay"+overlayName)==null) return;
	$("overlay"+overlayName).setStyles({
		height:$(document.body).getScrollSize().y+"px",
		width:$(document.body).getScrollSize().x+"px"
	});
}

function closeOverlay(overlayName)
{
	if(overlayName==null) overlayName="";
	if($("overlayInput"+overlayName)==null) return;
	$(document.body).removeChild($("overlay"+overlayName));
	$(document.body).removeChild($("overlayInput"+overlayName))
	return true;
}

function getScreenSize()
{
  boSz=$(document.body).getSize();
	return boSz;
}

function implode(array,delimiter,start,end)
{
  if(start==null) start=0;
	if(end==null) end=array.length;
	var text="";
  for(var i=start;i<end;i++) text+=array[i]+delimiter;
	return text.substr(0,text.length-2);
}

function returnDayName(day)
{
  if(day==1) return "Montag";
  if(day==2) return "Dienstag";
  if(day==3) return "Mittwoch";
  if(day==4) return "Donnerstag";
  if(day==5) return "Freitag";
  if(day==6) return "Samstag";
  if(day==0 || day==7) return "Sonntag";
}

function returnMonthName(mnr)
{
  if(mnr==0) return "Januar";
  if(mnr==1) return "Februar";
  if(mnr==2) return unescape("M%E4rz");
  if(mnr==3) return "April";
  if(mnr==4) return "Mai";
  if(mnr==5) return "Juni";
  if(mnr==6) return "Juli";
  if(mnr==7) return "August";
  if(mnr==8) return "September";
  if(mnr==9) return "Oktober";
  if(mnr==10) return "November";
  if(mnr==11) return "Dezember";
}

function returnMonthLength(mnr,year)
{
  if(mnr==0) return 31;
  if(mnr==1) 
  {
    r=28;
    if (year % 4 == 0) r++;
    if (year % 100 == 0) r--;
    if (year % 400 == 0) r++;
    return r;
  }
  if(mnr==2) return 31;
  if(mnr==3) return 30;
  if(mnr==4) return 31;
  if(mnr==5) return 30;
  if(mnr==6) return 31;
  if(mnr==7) return 31;
  if(mnr==8) return 30;
  if(mnr==9) return 31;
  if(mnr==10) return 30;
  if(mnr==11) return 31;
}

//makes 0=monday and 6=sunday not english formated
function parseEngDayToGerman(actdate)
{
  actDay=actdate.getDay()-1;
	actDay=(actDay<0)?6:actDay;
	return actDay;
}

//returns php time() (in js time() is with milisecounds
function dateToUnixTime(actdate) 
{
  actdate=actdate.getTime()+"";
	return actdate.substr(0,actdate.length-3);
}

//reset hours/minutes/secounds/milisec. from date
function dateToFullDayInUnixTime(actdate)
{
  actdate.setHours(0);
	actdate.setMilliseconds(0);
  actdate.setMinutes(0);
	actdate.setSeconds(0);
	return dateToUnixTime(actdate);
}

function trim(str)
{
  return str.replace(/\s+$/,"").replace(/^\s+/,"");
}

loadImage=function()
{
	this.imgLoadInfo=new Image();
	this.imgLoadInfo.src="assets/tpl/loadInfo.gif";
	
	this.init=function(x,y,src,onload)
	{
		div=new Element("div",{styles:{textAlign: "center"}});
		div.adopt(this.imgLoadInfo);
		this.img=$(new Image());
		this.img.addEvent("load",function(){this.img.replaces(this.imgLoadInfo);if(onload!=null) onload()}.bind(this));
		this.img.src=src;
		this.img.setStyles({'max-width': x,'max-height': y});
		return div;
	}
	
	this.getImage=function()
	{
		return this.img;
	}
	
}

function image_resize(img,maxHeight,maxWidth,rePos,makeBigger)
{
  img=$(img);
	var width=img.width;
	var height=img.height;
	
	var z=1;
	
	if((width>maxWidth || (width<=maxWidth && makeBigger===true)) && width>=height) 
	{
  	z=maxWidth/width;
  	if(makeBigger===true && maxHeight<Math.round(height*z)) z=maxHeight/height;
	}
	if((height>maxHeight || (height<=maxHeight && makeBigger===true)) && height>width) 
	{
  	z=maxHeight/height;
		if(makeBigger===true && maxWidth<Math.round(width*z)) z=maxWidth/width;
	}
	
	img.setStyle("width",Math.round(width*z));
	img.setStyle("height",Math.round(height*z));

	if(rePos===true)
	{
  	var newWidth=img.getStyle("width").toInt();
  	var newHeight=img.getStyle("height").toInt();
		var pL=Math.round((maxWidth-newWidth)/2);
		var pT=Math.round((maxHeight-newHeight)/2);
		if(newWidth<maxWidth) img.setStyle("paddingLeft",pL==1?0:pL);
		if(newHeight<maxHeight) img.setStyle("paddingTop",pT==1?0:pT);
	}
}

function abs(x)
{
  if(x<0) x=-x;
  return x;
}

uploadFormOverlay = 
{
	start: function(upID,uploadPhpURL,readyfuncName)
	{
		var div=new Element("div",{styles:{backgroundColor: "#fff",padding: 20,border: "3px solid #aaa"}});
		div.adopt(new Element("form",{action:uploadPhpURL,method:"post",enctype:"multipart/form-data",encoding:"multipart/form-data",target:"upload_target"+upID,events: {submit: function()
		{
			document.getElementById('loadInfo'+upID).style.display = '';
			document.getElementById('loadForm'+upID).style.display = 'none';
		}},
		html: 
		'<h1>Bild hochladen</h1>'+
		'<span id="loadInfo'+upID+'" style="display: none">Lade hoch...</span>'+
		'<div id="loadForm'+upID+'">'+
			'<p>Neues Bild hochladen (max. 500kB und nur .jpg)<br/><input name="'+upID+'" type="file" /></p>'+
			'<input type="hidden" name="fileId" value="'+upID+'" />'+
			'<input type="hidden" name="readyfuncName" value="'+readyfuncName+'" />'+
			'<table width="280px"><tr><td><input type="reset" class="flatbutton" onclick="closeOverlay(\''+upID+'\'); return false;" name="reset" value="schließen" /></td>'+
			'<td style="text-align:right"><input type="submit" class="flatbutton" name="submitBtn" value="hochladen" /></td></tr></table>'+	
		'</div>'+
		'<iframe name="upload_target'+upID+'" src="'+uploadPhpURL+'" style="width:0;height:0;border:0px solid #fff;"></iframe>'		
		}));
		addOverlay(div,upID);
	},
	done: function(uploadedImageName,errormsg,result,upID,readyfuncName)
	{
			document.getElementById('loadInfo'+upID).style.display = 'none';
			document.getElementById('loadForm'+upID).style.display = '';
			if(result == false)
			{
				if(errormsg==="") errormsg="Upload fehlgeschlagen";
				alert(errormsg);
			}
			else window[readyfuncName](uploadedImageName);
	}
}
imageBrowser=
{
	open: function(href,retFunc,browserName,imgPath)
	{
		var errorFunc=function(){alert("Fehler, Aktion konnte nicht ausgeführt werden")};
		var myRequest = new Request.JSON(
		{
			url: href,
			onSuccess: function(responseJSON,responseText){closeOverlay(browserName+"wait"); if(responseJSON===false) errorFunc();else imageBrowser.show(responseJSON,retFunc,browserName,imgPath,href);},
			onError: errorFunc
		});
		myRequest.send();
		addOverlay(new Element("div",{styles: {border: "3px solid #ccc",backgroundColor: "#fff",padding:"30px",fontSize:"18pt"},text: "bitte warten..."}),browserName+"wait");
	},
	
	show: function(responseJSON,retFunc,browserName,imgPath,href)
	{
		var fnc=retFunc;
		if(responseJSON.length==0) 
		{
			alert("Keine Bilder vorhanden. Nutzen Sie die Funktion \"Bild hochladen\"");
			return;
		}
		var div=new Element("div",{styles: {border: "3px solid #ccc",'width': 600,overflow: 'auto',backgroundColor: "#fff",padding:"30px"}});
		
		addOverlay(div,browserName+"show");
		responseJSON.each(function(ite,ind)
		{
			var img=new Image();
			img.src=imgPath+ite;
			img=$(img);
			img.setStyles({
				width:100,
				height:100,
				padding: "0 10px 5px 0"
			});
			var s=new Element("div",{id: "previewImage"+ind,styles:{position: 'relative',float: 'left',paddingBottom: 10,width: 110,height: 150}});
			s.adopt(new Element("span",{styles:{position: 'absolute',cursor: "pointer",backgroundColor: "#f00",color: "#fff",padding: "2px 4px",top: 0,right: 10,display: 'block'},text: "x",events:{click: function(){imageBrowser.del(href,browserName,ite,"previewImage"+ind)}}}));
			s.adopt(img);
			s.adopt(new Element("span",{text:ite}));
			s.inject(div);
			img.addEvent("load",function(){newPosOverlay(browserName+"show")});
			img.addEvent("click",function(){fnc(ite);closeOverlay(browserName+"show")});
		});
		new Element("span",{styles:{clear: "both",float:"right",display: "block"},'class': "flatbutton",text:"abbrechen",events:{click: function(){closeOverlay(browserName+"show");}}}).inject(div);
	},
	
	del: function(href,browserName,ite,divid)
	{
		if(confirm("Bild \""+ite+"\" wirklich löschen?")!==true) return;
		var errorFunc=function(){alert("Fehler, Aktion konnte nicht ausgeführt werden")};
		var myRequest = new Request.JSON(
		{
			url: href,
			onSuccess: function(responseJSON,responseText){closeOverlay(browserName+"delete"); if(responseJSON===true) $(divid).dispose(); else errorFunc();},
			onError: errorFunc
		});
		myRequest.post("delete="+ite);
		addOverlay(new Element("div",{styles: {border: "3px solid #ccc",backgroundColor: "#fff",padding:"30px",fontSize:"18pt"},text: "bitte warten..."}),browserName+"delete");
	}
}

/* EXTRA */
function loadCalendar(insertEl,userfunc,userModTimeFunc,AKT_DATE,tblClassName)
{
	//init calendar
	var cal,thead,th,tr;
	if(AKT_DATE==null) AKT_DATE=new Date();
	insertEl.innerHTML="";
	cal=createCalendar(AKT_DATE.getMonth(),AKT_DATE.getFullYear(),userfunc,true,tblClassName);

	//create headline
	thead=new Element("thead");
	th=new Array();

	//backward Month (cell)
	th[0]=new Element("th",{id:"preMonth",styles: {cursor: "pointer"},text:"<",events: {click:function()
	{
		insertEl.innerHTML="";
		AKT_DATE.setMonth(AKT_DATE.getMonth()-1);
		loadCalendar(insertEl,userfunc,userModTimeFunc,AKT_DATE,tblClassName);
	}}});

	//MonthName (cell)
	th[1]=new Element("th",{id:"monthName",text:returnMonthName(AKT_DATE.getMonth())+" "+AKT_DATE.getFullYear()});
	th[1].colSpan="6";

	//forward Month (cell)
	th[2]=new Element("th",{id:"nexMonth",styles: {cursor: "pointer"},text:">",events: {click:function()
	{
		insertEl.innerHTML="";
		AKT_DATE.setMonth(AKT_DATE.getMonth()+1);
		loadCalendar(insertEl,userfunc,userModTimeFunc,AKT_DATE,tblClassName);
	}}});

	//insert and create
	tr=new Element("tr");
	th.each(function(ite){tr.adopt(ite)});
	thead.adopt(tr);
	cal.insertBefore(thead,cal.getElementsByTagName("tbody")[0]);
	if(userModTimeFunc!=null) userModTimeFunc(cal,AKT_DATE,insertEl);
	/*MODIFIED!!!*/
	//orginal: aC(insertEl,cal);
	//mod:
	insertEl.insertBefore(cal,insertEl.firstChild);
}

function createCalendar(month,year,userModCellFunc,kw,tblClassName)
{
	var nd,tds,a,tr,aktDay,tbody,thead,tbl,dn,td;
	kw=(kw===true)?true:false;
	nd=new Date();
	nd.setHours(0);
	nd.setMilliseconds(0);
	nd.setMinutes(0);
	nd.setSeconds(0);
	tbody=new Element("tbody");
	tbl=new Element("table");
	tbl.id="calendar";
	tbl.className=tblClassName;
	//thead=new Element("thead");
	//generate table heading
	tds=new Array();
	for(var a=1;a<8;a++)
	{
		dn=returnDayName(a);
		tds[a-1]=new Element("td",{'class':"head",text:dn.substr(0,2)});
	}
	tds[5].className+=" weekend";
	tds[6].className+=" weekend";
	tr=new Element("tr");
	if(kw===true)
	{
		td=new Element("td",{text: "KW",'class':"head KW"});
		tr.adopt(td);
	}
	tds.each(function(ite){tr.adopt(ite)});
	tbody.adopt(tr);
	tbl.adopt(tbody);
	tds=cEs("td",7);
	if(month==null) month=nd.getMonth();
	if(year==null) month=nd.getFullYear();
	for(a=1;a<=returnMonthLength(month,year);a++)
	{
		nd.setDate(a);
		nd.setMonth(month);
		nd.setFullYear(year);

		aktDay=parseEngDayToGerman(nd);//eng: sunday=0 monday=1 -> bullshits
		tds[aktDay].set("text",a);
		tds[aktDay].onselectstart=new Function("return false");
		tds[aktDay].id=digits(nd.getDate())+"."+digits(nd.getMonth()+1)+"."+nd.getFullYear().toString().substr(2,2);
		
		if(userModCellFunc!=null)  userModCellFunc(new Date(nd.getTime()),tds[aktDay],aktDay);
		if(aktDay==6 || a==returnMonthLength(month,year))
		{
			tds[5].className+=" weekend";
			tds[6].className+=" weekend";
			tds[0].className+=" first";
			tr=new Element("tr");
			if(kw===true)
			{
				td=new Element("td");
				td.className="KW";
				td.set("text",kalenderwoche(nd.getFullYear(),nd.getMonth()+1,nd.getDate()));
				tr.adopt(td);
			}
			tds.each(function(ite){tr.adopt(ite)});
			tbody.adopt(tr);
			tds=cEs("td",7);
		}
	}
	tbl.adopt(tbody);
	return tbl;
}

function cEs(el,count)
{
	var x=new Array();
	for(var y=0;y<count;y++) x[x.length]=new Element(el);
	return x;
}


function kalenderwoche(jahr,monat,tag) 
{
  var datum=new Date(jahr,monat-1,tag); // Anm. 1
  var jh=jahr+1; // Anm. 2
  var kalwo=kaldiff(datum,jh);
  while(kalwo<1) { jh--; kalwo=kaldiff(datum,jh); }
  return kalwo;
}

function kaldiff(datum,jahr) 
{
  var d4j=new Date(jahr,0,4);
  var wt4j=(d4j.getDay()+6)%7; // Anm. 3
  var m1wjT=Math.floor(0.01+d4j.getTime()/864e5-wt4j); // Anm. 4
  var datumT=Math.floor(0.01+datum.getTime()/864e5); // Anm. 5
  return Math.floor(1+(datumT-m1wjT)/7); // Anm. 6
}

function digits(x)
{
  if(x.toString().length<2) x="0"+x;
  return x;
}
