function loadJavascript(src,onload){
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
	if(onload){
		script.onreadystatechange = function(){
			if(this.readyState == 'complete' || this.readyState == 'loaded'){
				if(this.onload) this.onload();
				this.onload = null;
			}
		};
		script.onload = onload;
	}
  document.getElementsByTagName('head')[0].appendChild(script);
}

function correctPNG(){
  for(var i=0; i<document.images.length; i++){
		var img = document.images[i];
		var imgName = img.src.toUpperCase();
		if (imgName.substring(imgName.length-3, imgName.length) != "PNG") continue;
		var imgID = (img.id) ? "id='" + img.id + "' " : "";
		var imgClass = (img.className) ? "class='" + img.className + "' " : "";
		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
		var imgStyle = "display:inline-block;" + img.style.cssText;
		if (img.align == "left") imgStyle = "float:left;" + imgStyle;
		if (img.align == "right") imgStyle = "float:right;" + imgStyle;
		if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
		var strNewHTML = "<span " + imgID + imgClass + imgTitle;
		+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";";
		+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader";
		+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
		img.outerHTML = strNewHTML;
		i = i-1;
  }
}

function fix_img_png(img){
	img = $(img);
	if(!img) return;
	var src = img.src;
  if(!src.match(/\.png/i)) return;
	img.style.width = img.width + "px";
	img.style.height = img.height + "px";
	img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')";
	img.src = sroot+'homes/images/blank.gif';
};
	
function fix_bg_png(el){
	el = $(el);
	if(!el) return;
  var bg = new String(el.getStyle('background-image'));
  if(!bg.match(/\.png/i)) return;
	var src = bg.substring(5,bg.length-2);
	el.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='crop')";
	el.style.backgroundImage = 'none';
}

function _FadeInElement(el){
	this.myFadeOut.stop();
	this.myFadeIn.stop();
	this.myFadeIn.start(1);
}

function _FadeOutElement(el){
	this.myFadeOut.stop();
	this.myFadeIn.stop();
	this.myFadeOut.start(0.5);
}

// JavaScript Document
function _Start_Effect_FadeIn(el){
	var myFadeIn = new Fx.Style(el, 'opacity', {duration: 500, transition: Fx.Transitions.linear});
	var myFadeOut = new Fx.Style(el, 'opacity', {duration: 100, transition: Fx.Transitions.linear});
	el.myFadeIn = myFadeIn;
	el.myFadeOut = myFadeOut;
	el.addEvent('mouseenter',_FadeInElement.bindWithEvent(el));
	el.addEvent('mouseleave',_FadeOutElement.bindWithEvent(el));
}

function _Start_Effect_TableCellFX(el){
	if(!el.hasClass('no_effect'))
	{
		// grab the true height before we even start
		el.start_height = el.getSize()['size']['y'];
		el.end_height = 113;
		el.start_bgcol = el.getStyle('background-color');
		el.end_bgcol = '#61604d';
		el.start_col = '#000000';
		el.end_col = '#FFFFFF';
		
		// instead of moving it back when the mouse leaves, we move it when it hits another
		el.my_effect = new Fx.Styles(el, {duration: 500, transition: Fx.Transitions.Expo.easeOut});
		el.my_effect2 = new Fx.Styles($E('div.thumb',el), {duration: 500, transition: Fx.Transitions.Expo.easeOut});
		
		// make sure they have a list
		/*
		if($E('div.lobj',el)){
			el.my_effect3 = new Fx.Styles($E('div.lobj',el), {duration: 500, transition: Fx.Transitions.Expo.easeOut});
			el.my_effect3_h = $ES('div',$E('div.lobj',el)).length * 16;
		}
		*/

		/*
			Originaly the list was developed to be used by one item in the table, we now need to attach
			it to multiple cells.
		 */
		// Grab all list items
		el.list_objects = $ES('div.lobj',el);
		$ES('div.lobj',el).each(function(e){
			e.list_effect = new Fx.Styles(e, {duration: 500, transition: Fx.Transitions.Expo.easeOut});
			e.list_effect_h = $ES('div',e).length * 16;
		});

		// enumerate all thumbs so that they go from 0 to 113 and back
		el.addEvent('mouseenter',function(e){
			if(this.list_objects.length > 0){
				this.list_objects.each(function(lo){
					lo.list_effect.stop();
				});
			};
			this.my_effect2.stop();
			this.my_effect.stop();
			this.my_effect.start({
				'height': this.end_height,
				'background-color': [this.start_bgcol,this.end_bgcol],
				'color': [this.start_col,this.end_col]
			});
			this.my_effect2.start({
				'height': 113
			});

			if(this.list_objects.length > 0){
				this.list_objects.each(function(lo){
					lo.list_effect.start({
						'height': lo.list_effect_h
					});
				});
			};
		}.bindWithEvent(el));
		el.addEvent('mouseleave',function(){
			if(this.list_objects.length > 0){
				this.list_objects.each(function(lo){
					lo.list_effect.stop();
				});
			};
			this.my_effect2.stop();
			this.my_effect.stop();
			this.my_effect.start({
				'height': this.start_height,
				'background-color': [this.end_bgcol,this.start_bgcol],
				'color': [this.end_col,this.start_col]
			});
			this.my_effect2.start({
				'height': 0
			});
			if(this.list_objects.length > 0){
				this.list_objects.each(function(lo){
					lo.list_effect.start({
						'height': 16
					});
				});
			};
		}.bindWithEvent(el));
	}
}

