// --------------------------------------------------------------------------------------------- Define Global Variables

var drag = null;
var debug = false; // If set to true.. error messages will be displayd to user
var maxPollCounts = 50;
var pollInterval = 2500;
var toggleOptions = { duration: 0.20 };
var gCallData; // used to hold call data
var gCallDataIsDesc = true; // used to controll calldata display direction
var norditCal = null; // placeholder for calendar object;

// -------------------------------------------------------------------------------------------- Misc. Utillity functions

function createDatePicker(args) {
    return new DatePicker({
	relative: args.relative,
    language: 'dk',
	keepFieldEmpty:true,
//    relativePosition:true,
    externalControl:args.externalControl,
    dateFormat:[ ["yyyy","mm","dd"], "-" ],
	dateFilter: args.dateFilter
    });
}

//function showCalendar(calInputId, dateFormat, disableWeekend, returnFunction) {
//    if (dateFormat == undefined) dateFormat = 'yyyy-MM-dd';
//    if (disableWeekend == undefined) disableWeekend = false;
//    if (norditCal == null) {
//        norditCal = new CalendarPopup('myPopupCalendar');
//        norditCal.setCssPrefix("MyPopUp");
//        norditCal.setMonthNames("Januar","Februar","Marts","April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December");
//        norditCal.setMonthAbbreviations("Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec");
//        norditCal.setDayHeaders("S", "M", "T", "O", "T", "F", "L");
//        norditCal.setWeekStartDay(1);
//        if (disableWeekend)
//            norditCal.setDisabledWeekDays(5,6);
//        norditCal.setTodayText("I dag");
//        norditCal.offsetX = 0;
//        if (returnFunction)
//            norditCal.setReturnFunction(returnFunction);
//    }
//    norditCal.select($(calInputId), calInputId, dateFormat);
//}


/**
 * Method to validate phonenumber.
 */
var isValidPhoneNumber = function() {
    var numberMatch = new RegExp("^[2-9]{1}[0-9]{7}$");
    return function(numberString) {
        return numberMatch.test(numberString);
    };
}();

/**
 * Method to validate A string for teh yyyy-MM-dd date format
 * @param dateString String containing the date
 */
var isValidDate = function() {
    var regExp = new RegExp(/^\d\d\d\d-?\d\d\-?\d\d$/);
    return function (dateString) {
        return regExp.test(dateString);
    };
}();

/**
 * Method to validate user part of Email Alias
 * @param alias user part of alias
 */
var isValidAlias = function() {
    var validAlias = new RegExp(/^[a-zA-Z0-9][a-zA-Z0-9\\._-]*[a-zA-Z0-9]*$/);
    var invalidAlias = new RegExp(/^(mbx|mail)[0-9]*/);
    return function (alias) {
        return ( validAlias.test(alias) && !invalidAlias.test(alias) );
    };
}();

/**
 * Method to validate complete emailaddress
 * @param email emailaddress to validate.
 */
var isValidEmail = function () {
    var validEmail = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i);
    return function (email) {
        return ( validEmail.test(email) );
    };
}();


/**
 * Method to validat link part of Webspace url
 * @param link linkpart of url
 */
var isValidLink = function() {
    var validLink = new RegExp(/^[a-zA-Z0-9][a-zA-Z0-9\\._-]*[a-zA-Z0-9]*$/);
    var invalidLink = new RegExp(/(^web[0-9]*)|(\\)|(\/)/);
    return function (link) {
        return ( validLink.test(link) && !invalidLink.test(link.toLowerCase()) );
    };
}();

/**
 * Method to return Date object from a ISO8601 formated string
 * @param dString string (iso8601)
 */
function iso8601Date(dString) {
    return new Date().setISO8601(dString).format('yyyy-mm-dd HH:MM:ss');
}

/**
 * Metod to leftpad a string
 * @param str string to be padded
 * @param padstr the string to be padded with
 * @param size the length of the padded string
 */
function lpad(str, padstr, size) {
    var res = str;
    while (res.length < size) {
        res = padstr + res;
    }
    return res;
}

