///////////////
// ACCORDION //
///////////////
jQuery().ready(function(){
jQuery('#userControls').accordion({
		header: 'div.title,div.title-green,div.title-purple',
		active: false,
		alwaysOpen: false,
		animated: false,
		autoheight: false
	});
jQuery('#userProfile').accordion({
		header: 'div.title,div.title-green,div.title-purple',
		autoheight: false
	});
});

////////////////
// ADMIN MENU //
////////////////
menuHover = function() {
	var cssRule;
	var newSelector;
	for (var i = 0; i < document.styleSheets.length; i++)
		for (var x = 0; x < document.styleSheets[i].rules.length ; x++)
			{
			cssRule = document.styleSheets[i].rules[x];
			if (cssRule.selectorText.indexOf("LI:hover") >= 0)
			{
				 newSelector = cssRule.selectorText.replace(/LI:hover/gi, "LI.fuseHover");
				document.styleSheets[i].addRule(newSelector , cssRule.style.cssText);
			}
		}
	var getElm = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<getElm.length; i++) {
		getElm[i].onmouseover=function() {
			this.className+=" fuseHover";
		}
		getElm[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" fuseHover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", menuHover);
///////////////////
// TAB FUNCTIONS //
///////////////////
$j(document).ready(function(){
	$j("a.intellitab").click(function () {
		$j(".active").removeClass("active");
		$j(this).addClass("active");
		$j(".intellicontent").slideUp();
		var content_show = $j(this).attr("title");
		$j("#"+content_show).slideDown();
	});
});

//////////////////
// SORT WIDGETS //
//////////////////
$j(document).ready(function() {
$j("#sortme_right").sortable({
  handle : '.handle',
  update : function () {
	serial = $j('#sortme_right').sortable('serialize');
	$j.ajax({
	url: "index.php?page=admin_pages",
	type: "post",
	data: serial,  
	error: function(){
	alert("Theres an error with AJAX");
	}
	});
  }
});
$j("#sortme_center").sortable({
  handle : '.handle',
  update : function () {
	serial = $j('#sortme_center').sortable('serialize');
	$j.ajax({
	url: "index.php?page=admin_pages",
	type: "post",
	data: serial,  
	error: function(){
	alert("Theres an error with AJAX");
	}
	});
  }
});
$j("#sortme_left").sortable({
	handle : '.handle',
	update : function () {
	serial = $j('#sortme_left').sortable('serialize');
	$j.ajax({
	url: "index.php?page=admin_pages",
	type: "post",
	data: serial,
	error: function(){
	alert("Theres an error with AJAX");
	}
	});
  }
});
});

function initTabs(_hold, tabs_hold, nav_hold, _autorotate, _switchTime){
	$j(_hold).each(function(){
		var _timer;
		var _btn = $j(this).find(nav_hold+' a');
		var _tabs = $j(this).find(tabs_hold).children();
		var _tabCount = _btn.length-1;
		_tabs.hide();
		var _a = _btn.index(_btn.filter('.selected:eq(0)'));
		if(_a == -1) _a = 0;
		_btn.removeClass('selected').eq(_a).addClass('selected');
		_tabs.hide().filter(_btn.get(_a).hash).show();
		_btn.click(function(){
			if($j(this).hasClass('more')) {
				var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
				if(_currentIndex<_tabCount-1) _btn.eq(++_currentIndex).trigger('click');
			} else {
				_tabs.hide().filter(this.hash).show();
				_btn.removeClass('selected'); 
				$j(this).addClass('selected');
			}
			return false;
		});

		function nextSlide() {
			if(_autorotate && _switchTime) {
				_timer = setTimeout(function(){
					var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
					if(_currentIndex<_tabCount) _currentIndex++;
					else _currentIndex=0;
					_btn.eq(_currentIndex).trigger('click');
					nextSlide();
				},_switchTime);
			}
		}
		if(_autorotate && _switchTime) {
			_timer = setTimeout(function(){
				nextSlide();
			},_switchTime);
		}
	});
}


function initExpandOnToday(){
	var _holder = $j('div.on-today');
	_holder.each(function(){
		var _list = $j('ul', $j(this)).find('li:gt(4)').hide();
		var _btn = $j(this).find('span.btn-expand');
		_btn.click(function()
		{
			if($j(this).hasClass("shown"))
			{
				$j(this).removeClass("shown");
				_list.each(function(){$j(this).hide(200);})
			} else
			{
				$j(this).addClass('shown');
				_list.each(function(){$j(this).show(200);})
			}
			return false;
		});
	})
}

function initAlphbet(){
	var _hold = $j("div.alphaholder");
	_hold.each(function(){
		var _nav = $j("ul.alphanavigation");
		var _numLink = $j("li a", _nav);
		var _itemHold = $j("ul.alphalist");
		var _item = $j("> li", _itemHold);
		var _lable = $j(this).find("span.hidden-lable");

		_numLink.click(function(){
			_numLink.removeClass("selected");
			$j(this).addClass("selected");
			var _letter = $j(this).children().text();
			_item.hide();
			_lable.each(function(){
				if ($j(this).text()== _letter ) {
					$j(this).parents("li").show();
					return;
				};
			});
			if (_letter == "All") {
				_lable.parents("li").show();
			}
			return false;
		})
	});
}
function initExpandTextArea(){
	$j('div.comments textarea').each(function(){
		var _hold = $j(this).parents('div.comments:eq(0)');
		var _text = this.value;
		this.onfocus = function(){
			_hold.addClass('active-text');
			if(this.value == _text) this.value = '';
		}
		this.onblur = function(){
			if(this.value == '') this.value = _text;
		}
	});
}



function initMenu()
{
	var _nav = document.getElementById("nav");
	if (_nav) {
		var nodes = _nav.getElementsByTagName("li");
		for (var i=0; i<nodes.length; i++)
		{
			nodes[i].onmouseover = function()
			{
				if (this.className.indexOf('hover') == -1)
				this.className += " hover";
			}
			nodes[i].onmouseout = function()
			{
				this.className = this.className.replace(" hover", "");
			}
		}
	}
	var _log = document.getElementById("log");
	if (_log) {
		var nodes = _log.getElementsByTagName("li");
		for (var i=0; i<nodes.length; i++)
		{
			nodes[i].onmouseover = function()
			{
				if (this.className.indexOf('hover') == -1)
				this.className += " hover";
			}
			nodes[i].onmouseout = function()
			{
				this.className = this.className.replace(" hover", "");
			}
		}
	}
}
if (document.all && !window.opera) attachEvent("onload", initMenu);


function ClearText()
{
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].type == "text")
		{
			inputs[i].onfocus = function ()
			{
					if (this.value == "Search Users...")
						this.value = "";
					if (this.value == "Search all locations...")
						this.value = "";
					if (this.value == "What would you like to say?")
						this.value = "";
					if (this.value == "Search Real-Time Activities...")
						this.value = "";
			}
			inputs[i].onblur = function ()
			{
					if (this.value == "" && this.name == "search"){
						this.value = "What would you like to say?";
						
					}
					if (this.value == "" && this.name == "realtime_status") this.value = "What would you like to say?";
					
					if (this.value == "" && this.name == "find") {
						this.value = "Search locations...";
						
					}
					if(this.name == "find")
					{
					}
					if (this.value == "" && this.name == "search_form_value") this.value = "Search real-time status";
					if (this.value == "" && this.name == "search_rt") this.value = "Search Real-Time Activities...";
					if (this.value == "" && this.name == "search-content-photos") this.value = "Search for photos";
					if (this.value == "" && this.name == "search-q") this.value = "Search Users...";}
		}
		
	}
}




