/**
 * Edit Contact Ajax Functions
 */

/**
 * Initailise Edit Contact
 * This initialises the edit contact and edit password form as they are in the same component
 */
function form_MyPwn_Edit_Contact_Init() {
    $('#form-edit-contact').ajaxForm({
        success:      form_MyPwn_Edit_Contact_Response,
        error:        formCommunicationError
    });
    $('#form-edit-password').ajaxForm({
        success:      form_MyPwn_Edit_Contact_EditPassword_Response,
        error:        formCommunicationError
    });
}

/**
 * Edit Contact Response
 */
function form_MyPwn_Edit_Contact_Response(responseText) {

    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'form-edit-contact', true);
    }

    $('#form-edit-contact-response-placeholder').fadeOut('slow', function() {
        $('#form-edit-contact-response-placeholder').html(responseArr['html']);
        /* applyCufon(); */
    });

    $('#form-edit-contact-response-placeholder').fadeIn('slow');

    return true;
}

/**
 * Edit Contact - Edit Password Response
 */
function form_MyPwn_Edit_Contact_EditPassword_Response(responseText) {

    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'form-edit-password', true);
    }

    $('#form-edit-contact-edit-password-response-placeholder').fadeOut('slow', function() {
        $('#form-edit-contact-edit-password-response-placeholder').html(responseArr['html']);
        /* applyCufon(); */
        $('#form-edit-contact-edit-password-response-placeholder').fadeIn('slow');
    });

    return true;
}

function form_MyPwn_Create_Pin_Init() {
    $('#form-create-pin').ajaxForm({
        beforeSubmit: form_MyPwn_Create_Pin_Validate,
        success:      form_MyPwn_Create_Pin_Response,
        error:        formCommunicationError
        
    });
    form_MyPwn_Create_Pin_showHideCreateContact();
}

function form_MyPwn_Create_Pin_showHideCreateContact(){
    if($('#contact_ref').val() == '') {
        $('#new_user_options').show();
    } else {
        $('#new_user_options').hide();
    }
}

function form_MyPwn_Create_Pin_Validate()
{
    $('#form-create-pin-submit').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
    $('#form-create-pin-submit').attr('disabled', 'true');
    return true;
}


/**
 * 
 */
function form_MyPwn_Create_Pin_Response(responseText) {

    $('#ajaxloader').remove();
    $('#form-create-pin-submit').removeAttr('disabled');

    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'form-create-pin', true);
    }

    alert(responseArr['html']);

    window.location = URL_MYPWN_PINS;

    return true;
}

/**
 * Edit Contact - Initialise Edit Call Settings - Plus and Premium
 */
function form_MyPwn_Edit_CallSettings_Init() {
    $('#form-edit-call-settings').ajaxForm({
        beforeSubmit: form_MyPwn_Edit_CallSettings_Validate,
        success:      form_MyPwn_Edit_CallSettings_Response,
        error:        formCommunicationError
    });
}

/**
 * Edit Contact - Initialise Edit Call Settings - Powwownow
 */
function form_MyPwn_Edit_CallSettings_Init1() {
    $('#form-edit-call-settings').ajaxForm({
        beforeSubmit: form_MyPwn_Edit_CallSettings_Validate1,
        success:      form_MyPwn_Edit_CallSettings_Response,
        error:        formCommunicationError
    });
}

/**
 * Validate Edit Call Settings. Confirmation Response Required - Plus and Premium
 */
function form_MyPwn_Edit_CallSettings_Validate() {
	var answer = confirm(MYPWN_CALLSETTINGS_CONFIRM);
    if (answer) {
        $('#form-call-settings-submit').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
        $('#form-call-settings-submit').attr('disabled', 'true');
    } else {
        return false;
    }
    return true;
}

/**
 * Validate Edit Call Settings. Confirmation Response Required - Powwownow
 */
function form_MyPwn_Edit_CallSettings_Validate1() {
    $('#form-call-settings-submit').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
    $('#form-call-settings-submit').attr('disabled', 'true');
    return true;
}

/**
 * Edit Contact - Edit Call Settings  Response
 */
