// Chris Pyper 2006
// Utility functions

var XMLREQUEST_COMPLETE = 4;

// a convenience function for AJAX work
function newXMLHTTPRequest(url,meth,callbackFunc,async)
{
    var xmlreq = false;

    if (window.XMLHttpRequest)
    {
        // Non-MS browsers
        xmlreq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        // MS browsers
        try {
            xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                // Try for an older version
                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                // Complete and utter failure.
            }
        }
    }

    if ( xmlreq )
    {
        meth = ( meth == null ) ? "GET" : meth.toUpperCase();
        async = ( async == null ) ? true : async;
        if ( callbackFunc != null )
        {
            xmlreq.onreadystatechange = function() {
                if ( xmlreq.readyState == XMLREQUEST_COMPLETE )
                {
                    if ( xmlreq.status == 200 ) // HTTP status code 200 = OK
                    {
                        callbackFunc(xmlreq.responseXML,xmlreq.responseText);
                    }
                    else
                    {
                        alert("XMLHTTP: "+ xmlreq.status +" "+ xmlreq.statusText  +"]");
                    }
                }

            };
        }

        // set up the request
        // note: this doesn't actually submit the request
        // a call to the xmlreq.send() method is needed for that.
        xmlreq.open(meth,url,async);

        if ( meth == "POST" )
            xmlreq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    }

    return( xmlreq );
}

// Eseentially URL encode
function encodeHtml(data)
{

	return encodeURIComponent(data);
/*
        encodedHtml = escape(data);
        encodedHtml = encodedHtml.replace(/\//g,"%2F");
        encodedHtml = encodedHtml.replace(/\?/g,"%3F");
        encodedHtml = encodedHtml.replace(/=/g,"%3D");
        encodedHtml = encodedHtml.replace(/&/g,"%26");
        encodedHtml = encodedHtml.replace(/@/g,"%40");

        return encodedHtml;
*/
}

// return a random number between 0 and max with an option to force ints
// Used to prevent cachching of requests
function getRandom(max,forceInt)
{
    var num;

    if ( !max )
        max = 10;

    if ( forceInt )
        num = Math.floor( Math.random()*max );
    else
        num = Math.random() * max;

    return( num );
}

// returns hexadecimal color representation from a number or a rgb-style color.
function convertColor(v) 
{
    // returns the hex representation of one byte (2 digits)
    function hex(d) {
        return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
    };

    if (typeof v == "number") {
        // we're talking to IE here
        var r = v & 0xFF;
        var g = (v >> 8) & 0xFF;
        var b = (v >> 16) & 0xFF;
        return "#" + hex(r) + hex(g) + hex(b);
    }

    if (v.substr(0, 3) == "rgb") {
        // in rgb(...) form -- Mozilla
        var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
        if (v.match(re)) {
            var r = parseInt(RegExp.$1);
            var g = parseInt(RegExp.$2);
            var b = parseInt(RegExp.$3);
            return "#" + hex(r) + hex(g) + hex(b);
        }
        // doesn't match RE?!  maybe uses percentages or float numbers
        // -- FIXME: not yet implemented.
        return null;
    }

    if (v.substr(0, 1) == "#") {
        // already hex rgb (hopefully :D )
        return v;
    }

    // if everything else fails ;)
    return null;
}

// translate a string
function translate(key)
{
	var str = "";

	if ( ISTRINGS[EDITORUSERLANGUAGE] && ISTRINGS[EDITORUSERLANGUAGE][key] ) 
	{
		str = ISTRINGS[EDITORUSERLANGUAGE][key];
	}
	else if ( ISTRINGS['en'][key] )
	{
		str = ISTRINGS['en'][key];
	}
	else
	{
		str = key;
	}

	return str;
}

// cross-platform document height determination
// Credit: alistapart.com
function getWindowHeight()
{
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
        } else {
                if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                } else {
                        if (document.body && document.body.clientHeight) {
                                windowHeight = document.body.clientHeight;
                        }
                }
        }
        return( windowHeight );
}

function getWindowWidth()
{
	try{
		return window.innerWidth ? window.innerWidth : document.body.offsetWidth;
	}catch(e){}
}

function show_hint(id, content)
{
	var hlp_el = document.getElementById('help_hint_wnd');
	setHelpContent(content);
	hlp_el.style.display = "block";
}

function setHelpContent(content)
{
	var hlp_el = document.getElementById('help_hint_wnd');
	hlp_el.innerHTML = translate(content);
}
function hide_hint(id)
{
	var hlp_el = document.getElementById('help_hint_wnd');
	hlp_el.style.display = "none";
	//document.documentElement.removeChild(hlp_el);
}

