DWI.namespace("util"); // will be used for some common use functions
// setup some shortcuts
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var $ = Dom.get;
var $D = document;

DWI.util.head = null;
DWI.util.load_js = function (src,onload)
{
    if (! this.head) {
        this.head = document.getElementsByTagName('head')[0];
    }
    var js;
    if (typeof src == 'string') {
        js = document.createElement('script');
        js.src = src;
        if (onload) {
            js.onload = onload;
        }
        this.head.appendChild(js);
    } else if (typeof src == 'object'){
        var i;
        for (i in src) {
            js = document.createElement('script');
            js.src = src[i];
            this.head.appendChild(js);
        }
    }
}

DWI.util.remove_class = function (ob,cl)
{
    var new_class = ob.className;
        new_class = new_class.replace(cl, ' ');
    ob.className = new_class;
}

DWI.util.add_class = function (ob,cl)
{
    var new_class = ob.className;
        new_class += ' ' + cl;
    ob.className = new_class;
}

DWI.util.createCookie = function (name,value,days)
{
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

DWI.util.readCookie = 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;
}

DWI.util.eraseCookie = function (name)
{
	this.createCookie(name,"",-1);
}

// Retrieve the rendered width of an element
DWI.util.objWidth = function (elem)
{
    var result = 0;
    if (elem.offsetWidth) {
        result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}

// Retrieve the rendered height of an element
DWI.util.objHeight = function (elem)
{
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

DWI.util.fast_innerHTML = function (el,html)
{
    if (typeof el == 'string') {
        el = this.get(el);
    }
	/*@cc_on // Pure innerHTML is slightly faster in IE
		el.innerHTML = html;
		return el;
	@*/
	var newEl = el.cloneNode(false);
	newEl.innerHTML = html;
	el.parentNode.replaceChild(newEl, el);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
}

DWI.util.form_scan = function (form,reset,field)
{
    var data = {};
    if (! field) {
        field = 'form_field';
    }
    var set = YAHOO.util.Dom.getElementsByClassName(field,'',form);
    var i;
    for (i in set) {
        var el = set[i];
        if (el.nodeName == 'INPUT' || el.nodeName == 'TEXTAREA') {
            if (el.type == 'checkbox') {
                if (el.checked) {
                    data[el.name] = el.value;
                    if (reset) { el.checked = false; }
                }
            } else {
                data[el.name] = el.value;
                if (reset) { el.value = ''; }
            }
        } else if (el.nodeName == 'SELECT') {
            data[el.name] = this.get_select_value(el);
        }/**
            de adaugat radio

        **/
    }    
    return data;
}


DWI.util.get_select_value = function(sel_h)
{
    var option_index = sel_h.selectedIndex;
    if (typeof sel_h[option_index] == "undefined") {
        return 0;
    }
    var option_value = sel_h[option_index].value;
//    var option_name = sel_h[option_index].text;
    return option_value;
}

DWI.util.dom_cache = {};
DWI.util.get_cache = function(el, root)
{
    if (!el || el.tagName || el.item) { // null, HTMLElement, or HTMLCollection
        return el;
    }

    if (YAHOO.lang.isString(el)) { // HTMLElement or null
        if (DWI.util.dom_cache[el]) {
            return DWI.util.dom_cache[el];
        }
        if (! root) {
            root = document;
        }
        DWI.util.dom_cache[el] = root.getElementById(el);
        return DWI.util.dom_cache[el];
    }

    return null;
}
DWI.util.get = function(el, root)
{
    if (!el || el.tagName || el.item) { // null, HTMLElement, or HTMLCollection
        return el;
    }

    if (YAHOO.lang.isString(el)) { // HTMLElement or null
        if (! root) {
            root = document;
        }
        return root.getElementById(el);
    }

    return null;
}

/**
    http://mattsnider.com/languages/javascript/removenode-and-appendnode-methods/
**/
DWI.util.animParamsIn = {
                opacity: {from: 0, to: 1}
                };
DWI.util.animParamsOut = {
                opacity: {from: 0.9, to: 0}
                };
                
DWI.util.insertNode = function(root, elem, ap, fn) {
    var node = $(elem),
        parent = $(root);
        
    if (! parent.hasChildNodes()) {
        return this.appendNode(root,elem,ap,fn);
    }

    if (parent && node) {
        parent.insertBefore(node,parent.firstChild);

        var animParams = (ap && typeof ap == 'object') ? ap : this.animParamsIn,
            anim = new YAHOO.util.Anim(node, animParams, 0.5, YAHOO.util.Easing.easeIn);

        anim.onComplete.subscribe(function() {
            if (fn && typeof fn == 'function') {fn(node);}
        });
        anim.animate();
    }

    return node;
};

DWI.util.appendNode = function(root, elem, ap, fn) {
    var node = $(elem),
        parent = $(root);

    if (parent && node) {
        parent.appendChild(node);

        var animParams = (ap && typeof ap == 'object') ? ap : this.animParamsIn,
            anim = new YAHOO.util.Anim(node, animParams, 0.5, YAHOO.util.Easing.easeIn);

        anim.onComplete.subscribe(function() {
            if (fn && typeof fn == 'function') {fn(node);}
        });
        anim.animate();
    }

    return node;
};


DWI.util.removeNode = function(elem, ap, fn, isRemoveListeners) {
    var node = $(elem),
        parent = node.parentNode;

    if (parent) {
        var animParams = (ap && typeof ap == 'object') ? ap : this.animParamsOut,
            anim = new YAHOO.util.Anim(node, animParams, 0.5, YAHOO.util.Easing.easeOut);

        if (isRemoveListeners) {Event.purgeElement(node, true);}

        anim.onComplete.subscribe(function() {
            parent.removeChild(node);
            if (fn && typeof fn == 'function') {fn();}
        });

        anim.animate();
    }
};

DWI.util.valid_url = function (url)
{
/* 
    renuntam la http://
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
*/
    var regexp = /(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(url);
}


DWI.util.in_array = function(ob, datum, strict) {
    if (strict) function equals(a,b) { return a === b }
    else function equals(a,b) { return a == b }

    for (var i in ob) {
        if (equals(ob[i], datum)) return true;
    }
    return false;
}

DWI.util.html_entity_decode = function (str) {
    var ta = document.createElement("textarea");
    ta.innerHTML = str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
    return ta.value;
}


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

// credit: http://www.dieterraber.net
/**
 * htmlEntities
 *
 * Convert all applicable characters to HTML entities
 *
 * object string
 * return string
 *
 * example:
 *   test = 'äöü'
 *   test.htmlEntities() //returns '&auml;&ouml;&uuml;'
 */

String.prototype.htmlEntities = function()
{
  var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
                         '>','¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','­','®','¯','°','±','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');

  var entities = new Array ('amp','agrave','aacute','acirc','atilde','auml','aring',
                            'aelig','ccedil','egrave','eacute','ecirc','euml','igrave',
                            'iacute','icirc','iuml','eth','ntilde','ograve','oacute',
                            'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc',
                            'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc',
                            'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute',
                            'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde',
                            'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave',
                            'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig',
                            'lt','gt','cent','pound','curren','yen','brvbar','sect','uml',
                            'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn',
                            'sup2','sup3','acute','micro','para','middot','cedil','sup1',
                            'ordm','raquo','frac14','frac12','frac34');

  newString = this;
  for (var i = 0; i < chars.length; i++)
  {
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g')
    newString = newString.replace (myRegExp, '&' + entities[i] + ';');
  }
  return newString;
}


/**
 * numericEntities
 *
 * Convert all applicable characters to numeric entities
 *
 * object string
 * return string
 *
 * example:
 *   test = 'äöü'
 *   test.numericEntities() //returns '&#228;&#246;&#252;'
 */

String.prototype.numericEntities = function()
{
  var i;
  var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
                         '>','¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','­','®','¯','°','±','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');

  var entities = new Array()
  for (i = 0; i < chars.length; i++)
  {
    entities[i] = chars[i].charCodeAt(0);
  }

  newString = this;
  for (i = 0; i < chars.length; i++)
  {
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g')
    newString = newString.replace (myRegExp, '&#' + entities[i] + ';');
  }
  return newString;
  
}


function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}


