/**
 * @author jfturcot
 */
$(document).ready(function(){
		$('.js-help').remove();
	
    var LANGUAGE = $('body').attr('class');
		
		resizeWrapperMargin();
		var resizeTimer = null;
		$(window).bind('resize', function() {
		    if (resizeTimer) clearTimeout(resizeTimer);
		    resizeTimer = setTimeout(resizeWrapperMargin, 100);
		});
		function resizeWrapperMargin() {
			if ($(window).width() < 1024) {
				$('#wrapper').css('margin-left', '-' + $(window).width() / 2 + 'px');
			} else {
				$('#wrapper').css('margin-left', '-512px');
			}
		};
    
    function showSubMenu(){
        $("#main-navigation > ul > li#nav-services > ul").fadeIn();
    }
    
    function hideSubMenu(){
        $("#main-navigation > ul > li#nav-services > ul").fadeOut('fast');
    }
    
    var config = {
        sensitivity: 4,
        interval: 120,
        over: showSubMenu,
        out: hideSubMenu
    };
    
    $("#main-navigation > ul > li#nav-services").hoverIntent(config);
    
		// Translation menu
		$('.locale input').hide();

    $('#body-audio a').click(function(){
        var file = $(this).attr('href');
        
        var audioPlayer = '<object type="application/x-shockwave-flash" data="/flash/player_mp3_maxi.swf" width="200" height="20">';
        audioPlayer += '<param name="movie" value="/flash/player_mp3_maxi.swf" />';
        audioPlayer += '<param name="bgcolor" value="#ffffff" />';
        audioPlayer += '<param name="FlashVars" value="mp3=' + file + '&amp;showstop=1&amp;showvolume=1&amp;autoplay=1" />';
        audioPlayer += '</object>';
        $('#body-audio').html(audioPlayer);
        
        return false;
    });

		if ($('#admin').length > 0) {
			$('ul.note-content').hide();
			$('a.show-note').click(function() {
				$(this).next().next('ul').slideToggle();
				return false;
			});
			
			$('#new_note, #new_project').hide();
			$('h3 a').click(function() {
				$(this).parent().next('form').slideToggle();
				return false;
			});
		};
    
    if ($('#demos #demo-player').length > 0) {
        var demoEnglish = $('#demos ul#download-links li a.english').attr('href');
        var demoFrancais = $('#demos ul#download-links li a.francais').attr('href');
        if ($('#demos').attr('class') == "fr") {
            $('#demos #main-content').append('<div id="demo-language-switcher"><a href="' + demoEnglish + '">Écouter ce démo en anglais</a></div>');
            var s2 = new SWFObject('/flash/player.swf', 'player', '320', '260', '9');
            s2.addParam('allowscriptaccess', 'always');
            s2.addParam('allowfullscreen', 'true');
            s2.addParam('flashvars', 'file=' + demoFrancais);
            s2.write('demo-player');
            
            $('#demos #demo-language-switcher a').click(function(){
                var currentLanguage = $('#demos #demo-player').attr('class');
                
                var s2 = new SWFObject('/flash/player.swf', 'player', '320', '260', '9');
                s2.addParam('allowscriptaccess', 'always');
                s2.addParam('allowfullscreen', 'true');
                if (currentLanguage == 'english') {
                    s2.addParam('flashvars', 'file=' + demoFrancais + '&autostart=true');
                    $('#demos #demo-player').attr('class', 'francais');
                    $('#demos #demo-language-switcher a').text('Écouter ce démo en anglais').attr('href', demoEnglish);
                }
                else 
                    if (currentLanguage == 'francais') {
                        s2.addParam('flashvars', 'file=' + demoEnglish + '&autostart=true');
                        $('#demos #demo-player').attr('class', 'english');
                        $('#demos #demo-language-switcher a').text('Écouter ce démo en français').attr('href', demoFrancais);
                    }
                s2.write('demo-player');
                
                return false;
            });
        }
        else {
            $('#demos #main-content').append('<div id="demo-language-switcher"><a href="' + demoFrancais + '">Listen to this demo in French</a></div>');
            var s2 = new SWFObject('/flash/player.swf', 'player', '320', '260', '9');
            s2.addParam('allowscriptaccess', 'always');
            s2.addParam('allowfullscreen', 'true');
            s2.addParam('flashvars', 'file=' + demoEnglish);
            s2.write('demo-player');
            
            $('#demos #demo-language-switcher a').click(function(){
                var currentLanguage = $('#demos #demo-player').attr('class');
                
                var s2 = new SWFObject('/flash/player.swf', 'player', '320', '260', '9');
                s2.addParam('allowscriptaccess', 'always');
                s2.addParam('allowfullscreen', 'true');
                if (currentLanguage == 'english') {
                    s2.addParam('flashvars', 'file=' + demoFrancais + '&autostart=true');
                    $('#demos #demo-player').attr('class', 'francais');
                    $('#demos #demo-language-switcher a').text('Listen to this demo in English').attr('href', demoEnglish);
                }
                else 
                    if (currentLanguage == 'francais') {
                        s2.addParam('flashvars', 'file=' + demoEnglish + '&autostart=true');
                        $('#demos #demo-player').attr('class', 'english');
                        $('#demos #demo-language-switcher a').text('Listen to this demo in French').attr('href', demoFrancais);
                    }
                s2.write('demo-player');
                
                return false;
            });
        }
    }

		// Flash lightbox
		if ($('#lightbox.flash').length > 0) {
			$('#lightbox.flash').show();
			$('#lightbox.flash a.close').click(function() {
				$('#lightbox.flash').remove();
				return false;
			});
			$('#content-body div.flash').hide();
			$('#lightbox.flash #inner-lightbox').draggable();
		}
		
		// Error explanation lightbox
		if ($('div#errorExplanation').length > 0) {
			html = '';
			html += '<div id="lightbox">';
			html += '	<div id="inner-lightbox">';
			html += '		<a class="close" href="#">Close</a>';
			html += '	</div>';
			html += '</div>';
			$('body').append(html);
			$('#inner-lightbox').prepend($('div#errorExplanation')).parent().show();
			$('#lightbox a.close').click(function() {
				$('#lightbox').remove();
				return false;
			});
			
			$('div.fieldWithErrors input, div.fieldWithErrors textarea').focus(function() {
				$(this).css({'background-color' : '#fff'})
			});
		}
		
		/*
     * About Page
     */
		
		$('#about #content #about-june-gallery .gallery a').click(function() {
			var image = $(this).attr('href');
			var imageTitle = $(this).attr('alt');
			var windowHeight = $(window).height();
			var windowWidth = $(window).width();
			if (windowHeight / 1.5 > 800) {
				var imageHeight = 800;
			} else {
				var imageHeight = windowHeight / 1.5;
			}
			
			var html = "";
      html += '<div id="lightbox">';
      html += '<div id="inner-lightbox">';
			html += '<br />';
      html += '<img src="' + image + '" alt="' + imageTitle + '" height="' + imageHeight + '" />';
      html += '<a class="close" href="#">Close</a>';
      html += '</div>';
      html += '</div>';
      $('body').append(html);
			var cssWidth = (imageHeight * 1.28) + 'px';
			if (windowWidth < (imageHeight * 1.40)) {
				var cssMarginLeft = '-' + (((windowWidth * 0.8) / 2) + 25) + 'px';
			} else {
				var cssMarginLeft = '-' + (((imageHeight * 1.28) / 2) + 25) + 'px';
			}
			
			$('#lightbox #inner-lightbox').css({'width' : cssWidth, 'margin-left' : cssMarginLeft});
			
			$('#lightbox').show().children().draggable().children('a.close').click(function() {
				$('#lightbox').remove();
				return false;
			});
			
			return false;
		});
		
		
    
    /*
     * Demo Page
     */
    // Create lightbox
    if ($('body#demos').length > 0 || $('body#services').length > 0) {
        var html = "";
        html += '<div id="lightbox">';
        html += '<div id="inner-lightbox">';
        html += '<h2>category</h2>';
        html += '<h3>title</h3>';
        html += '<img src="/images/lightbox-image.jpg" alt="title" />';
        html += '<p id="player"></p>';
        html += '<p class="download"><a href="/file.mp3">text</a><span> / </span><a href="/file.mp3" class="french" title="title_fr">text</a></p>';
        html += '<a class="close" href="#">Close</a>';
        html += '</div>';
        html += '</div>';
        $('body').append(html);

				$('#lightbox #inner-lightbox').draggable({cancel: 'p#player'});
        
        // On click, play the demo in the lightbox
        $('#demo-list > ul > li > a').click(function(){
        
            if (LANGUAGE == 'en') {
                $('#lightbox #inner-lightbox p.download a').eq(0).text('Download this file');
                $('#lightbox #inner-lightbox p.download a').eq(1).text('Listen in French');
                $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'french');
            }
            else 
                if (LANGUAGE == 'fr') {
                    $('#lightbox #inner-lightbox p.download a').eq(0).text('Télécharger ce fichier');
                    $('#lightbox #inner-lightbox p.download a').eq(1).text('Version Anglaise');
                    $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'french');
                }
            
            var category = $(this).parent().parent().prev().text();
            var title = $(this).attr('title');
            var file = $(this).attr('href');
            var title_fr = $(this).parent().next().children().attr('title');
            var file_fr = $(this).parent().next().children().attr('href');
            var file_type = $(this).attr('class');
						var image = $(this).parent().prev().children().attr('src');
            $('#lightbox #inner-lightbox h2').text(category);
            $('#lightbox #inner-lightbox h3').text(title);
						$('#lightbox #inner-lightbox img').attr('src', image);
            $('#lightbox #inner-lightbox p.download a').eq(0).attr('href', file);
            $('#lightbox #inner-lightbox p.download a').eq(1).attr('title', title_fr);
            $('#lightbox #inner-lightbox p.download a').eq(1).attr('href', file_fr);
            
            // Load Flash multimedia player
            $('#lightbox #inner-lightbox p#player').html("");
            if (file_type == 'audio') {
                var audioPlayer = '<object type="application/x-shockwave-flash" data="/flash/player_mp3_maxi.swf" width="200" height="20">';
                audioPlayer += '<param name="movie" value="/flash/player_mp3_maxi.swf" />';
                audioPlayer += '<param name="bgcolor" value="#ffffff" />';
                audioPlayer += '<param name="FlashVars" value="mp3=' + file + '&amp;showstop=1&amp;showvolume=1&amp;autoplay=1" />';
                audioPlayer += '</object>';
                $('#lightbox #inner-lightbox p#player').html(audioPlayer);
                $('#lightbox #inner-lightbox img').show();
            }
            else 
                if (file_type == 'video') {
                    var videoPlayer = '<object type="application/x-shockwave-flash" data="/flash/player_flv_maxi.swf" width="480" height="270">';
                    videoPlayer += '<param name="movie" value="/flash/player_flv_maxi.swf" />';
                    videoPlayer += '<param name="bgcolor" value="#ffffff" />';
                    videoPlayer += '<param name="FlashVars" value="flv=' + file + '&amp;showstop=1&amp;showvolume=1&amp;autoplay=1" />';
                    videoPlayer += '</object>';
                    $('#lightbox #inner-lightbox p#player').html(videoPlayer);
                    $('#lightbox #inner-lightbox img').hide();
                }
            
            
            $('#lightbox').show();
            
						$('#lightbox #inner-lightbox p.download a').eq(0).unbind('click').click(function(){
							var path = $(this).attr('href').split('?');
							window.location = '/download?path=' + path[0];
							return false;
						});
						
            $('#lightbox #inner-lightbox p.download a').eq(1).unbind('click').click(function(){
                var title_switch_a = $('#lightbox #inner-lightbox h3').text();
                var file_switch_a = $('#lightbox #inner-lightbox p.download a').eq(0).attr('href');
                var title_switch_b = $('#lightbox #inner-lightbox p.download a').eq(1).attr('title');
                var file_switch_b = $('#lightbox #inner-lightbox p.download a').eq(1).attr('href');
                
                $('#lightbox #inner-lightbox h3').text(title_switch_b);
                $('#lightbox #inner-lightbox p#player').text(file_switch_b);
                $('#lightbox #inner-lightbox p.download a').eq(0).attr('href', file_switch_b);
                $('#lightbox #inner-lightbox p.download a').eq(1).attr('title', title_switch_a);
                $('#lightbox #inner-lightbox p.download a').eq(1).attr('href', file_switch_a);
                
                if (LANGUAGE == 'en') {
                    if ($('#lightbox #inner-lightbox p.download a').eq(1).attr('class') == "french") {
                        $('#lightbox #inner-lightbox p.download a').eq(0).text('Download this file (French version)');
                        $('#lightbox #inner-lightbox p.download a').eq(1).text('Listen in English');
                        $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'english')
                    }
                    else 
                        if ($('#lightbox #inner-lightbox p.download a').eq(1).attr('class') == "english") {
                            $('#lightbox #inner-lightbox p.download a').eq(0).text('Download this file');
                            $('#lightbox #inner-lightbox p.download a').eq(1).text('Listen in French');
                            $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'french')
                        }
                }
                else 
                    if (LANGUAGE == 'fr') {
                        if ($('#lightbox #inner-lightbox p.download a').eq(1).attr('class') == "french") {
                            $('#lightbox #inner-lightbox p.download a').eq(0).text('Télécharger ce fichier (version anglaise)');
                            $('#lightbox #inner-lightbox p.download a').eq(1).text('Version Française');
                            $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'english')
                        }
                        else 
                            if ($('#lightbox #inner-lightbox p.download a').eq(1).attr('class') == "english") {
                                $('#lightbox #inner-lightbox p.download a').eq(0).text('Télécharger ce fichier');
                                $('#lightbox #inner-lightbox p.download a').eq(1).text('Version Anglaise');
                                $('#lightbox #inner-lightbox p.download a').eq(1).attr('class', 'french')
                            }
                    }
                
                // Load Flash multimedia player
                $('#lightbox #inner-lightbox p#player').html("");
                if (file_type == 'audio') {
                    var audioPlayer = '<object type="application/x-shockwave-flash" data="/flash/player_mp3_maxi.swf" width="200" height="20">';
                    audioPlayer += '<param name="movie" value="/flash/player_mp3_maxi.swf" />';
                    audioPlayer += '<param name="bgcolor" value="#ffffff" />';
                    audioPlayer += '<param name="FlashVars" value="mp3=' + file_switch_b + '&amp;showstop=1&amp;showvolume=1&amp;autoplay=1" />';
                    audioPlayer += '</object>';
                    $('#lightbox #inner-lightbox p#player').html(audioPlayer);
                }
                else 
                    if (file_type == 'video') {
                        var videoPlayer = '<object type="application/x-shockwave-flash" data="/flash/player_flv_maxi.swf" width="480" height="270">';
                        videoPlayer += '<param name="movie" value="/flash/player_flv_maxi.swf" />';
                        videoPlayer += '<param name="bgcolor" value="#ffffff" />';
                        videoPlayer += '<param name="FlashVars" value="flv=' + file_switch_b + '&amp;showstop=1&amp;showvolume=1&amp;autoplay=1" />';
                        videoPlayer += '</object>';
                        $('#lightbox #inner-lightbox p#player').html(videoPlayer);
                    }
                
                return false;
            });
            
						if (file_fr == null) {
							$('#lightbox #inner-lightbox p.download a').eq(1).hide();
							$('#lightbox #inner-lightbox p.download span').hide();
						}

            return false;
        });
        
        $('#lightbox #inner-lightbox a.close').click(function(){
            $('#lightbox').hide();
						$('#lightbox #inner-lightbox p.download a').eq(1).show();
						$('#lightbox #inner-lightbox p.download span').show();
            return false;
        });
    }

		/*
     * Project
     */

		if ($('body#projects')) {
			$('body#projects form#new_comment select#auto_comment_comment').change(function() {
				$(this).next('span').remove();
				
				var id = $(this).val().split("-")[0]
				if ($(this).val() != "") {
					$(this).after("<span><a href=\"/auto_comments/edit/" + id + "\">edit</a>");
				} else {
					$(this).after("<span><a href=\"/auto_comments/new\">New auto comment</a></span>");
				}
				
				var comment = $(this).val().split("-").splice(1).join("-");
				$('body#projects form#new_comment textarea').text('').text(comment);
			});
			
			$('a.download').click(function(){
				var path = $(this).attr('href').split('?');
				window.location = '/download?path=' + path[0];
				return false;
			});
			
			$('a.download').bind("contextmenu",function(e){  
				return false;  
			});
			
		}
		
		/*
     * Store Cart Form
    */
		if ($('body#store-cart').length > 0) {
			$('#cart_address_country').change(function() {
				var country = 'country=' + $('select#cart_address_country :selected').text();
				$.getScript('/store?' + country, function() {});
			});
		}

    
    /*
     * Store Order Form
     */
    if ($('body#store-order').length > 0) {
	
				/* Rates	*/
				$('#store-order #content-body a.price').click(function(){
            $('#store-order #rates').show();
            return false;
        });
				
				$('#store-order #rates a.close').click(function(){
            $(this).parent().parent().hide();
            return false;
        });

				$('#store-order #rates #inner-rates').draggable();

				/* How to order	*/
				$('#store-order #content-body a.how_to').click(function(){
            $('#store-order #how_to').show();
            return false;
        });
				
				$('#store-order #how_to a.close').click(function(){
            $(this).parent().parent().hide();
            return false;
        });
				
				$('#store-order #how_to div.help').hide();
				$('#store-order #how_to div.help').eq(0).show();
				$('#store-order #how_to ul li:eq(0) a').attr('class', 'selected') 
				$('#store-order #how_to ul li a').click(function(){
						$(this).parent().parent().parent().children('div').hide();
						$('#store-order #how_to ul li a').attr('class', '') 
						
            var divToShow = $(this).attr('href');
						$('#store-order #how_to div' + divToShow).show()
						$(this).attr('class', 'selected') 
            return false;
        });

				$('#store-order #how_to #inner-how_to').draggable();
    
        /* Pricing details */
        
        // Create lightbox
        var html = "";
        html += '<div id="lightbox">';
        html += '	<div id="inner-lightbox">';
				if (LANGUAGE == 'fr') {
					html += '		<h2>Détails des coûts</h2>';
				} else {
					html += '		<h2>Pricing details</h2>';
				}
        html += '		<a class="close" href="#">Close</a>';
        html += '		<div id="pricing-details-table"></div>';
        html += '	</div>';
        html += '</div>';
        $('body#store-order').append(html);
        
        $('#store-order #lightbox a.close').click(function(){
            $(this).parent().parent().hide();
            return false;
        });

				$('#lightbox #inner-lightbox').draggable();
        
        /* Total */
        
        $('#store-order form #price-total').remove();
				if (LANGUAGE == 'fr') {
					$('#store-order form #file-attachments').after('<div id="price-total"><p>Total: <span>0</span> $ CAD</p><a href="#">Cliquer pour voir les détails des coûts</a></div>');
				} else {
					$('#store-order form #file-attachments').after('<div id="price-total"><p>Total: $<span>0</span> CAD</p><a href="#">Click to review pricing details</a></div>');
				}
        
        $('#store-order form #price-total a').click(function(){
            $('#store-order #lightbox').show();
            return false;
        });
        
				function calculateTotals() {
				    var grandTotal = 0;

				    // Voice prompts total
				    var priceVoicePromptA = 15;
				    var priceVoicePromptB = 10;
				    var qtyVoicePrompts = 0;
				    var totalExtraWords = 0;

				    var priceExtraWordsA = 1;
				    var extraWordsB = 50;
				    var priceExtraWordsB = 0.75;
				    var extraWordsC = 150;
				    var priceExtraWordsC = 0.50;
				    var totalPriceExtraWords = 0;

				    $('#store-order #lightbox #pricing-details-table table').remove();

				    var html = '';
				    html += '<table cellspacing="0" cellpadding="0" border="0">';
				    html += '	<thead>';
				    html += '		<tr id="voice-prompts-head">';
						if (LANGUAGE == 'fr') {
							html += '			<th class="items">Messages téléphoniques</th>';
					    html += '			<th class="quantity">Quantité</th>';
					    html += '			<th class="price">Prix</th>';
					    html += '			<th class="total">Total</th>';
						} else {
							html += '			<th class="items">Voice prompts</th>';
					    html += '			<th class="quantity">Quantity</th>';
					    html += '			<th class="price">Price</th>';
					    html += '			<th class="total">Total</th>';
						}
				    html += '		</tr>';
				    html += '	</thead>';
				    html += '	<tbody>';
				    html += '	</tbody>';
				    html += '</table>';

				    $('#store-order #lightbox #pricing-details-table').append(html);
						
						var voicePromptsTotal = 0;
				    $('#store-order form #voice-prompts fieldset').each(function(i) {
				        var totalVoicePrompt = 0;

				        if ($(this).children('ul').children('li.voice-prompt').children('textarea').attr('value') != "") {
				            var html = '';
				            html += '	<tr id="voice-prompt-' + [i + 1] + '-row">';
										if (LANGUAGE == 'fr') {
											html += '		<td class="items">Message téléphonique ' + [i + 1] + '</td>';
										} else {
											html += '		<td class="items">Voice prompt ' + [i + 1] + '</td>';
										}
				            html += '		<td class="quantity">1</td>';
				            html += '		<td class="price">$15.00</td>';
				            html += '		<td class="total">$0.00</td>';
				            html += '	</tr>';
				            $('#store-order #lightbox table tbody').append(html);

				            qtyVoicePrompts++;
				            var totalWords = parseInt($(this).children('ul').children('li:eq(0)').children('p.words').children('span.total-words').text());

				            // Add total words to table
				            $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-words-total-row td.quantity').text(totalWords);

				            if (i == 0) {
				                totalVoicePrompt = priceVoicePromptA;

				                // Add voice prompt's quantity and price to table
												if (LANGUAGE == 'fr') {
													$('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.price').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency({ positiveFormat: '%n %s' });
					                $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.total').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency({ positiveFormat: '%n %s' });
												} else {
													$('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.price').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency();
					                $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.total').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency();
												}
				
												if (totalWords < priceVoicePromptA) {
													$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.included-words').text(totalWords);
												} else {
													$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.included-words').text(priceVoicePromptA);
												}
												

				                var extraWords = totalWords - priceVoicePromptA;
				                var extraWordsPrice = 0;
				
				                if (extraWords > 0) {
														$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.extra-words').text(extraWords);
					
				                    totalExtraWordsPrev = totalExtraWords;
				                    totalExtraWords += extraWords;

				                    var extraWordsPrice = 0;
				                    if (totalExtraWords > extraWordsC) {
				                        if (totalExtraWordsPrev > extraWordsC) {
				                            extraWordsPrice += extraWords * priceExtraWordsC;
				                        }
				                        else if (totalExtraWordsPrev > extraWordsB && totalExtraWordsPrev <= extraWordsC) {
				                            extraWordsPrice += ((extraWordsC - totalExtraWordsPrev) * priceExtraWordsB) + ((extraWords - (extraWordsC - totalExtraWordsPrev)) * priceExtraWordsC);
				                        } else {
				                            extraWordsPrice += ((extraWordsB - totalExtraWordsPrev) * priceExtraWordsA) + ((extraWordsC - extraWordsB) * priceExtraWordsB) + ((extraWords - (extraWordsC - totalExtraWordsPrev)) * priceExtraWordsC)
				                        }
				                    } else if (totalExtraWords > extraWordsB && totalExtraWords <= extraWordsC) {
				                        if (totalExtraWordsPrev > extraWordsB) {
				                            extraWordsPrice += extraWords * priceExtraWordsB;
				                        } else {
				                            extraWordsPrice += ((extraWordsB - totalExtraWordsPrev) * priceExtraWordsA) + ((extraWords - (extraWordsB - totalExtraWordsPrev)) * priceExtraWordsB);
				                        }
				                    } else {
				                        extraWordsPrice = extraWords * priceExtraWordsA;
				                    }

				                    // Add voice prompt's extra words quantity and total to table
				                    $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-words-extra-row td.quantity').text(extraWords);
				                }

				            }
				            else {
				                totalVoicePrompt = priceVoicePromptB;

				                // Add voice prompt's quantity and price to table
												if (LANGUAGE == 'fr') {
													$('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.price').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency({ positiveFormat: '%n %s' });
					                $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.total').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency({ positiveFormat: '%n %s' });
												} else {
													$('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.price').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency();
					                $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-row td.total').attr('title', totalVoicePrompt).text(totalVoicePrompt).formatCurrency();
												}
				
												if (totalWords < priceVoicePromptB) {
													$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.included-words').text(totalWords);
												} else {
													$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.included-words').text(priceVoicePromptB);
												}

				                var extraWords = totalWords - priceVoicePromptB;
				                var extraWordsPrice = 0;
				                if (extraWords > 0) {
														$(this).children('ul').children('li.voice-prompt').children('p.words').children('span.extra-words').text(extraWords);
										
				                    totalExtraWordsPrev = totalExtraWords;
				                    totalExtraWords += extraWords;

				                    if (totalExtraWords > extraWordsC) {
				                        if (totalExtraWordsPrev > extraWordsC) {
				                            extraWordsPrice += extraWords * priceExtraWordsC;
				                        }
				                        else if (totalExtraWordsPrev > extraWordsB && totalExtraWordsPrev <= extraWordsC) {
				                            extraWordsPrice += ((extraWordsC - totalExtraWordsPrev) * priceExtraWordsB) + ((extraWords - (extraWordsC - totalExtraWordsPrev)) * priceExtraWordsC);
				                        } else {
				                            extraWordsPrice += ((extraWordsB - totalExtraWordsPrev) * priceExtraWordsA) + ((extraWordsC - extraWordsB) * priceExtraWordsB) + ((extraWords - (extraWordsC - totalExtraWordsPrev)) * priceExtraWordsC)
				                        }
				                    } else if (totalExtraWords > extraWordsB && totalExtraWords <= extraWordsC) {
				                        if (totalExtraWordsPrev > extraWordsB) {
				                            extraWordsPrice += extraWords * priceExtraWordsB;
				                        } else {
				                            extraWordsPrice += ((extraWordsB - totalExtraWordsPrev) * priceExtraWordsA) + ((extraWords - (extraWordsB - totalExtraWordsPrev)) * priceExtraWordsB);
				                        }
				                    } else {
				                        extraWordsPrice = extraWords * priceExtraWordsA;
				                    }

				                    // Add voice prompt's extra words quantity and total to table
				                    $('#store-order #lightbox table tr#voice-prompt-' + [i + 1] + '-words-extra-row td.quantity').text(extraWords);
				                }
				            }
				        }
								
								if (LANGUAGE == 'fr') {
									$(this).children('p.price').children().attr('title', totalVoicePrompt + extraWordsPrice).text(totalVoicePrompt + extraWordsPrice).formatCurrency({
					            symbol: '',
											positiveFormat: '%n %s'
					        });
								} else {
									$(this).children('p.price').children().attr('title', totalVoicePrompt + extraWordsPrice).text(totalVoicePrompt + extraWordsPrice).formatCurrency({
					            symbol: ''
					        });
								}
				        
								voicePromptsTotal += totalVoicePrompt + extraWordsPrice;
				        grandTotal += totalVoicePrompt;
				    });

				    // Extra words table
				    $('#store-order #extra-words fieldset ul li p span').text(totalExtraWords);

				    var html = '';
				    html += '<thead id="extra-words-thead" style="display: none;">';
				    html += '	<tr id="extra-words-head">';
						if (LANGUAGE == 'fr') {
							html += '		<th class="items">Mots additionnels</th>';
					    html += '		<th class="quantity">Quantité</th>';
					    html += '		<th class="price">Prix</th>';
					    html += '		<th class="total">Total</th>';
						} else {
							html += '		<th class="items">Extra words</th>';
					    html += '		<th class="quantity">Quantity</th>';
					    html += '		<th class="price">Price</th>';
					    html += '		<th class="total">Total</th>';
						}
				    html += '	</tr>';
				    html += '</thead>';
				    html += '<tbody id="extra-words-tbody" style="display: none;">';
				    html += '	<tr id="extra-words-row-1">';
						if (LANGUAGE == 'fr') {
							html += '		<td class="items">Mots additionnels - Premiers 50 mots</td>';
						} else {
							html += '		<td class="items">Extra words - First 50</td>';
						}
				    html += '		<td class="quantity">0</td>';
				    html += '		<td class="price">0</td>';
				    html += '		<td class="total">0</td>';
				    html += '	</tr>';
				    html += '	<tr id="extra-words-row-2" style="display: none;">';
						if (LANGUAGE == 'fr') {
							html += '		<td class="items">Mots additionnels - Entre 51 et 150 mots</td>';
						} else {
							html += '		<td class="items">Extra words - Between 51 and 150</td>';
						}
				    html += '		<td class="quantity">0</td>';
				    html += '		<td class="price">0</td>';
				    html += '		<td class="total">0</td>';
				    html += '	</tr>';
				    html += '	<tr id="extra-words-row-3" style="display: none;">';
						if (LANGUAGE == 'fr') {
							html += '		<td class="items">Mots additionnels - 151 et plus</td>';
						} else {
							html += '		<td class="items">Extra words - 151 and up</td>';
						}
				    
				    html += '		<td class="quantity">0</td>';
				    html += '		<td class="price">0</td>';
				    html += '		<td class="total">0</td>';
				    html += '	</tr>';
				    html += '</tbody>';
				    $('#store-order #lightbox table').append(html);

				    if (totalExtraWords > 0) {
				        $('#store-order #lightbox table thead#extra-words-thead, #store-order #lightbox table tbody#extra-words-tbody').show();
				        if (totalExtraWords > extraWordsC) {
				            totalPriceExtraWords = (totalExtraWords - extraWordsC) * priceExtraWordsC;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3 td.quantity').text(totalExtraWords - extraWordsC);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3 td.price').attr('title', priceExtraWordsC).text(priceExtraWordsC).formatCurrency({ positiveFormat: '%n %s' });
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3 td.total').attr('title', (totalExtraWords - extraWordsC) * priceExtraWordsC).text((totalExtraWords - extraWordsC) * priceExtraWordsC).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3 td.price').attr('title', priceExtraWordsC).text(priceExtraWordsC).formatCurrency();
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3 td.total').attr('title', (totalExtraWords - extraWordsC) * priceExtraWordsC).text((totalExtraWords - extraWordsC) * priceExtraWordsC).formatCurrency();
										}
				            
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-3').show();
				            totalPriceExtraWords += (extraWordsC - extraWordsB) * priceExtraWordsB;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.quantity').text(extraWordsC - extraWordsB);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.price').attr('title', priceExtraWordsB).text(priceExtraWordsB).formatCurrency({ positiveFormat: '%n %s' });
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.total').attr('title', (extraWordsC - extraWordsB) * priceExtraWordsB).text((extraWordsC - extraWordsB) * priceExtraWordsB).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.price').attr('title', priceExtraWordsB).text(priceExtraWordsB).formatCurrency();
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.total').attr('title', (extraWordsC - extraWordsB) * priceExtraWordsB).text((extraWordsC - extraWordsB) * priceExtraWordsB).formatCurrency();
										}
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2').show();
				            totalPriceExtraWords += extraWordsB * priceExtraWordsA;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.quantity').text(extraWordsB);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', extraWordsB * priceExtraWordsA).text(extraWordsB * priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency();
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', extraWordsB * priceExtraWordsA).text(extraWordsB * priceExtraWordsA).formatCurrency();
										}
				        } else if (totalExtraWords > extraWordsB) {
				            totalPriceExtraWords = (totalExtraWords - extraWordsB) * priceExtraWordsB;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.quantity').text(totalExtraWords - extraWordsB);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.price').attr('title', priceExtraWordsB).text(priceExtraWordsB).formatCurrency({ positiveFormat: '%n %s' });
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.total').attr('title', (totalExtraWords - extraWordsB) * priceExtraWordsB).text((totalExtraWords - extraWordsB) * priceExtraWordsB).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.price').attr('title', priceExtraWordsB).text(priceExtraWordsB).formatCurrency();
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2 td.total').attr('title', (totalExtraWords - extraWordsB) * priceExtraWordsB).text((totalExtraWords - extraWordsB) * priceExtraWordsB).formatCurrency();
										}
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-2').show();
				            totalPriceExtraWords += extraWordsB * priceExtraWordsA;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.quantity').text(extraWordsB);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', extraWordsB * priceExtraWordsA).text(extraWordsB * priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency();
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', extraWordsB * priceExtraWordsA).text(extraWordsB * priceExtraWordsA).formatCurrency();
										}
				        } else {
				            totalPriceExtraWords = totalExtraWords * priceExtraWordsA;
				            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.quantity').text(totalExtraWords);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', totalExtraWords * priceExtraWordsA).text(totalExtraWords * priceExtraWordsA).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.price').attr('title', priceExtraWordsA).text(priceExtraWordsA).formatCurrency();
					            $('#store-order #lightbox table tbody#extra-words-tbody tr#extra-words-row-1 td.total').attr('title', totalExtraWords * priceExtraWordsA).text(totalExtraWords * priceExtraWordsA).formatCurrency();
										}
				        }
				    }

				    grandTotal += totalPriceExtraWords;


				    // File format total
				    var fileFormatTotal = 0;
				    var format = $('#store-order form fieldset#opt-audio-formats-fieldset li:eq(0) select:eq(0)').attr('value');
				    var resolution = $('#store-order form fieldset#opt-audio-formats-fieldset li:eq(1) select').attr('value');
				    var sampling = $('#store-order form fieldset#opt-audio-formats-fieldset li:eq(2) select').attr('value');
				    var fileFormatPriceA = 5;
				    var fileFormatPriceB = 3;

				    if (format != 'WAV' && qtyVoicePrompts > 0 || resolution != '16' && qtyVoicePrompts > 0 || sampling != '48' && qtyVoicePrompts > 0) {
				        if (qtyVoicePrompts > 1) {
				            fileFormatTotal = fileFormatPriceA + ((qtyVoicePrompts - 1) * fileFormatPriceB);
				        } else {
				            fileFormatTotal = fileFormatPriceA;
				        }

				        // Add to table
				        var html = '';
				        html += '<thead>';
				        html += '	<tr id="opt-file-format-head">';
								if (LANGUAGE == 'fr') {
									html += '		<th class="items">Formats de fichier</th>';
					        html += '		<th class="quantity">Quantité</th>';
					        html += '		<th class="price">Prix</th>';
					        html += '		<th class="total">Total</th>';
								} else {
									html += '		<th class="items">File format conversion(s)</th>';
					        html += '		<th class="quantity">Quantity</th>';
					        html += '		<th class="price">Price</th>';
					        html += '		<th class="total">Total</th>';
								}
				        html += '	</tr>';
				        html += '</thead>';
				        html += '<tbody>';
				        html += '	<tr id="opt-file-format-1-row">';
								if (LANGUAGE == 'fr') {
									html += '		<td class="items">Format de fichier (premier message)</td>';
								} else {
									html += '		<td class="items">File format conversion (first voice prompt)</td>';
								}
				        html += '		<td class="quantity">0</td>';
								html += '		<td class="price">' + fileFormatPriceA + '</td>';
				        html += '		<td class="total">$0.00</td>';
				        html += '	</tr>';
				        html += '	<tr id="opt-file-format-2-row" style="display: none;">';
								if (LANGUAGE == 'fr') {
									html += '		<td class="items">Format de fichier (deuxième message et subséquent)</td>';
								} else {
									html += '		<td class="items">File format conversion(s) (second voice prompt or more)</td>';
								}
				        html += '		<td class="quantity">0</td>';
				        html += '		<td class="price">' + fileFormatPriceB + '</td>';
				        html += '		<td class="total">$0.00</td>';
				        html += '	</tr>';
				        html += '</tbody>';
				        $('#store-order #lightbox table').append(html);
				        $('#store-order #lightbox table tr#opt-file-format-1-row td.quantity').text('1');
								if (LANGUAGE == 'fr') {
									$('#store-order #lightbox table tr#opt-file-format-1-row td.price').text(fileFormatPriceA).formatCurrency({ positiveFormat: '%n %s' });
									$('#store-order #lightbox table tr#opt-file-format-1-row td.total').attr('title', fileFormatPriceA).text(fileFormatPriceA).formatCurrency({ positiveFormat: '%n %s' });
								} else {
									$('#store-order #lightbox table tr#opt-file-format-1-row td.price').text(fileFormatPriceA).formatCurrency();
									$('#store-order #lightbox table tr#opt-file-format-1-row td.total').attr('title', fileFormatPriceA).text(fileFormatPriceA).formatCurrency();
								}
				        if ((qtyVoicePrompts - 1) > 0) {
				            $('#store-order #lightbox table tr#opt-file-format-2-row td.quantity').text(qtyVoicePrompts - 1);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-file-format-2-row td.price').text(fileFormatPriceB).formatCurrency({ positiveFormat: '%n %s' });
											$('#store-order #lightbox table tr#opt-file-format-2-row td.total').attr('title', (qtyVoicePrompts - 1) * fileFormatPriceB).text((qtyVoicePrompts - 1) * fileFormatPriceB).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-file-format-2-row td.price').text(fileFormatPriceB).formatCurrency();
											$('#store-order #lightbox table tr#opt-file-format-2-row td.total').attr('title', (qtyVoicePrompts - 1) * fileFormatPriceB).text((qtyVoicePrompts - 1) * fileFormatPriceB).formatCurrency();
										}
				            $('#store-order #lightbox table tr#opt-file-format-2-row').show();
				        }


				    }
						if (LANGUAGE == 'fr') {
							$('#store-order form fieldset#opt-audio-formats-fieldset p.price span').attr('title', fileFormatTotal).text(fileFormatTotal).formatCurrency({
									positiveFormat: '%n %s',
					        symbol: ''
					    });
						} else {
							$('#store-order form fieldset#opt-audio-formats-fieldset p.price span').attr('title', fileFormatTotal).text(fileFormatTotal).formatCurrency({
					        symbol: ''
					    });
						}

				    grandTotal += fileFormatTotal;

				    // Language total
				    var languageTotal = 0;
				    if ($('input[name=order[voice_prompt_language]]:checked').val() != "") {

				        // Create table content
				        var html = '';
				        html += '<thead>';
				        html += '	<tr id="opt-language-head">';
								if (LANGUAGE == 'fr') {
									html += '		<th class="items">Traduction</th>';
					        html += '		<th class="quantity">Quantité</th>';
					        html += '		<th class="price">Prix</th>';
					        html += '		<th class="total">Total</th>';
								} else {
									html += '		<th class="items">Language(s)</th>';
					        html += '		<th class="quantity">Quantity</th>';
					        html += '		<th class="price">Price</th>';
					        html += '		<th class="total">Total</th>';
								}
				        html += '	</tr>';
				        html += '</thead>';
				        html += '<tbody>';
				        html += '	<tr id="opt-language-words-row">';
								if (LANGUAGE == 'fr') {
									html += '		<td class="items">Mots à traduire</td>';
								} else {
									html += '		<td class="items">Words to be translated</td>';
								}
				        html += '		<td class="quantity">0</td>';
				        html += '		<td class="price">0.50</td>';
				        html += '		<td class="total">$0.00</td>';
				        html += '	</tr>';
				        html += '	<tr id="opt-language-recorded-translations-row" style="display: none;">';
								if (LANGUAGE == 'fr') {
									html += '		<td class="items">Enregistrement(s) supplémentaire(s) (traduction)</td>';
								} else {
									html += '		<td class="items">Addtional recording(s) (translation)</td>';
								}
				        html += '		<td class="quantity">0</td>';
				        html += '		<td class="price">&nbsp;</td>';
				        html += '		<td class="total">$0.00</td>';
				        html += '	</tr>';
				        html += '	<tr id="opt-language-recorded-translations-opt-files-row" style="display: none;">';
								if (LANGUAGE == 'fr') {
									html += '		<td class="items">Conversion de fichier(s) (traduction)</td>';
								} else {
									html += '		<td class="items">File format(s) conversion(s) (translation)</td>';
								}
				        html += '		<td class="quantity">0</td>';
				        html += '		<td class="price">&nbsp;</td>';
				        html += '		<td class="total">$0.00</td>';
				        html += '	</tr>';
				        html += '</tbody>';
				        $('#store-order #lightbox table').append(html);

				        var totalWords = 0;
				        var totalPrice = 0;
				        var translationPricePerWord = 0.5;
				        var translationPricePerFile = 0;
				        $('#store-order form #voice-prompts fieldset').each(function(i) {
				            if ($(this).children('ul').children('li.voice-prompt').children('textarea').attr('value') != "") {
				                totalWords += parseInt($(this).children('ul').children('li.voice-prompt').children('p.words').children('span.total-words').text());
				                totalPrice += parseInt($(this).children('p.price').children().attr('title'));
				            }
				        });
				        if ($('input[name=order[voice_prompt_language]]:checked').val() == 'translation_only') {
				            languageTotal = totalWords * translationPricePerWord;
				            $('#store-order #lightbox table tr#opt-language-words-row td.quantity').text(totalWords);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency();
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency();
										}
				        } else if ($('input[name=order[voice_prompt_language]]:checked').val() == 'english_and_french_1_file') {
				            languageTotal = (totalWords * translationPricePerWord) + voicePromptsTotal;
				            $('#store-order #lightbox table tr#opt-language-words-row td.quantity').text(totalWords);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency();
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency();
										}

				            $('#store-order #lightbox table tr#opt-language-recorded-translations-row td.quantity').text(qtyVoicePrompts);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-language-recorded-translations-row td.total').attr('title', voicePromptsTotal).text(voicePromptsTotal).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-language-recorded-translations-row td.total').attr('title', voicePromptsTotal).text(voicePromptsTotal).formatCurrency();
										}
				            $('#store-order #lightbox table tr#opt-language-recorded-translations-row').show();

				        } else if ($('input[name=order[voice_prompt_language]]:checked').val() == 'english_and_french_2_files') {
				            languageTotal = (totalWords * translationPricePerWord) + voicePromptsTotal + (qtyVoicePrompts * translationPricePerFile);
				            $('#store-order #lightbox table tr#opt-language-words-row td.quantity').text(totalWords);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-language-words-row td.price').text(translationPricePerWord).formatCurrency();
											$('#store-order #lightbox table tr#opt-language-words-row td.total').attr('title', totalWords * translationPricePerWord).text(totalWords * translationPricePerWord).formatCurrency();
										}

				            $('#store-order #lightbox table tr#opt-language-recorded-translations-row td.quantity').text(qtyVoicePrompts);
										if (LANGUAGE == 'fr') {
											$('#store-order #lightbox table tr#opt-language-recorded-translations-row td.total').attr('title', voicePromptsTotal).text(voicePromptsTotal).formatCurrency({ positiveFormat: '%n %s' });
										} else {
											$('#store-order #lightbox table tr#opt-language-recorded-translations-row td.total').attr('title', voicePromptsTotal).text(voicePromptsTotal).formatCurrency();
										}
				            $('#store-order #lightbox table tr#opt-language-recorded-translations-row').show();

				            if (fileFormatTotal > 0) {
												languageTotal += (qtyVoicePrompts * fileFormatPriceB);
				                $('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row td.quantity').text(qtyVoicePrompts);
												if (LANGUAGE == 'fr') {
													$('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row td.price').attr('title', fileFormatPriceB).text(fileFormatPriceB).formatCurrency({ positiveFormat: '%n %s' });
					                $('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row td.total').attr('title', qtyVoicePrompts * fileFormatPriceB).text(qtyVoicePrompts * fileFormatPriceB).formatCurrency({ positiveFormat: '%n %s' });
												} else {
													$('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row td.price').attr('title', fileFormatPriceB).text(fileFormatPriceB).formatCurrency();
					                $('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row td.total').attr('title', qtyVoicePrompts * fileFormatPriceB).text(qtyVoicePrompts * fileFormatPriceB).formatCurrency();
												}
				                $('#store-order #lightbox table tr#opt-language-recorded-translations-opt-files-row').show();
				            }
				        }
				    }
						if (LANGUAGE == 'fr') {
							$('#store-order form fieldset#opt-language-fieldset p.price span').attr('title', languageTotal).text(languageTotal).formatCurrency({
									positiveFormat: '%n %s',
					        symbol: ''
					    });
						} else {
							$('#store-order form fieldset#opt-language-fieldset p.price span').attr('title', languageTotal).text(languageTotal).formatCurrency({
					        symbol: ''
					    });
						}

				    grandTotal += languageTotal;


				    // Add Grand Total to table
				    var html = '';
				    html += '<tfoot>';
				    html += '	<tr id="grand-total-row">';
				    html += '		<td colspan="3">Total:</td>';
				    html += '		<td class="total">0.00</td>';
				    html += '	</tr>';
				    html += '</tfoot>';
				    $('#store-order #lightbox table').append(html);
						if (LANGUAGE == 'fr') {
							$('#store-order #lightbox table tr#grand-total-row td.total').attr('title', grandTotal).text(grandTotal).formatCurrency({ positiveFormat: '%n %s' });
						} else {
							$('#store-order #lightbox table tr#grand-total-row td.total').attr('title', grandTotal).text(grandTotal).formatCurrency();
						}
						
						if (LANGUAGE == 'fr') {
							$('#store-order form #price-total p span').attr('title', grandTotal).text(grandTotal).formatCurrency({
									positiveFormat: '%n %s',
					        symbol: ''
					    });
						} else {
							$('#store-order form #price-total p span').attr('title', grandTotal).text(grandTotal).formatCurrency({
					        symbol: ''
					    });
						}

				    if (grandTotal > 0) {
				        $('#store-order form #price-total a').fadeIn();
				    }
				    else {
				        $('#store-order form #price-total a').fadeOut();
				    }
				}
        
        
        /* --- Voice prompts --- */
        
				if ($('#store-order form #voice-prompts.existing fieldset').size() > 0) {
					var existingFieldsets = $('#store-order form #voice-prompts.existing fieldset');
				}
				
				var voicePromptHelp = $('#store-order form #voice-prompts fieldset p.help').html();
        $('#store-order form #voice-prompts fieldset').remove();
        
        var voicePromptNumber = 1;
        
        function prepVoicePromptFieldset(vp, vpTitle, vpComments, totalFieldsets) {
            var html = '';
						if (vp === undefined) {
							html += '<fieldset id="voice-prompts-fieldset-' + voicePromptNumber + '">';
						} else {
							html += '<fieldset id="voice-prompts-fieldset-' + voicePromptNumber + '" class="existing">';
						}
						if (LANGUAGE == 'fr') {
							html += '	<legend>Message téléphonique ' + voicePromptNumber + '</legend>';
	            html += '	<a href="#" class="help">Afficher aide</a>';
						} else {
							html += '	<legend>Voice prompt ' + voicePromptNumber + '</legend>';
	            html += '	<a href="#" class="help">Show help</a>';
						}
						html += '	<p class="help" style="display: none;">' + voicePromptHelp + '</p>';
            html += '	<ul>';
            html += '		<li class="voice-prompt">';
						if (vp === undefined) {
							if (LANGUAGE == 'fr') {
								html += '			<p class="remove"><a href="#">Effacer ce message téléphonique</a></p>';
								html += '			<label for="order_new_voice_prompt_attributes__voice_prompt">Message téléphonique (un seul message par boîte de texte de <em>Message téléphonique</em>) :</label>';
							} else {
								html += '			<p class="remove"><a href="#">Delete this voice prompts</a></p>';
								html += '			<label for="order_new_voice_prompt_attributes__voice_prompt">Voice prompt (only 1 file per <em>Voice prompt</em> box):</label>';
							}
							html += '			<textarea cols="40" id="order_new_voice_prompt_attributes__voice_prompt" name="order[new_voice_prompt_attributes][][voice_prompt]" rows="20"></textarea>';
						} else {
							if (LANGUAGE == 'fr') {
								html += '			<p class="remove"><a href="#">Effacer ce message téléphonique</a></p>';
							} else {
								html += '			<p class="remove"><a href="#">Delete this voice prompts</a></p>';
							}
							html += vp.html();
						};
						if (LANGUAGE == 'fr') {
							html += '			<p class="words">Mots inclus : <span class="included-words">0</span><br />Mots extras : <span class="extra-words">0</span><br />Mots total : <span class="total-words">0</span></p>';
						} else {
							html += '			<p class="words">Included words: <span class="included-words">0</span><br />Extra Words: <span class="extra-words">0</span><br />Total words: <span class="total-words">0</span></p>';
						}
            html += '		</li>';
						
						html += '		<li>';
						if (vpTitle === undefined) {
							if (LANGUAGE == 'fr') {
								html += '			<label for="order_new_voice_prompt_attributes__title">Nom du fichier (optionnel) :</label>';
							} else {
								html += '			<label for="order_new_voice_prompt_attributes__title">File name (optional):</label>';
							}
							html += '			<input class="text_field" id="order_new_voice_prompt_attributes__title" name="order[new_voice_prompt_attributes][][title]" size="30" type="text">';
						} else {
							html += vpTitle.html();
						}
						html += '		</li>';

            html += '		<li class="voice-prompt-comments">';
            if (vpComments === undefined) {
							if (LANGUAGE == 'fr') {
								html += '			<label for="order_new_voice_prompt_attributes__comments">Commentaires / Instructions spéciales (optionnel) :</label>';
							} else {
								html += '			<label for="order_new_voice_prompt_attributes__comments">Comments / Special instructions (optional):</label>';
							}
							html += '			<textarea cols="40" id="order_new_voice_prompt_attributes__comments" name="order[new_voice_prompt_attributes][][comments]" rows="20" style="display: none;"></textarea>';
						} else {
							html += vpComments.html();
						};
						if (LANGUAGE == 'fr') {
							html += '			<input type="button" class="button" value="Sauvegarder" style="display: none;" />';
	            html += '			<span></span> <a class="edit" href="#">écrire un commentaire</a>';
						} else {
							html += '			<input type="button" class="button" value="Save" style="display: none;" />';
	            html += '			<span></span> <a class="edit" href="#">write comments</a>';
						}
            html += '		</li>';
            html += '	</ul>';
						if (LANGUAGE == 'fr') {
							html += '	<p class="add"><a href="#">Ajouter un message téléphonique</a></p>';
	            html += '	<p class="price">Prix: <span>0.00</span> $ CAD</p>';
						} else {
							html += '	<p class="add"><a href="#">Add more voice prompts</a></p>';
	            html += '	<p class="price">Price: $<span>0.00</span> CAD</p>';
						}
            html += '</fieldset>';
            
            $(html).appendTo($('#store-order #voice-prompts')).slideDown(function() {
							if (vpComments !== undefined) {
								$(this).children('ul').children('li:eq(2)').children('textarea').hide();
								
								$('#store-order #voice-prompts fieldset').each(function(i){
                    $(this).attr('id', 'voice-prompts-fieldset-' + [i + 1])
										if (LANGUAGE == 'fr') {
					            $(this).children('legend').text('Message téléphonique ' + [i + 1]);
										} else {
											$(this).children('legend').text('Voice prompt ' + [i + 1]);
										}
                });
								
								if ($(this).children('ul').children('li:eq(2)').children('textarea').text() != "") {
									var comments = $(this).children('ul').children('li:eq(2)').children('textarea').text();
	                if (comments.length > 60) {
	                    comments = comments.substring(0, 60) + ' ...';
	                }
									if (LANGUAGE == 'fr') {
										$(this).children('ul').children('li:eq(2)').children('a.edit').text("éditer votre commentaire").prev().text(comments);
									} else {
										$(this).children('ul').children('li:eq(2)').children('a.edit').text("edit comments").prev().text(comments);
									}
								}
							}
						});
            
            if (voicePromptNumber == 1) {
                $('#store-order form #voice-prompts fieldset:first p.remove').hide();
            }
            
            $('#store-order form #voice-prompts li.voice-prompt-comments input.button').unbind().click(function(){
                var comments = $(this).prev().attr('value');
                if (comments.length > 60) {
                    comments = comments.substring(0, 60) + ' ...';
                }
                $(this).hide().prev().hide();
                if (comments != "") {
										if (LANGUAGE == 'fr') {
											$(this).next().text(comments).fadeIn().next().text("éditer votre commentaire").fadeIn();
										} else {
											$(this).next().text(comments).fadeIn().next().text("edit comments").fadeIn();
										}
                }
                else {
										if (LANGUAGE == 'fr') {
											$(this).next().text('').fadeIn().next().text("écrire un commentaire").fadeIn();
										} else {
											$(this).next().text('').fadeIn().next().text("write comments").fadeIn();
										}
                }
                return false;
            });
            $('#store-order form #voice-prompts li.voice-prompt-comments a').unbind().click(function(){
                $(this).hide().prev().hide().prev().fadeIn().prev().fadeIn();
                return false;
            });
            
            $('#store-order form #voice-prompts a.help').unbind().click(function(){
								if (LANGUAGE == 'fr') {
									$(this).toggleText('Cacher aide', 'Afficher aide').next().slideToggle();
								} else {
									$(this).toggleText('Hide help', 'Show help').next().slideToggle();
								}
                return false;
            });
            
            $('#store-order form #voice-prompts fieldset p.add a').unbind().click(function(){
                voicePromptNumber++;
                prepVoicePromptFieldset();
								$('#store-order form #voice-prompts fieldset:last p.add').show();
                $(this).parent().hide();
                if (voicePromptNumber == 10) {
                    $('#store-order form #voice-prompts fieldset:last p.add').hide();
                }
                $('#store-order form #voice-prompts fieldset:first p.remove').show();
                
                return false;
            });
            
            $('#store-order form #voice-prompts fieldset p.remove a').unbind().click(function(){
							voicePromptNumber--;
                $(this).parent().parent().parent().parent().slideUp(function(){
                    $(this).remove();
                    // Update the number of each attributes of the fieldset
                    $('#store-order #voice-prompts fieldset').each(function(i){
                        $(this).attr('id', 'voice-prompts-fieldset-' + [i + 1])
												if (LANGUAGE == 'fr') {
							            $(this).children('legend').text('Message téléphonique ' + [i + 1]);
												} else {
													$(this).children('legend').text('Voice prompt ' + [i + 1]);
												}
                    });
                    if (voicePromptNumber < 10) {
                        $('#store-order form #voice-prompts fieldset:last p.add').show();
                    }
                    if (voicePromptNumber == 1) {
                        $('#store-order form #voice-prompts fieldset:first p.remove').hide();
                    }
                    calculateTotals();
                });
                
                return false;
            });
            
            $('#store-order form #voice-prompts fieldset li.voice-prompt textarea').unbind().blur(function(){
                var wordsQuantity = 0;
                if ($(this).attr('value') == '') {
                    wordsQuantity = 0;
                }
                else {
                    wordsQuantity = jQuery.trim($(this).val()).split(/[\s]+/).length;
                }
								$(this).next().children('span.included-words').text('0');
								$(this).next().children('span.extra-words').text('0');
                $(this).next().children('span.total-words').text(wordsQuantity);
                calculateTotals();
            }).keyup(function(){
                var wordsQuantity = 0;
                if ($(this).attr('value') == '') {
                    wordsQuantity = 0;
                }
                else {
                    wordsQuantity = jQuery.trim($(this).val()).split(/[\s]+/).length;
                }
								$(this).next().children('span.included-words').text('0');
								$(this).next().children('span.extra-words').text('0');
                $(this).next().children('span.total-words').text(wordsQuantity);
                calculateTotals();
            });
			
						$('#store-order form #voice-prompts fieldset li.voice-prompt textarea:last').unbind().blur(function(){
							var wordsQuantity = 0;
							if ($(this).attr('value') == '') {
								wordsQuantity = 0;
							}
							else {
								wordsQuantity = jQuery.trim($(this).val()).split(/[\s]+/).length;
								$(this).parent().parent().next('p.add').show();
							}
							$(this).next().children('span.included-words').text('0');
							$(this).next().children('span.extra-words').text('0');
							$(this).next().children('span.total-words').text(wordsQuantity);
							calculateTotals();
            }).keyup(function(){
							var wordsQuantity = 0;
							if ($(this).attr('value') == '') {
								wordsQuantity = 0;
							}
							else {
								wordsQuantity = jQuery.trim($(this).val()).split(/[\s]+/).length;
								$(this).parent().parent().next('p.add').show();
							}
							$(this).next().children('span.included-words').text('0');
							$(this).next().children('span.extra-words').text('0');
							$(this).next().children('span.total-words').text(wordsQuantity);
							calculateTotals();
            });

						if (totalFieldsets !== undefined) {
							$('#store-order form #voice-prompts fieldset li.voice-prompt textarea').each(function(i) {
								var wordsQuantity = 0;
								if ($(this).attr('value') == '') {
									wordsQuantity = 0;
								}
								else {
									wordsQuantity = jQuery.trim($(this).val()).split(/[\s]+/).length;
									if ((i + 1) == totalFieldsets) {
										$(this).parent().parent().next('p.add').show();
									}
								}
								$(this).next().children('span.included-words').text('0');
								$(this).next().children('span.extra-words').text('0');
								$(this).next().children('span.total-words').text(wordsQuantity);
								calculateTotals();
							});
						}
            
            calculateTotals();
        }
        
				if (existingFieldsets) {
					var totalFieldsets = existingFieldsets.size();
					existingFieldsets.each(function(i) {
						var vp = $(this).children('ul').children('li:eq(0)');
						var vpTitle = $(this).children('ul').children('li:eq(1)');
						var vpComments = $(this).children('ul').children('li:eq(2)');
						prepVoicePromptFieldset(vp, vpTitle, vpComments, totalFieldsets);
					});
					voicePromptNumber = totalFieldsets;
				} else {
					prepVoicePromptFieldset();
				}
		
        
        
        /* --- File format --- */
        
        $('#store-order form fieldset#opt-audio-formats-fieldset .audio_format_select').change(function(){
			if ($('#store-order form fieldset#opt-audio-formats-fieldset li:eq(0) select').attr('value') == "MP3") {
				$(this).next().show();
				$(this).next().find('option:last').attr('selected', 'selected');
			} else {
				$(this).next().hide();
				$(this).next().find('option:first').attr('selected', 'selected');
			}
			
        	calculateTotals();
        });
        
		$('#store-order form fieldset#opt-audio-formats-fieldset li:eq(0) select:eq(1)').hide();
        $('#store-order form fieldset#opt-audio-formats-fieldset p.help').hide();
				if (LANGUAGE == 'fr') {
					$('#store-order form fieldset#opt-audio-formats-fieldset legend').after('<a href="#" class="help">Afficher aide</a>').next().click(function(){
	            $(this).toggleText('Cacher aide', 'Afficher aide').next().slideToggle();
	            return false;
	        });
				} else {
					$('#store-order form fieldset#opt-audio-formats-fieldset legend').after('<a href="#" class="help">Show help</a>').next().click(function(){
	            $(this).toggleText('Hide help', 'Show help').next().slideToggle();
	            return false;
	        });
				}
        
        if (LANGUAGE == 'fr') {
					$('#store-order form fieldset#opt-audio-formats-fieldset').append('<p class="price">Prix: <span>0.00</span> $ CAD</p>');
				} else {
					$('#store-order form fieldset#opt-audio-formats-fieldset').append('<p class="price">Price: $<span>0.00</span> CAD</p>');
				}
        
        
        /* --- Language --- */
        
        // When language is changed, recalculate
        $('#store-order form fieldset#opt-language-fieldset input[name=order[voice_prompt_language]]').change(function(){
            calculateTotals();
        });
        
        $('#store-order form fieldset#opt-language-fieldset p.help').hide();
				if (LANGUAGE == 'fr') {
					$('#store-order form fieldset#opt-language-fieldset legend').after('<a href="#" class="help">Afficher aide</a>').next().click(function(){
	            $(this).toggleText('Cacher aide', 'Afficher aide').next().slideToggle();
	            return false;
	        });
				} else {
					$('#store-order form fieldset#opt-language-fieldset legend').after('<a href="#" class="help">Show help</a>').next().click(function(){
	            $(this).toggleText('Hide help', 'Show help').next().slideToggle();
	            return false;
	        });
				}
        
				if (LANGUAGE == 'fr') {
					$('#store-order form fieldset#opt-language-fieldset').append('<p class="price">Prix: <span>0.00</span> $ CAD</p>');
				} else {
					$('#store-order form fieldset#opt-language-fieldset').append('<p class="price">Price: $<span>0.00</span> CAD</p>');
				}
		
		
				/* --- Options --- */
		
				$('#store-order form div#options fieldset ul').hide();
				$('#store-order form div#options fieldset a.help').hide();
				$('#store-order form div#options fieldset p.price').hide();
		
				$('#store-order form div#options fieldset legend a').click(function() {
					$(this).toggleClass('hide')
					$(this).parent().next().next().next().slideToggle(function() {
						$(this).prev().prev().toggle();
						
						$(this).next().show();
						if ($(this).prev().prev().prev().children().attr('class') == '' && $(this).next().children().text() == '0.00') {
							$(this).next().hide();
						}
						
						if (LANGUAGE == 'fr') {
							$(this).prev().prev().prev().children().children().toggleText('cliquer pour consulter', 'cliquer pour cacher');
						} else {
							$(this).prev().prev().prev().children().children().toggleText('click to hide', 'click to show');
						}
					});
					return false;
				});
				
				/* --- File attachments --- */
				
				$('#store-order form fieldset#file-attachments-fieldset p.help').hide();
				if (LANGUAGE == 'fr') {
					$('#store-order form fieldset#file-attachments-fieldset legend').after('<a href="#" class="help">Afficher aide</a>').next().click(function(){
	            $(this).toggleText('Cacher aide', 'Afficher aide').next().slideToggle();
	            return false;
	        });
				} else {
					$('#store-order form fieldset#file-attachments-fieldset legend').after('<a href="#" class="help">Show help</a>').next().click(function(){
	            $(this).toggleText('Hide help', 'Show help').next().slideToggle();
	            return false;
	        });
				}
        
    }
    
});