function _End_Effect_TableCellFX(el){
	
}

function _Start_Effect_GrowTable(el){
	$ES('tr',el).each(_Start_Effect_TableCellFX);
}

function _End_Effect_GrowTable(el){
	$ES('tr',el).each(_End_Effect_TableCellFX);
}

function StartEffects(){
	$$('*.fade_in').each(_Start_Effect_FadeIn);
	$$('table.make_gtable').each(_Start_Effect_GrowTable);
	//correctPNG();
}

/* sorts the table ASCENDING to begin with*/
function SortTable(t_elem, ncol, desc){
	// get the table data
	var sortType = t_elem.getParent().data['col'][ncol]['type'];
	// do the actual sorting
	switch(sortType){
		case 'number':
			if(desc)
				t_elem.getParent().data['row'].sort(function(a,b){
					return parseInt(a[this]['value']) - parseInt(b[this]['value']);
				}.bind(ncol));
			else
				t_elem.getParent().data['row'].sort(function(a,b){
					return parseInt(b[this]['value']) - parseInt(a[this]['value']);
				}.bind(ncol));
			break;
		default:
			if(desc)
				t_elem.getParent().data['row'].sort(function(a,b){
					if(a[this]['value'] > b[this]['value']) return 1;
					if(b[this]['value'] > a[this]['value']) return -1;
					return 0;
				}.bind(ncol));
			else
				t_elem.getParent().data['row'].sort(function(a,b){
					if(a[this]['value'] > b[this]['value']) return -1;
					if(b[this]['value'] > a[this]['value']) return 1;
					return 0;
				}.bind(ncol));
			break;
	}
	// now we go through each item in order and redom
	for(var i=0; i<t_elem.getParent().data['row'].length; i++){
		var row = t_elem.getParent().data['row'][i];
		// move it to the front
		row['trlink'].injectAfter(t_elem.getLast());
		// fix alt
		row['trlink'].removeClass('alt');
		if(i%2==0)
			row['trlink'].addClass('alt');		
	}
}

function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}

