window.addEvent('load',  function() {

	$('FlashLoader').dispose();
	$('parent_container').removeClass('hideClass');
	
	
	var href = window.location.href;
	href = href.substr(href.indexOf("#",0));
		
	if( href.substr(0,1) == '#')
	{
		menu_hilight(href);
		
		//scroll down to the specific spot
		var scroll = new Fx.Scroll(window, { wait: false,  wheelStops: false, duration: 0, transition: Fx.Transitions.Quad.easeInOut });
		scroll.toElement(href.substr(1));
	}
}); 

window.addEvent('domready', function(){

	new SmoothScroll({duration: 2800,  wheelStops: false, wait: false});
		
	$$('a').addEvent('click',function(e){
	
		var href = this.get('href');
		href = href.substr(href.indexOf("#",0));
		
		if( href.substr(0,1) != '#')
			return;
			
		menu_hilight(href);
	});
	
	formcheck = new FormCheck('form1',{
					submitByAjax: true, onAjaxRequest: registration_start, onAjaxSuccess: registration_done,
					display : {indicateErrors: 1, scrollToFirst : false, flashTips : 1}
	});
	
	function registration_start()
	{
		$('submit').set('disabled','disabled');
		$('log_error').empty().addClass('ajax-loading');
	}
	
	function registration_done(response)
	{
		$('submit').set('disabled',false);
		$('log_error').removeClass('ajax-loading');
		$('log_error').set('html', response );
		
		if( response.substr(0,4) == '<ul>')
			$('log_error').addClass('error');
		else
			$('log_error').addClass('success');
	}
	
	init_star_rating();
	
	formcheck = new FormCheck('form_login',{
					display : {indicateErrors: 1, scrollToFirst : false, flashTips : 1}
	});
	
	formcheck = new FormCheck('form_register',{
					display : {indicateErrors: 1, scrollToFirst : false, flashTips : 1}
	});
	
	$('form_login').addEvent('submit',function(e){
		e.stop();
	});
	
	$('form_register').addEvent('submit',function(e){
		e.stop();
	});
});

function menu_hilight(href)
{
	if( ( href == '#home' ) || ( href == '#about' ) || ( href == '#participate' ) || ( href == '#helping' ) || ( href == '#faq' ) )
		$$('#menu_home img').set('src','images/menu_red/1_home.gif');
	else
		$$('#menu_home img').set('src','images/menu_grey/1_home.gif');
	
	if( href == '#register' )
		$$('#menu_register img').set('src','images/menu_red/2_register.gif');
	else
		$$('#menu_register img').set('src','images/menu_grey/2_register.gif');

	if( ( href == '#schools' ) || ( href == '#scoreboard' ))
		$$('#menu_schools img').set('src','images/menu_red/3_schools.gif');
	else
		$$('#menu_schools img').set('src','images/menu_grey/3_schools.gif');
		
	if( ( href == '#prizes' ) )
		$$('#menu_prizes img').set('src','images/menu_red/4_win.gif');
	else
		$$('#menu_prizes img').set('src','images/menu_grey/4_win.gif');
		
	if( ( href == '#corner' ) || ( href == '#videos' ) || ( href == '#diskidance' ) )
		$$('#menu_corner img').set('src','images/menu_red/5_yourcorner.gif');
	else
		$$('#menu_corner img').set('src','images/menu_grey/5_yourcorner.gif');
		
	if( ( href == '#bigfive' ) )
		$$('#menu_bigfive img').set('src','images/menu_red/6_big5.gif');
	else
		$$('#menu_bigfive img').set('src','images/menu_grey/6_big5.gif');
		
	if( ( href == '#tricstar' ) )
		$$('#menu_tricstar img').set('src','images/menu_red/7_trickstar.gif');
	else
		$$('#menu_tricstar img').set('src','images/menu_grey/7_trickstar.gif');
		
	if( ( href == '#info' ) || ( href == '#contactus' ))
		$$('#menu_info img').set('src','images/menu_red/8_info.gif');
	else
		$$('#menu_info img').set('src','images/menu_grey/8_info.gif');
}

