// FM Contest JS
// Version: 2.3.2
// Updated: March 16 2011
// By: Jshaw
	// Updated handleValidation function to account for recaptcha sendtoafriend
	// added variable to keep track of recaptcha state
	// updated sendtoafriend function to use recaptcha
	// march 16
	// province validation

//keeps track of recaptcha state
var imageCaptcha = 1;
var audioCaptcha = 0;

// 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
	
	var lang = $('language').value;
	
	if(lang == 'en'){

	}else if(lang == 'fr'){
		
		//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.
	}
	
	// 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 if (element.id == 'recaptcha_response_field') {
			
			if(imageCaptcha == 1){
				var label = $(element).previous(3);
			}else{
				var label = $(element).previous(2);
			}

			label.addClassName('error');
			
		}else if(element.id == "province" || element.id == "state_province"){
			var label = $('stateLabel');
		}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) {
				labels[i].innerHTML = out;
				labels[i].addClassName('error');
				
				// remove the old border-color
				// this fixes an issue when fading out the border
				element.setStyle({'borderColor':''});
				element.addClassName('errorField');
				labels[i].scrollTo();
			}else if(labels[i].htmlFor=="state"){
				//see comments in above case
				label.innerHTML = out;
				label.addClassName('error');
				element.setStyle({'borderColor':''});
				element.addClassName('errorField');
				label.scrollTo();
			}
		}
	
		// remove the styles from the failed form element and the label
		// search though all the labels again
		// find matching label form element and remove error
		// because of the province/state per country special case for prov/state
		function removeStyles(t) {
			
			for(var i=0;i<labels.length;i++) {
				if (labels[i].htmlFor==element.id) {
					labels[i].innerHTML = t;
					labels[i].removeClassName('error');
					element.removeClassName('errorField');
				}else if(labels[i].htmlFor=="state"){
					label.innerHTML = t;
					label.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;

		var params = {
			"mid" : mid,
			"vote" : 1,
			"recaptcha" : false
		}

		jsonRequest('media.vote', params,
			function(result) { 
				console.log("Vote Logged");
				$(element).addClassName("disabled");
				$(element).innerHTML = $('voteResult').value;
				
				if($('user_account').value == 1){
					if ($('votePublishToFacebook') != null && $('votePublishToFacebook').checked) {
						votePublishToFb();
					}
				}
			},
			function(exception) { 
				exception(exception);
			}
		);
	}
}

function votePublishToFb(){

	var message = "I voted for "+$('voteUserFirstName').value+" in the "+ $('app_name').value +".";
	var attach = {
		'media': [{	
			'type'	  :	'image',
			'src'	  :	$('voteMediaImage').value,
			'href'	  :	$('voteMediaUrl').value
		}],
		'name'    : $('voteMediaTitle').value,
		'caption' : "I voted for "+$('voteMediaTitle').value+" in the "+ $('app_name').value, 
		'href'    : window.location.href
	};
	
	var publish = {
		method: 'stream.publish',
		message: message,
		attachment: attach,
		action_links: [{text: $('app_name').value , href: 'http://'+$('siteUrl').value}],
		user_prompt_message: 'Share your thoughts.'
	};

	FB.ui(publish, function(){ });

}

function loginToVote(){
	$('voteButtonHolder').hide();
	$('logintovote').show();	
}

/*
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;

		var params = {
			"mid" : mid,
			"vote" : 1,
			"recaptcha" : false
		}

		jsonRequest('media.vote', params,
			function(result) { 
				$(element).addClassName("disabled");
				$(element).innerHTML = $('voteResult').value;
			},
			function(exception) { 
				exception(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) { exception(exception); }
	  		);
  		}
	}
}

// oops, something went wrong
function exception(exception) {
	alert(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;
		}
	});
}

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,type){
	var reportFade = false;
	
	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>';
			args = 'reason='+reason+'&mid='+mid+'&sendto=jordan@filemobile.com';
			
			new Ajax.Request('/action/v2/reportoffensive', {
				method: 'post',
				postBody: args,
				onSuccess: function(data) {
					
					// sets the message to the user
					if (type == 'entry') {
						text = reportReasons[2][6];		
					} else {	
						text = reportReasons[2][5];	
					}
										
			    	$('fmReportBox').innerHTML ='<div class="fmTitle">'+reportReasons[2][0]+'</div><span class="report" onclick="$(\'fmReportBox\').remove();">'+reportReasons[2][7]+'</span> <p>'+text+'</p><a class="fmButtonSm r" onclick="$(\'fmReportBox\').remove();"><span>'+reportReasons[2][7]+'</span></a></a>';
			    	
			    	if (reportFade === true) {
			    		Effect.Fade("fmReportBox", { duration: 4.0 });
			    	}
	
				}
			});
			
		}
	}
}

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,\''+type+'\');"><span>'+reportReasons[2][3]+'</span></a><a class="fmButtonSm" onclick="$(\'fmReportBox\').remove(); $(\'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();
			});
		});
	}
}


//keep track of reCaptcha type
function recaptchaState(type){
	if(type == 'image'){
		imageCaptcha = 1;
		audioCaptcha = 0;
	}else if(type == 'audio'){
		imageCaptcha = 0;
		audioCaptcha = 1;
	}
}

//send to a friend
function sendToAFriend(e) {

	try {
	// 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,
			onSuccess: function(transport) {
				if (transport.responseText.match(/fm_error=invalidcaptcha/)){
					Recaptcha.reload()
					$('incorrectCaptcha').show();
					$('incorrectCaptcha').addClassName('error');
					
					if(imageCaptcha == 1){
						$('recaptcha_only_if_image').hide();						
					}else if(audioCaptcha == 1){
						$('recaptcha_only_if_audio').hide();
					}
					
				}else{
					$(e).hide();
					$(e).next(0).show();
				}
			},
			onComplete: function(transport) {}
		});		
	}
	} catch (e)  {
		console.log(e);	
	}
}

function recaptchaMessage(){
	$('incorrectCaptcha', 'recaptcha_only_if_image', 'recaptcha_only_if_audio').invoke('removeClassName','error');	
	
	var reImage = $('recaptcha_only_if_image');
	var reAudio = $('recaptcha_only_if_audio');
	var incorrectEle = $('incorrectCaptcha');
	
	var reImageVisable = $('recaptcha_only_if_image').visible();
	var reAudioVisable = $('recaptcha_only_if_audio').visible();
	
	if(reImageVisable == false || reAudioVisable == false){
		$(incorrectEle).hide();
		if(imageCaptcha == 1){
			$(reImage).show();
		}else if(audioCaptcha == 1){
			$(reAudio).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();
	});
	
}

function updateBirthday() {
	$('birthday').value = $('year').value+"-"+$('month').value+"-"+$('day').value;
}

//depending on country choosen make postal code required or not
//currently our validaiton only supports Canadian + USA formats 
function setPostalCode(addRemove){
	if($('postalcode')){
		if(addRemove == 1){
			$('postalcode').addClassName('fmPostalcode').addClassName('required');
		}else{
			$('postalcode').removeClassName('fmPostalcode').removeClassName('required');
		}
	}	
}

// sets the state and shows / hides and sets required state for status
// shows / hides postal code status
function setStates(){
    if($('country').value == 'US'){
	    $('country_us').show();
	    $('country_canada', 'country_other').invoke('hide');
	    $('province').value = "";
	    $('state_province').addClassName('required');
	    $('province').removeClassName('required');
	    setPostalCode(1);
    }else if($('country').value == 'CA'){
	    $('country_canada').show();
	    $('country_us', 'country_other').invoke('hide');
	    $('state_province').value = "";
	    $('state_province').removeClassName('required');
	    $('province').addClassName('required');
	    setPostalCode(1);
	}else if($('country').value == 'GB'){
		$('country_other').show();
	    $('country_us', 'country_canada').invoke('hide');
	    $('state').value = "";
	    $('state_province').value = "";
	    $('province').value = "";
	    $$('#state_province','#province').invoke('removeClassName', 'required');
	    setPostalCode(1);
    }else{
	    $('country_other').show();
	    $('country_us', 'country_canada').invoke('hide');
	    $('state').value = "";
	    $('state_province').value = "";
	    $('province').value = "";
		$$('#state_province','#province').invoke('removeClassName', 'required');
	    setPostalCode(0);
    }
}

function setState(s){
	$('state').value = s;
}

/* Map Input search key up for location search */
if($('searchAddressField')){
	Event.observe($('searchAddressField'), 'keypress', function(event){
		if(event.keyCode == Event.KEY_RETURN){
			searchAddress($('searchAddressField').value);
		};
	});
}

function disableEnterKey(e){

	var key;
	if(window.event){
		//IE
		key = window.event.keyCode;
	}else{
		//firefox
		key = e.which;
	}
	
	if(key == 13){
		searchAddress($('searchAddressField').value);
		return false;
	}else{
		return true;
	}
}

//adding links to the tags
function entryTags(tags){
	tags = tags.split(' ');
	var out = '';
	var l = tags.length;
	for(var i=0;i<l;i++) {
		out += '<a href="/gallery/search?q='+tags[i]+'">'+tags[i]+'</a>';
		if (i!=l-1) { out += ', '; }
	}
	$('entryTags').innerHTML = out;
}
