/**
 * @author Cristin<cristin.iosif@gmail.com>
 */
 
$(document).ready(function(){
    
    $("#page_title_ro").change(function(){
        getUrlByTitle("#page_title_ro", "#url_ro");
    });
    
    $("#page_title_en").change(function(){
        getUrlByTitle("#page_title_en", "#url_en");
    });
    
    $( "a.addBtn", ".admin-container" ).button();
    
    $("input.wpAfg_button").click(function(){
        var email_from = $("#your_email").val();
        var email_to = $("#recipient_email").val();
        var message = $("#message").val();
        
        var email_patt = /^[A-Za-z0-9-\._]+@[A-Za-z0-9-]+\.[A-Za-z]{2,4}(\.[A-Za-z]{2}){0,1}$/;
        var error = 0;
        
        if(!email_patt.test(email_from)){
                alert("Your email is invalid!");
            error = 1;
        }
        
        if(!email_patt.test(email_to)){
                alert("Your friend's email is invalid!");
            error = 2;
        }
        
        if(message.length <= 0){
                alert("You have to enter a message!");
            error = 3;
        }
        
        if(error == 0){
            $.ajax({
                url: "send_email.php",
                type: "post",
                data: {
                    'email_from': email_from,
                    'email_to': email_to,
                    'message': message
                },
                success: function(data){
                    alert(data);
                }
            });
        }
    });
});

function getUrlByTitle(titleID, urlID){
    $(urlID).val( generateUrl( $(titleID).val() ) );
}

function generateUrl(titleString){
    var url = titleString.toLowerCase();
    
    url = url.replace(/[^a-z0-9\s-]/g, "");
    url = url.replace(/[\s-]+/g, " ");
    // trim
    url = url.replace(/^\s*/, "").replace(/\s*$/, "");
    url = url.replace(/\s/g, "-");
   
    
    return url;
}

/* DOCUMENT READY FUNCTIONS - drf 
 * 
 * This are functions called of different pages, after the document has been loaded. 
 * This way we don't have to write much JS code in the Smarty template.
 */

function drfSmsSend(args){
    
    // add the onclick event for the add button
    $("#" + args["selected-contact-list-btn-id"]).click(function(){
        // the contact lists selected elem obj
        var selectObj = $("#" + args["contact-lists-select-id"] + " option:selected");
        // get the selected list id
        var selectedListId = selectObj.attr("id");
        if(!selectedListId) return false;
        // get the selected list text
        var selectedListText = selectObj.text();
        // add the list to the selected contact lists
        var selectedContactListsObj = $("#" + args["selected-contact-lists-id"]);
        selectedContactListsObj.append('<li id="'+ selectedListId +'"><input type="checkbox" name="selected-contact-lists[]" value="'+ selectedListId +'" class="hidden" checked /><label for="'+ selectedListId +'" class="inline">'+ selectedListText +'</label> <span class="remove-new">X</span></li>');
        // add the onclick event for the remove contact list from selected lists
        selectedContactListsObj.find(".remove-new").click(function(){
            // get the contact lists' id and text
            var cl_id = $(this).parent().find("li:first").attr("id");
            var cl_text = $(this).parent().find("label:first").text();
                
            // add the contact list back to the select
            $("#" + args["contact-lists-select-id"]).append('<option id="'+ cl_id +'">'+ cl_text +'</option>');
            // and remove it from the selected lists
            $(this).parent().remove();
        });
        // change the class of the remove element, so that when the next class is added, the already selected lists don't get onclick event again
        selectedContactListsObj.find(".remove-new").attr("class", "remove");
        // remove the added contact list from the select list element
        selectObj.remove();
    });
    
    // Add custom fields dialog
    useCustomFieldObj.init({
        "dialogId": args["custom-fields-dialog-id"],
        "targetId": args["message-textarea-id"]
    });
    $("#" + args["add-custom-field-link-id"]).click(function(){
        useCustomFieldObj.openDialog();
    });
}

function drfSmsHistory(args){
    // Init datePicker boxes
    if(args["filter_periode_start_id"]){
        $("#" + args["filter_periode_start_id"]).datepicker({
            dateFormat: args["date_format"]
        });
    }
    if(args["filter_periode_end_id"]){
        $("#" + args["filter_periode_end_id"]).datepicker({
            dateFormat: args["date_format"]
        });
    }

    chart1 = new Highcharts.Chart({
      chart: {
         renderTo: 'chart-container-1',
         defaultSeriesType: 'column'
      },
      title: {
         text: chartData.name
      },
      subtitle: {
         text: ''
      },
      xAxis: {                    
         categories: chartData.categories
      },
      yAxis: {
         min: 0,
         title: {
            text: 'No of sms'
         }
      },
      legend: {
         align: 'center',
         verticalAlign: 'bottom'
      },
      tooltip: {
         formatter: function() {
            return ''+
               this.x +': '+ this.y +' sms';
         }
      },
      plotOptions: {
         column: {
            pointPadding: 0.2,
            borderWidth: 0
         }
      },
      series: chartData.series
   });
}