/**
 * Method to format seconds into HH:MM:SS format
 * @param psec number of seconds
 */
function secondsToTimeFormat(psec) {
    var hour = Math.floor(psec/3600);
    psec = psec - (hour*3600);
    var min = Math.floor(psec/60);
    psec = psec - (min*60);
    var sec = psec;
    var hourstr = lpad(""+hour, "0", 2);
    var minstr = lpad(""+min, "0", 2);
    var secstr = lpad(""+sec, "0", 2);
    return hourstr+":"+minstr+":"+secstr;
}

/**
 * Method Used to create a post/get request from Javascript
 * @param path The url that is to be posted to
 * @param params parameters that is to be posted
 * @param method method of post GET/POST
 */
function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}

// ------------------------------------------------------------ Methods usded to handle the popup (fx.used when polling)

function refresh() {
    window.location.reload(true);
}

//TODO: fix chrome + IE problem
var escapeOverlay = {
    fx: function(e) {
        // To make script compatable with both MSIE and Firefox
        var kC = (window.event) ? event.keyCode : e.keyCode;
        var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE;

        // If keypressed is escape and the new entry field is empty
        if (kC === Esc)
            closeDialog();
    }
}

escapeOverlay.bfx = escapeOverlay.fx.bindAsEventListener(escapeOverlay);
var overlayDrag = null;


function loadPopup() {
    $('overlay').setOpacity(.6);
    if (window.innerHeight > $('content').scrollHeight) {
        $('overlay').style.height = window.innerHeight + 'px';
    } else {
        $('overlay').style.height = ($('content').scrollHeight + 30) + 'px';
    }
    showOverlay();
    window.scrollTo(0, 0);

    $('result').show();
}

function showOverlay() {
    $('overlay').show();
    Event.observe(document, 'keypress', escapeOverlay.bfx);
}

function hideOverlay() {
    $('overlay').hide();
    Event.stopObserving(document, 'keypress', escapeOverlay.bfx);
}

function closeDialog() {
    hideOverlay();

    // Hide dialog
    $('result').hide();
    $('result').style.left = '50%';
    $('result').style.top = '150px';
    $('result').style.marginLeft = '-200px';

    // Clear dialog
    $('result').innerHTML = '';
    if (overlayDrag != null)
        overlayDrag.destroy();

    overlayDrag = null;
    return true;
}

// ----------------------------------------------------------------------- Methods used for handeling of Zeus Workorders

/**
 * Method used to poll for the status of a Zues Workorder
 * @param wid WorkorderId
 * @param count currnet count number (should always start at 0)
 * @param url url that will be posted to when the workorder completes successfully
 * @param params parametres that is to be posted.
 */
function poll(wid, count, url, params) {
    new Ajax.Request('poll.php?wid=' + wid,
    {
        onSuccess: function(transport) {
            if (transport.responseText.match("^CS")) {
                closeDialog();
                if ( url != undefined && params != undefined ) {
                    post_to_url(url,params,'post');
                }
            } else if (transport.responseText.match("^TE")) {
                closeDialog();
                $('error').innerHTML = "Der opstod en fejl under opdateringen af vore systemer.<br>Venligst kontakt Nordits kundeservice, hvis der opleves problemer";
                if (debug) $('error').innerHTML += '<pre>'+transport.responseText+'</pre>';
                $('error').show();
            } else {
                if (count >= maxPollCounts) {
                    closeDialog();
                    $('error').innerHTML = "Modtog ikke svar fra systemet indenfor forventet tid.\nDin ændring vil stadig blive gennemført, men er forsinket af ukendte årsager.";
                    $('error').show();
                    return;
                }

                var f = function() {
                    poll(wid, ++count, url, params);
                };
                setTimeout(f, pollInterval);
            }
        },
        onFailure: function(transport) {
            alert('An error occured:\n\n' + transport.responseText);
            closeDialog();
        }
    }
  );
}

// --------------------------------------------------- Methods used for creation and alteration of Mailbox-Subscriptions

