function setTabActive(myTab, idParts, totalTabs, currentTab){
	var allTabs = myTab.parentNode.childNodes;
	for(var i = 0; i < allTabs.length; i++){
		if(allTabs[i].nodeType == 1) allTabs[i].className='';
	}
	myTab.className='active';
	for(var i = 0; i <= totalTabs; i++){
		var tmp = document.getElementById(idParts + i);
		if(tmp) {
			if(i==currentTab) tmp.className='activeTab';
			else tmp.className='inactiveTab';
		}
	}
}

function loadContentTab(targetTab, containerObject, getUrl, resetPagination, useFilter) {
	targetTab = $(targetTab);
	useFilter && __GlobalNS_Portal.length && (getUrl = '/'+ __GlobalNS_Portal + getUrl);
	if (!targetTab.hasClass('active')) {
 		$.get(getUrl, function(data) {
 			if (data && data.length) {
				targetTab.parent().children('.active').removeClass('active');
 				targetTab.addClass('active');
 				$(containerObject).empty().html(data);
 				if (resetPagination) {
 					var pObj = gPaginationManager.instance();
	 				pObj.config.set('targetUrl', getUrl);
	 				pObj.config.set('currentPage', 1);
	 				pObj.render.links();
	 			}	
			}	
 		});		
	}
}

function activateProfileTab(tabName, urlExtra, urlOverride) {
	var isProfilePage = window.location.href.match(/profile/);
	var tabUrl = tabName + '/';
	var windowUrl = '/profile/#' + tabName;
	urlExtra && urlExtra.indexOf('#urlExtra#') >= 0 && (tabUrl += urlExtra.replace('#urlExtra#', ''));
	urlExtra && urlExtra.indexOf('#urlExtra#') < 0 && (windowUrl += urlExtra);
	urlOverride && (windowUrl = '/profile/#' + urlOverride);
	if (isProfilePage && isProfilePage[0]) {
		$.get('/profile/tab/' + tabUrl, function(data) {
			$('#profileContainer').empty().html(data);
			window.location.href = windowUrl;
		});	
	} else {
		$.getJSON('/ajax/setprofiletab/' + tabUrl, function(data) {
			data.success && data.success == true && (window.location.href = windowUrl);
		});	
	}
}

function loadTab(tabUrl, contentContainer, refObj) {
	!$(refObj).hasClass('active') && contentContainer && $.get(tabUrl, function(data) {
		$('#'+ contentContainer).empty().html(data);
	});
}

function toggleComment(id) {
	$(id).toggle('slow');
}

function toggleHeadline(title, body, date) {
	$('#headlinesTitle').html(title);
	$('#headlinesText').html(body);
	$('#headlinesDoor').html(date);
	$('#headlinesOverlay').toggle();
}

function toggleSpoiler(o) {
	$(o).next('span.content').toggle();
}

(function($) {
	gDropdown = {
		user: function() {
			return {
				show: function() {
					$('#user_dropdown').fadeIn('fast');
					$('#closer').show();
					$('#user_namefield').css({'color': '#fff'});
				},
				hide: function() {
					$('#user_dropdown').fadeOut('fast');
					$('#closer').hide();
					$('#user_namefield').css({'color': '#ef831a'});
				}
			};
		},
		portal: function() {
			return {
				show: function() {
					$('#portal_dropdown').show();
					$('#portal_drop div.name').css({'color': '#fff'});
				},
				hide: function() {
					$('#portal_dropdown').hide();
					$('#portal_drop div.name').css({'color': '#ef831a'});
				}
			};
		},
		search : function() {
			return {
				show: function() {
					$('#searchquery').val('');
					$('#search_dropdown').fadeIn('fast');
				},
				hide: function() {
					$('#search_dropdown').fadeOut('fast');
				}
			}
		},
		searchSubmit : function(event) {
			if (event.keyCode == 13) {
				doSearch('searchquery'); 
			}
		}
	};
})(jQuery);

function doSearch(id, index, word) {
	var url = '/search/';
	index && (url = url + index + '/');
	var query = id && $('#'+id) ? $('#'+id).val() : word ? word : null;
	if (query && query != 'zoeken') {
		var form = $('<form action="'+ url +'" method="post" style="display:none;"><input type="text" name="query" value="'+ query +'" /></form>');
		$('body').append(form);
		form.submit();
	}	
}

