﻿/* This file contains common library of velumrent scripts */
var VelumRent = {};


////////////////////////////////////////////////////////////////////////

VelumRent.Page = {};
VelumRent.Utility = {};
VelumRent.PageHelper = {};

// parsira broj koji ima zarez kao decimalni separator
VelumRent.Utility.parseLocalNumber = function (number) {
    return number.replace(",", ".") - 0;
};

// mice html iz stringa i salje nazad cisti text, mora se izvrsiti u browser-u
VelumRent.Utility.stripHtml = function (htmlString) {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = htmlString;
    return tmp.textContent;
};

VelumRent.Utility.daysBetweenTwoDates = function (date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);

    // Convert back to days and return
    return Math.round(difference_ms / ONE_DAY);
};

// vadi url query varijable iz urla windowa
VelumRent.PageHelper.getUrlVars = function () {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
};

////////////////////////////////////////////////////////////////////////

/* converts date to user selected format. Requires datejs script from datejs.com */
VelumRent.getFormatedDate = function(date, format) {
    var userFormatedDate;
    userFormatedDate = Date.parse(date);
    if (userFormatedDate == null) {
        return date;
    }
    return userFormatedDate.toString(format);
};

// displays confirmatin box, requires jQuery.alerts
// if result of confirmation dialog is true, then it set the hidden value (for server) to true and click the button (with given ID) which does the real action
VelumRent.showConfirmationBeforeDeleting = function (buttonElementId, hiddenValueId, text) {
    var resultCallBack = function (result) {
        if (result) {
            var hiddenConfirmedValue = $('#' + hiddenValueId).val('true');
            var button = $('#' + buttonElementId).click();
        }
    }
    jConfirm(text, '', resultCallBack);
};

VelumRent.getBaseUrl = function() {
    var index = window.location.href.indexOf('?');
    return window.location.href.substring(0, index);
};

/**
 * Returns object with URL query keys and values as object keys and their values.
 * ?car=blue => object.car = blue
 */
VelumRent.getUrlQueryValues = function() {
    // Build an empty URL structure in which we will store
    // the individual query values by key.
    var objURL = new Object();

    // Use the String::replace method to iterate over each
    // name-value pair in the query string. Location.search
    // gives us the query string (if it exists).
    window.location.search.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),

    // For each matched query string pair, add that
    // pair to the URL struct using the pre-equals
    // value as the key.
        function($0, $1, $2, $3) {
            objURL[$1] = $3;
        }
    );

    return objURL;
};

/**
* Gets value of query variable in URL. Returns empty string if not found.
*/
VelumRent.getQueryParameterByName = function(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        return "";
    }
    else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
};

VelumRent.showErrorMessageForIE6AndIE7 = function() {
    var isIE6 = (navigator.appVersion.indexOf('MSIE 6.') == -1) ? false : true;
    var isIE7 = (navigator.appVersion.indexOf('MSIE 7.') == -1) ? false : true;

    var errorMessage = '' +
    'Unfortunately browser you are using is NOT FULLY SUPPORTED. Internet Explorer 6 & 7 are not fully supported due to their lack of compliance with web standards. Please use one of other browsers:' +
    '<br />' +
    '<br />' +
    '<ul style="margin-left: 30px">' +
    '    <li><a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Internet Explorer 8+</a></li>' +
    '    <li><a href="http://www.getfirefox.com">Mozzila Firefox</a></li>' +
    '    <li><a href="http://www.google.com/chrome">Google Chrome</a></li>' +
    '    <li><a href="http://www.apple.com/safari/">Apple Safari</a></li>' +
    '    <li><a href="http://www.opera.com/download/">Opera</a></li>' +
    '</ul>' +
    '<br />' +
    'You can go to download page by clicking on their name before you close this window. If you have a question contact us on <a href="mailto:info@constructivecode.com">info@constructivecode.com</a>';
    
    if (isIE6 || isIE7) {
        jAlert(errorMessage);
    }
};

VelumRent.initDataTables = function () {
    VelumRent.initDataTableCustomDateTimeSort();

    // ako se klikne link unutar tablice sprijeci propagiranje na red
    $('table.sortableTable tr a, table.sortableTable tr .action').click(function (event) {
        event.stopPropagation();
    });
    // ako se klikne na redak u tablici onda se otvara entitet
    $('table.sortableTable tr').click(function (event) {
        var url = $(this).find('.actionHref');
        if (url) {
            url.click();
        }
    });

    // make table sortable

    $('table.sortableTable.simple').dataTable({
        "sScrollX": "100%",
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": false,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "iDisplayLength": 50,
        "oLanguage": VelumRent.initDataTables.LanguageOptions
    });

    $('table.sortableTable.miniList').dataTable({
        "sScrollX": "100%",
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "bSortClasses": false,
        "iDisplayLength": 50,
        "oLanguage": VelumRent.initDataTables.LanguageOptions
    });

    $('table.sortableTable.filter').dataTable({
        "sScrollX": "100%",
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bSort": true,
        "bInfo": false,
        "bAutoWidth": false,
        "iDisplayLength": 50,
        "sPaginationType": "full_numbers",
        "oLanguage": VelumRent.initDataTables.LanguageOptions
    });

    $('table.sortableTable.full').dataTable({
        "sScrollX": "100%",
        "bPaginate": true,
        "bLengthChange": true,
        "bFilter": true,
        "bSort": true,
        "bInfo": true,
        "bAutoWidth": false,
        "iDisplayLength": 50,
        "sPaginationType": "full_numbers",
        "oLanguage": VelumRent.initDataTables.LanguageOptions
    });
};
// language options for data table
VelumRent.initDataTables.LanguageOptions = {
    "sProcessing": "Procesiram...",
    "sLengthMenu": "Prika\u017Ei po _MENU_",
    "sZeroRecords": "Nema podataka.",
    "sInfo": "Prikazano _START_ do _END_ od _TOTAL_ rezultata",
    "sInfoEmtpy": "Prikazano 0 do 0 od 0 rezultata",
    "sInfoFiltered": "(filtrirano iz _MAX_ ukupnih rezultata)",
    "sInfoPostFix": "",
    "sSearch": "Pretraga:",
    "sUrl": "",
    "oPaginate": {
        "sFirst": "Prva",
        "sPrevious": "Prethodna",
        "sNext": "Sljede\u0107a",
        "sLast": "Posljednja"
    }
};

VelumRent.initDataTableCustomDateTimeSort = function () {
    jQuery.fn.dataTableExt.aTypes.unshift(
	    function (sData) {
	        sData = VelumRent.Utility.stripHtml(sData);
	        if ((sData.length == 10 || sData.length == 11) && sData.match(/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20|21)(\d\d)(\.)?/)) {
	            return 'ddMMyyyy-date';
	        }
	        return null;
	    }
    );

    jQuery.fn.dataTableExt.oSort['ddMMyyyy-date-asc'] = function (a, b) {
        a = Date.parseExact(VelumRent.Utility.stripHtml(a), 'dd. MM. yyyy. hh:mm');
        b = Date.parseExact(VelumRent.Utility.stripHtml(b), 'dd. MM. yyyy. hh:mm');
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['ddMMyyyy-date-desc'] = function (a, b) {
        a = Date.parseExact(VelumRent.Utility.stripHtml(a), 'dd. MM. yyyy. hh:mm');
        b = Date.parseExact(VelumRent.Utility.stripHtml(b), 'dd. MM. yyyy. hh:mm');
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    };
};