$j(document).ready(function initPage() {
	initTabs('div.tabs.user-banner','div.banner','ul.tabNavigation',true,5000);
	initTabs('div.tabs','div.tabs-holder','ul.tabNavigation');
	//initTabs('div.tabs-main','div.tabs-holder-main','ul.tabNavigation-main');
	initExpandTextArea();
	//initExpandOnToday();
	initAlphbet();
	ClearText();
	
});




/* start file autogrow.js */
/*
 * SocialEngineMods Javascript Library Lite v0.1
 * http://www.SocialEngineMods.Net
 *
 * Copyright SocialEngineMods.Net
 * This code is licensed GPL for use exclusively on SocialEngine sites
 *
 */

/* Extensions */


Function.prototype.bind = function(obj) {
  var method = this, temp = function() {
    return method.apply(obj, arguments)
  };
  return(temp);
}; 


/* SEMods */


SEMods = function () {};

/* SEMods TextAreaControl */


SEMods.TextAreaControl = function(object) {
    this.obj = object;
    this.obj.style['overflow'] = 'hidden';
    this.originalHeight = this.obj.getStyle('height').toInt();
    var updater = this.update.bind(this);
    object.addEvent("focus", this.onFocus.bind(this));
    object.addEvent("blur", this.onBlur.bind(this));
    this.update();
};