function form_MyPwn_Edit_CallSettings_Response(responseText) {
    $('#ajaxloader').remove();
    $('#form-call-settings-submit').removeAttr('disabled');

    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'form-edit-call-settings', true);
    }

    $('#form-edit-call-settings-response-placeholder').fadeOut('slow', function() {
        $('#form-edit-call-settings-response-placeholder').html(eval('(' + responseArr['html'] + ')'));
    });

    $('#form-edit-call-settings-response-placeholder').fadeIn('slow');

    return true;
}

/**
 * Request Wallet Card Ajax Functions
 */

/**
 * Initialise Request Wallet Card
 */
function form_MyPwn_RequestWalletCard_Init() {
	$('.frmwalletcard').ajaxForm({
		success:      form_MyPwn_RequestWalletCard_Response,
		error:        formCommunicationError
	});
}

/**
 * Request Wallet Card Response
 */
function form_MyPwn_RequestWalletCard_Response(responseText) {
	responseArr = $.parseJSON(responseText);
    
    //Catch the Default Form Error Messages
	if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'frmwalletcard', true);
	}

    /*Build the Alert Output Box*/
    
    //Initial Messages
    var success1     = WALLET_CARD_REQUEST_SUCCESS_SINGLE; //Admin Success Message
    var failure1     = WALLET_CARD_REQUEST_FAILURE_SINGLE; //Admin Failure Message 1
    var failure2     = WALLET_CARD_REQUEST_EXCEEDED_MAX_SINGLE; //Admin Failure Message 2
    var failure3     = WALLET_CARD_REQUEST_NO_PERMISSION_SINGLE; //Admin Failure Message 3
    
    //Admin Success and Failure Pin Pair Lists
    var successList  = '';
    var failure1List = '';
    var failure2List = '';
    var failure3List = '';

    //Final Success and Failure Messages
    var successUser  = '';
    var success      = '';
    var failure      = '';

    //Build Success Messages
	if ((responseArr['success'] instanceof Array) && responseArr['success'].length > 0) {
        var successArr = responseArr['success'];
        for (successID in successArr) {
            successList = successList + successArr[successID]['chairPin'] + '/' + successArr[successID]['partPin'] + " , ";
        }
        
        //Update the Success Listings using Replace Command
        if (successList != '') {
            successList = successList.substring(0,successList.length-3);
            successList = success1.replace("%%PINPAIR%%", successList) + "\n";
        }
        
        success = successList;
        
	}else if ((responseArr['html'] instanceof Array) && responseArr['html'].length > 0) {
         //Single Welcome Pack
         //successUser = eval(responseArr['html']); //Not Sure of this Line
         successUser = WALLET_CARD_REQUEST_SUCCESS;
    }
    
    //Build Failure Messages
	if ((responseArr['fails'] instanceof Array) && responseArr['fails'].length > 0) {
        var failureArr = responseArr['fails'];
        for (failureID in failureArr) {
            var failureTMP = eval(failureArr[failureID]['message']);
            
            //Add Failure Type into Its own Failure Listing
            if (WALLET_CARD_REQUEST_FAILURE_SINGLE == failureTMP) {
                failure1List = failure1List + failureArr[failureID]['chairPin'] + '/' + failureArr[failureID]['partPin'] + " , ";
            }else if (WALLET_CARD_REQUEST_EXCEEDED_MAX_SINGLE == failureTMP) {
                failure2List = failure2List + failureArr[failureID]['chairPin'] + '/' + failureArr[failureID]['partPin'] + " , ";
            }else if (WALLET_CARD_REQUEST_NO_PERMISSION_SINGLE == failureTMP) {
                failure3List = failure3List + failureArr[failureID]['chairPin'] + '/' + failureArr[failureID]['partPin'] + " , ";
            }
        }
        
        //Update the Failure Listings using Replace Command
        if (failure1List != '') {
            failure1List = failure1List.substring(0,failure1List.length-3);
            failure1List = failure1.replace("%%PINPAIR%%", failure1List) + "\n";
        }
        
        if (failure2List != '') {
            failure2List = failure2List.substring(0,failure2List.length-3);
            failure2List = failure2.replace("%%PINPAIR%%", failure2List) + "\n";
        }
        
        if (failure3List != '') {
            failure3List = failure3List.substring(0,failure3List.length-3);
            failure3List = failure3.replace("%%PINPAIR%%", failure3List) + "\n";
        }
        
        failure = failure1List + failure2List + failure3List;
	}

    //Response Decider
    if (failure === '') {
        //There was no failure Requests, so Show Success Message and Redirect to MyPINS page
        alert(WALLET_CARD_REQUEST_SUCCESS);
        window.location = URL_MYPWN_PINS;
    }else if (success === '') {
        //There was no successfull Requests, so Show Failure Messages and Stay on Current page
        alert(failure);
    }else if (successUser != ''){
        //Success Non Admin
        alert(successUser);
    }else {
        //There was a mix of Successfull and Failed Requests, so Stay on Current page
        alert(success + "\n\n" + failure);
    }

	return true;
}

