// contest.js
// version 1.0.2
// last update: April 15th 2010



// Form Validator

function handleValidation(element,message) {


	// For more discriptive validation errors
	// Make sure the error message's first word is the element's name attribute
	
	//the forms language
	var lang = $('language').value;
	//console.log(lang);
	if(lang == 'en'){
		//console.log('english');
		//console.log('english message -> '+message);

	}else if(lang == 'fr'){
		//console.log('french');
		
		//This is for the validation depending on if french of english urls used
		message = message.replace("is a required field","est un champ obligatoire.");
	    message = message.replace("does not contain a valid Canadian postal code","ne contient pas de code postal canadien valide.");
	    message = message.replace("does not contain a valid phone number","ne contient pas de numéro de téléphone valide.");
	    message = message.replace("does not contain a valid email address","ne contient pas une adresse email valide.");
	    message = message.replace("The captcha you entered was invalid, please try again","Le captcha que vous avez entré est incorrect. Veuillez SVP essayer de nouveau.");
	    message = message.replace("The email address supplied is already registered. Did you forget your login information?","Le courriel que vous avez inscrit a déjà été utilisé. Veuillez SVP utiliser la section Me connecter pour participer à nouveau.");
	    message = message.replace("does not have a valid date","n'a pas une date valide.");
	    message = message.replace("Your password needs to be at least 6 characters long","Votre mot de passe doit contenir au minimum 6 caractères.");
	    message = message.replace("The passwords did not match","Les mots de passe ne correspondent pas.");
	    message = message.replace("The email fields do not match","Les emails ne correspondent pas");
	    message = message.replace("A username has to be a minimum of 6 characters, can only contain A-Z 0-9 and _ (underscore) and has to start with a letter","Le nom d'utilisateur doit contenir au minimum 6 caractères du type A-Z 0-9 and _ (underscore) et doit commencer par une lettre");
	    message = message.replace("The username you picked was already taken. Please try something else","Le nom d'utilisateur que vous avez saisi est déjô utilisé. Veuillez recommencer.");
		message = message.replace("The email or password you specified were incorrect","L'email ou le mot de passe indiqués sont incorrects.");
	    
	    // Translate the field names
	    message = message.replace("firstname","Prenom");
	    message = message.replace("lastname","Nom");
	    message = message.replace("email","Courriel");
	    message = message.replace("phonenumber", "T&eacute;l&eacute;phone");
	    message = message.replace("meta[birthyear]", "Ann&eacute;e de naissance");
	    message = message.replace("gender", "Sexe");
	    message = message.replace("meta[CodePostal]", "Code postal");
	    message = message.replace("password", "Mot de passe");
	    message = message.replace("confirm", "Confirmer le mot de passe");
	    // Add more here translations here.

		//console.log('the message has ben translated into french, the following-> ' + message);
	}


	// we check if it already has the error class to prevent multiple messages appearing on the same element
	if (!element.hasClassName('errorField')) {
	
		// the name of the element
		var name = message.substr(0,message.indexOf(' '));
		
		// the actually error message
		var originalMessage = message;
		var message = message.substr(message.indexOf(' '));
		
		// if its a checkbox, don't highlight the element but highlight the text beside it
		if (element.type == "checkbox") {
			var label = $(element).next();
		} else {
			var label = $(element).up(0).previousSiblings()[0].down(0);
		}
		
		// the title we're going to use
		var title = element.title;
		
		// without *
		var titlesub = title.substr(0,title.indexOf('*'))
		
		// the output
		var out = '';
		
		// check the message and output the right title and message combo
		if (name == element.name && title) {
			if (message != "The email address supplied is already registered. Did you forget your login information?" && message.substr(1,8) != "username" && message.substr(0,11) != "The captcha") {
				if (title.indexOf('*') > -1) {
					out = titlesub+" "+message;
				} else {
					out = title+message;
				}
			} else if (message == "The email address supplied is already registered. Did you forget your login information?") {
				out = "The email address supplied is already registered.";
			} else {
				out = titlesub+" "+message;
			}
		} else {
		
			if (message.substr(1,8) === "username" && message.substr(14,6) !== "picked") {
				out = titlesub+" "+message.substr(10);
			} else	if (message.substr(1) === "passwords did not match") {
				out = "P"+message.substr(2);
			} else if (element.type == "checkbox") {
				out = titlesub+message;
			} else {
				out = originalMessage;
			}
		}
		
		// get all the labels in this from
		var labels = element.form.getElementsByTagName('label');
		for(var i=0;i<labels.length;i++) {
			// check all the labels for the one that matches the failed form element
			if (labels[i].htmlFor==element.id) {
				// put the message inside the label
				//if (element.type != "checkbox") {
					labels[i].innerHTML = out;
				//}
				// make the label stand out
				labels[i].addClassName('error');
				// remove the old border-color
				// this fixes an issue when fading out the border
				element.setStyle({'borderColor':''});
				// make the input stand out
				element.addClassName('errorField');
				// scroll the browser to that element.
				labels[i].scrollTo();

			}
		}
	
		// remove the styles from the failed form element and the label
		function removeStyles(t) {
			// search though all the labels again
			for(var i=0;i<labels.length;i++) {
				// find the label that matches the failed form element
				if (labels[i].htmlFor==element.id) {
					// return everything to normal
					labels[i].innerHTML = t;
					labels[i].removeClassName('error');
					element.removeClassName('errorField');
				}
			}
		}

	}

	// we want the element and label to retrun to normal when the user relizes the error.
	element.observe('focus', function(event) {
		removeStyles(title);
	});
}



