var gadgetUserId = '0';

var mapsMenu = {
	init: function() {
		var gmap_menu = $('gmap-menu');
		if (gmap_menu) {
			var inputs = $$('#gmap-menu ul li input')
      inputs.each(function(input) {
        input.hide();
        var list_item = input.up();

				if(input.checked == true){
					list_item.addClassName('selected');
				}

				input.observe('click', function(){
					if(input.checked == true){
						list_item.addClassName('selected');
					}else{
						list_item.removeClassName('selected');
					}
				});

				list_item.observe('click', function(){
					if(list_item.hasClassName('selected')){
						list_item.removeClassName('selected');
						input.checked = false;
					}else{
						list_item.addClassName('selected');
						input.checked = true;
					}
					gmap_menu.submit();
				});
		  });
		}
	}
}

var menu = {
	init: function(){
    $$('.submenu-categories').each(function(el)
    {
      var list = el.firstDescendant();
      el.setStyle({height: (list.childElements().length * 20 + 20) + 'px'});
    });
	}
}

var tooltips = {
	init: function(){

  	$$('a.star-rate').each(function(el){
			el.observe('click', function(e){
				var linkObject = this;
				var itemId = linkObject.rel.substr(5, linkObject.rel.length - 7);
        var itemType = linkObject.rel.substr(0, 4);
				var ratingValue = linkObject.rel.substr(linkObject.rel.length - 1);

				Event.stop(e);

        var url = '/rate/' + itemId;

        if(itemType == 'surv'){
          var url = '/enquete-rate/' + itemId;
        }

				var holder = linkObject.ancestors()[2];

				new Ajax.Request(url, {
  				method: 'post',
  				parameters: { rating:ratingValue },
  				onSuccess: function(transport){
  					holder.innerHTML = 'Bedankt voor je stem!';
				  }
		    });
			});
		});

  	$$('.star-content').each(function(el){
      el.observe('mouseover', function(e){
        if(this.down()){
          this.down().childElements().each(function(li){
            li.down().removeClassName('selected');
          });
        }
      });
  	});

    if ($$('.tags')) {
      $$('.tags').each(function(el){
        el.observe('mouseover', function(e){
          this.addClassName('hover');
        });
        el.observe('mouseout', function(e){
          this.removeClassName('hover');
        });
      });
	  }

	  if ($('bookmarks')) {
	    $('bookmarks').observe('mouseover', function(e){
	      this.addClassName('hover');
	    });
	    $('bookmarks').observe('mouseout', function(e){
	      this.removeClassName('hover');
	    });
	  }
	}
}
var carousel = {
	init: function(){
		$$('div.carousel').each(function(el){
			new UI.Carousel(el, {scrollInc:1});
		});
	}
}
var fontSizes = {
	init: function(){

		var results = document.cookie.match ( '(^|;) ?fontSize=([^;]*)(;|$)' );
		if(results)
		{
			var fontSize = results[2];
			if(fontSize == 'normal')
			{
				var fontSizeCss = 'layout.css';
			}
			else
			{
				var fontSizeCss = 'layout-' + fontSize + '.css';
			}
		}
		else
		{
			var fontSize = 'normal';
			var fontSizeCss = 'layout.css';
		}

		if(fontSize != 'normal')
		{
  		if($('font-size-stylesheet')){
  			$('font-size-stylesheet').href = stylesheetPath + fontSizeCss;
  		}
  		else
  		{
  			var stylesheet = document.createElement('link');
  			stylesheet.id = 'font-size-stylesheet';
  			stylesheet.rel = 'stylesheet';
  			stylesheet.type= 'text/css';
  			stylesheet.href = stylesheetPath + fontSizeCss;
  			$('layout-stylesheet').parentNode.appendChild(stylesheet);
  		}
		}

		$$('li.text-size a').each(function(el){
			if(el.rel == fontSize){
				el.addClassName('selected');
			}
			Element.observe(el, 'click', function(e){
				Event.stop(e);
				if(el.rel == 'normal')
				{
					fontSizeCss = 'layout.css';
					if($('font-size-stylesheet')){
      			$('font-size-stylesheet').remove();
      		}
				}
				else
				{
					fontSizeCss = 'layout-' + el.rel + '.css';
      		if($('font-size-stylesheet')){
      			$('font-size-stylesheet').href = stylesheetPath + fontSizeCss;
      		}
      		else
      		{
      			var stylesheet = document.createElement('link');
      			stylesheet.id = 'font-size-stylesheet';
      			stylesheet.rel = 'stylesheet';
      			stylesheet.type= 'text/css';
      			stylesheet.href = stylesheetPath + fontSizeCss;
      			$('layout-stylesheet').parentNode.appendChild(stylesheet);
      		}
				}
				var cookie_date = new Date ( );  // current date & time
				cookie_date.setTime ( cookie_date.getTime() + (86400*7) );
				document.cookie = "fontSize=" + el.rel + "; expires=" + cookie_date.toGMTString();
				fontSize = this.rel;
				$$('li.text-size a').each(function(el){
					if(el.rel == fontSize){
						el.addClassName('selected');
					}else{
						el.removeClassName('selected');
					}
				});
			});
		});
	}
}

