var confirming = false;
var ATYPE = false;
var IE = document.all?true:false
var error_displayed = false;
var mnotice_done = false;
var dhtmlgoodies_tooltip = false;
var dhtmlgoodies_tooltipShadow = false;
var dhtmlgoodies_shadowSize = 4;
var dhtmlgoodies_tooltipMaxWidth = 200;
var dhtmlgoodies_tooltipMinWidth = 300;
var dhtmlgoodies_iframe = false;
var tooltip_is_msie = (navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('opera')==-1 && document.all)?true:false;
var timer1;
var last_prompt = false;
var dep_check_throttler = new Array();
var uploadStatus = new Array();
var form_submitted = false;
var done_autoplay = false;
var next_onclick = false;
var next_onmouseover = false;
var next_imgsrc = false;
var abn_error = false;
var state_html = '';
var submit_done = false;
var i_answers = new Array();
var mobile_field_required = true;
var last_d_val = '';
var last_d_alert = false;
var just_dragged = false;
var ilimit = 100;
var icnt = 0;
var last_c_edit = 0;

function show_sound_iframe(src) {
    if(typeof($('#mod_iframe').attr('id')) == 'undefined') {
        var html = "<iframe id=\"mod_iframe\" src=\"\" style=\"display: none; border: 0px; position: absolute; width: 50px; height: 50px; top: 10px; left: -100px;\"></iframe>";
         $('body').html($('body').html() + html);
    }

    if($('#mod_iframe').attr('src') == src) { return; }
    $('#mod_iframe').attr('src', src);
    $('#mod_iframe').css('display', 'inline');
}

function clear_sound_iframe() {
    if(typeof($('#mod_iframe').attr('id')) == 'undefined') {
        return;
    }
    
    $('#mod_iframe').attr('src', '');
    $('#mod_iframe').css('display', 'none');    
}

function hide_sys_msg(sys_id) {
    if(confirm('Are you sure you don\'nt want to see this message again?')) {
        $.post('#', {hide_msg: sys_id}, function(data) { reload_page(); });
    }
}
function redeem_code_value(cid) {
     var nname = $('#new_s_name').val();

     if(nname == '') {
         alert('You need to enter a Site Access Card Token continue');
         $('#new_s_name').focus();
         return;
     }
    
    $.post('#', {redeem_code: 1, code_id: nname}, function(data) { 
        if(data.match('^OK$')) {
            reload_page(); 
        } else {
            alert('Unable to redeem Site Access Card Token');
        }
    })
}

function redeem_code(sid, obj) {
     $('#s_renamer').css('position', 'absolute');
     $('#s_renamer').css('width', '300px');
     $('#s_renamer').css('height', '30px');
     $('#s_renamer').show('fast');

     var nlef = $(obj).position().left;
     var ntop = $(obj).position().top;

     $('#s_renamer').css('top', ntop + 15);
     $('#s_renamer').css('left', nlef + 15);

     var html = '<center><b class="txt_EIB">Enter Token Code:</b> '
                +'<input class="text2" style="width: 150px;" id="new_s_name" value="" /> '
                +'<img src="/files/images/add.png" align="top" class="fakelink" title="Redeem Token" onclick="redeem_code_value('+sid+')" />'
                +'<img src="/files/images/no.png" align="top" class="fakelink" title="Cancel" onclick="hide_renamer();" />'
                +'</center>';
     $('#s_renamer').html(html);
     $('#new_s_name').focus();    
}

function e_assign_card(mid) {
    if(confirm('Are you sure you wish to assign an access card to this user?')) {
        $.post('#', {assign_card: 1, nrec_id: mid}, function(data) { reload_page(); })
    }    
}

 function edit_p_record(sid, obj) {
     $('#s_renamer').css('position', 'absolute');
     $('#s_renamer').css('width', '300px');
     $('#s_renamer').css('height', '30px');
     $('#s_renamer').show('fast');

     var nlef = $(obj).position().left;
     var ntop = $(obj).position().top;

     $('#s_renamer').css('top', ntop + 15);
     $('#s_renamer').css('left', nlef + 15);

     var html = '<center><b class="txt_EIB">New Number:</b> '
                +'<input class="text2" style="width: 150px;" id="new_s_name" value="" /> '
                +'<img src="/files/images/icons/save.png" align="top" class="fakelink" title="Save this number" onclick="save_new_ph('+sid+')" />'
                +'<img src="/files/images/no.png" align="top" class="fakelink" title="Cancel Rename" onclick="hide_renamer();" />'
                +'</center>';
     $('#s_renamer').html(html);
     $('#new_s_name').focus();
 }
 
function save_new_ph(sid) {
     var nname = $('#new_s_name').val();

     if(nname == '') {
         alert('You need to enter a new number to continue');
         $('#new_s_name').focus();
         return;
     }

     $.post('#', {new_ph: nname, nrec_id: sid}, function(data) {
        if(data.match('^OK$')) {
            reload_page();
        } else {
            //alert(data);
            alert('Could not save new number');
        }
     });
 } 
function hide_swipe_video() {
    $('#vplay_i').attr('src', '');
    $('#vplay_i').css('display', 'none');
    $('#vplay_i_ctl').css('display', 'none');
}
function play_swipe_video(fid) {
    var st = $(window).scrollTop();
    
    var height = $(window).height();
    var width = $(window).innerWidth();
    
    var iw = '800';
    var ih = '600';
    
    var left = (width - iw) / 2;
    var top = (height - ih) / 2;
    top += st;
        
    $('#vplay_i_ctl').css({'display': 'inline', 'position': 'absolute', 'width': iw + 'px', 'height': '20px', 'position': 'absolute', 'top': (top - 20) + 'px', 'left': left + 'px'});
    $('#vplay_i').css({'display': 'inline', 'position': 'absolute', 'width': iw + 'px', 'height': ih + 'px', 'position': 'absolute', 'top': top + 'px', 'left': left + 'px'});
    $('#vplay_i').attr('src', '/videos/' + fid + '/svid/');
}

function print_site_report() {
    var vars = {snav: 'reports', rtype: 'printsite'};
    load_supervisor_content(vars, 'report_content');
}

function view_site_report() {
    var vars = {snav: 'reports', rtype: 'viewsite'};
    load_supervisor_content(vars, 'report_content');
}

function view_swipe_log() {
    var vars = {snav: 'reports', rtype: 'swipelog'};
    load_supervisor_content(vars, 'report_content');    
}

function supervisor_home() {
    var vars = {snav: 'home'};
    load_supervisor_content(vars);    
}

function load_supervisor_reports() {
    var vars = {snav: 'reports'};    
    load_supervisor_content(vars);    
}

function load_supervisor_visitor() {
    var vars = {snav: 'visitor'};    
    load_supervisor_content(vars);
}

function submit_visitor_add() {
    var fn = $('#name_first');
    var sn = $('#name_surname');
    var co = $('#company');
    var mo = $('#mobile');
    
    var vars = {firstname: fn.val(), surname: sn.val(), company: co.val(), mobile: mo.val(), add_visitor: true, snav: 'visitor'};
    load_supervisor_content(vars);
}

function show_user_info(uid) {
    last_vars.show_user = uid;
    resend_last_supervisor_request();
}

function page_change(offset) {
    last_vars.n_offset = offset;
    resend_last_supervisor_request();
}

function resend_last_supervisor_request() {
    load_supervisor_content(last_vars, last_target);
}

function load_supervisor_content(vars, target_id) {
    vars.ajax = 1;
    vars.ws_call = 1;
    
    if(typeof(target_id) == 'undefined') { target_id = 'web_content_div'; }

    $.post('#', vars, function(data) {
        if(data.match('ERR:')) {
            alert(data.replace('ERR:', ''));
            reload_page();
            return;
        }
      
       if(data != '') {
           $('#' + target_id).html(data);
           last_vars = vars;
           last_target = target_id;
       }
    });     
}

 function save_new_s_name(sid) {
     var nname = $('#new_s_name').val();

     if(nname == '') {
         alert('You need to enter a new name to continue');
         $('#new_s_name').focus();
         return;
     }

     $.post('#', {new_name: nname, sound_id: sid}, function(data) {
        if(data.match('^OK$')) {
            reload_content_edit();
        } else {
            alert('Could not save new name');
        }
     });
 }

 function hide_renamer() {
     $('#s_renamer').hide('fast');
 }
 
 function s_s_rename_clip(sid, obj) {
     $('#s_renamer').css('position', 'absolute');
     $('#s_renamer').css('width', '300px');
     $('#s_renamer').css('height', '30px');
     $('#s_renamer').show('fast');

     var nlef = $(obj).position().left;
     var ntop = $(obj).position().top;

     $('#s_renamer').css('top', ntop + 15);
     $('#s_renamer').css('left', nlef + 15);

     var html = '<center><b class="txt_EIB">New Name:</b> '
                +'<input class="text2" style="width: 150px;" id="new_s_name" value="" /> '
                +'<img src="/files/images/icons/save.png" align="top" class="fakelink" title="Save this name" onclick="save_new_s_name('+sid+')" />'
                +'<img src="/files/images/no.png" align="top" class="fakelink" title="Cancel Rename" onclick="hide_renamer();" />'
                +'</center>';
     $('#s_renamer').html(html);
     $('#new_s_name').focus();
 }
 
function toggle_voiceover(nval, sound_id) {
    $.post('#', {sound_id: sound_id, voiceover: 1, new_val: nval}, function(data) {
            reload_content_edit();
    });
} 
function toggle_require_listen(nval, sound_id, has_voice) {
    if(has_voice == '1') {
        alert('These options are not available for voiceover tracks');
        return;
    }
    $.post('#', {sound_id: sound_id, require_listen: 1, new_val: nval}, function(data) {
            reload_content_edit();
    });
}

function toggle_autoplay(nval, sound_id, has_voice) {
    if(has_voice == '1') {
        alert('These options are not available for voiceover tracks');
        return;
    }
    $.post('#', {sound_id: sound_id, autoplay: 1, new_val: nval}, function(data) {
            reload_content_edit();
    });
}