/**
 * Method tho handle the AJAX call to change the password of a SubscriptionMailbox
 * @param mailboxsid SubscriptionId of the Subscription
 * @param newpassword new password
 * @param newpassword2 confirmation of new password
 */
function changeMailboxPassword(mailboxsid, newpassword, newpassword2) {
    var params = {
        'action': 'chPwd',
        'page': 'mail',
        'passwd': newpassword,
        'again': newpassword2,
        'sid': mailboxsid
    };

    if ( newpassword.length < 4 || newpassword.length >16 ) {
        $('error').innerHTML = "Dit kodeord skal være mellem 4 og 16 karakterer og kan bestå af tal og/eller bogstaver.";
        $('error').show();
        return false;
    } else if ( newpassword != newpassword2 ) {
        $('error').innerHTML = "De indtastede kodeord er ikke ens.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Skifter kodeord, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'mail','success':'Kodeordet er ændret'});
        },
        onFailure: function(transport) {
            closeDialog();
            $('error').innerHTML = "Der opstod en fejl under ændring af kodeord på mailkonto.";
            if ( debug ) {
                $('error') .innerHTML += '<pre>'+transport+'</pre>';
            }
            $('error').show();
        }
    }
   );

    return false;
}
/**
 * Method to handle the AJAX call to change the alias of a Mailbox
 * @param mailboxsid SubscriptionId of the Mailbox-Subscription
 * @param alias User part (that is before the @) of the alias that is to be created for the mailbox
 * @param domain Domain part (that is after the @) of the alias that is to be created for the mailbox
 * @param oldalias current alias of the mailbox Subscription.
 */
function changeMailboxAlias(mailboxsid, alias, domain, oldalias) {
    alias = alias.trim();
    var params = {
        'action': 'chAlias',
        'page': 'mail',
        'domain': domain,
        'alias': alias,
        'oldalias': oldalias,
        'sid': mailboxsid
    };

    if ( alias.length === 0 || !isValidAlias(alias) ) {
        $('error').innerHTML = "Den angivne adresse '"+alias+"' er ikke valid.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Skifter alias, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'mail','success':'Alias er ændret til <b>'+alias+'@'+domain+'<b>'});
        },
        onFailure: function(transport) {
            closeDialog();
            if (transport.status === 501) {
                // MailboxAliasExists
                $('error').innerHTML = 'Mailkonto alias <b>'+alias+'@'+domain+'</b> bliver allerede brugt af en anden mailkonto';
            } else {
                $('error').innerHTML = 'Der opstod en fejl under ændring af mailkonot alias';
            }
            if ( debug ) {
                $('error').innerHTML += '<pre>'+transport.responseText+'</pre>'
            }
            $('error').show();
        }
    }
   );

    return false;
}
/**
 * Method to handle AJAX call to create a new SubscriptionExtraMailbox
 * @param inetsid SubscriptionId of the SubscriptionInternet that is the parrent of the new Subscription
 * @param alias User part (that is before the @) of the email alias to be created for the Mailbox
 * @param domain Domain part (that is after the @) of the email alias
 * @param password password to be assigned to the new Mailbox
 * @param password2 confirmation of password
 */
function createExtraMailbox(inetsid,alias,domain,password,password2) {
    var params = {
        'action': 'createMail',
        'inetsid': inetsid,
        'domain': domain,
        'alias': alias,
        'passwd': password,
        'again': password2
    };

    // Validate alias
    if ( alias.trim().length === 0 ) {
        $('error').innerHTML = "Alias kan ikke være tom";
        $('error').show();
        return false;
    } else if ( !isValidAlias(alias.trim()) ) {
        $('error').innerHTML = "Den angivne adresse '"+alias+"' er ikke valid.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }
    // Validate password
    if ( password != password2 ) {
        $('error').innerHTML = "De indtastede kodeord er ikke ens.";
        $('error').show();
        return false;
    } else if ( password.length < 4 || password.length >16 ) {
        $('error').innerHTML = "Dit kodeord skal være mellem 4 og 16 karakterer og kan bestå af tal og/eller bogstaver.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Opretter Ekstra Mailbox, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'mail','success':'Mailkonto <b>'+alias+'@'+domain+'</b> oprettet.'});
        },
        onFailure: function(transport) {
            closeDialog();
            if (transport.status === 501) {
                // MailboxAliasExists
                $('error').innerHTML = 'Mailkonto alias <b>'+alias+'@'+domian+'</b> bliver allerede brugt af en anden mailkonto';
            } else if ( transport.status === 503 )  {
                // MaxMailboxException
                $('error').innerHTML = 'Det er ikke muligt at oprette flere mailkonti';
            } else {
                $('error').innerHTML = 'Der opstod en fejl under oprettelsen af mailkonto <b>'+alias+'@'+domain+'</b>';
            }
            $('error').show();
        }
    }
   );
   return false;
}

