var prices = {
	
	// Songs up to {% min_minutes %} minutes will cost a {% up_to_min_minutes %} amount, every minute or portion of a 
	// minute after that will be an additional {% per_minute_after %}. If the song requires lyrics (box un checked) and no 
	// no lyrics are uploaded, there is a {% lyrics_fee %} transcription fee.
	
	min_minutes: 4,
	up_to_min_minutes: 39,
	per_minute_after: 10,
	lyrics_fee: 10
}

var lines_id = 1;
function re_calculate_price() {
	var total = 0;
    $('.song').each(function () {
    	if ($(this).find('.title').val()=='') {
    		return true; //Ignore instance since there is no uploaded song
    	}
        var duration = $(this).find('.time').val().split(':');
        var minutes = parseInt(duration[0]), seconds = parseInt(duration[1]);
        var song_requires_lyrics = !$(this).find('.song-does-not-require-lyrics').is(':checked');
        var has_attached_file = $(this).find('.lyrics').val()!='';
        
        var price = 0;
        
        if (minutes < prices.min_minutes) {
        	price += prices.up_to_min_minutes;
        } else {
        	if (seconds!=0) {
        		minutes++;
        	}
        	price = prices.up_to_min_minutes + (minutes - prices.min_minutes) * prices.per_minute_after;
        }
        
        if (song_requires_lyrics && !has_attached_file) {
        	price += prices.lyrics_fee;
        }
        
        total += price;
    });
    if (isNaN(total)) {
    	$('p.cost').hide();
    	return;
    }
    $('p.cost').show();
    $('p.cost span').html("$" + total);
    $('input[name=price]').val("$" + total);
}
var song_structure_html = $('.song:first').clone();
function init_flash_uploader(btn_id) {
	
	// Songs uploader
    new SWFUpload({
		// Backend Settings
		upload_url: "upload.php",
		post_params: {"PHPSESSID": PHPSESSID},

		// File Upload Settings
		file_size_limit: "150 MB",	
		file_types: get_allowed_formatts(),
		file_types_description: "Music files",
		file_upload_limit: "0",

		// Event Handler Settings - these functions as defined in Handlers.js
		// The handlers are not part of SWFUpload but are part of my website and control how
		// my website reacts to the SWFUpload events.
		file_queue_error_handler: fileQueueError,
		file_dialog_complete_handler: fileDialogComplete,
		upload_progress_handler: uploadProgress,
		upload_error_handler: function () {},
		upload_success_handler: uploadSuccess,
		upload_complete_handler: function () {},

		// Button Settings
		button_image_url : "css/images/browse-song.gif",
		button_placeholder_id : "upload_song_" + btn_id,
		button_width: 127,
		button_height: 27,
		button_text : '<span class="button3"></span>',
		button_text_top_padding: 0,
		button_text_left_padding: 0,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,
		
		// Flash Settings
		flash_url : "swfupload/swfupload.swf",
		
		custom_settings: {
			row: btn_id
		},
		
		// Debug Settings
		debug: false
	});

	
	// Lyrics uploader
	new SWFUpload({
		// Backend Settings
		upload_url: "upload.php?lyrics",
		post_params: {"PHPSESSID": PHPSESSID},

		// File Upload Settings
		file_size_limit: "150 MB",	
		file_types: '*.doc;*.docx;*.pdf;*.txt;*.rtf',
		file_types_description: "Lyrics files",
		file_upload_limit: "0",
		
		// Event Handler Settings - these functions as defined in Handlers.js
		// The handlers are not part of SWFUpload but are part of my website and control how
		// my website reacts to the SWFUpload events.
		file_queue_error_handler: fileQueueError,
		file_dialog_complete_handler: lyrics_file_dialog_complete,
		upload_progress_handler: lyrics_upload_progress,
		upload_error_handler: function () {},
		upload_success_handler: lyrics_upload_success,
		upload_complete_handler: function () {},
		
		// Button Settings
		button_image_url : "css/images/browse-lyrics.gif",
		button_placeholder_id : "upload_lyrics_" + btn_id,
		button_width: 127,
		button_height: 27,
		button_text : '<span class="button3"></span>',
		button_text_top_padding: 0,
		button_text_left_padding: 0,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		button_cursor: SWFUpload.CURSOR.HAND,

		// Flash Settings
		flash_url : "swfupload/swfupload.swf",
		
		custom_settings : {
			row: btn_id
		},
		
		// Debug Settings
		debug: false
	});
	
}
jQuery(function ($) {
	song_structure_html = $('.song:first').clone();
	init_flash_uploader(1);
	$('input[type=hidden]').hide();
});
function error(msg) {
	if (msg==SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE) {
		msg = "You're trying to upload empty file";
	} else if (msg==SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
		msg = "You're trying to upload too big file";
	}
    alert(msg);
}
function fileQueueError(file, errorCode, message) {
	try {
		var imageName = "error.gif";
		var errorName = "";
		if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
			errorName = "You have attempted to queue too many files.";
		}

		if (errorName !== "") {
			alert(errorName);
			return;
		}
		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			error(SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE);
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			error(SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT);
			imageName = "toobig.gif";
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		default:
			error(message);
			break;
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	if (numFilesQueued > 0) {
		$('#uploading-overlay').modal();
		this.startUpload();
	}
}

