//var rootUrl = "/activepictures/clients/";
var rootUrl = "/clients/";

var loadingDiv = "#loading";
var contentDiv = "#content";
var messageDiv = "#message";
var videoLoadingDiv = "#videoloading";

var addClientLink = ".addclient";
var editClientsLink = ".editclients";

var addVideoLink = ".addvideo";
var showVideosLink = ".showvideos";

var speed = 200;

function ShowLoading(callback){
//	alert("show loading");
	$(messageDiv).html("");
	$(contentDiv).fadeOut(speed,
		function(){
			$(loadingDiv).fadeIn(speed, callback);
		}
	);	
}

function HideLoading(callback){
//		alert("hide loading");
	$(loadingDiv).fadeOut(speed,
			function(){
				$(contentDiv).fadeIn(speed, callback);
			}
		);
}

// Loads the client list into the content div
function LoadClientList(){
	ShowLoading(function(){
		$(contentDiv).load(
			rootUrl + "_fragments/listclients.php" + location.search,
			// attach the click event to anchor elements
			function(){
				$(contentDiv + " a").click(function(){
					// Handle the clicks
					if(this.className == "DeleteClient"){
						DeleteClient(this.hash.replace("#",""));
					}
					
					// Handle edit links
					if(this.className == "EditClient"){
						ShowClientForm(this.hash.replace("#",""));
					}
				});
			},
			HideLoading()
			);
		});
}

function AttachVideoListLinks(){
	$(contentDiv + " a").click(function(){
		// Handle the clicks
		if(this.className == "DeleteVideo"){
			DeleteVideo(this.hash.replace("#",""));
		}
	});
}

// Delete a client from the db
function DeleteClient(clientId){
	if(confirm("Are you sure you want to delete this client?")){
		$.get(rootUrl + "_fragments/deleteclient.php?del=" + clientId);
		// Hide the row
		$(".row."+ clientId).fadeOut();
	}
}

// Attach the click event to add client links
function AttachClientLinks()	{
	$(addClientLink).click(function(){ShowClientForm();});
	$(editClientsLink).click(function(){LoadClientList();});
}

// Show the client form
function ShowClientForm(clientId){
		// Show the loading layer
		ShowLoading(function(){
			// Load the add client form and show it
			var url = rootUrl + "_fragments/formclient.php";
			if(clientId != undefined){
				url += "?ClientId=" + clientId;
			}
			$(contentDiv).load(url,
				function(){
					HideLoading();
			});
	});
}

// Validate the client form
function ValidateClientForm(clientName, clientEmail, clientPassword, clientImage){
	if(
	clientName.attr("value") != "" &&
//	clientEmail.attr("value") != "" &&
	clientPassword.attr("value") != "" && 
	(clientImage != null || clientImage.attr("value") != "")){
		return true;
	} else {
		alert("Please check you have completed all fields");
		return false;
	}
}

// Add/edit client
function ProcessClientForm(clientId, clientName, clientEmail, clientPassword){
	// post the values to the processing script
	if(
   clientName.attr("value") != "" &&
   clientEmail.attr("value") != "" &&
   clientPassword.attr("value") != ""){
		var url = rootUrl + "_fragments/processclient.php";
		ShowLoading(function(){
		$.post(url,
				{
					clientid: clientId.attr("value"),
					clientname: clientName.attr("value"),
					clientpassword: clientPassword.attr("value"),
					clientemail: clientEmail.attr("value")
				},
				function(data){
					LoadClientList();
					$(messageDiv).html(data);
				}
				)});
	} else {
		alert("Please check that you have completed all fields");
	}
}

// Email password to client
function EmailClientPassword(clientId){
	var url = rootUrl + "_fragments/clientemailpassword.php";
	$.post(
			url,
			{clientid: clientId},
			function(data){
				$("#message").html(data);
			}
		);
}

/** JS FUNCTIONS FOR VIDEO MANAGEMENT **/