// --------------------------------------------- Methods to handle the creation and alteration of Webspace-Subscriptions

/**
 * Method to handle AJAX call to change the password for at SubscriptionWebspace
 * @param webspacesid SubscriptionId of the SubscriptionWebspace on witch to change the password
 * @param newpassword new password
 * @param newpassword2 confirmation of new password
 */
function changeWebspacePassword(webspacesid, newpassword, newpassword2) {
    var params = {
        'action': 'wsPwd',
        'passwd': newpassword,
        'again': newpassword2,
        'sid': webspacesid
    };

    if ( newpassword.length < 4 || newpassword.length >16 ) {
        $('error').innerHTML = "Dit kodeord skal være mellem 4 og 16 karakterer og kan bestå af tal og/eller bogstaver.";
        $('error').show();
        return false;
    } else if ( newpassword != newpassword2 ) {
        $('error').innerHTML = "De indtastede kodeord er ikke ens.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Skifter kodeord, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'webspace','success':'Kodeordet er ændret'});
        },
        onFailure: function(transport) {
            closeDialog();
            $('error').innerHTML = "Der opstod en fejl under ændring af kodeord på webspacekonto";
            $('error').show();
        }
    }
    );

    return false;
}
/**
 * Method to handle AJAX call to change the link of an existing SubscriptionWebspace
 * @param webspacesid SubscriptionId of the SubscriptionWebspace on witch to change the link
 * @param link name of the new link to be created for the SubscriptionWebspace
 */
function changeWebspaceLink(webspacesid, link) {
    link = link.trim(); // trim of whitespaces.
    var params = {
        'action': 'wsEdit',
        'link': link,
        'sid': webspacesid
    };

    if ( link.length === 0 || !isValidLink(link) ) {
        $('error').innerHTML = "Den angivne adresse 'http://webspace.nordit.dk/"+link+"' er ikke valid.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Skifter link, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'webspace','success':'Link er ændret til <a href="http://webspace.nordit.dk/'+link+'"><b>http://webspace.nordit.dk/'+link+'</b></a>'});
        },
        onFailure: function(transport) {
            closeDialog();
            $('error').innerHTML = "Der opstod en fejl under ændring af link på webspace konto";
            $('error').show();
        }
    }
   );
    return false;
}
/**
 * Method to handle AJAX call to create a new webspace account
 * @param inetsid SubscriptionId of the SubscriptionInternet that is the parrent for the new SubscriptionWebspace
 * @param link name of the link to be created for the new webspace
 * @param password password for the new account
 * @param password2 confirmation of password
 */