document.observe('dom:loaded', function() {
	fontSizes.init();
  menu.init();
  mapsMenu.init();
  tooltips.init();
  carousel.init();
	$$('a').each(function(el){
    if(el.rel.split(' ').indexOf('external') > -1) {
      el.target = '_blank';
    }
	});

	$$('#itemdetail div.broadcast').each(function(el){
    videoPlayback.setVideo(el);
	});

});

var jsonCookie = {
  get: function(c_name) {
    if (document.cookie.length > 0)
    {
      c_start = document.cookie.indexOf(c_name + '=');
      if (c_start != -1)
      {
        c_start = c_start + c_name.length+1;
        c_end = document.cookie.indexOf(';',c_start);
        if (c_end == -1) c_end = document.cookie.length;
        return unescape(document.cookie.substring(c_start, c_end)).evalJSON(true);
      }
    }
    return '{}'.evalJSON(true);
  },
  set: function(c_name, value, expiredays) {
    if (expiredays != undefined)
    {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiredays);
    }
    document.cookie = c_name + '=' + escape(Object.toJSON(value)) + (expiredays == undefined ? '' : ';expires=' + exdate.toGMTString()) + ';domain=.eenvandaag.nl;path=/';
  }
}
var container = {
  init: function() {
    var containers = jsonCookie.get('evContainers');
    $$('.container_link').each(function(el){

      var linkElement = el;
      var containerElement = linkElement.id.substr(0, linkElement.id.length-5);
      if (containers[containerElement] != undefined) {
        if (containers[containerElement] == 1) {
          container.show(linkElement, containerElement);
        } else {
          container.hide(linkElement, containerElement);
        }
      }

      if(linkElement.hasClassName('minus')){
        $$('#' + containerElement + '_content div.broadcast').each(function(el){
          videoPlayback.setVideo(el);
        });
      }

      Element.observe(el, 'click', function(e){

        Event.stop(e);
        if(linkElement.hasClassName('minus')){
          container.hide(linkElement, containerElement);
          if(!linkElement.hasClassName('no_ajax')) {
            container.close(containerElement);
          }
        }else{
          container.show(linkElement, containerElement);
          $$('#' + containerElement + '_content div.broadcast').each(function(el){
            videoPlayback.setVideo(el);
          });
          if(!linkElement.hasClassName('no_ajax')) {
            container.open(containerElement);
          }
        }
      });
    });
  },
  show: function(linkElement, containerElement) {
    $(containerElement+'_content').setStyle({display: 'block'});
    linkElement.removeClassName('plus');
    linkElement.addClassName('minus');
  },
  hide: function(linkElement, containerElement) {
    $(containerElement+'_content').setStyle({display: 'none'});
    linkElement.removeClassName('minus');
    linkElement.addClassName('plus');
  },
  open: function(containerElement) {
    var current = jsonCookie.get('evContainers');
    eval('current.' + containerElement + ' = 1;');
    jsonCookie.set('evContainers', current, 30);
  },
  close: function(containerElement) {
    var current = jsonCookie.get('evContainers');
    eval('current.' + containerElement + ' = 0;');
    jsonCookie.set('evContainers', current, 30);
  }
}
Event.observe(window, 'load', container.init);

