YAHOO.namespace ("Fiveself.Utils.Url");
YAHOO.namespace ("Fiveself.Utils.Window");
YAHOO.namespace ("Fiveself.Utils.Dom");
YAHOO.namespace ("Fiveself.Utils.Lang");
YAHOO.namespace ("Fiveself.Utils.Format");
YAHOO.namespace ("Fiveself.Utils.Translation");
YAHOO.namespace ("Fiveself.Utils.Input");

YAHOO.Fiveself.Utils.Dom.clearPlaceholder = function(el, placeholderText, callback) {	
    if(el.value == placeholderText) {
        el.value = '';
        callback();
    }
};

YAHOO.Fiveself.Utils.Dom.setInnerHTML = function (el, html) {
    el = YAHOO.util.Dom.get(el);
    if (!el || typeof html !== 'string') {
        return null;
    }

    // Break circular references.
    (function (o) {

        var a = o.attributes, i, l, n, c;
        if (a) {
            l = a.length;
            for (i = 0; i < l; i += 1) {
                n = a[i].name;
                if (typeof o[n] === 'function') {
                    o[n] = null;
                }
            }
        }

        a = o.childNodes;

        if (a) {
            l = a.length;
            for (i = 0; i < l; i += 1) {
                c = o.childNodes[i];

                // Purge child nodes.
                arguments.callee(c);

                // Removes all listeners attached to the element via YUI's addListener.
                YAHOO.util.Event.purgeElement(c);
            }
        }

    })(el);

    // Remove scripts from HTML string, and set innerHTML property
    el.innerHTML = html.replace(/<script[^>]*>[\S\s]*?<\/script[^>]*>/ig, "");

    // Return a reference to the first child
    return el.firstChild;
};

YAHOO.Fiveself.Utils.Input.getSelectInputValue = function(domId) {
	return document.getElementById(domId).options[document.getElementById(domId).selectedIndex].value
};

YAHOO.Fiveself.Utils.Input.insertAtTextAreaCursor = function(myField, myValue) {

	// IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;	
	} // MOZILLA/NETSCAPE support 
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	} 
	else {
		myField.value += myValue;
	}
	
};

YAHOO.Fiveself.Utils.Window.refreshOnTimeout = function(timeout) {
	setTimeout("window.location.href=YAHOO.Fiveself.Utils.Url.getCurrentUrl()",timeout);
};

YAHOO.Fiveself.Utils.Window.scrollPopup = function(url_add, width, height) { 
	window.open(url_add,'welcome', 'width=' + width + ',height=' + height + ", scrollbars=yes");
};

YAHOO.Fiveself.Utils.Window.popup = function(url_add, width, height) { 
	window.open(url_add,'welcome', 'width=' + width + ',height=' + height);
	//,menubar=yes,status=yes, location=yes,toolbar=yes,scrollbars=yes
};


YAHOO.Fiveself.Utils.Format.formatCurrency = function(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
};

YAHOO.Fiveself.Utils.Url.getBaseUrl = function() {

	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(url);
	
	var portStr = '';
	if(YAHOO.Fiveself.Utils.Lang.isSet(parsedUri.port)) {
		portStr = ":" + parsedUri.port;
	}
	
	url = parsedUri.protocol + "://" + parsedUri.host + portStr + parsedUri.path;
	return url;

};

YAHOO.Fiveself.Utils.Url.replacePort = function(port, url) {
	
	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(url);
	
	var portStr = ":" + port;
	
	url = parsedUri.protocol + "://" + parsedUri.host + portStr + parsedUri.path + '?' + parsedUri.query;
	return url;		
	
};

YAHOO.Fiveself.Utils.Url.replaceProtocol = function(protocol, url) {
	
	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(url);
	
	var portStr = '';
	if(YAHOO.Fiveself.Utils.Lang.isSet(parsedUri.port)) {
		portStr = ":" + parsedUri.port;
	}	
	
	url = protocol + "://" + parsedUri.host + portStr + parsedUri.path + '?' + parsedUri.query;
	return url;		
	
};

YAHOO.Fiveself.Utils.Url.replaceUrlPath = function(path) {
	
	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(YAHOO.Fiveself.Utils.Url.getCurrentUrl());
	
	var portStr = '';
	if(YAHOO.Fiveself.Utils.Lang.isSet(parsedUri.port)) {
		portStr = ":" + parsedUri.port;
	}	
	
	url = parsedUri.protocol + "://" + parsedUri.host + portStr + parsedUri.directory + path + '?' + parsedUri.query;
	return url;	
	
};

/**
 * appends param to the current url, replacing the path,
 * note the advantage is it keeps the existing query intact
 */
YAHOO.Fiveself.Utils.Url.appendParamForPath = function(path, name, value) {
	var url = YAHOO.Fiveself.Utils.Url.replaceUrlPath(path);
	return YAHOO.Fiveself.Utils.Url.addParam(url, name, value);
	
};

YAHOO.Fiveself.Utils.Url.removeQuery = function(url) {
	
	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(url);
	
	var portStr = '';
	if(YAHOO.Fiveself.Utils.Lang.isSet(parsedUri.port)) {
		portStr = ":" + parsedUri.port;
	}		
	
	url = parsedUri.protocol + "://" + parsedUri.host + portStr + parsedUri.path;
	return url;
	
};