function uploadProgress(file, bytesLoaded) {
	var percent = Math.ceil((bytesLoaded / file.size) * 100);
	$('#loading-inner').css('width', percent + '%');
}

function c(c) {
	return c < 10 ? '0' + c : c;
}

function uploadSuccess(file, response_data) {
	if (response_data=='Upload error') {
		alert("Sorry, error occured. Please try again");
	}
	eval('var response_data = (' + response_data + ')');
	
	var playtime_seconds = response_data.playtime_seconds
	var formatted = c(Math.floor(playtime_seconds / 60)) + ':' + c(playtime_seconds % 60);
	
	$('#song-' + this.customSettings.row + ' .title').val(response_data.title);
	$('#song-' + this.customSettings.row + ' .time').val(formatted);
	$('.simplemodal-close').click();
	re_calculate_price();
	
}
function lyrics_file_dialog_complete(numFilesSelected, numFilesQueued) {
	if (numFilesQueued > 0) {
		$('#uploading-overlay').modal();
		this.startUpload();
	}
}
function lyrics_upload_progress(file, bytesLoaded) {
    var percent = Math.ceil((bytesLoaded / file.size) * 100);
	$('#loading-inner').css('width', percent + '%');
}
function lyrics_upload_success(file, response_data) {
    if (response_data=='Upload error') {
		alert("Sorry, error occured. Please try again");
	}
	if (response_data=='unallowed file format') {
		// throw "assertation error E44";
		alert("Internal Error");
		$('.simplemodal-close').click();
		return;
	}
	eval('response_data = (' + response_data + ')');
	
	$('#song-' + this.customSettings.row + ' .lyrics').val(response_data.title);
	$('#song-' + this.customSettings.row + ' .song-does-not-require-lyrics').attr('checked', false);
	
	$('.simplemodal-close').click();
	
	re_calculate_price();
}

$(function () {
	$('.song-does-not-require-lyrics').live('click', function () {
		var corresponding_input = $(this).parents('tr:eq(0)').find('input[type=text]');
	    if ($(this).is(':checked')) {
	    	corresponding_input.data('orig-val', corresponding_input.val()).val('');
	    } else if (corresponding_input.data('orig-val')) {
	    	corresponding_input.val(corresponding_input.data('orig-val'));
	    }
	    re_calculate_price();
	});
	$('.button-add-another-song').click(function () {
		var c = song_structure_html.clone();
		var num = ++lines_id;
		
		c.attr('id', 'song-' + num)
		
		c.find('.increment-id').each(function () {
		    $(this).attr('id', $(this).attr('id').replace(/\d+$/, num));
		});
		
		c.find('.increment-name').each(function () {
		    $(this).attr('name', $(this).attr('name').replace(/\d+$/, num));
		});
		
	    $('.songs').append(c);
        init_flash_uploader(num);
	    return false;
	});
	
	$('.remove').live('click', function () {
		if ($('.song').length==1) {
			alert("You should upload at least one song");
			return false;
		}
	    $(this).parents('.song').remove();
	    re_calculate_price();
	    return false;
	    
	});
	
	$('.time').mask("99:99", {placeholder: " "});
	$('.time').keyup(re_calculate_price);
	
	// Validation
	$('.orderform').submit(function () {
	    var fname = $(this).find('[name=fname]');
	    if (fname.val()=='') {
	    	alert("Please enter first name");
	    	fname.focus();
	    	return false;
	    }
	    
	    var lname = $(this).find('[name=lname]');
	    if (lname.val()=='') {
	    	alert("Please enter last name");
	    	lname.focus();
	    	return false;
	    }
	    
	    var mail = $(this).find('[name=mail]');
	    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(mail.val())==false) {
	    	alert("Please enter valid email address");
	    	mail.focus();
	    	return false;
	    }
	    
	    var phone1 = $(this).find('[name=phone-1]'),
	    	phone2 = $(this).find('[name=phone-2]'),
	    	phone3 = $(this).find('[name=phone-3]');
	    if (phone1.val()=='' || phone2.val()=='' || phone3.val()=='') {
	    	alert("Please enter phone number");
	    	phone1.focus();
	    	return false;
	    }
	    return true;
	});
})