function toggle_allow_dl(nval, sound_id, has_voice) {
    if(has_voice == '1') {
        alert('These options are not available for voiceover tracks');
        return;
    }
    $.post('#', {sound_id: sound_id, allow_download: 1, new_val: nval}, function(data) {
            reload_content_edit();
    });
}

function toggle_hide_snd(nval, sound_id, has_voice) {
    if(has_voice == '1') {
        alert('These options are not available for voiceover tracks');
        return;
    }
    $.post('#', {sound_id: sound_id, hide_sound: 1, new_val: nval}, function(data) {
            reload_content_edit();
    });
}

function delete_sound(snum, sound_id) {
    if(!confirm('Are you sure you wish to delete Clip ' + snum + '?\n\nThis action *CANNOT BE UNDONE*.\nPress OK to DELETE.')) { return; }
    $.post('#', {delete_sound: sound_id}, function(data) {
        reload_content_edit();
    });
}
 
function update_chart_ajax(cid, rid) {
    var fchart = getChartFromId(cid);
    $.post('/reports/fcajax/', {chart_id: cid, report_id: rid}, function(data) {
        fchart.setDataXML(data);
    })
   setTimeout('update_chart_ajax("'+cid+'", "'+rid+'");', 30000);
}

function load_web_content() {
    if(icnt++ > ilimit) { reload_page(); }
    
    $.post('#', {s_content: 1}, function(data) {
       if(data != '') {
           $('#web_content_div').html(data);
           if(!data.match('uad-flag')) {
                setTimeout('reload_page();', 5000);               
           }
       } else {
           $('#web_content_div').html(default_text);
           setTimeout('load_web_content();', 500);
       }
    });    
}

function insight_set_usertype(uid, utype) {
	if(confirm('Are you sure you would like to change this users status to: ' + utype + '?')) {
		$.post('/insight/', {n_utype: utype, user: uid});
	}
}

function togglesstatus(sid, hstr) {
    if(hstr == '') { return; }
    if(confirm('Set this object to ' + hstr + '?')) {
        $.post('#', {ssid: sid}, function() { reload_page(); });
    }
}

function tasub() {
    $.post('#', {crsite: $('#crhost').val()}, function() { reload_page(); });
}

function tavis() {
    var s = $('#crlink').css('display');
    if(s == '' || s == 'inline') {
        $('#crlink').hide('fast');
        $('#crtext').show('fast');
    }
}

function confsel(iid, obj) {
	var val = $(obj).val();
	var str = '#' + obj.id + " option[value='"+val+"']";
	var s = $(str).text();
	
	if(confirm('Are you sure you want to link this host to ' + s + '?')) {
		$.post('#', {link_s: $(obj).val(), pid: iid}, function() { reload_page(); });
	}
}

function save_new_email() {
    var sj = $('#em_subject').val();
    var sm = $('#em_message').val();
    
    if(sj == '' || sm == '' || !sj || !sm) {
        alert('You must fill in both the Subject and Message fields to save');
        return;
    }
    
    $.post('#', {save_email: 1, subject: sj, message: sm}, function() {
        window.location.href=window.location.href.replace('/create', '');
    });
}

function secondsToHms(d) {
	d = Number(d);
	var h = Math.floor(d / 3600);
	var m = Math.floor(d % 3600 / 60);
	var s = Math.floor(d % 3600 % 60);
	return ((h > 0 ? h + "h " : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + "m " : "0:") + (s < 10 ? "0" : "") + s + "s");
}	

function r_confirm_code_request() {
	$.post('/verify_token/', {sendcode: 1}, function(data) {
		if(data.match('FAIL')) {
			alert('Unable to send secure code.');
		} else {
			reload_page();
		}
	});
}

function confirm_code_request() {
	disp_dialog('You are about to request a secure code', 'Please ensure that you have your mobile phone with you as the code will expire after 5 minutes.',
			    new Array(new Array('Request Code', 'r_confirm_code_request()'), new Array('Cancel', 'hide_m_dialog()'))
			   );
}

function save_new_mobile() {
	$.post('/ajax/',
        	{new_mobile:$('#new_mobile').val()},
        	 function(data) {
       			if(!data.match('#ff0000')) {
           			$('#current_mobile').html($('#new_mobile').val());
           			setTimeout('hide_m_dialog();', 500);
       			}
           	 	$('#update_result').html(data);
           	 }
           );
}

function disp_dialog(error_title, error_msg, buttons, focuson) {
	if(error_displayed) { return; }
	
	if(typeof(buttons) == 'undefined') {
		buttons = '<button onclick="javascript:hide_m_dialog();">Close</button>';
	} else {
		var btn_out = '';
		for (var btn in buttons) {
			btn_out = btn_out + '<button onclick="'+buttons[btn][1]+'">' + buttons[btn][0] + '</button>';
		}
		buttons = btn_out;
	}
	$('#dialog_b').css('display', 'inline');
	
	$('#dialog_buttons').html(buttons);
	$('#dialog_text').html(error_msg);
	$('#dialog_title').html(error_title);
	resize_d_dialog();
	error_displayed = true;
	if(typeof(focuson) != 'undefined') {
		$('#' + focuson).focus();
	}

	window.onscroll=move_d_dialog;
	window.onresize=resize_d_dialog;
}

function move_d_dialog() {
	clearTimeout(timer1);
	timer1 = setTimeout('r_move_d_dialog();', 50);
}

function r_move_d_dialog() {
	var st = $(window).scrollTop();
	resize_d_dialog();
	var ntop = 0 + st;
	$("#dialog_b").animate({ 
        top: ntop + 'px'}, 50 );
}

function hide_m_dialog() {
	setTimeout('error_displayed = false;', 500);
	$('#dialog_b').fadeOut('slow');	
}


function resize_d_dialog() {
	var height = $(window).height();
	var width = $(window).width();
	if($(window).scrollTop() > 0) {
		width -= 15;
	}
	var dh = $('#dialog_table').height();
	var dhtop = (height - dh) / 3;
	$('#dialog_table').css('margin-top', dhtop + 'px');
	
	$('#dialog_b').css('height', height + 'px');
	$('#dialog_b').css('width', width + 'px');	
}

function collapse_box(id) {
	$('#' + id + '_hide').hide('fast');	
	$('#' + id + '_show').show('fast');
}

function expand_box(id) {
	$('#' + id + '_show').hide('fast');
	$('#' + id + '_hide').show('fast');
}

function edit_content_item(cid, bool) {
	if(just_dragged) { return; }

	var st = $(window).scrollTop();
	
	var height = $(window).height();
	var width = $(window).innerWidth();
	
	var iw = $('#ceditor').width();
	var ih = $('#ceditor').height();
	
	var left = (width - iw) / 2;
	var top = (height - ih) / 2;
	top += st;

	$('#shadow_overlay').css('left', '0px');
	$('#shadow_overlay').css('top', st + 'px');
	$('#shadow_overlay').css('width', (width-15)+'px');
	$('#shadow_overlay').css('height', height+'px');
	$('#shadow_overlay').show('fast');
	
	$('#ceditor').css('top', top+'px');
	$('#ceditor').css('left', left+'px');
	$('#ceditor').show('fast');
	
	if(bool) { return; }
	
	window.onscroll=function() {
		clearTimeout(timer1);
		timer1 = setTimeout("edit_content_item('"+cid+"', 1);", 100);
	}
	
    last_c_edit = cid;	
	$.post('#', {ecid: cid}, function(data) {
		$('#ceditor').html(data);
	});
}

function reload_content_edit() {
    if(last_c_edit == 0) { return; }
    edit_content_item(last_c_edit);
}

function validate_date(obj) {
	if(obj.value == '') { return; }
	if(obj.value != last_d_val) { last_d_alert = false; }
	
	if(!obj.value.match('^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$')) {
		if(!last_d_alert) {
			alert('The date you have entered is invalid. Format must be dd/mm/yyyy');
			last_d_val = obj.value;
			last_d_alert = true;
			$(obj).focus();
		}
		return;
	}
}

function toggle_ind_status(obj, iid, status) {
    if(status == 'Live') {
        var msg = 'Are you sure you wish to disable this induction?';
    } else {
        var msg = 'Are you sure you wish to enable this induction?';
    }
    
    if(confirm(msg)) {
        $.post('#', {toggle_status: iid}, function(data) {
            if(data != '') {
                $(obj).html(data);
            }
        });
    }
}
function expand_i_row(iid) {
    $( "tr[ id ^= 'tr_']" ).each(function() {
        $(this).css('display', 'none');
    });
    var v1 = $('#tr_' + iid + '_1');
    var v2 = $('#tr_' + iid + '_2');
    
    if(v1.css('display') == 'table-row') {
        v1.css('display', 'none');
        v2.css('display', 'none');
    } else {
        v1.css('display', '');
        v2.css('display', '');
    }
}

function toggle_help_pin(obj) {
	var act = '';
	if(obj.src.match('pin-out')) {
		obj.src = obj.src.replace('-out', '-in');
		act = 'in';
	} else {
		obj.src = obj.src.replace('-in', '-out');
		act = 'out';
	}
	
	$.post('/help/', {nact: act});
}

function open_report_window(uri) {
    window.open(uri, "pu", "menubar=no,toolbar=no,width=1024,height=768,location=no,scrollbars=yes");
}

function edit_h_content() {
    $('#show_mce_btn').hide('fast');
    $('#help_c_content').hide('fast');
    $('#mce_editor_div').show('fast', function() { 
        //init_mce();
    });
}

function save_h_content() {
    $.post('/help/save/', {hcontent: tinyMCE.get('help_editor1').getContent(), hiid: $('#help_item_id').val(), h_uri: window.location.href}, function(data) {
        $.post('/help/', {h_uri: window.location.href}, function(data) { $('#help_panel').html(data); }); 
    });
}

function init_mce() {
    tinyMCE.idCounter = 0;
    tinyMCE.execCommand('mceAddControl', true, 'help_editor1');
    //tinyMCE.addMCEControl($('#help_editor1'),  'help_editor1');
}

