/* Author: Agilex

 */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['backbone'], function(Backbone) {
            root = factory(root, Backbone);
        });
    } else {
        root = factory(root, root.Backbone);
    }
}(this, function(root, $) {

    root.formatDate = function (date) {
        'use strict';
        date = new Date(date);
        if (typeof date !== 'undefined' && !isNaN(date)) {
            var month = date.getMonth() + 1,
                day = date.getDate(),
                year = date.getFullYear();

            day = day < 10 ? '0' + day : day;
            month = month < 10 ? '0' + month : month;

            return (month + "/" + day + "/" + year);
        }

        return '';
    };

    root.produceDate = function (duration, date) {
        'use strict';
        var nonNullDate = date ? new Date(date) : new Date();
        return subtractFromDate(0, 0, duration, 0, 0, 0, 0, nonNullDate);
    };

    root.subtractFromDate = function (month, day, year, hours, minutes, seconds, milliseconds, date) {
        'use strict';
        return formatDate(subtractFromDateUnformatted(month, day, year, hours, minutes, seconds, milliseconds, date));
    };

    root.produceDateFromMonths = function (durationInMonths, date) {
        'use strict';
        var nonNullDate = date ? new Date(date) : new Date();
        return subtractFromDate(durationInMonths, 0, 0, 0, 0, 0, 0, nonNullDate);
    };

    root.produceDateFromDays = function (durationInDays, date) {
        'use strict';
        var nonNullDate = date ? new Date(date) : new Date();
        return subtractFromDate(0, durationInDays, 0, 0, 0, 0, 0, nonNullDate);
    };

    root.subtractFromDateUnformatted = function (month, day, year, hours, minutes, seconds, milliseconds, date) {
        'use strict';
        month = date.getMonth() - parseInt(month);
        day = date.getDate() - parseInt(day);
        year = date.getFullYear() - parseInt(year);
        hours = date.getHours() - parseInt(hours);
        minutes = date.getMinutes() - parseInt(minutes);
        seconds = date.getSeconds() - parseInt(seconds);
        milliseconds = date.getMilliseconds() - parseInt(milliseconds);

        return new Date(year, month, day, hours, minutes, seconds, milliseconds);
    };

    root.addCustomDates = function (dateFrom, dateTo, callbackFn) {
        'use strict';
        $('#add-custom').before('<li data-startDate="'+ dateFrom +'" data-endDate="'+ dateTo +'">'+ dateFrom + ' - ' + dateTo + '<div class="listing-bg"></div></li>')

        if ($.isFunction(callbackFn)) {
            callbackFn.call();
        }
    };

    root.indexOf = function (array, searchElement) {
        'use strict';
        var size = array.length,
            i = 0;
        for (i; i < size; i++) {
            if (array[i] === searchElement) {
                return i;
            }
        }
        return -1;
    };

    root.formatTime = function (date) {
        'use strict';
        var d = new Date(date),
            hh = d.getHours(),
            m = d.getMinutes(),
            s = d.getSeconds(),
            dd = "",
            h = hh;

        m = m < 10 ? "0" + m : m;

        s = s < 10 ? "0" + s : s;

        h = h < 10 ? "0" + h : h;

        return h + ":" + m + " " + dd;
    };

    root.formatDateToDays = function (date, shortenWeekday) {
        'use strict';
        var d = new Date(date),
            weekday = shortenWeekday ? ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        return weekday[d.getDay()]  + month[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();

    };

    root.writeLocationsToStorage = function (key, value) {
        'use strict';
        if (value) {
            try {
                if (typeof(window.localStorage) !== 'undefined') {
                    var currentArray = readLocationsFromStorage(key),
                        currentArrayLength = currentArray.length,
                        i = 0;

                    if (currentArrayLength > 0) {
                        for (i; i < currentArrayLength; i++) {
                            if (!currentArray[i] || currentArray[i].name === value.name) {
                                currentArray.splice(i, 1);
                            }
                        }
                        if (currentArray.length >= 3) {
                            currentArray.pop();
                        }
                    }
                    currentArray.unshift(value);
                    window.localStorage[key] = JSON.stringify(currentArray);
                }
            } catch (e) {
                /*if (e == QUOTA_EXCEEDED_ERR) {
                 alert('Quota exceeded!');
                 }*/
            }
        }
    };

    root.readLocationsFromStorage = function (key) {
        'use strict';
        var value = null;
        if (typeof(window.localStorage) !== 'undefined') {
            value = JSON.parse(window.localStorage[key] || null);
        }

        if (value) {
            var currentArrayLength = value.length;
            for (var i = 0; i < currentArrayLength; i ++) {
                if (!value[i]) {
                    value.splice(i, 1);
                }
            }
        }

        return value ? value : [];
    };

    root.getUriByTitle = function (atomLinks, title) {
        'use strict';
        var uri = null;
        $.each(atomLinks, function (index, atomLink) {
            if (atomLink.rel === 'related' && atomLink.title === title){
                uri = atomLink.href;
                return;
            }
        });

        return uri;
    };

    root.flattenLinks = function (object) {
        'use strict';
        var links = object.get('link'),
            size = links.length,
            i = 0;
        for (i; i<size; i++) {
            object.set(links[i].title,links[i]);
        }
        object.unset('link');
    };

    // First letter of first entire string
    root.capitaliseFirstLetter = function (string) {
        'use strict';
        string = string.toLowerCase();
        return string.charAt(0).toUpperCase() + string.slice(1);
    };

    // First letter of each word in string
    root.titleCase = function (str) {
        'use strict';
        return str.replace(/\w\S*/g, function (txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    };


    root.isWithinDateRange = function(startDate, endDate, checkDate) {
        if (typeof startDate === 'undefined' || typeof endDate === 'undefined') {
            return true;
        } else {
            var sDate = new Date(startDate);
            var eDate = new Date(endDate);
            var cDate = new Date(checkDate);
            return cDate >= sDate && cDate <= eDate;
        }
    };

    root.getAlertLevel = function(daysOnList) {
        if (daysOnList >= 38) {
            return 'C';
        } else if (daysOnList >= 37) {
            return 'B';
        } else if (daysOnList >= 35) {
            return 'A';
        } else if (daysOnList >= 8) {
            return 'C';
        } else if (daysOnList >= 7) {
            return 'B';
        } else if (daysOnList >= 5) {
            return 'A';
        } else {
            return '';
        }
        return '';
    };

    root.isValidDate = function(date) {
        //Enforces the format mm/dd/yyyy
        var valid = true,
            dateRegex = /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/;

        if (dateRegex.test(date)) {
            var dateParts = date.split('/'),
                month = parseInt(dateParts[0]),
                day = parseInt(dateParts[1]),
                year = parseInt(dateParts[2]),
                months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
                leapYear = isLeapYear(year);

            if (leapYear) {
                months[1] = 29;
            }

            if (month < 1 || month > 12 || year < 1900 || year > 2100 || day < 1 || day > months[month - 1]) {
                valid = false;
            }
        } else {
            valid = false;
        }

        return valid;
    };

    root.isLeapYear = function(year) {
        var leapYear;

        if (year % 4 !== 0) {
            leapYear = false;
        } else if (year % 100 !== 0) {
            leapYear = true;
        } else if (year % 400 !== 0) {
            leapYear = false;
        } else {
            leapYear = true;
        }

        return leapYear;
    };

}));