function clearPortal(redirect) {
	$.cookie('portal', null);
	redirect && redirect.length && (window.location.href = redirect);
}

/**
 * Stuff from Martijn
 * TO-DO: change to jQuery syntax
 */  
function mHover(theField, type) {
	//theField.style.backgroundColor = (type && type == 'On') ? "#f0f0f0" : "#fff";
}

function underlineColor() {
	var theColors = new Array();
	$('#menucolor').css({'backgroundColor': '#2d2d2d'});
	/*
	theColors['events'] = '#5e9712';
	theColors['forums'] = '#0081b2';
	theColors['topics'] = '#1b027d';
	theColors['media'] = '#8f0d0d';
	theColors['users'] = '#2d2d2d';
	theColors['profile'] = '#2d2d2d';
	theColors['connect'] = '#ffff75';
	
	var theString = new String(window.location);
	var theArray = theString.split('/');
	var theIndex = theArray[3] ? (theArray[3].match(/(starcraft2|bc2|poker)/g) ? 4 : 3) : null;
	if (theIndex && theArray[theIndex] != "" && theArray[theIndex] != "#") {
		theArray[theIndex] == "topics" && (theArray[theIndex] = "forums");
		theArray[theIndex] == "profile" && (theArray[theIndex] = "users");
		var htmlObject, objectColor = null;
		if ($('#menuItem_' + theArray[theIndex])) {
			htmlObject = $('#menuItem_' + theArray[theIndex]);
			objectColor = theColors[theArray[theIndex]];
		}
		htmlObject && objectColor && htmlObject.css({'color': (theArray[theIndex] == "connect" ? '#808000' : objectColor)});
		objectColor && $('#menucolor').css({'backgroundColor': objectColor});
	} else {
		$('#menuItem_frontpage').css({'color': '#2d2d2d'});
		$('#menucolor').css({'backgroundColor': '#2d2d2d'});
	}
	*/
}

function pingServer(url, divId) {
	var start = new Date();
	$.get(url, function(data) {
		var end = new Date();
		$('#'+divId).html(end.getTime() - start.getTime() + 'ms');
	});
}

/**
 * /END @ Martijn's stuff
 */ 

function validateEmail(email) {
	// from http://docs.jquery.com/Plugins/Validation/validate
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
}

function getPageSize() {
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
	}
	return {x:xWithScroll, y:yWithScroll}
}

function gTypes(typeName) {
	switch (typeName) {  // Taken from /shared/modules/collection/TypeCollection.php
		case 'Video': return 4;
		case 'Coverage': return 5;
		case 'Album': return 9;
		case 'Photo': return 10; 
		
		case 'AddMode': return 100;
		case 'EditMode': return 110;
		
		case 'InboxMessage': return 1;
		case 'OutboxMessage': return 2;
		case 'SystemMessage': return 3;
		
		default: return null;
	}
}

function notifyUser(errorMessage, errorLevel, timeout) {
	var message = $('<div />').css({
		'padding':'10px',
		'font-size':'14px',
		'text-align':'center'
	}).html(errorMessage);
	var holder = $('<div />').css({
		'position':'absolute',
		'top':'-1000px',
		'left':'0px',
		'width':'100%',
		'overflow':'hidden'		
	}).attr('id', 'userNotification').append(message);
	switch (errorLevel) {
		case 1: // Notice
			holder.css({'background':'#F4F4F4','color':'#707070'});
			break;
		case 2: // Success
			holder.css({'background':'#339933','color':'white'});
			break;
		default: // Error
			holder.css({'background':'red','color':'white'});
			break;
	}
	$('body').append(holder);
	holder.css('top', $(window).scrollTop() + $(window).height() - message.height() - 20 + 'px');
	!timeout && (timeout = 7000);
	holder.fadeOut(timeout);
	$(window).scroll(function () {
		holder.css('top', $(window).scrollTop() + $(window).height() - message.height() - 20 + 'px'); 
	});
}

function pingServer() {
	document['pObj'] && document['pObj'].pingServer(); 
}

function pingReply(value) {
	console.log(value);
}

function settingsModule(o) {
	var _ = o;
	return {
		get: function(key) {
			return this.exists(key) ? _[key] : null;
		},
		set: function(key, value) {
			return this.exists(key) && (_[key] = value);
		},
		exists: function(key) {
			return !(typeof(_[key]) === 'undefined' || _[key] === null);
		},
		vDump: function() {
		    return _;
		}
	};
}

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
