/* PC Global */

var PC = {
	sitetitle: '',
	init: function() {
		/* Text Size Change */
		var textsizelinks = $(document.body).select('.textsizelink');
		textsizelinks.each(function(lnk) {
			switch (lnk.rel) {
				case "plus":
					Event.observe(lnk, 'click', function() { PC.set_textsize('plus'); });
				break;
				case "min":
					Event.observe(lnk, 'click', function() { PC.set_textsize('min'); });
				break;
			}
		});
		var textsize = this.getCookie('textsize');
		if (textsize) {
			this.set_textsize(textsize);
		}
		
		// help icons
		/*
		var helpicons = $$('img.help');
		helpicons.each(function(icon) {
			if (!icon.id || $(icon.id+'_info')) { return; }
			new Tip($(icon), $(icon.id+'_info'), {
				style: 'default',
				radius: 1,
				border: 1,
				width: 'auto',
				hideOthers: true
			});
		});
		*/
	},
	socialshare: function(btn,linktitle,linkurl,linkdesc,linksource,replace,windowconf) {
		if (!$(btn)) { return false; }
		if ($(btn).prototip && replace == false) {
			$(btn).prototip.show();
			return;
		}
		if ($(btn).prototip) {
			$(btn).prototip.remove();
		}
		
		var defaultwindowoptions = {
					style: 'ihvn-orange',
					stem: 'topMiddle',
					hook: { target: 'bottomMiddle', tip: 'topMiddle' },
					offset: { x: -5, y: 2 }
				};
		
		if (!windowconf) {
			var windowconf = {
				title: '',
				desc: '',
				options: defaultwindowoptions
			};
		} else if (!windowconf.options) {
			windowconf['options'] = defaultwindowoptions;
		}

		var socialdiv = new Element('div', { 'class': 'socialshare' });
		if (windowconf['desc']) {
			var socialdesc = new Element('div', { 'class': 'desc' } ).update(windowconf['desc']);
			socialdiv.appendChild(socialdesc);
		}
		var socialtools = new Element('div', { 'class': 'tools' });
		var iframe = new Element('iframe', { allowtransparency: true, frameborder:'0', scrolling: 'no', style: 'width:100px;height:21px;', 
			src: 'http://platform1.twitter.com/widgets/tweet_button.html?text='+encodeURIComponent(linktitle)+'&via='+encodeURIComponent(linksource)+'&lang=nl&url='+encodeURIComponent(linkurl)+'' });
		var div = new Element('div', { 'class': 'twitter' }).update(iframe);
		socialtools.appendChild(div);
		
		iframe = new Element('iframe', { allowtransparency: true, frameborder:'0', scrolling: 'no', style: 'border:none; overflow:hidden; width:80px; height:21px;', 
			src: 'http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(linkurl)+'&layout=button_count&show_faces=false&width=80&action=recommend&colorscheme=light&height=21' });
		div = new Element('div', { 'class': 'facebook' }).update(iframe);
		socialtools.appendChild(div);
		
		div = new Element('div', { 'class': 'linkedin' }).update(new Element('a', { href:'http://www.linkedin.com/shareArticle?mini=true&url='+escape(linkurl)+'&title='+escape(linktitle)+'&summary='+escape(linkdesc)+'&source='+escape(this.sitetitle)+'', target: '_blank' } ).update('<img src="/pincity/designs/ihvnv5/images/linkedin.gif" width="70" height="20">'));
		socialtools.appendChild(div);

		div = new Element('div', { 'class': 'hyves', id: 'hyves_'+btn }).update('');
		socialtools.appendChild(div);
		
		div = new Element('div', { 'class': 'email' }).update('<a href="#"><img src="/pincity/designs/ihvnv5/images/emailforward.png" width="24" height="24" border="0"> Doorsturen via e-mail</a>');
		socialtools.appendChild(div);
		
		socialdiv.appendChild(socialtools);
		
		var windowoptions = {
			radius: 4,
			width: 'auto',
			showOn: 'click',
			hideOn: { element: 'closeButton', event: 'click' },
			hideOthers: true
		};
		if (windowconf.title) {
			windowoptions['title'] = windowconf.title;
		}
		var windowkeys = ['style','stem','hook','offset'];
		windowkeys.each(function(key) {
			if (windowconf.options && windowconf.options[key]) {
				windowoptions[key] = windowconf.options[key];
			}
		});
	
		new Tip($(btn), socialdiv, windowoptions);
		$(btn).prototip.show();
		
		Hyves.connect.tip({title: linktitle, body:((linkdesc) ? linkdesc : linktitle)+'\n\n[url='+linkurl+']'+linkurl+'[/url]', category:'12', rating:'5'}, {iconsize:24},'hyves_'+btn);
	},
	
	textsize: 0,
	textsizes: { plus: ['large'], min: ['small','x-small'] },
	set_textsize: function(dir) {
		var newtextsize = 0;
		var newtextstr = '';
		switch (dir) {
			case "plus":
				newtextsize = this.textsize + 1;
				if (newtextsize == 0) {
					newtextstr = '';
				} else if (newtextsize<0) {
					newtextstr = this.textsizes.min[((newtextsize*-1)-1)];
				} else {
					if (!this.textsizes.plus[(newtextsize-1)]) {
						newtextsize--;
					}
					newtextstr = this.textsizes.plus[(newtextsize-1)];
				}
			break;
			case "min":
				newtextsize = this.textsize - 1;
				if (newtextsize == 0) {
					newtextstr = '';
				} else if (newtextsize>0) {
					newtextstr = this.textsizes.plus[(newtextsize-1)];
				} else {
					if (!this.textsizes.min[((newtextsize*-1)-1)]) {
						newtextsize++;
					}
					newtextstr = this.textsizes.min[((newtextsize*-1)-1)];
				}
			break;
			default:
				dir = parseInt(dir);
				if (dir == 0) {
					return false;
				}
				if (dir<0) {
					if (!this.textsizes.min[((dir*-1)-1)]) {
						return false;
					} 
					newtextstr = this.textsizes.min[((dir*-1)-1)];
				} else {
					if (!this.textsizes.plus[(dir-1)]) {
						return false;
					}
					newtextstr = this.textsizes.plus[(dir-1)];
				}
				newtextsize = dir;
			break;
		}
		$$('body')[0].style.fontSize = newtextstr;
		this.setCookie('textsize',newtextsize,1);
		this.textsize = newtextsize;
		if ($('textsizestatus')) {
			if (newtextstr == '') {
				$('textsizestatus').update('');
				
			} else {
				var status = '';
				switch(newtextstr) {
					case "large":
						status = 'groot';
					break;
					case "small":
						status = 'klein';
					break;
					case "x-small":
						status = 'extra klein';
					break;
				}
				$('textsizestatus').update('Huidige grootte: '+status);
				$('textsizestatus').show();
			}
		}
	},
	setCookie: function(c_name,value,expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +this.escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
		((this.domain==null) ? "" : ";domain="+this.domain+"");
	},
	getCookie: 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));
			}
		}
		return "";
	},
	escape: function(txt) {
		return escape(txt).replace( 
			new RegExp( "\\+", "g" ), 
			"%2B" 
		);
	}
};
document.observe("dom:loaded", function() {
	PC.init();
});

