try{console}catch(e){console = new Object();}
console.info = console.info || function(data){alert(data);}
function popitup(url, name, params) {
    name = typeof(name) != 'undefined' ? name : 'name';
    defParams = {'height':600,'width':700,scrollbars:'yes', 'center':'yes'};
    paramsA = {}; paramsO = '';
    if(typeof(params) == 'string'){
    	param = params.split(',');
    	for(kayP in param){
    		para = param[kayP].split('=');
    		paramsA[para[0]] = para[1];
    	}
    }
    if(typeof(params) == 'object'){
    	paramsA = params;
    }
    for(key in defParams){
    	if(typeof(paramsA[key]) == 'undefined')
    		paramsA[key] = defParams[key];
    }
    if(paramsA.center =='yes'){
    	paramsA.left = (window.screen.width - parseInt(paramsA.width,10)) / 2;
    	paramsA.top = (window.screen.height - parseInt(paramsA.height,10)) / 2;
    }
    for(param in paramsA)
    	paramsO += param +'='+paramsA[param] + ',';

    newwindow=window.open(url, name, paramsO);
    if (window.focus) {newwindow.focus();}
    return false;
}

function go_saveas() {
    if (!!window.ActiveXObject) {
        document.execCommand("SaveAs");
    } else if (!!window.netscape) {
        var r=document.createRange();
        r.setStartBefore(document.getElementsByTagName("head")[0]);
        var oscript=r.createContextualFragment('<script id="scriptid" type="application/x-javascript" src="chrome://content/global/contentAreaUtils.js"><\/script>');
        document.body.appendChild(oscript);
        r=null;
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            saveDocument(document);
        } catch (e) {
            //no further notice as user explicitly denied the privilege
        } finally {
            var oscript=document.getElementById("scriptid");    //re-defined
            oscript.parentNode.removeChild(oscript);
        }
    }
}

function sprintf()
{
    if (!arguments || arguments.length < 1 || !RegExp)
    {
        return;
    }
    var str = arguments[0];
    var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
    var a = b = [], numSubstitutions = 0, numMatches = 0;
    while (a = re.exec(str))
    {
        var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
        var pPrecision = a[5], pType = a[6], rightPart = a[7];

        //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

        numMatches++;
        if (pType == '%')
        {
            subst = '%';
        }
        else
        {
            numSubstitutions++;
            if (numSubstitutions >= arguments.length)
            {
                alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
            }
            var param = arguments[numSubstitutions];
            var pad = '';
                   if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
              else if (pPad) pad = pPad;
            var justifyRight = true;
                   if (pJustify && pJustify === "-") justifyRight = false;
            var minLength = -1;
                if (pMinLength) minLength = parseInt(pMinLength);
            var precision = -1;
                if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
            var subst = param;
                if (pType == 'b') subst = parseInt(param).toString(2);
            else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
            else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
            else if (pType == 'u') subst = Math.abs(param);
            else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
            else if (pType == 'o') subst = parseInt(param).toString(8);
            else if (pType == 's') subst = param;
            else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
            else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
        }
        str = leftpart + subst + rightPart;
    }
    return str;
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

        // private property
        _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        // public method for encoding
        encode : function (input) {
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;

                input = Base64._utf8_encode(input);

                while (i < input.length) {

                        chr1 = input.charCodeAt(i++);
                        chr2 = input.charCodeAt(i++);
                        chr3 = input.charCodeAt(i++);

                        enc1 = chr1 >> 2;
                        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                        enc4 = chr3 & 63;

                        if (isNaN(chr2)) {
                                enc3 = enc4 = 64;
                        } else if (isNaN(chr3)) {
                                enc4 = 64;
                        }

                        output = output +
                        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

                }

                return output;
        },

        // public method for decoding
        decode : function (input) {
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;

                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

                while (i < input.length) {

                        enc1 = this._keyStr.indexOf(input.charAt(i++));
                        enc2 = this._keyStr.indexOf(input.charAt(i++));
                        enc3 = this._keyStr.indexOf(input.charAt(i++));
                        enc4 = this._keyStr.indexOf(input.charAt(i++));

                        chr1 = (enc1 << 2) | (enc2 >> 4);
                        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                        chr3 = ((enc3 & 3) << 6) | enc4;

                        output = output + String.fromCharCode(chr1);

                        if (enc3 != 64) {
                                output = output + String.fromCharCode(chr2);
                        }
                        if (enc4 != 64) {
                                output = output + String.fromCharCode(chr3);
                        }

                }

                output = Base64._utf8_decode(output);

                return output;

        },

        // private method for UTF-8 encoding
        _utf8_encode : 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;
        },

        // private method for UTF-8 decoding
        _utf8_decode : 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;
        }

}

function autoFill(id, v){
	$(id).attr({ value: v }).focus(function(){
		if($(this).val()==v){
			$(this).val("");
		}
	}).blur(function(){
		if($(this).val()==""){
			$(this).val(v);
		}
	});

}

function switchTextFocus()
{
	if ($(this).val() == $(this).attr('title'))
		$(this).val('');
}
function switchTextBlur()
{
	if ($.trim($(this).val()) == '')
		$(this).val($(this).attr('title')).fadeIn(1000);
}

$(function(){
    $('input[type=text][title!=""]').each(function() {
    	if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
    }).focus(switchTextFocus).blur(switchTextBlur);

    $('input[type=password][title!=""]').each(function() {
    	if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
    }).focus(switchTextFocus).blur(switchTextBlur);

    $('textarea[title!=""]').each(function() {
    	if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
    }).focus(switchTextFocus).blur(switchTextBlur);

    $('form').submit(function() {
    	$(this).find('input[type=text][title!=""]').each(function() {
    		if ($(this).val() == $(this).attr('title') && $(this).attr('clean')!='no') $(this).val('');
    	});
    	$(this).find('textarea[title!=""]').each(function() {
    		if ($(this).val() == $(this).attr('title') && $(this).attr('clean')!='no') $(this).val('');
    	});
    });
});

function getFileExtension(filename)
{
    filename = filename.toLowerCase();
    if( filename.length == 0 ) return "";
    var dot = filename.lastIndexOf(".");
    if( dot == -1 ) return "";
    var extension = filename.substr(dot+1,filename.length);
    return extension;
}

function Sleep(naptime){
    naptime = naptime * 1000;
    var sleeping = true;
    var now = new Date();
    var alarm;
    var startingMSeconds = now.getTime();
    while(sleeping){
        alarm = new Date();
        alarmMSeconds = alarm.getTime();
        if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
    }
}

(function($) {
	$.fn.extend({
		insertAtCaret: function(myValue){
		  this.each(function(i) {
		    if (document.selection) {
		      this.focus();
		      sel = document.selection.createRange();
		      sel.text = myValue;
		      this.focus();
		    }
		    else if (this.selectionStart || this.selectionStart == '0') {
		      var startPos = this.selectionStart;
		      var endPos = this.selectionEnd;
		      var scrollTop = this.scrollTop;
		      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
		      this.focus();
		      this.selectionStart = startPos + myValue.length;
		      this.selectionEnd = startPos + myValue.length;
		      this.scrollTop = scrollTop;
		    } else {
		      this.value += myValue;
		      this.focus();
		    }
		  })
		}
	});
})(jQuery);

