// YTUploader 1.0
// stefan.barasso@loki.sk

// default script napespace to prevent collisions with other scripts
YTUploader = (typeof YTUploader == "undefined") ? {} : YTUploader;

// simple form validator
YTUploader.Validate = function(f){
    var inputs = $("#" + f + " input[type=text], input[type=file]");
    
    for (var i=0;i<inputs.length;i++)
    {
       if (inputs[i].value=="")
       {
            return false;
       } 
    }
    
    return true;
}

// youtube handler
YTUploader.SendVideo = function(btn){
    // disable the submit button to prevent multiple postbacks
    btn.disabled = true;
    
	// validate form
    if (YTUploader.Validate("YTUploader_form"))
	{
        // display wait message
        $("#wait").show("slow");

		// populate object with parameters
        var r = {
			video_name : $("#YTUploader_name").val(),
			video_description : $("#YTUploader_description").val(),
			video_tags : $("#YTUploader_tags").val()
		}
        
	    // send object to retrieve post iformation from youtube
        $.get(YTUploader.youtubeRedirectURL, r, function(data) {
    		
            // try to eval the data retrieved (we create a new object)
            try
    		{
				eval(data);
			}
			catch(err)
			{
			}
            
    		// check if the new object exists
            if (typeof VideoResponse != "undefined")
    		{
    			// fill the form with correct values
                $("#YTUploader_form").attr("action", VideoResponse.postUrl + "?nexturl=" + VideoResponse.nextUrl + "?guid=" + VideoResponse.guid);
    			$("#YTUploader_token").val(VideoResponse.tokenValue);
                
                // submit the form and movie to youtube
    			$("#YTUploader_form").submit();
    		}
    		else
    		{
                alert("Something went wrong! Please check settings.");

                // hide wait message
                $("#wait").hide();

                btn.disabled = false;
    		}
            
    	}, "text")
		
	}
	else
	{
        alert("Please fill out all required fields!");

        // hide wait message
        $("#wait").hide();

        btn.disabled = false;
	}
	
	return false;
}


