/**
 * Created by vlade on 2/23/15.
 */
/**
 * Check device
 * @returns {0: Cell phone, 1: Tablet, 2: Others}
 */
function check_device(){
    var device = 2;
    var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
    if(isIE)
        return device;
    var userAgent = navigator.userAgent.toLowerCase();
    device = (/iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/i.test(userAgent)) ? 0
        : (/ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent)) ? 1 : 2;

    if(device != 2){
        if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
            device = 0;
        else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
            device =  1;
    }

    return device;
}
function sanitize_entry(regex, value){
        var sanitized = regex.test(value) ? value : value.substr(0,value.length-1);
        return sanitized;
}

String.prototype.format = function() {
    // The string containing the format items (e.g. "{0}")
    // will and always has to be the first argument.
    var theString = arguments[0];

    // start with the second argument (i = 1)
    for (var i = 1; i < arguments.length; i++) {
        // "gm" = RegEx options for Global search (more than one instance)
        // and for Multiline search
        var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
        theString = theString.replace(regEx, arguments[i]);
    }

    return theString;
}
String.prototype.replaceAll = function(str1, str2, ignore){
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);
    else
        return string + this;
}
String.prototype.contains = function(cad) {
    return this.toLowerCase().indexOf(cad.toLowerCase()) != -1;
};
Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};
Date.prototype.addDays = function(days){
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
}

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

if (!Array.prototype.first){
    Array.prototype.first = function(){
        return this[0];
    };
};



/*Knockout variants*/
ko.bindingHandlers.stopBubble = {
    init: function(element) {
        ko.utils.registerEventHandler(element, "click", function(event) {
            event.cancelBubble = true;
            if (event.stopPropagation) {
                event.stopPropagation();
            }
        });
    }
};

ko.bindingHandlers.enterkeypress = {
    init: function (element, valueAccessor, allBindings, viewModel) {
        var callback = valueAccessor();
        $(element).keypress(function (event) {
            var keyCode = (event.which ? event.which : event.keyCode);
            if (keyCode === 13) {
                callback.call(viewModel);
                return false;
            }
            return true;
        });
    }
};

function extrim(cad){
    cad = $.trim(cad);
    var unvalid_characters = "!@#$%^&*()_+={}[]:?><,./~ ";

    if(unvalid_characters.indexOf(cad.charAt(cad.length - 1)) >= 0){
        cad = cad.substr(0, cad.length - 1);
        return extrim(cad);
    }
    return cad;
}

function getFirstWeekDay(){
    /*var curr = new Date();
    var startOfWeek = curr.getDate() - curr.getDay() + 3;
    startOfWeek = new Date(curr.setDate(startOfWeek));*/

    var first_day = new Date();
    var date = new Date();
    if(date.getDay() != 3){
        var startOfWeek = date.getDate() - date.getDay() + 3;
        date = new Date(first_day.setDate(startOfWeek));
    }

    return date;
}
function getLastWeekDay(){
    var last_day = new Date();
    var date = new Date();
    date = getFirstWeekDay().getDate() + 6;
    date = new Date(last_day.setDate(date));

    return date;
}

function getFirstXAgoWeekDay(xago){
    var first_day = new Date();
    var date = new Date();
    if(xago <= 0)
        return getFirstWeekDay();
    else{
        var startOfWeek = date.getDate() - date.getDay() - 4 - (7 * (xago - 1));
        date = new Date(first_day.setDate(startOfWeek));
        return date;
    }
}
function getLastXAgoWeekDay(xago, xweek){
    xweek = xweek >= 1 ? xweek : 1;
    var last_day = getFirstXAgoWeekDay(xago);
    var date = new Date();
    date = last_day.getDate() + 6 + (7 * (xweek - 1));
    date = new Date(last_day.setDate(date));

    return date;
}

function getXAgoWeekDateRange(xago){
    var range = new Array();
    var now = new Date();
    range.push(getFirstXAgoWeekDay(xago));
    range.push(getLastXAgoWeekDay(xago, 1));
    return range;
}
function getXAgoBiWeekDateRange(xago){
    var range = new Array();
    var now = new Date();
    range.push(getFirstXAgoWeekDay(xago * 2));
    range.push(getLastXAgoWeekDay(xago * 2, 2));
    return range;
}
function getXAgo4WeekDateRange(xago){
    var range = new Array();
    var now = new Date();
    range.push(getFirstXAgoWeekDay(xago * 4));
    range.push(getLastXAgoWeekDay(xago * 4, 4));
    return range;
}

