
if (typeof( console ) == 'undefined') {
	console = { log: function( str ) { $('#debugDiv').append( "<pre>" + str + "</pre>" ); },
				clear: function(  ) { $('#debugDiv').html( "" ); } };
}

jQuery.log = function(message) {
	if(window.console) {
		console.log(message);
	} else {
		alert(message);
	}
};
jQuery.fn.debug = function() {
	return this.each(function(){
		jQuery.log(this);
	});
};
jQuery.get_sync = function( url, data, callback ) {
    options = {
        async: false,
        cache: false,
        success: callback,
        data: data,
        url: url,
        dataType: 'json',
        type: 'GET'
    }
    $.ajax( options );
}
jQuery.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

jQuery.fn.extend({
	check: function() {
		try {
    	if ($(this).hasClass('nice_checkbox')) {
          	var id = $(this).attr('id' ).substr( 0, $(this).attr('id' ).length - 2 );

          	$(this).removeClass( 'nice_checkbox_checked' );
          	$(this).removeClass( 'nice_checkbox_unchecked' );

            $('#' + id ).check();
        	$(this).addClass( 'nice_checkbox_checked' );
            //$(this).attr( 'checked', true );
    		$('#' + id ).change();
        }
			$(this).attr('checked', 'checked' );
		} catch (er) {}
	},
	uncheck: function() {
		try {
    	if ($(this).hasClass('nice_checkbox')) {
          	var id = $(this).attr('id' ).substr( 0, $(this).attr('id' ).length - 2 );

          	$(this).removeClass( 'nice_checkbox_checked' );
          	$(this).removeClass( 'nice_checkbox_unchecked' );

    		$('#' + id ).uncheck();
        	$(this).addClass( 'nice_checkbox_unchecked' );
            //$(this).attr( 'checked', true );
    		$('#' + id ).change();
        }
			$(this).attr('checked', false );
		} catch (er) {}
	},
	toggleCheck: function() {
		try {
			isCh = (typeof( $(this).attr('checked') ) == 'string') ?
						$(this).attr('checked') != 'false' :
						$(this).attr('checked');
			//$(this).attr('checked', isCh ? 'checked' : false );
        if (isCh) {
        	$(this).uncheck();
        } else {
        	$(this).check();
        }
		} catch (er) {}
	},
	isChecked: function() {
		try {
			return (typeof( $(this).attr('checked') ) == 'string') ?
			$(this).attr('checked') != 'false' :
			$(this).attr('checked');
		} catch (er) {}
	},
	enable: function() {
		try {
			$(this).attr('disabled', false );
			$(this).removeClass('_disabled' );
        if ($(this).hasClass('overridden')) {
        	var _id = '#_' + $(this).attr('id') + '_';
            $(_id).attr('disabled', false );
            $(_id).removeClass('_disabled' );
        }
		} catch (er) {}
	},
	disable: function() {
		try {
			$(this).attr('disabled', 'disabled' );
			$(this).addClass('disabled_' );

	        if ($(this).hasClass('overridden')) {
	        	var _id = '#_' + $(this).attr('id') + '_';
	            $(_id).attr('disabled', 'disabled');
	            $(_id).addClass('disabled_');
	        }
	        if ($(this).hasClass('niceWrapped')) {
	        	$(this).parent('.selectWrap').addClass( 'disabled_' );
	        }
		} catch (er) {}
	},
	isEnabled: function() {
		try {
			return $(this).attr('disabled') == false;
		} catch (er) {}
		try {
			return !$(this).hasClass('disabled_');
		} catch (er) {}
		return true;
	},
	isDisabled: function() {
		try {
			return $(this).attr('disabled') == 'disabled';
		} catch (er) {}
		try {
			return $(this).hasClass('disabled_');
		} catch (er) {}
		return false;
	},
	disabled: function( v ) {
		try {
			if (typeof v == 'undefined') {
				return $(this).attr('disabled') == 'disabled';
			} else {
				if (v) {
					$(this).addClass('disabled_');
	                if ($(this).hasClass('overridden')) {
	                	var _id = '#_' + $(this).attr('id') + '_';
	                    $(_id).attr('disabled', 'disabled' );
	                    $(_id).addClass('disabled_');
	                }
			        if ($(this).hasClass('niceWrapped')) {
			        	$(this).parent('.selectWrap').addClass( 'disabled_' );
			        }
				} else {
					$(this).removeClass('disabled_' );
	                if ($(this).hasClass('overridden')) {
	                	var _id = '#_' + $(this).attr('id') + '_';
	                    $(_id).attr('disabled', false );
	                    $(_id).removeClass('disabled_' );
	                }
			        if ($(this).hasClass('niceWrapped')) {
			        	$(this).parent('.selectWrap').removeClass( 'disabled_' );
			        }
				}
				return $(this).attr('disabled', ( v ? 'disabled': false ) );
			}
		} catch (er) {}
	}
});

