function log_console(str) {
	console.log(str)
}

function ClearMsg(msgobj, time, callback) {
	var time = (time  || 3) * 1000;
	if (msgobj.timoeout != undefined) { window.clearTimeout(msgobj.timoeout); }
	msgobj.timeout = window.setTimeout(function () { msgobj.html(""); if (typeof callback == 'function') {callback();}}, time);
}

function PrintPDFURL(url) {
	var d = $("#helper-pdf-loader");
	if (d.length == 0) { d = $("<div style='display: none;' id='helper-pdf-loader'>"); }
	d.appendTo("body").html("<iframe src='"+url+"' />");
}

function CloseWindow() {
	window.opener.window.location.reload();
	window.close();
}

function jqd(uri) {
	jqueryDownloadFile(uri);
}

function jqueryDownloadFile(uri) {
	var iframe = $('#jqueryDownloadFakeIFrame');
	if (iframe.length == 0) {iframe = $('<iframe id="jqueryDownloadFakeIFrame" style="display:none">'); } 
	iframe.appendTo('body').attr('src', uri);
	return false;
}

function OverPop(Url, id, width, height) {
    var wh = width || '900';
    var ht = height || '678';
    var d = $("#" + id);
    if (d.length == 0 && id == undefined) {d = $("<div>"); }
    if (d.length == 0 && id != undefined) {d = $("<div id='"+id+"'>"); }
    d.html('<iframe border="0" src="'+Url+'" style="border:none; width: '+wh+'px; height: '+ht+'px;">')
    	.dialog($.extend({}, dialogdefault, {
    		closeOnEscape : false,
    		width : "auto",
    		close : function () { 
    			d.dialog("destroy").remove(); 
			}
    	}))
    	.dialog("open");
}

function popup(URL, id, width, height) {
    var wh = width || '900';
    var ht = height || '678';
    day = new Date();
    if (id == null) {
        id = day.getTime();
    }
    return window.open(URL, id, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width='+wh+',height='+ht);
}

function timer(time, target, type, format) {
    if (typeof (target) == "undefined") {
        return;
    }
    if (typeof(type) == "undefined") {
        type = 0;
    }
    if (typeof(timer.timers) == "undefined") {
        timer.timers = [];
    }

    if (type == 0) {
        document.getElementById(target).innerHTML = dateFormat(time * 1000, format);
        timer.timers[target] = {
            obj : window.setInterval(tickDown, 1000, time, target),
            iterator : -1,
            dateformat : format
        };
    } else {
        timer.timers[target] = {
            obj : window.setInterval(tickUp, 1000, time, target),
            iterator : -1,
            dateformat : format
        };
    }
    timer.counter++;
    
}

function tickDown(time, target) {
    if (timer.timers[target].iterator == -1) {
        timer.timers[target].iterator = time;
    }

    timer.timers[target].iterator--;
    document.getElementById(target).innerHTML = dateFormat(timer.timers[target].iterator * 1000, timer.timers[target].dateformat);
    if (timer.timers[target].iterator == 0) {
        window.clearInterval(timer.timers[target].obj);
    }
}

function tickUp (time, target) {
    if (timer.timers[target].iterator == time) {
        timer.timers[target].iterator = 0;
    }

    timer.timers[target].iterator++;
    document.getElementById(target).innerHTML = dateFormat(timer.timers[target].iterator * 1000, timer.timers[target].dateformat);
    if (timer.timers[target].iterator == time) {
        window.clearInterval(timer.timers[target].obj);
    }
}

function dateFormat(time, format) {
    if (typeof(format) == "undefined") {
        format = "´YY-´MM-´DD ´hh:´mm:´ss";
    }
    var date = new Date(time);
    var datestring = format;
    datestring = datestring.replace(/´ss/, (date.getSeconds().length > 1 ? date.getSeconds() : "0"+date.getSeconds().toString()));
    datestring = datestring.replace(/´s/, date.getSeconds());
    datestring = datestring.replace(/´mm/, (date.getMinutes().length > 1 ? date.getMinutes() : "0"+date.getMinutes().toString()));
    datestring = datestring.replace(/´m/, date.getMinutes());
    datestring = datestring.replace(/´hh/, (date.getHours().length > 1 ? date.getHours() : "0"+date.getHours().toString()));
    datestring = datestring.replace(/´h/, date.getHours());
    datestring = datestring.replace(/´DD/, (date.getDate().length > 1 ? date.getDate() : "0"+date.getDate().toString()));
    datestring = datestring.replace(/´D/, date.getDate());
    datestring = datestring.replace(/´MM/, (date.getMonth().length > 1 ? (date.getMonth() + 1) : "0"+(date.getMonth()+1).toString()));
    datestring = datestring.replace(/´M/, (date.getMonth().length > 1 ? date.getMonth() + 1 : "0"+(date.getMonth() + 1).toString()));
    datestring = datestring.replace(/´YY/, date.getFullYear());
    return datestring.replace(/´Y/, (date.getYear() <0 ? date.getYear() * -1 : date.getYear()).toString().substring(1));
}

function Set_Cookie( names, value, expires)
{
	var name = ("HUMANPORTAL_" + names).toUpperCase();
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ";path=/";
}

//this fixes an issue with the old method, ambiguous values
//with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name, def) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var check_name = ("HUMANPORTAL_" + check_name).toUpperCase();
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return def;
	}
}
	
//this deletes the cookie when called
function Delete_Cookie( name) {
	var name = "HUMANPORTAL_" + name;
	if ( Get_Cookie( name ) ) document.cookie = name + "=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array
    //
    // version: 1009.2513
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;}
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {return true;
            }
        }
    }
     return false;
}

function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonphp nneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

String.prototype.padLeft = function(n, pad)
{
	t = '';
	if(n>this.length){
		for(i=0;i < n-this.length;i++){
			t+=pad;
		}
	}
	return t+this;
};

String.prototype.padRight = function(n, pad)
{
	t = this;
	if(n>this.length){
		for(i=0;i < n-this.length;i++){
			t+=pad;
		}
	}
	return t;
};

String.prototype.capitalize = function(all){
    if (all)
        return this.replace( /(^|\s)([a-z])([^\s]{2,})/g , function(m,p1,p2,p3){ return p1+p2.toUpperCase()+p3; } );
    else 
        return this.substring(0, 1).toUpperCase() + this.substring(1);
};

Object.isDate = function(obj) {
	/// <summary>
	/// Determines if the passed object is an instance of Date.
	/// </summary>
	/// <param name="obj">The object to test.</param>

    return Object.prototype.toString.call(obj) === '[object Date]';
};

Object.isValidDate = function(obj) {
	/// <summary>
	/// Determines if the passed object is a Date object, containing an actual date.
	/// </summary>
	/// <param name="obj">The object to test.</param>

    return Object.isDate(obj) && !isNaN(obj.getTime());
};

/*
 *
 * usage colorToHex('rgb(255,255,255)');
 */
function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

function isAN (key) {
    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
       return true;
    } else if ((("0123456789").indexOf(keychar) > -1)) {
       return true;
    }
    else if ((keychar == ".")) {
      return true;
    }
    else
       return false;
}


function __(str) {
	var str = str.split(".");
	var sub = str[0];
	var toTest;
	for (var i = 1 ; i < str.length; i++) {
		sub += "." + str[i];
		eval("toTest = " + sub + ";");
		if ( typeof toTest == 'undefined') {
			return sub.split(".").pop();
		}
	}
	return toTest;
}

