var loc = 'app.php';
var spu = "images/interface/spinnerupl.png";
var spd = "images/interface/spinnerdown.png";

BSI = {
	actionQueue : [],
  	init :function(referer){
		this.referer 				= referer;
		this.stateTable 			= $H();
		this.loadClasses();
		//SMA.loadStateHash();
	},
	loadClasses:function(){
		ui = new UI();
		popup = new Popup();
	}
};

util = {
	init : function(){
		draggable = null;
	},
	onEnter:function(event,funct){
		if(event.keyCode==13) eval(funct);
	},
	qualifyBrowser : function(){
		var msg = "";
		var bmsg = '<p style="color:#CC1616">Problem found: <br>You are using an unsupported browser. Please use one of the browsers listed in the minimum requirements list.</p><p> If you still want to sign in <a href="#" onclick="$(\'loginForm\').style.display=\'\';">click here</a></p>';
		var flashmsg = '<p style="color:#CC1616">Problem found: <br>Your version of Flash is incorrect. Please download the latest version of Flash</p>';
		var javamsg = '<p style="color:#CC1616">Problem found: <br>To use the softproofing features of SendMyAd you will need the JAVA plugin. Please download the latest version of java for your browser.</p>';
		
		if(!this.detectJava()) msg +=javamsg;
		
		var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if(!hasReqestedVersion) msg +=flashmsg;

		if($('loginMsg')) $('loginMsg').innerHTML = msg;
		
		this.detectIE(msg);
		this.checkCookie();
	},
	detectJava:function(){
		if(Prototype.Browser.IE){
			return true;
		}else{
			java = false;
			plugins = $A(navigator.plugins);
			plugins.each(function(pluginlist){
				$A(pluginlist).each(function(plugin){
					if(plugin.description.indexOf('Java Applet') != -1){
						java = true;
					}
				});
			});
			return (java)?true:false;
		}
	},
	detectIE:function(msg){
		if(Prototype.Browser.IE){
			if (!ieGood) {
				bmsg = '<p style="color:#CC1616">You must upgrade to at least Internet Explorer 7 to use SendMyAd.</p>';
				if($('login')) {
					//front login screen
					$('login').hide();
				} else {
					// advertiser signup screen
					$('popupInner').hide();
				}
				msg += bmsg;
				if($('loginMsg')) $('loginMsg').innerHTML = msg;
			} 
		}
	},
	checkCookie:function(){
		this.setCookie("testCookie","1",1);
		var testCookie = this.getCookie('testCookie');
		if(testCookie != "1"){
			cookieMsg = '<h2 style="color:orange">WARNING: Cookies must be enabled in your browser.</h2>';
			msg += cookieMsg;
			if($('loginMsg')) $('loginMsg').innerHTML = msg;
		};
	},
	setCookie:function(name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=name+"="+escape(value)+
		((expiredays==null)?"":";expires="+exdate.toGMTString());
	},
	getCookie:function(name){
		if(document.cookie.length>0){
		  start=document.cookie.indexOf(name + "=");
		  if (start!=-1){ 
		    start=start + name.length+1; 
		    end=document.cookie.indexOf(";",start);
		    if (end==-1) end=document.cookie.length;
		    return unescape(document.cookie.substring(start,end));
		    } 
		}
		return "";
	},
	checkRequired : function(values,namemap){
		var ervalues = '',name,value;
		valuesArray = values.split(',');
		nMArray = namemap.split(',');
			
		for (var i=0;i<=valuesArray.length-1;i++) {				
			nm = nMArray[i];
			if($(valuesArray[i])){
				name = $(valuesArray[i]).name;
				value = $F(valuesArray[i]);
				if(value == '') { 
					ervalues += nm+' is required! Please fill it in. \n';	
				}else if(name == 'email' && value.length > 0 && !util.isEmail(value)){
					ervalues +='Email is incorrect, please correct it. \n';	
				}
			}else{
				ervalues += nm+' is required! Please fill it in. \n';
			}	
		} 
		if (ervalues.length != 0){
			alert(ervalues);
			return false;
		}else{
			return true;	
		}
	},
	validatePassword : function(f1,f2){
		if($F(f1).length < 8) {
			alert("Passwords was empty or too short. Please specify a password with at least 8 characters.");
				return false;
		}else if(this.hasSpaces($F(f1))){
			alert("Sorry your password cannot contain any spaces.");
				return false;
		}else if($F(f1).startsWith("12345")){
			alert("Password is too common please choose different one");
			return false;
		}else if($F(f1).include('password')){
			alert("Password is too simple please choose different one");
			return false;
		}else if($F(f1).include('Password')){
			alert("Password is too simple please choose different one");
			return false;
		}else if ($F(f1) != $F(f2)) {
			alert("Passwords did not match. Please retype your password");
			return false;
		}else if(util.isSpecialCharacter($(f1))){
			alert("Special characters not allowed");
			return false;
		}else {
			return true;
		}
	},
	setValidate:function(className){
		// console.log("In setValidate, got " + className);
		validations = new Array();
		elements = new Array();
		var i = 0;
		className.each(function(c){
		$$("."+c+"").each(function(el){
			j = elements.indexOf(el.id);
			// console.log("Got form element: " + el.id);
			if(j == -1) {
				validations[i] = new LiveValidation(el.id, {validMessage:"",onlyOnBlur:true});
				validations[i].add( Validate[c.capitalize()] );
				i++;
			} else {
				// console.log("index: " + j);
				// console.debug(validations[j]);
				validations[j].add( Validate[c.capitalize()] );
			}
			elements.push(el.id);
			
		});
		});
	},
	addValidation:function(el,type,params){
		// var i = 0;
		i = elements.indexOf(el.id);
		if(i == -1) {
			v = new LiveValidation(el.id, {validMessage:"",onlyOnBlur:true});
			v.add( Validate[type.capitalize()], params );
			validations.push(v);
		} else {
			validations[i].add( Validate[type.capitalize()], params );
		}
		elements.push(el.id);
	},
	toPts:function(v){
		var units = $F('units');
		if (units == 2) {
			// for mm
			return v*2.834645669
		} else if (units == 3){
			// for picas
		} else {
			// default to inches
			return v*72;
		}
	},
	clearArray : function(arr){
		arr.length = 0;
	},
	zeroFill: function(n, totalDigits){ 
	   n = n.toString(); 
	   var pd = ''; 
	   if(totalDigits > n.length){ 
	      for(i=0; i<(totalDigits-n.length);i++){ 
	        pd += '0'; 
	      }
	   } 
	   return pd+n.toString();
	},
	getMonthsArray : function(abrv){
		return (abrv)?
			new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'):
			new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	},
	gup:function(url,name){
	  exp = "[\\?&]"+name+"=([^&#]*)";
	  regex = new RegExp(exp);
	  res = regex.exec(url);
	  return (res == null)?"":res[1];	
	},
	doResize : function(handle,el1,el2,direction){
		handleOffsetX = 15;
		if(direction == "horizontal"){
			left = (parseInt(handle.style.left)+handleOffsetX);
			el1.style.width=left+'px';
			el2.style.left=(left+1)+'px';
		}else{
			top = handle.style.top;
			el1.style.height=top;
			el2.style.top=top;
		}
	},
	isNumeric:function(n){
		return (!isNaN(n))?true:false;
	},
	isFloat:function(n){
		return ((q % 1) == 0)?false:true;
	},
	isWithinBounds:function(n, min, max){
		n = parseFloat(n);
		return (n >= min && n <= max);
	},
	isSpecialCharacter:function(elem){
		var iChars = "!#$%^&*()+=[]\\\';,/{}|\":<>?";
		for (var i = 0; i < elem.value.length; i++) {
		  	if (iChars.indexOf(elem.value.charAt(i)) != -1) {
		  		// alert ("Your query has special characters. \nThese are not allowed.\n Please remove them and try again.");
		  		return true;
		  	}
		}
	},
	padNumber:function(number, padLength){
	   	number += '';
		while(number.length < padLength) {
			number = '0'+number;
		}
		return number;
	},
	hasSpaces : function(string){
		return (string.indexOf(" ") != "-1")?true:false;
	},
	isEmail : function(email){
		re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		return (!re.test(email))?false:true;
	},
	encode:function(str){
		return "ccid="+Base64.encode(str);
	},
	enc: function(str){
	    lenStrMsg=str.length;
	    encMsg="";
	    for (pos = 0; pos<lenStrMsg; pos++){
	        key = ((lenStrMsg+pos)+1); // (+5 or *3 or ^2)
	        key = (255+key) % 255;
	        byteToBeEnc = str.substr(pos, 1);
	        numByteEncrypt = byteToBeEnc.charCodeAt(0);
	        xByte = numByteEncrypt ^ key;  
	        encByte = String.fromCharCode(xByte);
	        encMsg += encByte;
	    }
	    return encMsg;
	},
	getFileExtension:function(fileStr){
		var numSlash = fileStr.lastIndexOf("\\");
		if(numSlash < 1){ numSlash = fileStr.lastIndexOf("/"); }
		filename = fileStr.slice(numSlash + 1, fileStr.length);
		extension = filename.slice(filename.indexOf(".")).toLowerCase();
		return extension;
	},
	getFileName:function(str){
		return str.slice(str.lastIndexOf("/") + 1, str.length);
	},
	checkFileExt:function(extsExp,str){
		exp = new RegExp(extsExp);
  		if(str != ""){
  			var numSlash = str.lastIndexOf("\\");
			if(numSlash < 1){ numSlash = str.lastIndexOf("/"); }
			fileName = str.slice(numSlash + 1, str.length);
			extension = fileName.slice(fileName.indexOf(".")).toLowerCase();
			
			if(!str.match(exp)){
  				alert('"' + extension + '" is not an allowed ad type.');
	  			return true;
	  		}
			if(extension == ""){
				alert('an extension is required.');
				return true;
			}
			if(extension.length != 4){
				alert('This extension is not allowed.');
				return true;
			}
	  	}
		return false;
	},
	stripNonNumeric:function(num){
		var v = "0123456789";
		var nNum = "";
		for (i=0; i < num.length; i++) {
			cNum = num.charAt(i);
			if(v.indexOf(cNum,0) != -1)
			nNum += cNum;
		}
		return nNum;
	},
	disableEnterKey:function(e){
		
		var key = (window.event)?window.event.keyCode:e.which;
	   return (key == 13)?false:true;
	},
	sizeFormat:function(b){
	    if(b<1024){
	        return b+" bytes";
	    }else if(b<(1024*1024)){
	        $b=Math.round(b/1024,1);
	        return b+" KB";
	    }else if(b<(1024*1024*1024)){
	        b=Math.round(b/(1024*1024),1);
	        return b+" MB";
	    }else{
	        b=Math.round(b/(1024*1024*1024),1);
	        return b+" GB";
	    }

	},
	validateMaxChars:function(el, max){
		if(el.value.length > max){
			if ($('error'+el.id)) {
				//console.log("too much text, error already shown");
			} else {
				el.insert({after: '<div id="error' + el.id + '" style="color:red;">Field limited to ' + max + ' characters. Please edit.'});
			}
			// el.activate(); doesn't work
		}
	},
	validateFormValueForStorage:function(evt,el) {
		// console.log("Got char: " + evt.charCode);
		var charCode = evt.charCode;
		if(charCode != 0 && charCode != 46) {
			if((charCode >= 65 && charCode <= 97) || (charCode >= 90 && charCode <= 122) 
				|| (charCode >= 48 && charCode <= 57) || (charCode == 45) || (charCode == 95)){
				return true;
			} else {
				evt.preventDefault();
				if (!($('error' + el.id))) {
					el.insert({after: '<div id="error' + el.id + '" style="color:red;">No special characters allowed.'});

				};

			}
		}
	},
	toggleDiv:function(id){
		if ($(id).visible()) {
			$(id).hide();
		} else {
		    $(id).show();
		};
	},
	parseFractions: function (input) {
		var myRegex = new RegExp('(\\d*)(\\s*)(\\d+)(/)(\\d+)');
		var m = input.match(myRegex);
	    if (m){
			if (m[1] != '') {
				wholeNum = parseInt(m[1]);
			} else {
				wholeNum = 0;
			}
			var numerator = parseInt(m[3]);
	        var denominator = parseInt(m[5]);
			if (denominator != 0 || denominator != '') {
				var sum = wholeNum + (numerator / denominator);
				return Math.round(sum*100000)/100000;
			};			
	    } else {
			return input;
			
		}
	},
	getFlObject:function(name) {
	    if (navigator.appName.indexOf("Microsoft") != -1) {
	        return window[name];
	    } else {
	        return document[name];
	    }
	}

	
};

