// JavaScript Document

var hasBG       = true;
var showKeyvis  = true;
var fontClass   = "";
var isAnimating = false;
var aniSteps    = 5;
var aniStep     = 0;
var aniTimer    = null;


function start() {
	time();
	window.setInterval("time()", 1000);

  var t = getCookie("fontClass");
  fontClass = t;
  setContentClass(t);
  
  var c = getCookie("BG");
  var doBG = (c == "true") ? true : (c == null) ? true : false;  
  //setBackground(doBG);
  setBGToggleIcon(doBG);
  /*
  var k = getCookie("showKeyvis");
  var doKeyvis = (k == "true") ? true : (k == null) ? true : false; 
  setKeyvisVisibility(doKeyvis);
	*/
	// temporär alle Links umschreiben, damit man in der Staging navigieren kann
	if (window.location.hostname == "vogl.ve.m-online.net") {
		window.setTimeout(function() {
			var links = document.getElementsByTagName("a");
			for (var i=0, link; link = links[i]; i++) {
				link.href = link.href.replace("http://druckerei-vogl.de/", "http://vogl.ve.m-online.net/staging.druckerei-vogl.de/");
			}
			var forms = document.getElementsByTagName("form");
			for (var i=0, form; form = forms[i]; i++) {
				form.action = form.action.replace("http://druckerei-vogl.de/", "http://vogl.ve.m-online.net/staging.druckerei-vogl.de/");
			}
		}, 500);
	}


	// vmag
	var vmag = document.createElement("a");
	//vmag.href = window.location.href.replace(/_site\/(\w{2}).*/, "_site/$1-vmag");
	vmag.href = "http://v-mag.com/";
	vmag.id = "vmag-link";
	vmag.target = "_blank";
	document.body.appendChild(vmag);
	
	
	
	// skalierbares Hintergrundbild
	var bgImgMappings = {
			'de': ['05-Julia-PorodHaarsturm.jpg', 'http://v-mag.com/index.php?id=18&uid=93', 'Julia Maria Porod', '#fff'],
			'de-news': ['01-Duemig-InesDuemig_Ines_3.jpg', 'http://v-mag.com/index.php?id=18&uid=141', 'Inès Dümig', '#fff'],
			'de-news-archiv': ['07-Franziska-Straussfranziska_strauss_11.jpg', 'http://v-mag.com/index.php?id=18&uid=89', 'Franziska Strauß', '#fff'],
			'de-druck': ['01-Miriam-KsollKsoll_1.jpg', 'http://v-mag.com/index.php?id=18&uid=109', 'Miriam Ksoll', '#fff'],
			'de-druck-beratung': ['14-Cornelius-Kaessdoppelseite1.jpg', 'http://v-mag.com/index.php?id=18&uid=92', 'Cornelius Käss', '#fff'],
			'de-high-gamut': ['09-Michael-Dengler4.jpg', 'http://v-mag.com/index.php?id=18&uid=31', 'Michael Dengler', '#000'],
			'de-druck-dtpdruckvorstufe': ['01-Julian-KramermasterA4.jpg', 'http://v-mag.com/index.php?id=18&uid=127', 'Julian Kramer', '#000'],
			'de-druck-maschinenpark': ['01-Leyla-Rodriguezleylarodriguez_05.jpg', 'http://v-mag.com/index.php?id=18&uid=56', 'Leyla Rodriguez', '#fff'],
			'de-druck-weiterverarbeitung': ['08-Jie-Liusquare-succession-X.jpg', 'http://v-mag.com/index.php?id=18&uid=95', 'Jie Liu', '#fff'],
			'de-druck-druckanfrage': ['12-Louisa-Marie-Summer05_LSummer_MG_5116.jpg', 'http://v-mag.com/index.php?id=18&uid=150', 'Louisa Marie Summer', '#fff'],
			'de-druck-uv-offset': ['03-Wiebke-Christin-Lebusbubonic_dress3.jpg', 'http://v-mag.com/index.php?id=18&uid=121', 'Wiebke Christin Lebus', '#fff'],
			'de-referenzen': ['07-Julia-Klenk-Claudia-Klee1_En-Ig-Ma_Entfremdung.jpg', 'http://v-mag.com/index.php?id=18&uid=134', 'Julia Klenk & Claudia Klee', '#fff'],
			'de-referenzen-kunden': ['21-Jennifer-Schaeferauswahl_24.jpg', 'http://v-mag.com/index.php?id=18&uid=149', 'Jennifer Schäfer', '#fff'],
			'de-service-stanzformen': ['13-Sebastian-Linderlinder_3.jpg', 'http://v-mag.com/index.php?id=18&uid=82', 'Sebastian Linder', '#fff'],
			'de-service-lettershop': ['10-Larissa-RudolphLarissa-Rudolph-Visakhapatnam-2.jpg', 'http://v-mag.com/index.php?id=18&uid=157', 'Larissa Rudolph', '#fff'],
			'de-service-produktionsservice': ['05-Sabine-MoebiusMoebius_Sabine_03.jpg', 'http://v-mag.com/index.php?id=18&uid=138', 'Sabine Möbius', '#fff'],
			'de-service-rueckrufservice': ['03-Andreas-Drosdz05_Andreas_Drosdz_V-Mag.jpg', 'http://v-mag.com/index.php?id=18&uid=151', 'Andreas Drosdz', '#fff'],
			'de-service-links': ['15-lukas-schoenthal-marco-stancatoEating-Bois_A3_300dpi.jpg', 'http://v-mag.com/index.php?id=18&uid=137', 'Lukas Schönthal & Marco Stancato', '#fff'],
			'de-kundenbereich': ['03-Alicia-Freksa_MG_7489.jpg', 'http://v-mag.com/index.php?id=18&uid=64', 'Alicia Freksa', '#fff'],
			'de-kundenbereich-online-ftp': ['20-Klee-Claudia500Blatt_B.jpg', 'http://v-mag.com/index.php?id=18&uid=118', 'Claudia Klee', '#000'],
			'de-kundenbereich-druckanfrage': ['21-Jennifer-Schaeferauswahl_25.jpg', 'http://v-mag.com/index.php?id=18&uid=149', 'Jennifer Schäfer', '#000'],
			'de-umwelt': ['23-Inga-PloennigsLL1_grau.jpg', 'http://v-mag.com/index.php?id=18&uid=100', 'Inga Plönnigs', '#000'],
			'de-umwelt-fcs-zertifizierung': ['09-Georg-Schopp_MG_2405.jpg', 'http://v-mag.com/index.php?id=18&uid=124', 'Georg Schopp', '#fff'],
			'de-umwelt-klimaneutrales_drucken': ['07-Julia-Klenk-Claudia-Klee7_En-Ig-Ma_Elektroauto_lithium.jpg', 'http://v-mag.com/index.php?id=18&uid=134', 'Julia Klenk & Claudia Klee', '#fff'],
			'de-kontakt': ['04-Christopher-Vazanskyvazansky_obama.jpg', 'http://v-mag.com/index.php?id=18&uid=70', 'Christopher Vazansky', '#000'],
			'de-kontakt-newsletter': ['06-Sandra-DieckmannSearch.jpg', 'http://v-mag.com/index.php?id=18&uid=40', 'Sandra Dieckmann', '#fff'],
			'de-kontakt-ansprechpartner': ['03-Patrick-Fauckbild-9-vollbluttrojaner.jpg', 'http://v-mag.com/index.php?id=18&uid=96', 'Patrick Fauck', '#fff'],
			'de-kontakt-kontaktformular': ['08-Marie-Louise-HaaseEiszeiten.jpg', 'http://v-mag.com/index.php?id=18&uid=30', 'Marie-Louise Haase', '#fff'],
			'de-sitemap': ['02-Christina-StihlerSerie1_bild1.jpg', 'http://v-mag.com/index.php?id=18&uid=115', 'Christina Stihler', '#fff'],
			'de-agbs': ['12-Johannes-von-Dasselnice-chap-Kopie-2.jpg', 'http://v-mag.com/index.php?id=18&uid=99', 'Johannes von Dassel', '#fff'],
			'de-impressum': ['04-Marven-Grafmarven1_300dpi.jpg', 'http://v-mag.com/index.php?id=18&uid=78', 'Marven Graf', '#fff'],
			'de-suchergebnisse': ['25-Cindy-Schmidbild1.jpg', 'http://v-mag.com/index.php?id=18&uid=39', 'Cindy Schmid', '#000']
		},
		bgImgMappingKey = window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1);
	while (!bgImgMappings[bgImgMappingKey]) {
		if (bgImgMappingKey.lastIndexOf("-") < 0) {
			bgImgMappingKey = "de";
		}
		else {
			bgImgMappingKey = bgImgMappingKey.substring(0, bgImgMappingKey.lastIndexOf("-"));
		}
	}
	
	var bgImgMapping = bgImgMappings[bgImgMappingKey],
		bgImgUrl = "img/background/"+bgImgMapping[0],
		img = new Image(),
		bg = document.createElement("div");
	
	bg.id = "bg-container";
	
	// credits-container for background image
	var credits = document.createElement("div"),
		creditsLink = document.createElement("a");
	credits.id = "bg-credits";
	credits.appendChild(document.createTextNode("MOTIV: "));
	creditsLink.href = bgImgMapping[1];
	creditsLink.innerHTML = bgImgMapping[2];
	credits.style.color = bgImgMapping[3];
	creditsLink.style.color = bgImgMapping[3];
	credits.appendChild(creditsLink);
	document.getElementById("main").appendChild(credits);
	
	document.getElementById("cms-content").getElementsByTagName("h2")[0].style.color = bgImgMapping[3];
	
	
	/*
	if (document.body.currentStyle) {
		bgImgUrl = document.body.currentStyle.backgroundImage;
	}
	else {
		bgImgUrl = getComputedStyle(document.body,'').getPropertyValue('background-image');
	}
	bgImgUrl = bgImgUrl.substring(4, bgImgUrl.length-1).replace(/"/g, "");
	*/
	img.onload = function() {
		document.body.style.background = "";
		
		var tempImg = new Image();
			tempImg.src = bgImgUrl;
		var ow = tempImg.width,
			oh = tempImg.height;
		
		window.onresize = function() {
			var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
			
			// Faktor der Skalierung berechnen
			var factor = x/ow;
			//console.log(x, ow, factor);
			if (oh*factor < y) {
				//console.log(y, oh, factor, "=", oh*factor);
				factor = y/oh;
			}
			bg.style.height = y+"px";
			img.style.width = ow*factor+"px";
			img.style.height = oh*factor+"px";
			img.style.left = Math.round((x - ow*factor)/2) + "px";
			img.style.top = Math.round((y - oh*factor)/2) + "px";
		};
		window.onresize();
	};
	img.src = bgImgUrl;
	
	bg.appendChild(img);
	document.body.appendChild(bg);
}

