var rootpath = "http://www.vispinfo.ch";

function setValues() {
	var lang = "de";
	var weekday = 5;
	var nowDate = new Date();
	var delta = 7 - (nowDate.getDay()+6-weekday)%6;
	
	var date = getCurrDate('d.m.Y');
	var time = getCurrDate('h:00');
	var field1 = document.getElementById("sbb_datum");
	var field2 = document.getElementById("sbb_zeit");
	var form1 = document.getElementById("sbb_form");
	var form2 = document.getElementById("scout");
	
	if (field1 != null) field1.value = date;
	if (field2 != null) field2.value = time;
	if (form1 != null) form1.target = "_blank";
	if (form2 != null) form2.target = "_blank";
}

function setupPage () {
    setActiveParents();
	setValues();
    //setCSSClasses();
	//insDatum();
	insDatumEventkalender(); 
   	photoShufflerLaunch();
   	startSearch();
}

function redirectToPage(paramPage) {
    var a = location.href.search(/http:\/\/www.vispinfo.ch/);
	paramPage = clearSpecChars(paramPage);
    
    if(a+0 != -1) {        
        location.href = rootpath + "/" + paramPage;
    }
}

function ajaxRequest() {
    new Ajax.Request(rootpath + "/" + paramPage,
      {
        method:'get',
        onSuccess: function(transport){
          var response = transport.responseText || "no response text";
          //alert("Success! \n\n" + response);
          var arr = response.split(/<div id="content">/);
          var arr2 = arr[1].split(/<div id="fusszeile">/);
          content = arr2[0].substr(0,arr2[0].length-5);

          document.getElementById('content').innerHTML = content;
        },
        onFailure: function(){ 
            // Ajax didnt work
        }
      });    
}

function setCSSClasses() {
    var path = clearSpecChars(location.href.replace(rootpath,""));
    var sel = 'a[href=\'' + path + '\']';

    var countArray = path.split('/');
    
    countPath = countArray.length;
    countHide = (countPath == 2) ? 1 : countPath;
    countHide = (countPath == 3) ? 1 : countHide;
    countHide = (countPath == 4) ? 2 : countHide;
    countHide = (countPath == 5) ? 4 : countHide;
    //alert(countPath);

    $$(sel).each(function(el){
        if(countPath == 2 || countPath == 3) {
            myArray = el.ancestors();
            var item = myArray[0];
            
            item.addClassName('hide');
            
            // Add class to previous sibling
            siblings = item.previousSiblings();

            for (var indexS = 0; indexS < siblings.length; ++indexS) {
                siblings[indexS].addClassName('hide');
            }
        
            // Add class to next sibling
            siblings = item.nextSiblings();

            for (var indexS = 0; indexS < siblings.length; ++indexS) {
                if(indexS != 0) {
                    siblings[indexS].addClassName('hide');
                }
            }
        }
        else {
            myArray = el.ancestors();
        
            for (var index = 0; index < myArray.length; ++index) {
                var item = myArray[index];
            
                // Give parent li a class named 'activeParent'
                if(index == countHide) {
                    // Add class to previous sibling
                    siblings = item.previousSiblings();

                    for (var indexS = 0; indexS < siblings.length; ++indexS) {
                        siblings[indexS].addClassName('hide');
                    }
                
                    // Add class to next sibling
                    siblings = item.nextSiblings();

                    for (var indexS = 0; indexS < siblings.length; ++indexS) {
                        siblings[indexS].addClassName('hide');
                    }
                }
            }
        }
      });
}   

function setActiveParents() {
    var path = location.href.replace(rootpath,"");
    path = decodeURIComponent(path);
	path = clearSpecChars(path);
    var sel = 'a[href=\'' + path + '\']';

    $$(sel).each(function(el){
        myArray = el.ancestors();
        myArray[0].addClassName('activeItem');
        
        for (var index = 0; index < myArray.length; ++index) {
            var item = myArray[index];
            
            // Give parent li a class named 'activeParent'
            if(index == 2 || index == 4) {
                // Add class to previous sibling
                siblings = item.previousSiblings();
                if(siblings.length > 0) {                    
                    siblings[0].addClassName('activeParent');
                }
            }
        }
      });
}   