SEMods.TextAreaControl.prototype = {
    obj : null,
    updating : false,
    autoGrow : false,
    originalHeight : null,
    shadowElement : null,
    increment : 0,
    timer : null,
    lastLength : 0,
    
    setAutoGrow : function(autoGrow) {
        this.autoGrow = autoGrow;
        this.createShadowElement();
        this.update();
    },
    
    onUpdate : function() {
        if(this.autoGrow && this.lastLength != this.obj.value.length) {
            this.lastLength = this.obj.value.length;
            this.updateShadowElement();
            this.obj.style.height = Math.max(this.originalHeight, this.shadowElement.offsetHeight + this.increment) + 'px';
        }
    },
    
    beginUpdate : function() {
        if(this.updating)
            return false;
        this.updating = true;
        return true;
    },
    
    endUpdate : function() {
        this.updating = false;
    },
    
    update : function() {
        if(!this.beginUpdate())
            return;
        
        this.onUpdate();
        this.endUpdate();
    },
    
    createShadowElement : function() {
        if(this.shadowElement)
            return;
        
        this.shadowElement = document.createElement("DIV");
        this.shadowElement.style.position = "absolute";
        this.shadowElement.style.top = "-99999px";
        this.shadowElement.style.left = "-99999px";
        
        document.body.appendChild(this.shadowElement);
    },
    
    updateShadowElement : function () {
        if(this.shadowElement) {
	    text = this.obj.value+'<br>';
            this.shadowElement.innerHTML = text.toString().replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br />');
            var fontSize = this.getPXMetrics( this.obj.getStyle('font-size'), 10);
            var lineHeight = this.obj.getStyle('line-height');
            // Opera misses on line-height
            if((/Opera/i.test(navigator.userAgent))) 
              lineHeight = this.getPXMetrics( lineHeight, 0) + 3 + 'px';
              
            this.increment = fontSize + 10;
        
            this.shadowElement.style['width'] = this.obj.offsetWidth + 'px';
            this.shadowElement.style['lineHeight'] = lineHeight;
            this.shadowElement.style['fontSize'] = this.obj.getStyle('font-size');

            this.shadowElement.style['fontFamily'] = this.obj.getStyle('font-family');
            this.shadowElement.style['paddingLeft'] = this.obj.getStyle('padding-left');
            this.shadowElement.style['paddingRight'] = this.obj.getStyle('padding-right');
            
        } 
    },
    
    onFocus : function() {
      this.timer = setInterval(this.update.bind(this), 500);
    },
    
    onBlur : function() {
      if(this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // em's not supported for now
    getPXMetrics : function(metric, defvalue) {
      var metricBase = parseFloat(metric);
      if(isNaN(metricBase)) return defvalue!=null ? defvalue : metricBase;
      return /px/i.test(metric) ? metricBase : /pt/i.test(metric) ? 1.3333*metricBase  : metricBase;
    }
    
};


/* Global namespace helper functions */


function textarea_autogrow(elementid) {
    var el = $(elementid);
//    if(!el) alert("textarea_autogrow(): element not found");
    if(el && !el._controlled) {
        el._controlled = true;
        new SEMods.TextAreaControl(el).setAutoGrow(true);
	return el.getStyle('height').toInt();
    }
};


/* end file autogrow.js 
start file  smoothbox.js */


/*
 * Smoothbox v20080623 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.2
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
	$$("a.smoothbox").each(function(el){el.onclick=TB_bind});
}

function TB_bind(event){
	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
    this.onclick = TB_bind;
    return false;
}

// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel, loading, disable_close) {

  // set default closing mechanism
  if(!disable_close) { disable_close = 0; }

  // create iframe, overlay and box if non-existent
  if (!$("TB_overlay")) {
    new Element('div').setProperty('id', 'TB_overlay').inject(document.body);
    $('TB_overlay').setOpacity(0.6);
    TB_overlaySize();
  }

  if (!$("TB_window")) {
    new Element('div').setProperty('id', 'TB_window').inject(document.body);
    $('TB_window').setOpacity(0);
  }
  else 
  {
    $('TB_window').dispose();
    new Element('div').setProperty('id', 'TB_window').inject(document.body);
    $('TB_window').setOpacity(0);
  }

  if(disable_close == 0) { $("TB_overlay").onclick=TB_remove; } else { $("TB_overlay").onclick = ''; }
  window.onscroll = TB_position;
    
  // check if a query string is involved
  var baseURL = url.match(/(.+)?/)[1] || url;
    
  // CODE TO SHOW IFRAME
  var queryString = url.match(/\?(.+)/)[1];
  var params = TB_parseQuery(queryString);
        
  TB_WIDTH = (params['width'] * 1) + 30;
  TB_HEIGHT = (params['height'] * 1) + 40;
        
  var ajaxContentW = TB_WIDTH - 30, ajaxContentH = TB_HEIGHT - 45;

   if (url.indexOf('TB_iframe') != -1) {
    urlNoQuery = url.split('TB_');
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a></div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "&in_smoothbox=true' id='TB_iframeContent' name='TB_iframeContent' scrolling='auto' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' onload='TB_showWindow()'> </iframe>";
  }
  else {
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>X</a></div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>";
  }
  /*if (url.indexOf('TB_iframe') != -1) {
    urlNoQuery = url.split('TB_');
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a></div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "&in_smoothbox=true' id='TB_iframeContent' name='TB_iframeContent' scrolling='auto' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' onload='TB_showWindow()'> </iframe>";
  }
  else {
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>X</a></div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>";
  }*/

  $("TB_closeWindowButton").onclick = TB_remove;

  if (url.indexOf('TB_inline') != -1) {
    $("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
    TB_position();
    TB_showWindow();
  } else if (url.indexOf('TB_iframe') != -1) {
    TB_position();
    if (frames['TB_iframeContent'] == undefined) {//be nice to safari
      $(document).keyup(function(e){
                    var key = e.keyCode;
                    if (key == 27) {
                        TB_remove()
                    }
      });
      TB_showWindow();
    }
  } else {
    var handlerFunc = function(){
          TB_position();
          TB_showWindow();
    };
    new Request.HTML({
                    method: 'get',
                    update: $("TB_ajaxContent"),
                    onComplete: handlerFunc
    }).get(url);
  }

  window.onresize = function(){
      TB_position();
      TB_overlaySize();
  }

  document.onkeyup = function(event){
      var event = new Event(event);
      if (event.code == 27) { // close
          TB_remove();
      }
  }


}

// called when the user clicks on a smoothbox link
function TB_show2(caption, url, rel, loading, disable_close) {

  // set default closing mechanism
  if(!disable_close) { disable_close = 0; }

  // create iframe, overlay and box if non-existent
  if (!$("TB_overlay")) {
    new Element('div').setProperty('id', 'TB_overlay').inject(document.body);
    $('TB_overlay').setOpacity(0.6);
    TB_overlaySize();
  }

  if (!$("TB_window")) {
    new Element('div').setProperty('id', 'TB_window').inject(document.body);
    $('TB_window').setOpacity(0);
  }
  else 
  {
    $('TB_window').dispose();
    new Element('div').setProperty('id', 'TB_window').inject(document.body);
    $('TB_window').setOpacity(0);
  }

  if(disable_close == 0) { $("TB_overlay").onclick=TB_remove; } else { $("TB_overlay").onclick = ''; }
  window.onscroll = TB_position;
    
  // check if a query string is involved
  var baseURL = url.match(/(.+)?/)[1] || url;
    
  // CODE TO SHOW IFRAME
  var queryString = url.match(/\?(.+)/)[1];
  var params = TB_parseQuery(queryString);
        
  TB_WIDTH = (params['width'] * 1) + 30;
  TB_HEIGHT = (params['height'] * 1) + 40;
        
  var ajaxContentW = TB_WIDTH - 30, ajaxContentH = TB_HEIGHT - 45;

  if (url.indexOf('TB_iframe') != -1) {
    urlNoQuery = url.split('TB_');
    $("TB_window").innerHTML += "<div id='TB_title2'><a href='#' id='TB_closeWindowButton' title='Close'></a></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "&in_smoothbox=true' id='TB_iframeContent' name='TB_iframeContent' scrolling='no' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' onload='TB_showWindow()'> </iframe>";
  }
  else {
    $("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>X</a></div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>";
  }

  $("TB_closeWindowButton").onclick = TB_remove;

  if (url.indexOf('TB_inline') != -1) {
    $("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
    TB_position();
    TB_showWindow();
  } else if (url.indexOf('TB_iframe') != -1) {
    TB_position();
    if (frames['TB_iframeContent'] == undefined) {//be nice to safari
      $(document).keyup(function(e){
                    var key = e.keyCode;
                    if (key == 27) {
                        TB_remove()
                    }
      });
      TB_showWindow();
    }
  } else {
    var handlerFunc = function(){
          TB_position();
          TB_showWindow();
    };
    new Request.HTML({
                    method: 'get',
                    update: $("TB_ajaxContent"),
                    onComplete: handlerFunc
    }).get(url);
  }

  window.onresize = function(){
      TB_position();
      TB_overlaySize();
  }

  document.onkeyup = function(event){
      var event = new Event(event);
      if (event.code == 27) { // close
          TB_remove();
      }
  }


}
//helper functions below

function TB_showWindow(){

    if (TB_doneOnce == 0) {
        TB_doneOnce = 1;
        
        $('TB_window').set('tween', {
            duration: 250
        });
        $('TB_window').tween('opacity', 0, 1);
        
    }
    else {
        $('TB_window').setStyle('opacity', 1);
    }

//  $('TB_window').setStyle('opacity', 1);
}

function TB_remove(){
    $("TB_overlay").onclick = null;
    document.onkeyup = null;
    document.onkeydown = null;
    
    if ($('TB_closeWindowButton')) 
        $("TB_closeWindowButton").onclick = null;
    
    $('TB_window').set('tween', {
        duration: 250,
        onComplete: function(){
            $('TB_window').dispose();
        }
    });
    $('TB_window').tween('opacity', 1, 0);
    
    
    
    $('TB_overlay').set('tween', {
        duration: 400,
        onComplete: function(){
            $('TB_overlay').dispose();
        }
    });
    $('TB_overlay').tween('opacity', 0.6, 0);
    
    window.onscroll = null;
    window.onresize = null;
    
    TB_init();
    TB_doneOnce = 0;
    return false;
}

function TB_position(){
    $('TB_window').set('morph', {
        duration: 75
    });
    $('TB_window').morph({
		width: TB_WIDTH + 'px',
		left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2) + 'px',
		top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT) / 2) + 'px'
	});	
}

function TB_overlaySize(){
    // we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
    $("TB_overlay").setStyles({
        "height": '0px',
        "width": '0px'
    });
    $("TB_overlay").setStyles({
        "height": window.getScrollHeight() + 'px',
        "width": window.getScrollWidth() + 'px'
    });
}


function TB_parseQuery(query){
    // return empty object
    if (!query) 
        return {};
    var params = {};
    
    // parse query
    var pairs = query.split(/[;&]/);
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        if (!pair || pair.length != 2) 
            continue;
        // unescape both key and value, replace "+" with spaces in value
        params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
    }
    return params;
}