function display_help_panel(right) {
	resize_help_panel(right);
		$.post('/help/', {h_uri: window.location.href}, function(data) {
			$('#help_panel').show('normal', function() {
			$('#help_panel').html(data);
			resize_help_panel(right);
		});
	});
	window.onscroll=move_help_panel;
	window.onresize=resize_help_panel;
}

function resize_help_panel(right) {
	if(typeof(right) == 'undefined') {
		right = false;
	}

	var pH = $(window).height() - 2;
	var pw = $(window).width();
	var nwid = (pw - 800) / 2;

	//if(right) {
	//	var pL = pw - nwid - 23;
		//$('#help_panel').addClass('ui-corner-left');
	//} else {
		//$('#help_panel').addClass('ui-corner-right');
		var pL = 0;
	//}
	var st = $(window).scrollTop();
	var ntop = 0 + st;
	if(nwid < 179) { nwid = 179; }
	$('#help_panel').css({left: pL +'px', top: ntop + 'px', height: pH, width: nwid + 'px'});
	$('#overbox').css('height', (pH-110));
	var rwid = $('#help_panel').width();
	if(rwid < nwid) { nwid = rwid; }
	//alert(rwid + ' / ' + nwid);
	$('#tbl_help_content').css({height: (pH-100) + 'px', width: nwid + 'px'});
}

function move_help_panel() {
	clearTimeout(timer1);
	timer1 = setTimeout('r_move_help_panel();', 300);
}

function r_move_help_panel() {
	var st = $(window).scrollTop();
	var ntop = 0 + st;
	$("#help_panel").animate({ 
        top: ntop + 'px'}, 100 );
}
function hide_help_panel() {
	window.onscroll='';
    tinyMCE.execCommand('mceRemoveControl', true, 'help_editor1');
	$('#help_panel').hide('normal');
    $('#help_panel').html('');
}

function show_r_row(id, bool) {
	var attr;

	if(bool) {
		attr = 'table-row';
		if(IE) {
			attr = '';
		}
	} else {
		attr = 'none';
	}

	$('#tr_qid_' + id).css('display', attr);
}

function ped_site_alert(bool) {
    if(bool == '1') {
        alert('** IMPORTANT NOTICE **\n\nYou need to print this document, complete it and take it with you to the work site');
    } else {
        alert('** IMPORTANT NOTICE **\n\nYou cannot download this document until you have been assigned a PED number and completed an induction');
    }
}

function certify_bgcheck_signed(doc_id) {
    if(!confirm('** IMPORTANT NOTICE **\n\nBy clicking OK you agree that the document you have uploaded is a true and accurate copy and has been signed by yourself')) {
        return;
    }
    
    $.post('/documents/', {doc_certify: doc_id}, function(data) {
        reload_page();
    });
}

function certify_ped_signed(document_id) {
	if(!confirm('** IMPORTANT NOTICE **\n\nBy clicking OK you agree that the document you have uploaded is a true and accurate copy and has been signed by yourself')) {
		return;
	}
	
	$.post('/documents/', {ped_certify: 1, doc_id: document_id}, function(data) {
		reload_page();
	});
}

function expand_report_div(report_id) {
    
    $('.rdiv').each(function() {
        if($(this).attr('id') == 'rdiv_' + report_id) { return; }
        $(this).html('');
        $(this).hide('fast');
    })
    
    if($('#rdiv_' + report_id).is(':visible')) {
        $('#rdiv_' + report_id).html();
        $('#rdiv_' + report_id).hide('fast');
    } else {
        $('#rdiv_' + report_id).html('<img align="left" src="/files/images/loading.gif" />');
        $('#rdiv_' + report_id).show('fast');
    }

    $.post('/reports/', {l_report: report_id}, function(data) {
        $('#rdiv_' + report_id).html(data);
    })    
}

function verify_document(docid) {
	if(confirm('** IMPORTANT NOTICE **\n\nBy clicking OK you agree that the document you have uploaded is a true and accurate copy of your original document')) {
		$.post('/100_pts/', {agree: docid}, function(data) {
			reload_page();
		});
		
	}
}

function submit_i_answer() {
    if(i_answers.length < 1) {
        alert('You must select your answer before clicking submit');
        return;
    }
    
    var s_answers = '';
    if(i_answers.length > 1) {
        for(var x = 0; x < i_answers.length; x++) {
            s_answers += i_answers[x] + ':';
        }
    } else {
        s_answers = i_answers[0];
    }
    play_sound('stopall');
    done_autoplay = false;
    for(var x = 1;x < sounds.length; x++) {
    	sounds[x].destruct();
    }
    clip_finished = new Array();
        
    $.post('#', {s_astring: s_answers, ajax: 1}, function(data) {
        i_answers = new Array();
        if(data.match('^REDIR:')) {
            data = data.replace('REDIR:', '');
            window.location.href=data;
            return;
        }
        $('#ind_content').html(data);
    });
}

function remove_answer(val) {
    var na = new Array();
    for(var x = 0; x < i_answers.length; x++) {
        if(i_answers[x] != val) {
            na.push(i_answers[x]);
        }
    }
    
    if(na.length > 0) {
        i_answers = na;
    } else {
        i_answers = new Array();
    }
}

function set_q_hover(qid, bool, qz, qo) {
	var icon = $('#icon_' + qid);
	
	if(bool) {
		if(icon.attr('src').match('_blank.' + qo)) {
			icon.attr('src', '/files/images/icons/chk_'+qz+'_over.' + qo);
		}
	} else {
		if(icon.attr('src').match('_over.' + qo)) {
			icon.attr('src', '/files/images/icons/chk_'+qz+'_blank.' + qo);
		}
	}
}

function set_q_select(qid, bool, qz, qo) {

    if(sound_action_var) { return; }
    
    var is_single = bool;
    
    if(is_single) {
        // single type question
        $('.icon_search').each(function(obj) {
            if(!$(this).attr('id').match(qid)) {
                remove_answer(qid);
                $(this).attr('src', '/files/images/icons/chk_'+qz+'_blank.' + qo);
            }
        });
        
        $('.q_search').each(function() {
        	$(this).css('font-weight', 'normal');
        });
    }
    var icon = $('#icon_' + qid);
    var text = $('#q_' + qid);
    
    if(icon.attr('src').match('_selected.' + qo)) {
        icon.attr('src', '/files/images/icons/chk_'+qz+'_blank.' + qo);
    	text.css('font-weight', 'normal');
        remove_answer(qid);
    } else {
        icon.attr('src', '/files/images/icons/chk_'+qz+'_selected.' + qo);
    	text.css('font-weight', 'bold');
        if(is_single) {
            i_answers = new Array();
        }
        i_answers.push(qid);
    }
}

function induction_nav(dir) {
    i_answers = new Array();
    play_sound('stopall');
    done_autoplay = false;
    has_playlist = '';
    for(var x = 1;x < sounds.length; x++) {
    	sounds[x].destruct();
    }
    clear_sound_iframe();
    clip_finished = new Array();
	$.post('/induction/', {set_nav: dir, ajax: 1}, function(data) {
		$('#ind_content').html(data);
	});
}

function iextra_questions(ewhich, bool, qid) {
	var val = '';
    if(bool) {
        val = $('#' + ewhich).val();//document.getElementById(ewhich);
    } else {
        val = ewhich;
    }

    if(window.location.href.match('/welcome/')) {
    	var jext = 'yes';
    } else {
    	var jext = 'no';
    }
    
    $.post('/induction_start/', {question_id: qid, answer: val, just_exit: jext}, function(data) {
    	reload_page();
    });
}

function show_overlay(data) {
	var height = $(window).height();
	var width = $(window).width();
	var iw = Math.floor(width * .80);
	var ih = Math.floor(height * .80);

	var left = (width - 740) / 2;
	var top = (height - 500) / 2;

	$(window).resize(function() { resize_overlay(); });
	resize_overlay();

	$('#overlay_content').css('height', '300px');
	$('#overlay_content').css('width', '740px');
	$('#overlay_content').css('left', left + 'px');
	$('#overlay_content').css('top', top + 'px');
	$('#overlay_content').html(data);
	$('#overlay_content').show('fast');

}

function resize_overlay() {
	var height = $(window).height();
	var width = $(window).width();

	$('#shadow_overlay').css('width', width + 'px');
	$('#shadow_overlay').css('height', height+'px');
	$('#shadow_overlay').css('left', '0px');
	$('#shadow_overlay').css('top', '0px');
	$('#shadow_overlay').show('fast');
}

function update_client_settings() {
	var a1 = $('#c_iword').val();
	var a2 = $('#c_iretry').val();
	var a3 = $('#c_courses').attr('checked');
	var a4 = $('#c_onetoken').attr('checked');
	var a5 = $('#c_onescode').attr('checked');
	var a6 = $('#c_noscode').attr('checked');
    var a7 = $('#c_ignoretoken').attr('checked');
	
	$.post('#', {ucsett: 1, av1: a1, av2: a2, av3: a3, av4: a4, av5: a5, av6: a6, av7: a7}, function(data) {
		reload_page();
	});
}
function check_c_country() {
	var sh = $('#state_html').html();

	if(state_html == '') {
		state_html = sh;
	}
	
	if($('#c_country').val() != 'Australia') {
		$('#state_html').html('<input autocomplete="off" class="text2" name="c_state" id="c_state" size="40" onchange="$(this).removeClass(&#39;error&#39;);" />');
        if($('#c_country').val() == 'Singapore') {
            $('#c_pcode').attr('maxlength', 6);
        } else {
            $('#c_pcode').attr('maxlength', 4);
        }
	} else {
		$('#state_html').html(state_html);
        $('#c_pcode').attr('maxlength', 4);
	}
}

function check_country() {
	var sh = $('#state_html').html();

	if(state_html == '') {
		state_html = sh;
	}
	
	if($('#r_country').val() != 'Australia') {
		$('#state_html').html('<input autocomplete="off" class="text2" name="r_state" id="r_state" size="40" onchange="$(this).removeClass(&#39;error&#39;);" />');
        if($('#r_country').val() == 'Singapore') {
            $('#r_pcode').attr('maxlength', 6);
        } else {
            $('#r_pcode').attr('maxlength', 4);
        }
	} else {
		$('#state_html').html(state_html);
        $('#r_pcode').attr('maxlength', 4);
	}
}

