/**
 * Extra functions used by angular Digpedia application
 * @author Massimiliano Battan
 * @version 3.6
 * 
 **/

var tobeClosed;
var regExpDateRange = new RegExp("\\[([0-9]{4}-[0-9]{2}-[0-9]{2})?,([0-9]{4}-[0-9]{2}-[0-9]{2})?\\]");
var regExpMonthDayRange = new RegExp("\\[([0-9]{2}-[0-9]{2})?,([0-9]{2}-[0-9]{2})?\\]");

function collapseSettings(){
    $(el).collapse('toggle');
}

function collapseAll() {
    $("[id^='collapse'").each(function (index, entry) {
        if ($(entry).hasClass("in")) {
            $(entry).collapse('hide');
        }
    });
    $(window).scrollTop("#modal_wait");
    $("#modal_wait").dialog({
        autoOpen: true,
        title: "Info",
        modal: true,
        hide: {
            effect: "explode",
            duration: 100
        }
    });
    $("#modal_wait").animate({scrollTop: 0});
}

function showAdvanced() {
    $(".collapsable").slideToggle(400);
}


function showDialog(element, data) {
    var content = document.createElement("p");
    content.innerHTML = data;
    $("#dialogInfo").empty().append(content);
    $("#dialogInfo").dialog("option", "position", {my: "center bottom", at: "center top", of: element});
    $("#dialogInfo").dialog("open");
    tobeClosed = 0;
}

$(window).load(function () {

    $("#openAdv").click(function () {
        $(".collapsable").slideToggle(400);
    });

    function listenOutside() {
        if (tobeClosed) {
            $("#dialogInfo").dialog("close");
        }
        tobeClosed = 1;
    }

    $("#dialogInfo").dialog({
        title: 'Info',
        autoOpen: false,
        show: {
            effect: "fade",
            duration: 300
        },
        hide: {
            effect: "explode",
            duration: 150
        },
        open: function () {
            tobeClosed = 1;
            $(document).bind('click', listenOutside);
        },
        focus: function () {

        },
        close: function () {
            $(document).unbind('click', listenOutside);
        }
    });

});

function getSteps(currentValue) {

    var steps = []; //step,minvalue,maxvalue,startmin,startmax
    var step = 5 * (Math.round(Math.round(currentValue / 25) / 5));
    if (step > 5) {
        steps.push(step);
    } else {
        steps.push(1);
    }
    steps.push(0); //min value
    var step2 = 5 * (Math.round((currentValue * 2) / 5)); //max value is the next multiple of 5 of value*2
    steps.push(step2);
    var step3 = 5 * (Math.round((steps[2] / 4) / 5)); //startmin is the next multiple of 5 of 1/4 of max
    steps.push(step3);
    var step4 = 5 * (Math.round(((steps[2] / 4) * 3) / 5)); //startmax is the next multiple of 5 of 3/4 of max 
    steps.push(step4);
    return steps;
}

function hasYear(date) {
    var jsDate = new Date(Date.parse(date));
    var year = jsDate.getFullYear();
    return year == 1;
}

function clickSingleDigit(uniqueKey, limits) {
    var rangeinstance = $("[id='sliderRange" + uniqueKey + "']").slider("instance");
    var input = $("[id='input" + uniqueKey + "']");
    if (rangeinstance != undefined) {
        $("[id='sliderRange" + uniqueKey + "']").slider("destroy");
    }
    input.attr("class", "inputWithSelect");
    //this is required because if i'm passing from range to single the actual model has = as value type but maybe before switching
    //from single to range I changed the type to something else. This will lead to an icon different from "=" and the model being "="
//    input.css("background-image", "url('js/img/equal.png')");
    $("[id='sliderSingle" + uniqueKey + "']").slider({
        slide: function (event, ui) {//change on single slider value
            var value = ui.value;
            input.val(value);
            input.trigger('input'); //required by angular model to catch the change!!
        },
        min: limits[1],
        max: limits[2],
        value: 0,
        step: limits[0]
    });
}