function makeMachineReadable( str )
{
	alias = str.replace( / /g, '' );
	alias = alias.replace( /Ã¥/g, 'a' ).replace( /Ã¤/g, 'a' ).replace( /[Ã¶]/g, 'o' );
	alias = alias.replace( /Ã…/g, 'A' ).replace( /Ã„/g, 'A' ).replace( /[Ã–]/g, 'O' );

	return alias;
}

function treatJSON( str )
{
	try {
		var obj = null;
		eval( 'obj = ' + str );
		return obj;
	} catch (Err) {
		jQuery.log( Err );
		return null;
	}
}

$(document).ready( function() {
	$('.contractor').css ( {
		border:			'1px solid #000',
		background:		'#fff',
		display:		'block',
		float:			'left',
		padding:		'0px',
		textAlign:		'center',
		lineHeight:		'9px',
		fontSize:		'9px',
		height:			'9px',
		width:			'9px',
		cursor:			'pointer'
	} ).click( function() {
		if ($(this).html() == '+') { $(this).html('-'); }
		else { $(this).html('+'); }
		$(this).next().toggle();
	} );
	$('.contractor').click();

	$('.nice_checkbox_').addClass( 'nice_checkbox' ); // Aktivera då JavaScript är ok...
	$('.nice_checkbox').each( function() {
		var id = $(this).attr('id' ).substr( 0, $(this).attr('id' ).length - 2 );

		if( $('#' + id ).attr('checked') ) {
			$(this).addClass( 'nice_checkbox_checked' );
		    $(this).attr( 'checked', true );
		} else {
			$(this).addClass( 'nice_checkbox_unchecked' );
		    $(this).attr( 'checked', false );
		}

		$('#' + id).css( 'display', 'none' );
	} );

	$('.nice_checkbox').live( 'click', function() {
		var id = $(this).attr('id' ).substr( 0, $(this).attr('id' ).length - 2 );

		if( $('#' + id ).isChecked() ) {
			$(this).uncheck();
		} else {
			$(this).check();
		}
	} );


	$('#sysMsgBox').hide();
	if ($.trim( $('#sysMsgBox span').html() ) != '') {
		setMessage( $('#sysMsgBox').html() );
	}
	$('body').bind('ajaxError', function(event, request, settings) {
		setMessage( 'Fel vid laddningen av ' + settings.url + '!', 'error', false, 3000  );
	});
} );

function setMessage( msg, msgType, doStay, timeOut )
{
	if (typeof(msgType) == 'undefined') {
    	msgType = 'notice';
    }
	if (typeof(doStay) == 'undefined') {
    	doStay = false;
    }
	if (typeof(timeOut) == 'undefined') {
    	if (msgType == 'notice') {
				timeOut = 2000;
        } else {
				timeOut = 5000;
        }
    }
    alert( msg )
/*
    jQuery.noticeAdd({
        text:		msg,
        stay:		doStay,
        stayTime:	timeOut,
        type:		msgType
    });*/
}