/* end smoothbox.js
start file thickbox.js */

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "templates/default/images/loading.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$j(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$j(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$j("body","html").css({height: "100%", width: "100%"});
			$j("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$j("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$j("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$j("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$j("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$j("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$j('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $j("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$j("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$j("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($j(document).unbind("click",goPrev)){$j(document).unbind("click",goPrev);}
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$j("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$j("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$j("#TB_load").remove();
			$j("#TB_ImageOff").click(tb_remove);
			$j("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$j("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$j("#TB_overlay").unbind();
						$j("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($j("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$j("#TB_overlay").unbind();
						$j("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$j("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$j("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$j("#TB_ajaxContent")[0].scrollTop = 0;
						$j("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$j("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$j("#TB_ajaxContent").append($j('#' + params['inlineId']).children());
					$j("#TB_window").unload(function () {
						$j('#' + params['inlineId']).append( $j("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$j("#TB_load").remove();
					$j("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$j("#TB_load").remove();
						$j("#TB_window").css({display:"block"});
					}
				}else{
					$j("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$j("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$j("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$j("#TB_load").remove();
	$j("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$j("#TB_imageOff").unbind("click");
	$j("#TB_closeWindowButton").unbind("click");
	$j("#TB_window").fadeOut("fast",function(){$j('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$j("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$j("body","html").css({height: "auto", width: "auto"});
		$j("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$j("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$j("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


/* end file thickbox.js
start file autosuggest.js */



/**
 *  author:		Timothy Groves - http://www.brandspankingnew.net
 *	version:	1.2 - 2006-11-17
 *              1.3 - 2006-12-04
 *              2.0 - 2007-02-07
 *              2.1.1 - 2007-04-13
 *              2.1.2 - 2007-07-07
 *              2.1.3 - 2007-07-19
 *
 */


if (typeof(bsn) == "undefined")
	_b = bsn = {};


if (typeof(_b.Autosuggest) == "undefined")
	_b.Autosuggest = {};
else
	alert("Autosuggest is already set!");












_b.AutoSuggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:0, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25, blurtrigger: false, multisuggest: true};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	var p = this;
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 	= function(ev){ return p.onKeyUp(ev); };
	if (typeof(this.oP.callback) == "function" && this.oP.blurtrigger) {
	  this.fld.onblur = function(event) { 
		if(document.activeElement && typeof(event) === "undefined") { 
			var targetFocus = document.activeElement;
		} else {
			var targetFocus = event.explicitOriginalTarget;
			while(targetFocus.parentNode) {
			  if(targetFocus.tagName == 'A' && typeof(targetFocus.id) == 'string') { if(targetFocus.id.substring(0, 10) == 'bsnsuggest') { break; } }
			  targetFocus = targetFocus.parentNode;
			}
			if(typeof(targetFocus.id) != 'string') { targetFocus.id = ''; }
		}
		if(targetFocus.id.substring(0, 10) != 'bsnsuggest') {
		  p.oP.callback( {id:p.fld.value, value: p.fld.value} ); 
		  p.clearSuggestions();
		}
	  }
	}
	
	this.fld.setAttribute("autocomplete","off");
};
















_b.AutoSuggest.prototype.onKeyPress = function(ev)
{
	
	var key = (window.event) ? window.event.keyCode : ev.keyCode;



	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var SEMICOLON = 186;
	
	var bubble = 1;

	switch(key)
	{
		case RETURN:
			if(this.aSug.length != 0 && this.iHigh) {
				this.setHighlightedValue();
				bubble = false;
			} else {
				if(this.fld.value.length > 0) {
					if (typeof(this.oP.callback) == "function") {
						this.clearSuggestions();
						this.oP.callback( {id:this.fld.value, value: this.fld.value} );
					}
					bubble = false;
				} else  {
					bubble = false;
				}
				
			}
			break;

		case ESC:
			this.clearSuggestions();
			break;
				
	}

	return bubble;
};



_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	


	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			//this.getSuggestions(this.fld.value);
			// ADDED BY WEBLIGO
			var new_value = this.fld.value.split(/[;]+/ig);
			this.getSuggestions(new_value[new_value.length-1]);
	}

	return bubble;
	

};








_b.AutoSuggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	
	
	var ol = this.nInpC; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	var l = this.aSug.length;
		if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		var arr = [];
		for (var i=0;i<l;i++)
		{
			if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase() || this.aSug[i].info.substr(0,val.length).toLowerCase() == val.toLowerCase()) {
				arr.push( this.aSug[i] );
			}
		}
		this.aSug = arr;
		
		// ADDED BY WEBLIGO
		if(this.aSug.length < l) {
			var pointer = this;
			var input = this.sInp;
			clearTimeout(this.ajID);
			this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
		} else {
			this.createList(this.aSug);
		}
		
		return false;
	}
	else
	// do new request
	//
	{
		var pointer = this;
		var input = this.sInp;
		clearTimeout(this.ajID);
		this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
	}

	return false;
};





_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
	// check that saved input is still the value of the field
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	
	
	var pointer = this;
	
	
	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
	
	if (!url)
		return false;
	
	var meth = this.oP.meth;
	var input = this.sInp;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
	var onErrorFunc = function (status) {  };

	var myAjax = new _b.Ajax();
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};





_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
	// if field input no longer matches what was passed to the request
	// don't show the suggestions
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	this.aSug = [];
	
	
	if (this.oP.json)
	{
		var jsondata = eval('(' + req.responseText + ')');
		
		for (var i=0;i<jsondata.results.length;i++)
		{
			// CHANGED BY WEBLIGO
			this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info, 'photo':jsondata.results[i].photo, 'photo_width':jsondata.results[i].photo_width }  );
		}
	}
	else
	{

		var xml = req.responseXML;
	
		// traverse xml
		//
		var results = xml.getElementsByTagName('results')[0].childNodes;

		for (var i=0;i<results.length;i++)
		{
			if (results[i].hasChildNodes())
				this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
		}
	
	}
	
	this.idAs = "as_"+this.fld.id;
	

	this.createList(this.aSug);

};














_b.AutoSuggest.prototype.createList = function(arr)
{
	var pointer = this;
	
	
	
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults) 
		return false;
	
	
	// create holding div
	//
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	var hbar = _b.DOM.cE("div", {className:"as_bar"});
	var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	
	
	// create and populate ul
	//
	var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (var i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		var val = arr[i].value;
		var val2 = arr[i].info;
		var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		var st2 = val2.toLowerCase().indexOf( this.sInp.toLowerCase() );
		
		if(st != -1) {
			var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
			var output2 = val2;
		} else {
			var output = val;
			var output2 = val2.substring(0,st2) + "<em>" + val2.substring(st, st2+this.sInp.length) + "</em>" + val2.substring(st2+this.sInp.length);
		}
		
		if (val != val2) {
			output = output2+" ("+output+")";
		}
		
		var span 		= _b.DOM.cE("span", {}, output, true);
		
		// CHANGED BY WEBLIGO
		var image		= _b.DOM.cE("img", {src:arr[i].photo, width: arr[i].photo_width, border:"0"});
		image.removeAttribute("height");
		span.insertBefore(image, span.childNodes[0]);

		var a 			= _b.DOM.cE("a", { href:"javascript:void(0);" });
		
		var tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		var tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.id = 'bsnsuggest_'+(i+1);
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		var li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	var fcorner = _b.DOM.cE("div", {className:"as_corner"});
	var fbar = _b.DOM.cE("div", {className:"as_bar"});
	var footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	var pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	
	
	
	
	// remove list after an interval
	//
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};















_b.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	var n;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};



_b.AutoSuggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		// CHANGED BY WEBLIGO
		var all_values = this.fld.value.split(/[;]+/ig);
		all_values.pop();
		all_values.push(this.aSug[ this.iHigh-1 ].value);
		if(this.oP['multisuggest']) { var semicolon = ';'; } else { var semicolon = ''; }
		this.sInp = this.fld.value = all_values.join(';')+semicolon;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
			
			
		this.clearSuggestions();
	}
};













_b.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};







_b.AutoSuggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	this.aSug 	= [];
	var ele = _b.DOM.gE(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};










// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};



_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
};


_b.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
};










// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};



/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return 0;
		
	
	for (var a in attr) 
		ne[a] = attr[a];

	var t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};



/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e);
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		var re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};



/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};



/* get position */
_b.DOM.getPos = function ( e )
{
	var e = this.gE(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	var obj = e;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};










// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};





_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};




_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};