function clickSingleDate(uniqueKey, isMonthDay) {
    var dateFormat;
    if (isMonthDay) {
        dateFormat = "mm-dd";
    } else {
        dateFormat = "yy-mm-dd";
    }
    var input = $("[id='input" + uniqueKey + "']");
    //this is required because if i'm passing from range to single the actual model has = as value type but maybe before switching
    //from single to range I changed the type to something else. This will lead to an icon different from "=" and the model being "="
    input.css("background-image", "url('js/img/equal.png')");
    $("[id='fromTo" + uniqueKey + "']").hide();
    var instaTo = $("[id='inputTo" + uniqueKey + "']").hasClass("hasDatepicker");
    var instaFrom = $("[id='inputFrom" + uniqueKey + "']").hasClass("hasDatepicker");
    if (instaTo != undefined) {
        $("[id='inputTo" + uniqueKey + "']").datepicker("destroy");
    }
    if (instaFrom != undefined) {
        $("[id='inputFrom" + uniqueKey + "']").datepicker("destroy");
    }

    input.attr("class", "inputWithSelect");
    input.datepicker({
        changeYear: true,
        changeMonth: true,
        yearRange: "-500:+0",
        dateFormat: dateFormat

    });
}

function clickRangeDigit(uniqueKey, limits) {
    var input = $("[id='input" + uniqueKey + "']");
    var singleinstance = $("[id='sliderSingle" + uniqueKey + "']").slider("instance");
    if (singleinstance != undefined) {
        $("[id='sliderSingle" + uniqueKey + "']").slider("destroy");
    }
    input.attr("class", "inputNoSelect");
    $("[id='sliderRange" + uniqueKey + "']").slider({
        range: true,
        min: limits[1],
        max: limits[2],
        values: [limits[3], limits[4]],
        slide: function (event, ui) {//change on range slider values
            var values = ui.values;
            input.val("[" + values[0] + "," + values[1] + "]");
            input.trigger('input');
        }
    });
}

function clickRangeDate(uniqueKey, isMonthDay) {
    var dateFormat;
    if (isMonthDay) {
        dateFormat = "mm-dd";
    } else {
        dateFormat = "yy-mm-dd";
    }
    var input = $("[id='input" + uniqueKey + "']");
    $("[id='fromTo" + uniqueKey + "']").show();
    var instaSingle = input.hasClass("hasDatepicker");
    if (instaSingle != undefined) {
        input.datepicker("destroy");
    }
    input.attr("class", "inputNoSelect");
    $("[id='inputFrom" + uniqueKey + "']").datepicker({
        changeYear: true,
        changeMonth: true,
        yearRange: "-500:+0",
        dateFormat: dateFormat,
        onClose: function (selectedDate) {
            var text = input.val();
            var match;
            if (isMonthDay) {
                match = regExpMonthDayRange.exec(text);
            } else {
                match = regExpDateRange.exec(text);
            }
            if (match[2] != undefined) {
                input.val("[" + selectedDate + "," + match[2] + "]");
            } else {
                input.val("[" + selectedDate + ",]");
            }
            input.trigger('input');
        }

    });
    $("[id='inputTo" + uniqueKey + "']").datepicker({
        changeYear: true,
        changeMonth: true,
        yearRange: "-500:+0",
        dateFormat: dateFormat,
        onClose: function (selectedDate) {
            var text = input.val();
            var match;
            if (isMonthDay) {
                match = regExpMonthDayRange.exec(text);
            } else {
                match = regExpDateRange.exec(text);
            }
            if (match[1] != undefined) {
                input.val("[" + match[1] + "," + selectedDate + "]");
            } else {
                input.val("[," + selectedDate + "]");
            }
            input.trigger('input');
        }
    });
}

function showDrop(el) {
    var list = $(el).siblings("ul");
    $(list).children().bind("mouseover", function () {
        $(el).val($(this).children().text());
        $(el).trigger('input');
    });
    if ($(list).css("visibility") == "hidden") {
        $(list).hide();
    } else {
        $(list).show("slide", {}, 400);
        $(list).addClass("openN");
        tobeClosed = 0;
        $(document).bind("click", closeDrop);
    }
}

function closeDrop() {
    if (tobeClosed) {
        $(".openN").hide();
        $(document).unbind("click", closeDrop);
        $(".openN").children().unbind("mouseover");
    }
    tobeClosed = 1;
}

function showHiddenInfo(el) {
    var element = $("[id='hiddenSel" + el + "']");
    element.show("slide", {
        complete: function () {
            $(document).bind('click',{
                el:element
            }, outsideClick);
        }
    }, 500);
}

function outsideClick(event) {
    var element = event.data.el;
    var isaChild = $.contains(element[0], event.target);
    if (event.target.id != element[0].id
            && !isaChild) {
        element.hide("slide", {}, 200);
        $(document).unbind('click', outsideClick);
    }
}