function getFirstWeekDayByDate(date){
    /*var curr = new Date();
     var startOfWeek = curr.getDate() - curr.getDay() + 3;
     startOfWeek = new Date(curr.setDate(startOfWeek));*/

    var first_day = new Date(date);
    date = new Date(date);
    var a = date.getDate();
    var b = date.getDay();
    if(date.getDay() != 3){
        if(date.getDay() > 3){
            var startOfWeek = date.getDate() - date.getDay() + 3;
            date = new Date(first_day.setDate(startOfWeek));
        }
        else if(date.getDay() < 3){
            var startOfWeek = date.getDate() - date.getDay() - 4;
            date = new Date(first_day.setDate(startOfWeek));
        }

    }

    return date;
}
function getLastWeekDayByDate(date){
    var last_day = new Date(date);
    date = getFirstWeekDayByDate(date).addDays(6);
    //date = new Date(last_day.setDate(date));

    return date;
}
function getWeekDateRangeByDate(date){
    var range = new Array();
    range.push(getFirstWeekDayByDate(date));
    range.push(getLastXAgoWeekDayByDate(date, 1));
    return range;
}

function getPeriodByDate(date){
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var firstDate = new Date(first_pay_cycle[1]);
    var secondDate = new Date(date);

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    var x = diffDays % 14 - 1;

    var cicle_start = new Date(date);
    cicle_start.setDate(cicle_start.getDate() - x);
    var cicle_end = new Date(cicle_start);
    cicle_end.setDate(cicle_end.getDate() + 13);
    alert(cicle_start + ' - ' + cicle_end);
    alert(getFirstWeekDayByDate(date) + ' - ' + getLastWeekDayByDate(date));
}

function refreshValue($char, $char1, element){
    if($char === 13 || $char1 === 13){
        element.blur();
    }
}
function applyFocus2Element(element){
    $(element).focus();
}

/**
 * Show message
 * @param message
 * @param caption
 * @param cssclass for vizualization
 */
function ShowMessage(){//message, caption, cssclass, id){
    /*<div class="modal fade bs-example-modal-lg"
    id="alternative-message"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                        <span class="sr-only">Cancel</span>
                    </button>
                    <h4 class="modal-title">Question???</h4>
                </div>
                <div class="modal-body">
                    <div class="container-fluid"
                    style="padding: 0px;">
                        <div style="font-size: 18px;">
                            <p>There's no stock uploaded with that number...</p>
                            <p>Do you want to create a new one. This new stock will be\\n updated as soon as it's
                            uploded to "http://www.aeroservicios.com".</p>
                            <p>Click Create to generate a new stock or Cancel to close this wizard.</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="stock-modal-cancel-button" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button id="stock-modal-cancel-button" type="button"
                    class="btn btn-primary" data-dismiss="modal"
                    data-bind="click: chosenwo().create_stock">Create</button>
                </div>
            </div>
        </div>
    </div>*/
    $('.modal').modal('hide');
}

/**
 * Styling
 * */
function set_error_style(el_id){
    $("#" + el_id).addClass("error-style");
}
function set_valid_style(el_id){
    $("#" + el_id).removeClass("error-style");
}
var task_status = [
    "Canceled",
    "Complete",
    "Current",
    "Hold"];
var wo_status = ["Current",
    "Hold",
    "Rented",
    "Out",
    "Sold"];
var stock_status = ["Current",
    "Hold",
    "Rented",
    "Out",
    "Sold"];
var stock_areas = [{name: "Electricidad", color: "#BA55D3"},
    {name: "Mecánica", color: "#E066FF"},
    {name: "Pintura", color: "#E0B0FF",
        works: [{code: "001", work: "Retirar Stickers", color: "#BA55D3"},
            {code: "001", work: "Retirar Stickers", color: "#BA55D3"},
            {code: "002", work: "Retirar Pintura con  Removedor", color: "#BA55D3"},
            {code: "003", work: "Retirar Pintura con  Lija", color: "#BA55D3"},
            {code: "004", work: "Retirar Pintura con  RacaRaca", color: "#BA55D3"},
            {code: "005", work: "Sand Blasting", color: "#BA55D3"},
            {code: "006", work: "Preparar", color: "#BA55D3"},
            {code: "007", work: "Aplicar Primer", color: "#BA55D3"},
            {code: "008", work: "Enmascarar", color: "#BA55D3"},
            {code: "009", work: "pintar", color: "#BA55D3"},
            {code: "010", work: "Desenmascarar", color: "#BA55D3"},
            {code: "011", work: "Acabados", color: "#BA55D3"}
        ]},
    {name: "Soldadura", color: "#9E7BFF"}];

