// settings main object ( Private methods )	
///////////////////////////////////////////////////////////////////////////
var contestSettings = (function(){
	
	var defaultUrl;
	var userid;
	var userGrade;
	var subscribeUrl;
	var unsubscribeUrl;
	var uploadAreaUrl;
	var entryListUrl;
	var loaderGif;
	var deleteEntryUrl;
	var ajaxErrorMsg;
	
	return function( options ){

		this.getDefaultUrl = function(){
			return defaultUrl;	
		};
		
		this.getUserid = function(){
			return userid;	
		};

		this.getUserGrade = function(){
			return userGrade;	
		};
		
		this.getSubscribeUrl = function(){
			return subscribeUrl;			
		};
		
		this.getUnsubscribeUrl = function(){
			return unsubscribeUrl;			
		};

		this.getUploadAreaUrl = function(){
			return uploadAreaUrl;			
		};

		this.getEntryListUrl = function(){
			return entryListUrl;			
		};

		this.getLoaderGif = function(){
			return loaderGif;			
		};

		this.getDeleteEntryUrl = function(){
			return deleteEntryUrl;			
		};		
		
		this.getAjaxErrorMsg = function(){
			return ajaxErrorMsg;			
		};

							
		defaultUrl = options.defaultUrl;
		userid = options.userid;
		userGrade = options.userGrade;
		subscribeUrl = options.subscribeUrl;
		unsubscribeUrl = options.unsubscribeUrl;
		uploadAreaUrl = options.uploadAreaUrl;
		entryListUrl = options.entryListUrl;
		loaderGif = options.loaderGif;
		deleteEntryUrl = options.deleteEntryUrl;
		ajaxErrorMsg = options.ajaxErrorMsg;
	};

})();


// contest main object ( first to be loaded )	
///////////////////////////////////////////////////////////////////////////
var contestManager = function(){};