var UI = Class.create({
	initialize : function(){
	},
	setupResizeWatcher : function(storeName,bar,elem1,elem2,direction){
		el1 = $(elem1);
		el2 = $(elem2);
		bar = $(bar);
		draggable = new Draggable(bar,{constraint:direction, 
			change: function (){ util.doResize(bar,el1,el2,direction); }, 
			endeffect: function(){ util.setUserState(storeName,el1.style.width); }
			});
	},
	setAllSortable : function(){
		s = new sorttable('sortable');
	},
	autoSorterOnClick:function(el,table){
		var el = $(el);
		if(el.value == 'Search') el.clear();
		el.select(); 
		ui.autoSorter(el,table);
		ui.startAutoSorter(el,table);
	},
	autoSorter : function(elem,table){
		var searchText = elem.value.toLowerCase();
		if($(table)){
			
			var rows = $(table).rows;
			var rCount = rows.length-1;
			
			for (var i=0;i<=rCount;i++) {	
				var cellsArr = rows[i].cells;
					for (var e=0;e<=cellsArr.length-1;e++) {
							cellText = cellsArr[e].innerHTML.toLowerCase();
							if(cellText.indexOf(searchText,0) == -1){
								var hasMatch = false;
							}else{
								var hasMatch = true;
								break
							}	
					}
					if(i>0) rows[i].style.display = (hasMatch)?"":"none";
			}
		}else{
			var rows = $$('.searchable');
			var rCount = rows.length;
			for (var e=0;e<=rows.length-1;e++) {				
				cellText = rows[e].innerHTML.toLowerCase();
				rows[e].style.display = (cellText.indexOf(searchText,0) == -1)?"none":"";		
			}
		}
		
		for(var r=0;r<=rows.length-1;r++){
			if(!$(rows[r]).visible()) --rCount;	
		}
		
		$('centerFooterMsg').innerHTML = rCount+" "+'<span class="loc">'+table+'</span>';
	},
	startAutoSorter : function(elem,table){
		Event.observe(elem,'keyup',function(){ ui.autoSorter(elem,table);});
		var found = false;
		var enterAction = function(event){ if(event.keyCode==13){ $A($(ui.currentListName).rows).each(function(row,i){ if(i != 0 && row.visible() && found!=true){ ad.drawEditAd(row.id.replace('row','')); found = true; } }); }};
		Event.observe(elem, 'keypress',enterAction);
	},
	request:function(action,klass,params,onComplete){
		qps = (params)?Object.toQueryString(params):"";
		onComplete = onComplete || "";
		pBody = 'action='+action+'&class='+klass+'&'+qps;
		new Ajax.Request(loc, {postBody:pBody,onComplete:onComplete});
	},
	update:function(container,action,klass,params,onComplete){
		qps = (params)?Object.toQueryString(params):"";
		onComplete = onComplete || "";
		//console.log(qps);
		pBody = 'action='+action+'&class='+klass+'&'+qps;
		new Ajax.Updater(container,loc, {postBody:pBody,onComplete:onComplete});
	},
	updateDateCell : function(cellId) {	
		if($(cellId)){
			t = "";
			zero = "";
			d = new Date();
			ch = d.getHours();
			cm = d.getMinutes();	
			t =(ch<12)?"am":"pm";
			if (ch == 0)ch = 12;
			if (ch > 12)ch = ch - 12;
			if (cm < 10){zero = '0';}
			d = ch + ":" + zero + cm + " " + t;
			$(cellId).innerHTML='Today &nbsp;&nbsp;'+d;
		}
	},
	showBLI:function(obj){
		$(obj).innerHTML = "<div class='diContainer bli'></div>";
		Element.show(obj);
	},
	showBDI : function(obj){
		ui.setBDI(obj);
		Element.show(obj);
	},
	showDI : function(obj){	
		$(obj).innerHTML = "<div class='diContainer sgi'></div>";
		Element.show(obj);
	},
	showLI : function(obj){
		$(obj).innerHTML = "<div class='diContainer sli'></div>";
		Element.show(obj);
	},
	setBDI : function(obj){
		$(obj).innerHTML = "<div class='diContainer bdi'></div>";
	},
	getDI:function(){
		return "<img src='images/interface/smallgrayindicator.gif' class='asFilterIcon'/>";
	},
	getBDI:function(){
		return "<img src='images/interface/indicatorbigdrk.gif'/>";
	},
	clearAllListeners:function(){
		clearInterval(ad.adViewableListener);
		clearInterval(ad.adQueueListener);
		clearInterval(ad.adDeliveredListener);
		clearInterval(ad.adNotesListener);
		clearInterval(ad.adStateListener);
	},
	fade:function(el){
		Element.hide(el);
	},
	appear:function(el){
		Effect.Appear(el,{duration:0.5});
	},
	skinSelects:function(){
		if(!Prototype.Browser.IE){
			$$(".custom").each(function(el){
			if(el.type == "select-one") new SMASelect(el);
		});
		}
	},
	skinUpload:function(){
		if($('overFile')){
			$('upfile_0').onchange = function(){
				$('overFile').value= util.getFileName($F('upfile_0'));
			}
		}
	},
	findDraggable:function(){
		objs = $$('.draggable');
		objs.each(function(obj){
			if (obj.id == 'specTrim') {
				adSpec.draggableSpecTrim(obj);
			} else {
				new Draggable(obj);
			};
		});
	},
	disableButton:function(el){
		el.tmpclick = el.onclick;
		el.onclick = "";
		el.style.cursor = 'none';
		el.style.opacity = .2;
	},
	enableButton:function(el){
		if(el.tmpclick) el.onclick = el.tmpclick; 
		el.style.cursor = 'pointer';
		el.style.opacity = 1;
	},
	removeTableRow : function(rowId){
		if($(rowId)) $(rowId).parentNode.removeChild($(rowId));
	},
	getSelectorLabel : function(elem){
		return $(elem).options[$(elem).selectedIndex].innerHTML;
	},
	reverseSelection:function(){
		util.clearArray(SMA.actionQueue);
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			if(cb.checked){
				cb.checked = false;
			}else{
				if($('row'+$(cb).value).visible()){
					cb.checked = true;
					SMA.addToActionQueue(cb);
				}
			}
		});
	},
	deselectAll:function(){
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			cb.checked = false;
		});
		util.clearArray(SMA.actionQueue);
	},
	selectAll:function(){
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			if($('row'+$(cb).value).visible()){
				cb.checked = true;
				SMA.addToActionQueue(cb);
			}
		});
	},
	hideSelects:function(){
		var selects = $$('.custom');
		selects.each(function(select){
			select.hide();
		});
	},
	showSelects:function(){
		var selects = $$('.custom');
		selects.each(function(select){
			select.show();
		});
	}
});