function move_hint(event,id)
{
	if (!event) {event=window.event};
	var wind_width = document.getElementById('help_hint_wnd').clientWidth;
	var wind_height = document.getElementById('help_hint_wnd').clientHeight;
	if ( ie )
	{
		var pageX = event.clientX + document.body.scrollLeft;
		var pageY = event.clientY + document.body.scrollTop;
	}
	else
	{
		var pageX = event.pageX;
		var pageY = event.pageY;
	}
	var top =  parseInt(pageY) + 15;
	var left = parseInt(pageX)+15;

	if ((left + wind_width) > getWindowWidth()) 
	{
		left = pageX - wind_width;
		top = top + 20;
	}
	if ((top + wind_height) > getWindowHeight()) 
	{
		top = pageY - 20 - wind_height;
	}
	document.getElementById('help_hint_wnd').style.left = left + 'px';
	document.getElementById('help_hint_wnd').style.top= top +'px';
}

function getEl(el)
{
	var elObj = document.getElementById(el);
	if (!elObj)
		elObj = null;
	return elObj;

}

function flashElement(docRef)
{
//alert(getCssStyle(docRef,'border'));
//getCssStyle(docRef,'border');
//getCssStyle(docRef,'border-bottom-style');


	var borderBottomStyle = getCssStyle(docRef,'border-bottom-style');
	var borderBottomColor = getCssStyle(docRef,'border-bottom-color');
	var borderBottomWidth = getCssStyle(docRef,'border-bottom-width');
	var borders = new Array(borderBottomStyle, borderBottomColor, borderBottomWidth);
/*
var borderLeftStyle = getCssStyle(docRef,'border-left-style');
var borderLeftColor = getCssStyle(docRef,'border-left-color');
var borderLeftWidth = getCssStyle(docRef,'border-left-width');


var borderTopStyle = getCssStyle(docRef,'border-top-style');
var borderTopColor = getCssStyle(docRef,'border-top-color');
var borderTopWidth = getCssStyle(docRef,'border-top-width');


var borderRightStyle = getCssStyle(docRef,'border-right-style');
var borderRightColor = getCssStyle(docRef,'border-right-color');
var borderRightWidth = getCssStyle(docRef,'border-right-width');

  */




	setTimeout( function() { setStyle(docRef,'border','2px dotted #0289E1'); }, 100 );
	setTimeout( function() { setStyle(docRef,'border','none'); }, 250 );
	setTimeout( function() { setStyle(docRef,'border','2px dotted #04B9FF'); }, 350 );
//	setTimeout( function() { setStyle(docRef,'border','none'); }, 500 );
	setTimeout( function() { clearFlashBorders(docRef, borders); }, 450 );
//	setTimeout( function() { clearFlashBorders(docRef); }, 451 );




}

function clearFlashBorders(docRef, borders)
{

	setStyle(docRef,'border','');
///	setStyle(docRef,'border-top','');
//	setStyle(docRef,'border-right','');
//	setStyle(docRef,'border-bottom','');
//	setStyle(docRef,'border-left','');

	docRef.style.borderTopStyle = '';
	docRef.style.borderTopWidth = '';
	docRef.style.borderTopColor = '';

	docRef.style.borderLeftStyle = '';
	docRef.style.borderLeftWidth = '';
	docRef.style.borderLeftColor = '';

	docRef.style.borderBottomStyle = '';
	docRef.style.borderBottomWidth = '';
	docRef.style.borderBottomColor = '';

	docRef.style.borderRightStyle = '';
	docRef.style.borderRightWidth = '';
	docRef.style.borderRightColor = '';

	docRef.style.borderStyle = borders[0];
	docRef.style.borderWidth = borders[2];
	docRef.style.borderColor = borders[1];


}
function print_r( array, return_val ) {    // Prints human-readable information about a variable
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://crestidg.com)
 
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString(); // They didn't pass in an array.... why? -- Do the best we can to output this object.
        };
 
        return str;
    };
 
    var repeat_char = function (len, char) {
        var str = "";
        for(var i=0; i < len; i++) { str += char; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char);
 /*
    if(return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
*/
alert(output);
}

function getCssStyle(oElm, strCssRule){
    var cs = window.getComputedStyle(oElm, "");
    // Получим значение свойства color для ссылки с помощью метода getPropertyValue
//    alert(cs.getPropertyValue(strCssRule));
 return cs.getPropertyValue(strCssRule);

/*
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
*/
}

// add getComputedStyle
if (!window.getComputedStyle) {
    window.getComputedStyle = function(el, pseudo) {
        this.el = el;
        this.getPropertyValue = function(prop) {
            var re = /(\-([a-z]){1})/g;
            if (prop == 'float') prop = 'styleFloat';
            if (re.test(prop)) {
                prop = prop.replace(re, function () {
                    return arguments[2].toUpperCase();
                });
            }
            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
        }
        return this;
    }
}