//load the left menu with the contests situation for the user logged
contestManager.prototype = {
	
	init : function(options){
			contestManager.settings =  new contestSettings(options);
			contestManager.prototype.setUp();
	},

	setUp : function() {
			
			contestManager.helper.blockUI();
			
			var url = contestManager.settings.getDefaultUrl() + '?uuserId=' + contestManager.settings.getUserid();
			contestManager.helper.ajaxCall( url , 'html' , contestManager.handlers.leftLoadHandler , contestManager.handlers.ajaxErrorHanlder );
	
			},

	// Subscribe to the passed contest
	subscribe: function( contestId , msg ){
	
			
			var box = new contestManager.helper.confirmBox( msg , function(){
			
				var url = contestManager.settings.getSubscribeUrl() + '?uuserId=' + contestManager.settings.getUserid() + '&contestId=' + contestId;
				contestManager.helper.ajaxCall( url , 'json' , contestManager.handlers.subscribeHandler , contestManager.handlers.ajaxErrorHanlder );				
			
			})
			
			box.show();
			
	},
	
	// UnSubscribe to the passed contest
	unsubscribe : function ( contestUserId , msg ){
		
			var box = new contestManager.helper.confirmBox( msg , function(){
				
				var url = contestManager.settings.getUnsubscribeUrl() + '?contestUserId=' + contestUserId;
				contestManager.helper.ajaxCall( url , 'json' , contestManager.handlers.unsubscribeHandler , contestManager.handlers.ajaxErrorHanlder );
			
			})
			
			box.show();
				
		},

	// UnSubscribe to the passed contest
	cannot_unsubscribe : function ( msg ){

			var box = new contestManager.helper.alertBox( msg )

			box.show();

		},

	// Load the upload area
	loadUploadArea : function ( contestId , cleanMsg){
			
			var cleanMsg = cleanMsg || false;
			
			// save reference to the contestId
			contestManager.settings.contestid = contestId;
			
			// block the UI
			contestManager.helper.blockUI();
	
			var url = contestManager.settings.getUploadAreaUrl() + '?uuserId=' + contestManager.settings.getUserid() + '&contestId=' + contestManager.settings.contestid + '&userGrade=' + contestManager.settings.getUserGrade();
			contestManager.helper.ajaxCall( url , 'html' , contestManager.handlers.uploadAreaHandler , contestManager.handlers.ajaxErrorHanlder );
		
			if (cleanMsg == true) {
				// clean the message box
				contestManager.helper.cleanMsgBox();
			}
		},
	
	loadEntries : function (){
			
			// ui block is made over cause loadEntries is always a callback of others events
			
			var url = contestManager.settings.getEntryListUrl() + '?contestUserId=' + contestManager.settings.contestUserId + '&contestId=' + contestManager.settings.contestid;
			contestManager.helper.ajaxCall( url , 'html' , contestManager.handlers.loadEntriesHandler , contestManager.handlers.ajaxErrorHanlder );
		
	},
	
	deleteEntry : function( msg , assetid ){
		
		var box = new contestManager.helper.confirmBox( msg , function(){
		
			var url = contestManager.settings.getDeleteEntryUrl() + '?assetid=' + assetid + '&contestUserId=' + contestManager.settings.contestUserId + '&contestId=' + contestManager.settings.contestid;
			contestManager.helper.ajaxCall( url , 'json' , contestManager.handlers.deleteEntryHandler , contestManager.handlers.ajaxErrorHanlder );

		})		
		
		box.show();
	},
	
	editEntry : function( assetid , elem ){

		// get the form inside the div to show
		var editForm = jQuery(elem).find('form');

		// validate it
		var options = {
			dataType:'json',
			cache: false,
			success: contestManager.handlers.editEntryhandler,
			error: contestManager.handlers.ajaxErrorHanlder							
 		}
						  												 
		jQuery(editForm).validate({
			errorLabelContainer: jQuery(editForm).prev(),
			errorElement : "p",
			submitHandler: function(form) {
					jQuery(form).ajaxSubmit(options);
			}
		});

		var blockBox = new contestManager.helper.editForm( elem );
		
	},
	
	showClassWorkAges : function(el,index){
		
		var val = jQuery(el).val();
		var elToHide = jQuery('.oldestStudent_' + index);
		
		if(val == 0){
			elToHide.slideUp();
			elToHide.find('.maxAgeForClassWork').removeClass('required');		
		}else{
			elToHide.slideDown();
			elToHide.find('.maxAgeForClassWork').addClass('required');					
		}
		
		var f = jQuery('.uploadForm_' + index);
		
		jQuery(f).validate({
			errorLabelContainer: jQuery(f).prev(),
			wrapper: 'p',
			submitHandler: function(form) {
					//block the ui
					contestManager.helper.blockUI();
					jQuery(form).ajaxSubmit(options);
			}
		});

	}
		
};

	
// contest handler class	
///////////////////////////////////////////////////////////////////////////
contestManager.handlers = {};	

contestManager.handlers.subscribeHandler = function(responseText, textStatus){
		if(responseText[0].STATUS){
			// refresh the left region
			contestManager.prototype.setUp();
			// show the success message
			contestManager.helper.writeInMsgBox(responseText[0].TEXT);
			//unblock the UI
			contestManager.helper.unblockUI();

		}else{

			// show the error message
			contestManager.helper.writeInMsgBox(responseText[0].TEXT);

		}
	}

contestManager.handlers.unsubscribeHandler = function ( responseText, textStatus ){
		if(responseText[0].STATUS){
			// refresh the left region
			contestManager.prototype.setUp();
			// clean the center region
			jQuery('#dashBoardRight').empty();
			//show teh success message
			contestManager.helper.writeInMsgBox(responseText[0].TEXT);
			//unblock the UI
			contestManager.helper.unblockUI();
		}else{
			//show the message
			contestManager.helper.writeInMsgBox(responseText[0].TEXT);
			//unblock the UI
			contestManager.helper.unblockUI();
		}

	}