var area_works = [{name: "Adaptar", color: "#BA55D3"},
    {name: "Ajustar", color: "#E066FF"},
    {name: "Arrancar", color: "#E0B0FF"},
    {name: "Desarmar", color: "#9E7BFF"},
    {name: "Desempap.", color: "#8470FF"},
    {name: "Desmontar", color: "#6A5ACD"},
    {name: "Diseñar", color: "#6495ED"},
    {name: "Distribuir", color: "#CAE1FF"},
    {name: "Empapelar", color: "#B9D3EE "},
    {name: "Engrasar", color: "#63B8FF"},
    {name: "Ensamblar", color: "#33A1C9"},
    {name: "Esmerilar", color: "#00E5EE"},
    {name: "Fabricar", color: "#00C5CD"},
    {name: "Fregar", color: "#00868B"},
    {name: "Identificar", color: "#5F9EA0"},
    {name: "Instalar", color: "#00C78C"},
    {name: "Levantar", color: "#7FFFD4"},
    {name: "Limpiar", color: "#66CDAA"},
    {name: "Mant.", color: "#458B74"},
    {name: "Montar", color: "#00CD66"},
    {name: "Movimiento", color: "#3CB371"},
    {name: "Organizar", color: "#43CD80"},
    {name: "Pintar", color: "#9BCD9B"},
    {name: "Preparar", color: "#9ACD32"},
    {name: "Probar", color: "#BDB76B"},
    {name: "Recuperar", color: "#EEE685"},
    {name: "Reemplazar", color: "#FFD700"},
    {name: "Reparar", color: "#EEC900"},
    {name: "Revisar", color: "#CDAD00"},
    {name: "Sandblasting", color: "#FFC125"},
    {name: "Sellar", color: "#FFA500"},
    {name: "Ajustar", color: "#E066FF"},
    {name: "Arrancar", color: "#E0B0FF"},
    {name: "Desarmar", color: "#9E7BFF"},
    {name: "Desempap.", color: "#8470FF"},
    {name: "Desmontar", color: "#6A5ACD"},
    {name: "Diseñar", color: "#6495ED"},
    {name: "Distribuir", color: "#CAE1FF"},
    {name: "Empapelar", color: "#B9D3EE "},
    {name: "Engrasar", color: "#63B8FF"},
    {name: "Ensamblar", color: "#33A1C9"},
    {name: "Esmerilar", color: "#00E5EE"},
    {name: "Fabricar", color: "#00C5CD"},
    {name: "Fregar", color: "#00868B"},
    {name: "Identificar", color: "#5F9EA0"},
    {name: "Instalar", color: "#00C78C"},
    {name: "Levantar", color: "#7FFFD4"},
    {name: "Limpiar", color: "#66CDAA"},
    {name: "Mant.", color: "#458B74"},
    {name: "Montar", color: "#00CD66"},
    {name: "Movimiento", color: "#3CB371"},
    {name: "Organizar", color: "#43CD80"},
    {name: "Pintar", color: "#9BCD9B"},
    {name: "Preparar", color: "#9ACD32"},
    {name: "Probar", color: "#BDB76B"},
    {name: "Recuperar", color: "#EEE685"},
    {name: "Ajustar", color: "#E066FF"},
    {name: "Arrancar", color: "#E0B0FF"},
    {name: "Desarmar", color: "#9E7BFF"},
    {name: "Desempap.", color: "#8470FF"},
    {name: "Desmontar", color: "#6A5ACD"},
    {name: "Diseñar", color: "#6495ED"},
    {name: "Distribuir", color: "#CAE1FF"},
    {name: "Empapelar", color: "#B9D3EE "},
    {name: "Engrasar", color: "#63B8FF"},
    {name: "Ensamblar", color: "#33A1C9"},
    {name: "Esmerilar", color: "#00E5EE"},
    {name: "Fabricar", color: "#00C5CD"},
    {name: "Fregar", color: "#00868B"},
    {name: "Identificar", color: "#5F9EA0"},
    {name: "Instalar", color: "#00C78C"},
    {name: "Levantar", color: "#7FFFD4"},
    {name: "Limpiar", color: "#66CDAA"},
    {name: "Mant.", color: "#458B74"},
    {name: "Montar", color: "#00CD66"},
    {name: "Movimiento", color: "#3CB371"},
    {name: "Organizar", color: "#43CD80"},
    {name: "Pintar", color: "#9BCD9B"},
    {name: "Preparar", color: "#9ACD32"},
    {name: "Probar", color: "#BDB76B"},
    {name: "Recuperar", color: "#EEE685"},
    {name: "Reemplazar", color: "#FFD700"},
    {name: "Reparar", color: "#EEC900"},
    {name: "Revisar", color: "#CDAD00"},
    {name: "Sandblasting", color: "#FFC125"},
    {name: "Sellar", color: "#FFA500"},
    {name: "Serviciar", color: "#FF6103"}];
var colors = ["#BA55D3","#E066FF","#E0B0FF","#9E7BFF","#8470FF","#6A5ACD","#6495ED","#CAE1FF","#B9D3EE ","#63B8FF",
    "#33A1C9","#00E5EE","#00C5CD","#00868B","#5F9EA0","#00C78C","#7FFFD4","#66CDAA","#458B74","#00CD66","#3CB371",
    "#43CD80","#9BCD9B","#9ACD32","#BDB76B","#EEE685","#FFD700","#EEC900","#CDAD00","#FFC125","#FFA500"];
var first_pay_cycle = ["01/07/2015", "01/20/2015"];