/**
 * Updates the wallet card preview with the selected pins
 */
function form_MyPwn_RequestWalletCard_UpdatePreview(chairPin, participantPin, firstName, surname) {

    $('#walletCardPreview_line_name').html(firstName + ' ' + surname);

    if (chairPin !== undefined) {
        $('#walletCardPreview_line_chairPin').show();
        $('#walletCardPreview_chairPin').html(chairPin);
    } else {
        $('#walletCardPreview_line_chairPin').hide();
    }

    if (participantPin !== undefined) {
        $('#walletCardPreview_participantPin').html(participantPin);
        $('#walletCardPreview_line_participantPin').show();
    } else {
        $('#walletCardPreview_line_participantPin').hide();
    }

}

/**
 * Refreshes the Call-Settings Page, with the correct Information
 */
function form_MyPwn_CallSettings_ReloadPage(pin_ref) {
    window.location = URL_MYPWN_CALL_SETTINGS + '?r[]=' + pin_ref;
}

/**
 * Call History Ajax Functions
 */

/**
 * Initial Date Picker Function for Call History Page
 */ 
function date_Picker_CallHistory_Init() {
    //Javascript Date Picker
    var today = new Date();
    var date100Days = new Date()
    date100Days.setDate(date100Days.getDate()-100);

    //From Date
    $("#from_date").datepicker({
        dateFormat:'yy-mm-dd',
        defaultDate:date100Days,
        minDate:date100Days,
        maxDate:today,
        showButtonPanel:true
    });

    //To Date
    $("#to_date").datepicker({
        dateFormat:'yy-mm-dd',
        defaultDate:today,
        minDate:date100Days,
        maxDate:today,
        showButtonPanel:true
    });

    //Close Information Message Box
    $('#mypwn-page-msgbox').click(function(){
        $(this).removeClass().html('').fadeOut('normal');
        $('#mypwn-page-mask').css({'opacity':0}).hide("fast");
    }); 
}
 
/**
 * Initialise Request Call History
 */
function form_MyPwn_CallHistory_Init() {
    $('.frmcallhistory').ajaxForm({
		beforeSubmit: function(){$('.frmcallhistory-results-placeholder').html('<div align="center"><img src="/img/ajax-loader-h.gif"></div>');return true;},
        success:      form_MyPwn_CallHistory_Response,
		error:        formCommunicationError
	});
}

/**
 * Call History Response
 */
function form_MyPwn_CallHistory_Response(responseText) {
	responseArr = $.parseJSON(responseText);

	//Clear Results
	$('.frmcallhistory-results-placeholder').html('');

	if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'frmcallhistory', true);
	}

	//Clone Headers from Head Table
	switch(responseArr['report_lvl']){
		case 'summary_by_service':
			$('.tblcallhistory1').clone().appendTo('.frmcallhistory-results-placeholder');
			$('.frmcallhistory-results-placeholder > .tblcallhistory1').attr("id", "tblcallhistory");
            var ch_headers = $('#csv_sbs').html();
            $('.frmcsvcallhistory > #csv_headers').val(ch_headers);
			break;
		case 'summary_by_dialin':
			$('.tblcallhistory2').clone().appendTo('.frmcallhistory-results-placeholder');
			$('.frmcallhistory-results-placeholder > .tblcallhistory2').attr("id", "tblcallhistory");
            var ch_headers = $('#csv_sbd').html();
            $('.frmcsvcallhistory > #csv_headers').val(ch_headers);            
			break;
		case 'detail':
			$('.tblcallhistory3').clone().appendTo('.frmcallhistory-results-placeholder');
			$('.frmcallhistory-results-placeholder > .tblcallhistory3').attr("id", "tblcallhistory");
            var ch_headers = $('#csv_dst').html();
            $('.frmcsvcallhistory > #csv_headers').val(ch_headers);            
			break;
		default:
			$('.frmcallhistory-results-placeholder').html('No Contents Given');
	}

	//Update Main Table
	$('#tblcallhistory').append(responseArr['html']);
	$('.frmcallhistory-results-placeholder').fadeIn('slow');
    
    //Update the Download CSV Form
    if(responseArr['html'] == null){
        $('.csvcallhistory').hide();
    }else{
        $('.csvcallhistory').show();
        $('.frmcsvcallhistory > #args').val(responseArr['args']);
    }

	//Data Tables Plugin
	table_Call_History_Init();

	return true;
}