function show_login()
{
	$('display_video').set('style','position: absolute; z-index: -100; display: none; ');
	$('video_login').set('style','position: absolute; display: block; z-index: 100;');
}

function show_add_comment()
{
	if( $('user_id').get('value') == "" || $('user_id').get('value') == "0" )
	{
		$('display_video').set('style','position: absolute; z-index: -100; display: none; ');
		$('video_login').set('style','position: absolute; display: block; z-index: 100;');
	}
	else
	{
		//$('add_comments').set('style','display: block');
		$('video_comments').set('html', $('add_comments').get('html'));
	}
}

function user_login()
{
	var login_request = new Request({
		url: 'video_login.php',
		method: 'post',
		update: 'refresh-me',
		onComplete: function(response) {

			if( response == "" || response == "0" )
			{
				alert("Invalid username or password");
			}
			else
			{
				$('video_login').set('style','display: none');
				$('display_video').set('style','display: table');
				$('user_id').set('value', response);
				
				$('login').addClass('hideClass');
				$('logout').removeClass('hideClass');
			}
		}
	})
	login_request.send('username=' + $('username').get('value') + '&password=' + $('password').get('value'));
}

function user_logout()
{
	$('user_id').set('value', '');
	$('login').removeClass('hideClass');
	$('logout').addClass('hideClass');
}

function user_register()
{
	if( ($('reg_username').get('value') == "") 
		|| ($('reg_password').get('value') == "")
		|| ($('reg_firstname').get('value') == "")
		|| ($('reg_surname').get('value') == "")
		|| ($('reg_cellno').get('value') == "")
	)
	{
		return;
	}

	var register_request = new Request({
		url: 'video_register.php',
		method: 'post',
		update: 'refresh-me',
		onComplete: function(response) {	

			if( isNaN(response) )
			{
				alert(response);
			}
			else
			{
				$('video_login').set('style','display: none');
				$('display_video').set('style','display: table');
				$('user_id').set('value', response);
				$('login').addClass('hideClass');
				$('logout').removeClass('hideClass');
			}
		}
	})
	register_request.send('username=' + $('reg_username').get('value') + '&password=' + $('reg_password').get('value') + '&firstname=' + $('reg_firstname').get('value') + '&surname=' + $('reg_surname').get('value') + '&cellno=' + $('reg_cellno').get('value') + '&email=' + $('reg_email').get('value') + '&school=' + $('reg_school').get('value') + '&big5=' + $('reg_big5').get('checked'));
}

function post_comment()
{
	var newcomment = new Request({
		url: 'video_comment.php',
		method: 'post',
		update: 'refresh-me',
		onComplete: function(response) {
			if(	response.length > 0 )
			{
				alert(response);
				$('display_video').set('style','position: absolute; z-index: -100; display: none; ');
				$('video_login').set('style','position: absolute; display: block; z-index: 100;');
			}
			else
			{
				load_video($('moostar').get('vid'));
			}
		}
	})
	newcomment.send('user_id=' + $('user_id').get('value') + '&video_id=' + $('moostar').get('vid') + '&comment=' + $('new_comment').get('value') );
}

function load_video(id)
{
	$('video_login').set('style','display: none');
	$('display_video').set('style','display: table');
	$('display_video').set('html',"<tr><td colspan='2' style='background: url(../scripts/spinner.gif) no-repeat center;'></td></tr>");
	
//	$('display_video').innerHTML = "<tr><td colspan='2' style='background: url(../scripts/spinner.gif) no-repeat center;'></td></tr>"
//	$('display_video').empty().set('style', 'height: 409px; background: url(../scripts/spinner.gif) no-repeat center;');

	var rating_request = new Request({
		url: 'video_load.php',
		method: 'get',
		update: 'refresh-me',
		onComplete: function(response) {		
					
						
			$('display_video').set('html',response);
			
			init_star_rating();
			
		}
	})
	rating_request.send('id=' + id);
}

