// JavaScript Document
var _clip = null;
var _ajax_count = 0;
var _my = false;
var _ms = false;
var _mc = false;
var _mo = false;
var _selected_y = '';
var _selected_s = '';
var _selected_c = '';
var _selected_o = '';

$(document).ready(function()
{
        //$('#product_tip_1,#product_tip_2,#product_tip_3').hoverIntent(function(){$('#'+this.id+'_pop').fadeIn('slow');},function(){$('#'+this.id+'_pop').fadeOut('slow');});
        
        //$('#tablelist tbody tr:even').addClass('alt');      

        $('.check-all').click(
                function(){
                        $(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));
                }
        );
        
        if ($("#tablelist tbody tr").length > 0)
        {
                $("#tablelist").tablesorter({textExtraction: sortExtraction, headers: { 
                                0: { sorter: false }, 
                                7: { sorter: false } 
                        }, widgets: ['zebra'], sortList: [[2,0]]
                }); //.tablesorterPager({container: $("#pager")})
        }
        else
        {
                $("#tablelist").tablesorter({textExtraction: sortExtraction, headers: {0: { sorter: false },6: { sorter: false}}});
        }

        if ($("#tablelist2 tbody tr").length > 0)
        {
                $("#tablelist2").tablesorter({textExtraction: sortExtraction, headers: { 
                                0: { sorter: false }, 
                                7: { sorter: false } 
                        }, widgets: ['zebra'], sortList: [[1,0]]
                }); //.tablesorterPager({container: $("#pager")})
        }
        else
        {
                $("#tablelist2").tablesorter({textExtraction: sortExtraction, headers: {0: { sorter: false },6: { sorter: false}}});
        }
		
	$('a.btnFilter').click(function()
	{
		if ($('#modalBg').is(':hidden'))
		{
			var _id = parseInt(this.id.replace('Filter',''));
			var _title = $('#titleAreaReport span.title').html();
			$('#modal_image').hide();
			var _path = $('#titleAreaReport span.group').html();
			$('#modal_path').html(_path);
			$('#modalBg').height($(document).height());
			$('#modal_heading').html(_title);
			$('#modal_id').val(_id);
			$('#loaderBg').centerInClient().show();
			var _lf = $('#reportsActions .reportCount').text();
			//var _mtch = _lf.match('^.*([0-9]+)$');
			//if (_mtch.length == 2)
			//{
				$('#modal_output p.learners').text(' learners found: '+_lf.substr(_lf.indexOf(" ")+1, _lf.length-_lf.indexOf("-")-1));
				//$('#modal_output p.learners').css('visibility','hidden');
 			//}
			var _parameters = 'filters=1&id='+_id;
			$.ajax({type: 'POST', url: '?do=load-filters&report=1', data: _parameters, dataType: 'json', success: function(_data) 
			{
				if (_data.ok == 1)
				{
					_ms.dropdownchecklist('destroy');
					_my.dropdownchecklist('destroy');
					_mc.dropdownchecklist('destroy');
					_mo.dropdownchecklist('destroy');
					_ms.html(_data.subjects);
					_my.html(_data.years);
					_ms.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateSubjects});
					updateDropdown('s',$('#modalsubject')[0]);
					_my.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateYears});
					updateDropdown('y',$('#modalyear:only')[0]);
					if (_data.classes)
					{
						_mc.html(_data.classes);
						_mc.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateClasses});
						updateDropdown('c',$('#modalclass:only')[0]);
					}
					if (_data.others)
					{
						_mo.html(_data.others);
						_mo.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateOthers});
						updateDropdown('o',$('#modalother:only')[0]);
					}

				}
		
				$('#loaderBg').hide();

				$('#modalBg').css('opacity', 0).show();
				$('#modalBg').fadeTo('fast', 0.5, function()
				{
					$('#modalContainer').centerInClient().show();
				});
			}
			});
			
		}
		return false;
	});
	
	$('a.edit').live('click', function()
	{
		if ($('#modalBg').is(':hidden'))
		{
			var _id = parseInt(this.id.replace('Edit',''));
			var _title = this.title.replace('Edit ','');
			$('#modal_image').hide();
			var _path = $('#Path'+_id);
			if (_path.length == 1)
			{
				$('#modal_path').html(_path.html());
			}
			$('#modalBg').height($(document).height());
			$('#modal_heading').html($('#titleAreaAlt .title:first').html());
			$('#modal_id').val(_id);
			$('#modal_mode').val('edit');
			$('#modal_output').css('visibility','hidden');
			$('#modal_error').html('').hide();
			$('#modal_group').val(_title).removeClass('default');
			$('#modal_url').val($('#url'+_id).attr('href')).removeClass('default').removeClass('success');
			$('#modalContainer .schedule').hide();
			$('#modalContainer .update').show();
			$('#loaderBg').centerInClient().show();
			var _parameters = 'id='+_id;
			
			$.ajax({type: 'POST', url: '?do=load-filters', data: _parameters, dataType: 'json', success: function(_data) 
			{
				if (_data.ok == 1)
				{
					_ms.dropdownchecklist('destroy');
					_my.dropdownchecklist('destroy');
					_mc.dropdownchecklist('destroy');
					_mo.dropdownchecklist('destroy');
					_ms.html(_data.subjects);
					_my.html(_data.years);
					_ms.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateSubjects});
					updateDropdown('s',$('#modalsubject')[0]);
					_my.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateYears});
					updateDropdown('y',$('#modalyear:only')[0]);

					if (_data.classes && (_selected_s!="" || _selected_y!=""))
					{
						_mc.html(_data.classes);
						_mc.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateClasses});
						updateDropdown('c',$('#modalclass:only')[0]);
					}
					if (_data.others && (_selected_s!="" || _selected_y!=""))
					{
						_mo.html(_data.others);
						_mo.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateOthers});
						updateDropdown('o',$('#modalother:only')[0]);
					}					
				}
		
				$('#loaderBg').hide();

				$('#modalBg').css('opacity', 0).show();
				$('#modalBg').fadeTo('fast', 0.5, function()
				{
					$('#modalContainer').centerInClient().show();
				});
			}
			});
			
		}
		return false;
	});
				

      $('a.btnSchedule').click(function()
	{
		if ($('#modalBg').is(':hidden'))
		{
			var _id = parseInt(this.id.replace('Schedule',''));
			var _title = this.title.replace('Schedule ','');
			var _image = $('#image'+_id);
			if (_image.length == 1)
			{
				$('#modal_image').html($(_image).html()).show();
			}
			else
			{
				$('#modal_image').hide();
			}
			var _path = $('#Path'+_id);
			if (_path.length == 1)
			{
				$('#modal_path').html(_path.html());
			}
			

			$('#modalContainer .schedule').show();
			$('#modalContainer .update').hide();
			$('#modalBg').height($(document).height());
			$('#modal_heading').html(_title);
			$('#modal_id').val(_id);
			$('#modal_mode').val('add');
			$('#modal_output').css('visibility','hidden');
			$('#modal_error').html('').hide();
			$('#modal_group').val(COHORT_NAME_REQ).addClass('default').removeClass('success');
			$('#modal_url').val(SCHEDULE_TEXT).addClass('default');
			_ms.dropdownchecklist('destroy');
			_my.dropdownchecklist('destroy');
			_mc.dropdownchecklist('destroy');
			_mo.dropdownchecklist('destroy');
			_selected_y = '';
			_selected_s = '';
			_selected_c = '';
			_selected_o = '';
			_ms.children().each(function()
			{
				this.selected = false;
			});
			_my.children().each(function()
			{
				this.selected = false;
			});
			_ms.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateSubjects});
			_my.dropdownchecklist({ emptyText:'Please select',icon:{},minWidth:400,width:400,maxDropHeight:150,onComplete:updateYears});

			$('#modalBg').css('opacity', 0).show();
			$('#modalBg').fadeTo('fast', 0.5, function()
			{
				$('#modalContainer').centerInClient().show();
			});
		}
		return false;
	});
		
	$('a.flip').live('click', function()
	{
		var _this_btn = this;
		var _id = parseInt(this.id.replace('Flip',''));
		var _action = this.href;
		var _parameters = 'id[]='+_id;

		_ajax_count++;
	
		$('#loaderBg').centerInClient().show(); 

		$.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
		{
			_ajax_count--;
			
			if(_ajax_count <= 0)
			{
				$('#loaderBg').hide();
			}
			
			if (_data.ok == 1)
			{
				$(_this_btn).toggleClass('btnActive').toggleClass('btnInActive');
				var _parent_row = $(_this_btn).parent().parent();
				_parent_row.toggleClass('inactive');
			}
			else
			{
				alert(_data.response);
			}
		}
		});
		return false;
	});
        
	$('#actions_grp select').change(function()
	{
		var _val = $('#actions_grp select').val();

		var _url = window.location.toString();

		var pos=_url.indexOf("&grp=");
		
		if(pos>=0) {
			_url = _url.substring(0, pos);
		}
              _url += '&grp='+_val;

		window.location = _url;
	});

        $('#actions .button-apply').click(function()
        {
                var _val = $('#actions select').val();


		$('a.flip').each(function()
              {
              	_parent_row = $(this).parent().parent();
                                                
              	if ($('.SelectCheckbox',_parent_row).is(':checked'))
               	{
               		var _this_btn = this;
                         	if($(this).hasClass('btnShared')) {
					alert("You do not have permission to modify shared tests. Please deselect them and try again");
					return;
				}
                     }
               });
		
                
                if (_val == 'Delete')
                {
                        $('#modalBg').height($(document).height());
                        $('#modalContainerConfirm > div > div > p > span').html(QUIZ_DATA_LOST);
                        $('#modalContainerError').html('');
                        $('#modalBg').css('opacity', 0).show();
                        $('#modalBg').fadeTo('fast', 0.5, function()
                        {
                                $('#modalContainerConfirm').centerInClient().show();
                                $('.btnOk').unbind('click').click(function()
                                {
                                        var _ids = new Array(); 
                                        var _counter = 0;
                                        var _action = '?do=delete-quiz';
                                        var _parameters = 'a=1';

                                        $('a.flip').each(function()
                                        {
                                                _parent_row = $(this).parent().parent();
                                                
                                                if ($('.SelectCheckbox',_parent_row).is(':checked'))
                                                {
                                                        var _this_btn = this;
                                                        var _id = parseInt(this.id.replace('Flip',''));
                                                        _parameters += '&id[]='+_id;
                                                        _ids[_counter] = this.id;
                                                        _counter++;
                                                }
                                        });
                                        
                                        if (_counter > 0)
                                        {
                                                _ajax_count++;
                                                $('#loaderBg').centerInClient().show(); 
                                        
                                                $.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
                                                {
                                                        _ajax_count--;
                                                        
                                                        if(_ajax_count <= 0)
                                                        {
                                                                $('#loaderBg').hide();
                                                        }
                                                        
                                                        if (_data.ok == '1')
                                                        {
                                                                $.each(_ids, function(_i, _v) 
                                                                { 
                                                                        $('#'+_v).parent().parent().html('<td colspan="6">* Deleted *</td>');
                                                                });
                                                                $('#modal_close3').click();
                                                        }
                                                        else
                                                        {
                                                                $('#modalContainerError').html(_data.response);
                                                        }
                                                }});
                                        }
                                        else
                                        {
                                                $('#modal_close3').click();
                                        }
                                        return false;
                                });
                        });
                }
                else
                {
                        var _ids = new Array(); 
                        var _counter = 0;
                        var _action = '?do=flip-test';
                        var _parameters = 'a=1';

                        $('a.flip').each(function()
                        {
                                _parent_row = $(this).parent().parent();
                                
                                if ($('.SelectCheckbox',_parent_row).is(':checked'))
                                {
                                        if ((_val == 'Turn On' && $(this).hasClass('btnInActive')) || (_val == 'Turn Off' && $(this).hasClass('btnActive')))
                                        {
                                                var _this_btn = this;
                                                var _id = parseInt(this.id.replace('Flip',''));
                                                _parameters += '&id[]='+_id;
                                                _ids[_counter] = this.id;
                                                _counter++;
                                        }
                                }
                        });
                        
                        if (_counter > 0)
                        {
                                _ajax_count++;
                                $('#loaderBg').centerInClient().show(); 
                        
                                $.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
                                {
                                        _ajax_count--;
                                        
                                        if(_ajax_count <= 0)
                                        {
                                                $('#loaderBg').hide();
                                        }
                                        
                                        if (_data.ok == '1')
                                        {
                                                $.each(_ids, function(_i, _v) 
                                                { 
                                                        var _this_btn = $('#'+_v);
                                                        $(_this_btn).toggleClass('btnActive').toggleClass('btnInActive');
                                                        var _parent_row = $(_this_btn).parent().parent();
                                                        _parent_row.toggleClass('inactive');
                                                });
                                        }
                                        else
                                        {
                                                alert(_data.response);
                                        }
                                }});
                        }
                        return false;
                }
                return false;
        });

	$('#button-apply-filter').click(function() {

		var _val = $('#actions select').val();


		var _url = window.location;
              _url += '&grp='+_val;

		window.location = _url;
	});

        
        $('#button-apply-instances').click(function()
        {
                var _val = $('#actions select').val();
                
                if (_val == 'Delete')
                {
                        $('#modalBg').height($(document).height());
                        $('#modalContainerConfirm > div > div > p > span').html(DATA_LOST);
                        $('#modalContainerError').html('');
                        $('#modalBg').css('opacity', 0).show();
                        $('#modalBg').fadeTo('fast', 0.5, function()
                        {
                                $('#modalContainerConfirm').centerInClient().show();
                                $('.btnOk').unbind('click').click(function()
                                {
                                        var _ids = new Array(); 
                                        var _counter = 0;
                                        var _action = '?do=delete-test-instance';
                                        var _parameters = 'a=1';

                                        $('#tablelist .SelectCheckbox:checked').each(function()
                                        {
                                                var _this_btn = this;
                                                var _id = parseInt(this.id.replace('s_',''));
                                                _parameters += '&id[]='+_id;
                                                _ids[_counter] = this.id;
                                                _counter++;
                                        });
                                        
                                        if (_counter > 0)
                                        {
                                                _ajax_count++;
                                                $('#loaderBg').centerInClient().show(); 
                                        
                                                $.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
                                                {
                                                        _ajax_count--;
                                                        
                                                        if(_ajax_count <= 0)
                                                        {
                                                                $('#loaderBg').hide();
                                                        }
                                                        
                                                        if (_data.ok == '1')
                                                        {
                                                                $.each(_ids, function(_i, _v) 
                                                                { 
                                                                        $('#'+_v).parent().parent().html('<td colspan="8">* Deleted *</td>');
                                                                });
                                                                $('#modal_close3').click();
                                                        }
                                                        else
                                                        {
                                                                $('#modalContainerError').html(_data.response);
                                                        }
                                                }});
                                        }
                                        else
                                        {
                                                $('#modal_close3').click();
                                        }
                                        return false;
                                });
                        });
                }
                
                return false;
                
        });

        $('#modal_schedule,#modal_update').click(function()
		{
                if ($('#modal_group').val() == COHORT_NAME_REQ)
                {
                        $('#modal_group').val('')
                }
                if ($('#modal_url').val() == ADD_COHORT_NAME)
                {
                        $('#modal_url').val('')
                }
                $('#modal_form').submit();
                return false;
        });
        
		$('#modal_update_report').click(function()
	{
		var thetext = $('#reportsActions .reportCount').text();
		var _id = $('#modal_id').val();
		var _action = this.href;
		var _parameters = 'id='+_id+'&s='+escape(_selected_y+_selected_s);
		var _idlist = (_selected_c.length && _selected_o.length) ? _selected_c+','+_selected_o : _selected_c+_selected_o;
		if (_idlist.length)
		{
			_parameters += '&ids='+_idlist;			
		}
		
		if (_selected_y.length > 0 || _selected_s.length > 0 || _idlist.length > 0)
		{
			$('#loaderBg').centerInClient().show(); 
			_ajax_count++;
			$.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
			{
				_ajax_count--;
	
				if(_ajax_count <= 0)
				{
					$('#loaderBg').hide();
				}
	
				if (_data.ok == 1)
				{
					$('#tablelist tbody tr').each(function()
					{
						$(this).addClass('filtered');
					});
					if (_data.items.length > 0)
					{
						$('#modal_output p.learners').text(' learners found: '+_data.items.length);
						//$('#modal_output p.learners').css('visibility','');
						$('#reportsActions span.reportCount').text('Displaying '+_data.items.length+' - '+thetext.substr(thetext.indexOf("-")+2));
						$.each(_data.items, function(_i, _v) 
						{
							$('#d_'+_v).closest('tr').removeClass('filtered');
						});

					} else {
						$('#modal_output p.learners').text(' learners found: 0');
						//$('#modal_output p.learners').css('visibility','');
						$('#reportsActions span.reportCount').text('Displaying '+_data.items.length+' - '+thetext.substr(thetext.indexOf("-")+2));
					}
				}
			}
			});
		}
		else
		{
			var _count=0;
			$('#tablelist tbody tr').each(function()
			{
				$(this).removeClass('filtered');
				_count++;
			});
			$('#modal_output p.learners').text(' learners found: '+_count);
			//$('#modal_output p.learners').css('visibility','');
			$('#reportsActions span.reportCount').text('Displaying 0 - '+thetext.substr(thetext.indexOf("-")+2));
		}
		
		return false;
	});

        $('#modal_group')
                .focus(function() 
                {
                        if (this.value==COHORT_NAME_REQ) $(this).removeClass('default').val('');
                }).blur(function() 
                {
                        if (this.value=='') $(this).addClass('default').val(COHORT_NAME_REQ);
                });
        
        $('#modal_form').submit(function()
	{
		var _group = $('#modal_group').val();
		
		if (_group.length > 0)
		{
			var _id = $('#modal_id').val();
			var _mode = $('#modal_mode').val();
			var _action = this.action;
			var _parameters = 'id='+_id+'&mode='+_mode+'&group='+_group+'&s='+escape(_selected_y+_selected_s);
			var _idlist = (_selected_c.length && _selected_o.length) ? _selected_c+','+_selected_o : _selected_c+_selected_o;
			if (_idlist.length)
			{
				_parameters += '&ids='+_idlist;			
			}
			$('#modal_group').removeClass('req');
			$('#modal_error').html('').hide();
			$('#modal_output').css('visibility','hidden');
			$('#loaderBg').centerInClient().show(); 
			_ajax_count++;
			$.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
			{
				_ajax_count--;
	
				if(_ajax_count <= 0)
				{
					$('#loaderBg').hide();
				}

				if (_data.ok == 1)
				{
					var _group = $('#modal_group').val();
					
					if (_mode == 'add')
					{
						$('#modal_url').val('Your Schedule was successfully created, \''+$('#modal_heading').html().replace('Schedule ','')+', '+_group+'\' can be found at:\n\n'+_data.response).removeClass('default').addClass('success');
					}
					else
					{
						$('#t_'+_id).html(_group);
						$('#Edit'+_id).attr('title','Edit '+_group);
					}
					$('#modal_output').css('visibility','visible');
				}
				else
				{
					$('#modal_group').addClass('req');
					$('#modal_error').html(_data.response).show();
				}
			}
			});
		}
		else
		{
			$('#modal_group').addClass('req');
			$('#modal_error').html('Required').show();
		}
		
		return false;
	});
        
        /*$('a.btnExport').click(function()
        {
                if (!this.base_href)
                        this.base_href = this.href;
                
                var _url = this.base_href;
		  var _parameters = '&i=on&csv=on';

                $('a.btnDownloadpdf').each(function()
                {
                        _parameters += '&id[]='+this.id.replace('d_','');
                });
                
                //this.href = _url + _parameters;

		  window.open(_url + _parameters,'_blank');                

                return false;
        });*/
        
        $('a.btnExport').click(function()
        {                
                var _parameters = '&i=on&csv=on';
                
                if (!this.base_href)
                        this.base_href = this.href;
                
                var _url = this.base_href;
                  _url += '&json=on';
                
                $('.SelectCheckboxCompleted:checked').each(function()
                {
                        _parameters += '&id[]='+this.id.replace('s_','');
                });
                
                        _ajax_count++;
                        $('#loaderBg').centerInClient().show(); 
                        var _action = _url;
                        $.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
                        {
                        			if(_ajax_count-- <= 1)
                                {
                                        $('#loaderBg').hide();
                                }
                                if (_data.ok == 1)
                                {
                                        $('#modalBg').height($(document).height());
                                                $('#modalBg').css('opacity', 0).show();
                                                $('#modalBg').fadeTo('fast', 0.5, function()
                                                {
                                                        var _modal_html = '<ul>';
                                                        for ( var _i=0, _len=_data.links.length; _i<_len; ++_i )
                                                        {
                                                                _modal_html += '<li>Report successfully generated!<br><br><a href="'+_data.links[_i]['url']+'" target="_blank">'+'Click here to download your CSV file.'+'</a></li>';
                                                        }
                                                        $('#modalContainer .mid').html('<ul>'+_modal_html+'</ul>');
                                                        $('#modalContainer').centerInClient().show();
                                                });
                                        
                                }
	                        }
                        });
                
                return false;
        });
        
		$('#groupReports,#individualReports').click(function()
        {
                
                var _parameters = 'pdf=on';
                var _count = 0;
                var _use_ajax;
                var _id = this.id;

                // Save the original href on the first click.
                if (!this.base_href)
                        this.base_href = this.href;
                else
                        this.href = this.base_href
                
               if (_id == 'groupReports') _parameters += '&g=on';
		// Either we are generating individual reports and we should deliver
		// a .zip through the link, or a PDF in a new window, generated via an
		// AJAX call.
		if (_id == 'individualReports' || _parameters == 'pdf=on') {
		  _use_ajax = false;
		  _parameters += '&i=on';
		} else {
		  _use_ajax = true;
		  this.href += '&json=on';
		}
                
                $('.SelectCheckboxCompleted:checked').each(function()
                {
                        _count++;
                        _parameters += '&id[]='+this.id.replace('s_','');
                });
                
                if (_count > 0)
                {
                        if (!_use_ajax) {
                                this.href = this.base_href + '&' + _parameters;
                                return true;
                        }
                        
						_ajax_count++;
                        $('#loaderBg').centerInClient().show(); 
                        
						var _action = this.href;
                        $.ajax({type: 'POST', url: _action, data: _parameters, dataType: 'json', success: function(_data) 
			{
				if(_ajax_count-- <= 1)
				{
					$('#loaderBg').hide();
				}
				if (_data.ok == 1)
				{
					if (_data.links.length == 1)
					{
						window.open(_data.links[0]['url'],'_blank');
					}
					else if (_data.links.length > 1)
					{
						$('#modalBg').height($(document).height());
						$('#modalBg').css('opacity', 0).show();
						$('#modalBg').fadeTo('fast', 0.5, function()
						{
							var _modal_html = '<ul>';
							for ( var _i=0, _len=_data.links.length; _i<_len; ++_i )
							{
								_modal_html += '<li><a href="'+_data.links[_i]['url']+'" target="_blank">'+_data.links[_i]['url']+'</a></li>';
							}
							$('#modalContainer .mid').html('<ul>'+_modal_html+'</ul>');
							$('#modalContainer').centerInClient().show();
						});
					}
				}
				else
				{
					alert(_data.response);
				}
			}
			});
		}
		
		return false;
	});


        $('#modal_close').click(function()
	{
		$('#modalContainer').hide();
		$('.ui-state-active').trigger('click');
		$('#modalBg').fadeOut('fast',function()
		{
			$('#modal_group').removeClass('req');
			$('#modal_error').html('');
		});
		return false;
	});

	$('#modal_close2').click(function()
	{
		$('#modalContainerinfo').hide();
		$('#modalBg').fadeOut('fast',function()
		{
			$('#modal_group').removeClass('req');
			$('#modal_error').html('');
		});
		return false;
	});

	$('#modal_close3,.btnCancel').click(function()
	{
		$('#modalContainerConfirm').hide();
		$('#modalBg').fadeOut('fast');
		return false;
	});

        $('a.iconQuestionSmall').hoverIntent(function(){$(this).next('div.tooltip').show();},function(){$(this).next('div.tooltip').hide();}).click(function(){return false;});
        $('a.iconQuestion').hoverIntent(function(){$(this).next('div.tooltipLarge').show();},function(){$(this).next('div.tooltipLarge').hide();}).click(function(){return false;});
        
        ZeroClipboard.setMoviePath('/ZeroClipboard.swf');
        _clip = new ZeroClipboard.Client();
        _clip.setHandCursor( true );
    	_clip.addEventListener( 'complete', function(client, text) 
        {
                $('#modalBg').height($(document).height());
                $('#modalContainerinfo > div > div > p > span').html(QUIZ_ADDR_CPY + text);
                $('#modalBg').css('opacity', 0).show();
                $('#modalBg').fadeTo('fast', 0.5, function()
                {
                        $('#modalContainerinfo').centerInClient().show();
                });
    	});
        
        $('a.btnCopyUrl').live('mouseover',function() 
        {
                _clip.setText(this.href);

                if (_clip.div) 
                {
                        _clip.receiveEvent('mouseout', null);
                        _clip.reposition(this);
                }
                else _clip.glue(this);
                
                _clip.receiveEvent('mouseover', null);
        });

        var _ac_input = $('#school_search');
        var _select_school_default = SCH_SEL;
        
        _ac_input.blur(function()
    {
                if ($(this).val() == '') $(this).val(_select_school_default).addClass('default');
    })
        .focus(function()
    {
            if ($(this).val() == _select_school_default) $(this).val('').removeClass('default');
    })
      .autocomplete('/?do=school-search', {
        scroll: true,
        matchContains: true,
        formatItem: function(row) {
          return row[1];
        },
        formatResult: function(row) {
                  return html_entity_decode(row[1]);
        }
      })
      .result(function(evt, data, formatted)
      {
        location.href = '/' + data[0];
      });
      
      if (_ac_input.val() == '' || _ac_input.val() == _select_school_default) _ac_input.val(_select_school_default).addClass('default');
          
           $('th.noclick').unbind('click').unbind('mousedown');
           
        $('#contactForm').submit(function()
        {
                var _type = $('#tbxEnquiryType').val();
                var _e = $('#tbxEnquiry').val();
                var _n = '';
                var _m = '';
                var _p = '';
                var _rc = '';
                var _rr = '';
                
                var _error = false;

                $('.info-error, .info-notice').remove();

                if (_e == '')
                {
                        $('#tbxEnquiryContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                        _error = true;
                }
                
                if (_type == 2)
                {
                        _m = $('#tbxEmail').val();
                        if (_m == '')
                        {
                                $('#tbxEmailContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                                _error = true;
                        }

                        _n = $('#tbxName').val();
                        if (_n == '')
                        {
                                $('#tbxNameContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                                _error = true;
                        }
                        
                        _p = $('#tbxPostcode').val();
                        if (_p == '')
                        {
                                _error = true;
                                $('#tbxPostcodeContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                        }

                        _rc = $('#recaptcha_challenge_field').val();
                        _rr = $('#recaptcha_response_field').val();
                }
                
                if (_error == false)
                {
                        $('#loaderBg').centerInClient().show();
                        var _t = $('#tbxTel').val();
        
                        $.ajax({type: 'POST', url: '?do=email', data: 'e='+_e+'&t='+_t+'&n='+_n+'&p='+_p+'&m='+_m+'&rc='+_rc+'&rr='+_rr, dataType: 'json', success: function(_data) 
                        {
                                $('#loaderBg').hide();
                                
                                $('.info-error, .info-notice').remove();

                                if (_data.ok == 1)
                                {
                                        $('#tbxEnquiryContainer').append('<div class="info-notice"><div class="clearer"/><p>'+_data.response+'<br/><br/></p></div>');
                                        //$('#tbxEnquiry').val('');
                                        //$('#tbxName').val('');
                                        //$('#tbxEmail').val('');
                                        //$('#tbxPostcode').val('');
                                }
                                else
                                {
                                        $('#tbxEnquiryContainer').append('<div class="info-error"><div class="clearer"/><p> '+_data.response+'<br/><br/></p></div>');
                                }
                                if (_rc)
                                {
                                        Recaptcha.reload();
                                }
                        }
                        });
                        return false;
                }
                return false;
        });
        
        $('#accountRegister').submit(function()
        {
                var _u = $('#tbxUser').val();
                $('.info-error, .info-notice').remove();
                if (_u == '')
                {
                        $('#tbxUserContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                        _error = true;
                }
                else
                {
                        $('#loaderBg').centerInClient().show();
                        var _t = $('#tbxTel').val();
        
                        $.ajax({type: 'POST', url: '?do=reset-password', data: 'u='+_u, dataType: 'json', success: function(_data) 
                        {
                                $('#loaderBg').hide();
                                
                                $('.info-error, .info-notice').remove();

                                if (_data.ok == 1)
                                {
                                        $('#tbxUserContainer').append('<div class="info-notice"><div class="clearer"/><p>'+_data.response+'<br/><br/></p></div>');
                                }
                                else
                                {
                                        $('#tbxUserContainer').append('<div class="info-error"><div class="clearer"/><p> '+_data.response+'<br/><br/></p></div>');
                                }
                        }
                        });
                        return false;
                }
                return false;
        });

        $('#accountPassword').submit(function()
        {
                var _p = $('#tbxPassword').val();
                var _c = $('#tbxConfirmPassword').val();
                var _h = $('#tbxHint').val();
		  var _error = false;

                $('.info-error, .info-notice').remove();

                if (_p == '')
                {
                        $('#tbxPasswordContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                        _error = true;
                }
                else if (_h == '')
                {
                        $('#tbxHintContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Required<br/><br/></p></div>');
                        _error = true;
                }
                else
                {
                        if (_c == '' || _c != _p)
                        {
                                $('#tbxConfirmPasswordContainer').append('<div class="info-error"><div class="clearer"/><p><strong>Error:</strong> Both passwords must be the same<br/><br/></p></div>');
                                _error = true;
                        }
                }
                
                if (_error == false)
                {
                        $('#loaderBg').centerInClient().show();
        
                        $.ajax({type: 'POST', url: '?do=change-password', data: 'p='+_p+'&h='+_h, dataType: 'json', success: function(_data) 
                        {
                                $('#loaderBg').hide();
                                
                                $('.info-error, .info-notice').remove();

                                if (_data.ok == 1)
                                {
                                        window.location='?do=home';
                                }
                                else
                                {
                                        $('#tbxPasswordContainer').append('<div class="info-error"><div class="clearer"/><p> '+_data.response+'<br/><br/></p></div>');
                                }
                        }
                        });
                        return false;
                }
                return false;
        });

        $('#tbxUser').autocomplete('?do=user-search', {
        scroll: true,
        matchContains: true,
        delay: 50,
        formatResult: function(data)
        {
          if (data == '...') {
                return $('#tbxUser').val();
          } else {
                return data;
          }
        }
  });
        
        $('#digitalTests div.dtLevel').click(function(_e)
        {
                var _target = $(_e.target);
                var _parent = _target.parent();
		  var _parent2 = _parent.parent();

			var check=_target;
			if(check.attr('id')=="") {
				check=_parent;
			}

		var open = getCookie("alfsavestate");

		if(check.attr('id').indexOf("res_")>=0) {
			open = getCookie("alfressavestate");
		}
		  
		  
                if (_target.hasClass('dtLevel') || _parent.hasClass('dtLevel') || _parent.hasClass('dtName'))
                {
                        var _that = $(this).closest('div.dtLevel');
                        _that.children().each(function()
                        {
                                var _this = $(this);
				    if (_this.hasClass('dtName'))
                                {
                                        if (!_this.hasClass('on'))
                                        {
                                                if (_that.hasClass('dtLevel1') || _that.hasClass('dtLevel2') ||
								_that.hasClass('dtLevel3') || _that.hasClass('dtLevel4'))
                                                {
								var _lev = $('#digitalTests div.dtLevel1');
								if(_that.hasClass('dtLevel2')) {
									_lev = $('#digitalTests div.dtLevel2');
								} else if(_that.hasClass('dtLevel3')) {
									_lev = $('#digitalTests div.dtLevel3');
								} else if(_that.hasClass('dtLevel4')) {
									_lev = $('#digitalTests div.dtLevel4');
								}
								_lev.not(_that).each(function()
								{
									var _theparent = $(this).parent();
		  							var _theparent2 = _theparent.parent();
									
								       $(this).children('.dtLevel,.dtItems').slideUp(500);
                                                               $(this).children('.dtLevel,.dtItemsRes').slideUp(500);

									if(_theparent.attr('id')==_parent2.attr('id')) {									
										$(this).children('.dtName').removeClass('on');								
									}

									if($(this).children('.dtLevel,.dtItems').attr('id')!="") {
										open = open.replace($(this).children('.dtLevel,.dtItems').attr('id')+",", "");
									}
									if($(this).children('.dtLevel,.dtItemsRes').attr('id')!="") {
										open = open.replace($(this).children('.dtLevel,.dtItemsRes').attr('id')+",", "");
									}
									if($(this).children('.dtName').attr('id')!="") {
										open = open.replace($(this).children('.dtName').attr('id')+",", "");
              							}
		                                          });
                                                }
                                        }
                                        _this.toggleClass('on');
                                }
                                else
                                {
                                        _this.slideToggle(500);
                                }
				    
                        });

			if(check.attr('id')!="") {

				if (check.hasClass('on')) {
				
					if(open.indexOf(check.attr('id')+",")<0) {
						open+=check.attr('id')+",";			    
					}

					if(check.attr('id').indexOf("res_")>=0) {
						setCookie("alfressavestate", open, 1);
					} else {
						setCookie("alfsavestate", open, 1);		  
					}   
				} else {
					
					open = open.replace(check.attr('id')+",", "");
					if(check.attr('id').indexOf("res_")>=0) {
						setCookie("alfressavestate", open, 1);
					} else {
						setCookie("alfsavestate", open, 1);		  
					}
				  }
			}

                        return false;
                }
        });
        
        _ms = $('#modalsubject');
	
	if (_ms.length)
	{
		_my = $('#modalyear');
		_mc = $('#modalclass');
		_mo = $('#modalother');
	
		_ms.dropdownchecklist({ emptyText:'Please select',icon:{},width:400,maxDropHeight:150,onComplete:updateSubjects});
		_my.dropdownchecklist({ emptyText:'Please select',icon:{},width:400,maxDropHeight:150,onComplete:updateYears});
	}
});


$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}

var sortExtraction = function(_node)  
{  
    // extract data from markup and return it  
	if ($(_node).hasClass('tableDate'))
	{
		return _node.id.substring(2);
	}
	
	return _node.innerHTML; 
} 

var html_entity_decode = function(str)
{
	try
    {
		var tarea=document.createElement('textarea');
      	tarea.innerHTML = str; return tarea.value;
      	tarea.parentNode.removeChild(tarea);
    }
    catch(e)
    {
      document.getElementById('htmlconverter').innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
      var content = document.getElementById("innerConverter").value;
      document.getElementById("htmlconverter").innerHTML = "";
      return content;
    }
}
var updateDropdown = function(_type,_sel)
{
	var _selected = [];
	for(_i=0;_i<_sel.options.length;_i++) 
	{
		if (_sel.options[_i].selected && (_sel.options[_i].value != '')) 
		{
			_selected.push(_sel.options[_i].value);
		}
	}
	
	switch (_type)
	{
		case 's':
			_selected_s = (_selected.length) ? '&gtype[]=Subject&gvalue[]='+_selected.join('&gtype[]=Subject&gvalue[]=') : '';
		break;

		case 'y':
			_selected_y = (_selected.length) ? '&gtype[]=National+Curriculum+Year&gvalue[]='+_selected.join('&gtype[]=National+Curriculum+Year&gvalue[]=') : '';
		break;

		case 'c':
			_selected_c = (_selected.length) ? _selected.join() : '';
		break;

		case 'o':
			_selected_o = (_selected.length) ? _selected.join() : '';
		break;
	}
	
	$('.ui-open').removeClass('ui-open');
	$('#modal_update_report').css('visibility','visible');

	_selected = [];
	
	return true;
}

var updateSubjects = function(_sel)
{
	var _old_s = _selected_s;
	updateDropdown('s',_sel);
	if (_old_s != _selected_s)
	{
		updateFilters();
	}
	else
	{
		setTimeout('enableDropdowns()', 500);
	}
}

var updateClasses = function(_sel)
{
	updateDropdown('c',_sel);
	setTimeout('enableDropdowns()', 500);
}

var updateOthers = function(_sel)
{
	updateDropdown('o',_sel);
	setTimeout('enableDropdowns()', 500);
}

var updateYears = function(_sel)
{
	var _old_y = _selected_y;
	updateDropdown('y',_sel);
	if (_old_y != _selected_y)
	{
		updateFilters();
	}
	else
	{
		setTimeout('enableDropdowns()', 500);
	}
}

var enableDropdowns = function()
{
	$('.ui-dropdownchecklist-selector-wrapper').removeClass('ui-dis');
}

var updateFilters = function()  
{  
	var _parameters = 's='+escape(_selected_y+_selected_s+_selected_c+_selected_o);
	$('#loaderBg').centerInClient().show();
	$('div#modalContainer').css('z-index',99991);
	$.ajax({type: 'POST', url: '?do=update-filters', data: _parameters, dataType: 'json', success: function(_data) 
	{
		_mc.dropdownchecklist('destroy');
		_mo.dropdownchecklist('destroy');
		_selected_c = '';
		_selected_o = '';
		if (_data.ok == 1 && (_selected_y.length || _selected_s.length))
		{
			if (_data.classes)
			{
				_mc.html(_data.classes);
				_mc.dropdownchecklist({ emptyText:'Please select',icon:{},width:400,maxDropHeight:150,onComplete:updateClasses});
			}
			
			if (_data.others)
			{
				_mo.html(_data.others);
				_mo.dropdownchecklist({ emptyText:'Please select',icon:{},width:400,maxDropHeight:150,onComplete:updateOthers});
			}
		}

		$('#loaderBg').hide();
		$('div#modalContainer').css('z-index',99992);
		enableDropdowns();
	}
	});
}

var setCookie = function(c_name,value,expiredays) {
	
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  var c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    var c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