/**
 * Call History Page Start Ajax Function
 */
function form_MyPwn_CallHistory_PageStart() {
   $('.frmcallhistory-results-placeholder').html('<div align="center"><img src="/img/ajax-loader-h.gif"></div>');
   $.ajax({
        type: "POST",
        url: "/ajax/mypwn/form-mypwn-call-history-init.php",
        data: $('.frmcallhistory').serialize(),
        cache: false,
        success: function(html){
            //Clear Results
            $('.frmcallhistory-results-placeholder').html('');
            
            //Check JS Response from HTML
            responseArr = $.parseJSON(html);

            if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
                //return showInputErrorsBoxes(responseArr['error_messages'], 'frmcallhistory', true);
            }

            //Clone Headers from Head Table
            switch($('#report_level').val()){
                case 'summary_by_service':
                    $('.tblcallhistory1').clone().appendTo('.frmcallhistory-results-placeholder');
                    $('.frmcallhistory-results-placeholder > .tblcallhistory1').attr("id", "tblcallhistory");
                    var ch_headers = $('#csv_sbs').html();
                    $('.frmcsvcallhistory > #csv_headers').val(ch_headers);
                    break;
                case 'summary_by_dialin':
                    $('.tblcallhistory2').clone().appendTo('.frmcallhistory-results-placeholder');
                    $('.frmcallhistory-results-placeholder > .tblcallhistory2').attr("id", "tblcallhistory");
                    var ch_headers = $('#csv_sbd').html();
                    $('.frmcsvcallhistory > #csv_headers').val(ch_headers);            
                    break;
                case 'detail':
                    $('.tblcallhistory3').clone().appendTo('.frmcallhistory-results-placeholder');
                    $('.frmcallhistory-results-placeholder > .tblcallhistory3').attr("id", "tblcallhistory");
                    var ch_headers = $('#csv_dst').html();
                    $('.frmcsvcallhistory > #csv_headers').val(ch_headers);            
                    break;
                default:
                    $('.frmcallhistory-results-placeholder').html('No Contents Given');
            }

            //Update Main Table
            $('#tblcallhistory').append(responseArr['html']);
            $('.frmcallhistory-results-placeholder').fadeIn('slow');
            
            //Update the Download CSV Form
            if(responseArr['html'] == null){
                $('.csvcallhistory').hide();
            }else{
                $('.csvcallhistory').show();
                $('.frmcsvcallhistory > #args').val(responseArr['args']);
            }

            //Data Tables Plugin
            table_Call_History_Init();

            return true;
        }
    });
}

/**
 * Account Details Ajax Functions
 */

/**
 * Initialise Account Details
 */
function form_MyPwn_AccountDetails_Init() {
	$('.frm_account_details_my_details').ajaxForm({
		success:      form_MyPwn_AccountDetails1_Response,
		error:        formCommunicationError
	});
	$('.frm_account_details_my_password').ajaxForm({
		success:      form_MyPwn_AccountDetails2_Response,
		error:        formCommunicationError
	});    
}

/**
 * Request Account Details - My Details Response
 */
function form_MyPwn_AccountDetails1_Response(responseText) {
	responseArr = $.parseJSON(responseText);

	if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'frm_account_details_my_details', true);
	}

	$('.frmaccountdetails-results-placeholder1').html(responseArr['html']);
	$('.frmaccountdetails-results-placeholder1').fadeIn('slow');

	return true;
}

/**
 * Request Account Details - My Password Response
 */
function form_MyPwn_AccountDetails2_Response(responseText) {
	responseArr = $.parseJSON(responseText);

	if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'frm_account_details_my_password', true);
	}

	$('.frmaccountdetails-results-placeholder2').html(responseArr['html']);
	$('.frmaccountdetails-results-placeholder2').fadeIn('slow');

	return true;
}