_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};



/* end file autosuggest.js
start file sprintf.js */


/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf()

{
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

/* end file sprintf.js
start file   functions.js */


$j(document).ready(function() {
  var _w=0;
  $j('.search-result .rel-videos ul .txt-box .txt-inner').each(function(){
    if($j(this).height()>_w){
      _w=$j(this).height();
    }
  });
//  alert('w:'+_w);
 if(_w>0){
    $j('.search-result .rel-videos ul .txt-box .txt-inner').each(function(){
      $j(this).height(_w);
    });
  }
});
// here search f

function URLDecode(encodedString){
  encodedString = encodedString.toString();
  var x=0;
  var _len = encodedString.length;
  var _new_string='';
  while( x < _len ){

    if( encodedString.charCodeAt(x) == 37 && x < _len - 2 && encodedString.substr( x+1 , 2).search(/[a-f0-9]{2}/i) == 0){
      var _hex = encodedString.substr(x+1,2);
    var _dehex = String.fromCharCode('0x'+_hex);
    _new_string+=_dehex;
    x+=2;
    }else{
      _new_string+=encodedString.substr(x,1);
  }
  x++;
  }
  _new_string = _new_string.replace(/\+/g,' ');
  return _new_string;
}

function URLEncode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString().replace(/ /g,'+');
  var regex = /(^[a-zA-Z0-9+_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
      output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function ucfirst (str) {
  
  str += '';
  str = str.toLowerCase();
  var str_arr = str.split(' ');
  var str_ret = '';
  for( var i=0;i<str_arr.length;i++){
    var str_i = str_arr[i];
    var f = str_i.charAt(0).toUpperCase();
    str_ret+= f + str_i.substr(1)+(i<str_arr.length-1?' ':'');
  }
  return str_ret;
}


function doSearchSmall(){
  var _term = $j('#search-small-box').val();
  if(_term.length >= 3 ){
    _term = URLEncode(_term);
    $j('#search-form-small').attr('action','/search/users/' + _term + '/1');
    $j('#search-form-small').submit();

  }else{
    alert('min 3 chars');
  }
  return void(0);
}
function doSearchById(term,sfid){
  var _term = term || false;
  if( _term === false ){
    var _form = $j('#'+sfid)[0];
    _term = $j(".dosearch",_form).val();
  }
  if(_term.length >= 3 ){
    _term = URLEncode(_term);
     $j('#'+sfid).attr('action','/search/users/' + _term + '/1');
     $j('#'+sfid).submit();
   }else{
     alert('min 3 chars');
   }
   return void(0);
}

function doSearchPage(page){
  
  var _loc_split = document.location.href.split('/');

  var _term = _loc_split[5];
  doSearch(URLDecode(_term),page);
  return void(0);
}
  
function doSearchBtn(form_id,type,uid){
	var user_id=uid;
	if(user_id==0)
	{
		alert("Please sign in first to submit it...");
		return false;
	}
	else {
  var _type = type || false;
  var _form = $j('#'+form_id)[0];
//return doSearchById(false,form_id);
  return doSearch(false,1,_type,_form);
	}
}
function doSearch(term,page,type,form){
  var page = page || 1;
  var term = term || false;
  var form = form || false;
	
  var _type = type || false;
  if(_type === false){
		_type = $j('input[name="search_type"]:checked').val();
	  $j('input[name="search_type"]:checked').attr('checked','');
	}
  if(_type == 'towns' ){
    var type = 'locations';
  } else if(_type == 'profiles' ){
    var type = 'usernames';
  }else{
    var type = 'users';
  }
//  $j('#search-top-box').curtain();
//  alert('t'+term);
  if( term === false ){
    if(form === false){
      term = $j("#bigsearchbox2").val();
    }else{
      term = $j(".dosearch",form).val();
    }
  }
//  alert('t:'+term+',t:'+type);
  if(term.length > 0){
    var _term = URLEncode(term);
    var _action = 'index.php?page=search&cursectionid=0&sectionid=0&srchusername=' + _term + '&advsearch=Search';
    if(form === false){
      var _form = $j('#search-form')[0];
    }else{
      _form = form;
    }
    $j(_form).attr('action',_action);
//    alert('act:'+_action);
    $j(_form).submit();
  }else{
//    $j('#search-top-box').curtain("remove");
    alert('empty query');
  }
  return void(0);
}

function fixEnter(field,e,small,type,sfid){
  var keynum;
  var keychar;
  var numcheck;
  var _small = small || false;
	var _type = type || false;
  var _sfid = sfid || false;
  if(window.event){
    keynum = e.keyCode;
  }else if(e.which){
    keynum = e.which;
  }
//alert(keynum);
//return false;
  keychar = String.fromCharCode(keynum);
  var _input_value = field.value;
//  alert(_input_value);
//  if(keynum==13 && document.getElementById("input-box-main").value.length == 0 ){
  if(keynum==13 && _input_value.length == 0 ){
    return false;
  }else if(keynum==13){
    if(_small===false){
      doSearch(_input_value,1,_type);
    }else if(_small===true){
      doSearchSmall(_input_value);
    }else if(_sfid!==false&&_small==2){
      doSearchById(_input_value,_sfid);
    }
    return false;
  }


  return true;
}



