var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};


/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff == 7 && "1 week ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}


var DEF_VAL   = "Search..."; // Default Value
var here = window.location.href;
if(here.indexOf('people') != -1){
	DEF_VAL = 'Search people...';
}else if(here.indexOf('person') != -1){
	DEF_VAL = 'Search people...';
}else if(here.indexOf('forum') != -1){
	DEF_VAL = 'Search messages...';
}else if(here.indexOf('thread') != -1){
	DEF_VAL = 'Search messages...';
}
var isSafari = (navigator.userAgent.indexOf("AppleWebKit") !=-1); // Detecting not only Safari but WebKit-based browsers

function searchFields() {
	if($('notice')){
		window.setTimeout("Effect.Fade('notice')",5000);
	};
    var theSearchFields = document.getElementsByClassName('search');
	for (var i = theSearchFields.length - 1; i >= 0; i--){
	    if (isSafari) {
	        // Changing type to 'search' from 'text'
	        // and inserting 'autosave,' 'results,' 'placeholder' values for Safari and WebKit-based browsers
	        theSearchFields[i].setAttribute('type', 'search');
	        theSearchFields[i].setAttribute('autosave', 'saved.data');
	        theSearchFields[i].setAttribute('results', '5');
	        theSearchFields[i].setAttribute('placeholder', DEF_VAL);
	    } else {
	        // Doing the 'Live Search'-displaying-&-hiding-stuff for non-WebKit-based browsers
	        if(theSearchFields[i]){
				theSearchFields[i].onfocus    = focusSearch;
	        	theSearchFields[i].onblur     = blurSearch;
	        	if (theSearchFields[i].value=='') theSearchFields[i].value = DEF_VAL;
			}
	    }
	};
}

function focusSearch() {
    if (this.value==DEF_VAL) {
        this.value = '';
    }
}

function blurSearch() {
    if (this.value=='') {
        this.value = DEF_VAL;
    }
}
Event.observe(window,'load',searchFields);
Event.observe(window, 'load', function(){
	if($('form_container')){
		var path = encodeURIComponent(window.location.pathname);
		new Ajax.Updater('form_container','/form.php',{parameters:{route_string: path},evalScripts: true});
	}
});

function decorateQuotes(){
	if($('registered_reply')){
		$$('a.quote_tool').invoke('observe','click',function(evt){
			var elm = Event.element(evt);
			var index = elm.id.replace('quote_','');
			new Ajax.Updater('reply','/ajax_quote.php',{parameters:{id:index},insertion: Insertion.Bottom,onCreate:function(){$('reply').addClassName('loading')},onComplete:function(){$('reply').removeClassName('loading')}});
		});
	}else{
		$$('p.quote_tool').invoke('hide');
	}
};

//Event.observe(window,'load',function(){window.setTimeout(decorateQuotes,2000)});

// Event.observe(window,'load',function(){
// 	$$('p').each(function(s){s.replace('a','b')});
// });