function video_rating(id, rating) {

	if( $('user_id').get('value') == "" || $('user_id').get('value') == "0" )
	{
		$('display_video').set('style','position: absolute; z-index: -100; display: none; ');
		$('video_login').set('style','position: absolute; display: block; z-index: 100;');
	}
	else
	{
		var rating_request = new Request({
			url: 'video_rating.php',
			method: 'post',
			update: 'refresh-me',
			onComplete: function(response) {		
				moostar_enabled = false;
				
				$('moostar').getChildren()[0].setStyles({'width': (moostarwidth/moostarnum) *response});
				$('moostartval').set('html',response);
				
				$('thankyou').set('html',"Thank you for Voting");
				
			}
		})
		rating_request.send('rating=' + rating + '&video_id=' + id + '&user_id=' + $('user_id').get('value') );
	}
} 

function next_videos(type, page)
{
	//$('video_display_area').empty();
	//	$('video_display_area').set('style', 'height: 409px; background: url(../scripts/spinner.gif) no-repeat center;');
		
	if( type == 'new' )
	{
		var load_vids = new Request({
			url: 'video_load_new_thumbs.php',
			method: 'post',
			update: 'refresh-me',
			onComplete: function(response) {		
				$('new_videos').set('html',response);;
				
			}
		})
		load_vids.send('page=' + page);
	}
	else if( type == 'top' )
	{
		var load_vids = new Request({
			url: 'video_load_top_thumbs.php',
			method: 'post',
			update: 'refresh-me',
			onComplete: function(response) {		
				$('top_videos').set('html',response);
				
			}
		})
		load_vids.send('page=' + page);
	}
}



var moostarwidth= 84; // width of Star Rating container
var moostarnum = 5 // number of stars
var moostar_enabled = true;
	
function init_star_rating()
{
	moostar_enabled = true;
	
	$('moostar').set('revert',true);
			
	// Behavior for each star rating
	$('moostar').addEvents({
		'mousemove': function(event){
					
				if( moostar_enabled == false )
					return;
					
				w = event.page.x - this.getPosition().x;
							
				//status=event.client.x; //For test purpose only
				this.getChildren()[0].setStyles({'width': w});
										
				var x = (w/moostarwidth) * moostarnum;
				$('moostartval').set('html',Math.round(x));

		},
		'click': function(){ 
				if( moostar_enabled == false )
					return;
						
				video_rating(this.get('vid'), $('moostartval').get('html') );
				this.getChildren()[0].title = parseFloat($('moostartval').get('html'));
				this.set('revert',false);
		},
		'mouseleave': function(){
				if( moostar_enabled == false )
					return;
						
				//status ="left"; //For test purpose only
				if(this.get('revert'))
				{
					$('moostartval').set('html',parseInt(this.getChildren()[0].title));
					
					w = parseInt(this.getChildren()[0].title) * (moostarwidth/moostarnum);
					
					this.getChildren()[0].setStyles({'width': w});
				}
				this.set('revert',true);
		}
	});

}

function formatNumber(myNum, numOfDec) { var decimal = 1; for(i=1; i<=numOfDec;i++)decimal = decimal *10
  var myFormattedNum = (Math.round(myNum * decimal)/decimal).toFixed(numOfDec)
  return myFormattedNum;
} 
		
		
////// FORM CHECK

function numeric_only( field )
{
	if(field.value.match(/\D/))
		field.value = field.value.replace(/\D/g,'')
}

function PAN(el){
	
	if (!el.value.test(/^(5900|6007|4164)\d{12}$/)) {
		el.errors.push("Invalid Card Number"); 
		return false;
	} else {
		return true;
	}
}