function hide_pl_iframe() {
	$('#iframe_ctl').hide('fast');
	$('#mod_iframe').attr('src','');
	$('#mod_iframe').hide('fast');
	$('#shadow_overlay').hide('fast');
}

function position_pl_iframe() {
	var height = $(window).height();
	var width = $(window).width();
	var iw = Math.floor(width * .80);
	var ih = Math.floor(height * .80);
	$('#mod_iframe').css('height', ih + 'px');
	$('#mod_iframe').css('width', iw + 'px');

	var left = (width - iw) / 2;
	var top = (height - ih) / 2;
	$('#mod_iframe').css('left', left + 'px');
	$('#mod_iframe').css('top', top + 'px');

	$('#shadow_overlay').css('left', '0px');
	$('#shadow_overlay').css('top', '0px');
	$('#shadow_overlay').css('width', width+'px');
	$('#shadow_overlay').css('height', height+'px');

	$('#iframe_ctl').css('top', (top-19)+'px');
	$('#iframe_ctl').css('left', (iw - 50)+'px');
}

function show_spl_iframe(src, bool) {
	if(typeof(bool) == 'undefined') {
		src = '/nuance_sales/' + src + '/';
	} 
	$('#shadow_overlay').css('display', 'inline');
	$('#iframe_ctl').css('display', 'inline');
	$('#mod_iframe').attr('src', src);
	$('#mod_iframe').css('display', 'inline');

	position_pl_iframe();
}
function show_pl_iframe(src) {
	src = '/nuance_videos/' + src + '/';
	$('#shadow_overlay').css('display', 'inline');
	$('#iframe_ctl').css('display', 'inline');
	$('#mod_iframe').attr('src', src);
	$('#mod_iframe').css('display', 'inline');

	position_pl_iframe();
}

function save_new_invite(uitype) {
	var fname = $('#user_firstname');
	var sname = $('#user_surname');
	var email = $('#user_email');
	var cmail = $('#user_emailconfirm');
	var company = $('#user_company');
	var udate = $('#user_date');
	
    var uf1 = $('#gold_ef1');
    var uf2 = $('#gold_ef2');
    var uf3 = $('#gold_ef3');
    var uf4 = $('#gold_ef4');
    var uf5 = $('#gold_ef5');
    
	company.removeClass('error');
	fname.removeClass('error');
	sname.removeClass('error');
	email.removeClass('error');
	cmail.removeClass('error');
	udate.removeClass('error');
    
    try {
       uf1.removeClass('error'); 
       uf2.removeClass('error'); 
       uf3.removeClass('error'); 
       uf4.removeClass('error'); 
       uf5.removeClass('error'); 
    } catch (e) {}

	var rf = new Array();
	if(company.val() == '') {
		company.addClass('error');
		rf.push('Company');
	}
	
	if(fname.val() == '') {
		fname.addClass('error');
		rf.push('First name');
	}
	if(sname.val() == '') {
		sname.addClass('error');
		rf.push('Surname');
	}
	if(email.val() == '') {
		email.addClass('error');
		rf.push('Email');
	}
	if(cmail.val() == '') {
		cmail.addClass('error');
		rf.push('Email Confirmation');
	}
	if(udate.val() == '') {
		udate.addClass('error');
		rf.push('Completion Date');
	}
	
    try {
        if(uf1.val() == '') { uf1.addClass('error'); rf.push('Level 1 - Lower Figure'); }    
        if(uf2.val() == '') { uf2.addClass('error'); rf.push('Level 1 - Upper Figure'); }    
        if(uf3.val() == '') { uf3.addClass('error'); rf.push('Level 2 - Lower Figure'); }    
        if(uf4.val() == '') { uf4.addClass('error'); rf.push('Level 2 - Upper Figure'); }    
        if(uf5.val() == '') { uf5.addClass('error'); rf.push('Level 3 - Lower Figure'); }    
    } catch (e) {}
    
	if(rf.length > 0) {
		alert('The following required fields are missing: ' + rf);
		return;
	}
	
	if(cmail.val() != email.val()) {
		cmail.addClass('error');
		email.addClass('error');
		alert('Email fields are different, please double check them');
		return;
	}
	
	if(!validateEmail(cmail.val())) {
		alert(cmail.val() + " doesn't appear to be a valid email address");
		return;
	}
	var ued = '';
    
    try {
        ued = 'ef1=' + uf1.val() + '::ef2=' +  uf2.val() + '::ef3=' + uf3.val() + '::ef4=' + uf4.val() + '::ef5=' + uf5.val(); 
    } catch (e) {   
    }
	$.post('/manage/invites/', {utype: uitype, cn: company.val(), fn: fname.val(), sn: sname.val(), em: email.val(), ud: udate.val(), edata: ued}, function(data) {
		if(data.match('^OK$')) {
			reload_page();
		} else {
			alert('There was a problem sending the invitation (' + data + ')');
		}
	});
}

function confirm_mreq_change(obj) {
	var nval = $(obj).val();
	var mid = $(obj).attr('id');

	if(confirm('Are you sure you wish to change this modules prerequisite?')) {
		$.post('#', {sel_id: mid, new_val: nval}, function() {
			reload_page();
		});
	}
}

function mark_a_complete() {
    $.post('/induction/', {mark_completed: true}, function(data) {
        window.location.href=data;
    });
}

function mark_i_complete(iid) {
	$.post('/users/induction.php', {mark_completed: iid}, function(data) {
		window.location.href='/welcome/';
	});
}

function save_creq_edit(cid) {
	var nreq = $('#ncreq').val();
	if(nreq == '0') { return; }
	$.post('/clients/course-manager/', {save_req: true, new_rid: nreq, course_id: cid}, function(data) {
		reload_page();
	});
}

function hide_creq_edit() {
	$('#creq_edit2').hide('fast');
	$('#creq_edit').show('fast');
}

function edit_course_req() {
	$('#creq_edit').hide('fast');
	$('#creq_edit2').show('fast');
}

function save_course_edit(cid) {
	if($('#new_cname').val() == '') {
		hide_course_edit();
		return;
	}

	var nname = $('#new_cname').val();
	$.post('/clients/course-manager/', {save_course: true, new_name: nname, course_id: cid}, function(data) {
		reload_page();
	});
}

function hide_course_edit() {
	$('#cname_edit2').hide('fast');
	$('#cname_edit').show('fast');
}

function edit_course_name() {
	$('#cname_edit').hide('fast');
	$('#cname_edit2').show('fast');
}

function validate_company_registration_form() {
	if(submit_done) {
		return false;
	}
	
	var errors = new Array();
	var rf = new Array();

	$('.error').each(function(ff) {
		if($(this).attr('id').match('^c_')) {
			$(this).removeClass('error');
		}
	});


	if($('#c_company_name').val() == '') {
		rf.push('Company Name');
		$('#c_company_name').addClass('error');
	}

	if($('#c_abn').val() == '' || abn_error) {
		rf.push('Company ABN');
		$('#c_abn').addClass('error');
	}

	if($('#c_sub_abn').val() == '') {
		rf.push('Contractor\'s ABN');
		$('#c_sub_abn').addClass('error');
	}

	if($('#c_num_employees').val() == '') {
		rf.push('No. of Employees');
		$('#c_num_employees').addClass('error');
	}

	if($('#c_address1').val() == '') {
		rf.push('Address 1');
		$('#c_address1').addClass('error');
	}

	if($('#c_suburb').val() == '') {
		rf.push('Suburb');
		$('#c_suburb').addClass('error');
	}

	if($('#c_country').val() == '') {
		rf.push('Country');
		$('#c_country').addClass('error');
	}

	if($('#c_state').val() == '') {
		rf.push('State');
		$('#c_state').addClass('error');
	}

	if($('#c_pcode').val() == '') {
		rf.push('Postcode');
		$('#c_pcode').addClass('error');
	}

	if($('#c_phone').val() == '') {
		rf.push('Phone Number');
		$('#c_phone').addClass('error');
	}

	if(rf.length > 0) {
		var rfs = '';
		for (var i in rf) {
			rfs += rf[i];
			if(i < (rf.length - 1)) { rfs += ', '; }
		}
		errors.push('The following required fields are missing or contain errors: ' + rfs);
	}

	if(errors.length > 0) {
		var out = '<img src="/files/images/no.png" onclick="$(\'#error_box\').hide(\'fast\');" style="float:right; padding-right: 3px; padding-top: 3px; cursor: pointer;" title="Hide this error message" />';
		for (var str in errors) {
			out += '<b class="error">*</b> ' + errors[str] + ' <b class="error">*</b><br />';
		}

		out += '<hr />To continue with your registration, please correct the above errors and try again';
		$('#error_box').html(out);
		$('#error_box').show();
	} else {
		if(!submit_done) {
			submit_done = true;
			$('#registration_form').submit();
		}
	}

}

function err_hilite(obj) {
	$(obj).addClass('error');
}

function show_account_app() {
	if(IE) {
		$('.disp_act_cls').each(function() {
			$(this).css('display', 'block');
		});
	} else {
		$('#disp_acct').css('display', 'table-row');
	}
}

var is_valid_username = false;