function createWebspace(inetsid,link,password,password2) {
    var params = {
        'action': 'createWebspace',
        'inetsid': inetsid,
        'link': link,
        'passwd': password,
        'again': password2
    };

    // Validate alias
    if ( link.trim().length === 0 ) {
        $('error').innerHTML = "Link kan ikke være tom";
        $('error').show();
        return false;
    } else if ( !isValidLink(link.trim()) ) {
        $('error').innerHTML = "Det angivne link '"+link+"' er ikke valid.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }
    // Validate password
    if ( password != password2 ) {
        $('error').innerHTML = "De indtastede kodeord er ikke ens.";
        $('error').show();
        return false;
    } else if ( password.length < 4 || password.length >16 ) {
        $('error').innerHTML = "Dit kodeord skal være mellem 4 og 16 karakterer og kan bestå af tal og/eller bogstaver.";
        $('error').show();
        return false;
    } else {
        $('error').hide();
    }

    new Ajax.Request('index.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Opretter Webspace konto, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "index.php", {'page':'webspace','success':'webspace <b>http://webspace.nordit.dk/'+link+'</b> oprettet.'});
        },
        onFailure: function(transport) {
            closeDialog();
            if (transport.status === 501) {
                // MailboxAliasExists
                $('error').innerHTML = 'Webspace link <b>http://webspace.noridt.dk/'+link+'</b> bliver allerede brugt af en anden webspacekonto';
            } else if ( transport.status == 503 )  {
                // MaxMailboxException
                $('error').innerHTML = 'Det er ikke muligt at oprette flere webspacekonti';
            } else {
                $('error').innerHTML = 'Der opstod en fejl under oprettelsen af webspacekonto <b>http://webspace.nordit.dk/'+link+'</b>';
            }
            if ( debug ) $('error').innerHTML += '<pre>('+transport.status+')'+transport.responseText+'</pre>';
            $('error').show();
        }
    }
   );
   return false;
}

// ------------------------------------------------------------------- Method to handle modem registration (user signup)

/**
 * Method to handle AJAX call to signup User
 * @param signupuser username
 * @param password password
 */
function signup(signupuser,password) {
    var params = {
        'action': 'doSignup',
        'signupuser': signupuser,
        'password': password
    };

    // Validate signupuser
    if ( signupuser.trim().length === 0) {
        $('error').innerHTML = 'Brugernavn kan ikke være tom.';
        $('error').show();
        return false;
    }

    // Validate password
    if ( password.trim().length === 0 ) {
        $('error').innerHTML = 'Kodeord kan ikke være tom.';
        $('error').show();
        return false;
    }

    new Ajax.Request('signup.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Udføre registrering, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            var wid = transport.responseText;
            poll(wid, 1, "signup.php", {'action':'done','success':'Registrering gennemført.<br>Du skal nu genstarte din computer..<br><b>NB:</b> Hvis du anvender en router, er det denne du skal genstarte og ikke din computer.<br>God fornøjelse. '});
        },
        onFailure: function(transport) {
            closeDialog();
            $('password').value = ''; // clear entry fields
            if ( transport.status === 401 ) {
                $('error').innerHTML = 'Det indtastede brugernavn og kodeord er ikke korrekt.';
                if ( debug ) $('error').innerHTML += '<pre>('+transport.status+')\n'+transport.responseText+'</pre>';
                $('error').show();
            }
            if ( transport.status === 502 ) {
                $('notice') .innerHTML = 'Det er ikke nødvendigt at registrere din internet forbindelse, da dette allerede er sket.<br>Hvis du oplever problemer med at komme på internettet<br>kontakt venligst Nordit kundeservice på <b>96780808</b>'
                $('notice').show();
            }
            if ( transport.status === 501 || transport.status === 500 ) {
                $('error').innerHTML = 'Det er desværre ikke muligt at registrere dit internet automatisk.<br>Kontakt venligts nordit kundeservice på <b>96780808</b>';
                if ( debug ) $('error').innerHTML += '<pre>('+transport.status+')\n'+transport.responseText+'</pre>';
                $('error').show();
            }
        }
    }
   );
   return false;
}

// ------------------------------------------------------------------------ Functions to handle the showing of call data
/**
 * Mehtod usded to determain the "type" of a call.
 * @param call
 */
function getCallType(call) {
    if (!call.destination.startsWith('45') ) {
        return 'Udland';
    } else if ( call.mobile ) {
        return 'Mobil';
    } else if ( call.local ) {
        return 'Lokal';
    } else {
        return 'Fastnet';
    }

}

/**
 * Comparison method usd when sorting call array Descending
 * @param a
 * @param b
 */
function cmpCallDesc(a,b) {
    if ( a.started === b.starterd ) return 0;
    return a.started < b.started ? 1:-1;
}