function insDatum()
{
    var jetzt = new Date();
	jetzt.setDate(jetzt.getDate() + 1);
    var Jahr = jetzt.getFullYear();         
    var Monat = jetzt.getMonth() + 1;
    var Tag = jetzt.getDate();
    var Datum = Tag + "." + Monat + "." + Jahr;
    document.getElementById("sbb_datum").value = Datum;
    // document.getElementById("sbb_datum").value = Datum;
}   

function startSearch()
{
    var arrSearch = location.href.split('?search=');

    if(arrSearch[1])
    {
        var searchTerm = arrSearch[1].split("'").join("\'");
        var searchURL = "http://www.wallcon.ch/clients/visp/google.php?s=" + encodeURIComponent(searchTerm);
        document.getElementById('googleiframe').src = searchURL;
        document.getElementById('searchmain').value = decodeURIComponent(searchTerm);//decodeURIComponent;
    }
        
}
function insDatumEventkalender()
{
    if(checkPage("/veranstaltungen/eventkalender/"))
    {
        var jetzt = new Date();
        var Jahr = jetzt.getFullYear();         
        var Monat = jetzt.getMonth() + 1;
        var Tag = jetzt.getDate();
        var DatumStart = Tag + "." + Monat + "." + Jahr; 

        jetzt.setDate(jetzt.getDate() + 15);
        Jahr = jetzt.getFullYear();         
        Monat = jetzt.getMonth() + 1;
        Tag = jetzt.getDate();
        var DatumEnde = Tag + "." + Monat + "." + Jahr;

        document.getElementById("startdate").value = DatumStart;
        document.getElementById("enddate").value = DatumEnde;
    }
}    

function checkPage(page) 
{
    var path = location.href.replace(rootpath,"");
    if(path == page) {
        return true;
    }
    
    return false;
}

function getVarFromURL(name)
{
    get_string = document.location.search;         
    return_value = '';

    do { //This loop is made to catch all instances of any get variable.
        name_index = get_string.indexOf(name + '=');

        if(name_index != -1)
        {
            get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);

            end_of_value = get_string.indexOf('&');
            if(end_of_value != -1)                
            value = get_string.substr(0, end_of_value);                
            else                
            value = get_string;                

            if(return_value == '' || value == '')
            return_value += value;
            else
            return_value += ', ' + value;
        }
    } while(name_index != -1)

    //Restores all the blank spaces.
    space = return_value.indexOf('+');
    while(space != -1)
    { 
        return_value = return_value.substr(0, space) + ' ' + 
        return_value.substr(space + 1, return_value.length);

        space = return_value.indexOf('+');
    }

    return(return_value);        
}

//
// CSS Photo Shuffler v1.0 by
//   Carl Camera
//   http://iamacamera.org 
//
// SetOpacity Function and inpiration from Photo Fade by
//   Richard Rutter
//   http://clagnut.com
//
// License: Creative Commons Attribution 2.5  License
//   http://creativecommons.org/licenses/by/2.5/
//

// Customize your photo shuffle settings
// 
// * Surround the target <img /> with a <div>. specify id= in both
// * set background-repeat:no-repeat in CSS for the div
// * The first and final photo displayed is in the html <img> tag
// * The array contains paths to photos you want in the rotation. 
//   If you want the first photo in the rotation, then it's best to
//   put it as the final array image.  All photos must be same dimension
// * The rotations variable specifies how many times to repeat array.
//   images. zero is a valid rotation value.

var gblPhotoShufflerDivId = "foto";
var gblPhotoShufflerImgId = "photoimg"; 
var gblImg = new Array(
  "http://www.wallcon.ch/clients/visp/images/head_winter/w001.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w002.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w003.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w004.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w005.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w006.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w007.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w008.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w009.jpg",
  "http://www.wallcon.ch/clients/visp/images/head_winter/w010.jpg" 
  );
var gblPauseSeconds = 7.25;
var gblFadeSeconds = .85;
var gblRotations = 1;

// End Customization section

var gblDeckSize = gblImg.length;
var gblOpacity = 100;
var gblOnDeck = 0;
var gblStartImg;
var gblImageRotations = gblDeckSize * (gblRotations+1);

// window.onload = photoShufflerLaunch;

function photoShufflerLaunch()
{
	var theimg = document.getElementById(gblPhotoShufflerImgId);
      gblStartImg = theimg.src; // save away to show as final image

	document.getElementById(gblPhotoShufflerDivId).style.backgroundImage='url(' + gblImg[gblOnDeck] + ')';
	setTimeout("photoShufflerFade()",gblPauseSeconds*1000);
}