function validate_registration_form() {
	$('#r_button_s').css('display', 'none');
	$('#r_button_p').css('display', 'inline');
			
	var errors = new Array();
	var rf = new Array();

	$('.error').each(function(ff) {
		if($(this).attr('id').match('^r_') || $(this).attr('id').match('^eq_')) {
			$(this).removeClass('error');
		}
	});

	if($('#r_salutation').val() == '') {
		rf.push('Salutation');
		$('#r_salutation').addClass('error');
	}

	if($('#r_fname').val() == '' || trim($('#r_fname').val()).length < 2) {
		rf.push('First name');
		$('#r_fname').addClass('error');
	}

	if($('#r_sname').val() == '' || trim($('#r_sname').val()).length < 2) {
		rf.push('Surname');
		$('#r_sname').addClass('error');
	}

	if($('#r_abn').val() == '' || abn_error) {
		rf.push('Employers ABN');
		$('#r_abn').addClass('error');
	}

	if($('#r_address1').val() == '') {
		rf.push('Address');
		$('#r_address1').addClass('error');
	}

	if($('#r_suburb').val() == '') {
		rf.push('Suburb');
		$('#r_suburb').addClass('error');
	}

	if($('#r_state').val() == '') {
		rf.push('State');
		$('#r_state').addClass('error');
	}

    if($('#r_country').val() == 'Singapore') {
        if($('#r_pcode').val() == '' || repspace($('#r_pcode').val()).length != 6) {
            rf.push('Postcode');
            $('#r_pcode').addClass('error');
        }
    } else {
	    if($('#r_pcode').val() == '' || repspace($('#r_pcode').val()).length != 4) {
		    rf.push('Postcode');
		    $('#r_pcode').addClass('error');
	    }
    }

	if($('#r_country').val() == '') {
		rf.push('Country');
		$('#r_country').addClass('error');
	}

    if(mobile_field_required) {
	    if(window.location.href.match('nuance')) {
            if($('#r_mobile').val() == '' || repspace($('#r_mobile').val()).length < 6) {
                    rf.push('Mobile phone');
                    $('#r_mobile').addClass('error');
            }
	    } else {
	    if($('#r_mobile').val() == '' || repspace($('#r_mobile').val()).length != 10) {
		    rf.push('Mobile phone');
		    $('#r_mobile').addClass('error');
	    }
	    }
    }
	var is_aussie = true;
	if($('#r_country').val() != 'Australia' && $('#r_country').val() != '') {
		is_aussie = false;
	}
	if($('#r_mobile').val().substr(0,2) != '04') {
		is_aussie = false;
	}
	if(window.location.href.match('nuance')) {
	if(!is_aussie) {
		if($('#r_mobile').val().substr(0,1) != '+' && $('#r_mobile').val() != '') {
			alert('Please ensure that your mobile number is prefixed with a country code. i.e. +64 21 1111');
			$('#r_mobile').focus();
		}
	}
	}

	if($('#r_username').val() == '' || trim($('#r_username').val()).length < 6 || $('#r_username').val().match(' ')) {
		rf.push('Username');
		$('#r_username').addClass('error');
	}

	if($('#r_username1').val() == '') {
		rf.push('Username confirmation');
		$('#r_username1').addClass('error');
	}

	if($('#r_password').val() == '' || trim($('#r_password').val()).length < 4) {
		rf.push('Password');
		$('#r_password').addClass('error');
	}

	if($('#r_password1').val() == '') {
		rf.push('Password confirmation');
		$('#r_password1').addClass('error');
	}

	done_push = false;
	$('.required').each(function() {
		if (!$(this).is(':hidden') ) {
			if($(this).val() == '') {
				if(!done_push) {
					rf.push('Additional Questions');
					done_push = true;
				}
				$(this).addClass('error');
			}
		} 
	});

	//if($('#r_agreeterms').val() == '' || $('#r_agreeterms').val() == 'No') {
	if(!$('#r_agreeterms').attr('checked')) {
		errors.push('<b class="error">You must agree to the terms and conditions</b>');
		$('#r_agreeterms').addClass('error');
	}


	if(rf.length > 0) {
		var rfs = '';
		for (var i in rf) {
			rfs += rf[i];
			if(i < (rf.length - 1)) { rfs += ', '; }
		}
		errors.push('The following required fields are missing or contain errors: ' + rfs);
	}

	//errors = new Array();
	if(errors.length > 0) {
		var out = '<img src="/files/images/no.png" onclick="$(\'#error_box\').hide(\'fast\');" style="float:right; padding-right: 3px; padding-top: 3px; cursor: pointer;" title="Hide this error message" />';
		for (var str in errors) {
			out += '<b class="error">*</b> ' + errors[str] + ' <b class="error">*</b><br />';
		}

		out += '<hr />To continue with your registration, please correct the above errors and try again';
		$('#error_box').html(out);
		$('#error_box').show();
		$('#r_button_s').css('display', 'inline');
		$('#r_button_p').css('display', 'none');		
	} else {
        if(!is_valid_username) {
            validate_username();
            $('#r_button_s').css('display', 'inline');
            $('#r_button_p').css('display', 'none');
            return;
        }
		if(typeof(email_warning) == 'function' && $('#r_email').val() == '') {
			if(!email_warning()) {
				$('#r_email').focus();
				$('#r_button_s').css('display', 'inline');
				$('#r_button_p').css('display', 'none');		
				return false;
			}
		}

		if(!submit_done) {
			submit_done = true;
			$('#registration_form').submit();
		}
		return false;
	}
	return false;
}

function ask_username(obj) {
	var em = obj.value;
	if(em == '') { return; }

	if(confirm('Would you like to use your email address as your username?')) {
		$('#r_username').val(em);
	}
}

function validate_password() {
	var p1 = $('#r_password').val();
	var p2 = $('#r_password1').val();

	if(p1 == '' || p2 == '') { return; }

	if(p1 == '' || p1 != p2) {
		$('#r_password').addClass('error');
		$('#r_password1').addClass('error');
	} else {
		$('#r_password').removeClass('error');
		$('#r_password1').removeClass('error');
	}
}

function validate_username() {
	is_valid_username = false;
	
	var nuser = $('#r_username').val();
	if(nuser == '') { return false; }
	if(nuser.length < 6 || nuser.match(' ')) {
		alert('Username must be 6 characters or longer and not contain spaces');
		$('#r_username').addClass('error');
		return false;
	}

	if(validate_username1() && nuser != '') {
		$.post('/ajax/', {username: nuser}, function(data) {
			if(data == 'true') {
				$('#r_username').removeClass('error');
				is_valid_username = true;
				return true;
			} else {
				$('#r_username').addClass('error');
				$('#r_username').focus().select();
				alert('The username you have chosen already exists. Please select another (your email address makes a good username)');
				return false;
			}
		});
	}
	return false;
}

function validate_username1() {
	var un1 = $('#r_username1').val();
	var un2 = $('#r_username').val();

	if(un1 == '' || un2 == '') { return true; }

	if(un1 != un2) {
		alert('Both usernames must be the same')
		$('#r_username').addClass('error');
		$('#r_username1').addClass('error');
		return false;
	} else {
		$('#r_username').removeClass('error');
		$('#r_username1').removeClass('error');
		return true;
	}
}

function repspace(val) {
	while(val.match(' ')) {
		val = val.replace(' ', '');
	}
	while(val.match('-')) {
		val = val.replace('-', '');
	}
	return val;
}

function validate_mobile(obj) {
		var mobilev = obj.value;
		if(mobilev == '') { return; }
		mobilev = repspace(mobilev);

		var cval = $('#r_country').val();
		var check_country = false;
		
		if(cval != '' && cval != 'Australia') {
			check_country = true;
		}
		
		if(window.location.href.match('nuance')) {
			if(check_country) {
				if(mobilev.substr(0,1) != '+' && mobilev != '') {
					alert('Please ensure that your mobile number is prefixed with a country code. i.e. +64 21 1111');
					obj.focus();
					return;
				}
			}
			if(mobilev.length < 6) {
				$(obj).addClass('error');
				return;
			}
		} else {
			if(mobilev.substr(0,2) != '04' || mobilev.length != 10) {
				$(obj).addClass('error');
				return;
			}
		}

		$.post('/ajax/', {mobile: mobilev}, function(data) {
			if(data == 'true') {
				$(obj).removeClass('error');
				return true;
			} else {
				$(obj).addClass('error');
				$(obj).focus().select();
				alert('This Mobile phone number has already been used in the system. Every user needs a unique mobile number to complete their registration');
				return false;
			}
		});
		return true;
}

function validate_postcode(obj) {
	if($('#r_state').val() == 'NA' || $('#r_country').val() != 'Australia') {
		return;
	}
	
	var pcode = obj.value;
	if(pcode == '') { return; }

	$.post('/ajax/', {postcode: pcode}, function(data) {
		if(data == 'true') {
			$(obj).removeClass('error');
		} else {
			$(obj).addClass('error');
		}
	});
}

function validate_abn(obj, type) {
	if(obj.value == '') { return; }
	var abn_str = obj.value;

	$.post('/ajax/', {vabn: abn_str, vtype: type}, function(data) {
        if(data == "OK,0") { 
            mobile_field_required = false;
            $('#mobile_req_span').css('color', '#ffffff');
            data = "OK"; 
        }
        
		if(data.match('^throw_error')) {
			eval(data);
			if(type == 'emp') {
				$('#tbl_abn_error').hide('normal');
			} else if (type == 'man') {
				$('#tbl_cabn_error').hide('normal');
			} else if (type == 'sub') {
				$('#tbl_subabn_error').hide('normal');
			}
			abn_error = false;
			return true;
		} else if(data == "OK") {
			if(type == 'emp') {
				$('#tbl_abn_error').hide('normal');
			} else if (type == 'man') {
				$('#tbl_cabn_error').hide('normal');
			} else if (type == 'sub') {
				$('#tbl_subabn_error').hide('normal');
			}
			$(obj).removeClass('error');
			abn_error = false;            
			return true;
        }

		$(obj).addClass('error');
		abn_error = true;
		if(type == 'emp') {
			$('#tbl_abn_error').show('normal');
		} else if (type == 'man') {
			$('#tbl_cabn_error').show('normal');
		} else if (type == 'sub') {
			$('#tbl_subabn_error').show('normal');
		}
	});
}

function toggle_visibility(obj) {
	$('#' + obj).toggle('show');
}

function toggle_ishow(obj) {
	obj = document.getElementById(obj);
	
	if(obj.src.match('tab_B_list-hide_G240_760w')) {
		obj.src = '/eI_shared_images/bkg_tabs/tab_B_list-show_G240_760w_std.gif';
	} else {
		obj.src = '/eI_shared_images/bkg_tabs/tab_B_list-hide_G240_760w_std.gif';
	}
}