/*
	News Bits
*/

var PC_latestnews = {
	containers: ['social'], // ,'replies'
	newsitems: [],
	sitetitle: '',
	init: function() {
		if (!$('latestnewsbits')) { return false; }
		var newsbits = $('latestnewsbits').select('li.latestnewsbit');
		newsbits.each(function(newsbit) {
			var newsid = newsbit.id.replace(/^latestnewsbit_/,'');
			PC_latestnews.newsitems.push(newsid);
			$('latestnewsbit_'+newsid).select('div.left')[0].id = 'latestnewsbit_title_'+newsid;
			$('latestnewsbit_'+newsid).select('div.left a')[0].id = 'latestnewsbit_link_'+newsid;
			
			var itemlink = $('latestnewsbit_'+newsid).select('div.left a')[0];
			var itemtitle = itemlink.innerHTML;
			$('latestnewsbit_'+newsid).select('div.latestnewssnippet')[0].id = 'latestnewssnippet_snippet_'+newsid;
			
			$('latestnewsbit_'+newsid).select('div.footer span.reset')[0].id = 'latestnewsbit_reset_'+newsid;
			$('latestnewsbit_'+newsid).select('div.footer span.reset a')[0].id = 'latestnewsbit_resetlink_'+newsid;
			Event.observe($('latestnewsbit_resetlink_'+newsid), 'click', function() { PC_latestnews.reset(this.id.replace(/^latestnewsbit_resetlink_/,'')); });
			
			$('latestnewsbit_'+newsid).select('div.socialtools')[0].id = 'latestnewsbit_social_'+newsid;
			$('latestnewsbit_'+newsid).select('div.footer a.social')[0].id = 'latestnewsbit_sociallink_'+newsid;
			Event.observe($('latestnewsbit_sociallink_'+newsid), 'click', function() { PC_latestnews.social(this.id.replace(/^latestnewsbit_sociallink_/,''),-1); });
			
			//$('newsbit_'+newsid).select('div.replies')[0].id = 'newsbit_replies_'+newsid;
			//$('newsbit_'+newsid).select('div.footer a.replies')[0].id = 'newsbit_replieslink_'+newsid;
			//Event.observe($('newsbit_replieslink_'+newsid), 'click', function() { PC_latestnews.replies(this.id.replace(/^newsbit_replieslink_/,''),-1); });
			
			new Tip(itemlink, $('latestnewssnippet_snippet_'+newsid), {
				title: itemtitle,
				style: 'ihvn-orange',
				radius: 4,
				stem: 'rightTop',
				hook: { target: 'topLeft', tip: 'rightTop' },
				offset: { x: -5, y: 2 },
				width: 'auto',
				hideOn: false,
				hideAfter: 2,
				hideOthers: true
			});
			
			$(itemlink).observe('prototip:shown', function() { PC_latestnews.reset(this.id.replace(/^latestnewsbit_link_/,'')); });
			
		});
	},
	social: function(id,state) {
		if (state==-1) {
			state = $('latestnewsbit_social_'+id).visible() ? 1 : 0;
		}
		switch (state) {
			case 0:
			
				if ($('latestnewssnippet_snippet_'+id).select('div.socialtools')[0].select('div.tools')[0].innerHTML == '') {
					var newsurl = $('latestnewsbit_title_'+id).select('a')[0].href;
					var newstitle = $('latestnewsbit_title_'+id).select('a')[0].innerHTML;
					var newsmessage = $('latestnewssnippet_snippet_'+id).select('span.message')[0].innerHTML;
					var toolscon = $('latestnewssnippet_snippet_'+id).select('div.socialtools')[0].select('div.tools')[0];

					var iframe = new Element('iframe', { allowtransparency: true, frameborder:'0', scrolling: 'no', style: 'width:100px;height:21px;', 
						src: 'http://platform.twitter.com/widgets/tweet_button.html?url='+encodeURI(newsurl)+'&text='+encodeURI(newstitle)+'&via='+encodeURI(this.sitetitle)+'&lang=nl' });
					var div = new Element('div', { 'class': 'twitter' }).update(iframe);
					toolscon.appendChild(div);
					
					iframe = new Element('iframe', { allowtransparency: true, frameborder:'0', scrolling: 'no', style: 'border:none; overflow:hidden; width:80px; height:21px;', 
						src: 'http://www.facebook.com/plugins/like.php?href='+encodeURI(newsurl)+'&layout=button_count&show_faces=false&width=80&action=recommend&colorscheme=light&height=21' });
					div = new Element('div', { 'class': 'facebook' }).update(iframe);
					toolscon.appendChild(div);
					
					div = new Element('div', { 'class': 'linkedin' }).update(new Element('a', { href:'http://www.linkedin.com/shareArticle?mini=true&url='+encodeURI(newsurl)+'&title='+encodeURI(newstitle)+'&summary='+encodeURI(newsmessage)+'&source='+encodeURI(this.sitetitle)+'' } ).update('<img src="/pincity/designs/ihvnv5/images/linkedin.gif" width="70" height="20">'));
					toolscon.appendChild(div);

					div = new Element('div', { 'class': 'hyves', id: 'newssnippet_hyves_'+id }).update('');
					toolscon.appendChild(div);
					
					Hyves.connect.tip({title: newstitle, body:newsmessage+'\n\n[url='+newsurl+']'+newsurl+'[/url]', category:'12', rating:'5'}, {iconsize:24},'newssnippet_hyves_'+id);
					
					div = new Element('div', { 'class': 'email' }).update('<a href="#"><img src="/pincity/designs/ihvnv5/images/emailforward.png" width="24" height="24" border="0"> Doorsturen via e-mail</a>');
					toolscon.appendChild(div);
				}
			
				$('latestnewssnippet_snippet_'+id).select('div.snippet')[0].hide();
				this.showcontainer(id,'social');
			break;
			case 1: 
				this.reset(id);
			break;
		}
	},
	replies: function(id,state) {
		if (state==-1) {
			state = $('latestnewsbit_replies_'+id).visible() ? 1 : 0;
		}
		switch (state) {
			case 0:
				$('latestnewssnippet_snippet_'+id).select('div.snippet')[0].hide();
				this.showcontainer(id,'replies');
			break;
			case 1: 
				this.reset(id);
			break;
		}
	},
	reset: function(id) {
		this.showcontainer(id,false);
		$('latestnewsbit_reset_'+id).hide();
		$('latestnewssnippet_snippet_'+id).select('div.snippet')[0].appear({ duration: 0.1 });
	},
	showcontainer: function(id,show) {
		if (show) { $('latestnewsbit_reset_'+id).show(); }
		this.containers.each(function(container) {
			if (container == show) {
				$('latestnewsbit_'+container+'_'+id).appear({ duration: 0.1 });
			} else {
				$('latestnewsbit_'+container+'_'+id).hide();
			}
		});
	}
}
document.observe("dom:loaded", function() {
	PC_latestnews.init();
});