YAHOO.Fiveself.Utils.Url.addParam = function(url, name, value) {
	
	var parsedUri = YAHOO.Fiveself.Utils.Url.parseUri(url);
	
	var portStr = '';
	if(YAHOO.Fiveself.Utils.Lang.isSet(parsedUri.port)) {
		portStr = ":" + parsedUri.port;
	}		
	
	
	url = parsedUri.protocol + "://" + parsedUri.host + portStr + parsedUri.path;
	
	var foundFirst = false;
	for (var paramName in parsedUri.queryKey) {

		var paramValue = parsedUri.queryKey[paramName];		
		
		// skip because we want to replace
		if(name == paramName) {
			continue;
		}
		
		if(foundFirst) {
			url = url + "&" + paramName + "=" + paramValue;
		}
		else {
			url = url + "?" + paramName + "=" + paramValue;			
			foundFirst = true;
		}
	}

	if(YAHOO.Fiveself.Utils.Lang.isSet(name) && YAHOO.Fiveself.Utils.Lang.isSet(value)) {
		
		if(url.indexOf('?') < 0) {
			url = url + '?' + name + '=' + value;
		}
		else {
			url = url + '&' + name + '=' + value;
		}
		
	}
	
	return url;

}

YAHOO.Fiveself.Utils.Url.getCurrentUrl = function() {
	return window.location.href;	
};

YAHOO.Fiveself.Utils.Url.getParameter = function(name, url) {
	
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  
  var urlToParse = window.location.href;
  if(YAHOO.Fiveself.Utils.Lang.isSet(url)) {
	  urlToParse = url;
  }
  
  var results = regex.exec( urlToParse );
  
  if( results == null ) {
    return "";
  }
  else {
    return results[1];
  }
};


YAHOO.Fiveself.Utils.Dom.getAttribute = function(el, name) {
	
	for ( i=0; i < el.attributes.length; i++ ) {
		
		if(el.attributes[i].name == name) {
			return el.attributes[i].value;
		}
	}
	
	return null;
	
};

YAHOO.Fiveself.Utils.Lang.isSet = function(variable) {
	
	if(typeof(variable)=="undefined") {
		return false;
	}
	
	if(variable==null) {
		return false;
	}
	
	if(variable=="") {
		return false;
	}
	
	return true;
}

/*
parseUri 1.2.1
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT License
*/

YAHOO.Fiveself.Utils.Url.parseUri = function(str) {
	var	o   = YAHOO.Fiveself.Utils.Url.parseUri.options,
	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	i   = 14;
	
	while (i--) uri[o.key[i]] = m[i] || "";
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});
	
	return uri;
};

YAHOO.Fiveself.Utils.Url.parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

/**
 * convert a utf8 url parameter into a readable value
 */
YAHOO.Fiveself.Utils.Translation.convertUTF8Param = function(value) {	
	return YAHOO.Fiveself.Utils.Url.urlDecode(YAHOO.Fiveself.Utils.Url.decodeUTF8(unescape(value)));	
};


YAHOO.Fiveself.Utils.Url.urlDecode = function(psEncodeString) {
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
};

// public method for url encoding
YAHOO.Fiveself.Utils.Url.encodeUTF8 = function (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;
};

// public method for url decoding
YAHOO.Fiveself.Utils.Url.decodeUTF8 = function (utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
};

YAHOO.Fiveself.Utils.Input.createQuickHelp = function(domId, text) {
    new YAHOO.widget.Tooltip(domId + "tt", { autodismissdelay:999999, context:domId, text:text });	
};

YAHOO.Fiveself.Utils.Input.createSelectMenu = function(domId) {
	
	var menu = new YAHOO.Fiveself.Utils.Input.SelectMenu({ 
        id: domId, 
        /*name: domName,*/
        type: "menu",
        lazyloadmenu: false,
        menu: domId, 
        container: domId + "_container" });
	menu.on("selectedMenuItemChange", YAHOO.Fiveself.Utils.Input.onSelectedMenuItemChange);
	
	return menu;
};
YAHOO.Fiveself.Utils.Input.SelectMenu = YAHOO.widget.Button;    
YAHOO.Fiveself.Utils.Input.onSelectedMenuItemChange = function (event) {
	var oMenuItem = event.newValue;
	this.set("label", ("<em class=\"yui-button-label\">" + oMenuItem.cfg.getProperty("text") + "</em>"));
};	

YAHOO.Fiveself.Utils.Input.initCustomFileInput = function(domId, label) {
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'file-input-fake';
	var input = document.createElement('input');
	input.className="text-input";
	input.size="30";
	fakeFileUpload.appendChild(input);
	input.value=label;
	fakeFileUpload.appendChild(input);
	var x = document.getElementById(domId);
		x.className = 'file-input';
		var clone = fakeFileUpload.cloneNode(true);
		x.parentNode.appendChild(clone);
		x.relatedElement = clone.getElementsByTagName('input')[0];
		x.onchange = x.onmouseout = function () {
			this.relatedElement.value = this.value;
		}
};	