function toggle_istdsrc(id, bool) {
	var obj = document.getElementById(id);
	if(typeof(bool) == 'undefined') { bool = false;	}

	if(bool) {
		obj.src = obj.src.replace('_std', '_over');
	} else {
		obj.src = obj.src.replace('_over', '_std');
	}
}

function toggle_isrc(id, file, file2) {
	var obj = document.getElementById(id);
	f2m = file2.replace('_std.png', '');
	f2m = f2m.replace('_over.png', '');

	if(obj.src.match(f2m)) {
		obj.src = '/files/images/icons/' + file;
	} else {
		obj.src = '/files/images/icons/' + file2;
	}
	toggle_istdsrc(id, false);
}

function remove_ticket(ticket_id) {
	if(!confirm('Are you sure you wish to remove this ticket from the system?')) { return; }

	$.post('#', {remove_ticket: true, tid: ticket_id}, function(data) {
		reload_page();
	});
}

function g(id) { return document.getElementById(id); }

function hide_photo_notify() {
	$('#photo_prob').hide('slow');
	$.post('/welcome/', {hide_photo_notify: true}, function(data) {
	});
}

function validate_new_ticket(t_type) {
	try {
		var f1 = $('#ticket_data1');
		var f2 = $('#ticket_data2');
		var f3 = $('#ticket_data3');
		var f4 = $('#ticket_data4');
		var f5 = $('#ticket_data5');

		var f1v = f1.val();
		var f2v = f2.val();
		var f3v = f3.val();
		var f4v = f4.val();
		var f5v = f5.val();
	} catch (e) { }

	if(f1.val() == '') { return false; }
	if(t_type == 'TRADE_LICENSE') {
		if(trim(f2v) == '' || trim(f3v) == '' || trim(f5v) == '') {
			alert('Please fill in all required fields');
			return false;
		}
	} else if (t_type == 'DRIVERS_LICENSE') {
		if(trim(f2v) == '' || trim(f3v) == '' || trim(f5v) == '') {
			alert('Please fill in all required fields');
			return false;
		}
	} else if (t_type == 'DRIVERS_LICENSE_2') {
		if(trim(f1v) == '' || trim(f2v) == '' || trim(f3v) == '') {
			alert('Please fill in all required fields');
			return false;
		}
    } else if (t_type == 'DRIVERS_LICENSE_3') {
        if(trim(f1v) == '' || trim(f2v) == '' || (trim(f3v) == '' || f3v == 'Select Country')) {
            alert('Please fill in all required fields');
            return false;
        }
	} else if (t_type == 'INDUSTRY_TRAIN') {
		if(trim(f2v) == '') {
			alert('Please fill in all required fields');
			return false;
		}
	} else if (t_type == 'WORK_TICKETS') {
		if(trim(f2v) == '') {
			alert('Please fill in all required fields');
			return false;
		}
	}
	return true;
}

function update_var(tid, obj) {
	var hid = $('#' + tid);
	
	var val = hid.val();
	if(val.match(',')) {
		val = val.split(',');
	} else {
		if(val == '') { 
			val = new Array();
		} else {
			val = new Array(val);
		}
	}
	if(obj.checked) {
		val.push(obj.value);
	} else {
		var nout = new Array();
		for(var x = 0; x < val.length; x++) {
			if(val[x] == obj.value) { continue; }
			nout.push(val[x]);
		}
		val = nout;
	}
	hid.val(val);
}

function set_a_default(hid) {
    $.post('/help/', {uhid: hid}, function(data) { reload_page(); });
}

function save_new_ticket() {
	var obj = {};

	obj['ticket_type'] = $('#n_ticket_type').val();
	if(!validate_new_ticket(obj['ticket_type'])) {
		return;
	}
	obj['save_ticket'] = true;
	for(var x = 1; x < 6; x++) {
		obj['ticket_data' + x] = "@@" + $('#ticket_data'+x).val() + "@@";
	}
	$.post('#', obj, function(data) {
		reload_page();
	});
}

function toggle_ticket_row_edit(rowcount) {
	for(var x = 1; x < 6; x++) {
		$('#disp_ticket_data' + x + '_' + rowcount).hide('fast');
		$('#edit_ticket_data' + x + '_' + rowcount).css('display', 'inline');
	}
	$('#disp_bedit_' + rowcount).hide('fast');
	$('#disp_bsave_' + rowcount).css('display', 'inline');

}
function save_ticket_row_edit(rowid) {
	var obj = {ticket_data1: null, ticket_data2: null, ticket_data3: null, ticket_data4: null, ticket_data5: null, ticket_id: null, update_ticket: true};
	for(var x = 1; x < 6; x++) {
		obj['ticket_data'+x] = $('#ticket_data'+x+'_'+rowid).val();
		if(typeof(obj['ticket_data'+x]) == 'undefined') {
			obj['ticket_data'+x] = null;
		}
		$('#edit_ticket_data' + x + '_' + rowid).hide('fast');;
		$('#disp_ticket_data' + x + '_' + rowid).css('display', 'inline');
	}

	obj.ticket_id = $('#hidden_tid_' + rowid).val();
	$('#disp_bsave_' + rowid).hide('fast');
	$('#disp_bedit_' + rowid).css('display', 'inline');

	$.post('#', obj, function(data) {
		reload_page();
	});
}

function load_uri_to_div(uri, params, target_div) {
	$.post(uri, params, function(data) {
		$('#' + target_div).html(data).show('slow');
		var d = new Date();
		var start_year = d.getFullYear();
		var end_year = start_year + 10;
		var year_str = start_year + ':' + end_year;
		$('.datepicker:visible').each(function() {
			$(this).datepicker({dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: year_str});
		});
	});
}

var snd_paused = false;
var playing_sound = 0;

function xplay_sound(action, num) {
    has_playlist = '';
    play_sound(action, num);
}

function play_sound(action, num) {
	if(typeof(num) == 'undefined' && action == 'stopall') {
        for(var x = 0; x < sounds.length; x++) {
        	if(x == num) { continue; }
            if(typeof(sounds[x]) == 'undefined') { continue; }
            play_sound('stop', x);
        }
        return;
	}

    if(typeof(sounds[num]) == 'undefined') {
    	if(!sound_ready) {
    		  alert('Your sound interface was unable to be initialised at this time. This could be due to an incompatible version of flash (version 8 required)');
   		} else {
            setTimeout('play_sound("' + action + '", "' + num + '");', 500);
			return;
   	   		alert('Audio was unable to be played at this time');
   		}

        return;
    }
    var obj = sounds[num];
    var i_play = document.getElementById('img_play_' + num);
    var i_pause = document.getElementById('img_pause_' + num);

    if(action == 'play') {
        for(var x = 0; x < sounds.length; x++) {
        	if(x == num) { continue; }
            if(typeof(sounds[x]) == 'undefined') { continue; }
            play_sound('stop', x);
        }

        window.setTimeout(function() {
            soundManager.play('snd_' + num, {onfinish: function() { finish_playing(); }});
        });
        add_sound_highlights(num);

        playing_sound = num;
	try {
        	i_play.style.display = 'none';
        	i_pause.style.display = 'inline';
	} catch (e) { }
    } else if (action == 'stop') {
	try {
        obj.stop();
        i_pause.style.display = 'none';
        i_play.style.display = 'inline';
        clear_sound_highlights();
        snd_paused = false;
	} catch (e) { }
    } else if (action == 'pause') {
        clear_sound_highlights();
        snd_paused = num;
	try {
        obj.pause();
        i_pause.style.display = 'none';
        i_play.style.display = 'inline';
	} catch (e) { }
    }
    check_duration(num);
}

function add_sound_highlights(num) {
    clear_sound_highlights();
    if(default_sound_volume <= 0) { return; }
    try {
        $('#qsnd_t_' + num).attr('src', $('#qsnd_t_' + num).attr('src').replace('.gif', '_HL.gif'));
        $('#qsnd_m_' + num).attr('background', $('#qsnd_m_' + num).attr('background').replace('.gif', '_HL.gif'));
        $('#qsnd_b_' + num).attr('src', $('#qsnd_b_' + num).attr('src').replace('.gif', '_HL.gif'));
        $('#qsnd_txt_' + num).addClass('white');    
    } catch (e) {
        
    }
}
function clear_sound_highlights() {
    try {
        $('img').filter(function() { return this.id.match(/qsnd_t_/); }).each(function() { $(this).attr('src', $(this).attr('src').replace('_HL.gif', '.gif')) });
        $('table').filter(function() { return this.id.match(/qsnd_m_/); }).each(function() { $(this).attr('background', $(this).attr('background').replace('_HL.gif', '.gif')) });
        $('img').filter(function() { return this.id.match(/qsnd_b_/); }).each(function() { $(this).attr('src', $(this).attr('src').replace('_HL.gif', '.gif')) });
        $('td').filter(function() { return this.id.match(/qsnd_txt_/); }).each(function() { $(this).removeClass('white'); });
    } catch (e) {
        
    }
}