// Search form

function searchFormClick(e,x) {
	// check to see if the text input value is equal to the default value
	if (e.value == x) {
		// if they are the same, remove the default value and the grey text colour
		e.value = '';
		e.removeClassName('searchgrey');
	}
}

function searchFormBlur(e,x) {
	// check if the text input doesn't have a value
	if (e.value == '' || !e.value || e.value == null) {
		// if theres no value, add the default value and the grey text colour
		e.value = x;
		e.addClassName('searchgrey');
	}
}



// Vote

function fmVote(element, mid) {
	// check if the user has already voted
	if ($(element).disabled == true) {
		// this should be replaced with something more user friendly
		alert($('voteDisabled').value);
	} else {
		// disable the button to prevent multiple votes
		$(element).disabled = true;
		// set the parameters
		var params = {
			"mid" : mid,
			"vote" : 1
		}
  		// make the service call
		jsonRequest('media.vote', params,
			function(result) { 
				$(element).addClassName("disabled");
				$(element).innerHTML = $('voteResult').value;
			},
			function(exception) { 
				exception(exception);
			},
			true
		);


	}
}


// oops, something went wrong
function exception(exception) {
	alert(exception);
}


// Like comment

function fmLike(mid, uid) {
	// if the user isn't logged in display the error message asking them to log in
	if (uid == 1) {
		alert($('loginLike').value);
	} else {	
		if (!$('vote'+mid).next().hasClassName("disabled")) {
			$('vote'+mid).next().addClassName("disabled");
			$('vote'+mid).innerHTML = parseInt($('vote'+mid).innerHTML)+1;
			jsonRequest('media.rateFile', {"id":mid,"rating":10,"returnData":true},
	    		function(result) {
	    			// change the number after the action has been successful
	    			// $('#vote'+mid).innerHTML = result.votecount;
	    		},
	    		function(exception) { console.log(exception); }
	  		);
  		}
	}
}


// Ajax commenting

function ajaxComments(element, obj) {
	url = "/ajax_comments";
	vars = obj;
	new Ajax.Request(url, {
		method: 'get',
		parameters: vars,
		onSuccess: function(transport) {
			$(element).innerHTML = transport.responseText;
		}
	});

}

// Ajax form for Send to a Friend

function ajaxform(x) {
	// set the vars
	var vars  = Form.serializeElements($(x).getElements());
	// get the action url
	var url = $(x).action;
	// send the form using ajax
	new Ajax.Request(url, {
		method: 'post',
		postBody: vars,
		onSuccess: function(transport) {
			// hide the form and show the message that the email was sent
			x.hide();
			x.next(0).show();
		}
	});

}