var Popup = Class.create({
	initialize : function() {
		this.id  		= "";
		this.open 		= false;
		this.boxWidth 	= 500;
		this.msgBypass = 0;
		this.bigger 	= false;
	},
	update:function(action,klass,params,onComplete){
		ui.setBDI('popupContent');
		this.show();
		ui.update('popupContent',action,klass,params,onComplete);
	},
	message:function(msg){
		$('popupContent').innerHTML = '<div id="pMsg"><br><br><br><br><br>'+ui.getBDI()+'<h1><span class="loc">'+msg+"</span></h1></div>";
		this.updateUI();
		popup.show();
	},
	show:function(){
		$('formScreen').show();
		Effect.Appear('popupContainer');
	},
	hide:function(){
		ui.fade('formScreen');
		ui.fade('popupContainer');
		$('popupContent').innerHTML = "";
		this.msgBypass = 0;
	},
	/*toggle : function(){
		if(!$('formScreen').visible)
			this.show();
		else
			this.hide();
		ui.updateMainUI();
	},*/
	updateUI :function(){
		
		w = (this.bigger)?500:0;
		h = (this.bigger)?150:0;
		if($('popupContent') && document.viewport){
			var width =	document.viewport.getWidth();
			var height = document.viewport.getHeight();
			//not sure if this is needed anymore
			if((width == 0) && (height == 0)){
				var height=document.body.clientHeight;
				var width=document.body.clientWidth;
			}
			if($('body').scrollHeight > document.viewport.getHeight() ){
				$('formScreen').style.height = $('body').scrollHeight+'px';
			}
			var sh = $('popupContainer').scrollHeight;
			var boxTop = ((height /4.5) / 2) + $('body').cumulativeScrollOffset()[1];
			var mh = (height - (boxTop * 2))+1;
			var boxWidth =  this.boxWidth + w;
			$('popupContainer').style.width = boxWidth+'px';
			var left = ((width - boxWidth) /2);
			var ch = ($('popupContent').childElements().length > 0)?$('popupContent').childElements()[0].getHeight():0;
			ch = (ch>300)?ch:300;
			var boxHeight = ((ch<mh)?(ch+15):mh)+h;
			$('popupContainer').setStyle({left:left+'px',top:boxTop+'px',height:boxHeight+'px',minHeight:'300px'});
			if($('popupContainer').visible()){window.onresize = popup.updateUI.bindAsEventListener(this);}
			ui.findDraggable();
		}
	},
	updateScroll:function(){
		$('popupContainer').style.top = $('body').cumulativeScrollOffset()[1]+25+'px';
	}
});