/**
 * Account Details Ajax Functions
 */

/**
 * Initialise User Details
 */
function form_MyPwn_UserDetails_Init() {
	$('.frm_user_details_my_details').ajaxForm({
        beforeSubmit: form_MyPwn_UserDetails1_Validate,
		success:      form_MyPwn_UserDetails1_Response,
		error:        formCommunicationError
	});
	$('.frm_user_details_my_password').ajaxForm({
        beforeSubmit: form_MyPwn_UserDetails2_Validate,
		success:      form_MyPwn_UserDetails2_Response,
		error:        formCommunicationError
	});    
}

function form_MyPwn_UserDetails1_Validate()
{
    $('#form-user-details-submit').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
    $('#form-user-details-submit').attr('disabled', 'true');
    return true;
}

/**
 * Request User Details - User Details Response
 */
function form_MyPwn_UserDetails1_Response(responseText) {
    
    $('#ajaxloader').remove();
    $('#form-user-details-submit').removeAttr('disabled');

    responseArr = $.parseJSON(responseText);
    
    $('.frmuserdetails-results-placeholder1').html('');

    if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'frm_user_details_my_details', true);
    }

    $('.frmuserdetails-results-placeholder1').html(responseArr['html']);
    $('.frmuserdetails-results-placeholder1').fadeIn('slow');

    return true;
}

function form_MyPwn_UserDetails2_Validate()
{
    $('#form-user-details-submit-password').parent().after().append('<img src="/img/ajax-loader-white.gif" alt="" id="ajaxloader" />');
    $('#form-user-details-submit-password').removeAttr('disabled');
    return true;
}

/**
 * Request User Details - User Password Response
 */
function form_MyPwn_UserDetails2_Response(responseText) {
    
    $('#ajaxloader').remove();
    $('#form-user-details-submit-password').removeAttr('disabled');

    responseArr = $.parseJSON(responseText);
    
    $('.frmuserdetails-results-placeholder2').html('');

    if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'frm_user_details_my_password', true);
    }

    $('.frmuserdetails-results-placeholder2').html(responseArr['html']);
    $('.frmuserdetails-results-placeholder2').fadeIn('slow');

	return true;
}

/**
 * CLI (Caller Line Identification) Information Message
 */
function show_CLI_inline_help(){
   show_information_message(INFO_MESSAGE_CLI);
}

/**
 * Show Information Messages
 */
function show_information_message(message){
   var maskHeight = $(document).height();
   var maskWidth  = $(window).width();
   $('#mypwn-page-mask').css({'width':maskWidth,'height':maskHeight,'opacity':0.5}).show("fast");
   $('#mypwn-page-msgbox').removeClass().addClass('success').html('<b>What is this?</b><br/><br/>'+message).fadeIn('normal');
}

function form_MyPwn_Pins_Table_Init() {
    $('#form-pins-table').ajaxForm({
        beforeSubmit: form_MyPwn_Pins_Table_Validate,
        success:      form_MyPwn_Pins_Table_Response,
        error:        formCommunicationError
    });
}


function form_MyPwn_Pins_Table_Validate(args) {

    functionName = '';

    // See what function was called (this cant be the best way to get the
    // value of the sumitted button, but I cant figure out better way)
    for (i in args) {
        if (args[i].name == 'function' && args[i].value == 'delete_pins') {
            functionName = args[i].value;
        }
    }

    // If deleting pins, make sure at least one pin was selected
    if (functionName == 'delete_pins') {
        if ($('input[name="r[]"]:checked').length == 0) {
            alert(FORM_VALIDATION_NO_PIN);
            return false;
        }
        return confirm(FORM_CONFIRM_PIN_DELETION);
    }

    return true;
}

