<commit_before>/**
 * Created by Laurent on 22/08/2016.
 */

var SearchState = {
    LOADING: {value: 0},
    NO_RESULTS: {value: 1},
    RESULTS: {value: 2}
};

var EPMC = "http://www.europepmc.org/abstract/MED/";

$(document).ready(function() {
    var searchTerm = $('#query').text();
    console.log("Loading search module!");
    console.log("rsID: "+searchTerm);
    if (searchTerm != '') {
        console.log("Start search for SNP "+searchTerm);
        getSnpData(searchTerm);
    }
    getLDPopulations();
});

function getSnpData(rsId) {
    console.log("Solr research request received for " + rsId);

    setState(SearchState.LOADING);
    $.getJSON('/gwas/api/search/association',
              {
                  'q': "rsId:"+rsId,
                  'group': 'true',
                  'group.by': 'resourcename',
                  'group.limit': 5
              })
              .done(function(data) {
                  console.log(data.response);
                  processSnpData(data.response,rsId);
              });
    console.log("Solr research done for " + rsId);
}

function processSnpData(data,rsId) {
    // Snp summary panel
    getSnpInfo(data);
    // External links panel
    getLinkButtons(rsId);
    // Associations table
    getSnpAssociations(data.docs);
    // Traits table
    getSnpTraits(data.docs);
}

function getSnpInfo(data,rsId) {
    var chr = data.docs[0].chromosomeName[0];
    var pos = data.docs[0].chromosomePosition[0];
    var region = data.docs[0].region[0];
    var func = data.docs[0].context[0];

    var genes_reported = [];
    var genes_reported_url = [];
    var genes_mapped = [];
    var genes_mapped_url = [];
    $.each(data.docs, function (index, doc) {
        // Reported genes
        var reportedGenes = doc.reportedGene;
        $.each(reportedGenes, function (index, gene) {
            if (jQuery.inArray(gene, genes_reported) == -1) {
                genes_reported.push(gene);
                genes_reported_url.push(setQueryUrl(gene));
            }
        });
        // Mapped genes
        var mappedGenes = doc.entrezMappedGenes;
        $.each(mappedGenes, function (index, gene) {
            if (jQuery.inArray(gene, genes_mapped) == -1) {
                genes_mapped.push(gene);
                genes_mapped_url.push(setQueryUrl(gene));
            }
        });
    });

    $("#snpLocation").html("chr"+chr+":"+pos);
    $("#snpRegion").html(region);
    $("#snpClass").html(func);
    $("#snpReportedGenes").html(genes_reported_url.join(', '));
    $("#snpMappedGenes").html(genes_mapped_url.join(', '));
}

function getLinkButtons (rsId) {
    $("#ensembl_button").attr('onclick', "window.location.href='http://www.ensembl.org/Homo_sapiens/Variation/Explore?v="+rsId+"'");
    $("#dbsnp_button").attr('onclick', "window.location.href='http://www.ncbi.nlm.nih.gov/SNP/snp_ref.cgi?rs="+rsId+"'");
}