function photoShufflerFade()
{
	var theimg = document.getElementById(gblPhotoShufflerImgId);
	
	// determine delta based on number of fade seconds
	// the slower the fade the more increments needed
      var fadeDelta = 100 / (30 * gblFadeSeconds);

	// fade top out to reveal bottom image
	if (gblOpacity < 2*fadeDelta ) 
	{
	  gblOpacity = 100;
	  // stop the rotation if we're done
	  if (gblImageRotations < 1) return;
	  photoShufflerShuffle();
	  // pause before next fade
        setTimeout("photoShufflerFade()",gblPauseSeconds*1000);
	}
	else
	{
	  gblOpacity -= fadeDelta;
	  setOpacity(theimg,gblOpacity);
	  setTimeout("photoShufflerFade()",30);  // 1/30th of a second
	}
}

function photoShufflerShuffle()
{
	var thediv = document.getElementById(gblPhotoShufflerDivId);
	var theimg = document.getElementById(gblPhotoShufflerImgId);
	
	// copy div background-image to img.src
	theimg.src = gblImg[gblOnDeck];
	// set img opacity to 100
	setOpacity(theimg,100);

      // shuffle the deck
	gblOnDeck = ++gblOnDeck % gblDeckSize;
	// decrement rotation counter
	if (--gblImageRotations < 1)
	{
	  // insert start/final image if we're done
	  gblImg[gblOnDeck] = gblStartImg;
	}

	// slide next image underneath
	thediv.style.backgroundImage='url(' + gblImg[gblOnDeck] + ')';
}

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
	//output = output.replace(match[1], "");
  }
  return output;
}

function clearSpecChars(string) {
	var t_search = new Array("%C3%BC", "%C3%A4", "%FC", "%E4", "Ã¼", "Ã¤");
	var t_replace = new Array("ü", "ä", "ü", "ä", "ü", "ä");
	
	for (i = 0; i < t_search.length; i++) {
		string = string.replace(t_search[i], t_replace[i]);
	}
	
	return string;
}

function getCurrDate(format, timestamp) {
	var jetzt = new Date();
	var day = jetzt.getDate();
	var month = jetzt.getMonth() + 1;
	var year = jetzt.getYear();
	var fullYear = jetzt.getFullYear();
	var minutes = jetzt.getMinutes();
	var seconds = jetzt.getSeconds();
	var hours = jetzt.getHours();
	if (timestamp != "") {
		var expr = /([\+|\-])(\d{1}) (.+)/;
		expr.exec(timestamp);
		if (RegExp.$1 == "+") {
			switch (RegExp.$3) {
				case "days":
				case "day":
					day += RegExp.$2;
				break;
				case "months":
				case "month":
					month += RegExp.$2;
				break;
				case "years":
				case "year":
					fullYear += RegExp.$2;
				break;
			}
		} else {
			switch (RegExp.$3) {
				case "days":
				case "day":
					day -= RegExp.$2;
				break;
				case "months":
				case "month":
					month -= RegExp.$2;
				break;
				case "years":
				case "year":
					fullYear -= RegExp.$2;
				break;
			}
		}
	}
	if (day < 10) day = "0" + day;
	if (month < 10) month = "0" + month;
	if (hours < 10) hours = "0" + hours;
	if (minutes < 10) minutes = "0" + minutes;
	if (seconds < 10) seconds = "0" + seconds;
	
	var date = format.replace("d", day);
	date = date.replace("m", month);
	date = date.replace("Y", fullYear);
	date = date.replace("y", year);
	date = date.replace("h", hours);
	date = date.replace("i", minutes);
	date = date.replace("s", seconds);
	
	return date;
}
function getYearOptions(frm, elem, intv, duration)
{
	var Today = new Date();
	var startDate = new Date(Today.getTime()+intv*24*60*60*1000);
	var mySelect = document[frm][elem];
	var year = startDate.getYear();

	if (navigator.appName.indexOf("Microsoft")== -1) {
		year = year + 1900;
	}

	for(i=0;i<duration;i++)
	{
		mySelect.options[mySelect.length] = new Option(year+i,year+i,false,false);
	}
}

function showCam() {
	camWindow = window.open("http://www.rro.ch/wetter/webcam/show.php?c=rhone&amp;KeepThis=true&amp;TB_iframe=true&amp;height=620&amp;width=800", "Rhonetal", "height=620;width=700");
	if (window.focus) camWindow.focus();
	return false;
}