/*
 * Author: Yevgen Gorshkov, 'jatany at gmail dot com'
 * Last Modified: 2006-04-19
 * DAPI Lite is freely distributable under the terms of an MIT-style license.
 * 
 */

//* DAPI for Prototype version
_DAPI_PROTO_="1.17a";



/************************************
 * An add-on to Prototype 1.5 to speed up the $$ function in usual cases.
 * http://www.sylvainzimmer.com/index.php/archives/2006/06/25/speeding-up-prototypes-selector/
 * Authors: 
 *    - Sylvain ZIMMER <sylvain _at_ jamendo.com>
 ************************************/

var SelectorLiteAddon=Class.create();SelectorLiteAddon.prototype={initialize:function(stack){this.r=[];this.s=[];for(var i=stack.length-1;i>=0;i--){var s=["*","",[]];var t=stack[i];var cursor=t.length-1;do{var d=t.lastIndexOf("#");var p=t.lastIndexOf(".");cursor=Math.max(d,p);if(cursor==-1){s[0]=t.toUpperCase();}else if(d==-1||p==cursor){s[2].push(t.substring(p+1));}else if(!s[1]){s[1]=t.substring(d+1)}t=t.substring(0,cursor)}while(cursor>0);this.s[i]=s}},get:function(root){this.explore(root||document,(this.s.length-1)==0,0);return this.r},explore:function(elt,leaf,sp){var s=this.s[sp];var r=[];if(s[1]){e=$(s[1]);if(e&&(s[0]=="*"||e.tagName==s[0])&&e.childOf(elt)){r=[e]}}else{r=$A(elt.getElementsByTagName(s[0]))}if(s[2].length==1){r=r.findAll(function(o){if(o.className.indexOf(" ")==-1){return o.className==s[2][0]}else{return o.className.split(/\s+/).include(s[2][0])}});}else if(s[2].length>0){r=r.findAll(function(o){if(o.className.indexOf(" ")==-1){return false}else{var q=o.className.split(/\s+/);return s[2].all(function(c){return q.include(c)})}})}if(leaf){this.r=this.r.concat(r);}else{++sp;r.each(function(o){this.explore(o,sp==(this.s.length-1),sp)}.bind(this))}}};var $$old=$$;var $$=function(a,b){if(b||a.indexOf("[")>=0)return $$old.apply(this,arguments);return new SelectorLiteAddon(a.split(/\s+/)).get()};
//******************************

//* Simple browser detection
var Browser={
	DOM:(document.getElementById)?1:0,
	NS4:(document.layers)?1:0,
	IE:(document.all)?1:0,
	IE5:navigator.appVersion.indexOf('MSIE 5.0')!=-1,
	IE6:navigator.appVersion.indexOf('MSIE 6.0')!=-1,
	FF:navigator.userAgent.indexOf(' Gecko')!=-1
};

//* Useful functions
function getTags(name) { return document.getElementsByTagName(name); }

function $vis(o,vis,disp) {
	o=$(o); if(!o) return;
	if(vis) {
		disp = disp || 'block';
		o.style.visibility='visible';
		o.style.display=disp;
	} else {
		o.style.visiblity='hidden';
		if(disp) o.style.display='none';
	}
}


//* Forms
// another useful function: get and set form element value
function $Fe(form,name) {
	return $(form).elements[name];
}
function $Fv(form,name) {
	var v=$(form).elements[name];
	return (v&&v.value)?v.value:"";
}
function $Fs(form,name,value) {
	var v=$(form).elements[name];
	if(v)v.value=value;
}


//* Cookies operations
var Cookie={
  create:function(name,value,days) {
  	var expires="";
	if(days) {
		var date=new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
  },
  read:function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) {
		var c = ca[i];
		while(c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ)==0) return c.substring(nameEQ.length,c.length);
	}
	return null;
  },
  erase:function(name) {
	this.create(name,"",-1);
  },
  checkLocal:function(string) {
	placeOfDetect = detect.indexOf(string) + 1;
	thestring = string;
	return placeOfDetect;
  }
};


//* DOM extension
document.getElementsByTagNames = function(list,o) {
	if(!o) var o = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for(var i=0;i<tagNames.length;i++) {
		var tags = o.getElementsByTagName(tagNames[i]);
		for(var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	
	var testNode = resultArray[0];
	if (testNode.sourceIndex)
	{
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition)
	{
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

//* String functions
String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g, ""); };
String.prototype.normalise = function() { return this.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' '); };


//* Stylesheet switcher
var StyleSwitch={
	init:function() {
		var _ssc=Cookie.read("style");
		this.setActive(_ssc?_ssc:this.getPreferred());
		addEvent(window,"load",function() {
			var cookie=Cookie.read("style");
			this.setActive(cookie?cookie:this.getPreferred());
		}.bind(this));
		//addEvent(window,"unload",function() { Cookie.create("style", this.getActive(), 365); }.bind(this));
	},
	setActive:function(title) {
		var i, a;
		for(i=0; (a=document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				a.disabled = true;
				if(a.getAttribute("title") == title) {
					a.disabled = false;
					Cookie.create("style", a.getAttribute("title"), 365);
				}
			}
		}
	},
	getActive:function() {
		var i, a;
		for(i=0; (a=document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
				return a.getAttribute("title");
		}
		return null;
	},
	getPreferred:function() {
		var i, a;
		for(i=0; (a=document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("rel").indexOf("alt") == -1 && a.getAttribute("title"))
				return a.getAttribute("title");
		}
		return null;
	}
};

//* Location-related functions
function _goto(url,target) {
	if(target) eval(target+'.location.href="'+url+'";');
	else window.location.href=url; 
}



//* contains() method for Mozilla
if(window.Node && Node.prototype && !Node.prototype.contains) {
	Node.prototype.contains = function (arg) {
		return !!(this.compareDocumentPosition(arg) & 16)
	}
}


//* Text truncator utility
var TextUtils={
  lre:/[ \r\n\t]/g,
  limit:function(p,submit,limit) {
	var submit=$(submit);
	if(!submit) return;
	var disabled=p.value.replace(this.lre,'').length >= limit;
	submit.disabled=disabled;
  },
  rangelimit:function(p,submit,range) {
	var submit=$(submit);
	if(!submit) return;
	var len=p.value.replace(this.lre,'').length;
	submit.disabled=len<range[0] || len > range[1];
  }
};

var Truncator={
  len:100, text:'...',
  go:function(p) {
	p=$(p); if(!p) return;
	var trunc=p.innerHTML;
	if(trunc.length<=this.len) return;

	trunc=trunc.substring(0,this.len);
	trunc=trunc.replace(/\w+$/, '');
	var a=document.createElement('a');
	a.href="#";
	a.innerHTML=this.text;
	a.fullText=p.innerHTML;
	a.onclick=function() { this.parentNode.innerHTML=this.fullText; return false; };
	p.innerHTML=trunc;
	p.appendChild(a);
  }
};


//* UID functions
function randstr(len) {
	if(typeof len=='undefined') len=5;
    res="";
    while(len--) {	res+=""+Math.round(Math.random()*9); }
    return res;
}


//* prototype scoped selector addon
function $$S(scope) {
  return $A(arguments).without(arguments[0]).map(function(expression) {
    return expression.strip().split(/\s+/).inject([$(scope)], function(results, expr) {
      var selector = new Selector(expr);
      return results.map(selector.findElements.bind(selector)).flatten();
    });
  }).flatten();
}


//* onDOMReady event. http://www.vivabit.com/code/domready/domready.js
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});