function idnumber2(el){
	
	if (!el.value.test(/^\d{13}$/))
	{
		el.errors.push("Invalid ID number"); 
		return false;
	} 
	
	return true;
}

function idnumber(el){
	
	if (!el.value.test(/^\d{13}$/))
	{
		el.errors.push("Invalid ID number"); 
		return false;
	} 
	
	var month = el.value.substr(2,2);
	var day	  = el.value.substr(4,2);
	
	if( (month < 1) || (month > 12) || (day < 1) || (day > 31) )
	{
		el.errors.push("Invalid ID number"); 
		return false;
	}
	
	var a = 0;
	var b = 0;
	
	for(var i=0; i<6; i++)
	{
		a += parseInt(el.value[2*i]);
	}
	
	for(var i=0; i<6; i++)
	{
		b = b*10 + parseInt(el.value[2*i + 1]);
	}
	b = b * 2;
		
	var c = 0;
	do {
		c += (b % 10);
		b = Math.floor(b / 10);
	} while(b > 0);

	c = 10 - ((c + a) % 10);
	
	if(c == 10)
		c = 0;

	if( el.value[12] != c )
	{
		el.errors.push("Invalid ID number"); 
		return false;
	}

	return true;
}

function select_school_score(id)
{
	new Request({
		url: 'load_score.php',
		method: 'post',
		update: 'refresh-me',
		onComplete: function(response) {		

			$('score_block').set('html',response);
		}
	}).send('school_id=' + id);
}

function select_school(ref) {
	//e.stop();

	$$('.class_list').each(function(itm){
		itm.empty();
		itm.set('disabled',false);
	});
		
	if( ref == -1 )
	{
		$$('.class_list').set('disabled','disabled');
	}
	else
	{
		new Request.JSON({
			url: 'list_classes.php',
								
			onComplete: function(jsonObj) {

				jsonObj.each(function(json_option) {

					var option = new Element('option', {'html': json_option.html, '_school': json_option.school, 'value':json_option.value});
					
					$$('.class_list').each(function(opt){
						option.inject(opt,'top');
					});
					
				});
			}
		}).send("school=" + ref);
	}
}

function select_class()
{
	var value;
	
	$$('.class_list').each(function(itm){
	
		if( itm.get('value') != '')
		{
		/*	$('school').set('disabled',false);
			$('class').set('disabled',false);
			*/
			itm.getElements('option').each(function(opt){
				if( opt.get('value') == itm.get('value') )
				{
					var el = new Element('div', {'id': 'class_' + opt.get('value'), 'html': '<img src="images/delete.png" alt="delete" title="delete" class="button_remove" onclick="class_remove(\'class_' + opt.get('value') + '\');" /> ' + opt.get('_school') + ' - ' + opt.get('html') + '<input type="hidden" name="class_' + opt.get('value') + '" value="' + opt.get('value') + '" />' });
			
					$('school_class_list').adopt(el,'top');
				}
			});
		}
	});

	TB_remove();
}

function enter_class_code()
{
	$$('.class_code').each(function(itm){
	
		if( itm.get('value') != '')
		{
		
			new Request.JSON({
				url: 'list_classes.php',
									
				onComplete: function(jsonObj)
				{
					if( jsonObj == null )
						alert("Invalid 'Class Code'");
					else
					{
						jsonObj.each(function(json_option){
							
							var el = new Element('div', {'id': 'class_' + json_option.value, 'html': '<img src="images/delete.png" alt="delete" title="delete" class="button_remove" onclick="class_remove(\'class_' + json_option.value + '\');" /> ' + json_option.school + ' - ' + json_option.html + '<input type="hidden" name="class_' + json_option.value + '" value="' + json_option.value + '" />' });
			
							$('school_class_list').adopt(el,'top');
							TB_remove();
						});
					}
				}
			}).send("classcode=" + itm.get('value') );
		}
	});
}

function class_remove(class_name)
{
	$(class_name).dispose();
}