Event.observe(window, 'load', function(){
	$$('img.gravatar.sp').each(function(elm){
		elm.replace('<div class="gravatar" style="position:relative;"><img src="' + elm.src + '" width="' + elm.width + '" height="' + elm.height + '" alt=""/><span class="sp" style="position:absolute; bottom:0; right:0"></span></div>');
	})
	if($('member')){
		$('member').observe('click',function(evt){
			var what = Event.element(evt);
			if(what.hasClassName('forum')){
				var index = what.id.replace('fm_','');
				if(what.checked) {
					what.addClassName('checked');
					$('fmail_' + index).enable();
					$('fmail_' + index).removeClassName('disabled');
					$('fmail_' + index).previous('label').removeClassName('gray');
					new Effect.Highlight('mailexplan',{delay:0.5,duration:4.0});
				}else{
					what.removeClassName('checked');
					$('fmail_' + index).checked = false;
					$('fmail_' + index).disable();
					$('fmail_' + index).addClassName('disabled');
					$('fmail_' + index).previous('label').addClassName('gray');
				}
			}
			if(what.hasClassName('mail')){
				if(what.checked){
					what.addClassName('checked');
				}else{
					what.removeClassName('checked');
				}
			}
		});
	}
	if($('bio') && $('bio').type != 'textarea'){
		//var text = $('bio').innerHTML;
		text = $('bio').innerHTML;
		text = text.gsub(/\baim:([-a-zA-Z0-9_\.,@]+?)(<|\s)/,function(match){return 'AIM: <span class="fake_link aim" id="' + escape(match[1]) + '">' + match[1] + '</span>' + match[2]});
		text = text.gsub(/\bymsgr:([-a-zA-Z0-9_\.,@]+?)(<|\s)/,function(match){return 'Yahoo Messenger: <span class="fake_link ymsgr" id="' + escape(match[1]) + '">' + match[1] + '</span>' + match[2]});
		text = text.gsub(/\bmsnim:([-a-zA-Z0-9_\.,@]+?)(<|\s)/,function(match){return 'MSN: <span class="fake_link msnim" id="' + escape(match[1]) + '">' + match[1] + '</span>' + match[2]});
		text = text.gsub(/\bxmpp:([-a-zA-Z0-9_\.,@]+?)(<|\s)/,function(match){return 'Jabber: <span class="fake_link xmpp" id="' + escape(match[1]) + '">' + match[1] + '</span>' + match[2]});
		text = text.gsub(/\bskype:([-a-zA-Z0-9_\.,@]+?)(<|\s)/,function(match){return 'Skype: <span class="fake_link skype" id="' + escape(match[1]) + '">' + match[1] + '</span>' + match[2]});
		$('bio').update(text);
		$('bio').observe('click',function(evt){
			elm = Event.element(evt);
			if(elm.hasClassName('aim')){
				Event.stop(evt);
				return window.location.href = 'aim:goim?screenname=' + unescape(elm.id);
			}
			if(elm.hasClassName('ymsgr')){
				Event.stop(evt);
				return window.location.href = 'ymsgr:sendIM?' + unescape(elm.id);
			}
			if(elm.hasClassName('msnim')){
				Event.stop(evt);
				return window.location.href = 'msnim:chat?contact=' + unescape(elm.id);
			}
			if(elm.hasClassName('xmpp')){
				Event.stop(evt);
				return window.location.href = 'xmpp:' + unescape(elm.id);
			}
			if(elm.hasClassName('skype')){
				Event.stop(evt);
				return window.location.href = 'skype:' + unescape(elm.id) + '?call';
			}
		});
	}
	
	var months = $H({'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'});
	var days = $H({1:'01',2:'02',3:'03',4:'04',5:'05',6:'06',7:'07',8:'08',9:'09'});
	var cal = $$('.date');
	cal.each(function(elm){
		var dt = elm.innerHTML;
		var y = dt.sub(/(\d+?) (.+?) (\d{4}), (\d+):(\d+) (am|pm)/,function(match){return (match[3] + '-' + months[match[2]] + '-' + ((days[match[1]]) ? days[match[1]] : match[1]) + 'T' + ((match[6] == 'pm' && parseInt(match[4]) < 12) ? (parseInt(match[4]) + 12) : match[4]) + ':' + match[5] + ':00Z') });
		var pretty = prettyDate(y);
		if(pretty) elm.update(pretty)
	});
	
});

document.observe('dom:loaded',function(){
	var here = $$('input[type="hidden"]').find(function(elm){return elm.name == 'object' && elm.getValue() == 'message'});
	if(here){
		var f = here.up('fieldset.quiet');
		var s = f.down('input.search');
		if(f && s){
			var q = $F(s);
			var t = f.up('form');
			var d = new Element('div',{id:'filter_form'});
			f.insert(d);
			d.update('<p class="tiny" id="searchfilterwrap">Filter: <label class="inline"><input type="radio" class="tiny" name="searchfilter" id="no_filter" value="none" /> None</label> &nbsp; <label class="inline"><input type="radio" class="tiny" name="searchfilter" id="pro_filter" value="pro" /> Pro</label> &nbsp; <label class="inline"><input type="radio" class="tiny" name="searchfilter" id="express_filter" value="express" /> Express</label></p>');
			$('searchfilterwrap').observe('click',function(evt){
				q = $F(s);
				var filters = t.getInputs('radio','searchfilter').find(function(radio) { return radio.checked; });
				if(q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != DEF_VAL && q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != ''){
					q = q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '');
					var filter = (filters) ? filters.value : '';
					switch (filter){
						case 'pro':
						case 'express':
							q += ' +' + filter;
							break;
						default:
						break;
					}
					s.value = q;
					s.focus();
				}
				t.getInputs('radio').each(function(elm){elm.checked = q.include('+' + elm.value)});
				if(q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != DEF_VAL && q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != '' && t.getInputs('radio').pluck('checked').without(false).length == 0) $('no_filter').checked = true;
			});
			t.getInputs('radio').each(function(elm){elm.checked = q.include('+' + elm.value)});
			if(q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != '' && q.replace(/\+pro|\+express/,'').replace(/^\s+|\s+$/g, '') != DEF_VAL && t.getInputs('radio').pluck('checked').without(false).length == 0) $('no_filter').checked = true;
		}
	}
	$$('#reset_unread').invoke('observe','click',function(evt){
		Event.stop(evt);
		var tgt = $('reset_unread').up();
		new Ajax.Updater(tgt,'ajax_reset_unread.php',{
			onCreate:function(){
				tgt.update('<img src="/Resources/spinner.gif" width="16" height="16" alt="" />')
			}
		});
	});
});

