/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

window.searchSubmittable = false;
 
function l(expr) {
  try {
    //console.log(expr);
  } catch (e) {
    
  }
}

Date.prototype._shortDays = ['So','Mo','Di','Mi','Do','Fr','Sa'],
Date.prototype.getShortDay = function(){
	return this._shortDays[this.getDay()];
}
Date.prototype.getButtonDate = function(){
	var date = this.getDate().toString();
	if(date.length===1)date = "0"+date;
	var month = (this.getMonth()+1).toString();
	if(month.length===1)month = "0"+month;
	return date + "." + month;
}
//set hours to 2 for summer/winter time change
Date.prototype.normalize = function(){this.setHours(2, 0, 0, 0);return this}
Date.prototype.addDays = function(days) {this.setDate(this.getDate()+days);return this}

var KulturAgenda = {

	_dateButton: false,

  _isDateListExpanded : false,

  dateFromUrl: new Date().getTime()/1000,

  searchBox : {'element' : null, 'defaultText' : ''},

  onLoad: function(){
  	  //fetch a date button and create a cloner;
    //init lightbox
    hs.graphicsDir = KulturAgenda.root + 'assets/img/highslide/';

    KulturAgenda.loadGallery();
    KulturAgenda.initSearchBox(); 
	  KulturAgenda.getDateButton();
    try {
    KulturAgenda.fuguImage( {'type' : 'init'} );
    } catch(e) {
        //console.log(e);
    }
	 
	  //create date from URL
	  var date = new Date(parseInt(KulturAgenda.dateFromUrl)*1000).normalize();
	  //create horizontal calendar
	  new ScrollingButtons(AJS.$bytc('div','calendar_header_dates')[0],{
		  active: date,
		  from: new Date(date.getTime()-ScrollingButtons.daysToMilliSecs(3))
	  });
	  
	  //create marginal calendar (carbon copy)
	  var fromDate = new Date().normalize();
	  //Monday
	  var whichDayOfWeek = 1;
	  if(fromDate.getDay()!=whichDayOfWeek){
	  	  var add = 7-(6-fromDate.getDay()+whichDayOfWeek+1)%7;
	  	  fromDate.setTime(fromDate.getTime()-ScrollingButtons.daysToMilliSecs(add));
	  }
	  new ScrollingButtons(AJS.$bytc('div','marginal_item_search_dates')[0],{
			style: 'top',
			moveModifier: 0,
			moveDates: 7,
			nbrOfButtons: 14,
			active: new Date(),
			from: fromDate,
			hidePrevButton: true,
			onlyFutureClass: true
		});
	  //add issue
	  window.setTimeout(KulturAgenda.addIssuu, 1000);
  },

  addIssuu : function() {
    var issue = document.getElementById('issueplayer');
	  if(issue){
	  	issue.innerHTML = issue.innerHTML.replace('<!--','').replace('-->','');
	  }
  },


	getDateButton: function(data, showTill){
		//Init call
        showTill = showTill || 4;
		if(KulturAgenda._dateButton===false){
			//no datebutton in the store, so fetch one
			var btns = AJS.$bytc('*','date_ver_s');
			if(btns.length===0)return false;
			var btn = btns[0];
			//dispose it from the dom
			btn.parentNode.removeChild(btn);
			//clean
			for(var i = 0;i<8;i++)AJS.removeClass(btn,'bg_2_' + i);
			//create Cloner
			KulturAgenda._dateButton = btn;
			return;
		}
		
		var isValid = false;
		var button = null;
        var yesterday = false;
		data = KulturAgenda.extend({day:{style:{}},date:{style:{}},style:{}},data);
		if(data.d!=null){
			var now = new Date();
			now.normalize();
			data.d.normalize();
			isValid = data.d.getTime()>=now.getTime();
            if (!isValid) {
                var curDate = new Date(data.d.getTime());
                curDate.addDays(1)
                if (curDate.getTime() == now.getTime()) {
                     curDate = new Date();
                     if (curDate.getHours() < showTill) {
                         isValid = true;
                         yesterday = true;
                     }
                     
                }
            }
		}

        
		if(isValid){
			button = AJS.A();
		}
		else {
			button = AJS.SPAN();
		}
		button.className = KulturAgenda._dateButton.className;
        
        if (yesterday) {
            //button.className += ' bg_2_4 ';
        }
        
		button.innerHTML = KulturAgenda._dateButton.innerHTML ;
		var day = AJS.$bytc('span','date_ver_day',button)[0]  ;
		var date = AJS.$bytc('span','date_ver_date',button)[0];
		day.innerHTML = data.d.getShortDay();
		date.innerHTML = data.d.getButtonDate();
		KulturAgenda.extend(day,data.day.style,AJS.setStyle);
		KulturAgenda.extend(date,data.date.style,AJS.setStyle);
		KulturAgenda.extend(button,data.style,AJS.setStyle);
		//create link
		button.href = "#";
		if(isValid){
			var d = data.d.getDate().toString(), m = (data.d.getMonth()+1).toString();
			if(m.length===1)m = "0"+m;if(d.length===1)d = "0"+d;
			button.href = KulturAgenda.root + 'kalender/liste/'+d+'/'+m+'/'+data.d.getFullYear() + '/';
		}
		else {
			button.className = button.className += " bg_2_7";
		}
		return button;
	},

	extend: function(obj1,obj2,fn){
		for(var v in obj2)
			if(obj2.hasOwnProperty(v))
				fn?fn(obj1,v,obj2[v]):obj1[v] = obj2[v];
		return obj1;
	},

	insertDateButton: function(data,parent,where){
		var button = KulturAgenda.getDateButton(data);
		switch(where){
			case 'before':
				AJS.insertBefore(button, parent);
				break;
			case 'after':
				AJS.insertAfter(button, parent);
				break;
			case 'top':
				AJS.appendToTop(parent, button);
				break;
			case 'inside': default:
				AJS.appendChildNodes(parent, button);
		}
		return button;
	},

  expandDateList : function(elmId) {
    var options = {elm : AJS.$(elmId), set : null, opt : {}};
    options.opt.to = (KulturAgenda._isDateListExpanded) ? 69 : options.elm.scrollHeight
    options.opt.from = (KulturAgenda._isDateListExpanded) ? options.elm.scrollHeight : 69;
    options.set = (KulturAgenda._isDateListExpanded) ? false : true;
    options.imgStates = ['bottom', 'top'];
    var fx = AJS.fx.setHeight(options.elm, {
      from: options.opt.from,
      to: options.opt.to,
      duration : 500,
      onComplete : function() {
          AJS.$('fold_img').src = AJS.$('fold_img').src.replace(
            options.imgStates[KulturAgenda._isDateListExpanded + 0],
            options.imgStates[options.set + 0]
          );
          KulturAgenda._isDateListExpanded = options.set;
        }
    });
  },

  openIssuu : function(docName) {
    var win = window.open(
      'http://issuu.com/Berner_kulturagenda/docs/' + docName + '?mode=embed&layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&showFlipBtn=true',
      'Berner Kulturagenda',
      'height=700,width=1000,status=no,scrollbars=yes,resizable=no');
  },

  getGmap : function (color, lat, lng,zoom, div, asset) {
    if (GBrowserIsCompatible()) {
      gmap = new GMap2(AJS.$(div));
      gmap.disableGoogleBar();
      var latObj = new GLatLng(lat,lng);
      gmap.setCenter(latObj, zoom, G_HYBRID_MAP);

      gmap.addControl(new GSmallZoomControl());
      gmap.addControl(new GMapTypeControl());

      var icon = new GIcon();
      icon.image = asset + 'img/image.php?image=dot.png&color=' + color;
      icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
      icon.iconSize = new GSize(20, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      gmap.removeMapType(G_SATELLITE_MAP);

      gmapmarker = new GMarker(latObj, {icon:icon});
      gmap.addOverlay(gmapmarker);

      geocoder = new GClientGeocoder();
    }
  },

  initSearchBox : function() {
    elm = AJS.$(KulturAgenda.searchBox.element);
    KulturAgenda.searchBox.element = elm;
    if (elm) {
      window.searchSubmittable = KulturAgenda.searchBox.element.value != KulturAgenda.searchBox.defaultText
      AJS.AEV(elm, "focus", function(e) {
        window.searchSubmittable = true;
        if (KulturAgenda.searchBox.element.value == KulturAgenda.searchBox.defaultText) {
          KulturAgenda.searchBox.element.value = '';
        }
      });
      AJS.AEV(elm, "blur", function(e) {
        if (KulturAgenda.searchBox.element.value.length <= 0) {
          KulturAgenda.searchBox.element.value = KulturAgenda.searchBox.defaultText;
        }
      });
    }
  },

  fuguImage : function(event) {
      event = event || window.event;
      
      if (event.type == 'init') {
        AJS.AEV(AJS.$('fugu_link'), 'mouseover', KulturAgenda.fuguImage);
        AJS.AEV(AJS.$('fugu_link'), 'mouseout' , KulturAgenda.fuguImage);
      } else if (event.type == 'mouseover') {
        try {
          AJS.$('fugu_link').src  = KulturAgenda.root + 'assets/img/fugu_link_over.png';
        } catch (e) {
          //console.log(e);
        }
      } else {
        AJS.$('fugu_link').src  =   KulturAgenda.root + 'assets/img/fugu_link.png';
      }
  },
  
  active : false,
  
  gallery : null,

  holder : null,

  maxWidth : 620,

  imageCount : 0,

  loadGallery : function() {
    var i, id, url, holder, gallery;
    
    if(typeof(galleryData) == 'undefined') {
      return;
    }

    holder = AJS.$('image_div');

    if (galleryData[0].credit.length === 0 || galleryData[0].legend.length === 0) {
        AJS.$('gallery_info').style.height          = '0px';
    } else {
        AJS.$('gallery_info').style.height          = ( AJS.$('gallery_legend').offsetHeight + AJS.$('gallery_credit').offsetHeight) + 'px';
    }


    gallery = new Gallery(AJS.$('gallery_image'), 'simpleFadeTransition', false, holder);

    gallery.onImageProperty = function(image) {
      var crt = KulturAgenda.gallery.getCurrentImage();
      KulturAgenda.holder.style.width = image.width + 'px';
      KulturAgenda.holder.style.height = image.height + 'px';
      KulturAgenda.holder.style.marginLeft = (KulturAgenda.maxWidth / 2) -  (image.width / 2) + 'px';



      var legend = AJS.$('gallery_legend');
      var credit = AJS.$('gallery_credit');

      legend.innerHTML = galleryData[crt].legend;
      credit.innerHTML = galleryData[crt].credit;

      if (galleryData[crt].credit.length === 0 && galleryData[crt].legend.length === 0) {
        AJS.$('gallery_info').style.height          = '0px';
      } else {
        AJS.$('gallery_info').style.height          = ( AJS.$('gallery_legend').offsetHeight + AJS.$('gallery_credit').offsetHeight) + 'px';
      }


      return image;  
    };

    gallery.onImageChange = function(current, max) {
      AJS.$('gallery_prev').className = (KulturAgenda.gallery.hasPrev()) ? 'active' : 'inactive';
      AJS.$('gallery_next').className = (KulturAgenda.gallery.hasNext()) ? 'active' : 'inactive';
      AJS.$('gallery_status').innerHTML = (current + 1) + '/' + KulturAgenda.imageCount;
    }

    gallery.onFinish = function() {KulturAgenda.active = false;}

    AJS.addEventListener(document, 'keyup', function(event) {
        if (event.keyCode == 37 || event.keyCode == 38) {
          KulturAgenda.previous();
        } else if (event.keyCode == 39 || event.keyCode == 40) {
          KulturAgenda.next();
        }
      }
    );
    
    id = gallery.addCategory();
    for (i in galleryData) {
        url = galleryData[i].src;
        url = url.replace(/&amp;/g, '&');
        gallery.addImage(id, url,galleryData[i].width,galleryData[i].height);
    }
    gallery.setCategory(id);
    KulturAgenda.imageCount = galleryCount;
    KulturAgenda.gallery = gallery;
    KulturAgenda.holder = holder;
  },

  previous : function() {
    if (KulturAgenda.active == true) {
        return;
    }
    KulturAgenda.active = true;
    if (KulturAgenda.gallery.getPrev() == false) {
      KulturAgenda.active = false;
    }
  },

  next : function() {
    if (KulturAgenda.active == true) {
        return;
    }
    KulturAgenda.active = true;
    if (KulturAgenda.gallery.getNext() == false) {
      KulturAgenda.active = false;
    }
  }

};

//<TO_BE_ FIXED>

/**
 * class for scrolling buttons in a contanier with date functionality
 * @author Simon <simon.hiller@fugu.ch>
 */
function ScrollingButtons(elem, opts){
	if(!elem)return;
	
	this.options = {
		style: 'left',
		moveModifier: 7,
		moveDates: 7,
		from: new Date(new Date().getTime()-ScrollingButtons.daysToMilliSecs(3)),
		active: new Date(),
		nbrOfButtons: 7,
		classModifier: 3,
		onlyFutureClass: false,
		hidePrevButton: false,
		duration: 500,
		fps: 50,
		transition: AJS.fx.Transitions.sineInOut
	};
	
	KulturAgenda.extend(this.options,opts);
	
	this.options.from.normalize();
	this.options.active.normalize();
	
	this.options.hidePrevButton =  ((!AJS.isIe())&&this.options.hidePrevButton);
	this.ctn = elem;
	this.fw = AJS.$bytc('a','cal_button_next',this.ctn)[0];
   this.fw.style.display = 'block';

	this.bw = AJS.$bytc('a','cal_button_prev',this.ctn)[0];
	this.bw.onresize = null;

  if(!this.options.hidePrevButton){
		this.bw.style.display = 'block';
	}
	if(this.options.hidePrevButton){
		this.fade = new AJS.fx.Styles(this.bw,{
			duration : 800,
			onComplete: AJS.bind(this.updateFade,this)
		});
		this.fade.to = {opacity:1};
	}
	
	var dateTime = ScrollingButtons.daysToMilliSecs(this.options.moveDates);
	this.dateFrom = new Date(this.options.from.getTime()-dateTime);
	this.dateTo = new Date(this.options.from.getTime()+(dateTime+ScrollingButtons.daysToMilliSecs(this.options.nbrOfButtons)));
	
	this.buttonCtn = AJS.DIV({className:'button_container'});
	this.buttonWrap =  AJS.DIV({className:'button_wrapper'});
	this.buttonConf = {width:0,height:0};
	this.initializeButtons().updateButtons();

	this.fx = new AJS.fx.Style(this.buttonCtn,this.options.style, {
		onComplete: AJS.bind(this.updateButtons,this),
		duration: this.options.duration,
		fps: this.options.fps,
		transition: this.options.transition
	});
	AJS.addEventListener(this.fw, 'click', AJS.bind(this.next,this));
	AJS.addEventListener(this.bw, 'click', AJS.bind(this.prev,this));
	//little fix for chromes asynchron loadproblems
	if (document.addEventListener){
		var $this = this;
      document.addEventListener('DOMContentLoaded', function(){$this.updateButtons();delete $this;}, false);
   }
}
ScrollingButtons.prototype.next = function(evt){
	var value = parseInt(this.buttonCtn.style[this.options.style]);
	this.fx.custom(value, value-this.computeMoveValue());
	this.updateDates(this.options.moveDates);
}
ScrollingButtons.prototype.prev = function(evt){
	if(this.options.hidePrevButton){
		if((this.dateFrom.getTime()+(this.options.moveDates))<this.options.from.getTime()){
			return;		
		}
	}
	
	var value = parseInt(this.buttonCtn.style[this.options.style]);
	this.fx.custom(value, value+this.computeMoveValue());
	this.updateDates(-this.options.moveDates);
}
ScrollingButtons.prototype.computeMoveValue = function(){
	return Math.max(1,this.options.moveModifier)*(this.options.style==='left'?this.buttonConf.width:this.buttonConf.height);
}
ScrollingButtons.prototype.initializeButtons = function(){
	AJS.map(AJS.$bytc('*','date_ver_s',this.ctn),function(item){
		AJS.removeElement(item);item = null;
	});
	AJS.insertBefore(this.buttonWrap, this.fw);
	AJS.appendChildNodes(this.buttonWrap, this.buttonCtn);
	//get the buttonconfig
	var button = KulturAgenda.insertDateButton({
		d:this.dateFrom
	}, this.buttonCtn);
	button = this.buttonCtn.childNodes[0];
	this.buttonConf = {
		width: button.offsetWidth+2,
		height: button.offsetHeight+2
	}
	return this;
}
ScrollingButtons.prototype.updateButtons = function(){
	var i = 0, button = this.buttonCtn.childNodes[0];;
	this.buttonConf = {
		width: button.offsetWidth+2,
		height: button.offsetHeight+2
	}
	//delete all old buttons
	while(this.buttonCtn.childNodes.length>0){
		button = this.buttonCtn.childNodes[0];
		AJS.removeElement(button);button = null;
	}
	var dateTime = ScrollingButtons.milliSecsPerDay;
	var d = new Date(this.dateFrom.getTime());
	//we add 4 hours for the summer/winter time fix
	var diff = this.options.classModifier*dateTime + (4*1000*3600);
	var center = this.options.active.getTime();
	var l = this.dateTo.getTime();
	var act = new Date().normalize().getTime();
	var newDiff = 0, classNumber = 0;
	for(i = this.dateFrom.getTime();i<l;i+=dateTime){
		d.setTime(i);
		newDiff = this.options.onlyFutureClass?i-center:Math.abs(i-center);
		button = KulturAgenda.insertDateButton({d:d}, this.buttonCtn);
		if(newDiff<=diff && newDiff>=0){
			classNumber = Math.round(newDiff/dateTime);
			if(classNumber>=1){
				AJS.addClass(button,"bg_2_"+classNumber);
			}
		}
		else {
			if(act>i) {
                if (button.href.length < 5) {
                    AJS.addClass(button,"bg_2_7");
                } else {
                    AJS.addClass(button,"bg_2_4");
                }
            } else {
                AJS.addClass(button,"bg_2_4");
            }
		}
	}
	this.buttonCtn.style[this.options.style] = (-this.computeMoveValue())+"px";

	if(this.options.hidePrevButton){
		if((this.dateFrom.getTime()+(this.options.moveDates))<this.options.from.getTime()){
			if(this.fade.to.opacity === 1)
				this.fade.custom({opacity:[1,0],height:[15,0]});
		}else if(this.fade.to.opacity === 0){
			this.bw.style.display = 'block';
			AJS.setStyle(this.bw,'display','block');
			this.fade.custom({opacity:[0,1],height:[0,15]});
		}
	}
	return this;
}
ScrollingButtons.prototype.updateDates = function(value){
	value = ScrollingButtons.daysToMilliSecs(value);
	this.dateFrom.setTime(this.dateFrom.getTime()+value);
	this.dateTo.setTime(this.dateTo.getTime()+value);	
	return this;
}
ScrollingButtons.prototype.updateFade = function(value){
	if(this.fade.to.opacity == 0)AJS.setStyle(this.bw,'display','none');
}
/**
 * Static vars and functions
 */
KulturAgenda.extend(ScrollingButtons, {
	milliSecsPerDay: (24 * 60 * 60 * 1000),
	daysToMilliSecs: function(value){return ScrollingButtons.milliSecsPerDay*value;},
	milliSecsToDays: function(value){return Math.floor(ScrollingButtons.milliSecsPerDay/value);}
})



function unscrambleLink (id, sUrl, sText, isEmail) {
  var obj = document.getElementById (id);
  if (obj == null) {
    alert ('unscrambleLink: Object not found (' + id + ')');
    return;
  }
  var parent = obj.parentNode;
  if (parent == null) {
    alert ('unscrambleLink: Parent object not found');
    return;
  }
  if (parent.nodeName.toLowerCase () == 'div') parent = parent.firstChild;
  if (parent.nodeName.toLowerCase () != 'a') {
    alert ('unscrambleLink: Parent object is not an anchor tag');
    return;
  }
  if (sUrl != null && sUrl.length > 0) {
    eval ('var txt = String.fromCharCode(' + sUrl + ');');
    parent.href = txt;
  }
  if (sText != null && sText.length > 0) {
    var firstChild = parent.firstChild;
    if (firstChild && firstChild.nodeType == 3 && firstChild.nodeValue != null && firstChild.nodeValue.replace (' ', '').length > 0) return;
    eval ('var txt = String.fromCharCode (' + sText + ');');
    txt = txt.replace (/&amp;/g, '&');
    parent.innerHTML = txt;
    if (parent.title != null && parent.title.length == 0) {
      parent.title = txt;
  }
  }
}


window.KG = KulturAgenda;


function b(text, link, clas, radius, elm, ret) {
    link = link || false;
    clas = clas || '';
    radius = radius || 5;
    elm = (link) ? ['a href="' + link + '"', 'a'] : ['span', 'span'];
    ret  =  '<' + elm[0] + '  class="r r_' + radius + ' ' + clas + '" >';
    ret += '<span class="rtl rs"></span><span class="rtr rs"></span>';
    ret += '<span class="rc" >' + text + '</span>';
    ret += '<span class="rbl rs"></span><span class="rbr rs"></span>';
    return ret  + '</' + elm[1] + '>';
}