/** 		Plugins 		**/

/**
 * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 *
 * @param  f  onMouseOver function || An object with configuration options
 * @param  g  onMouseOut function  || Nothing (use configuration options object)
 * @author    Brian Cherne <brian@cherne.net>
 */
(function($){
    $.fn.hoverIntent = function(f, g){
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        cfg = $.extend(cfg, g ? {
            over: f,
            out: g
        } : f);
        var cX, cY, pX, pY;
        var track = function(ev){
            cX = ev.pageX;
            cY = ev.pageY;
        };
        var compare = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            }
            else {
                pX = cX;
                pY = cY;
                ob.hoverIntent_t = setTimeout(function(){
                    compare(ev, ob);
                }, cfg.interval);
            }
        };
        var delay = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };
        var handleHover = function(e){
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) {
                try {
                    p = p.parentNode;
                } 
                catch (e) {
                    p = this;
                }
            }
            if (p == this) {
                return false;
            }
            var ev = jQuery.extend({}, e);
            var ob = this;
            if (ob.hoverIntent_t) {
                ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            }
            if (e.type == "mouseover") {
                pX = ev.pageX;
                pY = ev.pageY;
                $(ob).bind("mousemove", track);
                if (ob.hoverIntent_s != 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        compare(ev, ob);
                    }, cfg.interval);
                }
            }
            else {
                $(ob).unbind("mousemove", track);
                if (ob.hoverIntent_s == 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        delay(ev, ob);
                    }, cfg.timeout);
                }
            }
        };
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);