function form_MyPwn_Pins_Table_Response(responseText) {

    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'form-edit-contact', true);
    }

    // Show alert box depending on pin delete success and failures
    if (((responseArr['deleted']['success'] instanceof Array) && responseArr['deleted']['success'].length > 0) && 
        ((responseArr['deleted']['failed'] instanceof Array) && responseArr['deleted']['failed'].length > 0)) {
        alert(FORM_RESPONSE_PINS_DELETED_SUCCESS_AND_FAILURE);
    } else if (((responseArr['deleted']['success'] instanceof Array) && responseArr['deleted']['success'].length > 0) && 
        ((responseArr['deleted']['failed'] instanceof Array) && responseArr['deleted']['failed'].length == 0)) {
        alert(FORM_RESPONSE_PINS_DELETED_SUCCESS);
    } else if (((responseArr['deleted']['success'] instanceof Array) && responseArr['deleted']['success'].length == 0) && 
        ((responseArr['deleted']['failed'] instanceof Array) && responseArr['deleted']['failed'].length > 0)) {
        alert(FORM_RESPONSE_PINS_DELETED_FAILURE);
    }

    // If pins have been deleted, then reload page
    if (responseArr['deleted']['success'].length > 0) {
        // Reload page
        window.location.reload();
    }

    return true;
}

/**
 * Handles some of the buttons at the bottom of the pins table, such
 * as requesting a wallet card or editing multiple pins
 * 
 * @param    string    edit_pins or request_wallet_card
 * @return   void      User is redirected to relevant page
 */
function form_MyPwn_Pins_Process(action) {

    // If we are editing pins, ensure at least one pin is selected
    if(action == 'edit_pins') {
        if ($('input[name="r[]"]:checked').length == 0) {
            alert(FORM_VALIDATION_NO_PIN);
            return false;
        }
    }

    // if we are ordering wallet cards, make sure only one pin is selected
    if(action == 'request_wallet_card') {
        if ($('input[name="r[]"]:checked').length == 0) {
            alert(FORM_VALIDATION_NO_PIN);
            return false;
        } else if ($('input[name="r[]"]:checked').length > 1) {
            alert(WALLET_CARD_PINS_TABLE_ONLY_ONE_PIN);
            return false;
        }
    }

    // Build URL to redirect user to, this will contain all the selected
    // pins on the page like so:
    // whateverurl?r[]=1234&r[]=56789
    if(action == 'edit_pins') {
        url = URL_MYPWN_CALL_SETTINGS;
    } else if(action == 'request_wallet_card' || action == 'request_welcome_pack') {
        url = URL_MYPWN_REQUEST_WALLET_CARD;
    }

    url += '?';
    $('input[name="r[]"]:checked').each(function(i) {
        url += 'r[]=' + $(this).val() + '&';
    });

    // remove trailing & from URL
    if(url.charAt(url.length - 1) == '&') {
        url = url.substr(0, url.length - 1);
    }

    window.location = url;

    return false;
}


/*Data Table Init Functions*/
function table_Contact_Dial_In_Numbers_Init() {
    $('#tblcontactdialinnumbers').dataTable({
        "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "sPaginationType": "full_numbers",
        "oLanguage" : {
            "sProcessing": DATA_TABLES_sProcessing,
            "sLengthMenu": DATA_TABLES_sLengthMenu,
            "sZeroRecords": DATA_TABLES_sZeroRecords,
            "sEmptyTable": DATA_TABLES_sEmptyTable,
            "sLoadingRecords": DATA_TABLES_sLoadingRecords,
            "sInfo": DATA_TABLES_sInfo,
            "sInfoEmpty": DATA_TABLES_sInfoEmpty,
            "sInfoFiltered": DATA_TABLES_sInfoFiltered,
            "sInfoPostFix": "",
            "sInfoThousands": ",",
            "sSearch": DATA_TABLES_sSearch,
            "sUrl": "",
            "fnInfoCallback": null,
            "oPaginate": {
                "sFirst":    DATA_TABLES_sFirst,
                "sPrevious": DATA_TABLES_sPrevious,
                "sNext":     DATA_TABLES_sNext,
                "sLast":     DATA_TABLES_sLast
            }
        }
    });
}