function AttachVideoLinks(){
	$(addVideoLink).click(function(){ShowVideoForm();});
	$(showVideosLink).click(function(){LoadVideoList();});
}

//Show the video form
function ShowVideoForm(videoId){
	// Show the loading layer
	ShowLoading(function(){
		// Load the add client form and show it
		var url = rootUrl + "_fragments/formvideo.php";
		if(videoId != undefined){
			url += "?videoId=" + videoId;
		}
		$(contentDiv).load(url,
			function(){
				HideLoading();
		});
	});
}

//Loads the video list into the content div
function LoadVideoList(){
	$.ajaxSetup ({
	    // Disable caching of AJAX responses */
	    cache: false
	});

	ShowLoading(function(){
		$(contentDiv).load(
			rootUrl + "_fragments/listvideos.php" + location.search,
			// attach the click event to anchor elements
			function(){
				$(contentDiv + " a").click(function(){
					// Handle the clicks
					if(this.className == "DeleteVideo"){
						DeleteVideo(this.hash.replace("#",""));
					}
					
					// Handle edit links
					if(this.className == "EditVideo"){
						ShowVideoForm(this.hash.replace("#",""));
					}
				});
			},
			HideLoading()
			);
		});
}


//Add/edit video
function ProcessVideoForm(videoId, videoTitle, videoNotes, videoClientId, videoFile){
	// post the values to the processing script
	alert("Processing");
	var url = rootUrl + "_fragments/processvideo.php";
	$.post(url,
			{
				videoid: videoId.attr("value"),
				videotitle: videoTitle.attr("value"),
				videonotes: videoNotes.attr("value"),
				videoclientid: videoClientId.attr("value"),
				videofilename: videoFile
			},
			function(data){
				alert(data);
				$(messageDiv).html(data);
				LoadVideoList();
			}
			);
	return false;
}

//Delete a video from the db
function DeleteVideo(videoId){
	if(confirm("Are you sure you want to delete this video?")){
		$.get(rootUrl + "_fragments/deletevideo.php?del=" + videoId);
		// Hide the row
		$(".row."+ videoId).css({float:"none"});
		$(".row."+ videoId).fadeOut();
	}
}

// Ajax upload
function VideoUpload(videoId, videoTitle, videoNotes, videoClientId, videoFile)
{
	var filename = "";
    //starting setting some animation when the ajax starts and completes
    $(videoLoadingDiv)
    .ajaxStart(function(){
        $(this).fadeIn(speed);
    });

    /*
        prepareing ajax file upload
        url: the url of script file handling the uploaded files
		fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
        dataType: it support json, xml
        secureuri:use secure protocol
        success: call back function when the ajax complete
        error: callback function when the ajax failed
        
            */
    $.ajaxFileUpload
    (
        {
            url:'_fragments/processvideoupload.php', 
            secureuri:false,
            fileElementId:'cvideofile',
            dataType: 'text',
            success: function (data, status)
            {
                if(typeof(data.error) != undefined)
                {
                    if(data.error != '' && data.error != undefined)
                    {
                        alert("Error: " + data.error);
                    }else
                    {
                    	// set the video details
						alert("Message : " + data.msg.filename);
                    	ProcessVideoForm(videoId, videoTitle, videoNotes, videoClientId, data.msg.filename);
                    }
                }
                
            },
            error: function (data, status, e)
            {
                alert("Crit error: " + e);
				alert(data.msg);
            }
        },
        HideLoading()
    );
    
    return false;

} 


// Load the html for a video and place it in the speciifed container 
function LoadVideo(videoContainerId, videoId){
	ShowLoading(function(){
		var url = rootUrl + "_fragments/getvideohtml.php?videoid=" + videoId;
		$(videoContainerId).load(url, function(data){HideLoading();});
		
	});
}

function LoadClientVideos(){
		var url = rootUrl + "_fragments/listclientvideos.php";
		$("#videolist").load(url);
}