function getSnpAssociations(data) {
    var asso_count = data.length;

    $("#association_count").html(asso_count);

    if (asso_count == 1) {
        $("#association_label").html("Association");
    }

    $.each(data, function(index,asso) {

        var row = $('
');

        // Risk allele
        var riskAllele = asso.strongestAllele[0];
        riskAllele = setQueryUrl(riskAllele);
        row.append(newCell(riskAllele));

        // Risk allele frequency
        var riskAlleleFreq = asso.riskFrequency;
        row.append(newCell(riskAlleleFreq));

        // p-value
        var pValue = asso.pValueMantissa;
        if (pValue) {
            var pValueExp = " x 10" + asso.pValueExponent + "";
            pValue += pValueExp;
            if (asso.qualifier) {
                if (asso.qualifier[0].match(/\w/)) {
                    pValue += " " + asso.qualifier.join(',');
                }
            }
            row.append(newCell(pValue));
        } else {
            row.append(newCell('-'));
        }

        // OR
        var orValue = asso.orPerCopyNum;
        if (orValue) {
            if (asso.orDescription) {
                orValue += " " + asso.orDescription;
            }
            row.append(newCell(orValue));
        } else {
            row.append(newCell('-'));
        }

        // Beta
        var beta = asso.betaNum;
        if (beta) {
            if (asso.betaUnit) {
                beta += " " + asso.betaUnit;
            }
            if (asso.betaDirection) {
                beta += " " + asso.betaDirection;
            }
            row.append(newCell(beta));
        } else {
            row.append(newCell('-'));
        }

        // CI
        var ci = asso.range;
        if (ci) {
            row.append(newCell(ci));
        } else {
            row.append(newCell('-'));
        }

        // Reported genes
        var genes = [];
        var reportedGenes = asso.reportedGene;
        if (reportedGenes) {
            $.each(reportedGenes, function(index, gene) {
                genes.push(setQueryUrl(gene));
            });
            row.append(newCell(genes.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Reported traits
        var traits = [];
        var reportedTraits = asso.traitName;
        if (reportedTraits) {
            $.each(reportedTraits, function(index, trait) {
                traits.push(setQueryUrl(trait));
            });
            row.append(newCell(traits.join(', ')));
        } else {
           row.append(newCell('-'));
        }

        // Mapped traits
        var mappedTraits = asso.mappedLabel;
        if (mappedTraits) {
            row.append(newCell(mappedTraits.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Study
        var author = asso.author_s;
        var publicationDate = asso.publicationDate;
        var pubDate = publicationDate.split("-");
        var pubmedId = asso.pubmedId;
        var study = setQueryUrl(author, author + " - " + pubDate[0]);
        study += ' PMID:'+pubmedId+' ';
        row.append(newCell(study));

        var studyId = asso.studyId;

        row.append(newCell(showHideStudy(studyId)));

        // Populate the table
        $("#association-table-body").append(row);

        // Add hidden study description/details
        var studyRow = $('
');
        studyRow.addClass("accordion-body hidden-study-row collapse");
        studyRow.attr('id',"study-"+studyId);

        var sudyContent = $("	");
        sudyContent.attr('colspan',11);
        sudyContent.attr('style',"border-top: none");

        var initialSampleDescription = asso.initialSampleDescription;
        var replicateSampleDescription = asso.replicateSampleDescription;
        var ancestralGroups = asso.ancestralGroups;

        var studyTable = $("
").addClass('sample-info sample-info-border');

        // Header //
        studyTable.append($("
").append($("
").append($("").attr("colspan","2").attr("style", "background-color:#E7F7F9").html("Study information"))));

        // Content //
        var studyTableContent = $("
");

        // Initial sample description
        var initialSampleDescriptionRow = $("
");
        initialSampleDescriptionRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Initial sample description"));
        initialSampleDescriptionRow.append($("").attr("style", "text-align:left").html(initialSampleDescription));
        studyTableContent.append(initialSampleDescriptionRow);

        // Replication sample description
        var replicateSampleDescriptionRow = $("
");
        replicateSampleDescriptionRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Replication sample description"));
        replicateSampleDescriptionRow.append($("").attr("style", "text-align:left").html(replicateSampleDescription));
        studyTableContent.append(replicateSampleDescriptionRow);

        // Ancestral groups
        var ancestralGroupsRow = $("
");
        ancestralGroupsRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Ancestral groups"));
        ancestralGroupsRow.append($("").attr("style", "text-align:left").html(ancestralGroups.join(', ')));
        studyTableContent.append(ancestralGroupsRow);

        studyTable.append(studyTableContent);

        /*var content = '

Study information

' +
        '
' +
        '
' +
        '      Initial sample description	' +
        '      '+initialSampleDescription+'	' +
        '
' +
        '
' +
        '      Replication sample description	' +
        '      '+replicateSampleDescription+'	' +
        '
' +
        '
' +
        '      Ancestral groups	' +
        '      '+ancestralGroups.join(', ')+'	' +
        '
' +
        '
' +
        '
';

        sudyContent.html(content);*/
        sudyContent.html(studyTable);
        studyRow.append(sudyContent);

        $("#association-table-body").append(studyRow);
    });
}

function getSnpTraits(data) {

    // Fetch data //
    var traits = [];
    var mappedtraits = {};
    var mappedtraitsUri = {};
    var synonymtraits = {};
    var studytraits = {};
    $.each(data, function(index,asso) {
        // Trait
        var trait = asso.traitName_s;
        if (jQuery.inArray(trait, traits) == -1) {
            traits.push(trait);
        }

        // Mapped trait(s)
        mappedtraits[trait] = asso.mappedLabel;
        mappedtraitsUri[trait] = asso.mappedUri;

        // Synonym trait(s)
        synonymtraits[trait] = asso.synonym;

        // Study trait(s)
        var author = asso.author_s;
        var publicationDate = asso.publicationDate;
        var pubDate = publicationDate.split("-");
        var pubmedId = asso.pubmedId;
        var study = setQueryUrl(author, author + " - " + pubDate[0]);
        study += setExternalLink(EPMC+pubmedId);
        if (jQuery.inArray(study, studytraits[trait]) == -1) {
            if (!studytraits[trait]) {
                studytraits[trait] = [];
            }
            studytraits[trait].push(study);
        }
    });

    // Display/print data //
    $("#diseasetrait_count").html(traits.length);

    if (traits.length == 1) {
        $("#diseasetrait_label").html("Trait");
    }

    traits.sort();

    $.each(traits, function(index,trait) {
        var row = $('
');

        // Trait
        row.append(newCell(setQueryUrl(trait)));

        // Mapped trait(s)
        if (mappedtraits[trait]) {
            var mappedtrait = [];
            $.each(mappedtraits[trait], function(index, mtrait) {
                var mapped_html = setQueryUrl(mtrait);
                mapped_html += setExternalLink(mappedtraitsUri[trait][index]);
                mappedtrait.push(mapped_html);
            });
            row.append(newCell(mappedtrait.join(',
')));
        } else {
            row.append(newCell('-'));
        }

        // Synonym trait(s)
        if (synonymtraits[trait]) {
            var synonymtrait = [];
            $.each(synonymtraits[trait], function(index, syntrait) {
                synonymtrait.push(setQueryUrl(syntrait));
            });
            row.append(newCell(synonymtrait.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Study trait(s)
        if (studytraits[trait]) {
            row.append(newCell(studytraits[trait].join(',
')));
        } else {
            row.append(newCell('-'));
        }
        $("#diseasetrait-table-body").append(row);
    });
}

function setQueryUrl(query, label) {
    if (!label) {
        label = query;
    }
    return ''+label+'';
}

function setExternalLink(url) {
    return '';
}

function newCell(content) {
    return $("	").html(content);
}

function showHideStudy(studyId) {
    //return '<button title="Click to show/hide more study information" class="row-toggle btn btn-default btn-xs accordion-toggle" data-toggle="collapse" data-target=".study-'+studyId+'.hidden-study-row" aria-expanded="false" aria-controls="study:'+studyId+'">' +
    var study_button = $("<button></button>");
    study_button.attr('title', 'Click to show/hide more study information');
    study_button.attr('id', 'button-study-'+studyId);
    study_button.attr('onclick', 'toggleDiv("study-'+studyId+'")');
    study_button.addClass("btn btn-default btn-xs btn-study");
    study_button.html('');

    return study_button;
}

function getLDPopulations() {
    $.getJSON('http://rest.ensembl.org/info/variation/populations/homo_sapiens?content-type=application/json;filter=LD')
            .done(function(data) {
                console.log(data);
                processLDPopulationData(data);
            });
    console.log("Ensembl REST query done to retrieve LD populations");
}

function processLDPopulationData(data) {
    $.each(data, function(index, pop) {
        var popName = pop.name;
        var popLabel = popName.split(':')[2] + " - " + pop.description;
        $('#ld-population-selection').append($("<option>").attr("value", popName).html(popLabel));
    });
}

function setState(state) {
    var loading = $('#loading');
    var noresults = $('#noResults');
    var results = $('#results');
    console.log("Search state update...");
    console.log(state);
    switch (state.value) {
        case 0:
            loading.show();
            noresults.hide();
            results.hide();
            break;
        case 1:
            loading.hide();
            noresults.show();
            results.hide();
            break;
        case 2:
            loading.hide();
            noresults.hide();
            results.show();
            break;
        default:
            console.log("Unknown search state; redirecting to search page");
            window.location = "snp";
    }
}<commit_msg>Sort arrays<commit_after>/**
 * Created by Laurent on 22/08/2016.
 */

var SearchState = {
    LOADING: {value: 0},
    NO_RESULTS: {value: 1},
    RESULTS: {value: 2}
};

var EPMC = "http://www.europepmc.org/abstract/MED/";

$(document).ready(function() {
    var searchTerm = $('#query').text();
    console.log("Loading search module!");
    console.log("rsID: "+searchTerm);
    if (searchTerm != '') {
        console.log("Start search for SNP "+searchTerm);
        getSnpData(searchTerm);
    }
    getLDPopulations();
});

function getSnpData(rsId) {
    console.log("Solr research request received for " + rsId);

    setState(SearchState.LOADING);
    $.getJSON('/gwas/api/search/association',
              {
                  'q': "rsId:"+rsId,
                  'group': 'true',
                  'group.by': 'resourcename',
                  'group.limit': 5
              })
              .done(function(data) {
                  console.log(data.response);
                  processSnpData(data.response,rsId);
              });
    console.log("Solr research done for " + rsId);
}

function processSnpData(data,rsId) {
    // Snp summary panel
    getSnpInfo(data);
    // External links panel
    getLinkButtons(rsId);
    // Associations table
    getSnpAssociations(data.docs);
    // Traits table
    getSnpTraits(data.docs);
}

function getSnpInfo(data,rsId) {
    var chr = data.docs[0].chromosomeName[0];
    var pos = data.docs[0].chromosomePosition[0];
    var region = data.docs[0].region[0];
    var func = data.docs[0].context[0];

    var genes_reported = [];
    var genes_reported_url = [];
    var genes_mapped = [];
    var genes_mapped_url = [];
    $.each(data.docs, function (index, doc) {
        // Reported genes
        var reportedGenes = doc.reportedGene;
        $.each(reportedGenes, function (index, gene) {
            if (jQuery.inArray(gene, genes_reported) == -1) {
                genes_reported.push(gene);
                genes_reported_url.push(setQueryUrl(gene));
            }
        });
        // Mapped genes
        var mappedGenes = doc.entrezMappedGenes;
        $.each(mappedGenes, function (index, gene) {
            if (jQuery.inArray(gene, genes_mapped) == -1) {
                genes_mapped.push(gene);
                genes_mapped_url.push(setQueryUrl(gene));
            }
        });
    });
    genes_reported_url.sort();
    genes_mapped_url.sort();

    $("#snpLocation").html("chr"+chr+":"+pos);
    $("#snpRegion").html(region);
    $("#snpClass").html(func);
    $("#snpReportedGenes").html(genes_reported_url.join(', '));
    $("#snpMappedGenes").html(genes_mapped_url.join(', '));
}

function getLinkButtons (rsId) {
    $("#ensembl_button").attr('onclick', "window.location.href='http://www.ensembl.org/Homo_sapiens/Variation/Explore?v="+rsId+"'");
    $("#dbsnp_button").attr('onclick', "window.location.href='http://www.ncbi.nlm.nih.gov/SNP/snp_ref.cgi?rs="+rsId+"'");
}

function getSnpAssociations(data) {
    var asso_count = data.length;

    $("#association_count").html(asso_count);

    if (asso_count == 1) {
        $("#association_label").html("Association");
    }

    $.each(data, function(index,asso) {

        var row = $('
');

        // Risk allele
        var riskAllele = asso.strongestAllele[0];
        riskAllele = setQueryUrl(riskAllele);
        row.append(newCell(riskAllele));

        // Risk allele frequency
        var riskAlleleFreq = asso.riskFrequency;
        row.append(newCell(riskAlleleFreq));

        // p-value
        var pValue = asso.pValueMantissa;
        if (pValue) {
            var pValueExp = " x 10" + asso.pValueExponent + "";
            pValue += pValueExp;
            if (asso.qualifier) {
                if (asso.qualifier[0].match(/\w/)) {
                    pValue += " " + asso.qualifier.join(',');
                }
            }
            row.append(newCell(pValue));
        } else {
            row.append(newCell('-'));
        }

        // OR
        var orValue = asso.orPerCopyNum;
        if (orValue) {
            if (asso.orDescription) {
                orValue += " " + asso.orDescription;
            }
            row.append(newCell(orValue));
        } else {
            row.append(newCell('-'));
        }

        // Beta
        var beta = asso.betaNum;
        if (beta) {
            if (asso.betaUnit) {
                beta += " " + asso.betaUnit;
            }
            if (asso.betaDirection) {
                beta += " " + asso.betaDirection;
            }
            row.append(newCell(beta));
        } else {
            row.append(newCell('-'));
        }

        // CI
        var ci = asso.range;
        if (ci) {
            row.append(newCell(ci));
        } else {
            row.append(newCell('-'));
        }

        // Reported genes
        var genes = [];
        var reportedGenes = asso.reportedGene;
        if (reportedGenes) {
            $.each(reportedGenes, function(index, gene) {
                genes.push(setQueryUrl(gene));
            });
            row.append(newCell(genes.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Reported traits
        var traits = [];
        var reportedTraits = asso.traitName;
        if (reportedTraits) {
            $.each(reportedTraits, function(index, trait) {
                traits.push(setQueryUrl(trait));
            });
            row.append(newCell(traits.join(', ')));
        } else {
           row.append(newCell('-'));
        }

        // Mapped traits
        var mappedTraits = asso.mappedLabel;
        if (mappedTraits) {
            row.append(newCell(mappedTraits.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Study
        var author = asso.author_s;
        var publicationDate = asso.publicationDate;
        var pubDate = publicationDate.split("-");
        var pubmedId = asso.pubmedId;
        var study = setQueryUrl(author, author + " - " + pubDate[0]);
        study += ' PMID:'+pubmedId+' ';
        row.append(newCell(study));

        var studyId = asso.studyId;

        row.append(newCell(showHideStudy(studyId)));

        // Populate the table
        $("#association-table-body").append(row);

        // Add hidden study description/details
        var studyRow = $('
');
        studyRow.addClass("accordion-body hidden-study-row collapse");
        studyRow.attr('id',"study-"+studyId);

        var sudyContent = $("	");
        sudyContent.attr('colspan',11);
        sudyContent.attr('style',"border-top: none");

        var initialSampleDescription = asso.initialSampleDescription;
        var replicateSampleDescription = asso.replicateSampleDescription;
        var ancestralGroups = asso.ancestralGroups;

        var studyTable = $("
").addClass('sample-info sample-info-border');

        // Header //
        studyTable.append($("
").append($("
").append($("").attr("colspan","2").attr("style", "background-color:#E7F7F9").html("Study information"))));

        // Content //
        var studyTableContent = $("
");

        // Initial sample description
        var initialSampleDescriptionRow = $("
");
        initialSampleDescriptionRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Initial sample description"));
        initialSampleDescriptionRow.append($("").attr("style", "text-align:left").html(initialSampleDescription));
        studyTableContent.append(initialSampleDescriptionRow);

        // Replication sample description
        var replicateSampleDescriptionRow = $("
");
        replicateSampleDescriptionRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Replication sample description"));
        replicateSampleDescriptionRow.append($("").attr("style", "text-align:left").html(replicateSampleDescription));
        studyTableContent.append(replicateSampleDescriptionRow);

        // Ancestral groups
        var ancestralGroupsRow = $("
");
        ancestralGroupsRow.append($("").attr("style", "max-width:30%;text-align:right;font-weight:bold").html("Ancestral groups"));
        ancestralGroupsRow.append($("").attr("style", "text-align:left").html(ancestralGroups.join(', ')));
        studyTableContent.append(ancestralGroupsRow);

        studyTable.append(studyTableContent);

        /*var content = '

Study information

' +
        '
' +
        '
' +
        '      Initial sample description	' +
        '      '+initialSampleDescription+'	' +
        '
' +
        '
' +
        '      Replication sample description	' +
        '      '+replicateSampleDescription+'	' +
        '
' +
        '
' +
        '      Ancestral groups	' +
        '      '+ancestralGroups.join(', ')+'	' +
        '
' +
        '
' +
        '
';

        sudyContent.html(content);*/
        sudyContent.html(studyTable);
        studyRow.append(sudyContent);

        $("#association-table-body").append(studyRow);
    });
}

function getSnpTraits(data) {

    // Fetch data //
    var traits = [];
    var mappedtraits = {};
    var mappedtraitsUri = {};
    var synonymtraits = {};
    var studytraits = {};
    $.each(data, function(index,asso) {
        // Trait
        var trait = asso.traitName_s;
        if (jQuery.inArray(trait, traits) == -1) {
            traits.push(trait);
        }

        // Mapped trait(s)
        mappedtraits[trait] = asso.mappedLabel;
        mappedtraitsUri[trait] = asso.mappedUri;

        // Synonym trait(s)
        synonymtraits[trait] = asso.synonym;

        // Study trait(s)
        var author = asso.author_s;
        var publicationDate = asso.publicationDate;
        var pubDate = publicationDate.split("-");
        var pubmedId = asso.pubmedId;
        var study = setQueryUrl(author, author + " - " + pubDate[0]);
        study += setExternalLink(EPMC+pubmedId);
        if (jQuery.inArray(study, studytraits[trait]) == -1) {
            if (!studytraits[trait]) {
                studytraits[trait] = [];
            }
            studytraits[trait].push(study);
        }
    });

    // Display/print data //
    $("#diseasetrait_count").html(traits.length);

    if (traits.length == 1) {
        $("#diseasetrait_label").html("Trait");
    }

    traits.sort();

    $.each(traits, function(index,trait) {
        var row = $('
');

        // Trait
        row.append(newCell(setQueryUrl(trait)));

        // Mapped trait(s)
        if (mappedtraits[trait]) {
            var mappedtrait = [];
            $.each(mappedtraits[trait], function(index, mtrait) {
                var mapped_html = setQueryUrl(mtrait);
                mapped_html += setExternalLink(mappedtraitsUri[trait][index]);
                mappedtrait.push(mapped_html);
            });
            row.append(newCell(mappedtrait.join(',
')));
        } else {
            row.append(newCell('-'));
        }

        // Synonym trait(s)
        if (synonymtraits[trait]) {
            var synonymtrait = [];
            $.each(synonymtraits[trait], function(index, syntrait) {
                synonymtrait.push(setQueryUrl(syntrait));
            });
            row.append(newCell(synonymtrait.join(', ')));
        } else {
            row.append(newCell('-'));
        }

        // Study trait(s)
        if (studytraits[trait]) {
            row.append(newCell(studytraits[trait].join(',
')));
        } else {
            row.append(newCell('-'));
        }
        $("#diseasetrait-table-body").append(row);
    });
}

function setQueryUrl(query, label) {
    if (!label) {
        label = query;
    }
    return ''+label+'';
}

function setExternalLink(url) {
    return '';
}

function newCell(content) {
    return $("	").html(content);
}

function showHideStudy(studyId) {
    //return '<button title="Click to show/hide more study information" class="row-toggle btn btn-default btn-xs accordion-toggle" data-toggle="collapse" data-target=".study-'+studyId+'.hidden-study-row" aria-expanded="false" aria-controls="study:'+studyId+'">' +
    var study_button = $("<button></button>");
    study_button.attr('title', 'Click to show/hide more study information');
    study_button.attr('id', 'button-study-'+studyId);
    study_button.attr('onclick', 'toggleDiv("study-'+studyId+'")');
    study_button.addClass("btn btn-default btn-xs btn-study");
    study_button.html('');

    return study_button;
}

function getLDPopulations() {
    $.getJSON('http://rest.ensembl.org/info/variation/populations/homo_sapiens?content-type=application/json;filter=LD')
            .done(function(data) {
                console.log(data);
                processLDPopulationData(data);
            });
    console.log("Ensembl REST query done to retrieve LD populations");
}

function processLDPopulationData(data) {
    $.each(data, function(index, pop) {
        var popName = pop.name;
        var popLabel = popName.split(':')[2] + " - " + pop.description;
        $('#ld-population-selection').append($("<option>").attr("value", popName).html(popLabel));
    });
}

function setState(state) {
    var loading = $('#loading');
    var noresults = $('#noResults');
    var results = $('#results');
    console.log("Search state update...");
    console.log(state);
    switch (state.value) {
        case 0:
            loading.show();
            noresults.hide();
            results.hide();
            break;
        case 1:
            loading.hide();
            noresults.show();
            results.hide();
            break;
        case 2:
            loading.hide();
            noresults.hide();
            results.show();
            break;
        default:
            console.log("Unknown search state; redirecting to search page");
            window.location = "snp";
    }
}<|endoftext|>


<commit_before>// Load in child_process and chai
var cp = require('child_process'),
    exec = cp.exec,
    async = require('async'),
    chai = require('chai'),
    expect = chai.expect;

// Outline
// Basic tests
var basicTests = {
  'doubleshot': {
    'reads the `test` directory implicitly': true,
    'allows for usage of `mocha` options': true,
    'allows for explicit directory specification': true,
    'allows for explicity file (and pattern) matching alongside mocha options': true
  }
};

var intermediateTests = {
  'doubleshot': {
    'can be run against a folder not labelled `test` and options exclusively': true,
    'can be run against a .yaml file': true,
    'resets timer for long running tests': true,
    'can chain global hooks': true,
    'can chain local hooks': true
  }
};

// Kitchen sink
var kitchenSink = {
  'doubleshot': {
    'warns user when keys are unused': true,
    'warns user when keys are not found': true,
    'warns user when aliases are not found': true,
    'runs batches in isolation': true,
    'throws errors for invalid values': true,
    'runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks': true,
    'throws errors for aliasing within objects to other objects': true,
    'chains `after` hooks': true
  }
};

// Handle stderr throwbacks
function cleanStdErr(stdout, stderr, cb) {
  // If there were any errors, callback with them
  // console.log(stdout);
  if (stderr) {
    var err = new Error(stderr);
    cb(err);
  } else {
  // Otherwise, callback with stdout
    cb(null, stdout);
  }
}

// Assertions for `dot` reporter
function assertDotSuccess(stdout, cb) {
  expect(stdout).to.contain('complete');
  expect(stdout).to.not.contain('pending');
  expect(stdout).to.not.contain('failed');
  cb(null, stdout);
}

// Assertions for `nyan` reporter
function assertNyanSuccess(stdout, cb) {
  expect(stdout).to.contain('( ^ .^)');
  // '( ^ .^)'; // Success face
  // '( - .-)'; // Pending face
  // '( o .o)'; // Fail face
  cb(null, stdout);
}

// Content
// Basic tests
var path = require('path'),
    doubleshot = 'node ' + path.resolve(__dirname, '../bin/doubleshot');
describe('doubleshot', function () {
  it('reads the `test` directory implicitly', function (done) {
    async.waterfall([
      // Run doubleshot implicitly
      function runDblImplicitly (cb) {
        exec(doubleshot, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for usage of `mocha` options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });

  it('allows for explicit directory specification', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' test';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for explicity file (and pattern) matching alongside mocha options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --outline test/doubleshot_outline.js --content test/doubleshot_content.js --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });
});

describe('doubleshot', function () {
  it('warns user when keys are unused', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/unused_keys/content.js --outline test/test_files/unused_keys/outline.json';
    exec(cmd, function handleDblUnusedKeys (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals three');
      expect(stderr).to.contain('not used');

      // Callback
      done();
    });
  });

  it('warns user when keys are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/keys_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals two');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('warns user when aliases are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/aliases_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals too');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('can be run against a folder not labelled `test` and options exclusively', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    var cmd = doubleshot + ' --content spec/content.js --outline spec/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr is empty
      expect(stderr).to.equal('');

      // Go back to original directory
      process.chdir(cwd);

      // Callback
      done();
    });
  });

  it('can be run against a .yaml file', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblYamlTest (cb) {
        var cmd = doubleshot + ' yaml';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('runs batches in isolation', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' isolated_batches';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('does not interfere with shared contexts', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' nested_shared_context';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('throws errors for invalid values', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_values';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Value of objects can only be arrays');

      // Callback
      done();
    });
  });

  it('runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' after_etc_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll');
        expect(stdout).to.contain('beforeAll1');
        expect(stdout).to.contain('global beforeEach');
        expect(stdout).to.contain('beforeEach1');
        expect(stdout).to.contain('afterEach1');
        expect(stdout).to.contain('global afterEach');
        expect(stdout).to.contain('afterAll1');
        expect(stdout).to.contain('global afterAll');
        cb();
      }
    ], done);
  });

  it('resets timer for long running tests', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    this.timeout(10000);
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' slow_expansions';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('can chain global hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_global_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll1\nglobal beforeAll2');
        cb();
      }
    ], done);
  });

  it('can chain local hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_local_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('local afterAll1\nlocal afterAll2');
        cb();
      }
    ], done);
  });

  it('throws errors for aliasing within objects to other objects', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_object_object_alias';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Aliasing within an object to another object is not allowed');

      // Callback
      done();
    });
  });

  it.skip('chains `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_after_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('afterAll1\nafterAll2');
        cb();
      }
    ], done);
  });
});<commit_msg>Enabled new test<commit_after>// Load in child_process and chai
var cp = require('child_process'),
    exec = cp.exec,
    async = require('async'),
    chai = require('chai'),
    expect = chai.expect;

// Outline
// Basic tests
var basicTests = {
  'doubleshot': {
    'reads the `test` directory implicitly': true,
    'allows for usage of `mocha` options': true,
    'allows for explicit directory specification': true,
    'allows for explicity file (and pattern) matching alongside mocha options': true
  }
};

var intermediateTests = {
  'doubleshot': {
    'can be run against a folder not labelled `test` and options exclusively': true,
    'can be run against a .yaml file': true,
    'resets timer for long running tests': true,
    'can chain global hooks': true,
    'can chain local hooks': true
  }
};

// Kitchen sink
var kitchenSink = {
  'doubleshot': {
    'warns user when keys are unused': true,
    'warns user when keys are not found': true,
    'warns user when aliases are not found': true,
    'runs batches in isolation': true,
    'throws errors for invalid values': true,
    'runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks': true,
    'throws errors for aliasing within objects to other objects': true,
    'chains `after` hooks': true
  }
};

// Handle stderr throwbacks
function cleanStdErr(stdout, stderr, cb) {
  // If there were any errors, callback with them
  // console.log(stdout);
  if (stderr) {
    var err = new Error(stderr);
    cb(err);
  } else {
  // Otherwise, callback with stdout
    cb(null, stdout);
  }
}

// Assertions for `dot` reporter
function assertDotSuccess(stdout, cb) {
  expect(stdout).to.contain('complete');
  expect(stdout).to.not.contain('pending');
  expect(stdout).to.not.contain('failed');
  cb(null, stdout);
}

// Assertions for `nyan` reporter
function assertNyanSuccess(stdout, cb) {
  expect(stdout).to.contain('( ^ .^)');
  // '( ^ .^)'; // Success face
  // '( - .-)'; // Pending face
  // '( o .o)'; // Fail face
  cb(null, stdout);
}

// Content
// Basic tests
var path = require('path'),
    doubleshot = 'node ' + path.resolve(__dirname, '../bin/doubleshot');
describe('doubleshot', function () {
  it('reads the `test` directory implicitly', function (done) {
    async.waterfall([
      // Run doubleshot implicitly
      function runDblImplicitly (cb) {
        exec(doubleshot, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for usage of `mocha` options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });

  it('allows for explicit directory specification', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' test';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('allows for explicity file (and pattern) matching alongside mocha options', function (done) {
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblMochaOptions (cb) {
        var cmd = doubleshot + ' --outline test/doubleshot_outline.js --content test/doubleshot_content.js --reporter nyan';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertNyanSuccess
    ], done);
  });
});

describe('doubleshot', function () {
  it('warns user when keys are unused', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/unused_keys/content.js --outline test/test_files/unused_keys/outline.json';
    exec(cmd, function handleDblUnusedKeys (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals three');
      expect(stderr).to.contain('not used');

      // Callback
      done();
    });
  });

  it('warns user when keys are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/keys_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals two');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('warns user when aliases are not found', function (done) {
    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' --content test/test_files/aliases_not_found/content.js --outline test/test_files/keys_not_found/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr contains info about failing items
      expect(stderr).to.contain('equals too');
      expect(stderr).to.match(/not found/);

      // Callback
      done();
    });
  });

  it('can be run against a folder not labelled `test` and options exclusively', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    var cmd = doubleshot + ' --content spec/content.js --outline spec/outline.json';
    exec(cmd, function handleDblKeysNotFound (err, stdout, stderr) {
      // If there is an error, callback
      if (err) { return done(err); }

      // Assert stderr is empty
      expect(stderr).to.equal('');

      // Go back to original directory
      process.chdir(cwd);

      // Callback
      done();
    });
  });

  it('can be run against a .yaml file', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDblYamlTest (cb) {
        var cmd = doubleshot + ' yaml';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('runs batches in isolation', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' isolated_batches';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('does not interfere with shared contexts', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' nested_shared_context';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('throws errors for invalid values', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_values';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Value of objects can only be arrays');

      // Callback
      done();
    });
  });

  it('runs global and local `before`, `beforeEach`, `afterEach` and `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' after_etc_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll');
        expect(stdout).to.contain('beforeAll1');
        expect(stdout).to.contain('global beforeEach');
        expect(stdout).to.contain('beforeEach1');
        expect(stdout).to.contain('afterEach1');
        expect(stdout).to.contain('global afterEach');
        expect(stdout).to.contain('afterAll1');
        expect(stdout).to.contain('global afterAll');
        cb();
      }
    ], done);
  });

  it('resets timer for long running tests', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    this.timeout(10000);
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' slow_expansions';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess
    ], done);
  });

  it('can chain global hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_global_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('global beforeAll1\nglobal beforeAll2');
        cb();
      }
    ], done);
  });

  it('can chain local hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' complex_local_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('local afterAll1\nlocal afterAll2');
        cb();
      }
    ], done);
  });

  it('throws errors for aliasing within objects to other objects', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against unused keys files
    var cmd = doubleshot + ' invalid_object_object_alias';
    exec(cmd, function handleDblInvalidValues (err, stdout, stderr) {
      // Assert stderr contains info about failing items
      expect(stderr).to.contain('Aliasing within an object to another object is not allowed');

      // Callback
      done();
    });
  });

  it('chains `after` hooks', function (done) {
    // Move to the current directory for execution
    var cwd = process.cwd();
    process.chdir(__dirname + '/test_files');

    // Run doubleshot against spec folder
    async.waterfall([
      // Run doubleshot with mocha options
      function runDbIsolatedTest (cb) {
        var cmd = doubleshot + ' chained_after_hooks';
        exec(cmd, cb);
      },
      // Clean up and errors from stderr
      cleanStdErr,
      // Assert the test suite ran successfully
      assertDotSuccess,
      function assertAllHooksRan (stdout, cb) {
        expect(stdout).to.contain('afterAll1\nafterAll2');
        cb();
      }
    ], done);
  });
});<|endoftext|>


<commit_before>angular.module('dd.ui.dd-datetimepicker', ['ui.bootstrap'])
    .directive('ddDatetimepicker', ['$timeout', 'dateFilter', function ($timeout, dateFilter) {
        return {
            restrict: 'EA',
            require: 'ngModel',
            templateUrl: function (element, attrs) {
                return attrs.templateUrl || 'template/dd-datetimepicker/dd-datetimepicker.html';
            },
            scope: {
                ngModel: '=',
                minuteStep: '=?',
                showMeridian: '=?',
                ngDisabled: '=?',
                ngRequired: '=?',
                dateDisabled: '&',
                dateFormat: '@',
                showDayName: '=?',
                allowForwardDateAdjustment: '=?'
            },
            link: function (scope, element, attrs, ctrl) {

                var timeChanged = false;
                var timepickerElement = element.find('.timepicker-container input');
                var canExecuteNgModelChanges = true;

                scope.time = null;
                scope.date = null;

                init();

                scope.$watch('ngModel', function (value) {
                    if (canExecuteNgModelChanges){
                        init();
                    }
                });

                scope.$watch('date', function (newTime, oldTime) {
                    updateMainModel();
                    setValidity();
                });

                scope.$watch('time', function (newTime, oldTime) {
                    timeChanged = true;
                    updateMainModel();
                    setValidity();
                });

                timepickerElement.on('blur', function () {
                    jumpToNextDayIfPossible();
                });

                function updateMainModel() {
                    canExecuteNgModelChanges = false;
                    ensureDateTypes();

                    var model = angular.copy(scope.date);
                    if (model) {
                        if (scope.time) {
                            model.setHours(scope.time.getHours(), scope.time.getMinutes(), 0, 0);
                        } else {
                            model.setHours(0, 0, 0, 0);
                        }
                    }
                    ctrl.$setViewValue(model);
                    ctrl.$render();

                    $timeout(function () {
                        canExecuteNgModelChanges = true;
                    }, 500);
                }

                function init() {
                    ctrl.$modelValue = angular.copy(scope.ngModel);
                    scope.time = angular.copy(ctrl.$modelValue);
                    scope.date = angular.copy(ctrl.$modelValue);
                }

                function ensureDateTypes() {
                    if (scope.date && !(scope.date instanceof Date)) {
                        scope.date = new Date(scope.date);
                    }
                    if (scope.time && !(scope.time instanceof Date)) {
                        scope.time = new Date(scope.time);
                    }
                }

                function setValidity() {
                    if (scope.ngRequired && (!scope.time || !scope.date)) {
                        ctrl.$setValidity('required', false);
                    } else {
                        ctrl.$setValidity('required', true);
                    }
                }

                function jumpToNextDayIfPossible() {
                    if (!scope.date || !scope.time) {
                        return;
                    }

                    var currentDate = scope.date.getDate();
                    var canAddDay = canAddDayIfUserDecreaseTime();

                    if (canAddDay) {
                        scope.date.setDate(currentDate + 1);
                        updateMainModel();
                        syncDatepickerModel();
                        notifyWithDatepickerChange();
                        _addDayExecuted = canAddDay;
                    }
                }

                var _addDayExecuted = false;
                function canAddDayIfUserDecreaseTime() {
                    return scope.allowForwardDateAdjustment && !_addDayExecuted && timeChanged && ctrl.$modelValue.getTime() < new Date().getTime();
                }

                function notifyWithDatepickerChange() {
                    var datepickerElement = element.find('.datepicker-container .display-input');
                    datepickerElement.css('background-color', 'rgba(0, 128, 0, 0.15)');
                    $timeout(function () {
                        datepickerElement.css('background-color', '');
                    }, 500);
                }

                function syncDatepickerModel(element) {
                    scope.$broadcast('ddDatepicker:sync', { model: ctrl.$modelValue });
                }

            }
        };
    }]);<commit_msg>fix(datetimepicker): init values from ngWatch<commit_after>angular.module('dd.ui.dd-datetimepicker', ['ui.bootstrap'])
    .directive('ddDatetimepicker', ['$timeout', 'dateFilter', function ($timeout, dateFilter) {
        return {
            restrict: 'EA',
            require: 'ngModel',
            templateUrl: function (element, attrs) {
                return attrs.templateUrl || 'template/dd-datetimepicker/dd-datetimepicker.html';
            },
            scope: {
                ngModel: '=',
                minuteStep: '=?',
                showMeridian: '=?',
                ngDisabled: '=?',
                ngRequired: '=?',
                dateDisabled: '&',
                dateFormat: '@',
                showDayName: '=?',
                allowForwardDateAdjustment: '=?'
            },
            link: function (scope, element, attrs, ctrl) {

                var timeChanged = false;
                var timepickerElement = element.find('.timepicker-container input');
                var canExecuteNgModelChanges = true;

                scope.time = null;
                scope.date = null;

                scope.$watch('ngModel', function (value) {
                    if (canExecuteNgModelChanges){
                        init();
                    }
                });

                scope.$watch('date', function (newTime, oldTime) {
                    updateMainModel();
                    setValidity();
                });

                scope.$watch('time', function (newTime, oldTime) {
                    timeChanged = true;
                    updateMainModel();
                    setValidity();
                });

                timepickerElement.on('blur', function () {
                    jumpToNextDayIfPossible();
                });

                function updateMainModel() {
                    canExecuteNgModelChanges = false;
                    ensureDateTypes();

                    var model = angular.copy(scope.date);
                    if (model && scope.time) {
                        model.setHours(scope.time.getHours(), scope.time.getMinutes(), 0, 0);
                    }

                    ctrl.$setViewValue(model);
                    ctrl.$render();

                    $timeout(function () {
                        canExecuteNgModelChanges = true;
                    }, 100);
                }

                function init() {
                    ctrl.$modelValue = angular.copy(scope.ngModel);
                    scope.time = angular.copy(ctrl.$modelValue);
                    scope.date = angular.copy(ctrl.$modelValue);
                }

                function ensureDateTypes() {
                    if (scope.date && !(scope.date instanceof Date)) {
                        scope.date = new Date(scope.date);
                    }
                    if (scope.time && !(scope.time instanceof Date)) {
                        scope.time = new Date(scope.time);
                    }
                }

                function setValidity() {
                    if (scope.ngRequired && (!scope.time || !scope.date)) {
                        ctrl.$setValidity('required', false);
                    } else {
                        ctrl.$setValidity('required', true);
                    }
                }

                function jumpToNextDayIfPossible() {
                    if (!scope.date || !scope.time) {
                        return;
                    }

                    var currentDate = scope.date.getDate();
                    var canAddDay = canAddDayIfUserDecreaseTime();

                    if (canAddDay) {
                        scope.date.setDate(currentDate + 1);
                        updateMainModel();
                        syncDatepickerModel();
                        notifyWithDatepickerChange();
                        _addDayExecuted = canAddDay;
                    }
                }

                var _addDayExecuted = false;
                function canAddDayIfUserDecreaseTime() {
                    return scope.allowForwardDateAdjustment && !_addDayExecuted && timeChanged && ctrl.$modelValue.getTime() < new Date().getTime();
                }

                function notifyWithDatepickerChange() {
                    var datepickerElement = element.find('.datepicker-container .display-input');
                    datepickerElement.css('background-color', 'rgba(0, 128, 0, 0.15)');
                    $timeout(function () {
                        datepickerElement.css('background-color', '');
                    }, 500);
                }

                function syncDatepickerModel(element) {
                    scope.$broadcast('ddDatepicker:sync', { model: ctrl.$modelValue });
                }

            }
        };
    }]);<|endoftext|>


<commit_before>/*##################################################|*/
/* #CMS# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * Sideframe
	 * Controls a cms specific sideframe
	 */
	CMS.Sideframe = new CMS.Class({

		implement: [CMS.API.Helpers],

		options: {
			'onClose': false,
			'sideframeDuration': 300,
			'sideframeWidth': 320,
			'urls': {
				'css_sideframe': 'cms/css/cms.toolbar.sideframe.css'
			}
		},

		initialize: function (options) {
			this.options = $.extend(true, {}, this.options, options);
			this.config = CMS.config;
			this.settings = CMS.settings;

			// elements
			this.sideframe = $('.cms_sideframe');
			this.body = $('html');

			// states
			this.click = (document.ontouchstart !== null) ? 'click.cms' : 'touchend.cms';
			this.enforceReload = false;

			// if the modal is initialized the first time, set the events
			if(!this.sideframe.data('ready')) this._events();

			// ready sideframe
			this.sideframe.data('ready', true);
		},

		// initial methods
		_events: function () {
			var that = this;

			// attach close event
			this.sideframe.find('.cms_sideframe-close').bind(this.click, function () {
				that.close(true);
			});

			// attach hide event
			this.sideframe.find('.cms_sideframe-hide').bind(this.click, function () {
				if($(this).hasClass('cms_sideframe-hidden')) {
					that.settings.sideframe.hidden = false;
					that._show(that.settings.sideframe.position || that.options.sideframeWidth, true);
				} else {
					that.settings.sideframe.hidden = true;
					that._hide();
				}
				that.settings = that.setSettings(that.settings);
			});

			// attach maximize event
			this.sideframe.find('.cms_sideframe-maximize').bind(this.click, function () {
				if($(this).hasClass('cms_sideframe-minimize')) {
					that.settings.sideframe.maximized = false;
					that._minimize();
				} else {
					that.settings.sideframe.maximized = true;
					that.settings.sideframe.hidden = false;
					that._maximize();
				}
				that.settings = that.setSettings(that.settings);
			});

			this.sideframe.find('.cms_sideframe-resize').bind('mousedown', function (e) {
				e.preventDefault();
				that._startResize();
			});

			// stopper events
			$(document).bind('mouseup.cms', function () {
				that._stopResize();
			});
		},

		// public methods
		open: function (url, animate) {
			// prepare iframe
			var that = this;
			var language = 'language=' + CMS.config.request.language;
			var page_id = 'page_id=' + CMS.config.request.page_id;
			var holder = this.sideframe.find('.cms_sideframe-frame');

			// push required params if defined
			var params = [];
			if(CMS.config.request.language) params.push(language);
			if(CMS.config.request.page_id) params.push(page_id);

			var iframe = $('<iframe src="'+this._url(url, params)+'" class="" frameborder="0" />');
				iframe.hide();
			var width = this.settings.sideframe.position || this.options.sideframeWidth;

			// attach load event to iframe
			iframe.bind('load', function () {
				// after iframe is loaded append css
				iframe.contents().find('head').append($('<link rel="stylesheet" type="text/css" href="' + that.config.urls.static + that.options.urls.css_sideframe + '" />'));
				// remove loader
				that.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');
				// than show
				iframe.show();
				// if a message is triggerd, refresh
				var messages = iframe.contents().find('.messagelist li');
				if(messages.length || that.enforceReload) {
					that.enforceReload = true;
				} else {
					that.enforceReload = false;
				}

				// add debug infos
				if(that.config.debug) iframe.contents().find('body').addClass('cms_debug');

				// save url in settings
				that.settings.sideframe.url = iframe.get(0).contentWindow.location.href;
				that.settings = that.setSettings(that.settings);

				// bind extra events
				iframe.contents().find('body').bind(that.click, function () {
					$(document).trigger(that.click);
				});
			});

			// cancel animation if sideframe is already shown
			if(this.sideframe.is(':visible')) {
				// sideframe is already open
				insertHolder(iframe);
				// reanimate the frame
				if(parseInt(this.sideframe.css('width')) <= width) this._show(width, animate);
			} else {
				// load iframe after frame animation is done
				setTimeout(function () {
					insertHolder(iframe);
				}, this.options.sideframeDuration);
				// display the frame
				this._show(width, animate);
			}

			function insertHolder(iframe) {
				// show iframe after animation
				that.sideframe.find('.cms_sideframe-frame').addClass('cms_loader');
				holder.html(iframe);
			}
		},

		close: function () {
			this._hide(true);

			// remove url in settings
			this.settings.sideframe = {
				'url': null,
				'hidden': false,
				'maximized': false,
				'width': this.options.sideframeWidth
			};

			// resets
			this.sideframe.find('.cms_sideframe-maximize').removeClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').show();

			// update settings
			this.settings = this.setSettings(this.settings);

			// handle refresh option
			if(this.options.onClose) this.reloadBrowser(this.options.onClose, false, true);
		},

		// private methods
		_show: function (width, animate) {
			// add class
			this.sideframe.find('.cms_sideframe-hide').removeClass('cms_sideframe-hidden');

			// make sure the close / hide / maximize controls appear, regardless of hidden / maximized state
			this.sideframe.show();

			// check if sideframe should be hidden
			if(this.settings.sideframe.hidden) this._hide();

			// check if sideframe should be maximized
			if(this.settings.sideframe.maximized) this._maximize();

			// otherwise do normal behaviour
			if(!this.settings.sideframe.hidden && !this.settings.sideframe.maximized) {
				if(animate) {
					this.sideframe.animate({ 'width': width }, this.options.sideframeDuration);
					this.body.animate({ 'margin-left': width }, this.options.sideframeDuration);
				} else {
					this.sideframe.animate({ 'width': width }, 0);
					this.body.animate({ 'margin-left': width }, 0);
					// reset width if larger than available space
					if(width >= $(window).width()) {
						this.sideframe.animate({ 'width': $(window).width() - 20 }, 0);
						this.body.animate({ 'margin-left': $(window).width() - 20 }, 0);
					}
				}
				this.sideframe.find('.cms_sideframe-btn').css('right', -20);
			}

			// lock toolbar, set timeout to make sure CMS.API is ready
			setTimeout(function () {
				CMS.API.Toolbar._lock(true);
				CMS.API.Toolbar._showToolbar(true);
			}, 100);
		},

		_hide: function (close) {
			// add class
			this.sideframe.find('.cms_sideframe-hide').addClass('cms_sideframe-hidden');

			var duration = this.options.sideframeDuration;
			// remove the iframe
			if(close && this.sideframe.width() <= 0) duration = 0;
			if(close) this.sideframe.find('iframe').remove();
			this.sideframe.animate({ 'width': 0 }, duration, function () {
				if(close) $(this).hide();
			});
			this.body.animate({ 'margin-left': 0 }, duration);
			this.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');

			// should we reload
			if(this.enforceReload) this.reloadBrowser();

			// lock toolbar, set timeout to make sure CMS.API is ready
			setTimeout(function () {
				CMS.API.Toolbar._lock(false);
			}, 100);
		},

		_minimize: function () {
			this.sideframe.find('.cms_sideframe-maximize').removeClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').show();

			// hide scrollbar
			this.preventScroll(false);

			// reset to first state
			this._show(this.settings.sideframe.position || this.options.sideframeWidth, true);

			// remove event
			$(window).unbind('resize.cms.sideframe');
		},

		_maximize: function () {
			var that = this;

			this.sideframe.find('.cms_sideframe-maximize').addClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').hide();

			// reset scrollbar
			this.preventScroll(true);

			this.sideframe.find('.cms_sideframe-hide').removeClass('cms_sideframe-hidden').hide();
			// do custom animation
			this.sideframe.animate({ 'width': $(window).width() }, 0);
			this.body.animate({ 'margin-left': 0 }, 0);
			// invert icon position
			this.sideframe.find('.cms_sideframe-btn').css('right', -2);
			// attach resize event
			$(window).bind('resize.cms.sideframe', function () {
				that.sideframe.css('width', $(window).width());
			});
		},

		_startResize: function () {
			var that = this;
			var outerOffset = 20;
			var timer = function () {};
			// this prevents the iframe from being focusable
			this.sideframe.find('.cms_sideframe-shim').css('z-index', 20);

			$(document).bind('mousemove.cms', function (e) {
				if(e.clientX <= 320) e.clientX = 320;
				if(e.clientX >= $(window).width() - outerOffset) e.clientX = $(window).width() - outerOffset;

				that.sideframe.css('width', e.clientX);
				that.body.css('margin-left', e.clientX);

				// update settings
				that.settings.sideframe.position = e.clientX;

				// save position
				clearTimeout(timer);
				timer = setTimeout(function () {
					that.settings = that.setSettings(that.settings);
				}, 500);
			});
		},

		_stopResize: function () {
			this.sideframe.find('.cms_sideframe-shim').css('z-index', 1);

			$(document).unbind('mousemove.cms');
		},

		_url: function (url, params) {
			var arr = [];
			var keys = [];
			var values = [];
			var tmp = '';
			var urlArray = [];
			var urlParams = [];
			var origin = url;

			// return url if there is no param
			if(!(url.split('?').length <= 1 || window.JSON === undefined)) {
				// setup local vars
				urlArray = url.split('?');
				urlParams = urlArray[1].split('&');
				origin = urlArray[0];
			}

			// loop through the available params
			$.each(urlParams, function (index, param) {
				arr.push({ 'param': param.split('=')[0], 'value': param.split('=')[1] });
			});
			// loop through the new params
			$.each(params, function (index, param) {
				arr.push({ 'param': param.split('=')[0], 'value': param.split('=')[1] });
			});

			// merge manually because jquery...
			$.each(arr, function (index, item) {
				var i = $.inArray(item.param, keys);

				if(i === -1) {
					keys.push(item.param);
					values.push(item.value);
				} else {
					values[i] = item.value;
				}
			});

			// merge new url
			$.each(keys, function (index, key) {
				tmp += '&' + key + '=' + values[index];
			});
			tmp = tmp.replace('&', '?');
			url = origin + tmp;

			return url;
		}

	});

});
})(CMS.$);
<commit_msg>just disable it for reference<commit_after>/*##################################################|*/
/* #CMS# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * Sideframe
	 * Controls a cms specific sideframe
	 */
	CMS.Sideframe = new CMS.Class({

		implement: [CMS.API.Helpers],

		options: {
			'onClose': false,
			'sideframeDuration': 300,
			'sideframeWidth': 320,
			'urls': {
				'css_sideframe': 'cms/css/cms.toolbar.sideframe.css'
			}
		},

		initialize: function (options) {
			this.options = $.extend(true, {}, this.options, options);
			this.config = CMS.config;
			this.settings = CMS.settings;

			// elements
			this.sideframe = $('.cms_sideframe');
			this.body = $('html');

			// states
			this.click = (document.ontouchstart !== null) ? 'click.cms' : 'touchend.cms';
			this.enforceReload = false;

			// if the modal is initialized the first time, set the events
			if(!this.sideframe.data('ready')) this._events();

			// ready sideframe
			this.sideframe.data('ready', true);
		},

		// initial methods
		_events: function () {
			var that = this;

			// attach close event
			this.sideframe.find('.cms_sideframe-close').bind(this.click, function () {
				that.close(true);
			});

			// attach hide event
			this.sideframe.find('.cms_sideframe-hide').bind(this.click, function () {
				if($(this).hasClass('cms_sideframe-hidden')) {
					that.settings.sideframe.hidden = false;
					that._show(that.settings.sideframe.position || that.options.sideframeWidth, true);
				} else {
					that.settings.sideframe.hidden = true;
					that._hide();
				}
				that.settings = that.setSettings(that.settings);
			});

			// attach maximize event
			this.sideframe.find('.cms_sideframe-maximize').bind(this.click, function () {
				if($(this).hasClass('cms_sideframe-minimize')) {
					that.settings.sideframe.maximized = false;
					that._minimize();
				} else {
					that.settings.sideframe.maximized = true;
					that.settings.sideframe.hidden = false;
					that._maximize();
				}
				that.settings = that.setSettings(that.settings);
			});

			this.sideframe.find('.cms_sideframe-resize').bind('mousedown', function (e) {
				e.preventDefault();
				that._startResize();
			});

			// stopper events
			$(document).bind('mouseup.cms', function () {
				that._stopResize();
			});
		},

		// public methods
		open: function (url, animate) {
			// prepare iframe
			var that = this;
			var language = 'language=' + CMS.config.request.language;
			var page_id = 'page_id=' + CMS.config.request.page_id;
			var holder = this.sideframe.find('.cms_sideframe-frame');
			// var initialized = false;

			// push required params if defined
			var params = [];
			if(CMS.config.request.language) params.push(language);
			if(CMS.config.request.page_id) params.push(page_id);

			var iframe = $('<iframe src="'+this._url(url, params)+'" class="" frameborder="0" />');
				iframe.hide();
			var width = this.settings.sideframe.position || this.options.sideframeWidth;

			// attach load event to iframe
			iframe.bind('load', function () {
				// after iframe is loaded append css
				iframe.contents().find('head').append($('<link rel="stylesheet" type="text/css" href="' + that.config.urls.static + that.options.urls.css_sideframe + '" />'));
				// remove loader
				that.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');
				// than show
				iframe.show();
				// if a message is triggerd, refresh
				var messages = iframe.contents().find('.messagelist li');
				if(messages.length || that.enforceReload) {
					that.enforceReload = true;
				} else {
					that.enforceReload = false;
				}

				// add debug infos
				if(that.config.debug) iframe.contents().find('body').addClass('cms_debug');

				// save url in settings
				that.settings.sideframe.url = iframe.get(0).contentWindow.location.href;
				that.settings = that.setSettings(that.settings);

				// bind extra events
				iframe.contents().find('body').bind(that.click, function () {
					$(document).trigger(that.click);
				});

				// attach reload event
				// if(initialized) that.reloadBrowser(false, false, true);
				// initialized = true;
			});

			// cancel animation if sideframe is already shown
			if(this.sideframe.is(':visible')) {
				// sideframe is already open
				insertHolder(iframe);
				// reanimate the frame
				if(parseInt(this.sideframe.css('width')) <= width) this._show(width, animate);
			} else {
				// load iframe after frame animation is done
				setTimeout(function () {
					insertHolder(iframe);
				}, this.options.sideframeDuration);
				// display the frame
				this._show(width, animate);
			}

			function insertHolder(iframe) {
				// show iframe after animation
				that.sideframe.find('.cms_sideframe-frame').addClass('cms_loader');
				holder.html(iframe);
			}
		},

		close: function () {
			this._hide(true);

			// remove url in settings
			this.settings.sideframe = {
				'url': null,
				'hidden': false,
				'maximized': false,
				'width': this.options.sideframeWidth
			};

			// resets
			this.sideframe.find('.cms_sideframe-maximize').removeClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').show();

			// update settings
			this.settings = this.setSettings(this.settings);

			// handle refresh option
			if(this.options.onClose) this.reloadBrowser(this.options.onClose, false, true);
		},

		// private methods
		_show: function (width, animate) {
			// add class
			this.sideframe.find('.cms_sideframe-hide').removeClass('cms_sideframe-hidden');

			// make sure the close / hide / maximize controls appear, regardless of hidden / maximized state
			this.sideframe.show();

			// check if sideframe should be hidden
			if(this.settings.sideframe.hidden) this._hide();

			// check if sideframe should be maximized
			if(this.settings.sideframe.maximized) this._maximize();

			// otherwise do normal behaviour
			if(!this.settings.sideframe.hidden && !this.settings.sideframe.maximized) {
				if(animate) {
					this.sideframe.animate({ 'width': width }, this.options.sideframeDuration);
					this.body.animate({ 'margin-left': width }, this.options.sideframeDuration);
				} else {
					this.sideframe.animate({ 'width': width }, 0);
					this.body.animate({ 'margin-left': width }, 0);
					// reset width if larger than available space
					if(width >= $(window).width()) {
						this.sideframe.animate({ 'width': $(window).width() - 20 }, 0);
						this.body.animate({ 'margin-left': $(window).width() - 20 }, 0);
					}
				}
				this.sideframe.find('.cms_sideframe-btn').css('right', -20);
			}

			// lock toolbar, set timeout to make sure CMS.API is ready
			setTimeout(function () {
				CMS.API.Toolbar._lock(true);
				CMS.API.Toolbar._showToolbar(true);
			}, 100);
		},

		_hide: function (close) {
			// add class
			this.sideframe.find('.cms_sideframe-hide').addClass('cms_sideframe-hidden');

			var duration = this.options.sideframeDuration;
			// remove the iframe
			if(close && this.sideframe.width() <= 0) duration = 0;
			if(close) this.sideframe.find('iframe').remove();
			this.sideframe.animate({ 'width': 0 }, duration, function () {
				if(close) $(this).hide();
			});
			this.body.animate({ 'margin-left': 0 }, duration);
			this.sideframe.find('.cms_sideframe-frame').removeClass('cms_loader');

			// should we reload
			if(this.enforceReload) this.reloadBrowser();

			// lock toolbar, set timeout to make sure CMS.API is ready
			setTimeout(function () {
				CMS.API.Toolbar._lock(false);
			}, 100);
		},

		_minimize: function () {
			this.sideframe.find('.cms_sideframe-maximize').removeClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').show();

			// hide scrollbar
			this.preventScroll(false);

			// reset to first state
			this._show(this.settings.sideframe.position || this.options.sideframeWidth, true);

			// remove event
			$(window).unbind('resize.cms.sideframe');
		},

		_maximize: function () {
			var that = this;

			this.sideframe.find('.cms_sideframe-maximize').addClass('cms_sideframe-minimize');
			this.sideframe.find('.cms_sideframe-hide').hide();

			// reset scrollbar
			this.preventScroll(true);

			this.sideframe.find('.cms_sideframe-hide').removeClass('cms_sideframe-hidden').hide();
			// do custom animation
			this.sideframe.animate({ 'width': $(window).width() }, 0);
			this.body.animate({ 'margin-left': 0 }, 0);
			// invert icon position
			this.sideframe.find('.cms_sideframe-btn').css('right', -2);
			// attach resize event
			$(window).bind('resize.cms.sideframe', function () {
				that.sideframe.css('width', $(window).width());
			});
		},

		_startResize: function () {
			var that = this;
			var outerOffset = 20;
			var timer = function () {};
			// this prevents the iframe from being focusable
			this.sideframe.find('.cms_sideframe-shim').css('z-index', 20);

			$(document).bind('mousemove.cms', function (e) {
				if(e.clientX <= 320) e.clientX = 320;
				if(e.clientX >= $(window).width() - outerOffset) e.clientX = $(window).width() - outerOffset;

				that.sideframe.css('width', e.clientX);
				that.body.css('margin-left', e.clientX);

				// update settings
				that.settings.sideframe.position = e.clientX;

				// save position
				clearTimeout(timer);
				timer = setTimeout(function () {
					that.settings = that.setSettings(that.settings);
				}, 500);
			});
		},

		_stopResize: function () {
			this.sideframe.find('.cms_sideframe-shim').css('z-index', 1);

			$(document).unbind('mousemove.cms');
		},

		_url: function (url, params) {
			var arr = [];
			var keys = [];
			var values = [];
			var tmp = '';
			var urlArray = [];
			var urlParams = [];
			var origin = url;

			// return url if there is no param
			if(!(url.split('?').length <= 1 || window.JSON === undefined)) {
				// setup local vars
				urlArray = url.split('?');
				urlParams = urlArray[1].split('&');
				origin = urlArray[0];
			}

			// loop through the available params
			$.each(urlParams, function (index, param) {
				arr.push({ 'param': param.split('=')[0], 'value': param.split('=')[1] });
			});
			// loop through the new params
			$.each(params, function (index, param) {
				arr.push({ 'param': param.split('=')[0], 'value': param.split('=')[1] });
			});

			// merge manually because jquery...
			$.each(arr, function (index, item) {
				var i = $.inArray(item.param, keys);

				if(i === -1) {
					keys.push(item.param);
					values.push(item.value);
				} else {
					values[i] = item.value;
				}
			});

			// merge new url
			$.each(keys, function (index, key) {
				tmp += '&' + key + '=' + values[index];
			});
			tmp = tmp.replace('&', '?');
			url = origin + tmp;

			return url;
		}

	});

});
})(CMS.$);
<|endoftext|>


<commit_before>/**
 * @fileOverview Plaintext File I/O Library for Firefox 3.5 or later
 * @author       ClearCode Inc.
 * @version      3
 *
 * @license
 *   The MIT License, Copyright (c) 2010 ClearCode Inc.
 * @url https://github.com/clear-code/js-codemodule-text-io
 */

if (typeof window == 'undefined' ||
	(window && typeof window.constructor == 'function'))
	this.EXPORTED_SYMBOLS = ['textIO'];

// var namespace;
if (typeof namespace == 'undefined') {
	// If namespace.jsm is available, export symbols to the shared namespace.
	// See: https://github.com/piroor/fxaddonlibs/blob/master/namespace.jsm
	try {
		let ns = {};
		Components.utils.import('resource://my-modules/namespace.jsm', ns);
		namespace = ns.getNamespaceFor('clear-code.com');
	}
	catch(e) {
		namespace = (typeof window != 'undefined' ? window : null ) || {};
	}
}

var textIO;
(function() {
	const currentRevision = 3;

	var loadedRevision = 'textIO' in namespace ?
			namespace.textIO.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		textIO = namespace.textIO;
		return;
	}

	const Cc = Components.classes;
	const Ci = Components.interfaces;

	const IOService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);

	/**
	 * @class
	 *   The plaintext I/O service, provides features to read/write
	 *   plaintext files.
	 *
	 * @example
	 *   Components.utils.import('resource://my-modules/textIO.jsm');
	 *   var text = textIO.readFrom(nsIFile, 'UTF-8');
	 *   textIO.writeTo(text, nsIFile, 'Shift_JIS');
	 */
	textIO = {
		/** @private */
		revision : currentRevision,

		/**
		 * Reads the contents of the given text file, and returns the contents
		 * as a string.
		 *
		 * @param {(nsIFile|nsIURI)} aFileOrURI
		 *   The pointer to the plain text file.
		 * @param {string=} aEncoding (optional)
		 *   The encoding of the contents of the file. If no encoding is given,
		 *   this returns the contents of the file as is.
		 *
		 * @returns {string}
		 *   The contents of the given file. If an encoding is given, a decoded
		 *   string will be returned. Otherwise this returns a raw bytes array
		 *   as a string.
		 */
		readFrom : function(aFileOrURI, aEncoding)
		{
			var stream;
			try {
				aFileOrURI = aFileOrURI.QueryInterface(Ci.nsIURI);
				var channel = IOService.newChannelFromURI(aFileOrURI);
				stream = channel.open();
			}
			catch(e) {
				aFileOrURI = aFileOrURI.QueryInterface(Ci.nsILocalFile)
				stream = Cc['@mozilla.org/network/file-input-stream;1']
							.createInstance(Ci.nsIFileInputStream);
				try {
					stream.init(aFileOrURI, 1, 0, false); // open as "read only"
				}
				catch(ex) {
					return null;
				}
			}

			var fileContents = null;
			try {
				if (aEncoding) {
					var converterStream = Cc['@mozilla.org/intl/converter-input-stream;1']
							.createInstance(Ci.nsIConverterInputStream);
					var buffer = stream.available();
					converterStream.init(stream, aEncoding, buffer,
						converterStream.DEFAULT_REPLACEMENT_CHARACTER);
					var out = { value : null };
					converterStream.readString(stream.available(), out);
					converterStream.close();
					fileContents = out.value;
				}
				else {
					var scriptableStream = Cc['@mozilla.org/scriptableinputstream;1']
							.createInstance(Ci.nsIScriptableInputStream);
					scriptableStream.init(stream);
					fileContents = scriptableStream.read(scriptableStream.available());
					scriptableStream.close();
				}
			}
			finally {
				stream.close();
			}

			return fileContents;
		},

		/**
		 * Outputs the given string to a file, as a plain text file.
		 *
		 * @param {string} aContents
		 *   The string you want to output. It should be a Unicode string (UCS2).
		 * @param {nsIFile} aFile
		 *   The pointer to the plain text file. If the file exists, it will be
		 *   overwritten. If there are some missing directories, then they are
		 *   automatically created.
		 * @param {string=} aEncoding (optional)
		 *   The encoding of the contents of the file. This encodes the given
		 *   string by the encoding before output. If no encoding is given,
		 *   this outputs the given string to the file as is.
		 *
		 * @returns {nsIFile}
		 *   The given file itself.
		 */
		writeTo : function(aContent, aFile, aEncoding)
		{
			// create directories
			(function(aDir) {
				try {
					if (aDir.parent) arguments.callee(aDir.parent);
					if (aDir.exists()) return;
					aDir.create(aDir.DIRECTORY_TYPE, 0755);
				}
				catch(e) {
				}
			})(aFile.parent);

			if (aFile.exists()) aFile.remove(true);
			aFile.create(aFile.NORMAL_FILE_TYPE, 0666);

			var stream = Cc['@mozilla.org/network/file-output-stream;1']
					.createInstance(Ci.nsIFileOutputStream);
			stream.init(aFile, 2, 0x200, false); // open as "write only"

			if (aEncoding) {
				var converterStream = Cc['@mozilla.org/intl/converter-output-stream;1']
						.createInstance(Ci.nsIConverterOutputStream);
				var buffer = aContent.length;
				converterStream.init(stream, aEncoding, buffer, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
				converterStream.writeString(aContent);
				converterStream.close();
			}
			else {
				stream.write(aContent, aContent.length);
			}

			stream.close();

			return aFile;
		}
	};

	namespace.textIO = textIO;
})();
<commit_msg>Don't use deprecated interface<commit_after>/**
 * @fileOverview Plaintext File I/O Library for Firefox 3.5 or later
 * @author       ClearCode Inc.
 * @version      4
 *
 * @license
 *   The MIT License, Copyright (c) 2010-2017 ClearCode Inc.
 * @url https://github.com/clear-code/js-codemodule-text-io
 */

if (typeof window == 'undefined' ||
	(window && typeof window.constructor == 'function'))
	this.EXPORTED_SYMBOLS = ['textIO'];

// var namespace;
if (typeof namespace == 'undefined') {
	// If namespace.jsm is available, export symbols to the shared namespace.
	// See: https://github.com/piroor/fxaddonlibs/blob/master/namespace.jsm
	try {
		let ns = {};
		Components.utils.import('resource://my-modules/namespace.jsm', ns);
		namespace = ns.getNamespaceFor('clear-code.com');
	}
	catch(e) {
		namespace = (typeof window != 'undefined' ? window : null ) || {};
	}
}

var textIO;
(function() {
	const currentRevision = 4;

	var loadedRevision = 'textIO' in namespace ?
			namespace.textIO.revision :
			0 ;
	if (loadedRevision && loadedRevision > currentRevision) {
		textIO = namespace.textIO;
		return;
	}

	const Cc = Components.classes;
	const Ci = Components.interfaces;

	const IOService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);

	/**
	 * @class
	 *   The plaintext I/O service, provides features to read/write
	 *   plaintext files.
	 *
	 * @example
	 *   Components.utils.import('resource://my-modules/textIO.jsm');
	 *   var text = textIO.readFrom(nsIFile, 'UTF-8');
	 *   textIO.writeTo(text, nsIFile, 'Shift_JIS');
	 */
	textIO = {
		/** @private */
		revision : currentRevision,

		/**
		 * Reads the contents of the given text file, and returns the contents
		 * as a string.
		 *
		 * @param {(nsIFile|nsIURI)} aFileOrURI
		 *   The pointer to the plain text file.
		 * @param {string=} aEncoding (optional)
		 *   The encoding of the contents of the file. If no encoding is given,
		 *   this returns the contents of the file as is.
		 *
		 * @returns {string}
		 *   The contents of the given file. If an encoding is given, a decoded
		 *   string will be returned. Otherwise this returns a raw bytes array
		 *   as a string.
		 */
		readFrom : function(aFileOrURI, aEncoding)
		{
			var stream;
			try {
				aFileOrURI = aFileOrURI.QueryInterface(Ci.nsIURI);
				var channel = IOService.newChannelFromURI(aFileOrURI);
				stream = channel.open();
			}
			catch(e) {
				aFileOrURI = aFileOrURI.QueryInterface(Ci.nsIFile)
				stream = Cc['@mozilla.org/network/file-input-stream;1']
							.createInstance(Ci.nsIFileInputStream);
				try {
					stream.init(aFileOrURI, 1, 0, false); // open as "read only"
				}
				catch(ex) {
					return null;
				}
			}

			var fileContents = null;
			try {
				if (aEncoding) {
					var converterStream = Cc['@mozilla.org/intl/converter-input-stream;1']
							.createInstance(Ci.nsIConverterInputStream);
					var buffer = stream.available();
					converterStream.init(stream, aEncoding, buffer,
						converterStream.DEFAULT_REPLACEMENT_CHARACTER);
					var out = { value : null };
					converterStream.readString(stream.available(), out);
					converterStream.close();
					fileContents = out.value;
				}
				else {
					var scriptableStream = Cc['@mozilla.org/scriptableinputstream;1']
							.createInstance(Ci.nsIScriptableInputStream);
					scriptableStream.init(stream);
					fileContents = scriptableStream.read(scriptableStream.available());
					scriptableStream.close();
				}
			}
			finally {
				stream.close();
			}

			return fileContents;
		},

		/**
		 * Outputs the given string to a file, as a plain text file.
		 *
		 * @param {string} aContents
		 *   The string you want to output. It should be a Unicode string (UCS2).
		 * @param {nsIFile} aFile
		 *   The pointer to the plain text file. If the file exists, it will be
		 *   overwritten. If there are some missing directories, then they are
		 *   automatically created.
		 * @param {string=} aEncoding (optional)
		 *   The encoding of the contents of the file. This encodes the given
		 *   string by the encoding before output. If no encoding is given,
		 *   this outputs the given string to the file as is.
		 *
		 * @returns {nsIFile}
		 *   The given file itself.
		 */
		writeTo : function(aContent, aFile, aEncoding)
		{
			// create directories
			(function(aDir) {
				try {
					if (aDir.parent) arguments.callee(aDir.parent);
					if (aDir.exists()) return;
					aDir.create(aDir.DIRECTORY_TYPE, 0755);
				}
				catch(e) {
				}
			})(aFile.parent);

			if (aFile.exists()) aFile.remove(true);
			aFile.create(aFile.NORMAL_FILE_TYPE, 0666);

			var stream = Cc['@mozilla.org/network/file-output-stream;1']
					.createInstance(Ci.nsIFileOutputStream);
			stream.init(aFile, 2, 0x200, false); // open as "write only"

			if (aEncoding) {
				var converterStream = Cc['@mozilla.org/intl/converter-output-stream;1']
						.createInstance(Ci.nsIConverterOutputStream);
				var buffer = aContent.length;
				converterStream.init(stream, aEncoding, buffer, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
				converterStream.writeString(aContent);
				converterStream.close();
			}
			else {
				stream.write(aContent, aContent.length);
			}

			stream.close();

			return aFile;
		}
	};

	namespace.textIO = textIO;
})();
<|endoftext|>