var server_result = '';
var searchStatus = 0;
var SEARCH_RESULTS = 80;
var SEARCH_ERROR = 81;
var SEARCH_EDITED = 82;
var PROCEED_UPLOAD = 90;


jQuery(document).ready(function () {


    jQuery('#filebase-upload').click(function() {
   
        // validate essential data
        // if invalid show error
        // - else send via ajax for search
		
		// if upload is clicked after search results are shown and the
		// input fields have not been modified.. proceed with upload
		if (searchStatus === SEARCH_RESULTS) {
			jQuery('#filebase-msg').fadeOut('normal');
			return true;
		}
		
 
        post_vars = '';
        errors    = '';
        
        jQuery('select, input, textarea').each(function() {
            //
            input_key = jQuery(this).attr('id');
            input_val = jQuery(this).val();
        
            // use only the inputs that have an id that starts with "file-"
            if (input_key.substring(0,5) == 'file-') {
                //
                
                if (jQuery.trim(input_val) == '') {
                    errors += '<p>' + buildErrorMsg(input_key) + '</p>';
                } else if (input_key == 'file-track' && input_val != '' ) {
                    if (input_val.substr(-4, 4).toLowerCase() != '.mp3') {
                        errors += '<p>Only .mp3 files are allowed</p>';
                    }
                }
                
                post_vars += input_key + '=' + input_val + '&';
            }
        });
        //.. each input
        
        if (errors) {
            // 
            cleanMsgs()
            jQuery("#filebase-msg h3").after(errors);
            jQuery("#filebase-msg").removeClass().addClass('fb-error').fadeIn("slow");
			jQuery('#ladebalken2').remove();
			
			return false;
        } else {
            // search database for duplicate tracks
            post_vars += 'ajax=1'; 
      
            jQuery("#filebase-msg").fadeOut("normal", function() {
                jQuery("#filebase-msg").removeClass();
                cleanMsgs();
                
                jQuery.ajax({
                    type: "POST",
                     url: "filebase_search.php",
                    data: post_vars,
                datatype: "json",
                beforeSend: function() {
                    jQuery("#filebase-msg h3").html("Searching filebase..").after("<p>Please wait while we search for similar tracks already in the filebase");
                    jQuery("#filebase-msg").removeClass().addClass("fb-search").fadeIn("slow");
                    
                },
                success: function(returned){
                    
                    // if nothing found then just proceed to normal upload
                    // - else display results
                    
                    jsond = eval("("+returned+")");
                    
                    setTimeout(function() {
                        
                        jQuery("#filebase-msg").fadeOut("normal", function() {
                            cleanMsgs();
						
							if (jsond.success) {
								searchStatus = PROCEED_UPLOAD;
								zeigeBalken();
								return;
							} else {
								jQuery("#filebase-msg > h3").html("Search Results").after('<p>'+jsond.output+'</p>');
								jQuery("#filebase-msg").removeClass().addClass("fb-success").fadeIn("slow");
								searchStatus = SEARCH_RESULTS;  	
							}
                        });
                        
                    }, 1200);
                }
                // success:
            });
            //.. Ajax
				
		});//.. msg fade
    } // end else
	
	return false;
}); //..click
	
	
	jQuery('.mod-file-upload input, .mod-file-upload textarea').keypress(function() {
		//
		if(searchStatus === SEARCH_RESULTS) {
			searchStatus = SEARCH_EDITED;
		}
	});
    
    
    jQuery('#credit-submit').click(function() {
        
        msg = '';
               
        user   = htmlspecialchars(jQuery.trim(jQuery('#credit_user').val()));
        amount = jQuery.trim(jQuery('#credit_amount').val());
        action = jQuery('#credit_action').val();
        
        if (action != 'add') {
            if (action != 'remove') {
                msg += '<b>Invalid Request - Please contact developer</b>';
            }
        }
        
        if (user == '') {
            msg += '<p>Please enter a username</p>';
        }
            
        if (!isNumeric(amount)) {
            msg += '<p>Credit field must contain a valid number of at least 1</p>';    
        } else if (amount < 1) {
            msg += '<p>Credit field must contain a valid number of at least 1</p>';    
        }
        
        jQuery('#acp-credit-msg').fadeOut('fast', function() {
            
            if (msg) {
                jQuery('#acp-credit-msg').html('').removeClass().addClass('credits-error').append(msg).fadeIn('normal');
            } else {
        
                jQuery('#acp-credit-msg').html('')
                                         .removeClass()
                                         .addClass('credits-working')
                                         .append('Performing credit update')
                                         .fadeIn('normal', function() { modifyUserCredits(user, amount, action);});
                
            }
        });
        
        return false;
    });
    
});
//.. document ready


function modifyUserCredits(user, amount, action)
{
    jQuery.ajax({
            type: 'POST',
             url: 'http://www.2shaderecords.co.uk/forum/adm/user_credits.php',
            data: 'username='+escape(user)+'&credit_amt='+escape(amount)+'&action='+escape(action),
        dataType: "json",
        success: function(returned) {
                if (returned.is_success) {
                    msg_class = 'credits-success';
                } else {
                    msg_class = 'credits-error';
                }
                
                jQuery('#acp-credit-msg').fadeOut('fast', function() {
                    jQuery('#acp-credit-msg').html('').removeClass().addClass(msg_class).append(returned.value).fadeIn('normal');    
                });
                
            }
        });
}



function cleanMsgs()
{
    jQuery("#filebase-msg > p, #filebase-msg > ul, #matches-msg").remove();  
}

function buildErrorMsg(field)
{
    if (field == 'file-name') {
        msg = 'Please give the track a name';
    }
    
    if (field == 'file-category') {
        msg = 'Please select a category for this track';
    }
    
    if (field == 'file-titel') {
        msg = 'Please give the track a short description';
    }
    
    if (field == 'file-track') {
        msg = 'Please select a track to upload';
    }
    
    return msg;
}


function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function isNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }
   
function htmlspecialchars(str) {
 if (typeof(str) == "string") {
  str = str.replace(/&/g, "&amp;"); /* must do &amp; first */
  str = str.replace(/"/g, "&quot;");
  str = str.replace(/'/g, "&#039;");
  str = str.replace(/</g, "&lt;");
  str = str.replace(/>/g, "&gt;");
  }
 return str;
 }
   