var InputLimit = Class.create();

InputLimit.prototype = {
	initialize: function(settings) {
	
		var e = settings.element;
		var maxLengthNumber = settings.limit;
		var maxLengthCountdown = settings.countdown;
	
		$(e).observe('keydown', function(event,e) {
			str = this.value;
			if (str.length > maxLengthNumber && (e.keyCode != 8 || e.keyCode != 46)) {
				$(this).value = str.substr(0,maxLengthNumber);
			}
		});
		
		$(e).observe('keyup', function(event) {
				
			var str = $(this).value;
			var out;
			
			if (str.length > maxLengthNumber && (e.keyCode != 8 || e.keyCode != 46)) {
				$(this).value = str.substr(0,maxLengthNumber);
			}
			
			var len = str.length;
					
			if (len > maxLengthNumber) {
				len = maxLengthNumber;
			}
			
			if (maxLengthCountdown === true) {
				if (len/maxLengthNumber*100 >= 75) {
					out = '<span class="fmWarning">'+(maxLengthNumber - len)+'</span>';
				} else {
					out = maxLengthNumber - len;
				}
			} else {
				if (len/maxLengthNumber*100 >= 75) {
					out = '<span class="fmWarning">'+len+'</span>/'+maxLengthNumber+'';
				} else {
					out = len+'/'+maxLengthNumber;
				}
			}
			
			$('fmCommentLength').down(0).innerHTML = out;
	
		});
	}

}

// Report as offensive

function fmSendReport(mid,reason) {
	if (reason === '' || !reason) {
		$('fmReportReason').addClassName('errorField');
		$('fmReportReason').observe('change',function() {
			$(this).removeClassName('errorField');
		});
	} else {	
		// find the report button
		var btn = $$('#fmReportBox .fmButtonSm')[0];
		// stop the ninja clicking
		if (btn.readAttribute('disabled') != "disabled") {	
			btn.writeAttribute('disabled','disabled');
			// add the loading image to the 'report' button
			btn.setStyle({'width':btn.getWidth()-1+"px"});
			btn.innerHTML = '<span><img src="/static/contest/images/loading.gif" class="fmLoading"/></span>';
			// send the request
			args = 'reason='+reason+'&mid='+mid+'&sendto=ashutsa';
			
			new Ajax.Request('/action/v2/reportoffensive', {
				method: 'post',
				postBody: args,
				onSuccess: function(data) {
					
					// hide the buttons and the select element
					$('#fmReportBox').find('select').remove();
					$('#fmReportBox').find('.fmButton').remove();
					data = jQuery.parseJSON(jQuery.trim(data));
				    if (data.result) {
				    	// remove the 'report' link from the comment 
				   		$('#fmReportBox').prev('.fmReport').remove();
				    	$('#fmReportBox').find('p').text(translate[6][4]);
				    	if (reportFade === true) {
				    		$('#fmReportBox').delay(5000).fadeOut(500);
				    	} else {
				    		$('#fmReportBox').remove();
				    	}
				    } else {
				    	btn.removeAttr("disabled");
				    	$('#fmReportBox').find('p').text(translate[6][5]);
				    }
					
				}
			});
			
		}
	}
}

function fmReport(mid, uid, e, type) {
	//
	if ($('fmReportBox')) {
		$('fmReportBox').remove();
	}
	//
	var selectBox = '<option value="">---</option>';
	//
	for (i=0;i<reportReasons[0].length;i++) {
		selectBox += '<option value="'+reportReasons[0][i]+'">'+reportReasons[1][i]+'</option>';
	}
	//
	
	if (type == 'entry') {
		text = reportReasons[2][2];		
	} else {	
		text = reportReasons[2][1];	
	}
	
	//
	$(e).insert({'after':'<div id="fmReportBox" class="fmClearfix"><div class="fmTitle">'+reportReasons[2][0]+'</div><span class="report" onclick="$(\'fmReportBox\').remove();">'+reportReasons[2][4]+'</span> <p>'+text+'</p><select class="fmSelect" name="reason" id="fmReportReason" style="width:100%;">'+selectBox+'</select><a class="fmButtonSm r" onclick="fmSendReport('+mid+',$(\'fmReportReason\').value); $(\'fmReportBox\').remove();"><span>'+reportReasons[2][3]+'</span></a><a class="fmButtonSm" onclick="$(\'fmReportBox\').remove();"><span>'+reportReasons[2][4]+'</span></a></div>'});
}