function loadIntoFancy( data )
{
    $('#fancy_ajax').css( 'position', 'absolute' );
    $('<div />').attr('id', 'fancy_ajax_')
    	.css( { width: '100%', height: '100%', overflow: 'auto', 'overflow-x': 'hidden',
    			position: 'absolute', top: '0px', left: $('#fancy_outer').css('width') } )
        .html( data )
        .insertAfter( '#fancy_ajax' );
    $('#fancy_ajax').animate( {
    	left: '-' + $('#fancy_outer').css('width')
    }, 'normal', 'linear', function() {
    	$('#fancy_ajax').remove();
    } );
    $('#fancy_ajax_').animate( {
    	left: '0px'
    }, 'slow', 'linear', function() {
        if (typeof( $('#fancy_ajax').attr('id') ) != 'undefined' ) {
        	$('#fancy_ajax').remove();
        }
        $('#fancy_ajax_').attr('id', 'fancy_ajax');
        if (typeof( addEffects ) == 'function') {
    			addEffects( '#fancy_ajax' );
        }
    } );
}

$.fn.ajaxSubmit = function(e, callback, validate_callback) {
	/* Change a form's submission type to ajax */
	this.submit(function(){
	    try {
	        if ( typeof( validate_callback ) == 'function' ) {
	            if ( ! validate_callback( this ) ) {
	                return false;
				}
			}
			var params = {};
			$(this)
			.find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea")
			.filter(":isEnabled")
			.each(function() {
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
			});
			$("body").addClass("curWait");

			$.postJSON(this.getAttribute("action") + "?ajax", params, callback);
		} catch (e) {
            alert (e);
		}
		return false;
	});

	return this;
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 = {
	// public method for url encoding
	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;
	},

	// public method for url decoding
	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;
	}
}

var kLib = {
	substr: function( str, start, len ) {
	    if ( ( typeof(len) == 'number' ) && ( len < 0 ) ) {
	        len = str.length + len;
		}
	    return str.substr( start, len );
	},
	cut: function( str, max_length, append ) {
		if ( typeof( append ) == 'undefined' ) { append = '...'; }
		if ( (str.length - append.length) > max_length ) {
			return str.substr( 0, max_length ) + append;
		} else {
			return str;
		}
	},
	padZero: function( value, num ) {
		if ( typeof( num ) == 'undefined' ) { num = 2; }
		value = '' + value + '';

		if ( value.length < num ) {
			for( i=value.length; i < num; i++ ) {
				value = '0' + value;
			}
		}

		return value;
	},
	get_id: function( value, by_first, by_last ) {
	    if ( typeof(by_first) == 'undefined' )	{ by_first	= false; }
	    if ( typeof(by_last) == 'undefined' )	{ by_last	= false; }
	    if ( typeof( value ) == 'object' ) {
		    try {
		        value = value.attr('id');
			} catch( e ) { console.log( 'E:' + e ); }
		}

		if ( by_first ) {
		    return value.substr( value.indexOf( '_' ) + 1 ); // If there's more than one underscore
		} else if ( by_last ) {
		    return value.substr( 0, value.lastIndexOf( '_' ) ); // If there's more than one underscore
		} else {
			return value.split('_')[1];
		}
	}
}

function fancy_close( )
{
	$('#fancy_close').click();
	return false;
}

function markErroredField( id )
{
	$('#' + id + ',#' + id + '_lbl').addClass('hasError');
}
function clearErroredFields( )
{
	$('.hasError').removeClass('hasError');
}

function yesNoDialog( str )
{
/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)

	str = str.replace( "\n", chr(10)+chr(13) );
    execScript('n = msgbox("'+str+'","4132")', "vbscript");
    return(n == 6);

@end @*/

	str = str + "\n(Ok = Ja, Avbryt/Cancel = Nej)";
	return confirm( str );
}