/**
 * Comparison method usd when sorting call array Ascending
 * @param a
 * @param b
 */
function cmpCallAsc(a,b) {
    if ( a.started === b.starterd ) return 0;
    return a.started > b.started ? 1:-1;
}

/**
 * Method to handle flip/flop action of the direction
 * @param showInvoicedFlag boolean just allown for the ride.. (not used here just passed allogn)
 */
function changeDirection(showInvoicedFlag) {
    gCallDataIsDesc = !gCallDataIsDesc;
    $('callinfo').innerHTML = processCallData(showInvoicedFlag);
}

/**
 * Method to remove 45 prefix on domestic calls.
 * @param number phoneNumber with or without the domestic country prefix.
 */
function unPrefixNumber(number) {
    return number.toString().startsWith('45') ? number.toString().substr(2) : number;
}

/**
 * Method used for formating a single call into a single <tr>
 * @param showInvoicedFlag flag used to determain if the "invoiced" collumn is to be added to output
 * @param idx index of the call (just used for the alternating background-color)
 * @param call the Call object itself.
 */
function formatSingleCall(showInvoicedFlag,idx,call) {
    var cr =  ( (idx%2 === 0) ? '<tr class="odd_call">' : '<tr class="even_call">' );
    cr += '<td>'+iso8601Date(call.started)+'</td>';
    cr += '<td>'+( call.destination.startsWith('45') ? call.destination.substr(2) : call.destination )+'</td>';
    cr += '<td >'+getCallType(call)+'</td>';
    cr += '<td style="text-align: right">'+secondsToTimeFormat(call.conversationDuration)+'</td>';
    if (showInvoicedFlag) {
        cr += '<td style="text-align: center;">'+( call.invoiced ? 'ja' : '&nbsp;')+'</td>';
    }
    cr += '<td style="text-align: right">'+call.invoicePrice.toFixed(2)+' kr.</td>';
    cr += '</tr>';
    return cr;
}

/**
 * Method used for generating a HTML presentation of the call data.
 * @param showInvoicedFlag boolean to determain if the "invoiced" collumn is added to output
 */
function processCallData(showInvoicedFlag) {

    if ( gCallDataIsDesc ) {
        gCallData.sort(cmpCallDesc);
    } else {
        gCallData.sort(cmpCallAsc);
    }

    var html = '<table width="100%" cellspacing="0" cellpadding="2">';
    html += '<tr>';
    html += '<th style="text-align: left;"><a href="#" onClick="changeDirection('+showInvoicedFlag.toString()+');">Tidspunkt'+( gCallDataIsDesc ? '&uarr;' : '&darr;')+'</a></th>';
    html += '<th style="text-align: left;">Opkald til</th>';
    html += '<th style="text-align: left;">Opkaldstype</th>';
    html += '<th style="text-align: right;">Varrighed</th>';
    if (showInvoicedFlag) {
        html += '<th style="text-align: center;">Faktureret</th>';
    }
    html += '<th style="text-align: right;">Pris</th>';
    html += '</tr>';

    var totalPrice = 0;
    var totalSec =0;
    for (var i=0; i < gCallData.length; i++)  {
        html += formatSingleCall(showInvoicedFlag,i,gCallData[i]);
        totalPrice += gCallData[i].invoicePrice;
        totalSec += gCallData[i].conversationDuration;
    }

    html += '<tr>';
    html += '<td style="text-align: left; font-weight: bold;" colspan="3">Total</td>';
    html += '<td style="text-align: right; font-weight: bold;">'+secondsToTimeFormat(totalSec)+'</td>';
    if (showInvoicedFlag) {
        html += '<td >&nbsp;</td>';
    }
    html += '<td style="text-align: right; font-weight: bold;">'+totalPrice.toFixed(2)+' kr.</td>';
    html += '</tr>';

    html += '</table>';

    return html;
}


/**
 * Method used to retrieve, calculate and update date fields on the search-dialog used when searching the call
 * data.
 * @param interval
 */