var videoPlayback = {
//  isHtml5: navigator.userAgent.match(/iP(ad|od|hone)/i) != null,
  isHtml5: navigator.userAgent.match(/symbian|midp|wap|phone|pocket|mobile|pda|psp/i) != null,

  setVideo: function(el)
  {
    if(!el.videoShown){

      el.videoShown = true;

      link = el.down();
      html5link = link.next();
      if(videoPlayback.isHtml5)
      {
        html5link.observe('click', function(e)
        {
				  Event.stop(e);
				  var video = '<video width="500" height="280" controls="controls" autobuffer autoplay><source src="' + this.href + '" type="video/mp4"></source></video>';
          this.ancestors()[0].update(video);
        });
      }
      else
      {
    		var so = new SWFObject(link.href,link.id,"500","280","9","#FFFFFF");
    		so.addParam('allowfullscreen','true');
    		so.addParam("quality", "high");
    		so.addParam("allowscriptaccess","always");
    		so.write(el.id);
      }

    }
  }
}

var commentCharacterCount = {
  init: function() {
    if($('comment_text'))
    {
      Event.observe('comment_text', 'keyup', function(e){

        var $characterValue = $('comment-form-characterValue');
        var $commentFormValue = $('comment_text').value;
        var $commentFormLength = $('comment_text').value.length;

        $characterValue.update(0 + $commentFormLength);

        if($commentFormLength > 249) {
          $('comment_text').value = $('comment_text').value.substr(0, 249);
        }

      });
    }
  }
}

Event.observe(window, 'load', function()
{

  commentCharacterCount.init();

	var user = jsonCookie.get('evUser');
	var expires = 1200; // sync cookie after 20 minutes

	if(user['id'] != undefined)
	{
    if(user['start'] == undefined)
    {
      user['start'] = Math.floor(new Date().getTime() / 1000);
      jsonCookie.set('evUser', user);
    }

    if((Math.floor(new Date().getTime() / 1000) - user['start']) > expires)
    {
      new Ajax.Request('/sync_cookie', {
        asynchronous: false,
        method: 'post',
        onSuccess: function(transport){
          var user = jsonCookie.get('evUser');
          if(user['id'] != undefined) {
	          user['start'] = Math.floor(new Date().getTime() / 1000);
	          jsonCookie.set('evUser', user);
          }
        }
      });
    }
  }

  var user = jsonCookie.get('evUser');

  if(user['id'] != undefined)
  {
		$('signout').show();
		if($('user-name'))
		{
			$('user-name').update(user['name']);
		}
		if($('c12'))
		{
			$('c12').show();
		}
		if($('gadget-iframe'))
		{
			$('gadget-iframe').src = '/gadget/iframe/' + user['id'];
		}
		if($('comment_name'))
		{
			$('comment_name').value = user['name'];
		}
		if($('comment_remember'))
		{
			$('comment_remember').parentNode.hide();
		}
		if($('comment_captcha') || $('newstip_captcha'))
		{
			if($('comment_captcha'))
			{
				$('comment_captcha').parentNode.hide();
			}
			if($('newstip_captcha'))
			{
				$('newstip_captcha').parentNode.hide();
			}

			$('captcha').parentNode.hide();
		}
		if($('add-del-file') && $('delete-from-file-button'))
		{
			var item_id = $('delete-from-file-button').href.replace(/[^0-9]/g, '');
			new Ajax.Request('/delete_from_file_button/' + item_id, {
		        method: 'post',
		        onComplete: function(transport){
					if(transport.responseText != '')
					{
						$('add-del-file').update(transport.responseText);
					}
		        }
		    });
		}
	}
	else
	{
		if($('signup'))
		{
			$('signup').show();
		}
		if($('signin'))
		{
			$('signin').show();
		}

		var commentName = jsonCookie.get('evCommentName');
		if(commentName['name'] != undefined)
		{
			if($('comment_name'))
			{
				$('comment_name').value = commentName['name'];
			}
			if($('comment_remember'))
			{
				$('comment_remember').checked = 'checked';
			}
		}
	}
}
);