function strlen (string) {
    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate(could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

var clip_finished = new Array();

function check_duration(num, nret) {
	var obj = sounds[num];
	if(!obj) {
		return;
	}

	var s_duration = (obj.duration / 1000);
	var s_position = (obj.position / 1000);

	if(typeof(nret) == 'undefined') {
	    for(var x = 0; x < sounds.length; x++) {
	    	if(x == num) { continue; }
	        if(typeof(sounds[x]) == 'undefined') { continue; }
	        check_duration(x, 1);
	    }
	}

    if(typeof($('#sound_duration_' + num + '_s').attr('id')) == 'undefined') {
	    $('#sound_duration_' + num).html('&nbsp;' + splitTime(s_position) + '  &nbsp; ' + splitTime(s_duration));
    } else {
        $('#sound_duration_' + num + '_s').html(splitTime(s_position));
        $('#sound_duration_' + num + '_e').html(splitTime(s_duration));
        // + '  &nbsp; ' + splitTime(s_duration));
    }

    if(clip_finished[num]) {
    	return; 
    }
    
    /*
	if(Math.ceil(s_position) >= Math.floor(s_duration)) {
		clip_finished[num] = true;
		if(typeof(enable_next) == 'function') {
			enable_next();
		}
		return;
	}
    */
	

	if(typeof(nret) != 'undefined') { return; }
	setTimeout('check_duration(' + num + ')',1000);
}

function enable_next() {
	if(!next_imgsrc) {
		return; 
	}
    num_sounds_heard++;
    if(num_sounds_heard < num_snd_req) { return; }

	var nobj = document.getElementById('btn_next');
	nobj.onclick = next_onclick;
	nobj.onmouseover = next_onmouseover;
	nobj.src = next_imgsrc;
	nobj.style.cursor = 'pointer';
	nobj.title = '';
}

function splitTime(a) {
	var hours=Math.floor(a/3600);
	var minutes=Math.floor(a/60)-(hours*60);
	var seconds=a-(hours*3600)-(minutes*60);

	minutes = Math.round(minutes);
	seconds = Math.round(seconds);

	if(strlen(minutes) == 1) { minutes = '0' + minutes; }
	if(strlen(seconds) == 1) { seconds = '0' + seconds; }
	return minutes + ':' + seconds;
}

function create_sound(sound_id, sound_file, autoplay) {
	if(!sound_ready) { 
		return; 
	}
	if(typeof(autoplay) == 'undefined') {
		autoplay = 0;
	}

	if(!done_autoplay) {
		done_autoplay = true;
	//} else {
	//	autoplay = 0;
	}

    var mySound = soundManager.createSound({
      id: sound_id,
      url: sound_file,
      autoPlay: autoplay,
      onfinish: finish_playing
    });


    if(autoplay > 0) {
        playing_sound = sound_id;
    	var sid = sound_id.replace('snd_', '');
		setTimeout('check_duration("'+sid+'");', 1000);
	}

    return mySound;
}

var sound_action_var = false;
function snd_toggle() {
    sound_action_var = true;
    setTimeout('sound_action_var=0;', 200);
}

function toggle_mute() {
    $.post('#', {toggle_mute: 1}, function(data) {
        for(var x = 1; x < sounds.length; x++) {
            sounds[x].setVolume(data);
        }
        default_sound_volume = data;
        soundManager.defaultOptions.volume = data;
        var i = $('#mute_audio');
        if(data == '0') {
            i.attr('src', i.attr('src').replace('_off_', '_on_'));
        } else {
            i.attr('src', i.attr('src').replace('_on_', '_off_'));            
        }     
    });  
}

var has_playlist = '';
function finish_playing(bool) {
    //if(typeof(bool) == 'undefined') { setTimeout('finish_playing(1);', 500); return; }
    if(!playing_sound.match('snd_')) { playing_sound = 'snd_' + playing_sound; }
    var csound = soundManager.getSoundById(playing_sound);
    if(!csound || typeof(csound.url) == 'undefined') { return; }
    var cfile = csound.url.split('/').pop();
    
    if(has_playlist.match(cfile + ',')) {
        has_playlist = has_playlist.replace(cfile + ',', '');
    }
    if(has_playlist.match(cfile)) {
        has_playlist = has_playlist.replace(cfile, '');
    }
    var id = playing_sound.replace('snd_', '');
    play_sound('stop', id);

    if(has_playlist == '' || has_playlist == ',') { return; }
    
    var next_fn = '';
    if(has_playlist.match(',')) {
        next_fn = has_playlist.split(',').shift();
    } else {
        next_fn = has_playlist;
    }
    
    clear_sound_highlights();
        
    for(var x = 1; x  < sounds.length; x++) {
        var puri = sounds[x].url;
        var psid = sounds[x].sID;
        if(puri.match(next_fn)) {
            play_sound('play', psid.replace('snd_', ''))
        }
        
    }
}

function owin(uri, width, height) {
	if(typeof(width) == 'undefined') { width = '640'; }
	if(typeof(height) == 'undefined') { height = '480'; }
	var lastchar = uri.substr(uri.length-1,1);
	var lastthree = uri.substr(uri.length-3,3);
	if(lastthree != "pdf") {
		if(lastchar == '/') {
			uri += 'popup/';
		} else {
			uri += '/popup/';
		}
	}
	window.open(uri	,"pu", "menubar=no,toolbar=no,width="+width+",height="+height+",location=no");
}

function hide_progress_bar(uid) {
	var nuid = uid.replace('fupl_', 'fupl_prog_');
	if(!nuid.match('fupl_prog')) { return; }

	$("#" + nuid).fadeOut('normal', function() {
		$("#" + nuid).progressbar('destroy');
		$("#" + nuid).html('<small style="padding-left: 15px;" class="txt_EIB">upload complete</small>');
		$("#" + nuid).fadeIn('normal');
	});
}

function updateProgress(uid, perc) {
	var nuid = uid.replace('fupl_', 'fupl_prog_');
	if(!nuid.match('fupl_prog')) { return; }

	if(!perc || perc < 0 || perc == '' || typeof(perc) == 'undefined') {
		perc = '0';
	}
	if($("#" + nuid).hasClass('textonly')) {
		$("#" + nuid).html("<small>" + perc + '%</small>');
	} else {
		if(perc == '0') {
			$("#" + nuid).progressbar('destroy');
			$("#" + nuid).html('');
			$("#" + nuid).progressbar({
				value: perc
			});
		} else {
			$("#" + nuid).progressbar('option', 'value', perc);
		}
	}

	return;
}

function pollTimer(uniqId) {
	  if (!uploadStatus[uniqId]) {
		  return;
	  }

		  $.post('/ajax/upload/stat/', {uid: uniqId}, function(data, textStatus) {
		      updateProgress(uniqId, data);
		      if(data == '100') { uploadStatus[uniqId] = 0; return; }

		  		if(!uploadStatus[uniqId]) {
			    	return;
				}

		    setTimeout("pollTimer('" + uniqId + "')", 1000);
		  });
}

function docmanager_upload(ele_id, allowed_types, uri_extra, up_uid, callback) {
	uploadStatus['fupl_' + ele_id] = 1;

    if(typeof(uri_extra) == 'undefined') {
        uri_extra = '';
    }

	new AjaxUpload('#fupl_' + ele_id, {
		  // Location of the server-side upload script
		  // NOTE: You are not allowed to upload files to another domain
		  action: '/ajax/upload/file/' + uri_extra,
		  // File upload name
		  name: 'up_file',
		  // Additional data to send
		  data: {
			  UPLOAD_IDENTIFIER: 'fupl_' +  ele_id,
			  UPLOAD_SID: up_uid
		  //  example_key2 : 'example_value2'
		  },
		  // Submit file after selection
		  autoSubmit: true,
		  // The type of data that you're expecting back from the server.
		  // HTML (text) and XML are detected automatically.
		  // Useful when you are using JSON data as a response, set to "json" in that case.
		  // Also set server response type to text/html, otherwise it will not work in IE6
		  responseType: false,
		  // Fired after the file is selected
		  // Useful when autoSubmit is disabled
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onChange: function(file, extension){},
		  // Fired before the file is uploaded
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onSubmit: function(file, ext) {
		      	var npreg = eval('/^('+allowed_types+')$/');
			  	// ensure that the extension is in the allowed types list
                if (!(ext && npreg.test(ext))){
                    // extension is not allowed
                    alert('Error: invalid file extension, allowed extensions are: ' + allowed_types);
                    // cancel upload
                    return false;
            	}
            	updateProgress('fupl_' + ele_id, '0');
        		uploadStatus['fupl_' + ele_id] = 1;
        		pollTimer('fupl_' + ele_id);
		  },
		  // Fired when file upload is completed
		  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		  // @param file basename of uploaded file
		  // @param response server response
		  onComplete: function(file, response) {
			  if(response.match('ajax') && response.match('')) {
				  var iob = document.getElementById('img_' + ele_id);
				  if(iob && typeof(iob) != 'undefined') {
					  iob.onclick = function() { eval(response); };
				  }
			  }
			  uploadStatus['fupl_' + ele_id] = 0;
			  updateProgress('fupl_' + ele_id, 100);
			  setTimeout('hide_progress_bar("fupl_'+ele_id+'");', 1000);
              if(typeof(callback) != 'undefined') {
                setTimeout(callback + '()', 100);
              }
		  }
		});
}

function reload_page() {
	window.location.reload(true);
}
function create_file_upload(ele_id, allow_sound, uri_extra, callback) {
	uploadStatus['fupl_' + ele_id] = 1;

    if(typeof(allow_sound) == 'undefined') {
        allow_sound = false;
    }
    if(typeof(uri_extra) == 'undefined') {
        uri_extra = '';
    }

	new AjaxUpload('#fupl_' + ele_id, {
		  action: '/ajax/upload/file/' + uri_extra,
		  name: 'up_file',
		  data: {
			  UPLOAD_IDENTIFIER: 'fupl_' +  ele_id
		  },
		  autoSubmit: true,
		  responseType: false,
		  onChange: function(file, extension){},
		  onSubmit: function(file, ext) {
            if(allow_sound) {
                if (! (ext && /^(wav|mp3|flv|swf)$/.test(ext))){
                    // extension is not allowed
                    alert('Error: invalid file extension');
                    // cancel upload
                    return false;
                }
            } else {
                if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
                    // extension is not allowed
                    alert('Error: invalid file extension');
                    // cancel upload
                    return false;
            	}
            }
            	updateProgress('fupl_' + ele_id, '0');
        		uploadStatus['fupl_' + ele_id] = 1;
        		pollTimer('fupl_' + ele_id);
		  },
		  onComplete: function(file, response) {
			  if(response.match('ajax') && response.match('')) {
				  var iob = document.getElementById('img_' + ele_id);
				  if(iob && typeof(iob) != 'undefined') {
					  iob.onclick = function() { eval(response); };
				  }
			  }
			  uploadStatus['fupl_' + ele_id] = 0;
			  updateProgress('fupl_' + ele_id, 100);
			  setTimeout('hide_progress_bar("fupl_'+ele_id+'");', 1000);
              if(typeof(callback) != 'undefined') {
                setTimeout(callback + '()', 100);
              }
		  }
		});
}

function activateTab(obj) {
	var tabs = document.getElementsByTagName('td');
	var xtab;

	for(var x = 0; x < tabs.length; x++) {
		if(!tabs[x].id || !tabs[x].id.match('tab_')) { continue; }
		tabs[x].className = tabs[x].className.replace('active', '');
		tabs[x].className = tabs[x].className.replace(' ', '');
		xtab = tabs[x].id.replace('tab_', 'tab_content_');
		xtab = document.getElementById(xtab);
		xtab.style.display = 'none';
	}

	obj.className += ' active';
	var ctab = obj.id.replace('tab_', 'tab_content_');
	ctab = document.getElementById(ctab);
	ctab.style.display = 'inline';
}


function get_deps(fid) {
	var tret = true;

	if(typeof(udeps[fid]) != 'undefined') {
		var nar = udeps[fid];
		for(var x = 0; x < nar.length; x++) {
			var jqobj = $('#' + nar[x]);
			if(!jqobj) { continue; }

			if(!jqobj.validSingleElement()) {
				if(IE) {
					var njj = document.getElementById(nar[x]);
					if(njj.type == 'select-one') {
						njj.style.backgroundColor = '#ffd7d7';
					}
				}

				tret = false;
			} else {
				if(IE) {
					var njj = document.getElementById(nar[x]);
					if(njj.type == 'select-one') {
						njj.style.backgroundColor = '';
					}
				}
			}
		}
	}
	clearTimeout(timer1);
	timer1 = setTimeout('check_parent("'+fid+'");', 500);
	return tret;
}

function check_child_fields(fid) {
	fid = fid.replace('frm_', '');
	var do_prompt = false;
	if(last_prompt) { return; }

	if(typeof(udeps[fid]) != 'undefined') {
		var nar = udeps[fid];
		for(var x = 0; x < nar.length; x++) {
			var jqobj = $('#' + nar[x]);
			if(jqobj.val() != '' && jqobj.val() != ' ') {
				do_prompt = true;
			}
		}
	}

	if(do_prompt && !last_prompt) {
		last_prompt = true;
		var ret = confirm('You appear to have filled in licence/ticket details but have not provided the type of licence/ticket/card you have.\n\n'
						 +'To provide this information please click OK, to remove the details you have entered, click CANCEL');
		setTimeout('last_prompt=false;', 500);
		return ret;
	}
	return;
}

function remove_child_formatting(fid) {
	fid = fid.replace('frm_', '');
	if(typeof(udeps[fid]) != 'undefined') {
		var nar = udeps[fid];
		for(var x = 0; x < nar.length; x++) {
			var jqobj = $('#' + nar[x]);
	  		$('#' + nar[x]).removeClass('error');
			var yx = $($('#' + nar[x]).form).find("label[for=" + nar[x] + "]");
			yx.hide();
			jqobj.attr('value', '');
		}
	}
}
function check_parent(fid) {
	var nobj = $('#frm_' + fid);
	if(trim(nobj.val()) == "") { return; }
	var mbool = nobj.valid();
	clearTimeout(timer1);
	//if(!mbool) {
		//timer1 = setTimeout('check_parent("'+fid+'");', 500);
	//}
}

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

function showTooltip(e,tooltipTxt, topzero) {

    var bodyWidth = Math.max(document.body.clientWidth,document.documentElement.clientWidth) - 20;
    var bodyHeight = Math.max(document.body.clientHeight,document.documentElement.clientHeight) - 20;

    if(!dhtmlgoodies_tooltip){
        dhtmlgoodies_tooltip = document.createElement('DIV');
        dhtmlgoodies_tooltip.id = 'dhtmlgoodies_tooltip';
        dhtmlgoodies_tooltipShadow = document.createElement('DIV');
        dhtmlgoodies_tooltipShadow.id = 'dhtmlgoodies_tooltipShadow';

        document.body.appendChild(dhtmlgoodies_tooltip);
        document.body.appendChild(dhtmlgoodies_tooltipShadow);

        if(tooltip_is_msie){
            dhtmlgoodies_iframe = document.createElement('IFRAME');
            dhtmlgoodies_iframe.frameborder='5';
            dhtmlgoodies_iframe.style.backgroundColor='#FFFFFF';
            dhtmlgoodies_iframe.src = '#';
            dhtmlgoodies_iframe.style.zIndex = 100;
            dhtmlgoodies_iframe.style.position = 'absolute';
            document.body.appendChild(dhtmlgoodies_iframe);
        }

    }

    dhtmlgoodies_tooltip.style.display='block';
    dhtmlgoodies_tooltipShadow.style.display='block';
    if(tooltip_is_msie)dhtmlgoodies_iframe.style.display='block';

    var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)st=0;
    var leftPos = e.clientX + 10;

    dhtmlgoodies_tooltip.style.width = null;    // Reset style width if it's set
    dhtmlgoodies_tooltip.innerHTML = tooltipTxt;
    dhtmlgoodies_tooltip.style.left = leftPos + 'px';
    var topPos = e.clientY + 10 + st;
    var tooltipHeight = dhtmlgoodies_tooltip.offsetHeight;

    if (typeof(topzero) != 'undefined') {
        topPos = 10;
    } else if((topPos + tooltipHeight)>bodyHeight) {
        topPos = bodyHeight - 30 - tooltipHeight;
    }
    dhtmlgoodies_tooltip.style.top = topPos + 'px';


    dhtmlgoodies_tooltipShadow.style.left =  leftPos + dhtmlgoodies_shadowSize + 'px';
    dhtmlgoodies_tooltipShadow.style.top = topPos + dhtmlgoodies_shadowSize + 'px';

    if(dhtmlgoodies_tooltip.offsetWidth>dhtmlgoodies_tooltipMaxWidth){    /* Exceeding max width of tooltip ? */
        dhtmlgoodies_tooltip.style.width = dhtmlgoodies_tooltipMaxWidth + 'px';
    }

    var tooltipWidth = dhtmlgoodies_tooltip.offsetWidth;
    if(tooltipWidth<dhtmlgoodies_tooltipMinWidth)tooltipWidth = dhtmlgoodies_tooltipMinWidth;


    dhtmlgoodies_tooltip.style.width = tooltipWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';

    if((leftPos + tooltipWidth)>bodyWidth){
        dhtmlgoodies_tooltip.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px','') - ((leftPos + tooltipWidth)-bodyWidth)) + 'px';
        dhtmlgoodies_tooltipShadow.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px','') - ((leftPos + tooltipWidth)-bodyWidth) + dhtmlgoodies_shadowSize) + 'px';
    }

    if(tooltip_is_msie){
        dhtmlgoodies_iframe.style.left = dhtmlgoodies_tooltip.style.left;
        dhtmlgoodies_iframe.style.top = dhtmlgoodies_tooltip.style.top;
        dhtmlgoodies_iframe.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
        dhtmlgoodies_iframe.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';

    }

}