function calculateDates(interval,fromId,toId) {
    if ( isValidDate($(toId).value.toString()) ) {
        var toDate = new Date().setYYYYMMDD($(toId).value);
        var from = toDate;
        if (interval === '1week') {
            // one week
            from.setFullYear(toDate.getFullYear(), toDate.getMonth(),toDate.getDate()-7);
        } else if ( interval === '1month' ) {
            // one month
            from.setFullYear(toDate.getFullYear(), toDate.getMonth()-1,toDate.getDate());
        } else if ( interval === '3months') {
            // one quarter
            from.setFullYear(toDate.getFullYear(), toDate.getMonth()-3,toDate.getDate());
        } else {
            alert("Unknown Interval '"+interval+"'");
        }
        $(fromId).value = from.format('yyyy-mm-dd');
        $(toId).value = new Date().setYYYYMMDD($(toId).value).format('yyyy-mm-dd');
        return true;
    } else {
        $('error').innerHTML = 'Den indtastede dato er ikke gyldig';
        $('error').show();
        $('notice').hide();
        $('success').hide();
        return false;
    }
}

/**
 * Method used to handle AJAX call to retrieve call data for at given period in time
 * @param sid SubscritpionId of the SubscriptionVoip
 * @param from first date of search
 * @param to Last date of search
 */
function getCallData(sid,from,to) {
    var params = {
        'action': 'doGetCallData',
        'sid': sid,
        'from': from,
        'to' : to
    };

    if ( !isValidDate(from.toString()) ) {
        if ( debug ) $('error').innerHTML += 'Den angivne fra-dato er ikke gyldig';
        $('error').show();
        $('notice').hide();
        $('success').hide();
        return false;
    }

    new Ajax.Request('jsonhelper.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            $('notice').hide();
            $('error').hide();
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Henter opkaldsinformation, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            gCallData = transport.responseText.evalJSON();
            if ( gCallData.length > 0 ) {
                $('callinfo').innerHTML = processCallData(true); // Sets callinfo
                $('callinfo').show();
            } else {
                $('notice').innerHTML = "Der blev ikke fundet nogle opkald for perioden";
                $('notice').show();
                $('callinfo').innerHTML='';
                $('callinfo').hide();
            }
            closeDialog();
        },
        onFailure: function(transport) {
            closeDialog();
            if ( debug ) $('error').innerHTML += '<pre>('+transport.status+')\n'+transport.responseText+'</pre>';
            $('error').show();
        }
    }
   );
   return false;
}
/**
 * Method to handle the AJAX call that retrieves the current non-invoiced-calldata.
 * @param sid SubscriptionId
 */
function getCallSaldoData(sid) {
    var params = {
        'action': 'doGetCallSaldoData',
        'sid': sid
    };

    new Ajax.Request('jsonhelper.php',
    {
        method: 'post',
        parameters: params,
        onCreate: function() {
            $('notice').hide();
            $('error').hide();
            loadPopup();
            $('result').style.backgroundColor = '#FFFFFF';
            $('result').style.border = '2px solid #000000';
            $('result').innerHTML = '<div id="loading"><h1>Henter opkaldsinformation, vent venligst..</h1><br><img src="images/loading.gif" title="Loading" alt="Loading" /></div>';
        },
        onSuccess: function(transport) {
            gCallData = transport.responseText.evalJSON();
            if ( gCallData.length > 0 ) {
                $('callinfo').innerHTML = processCallData(false); // Sets callinfo, invoicedTotal and nonInvoicedTotal Works on global callDetailData
                $('callinfo').show();
            } else {
                $('notice').innerHTML = "Der blev ikke fundet nogle opkald for perioden";
                $('notice').show();
                $('callinfo').innerHTML='';
                $('callinfo').hide();
            }
            closeDialog();
        },
        onFailure: function(transport) {
            closeDialog();
            if ( debug ) $('error').innerHTML += '<pre>('+transport.status+')\n'+transport.responseText+'</pre>';
            $('error').show();
        }
    }
   );
   return false;
}

// ---------------------------------------------------------------------------------------- Functions to handle Ordering