function table_Call_History_Init() {
    $('#tblcallhistory').dataTable({
        "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "sPaginationType": "full_numbers",
        "oLanguage" : {
            "sProcessing": DATA_TABLES_sProcessing,
            "sLengthMenu": DATA_TABLES_sLengthMenu,
            "sZeroRecords": DATA_TABLES_sZeroRecords,
            "sEmptyTable": DATA_TABLES_sEmptyTable,
            "sLoadingRecords": DATA_TABLES_sLoadingRecords,
            "sInfo": DATA_TABLES_sInfo,
            "sInfoEmpty": DATA_TABLES_sInfoEmpty,
            "sInfoFiltered": DATA_TABLES_sInfoFiltered,
            "sInfoPostFix": "",
            "sInfoThousands": ",",
            "sSearch": DATA_TABLES_sSearch,
            "sUrl": "",
            "fnInfoCallback": null,
            "oPaginate": {
                "sFirst":    DATA_TABLES_sFirst,
                "sPrevious": DATA_TABLES_sPrevious,
                "sNext":     DATA_TABLES_sNext,
                "sLast":     DATA_TABLES_sLast
            }
        }
    });
}

function myPwnFooter_init() {
    for (toolTipsIndex in MyPWNFooterToolTips) {
        $('.' + MyPWNFooterToolTips[toolTipsIndex] + '-link').click(function() {
            baseId = $(this).attr('class').replace('-link', '');
            myPwnFooter_ShowTooltip(baseId);
            return false;
        });

        $('.' + MyPWNFooterToolTips[toolTipsIndex] + '-close').click(function() {
            baseId = $(this).attr('class').replace('-close floatright sprite tooltip-close', '');
            $('.' + baseId).hide('fast');
            return false;
        });
    }
}

function myPwnFooter_ShowTooltip(toolTipId) {
    if ($('.' + toolTipId).is(':hidden')) {
        for (toolTiptoCloseIndex in MyPWNFooterToolTips) {
            if ($('.' + MyPWNFooterToolTips[toolTiptoCloseIndex]).is(':visible')) {
                $('.' + MyPWNFooterToolTips[toolTiptoCloseIndex]).hide('fast');
            }
        }
    }
    $('.' + toolTipId).toggle('fast');    
}

/**
 * Initialise Share My Desktop
 */
function form_MyPwn_ShareMyDesktop_Init() {
    $('.frmsharemydesktop').ajaxForm({
        success:      form_MyPwn_ShareMyDesktop_Response,
		error:        formCommunicationError
	});
}

/**
 * Share My Desktop Response
 */