function drfSmsView(args){
    
    chart_sms_status = new Highcharts.Chart({
      chart: {
         renderTo: args["chart-sms-status-id"],
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: false
      },
      title: {
         text: chartSmsStatusArgs.title
      },
      tooltip: {
         formatter: function() {
            return '<b>'+ this.point.name +'</b>: '+ this.y +' SMS';
         }
      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
               enabled: true,
               formatter: function() {
                  return '<b>'+ this.point.name +'</b>: '+ this.y +' SMS';
               }
            }
         }
      },
       series: chartSmsStatusSeries
   });
}

function importContactsDialog(args){
    
    
    $("#" + args["btnStartImport"]).click(function(){
        // open the dialog window
        /*
        $("#" + args["dialogId"]).dialog({
            modal: true
        });
        */
        importObj.initDialog(args);
        
        importObj.importContacts();
    });
    
    /*
    $("#" + args["progressBarId"]).progressbar({
        value: 100
    });
    */
}

var importObj = {
    status: 0,
    msg: "",
    curPos: 0,
    endPos: 0,
    noImportedContacts: 0,
    noRejectedContacts: 0,
    progressBarObj: null,
    dialogObj: null,
    initDialog: function(args){
        importObj.dialogObj = $("#" + args["dialogId"]);
        importObj.dialogObj.dialog({
            modal: true
        });
        importObj.initProgressBar(args["progressBarId"]);
    },
    closeDialog: function(){
        importObj.dialogObj.dialog("close");
    },
    initProgressBar: function(progressBarId){
        importObj.progressBarObj = $("#" + progressBarId);
        importObj.progressBarObj.progressbar({
            value: 0
        });
    },
    updateProgress: function(newValue){
        importObj.progressBarObj.progressbar({
            value: newValue
        });
    },
    importContacts: function(){
        // send the ajax request for contacts importing
        $.ajax({
            type: "POST",
            dataType: "json",
            url: APP_URL + "ajax.contacts.import.step.3.php",
            data: {
                "cur_pos": importObj.curPos,
                "end_pos": importObj.endPos,
                "no_imported_contacts": importObj.noImportedContacts,
                "no_rejected_contacts": importObj.noRejectedContacts
            },
            success: function(data){
                if(parseInt(data["status"]) != 0){
                    importObj.status = data["status"];
                    importObj.msg = data["msg"];
                }else{
                    importObj.curPos = parseInt(data["cur_pos"]);
                    importObj.endPos = parseInt(data["end_pos"]);
                    importObj.updateProgress(importObj.curPos * 100 / importObj.endPos);
                    
                    importObj.noImportedContacts = parseInt(data["no_imported_contacts"]);
                    importObj.noRejectedContacts = parseInt(data["no_rejected_contacts"]);
                    importObj.updateNoImportedContacts();
                    importObj.updateNoRejectedContacts();
                    
                    if(importObj.curPos < importObj.endPos){
                        importObj.importContacts();
                    }else{
                        importObj.processCompleteRequest();
                    }
                }
                //alert(data["status"]);
            }
        });
    },
    processCompleteRequest: function(){
        importObj.dialogObj.find("#dialog-import-text").fadeOut("slow", function(){
            importObj.dialogObj.find("#dialog-done-import").fadeIn("fast");
            //setTimeout(importObj.closeDialog, 800);
            setTimeout(window.location = APP_URL + "contacts", 800);
        });
    },
    updateNoImportedContacts: function(){
        $("#no-imported-contacts span").html(importObj.noImportedContacts);
    },
    updateNoRejectedContacts: function(){
        $("#no-rejected-contacts span").html(importObj.noRejectedContacts);
    }
}

var useCustomFieldObj = {
    targetObj: null,
    dialogObj: null,
    
    init: function(args){
        useCustomFieldObj.dialogObj = $("#" + args["dialogId"]);
        // Create the target textarea obj
        useCustomFieldObj.targetObj = $("#" + args["targetId"]);
        // add the event for adding custom field
        jQuery.each(useCustomFieldObj.dialogObj.find("ul a"), function(){
            $(this).click(function(){
                useCustomFieldObj.targetObj.val(useCustomFieldObj.targetObj.val()+$(this).text());
            });
        });
    },
    openDialog: function(){
        useCustomFieldObj.dialogObj.dialog({
            modal: true
        });
    }
}

