/**
 *
 * Copyright (c) 2013, EvoStream Inc.  All rights reserved.
 *
 * This software is provided free of charge to be used solely in conjunction
 * with the EvoStream Media Server.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the source code retain the above 
 * copyright notice, this list of conditions and the following disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 **/
	    
jQuery(document).ready(function(){
    
    $('#accountSettings').click(function () {
	$('#accountSettingsPanel').slideToggle(500);
	return false;
    });   
    
    //Load Account Lists on Tables
    function loadAccount(){
	var username;
	var ctr = 1;
	$.ajax({
	    type:'POST',
	    url:'phpacct/accounts.php',
	    data:'cmd=loadAccounts',
	    dataType:'json',
	    async: true,
	    error: function(json, status){
		alertBox("Loading of accounts encountered an error");   
	    },
	    success:function(json){
		for (var username in json) {
		    if(username == 'admin'){
			$('#accountTable tbody').append('<tr class="center" data-rowIndex="'+ ctr++ +'" ><td class="username">'+ username +'</td><td><a class="cmdResetPassword" href="#">Reset Password</a></td><td><a class="cmdChangePassword" href="#">Change Password</a></td><td></td></tr>');
		    }else{
			$('#accountTable tbody').append('<tr class="center" data-rowIndex="'+ ctr++ +'" ><td class="username">'+ username +'</td><td><a class="cmdResetPassword" href="#">Reset Password</a></td><td><a class="cmdChangePassword" href="#">Change Password</a></td><td><a class="cmdDeleteAccount" href="#">Delete Account</a></td></tr>');
		    }
		    
		}
	    }
	});  	
    }
    loadAccount();
                      
    // Reset Password
    $('.cmdResetPassword').live('click', function(){
	var rowIndex = $(this).closest('tr').attr('data-rowIndex');
	var username = $('#accountTable tr:eq(' + rowIndex + ') td:eq(0)').html();
	$.ajax({
	    type:'POST',
	    url:'phpacct/accounts.php',
	    data:'cmd=resetPassword&username=' + username,
	    dataType:'json',
	    async: true,
	    error: function(json, status){
		alertBox('Resetting password encountered an error');
	    },
	    success:function(json){
		if(json.success == true)
		    alertBox('Password Reset Successful');
		
	    }
	});   

	return false;
    });    
    
    // Change Password Panel
    $('.cmdChangePassword').live('click', function(){
	var rowIndex = $(this).closest('tr').attr('data-rowIndex');

	$('#changePasswordPanel').modal();
	$('#okChangePassword').attr('data-rowIndex',rowIndex);

	return false;
    });        
   
    //Proceed Change Password
    $('#okChangePassword').live('click', function(){
	var rowIndex = $(this).attr('data-rowIndex');
	var username = $('#accountTable tr:eq(' + rowIndex + ') td:eq(0)').html();
	var password = $('#changePasswordText').attr('value');
	
	if(password == ''){
	    showError('changePasswordError', "Enter a valid password");
	    return false;
	}
	
	if(checkPassword(password) == false)   
	{   
	    showError('changePasswordError', "Enter a valid password <br />Password must be between 7 to 16 characters \nwhich contain only characters, numeric digits, underscore \nand first character must be a letter");
	    return false;
	}  

	$.ajax({
	    type:'POST',
	    url:'phpacct/accounts.php',
	    data:'cmd=changePassword&username=' + username +'&password=' + password,
	    dataType:'json',
	    async: true,
	    error: function(json, status){
		showError('changePasswordError', "Changing of password encountered an error");
	    },
	    success:function(json){
		if(json.success == true)
		    alertBox('Password Change Successful');
		$.modal.close();
		$('#accountTable tbody').empty();
		loadAccount();		
		
	    }
	}); 

	return false;
    });     
    
    //Check a password between 7 to 16 characters which 
    //contain only characters, numeric digits, underscore and first character must be a letter 
    function checkPassword(password)   
    {   
	var passw = /^[A-Za-z]\w{7,14}$/;  
	if(password.match(passw))   
	{   
	    return true;  
	}  
	else  
	{   
	    return false;  
	}  
    }      
    
    
    // Delete Account
    $('.cmdDeleteAccount').live('click', function(){
	var rowIndex = $(this).closest('tr').attr('data-rowIndex');
	var username = $('#accountTable tr:eq(' + rowIndex + ') td:eq(0)').html();
	
	var deleteAction = confirm('Confirm delete of this account - '+username +' ?');
	
	if (deleteAction == true)
	{
	    $.ajax({
		type:'POST',
		url:'phpacct/accounts.php',
		data:'cmd=deleteAccount&username=' + username,
		dataType:'json',
		async: true,
		error: function(json, status){
		    alertBox('Encountered an error when deleting account');
		},
		success:function(json){
		    if(json.success == true){
			$('#accountTable tbody').empty();
			loadAccount();
		    }
		    
		    		
		}
	    });   
	}

	return false;
    });       
    
    // Add Account
    $('#cmdAddAccount').live('click', function(){
	$('#addAccountPanel').modal();
	return false;
    });         
    
    //Proceed Adding of Account
    $('#okAddAccount').live('click', function(){
	var username = $('#usernameText').attr('value');
	var password = $('#passwordText').attr('value');

	if(username == ''){	    
	    showError('usernameError', "Enter a valid username <br />Username must be between 7 to 16 characters \nwhich contain only characters, numeric digits, underscore \nand first character must be a letter");	  
	    return false;
	}
	
	if(checkPassword(username) == false)   
	{
	    showError('usernameError', "Enter a valid username <br />Username must be between 7 to 16 characters \nwhich contain only characters, numeric digits, underscore \nand first character must be a letter");
	    return false;
	}  
	
	if(password == ''){
	    showError('passwordError', "Enter a valid password <br />Password must be between 7 to 16 characters \nwhich contain only characters, numeric digits, underscore \nand first character must be a letter");
	    return false;
	}
	
	if(checkPassword(password) == false)   
	{   
	    showError('passwordError', "Enter a valid password <br />Password must be between 7 to 16 characters \nwhich contain only characters, numeric digits, underscore \nand first character must be a letter");
	    return false;
	}  	
	

	$.ajax({
	    type:'POST',
	    url:'phpacct/accounts.php',
	    data:'cmd=addAccount&username=' + username +'&password=' + password,
	    dataType:'json',
	    async: true,
	    error: function(json, status){
		alertBox("Adding of Account encountered an error");
	    },
	    success:function(json){
		if(json.success == true){
		    alertBox('Adding of Account Successful');
		    $.modal.close();
		    $('#accountTable tbody').empty();
		    loadAccount();
		}else{
		    showError('accountError', json.message);
		}
	    }
	}); 

	return false;
    });          
    
    function alertBox(message) {	
	$('#alertBox').modal({	    
	    zIndex: 1010,
	    onShow: function (dialog) {
		$('.message', dialog.data[0]).append(message);		
	    } 
	});	
    }       
        
    // Display error or success status messages
    function showError(typeError, msg) {
	var statMsg = '';

	// Create the status display
	statMsg = '<div class="notice error"><span class="icon" data-icon="x"></span>' + msg + ' <a href="#close" class="icon close" data-icon="x"></a></div>';

	// Update the DIV container of the status
	$("#"+typeError).html(statMsg);

	// Rerun the html kick start script for newly created html tags
	doKickStart();
    }
    
    
});	    