function time() {
	var now = new Date();
	day = now.getDate();
	month = now.getMonth()+1;
	year = now.getYear();
	hours = now.getHours();
	minutes = now.getMinutes();
	
	if(day<10) day = "0" + day;
	if(month<10) month= "0" + month;
	if(year<1000) year+=1900;

	thetime = (hours < 10) ? "0" + hours + ":" : hours + ":";
	thetime += (minutes < 10) ? "0" + minutes + "" : minutes;
	thetime += "&nbsp;&nbsp;---&nbsp;&nbsp;"
	thetime += day + "." + month + "." + year;

	element = document.getElementById("time");
  if (element != null) {
    element.innerHTML = thetime;
  }	
}

function toggleBackground(){

  var bodyClass = document.body.className;  
  bodyClass = (bodyClass == "bg-img") ? "" : "bg-img";
  document.body.className = bodyClass ;
  
  hasBG = (document.body.className == "bg-img") ;
  
  //~ alert('toggleBackground ' +hasBG);
  setBGToggleIcon(hasBG);
  //~ setCookie();
  var cookieValue = (hasBG) ? "true" : "false";
  setCookie("BG", cookieValue);
}

function setContentClass(t){
  var o = document.getElementById("content");
  o.className = t;
  setCookie("fontClass", t);
}