var sorttable = Class.create({
  initialize: function(className, options) {
	this.options = Object.extend({
		classNames : {
			oddRow : 'oddRow',
			evenRow : 'evenRow',
			sortAsc : 'sortasc',
			sortDesc : 'sortdesc'
		}}, options || {});
		
	this.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
	this.tables = $$('.'+className);
	this.colomnSortedTable = "";
	$A(this.tables).each(function(table){
		
		if(!table.getAttribute("sorted")){
			table.writeAttribute("sorted","true");
			this.makeSortable(table);
		}
	}.bind(this));
	this.stripeRows();
  },
  makeSortable:function(table){
	headrow = table.tHead.rows[0].cells;
    for (var i=0; i<headrow.length; i++) {
      if (!headrow[i].className.match(/\bnosort\b/)) { // skip this col
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) override = mtch[1];
	    	headrow[i].sorttable_sortfunction = (mtch && typeof sorttable["sort_"+override] == 'function')?sorttable["sort_"+override]:this.guessType(table,i);
	    	headrow[i].sorttable_columnindex = i;
	   	//IE is pure evil
			if(Prototype.Browser.IE){
				Event.observe(headrow[i], 'click', this.forward.bindAsEventListener(headrow[i],this,table.tBodies[0]));
			}else{
				headrow[i].onclick = this.forward.bindAsEventListener(headrow[i],this,table.tBodies[0]);
			}
	   }
	}
  },
  stripeRows:function(){
	this.tables.each(function(table){
		tbody = table.tBodies[0];
		rows = tbody.rows;
		dark =(table.hasClassName('dark'))?true:false;
		for (var i=0; i<rows.length; i++) {
			even = (dark)?'rowevenDark':'roweven';
			odd = (dark)?'rowoddDark':'rowodd';
			var css = ((i+1)%2 === 0 ?even:odd);
			var cn = rows[i].className.split(/\s+/);
			var newCn = [];
			for(var x = 0, l = cn.length; x < l; x += 1) {
				if(cn[x] !== even && cn[x] !== odd) 
					newCn.push(cn[x]); 
			}
			newCn.push(css);
			rows[i].className = newCn.join(" ");
		}
	});
  },
  guessType: function(table, column) {
	// guess the type of a column based on its first non-blank row
    sortfn = this.sort_alpha;
    for (var i=0; i<table.tBodies[0].rows.length; i++) {
		text = this.getInnerText(table.tBodies[0].rows[i].cells[column]);
		if(text != ''){
        if(text.match(/^-?[£$¤]?[\d,.]+%?$/))
          return this.sort_numeric;
     
        possdate = text.match(this.DATE_RE)
		
        if(possdate){
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if(first > 12)
            return this.sort_ddmm;
          else if (second > 12)
            return this.sort_mmdd;
          else
            sortfn = this.sort_ddmm;
        }
      }
    }
    return sortfn;
  },
  getInnerText: function(node){
	hasInputs = (typeof node.getElementsByTagName == 'function') && node.getElementsByTagName('input').length;
    if (node.getAttribute("sorttable_customkey") != null) {
	  return node.getAttribute("sorttable_customkey");
    }else if (typeof node.textContent != 'undefined' && !hasInputs) {
    	return node.textContent.replace(/^\s+|\s+$/g, '');
    }else if (typeof node.innerText != 'undefined' && !hasInputs) {
    	return node.innerText.replace(/^\s+|\s+$/g, '');
    }else if (typeof node.text != 'undefined' && !hasInputs) {
    	return node.text.replace(/^\s+|\s+$/g, '');
    }else {
	  switch (node.nodeType) {
        case 3:
	      if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
	      return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
			var innerText = '';
	          for (var i = 0; i < node.childNodes.length; i++) {
	            if(node.childNodes[i].value){
					innerText = node.childNodes[i].value;
					return innerText.replace(/^\s+|\s+$/g, '');
				}
	          }		
			return '';
        case 11:
	      var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += this.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
	      return '';
      }
    }
  },
  forward : function(e,t,tBody){
		var el = Event.element(e);
		sd = t.options.classNames.sortDesc;
		sa = t.options.classNames.sortAsc;
		if ($(el).hasClassName(sd)){
		//more IE evil  
		if(Prototype.Browser.IE) Event.stopObserving(el, 'click',t,tBody);
		
		t.reverse(tBody);
		el.className = el.className.replace(sd,sa);
        	return;
        }
		
        if(el.hasClassName(sa)) {
		  t.reverse(tbody);
          el.className = el.className.replace(sa,sd);
          return;
        }
		
        $A(el.parentNode.childNodes).each(function(cell){
			if(cell.nodeType == 1) {
		     	$(cell).removeClassName(sa);
		        $(cell).removeClassName(sd);
		     }
		});
        el.addClassName(sd);

	    rowArray = [];
	        col = el.sorttable_columnindex;
	        rows = $A(tbody.rows);
			rows.each(function(row){
				rowArray[rowArray.length] = [t.getInnerText(row.cells[col]), row];
			}.bind(this));
			
	        rowArray.sort(el.sorttable_sortfunction);
	       
			for (var j=0; j<rowArray.length; j++) {
	          tbody.appendChild(rowArray[j][1]);
	        }
	        delete rowArray;
			t.stripeRows();
  },
  reverse: function(tbody){
	newrows = [];
    for (var i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
	this.stripeRows();
  }, 
  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0]==b[0]) return 0;
    if (a[0]<b[0]) return -1;
    return 1;
  },
  sort_ddmm: function(a,b) {
	mtch = a[0].match(this.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(this.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  sort_mmdd: function(a,b) {
    mtch = a[0].match(this.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(this.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  }  
});

var Uploader = Class.create({
	initialize : function(){
		this.createIframe('test');
	},
	createIframe: function(id){
		var iframe = new Element('iframe', {'id':id,'name':id,style:'position:absolute;top:0px;left:0px'});	
        document.body.appendChild(iframe);
    }
});

var Base64 = {
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  	encode : function (input) {
    	 var output = "";
	     var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	     var i = 0;
    	if(input == "") return ""; 
		
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
	            enc1 = chr1 >> 2;
	            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	            enc4 = chr3 & 63;
	            if (isNaN(chr2)) {
	                enc3 = enc4 = 64;
	            } else if (isNaN(chr3)) {
	                enc4 = 64;
	            }
	            output = output +
	            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
	            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
	       }
	       return output;	
	},
	_utf8_encode : function (string) {
		if(string){
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
	        var c = string.charCodeAt(n);
		   	if (c < 128){ utftext += String.fromCharCode(c); }
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}else {
		     	utftext += String.fromCharCode((c >> 12) | 224);
		        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
		        utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
		}else{
			return "";
		}
	}
};

Ajax.currentRequests = {};

Ajax.Responders.register({
	onCreate: function(request) {
		request.options.postBody = util.encode(request.options.postBody+'&'+Object.toQueryString(request.options.parameters)); 
		if(request.options.override && Ajax.currentRequests[request.options.override]) {
			try { Ajax.currentRequests[request.options.override].transport.abort(); } catch(e) {}
		}
		Ajax.currentRequests[request.options.override] = request;
	},
	onComplete: function(request) {
		//console.log(request.transport.responseText);
		resp = request.transport.responseText;
		
		if(resp.include('{"logout":"true"}')){
			popup.update('drawPopupLogin','Sma');
		}
		
		if(!request.parameters.dontUpdateMainUI){
			ui.updateMainUI(); 
		};
		
		if($('popupContent').visible()){ popup.updateUI();}
		if(request.options.override) {
			Ajax.currentRequests[request.options.override] = null;
		}
		
		//post translater
		$$('.loc').each(function(e){
			tran = data[e.innerHTML.replace(/^\s+|\s+$/g, '')];
			cur = e.innerHTML;
			if(tran) e.innerHTML = tran;
		});
		
	},
	onException:function(request){
		if(request.transport.responseText.isJSON()){
			j = request.transport.responseText.evalJSON();
			if(j[0] == "logout"){
				//todo channge this to popup window for re login
				document.location.href=j[1];
			}
		}
	}
});