/** 
 * Toggle Text
 *
 * @param {Object} a	Toggle text || First text
 * @param {Object} b	Toggle text || Second text
 */
jQuery.fn.toggleText = function(a, b){
    return this.each(function(){
        jQuery(this).text(jQuery(this).text() == a ? b : a);
    });
};

/**
 * jQuery Format Currency Plugin
 * http://code.google.com/p/jquery-formatcurrency/
 * @param {Object} $
 */
(function($){
    $.formatCurrency = {};
    $.formatCurrency.regions = [];
    $.formatCurrency.regions[""] = {
        symbol: "$",
        positiveFormat: "%s%n",
        negativeFormat: "(%s%n)",
        decimalSymbol: ".",
        digitGroupSymbol: ",",
        groupDigits: true
    };
    $.fn.formatCurrency = function(destination, settings){
        if (arguments.length == 1 && typeof destination !== "string") {
            settings = destination;
            destination = false
        }
        var defaults = {
            name: "formatCurrency",
            colorize: false,
            region: "",
            global: true
        };
        defaults = $.extend(defaults, $.formatCurrency.regions[""]);
        settings = $.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region))
        }
        return this.each(function(){
            $this = $(this);
            var num = "0";
            num = $this[$this.is("input, select, textarea") ? "val" : "html"]();
            var trimRegex = new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
            num = num.replace(trimRegex, "");
            if (settings.decimalSymbol != ".") {
                num = num.replace(settings.decimalSymbol, ".")
            }
            if (isNaN(num)) {
                num = "0"
            }
            var isPositive = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100);
            var cents = num % 100;
            num = Math.floor(num / 100).toString();
            if (cents < 10) {
                cents = "0" + cents
            }
            if (settings.groupDigits) {
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                    num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3))
                }
            }
            num = num + settings.decimalSymbol + cents;
            var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
            var money = format.replace(/%s/g, settings.symbol);
            money = money.replace(/%n/g, num);
            if (!destination) {
                destination = $this
            }
            else {
                destination = $(destination)
            }
            destination[destination.is("input, select, textarea") ? "val" : "html"](money);
            if (settings.colorize) {
                destination.css("color", isPositive ? "black" : "red")
            }
        })
    };
    $.fn.toNumber = function(settings){
        var defaults = $.extend({
            name: "toNumber",
            region: "",
            global: true
        }, $.formatCurrency.regions[""]);
        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region))
        }
        return this.each(function(){
            var method = $(this).is("input, select, textarea") ? "val" : "html";
            var trimRegex = new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
            $(this)[method]($(this)[method]().replace(trimRegex, ""))
        })
    };
    $.fn.asNumber = function(settings){
        var defaults = $.extend({
            name: "asNumber",
            region: "",
            parse: true,
            parseType: "Float",
            global: true
        }, $.formatCurrency.regions[""]);
        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region))
        }
        settings.parseType = validateParseType(settings.parseType);
        var method = $(this).is("input, select, textarea") ? "val" : "html";
        var trimRegex = new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
        var num = $(this)[method]().replace(trimRegex, "");
        if (!settings.parse) {
            return num
        }
        if (num.length == 0) {
            num = "0"
        }
        if (settings.decimalSymbol != ".") {
            num = num.replace(settings.decimalSymbol, ".")
        }
        return window["parse" + settings.parseType](num)
    };
    function getRegionOrCulture(region){
        var regionInfo = $.formatCurrency.regions[region];
        if (regionInfo) {
            return regionInfo
        }
        else {
            if (/(\w+)-(\w+)/g.test(region)) {
                var culture = region.replace(/(\w+)-(\w+)/g, "$1");
                return $.formatCurrency.regions[culture]
            }
        }
        return null
    }
    function validateParseType(parseType){
        switch (parseType.toLowerCase()) {
            case "int":
                return "Int";
            case "float":
                return "Float";
            default:
                throw "invalid parseType"
        }
    }
})(jQuery);