// Tabbed gallery class

var Gallery = Class.create();

Gallery.prototype = {
	initialize: function(e) {
		this.element = $(e);
		this.element.childElements().each(function(e,i) {
			if (i > 1) {
				e.hide();
			}
		});
		this.tabs = this.element.down(1).childElements();
		this.tabs.each(function(e,i) {
			e.observe('click', function(event) {
				this.siblings().each(function(f,j) {
					f.removeClassName('active');
				});
				this.addClassName('active');
				this.up(2).childElements().each(function(f,j) {
					if (j > 0) {
						f.hide();
					}
				});
				this.up(2).childElements()[i+1].show();
			});
		});
	}
}


// Send to a friend

function sendToAFriend(e) {
	// gather all the form fields to be sent
	var vars  = Form.serializeElements($(e).getElements());
	// find what action the form is using
	var url = $(e).action;
	// if the form passes validation
	if(Validator_SendToFriend.submit($(e))){
		// send the request via Ajax
		new Ajax.Request(url, {
			method: 'post',
			postBody: vars,
			onComplete: function(transport) {
				console.log("done!");
				// hide the form and show the message that the email was sent
				$(e).hide();
				$(e).next(0).show();
			}
		});
		
	}
}


// Super simple Filemobile lightbox

function fmLightbox(obj) {

	// require the element that is going to appear in the lightbox
	if (!obj.element) {
		// remind the developer they need the element
		alert("Invalid Lightbox Parameter: Please pass element you wish to appear in the lightbox.");
		return false;
	} else {
		// create the element variable
		var element = obj.element;
	}

	
	// set the callback function if one is requested
	if (obj.callback) {
		var callback = obj.callback;
	}
	
	// remove the lightbox if it already exists for some reason
	if ($('lightbox_background')) {
		$('lightbox_background').remove();
		$('lightbox_inside').remove();
	}

	document.getElementsByTagName('html')[0].className = 'lightboxOn';
	
	// add a placeholder to the current position of the element
	$(element).insert({'after':'<div id="lightbox_placeholder"></div>'});
	
	// add the lightbox at the end of the page
	$('body').insert({'bottom':'<div class="background" id="lightbox_background"></div><div id="lightbox_inside" class="inside"></div>'});
	// get the width and height of the element so we can resize the lightbox window to that size
	var height = $('emailtoafriend').getHeight();
	var width = $('emailtoafriend').getWidth();	
	
	// resize and position the lightbox, add the element to the lightbox and make sure it's visible and add the close button
	$('lightbox_inside').setStyle({'width':width+'px','height':height+'px','marginTop':-(height/2)+'px','marginLeft':-(width/2)+'px'}).insert({'top':element}).insert({'bottom':'<div class="close" id="lightbox_close"></div>'}).firstDescendant().show();	
	
	// close the lightbox
	function closeLightbox() {
	
		//
		document.getElementsByTagName('html')[0].className = '';
		
		//hides the thank you message and displys the email form again
		//back to default
		$('emailform').reset();
		$('thanksforemail').hide();
		$('emailform').show();
		
		// hide the lightbox contents
		$('lightbox_inside').firstDescendant().hide();
		
		// move the lightbox contents back it's original position and remove the placeholder
		$('lightbox_placeholder').insert({'after':element}).remove();
		
		// remove the lightbox
		$('lightbox_background').remove();
		$('lightbox_inside').remove();
		
		// if we requested a callback function in the options, then run it
		if (callback != null) {
			callback();
		}
		
	}	
	
	// add the close function when the user hits the 'x'
	$('lightbox_close').observe('click',function() {
		closeLightbox();
	});	
	
	// add the close function when the user hits the background of the lightbox
	$('lightbox_background').observe('click',function() {
		closeLightbox();
	});
	
}