/*
	Generate a table from our SmartTable json data.
*/
function GenerateTable(s_table){
	var twrap = new Element('table');
	twrap.addClass('make_gtable');
	twrap.setStyle('width','100%');
	twrap.data = s_table;
	
	// Generate the table
	var table = new Element('tbody');
	table.injectInside(twrap);
	
	// Generate the header columns
	var head_row = new Element('tr');
	head_row.addClass('tblhead');
	head_row.addClass('no_effect');
	for(var i=0; i<s_table['col'].length; i++){
		var col = s_table['col'][i];
		var coltd = new Element('td');
		coltd.setHTML(col['title']);
		coltd.injectInside(head_row);
		if(col['width'] != 'auto')
			coltd.setStyle('width',col['width']);
		// add the sorting onclick handlers to the tags
		if(	col['type'] == 'string' ||
			col['type'] == 'number' ){
			coltd.addClass('sortnone');
		}
		coltd.addEvent('click',function(coln){
			var tbl = this.getParent().getParent();
			if(this.hasClass('sortasc')){
				this.removeClass('sortasc');
				this.addClass('sortdesc');
				SortTable(tbl, coln, false);
			}else if(this.hasClass('sortdesc')){
				this.removeClass('sortdesc');
				this.addClass('sortasc');
				SortTable(tbl, coln, true);
			}else if(this.hasClass('sortnone')){
				tbl.getFirst().getChildren().each(function(el){
					if(el.hasClass('sortdesc')){
						el.removeClass('sortdesc');
						el.addClass('sortnone');
					}else if(el.hasClass('sortasc')){
						el.removeClass('sortasc');
						el.addClass('sortnone');
					}
				});
				this.removeClass('sortnone');
				this.addClass('sortasc');
				SortTable(tbl, coln, true);
			}
		}.bind(coltd,[i]));
	}
	head_row.injectInside(table);
	
	// Go through each of the rows
	for(var m=0; m<s_table['row'].length; m++){
		var row = s_table['row'][m];
		var rowtr = new Element('tr');
		if(m%2==0)
			rowtr.addClass('alt');
		row['trlink'] = rowtr;
		for(var n=0; n<s_table['col'].length; n++){
			var col = s_table['col'][n];
			var celltd = new Element('td');
			switch(col['type']){
				case 'thumb':
					var img = new Element('div');
					img.addClass('thumb');
					if(row[n]['display'] == ""){
					  img.setStyle('background-image','url('+sroot+'homes/images/no_thumb.png)');
          }else{
            img.setStyle('background-image','url('+row[n]['display']+')');
          }
					img.setStyle('height',0);
					img.injectInside(celltd);
					celltd.addClass('image');
					celltd.setStyle('width',150);
					break;
				case 'list':
					// create the main (master) div
					var ldiv = new Element('div');
					ldiv.addClass('lobj');
					ldiv.setStyle('height','16px');
					ldiv.setStyle('overflow','hidden');
					
					// create the inner tags
					var litem = row[n]['display'].split(';');
					for(var q=0; q<litem.length; q++){
						var idiv = new Element('div');
						idiv.setStyle('height','16px');
						idiv.setStyle('overflow','hidden');
						idiv.setStyle('white-space','nowrap');
						idiv.setHTML(litem[q]);
						idiv.injectInside(ldiv);
					}
					ldiv.injectInside(celltd);

					//Adds underline to address text in cell...
					if(s_table['col'][n]['title'] == 'Address'){
						if(row[n]['link']!=''){
							celltd.addEvent('mouseover',function(){
								$ES('div.lobj div',this).each(
									function(e) { 
										if(e.innerHTML.indexOf("</a>") == -1) {
											e.addClass('hover'); 
										}
									}
								);
							}.bind(celltd));
							celltd.addEvent('mouseout',function(){
								$ES('div.lobj div',this).each(
									function(e) { 
										e.removeClass('hover'); 
									}
								);
							}.bind(celltd));
						}
					}

					break;
				default:
					celltd.setHTML(row[n]['display']);
					 if(row[n]['link']!=''){
              celltd.addEvent('mouseover',function(){
                this.setStyle('text-decoration','underline');
              }.bind(celltd));
              celltd.addEvent('mouseout',function(){
                this.setStyle('text-decoration','none');
              }.bind(celltd));
           }
			}
			if(row[n]['link'] != ''){
			   celltd.setStyle('cursor','pointer');
			   celltd.addEvent('click',function(){
			     window.location = this['link'];
         }.bind(row[n]));
      }
			celltd.injectInside(rowtr);
		}
		rowtr.injectInside(table);
	}
	
	return twrap;
}

function preloadUserinfo(checkType){
  new Ajax(sroot+'homes/data/load_userinfo.php'+(checkType ? '?checkType=true':''), {evalScripts: true}).request();
}

window.addEvent('domready',StartEffects);