contestManager.handlers.leftLoadHandler = function (responseText, textStatus){	
		
		// show the ajax result in the left region	
		jQuery('#dashBoardLeft').html(responseText);
		
		// attach events to injected html
		jQuery('.manageContest').click(function(){
			contestId = jQuery(this).attr("rel");
			contestManager.prototype.loadUploadArea( contestId , true );	
		});
		
		// subscribe
		jQuery('.subscribe').click(function(){				
			var contestId = jQuery(this).attr('rel');
			var msg = jQuery(this).attr('title');
			contestManager.prototype.subscribe( contestId , msg );			
		});
		
		// unsubscribe
		jQuery('.unsubscribe').click(function(){
			contestUserId = jQuery(this).attr('rel');
			var msg = "Are you sure do you want to unsubscribe? All the info and files will be permanently deleted.";
			contestManager.prototype.unsubscribe( contestUserId , msg );
					
		});

		// cannot_unsubscribe
		jQuery('.cannot_unsubscribe').click(function(){
			contestUserId = jQuery(this).attr('rel');
			var msg = "You cannot unsubscribe from a closed contest.";
			contestManager.prototype.cannot_unsubscribe( msg );
					
		});
		
		contestManager.helper.applyTypography();
						
		contestManager.helper.unblockUI();

	}

contestManager.handlers.uploadAreaHandler = function(responseText, textStatus){
		
		jQuery('#dashBoardRight').html(responseText);
		
		//set the tabs behaviour
		jQuery('#tabs  ul').tabs();

		// get the number of forms to validate
		var formsToValidate =  jQuery('.uploadForm');
		
		for( var i=0 ; i < formsToValidate.length ; ++i){

			var f = formsToValidate[i];
			var target = jQuery("#ajaxContent");
			
			var options = {
				dataType:'json',
				cache: false,
				// upload success handling
				success: function(responseText, statusText){
					if (responseText[0].STATUS) {
						//reload uplaod area
						contestManager.prototype.loadUploadArea(contestManager.settings.contestid , false);
						//unblock the UI
						contestManager.helper.unblockUI();
						// write out the result
						contestManager.helper.writeInMsgBox(responseText[0].TEXT);

					}else{
						// write out the result
						contestManager.helper.writeInMsgBox(responseText[0].TEXT);
						//unblock the UI
						contestManager.helper.unblockUI();
					}	
				},
				error: contestManager.handlers.ajaxErrorHanlder							
	 		}; 
				  												 
			jQuery(f).validate({
				errorLabelContainer: jQuery(f).prev(),
				errorElement : "p",
				submitHandler: function(form) {
						//block the ui
						contestManager.helper.blockUI();
						jQuery(form).ajaxSubmit(options);
				}
			});
		
		}//end loop	

	
	// get parameters from the page load
	contestManager.prototype.loadEntries();
	
	
}

contestManager.handlers.loadEntriesHandler = function (responseText, textStatus){			
		jQuery('#entries').html(responseText);
		
		// attach delete entry event
		jQuery('.deleteEntry').click(function(){
			var assetid = jQuery(this).attr('rel');
			var msg = jQuery(this).attr('title');
			contestManager.prototype.deleteEntry( msg , assetid );
		});
		
		jQuery('.editEntry').click(function(){
			var assetid = jQuery(this).attr('rel');
			var divId = '_' + assetid + 'entryFormDiv';
			var elem = jQuery('#' + divId );
			contestManager.prototype.editEntry( assetid , elem );
		});
		
		// attach th event to the X for unblock
		jQuery('.closeForm').click(function(ev){
			ev.preventDefault();
			contestManager.helper.unblockUI();
		});
		
		contestManager.helper.applyTypography();
			
		//unblock the UI
		contestManager.helper.unblockUI();

	}

contestManager.handlers.deleteEntryHandler = function(responseText, textStatus){							
			if(responseText[0].STATUS){
				//reload upload area ( also relaod entry list )
				contestManager.prototype.loadUploadArea( contestManager.settings.contestid );
				// write out the message
				contestManager.helper.writeInMsgBox(responseText[0].TEXT);
				//unblock the UI
				contestManager.helper.unblockUI();
			
			}else{
				// write out the message
				contestManager.helper.writeInMsgBox(responseText[0].TEXT);
				//unblock the UI
				contestManager.helper.unblockUI();
			}
	
	}