/* Nav */

var PC_nav = {
	navconf: [],
	selectednav: false,
	currentnav: false,
	subnavheight: '38px',
	timeout: 0,
	slidedowntimeout: 0,
	slideuptimeout: 0,
	reset_timeout: 2500,
	slideup: false,
	
	init: function() {
		if (!$('navtabs')) { return false; }
		var navtabs = $('navtabs').select('li');
		navtabs.each(function(navtab) {
			var navid = navtab.id.replace(/^navtab-/,'');
			PC_nav.navconf.push({ id: navid, subnav: (($('sub-nav-'+navid)) ? true : false)});
		});
		this.navconf.each( function(item) {
			if ($('navtab-'+item.id).className == 'current-tab') {
				PC_nav.selectednav = item.id;
				var selectednav = PC_nav.get_subnav(item.id);
				if (selectednav.subnav) {
					PC_nav.state('show',selectednav.id);
					PC_nav.currentnav = selectednav.id;
				}
			}
			Event.observe($('navtab-'+item.id), 'mouseover', function() { PC_nav.navhover(1,this.id.replace(/^navtab-/,'')); });
			Event.observe($('navtab-'+item.id), 'mouseout', function() { PC_nav.navhover(0,this.id.replace(/^navtab-/,'')); });
			if (item.subnav) {
				Event.observe($('sub-nav-'+item.id), 'mouseover', function() { PC_nav.subnavhover(1,this.id.replace(/^sub-nav-/,'')); });
				Event.observe($('sub-nav-'+item.id), 'mouseout', function() { PC_nav.subnavhover(0,this.id.replace(/^sub-nav-/,'')); });
			}
		});
		if ($('navtab-login')) {
			Event.observe($('navtab-login'), 'click', function() { PC_nav.login(); });
		}
	},
	
	navhover: function(state,name) {
		var subnav = this.get_subnav(name);
		if (!subnav) { return false; }
		switch(state) {
			case 1:
				if (this.slideup) {
					this.slideup.cancel();
					this.slideup = false;
					//$('sub-nav-'+this.currentnav).hide();
				}
				if (subnav.subnav) {
					if (this.timeout) {
						clearTimeout(this.timeout);
					}
					this.navconf.each( function(item) {
						$('navtab-'+item.id).className = '';
					} );
					$('navtab-'+subnav.id).className = 'current-tab';
					if (!$('sub-nav-'+subnav.id).visible()) {
						var subnav_visible = false;
						this.navconf.each( function(item) {
							if (item.subnav && $('sub-nav-'+item.id).visible()) {
								subnav_visible = item.id;
							}
						} );
						if (subnav_visible) {
							PC_nav.state('replace',[subnav_visible,subnav.id]);
						} else {
							PC_nav.state('down',subnav.id);
						}
					} else {
						this.navconf.each( function(item) {
							if (item.subnav && item.id != subnav.id) {
								$('sub-nav-'+item.id).hide();
								$('sub-nav-'+item.id).style.height = PC_nav.subnavheight;
							}
						} );
					}
					this.currentnav = subnav.id;
				} else {
					this.navconf.each( function(item) {
						$('navtab-'+item.id).className = '';
					} );
					if (this.currentnav) {
						clearTimeout(this.timeout);
						this.state('up',this.currentnav);
					} else {
						if (this.timeout) {
							clearTimeout(this.timeout);
						}
					}
					$('navtab-'+subnav.id).className = 'current-tab';
				}
			break;
			case 0:
				if (subnav.subnav) {
					this.timeout = window.setTimeout(function() {
						if ($('sub-nav-'+subnav.id).visible()) {
							if (PC_nav.selectednav) {
								PC_nav.navconf.each( function(item) { $('navtab-'+item.id).className = ''; } );
								var selectednav = PC_nav.get_subnav(PC_nav.selectednav);
								if (selectednav) {
									$('navtab-'+selectednav.id).className = 'current-tab';
									if (selectednav.subnav) {
										PC_nav.state('replace',[subnav.id,selectednav.id]); 
										PC_nav.currentnav = selectednav.id;
									} else {
										PC_nav.state('up',subnav.id,true);
									}
								}
							} else {
								PC_nav.state('up',subnav.id,true);
								PC_nav.navconf.each( function(item) { $('navtab-'+item.id).className = ''; } );
							}
						}
					},this.reset_timeout);
				} else {
					this.timeout = window.setTimeout(function() {
						if (PC_nav.selectednav) {
							PC_nav.navconf.each( function(item) { $('navtab-'+item.id).className = ''; } );
							var selectednav = PC_nav.get_subnav(PC_nav.selectednav);
							if (selectednav) {
								$('navtab-'+selectednav.id).className = 'current-tab';
								if (selectednav.subnav) {
									PC_nav.state('down',selectednav.id);
									PC_nav.currentnav = selectednav.id;
								}
							}
						} else {
							PC_nav.navconf.each( function(item) { $('navtab-'+item.id).className = ''; } );
						}
					},this.reset_timeout);
				}
			break;
		}
	},
	subnavhover: function(state,name) {
		switch(state) {
			case 1:
				if (this.timeout) {
					clearTimeout(this.timeout);
				}
			break;
			case 0:
				this.navhover(state,name);
			break;
		}
	},
	get_subnav: function(name) {
		var subnav = false;
		this.navconf.each(function(item) { 
			if (item.id == name) { 
				subnav = item;
			}
		});
		if (!subnav) {
			alert('Error: invalid subnav item ('+name+')');
			return false;
		} else {
			return subnav;
		}
	},
	state: function(state,name,slow) {
		switch (state) {
			case "show":
				$('sub-nav-'+name).show();
			break;
			case "hide":
				$('sub-nav-'+name).hide();
			break;
			case "up":
				if (slow) {
					PC_nav.slideup = Effect.SlideUp('sub-nav-'+name, { duration: 0.5 , transition: Effect.Transitions.sinoidal, afterFinish: function() { $('sub-nav-'+name).style.height = PC_nav.subnavheight; } } );
				} else {
					PC_nav.slideup = Effect.SlideUp('sub-nav-'+name, { duration: 0.2, afterFinish: function() { $('sub-nav-'+name).style.height = PC_nav.subnavheight; } } );
				}
			break;
			case "down":
				if (this.slideup) { 
					this.slideup.cancel();
					this.slideup = false;
				}
				PC_nav.navconf.each( function(item) {
					if (item.subnav) {
						$('sub-nav-'+item.id).hide();
						$('sub-nav-'+item.id).style.height = PC_nav.subnavheight;
					}
				} );
				PC_nav.slideup = Effect.SlideDown('sub-nav-'+name, { duration: 0.3, transition: Effect.Transitions.sinoidal, afterFinish: function() { $('sub-nav-'+name).style.height = PC_nav.subnavheight; } });
			break;
			case "replace":
				if (this.slideup) { 
					this.slideup.cancel();
					this.slideup = false;
				}
				$('sub-nav-'+name[0]).hide();
				$('sub-nav-'+name[1]).show();
				$('sub-nav-'+name[1]).style.height = PC_nav.subnavheight;
			break;
		}
	},
	login: function() {
		if (!$('navtab-login')) { return false; }
		if ($('navtab-login').prototip) {
			$('navtab-login').prototip.show();
		} else {
			var boxtitle = $('navbarlogin').select('.title')[0].innerHTML;
			var boxcontent = $('navbarlogin').select('.content')[0];
			new Tip($('navtab-login'), boxcontent, {
				title: boxtitle,
				style: 'ihvn-orange',
				border:2,
				radius: 2,
				stem: 'topRight',
				hook: { target: 'bottomMiddle', tip: 'topRight' },
				offset: { x: 4, y: -7 },
				width: 400,
				showOn: 'click',
				hideOn: { element: 'closeButton', event: 'click' },
				hideOthers: true
			});
			$('navtab-login').prototip.show();
		}
	}
};
document.observe("dom:loaded", function() {
	PC_nav.init();
});

/* Simulate */
(function(){
  
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }
  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  }
  
  Event.simulate = function(element, eventName) {
    var options = Object.extend(defaultOptions, arguments[2] || { });
    var oEvent, eventType = null;
    
    element = $(element);
    
    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView, 
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  }
  
  Element.addMethods({ simulate: Event.simulate });
})();