function setBackground(b){
  hasBG = b;
  var bodyClass = (hasBG) ? "bg-img" : "" ;
  document.body.className =bodyClass ;
}

function setBGToggleIcon(b){
  var src = (b) ? "img/bg-close.png" : "img/bg-open.png"; 
  var o = document.getElementById("img-bt-bgclose");
  if (o != undefined) {
    o.src = src;
  }
}

function toggleKeyvisVisibility(){
  
  if (!isAnimating) {
    aniStep  = 0;
    aniTimer = setTimeout("animateKeyvis()", 20);
  }
  
}

function animateKeyvis(){
  
  if (aniStep < aniSteps) {
    var o = document.getElementById("panel");
    if (o != undefined) {
      var h = 315;
      
      if (showKeyvis) {
        h = h / (2 + aniStep *2);
      } else {
        h = 33 + (h - 33) * (aniStep / aniSteps);
      }
      o.style.height = h + "px";
    }
    var o = document.getElementById("panel-img");
    if (o != undefined) {
      var t = 1 / (2 + aniStep);
      if (showKeyvis) {     
        o.style["opacity"] = t;
        o.style["moz-opacity"] = t;
        o.style["filter"] = "Alpha(opacity=" + parseInt(100 * t) + ")";
      } else {
        o.style.visibility = "visible";
        o.style["opacity"] = (1 - t);
        o.style["moz-opacity"] = (1 - t);
        o.style["filter"] = "Alpha(opacity=" + (100 - parseInt(100 * t)) + ")";      
      }
    }

    aniStep++;
    aniTimer = setTimeout("animateKeyvis()", 100);
    
  } else {
    var o = document.getElementById("panel-img");
    if (o != undefined) {
      o.style["opacity"] = "";
      o.style["moz-opacity"] = "";
      o.style["filter"] = "";
    }
    
    setKeyvisVisibility(!showKeyvis);
    var cookieValue = (showKeyvis) ? "true" : "false";
    setCookie("showKeyvis", cookieValue);
    
    clearTimeout(aniTimer);
  }  
}

function setKeyvisVisibility(b){
  var o = document.getElementById("panel");
  if (o != undefined) {
    o.style.height = (b) ? "315px" : "33px";
  }
  o = document.getElementById("panel-img");
  if (o != undefined) {
    o.style.visibility = (b) ? "visible" : "hidden";
  }
  o = document.getElementById("slider-btn");
  if (o != undefined) {
    o.style.backgroundPosition = (b) ? "0px 0px" : "0px -50px";
  }
  showKeyvis = b;
}

function setCookie( name, value, expires, path, domain, secure ) {
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expires )
  {
  expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );

  //~ var t = "";
  //~ t = t + (hasBG) ? "BG" : "";
  //~ document.cookie = t;
  
  //~ alert('setCookie ' + document.cookie);
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
