/**
* @author Ryan Johnson <ryan@livepipe.net>
* @copyright 2007 LivePipe LLC
* @package Prototype.Extensions
* @license MIT
* @url http://livepipe.net/projects/prototype_extensions/
*/

if(typeof(document.getElementsByAttribute) == "undefined"){
	document.getElementsByAttribute = function(attribute,parent) {
		return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
			return (child.getAttribute(attribute)) ? (elements.push(Element.extend(child)),elements) : elements;
		});
	}
}

if(typeof(document.getElementsByAttributeValue) == "undefined"){
	document.getElementsByAttributeValue = function(attribute,value,parent){
		return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
			return (child.getAttribute(attribute) && child.getAttribute(attribute) == value) ? (elements.push(Element.extend(child)),elements) : elements;
		});
	}
}

Element.addMethods({
	makeUnselectable: function(element,cursor){
		cursor = cursor || 'default';
		element.onselectstart = function() {
	        return false;
	    };
	    element.unselectable = "on";
	    element.style.MozUserSelect = "none";
	    element.style.cursor = cursor;
		return element;
	},
	makeSelectable: function(element){
		element.onselectstart = function() {
	        return true;
	    };
	    element.unselectable = "off";
	    element.style.MozUserSelect = "";
	    element.style.cursor = "inherit";
		return element;
	},
	getElementsByAttribute: function(element,attribute){
		return document.getElementsByAttribute(attribute,element);
	},
	getElementsByAttributeValue: function(element,attribute,value){
		return document.getElementsByAttributeValue(attribute,value,element);
	}
});

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			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
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

var Client = {
	browser: false,
	OS: false,
	version: false,
	current_place: 0,
	current_string: '',
	detect: navigator.userAgent.toLowerCase(),
	load: function(){
		if(Client.check("konqueror")){
			Client.browser = "Konqueror";
			Client.OS = "Linux";
		}else{
			$H({
				safari: "Safari",
				omniweb: "OmniWeb",
				opera: "Opera",
				webtv: "WebTV",
				icab: "iCab",
				msie: "Internet Explorer"
			}).each(function(browser){
				if(!Client.browser && Client.check(browser[0]))
					Client.browser = browser[1];
			});
		}
		if(!Client.browser && !Client.check('compatible')){
			Client.browser = "Netscape Navigator"
			Client.version = Client.detect.charAt(8);
		}
		if(!Client.version)
			Client.version = Client.detect.charAt(Client.current_place + Client.current_string.length);
		if(!Client.OS){
			$H({
				linux: "Linux",
				x11: "Unix",
				mac: "Mac",
				win: "Windows"
			}).each(function(OS){
				if(!Client.OS && Client.check(OS[0]))
					Client.OS = OS[1];
			});
			if(!Client.OS)
				Client.OS = "unknown";
		}
	},
	check: function(string){
		Client.current_string = string;
		Client.current_place = Client.detect.indexOf(string) + 1;
		return Client.current_place;
	}	
};
Client.load();


Object.extend(window,{	
	openedWindows: {},
	openCentered: function(location,name,params){
		this.openedWindows[name] = window.open(location,name,$H({
			width: 800,
			height: 600,
			left: Math.round((screen.width ? (screen.width - (params && params.width ? params.width : 800)) / 2 : 0)),
			top: Math.round((screen.height ? (screen.height - (params && params.height ? params.height : 600)) / 4 : 0)),
			dependent: true,
			directories: true,
			fullscreen: false,
			location: true,
			menubar: true,
			resizable: true,
			scrollbars: true,
			status: true,
			toolbar: true
		}).merge(params || {}).inject('',function(str,item){
			if(item[1] == true)
				value = 'yes';
			else if(item[1] == false)
				value = 'no';
			else
				value = item[1];
			return str + item[0] + '=' + value + ',';
		}).replace(/\,$/,''));
		this.openedWindows[name].focus();
		return this.openedWindows[name];
	}
});


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);
  }
});


/** 
* @projectDescription 	Poly9's polyvalent URLParser class
*
* @author	Denis Laprise - denis@poly9.com - http://poly9.com
* @version	0.1 
* @namespace	Poly9
*
* Usage: var p = new Poly9.URLParser('http://user:password@poly9.com/pathname?arguments=1#fragment');
* p.getHost() == 'poly9.com';
* p.getProtocol() == 'http';
* p.getPathname() == '/pathname';
* p.getQuerystring() == 'arguments=1';
* p.getFragment() == 'fragment';
* p.getUsername() == 'user';
* p.getPassword() == 'password';
*
* See the unit test file for more examples.
* URLParser is freely distributable under the terms of an MIT-style license.
*/

if (typeof Poly9 == 'undefined')
 var Poly9 = {};

/**
 * Creates an URLParser instance
 *
 * @classDescription	Creates an URLParser instance
 * @return {Object}	return an URLParser object
 * @param {String} url	The url to parse
 * @constructor
 * @exception {String}  Throws an exception if the specified url is invalid
 */
Poly9.URLParser = function(url) {
 this._fields = {'Username' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 'Host' : 6, 'Pathname' : 8, 'URL' : 0, 'Querystring' : 9, 'Fragment' : 10};
 this._values = {};
 this._regex = null;
 this.version = 0.1;
 this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;
 for(var f in this._fields)
  this['get' + f] = this._makeGetter(f);
 if (typeof url != 'undefined')
  this._parse(url);
}
 
/**
 * @method 
 * @param {String} url	The url to parse
 * @exception {String} 	Throws an exception if the specified url is invalid
 */
Poly9.URLParser.prototype.setURL = function(url) {
  this._parse(url);
}

Poly9.URLParser.prototype._initValues = function() {
   for(var f in this._fields)
   this._values[f] = '';
}

Poly9.URLParser.prototype._parse = function(url) {
  this._initValues();
  var r = this._regex.exec(url);
  if (!r) throw "DPURLParser::_parse -> Invalid URL"
  for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined')
   this._values[f] = r[this._fields[f]];
}

Poly9.URLParser.prototype._makeGetter = function(field) {
 return function() {
  return this._values[field];
 }
}