function form_MyPwn_ShareMyDesktop_Response(responseText) {
	responseArr = $.parseJSON(responseText);

	if ( (responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
		return showInputErrorsBoxes(responseArr['error_messages'], 'frmsharemydesktop', true);
	}

    //Show the Hidden Success Form
    if ( responseArr['status'] == 'success' && responseArr['filetype'] == 'pc') {
        $('.frmsharemydesktop-pc-results').show();
        $('.smd-get-started').hide();
        $('.ajaxpasswordbox').hide();
    }else if ( responseArr['status'] == 'success' && responseArr['filetype'] == 'mac') {
        $('.frmsharemydesktop-mac-results').show();
        $('.smd-get-started').hide();
        $('.ajaxpasswordbox').hide();
    }

	return true;
}


/**
 * Recordings settings
 */
 
function form_MyPwn_Recordings_Init() {
    //init datepicker
    $('head').append('<link href="/css/library/ui.theme.css" media="screen" rel="stylesheet" type="text/css">');
    $('head').append('<link href="/css/library/ui.datepicker.css" media="screen" rel="stylesheet" type="text/css">');
    $('<script type="text/javascript" src="/js/library/ui.datepicker.js"></script>').appendTo('head'); 
}

/**
 * Update Recording Response
 */
function form_MyPwn_Recordings_Response(responseText) {
    responseArr = eval('(' + responseText + ')');

    if ((responseArr['error_messages'] instanceof Array) && responseArr['error_messages'].length > 0) {
        return showInputErrorsBoxes(responseArr['error_messages'], 'recform_1', true);
    }
    
    processAjaxJavascript(responseArr['javascript']);
    $('#f_rec_desc').hide();
    $('#f_rec_online').hide();
    $('#f_rec_expire').hide();
    $('#f_rec_password_set').hide();
    $('#f_rec_password').hide();
    $('#btn-rec-cancel span').html(MYPWN_RECORDINGS_OK);
    $('#btn-rec-cancel').css('margin-bottom','40px');
    $('#btn-rec-save').hide();
    
    return true;
}


 
function form_MyPwn_ShowRecordingSettings(recording_ref, recording_publish, recording_expire, recording_password) {


//if tab already open - hide it
    if ($('#rec-'+recording_ref+' + #current-rec-settings').is(":visible")) {
        $('#current-rec-settings').hide();
    }
    else { 
        // close other settings, add row with settings for current row
        $('.rec-settings').remove();    
        $('#rec-'+recording_ref).after('<tr class="rec-settings" id="current-rec-settings" style="display: none; background: #ffffff"><td colspan="6" style="background: #ffffff url(/img/mypwn-rec-settings-bg.png); padding: 20px 10px 0 10px; "><div style="position:relative"><form method="post" action="/ajax/mypwn/form-mypwn-update-recording.php" id="recform_1" name="recform_1" enctype="application/x-www-form-urlencoded"><input type="hidden" value="'+recording_ref+'" name="recording_ref" /><div class="field" id="f_rec_desc"><span>'+MYPWN_RECORDINGS_DESCRIPTION+':</span><span class="mypwn-input-container"><input type="text" value="" id="rec_desc" name="rec_desc" class="mypwn-input font-small input-large" /></span></div><div class="field" id="f_rec_online"><span>'+MYPWN_RECORDINGS_PUBLISH_ONLINE+':</span><input type="checkbox" name="publish_set" id="publish_set" /></div><div class="field" id="f_rec_expire"><span>'+MYPWN_RECORDINGS_PUBLISH_UNTIL+':</span><span class="mypwn-input-container"><input value="" name="publish_expire" id="publish_expire" class="mypwn-input font-small input-large" /></span></div><div class="field" id="f_rec_password_set"><span>'+MYPWN_RECORDINGS_REQUIRE_PASSWORD+':</span><input type="checkbox" name="password_set" id="password_set"></div><div class="field" id="f_rec_password"><span>'+MYPWN_RECORDINGS_PASSWORD+':</span><span class="mypwn-input-container"><input type="password" value="" id="rec_password" name="rec_password" class="mypwn-input font-small input-large" /></span></div><div class="field"><button id="btn-rec-cancel" class="button-orange" type="button"><span>'+MYPWN_RECORDINGS_CANCEL+'</span></button><button id="btn-rec-save" class="button-green" type="submit"><span>'+MYPWN_RECORDINGS_SAVE+'</span></button></div></form><div id="f_rec_link">'+MYPWN_RECORDINGS_LINK_TEXT+':&nbsp;<br/><span class="mypwn-input-container"><input type="text" class="mypwn-input font-medium" readonly="readonly" value="http://www.powwownow.co.uk/Recordings/recording/id/'+recording_ref+'" /></span></div></div></td></tr>');
        $('#current-rec-settings').show();
        
        
        // init form
        recording_description = $('tr#rec-'+recording_ref+' td.desc').html();
        $('#rec_desc').val(recording_description);
        
       	$('#recform_1').ajaxForm({
		    success:      form_MyPwn_Recordings_Response,
		    error:        formCommunicationError
	    });
        
        
            $('#f_rec_expire').hide();
            $('#f_rec_password_set').hide();
            $('#f_rec_password').hide();
        
        //hide link if recording is not available    
        if (recording_publish != '1') $('#f_rec_link').hide();

        
        if (recording_publish == '1') {
            $("#publish_set").attr('checked', true);
            $('#publish_expire').val(recording_expire);
            $('#f_rec_expire').show();
            $('#f_rec_password_set').show();
            
        }
        
        if ((recording_password == '1')&&(recording_publish == '1')) {
            $('#password_set').attr('checked', true);
            $('#f_rec_password').show();
        }
        
        // show options field when user decides to publish a recording
        $('#publish_set').click(function(){
            $('#f_rec_expire').toggle();
            $('#f_rec_password_set').toggle();
            
            if ($('#password_set').attr('checked')) {
            $('#f_rec_password').toggle();
            }
            
        });
        
        // Show password field when user requires it
        $('#password_set').click(function(){
            $('#f_rec_password').toggle();
        });
        
        var today = new Date();
        var aftertomorrow = new Date(today.getTime() + (48 * 60 * 60 * 1000));

        $("#publish_expire").datepicker({
        dateFormat:'dd/mm/yy',
        defaultDate:aftertomorrow,
        minDate:aftertomorrow,
        showButtonPanel:true
        });
        
        $('#btn-rec-cancel').click(function(){
            $('#current-rec-settings').hide();        
        });
    }
    
 }