function hideTooltip() {
    dhtmlgoodies_tooltip.style.display='none';
    dhtmlgoodies_tooltipShadow.style.display='none';
    if(tooltip_is_msie)dhtmlgoodies_iframe.style.display='none';
}

function do_jquery_dialog(etitle, emsg) {
	if(typeof(emsg) == 'undefined') {
		emsg = etitle;
		etitle = 'Input Required';
	}
	emsg = emsg.replace('\n', '<br />');
	$("#j_dialog").html(emsg);

		$("#j_dialog").dialog({
			bgiframe: true,
			modal: true,
			title: etitle,
			height: '200',
			width: '300',
			buttons: {
				"Continue": function() {
					$(this).dialog('destroy');
					return true;
				},
				"Cancel": function() {
					$(this).dialog('destroy');
					return false;
				}

			}
		});
}

function throw_error(error_title, error_msg) {
	if(error_displayed) { return; }

	$('#errorpane').css('display', 'inline');
	$('#errorpane').css('height', f_clientHeight());
	$('#dialog_button_ok').focus();
	$('#errorpane_text').html(error_msg);
	$('#errorpane_title').html(error_title);
	error_displayed = true;

	if(IE) {
		var objs = document.getElementsByTagName('select');
		for(var x = 0; x < objs.length; x++) {
				objs[x].style.display = 'none';
		}
	}
}

function hide_dialog() {

	if(IE) {
		var objs = document.getElementsByTagName('select');
		for(var x = 0; x < objs.length; x++) {
				objs[x].style.display = 'inline';
		}
	}

	setTimeout('error_displayed = false;', 500);
	$('#errorpane').css('display', 'none');
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function send_ajax(uri, pvar, target_div, append_type) {
	$.post(uri,pvar,function(data){
        var a = $("#"+target_div);
        if(typeof(append_type) == 'undefined') {
            a.append(data);
            a.css('height', '100%');
        } else if (append_type == 'html') {
            a.html(data);
        }
    });
}

function MM_preloadImages() {
  var d=document;
  if(d.images) {
  	if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() {
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() {
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	  window.open(theURL,winName,features);
}

function validateEmail(addr,man) {
	if (addr == '' && man) {return false;}
	if (addr == '') return true;
	var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
	for (i=0; i<invalidChars.length; i++) {if (addr.indexOf(invalidChars.charAt(i),0) > -1) {return false;}}
	for (i=0; i<addr.length; i++) {if (addr.charCodeAt(i)>127) {return false;}}
	var atPos = addr.indexOf('@',0);
	if (atPos == -1) {return false;}
	if (atPos == 0) {return false;}
	if (addr.indexOf('@', atPos + 1) > - 1) {return false;}
	if (addr.indexOf('.', atPos) == -1) {return false;}
	if (addr.indexOf('@.',0) != -1) {return false;}
	if (addr.indexOf('.@',0) != -1){return false;}
	if (addr.indexOf('..',0) != -1) {return false;}
	var suffix = addr.substring(addr.lastIndexOf('.')+1);
	if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' && suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {return false;}
	return true;
}