contestManager.handlers.editEntryhandler = function(responseText, textStatus){
			if(responseText[0].STATUS){
				//reload the entries list to update the local data
				contestManager.prototype.loadEntries();
				// write out the message
				contestManager.helper.writeInMsgBox(responseText[0].TEXT);
				//unblock the UI
				contestManager.helper.unblockUI();
			
			}else{
				// write out the message
				contestManager.helper.writeInMsgBox(responseText[0].TEXT);
				//unblock the UI
				contestManager.helper.unblockUI();
			}
	
}

contestManager.handlers.ajaxErrorHanlder = function(){
		//unblock teh UI area
		jQuery('#contestUi').unblock();
		//place the default error message in the messages box		
		jQuery('#mainMessage').html(contestManager.settings.getAjaxErrorMsg());

	}

	

// contest helper class	
///////////////////////////////////////////////////////////////////////////
contestManager.helper = {};

contestManager.helper.ajaxCall = function( url , dataType , success , error){
	jQuery.ajax({
		url : url ,
		dataType : dataType,
		cache : false,
		success : success,
		error : error							
		});
	}

contestManager.helper.confirmBox = function( msg , fn ){
		
		var text = msg ;
		var fn = fn ;
		
		// reset the text of the box
		jQuery('div#blockBox #textBox').text( text );
		
		//remove previous events and attach new evs to both teh buttons
		jQuery('div#blockBox #yesBtn').unbind();
		jQuery('div#blockBox #noBtn').unbind();
		
		jQuery('div#blockBox #yesBtn').click(function(){		
			contestManager.helper.unblockUI();
			eval(fn());
		});
				
		jQuery('div#blockBox #noBtn').click(function(){
			jQuery('#contestUi').unblock();
		});
		
	
		this.show = function(){

			contestManager.helper.blockUI(jQuery('div#blockBox'));

		};
		
	}

contestManager.helper.alertBox = function( msg ){

		var text = msg ;

		// reset the text of the box
		jQuery('div#alertBox #textBox').text( text );

		//remove previous events and attach new evs to both teh buttons
		jQuery('div#alertBox #yesBtn').unbind();

		jQuery('div#alertBox #yesBtn').click(function(){		
			contestManager.helper.unblockUI();
		});


		this.show = function(){

			contestManager.helper.blockUI(jQuery('div#alertBox'));

		};

	}

contestManager.helper.editForm = function( elem){

		contestManager.helper.blockUI(elem, {
			backgroundColor: '#FFFFFF',
			color : '#CCCCCC',
			padding:15,
			width:600			
		});
	
	}
	
contestManager.helper.blockUI  = function( msg, css ){
	
	css = css || { 
		backgroundColor: '#000000',
		color : '#CCCCCC',
		padding:15
	}
	
	this.msg = msg || contestManager.settings.getLoaderGif();
		
	jQuery('#contestUi').block({
		message : this.msg,
		overlayCSS: {
			backgroundColor: '#FFFFFF'
		},
		css : css
    });

	}

contestManager.helper.unblockUI  = function(){
	jQuery('#contestUi').unblock();
	
	}

contestManager.helper.cleanMsgBox = function(){
	jQuery('#mainMessage').empty();	
	}

contestManager.helper.writeInMsgBox = function (text){	
	jQuery('#mainMessage').html(text);	
	}

contestManager.helper.applyTypography = function(){
	Cufon.set('fontFamily', 'ColaborateLight');
	Cufon.replace('h2, #main h3, h4, h5, h6, #slogan, .label', {
		hover: true
	});

	Cufon.set('fontFamily', 'Colaborate-Medium');
	Cufon.replace('#main_home h3', {
		hover: true
	});
	
}
